Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

version 4 fixes

tilakpatel22d2c1ce47a887
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index eb1313c43..32c86da43 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -843,6 +843,7 @@ set(STORAGE_SOURCES
src/storage/repositories/CustomIndexRepository.cpp
src/storage/repositories/DataMappingRepository.cpp
src/storage/repositories/AccountRepository.cpp
+ src/storage/repositories/OrderBasketRepository.cpp
# Workflow migration
src/storage/sqlite/migrations/v008_workflows.cpp
@@ -901,6 +902,9 @@ set(STORAGE_SOURCES
src/storage/sqlite/migrations/v045_scan_watch_universe.cpp
src/storage/sqlite/migrations/v046_fno_algo.cpp
src/storage/sqlite/migrations/v047_algo_multileg_trades.cpp
+ src/storage/sqlite/migrations/v048_instruments_exchange_unique.cpp
+ src/storage/sqlite/migrations/v049_order_baskets.cpp
+ src/storage/sqlite/migrations/v050_alpha_arena_rewrite.cpp
# Historical OHLCV data store (Historify, Phase 3 §13)
src/storage/HistoricalDataStore.cpp
@@ -929,6 +933,7 @@ set(LLM_SERVICE_SOURCES
src/services/llm/LlmFinceptAsync.cpp
src/services/llm/LlmToolLoop.cpp
src/services/llm/ModelCatalog.cpp
+ src/services/llm/ProviderCatalog.cpp
)
# AI Chat screen — UI for chatting with the LLM service
@@ -1013,6 +1018,8 @@ set(TRADING_SOURCES
src/trading/OrderMatcher.cpp
src/trading/BrokerRegistry.cpp
src/trading/UnifiedTrading.cpp
+ src/trading/UnifiedPortfolioService.cpp
+ src/trading/PortfolioMonitorSelftest.cpp
src/trading/SmartOrderEngine.cpp
src/trading/RateLimiter.cpp
src/trading/ActionCenter.cpp
@@ -1149,18 +1156,20 @@ set(SERVICE_SOURCES
src/services/cloud/NewsFeedCloudAdapter.cpp
src/services/cloud/NotebookCloudAdapter.cpp
src/services/akshare/AkShareService.cpp
- src/services/alpha_arena/AlphaArenaJson.cpp
- src/services/alpha_arena/Indicators.cpp
- src/services/alpha_arena/ContextBuilder.cpp
- src/services/alpha_arena/AlphaArenaRepo.cpp
- src/services/alpha_arena/RiskEngine.cpp
- src/services/alpha_arena/PaperVenue.cpp
- src/services/alpha_arena/SecretRedemptionServer.cpp
- src/services/alpha_arena/TickClock.cpp
- src/services/alpha_arena/ModelDispatcher.cpp
- src/services/alpha_arena/OrderRouter.cpp
- src/services/alpha_arena/AlphaArenaEngine.cpp
- src/services/alpha_arena/AlphaArenaService.cpp
+ src/services/alpha_arena/ArenaStore.cpp
+ src/services/alpha_arena/ArenaIndicators.cpp
+ src/services/alpha_arena/ArenaDecisionParser.cpp
+ src/services/alpha_arena/PaperExchange.cpp
+ src/services/alpha_arena/ArenaRisk.cpp
+ src/services/alpha_arena/ArenaModelRegistry.cpp
+ src/services/alpha_arena/ArenaPrompts.cpp
+ src/services/alpha_arena/ArenaLlmClient.cpp
+ src/services/alpha_arena/ArenaMarketData.cpp
+ src/services/alpha_arena/ArenaEngine.cpp
+ src/services/alpha_arena/HyperliquidLiveVenue.cpp
+ # Header-only Q_OBJECT interface — listed so AUTOMOC scans it (no sibling .cpp).
+ src/services/alpha_arena/ArenaMarketDataIface.h
+ src/services/alpha_arena/ArenaSelftest.cpp
src/services/asia_markets/AsiaMarketsService.cpp
src/services/crypto/TotpService.cpp
src/services/python_cli/PythonCliService.cpp
@@ -1572,8 +1581,10 @@ set(SCREEN_SOURCES
src/screens/common/PaperBlotterPanel.cpp
src/screens/equity_trading/AccountManagementDialog.cpp
src/screens/equity_trading/BroadcastOrderDialog.cpp
+ src/screens/equity_trading/BasketOrdersDialog.cpp
src/screens/equity_trading/OrderConfirmDialog.cpp
src/screens/equity_trading/PortfolioReplicationDialog.cpp
+ src/screens/portfolio_monitor/PortfolioMonitorScreen.cpp
# Feed monitor (reusable across screens)
src/screens/common/feeds/FeedCardView.cpp
src/screens/common/feeds/FeedTableView.cpp
@@ -1790,9 +1801,10 @@ set(SCREEN_SOURCES
# Alpha Arena
src/screens/alpha_arena/AlphaArenaScreen.cpp
- src/screens/alpha_arena/panels/LeaderboardPanel.cpp
- src/screens/alpha_arena/panels/ModelChatPanel.cpp
- src/screens/alpha_arena/panels/StatePanels.cpp
+ src/screens/alpha_arena/EquityCurveWidget.cpp
+ src/screens/alpha_arena/LeaderboardCards.cpp
+ src/screens/alpha_arena/ArenaTabs.cpp
+ src/screens/alpha_arena/NewCompetitionWizard.cpp
src/screens/alpha_arena/panels/LiveModeGateDialog.cpp
# Alternative Investments — partial-class split; see header.
@@ -1993,9 +2005,10 @@ set_source_files_properties(
src/screens/algo_trading/StrategyListPanel.cpp
src/screens/algo_trading/AlgoDeployDialog.cpp
src/screens/alpha_arena/AlphaArenaScreen.cpp
- src/screens/alpha_arena/panels/LeaderboardPanel.cpp
- src/screens/alpha_arena/panels/ModelChatPanel.cpp
- src/screens/alpha_arena/panels/StatePanels.cpp
+ src/screens/alpha_arena/EquityCurveWidget.cpp
+ src/screens/alpha_arena/LeaderboardCards.cpp
+ src/screens/alpha_arena/ArenaTabs.cpp
+ src/screens/alpha_arena/NewCompetitionWizard.cpp
src/screens/alpha_arena/panels/LiveModeGateDialog.cpp
src/screens/alt_investments/AltInvestmentsScreen.cpp
src/screens/alt_investments/AltInvestmentsScreen_Layout.cpp
@@ -2045,8 +2058,10 @@ set_source_files_properties(
src/screens/common/PaperBlotterPanel.cpp
src/screens/equity_trading/AccountManagementDialog.cpp
src/screens/equity_trading/BroadcastOrderDialog.cpp
+ src/screens/equity_trading/BasketOrdersDialog.cpp
src/screens/equity_trading/OrderConfirmDialog.cpp
src/screens/equity_trading/PortfolioReplicationDialog.cpp
+ src/screens/portfolio_monitor/PortfolioMonitorScreen.cpp
# Feed monitor (reusable across screens)
src/screens/common/feeds/FeedCardView.cpp
src/screens/common/feeds/FeedTableView.cpp
@@ -2403,6 +2418,8 @@ set_source_files_properties(
src/storage/sqlite/migrations/v045_scan_watch_universe.cpp
src/storage/sqlite/migrations/v046_fno_algo.cpp
src/storage/sqlite/migrations/v047_algo_multileg_trades.cpp
+ src/storage/sqlite/migrations/v048_instruments_exchange_unique.cpp
+ src/storage/sqlite/migrations/v050_alpha_arena_rewrite.cpp
# Polymarket screen files — each defines static fmt_* helpers in same namespace
src/screens/polymarket/PolymarketScreen.cpp
src/screens/polymarket/PolymarketCommandBar.cpp
@@ -2475,18 +2492,18 @@ set_source_files_properties(
# and Q_OBJECT-bearing helpers — exclude from unity to avoid the kind of
# ODR clashes that masked compile errors in early Phase 5c integration.
set_source_files_properties(
- src/services/alpha_arena/AlphaArenaJson.cpp
- src/services/alpha_arena/Indicators.cpp
- src/services/alpha_arena/ContextBuilder.cpp
- src/services/alpha_arena/AlphaArenaRepo.cpp
- src/services/alpha_arena/RiskEngine.cpp
- src/services/alpha_arena/PaperVenue.cpp
- src/services/alpha_arena/SecretRedemptionServer.cpp
- src/services/alpha_arena/TickClock.cpp
- src/services/alpha_arena/ModelDispatcher.cpp
- src/services/alpha_arena/OrderRouter.cpp
- src/services/alpha_arena/AlphaArenaEngine.cpp
- src/services/alpha_arena/AlphaArenaService.cpp
+ src/services/alpha_arena/ArenaStore.cpp
+ src/services/alpha_arena/ArenaIndicators.cpp
+ src/services/alpha_arena/ArenaDecisionParser.cpp
+ src/services/alpha_arena/PaperExchange.cpp
+ src/services/alpha_arena/ArenaRisk.cpp
+ src/services/alpha_arena/ArenaModelRegistry.cpp
+ src/services/alpha_arena/ArenaPrompts.cpp
+ src/services/alpha_arena/ArenaLlmClient.cpp
+ src/services/alpha_arena/ArenaMarketData.cpp
+ src/services/alpha_arena/ArenaEngine.cpp
+ src/services/alpha_arena/HyperliquidLiveVenue.cpp
+ src/services/alpha_arena/ArenaSelftest.cpp
src/trading/exchanges/hyperliquid/HyperliquidClient.cpp
src/trading/exchanges/hyperliquid/Keccak256.cpp
src/trading/exchanges/hyperliquid/HyperliquidSigner.cpp
@@ -2552,6 +2569,11 @@ set_source_files_properties(
src/algo_engine/fno/FnoLegResolver.cpp
src/trading/PaperTradingSelftest.cpp
src/trading/PaperMarkService.cpp
+ # Portfolio Monitor: file-local helpers (signed_qty/approx) would collide with
+ # sibling files' anonymous-namespace helpers inside a unity blob. (The screen
+ # cpp is excluded via the screens block above.)
+ src/trading/UnifiedPortfolioService.cpp
+ src/trading/PortfolioMonitorSelftest.cpp
PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE
)
diff --git a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt
index 270b922af..043a953a9 100644
--- a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt
+++ b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt
@@ -1,7 +1,7 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
-Copyright (C) 2025 Fincept Corporation
+Copyright (C) 2025-2026 Fincept Corporation
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
@@ -17,118 +17,274 @@ You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
================================================================================
-DUAL LICENSING NOTICE
+ DUAL LICENSING NOTICE
================================================================================
-Fincept Terminal is available under two licensing options:
+Fincept Terminal is dual-licensed. Every user must comply with ONE of the
+following licenses:
+
+1. AGPL-3.0 (Open Source)
+ - Free for personal use, individual learning, academic research by
+ individual students, and open-source contribution to this repository.
+ - Requires sharing modifications if distributed or made available as a
+ network service.
+ - Full text: https://www.gnu.org/licenses/agpl-3.0.html
+
+2. Fincept Commercial License
+ - REQUIRED for any business or internal company use, regardless of
+ revenue, size, or duration.
+ - Required for SaaS, cloud, hosted, white-label, or resale offerings.
+ - Required for forks that remove or replace Fincept's APIs, data
+ sources, or service endpoints, where used commercially or internally.
+ - See: docs/COMMERCIAL_LICENSE.md
+
+The AGPL-3.0 option is NOT available for Commercial Use as defined in
+docs/COMMERCIAL_LICENSE.md, Section 3. Commercial Use without an executed
+Commercial License is a breach of copyright and is subject to the full
+range of remedies set forth in docs/COMMERCIAL_LICENSE.md.
-1. AGPL-3.0 License (Open Source)
- - Free for personal and educational use
- - Free to use with your own data sources
- - Requires sharing modifications if you distribute or provide as a network service
- - Full source code must remain available under AGPL-3.0
- - See full license text at: https://www.gnu.org/licenses/agpl-3.0.html
+================================================================================
+ CLONING / FORKING / MODIFICATION DOES NOT GRANT
+ COMMERCIAL OR INTERNAL-USE RIGHTS
+================================================================================
+
+Cloning, forking, downloading, building, or modifying this repository does
+NOT grant any right to use Fincept Terminal — or any Modified Version or
+Derivative Work — for Commercial Use. Internal use within any for-profit
+organization, government body, fund, or revenue-generating non-profit is
+Commercial Use and requires a paid Commercial License.
-2. Commercial License
- - Required for any business/commercial use
- - Required to access Fincept Data Sources and APIs for commercial purposes
- - No obligation to share source code
- - Priority support available
- - See docs/COMMERCIAL_LICENSE.md for pricing and terms
+The license attaches to the codebase and any Derivative Work of it, not to
+specific API integrations. Removing, replacing, disabling, or rewiring
+Fincept's APIs, data sources, or service endpoints does NOT sever or
+extinguish the licensing obligation.
================================================================================
-FINCEPT DATA & API
+ FINCEPT DATA & API SERVICES
================================================================================
-The Fincept Terminal software is free under AGPL-3.0.
+The Fincept Terminal software is offered under AGPL-3.0 for non-commercial
+use as described above.
-Fincept Data Sources and APIs are separate services that require:
-- Commercial License for business use ($10,200/year)
-- University License for academic institutions ($799/month)
-- Free for personal/educational individual use
+Fincept Data Sources and APIs are separate services subject to:
+- Commercial License: USD 10,200 / year
+- University & Academic License: USD 799 / month (20 accounts)
+- Free for individual personal and educational use only
================================================================================
-TRADEMARK NOTICE
+ TRADEMARK NOTICE
================================================================================
-"Fincept Terminal", "Fincept", and the Fincept logo are trademarks of
-Fincept Corporation. All rights reserved.
+"Fincept", "Fincept Terminal", "Fincept Corporation", and the Fincept logo
+are trademarks of Fincept Corporation. All rights reserved.
-You may not use these trademarks without explicit written permission,
-except as necessary to comply with the AGPL-3.0 attribution requirements.
+You may not use these marks — or any colorable imitation, transliteration,
+abbreviation, translation, or variation or derivative thereof — without
+prior written permission from Fincept Corporation, except as strictly
+necessary to comply with AGPL-3.0 attribution requirements.
-Use of the trademarks to promote derivative works or competing products
-is strictly prohibited without a trademark license agreement.
+Removal, replacement, or rebranding of these marks in any fork or
+Derivative Work does NOT extinguish Fincept Corporation's rights in the
+underlying Software, nor does it sever the licensing obligations attaching
+to the codebase.
+
+The Fincept Trade Dress — including screen layouts, color palette,
+terminal command syntax, ticker conventions, function-code conventions,
+keyboard shortcut conventions, dashboard widget vocabulary, and overall
+visual identity of Fincept Terminal — is also protected. Substantially
+similar replication, even with branding removed, is prohibited.
+
+Use of the trademarks or trade dress to promote derivative works or
+competing products is strictly prohibited.
================================================================================
-ADDITIONAL RESTRICTIONS
+ ADDITIONAL RESTRICTIONS
================================================================================
-While the AGPL-3.0 grants broad freedoms, the following restrictions apply:
+While AGPL-3.0 grants broad freedoms for non-commercial use, the following
+additional restrictions apply to all users of this Software:
-1. NETWORK USE REQUIREMENT
- If you run a modified version of Fincept Terminal as a network service
- (SaaS, cloud platform, web application), you MUST:
+1. NETWORK USE REQUIREMENT (AGPL § 13)
+ If you run a modified version as a network service (SaaS, cloud
+ platform, web application), you MUST:
- Provide users with access to the complete source code
- Clearly indicate the source is available
- Make the source available via download or repository access
2. ATTRIBUTION REQUIREMENT
You must retain all copyright notices, attribution statements, and
- this license file in any distribution or derivative work.
+ this license file in any distribution or Derivative Work.
3. TRADEMARK RESTRICTIONS
- - Cannot use "Fincept" branding without permission
- - Must clearly differentiate derivative works from the official version
+ - Cannot use "Fincept" or related marks without permission
- Cannot imply endorsement by Fincept Corporation
+ - Must clearly differentiate Derivative Works from the official version
+ - Cannot replicate Fincept Trade Dress
+
+4. COMMERCIAL & INTERNAL-USE RESTRICTION
+ - Commercial Use of any kind requires a Commercial License
+ - Internal corporate use is Commercial Use, regardless of whether the
+ Software is exposed to third parties
+ - Forks that strip or replace Fincept APIs are still subject to the
+ Commercial License requirement
================================================================================
-CONTRIBUTOR LICENSE AGREEMENT
+ CONTRIBUTOR LICENSE AGREEMENT (CLA)
================================================================================
-By contributing to Fincept Terminal, you agree that:
+By contributing to Fincept Terminal (via pull request, patch, comment,
+issue, or any other means), each contributor agrees to the following terms:
+
+1. ASSIGNMENT AND LICENSE-IN. To the maximum extent permitted by law, each
+ contribution is a work made for hire owned by Fincept Corporation. To
+ the extent any contribution is not a work made for hire, the contributor
+ hereby presently and unconditionally ASSIGNS to Fincept Corporation all
+ right, title, and interest in and to the contribution, including all
+ copyright, moral rights (waived to the maximum extent permitted), and
+ related rights. Without limiting the foregoing, the contributor grants
+ Fincept Corporation a perpetual, worldwide, non-exclusive, royalty-free,
+ irrevocable, sublicensable license — with the right to sublicense
+ through multiple tiers — to use, reproduce, modify, distribute,
+ sublicense, and relicense the contribution under AGPL-3.0, the Fincept
+ Commercial License, and any future license selected by Fincept
+ Corporation.
+
+2. NO JOINT AUTHORSHIP. Each contributor expressly disclaims any claim of
+ joint authorship in the Software as a whole or in any other
+ contributor's contributions. Contributing does NOT grant the contributor
+ any license to the Software as a whole, to any other contributor's
+ contributions, or to Commercial Use of the Software.
+
+3. WARRANTY AND INDEMNITY. Each contributor warrants that (a) the
+ contribution is the contributor's original work or is properly attributed
+ and licensed for the contribution; (b) the contributor has the legal
+ right to make the contribution and grant the rights herein; (c) the
+ contribution is free of any obligations to any current or former
+ employer, client, university, or third party that would conflict with
+ this assignment; and (d) the contribution does not infringe any
+ third-party rights. The contributor shall indemnify, defend, and hold
+ harmless Fincept Corporation from any breach of these warranties.
+
+4. AS-IS. Contributions are provided "AS IS" without warranties of any
+ kind beyond the warranties in Section 3 above.
+
+5. NO COMMERCIAL RIGHTS BACK. Contributing does NOT grant the contributor
+ Commercial Use rights, license-back rights, or access to Fincept Data
+ Sources or APIs for commercial purposes.
-1. You grant Fincept Corporation a perpetual, worldwide, non-exclusive,
- royalty-free license to use, reproduce, modify, and distribute your
- contributions under both AGPL-3.0 and commercial licenses.
+================================================================================
+ WHEN A COMMERCIAL LICENSE IS REQUIRED
+================================================================================
-2. You certify that you have the right to make the contribution and grant
- these licenses.
+You NEED a Commercial License if you:
+- Use Fincept Terminal for any business purpose, paid or free
+- Use Fincept Terminal internally at a company, fund, or for-profit entity
+ (regardless of whether it is exposed to third parties)
+- Are a startup at any stage, including pre-revenue and pre-product
+- Are a hedge fund, prop firm, bank, brokerage, asset manager, family
+ office, fintech, or exchange
+- Offer Fincept Terminal as SaaS, PaaS, or any hosted service
+- White-label, rebrand, distribute, or resell Fincept Terminal
+- Maintain or operate a fork that strips or replaces Fincept APIs and use
+ it commercially or internally
+- Engage a third-party developer, integrator, or consultancy to build,
+ modify, deploy, host, or customize Fincept Terminal for any of the above
+
+You do NOT need a Commercial License if you:
+- Use Fincept Terminal for personal learning on your own machine
+- Are an individual student conducting non-commercial research
+- Are contributing to the open-source project
+
+When in doubt, assume a Commercial License is required and email
-3. Your contributions are provided "as-is" without warranties.
+================================================================================
+ ENFORCEMENT, PENALTIES & LIABILITY
+================================================================================
-4. Contributing does not grant you commercial rights to use Fincept
- Data Sources and APIs.
+Fincept Corporation actively monitors public code repositories, container
+registries, application stores, cloud marketplaces, SaaS platforms, and
+trademark registers for unlicensed Commercial Use of Fincept Terminal,
+Modified Versions, and Derivative Works.
+
+Unauthorized Commercial Use is subject to liquidated damages, including
+(without limitation):
+
+ * USD 50,000 per organization per year for unauthorized internal
+ corporate use (or 5x the then-current Commercial License fee,
+ whichever is greater)
+ * USD 250,000 per offering for unauthorized SaaS, hosting, or resale,
+ plus full disgorgement of revenue
+ * USD 100,000 per organization for unauthorized fork-and-replace-API
+ deployments, plus 5x the Commercial License fee for each year of use
+ * USD 150,000 per element for unauthorized use of Fincept Marks or
+ Fincept Trade Dress
+ * USD 10,000 per day for continued use after notice of breach
+
+In addition, Fincept Corporation will pursue:
+- Backdated license fees from the date of first unauthorized use, with
+ 18% annual interest
+- Disgorgement of all profits, revenue, and cost savings derived from
+ unauthorized use
+- DMCA takedowns (17 U.S.C. § 512), notices under the Information
+ Technology Act, 2000 (India), and equivalent foreign statutes
+- Cease-and-desist letters and civil action for copyright and trademark
+ infringement
+- Criminal complaints under the Copyright Act, 1957 (India) §§ 63-63B
+ and equivalent foreign laws
+- All attorneys' fees, court costs, expert fees, and investigation costs
+
+JOINT AND SEVERAL LIABILITY. Any organization that engages, hires, or
+contracts with a third-party developer, integrator, IT consultancy,
+outsourcing vendor, freelancer, or offshore development center to build,
+modify, deploy, fork, host, or customize Fincept Terminal or any
+Derivative Work shall be JOINTLY AND SEVERALLY LIABLE with that third
+party for any unauthorized Commercial Use, breach of license, or
+infringement. The contracting company cannot escape liability by claiming
+that the developer was solely responsible. Liability extends to parents,
+subsidiaries, affiliates, successors, joint-venture partners, and
+acquirers. The duty to verify license compliance is non-delegable.
+
+Full enforcement, penalty, and joint-and-several liability terms are set
+forth in docs/COMMERCIAL_LICENSE.md, Sections 12, 13, and 14.
================================================================================
-COMMERCIAL USE
+ GOVERNING LAW & JURISDICTION
================================================================================
-You NEED a commercial license if you:
-- Use Fincept Terminal for any business purpose
-- Use Fincept Data Sources or APIs commercially
-- Are a startup (even with $0 revenue)
-- Use internally at a company
-- Offer as SaaS or cloud platform
-- White-label or resell
-
-You DON'T need a commercial license if you:
-- Use for personal learning
-- Are an individual student
-- Use with your own data sources (non-commercial)
-- Contribute to the open-source project
+This License and any dispute arising out of or relating to it shall be
+governed by the laws of the Republic of India, without regard to its
+conflict-of-laws principles. The courts of Delhi, India shall have
+exclusive jurisdiction. Fincept Corporation reserves the right to seek
+injunctive or equitable relief in any court of competent jurisdiction
+worldwide to protect its intellectual property.
================================================================================
-CONTACT INFORMATION
+ CONTACT INFORMATION
================================================================================
-Phone: +91-9773034108
-Website: https://fincept.in
-Repository: https://github.com/Fincept-Corporation/FinceptTerminal
+Phone: +91-9773034108
+Website: https://fincept.in
+Repository: https://github.com/Fincept-Corporation/FinceptTerminal
Documentation: https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs
+Commercial: docs/COMMERCIAL_LICENSE.md
================================================================================
-Last Updated: February 2026
-Version: 3.3.1
+Document Version: 2.0
+In Force From: April 30, 2026
+Status: Current and binding. These terms remain in full force and
+ effect indefinitely until expressly superseded by a
+ subsequent version published by Fincept Corporation. The
+ date above marks the most recent revision and is NOT an
+ expiry date.
+Software Version: 4.0.2 (current release; license applies to all releases,
+ branches, tags, and commits of the Software)
+
+This License governs all current and future use of the Software, including
+use of historical versions, regardless of when those versions were
+originally published. Any commercial or internal-corporate use of any
+version of Fincept Terminal — past, present, or future — is subject to
+the terms of this License and the accompanying Commercial License at
+docs/COMMERCIAL_LICENSE.md.
diff --git a/fincept-qt/scripts/alpha_arena/__init__.py b/fincept-qt/scripts/alpha_arena/__init__.py
deleted file mode 100644
index a1db496bc..000000000
--- a/fincept-qt/scripts/alpha_arena/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-"""Alpha Arena package marker. Implementation lives in C++ engine; this package
-holds only the LLM-call subprocess (added in a later phase)."""
diff --git a/fincept-qt/scripts/alpha_arena/config/__init__.py b/fincept-qt/scripts/alpha_arena/config/__init__.py
deleted file mode 100644
index 467f653d9..000000000
--- a/fincept-qt/scripts/alpha_arena/config/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""Reserved package marker. Model registry lives in C++ ModelDispatcher."""
diff --git a/fincept-qt/scripts/alpha_arena/core/__init__.py b/fincept-qt/scripts/alpha_arena/core/__init__.py
deleted file mode 100644
index bd134a403..000000000
--- a/fincept-qt/scripts/alpha_arena/core/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""Reserved package marker. Core orchestration moved to C++ AlphaArenaEngine."""
diff --git a/fincept-qt/scripts/alpha_arena/llm_call.py b/fincept-qt/scripts/alpha_arena/llm_call.py
deleted file mode 100644
index 11be29b4f..000000000
--- a/fincept-qt/scripts/alpha_arena/llm_call.py
+++ /dev/null
@@ -1,256 +0,0 @@
-"""Alpha Arena LLM-call subprocess.
-
-Single-purpose: take a system prompt + user prompt + model identity, call the
-right provider SDK, return the response text + token/cost metadata as JSON on
-stdout. That is all this script does. No engine logic, no persistence, no
-trading state — those live in the C++ engine.
-
-Wire protocol (input — argv[1] is a path to a request JSON file):
- {
- "system_prompt": "<text>",
- "user_prompt": "<text>",
- "model": {
- "provider": "openai|anthropic|google|deepseek|xai|qwen",
- "id": "<model id, e.g. gpt-5>",
- "base_url": "<optional>",
- "api_version": "<optional>"
- },
- "temperature": 0.1,
- "max_output_tokens": 4096,
- "secret_handle": "<opaque token>",
- "secret_pipe": "fincept-aa-<nonce>"
- }
-
-Wire protocol (output — JSON on stdout):
- Success: {"response_text": "...", "latency_ms": int, "tokens_in": int,
- "tokens_out": int, "cost_usd": float}
- Failure: {"error": "<message>", "stage": "<redeem|sdk_call|response>"}
-
-Failure modes are non-fatal — caller logs and treats as a no-op tick.
-"""
-
-import json
-import os
-import socket
-import struct
-import sys
-import time
-from pathlib import Path
-
-
-def fail(stage: str, msg: str) -> None:
- sys.stdout.write(json.dumps({"error": msg, "stage": stage}))
- sys.stdout.flush()
- sys.exit(1)
-
-
-def redeem_secret(pipe_name: str, handle: str) -> str:
- """Connect to the engine's per-tick local IPC server, exchange the opaque
- handle for the actual API key. Server invalidates the handle after first
- redemption.
-
- On Windows the pipe is `\\\\.\\pipe\\<pipe_name>` (QLocalServer convention);
- on POSIX it's an abstract or file-based UNIX socket at the same name.
- """
- if not handle:
- return ""
- try:
- if os.name == "nt":
- # Open the named pipe directly. CreateFile-style read/write.
- pipe_path = r"\\.\pipe\\" + pipe_name
- with open(pipe_path, "r+b", buffering=0) as f:
- payload = json.dumps({"handle": handle}).encode("utf-8")
- f.write(struct.pack("<I", len(payload)) + payload)
- # Read length-prefixed reply.
- hdr = f.read(4)
- if len(hdr) != 4:
- raise RuntimeError("short read on secret pipe header")
- (n,) = struct.unpack("<I", hdr)
- body = f.read(n)
- if len(body) != n:
- raise RuntimeError("short read on secret pipe body")
- reply = json.loads(body.decode("utf-8"))
- else:
- # POSIX abstract namespace if the engine is using one (Qt
- # QLocalServer uses /tmp/<name> by default on Linux/macOS).
- sock_path = f"/tmp/{pipe_name}"
- with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
- s.connect(sock_path)
- payload = json.dumps({"handle": handle}).encode("utf-8")
- s.sendall(struct.pack("<I", len(payload)) + payload)
- hdr = s.recv(4)
- if len(hdr) != 4:
- raise RuntimeError("short read on secret socket header")
- (n,) = struct.unpack("<I", hdr)
- body = b""
- while len(body) < n:
- chunk = s.recv(n - len(body))
- if not chunk:
- break
- body += chunk
- reply = json.loads(body.decode("utf-8"))
-
- if "error" in reply:
- raise RuntimeError(reply["error"])
- return reply.get("api_key", "")
- except Exception as exc:
- raise RuntimeError(f"secret redemption failed: {exc}") from exc
-
-
-def call_openai_compatible(api_key, base_url, model_id, system, user, temperature, max_tokens):
- """OpenAI / DeepSeek / xAI / Qwen-via-DashScope use the OpenAI SDK shape.
- We import lazily so that a missing optional SDK doesn't break the script."""
- try:
- from openai import OpenAI
- except ImportError as exc:
- raise RuntimeError(f"openai SDK not installed: {exc}") from exc
-
- kwargs = {"api_key": api_key}
- if base_url:
- kwargs["base_url"] = base_url
- client = OpenAI(**kwargs)
-
- resp = client.chat.completions.create(
- model=model_id,
- messages=[
- {"role": "system", "content": system},
- {"role": "user", "content": user},
- ],
- temperature=temperature,
- max_tokens=max_tokens,
- )
- text = resp.choices[0].message.content or ""
- usage = getattr(resp, "usage", None)
- return text, getattr(usage, "prompt_tokens", 0), getattr(usage, "completion_tokens", 0)
-
-
-def call_anthropic(api_key, model_id, system, user, temperature, max_tokens):
- try:
- import anthropic
- except ImportError as exc:
- raise RuntimeError(f"anthropic SDK not installed: {exc}") from exc
-
- client = anthropic.Anthropic(api_key=api_key)
- resp = client.messages.create(
- model=model_id,
- system=system,
- messages=[{"role": "user", "content": user}],
- temperature=temperature,
- max_tokens=max_tokens,
- )
- text = "".join(b.text for b in resp.content if getattr(b, "type", "") == "text")
- return text, getattr(resp.usage, "input_tokens", 0), getattr(resp.usage, "output_tokens", 0)
-
-
-def call_google(api_key, model_id, system, user, temperature, max_tokens):
- try:
- import google.generativeai as genai
- except ImportError as exc:
- raise RuntimeError(f"google.generativeai SDK not installed: {exc}") from exc
-
- genai.configure(api_key=api_key)
- # Gemini takes the system prompt as a top-level instruction.
- model = genai.GenerativeModel(model_name=model_id, system_instruction=system)
- resp = model.generate_content(
- user,
- generation_config={"temperature": temperature, "max_output_tokens": max_tokens},
- )
- text = (resp.text or "") if hasattr(resp, "text") else ""
- usage = getattr(resp, "usage_metadata", None)
- in_tok = getattr(usage, "prompt_token_count", 0) if usage else 0
- out_tok = getattr(usage, "candidates_token_count", 0) if usage else 0
- return text, in_tok, out_tok
-
-
-def estimate_cost_usd(provider: str, model_id: str, in_tok: int, out_tok: int) -> float:
- """Approximate prices ($/1M tokens). The C++ side ultimately treats this
- as a competition signal, not an accounting truth — keep it directional."""
- rates = {
- # provider:model_prefix -> (in_per_m, out_per_m)
- "openai:gpt-5": (5.0, 15.0),
- "openai:gpt-4o": (2.5, 10.0),
- "anthropic:claude-sonnet": (3.0, 15.0),
- "anthropic:claude-opus": (15.0, 75.0),
- "google:gemini-2.5-pro": (1.25, 5.0),
- "deepseek:deepseek-chat": (0.14, 0.28),
- "xai:grok-4": (5.0, 15.0),
- "qwen:qwen3-max": (1.6, 6.4),
- }
- for key, (in_rate, out_rate) in rates.items():
- prefix_provider, prefix_model = key.split(":", 1)
- if provider == prefix_provider and model_id.startswith(prefix_model):
- return (in_tok * in_rate + out_tok * out_rate) / 1_000_000.0
- return 0.0
-
-
-def main() -> None:
- if len(sys.argv) < 2:
- fail("usage", "expected request JSON file path on argv[1]")
-
- request_path = Path(sys.argv[1])
- try:
- request = json.loads(request_path.read_text(encoding="utf-8"))
- except Exception as exc:
- fail("usage", f"failed to read request: {exc}")
- finally:
- # Best-effort delete; secrets aren't in the file, but reduce footprint.
- try:
- request_path.unlink()
- except OSError:
- pass
-
- model = request.get("model", {})
- provider = model.get("provider", "").lower()
- model_id = model.get("id", "")
- base_url = model.get("base_url", "") or None
- system = request.get("system_prompt", "")
- user = request.get("user_prompt", "")
- temperature = float(request.get("temperature", 0.1))
- max_tokens = int(request.get("max_output_tokens", 4096))
- handle = request.get("secret_handle", "")
- pipe_name = request.get("secret_pipe", "")
-
- try:
- api_key = redeem_secret(pipe_name, handle)
- except Exception as exc:
- fail("redeem", str(exc))
-
- if not api_key:
- fail("redeem", "no api_key available after redemption")
-
- started = time.monotonic()
- try:
- if provider in ("openai", "deepseek", "xai", "qwen"):
- text, in_tok, out_tok = call_openai_compatible(
- api_key, base_url, model_id, system, user, temperature, max_tokens
- )
- elif provider == "anthropic":
- text, in_tok, out_tok = call_anthropic(
- api_key, model_id, system, user, temperature, max_tokens
- )
- elif provider == "google":
- text, in_tok, out_tok = call_google(
- api_key, model_id, system, user, temperature, max_tokens
- )
- else:
- fail("sdk_call", f"unknown provider: {provider}")
- except Exception as exc:
- fail("sdk_call", str(exc))
-
- latency_ms = int((time.monotonic() - started) * 1000)
- sys.stdout.write(
- json.dumps(
- {
- "response_text": text,
- "latency_ms": latency_ms,
- "tokens_in": int(in_tok or 0),
- "tokens_out": int(out_tok or 0),
- "cost_usd": estimate_cost_usd(provider, model_id, in_tok or 0, out_tok or 0),
- }
- )
- )
- sys.stdout.flush()
-
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-qt/scripts/alpha_arena/schema.json b/fincept-qt/scripts/alpha_arena/schema.json
deleted file mode 100644
index c79c8d0df..000000000
--- a/fincept-qt/scripts/alpha_arena/schema.json
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "schema_version": 1,
- "_comment": "Mirror of src/services/alpha_arena/AlphaArenaSchema.h. Single source of truth is the C++ header — if you edit one, edit the other (CI verifies parity in Phase 6).",
- "signals": ["buy_to_enter", "sell_to_enter", "hold", "close"],
- "modes": ["baseline", "monk", "situational"],
- "perp_universe": ["BTC", "ETH", "SOL", "BNB", "DOGE", "XRP"],
- "limits": {
- "min_leverage": 1,
- "max_leverage": 20,
- "invalidation_condition_max_chars": 280,
- "justification_max_chars": 1000,
- "risk_usd_recompute_tolerance_frac": 0.05,
- "max_risk_per_trade_frac": 0.02,
- "min_liquidation_buffer_frac": 0.15
- },
- "action_object": {
- "signal": {"type": "string", "required": true, "enum": "signals"},
- "coin": {"type": "string", "required": true, "enum": "perp_universe"},
- "quantity": {"type": "number", "required": true, "positive_for_entry": true},
- "leverage": {"type": "integer", "required": true, "range": [1, 20]},
- "profit_target": {"type": "number", "required": true, "positive_for_entry": true},
- "stop_loss": {"type": "number", "required": true, "positive_for_entry": true},
- "invalidation_condition": {"type": "string", "required": true, "max_chars": 280},
- "confidence": {"type": "number", "required": true, "range": [0, 1]},
- "risk_usd": {"type": "number", "required": true, "server_recomputed": true},
- "justification": {"type": "string", "required": true, "max_chars": 1000}
- },
- "response_envelope": {
- "actions": {"type": "array", "items": "action_object", "required": true}
- }
-}
diff --git a/fincept-qt/scripts/alpha_arena/types/__init__.py b/fincept-qt/scripts/alpha_arena/types/__init__.py
deleted file mode 100644
index 7583253ea..000000000
--- a/fincept-qt/scripts/alpha_arena/types/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-"""Reserved package marker. Canonical schema lives in C++ AlphaArenaSchema.h
-and is mirrored as scripts/alpha_arena/schema.json (added in a later phase)."""
diff --git a/fincept-qt/scripts/alpha_arena/utils/__init__.py b/fincept-qt/scripts/alpha_arena/utils/__init__.py
deleted file mode 100644
index dd887d4e4..000000000
--- a/fincept-qt/scripts/alpha_arena/utils/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""Reserved package marker."""
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index 1598c1173..1dbe5f532 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -29,8 +29,10 @@
#include "datahub/DataHubMetaTypes.h"
#include "mcp/McpInit.h"
#include "mcp/ToolSelfTest.h"
+#include "services/alpha_arena/ArenaSelftest.h"
#include "services/feeds/FeedSelfTest.h"
#include "trading/PaperTradingSelftest.h"
+#include "trading/UnifiedPortfolioService.h"
#include "trading/replication/PortfolioReplicationSelftest.h"
#include "network/http/HttpClient.h"
#include "python/PythonSetupManager.h"
@@ -52,7 +54,7 @@
#include "services/options/FiiDiiService.h"
#include "services/options/OISnapshotter.h"
#include "services/options/OptionChainService.h"
-#include "services/alpha_arena/AlphaArenaEngine.h"
+#include "services/alpha_arena/ArenaEngine.h"
#include "services/news/NewsService.h"
#include "services/notebooks/NotebookLibraryService.h"
#include "services/polymarket/PolymarketWebSocket.h"
@@ -423,10 +425,10 @@ int main(int argc, char* argv[]) {
fincept::trading::ExchangeSessionManager::instance().ensure_registered_with_hub();
// Prediction Markets — `prediction:polymarket:*`.
fincept::services::polymarket::PolymarketWebSocket::instance().ensure_registered_with_hub();
- // Alpha Arena engine — TickClock, ModelDispatcher, OrderRouter,
- // PaperVenue. Not a DataHub Producer (callback-style by design).
- // init() is idempotent; pre-resolves crash-recovery state.
- fincept::services::alpha_arena::AlphaArenaEngine::instance().init();
+ // Alpha Arena engine — init() is idempotent and only scans for
+ // crashed competitions (no-op with none). Not a DataHub Producer
+ // (callback-style by design).
+ fincept::arena::ArenaEngine::instance().init();
{
auto& reg = fincept::services::prediction::PredictionExchangeRegistry::instance();
reg.register_adapter(
@@ -743,6 +745,9 @@ int main(int argc, char* argv[]) {
fincept::register_migration_v045();
fincept::register_migration_v046();
fincept::register_migration_v047();
+ fincept::register_migration_v048();
+ fincept::register_migration_v049();
+ fincept::register_migration_v050();
// Open main database
QString db_path = fincept::AppPaths::data() + "/fincept.db";
@@ -906,8 +911,12 @@ int main(int argc, char* argv[]) {
return fincept::algo::run_universe_scan_selftest();
if (qstrcmp(argv[i], "--selftest-paper") == 0)
return fincept::trading::run_paper_trading_selftest();
+ if (qstrcmp(argv[i], "--selftest-portfolio-monitor") == 0)
+ return fincept::trading::run_portfolio_monitor_selftest();
if (qstrcmp(argv[i], "--selftest-portfolio-replication") == 0)
return fincept::trading::replication::run_portfolio_replication_selftest();
+ if (qstrcmp(argv[i], "--selftest-arena") == 0)
+ return fincept::arena::run_arena_selftest();
}
// Start the scan-watch background service. Runs after Database::open() (which
diff --git a/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp b/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp
index 0644ab9e3..0568c464e 100644
--- a/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp
+++ b/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp
@@ -1,667 +1,484 @@
#include "screens/alpha_arena/AlphaArenaScreen.h"
-
-#include "core/logging/Logger.h"
-#include "screens/alpha_arena/panels/Geofence.h"
-#include "screens/alpha_arena/panels/LeaderboardPanel.h"
-#include "screens/alpha_arena/panels/LiveModeGateDialog.h"
-#include "screens/alpha_arena/panels/ModelChatPanel.h"
-#include "screens/alpha_arena/panels/StatePanels.h"
-#include "services/alpha_arena/AlphaArenaEngine.h"
-#include "services/alpha_arena/AlphaArenaSchema.h"
-#include "trading/exchanges/hyperliquid/HyperliquidSigner.h"
-#include "storage/repositories/LlmConfigRepository.h"
-#include "storage/repositories/LlmProfileRepository.h"
-#include "ui/theme/Theme.h"
-
-#include <QButtonGroup>
-#include <QGridLayout>
-#include <QGroupBox>
+#include "screens/alpha_arena/ArenaTabs.h"
+#include "screens/alpha_arena/EquityCurveWidget.h"
+#include "screens/alpha_arena/LeaderboardCards.h"
+#include "screens/alpha_arena/NewCompetitionWizard.h"
+#include "services/alpha_arena/ArenaEngine.h"
+#include "services/alpha_arena/ArenaStore.h"
+#include <QComboBox>
#include <QHBoxLayout>
-#include <QHideEvent>
-#include <QInputDialog>
+#include <QLabel>
#include <QLocale>
-#include <QMenu>
#include <QMessageBox>
-#include <QShowEvent>
+#include <QPushButton>
+#include <QSpinBox>
#include <QSplitter>
+#include <QStackedWidget>
+#include <QTimer>
#include <QVBoxLayout>
+#include <algorithm>
namespace fincept::screens::alpha_arena {
+using fincept::arena::ArenaEngine;
+using fincept::arena::ArenaStore;
-using fincept::services::alpha_arena::AgentSpec;
-using fincept::services::alpha_arena::AlphaArenaEngine;
-using fincept::services::alpha_arena::CompetitionMode;
-using fincept::services::alpha_arena::NewCompetitionConfig;
-using fincept::services::alpha_arena::kPerpUniverse;
-
-// ── Construction ────────────────────────────────────────────────────────────
+namespace {
+QString fmt_mid(double v) {
+ const int dp = v >= 1000 ? 1 : v >= 10 ? 2 : 4;
+ return QLocale(QLocale::English, QLocale::UnitedStates).toString(v, 'f', dp);
+}
+} // namespace
AlphaArenaScreen::AlphaArenaScreen(QWidget* parent) : QWidget(parent) {
setObjectName("aaScreen");
- build_ui();
-
- countdown_timer_ = new QTimer(this);
- countdown_timer_->setInterval(1000);
- connect(countdown_timer_, &QTimer::timeout, this, &AlphaArenaScreen::on_countdown_tick);
-
- populate_model_list();
-}
-
-void AlphaArenaScreen::build_ui() {
auto* root = new QVBoxLayout(this);
root->setContentsMargins(0, 0, 0, 0);
root->setSpacing(0);
-
root->addWidget(build_header());
+ root->addWidget(build_ticker_strip());
- disclaimer_ = new QLabel(tr(
- "⚠ LIVE MODE — orders are sent to Hyperliquid with real funds. "
- "Past performance ≠ future results. Not financial advice."));
- disclaimer_->setObjectName("aaDisclaimer");
- disclaimer_->setStyleSheet("background:#5C1F1F;color:#FFD; padding:6px 12px; font-weight:700;");
+ disclaimer_ = new QLabel(tr("⚠ LIVE MODE — orders are sent to Hyperliquid with real funds. "
+ "Past performance ≠ future results. Not financial advice."));
+ disclaimer_->setStyleSheet("background:#5C1F1F;color:#FFD;padding:4px 12px;font-weight:700;"
+ "font-size:11px;");
disclaimer_->hide();
root->addWidget(disclaimer_);
- root->addWidget(build_create_panel());
- root->addWidget(build_main(), 1);
+ body_ = new QStackedWidget;
+ body_->addWidget(build_empty_state());
+ body_->addWidget(build_dashboard());
+ root->addWidget(body_, 1);
+
+ countdown_ = new QTimer(this);
+ countdown_->setInterval(1000);
+ connect(countdown_, &QTimer::timeout, this, [this]() {
+ const int s = ArenaEngine::instance().next_round_in_seconds();
+ countdown_label_->setText(s >= 0 ? tr("next %1:%2").arg(s / 60).arg(s % 60, 2, 10, QChar('0'))
+ : QStringLiteral("--"));
+ round_label_->setText(tr("ROUND %1").arg(ArenaEngine::instance().round_seq()));
+ });
}
QWidget* AlphaArenaScreen::build_header() {
auto* hdr = new QWidget;
- hdr->setObjectName("aaHeader");
- hdr->setFixedHeight(44);
- auto* hl = new QHBoxLayout(hdr);
- hl->setContentsMargins(12, 0, 12, 0);
- hl->setSpacing(10);
-
- title_label_ = new QLabel(tr("ALPHA ARENA"));
- title_label_->setStyleSheet("color:#FF8800;font-weight:700;font-size:13px;");
- hl->addWidget(title_label_);
-
+ hdr->setFixedHeight(38);
+ hdr->setStyleSheet("background:#141414;border-bottom:1px solid #2A2A2A;");
+ auto* h = new QHBoxLayout(hdr);
+ h->setContentsMargins(10, 0, 10, 0);
+ h->setSpacing(8);
+ auto* title = new QLabel(tr("ALPHA ARENA"));
+ title->setStyleSheet("color:#FF8800;font-weight:700;font-size:12px;border:none;");
+ h->addWidget(title);
venue_badge_ = new QLabel(tr("PAPER"));
- venue_badge_->setStyleSheet("background:#222;color:#0F0;padding:2px 8px;font-weight:700;");
- hl->addWidget(venue_badge_);
-
status_badge_ = new QLabel(tr("IDLE"));
- status_badge_->setStyleSheet("background:#222;color:#888;padding:2px 8px;font-weight:700;");
- hl->addWidget(status_badge_);
-
- tick_label_ = new QLabel(tr("TICK %1").arg(tick_seq_));
- tick_label_->setStyleSheet("color:#bbb;");
- hl->addWidget(tick_label_);
-
+ round_label_ = new QLabel(tr("ROUND 0"));
countdown_label_ = new QLabel(QStringLiteral("--"));
- countdown_label_->setStyleSheet("color:#888;");
- hl->addWidget(countdown_label_);
-
- hl->addStretch(1);
-
- force_tick_btn_ = new QPushButton(tr("FORCE TICK"));
- connect(force_tick_btn_, &QPushButton::clicked, this, &AlphaArenaScreen::on_force_tick_clicked);
- hl->addWidget(force_tick_btn_);
-
- live_mode_btn_ = new QPushButton(tr("LIVE MODE…"));
- connect(live_mode_btn_, &QPushButton::clicked, this, &AlphaArenaScreen::on_live_mode_toggle_clicked);
- hl->addWidget(live_mode_btn_);
-
- kill_all_btn_ = new QPushButton(tr("KILL ALL"));
- kill_all_btn_->setStyleSheet("background:#C72020;color:#fff;font-weight:700;");
- connect(kill_all_btn_, &QPushButton::clicked, this, &AlphaArenaScreen::on_kill_all_clicked);
- hl->addWidget(kill_all_btn_);
-
- cadence_label_ = new QLabel(tr("CADENCE"));
- cadence_label_->setStyleSheet("color:#888;");
- hl->addWidget(cadence_label_);
- hot_cadence_spin_ = new QSpinBox;
- hot_cadence_spin_->setRange(10, 3600);
- hot_cadence_spin_->setValue(180);
- hot_cadence_spin_->setSuffix(QStringLiteral("s"));
- hl->addWidget(hot_cadence_spin_);
- apply_cadence_btn_ = new QPushButton(tr("APPLY"));
- connect(apply_cadence_btn_, &QPushButton::clicked, this, [this]() {
- auto r = AlphaArenaEngine::instance().set_cadence(hot_cadence_spin_->value());
- if (r.is_err()) {
+ for (auto* b : {venue_badge_, status_badge_})
+ b->setStyleSheet("background:#222;color:#888;padding:1px 7px;font-weight:700;font-size:10px;");
+ round_label_->setStyleSheet("color:#BBB;font-size:11px;border:none;"
+ "font-family:'Consolas','Courier New',monospace;");
+ countdown_label_->setStyleSheet("color:#888;font-size:11px;border:none;"
+ "font-family:'Consolas','Courier New',monospace;");
+ h->addWidget(venue_badge_); h->addWidget(status_badge_);
+ h->addWidget(round_label_); h->addWidget(countdown_label_);
+ h->addStretch(1);
+ switcher_ = new QComboBox;
+ switcher_->setMinimumWidth(180);
+ connect(switcher_, &QComboBox::activated, this, [this](int idx) {
+ show_competition(switcher_->itemData(idx).toString());
+ });
+ h->addWidget(switcher_);
+ pause_btn_ = new QPushButton(tr("⏸ PAUSE"));
+ connect(pause_btn_, &QPushButton::clicked, this, [this]() {
+ auto& e = ArenaEngine::instance();
+ const bool running = e.is_running();
+ auto r = running ? e.pause() : e.resume();
+ if (r.is_err()) QMessageBox::warning(this, tr("Alpha Arena"), QString::fromStdString(r.error()));
+ });
+ force_btn_ = new QPushButton(tr("⚡ FORCE ROUND"));
+ connect(force_btn_, &QPushButton::clicked, this, []() { ArenaEngine::instance().force_round(); });
+ kill_btn_ = new QPushButton(tr("✖ KILL ALL"));
+ kill_btn_->setStyleSheet("background:#C72020;color:#FFF;font-weight:700;");
+ connect(kill_btn_, &QPushButton::clicked, this, [this]() {
+ if (QMessageBox::question(this, tr("Alpha Arena"),
+ tr("Close every position and end the competition?")) != QMessageBox::Yes) return;
+ if (auto r = ArenaEngine::instance().kill_all(); r.is_err())
QMessageBox::warning(this, tr("Alpha Arena"), QString::fromStdString(r.error()));
- }
+ reload_competitions();
});
- hl->addWidget(apply_cadence_btn_);
-
+ auto* new_btn = new QPushButton(tr("+ NEW"));
+ new_btn->setStyleSheet("background:#FF8800;color:#000;font-weight:700;");
+ for (auto* b : {pause_btn_, force_btn_, kill_btn_, new_btn}) b->setFixedHeight(24);
+ connect(new_btn, &QPushButton::clicked, this, &AlphaArenaScreen::on_new_competition);
+ for (auto* b : {pause_btn_, force_btn_, kill_btn_, new_btn}) h->addWidget(b);
return hdr;
}
-QWidget* AlphaArenaScreen::build_create_panel() {
- create_panel_ = new QGroupBox(tr("New competition"));
- auto* grid = new QGridLayout(create_panel_);
- int row = 0;
-
- comp_name_lbl_ = new QLabel(tr("Name"));
- grid->addWidget(comp_name_lbl_, row, 0);
- comp_name_ = new QLineEdit(QStringLiteral("AlphaArena-1"));
- grid->addWidget(comp_name_, row++, 1);
-
- comp_mode_lbl_ = new QLabel(tr("Mode"));
- grid->addWidget(comp_mode_lbl_, row, 0);
- comp_mode_ = new QComboBox;
- comp_mode_->addItem(tr("Baseline"), QVariant::fromValue(int(CompetitionMode::Baseline)));
- comp_mode_->addItem(tr("Monk"), QVariant::fromValue(int(CompetitionMode::Monk)));
- comp_mode_->addItem(tr("Situational"), QVariant::fromValue(int(CompetitionMode::Situational)));
- grid->addWidget(comp_mode_, row++, 1);
-
- comp_venue_lbl_ = new QLabel(tr("Venue"));
- grid->addWidget(comp_venue_lbl_, row, 0);
- auto* venue_box = new QWidget;
- auto* vh = new QHBoxLayout(venue_box);
- vh->setContentsMargins(0, 0, 0, 0);
- venue_paper_ = new QRadioButton(tr("Paper"));
- venue_hl_ = new QRadioButton(tr("Hyperliquid (live)"));
- venue_us_eq_ = new QRadioButton(tr("US Equities (Season 2 — Coming)"));
- venue_us_eq_->setEnabled(false);
- venue_paper_->setChecked(true);
- auto* grp = new QButtonGroup(venue_box);
- grp->addButton(venue_paper_);
- grp->addButton(venue_hl_);
- grp->addButton(venue_us_eq_);
- vh->addWidget(venue_paper_);
- vh->addWidget(venue_hl_);
- vh->addWidget(venue_us_eq_);
- vh->addStretch(1);
- grid->addWidget(venue_box, row++, 1);
-
- comp_capital_lbl_ = new QLabel(tr("Initial capital / agent"));
- grid->addWidget(comp_capital_lbl_, row, 0);
- comp_capital_ = new QDoubleSpinBox;
- comp_capital_->setRange(100, 1'000'000);
- comp_capital_->setValue(10000);
- grid->addWidget(comp_capital_, row++, 1);
-
- comp_cadence_lbl_ = new QLabel(tr("Cadence (s)"));
- grid->addWidget(comp_cadence_lbl_, row, 0);
- comp_cadence_ = new QSpinBox;
- comp_cadence_->setRange(60, 600);
- comp_cadence_->setValue(180);
- grid->addWidget(comp_cadence_, row++, 1);
-
- comp_instruments_lbl_ = new QLabel(tr("Instruments"));
- grid->addWidget(comp_instruments_lbl_, row, 0);
- comp_instruments_ = new QListWidget;
- comp_instruments_->setSelectionMode(QAbstractItemView::MultiSelection);
- comp_instruments_->setMaximumHeight(80);
- for (const auto& sym : kPerpUniverse()) {
- auto* it = new QListWidgetItem(sym, comp_instruments_);
- it->setSelected(true);
- }
- grid->addWidget(comp_instruments_, row++, 1);
-
- comp_models_lbl_ = new QLabel(tr("Models"));
- grid->addWidget(comp_models_lbl_, row, 0);
- model_list_ = new QListWidget;
- model_list_->setSelectionMode(QAbstractItemView::MultiSelection);
- model_list_->setMaximumHeight(120);
- grid->addWidget(model_list_, row++, 1);
-
- auto* btn_row = new QWidget;
- auto* bh = new QHBoxLayout(btn_row);
- bh->setContentsMargins(0, 0, 0, 0);
- create_btn_ = new QPushButton(tr("CREATE"));
- start_btn_ = new QPushButton(tr("START"));
- start_btn_->setEnabled(false);
- bh->addStretch(1);
- bh->addWidget(create_btn_);
- bh->addWidget(start_btn_);
- grid->addWidget(btn_row, row++, 1);
-
- connect(create_btn_, &QPushButton::clicked, this, &AlphaArenaScreen::on_create_clicked);
- connect(start_btn_, &QPushButton::clicked, this, &AlphaArenaScreen::on_start_clicked);
-
- return create_panel_;
-}
-
-QWidget* AlphaArenaScreen::build_right_stack() {
- auto* container = new QWidget;
- auto* root = new QVBoxLayout(container);
- root->setContentsMargins(0, 0, 0, 0);
- root->setSpacing(0);
-
- auto* tabs = new QWidget;
- auto* tabs_h = new QHBoxLayout(tabs);
- tabs_h->setContentsMargins(0, 0, 0, 0);
- const QStringList labels = {tr("MODEL CHAT"), tr("POSITIONS"),
- tr("HITL"), tr("RISK"), tr("AUDIT")};
- for (int i = 0; i < labels.size(); ++i) {
- auto* b = new QPushButton(labels[i]);
- b->setProperty("active", i == 0);
- connect(b, &QPushButton::clicked, this, [this, i]() { on_right_tab_changed(i); });
- right_tab_btns_.append(b);
- tabs_h->addWidget(b);
- }
- tabs_h->addStretch(1);
- root->addWidget(tabs);
-
- right_stack_ = new QStackedWidget;
- modelchat_ = new ModelChatPanel;
- positions_ = new PositionsPanel;
- hitl_ = new HitlPanel;
- risk_ = new RiskPanel;
- audit_ = new AuditPanel;
- right_stack_->addWidget(modelchat_);
- right_stack_->addWidget(positions_);
- right_stack_->addWidget(hitl_);
- right_stack_->addWidget(risk_);
- right_stack_->addWidget(audit_);
- root->addWidget(right_stack_, 1);
-
- connect(hitl_, &HitlPanel::approval_resolved,
- this, &AlphaArenaScreen::on_hitl_resolved);
-
- return container;
-}
-
-QWidget* AlphaArenaScreen::build_main() {
- auto* split = new QSplitter(Qt::Horizontal);
- leaderboard_ = new LeaderboardPanel;
- connect(leaderboard_, &LeaderboardPanel::agent_double_clicked, this,
- [this](const QString& agent_id) {
- if (agent_id.isEmpty()) return;
- QStringList opts{tr("Halt"), tr("Resume")};
- bool ok = false;
- const QString choice = QInputDialog::getItem(
- this, tr("Agent action"),
- tr("Action for agent %1?").arg(agent_id.left(8)),
- opts, 0, false, &ok);
- if (!ok) return;
- auto& engine = AlphaArenaEngine::instance();
- auto r = (choice == opts[0]) ? engine.halt_agent(agent_id)
- : engine.resume_agent(agent_id);
- if (r.is_err()) {
- QMessageBox::warning(this, tr("Alpha Arena"),
- QString::fromStdString(r.error()));
- }
- refresh_all_panels();
- });
- split->addWidget(leaderboard_);
- split->addWidget(build_right_stack());
- split->setStretchFactor(0, 1);
- split->setStretchFactor(1, 1);
- return split;
+// Second strip: live mids ticker (left, monospace, colored vs previous tick)
+// + inline cadence editor (right: CADENCE [spin]s ✓).
+QWidget* AlphaArenaScreen::build_ticker_strip() {
+ auto* strip = new QWidget;
+ strip->setFixedHeight(24);
+ strip->setStyleSheet("background:#0D0D0D;border-bottom:1px solid #2A2A2A;");
+ auto* h = new QHBoxLayout(strip);
+ h->setContentsMargins(10, 0, 10, 0);
+ h->setSpacing(8);
+
+ ticker_ = new QLabel(QStringLiteral("--"));
+ ticker_->setTextFormat(Qt::RichText);
+ ticker_->setStyleSheet("color:#777;font-size:11px;border:none;"
+ "font-family:'Consolas','Courier New',monospace;");
+ h->addWidget(ticker_, 1);
+
+ auto* cad = new QLabel(tr("CADENCE"));
+ cad->setStyleSheet("color:#777;font-size:10px;font-weight:700;border:none;");
+ h->addWidget(cad);
+ cadence_spin_ = new QSpinBox;
+ cadence_spin_->setRange(60, 3600);
+ cadence_spin_->setValue(180);
+ cadence_spin_->setSuffix(QStringLiteral("s"));
+ cadence_spin_->setFixedHeight(18);
+ cadence_spin_->setToolTip(tr("Round cadence (60–3600 seconds)"));
+ cadence_spin_->setStyleSheet(
+ "QSpinBox{background:#141414;color:#DDD;border:1px solid #2A2A2A;font-size:11px;"
+ " padding:0 2px;font-family:'Consolas','Courier New',monospace;}");
+ h->addWidget(cadence_spin_);
+ auto* apply = new QPushButton(QStringLiteral("✓"));
+ apply->setToolTip(tr("Apply cadence to the running competition"));
+ apply->setFixedSize(20, 18);
+ apply->setCursor(Qt::PointingHandCursor);
+ apply->setStyleSheet("QPushButton{background:#222;color:#FF8800;border:1px solid #2A2A2A;"
+ "font-weight:700;padding:0;}QPushButton:hover{background:#2A2A2A;}");
+ connect(apply, &QPushButton::clicked, this, [this]() {
+ if (auto r = ArenaEngine::instance().set_cadence(cadence_spin_->value()); r.is_err())
+ QMessageBox::warning(this, tr("Alpha Arena"), QString::fromStdString(r.error()));
+ });
+ h->addWidget(apply);
+ return strip;
+}
+
+QWidget* AlphaArenaScreen::build_empty_state() {
+ auto* page = new QWidget;
+ auto* v = new QVBoxLayout(page);
+ v->addStretch(2);
+ auto* big = new QLabel(tr("ALPHA ARENA"));
+ big->setAlignment(Qt::AlignCenter);
+ big->setStyleSheet("color:#FF8800;font-size:28px;font-weight:800;");
+ auto* sub = new QLabel(tr("Pit LLMs against each other in a live crypto trading competition.\n"
+ "Real Hyperliquid market data · paper money · any provider, or free with Ollama."));
+ sub->setAlignment(Qt::AlignCenter);
+ sub->setStyleSheet("color:#999;font-size:13px;");
+ auto* cta = new QPushButton(tr("+ NEW COMPETITION"));
+ cta->setFixedSize(260, 44);
+ cta->setStyleSheet("background:#FF8800;color:#000;font-weight:800;font-size:14px;");
+ connect(cta, &QPushButton::clicked, this, &AlphaArenaScreen::on_new_competition);
+ v->addWidget(big);
+ v->addWidget(sub);
+ auto* hb = new QHBoxLayout;
+ hb->addStretch(1); hb->addWidget(cta); hb->addStretch(1);
+ v->addLayout(hb);
+ v->addStretch(3);
+ return page;
+}
+
+QWidget* AlphaArenaScreen::build_dashboard() {
+ chart_ = new EquityCurveWidget;
+ cards_ = new LeaderboardCards;
+ grid_ = new ArenaPanelGrid;
+
+ auto* top = new QSplitter(Qt::Horizontal);
+ top->setHandleWidth(1);
+ top->setChildrenCollapsible(false);
+ top->setStyleSheet("QSplitter::handle{background:#2A2A2A;}");
+ top->addWidget(chart_);
+ top->addWidget(cards_);
+ top->setStretchFactor(0, 58);
+ top->setStretchFactor(1, 42);
+ top->setSizes({580, 420});
+
+ auto* body = new QSplitter(Qt::Vertical);
+ body->setHandleWidth(1);
+ body->setChildrenCollapsible(false);
+ body->setStyleSheet("QSplitter::handle{background:#2A2A2A;}");
+ body->addWidget(top);
+ body->addWidget(grid_);
+ body->setStretchFactor(0, 45);
+ body->setStretchFactor(1, 55);
+ body->setSizes({450, 550});
+
+ auto* page = new QWidget;
+ auto* v = new QVBoxLayout(page);
+ v->setContentsMargins(0, 0, 0, 0);
+ v->setSpacing(0);
+ v->addWidget(body, 1);
+
+ connect(cards_, &LeaderboardCards::agent_selected, this, [this](const QString& id) {
+ grid_->set_agent_filter(id);
+ });
+ connect(cards_, &LeaderboardCards::halt_requested, this, [this](const QString& id) {
+ ArenaEngine::instance().halt_agent(id); refresh_dashboard();
+ });
+ connect(cards_, &LeaderboardCards::resume_requested, this, [this](const QString& id) {
+ ArenaEngine::instance().resume_agent(id); refresh_dashboard();
+ });
+ connect(cards_, &LeaderboardCards::kill_requested, this, [this](const QString& id) {
+ QString name = id.left(8);
+ for (const auto& a : agents_cache_)
+ if (a.id == id) name = a.display_name;
+ if (QMessageBox::question(this, tr("Alpha Arena"),
+ tr("Close all positions of %1 and halt it?").arg(name)) != QMessageBox::Yes) return;
+ if (auto r = ArenaEngine::instance().kill_agent(id); r.is_err())
+ QMessageBox::warning(this, tr("Alpha Arena"), QString::fromStdString(r.error()));
+ refresh_dashboard();
+ });
+ connect(grid_, &ArenaPanelGrid::hitl_resolved, this, [](const QString& id, bool ok) {
+ ArenaEngine::instance().resume_after_hitl(id, ok);
+ });
+ return page;
}
-// ── Lifecycle ──────────────────────────────────────────────────────────────
-
void AlphaArenaScreen::showEvent(QShowEvent* e) {
QWidget::showEvent(e);
- populate_model_list();
-
- // Reattach to the engine's currently-active competition (if any).
- auto& engine = AlphaArenaEngine::instance();
- if (!engine.active_competition_id().isEmpty()) {
- apply_competition_id(engine.active_competition_id());
- }
-
- connect_engine_signals();
- refresh_all_panels();
- countdown_timer_->start();
+ connect_engine();
+ reload_competitions();
+ const QString active = ArenaEngine::instance().active_competition_id();
+ if (!active.isEmpty()) show_competition(active);
+ else if (!competition_id_.isEmpty()) show_competition(competition_id_);
+ countdown_->start();
+ // The engine's crash_recovery_pending signal fires at app startup, before
+ // any screen exists — poll the queryable list here so the offer isn't lost.
+ // Deferred: a modal dialog inside showEvent can re-enter during dock
+ // retiling and stack a second prompt.
+ QTimer::singleShot(0, this, &AlphaArenaScreen::maybe_offer_crash_recovery);
}
void AlphaArenaScreen::hideEvent(QHideEvent* e) {
QWidget::hideEvent(e);
- disconnect_engine_signals();
- countdown_timer_->stop();
-}
-
-void AlphaArenaScreen::connect_engine_signals() {
- auto& engine = AlphaArenaEngine::instance();
- engine_conns_.append(connect(&engine, &AlphaArenaEngine::tick_fired,
- this, &AlphaArenaScreen::on_engine_tick));
- engine_conns_.append(connect(&engine, &AlphaArenaEngine::decision_received,
- this, &AlphaArenaScreen::on_engine_decision_received));
- engine_conns_.append(connect(&engine, &AlphaArenaEngine::hitl_requested,
- this, &AlphaArenaScreen::on_engine_hitl_requested));
- engine_conns_.append(connect(&engine, &AlphaArenaEngine::agent_circuit_open,
- this, &AlphaArenaScreen::on_engine_circuit_open));
- engine_conns_.append(connect(&engine, &AlphaArenaEngine::competition_status_changed,
- this, &AlphaArenaScreen::on_engine_status_changed));
- engine_conns_.append(connect(&engine, &AlphaArenaEngine::crash_recovery_pending,
- this, &AlphaArenaScreen::on_engine_crash_recovery));
+ disconnect_engine();
+ countdown_->stop();
}
-void AlphaArenaScreen::disconnect_engine_signals() {
- for (auto& c : engine_conns_) QObject::disconnect(c);
- engine_conns_.clear();
+void AlphaArenaScreen::connect_engine() {
+ if (!conns_.isEmpty()) return; // re-show without hide must not stack duplicates
+ auto& eng = ArenaEngine::instance();
+ conns_ << connect(&eng, &ArenaEngine::round_completed, this, [this](int) { refresh_dashboard(); });
+ conns_ << connect(&eng, &ArenaEngine::decision_received, this, [this](QString, QString, QString) {
+ if (grid_) grid_->refresh();
+ });
+ conns_ << connect(&eng, &ArenaEngine::order_executed, this, [this](QString, QString, QString) {
+ if (grid_) grid_->refresh();
+ });
+ conns_ << connect(&eng, &ArenaEngine::agent_status_changed, this, [this](QString, QString, QString) {
+ refresh_dashboard();
+ });
+ conns_ << connect(&eng, &ArenaEngine::competition_status_changed, this,
+ [this](QString id, QString status) {
+ if (id == competition_id_) update_badges(status); // don't restyle a viewed past comp
+ reload_competitions();
+ });
+ conns_ << connect(&eng, &ArenaEngine::hitl_requested, this,
+ [this](QString id, QString agent_id, QString summary) {
+ QString label = agent_id.left(8);
+ if (auto r = ArenaStore::instance().agents_for(competition_id_); r.is_ok())
+ for (const auto& a : r.value()) if (a.id == agent_id) label = a.display_name;
+ if (grid_) grid_->add_hitl(id, label, summary);
+ });
+ conns_ << connect(&eng, &ArenaEngine::crash_recovery_pending, this,
+ [this](QStringList) { maybe_offer_crash_recovery(); });
+ // Realtime: between-round live marks. Keep this handler LIGHT — ticker text,
+ // board rows from cached agent meta + account_view, positions uPnL column.
+ // No equity_series/chart re-read here (chart refreshes per round).
+ conns_ << connect(&eng, &ArenaEngine::marks_updated, this, [this]() {
+ update_ticker();
+ rebuild_board_light();
+ if (grid_) grid_->refresh_positions_only();
+ });
}
-// ── User intents ───────────────────────────────────────────────────────────
-
-void AlphaArenaScreen::on_create_clicked() {
- NewCompetitionConfig cfg;
- cfg.name = comp_name_->text();
- cfg.mode = static_cast<CompetitionMode>(comp_mode_->currentData().toInt());
- cfg.initial_capital_per_agent = comp_capital_->value();
- cfg.cadence_seconds = comp_cadence_->value();
- cfg.venue_kind = venue_hl_->isChecked() ? QStringLiteral("hyperliquid") : QStringLiteral("paper");
- cfg.live_mode = live_mode_engaged_;
-
- for (int i = 0; i < comp_instruments_->count(); ++i) {
- auto* it = comp_instruments_->item(i);
- if (it->isSelected()) cfg.instruments << it->text();
- }
- if (cfg.instruments.isEmpty()) {
- QMessageBox::warning(this, tr("Alpha Arena"), tr("Select at least one instrument."));
- return;
- }
-
- QList<QListWidgetItem*> selected = model_list_->selectedItems();
- if (selected.isEmpty()) {
- QMessageBox::warning(this, tr("Alpha Arena"), tr("Select at least one model."));
- return;
- }
- for (auto* it : selected) {
- const int idx = model_list_->row(it);
- if (idx < 0 || idx >= model_entries_.size()) continue;
- const auto& m = model_entries_[idx];
- AgentSpec a;
- a.provider = m.provider;
- a.model_id = m.model_id;
- a.display_name = m.display_name;
- a.api_key = m.api_key;
- a.base_url = m.base_url;
- cfg.agents.append(a);
+void AlphaArenaScreen::disconnect_engine() {
+ for (auto& c : conns_) QObject::disconnect(c);
+ conns_.clear();
+}
+
+void AlphaArenaScreen::maybe_offer_crash_recovery() {
+ static bool prompt_open = false; // multiple deferred show events must not stack dialogs
+ if (prompt_open) return;
+ auto& eng = ArenaEngine::instance();
+ const QStringList ids = eng.pending_crash_recoveries();
+ if (ids.isEmpty() || !eng.active_competition_id().isEmpty()) return;
+ prompt_open = true;
+ const auto pick = QMessageBox::question(this, tr("Alpha Arena — Crash Recovery"),
+ tr("The previous session left %1 competition(s) running.\nResume the most recent one?")
+ .arg(ids.size()));
+ prompt_open = false;
+ if (pick == QMessageBox::Yes) {
+ if (auto r = eng.start(ids.first()); r.is_ok()) show_competition(ids.first());
+ } else {
+ for (const auto& id : ids) eng.dismiss_crash_recovery(id);
}
+ reload_competitions();
+}
- auto r = AlphaArenaEngine::instance().create_competition(cfg);
- if (r.is_err()) {
- QMessageBox::critical(this, tr("Alpha Arena"),
- QString::fromStdString(r.error()));
- return;
- }
- apply_competition_id(r.value());
- start_btn_->setEnabled(true);
- LOG_INFO("AlphaArena", QStringLiteral("Competition created: %1").arg(r.value()));
+void AlphaArenaScreen::reload_competitions() {
+ switcher_->blockSignals(true);
+ switcher_->clear();
+ if (auto r = ArenaStore::instance().list_competitions(); r.is_ok())
+ for (const auto& c : r.value())
+ switcher_->addItem(QStringLiteral("%1 (%2)").arg(c.name, c.status), c.id);
+ for (int i = 0; i < switcher_->count(); ++i)
+ if (switcher_->itemData(i).toString() == competition_id_) switcher_->setCurrentIndex(i);
+ switcher_->blockSignals(false);
}
-void AlphaArenaScreen::on_start_clicked() {
+void AlphaArenaScreen::show_competition(const QString& id) {
+ if (id.isEmpty()) { body_->setCurrentIndex(0); return; }
+ competition_id_ = id;
+ auto comp = ArenaStore::instance().competition(id);
+ if (comp.is_err()) { body_->setCurrentIndex(0); return; }
+ body_->setCurrentIndex(1);
+ grid_->set_competition(id, comp.value().live_mode);
+ disclaimer_->setVisible(comp.value().live_mode);
+ cadence_spin_->setValue(comp.value().cadence_seconds);
+ last_mids_.clear(); // fresh ticker baseline for the new competition
+ venue_badge_->setText(comp.value().live_mode ? tr("HYPERLIQUID • LIVE") : tr("PAPER"));
+ venue_badge_->setStyleSheet(comp.value().live_mode
+ ? "background:#5C1F1F;color:#FFD;padding:1px 7px;font-weight:700;font-size:10px;"
+ : "background:#222;color:#0F0;padding:1px 7px;font-weight:700;font-size:10px;");
+ update_badges(comp.value().status);
+ refresh_dashboard();
+ reload_competitions();
+}
+
+void AlphaArenaScreen::refresh_dashboard() {
if (competition_id_.isEmpty()) return;
- auto r = AlphaArenaEngine::instance().start(competition_id_);
- if (r.is_err()) {
- QMessageBox::critical(this, tr("Alpha Arena"),
- QString::fromStdString(r.error()));
- return;
+ auto comp = ArenaStore::instance().competition(competition_id_);
+ auto agents = ArenaStore::instance().agents_for(competition_id_);
+ if (comp.is_err() || agents.is_err()) return;
+ cap_ = comp.value().capital_per_agent;
+ agents_cache_ = agents.value();
+ const bool is_active = ArenaEngine::instance().active_competition_id() == competition_id_;
+
+ // Chart series from equity snapshots.
+ auto eq = ArenaStore::instance().equity_series(competition_id_);
+ QHash<QString, EquitySeries> by_agent;
+ for (const auto& a : agents.value()) {
+ EquitySeries s; s.agent_id = a.id; s.label = a.display_name; s.color = QColor(a.color_hex);
+ by_agent[a.id] = s;
}
- create_panel_->hide();
- update_status_badge(QStringLiteral("running"));
-}
-
-void AlphaArenaScreen::on_force_tick_clicked() {
- AlphaArenaEngine::instance();
- // TickClock::force_tick is the public engine surface for this; if absent
- // (engine not running) we just refresh panels as a no-op.
- refresh_all_panels();
-}
-
-void AlphaArenaScreen::on_kill_all_clicked() {
- if (QMessageBox::question(this, tr("Alpha Arena"),
- tr("Close every agent's positions and stop the competition?\n"
- "This cannot be undone."),
- QMessageBox::Yes | QMessageBox::No)
- != QMessageBox::Yes) {
- return;
+ if (eq.is_ok())
+ for (const auto& snap : eq.value())
+ if (by_agent.contains(snap.agent_id))
+ by_agent[snap.agent_id].points.append(QPointF(double(snap.ts), snap.equity));
+ chart_->set_data(by_agent.values(), cap_);
+
+ // Agent board.
+ auto tokens = ArenaStore::instance().token_totals(competition_id_);
+ tokens_cache_ = tokens.is_ok() ? tokens.value() : QHash<QString, qint64>{};
+ QVector<AgentCardData> rows;
+ for (const auto& a : agents.value()) {
+ AgentCardData c;
+ c.agent_id = a.id; c.name = a.display_name; c.status = a.status; c.color = QColor(a.color_hex);
+ c.tokens = tokens_cache_.value(a.id);
+ if (is_active) {
+ const auto acct = ArenaEngine::instance().account_view(a.id);
+ c.equity = acct.equity; c.open_positions = acct.positions.size();
+ for (auto it = acct.upnl.cbegin(); it != acct.upnl.cend(); ++it) c.upnl += it.value();
+ } else if (!by_agent[a.id].points.isEmpty()) {
+ c.equity = by_agent[a.id].points.last().y();
+ } else {
+ c.equity = cap_;
+ }
+ c.pnl_pct = cap_ > 0 ? (c.equity - cap_) / cap_ * 100.0 : 0;
+ rows.append(c);
+ }
+ std::sort(rows.begin(), rows.end(),
+ [](const AgentCardData& x, const AgentCardData& y) { return x.equity > y.equity; });
+ cards_->set_data(rows);
+ grid_->refresh();
+ update_ticker();
+}
+
+// Mids ticker: `BTC 94,126.0 ▲ · ETH 3,120.5 ▼ · …`, arrow/color vs the
+// previously displayed mid. Runs every marks tick — string building only.
+void AlphaArenaScreen::update_ticker() {
+ const auto mids = ArenaEngine::instance().current_marks();
+ if (mids.isEmpty()) { ticker_->setText(QStringLiteral("--")); return; }
+ QStringList coins = mids.keys();
+ std::sort(coins.begin(), coins.end());
+ QStringList parts;
+ for (const auto& coin : coins) {
+ const double m = mids.value(coin);
+ const double prev = last_mids_.value(coin, m);
+ const QString color = m > prev ? QStringLiteral("#26A65B")
+ : m < prev ? QStringLiteral("#E0245E") : QStringLiteral("#999");
+ const QString arrow = m > prev ? QStringLiteral("▲")
+ : m < prev ? QStringLiteral("▼") : QStringLiteral("–");
+ parts << QStringLiteral("<span style='color:#777'>%1</span>"
+ " <span style='color:%2'>%3 %4</span>")
+ .arg(coin.toHtmlEscaped(), color, fmt_mid(m), arrow);
}
- auto r = AlphaArenaEngine::instance().kill_all();
- if (r.is_err()) {
- QMessageBox::critical(this, tr("Alpha Arena"),
- QString::fromStdString(r.error()));
+ last_mids_ = mids;
+ ticker_->setText(parts.join(QStringLiteral(" <span style='color:#444'>·</span> ")));
+}
+
+// Cheap board rebuild on a marks tick: cached agent meta/tokens + live
+// account_view (≤8 agents). Skips entirely when viewing a past competition.
+void AlphaArenaScreen::rebuild_board_light() {
+ if (competition_id_.isEmpty() || agents_cache_.isEmpty()) return;
+ if (ArenaEngine::instance().active_competition_id() != competition_id_) return;
+ QVector<AgentCardData> rows;
+ for (const auto& a : agents_cache_) {
+ AgentCardData c;
+ c.agent_id = a.id; c.name = a.display_name; c.status = a.status; c.color = QColor(a.color_hex);
+ c.tokens = tokens_cache_.value(a.id);
+ const auto acct = ArenaEngine::instance().account_view(a.id);
+ c.equity = acct.equity; c.open_positions = acct.positions.size();
+ for (auto it = acct.upnl.cbegin(); it != acct.upnl.cend(); ++it) c.upnl += it.value();
+ c.pnl_pct = cap_ > 0 ? (c.equity - cap_) / cap_ * 100.0 : 0;
+ rows.append(c);
}
- update_status_badge(QStringLiteral("halted_by_user"));
+ std::sort(rows.begin(), rows.end(),
+ [](const AgentCardData& x, const AgentCardData& y) { return x.equity > y.equity; });
+ cards_->set_data(rows);
}
-void AlphaArenaScreen::on_live_mode_toggle_clicked() {
- if (competition_id_.isEmpty()) {
+void AlphaArenaScreen::on_new_competition() {
+ if (ArenaEngine::instance().is_running()) {
QMessageBox::information(this, tr("Alpha Arena"),
- tr("Create a competition first, then engage live mode."));
+ tr("A competition is already running. Stop it (KILL ALL) before starting a new one."));
return;
}
- if (!fincept::trading::hyperliquid::HyperliquidSigner::is_wired()) {
- QMessageBox::critical(this, tr("Alpha Arena"),
- tr("Live mode is not available in this build — the Hyperliquid signer "
- "(secp256k1 + keccak256) failed to initialise. Check the build log."));
+ NewCompetitionWizard wiz(this);
+ if (wiz.exec() != QDialog::Accepted) return;
+ auto create_r = ArenaEngine::instance().create_competition(wiz.config());
+ if (create_r.is_err()) {
+ QMessageBox::critical(this, tr("Alpha Arena"), QString::fromStdString(create_r.error()));
return;
}
- // Geofence (best-effort).
-#ifndef FINCEPT_UNSAFE_DISABLE_GEOFENCE
- if (is_jurisdiction_blocked(QLocale::system().territory())) {
- QMessageBox::critical(this, tr("Alpha Arena"),
- tr("Live mode is unavailable in your jurisdiction."));
+ if (auto r = ArenaEngine::instance().start(create_r.value()); r.is_err()) {
+ QMessageBox::critical(this, tr("Alpha Arena"), QString::fromStdString(r.error()));
return;
}
-#endif
- LiveModeGateDialog dlg(competition_id_, this);
- if (dlg.exec() == QDialog::Accepted) {
- live_mode_engaged_ = true;
- show_disclaimer_if_live(true);
- update_venue_badge();
- }
-}
-
-void AlphaArenaScreen::on_right_tab_changed(int idx) {
- if (idx < 0 || idx >= right_stack_->count()) return;
- right_stack_->setCurrentIndex(idx);
- for (int i = 0; i < right_tab_btns_.size(); ++i) {
- right_tab_btns_[i]->setProperty("active", i == idx);
- right_tab_btns_[i]->style()->unpolish(right_tab_btns_[i]);
- right_tab_btns_[i]->style()->polish(right_tab_btns_[i]);
- }
- refresh_all_panels();
-}
-
-// ── Engine signal handlers ─────────────────────────────────────────────────
-
-void AlphaArenaScreen::on_engine_tick(int seq) {
- tick_seq_ = seq;
- tick_label_->setText(tr("TICK %1").arg(seq));
- refresh_all_panels();
-}
-
-void AlphaArenaScreen::on_engine_decision_received(QString decision_id, QString agent_id) {
- if (modelchat_) modelchat_->on_decision_received(decision_id, agent_id);
-}
-
-void AlphaArenaScreen::on_engine_hitl_requested(QString approval_id, QString agent_id, QString summary) {
- if (hitl_) hitl_->on_hitl_requested(approval_id, agent_id, summary);
- on_right_tab_changed(2); // surface HITL tab
-}
-
-void AlphaArenaScreen::on_engine_circuit_open(QString agent_id, QString reason) {
- LOG_WARN("AlphaArena", QStringLiteral("Agent %1 circuit open: %2").arg(agent_id, reason));
- if (risk_) risk_->refresh();
-}
-
-void AlphaArenaScreen::on_engine_status_changed(QString /*competition_id*/, QString status) {
- update_status_badge(status);
-}
-
-void AlphaArenaScreen::on_engine_crash_recovery(QStringList competition_ids) {
- if (competition_ids.isEmpty()) return;
- QMessageBox::warning(this, tr("Alpha Arena — Crash Recovery"),
- tr("The previous session left %1 competition(s) running. Open the "
- "competition picker to Resume / Halt / Reconcile.")
- .arg(competition_ids.size()));
-}
-
-void AlphaArenaScreen::on_hitl_resolved(QString approval_id, bool approved) {
- AlphaArenaEngine::instance().resume_after_hitl(approval_id, approved);
+ show_competition(create_r.value());
}
-void AlphaArenaScreen::on_countdown_tick() {
- auto& engine = AlphaArenaEngine::instance();
- if (!engine.is_running()) {
- countdown_label_->setText(QStringLiteral("--"));
- return;
- }
- countdown_label_->setText(QStringLiteral("%1s")
- .arg(engine.next_tick_in_seconds()));
-}
-
-// ── Helpers ────────────────────────────────────────────────────────────────
-
-void AlphaArenaScreen::populate_model_list() {
- model_list_->clear();
- model_entries_.clear();
-
- auto profiles_r = LlmProfileRepository::instance().list_profiles();
- if (profiles_r.is_ok()) {
- for (const auto& p : profiles_r.value()) {
- ArenaModelEntry e;
- e.display_name = p.name + QStringLiteral(" (") + p.model_id + QStringLiteral(")");
- e.provider = p.provider;
- e.model_id = p.model_id;
- e.api_key = p.api_key;
- e.base_url = p.base_url;
- e.profile_id = p.id;
- model_entries_.append(e);
- model_list_->addItem(e.display_name);
- }
- }
- auto cfg_r = LlmConfigRepository::instance().list_models();
- if (cfg_r.is_ok()) {
- for (const auto& m : cfg_r.value()) {
- if (!m.is_enabled) continue;
- ArenaModelEntry e;
- e.display_name = m.display_name + QStringLiteral(" (") + m.model_id + QStringLiteral(")");
- e.provider = m.provider;
- e.model_id = m.model_id;
- e.api_key = m.api_key;
- e.base_url = m.base_url;
- model_entries_.append(e);
- model_list_->addItem(e.display_name);
- }
- }
-}
-
-void AlphaArenaScreen::apply_competition_id(const QString& id) {
- competition_id_ = id;
- if (leaderboard_) leaderboard_->set_competition(id);
- if (modelchat_) modelchat_->set_competition(id);
- if (positions_) positions_->set_competition(id);
- if (hitl_) hitl_->set_competition(id);
- if (risk_) risk_->set_competition(id);
- if (audit_) audit_->set_competition(id);
-}
-
-void AlphaArenaScreen::update_status_badge(const QString& status) {
- competition_status_ = status;
- status_badge_->setText(status.toUpper());
- if (status == QLatin1String("running"))
- status_badge_->setStyleSheet("background:#0a4a18;color:#0F0;padding:2px 8px;font-weight:700;");
- else if (status.startsWith(QLatin1String("halted")) || status == QLatin1String("failed"))
- status_badge_->setStyleSheet("background:#5a1010;color:#FFB;padding:2px 8px;font-weight:700;");
- else
- status_badge_->setStyleSheet("background:#222;color:#888;padding:2px 8px;font-weight:700;");
-}
-
-void AlphaArenaScreen::update_venue_badge() {
- auto& engine = AlphaArenaEngine::instance();
- const QString k = engine.venue_kind();
- if (k == QLatin1String("hyperliquid")) {
- venue_badge_->setText(tr("HYPERLIQUID • LIVE"));
- venue_badge_->setStyleSheet("background:#5C1F1F;color:#FFD;padding:2px 8px;font-weight:700;");
+void AlphaArenaScreen::update_badges(const QString& status) {
+ status_badge_->setText(status.isEmpty() ? tr("IDLE") : status.toUpper());
+ if (status == QLatin1String("running")) {
+ status_badge_->setStyleSheet("background:#0A4A18;color:#0F0;padding:1px 7px;font-weight:700;font-size:10px;");
+ pause_btn_->setText(tr("⏸ PAUSE"));
} else {
- venue_badge_->setText(tr("PAPER"));
- venue_badge_->setStyleSheet("background:#222;color:#0F0;padding:2px 8px;font-weight:700;");
- }
-}
-
-void AlphaArenaScreen::show_disclaimer_if_live(bool live) {
- disclaimer_->setVisible(live);
-}
-
-void AlphaArenaScreen::refresh_all_panels() {
- if (leaderboard_) leaderboard_->refresh();
- if (modelchat_) modelchat_->refresh();
- if (positions_) positions_->refresh();
- if (hitl_) hitl_->refresh();
- if (risk_) risk_->refresh();
- if (audit_) audit_->refresh();
-}
-
-// ── Re-translation ──────────────────────────────────────────────────────────
-// Header chrome + create-panel labels. Status/venue badges and the tick line
-// are re-derived from current state; competition names, instrument symbols,
-// model display names and all table/list rows are model data, kept verbatim.
-
-void AlphaArenaScreen::changeEvent(QEvent* e) {
- if (e->type() == QEvent::LanguageChange)
- retranslateUi();
- QWidget::changeEvent(e);
-}
-
-void AlphaArenaScreen::retranslateUi() {
- // Header.
- if (title_label_) title_label_->setText(tr("ALPHA ARENA"));
- if (tick_label_) tick_label_->setText(tr("TICK %1").arg(tick_seq_));
- if (force_tick_btn_) force_tick_btn_->setText(tr("FORCE TICK"));
- if (live_mode_btn_) live_mode_btn_->setText(tr("LIVE MODE…"));
- if (kill_all_btn_) kill_all_btn_->setText(tr("KILL ALL"));
- if (cadence_label_) cadence_label_->setText(tr("CADENCE"));
- if (apply_cadence_btn_) apply_cadence_btn_->setText(tr("APPLY"));
- if (disclaimer_)
- disclaimer_->setText(tr(
- "⚠ LIVE MODE — orders are sent to Hyperliquid with real funds. "
- "Past performance ≠ future results. Not financial advice."));
-
- // Status + venue badges — re-derive from current state. The status code is
- // model data (uppercased verbatim); only the idle placeholder is translated.
- if (status_badge_) {
- if (competition_status_.isEmpty())
- status_badge_->setText(tr("IDLE"));
- else
- update_status_badge(competition_status_);
+ status_badge_->setStyleSheet("background:#222;color:#888;padding:1px 7px;font-weight:700;font-size:10px;");
+ pause_btn_->setText(tr("▶ RESUME"));
}
- if (venue_badge_) update_venue_badge();
-
- // Create panel.
- if (create_panel_) create_panel_->setTitle(tr("New competition"));
- if (comp_name_lbl_) comp_name_lbl_->setText(tr("Name"));
- if (comp_mode_lbl_) comp_mode_lbl_->setText(tr("Mode"));
- if (comp_venue_lbl_) comp_venue_lbl_->setText(tr("Venue"));
- if (comp_capital_lbl_) comp_capital_lbl_->setText(tr("Initial capital / agent"));
- if (comp_cadence_lbl_) comp_cadence_lbl_->setText(tr("Cadence (s)"));
- if (comp_instruments_lbl_) comp_instruments_lbl_->setText(tr("Instruments"));
- if (comp_models_lbl_) comp_models_lbl_->setText(tr("Models"));
- if (create_btn_) create_btn_->setText(tr("CREATE"));
- if (start_btn_) start_btn_->setText(tr("START"));
-
- // Mode combo — fixed UI labels; preserve current selection + enum data.
- if (comp_mode_ && comp_mode_->count() >= 3) {
- const int sel = comp_mode_->currentIndex();
- comp_mode_->setItemText(0, tr("Baseline"));
- comp_mode_->setItemText(1, tr("Monk"));
- comp_mode_->setItemText(2, tr("Situational"));
- comp_mode_->setCurrentIndex(sel);
- }
-
- // Venue radios.
- if (venue_paper_) venue_paper_->setText(tr("Paper"));
- if (venue_hl_) venue_hl_->setText(tr("Hyperliquid (live)"));
- if (venue_us_eq_) venue_us_eq_->setText(tr("US Equities (Season 2 — Coming)"));
-
- // Right-stack tab buttons.
- static const char* const kTabKeys[] = {
- QT_TR_NOOP("MODEL CHAT"), QT_TR_NOOP("POSITIONS"),
- QT_TR_NOOP("HITL"), QT_TR_NOOP("RISK"), QT_TR_NOOP("AUDIT")};
- for (int i = 0; i < right_tab_btns_.size() && i < 5; ++i)
- if (right_tab_btns_[i]) right_tab_btns_[i]->setText(tr(kTabKeys[i]));
}
-// ── State persistence ──────────────────────────────────────────────────────
-
void AlphaArenaScreen::restore_state(const QVariantMap& state) {
- if (state.contains(QStringLiteral("active_tab")))
- on_right_tab_changed(state.value(QStringLiteral("active_tab")).toInt());
+ competition_id_ = state.value(QStringLiteral("competition_id")).toString();
}
QVariantMap AlphaArenaScreen::save_state() const {
- QVariantMap m;
- if (right_stack_) m[QStringLiteral("active_tab")] = right_stack_->currentIndex();
- return m;
+ return {{QStringLiteral("competition_id"), competition_id_}};
}
} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.h b/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.h
index 50a03e6ca..b0660481b 100644
--- a/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.h
+++ b/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.h
@@ -1,172 +1,81 @@
#pragma once
-// AlphaArenaScreen — viewer over AlphaArenaEngine.
-//
-// Engine-side (AlphaArenaEngine, ModelDispatcher, OrderRouter, …) drives the
-// competition. The screen subscribes to engine signals while visible, posts
-// user intents (create / start / kill / halt), and delegates rendering to
-// per-tab panels (LeaderboardPanel / ModelChatPanel / PositionsPanel /
-// HitlPanel / RiskPanel / AuditPanel).
-//
-// Lifecycle (P3):
-// * showEvent → connect engine signals + first refresh
-// * hideEvent → disconnect engine signals; engine keeps running
-//
-// Reference: .grill-me/alpha-arena-production-refactor.md §Phase 7.
-
+// AlphaArenaScreen — nof1-style dashboard over fincept::arena::ArenaEngine.
+// Pure viewer: engine runs even when this screen is closed. Screen id
+// "alpha_arena" (CommandBar/ToolBar/WindowFrame registrations unchanged).
+// Terminal layout: header + mids ticker/cadence strip, then a splitter body
+// [equity chart | agent board] over the always-visible panel grid.
#include "screens/common/IStatefulScreen.h"
+#include "services/alpha_arena/ArenaTypes.h"
-#include <QComboBox>
-#include <QDoubleSpinBox>
-#include <QEvent>
-#include <QGroupBox>
#include <QHash>
-#include <QLabel>
-#include <QLineEdit>
-#include <QListWidget>
#include <QMetaObject>
-#include <QPushButton>
-#include <QRadioButton>
-#include <QSpinBox>
-#include <QStackedWidget>
-#include <QString>
-#include <QStringList>
-#include <QTimer>
+#include <QVariantMap>
#include <QVector>
#include <QWidget>
+class QComboBox; class QLabel; class QPushButton; class QSpinBox; class QStackedWidget;
+class QTimer;
+
namespace fincept::screens::alpha_arena {
-class LeaderboardPanel;
-class ModelChatPanel;
-class PositionsPanel;
-class HitlPanel;
-class RiskPanel;
-class AuditPanel;
-
-/// Lightweight descriptor for a user-configured LLM model entry.
-struct ArenaModelEntry {
- QString display_name;
- QString provider;
- QString model_id;
- QString api_key;
- QString base_url;
- QString profile_id;
-};
+class ArenaPanelGrid; class EquityCurveWidget; class LeaderboardCards;
class AlphaArenaScreen : public QWidget, public IStatefulScreen {
Q_OBJECT
public:
explicit AlphaArenaScreen(QWidget* parent = nullptr);
+ // IStatefulScreen (DockScreenRouter persists/restores lightweight UI state).
void restore_state(const QVariantMap& state) override;
QVariantMap save_state() const override;
QString state_key() const override { return QStringLiteral("alpha_arena"); }
- int state_version() const override { return 2; }
+ int state_version() const override { return 3; }
protected:
void showEvent(QShowEvent* e) override;
void hideEvent(QHideEvent* e) override;
- void changeEvent(QEvent* e) override;
-
- private slots:
- void on_create_clicked();
- void on_start_clicked();
- void on_force_tick_clicked();
- void on_kill_all_clicked();
- void on_live_mode_toggle_clicked();
- void on_right_tab_changed(int idx);
-
- void on_engine_tick(int seq);
- void on_engine_decision_received(QString decision_id, QString agent_id);
- void on_engine_hitl_requested(QString approval_id, QString agent_id, QString summary);
- void on_engine_circuit_open(QString agent_id, QString reason);
- void on_engine_status_changed(QString competition_id, QString status);
- void on_engine_crash_recovery(QStringList competition_ids);
-
- void on_hitl_resolved(QString approval_id, bool approved);
-
- void on_countdown_tick();
private:
- void build_ui();
QWidget* build_header();
- QWidget* build_create_panel();
- QWidget* build_main();
- QWidget* build_right_stack();
-
- /// Re-apply tr() lookups to persistent chrome after a QEvent::LanguageChange.
- /// Status/venue badges and the tick line are re-derived from current state;
- /// table/list data rows are model-driven and kept verbatim.
- void retranslateUi();
+ QWidget* build_ticker_strip(); // mids ticker + cadence editor
+ QWidget* build_empty_state();
+ QWidget* build_dashboard();
+ void connect_engine();
+ void disconnect_engine();
+ void reload_competitions(); // switcher combo
+ void show_competition(const QString& id);
+ void refresh_dashboard(); // chart + board + panels (full, per round)
+ void update_ticker(); // mids ticker (every marks tick)
+ void rebuild_board_light(); // board from cached agents + live account_view
+ void on_new_competition();
+ void update_badges(const QString& status);
+ void maybe_offer_crash_recovery(); // Resume-or-End prompt (signal + showEvent)
- void connect_engine_signals();
- void disconnect_engine_signals();
-
- void populate_model_list();
- void apply_competition_id(const QString& id);
- void update_status_badge(const QString& status);
- void update_venue_badge();
- void show_disclaimer_if_live(bool live);
- void refresh_all_panels();
-
- // State.
QString competition_id_;
- QString competition_status_;
- bool live_mode_engaged_ = false;
- QVector<ArenaModelEntry> model_entries_;
-
- // Engine connection handles (so we can disconnect cleanly in hideEvent).
- QVector<QMetaObject::Connection> engine_conns_;
-
- // Header.
- QLabel* title_label_ = nullptr;
+ QVector<QMetaObject::Connection> conns_;
+ QTimer* countdown_ = nullptr;
+ // Light-refresh caches (filled by refresh_dashboard; used on marks ticks).
+ QVector<fincept::arena::AgentRow> agents_cache_;
+ QHash<QString, qint64> tokens_cache_;
+ QHash<QString, double> last_mids_; // previously displayed mids (ticker arrows)
+ double cap_ = 0;
+ // Header
QLabel* venue_badge_ = nullptr;
QLabel* status_badge_ = nullptr;
- QLabel* tick_label_ = nullptr;
- int tick_seq_ = 0; // last seq shown on tick_label_
+ QLabel* round_label_ = nullptr;
QLabel* countdown_label_ = nullptr;
- QPushButton* force_tick_btn_ = nullptr;
- QPushButton* kill_all_btn_ = nullptr;
- QPushButton* live_mode_btn_ = nullptr;
- QLabel* cadence_label_ = nullptr;
- QSpinBox* hot_cadence_spin_ = nullptr;
- QPushButton* apply_cadence_btn_ = nullptr;
QLabel* disclaimer_ = nullptr;
-
- // Create panel.
- QGroupBox* create_panel_ = nullptr;
- QLabel* comp_name_lbl_ = nullptr;
- QLabel* comp_mode_lbl_ = nullptr;
- QLabel* comp_venue_lbl_ = nullptr;
- QLabel* comp_capital_lbl_ = nullptr;
- QLabel* comp_cadence_lbl_ = nullptr;
- QLabel* comp_instruments_lbl_ = nullptr;
- QLabel* comp_models_lbl_ = nullptr;
- QLineEdit* comp_name_ = nullptr;
- QComboBox* comp_mode_ = nullptr;
- QRadioButton* venue_paper_ = nullptr;
- QRadioButton* venue_hl_ = nullptr;
- QRadioButton* venue_us_eq_ = nullptr; // disabled — S2 stub
- QDoubleSpinBox* comp_capital_ = nullptr;
- QSpinBox* comp_cadence_ = nullptr;
- QListWidget* comp_instruments_ = nullptr;
- QListWidget* model_list_ = nullptr;
- QPushButton* create_btn_ = nullptr;
- QPushButton* start_btn_ = nullptr;
-
- // Main split panels.
- LeaderboardPanel* leaderboard_ = nullptr;
- ModelChatPanel* modelchat_ = nullptr;
- PositionsPanel* positions_ = nullptr;
- HitlPanel* hitl_ = nullptr;
- RiskPanel* risk_ = nullptr;
- AuditPanel* audit_ = nullptr;
-
- QStackedWidget* right_stack_ = nullptr;
- QList<QPushButton*> right_tab_btns_;
-
- // Visibility-driven countdown timer.
- QTimer* countdown_timer_ = nullptr;
+ QLabel* ticker_ = nullptr;
+ QSpinBox* cadence_spin_ = nullptr;
+ QPushButton* pause_btn_ = nullptr;
+ QPushButton* force_btn_ = nullptr;
+ QPushButton* kill_btn_ = nullptr;
+ QComboBox* switcher_ = nullptr;
+ // Body
+ QStackedWidget* body_ = nullptr; // 0 = empty state, 1 = dashboard
+ EquityCurveWidget* chart_ = nullptr;
+ LeaderboardCards* cards_ = nullptr;
+ ArenaPanelGrid* grid_ = nullptr;
};
} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/ArenaTabs.cpp b/fincept-qt/src/screens/alpha_arena/ArenaTabs.cpp
new file mode 100644
index 000000000..07241ae8b
--- /dev/null
+++ b/fincept-qt/src/screens/alpha_arena/ArenaTabs.cpp
@@ -0,0 +1,315 @@
+#include "screens/alpha_arena/ArenaTabs.h"
+#include "services/alpha_arena/ArenaEngine.h"
+#include "services/alpha_arena/ArenaStore.h"
+#include <QColor>
+#include <QDateTime>
+#include <QHBoxLayout>
+#include <QHeaderView>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QLabel>
+#include <QListWidget>
+#include <QPushButton>
+#include <QSplitter>
+#include <QTableWidget>
+#include <QTextBrowser>
+#include <QVBoxLayout>
+
+namespace fincept::screens::alpha_arena {
+using fincept::arena::ArenaEngine;
+using fincept::arena::ArenaStore;
+
+namespace {
+
+QTableWidget* make_table(const QStringList& headers) {
+ auto* t = new QTableWidget;
+ t->setColumnCount(headers.size());
+ t->setHorizontalHeaderLabels(headers);
+ t->horizontalHeader()->setStretchLastSection(true);
+ t->verticalHeader()->setVisible(false);
+ t->verticalHeader()->setDefaultSectionSize(20);
+ t->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ t->setSelectionMode(QAbstractItemView::NoSelection);
+ t->setShowGrid(false);
+ t->setStyleSheet(
+ "QTableWidget{background:#0D0D0D;border:none;font-size:11px;"
+ " font-family:'Consolas','Courier New',monospace;}"
+ "QTableWidget::item{padding:0 4px;border-bottom:1px solid #1C1C1C;}"
+ "QHeaderView::section{background:#141414;color:#777;border:none;"
+ " border-bottom:1px solid #2A2A2A;padding:1px 4px;font-size:10px;font-weight:700;}");
+ return t;
+}
+
+void fill_row(QTableWidget* t, int r, const QStringList& cells, const QColor& fg = QColor("#DDD")) {
+ for (int c = 0; c < cells.size(); ++c) {
+ auto* it = new QTableWidgetItem(cells[c]);
+ it->setForeground(fg);
+ t->setItem(r, c, it);
+ }
+}
+
+QLabel* micro_header(const QString& text) {
+ auto* l = new QLabel(text);
+ l->setFixedHeight(18);
+ l->setStyleSheet("background:#141414;color:#777;font-size:10px;font-weight:700;"
+ "padding:0 6px;border-bottom:1px solid #2A2A2A;");
+ return l;
+}
+
+QWidget* panel(QLabel* header, QWidget* content) {
+ auto* w = new QWidget;
+ auto* v = new QVBoxLayout(w);
+ v->setContentsMargins(0, 0, 0, 0);
+ v->setSpacing(0);
+ v->addWidget(header);
+ v->addWidget(content, 1);
+ return w;
+}
+
+} // namespace
+
+ArenaPanelGrid::ArenaPanelGrid(QWidget* parent) : QWidget(parent) {
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
+ // HITL approval banner — high-visibility row above the grid, hidden when
+ // empty. Entries are appended by add_hitl (live mode only).
+ hitl_banner_ = new QWidget;
+ hitl_banner_->setStyleSheet("background:#3A1414;border-bottom:1px solid #5C1F1F;");
+ auto* bh = new QHBoxLayout(hitl_banner_);
+ bh->setContentsMargins(8, 3, 8, 3);
+ bh->setSpacing(8);
+ auto* tag = new QLabel(tr("⚠ APPROVALS"));
+ tag->setStyleSheet("color:#FFB0B0;font-size:10px;font-weight:800;");
+ bh->addWidget(tag);
+ hitl_row_ = new QHBoxLayout;
+ hitl_row_->setSpacing(8);
+ bh->addLayout(hitl_row_, 1);
+ bh->addStretch(0);
+ hitl_banner_->hide();
+ root->addWidget(hitl_banner_);
+
+ chat_ = new QTextBrowser;
+ chat_->setOpenExternalLinks(false);
+ chat_->setStyleSheet("QTextBrowser{background:#0D0D0D;color:#DDD;border:none;font-size:11px;}");
+ positions_ = make_table({tr("Agent"), tr("Coin"), tr("Side"), tr("Qty"), tr("Entry"),
+ tr("Lev"), tr("uPnL $")});
+ trades_ = make_table({tr("Time"), tr("Agent"), tr("Coin"), tr("Action"), tr("Side"),
+ tr("Qty"), tr("Price"), tr("Notional"), tr("Fee"), tr("rPnL"),
+ tr("Status"), tr("Reason")});
+ risk_ = make_table({tr("Agent"), tr("Status"), tr("Fails"), tr("Halt reason")});
+ audit_ = new QListWidget;
+ audit_->setStyleSheet("QListWidget{background:#0D0D0D;color:#999;border:none;font-size:10px;"
+ " font-family:'Consolas','Courier New',monospace;}");
+
+ chat_hdr_ = micro_header(tr("MODEL CHAT"));
+ positions_hdr_ = micro_header(tr("POSITIONS"));
+ trades_hdr_ = micro_header(tr("TRADES"));
+ risk_hdr_ = micro_header(tr("RISK"));
+ audit_hdr_ = micro_header(tr("AUDIT"));
+
+ auto* mid = new QSplitter(Qt::Vertical);
+ mid->setHandleWidth(1);
+ mid->setChildrenCollapsible(false);
+ mid->addWidget(panel(positions_hdr_, positions_));
+ mid->addWidget(panel(trades_hdr_, trades_));
+ mid->setStretchFactor(0, 1);
+ mid->setStretchFactor(1, 1);
+
+ auto* right = new QSplitter(Qt::Vertical);
+ right->setHandleWidth(1);
+ right->setChildrenCollapsible(false);
+ right->addWidget(panel(risk_hdr_, risk_));
+ right->addWidget(panel(audit_hdr_, audit_));
+ right->setStretchFactor(0, 1);
+ right->setStretchFactor(1, 2);
+
+ auto* split = new QSplitter(Qt::Horizontal);
+ split->setHandleWidth(1);
+ split->setChildrenCollapsible(false);
+ split->setStyleSheet("QSplitter::handle{background:#2A2A2A;}");
+ split->addWidget(panel(chat_hdr_, chat_));
+ split->addWidget(mid);
+ split->addWidget(right);
+ split->setStretchFactor(0, 3);
+ split->setStretchFactor(1, 4);
+ split->setStretchFactor(2, 3);
+ root->addWidget(split, 1);
+}
+
+void ArenaPanelGrid::set_competition(const QString& id, bool live_mode) {
+ Q_UNUSED(live_mode); // approvals only ever arrive in live mode (engine-gated)
+ competition_id_ = id;
+ agent_filter_.clear();
+ // Drop stale approval entries from a previously viewed competition.
+ while (hitl_row_->count() > 0) {
+ auto* it = hitl_row_->takeAt(0);
+ if (it->widget()) it->widget()->deleteLater();
+ delete it;
+ }
+ hitl_banner_->hide();
+ refresh();
+}
+
+void ArenaPanelGrid::set_agent_filter(const QString& agent_id) { agent_filter_ = agent_id; refresh(); }
+
+void ArenaPanelGrid::refresh() {
+ if (competition_id_.isEmpty()) return;
+ refresh_chat();
+ refresh_positions();
+ refresh_trades();
+ refresh_risk();
+ refresh_audit();
+}
+
+void ArenaPanelGrid::refresh_positions_only() {
+ if (competition_id_.isEmpty()) return;
+ refresh_positions();
+}
+
+void ArenaPanelGrid::refresh_chat() {
+ auto agents_r = ArenaStore::instance().agents_for(competition_id_);
+ QHash<QString, QPair<QString, QString>> meta; // id → (name, color)
+ if (agents_r.is_ok())
+ for (const auto& a : agents_r.value()) meta[a.id] = {a.display_name, a.color_hex};
+ auto r = ArenaStore::instance().latest_decisions(competition_id_, agent_filter_, 50);
+ if (r.is_err()) return;
+ QString html;
+ for (const auto& d : r.value()) {
+ const auto m = meta.value(d.agent_id);
+ QString body;
+ if (d.status == QLatin1String("ok")) {
+ const auto acts = QJsonDocument::fromJson(d.actions_json.toUtf8()).array();
+ for (const auto& v : acts) {
+ const auto o = v.toObject();
+ // Every field is model-controlled at some layer — escape all of
+ // them (hold actions can carry an unvalidated coin string).
+ body += QStringLiteral("<b>%1 %2</b> %3 — <i>%4</i><br>")
+ .arg(o.value("action").toString().toUpper().toHtmlEscaped(),
+ o.value("coin").toString().toHtmlEscaped(),
+ o.value("side").toString().toHtmlEscaped(),
+ o.value("reason").toString().toHtmlEscaped());
+ }
+ } else {
+ body = QStringLiteral("<span style='color:#E0245E'>[%1] %2</span><br>")
+ .arg(d.status, d.parse_error.toHtmlEscaped());
+ }
+ html += QStringLiteral(
+ "<div style='margin:6px 0'>"
+ "<span style='color:%1'>●</span> <b style='color:#EEE'>%2</b>"
+ " <span style='color:#777'>round %3 · %4 · %5ms · %6 tok</span><br>%7</div>")
+ .arg(m.second, m.first.toHtmlEscaped()).arg(d.round_seq)
+ .arg(QDateTime::fromMSecsSinceEpoch(d.ts).toString("HH:mm:ss"))
+ .arg(d.latency_ms).arg(d.prompt_tokens + d.completion_tokens)
+ .arg(body);
+ }
+ chat_->setHtml(html);
+}
+
+void ArenaPanelGrid::refresh_positions() {
+ auto r = ArenaStore::instance().positions_for(competition_id_, agent_filter_);
+ auto agents_r = ArenaStore::instance().agents_for(competition_id_);
+ QHash<QString, QString> names;
+ if (agents_r.is_ok()) for (const auto& a : agents_r.value()) names[a.id] = a.display_name;
+ positions_->setRowCount(0);
+ if (r.is_err()) { positions_hdr_->setText(tr("POSITIONS")); return; }
+ for (const auto& p : r.value()) {
+ const auto acct = ArenaEngine::instance().account_view(p.agent_id);
+ const int row = positions_->rowCount();
+ positions_->insertRow(row);
+ fill_row(positions_, row,
+ {names.value(p.agent_id), p.coin, p.side.toUpper(),
+ QString::number(p.qty, 'g', 8), QString::number(p.entry_price, 'g', 8),
+ QString::number(p.leverage, 'f', 1),
+ QString::number(acct.upnl.value(p.coin), 'f', 2)},
+ acct.upnl.value(p.coin) >= 0 ? QColor("#26A65B") : QColor("#E0245E"));
+ }
+ positions_hdr_->setText(tr("POSITIONS · %1").arg(r.value().size()));
+}
+
+void ArenaPanelGrid::refresh_trades() {
+ auto r = ArenaStore::instance().orders_for(competition_id_, agent_filter_, 200);
+ auto agents_r = ArenaStore::instance().agents_for(competition_id_);
+ QHash<QString, QString> names;
+ if (agents_r.is_ok()) for (const auto& a : agents_r.value()) names[a.id] = a.display_name;
+ trades_->setRowCount(0);
+ if (r.is_err()) { trades_hdr_->setText(tr("TRADES")); return; }
+ for (const auto& o : r.value()) {
+ const int row = trades_->rowCount();
+ trades_->insertRow(row);
+ const QColor fg = o.status == QLatin1String("filled") ? QColor("#DDD")
+ : o.status == QLatin1String("liquidated") ? QColor("#FF6B6B") : QColor("#E0A800");
+ fill_row(trades_, row,
+ {QDateTime::fromMSecsSinceEpoch(o.ts).toString("HH:mm:ss"), names.value(o.agent_id),
+ o.coin, o.action, o.side, QString::number(o.qty, 'g', 6),
+ QString::number(o.price, 'g', 8), QString::number(o.notional_usd, 'f', 0),
+ QString::number(o.fee, 'f', 2), QString::number(o.realized_pnl, 'f', 2),
+ o.status, o.reject_reason}, fg);
+ }
+ trades_hdr_->setText(tr("TRADES · %1").arg(r.value().size()));
+}
+
+void ArenaPanelGrid::refresh_risk() {
+ auto r = ArenaStore::instance().agents_for(competition_id_);
+ risk_->setRowCount(0);
+ if (r.is_err()) return;
+ for (const auto& a : r.value()) {
+ const int row = risk_->rowCount();
+ risk_->insertRow(row);
+ fill_row(risk_, row, {a.display_name, a.status, QString::number(a.consecutive_failures),
+ a.halt_reason},
+ a.status == QLatin1String("active") ? QColor("#26A65B") : QColor("#E0245E"));
+ }
+}
+
+void ArenaPanelGrid::refresh_audit() {
+ auto r = ArenaStore::instance().recent_events(competition_id_, 200);
+ audit_->clear();
+ if (r.is_ok()) {
+ for (const auto& line : r.value()) audit_->addItem(line);
+ audit_hdr_->setText(tr("AUDIT · %1").arg(r.value().size()));
+ }
+}
+
+void ArenaPanelGrid::update_hitl_banner_visibility() {
+ bool any = false;
+ for (int i = 0; i < hitl_row_->count(); ++i)
+ if (auto* w = hitl_row_->itemAt(i)->widget(); w && w->isVisibleTo(hitl_banner_)) { any = true; break; }
+ hitl_banner_->setVisible(any);
+}
+
+void ArenaPanelGrid::add_hitl(const QString& approval_id, const QString& agent_label,
+ const QString& summary) {
+ auto* entry = new QWidget;
+ entry->setStyleSheet("background:#5C1F1F;border:none;");
+ auto* h = new QHBoxLayout(entry);
+ h->setContentsMargins(6, 1, 6, 1);
+ h->setSpacing(6);
+ auto* label = new QLabel(QStringLiteral("%1: %2").arg(agent_label, summary));
+ label->setTextFormat(Qt::PlainText); // summary may carry model-derived text
+ label->setStyleSheet("color:#FFD;font-size:11px;");
+ h->addWidget(label, 1);
+ auto* approve = new QPushButton(tr("✓ APPROVE"));
+ approve->setStyleSheet("background:#0A4A18;color:#9F9;font-size:10px;font-weight:700;"
+ "border:none;padding:2px 8px;");
+ auto* reject = new QPushButton(tr("✖ REJECT"));
+ reject->setStyleSheet("background:#4A0A0A;color:#F99;font-size:10px;font-weight:700;"
+ "border:none;padding:2px 8px;");
+ for (auto* b : {approve, reject}) b->setCursor(Qt::PointingHandCursor);
+ h->addWidget(approve); h->addWidget(reject);
+ hitl_row_->addWidget(entry);
+ hitl_banner_->show();
+ auto resolve = [this, entry, approval_id, approve, reject](bool ok) {
+ approve->setEnabled(false); // guard against a second click racing the
+ reject->setEnabled(false); // deferred entry deletion
+ emit hitl_resolved(approval_id, ok);
+ entry->hide();
+ entry->deleteLater(); // the clicked button is a child — defer
+ update_hitl_banner_visibility();
+ };
+ connect(approve, &QPushButton::clicked, this, [resolve]() { resolve(true); });
+ connect(reject, &QPushButton::clicked, this, [resolve]() { resolve(false); });
+}
+
+} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/ArenaTabs.h b/fincept-qt/src/screens/alpha_arena/ArenaTabs.h
new file mode 100644
index 000000000..bab5539c8
--- /dev/null
+++ b/fincept-qt/src/screens/alpha_arena/ArenaTabs.h
@@ -0,0 +1,44 @@
+#pragma once
+// ArenaPanelGrid — always-visible detail panel grid under the dashboard
+// (formerly a tab stack). Pure viewer: every refresh re-reads ArenaStore /
+// ArenaEngine. Layout: [MODEL CHAT] | [POSITIONS / TRADES] | [RISK / AUDIT],
+// plus a high-visibility HITL approval banner above the grid (live mode).
+#include <QWidget>
+
+class QHBoxLayout; class QLabel; class QListWidget; class QTableWidget;
+class QTextBrowser;
+
+namespace fincept::screens::alpha_arena {
+
+class ArenaPanelGrid : public QWidget {
+ Q_OBJECT
+ public:
+ explicit ArenaPanelGrid(QWidget* parent = nullptr);
+ void set_competition(const QString& id, bool live_mode);
+ void set_agent_filter(const QString& agent_id); // empty = all agents
+ void refresh(); // all panels (all visible)
+ void refresh_positions_only(); // cheap; every marks tick
+ void add_hitl(const QString& approval_id, const QString& agent_label, const QString& summary);
+ signals:
+ void hitl_resolved(QString approval_id, bool approved);
+ private:
+ void refresh_chat(); void refresh_positions(); void refresh_trades();
+ void refresh_risk(); void refresh_audit();
+ void update_hitl_banner_visibility();
+
+ QString competition_id_, agent_filter_;
+ QTextBrowser* chat_ = nullptr;
+ QTableWidget* positions_ = nullptr;
+ QTableWidget* trades_ = nullptr;
+ QTableWidget* risk_ = nullptr;
+ QListWidget* audit_ = nullptr;
+ QLabel* chat_hdr_ = nullptr;
+ QLabel* positions_hdr_ = nullptr;
+ QLabel* trades_hdr_ = nullptr;
+ QLabel* risk_hdr_ = nullptr;
+ QLabel* audit_hdr_ = nullptr;
+ QWidget* hitl_banner_ = nullptr; // hidden when no pending approvals
+ QHBoxLayout* hitl_row_ = nullptr;
+};
+
+} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/EquityCurveWidget.cpp b/fincept-qt/src/screens/alpha_arena/EquityCurveWidget.cpp
new file mode 100644
index 000000000..5f2c4d735
--- /dev/null
+++ b/fincept-qt/src/screens/alpha_arena/EquityCurveWidget.cpp
@@ -0,0 +1,96 @@
+#include "screens/alpha_arena/EquityCurveWidget.h"
+#include <QDateTime>
+#include <QMouseEvent>
+#include <QPainter>
+#include <QPainterPath>
+#include <algorithm>
+#include <cmath>
+#include <limits>
+
+namespace fincept::screens::alpha_arena {
+
+EquityCurveWidget::EquityCurveWidget(QWidget* parent) : QWidget(parent) {
+ setMouseTracking(true);
+ setMinimumHeight(220);
+ setMinimumWidth(160); // plot_rect() inverts below ~76px; keep a sane floor
+}
+
+void EquityCurveWidget::set_data(QVector<EquitySeries> series, double baseline) {
+ series_ = std::move(series);
+ baseline_ = baseline;
+ min_y_ = max_y_ = baseline;
+ min_x_ = std::numeric_limits<qint64>::max(); max_x_ = 0;
+ for (const auto& s : series_)
+ for (const auto& p : s.points) {
+ min_y_ = std::min(min_y_, p.y()); max_y_ = std::max(max_y_, p.y());
+ min_x_ = std::min(min_x_, qint64(p.x())); max_x_ = std::max(max_x_, qint64(p.x()));
+ }
+ if (min_x_ > max_x_) { min_x_ = 0; max_x_ = 1; }
+ const double pad = std::max(1.0, (max_y_ - min_y_) * 0.08);
+ min_y_ -= pad; max_y_ += pad;
+ update();
+}
+
+QRectF EquityCurveWidget::plot_rect() const { return QRectF(64, 12, width() - 76, height() - 40); }
+
+void EquityCurveWidget::paintEvent(QPaintEvent*) {
+ QPainter p(this);
+ p.setRenderHint(QPainter::Antialiasing);
+ p.fillRect(rect(), QColor("#0D0D0D"));
+ const QRectF r = plot_rect();
+ auto x_of = [&](double ts) { return r.left() + (max_x_ == min_x_ ? 0 : (ts - min_x_) / double(max_x_ - min_x_) * r.width()); };
+ auto y_of = [&](double v) { return r.bottom() - (v - min_y_) / (max_y_ - min_y_) * r.height(); };
+
+ // Grid + y labels.
+ p.setPen(QColor("#222"));
+ p.setFont(QFont(p.font().family(), 9));
+ for (int i = 0; i <= 4; ++i) {
+ const double v = min_y_ + (max_y_ - min_y_) * i / 4.0;
+ const double y = y_of(v);
+ p.drawLine(QPointF(r.left(), y), QPointF(r.right(), y));
+ p.setPen(QColor("#777"));
+ p.drawText(QRectF(0, y - 8, 58, 16), Qt::AlignRight | Qt::AlignVCenter,
+ QString::number(v, 'f', 0));
+ p.setPen(QColor("#222"));
+ }
+ // Baseline.
+ p.setPen(QPen(QColor("#555"), 1, Qt::DashLine));
+ p.drawLine(QPointF(r.left(), y_of(baseline_)), QPointF(r.right(), y_of(baseline_)));
+
+ // Series.
+ for (const auto& s : series_) {
+ if (s.points.size() < 2) continue;
+ QPainterPath path(QPointF(x_of(s.points[0].x()), y_of(s.points[0].y())));
+ for (int i = 1; i < s.points.size(); ++i)
+ path.lineTo(x_of(s.points[i].x()), y_of(s.points[i].y()));
+ p.setPen(QPen(s.color, 2));
+ p.drawPath(path);
+ // End label.
+ const QPointF last(x_of(s.points.last().x()), y_of(s.points.last().y()));
+ p.drawText(QPointF(std::min(last.x() + 4, r.right() - 60), last.y() - 2), s.label);
+ }
+
+ // Hover crosshair + values.
+ if (hover_.x() >= r.left() && hover_.x() <= r.right() && !series_.isEmpty() && max_x_ > min_x_) {
+ p.setPen(QPen(QColor("#444"), 1, Qt::DotLine));
+ p.drawLine(hover_.x(), int(r.top()), hover_.x(), int(r.bottom()));
+ const qint64 ts = min_x_ + qint64((hover_.x() - r.left()) / r.width() * (max_x_ - min_x_));
+ QStringList lines{QDateTime::fromMSecsSinceEpoch(ts).toString("MMM d HH:mm")};
+ for (const auto& s : series_) {
+ double best = baseline_; qint64 bd = std::numeric_limits<qint64>::max();
+ for (const auto& pt : s.points)
+ if (std::llabs(qint64(pt.x()) - ts) < bd) { bd = std::llabs(qint64(pt.x()) - ts); best = pt.y(); }
+ lines << QStringLiteral("%1 $%2").arg(s.label, QString::number(best, 'f', 0));
+ }
+ const QRectF box(std::min<double>(hover_.x() + 8, r.right() - 170), r.top() + 4, 165, 16.0 * lines.size() + 8);
+ p.fillRect(box, QColor(20, 20, 20, 230));
+ p.setPen(QColor("#DDD"));
+ for (int i = 0; i < lines.size(); ++i)
+ p.drawText(box.adjusted(6, 4 + i * 16, -4, 0), Qt::AlignLeft | Qt::AlignTop, lines[i]);
+ }
+}
+
+void EquityCurveWidget::mouseMoveEvent(QMouseEvent* e) { hover_ = e->pos(); update(); }
+void EquityCurveWidget::leaveEvent(QEvent*) { hover_ = {-1, -1}; update(); }
+
+} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/EquityCurveWidget.h b/fincept-qt/src/screens/alpha_arena/EquityCurveWidget.h
new file mode 100644
index 000000000..159b7b36d
--- /dev/null
+++ b/fincept-qt/src/screens/alpha_arena/EquityCurveWidget.h
@@ -0,0 +1,36 @@
+#pragma once
+// EquityCurveWidget — multi-line equity chart, custom QPainter (no WebEngine).
+// One line per agent in its brand color; dashed baseline at starting capital;
+// hover crosshair with per-agent values; range filter applied by caller.
+#include <QColor>
+#include <QPoint>
+#include <QString>
+#include <QWidget>
+#include <QVector>
+
+namespace fincept::screens::alpha_arena {
+
+struct EquitySeries {
+ QString agent_id, label;
+ QColor color;
+ QVector<QPointF> points; // x = ts (ms), y = equity
+};
+
+class EquityCurveWidget : public QWidget {
+ Q_OBJECT
+ public:
+ explicit EquityCurveWidget(QWidget* parent = nullptr);
+ void set_data(QVector<EquitySeries> series, double baseline);
+ protected:
+ void paintEvent(QPaintEvent*) override;
+ void mouseMoveEvent(QMouseEvent* e) override;
+ void leaveEvent(QEvent*) override;
+ private:
+ QRectF plot_rect() const;
+ QVector<EquitySeries> series_;
+ double baseline_ = 10000, min_y_ = 0, max_y_ = 1;
+ qint64 min_x_ = 0, max_x_ = 1;
+ QPoint hover_{-1, -1};
+};
+
+} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/LeaderboardCards.cpp b/fincept-qt/src/screens/alpha_arena/LeaderboardCards.cpp
new file mode 100644
index 000000000..9377c602c
--- /dev/null
+++ b/fincept-qt/src/screens/alpha_arena/LeaderboardCards.cpp
@@ -0,0 +1,154 @@
+#include "screens/alpha_arena/LeaderboardCards.h"
+#include <QHBoxLayout>
+#include <QHeaderView>
+#include <QLocale>
+#include <QPushButton>
+#include <QTableWidget>
+#include <QVBoxLayout>
+
+namespace fincept::screens::alpha_arena {
+namespace {
+
+enum Col { ColRank = 0, ColChip, ColModel, ColEquity, ColPnlPct, ColUpnl, ColPos, ColTok, ColSt, ColAct, ColCount };
+
+constexpr int kRowHeight = 22;
+
+QTableWidgetItem* cell(const QString& text, const QColor& fg,
+ Qt::Alignment align = Qt::AlignRight | Qt::AlignVCenter) {
+ auto* it = new QTableWidgetItem(text);
+ it->setForeground(fg);
+ it->setTextAlignment(align);
+ return it;
+}
+
+QPushButton* icon_btn(const QString& glyph, const QString& tip, const QString& color) {
+ auto* b = new QPushButton(glyph);
+ b->setToolTip(tip);
+ b->setCursor(Qt::PointingHandCursor);
+ b->setFixedSize(20, 18);
+ b->setFlat(true);
+ b->setStyleSheet(QStringLiteral(
+ "QPushButton{background:transparent;border:none;color:%1;font-size:11px;padding:0;}"
+ "QPushButton:hover{background:#2A2A2A;}").arg(color));
+ return b;
+}
+
+QString fmt_usd(double v) {
+ return QLocale(QLocale::English, QLocale::UnitedStates).toString(v, 'f', 0);
+}
+
+} // namespace
+
+LeaderboardCards::LeaderboardCards(QWidget* parent) : QWidget(parent) {
+ auto* v = new QVBoxLayout(this);
+ v->setContentsMargins(0, 0, 0, 0);
+ v->setSpacing(0);
+
+ table_ = new QTableWidget(0, ColCount);
+ table_->setHorizontalHeaderLabels({QStringLiteral("#"), QStringLiteral("●"), tr("MODEL"),
+ tr("EQUITY $"), tr("PnL %"), tr("uPnL $"), tr("POS"),
+ tr("TOK"), tr("ST"), tr("ACT")});
+ table_->verticalHeader()->setVisible(false);
+ table_->verticalHeader()->setDefaultSectionSize(kRowHeight);
+ table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table_->setSelectionMode(QAbstractItemView::NoSelection);
+ table_->setFocusPolicy(Qt::NoFocus);
+ table_->setShowGrid(false);
+ table_->setSortingEnabled(false); // caller order = rank (sorted by equity)
+ table_->setStyleSheet(
+ "QTableWidget{background:#0D0D0D;border:none;font-size:11px;"
+ " font-family:'Consolas','Courier New',monospace;}"
+ "QTableWidget::item{padding:0 6px;border-bottom:1px solid #1C1C1C;}"
+ "QHeaderView::section{background:#141414;color:#777;border:none;"
+ " border-bottom:1px solid #2A2A2A;padding:2px 6px;font-size:10px;font-weight:700;}");
+ auto* hh = table_->horizontalHeader();
+ hh->setSectionResizeMode(QHeaderView::ResizeToContents);
+ hh->setSectionResizeMode(ColModel, QHeaderView::Stretch);
+ hh->setHighlightSections(false);
+
+ // Row click (outside the ACT buttons — those eat the press) toggles
+ // selection. Deferred: the screen handler re-filters the panel grid and may
+ // rebuild this board; let the click handler unwind first.
+ connect(table_, &QTableWidget::cellClicked, this, [this](int row, int col) {
+ if (col == ColAct || row < 0 || row >= cards_.size()) return;
+ const QString next = selected_ == cards_[row].agent_id ? QString() : cards_[row].agent_id;
+ QMetaObject::invokeMethod(this, [this, next]() { emit agent_selected(next); },
+ Qt::QueuedConnection);
+ });
+ connect(this, &LeaderboardCards::agent_selected, this, [this](const QString& id) {
+ selected_ = id; rebuild();
+ });
+ v->addWidget(table_, 1);
+}
+
+void LeaderboardCards::set_data(QVector<AgentCardData> cards) { cards_ = std::move(cards); rebuild(); }
+
+void LeaderboardCards::rebuild() {
+ table_->setRowCount(cards_.size());
+ for (int i = 0; i < cards_.size(); ++i) {
+ const auto& d = cards_[i];
+ const bool selected = d.agent_id == selected_;
+ const QColor pnl_fg = d.pnl_pct >= 0 ? QColor("#26A65B") : QColor("#E0245E");
+ const QColor upnl_fg = d.upnl >= 0 ? QColor("#26A65B") : QColor("#E0245E");
+
+ table_->setItem(i, ColRank, cell(QString::number(i + 1), QColor("#777"),
+ Qt::AlignCenter));
+ table_->setItem(i, ColChip, cell(QStringLiteral("●"), d.color, Qt::AlignCenter));
+ table_->setItem(i, ColModel, cell(d.name, selected ? QColor("#FF8800") : QColor("#EEE"),
+ Qt::AlignLeft | Qt::AlignVCenter));
+ table_->setItem(i, ColEquity, cell(fmt_usd(d.equity), QColor("#FFF")));
+ table_->setItem(i, ColPnlPct, cell(QStringLiteral("%1%2%")
+ .arg(d.pnl_pct >= 0 ? "+" : "").arg(QString::number(d.pnl_pct, 'f', 2)),
+ pnl_fg));
+ table_->setItem(i, ColUpnl, cell(QStringLiteral("%1%2")
+ .arg(d.upnl >= 0 ? "+" : "").arg(QString::number(d.upnl, 'f', 2)),
+ upnl_fg));
+ table_->setItem(i, ColPos, cell(QString::number(d.open_positions), QColor("#DDD"),
+ Qt::AlignCenter));
+ table_->setItem(i, ColTok, cell(d.tokens >= 1000
+ ? QStringLiteral("%1k").arg(QString::number(d.tokens / 1000.0, 'f', 1))
+ : QString::number(d.tokens), QColor("#999")));
+ const bool active = d.status == QLatin1String("active");
+ const bool circuit = d.status == QLatin1String("halted_circuit");
+ auto* st = cell(active ? QStringLiteral("▶") : circuit ? QStringLiteral("⚡")
+ : QStringLiteral("⏸"),
+ active ? QColor("#26A65B") : circuit ? QColor("#E0A800") : QColor("#E0245E"),
+ Qt::AlignCenter);
+ st->setToolTip(d.status);
+ table_->setItem(i, ColSt, st);
+
+ // Per-row selection tint (set after all items exist).
+ const QColor bg = selected ? QColor("#1F1A10") : QColor("#0D0D0D");
+ for (int c = 0; c < ColCount; ++c)
+ if (auto* it = table_->item(i, c)) it->setBackground(bg);
+
+ // ACT: halt/resume toggle + kill. Emissions are deferred — handlers
+ // refresh the dashboard, which calls set_data → rebuild and would
+ // delete the clicked button under its own clicked() handler.
+ auto* act = new QWidget;
+ act->setStyleSheet(QStringLiteral("background:%1;").arg(bg.name()));
+ auto* h = new QHBoxLayout(act);
+ h->setContentsMargins(2, 0, 2, 0);
+ h->setSpacing(2);
+ const QString id = d.agent_id;
+ auto* toggle = icon_btn(active ? QStringLiteral("⏸") : QStringLiteral("▶"),
+ active ? tr("Halt agent") : tr("Resume agent"),
+ active ? "#E0A800" : "#26A65B");
+ connect(toggle, &QPushButton::clicked, this, [this, id, active]() {
+ QMetaObject::invokeMethod(this, [this, id, active]() {
+ if (active) emit halt_requested(id); else emit resume_requested(id);
+ }, Qt::QueuedConnection);
+ });
+ auto* kill = icon_btn(QStringLiteral("✖"), tr("Close positions & halt (kill)"), "#E0245E");
+ connect(kill, &QPushButton::clicked, this, [this, id]() {
+ QMetaObject::invokeMethod(this, [this, id]() { emit kill_requested(id); },
+ Qt::QueuedConnection);
+ });
+ h->addWidget(toggle);
+ h->addWidget(kill);
+ table_->setCellWidget(i, ColAct, act);
+ table_->setRowHeight(i, kRowHeight);
+ }
+}
+
+} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/LeaderboardCards.h b/fincept-qt/src/screens/alpha_arena/LeaderboardCards.h
new file mode 100644
index 000000000..e0d67546c
--- /dev/null
+++ b/fincept-qt/src/screens/alpha_arena/LeaderboardCards.h
@@ -0,0 +1,40 @@
+#pragma once
+// LeaderboardCards — dense terminal-style agent board (QTableWidget rows, one
+// per agent). Click a row to select (filters the panel grid); per-row action
+// icons: halt/resume toggle and kill (close positions + halt).
+#include <QColor>
+#include <QString>
+#include <QVector>
+#include <QWidget>
+
+class QTableWidget;
+
+namespace fincept::screens::alpha_arena {
+
+struct AgentCardData {
+ QString agent_id, name, status; // status: active|halted_user|halted_circuit
+ QColor color;
+ double equity = 0, pnl_pct = 0, upnl = 0;
+ int open_positions = 0;
+ qint64 tokens = 0;
+};
+
+class LeaderboardCards : public QWidget {
+ Q_OBJECT
+ public:
+ explicit LeaderboardCards(QWidget* parent = nullptr);
+ void set_data(QVector<AgentCardData> cards); // caller sorts by equity desc
+ QString selected_agent() const { return selected_; }
+ signals:
+ void agent_selected(QString agent_id); // empty = deselected
+ void halt_requested(QString agent_id);
+ void resume_requested(QString agent_id);
+ void kill_requested(QString agent_id); // close positions & halt one model
+ private:
+ void rebuild();
+ QVector<AgentCardData> cards_;
+ QString selected_;
+ QTableWidget* table_ = nullptr;
+};
+
+} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/NewCompetitionWizard.cpp b/fincept-qt/src/screens/alpha_arena/NewCompetitionWizard.cpp
new file mode 100644
index 000000000..e266ccce4
--- /dev/null
+++ b/fincept-qt/src/screens/alpha_arena/NewCompetitionWizard.cpp
@@ -0,0 +1,353 @@
+#include "screens/alpha_arena/NewCompetitionWizard.h"
+#include "screens/alpha_arena/panels/Geofence.h"
+#include "screens/alpha_arena/panels/LiveModeGateDialog.h"
+#include "services/llm/ProviderCatalog.h"
+#include "trading/exchanges/hyperliquid/HyperliquidSigner.h"
+#include <QColor>
+#include <QDateTime>
+#include <QDoubleSpinBox>
+#include <QGridLayout>
+#include <QGroupBox>
+#include <QHBoxLayout>
+#include <QHash>
+#include <QIcon>
+#include <QLabel>
+#include <QLineEdit>
+#include <QListWidget>
+#include <QLocale>
+#include <QMessageBox>
+#include <QPainter>
+#include <QPixmap>
+#include <QPlainTextEdit>
+#include <QPushButton>
+#include <QRadioButton>
+#include <QSet>
+#include <QSpinBox>
+#include <QStackedWidget>
+#include <QVBoxLayout>
+#include <algorithm>
+
+namespace fincept::screens::alpha_arena {
+using fincept::ai_chat::ProviderCatalog;
+using fincept::arena::ArenaConfig;
+using fincept::arena::ArenaAgentSpec;
+using fincept::arena::ArenaModelOption;
+using fincept::arena::ArenaModelRegistry;
+
+namespace {
+const QStringList kCoins = {"BTC", "ETH", "SOL", "BNB", "DOGE", "XRP", "AVAX", "LINK", "ARB", "OP"};
+constexpr int kDefaultChecked = 6;
+
+// Colored "●" for the provider rows (a QListWidgetItem can't color a substring).
+QIcon dot_icon(const QString& hex) {
+ QPixmap pm(12, 12);
+ pm.fill(Qt::transparent);
+ QPainter p(&pm);
+ p.setRenderHint(QPainter::Antialiasing);
+ p.setBrush(QColor(hex));
+ p.setPen(Qt::NoPen);
+ p.drawEllipse(1, 1, 10, 10);
+ return QIcon(pm);
+}
+} // namespace
+
+NewCompetitionWizard::NewCompetitionWizard(QWidget* parent) : QDialog(parent) {
+ setWindowTitle(tr("New Competition"));
+ setModal(true);
+ resize(560, 540);
+ auto* root = new QVBoxLayout(this);
+ steps_ = new QStackedWidget;
+ root->addWidget(steps_, 1);
+ build_step1();
+ build_step2();
+
+ auto* nav = new QHBoxLayout;
+ back_ = new QPushButton(tr("BACK"));
+ next_ = new QPushButton(tr("NEXT"));
+ auto* cancel = new QPushButton(tr("CANCEL"));
+ nav->addWidget(cancel); nav->addStretch(1); nav->addWidget(back_); nav->addWidget(next_);
+ root->addLayout(nav);
+ connect(cancel, &QPushButton::clicked, this, &QDialog::reject);
+ connect(back_, &QPushButton::clicked, this, [this]() { steps_->setCurrentIndex(0); update_nav(); });
+ connect(next_, &QPushButton::clicked, this, &NewCompetitionWizard::on_next_or_create);
+ connect(&ArenaModelRegistry::instance(), &ArenaModelRegistry::models_changed,
+ this, &NewCompetitionWizard::populate_models);
+ update_nav();
+}
+
+void NewCompetitionWizard::build_step1() {
+ auto* page = new QWidget;
+ auto* v = new QVBoxLayout(page);
+ auto* title = new QLabel(tr("1 · Pick the competing models"));
+ title->setStyleSheet("color:#FF8800;font-weight:700;font-size:14px;");
+ v->addWidget(title);
+ auto* panes = new QHBoxLayout;
+ provider_list_ = new QListWidget;
+ provider_list_->setFixedWidth(190);
+ provider_list_->setStyleSheet("background:#111;");
+ panes->addWidget(provider_list_);
+ model_list_ = new QListWidget;
+ model_list_->setStyleSheet("background:#111;");
+ panes->addWidget(model_list_, 1);
+ v->addLayout(panes, 1);
+ selection_summary_ = new QLabel(tr("Selected: none"));
+ selection_summary_->setWordWrap(true);
+ selection_summary_->setStyleSheet("color:#BBB;");
+ v->addWidget(selection_summary_);
+ model_hint_ = new QLabel(tr("Pick a provider on the left, then check its models — selections "
+ "from several providers combine. Greyed entries need an API key in "
+ "Settings → LLM Configuration. Ollama and Fincept work without one."));
+ model_hint_->setWordWrap(true);
+ model_hint_->setStyleSheet("color:#888;");
+ v->addWidget(model_hint_);
+ steps_->addWidget(page);
+ connect(provider_list_, &QListWidget::currentRowChanged,
+ this, &NewCompetitionWizard::on_provider_row_changed);
+ connect(model_list_, &QListWidget::itemChanged,
+ this, &NewCompetitionWizard::on_model_item_changed);
+ populate_models();
+}
+
+void NewCompetitionWizard::populate_models() {
+ repopulating_ = true;
+ const QString prev_provider = current_provider();
+
+ options_by_provider_.clear();
+ QSet<QString> valid_keys;
+ for (const auto& o : ArenaModelRegistry::instance().available_models()) {
+ options_by_provider_[o.provider.toLower()].append(o);
+ valid_keys.insert(o.provider + "/" + o.model_id);
+ }
+ // Drop selections whose model vanished from the registry (deleted profile/
+ // config row) — they could no longer resolve credentials at round time.
+ for (auto it = selected_models_.begin(); it != selected_models_.end();)
+ it = valid_keys.contains(it.key()) ? std::next(it) : selected_models_.erase(it);
+
+ // Provider pane, ordered by display name; keep the previous selection when
+ // still present, else default to the first provider with a ready option.
+ QStringList providers = options_by_provider_.keys();
+ std::sort(providers.begin(), providers.end(), [](const QString& a, const QString& b) {
+ return ProviderCatalog::display_name(a).compare(ProviderCatalog::display_name(b),
+ Qt::CaseInsensitive) < 0;
+ });
+ provider_list_->clear();
+ int restore_row = -1, first_ready = -1;
+ for (const QString& p : providers) {
+ auto* it = new QListWidgetItem(provider_list_);
+ it->setData(Qt::UserRole, p);
+ const int row = provider_list_->count() - 1;
+ if (p == prev_provider) restore_row = row;
+ if (first_ready < 0)
+ for (const auto& o : options_by_provider_.value(p))
+ if (o.ready) { first_ready = row; break; }
+ }
+ refresh_provider_decorations();
+ repopulating_ = false;
+ if (provider_list_->count() > 0)
+ // currentRowChanged → populate_model_pane (re-applies checks).
+ provider_list_->setCurrentRow(restore_row >= 0 ? restore_row
+ : (first_ready >= 0 ? first_ready : 0));
+ else
+ populate_model_pane(QString());
+ update_selection_summary();
+}
+
+void NewCompetitionWizard::on_provider_row_changed() {
+ if (repopulating_) return;
+ populate_model_pane(current_provider());
+}
+
+QString NewCompetitionWizard::current_provider() const {
+ auto* it = provider_list_ ? provider_list_->currentItem() : nullptr;
+ return it ? it->data(Qt::UserRole).toString() : QString();
+}
+
+void NewCompetitionWizard::populate_model_pane(const QString& provider) {
+ repopulating_ = true;
+ model_list_->clear();
+ for (const auto& o : options_by_provider_.value(provider)) {
+ auto* it = new QListWidgetItem(model_list_);
+ const QString key = o.provider + "/" + o.model_id;
+ it->setText(o.ready ? o.display_name : o.display_name + tr(" — needs API key"));
+ it->setData(Qt::UserRole, key);
+ it->setData(Qt::UserRole + 1, QVariant::fromValue(QStringList{o.provider, o.model_id,
+ o.display_name, o.color_hex, o.source_kind, o.source_ref}));
+ it->setForeground(QColor(o.ready ? "#DDD" : "#555"));
+ it->setFlags(o.ready ? (Qt::ItemIsEnabled | Qt::ItemIsUserCheckable) : Qt::NoItemFlags);
+ it->setCheckState(selected_models_.contains(key) ? Qt::Checked : Qt::Unchecked);
+ }
+ repopulating_ = false;
+}
+
+void NewCompetitionWizard::on_model_item_changed(QListWidgetItem* it) {
+ if (repopulating_ || !it) return;
+ const QString key = it->data(Qt::UserRole).toString();
+ if (it->checkState() == Qt::Checked) {
+ const auto f = it->data(Qt::UserRole + 1).value<QStringList>();
+ if (f.size() < 6) return;
+ ArenaModelOption o;
+ o.provider = f[0]; o.model_id = f[1]; o.display_name = f[2];
+ o.color_hex = f[3]; o.source_kind = f[4]; o.source_ref = f[5];
+ o.ready = true; // only ready rows are checkable
+ selected_models_.insert(key, o);
+ } else {
+ selected_models_.remove(key);
+ }
+ refresh_provider_decorations();
+ update_selection_summary();
+}
+
+void NewCompetitionWizard::refresh_provider_decorations() {
+ QHash<QString, int> counts; // checked models per provider (source of truth)
+ for (const auto& o : selected_models_) counts[o.provider.toLower()]++;
+ for (int i = 0; i < provider_list_->count(); ++i) {
+ auto* it = provider_list_->item(i);
+ const QString p = it->data(Qt::UserRole).toString();
+ bool any_ready = false;
+ for (const auto& o : options_by_provider_.value(p))
+ if (o.ready) { any_ready = true; break; }
+ QString text = ProviderCatalog::display_name(p);
+ if (const int n = counts.value(p); n > 0) text += QStringLiteral(" (%1)").arg(n);
+ if (!any_ready) text += tr(" — needs key");
+ it->setText(text);
+ it->setIcon(dot_icon(any_ready ? ProviderCatalog::brand_color(p)
+ : QStringLiteral("#555555")));
+ it->setForeground(QColor(any_ready ? "#DDD" : "#777"));
+ }
+}
+
+void NewCompetitionWizard::update_selection_summary() {
+ QStringList parts;
+ for (const auto& o : selected_models_)
+ parts << QStringLiteral("%1 (%2)").arg(o.model_id, ProviderCatalog::display_name(o.provider));
+ selection_summary_->setText(parts.isEmpty() ? tr("Selected: none")
+ : tr("Selected: ") + parts.join(", "));
+}
+
+void NewCompetitionWizard::build_step2() {
+ auto* page = new QWidget;
+ auto* v = new QVBoxLayout(page);
+ auto* title = new QLabel(tr("2 · Arena settings"));
+ title->setStyleSheet("color:#FF8800;font-weight:700;font-size:14px;");
+ v->addWidget(title);
+ auto* grid = new QGridLayout;
+ int row = 0;
+ grid->addWidget(new QLabel(tr("Name")), row, 0);
+ name_ = new QLineEdit(tr("Arena-%1").arg(QDateTime::currentDateTime().toString("MMdd-HHmm")));
+ grid->addWidget(name_, row++, 1);
+ grid->addWidget(new QLabel(tr("Instruments")), row, 0);
+ instruments_ = new QListWidget;
+ instruments_->setMaximumHeight(110);
+ for (int i = 0; i < kCoins.size(); ++i) {
+ auto* it = new QListWidgetItem(kCoins[i], instruments_);
+ it->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
+ it->setCheckState(i < kDefaultChecked ? Qt::Checked : Qt::Unchecked);
+ }
+ grid->addWidget(instruments_, row++, 1);
+ grid->addWidget(new QLabel(tr("Capital / agent ($)")), row, 0);
+ capital_ = new QDoubleSpinBox;
+ capital_->setRange(100, 10'000'000); capital_->setValue(10000); capital_->setDecimals(0);
+ grid->addWidget(capital_, row++, 1);
+ grid->addWidget(new QLabel(tr("Round cadence (s)")), row, 0);
+ cadence_ = new QSpinBox;
+ cadence_->setRange(60, 3600); cadence_->setValue(180);
+ grid->addWidget(cadence_, row++, 1);
+ grid->addWidget(new QLabel(tr("Max leverage")), row, 0);
+ max_lev_ = new QDoubleSpinBox;
+ max_lev_->setRange(1, 50); max_lev_->setValue(10); max_lev_->setDecimals(0);
+ grid->addWidget(max_lev_, row++, 1);
+ v->addLayout(grid);
+
+ auto* adv = new QGroupBox(tr("Advanced"));
+ adv->setCheckable(true);
+ adv->setChecked(false);
+ auto* av = new QVBoxLayout(adv);
+ av->addWidget(new QLabel(tr("Custom system prompt (JSON output contract is always appended):")));
+ custom_prompt_ = new QPlainTextEdit;
+ custom_prompt_->setPlaceholderText(tr("Leave empty for the default arena prompt."));
+ custom_prompt_->setMaximumHeight(90);
+ av->addWidget(custom_prompt_);
+ auto* vh = new QHBoxLayout;
+ venue_paper_ = new QRadioButton(tr("Paper (real market data, simulated fills)"));
+ venue_live_ = new QRadioButton(tr("Hyperliquid LIVE (real funds — beta: order mirroring not yet active)"));
+ venue_paper_->setChecked(true);
+ vh->addWidget(venue_paper_); vh->addWidget(venue_live_);
+ av->addLayout(vh);
+ // Hide content when unchecked. Collapsing Advanced also reverts the venue
+ // to Paper — live mode must never ride along invisibly.
+ const auto sync_adv = [adv, this]() {
+ for (auto* w : adv->findChildren<QWidget*>()) w->setVisible(adv->isChecked());
+ if (!adv->isChecked() && venue_live_->isChecked()) venue_paper_->setChecked(true);
+ };
+ connect(adv, &QGroupBox::toggled, this, sync_adv);
+ sync_adv();
+ v->addWidget(adv);
+ v->addStretch(1);
+ steps_->addWidget(page);
+}
+
+void NewCompetitionWizard::update_nav() {
+ const bool last = steps_->currentIndex() == 1;
+ back_->setVisible(last);
+ next_->setText(last ? tr("CREATE && START") : tr("NEXT"));
+}
+
+void NewCompetitionWizard::on_next_or_create() {
+ if (steps_->currentIndex() == 0) {
+ if (selected_models_.isEmpty()) {
+ QMessageBox::warning(this, windowTitle(), tr("Pick at least one model."));
+ return;
+ }
+ steps_->setCurrentIndex(1);
+ update_nav();
+ return;
+ }
+ // Build config.
+ cfg_ = ArenaConfig{};
+ cfg_.name = name_->text().trimmed().isEmpty() ? QStringLiteral("Arena") : name_->text().trimmed();
+ for (int i = 0; i < instruments_->count(); ++i)
+ if (instruments_->item(i)->checkState() == Qt::Checked)
+ cfg_.instruments << instruments_->item(i)->text();
+ if (cfg_.instruments.isEmpty()) {
+ QMessageBox::warning(this, windowTitle(), tr("Pick at least one instrument."));
+ return;
+ }
+ cfg_.capital_per_agent = capital_->value();
+ cfg_.cadence_seconds = cadence_->value();
+ cfg_.max_leverage = max_lev_->value();
+ cfg_.system_prompt_override = custom_prompt_->toPlainText().trimmed();
+ for (const auto& o : selected_models_) { // QMap values → deterministic order
+ ArenaAgentSpec a;
+ a.provider = o.provider; a.model_id = o.model_id; a.display_name = o.display_name;
+ a.color_hex = o.color_hex; a.source_kind = o.source_kind; a.source_ref = o.source_ref;
+ cfg_.agents.append(a);
+ }
+ if (venue_live_->isChecked()) {
+ if (!engage_live_gates()) return; // stays on the wizard
+ cfg_.venue = QStringLiteral("hyperliquid");
+ cfg_.live_mode = true; // carried from the START (fixes the old ordering bug)
+ }
+ accept();
+}
+
+bool NewCompetitionWizard::engage_live_gates() {
+ if (!fincept::trading::hyperliquid::HyperliquidSigner::is_wired()) {
+ QMessageBox::critical(this, windowTitle(),
+ tr("Live mode unavailable: the Hyperliquid signer failed to initialise in this build."));
+ return false;
+ }
+#ifndef FINCEPT_UNSAFE_DISABLE_GEOFENCE
+ if (is_jurisdiction_blocked(QLocale::system().territory())) {
+ QMessageBox::critical(this, windowTitle(), tr("Live mode is unavailable in your jurisdiction."));
+ return false;
+ }
+#endif
+ // competition id doesn't exist yet — gate stores the wallet key under the
+ // name we pass; engine re-keys it after create (Task 6).
+ LiveModeGateDialog dlg(QStringLiteral("pending"), this);
+ return dlg.exec() == QDialog::Accepted;
+}
+
+fincept::arena::ArenaConfig NewCompetitionWizard::config() const { return cfg_; }
+
+} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/NewCompetitionWizard.h b/fincept-qt/src/screens/alpha_arena/NewCompetitionWizard.h
new file mode 100644
index 000000000..25c794483
--- /dev/null
+++ b/fincept-qt/src/screens/alpha_arena/NewCompetitionWizard.h
@@ -0,0 +1,61 @@
+#pragma once
+// NewCompetitionWizard — 2-step modal (spec §6.2). Step 1: provider pane
+// (every catalog provider) → model pane (models of the selected provider,
+// ready/needs-key gating); checks survive provider switches via
+// selected_models_. Step 2: arena settings + Advanced (custom prompt, venue).
+// Finish = create + auto-start (caller does both).
+#include "services/alpha_arena/ArenaModelRegistry.h"
+#include "services/alpha_arena/ArenaTypes.h"
+#include <QDialog>
+#include <QMap>
+
+class QListWidget; class QListWidgetItem; class QLineEdit; class QDoubleSpinBox;
+class QSpinBox; class QPlainTextEdit; class QRadioButton; class QPushButton;
+class QStackedWidget; class QLabel;
+
+namespace fincept::screens::alpha_arena {
+
+class NewCompetitionWizard : public QDialog {
+ Q_OBJECT
+ public:
+ explicit NewCompetitionWizard(QWidget* parent = nullptr);
+ fincept::arena::ArenaConfig config() const; // valid after Accepted
+ private slots:
+ void on_provider_row_changed();
+ void on_model_item_changed(QListWidgetItem* it);
+ private:
+ void build_step1(); void build_step2();
+ void populate_models(); // both panes, from the registry
+ void populate_model_pane(const QString& provider); // right pane only
+ void refresh_provider_decorations(); // dots, counts, needs-key
+ void update_selection_summary();
+ QString current_provider() const;
+ void update_nav();
+ void on_next_or_create();
+ bool engage_live_gates(); // signer + geofence + LiveModeGateDialog
+
+ QStackedWidget* steps_ = nullptr;
+ QListWidget* provider_list_ = nullptr;
+ QListWidget* model_list_ = nullptr;
+ QLabel* model_hint_ = nullptr;
+ QLabel* selection_summary_ = nullptr;
+ /// Single source of truth for cross-provider selection, keyed
+ /// "provider/model_id" (QMap → deterministic agent order in the config).
+ QMap<QString, fincept::arena::ArenaModelOption> selected_models_;
+ /// Registry options grouped by lowercase provider id (rebuilt by populate_models).
+ QMap<QString, QVector<fincept::arena::ArenaModelOption>> options_by_provider_;
+ bool repopulating_ = false; // guards itemChanged during programmatic rebuilds
+ QLineEdit* name_ = nullptr;
+ QListWidget* instruments_ = nullptr;
+ QDoubleSpinBox* capital_ = nullptr;
+ QSpinBox* cadence_ = nullptr;
+ QDoubleSpinBox* max_lev_ = nullptr;
+ QPlainTextEdit* custom_prompt_ = nullptr;
+ QRadioButton* venue_paper_ = nullptr;
+ QRadioButton* venue_live_ = nullptr;
+ QPushButton* back_ = nullptr;
+ QPushButton* next_ = nullptr;
+ fincept::arena::ArenaConfig cfg_;
+};
+
+} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/panels/LeaderboardPanel.cpp b/fincept-qt/src/screens/alpha_arena/panels/LeaderboardPanel.cpp
deleted file mode 100644
index 16f347c59..000000000
--- a/fincept-qt/src/screens/alpha_arena/panels/LeaderboardPanel.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-#include "screens/alpha_arena/panels/LeaderboardPanel.h"
-
-#include "services/alpha_arena/AlphaArenaRepo.h"
-#include "ui/theme/Theme.h"
-
-#include <QColor>
-#include <QCryptographicHash>
-#include <QHBoxLayout>
-#include <QHeaderView>
-#include <QLabel>
-#include <QString>
-#include <QStringList>
-#include <QTableWidgetItem>
-#include <QVBoxLayout>
-
-namespace fincept::screens::alpha_arena {
-
-using namespace fincept::ui;
-using fincept::services::alpha_arena::AlphaArenaRepo;
-using fincept::services::alpha_arena::LeaderboardRow;
-
-namespace {
-
-const QStringList kPalette = {
- "#FF8800", "#00E5FF", "#9D4EDD", "#00D66F", "#FF3B3B",
- "#FFD700", "#0088FF", "#E91E63", "#4CAF50", "#FF5722",
-};
-
-QString fmt_dollars(double v) {
- return QStringLiteral("$%1").arg(v, 0, 'f', 2);
-}
-QString fmt_signed_pct(double frac) {
- const QString sign = (frac >= 0.0) ? QStringLiteral("+") : QString();
- return sign + QString::number(frac * 100.0, 'f', 2) + QStringLiteral("%");
-}
-
-} // namespace
-
-LeaderboardPanel::LeaderboardPanel(QWidget* parent) : QWidget(parent) {
- setObjectName("aaLeaderboardPanel");
-
- auto* root = new QVBoxLayout(this);
- root->setContentsMargins(0, 0, 0, 0);
- root->setSpacing(0);
-
- auto* hdr = new QWidget;
- hdr->setObjectName("aaLeaderboardHeader");
- hdr->setFixedHeight(34);
- auto* hl = new QHBoxLayout(hdr);
- hl->setContentsMargins(12, 0, 12, 0);
- title_ = new QLabel(tr("LEADERBOARD"));
- title_->setObjectName("aaLeaderboardTitle");
- hl->addWidget(title_);
- hl->addStretch(1);
- root->addWidget(hdr);
-
- table_ = new QTableWidget(this);
- table_->setColumnCount(8);
- table_->setHorizontalHeaderLabels(
- {tr("RANK"), tr("MODEL"), tr("EQUITY"), tr("RETURN"), tr("SHARPE"), tr("MAX DD"), tr("FEES"), tr("LEV")});
- table_->horizontalHeader()->setStretchLastSection(true);
- table_->verticalHeader()->setVisible(false);
- table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
- table_->setSelectionBehavior(QAbstractItemView::SelectRows);
- table_->setShowGrid(false);
- connect(table_, &QTableWidget::cellDoubleClicked, this, [this](int row, int) {
- auto* item = table_->item(row, 1);
- if (!item) return;
- emit agent_double_clicked(item->data(Qt::UserRole).toString());
- });
- root->addWidget(table_, 1);
-}
-
-void LeaderboardPanel::set_competition(const QString& competition_id) {
- competition_id_ = competition_id;
- table_->setRowCount(0);
-}
-
-QString LeaderboardPanel::stable_colour_for(const QString& model_id) const {
- if (model_id.isEmpty()) return colors::TEXT_SECONDARY();
- const auto hash = QCryptographicHash::hash(model_id.toUtf8(), QCryptographicHash::Md5);
- const int idx = static_cast<unsigned char>(hash.at(0)) % kPalette.size();
- return kPalette[idx];
-}
-
-void LeaderboardPanel::refresh() {
- if (competition_id_.isEmpty()) { table_->setRowCount(0); return; }
- auto r = AlphaArenaRepo::instance().leaderboard(competition_id_);
- if (r.is_err()) { table_->setRowCount(0); return; }
- const auto rows = r.value();
-
- table_->setSortingEnabled(false);
- table_->setRowCount(rows.size());
- for (int i = 0; i < rows.size(); ++i) {
- const LeaderboardRow& lr = rows[i];
-
- auto* rank_item = new QTableWidgetItem(QString::number(lr.rank));
- rank_item->setTextAlignment(Qt::AlignCenter);
- if (lr.rank == 1) rank_item->setForeground(QColor("#FFD700"));
- else if (lr.rank == 2) rank_item->setForeground(QColor("#C0C0C0"));
- else if (lr.rank == 3) rank_item->setForeground(QColor("#CD7F32"));
- table_->setItem(i, 0, rank_item);
-
- auto* model_item = new QTableWidgetItem(lr.display_name);
- model_item->setData(Qt::UserRole, lr.agent_id);
- const QString colour = !lr.color_hex.isEmpty() ? lr.color_hex
- : stable_colour_for(lr.display_name);
- model_item->setForeground(QColor(colour));
- table_->setItem(i, 1, model_item);
-
- auto* equity = new QTableWidgetItem(fmt_dollars(lr.equity));
- equity->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- equity->setForeground(QColor(colors::CYAN()));
- table_->setItem(i, 2, equity);
-
- auto* ret = new QTableWidgetItem(fmt_signed_pct(lr.return_pct));
- ret->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- ret->setForeground(QColor(lr.return_pct >= 0 ? colors::POSITIVE() : colors::NEGATIVE()));
- table_->setItem(i, 3, ret);
-
- auto* sharpe = new QTableWidgetItem(QString::number(lr.sharpe, 'f', 3));
- sharpe->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- table_->setItem(i, 4, sharpe);
-
- auto* dd = new QTableWidgetItem(fmt_signed_pct(-std::fabs(lr.max_drawdown)));
- dd->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- dd->setForeground(QColor(colors::NEGATIVE()));
- table_->setItem(i, 5, dd);
-
- auto* fees = new QTableWidgetItem(fmt_dollars(lr.fees_paid));
- fees->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- table_->setItem(i, 6, fees);
-
- auto* lev = new QTableWidgetItem(QString::number(lr.avg_leverage, 'f', 2) + QStringLiteral("x"));
- lev->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- table_->setItem(i, 7, lev);
- }
- table_->resizeColumnsToContents();
- table_->setSortingEnabled(true);
-}
-
-// ── Re-translation ───────────────────────────────────────────────────────────
-
-void LeaderboardPanel::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange)
- retranslateUi();
- QWidget::changeEvent(event);
-}
-
-void LeaderboardPanel::retranslateUi() {
- if (title_) title_->setText(tr("LEADERBOARD"));
- if (table_)
- table_->setHorizontalHeaderLabels(
- {tr("RANK"), tr("MODEL"), tr("EQUITY"), tr("RETURN"), tr("SHARPE"), tr("MAX DD"), tr("FEES"), tr("LEV")});
-}
-
-} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/panels/LeaderboardPanel.h b/fincept-qt/src/screens/alpha_arena/panels/LeaderboardPanel.h
deleted file mode 100644
index 9dfce1c41..000000000
--- a/fincept-qt/src/screens/alpha_arena/panels/LeaderboardPanel.h
+++ /dev/null
@@ -1,50 +0,0 @@
-#pragma once
-// LeaderboardPanel — primary surface of the Alpha Arena tab.
-//
-// Reads the latest pnl snapshot per agent from AlphaArenaRepo::leaderboard()
-// and renders 8 columns: RANK, MODEL, EQUITY, RETURN%, SHARPE, MAX DD, FEES,
-// LEVERAGE. Refreshes on AlphaArenaEngine::tick_fired and on demand.
-//
-// Stable colours: the row's model swatch hashes from `model_id` so the same
-// model gets the same colour across competitions. (User's previous prototype
-// keyed colours by row-index, so swap-rank → colour-flip — disorienting.)
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §10 (Scoring) and §11
-// (Frontend C++ surface).
-
-#include <QEvent>
-#include <QLabel>
-#include <QString>
-#include <QTableWidget>
-#include <QWidget>
-
-namespace fincept::screens::alpha_arena {
-
-class LeaderboardPanel : public QWidget {
- Q_OBJECT
- public:
- explicit LeaderboardPanel(QWidget* parent = nullptr);
-
- /// Set the competition the panel is bound to. Empty = idle.
- void set_competition(const QString& competition_id);
-
- public slots:
- /// Refresh the table from AlphaArenaRepo. Cheap to call.
- void refresh();
-
- signals:
- void agent_double_clicked(QString agent_id);
-
- protected:
- void changeEvent(QEvent* event) override;
-
- private:
- QString stable_colour_for(const QString& model_id) const;
- void retranslateUi();
-
- QString competition_id_;
- QLabel* title_ = nullptr;
- QTableWidget* table_;
-};
-
-} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/panels/LiveModeGateDialog.cpp b/fincept-qt/src/screens/alpha_arena/panels/LiveModeGateDialog.cpp
index 462c2b9a5..f80eff2d0 100644
--- a/fincept-qt/src/screens/alpha_arena/panels/LiveModeGateDialog.cpp
+++ b/fincept-qt/src/screens/alpha_arena/panels/LiveModeGateDialog.cpp
@@ -1,12 +1,13 @@
#include "screens/alpha_arena/panels/LiveModeGateDialog.h"
#include "core/logging/Logger.h"
-#include "services/alpha_arena/AlphaArenaRepo.h"
+#include "services/alpha_arena/ArenaStore.h"
#include "storage/secure/SecureStorage.h"
#include <QDateTime>
#include <QHBoxLayout>
#include <QHostInfo>
+#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <QRegularExpression>
@@ -109,14 +110,16 @@ void LiveModeGateDialog::on_confirm() {
return;
}
- QJsonObject payload{
+ // Immutable acceptance record (hostname doubles as the old ack's host field).
+ // competition_id_ may be "pending" when run from the wizard — the engine
+ // re-keys the wallet handle on start(); the event keeps the literal id.
+ const QJsonObject payload{
{"hostname", QHostInfo::localHostName()},
{"timestamp_iso", QDateTime::currentDateTimeUtc().toString(Qt::ISODate)},
{"competition_id", competition_id_}};
- services::alpha_arena::AlphaArenaRepo::instance()
- .append_event(competition_id_, "", QStringLiteral("live_mode_accepted"), payload);
- services::alpha_arena::AlphaArenaRepo::instance()
- .mark_live_mode_ack(competition_id_, QHostInfo::localHostName());
+ fincept::arena::ArenaStore::instance().insert_event(
+ competition_id_, QString(), QStringLiteral("live_mode_accepted"),
+ QString::fromUtf8(QJsonDocument(payload).toJson(QJsonDocument::Compact)));
LOG_WARN("AlphaArena", QStringLiteral("Live mode accepted for competition %1").arg(competition_id_));
diff --git a/fincept-qt/src/screens/alpha_arena/panels/LiveModeGateDialog.h b/fincept-qt/src/screens/alpha_arena/panels/LiveModeGateDialog.h
index 813cb85e9..a3b3e0dff 100644
--- a/fincept-qt/src/screens/alpha_arena/panels/LiveModeGateDialog.h
+++ b/fincept-qt/src/screens/alpha_arena/panels/LiveModeGateDialog.h
@@ -10,7 +10,9 @@
//
// On accept, the dialog stores the key in SecureStorage under the key
// `alpha_arena/agent_key/<competition_id>` and writes a single immutable
-// `live_mode_accepted` event into aa_events with timestamp + hostname.
+// `live_mode_accepted` event into arena_events (ArenaStore) with timestamp +
+// hostname. The wizard passes competition_id="pending" (the competition does
+// not exist yet); ArenaEngine::start() re-keys the wallet handle to the real id.
//
// Reference: .grill-me/alpha-arena-production-refactor.md §Phase 7.
diff --git a/fincept-qt/src/screens/alpha_arena/panels/ModelChatPanel.cpp b/fincept-qt/src/screens/alpha_arena/panels/ModelChatPanel.cpp
deleted file mode 100644
index e2f1e09c0..000000000
--- a/fincept-qt/src/screens/alpha_arena/panels/ModelChatPanel.cpp
+++ /dev/null
@@ -1,194 +0,0 @@
-#include "screens/alpha_arena/panels/ModelChatPanel.h"
-
-#include "services/alpha_arena/AlphaArenaRepo.h"
-#include "ui/theme/Theme.h"
-
-#include <QCoreApplication>
-#include <QDateTime>
-#include <QDialog>
-#include <QDialogButtonBox>
-#include <QHBoxLayout>
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QLabel>
-#include <QListWidgetItem>
-#include <QPlainTextEdit>
-#include <QPushButton>
-#include <QSplitter>
-#include <QString>
-#include <QTextEdit>
-#include <QVBoxLayout>
-
-namespace fincept::screens::alpha_arena {
-
-using fincept::services::alpha_arena::AlphaArenaRepo;
-using fincept::services::alpha_arena::ModelChatRow;
-
-namespace {
-
-QString fmt_tick_time(qint64 utc_ms, int seq) {
- const auto dt = QDateTime::fromMSecsSinceEpoch(utc_ms);
- return QStringLiteral("#%1 %2").arg(seq).arg(dt.toString("HH:mm:ss"));
-}
-
-QString row_summary(const ModelChatRow& r) {
- if (!r.parse_error.isEmpty()) {
- return fmt_tick_time(r.tick_utc_ms, r.tick_seq) +
- QStringLiteral(" ⚠ ") + r.parse_error.left(80);
- }
- auto doc = QJsonDocument::fromJson(r.parsed_actions_json.toUtf8());
- int n = doc.isArray() ? doc.array().size() : 0;
- return fmt_tick_time(r.tick_utc_ms, r.tick_seq) +
- QStringLiteral(" · ") +
- QCoreApplication::translate("ModelChatPanel", "%n action(s)", nullptr, n) +
- (r.cost_usd > 0 ? QStringLiteral(" $%1").arg(r.cost_usd, 0, 'f', 4) : QString());
-}
-
-} // namespace
-
-ModelChatPanel::ModelChatPanel(QWidget* parent) : QWidget(parent) {
- setObjectName("aaModelChatPanel");
- auto* root = new QVBoxLayout(this);
- root->setContentsMargins(0, 0, 0, 0);
- root->setSpacing(0);
-
- auto* header = new QWidget;
- auto* hl = new QHBoxLayout(header);
- hl->setContentsMargins(8, 6, 8, 6);
- agent_label_ = new QLabel(tr("AGENT"));
- hl->addWidget(agent_label_);
- agent_picker_ = new QComboBox;
- connect(agent_picker_, QOverload<int>::of(&QComboBox::currentIndexChanged),
- this, [this](int) { refresh(); });
- hl->addWidget(agent_picker_, 1);
- root->addWidget(header);
-
- timeline_ = new QListWidget(this);
- timeline_->setObjectName("aaModelChatList");
- timeline_->setSelectionMode(QAbstractItemView::SingleSelection);
- connect(timeline_, &QListWidget::itemDoubleClicked, this, [this](QListWidgetItem* it) {
- if (!it) return;
- show_decision_detail(it->data(Qt::UserRole).toString());
- });
- root->addWidget(timeline_, 1);
-}
-
-void ModelChatPanel::set_competition(const QString& competition_id) {
- competition_id_ = competition_id;
- reload_agent_picker();
- refresh();
-}
-
-void ModelChatPanel::reload_agent_picker() {
- agent_picker_->blockSignals(true);
- agent_picker_->clear();
- if (competition_id_.isEmpty()) {
- agent_picker_->blockSignals(false);
- return;
- }
- auto r = AlphaArenaRepo::instance().agents_for(competition_id_);
- if (r.is_ok()) {
- for (const auto& a : r.value()) {
- agent_picker_->addItem(a.display_name, a.id);
- }
- }
- agent_picker_->blockSignals(false);
-}
-
-void ModelChatPanel::on_decision_received(const QString& /*decision_id*/, const QString& agent_id) {
- if (agent_picker_->currentData().toString() == agent_id) refresh();
-}
-
-void ModelChatPanel::refresh() {
- timeline_->clear();
- if (competition_id_.isEmpty() || agent_picker_->currentIndex() < 0) return;
- const QString agent_id = agent_picker_->currentData().toString();
- auto r = AlphaArenaRepo::instance().modelchat_for(competition_id_, agent_id, 200, 0);
- if (r.is_err()) return;
- for (const auto& row : r.value()) {
- auto* item = new QListWidgetItem(row_summary(row));
- item->setData(Qt::UserRole, row.decision_id);
- if (!row.parse_error.isEmpty())
- item->setForeground(QColor(fincept::ui::colors::NEGATIVE()));
- timeline_->addItem(item);
- }
-}
-
-void ModelChatPanel::show_decision_detail(const QString& decision_id) {
- if (decision_id.isEmpty()) return;
- // Re-pull a single-row view by walking the cached list.
- if (competition_id_.isEmpty() || agent_picker_->currentIndex() < 0) return;
- const QString agent_id = agent_picker_->currentData().toString();
- auto r = AlphaArenaRepo::instance().modelchat_for(competition_id_, agent_id, 200, 0);
- if (r.is_err()) return;
-
- ModelChatRow target;
- bool found = false;
- for (const auto& row : r.value()) {
- if (row.decision_id == decision_id) { target = row; found = true; break; }
- }
- if (!found) return;
-
- auto* dlg = new QDialog(this);
- dlg->setAttribute(Qt::WA_DeleteOnClose);
- dlg->setWindowTitle(tr("Tick %1 — %2").arg(target.tick_seq).arg(agent_id.left(8)));
- dlg->resize(800, 600);
-
- auto* layout = new QVBoxLayout(dlg);
-
- auto* split = new QSplitter(Qt::Vertical, dlg);
-
- auto* response = new QPlainTextEdit;
- response->setReadOnly(true);
- response->setPlainText(target.raw_response);
- response->setPlaceholderText(tr("(no response)"));
-
- auto* parsed = new QPlainTextEdit;
- parsed->setReadOnly(true);
- auto pretty = [](const QString& json) {
- auto d = QJsonDocument::fromJson(json.toUtf8());
- if (d.isArray() || d.isObject()) return QString::fromUtf8(d.toJson(QJsonDocument::Indented));
- return json;
- };
- parsed->setPlainText(tr("Parsed actions:\n%1\n\nRisk verdicts:\n%2\n\nParse error: %3")
- .arg(pretty(target.parsed_actions_json),
- pretty(target.risk_verdict_json),
- target.parse_error.isEmpty() ? tr("(none)")
- : target.parse_error));
-
- split->addWidget(response);
- split->addWidget(parsed);
- layout->addWidget(split, 1);
-
- auto* meta = new QLabel(
- QStringLiteral("latency=%1ms in=%2 out=%3 cost=$%4")
- .arg(target.latency_ms)
- .arg(target.tokens_in)
- .arg(target.tokens_out)
- .arg(target.cost_usd, 0, 'f', 4));
- layout->addWidget(meta);
-
- auto* buttons = new QDialogButtonBox(QDialogButtonBox::Close, dlg);
- connect(buttons, &QDialogButtonBox::rejected, dlg, &QDialog::reject);
- layout->addWidget(buttons);
-
- dlg->show();
-}
-
-// ── Re-translation ───────────────────────────────────────────────────────────
-
-void ModelChatPanel::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange)
- retranslateUi();
- QWidget::changeEvent(event);
-}
-
-void ModelChatPanel::retranslateUi() {
- if (agent_label_) agent_label_->setText(tr("AGENT"));
- // Timeline row summaries embed translated "%n action(s)" — rebuild them so
- // they pick up the new language.
- refresh();
-}
-
-} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/panels/ModelChatPanel.h b/fincept-qt/src/screens/alpha_arena/panels/ModelChatPanel.h
deleted file mode 100644
index 4f2dbf404..000000000
--- a/fincept-qt/src/screens/alpha_arena/panels/ModelChatPanel.h
+++ /dev/null
@@ -1,53 +0,0 @@
-#pragma once
-// ModelChatPanel — per-agent decision timeline, the public-trace heart of
-// Alpha Arena. Two stacked widgets:
-// * Top: agent picker (combobox) + auto-scroll toggle.
-// * Bottom: scrollable list of decisions, newest first. Click any row to
-// pop a modal showing the full prompt, response, parsed actions and
-// risk verdict.
-//
-// Reads aa_decisions + aa_prompts via AlphaArenaRepo. Refreshes on
-// AlphaArenaEngine::decision_received.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §10.3 (ModelChat tab).
-
-#include <QComboBox>
-#include <QEvent>
-#include <QLabel>
-#include <QListWidget>
-#include <QString>
-#include <QWidget>
-
-namespace fincept::screens::alpha_arena {
-
-class ModelChatPanel : public QWidget {
- Q_OBJECT
- public:
- explicit ModelChatPanel(QWidget* parent = nullptr);
-
- /// Bind to a competition. Triggers reload of the agent picker.
- void set_competition(const QString& competition_id);
-
- public slots:
- /// Refresh the timeline for the currently-selected agent.
- void refresh();
-
- /// Engine notification — caller passes both ids; if either matches the
- /// current selection, refresh().
- void on_decision_received(const QString& decision_id, const QString& agent_id);
-
- protected:
- void changeEvent(QEvent* event) override;
-
- private:
- void show_decision_detail(const QString& decision_id);
- void reload_agent_picker();
- void retranslateUi();
-
- QString competition_id_;
- QLabel* agent_label_ = nullptr;
- QComboBox* agent_picker_;
- QListWidget* timeline_;
-};
-
-} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/panels/StatePanels.cpp b/fincept-qt/src/screens/alpha_arena/panels/StatePanels.cpp
deleted file mode 100644
index 3614ce3de..000000000
--- a/fincept-qt/src/screens/alpha_arena/panels/StatePanels.cpp
+++ /dev/null
@@ -1,425 +0,0 @@
-// StatePanels.cpp — implementations of PositionsPanel, HitlPanel, RiskPanel,
-// AuditPanel. See StatePanels.h for the contract.
-//
-// Reference: .grill-me/alpha-arena-production-refactor.md §Phase 7.
-
-#include "screens/alpha_arena/panels/StatePanels.h"
-
-#include "services/alpha_arena/AlphaArenaEngine.h"
-#include "services/alpha_arena/AlphaArenaRepo.h"
-#include "ui/theme/Theme.h"
-
-#include <QColor>
-#include <QDateTime>
-#include <QHBoxLayout>
-#include <QHeaderView>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QLabel>
-#include <QListWidgetItem>
-#include <QPushButton>
-#include <QStringList>
-#include <QTableWidgetItem>
-#include <QVBoxLayout>
-
-#include <cmath>
-
-namespace fincept::screens::alpha_arena {
-
-using fincept::services::alpha_arena::AlphaArenaEngine;
-using fincept::services::alpha_arena::AlphaArenaRepo;
-using fincept::services::alpha_arena::AgentRow;
-using fincept::services::alpha_arena::EventRow;
-using fincept::services::alpha_arena::Position;
-
-namespace {
-
-QString fmt_dollars(double v) {
- return QStringLiteral("$%1").arg(v, 0, 'f', 2);
-}
-QString fmt_signed_pct(double frac) {
- const QString sign = (frac >= 0.0) ? QStringLiteral("+") : QString();
- return sign + QString::number(frac * 100.0, 'f', 2) + QStringLiteral("%");
-}
-
-} // namespace
-
-// ── PositionsPanel ──────────────────────────────────────────────────────────
-
-PositionsPanel::PositionsPanel(QWidget* parent) : QWidget(parent) {
- setObjectName("aaPositionsPanel");
- auto* root = new QVBoxLayout(this);
- root->setContentsMargins(0, 0, 0, 0);
- root->setSpacing(0);
-
- auto* hdr = new QWidget;
- auto* hl = new QHBoxLayout(hdr);
- hl->setContentsMargins(12, 6, 12, 6);
- title_ = new QLabel(tr("OPEN POSITIONS"));
- title_->setObjectName("aaPanelTitle");
- hl->addWidget(title_);
- hl->addStretch(1);
- root->addWidget(hdr);
-
- table_ = new QTableWidget(this);
- table_->setColumnCount(8);
- table_->setHorizontalHeaderLabels(
- {tr("AGENT"), tr("COIN"), tr("QTY"), tr("ENTRY"), tr("MARK"), tr("uPnL"), tr("LEV"), tr("LIQ DIST")});
- table_->horizontalHeader()->setStretchLastSection(true);
- table_->verticalHeader()->setVisible(false);
- table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
- table_->setSelectionBehavior(QAbstractItemView::SelectRows);
- table_->setShowGrid(false);
- root->addWidget(table_, 1);
-}
-
-void PositionsPanel::set_competition(const QString& competition_id) {
- competition_id_ = competition_id;
- table_->setRowCount(0);
-}
-
-void PositionsPanel::refresh() {
- if (competition_id_.isEmpty()) {
- table_->setRowCount(0);
- return;
- }
- auto& repo = AlphaArenaRepo::instance();
- auto agents = repo.agents_for(competition_id_);
- if (agents.is_err()) {
- table_->setRowCount(0);
- return;
- }
-
- QVector<QPair<AgentRow, Position>> rows;
- for (const auto& a : agents.value()) {
- auto pos_r = repo.open_positions_for(a.id);
- if (pos_r.is_err()) continue;
- for (const auto& p : pos_r.value()) {
- rows.append({a, p});
- }
- }
-
- table_->setSortingEnabled(false);
- table_->setRowCount(rows.size());
- for (int i = 0; i < rows.size(); ++i) {
- const auto& [agent, p] = rows[i];
-
- auto* it_agent = new QTableWidgetItem(agent.display_name);
- it_agent->setForeground(QColor(agent.color_hex));
- table_->setItem(i, 0, it_agent);
-
- table_->setItem(i, 1, new QTableWidgetItem(p.coin));
-
- auto* it_qty = new QTableWidgetItem(QString::number(p.qty, 'f', 6));
- it_qty->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- it_qty->setForeground(QColor(p.qty >= 0 ? fincept::ui::colors::POSITIVE()
- : fincept::ui::colors::NEGATIVE()));
- table_->setItem(i, 2, it_qty);
-
- auto* it_entry = new QTableWidgetItem(fmt_dollars(p.entry));
- it_entry->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- table_->setItem(i, 3, it_entry);
-
- auto* it_mark = new QTableWidgetItem(fmt_dollars(p.mark));
- it_mark->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- table_->setItem(i, 4, it_mark);
-
- auto* it_pnl = new QTableWidgetItem(fmt_dollars(p.unrealized_pnl));
- it_pnl->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- it_pnl->setForeground(QColor(p.unrealized_pnl >= 0 ? fincept::ui::colors::POSITIVE()
- : fincept::ui::colors::NEGATIVE()));
- table_->setItem(i, 5, it_pnl);
-
- auto* it_lev = new QTableWidgetItem(QString::number(p.leverage) + QStringLiteral("x"));
- it_lev->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- table_->setItem(i, 6, it_lev);
-
- const double dist = (p.mark > 0.0 && p.liq_price > 0.0)
- ? std::fabs(p.mark - p.liq_price) / p.mark : 0.0;
- auto* it_dist = new QTableWidgetItem(fmt_signed_pct(dist));
- it_dist->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- if (dist < 0.05) it_dist->setForeground(QColor(fincept::ui::colors::NEGATIVE()));
- table_->setItem(i, 7, it_dist);
- }
- table_->resizeColumnsToContents();
- table_->setSortingEnabled(true);
-}
-
-void PositionsPanel::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange)
- retranslateUi();
- QWidget::changeEvent(event);
-}
-
-void PositionsPanel::retranslateUi() {
- if (title_) title_->setText(tr("OPEN POSITIONS"));
- if (table_)
- table_->setHorizontalHeaderLabels(
- {tr("AGENT"), tr("COIN"), tr("QTY"), tr("ENTRY"), tr("MARK"), tr("uPnL"), tr("LEV"), tr("LIQ DIST")});
-}
-
-// ── HitlPanel ───────────────────────────────────────────────────────────────
-
-HitlPanel::HitlPanel(QWidget* parent) : QWidget(parent) {
- setObjectName("aaHitlPanel");
- auto* root = new QVBoxLayout(this);
- root->setContentsMargins(0, 0, 0, 0);
- root->setSpacing(0);
-
- title_ = new QLabel(tr("PENDING HITL APPROVALS"));
- title_->setObjectName("aaPanelTitle");
- title_->setContentsMargins(12, 6, 12, 6);
- root->addWidget(title_);
-
- list_ = new QListWidget(this);
- list_->setObjectName("aaHitlList");
- root->addWidget(list_, 1);
-}
-
-void HitlPanel::set_competition(const QString& competition_id) {
- competition_id_ = competition_id;
- list_->clear();
-}
-
-void HitlPanel::refresh() {
- if (competition_id_.isEmpty()) {
- list_->clear();
- return;
- }
- // Re-surface any pending approvals from prior sessions (the engine signal
- // only fires on fresh requests, so on first show we walk the DB).
- auto r = AlphaArenaRepo::instance().pending_hitl_for(competition_id_);
- if (r.is_err()) return;
- list_->clear();
- for (const auto& row : r.value()) {
- const QString summary = QStringLiteral("%1 — %2").arg(row.requested_at.left(19),
- row.prompt_text.left(80));
- rebuild_buttons_for(row.approval_id, row.agent_id, summary);
- }
-}
-
-void HitlPanel::on_hitl_requested(QString approval_id, QString agent_id, QString summary) {
- rebuild_buttons_for(approval_id, agent_id, summary);
-}
-
-void HitlPanel::rebuild_buttons_for(const QString& approval_id, const QString& agent_id,
- const QString& summary) {
- auto* w = new QWidget;
- auto* hl = new QHBoxLayout(w);
- hl->setContentsMargins(8, 4, 8, 4);
-
- auto* label = new QLabel(QStringLiteral("⚠ %1 — %2").arg(agent_id.left(8), summary));
- hl->addWidget(label, 1);
-
- auto* approve = new QPushButton(tr("APPROVE"));
- auto* reject = new QPushButton(tr("REJECT"));
- hl->addWidget(approve);
- hl->addWidget(reject);
-
- auto* item = new QListWidgetItem(list_);
- item->setSizeHint(w->sizeHint());
- list_->addItem(item);
- list_->setItemWidget(item, w);
-
- connect(approve, &QPushButton::clicked, this, [this, approval_id, item]() {
- emit approval_resolved(approval_id, true);
- delete list_->takeItem(list_->row(item));
- });
- connect(reject, &QPushButton::clicked, this, [this, approval_id, item]() {
- emit approval_resolved(approval_id, false);
- delete list_->takeItem(list_->row(item));
- });
-}
-
-void HitlPanel::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange)
- retranslateUi();
- QWidget::changeEvent(event);
-}
-
-void HitlPanel::retranslateUi() {
- if (title_) title_->setText(tr("PENDING HITL APPROVALS"));
- // Approval rows carry translated APPROVE / REJECT buttons — rebuild them.
- refresh();
-}
-
-// ── RiskPanel ───────────────────────────────────────────────────────────────
-
-RiskPanel::RiskPanel(QWidget* parent) : QWidget(parent) {
- setObjectName("aaRiskPanel");
- auto* root = new QVBoxLayout(this);
- root->setContentsMargins(0, 0, 0, 0);
- root->setSpacing(0);
-
- title_ = new QLabel(tr("RISK & TELEMETRY"));
- title_->setObjectName("aaPanelTitle");
- title_->setContentsMargins(12, 6, 12, 6);
- root->addWidget(title_);
-
- telemetry_label_ = new QLabel(tr("Awaiting first tick…"));
- telemetry_label_->setObjectName("aaTelemetryLabel");
- telemetry_label_->setContentsMargins(12, 0, 12, 6);
- telemetry_label_->setStyleSheet("color:#aaa;font-family:monospace;");
- root->addWidget(telemetry_label_);
-
- table_ = new QTableWidget(this);
- table_->setColumnCount(6);
- table_->setHorizontalHeaderLabels(
- {tr("AGENT"), tr("STATE"), tr("PARSE FAILS"), tr("RISK REJECTS"), tr("MAX DD"), tr("AVG LEV")});
- table_->horizontalHeader()->setStretchLastSection(true);
- table_->verticalHeader()->setVisible(false);
- table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
- table_->setSelectionBehavior(QAbstractItemView::SelectRows);
- root->addWidget(table_, 1);
-}
-
-void RiskPanel::set_competition(const QString& competition_id) {
- competition_id_ = competition_id;
- table_->setRowCount(0);
-}
-
-void RiskPanel::refresh() {
- // Telemetry header — read regardless of agent table availability.
- if (telemetry_label_) {
- telemetry_seen_ = true;
- const auto t = AlphaArenaEngine::instance().telemetry();
- telemetry_label_->setText(QStringLiteral(
- "tick latency p50=%1ms p99=%2ms | parse-fail %3% risk-reject %4% venue-err %5 (n=%6)")
- .arg(t.tick_latency_p50_ms, 0, 'f', 0)
- .arg(t.tick_latency_p99_ms, 0, 'f', 0)
- .arg(t.parse_failure_rate * 100.0, 0, 'f', 1)
- .arg(t.risk_rejection_rate * 100.0, 0, 'f', 1)
- .arg(t.venue_errors)
- .arg(t.sample_count));
- }
- if (competition_id_.isEmpty()) {
- table_->setRowCount(0);
- return;
- }
- auto& repo = AlphaArenaRepo::instance();
- auto agents = repo.agents_for(competition_id_);
- auto lb = repo.leaderboard(competition_id_);
- if (agents.is_err()) {
- table_->setRowCount(0);
- return;
- }
-
- table_->setSortingEnabled(false);
- table_->setRowCount(agents.value().size());
- for (int i = 0; i < agents.value().size(); ++i) {
- const auto& a = agents.value()[i];
-
- auto* it_agent = new QTableWidgetItem(a.display_name);
- it_agent->setForeground(QColor(a.color_hex));
- table_->setItem(i, 0, it_agent);
-
- auto* it_state = new QTableWidgetItem(a.state);
- if (a.state == QLatin1String("circuit_open") || a.state == QLatin1String("halted"))
- it_state->setForeground(QColor(fincept::ui::colors::NEGATIVE()));
- table_->setItem(i, 1, it_state);
-
- table_->setItem(i, 2, new QTableWidgetItem(QString::number(a.consecutive_parse_failures)));
- table_->setItem(i, 3, new QTableWidgetItem(QString::number(a.consecutive_risk_rejects)));
-
- double max_dd = 0.0, avg_lev = 0.0;
- if (lb.is_ok()) {
- for (const auto& row : lb.value()) {
- if (row.agent_id == a.id) {
- max_dd = row.max_drawdown;
- avg_lev = row.avg_leverage;
- break;
- }
- }
- }
- auto* it_dd = new QTableWidgetItem(fmt_signed_pct(-std::fabs(max_dd)));
- it_dd->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- it_dd->setForeground(QColor(fincept::ui::colors::NEGATIVE()));
- table_->setItem(i, 4, it_dd);
-
- auto* it_lev = new QTableWidgetItem(QString::number(avg_lev, 'f', 2) + QStringLiteral("x"));
- it_lev->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- table_->setItem(i, 5, it_lev);
- }
- table_->resizeColumnsToContents();
- table_->setSortingEnabled(true);
-}
-
-void RiskPanel::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange)
- retranslateUi();
- QWidget::changeEvent(event);
-}
-
-void RiskPanel::retranslateUi() {
- if (title_) title_->setText(tr("RISK & TELEMETRY"));
- if (table_)
- table_->setHorizontalHeaderLabels(
- {tr("AGENT"), tr("STATE"), tr("PARSE FAILS"), tr("RISK REJECTS"), tr("MAX DD"), tr("AVG LEV")});
- // Only the pre-first-tick placeholder is translatable; once real telemetry
- // (a diagnostic key=value line) is shown we leave it untouched.
- if (telemetry_label_ && !telemetry_seen_)
- telemetry_label_->setText(tr("Awaiting first tick…"));
-}
-
-// ── AuditPanel ──────────────────────────────────────────────────────────────
-
-AuditPanel::AuditPanel(QWidget* parent) : QWidget(parent) {
- setObjectName("aaAuditPanel");
- auto* root = new QVBoxLayout(this);
- root->setContentsMargins(0, 0, 0, 0);
- root->setSpacing(0);
-
- title_ = new QLabel(tr("AUDIT LOG"));
- title_->setObjectName("aaPanelTitle");
- title_->setContentsMargins(12, 6, 12, 6);
- root->addWidget(title_);
-
- list_ = new QListWidget(this);
- list_->setObjectName("aaAuditList");
- root->addWidget(list_, 1);
-}
-
-void AuditPanel::set_competition(const QString& competition_id) {
- competition_id_ = competition_id;
- list_->clear();
- last_seq_ = 0;
-}
-
-void AuditPanel::refresh() {
- if (competition_id_.isEmpty()) return;
-
- auto rows = AlphaArenaRepo::instance().events_since(competition_id_, last_seq_, 200);
- if (rows.is_err()) return;
- for (const auto& e : rows.value()) {
- const QString summary = QStringLiteral("[%1] #%2 %3 %4")
- .arg(e.ts.left(19))
- .arg(e.seq)
- .arg(e.type, -16)
- .arg(e.payload_json.left(80));
- auto* it = new QListWidgetItem(summary);
- if (e.type.contains(QLatin1String("error")) ||
- e.type.contains(QLatin1String("circuit_open")) ||
- e.type.contains(QLatin1String("liquidation"))) {
- it->setForeground(QColor(fincept::ui::colors::NEGATIVE()));
- } else if (e.type.contains(QLatin1String("decision")) ||
- e.type.contains(QLatin1String("fill"))) {
- it->setForeground(QColor(fincept::ui::colors::POSITIVE()));
- }
- list_->addItem(it);
- last_seq_ = std::max<qint64>(last_seq_, e.seq);
- }
- list_->scrollToBottom();
-}
-
-void AuditPanel::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange)
- retranslateUi();
- QWidget::changeEvent(event);
-}
-
-void AuditPanel::retranslateUi() {
- if (title_) title_->setText(tr("AUDIT LOG"));
- // Audit rows are timestamped event data — kept verbatim.
-}
-
-} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/alpha_arena/panels/StatePanels.h b/fincept-qt/src/screens/alpha_arena/panels/StatePanels.h
deleted file mode 100644
index 76b76234e..000000000
--- a/fincept-qt/src/screens/alpha_arena/panels/StatePanels.h
+++ /dev/null
@@ -1,100 +0,0 @@
-#pragma once
-// StatePanels — four light-weight read-only panels grouped in one file.
-//
-// PositionsPanel : open positions per agent (coin, qty, entry, mark, uPnL,
-// leverage, liq distance).
-// HitlPanel : pending HITL approvals; Accept / Reject buttons emit a
-// signal the screen forwards to AlphaArenaEngine::resume_after_hitl.
-// RiskPanel : per-agent kill-switch state (parse fails, risk rejects,
-// drawdown) + average leverage. Reads aa_agents +
-// aa_pnl_snapshots.
-// AuditPanel : append-only event stream from aa_events; tails the latest
-// seq seen, polls AlphaArenaRepo::events_since.
-//
-// Each panel owns its own refresh() and is bound via set_competition().
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §11 (Frontend C++ surface).
-
-#include <QEvent>
-#include <QLabel>
-#include <QListWidget>
-#include <QString>
-#include <QTableWidget>
-#include <QWidget>
-
-namespace fincept::screens::alpha_arena {
-
-class PositionsPanel : public QWidget {
- Q_OBJECT
- public:
- explicit PositionsPanel(QWidget* parent = nullptr);
- void set_competition(const QString& competition_id);
- public slots:
- void refresh();
- protected:
- void changeEvent(QEvent* event) override;
- private:
- void retranslateUi();
- QString competition_id_;
- QLabel* title_ = nullptr;
- QTableWidget* table_;
-};
-
-class HitlPanel : public QWidget {
- Q_OBJECT
- public:
- explicit HitlPanel(QWidget* parent = nullptr);
- void set_competition(const QString& competition_id);
- public slots:
- void refresh();
- /// Surface a freshly-requested HITL approval (engine signal).
- void on_hitl_requested(QString approval_id, QString agent_id, QString summary);
- signals:
- void approval_resolved(QString approval_id, bool approved);
- protected:
- void changeEvent(QEvent* event) override;
- private:
- void rebuild_buttons_for(const QString& approval_id, const QString& agent_id,
- const QString& summary);
- void retranslateUi();
- QString competition_id_;
- QLabel* title_ = nullptr;
- QListWidget* list_;
-};
-
-class RiskPanel : public QWidget {
- Q_OBJECT
- public:
- explicit RiskPanel(QWidget* parent = nullptr);
- void set_competition(const QString& competition_id);
- public slots:
- void refresh();
- protected:
- void changeEvent(QEvent* event) override;
- private:
- void retranslateUi();
- QString competition_id_;
- QLabel* title_ = nullptr;
- QTableWidget* table_;
- QLabel* telemetry_label_ = nullptr; // p50/p99 + rates summary
- bool telemetry_seen_ = false; // false until first refresh sets real telemetry
-};
-
-class AuditPanel : public QWidget {
- Q_OBJECT
- public:
- explicit AuditPanel(QWidget* parent = nullptr);
- void set_competition(const QString& competition_id);
- public slots:
- void refresh();
- protected:
- void changeEvent(QEvent* event) override;
- private:
- void retranslateUi();
- QString competition_id_;
- QLabel* title_ = nullptr;
- QListWidget* list_;
- qint64 last_seq_ = 0;
-};
-
-} // namespace fincept::screens::alpha_arena
diff --git a/fincept-qt/src/screens/equity_trading/BasketOrdersDialog.cpp b/fincept-qt/src/screens/equity_trading/BasketOrdersDialog.cpp
new file mode 100644
index 000000000..3d119866e
--- /dev/null
+++ b/fincept-qt/src/screens/equity_trading/BasketOrdersDialog.cpp
@@ -0,0 +1,401 @@
+#include "screens/equity_trading/BasketOrdersDialog.h"
+
+#include "trading/AccountManager.h"
+#include "trading/BrokerRegistry.h"
+#include "trading/UnifiedTrading.h"
+#include "ui/theme/Theme.h"
+
+#include <QCheckBox>
+#include <QComboBox>
+#include <QDoubleSpinBox>
+#include <QHBoxLayout>
+#include <QHeaderView>
+#include <QLabel>
+#include <QLineEdit>
+#include <QListWidget>
+#include <QMessageBox>
+#include <QPointer>
+#include <QPushButton>
+#include <QSpinBox>
+#include <QSplitter>
+#include <QTableWidget>
+#include <QVBoxLayout>
+
+namespace fincept::screens::equity {
+
+using namespace fincept::ui;
+using trading::OrderSide;
+using trading::OrderType;
+using trading::ProductType;
+using trading::UnifiedOrder;
+
+namespace {
+enum LegCol { LSymbol = 0, LExchange, LSide, LQty, LType, LPrice, LProduct, LRemove, LColCount };
+} // namespace
+
+BasketOrdersDialog::BasketOrdersDialog(QWidget* parent) : QDialog(parent) {
+ setWindowTitle(tr("Order Baskets"));
+ setMinimumSize(860, 540);
+ setStyleSheet(QString("QDialog{background:%1;}").arg(colors::BG_BASE()));
+
+ auto* root = new QHBoxLayout(this);
+ auto* split = new QSplitter(Qt::Horizontal);
+ root->addWidget(split);
+
+ // ── Left: saved baskets ──────────────────────────────────────────────────
+ auto* left = new QWidget;
+ auto* lv = new QVBoxLayout(left);
+ lv->setContentsMargins(8, 8, 4, 8);
+ auto* title = new QLabel(tr("BASKETS"));
+ title->setStyleSheet("color:#808080;font-size:10px;font-weight:700;");
+ lv->addWidget(title);
+ basket_list_ = new QListWidget;
+ basket_list_->setStyleSheet("QListWidget{background:#080808;border:1px solid #1a1a1a;font-size:12px;}"
+ "QListWidget::item{padding:6px 8px;}"
+ "QListWidget::item:selected{background:rgba(217,119,6,0.15);color:#d97706;}");
+ connect(basket_list_, &QListWidget::currentRowChanged, this, &BasketOrdersDialog::on_basket_selected);
+ lv->addWidget(basket_list_, 1);
+ auto* lbtns = new QHBoxLayout;
+ new_btn_ = new QPushButton(tr("+ NEW"));
+ delete_btn_ = new QPushButton(tr("DELETE"));
+ for (auto* b : {new_btn_, delete_btn_}) {
+ b->setCursor(Qt::PointingHandCursor);
+ b->setStyleSheet("QPushButton{background:#111;border:1px solid #2a2a2a;color:#d97706;"
+ "padding:5px 10px;font-size:11px;font-weight:600;}"
+ "QPushButton:hover{border-color:#d97706;}");
+ lbtns->addWidget(b);
+ }
+ connect(new_btn_, &QPushButton::clicked, this, &BasketOrdersDialog::on_new_basket);
+ connect(delete_btn_, &QPushButton::clicked, this, &BasketOrdersDialog::on_delete_basket);
+ lv->addLayout(lbtns);
+ split->addWidget(left);
+
+ // ── Right: editor + execute ──────────────────────────────────────────────
+ auto* right = new QWidget;
+ auto* rv = new QVBoxLayout(right);
+ rv->setContentsMargins(4, 8, 8, 8);
+
+ auto* name_row = new QHBoxLayout;
+ name_row->addWidget(new QLabel(tr("Name:")));
+ name_edit_ = new QLineEdit;
+ name_edit_->setPlaceholderText(tr("e.g. Nifty Core 5"));
+ name_row->addWidget(name_edit_, 1);
+ save_btn_ = new QPushButton(tr("SAVE BASKET"));
+ save_btn_->setCursor(Qt::PointingHandCursor);
+ save_btn_->setStyleSheet("QPushButton{background:#111;border:1px solid #d97706;color:#d97706;"
+ "padding:5px 12px;font-size:11px;font-weight:700;}"
+ "QPushButton:hover{background:#d97706;color:#080808;}");
+ connect(save_btn_, &QPushButton::clicked, this, &BasketOrdersDialog::on_save_basket);
+ name_row->addWidget(save_btn_);
+ rv->addLayout(name_row);
+
+ legs_table_ = new QTableWidget(0, LColCount);
+ legs_table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Exch"), tr("Side"), tr("Qty"), tr("Type"),
+ tr("Price"), tr("Product"), QString()});
+ legs_table_->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
+ legs_table_->horizontalHeader()->setStretchLastSection(false);
+ legs_table_->setColumnWidth(LSymbol, 140);
+ legs_table_->setColumnWidth(LRemove, 36);
+ legs_table_->verticalHeader()->setVisible(false);
+ legs_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ legs_table_->setStyleSheet("QTableWidget{background:#080808;border:1px solid #1a1a1a;font-size:12px;}");
+ rv->addWidget(legs_table_, 1);
+
+ // Add-leg row
+ auto* add_row = new QHBoxLayout;
+ leg_symbol_ = new QLineEdit;
+ leg_symbol_->setPlaceholderText(tr("SYMBOL"));
+ leg_symbol_->setMaximumWidth(140);
+ leg_exchange_ = new QComboBox;
+ leg_exchange_->addItems({"NSE", "BSE", "NFO", "BFO", "MCX", "CDS"});
+ leg_side_ = new QComboBox;
+ leg_side_->addItems({tr("BUY"), tr("SELL")});
+ leg_qty_ = new QSpinBox;
+ leg_qty_->setRange(1, 1'000'000);
+ leg_type_ = new QComboBox;
+ leg_type_->addItems({tr("MARKET"), tr("LIMIT")});
+ leg_price_ = new QDoubleSpinBox;
+ leg_price_->setRange(0.0, 10'000'000.0);
+ leg_price_->setDecimals(2);
+ leg_price_->setEnabled(false);
+ connect(leg_type_, &QComboBox::currentIndexChanged, leg_price_,
+ [this](int idx) { leg_price_->setEnabled(idx == 1); });
+ leg_product_ = new QComboBox;
+ leg_product_->addItems({tr("INTRADAY"), tr("DELIVERY"), tr("MARGIN")});
+ auto* add_btn = new QPushButton(tr("+ ADD"));
+ add_btn->setCursor(Qt::PointingHandCursor);
+ add_btn->setStyleSheet("QPushButton{background:#111;border:1px solid #2a2a2a;color:#d97706;"
+ "padding:4px 10px;font-size:11px;font-weight:600;}"
+ "QPushButton:hover{border-color:#d97706;}");
+ connect(add_btn, &QPushButton::clicked, this, &BasketOrdersDialog::on_add_leg);
+ connect(leg_symbol_, &QLineEdit::returnPressed, this, &BasketOrdersDialog::on_add_leg);
+ for (QWidget* w : std::initializer_list<QWidget*>{leg_symbol_, leg_exchange_, leg_side_, leg_qty_,
+ leg_type_, leg_price_, leg_product_, add_btn})
+ add_row->addWidget(w);
+ rv->addLayout(add_row);
+
+ // Execute: account multi-select + button
+ build_accounts_box(rv);
+
+ status_label_ = new QLabel;
+ status_label_->setWordWrap(true);
+ status_label_->setStyleSheet("color:#808080;font-size:11px;");
+ rv->addWidget(status_label_);
+
+ split->addWidget(right);
+ split->setStretchFactor(0, 0);
+ split->setStretchFactor(1, 1);
+ split->setSizes({220, 640});
+
+ reload_baskets();
+}
+
+void BasketOrdersDialog::build_accounts_box(QVBoxLayout* into) {
+ auto* cap = new QLabel(tr("EXECUTE ON"));
+ cap->setStyleSheet("color:#808080;font-size:10px;font-weight:700;margin-top:6px;");
+ into->addWidget(cap);
+
+ auto* row = new QHBoxLayout;
+ const auto accounts = trading::AccountManager::instance().active_accounts();
+ for (const auto& account : accounts) {
+ auto* broker = trading::BrokerRegistry::instance().get(account.broker_id);
+ const QString broker_name = broker ? broker->profile().display_name : account.broker_id;
+ const QString mode_tag = account.trading_mode == "live" ? tr("LIVE") : tr("PAPER");
+ auto* cb = new QCheckBox(QString("%1 [%2·%3]").arg(account.display_name, broker_name, mode_tag));
+ cb->setStyleSheet("QCheckBox{color:#9ca3af;font-size:11px;}");
+ account_cbs_.append(cb);
+ account_ids_.append(account.account_id);
+ row->addWidget(cb);
+ }
+ row->addStretch(1);
+
+ execute_btn_ = new QPushButton(tr("EXECUTE BASKET"));
+ execute_btn_->setCursor(Qt::PointingHandCursor);
+ execute_btn_->setStyleSheet("QPushButton{background:#052e16;border:1px solid #16a34a;color:#22c55e;"
+ "padding:6px 16px;font-size:12px;font-weight:700;}"
+ "QPushButton:hover{background:#16a34a;color:#080808;}");
+ connect(execute_btn_, &QPushButton::clicked, this, &BasketOrdersDialog::on_execute);
+ row->addWidget(execute_btn_);
+ into->addLayout(row);
+}
+
+// ── Basket CRUD ──────────────────────────────────────────────────────────────
+
+void BasketOrdersDialog::reload_baskets(const QString& select_id) {
+ baskets_ = OrderBasketRepository::instance().list_all();
+ basket_list_->clear();
+ int select_row = baskets_.isEmpty() ? -1 : 0;
+ for (int i = 0; i < baskets_.size(); ++i) {
+ basket_list_->addItem(QString("%1 (%2)").arg(baskets_[i].name).arg(baskets_[i].legs.size()));
+ if (!select_id.isEmpty() && baskets_[i].id == select_id)
+ select_row = i;
+ }
+ basket_list_->setCurrentRow(select_row); // triggers on_basket_selected
+ if (select_row < 0) {
+ current_row_ = -1;
+ name_edit_->clear();
+ refresh_legs_table();
+ }
+}
+
+OrderBasket* BasketOrdersDialog::current_basket() {
+ return current_row_ >= 0 && current_row_ < baskets_.size() ? &baskets_[current_row_] : nullptr;
+}
+
+void BasketOrdersDialog::on_basket_selected(int row) {
+ current_row_ = row;
+ if (auto* b = current_basket())
+ name_edit_->setText(b->name);
+ refresh_legs_table();
+}
+
+void BasketOrdersDialog::on_new_basket() {
+ OrderBasket b;
+ b.name = tr("New Basket");
+ b = OrderBasketRepository::instance().save(b);
+ reload_baskets(b.id);
+ name_edit_->setFocus();
+ name_edit_->selectAll();
+}
+
+void BasketOrdersDialog::on_delete_basket() {
+ auto* b = current_basket();
+ if (!b)
+ return;
+ if (QMessageBox::question(this, tr("Delete Basket"), tr("Delete basket '%1'?").arg(b->name)) !=
+ QMessageBox::Yes)
+ return;
+ OrderBasketRepository::instance().remove(b->id);
+ reload_baskets();
+}
+
+void BasketOrdersDialog::on_save_basket() {
+ auto* b = current_basket();
+ if (!b)
+ return;
+ b->name = name_edit_->text().trimmed().isEmpty() ? tr("Unnamed") : name_edit_->text().trimmed();
+ *b = OrderBasketRepository::instance().save(*b);
+ const QString id = b->id;
+ reload_baskets(id);
+ status_label_->setText(tr("Basket saved"));
+ status_label_->setStyleSheet(QString("color:%1;font-size:11px;").arg(colors::POSITIVE()));
+}
+
+// ── Legs ─────────────────────────────────────────────────────────────────────
+
+void BasketOrdersDialog::refresh_legs_table() {
+ legs_table_->setRowCount(0);
+ auto* b = current_basket();
+ if (!b)
+ return;
+ legs_table_->setRowCount(int(b->legs.size()));
+ for (int i = 0; i < b->legs.size(); ++i) {
+ const UnifiedOrder& leg = b->legs[i];
+ auto set = [&](int col, const QString& text) {
+ legs_table_->setItem(i, col, new QTableWidgetItem(text));
+ };
+ set(LSymbol, leg.symbol);
+ set(LExchange, leg.exchange);
+ set(LSide, leg.side == OrderSide::Buy ? tr("BUY") : tr("SELL"));
+ legs_table_->item(i, LSide)->setForeground(leg.side == OrderSide::Buy
+ ? QColor(colors::POSITIVE())
+ : QColor(colors::NEGATIVE()));
+ set(LQty, QString::number(leg.quantity));
+ set(LType, leg.order_type == OrderType::Market ? tr("MKT") : tr("LMT"));
+ set(LPrice, leg.order_type == OrderType::Market ? QStringLiteral("—")
+ : QString::number(leg.price, 'f', 2));
+ set(LProduct, leg.product_type == ProductType::Delivery ? tr("CNC")
+ : leg.product_type == ProductType::Margin ? tr("NRML")
+ : tr("MIS"));
+ auto* rm = new QPushButton(QStringLiteral("✕"));
+ rm->setCursor(Qt::PointingHandCursor);
+ rm->setStyleSheet("QPushButton{background:transparent;border:none;color:#ef4444;font-size:12px;}");
+ connect(rm, &QPushButton::clicked, this, [this, i]() {
+ if (auto* bb = current_basket()) {
+ if (i < bb->legs.size()) {
+ bb->legs.removeAt(i);
+ OrderBasketRepository::instance().save(*bb);
+ refresh_legs_table();
+ }
+ }
+ });
+ legs_table_->setCellWidget(i, LRemove, rm);
+ }
+}
+
+void BasketOrdersDialog::on_add_leg() {
+ auto* b = current_basket();
+ if (!b) {
+ status_label_->setText(tr("Create or select a basket first"));
+ status_label_->setStyleSheet(QString("color:%1;font-size:11px;").arg(colors::NEGATIVE()));
+ return;
+ }
+ const QString symbol = leg_symbol_->text().trimmed().toUpper();
+ if (symbol.isEmpty())
+ return;
+ const bool is_limit = leg_type_->currentIndex() == 1;
+ if (is_limit && leg_price_->value() <= 0.0) {
+ status_label_->setText(tr("Enter a limit price for %1").arg(symbol));
+ status_label_->setStyleSheet(QString("color:%1;font-size:11px;").arg(colors::NEGATIVE()));
+ return;
+ }
+
+ UnifiedOrder leg;
+ leg.symbol = symbol;
+ leg.exchange = leg_exchange_->currentText();
+ leg.side = leg_side_->currentIndex() == 0 ? OrderSide::Buy : OrderSide::Sell;
+ leg.order_type = is_limit ? OrderType::Limit : OrderType::Market;
+ leg.quantity = leg_qty_->value();
+ leg.price = is_limit ? leg_price_->value() : 0.0;
+ leg.product_type = leg_product_->currentIndex() == 0 ? ProductType::Intraday
+ : leg_product_->currentIndex() == 1 ? ProductType::Delivery
+ : ProductType::Margin;
+ b->legs.append(leg);
+ OrderBasketRepository::instance().save(*b);
+ leg_symbol_->clear();
+ refresh_legs_table();
+ // Keep the list's leg-count label current without rebuilding selection.
+ if (auto* item = basket_list_->item(current_row_))
+ item->setText(QString("%1 (%2)").arg(b->name).arg(b->legs.size()));
+}
+
+// ── Execute ──────────────────────────────────────────────────────────────────
+
+void BasketOrdersDialog::on_execute() {
+ auto* b = current_basket();
+ if (!b || b->legs.isEmpty()) {
+ status_label_->setText(tr("Basket is empty — add legs first"));
+ status_label_->setStyleSheet(QString("color:%1;font-size:11px;").arg(colors::NEGATIVE()));
+ return;
+ }
+ QStringList selected;
+ QStringList labels;
+ for (int i = 0; i < account_cbs_.size(); ++i) {
+ if (account_cbs_[i]->isChecked()) {
+ selected.append(account_ids_[i]);
+ labels << account_cbs_[i]->text();
+ }
+ }
+ if (selected.isEmpty()) {
+ status_label_->setText(tr("Select at least one account"));
+ status_label_->setStyleSheet(QString("color:%1;font-size:11px;").arg(colors::NEGATIVE()));
+ return;
+ }
+
+ const auto ret = QMessageBox::question(
+ this, tr("Execute Basket"),
+ tr("Execute '%1' (%2 leg(s)) on %3 account(s)?\n\n%4")
+ .arg(b->name)
+ .arg(b->legs.size())
+ .arg(selected.size())
+ .arg(labels.join("\n")),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (ret != QMessageBox::Yes)
+ return;
+
+ execute_btn_->setEnabled(false);
+ status_label_->setText(tr("Executing on %1 account(s)…").arg(selected.size()));
+ status_label_->setStyleSheet("color:#d97706;font-size:11px;");
+
+ trading::BasketOrderRequest req;
+ req.orders = b->legs;
+ req.strategy_name = b->name;
+
+ // place_basket_orders runs on its own background thread per call and
+ // invokes the callback on this (caller's) thread. Aggregate across accounts.
+ struct Tally {
+ int pending = 0;
+ int ok = 0;
+ int fail = 0;
+ QStringList errors;
+ };
+ auto tally = std::make_shared<Tally>();
+ tally->pending = int(selected.size());
+
+ QPointer<BasketOrdersDialog> self(this);
+ for (const QString& acct_id : selected) {
+ const QString label = trading::AccountManager::instance().get_account(acct_id).display_name;
+ trading::UnifiedTrading::instance().place_basket_orders(
+ acct_id, req, [self, tally, label](const trading::BasketOrderResult& r) {
+ if (!self)
+ return;
+ tally->ok += r.successful;
+ tally->fail += r.failed;
+ for (const auto& or_ : r.results)
+ if (!or_.success)
+ tally->errors << QString("%1/%2: %3").arg(label, or_.symbol, or_.error);
+ if (--tally->pending == 0) {
+ QString msg = tr("✓ %1 leg(s) placed").arg(tally->ok);
+ if (tally->fail > 0)
+ msg += tr(" — ✗ %1 failed: %2").arg(tally->fail).arg(tally->errors.join("; "));
+ self->status_label_->setText(msg);
+ self->status_label_->setStyleSheet(QString("color:%1;font-size:11px;")
+ .arg(tally->fail == 0 ? colors::POSITIVE()
+ : colors::NEGATIVE()));
+ self->execute_btn_->setEnabled(true);
+ }
+ });
+ }
+}
+
+} // namespace fincept::screens::equity
diff --git a/fincept-qt/src/screens/equity_trading/BasketOrdersDialog.h b/fincept-qt/src/screens/equity_trading/BasketOrdersDialog.h
new file mode 100644
index 000000000..c96b21bdf
--- /dev/null
+++ b/fincept-qt/src/screens/equity_trading/BasketOrdersDialog.h
@@ -0,0 +1,71 @@
+#pragma once
+// BasketOrdersDialog — Zerodha-style order baskets, broker-agnostic.
+// Create/edit named baskets of order legs, then execute the whole basket on one
+// or several accounts at once. Execution goes through
+// UnifiedTrading::place_basket_orders per selected account, so each account
+// keeps its own paper/live routing and broker mapping.
+
+#include "storage/repositories/OrderBasketRepository.h"
+
+#include <QDialog>
+
+class QCheckBox;
+class QComboBox;
+class QLabel;
+class QLineEdit;
+class QListWidget;
+class QPushButton;
+class QSpinBox;
+class QDoubleSpinBox;
+class QTableWidget;
+class QVBoxLayout;
+
+namespace fincept::screens::equity {
+
+class BasketOrdersDialog : public QDialog {
+ Q_OBJECT
+ public:
+ explicit BasketOrdersDialog(QWidget* parent = nullptr);
+
+ private slots:
+ void on_basket_selected(int row);
+ void on_new_basket();
+ void on_delete_basket();
+ void on_save_basket();
+ void on_add_leg();
+ void on_execute();
+
+ private:
+ void reload_baskets(const QString& select_id = {});
+ void refresh_legs_table();
+ void build_accounts_box(QVBoxLayout* into);
+ OrderBasket* current_basket();
+
+ QVector<OrderBasket> baskets_;
+ int current_row_ = -1;
+
+ // Left: basket list
+ QListWidget* basket_list_ = nullptr;
+ QPushButton* new_btn_ = nullptr;
+ QPushButton* delete_btn_ = nullptr;
+
+ // Right: editor
+ QLineEdit* name_edit_ = nullptr;
+ QTableWidget* legs_table_ = nullptr;
+ QLineEdit* leg_symbol_ = nullptr;
+ QComboBox* leg_exchange_ = nullptr;
+ QComboBox* leg_side_ = nullptr;
+ QSpinBox* leg_qty_ = nullptr;
+ QComboBox* leg_type_ = nullptr;
+ QDoubleSpinBox* leg_price_ = nullptr;
+ QComboBox* leg_product_ = nullptr;
+ QPushButton* save_btn_ = nullptr;
+
+ // Execute
+ QVector<QCheckBox*> account_cbs_;
+ QVector<QString> account_ids_;
+ QPushButton* execute_btn_ = nullptr;
+ QLabel* status_label_ = nullptr;
+};
+
+} // namespace fincept::screens::equity
diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
index f3b3ff31e..53db5182d 100644
--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
@@ -183,7 +183,7 @@ void EquityBottomPanel::retranslateUi() {
if (holdings_table_)
holdings_table_->setHorizontalHeaderLabels(
{tr("Symbol"), tr("Qty"), tr("Avg Price"), tr("LTP"), tr("Invested"), tr("Current"), tr("P&L"),
- tr("P&L %")});
+ tr("P&L %"), tr("Day P&L"), tr("Action")});
if (orders_table_)
orders_table_->setHorizontalHeaderLabels({tr("Order ID"), tr("Symbol"), tr("Product"), tr("Side"), tr("Type"),
tr("Qty"), tr("Price"), tr("Status"), tr("Time"), tr("Action")});
@@ -208,6 +208,7 @@ void EquityBottomPanel::retranslateUi() {
if (holdings_invested_caption_) holdings_invested_caption_->setText(tr("INVESTED"));
if (holdings_current_caption_) holdings_current_caption_->setText(tr("CURRENT"));
if (holdings_pnl_caption_) holdings_pnl_caption_->setText(tr("TOTAL P&L"));
+ if (holdings_day_pnl_caption_) holdings_day_pnl_caption_->setText(tr("TODAY'S P&L"));
if (holdings_pnl_pct_caption_) holdings_pnl_pct_caption_->setText(tr("RETURN %"));
// Funds card captions
@@ -425,6 +426,7 @@ void EquityBottomPanel::setup_holdings_tab() {
holdings_invested_label_ = make_stat(tr("INVESTED"), holdings_invested_caption_);
holdings_current_label_ = make_stat(tr("CURRENT"), holdings_current_caption_);
holdings_pnl_label_ = make_stat(tr("TOTAL P&L"), holdings_pnl_caption_);
+ holdings_day_pnl_label_ = make_stat(tr("TODAY'S P&L"), holdings_day_pnl_caption_);
holdings_pnl_pct_label_ = make_stat(tr("RETURN %"), holdings_pnl_pct_caption_);
strip_layout->addStretch(1);
@@ -486,10 +488,10 @@ void EquityBottomPanel::setup_holdings_tab() {
holdings_table_ = new QTableWidget;
holdings_table_->setObjectName("eqTable");
- holdings_table_->setColumnCount(9);
+ holdings_table_->setColumnCount(10);
holdings_table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Qty"), tr("Avg Price"), tr("LTP"),
tr("Invested"), tr("Current"), tr("P&L"), tr("P&L %"),
- tr("Action")});
+ tr("Day P&L"), tr("Action")});
holdings_table_->verticalHeader()->setVisible(false);
holdings_table_->setSelectionBehavior(QAbstractItemView::SelectRows);
holdings_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
@@ -996,7 +998,7 @@ void EquityBottomPanel::set_positions(const QVector<trading::BrokerPosition>& po
update_positions_summary();
}
-void EquityBottomPanel::update_holding_quote(const QString& symbol, double ltp) {
+void EquityBottomPanel::update_holding_quote(const QString& symbol, double ltp, double prev_close) {
// Find this symbol's holding (one per symbol) and re-mark it to the live price.
trading::BrokerHolding* h = nullptr;
for (auto& it : last_holdings_)
@@ -1007,9 +1009,12 @@ void EquityBottomPanel::update_holding_quote(const QString& symbol, double ltp)
if (!h)
return;
h->ltp = ltp;
+ if (prev_close > 0.0)
+ h->prev_close = prev_close; // capture today's prev close from the live quote
h->current_value = h->quantity * ltp;
h->pnl = h->current_value - h->invested_value;
h->pnl_pct = h->invested_value > 0.0 ? (h->pnl / h->invested_value) * 100.0 : 0.0;
+ const double day_pnl = h->prev_close > 0.0 ? h->quantity * (ltp - h->prev_close) : 0.0;
const QColor pos_color(fincept::ui::colors::POSITIVE());
const QColor neg_color(fincept::ui::colors::NEGATIVE());
@@ -1037,16 +1042,22 @@ void EquityBottomPanel::update_holding_quote(const QString& symbol, double ltp)
pct_item->setData(Qt::DisplayRole, QString("%1%").arg(h->pnl_pct, 0, 'f', 2));
pct_item->setData(Qt::EditRole, h->pnl_pct);
pct_item->setForeground(h->pnl_pct >= 0 ? pos_color : neg_color);
+ auto* day_item = ensure_item(holdings_table_, r, 8); // Today's P&L
+ day_item->setData(Qt::DisplayRole, QString::number(day_pnl, 'f', 2));
+ day_item->setData(Qt::EditRole, day_pnl);
+ day_item->setForeground(day_pnl >= 0 ? pos_color : neg_color);
break; // one row per symbol
}
holdings_table_->setSortingEnabled(was_sorting);
- // Refresh the summary strip (CURRENT / TOTAL P&L / RETURN %); invested is fixed.
- double total_invested = 0.0, total_current = 0.0, total_pnl = 0.0;
+ // Refresh the summary strip (CURRENT / TOTAL P&L / TODAY'S P&L / RETURN %); invested is fixed.
+ double total_invested = 0.0, total_current = 0.0, total_pnl = 0.0, total_day_pnl = 0.0;
for (const auto& it : last_holdings_) {
total_invested += it.invested_value;
total_current += it.current_value;
total_pnl += it.pnl;
+ if (it.prev_close > 0.0)
+ total_day_pnl += it.quantity * (it.ltp - it.prev_close);
}
const double total_pct = total_invested > 0.0 ? (total_pnl / total_invested) * 100.0 : 0.0;
if (holdings_current_label_)
@@ -1058,6 +1069,13 @@ void EquityBottomPanel::update_holding_quote(const QString& symbol, double ltp)
QString("color:%1;font-size:13px;font-weight:700;")
.arg(total_pnl >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE()));
}
+ if (holdings_day_pnl_label_) {
+ holdings_day_pnl_label_->setText(
+ QString("%1%2").arg(total_day_pnl >= 0 ? "+" : "").arg(QString::number(total_day_pnl, 'f', 2)));
+ holdings_day_pnl_label_->setStyleSheet(
+ QString("color:%1;font-size:13px;font-weight:700;")
+ .arg(total_day_pnl >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE()));
+ }
if (holdings_pnl_pct_label_) {
holdings_pnl_pct_label_->setText(
QString("%1%2%").arg(total_pct >= 0 ? "+" : "").arg(QString::number(total_pct, 'f', 2)));
@@ -1093,7 +1111,8 @@ void EquityBottomPanel::update_quote(const QString& symbol, const trading::Broke
}
// Holdings (CNC) live the same quote stream as positions — patch them too.
- update_holding_quote(symbol, ltp);
+ // quote.close is today's previous-day close → drives the "Today's P&L" column.
+ update_holding_quote(symbol, ltp, quote.close);
const QColor pos_color(fincept::ui::colors::POSITIVE());
const QColor neg_color(fincept::ui::colors::NEGATIVE());
@@ -1149,7 +1168,19 @@ void EquityBottomPanel::update_quote(const QString& symbol, const trading::Broke
}
void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& holdings) {
+ // Carry forward prev_close (today's close, learned from the live quote feed)
+ // across REST holdings refreshes so the "Today's P&L" column/total don't blink
+ // to 0 on every poll — the REST payload doesn't carry prev_close.
+ QHash<QString, double> prev_close_by_sym;
+ for (const auto& it : last_holdings_)
+ if (it.prev_close > 0.0)
+ prev_close_by_sym.insert(it.symbol, it.prev_close);
last_holdings_ = holdings;
+ for (auto& it : last_holdings_) {
+ const auto pc = prev_close_by_sym.constFind(it.symbol);
+ if (pc != prev_close_by_sym.constEnd())
+ it.prev_close = pc.value();
+ }
if (holdings_import_btn_)
holdings_import_btn_->setEnabled(!holdings.isEmpty());
if (holdings_square_off_btn_)
@@ -1163,6 +1194,7 @@ void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& hold
double total_invested = 0.0;
double total_current = 0.0;
double total_pnl = 0.0;
+ double total_day_pnl = 0.0;
const QColor pos_color(fincept::ui::colors::POSITIVE());
const QColor neg_color(fincept::ui::colors::NEGATIVE());
@@ -1172,8 +1204,8 @@ void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& hold
it->setData(Qt::EditRole, v);
};
- for (int i = 0; i < holdings.size(); ++i) {
- const auto& h = holdings[i];
+ for (int i = 0; i < last_holdings_.size(); ++i) {
+ const auto& h = last_holdings_[i]; // carries prev_close across refreshes
ensure_item(holdings_table_, i, 0)->setText(h.symbol);
set_num(ensure_item(holdings_table_, i, 1), h.quantity, 0);
set_num(ensure_item(holdings_table_, i, 2), h.avg_price, 2);
@@ -1191,6 +1223,16 @@ void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& hold
pct_item->setData(Qt::EditRole, h.pnl_pct);
pct_item->setForeground(h.pnl_pct >= 0 ? pos_color : neg_color);
+ // Today's P&L = qty * (LTP - prev close). prev_close starts 0 (shown as 0)
+ // and is filled from the live quote feed in update_holding_quote — generic
+ // across brokers, no per-broker holdings parser needed.
+ const double day_pnl = h.prev_close > 0.0 ? h.quantity * (h.ltp - h.prev_close) : 0.0;
+ auto* day_item = ensure_item(holdings_table_, i, 8);
+ day_item->setData(Qt::DisplayRole, QString::number(day_pnl, 'f', 2));
+ day_item->setData(Qt::EditRole, day_pnl);
+ day_item->setForeground(day_pnl >= 0 ? pos_color : neg_color);
+ total_day_pnl += day_pnl;
+
// Per-row SELL → square off just this holding (market, CNC). Routed through
// the screen's close_position path (same as SQUARE OFF ALL) so it reliably
// reduces the holding instead of opening a counter-position.
@@ -1215,7 +1257,7 @@ void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& hold
});
action_lay->addWidget(sell_btn);
action_lay->addStretch();
- holdings_table_->setCellWidget(i, 8, action_cell);
+ holdings_table_->setCellWidget(i, 9, action_cell);
total_invested += h.invested_value;
total_current += h.current_value;
@@ -1238,6 +1280,14 @@ void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& hold
QString("color:%1;font-size:13px;font-weight:700;")
.arg(total_pnl >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE()));
}
+ if (holdings_day_pnl_label_) {
+ holdings_day_pnl_label_->setText(QString("%1%2")
+ .arg(total_day_pnl >= 0 ? "+" : "")
+ .arg(QString::number(total_day_pnl, 'f', 2)));
+ holdings_day_pnl_label_->setStyleSheet(
+ QString("color:%1;font-size:13px;font-weight:700;")
+ .arg(total_day_pnl >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE()));
+ }
if (holdings_pnl_pct_label_) {
holdings_pnl_pct_label_->setText(QString("%1%2%")
.arg(total_pct >= 0 ? "+" : "")
diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
index f490b5dc2..a166e4c34 100644
--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
@@ -116,7 +116,7 @@ class EquityBottomPanel : public QWidget {
// Live-quote patch for the Holdings table (CNC delivery): updates LTP / current
// value / P&L for the symbol's row and the summary strip, in place — same per
// tick refresh as the Positions table so Holdings tracks in real time.
- void update_holding_quote(const QString& symbol, double ltp);
+ void update_holding_quote(const QString& symbol, double ltp, double prev_close);
// Blank the shared positions/holdings/orders tables (and their row-aligned
// caches). Called on every account or paper↔live transition so one account's
@@ -170,6 +170,7 @@ class EquityBottomPanel : public QWidget {
QLabel* holdings_current_label_ = nullptr;
QLabel* holdings_pnl_label_ = nullptr;
QLabel* holdings_pnl_pct_label_ = nullptr;
+ QLabel* holdings_day_pnl_label_ = nullptr; // "Today's P&L" total
QLabel* holdings_count_label_ = nullptr;
// Holdings summary-strip caption labels (cached for retranslateUi)
QLabel* holdings_count_caption_ = nullptr;
@@ -177,6 +178,7 @@ class EquityBottomPanel : public QWidget {
QLabel* holdings_current_caption_ = nullptr;
QLabel* holdings_pnl_caption_ = nullptr;
QLabel* holdings_pnl_pct_caption_ = nullptr;
+ QLabel* holdings_day_pnl_caption_ = nullptr;
class QPushButton* holdings_import_btn_ = nullptr;
class QPushButton* holdings_replicate_btn_ = nullptr;
class QPushButton* holdings_square_off_btn_ = nullptr;
diff --git a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
index 7e4f937e1..c030f3860 100644
--- a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
@@ -2,20 +2,26 @@
#include "screens/equity_trading/EquityOrderEntry.h"
#include "core/logging/Logger.h"
+#include "screens/equity_trading/BasketOrdersDialog.h"
#include "screens/equity_trading/EquityTypes.h"
+#include "trading/AccountManager.h"
#include "trading/BrokerRegistry.h"
#include "trading/OptionsStrategyBuilder.h"
#include "ui/theme/Theme.h"
+#include <QCheckBox>
#include <QFrame>
#include <QGridLayout>
#include <QHBoxLayout>
+#include <QMenu>
#include <QMetaObject>
#include <QPointer>
#include <QScrollArea>
#include <QStyle>
#include <QTimer>
+#include <QToolButton>
#include <QVBoxLayout>
+#include <QWidgetAction>
#include <QtConcurrent/QtConcurrent>
#include <cmath>
@@ -373,6 +379,42 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
form->addWidget(summary);
+ // Multi-broker selector: BUY/SELL fires the same order to every checked
+ // account (empty selection = normal focused-account flow). QWidgetAction-
+ // wrapped checkboxes keep the menu open across toggles.
+ brokers_btn_ = new QToolButton;
+ brokers_btn_->setObjectName("eqBrokersBtn");
+ brokers_btn_->setPopupMode(QToolButton::InstantPopup);
+ brokers_btn_->setToolButtonStyle(Qt::ToolButtonTextOnly);
+ brokers_btn_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
+ brokers_btn_->setFixedHeight(24);
+ brokers_btn_->setCursor(Qt::PointingHandCursor);
+ brokers_menu_ = new QMenu(brokers_btn_);
+ brokers_btn_->setMenu(brokers_menu_);
+ connect(brokers_menu_, &QMenu::aboutToShow, this, &EquityOrderEntry::rebuild_brokers_menu);
+ update_brokers_btn();
+
+ // BASKETS — saved multi-leg order groups, executable on any account(s).
+ auto* baskets_btn = new QToolButton;
+ baskets_btn->setObjectName("eqBasketsBtn");
+ baskets_btn->setText(tr("BASKETS"));
+ baskets_btn->setFixedHeight(24);
+ baskets_btn->setCursor(Qt::PointingHandCursor);
+ baskets_btn->setStyleSheet(
+ QString("QToolButton{background:%1;border:1px solid %2;color:%3;font-size:10px;font-weight:700;"
+ "padding:2px 10px;}QToolButton:hover{border-color:%4;color:%4;}")
+ .arg(colors::BG_RAISED(), colors::BORDER_MED(), colors::TEXT_TERTIARY(), colors::AMBER()));
+ connect(baskets_btn, &QToolButton::clicked, this, [this]() {
+ BasketOrdersDialog dlg(this);
+ dlg.exec();
+ });
+
+ auto* brokers_row = new QHBoxLayout;
+ brokers_row->setSpacing(4);
+ brokers_row->addWidget(brokers_btn_, 1);
+ brokers_row->addWidget(baskets_btn);
+ form->addLayout(brokers_row);
+
// Submit row: main submit + broadcast
auto* submit_row = new QHBoxLayout;
submit_row->setSpacing(4);
@@ -575,9 +617,71 @@ void EquityOrderEntry::on_submit() {
order.take_profit = tp_edit_ ? tp_edit_->text().toDouble() : 0.0;
order.product_type = selected_product_type();
+ if (!broadcast_ids_.isEmpty()) {
+ // Multi-broker route: the same order to every checked account; the
+ // screen confirms, gates per-account (Semi-Auto), and broadcasts.
+ emit multi_broker_submit(order, QStringList(broadcast_ids_.begin(), broadcast_ids_.end()));
+ return;
+ }
+
emit order_submitted(order);
}
+// ── Inline multi-broker selector ─────────────────────────────────────────────
+
+void EquityOrderEntry::rebuild_brokers_menu() {
+ brokers_menu_->clear();
+
+ const auto accounts = trading::AccountManager::instance().active_accounts();
+ QSet<QString> alive;
+ for (const auto& account : accounts) {
+ alive.insert(account.account_id);
+ auto* broker = trading::BrokerRegistry::instance().get(account.broker_id);
+ const QString broker_name = broker ? broker->profile().display_name : account.broker_id;
+ const QString mode_tag = account.trading_mode == "live" ? tr("[LIVE]") : tr("[PAPER]");
+ const QString text = QString("%1 [%2] %3").arg(account.display_name, broker_name, mode_tag);
+
+ auto* cb = new QCheckBox(text, brokers_menu_);
+ cb->setChecked(broadcast_ids_.contains(account.account_id));
+ cb->setStyleSheet("QCheckBox{padding:4px 10px;font-size:11px;}");
+ const QString id = account.account_id;
+ connect(cb, &QCheckBox::toggled, this, [this, id](bool on) {
+ if (on)
+ broadcast_ids_.insert(id);
+ else
+ broadcast_ids_.remove(id);
+ update_brokers_btn();
+ });
+ auto* wa = new QWidgetAction(brokers_menu_); // checkbox click keeps the menu open
+ wa->setDefaultWidget(cb);
+ brokers_menu_->addAction(wa);
+ }
+
+ if (accounts.isEmpty()) {
+ auto* none = brokers_menu_->addAction(tr("No active accounts"));
+ none->setEnabled(false);
+ }
+
+ // Drop selections for accounts that were removed/deactivated since checked.
+ for (auto it = broadcast_ids_.begin(); it != broadcast_ids_.end();)
+ it = alive.contains(*it) ? std::next(it) : broadcast_ids_.erase(it);
+ update_brokers_btn();
+}
+
+void EquityOrderEntry::update_brokers_btn() {
+ const int n = int(broadcast_ids_.size());
+ brokers_btn_->setText(n == 0 ? tr("BROKERS: FOCUSED ▾") : tr("BROKERS: %1 SELECTED ▾").arg(n));
+ brokers_btn_->setToolTip(n == 0
+ ? tr("Orders go to the focused account. Click to pick multiple brokers.")
+ : tr("BUY/SELL will fire this order on %1 account(s)").arg(n));
+ // Amber accent when armed so a multi-broker submit is never a surprise.
+ brokers_btn_->setStyleSheet(
+ QString("QToolButton{background:%1;border:1px solid %2;color:%3;font-size:10px;font-weight:700;"
+ "padding:2px 8px;}QToolButton::menu-indicator{image:none;}")
+ .arg(colors::BG_RAISED(), n == 0 ? colors::BORDER_MED() : colors::AMBER(),
+ n == 0 ? colors::TEXT_TERTIARY() : colors::AMBER()));
+}
+
void EquityOrderEntry::show_order_status(const QString& msg, bool success) {
status_label_->setText(msg);
status_label_->setStyleSheet(QString("color: %1;").arg(success ? colors::POSITIVE() : colors::NEGATIVE()));
diff --git a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
index 9cb676c7d..2909b7211 100644
--- a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
+++ b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
@@ -10,11 +10,15 @@
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
+#include <QSet>
#include <QTimer>
#include <QWidget>
#include <atomic>
+class QMenu;
+class QToolButton;
+
namespace fincept::screens::equity {
class EquityOrderEntry : public QWidget {
@@ -36,6 +40,9 @@ class EquityOrderEntry : public QWidget {
signals:
void order_submitted(const trading::UnifiedOrder& order);
void broadcast_requested(const trading::UnifiedOrder& order);
+ /// Emitted instead of order_submitted when the inline BROKERS selector has
+ /// ≥1 account checked — the same order goes to every selected account.
+ void multi_broker_submit(const trading::UnifiedOrder& order, const QStringList& account_ids);
void strategy_order_submitted(const trading::BasketOrderRequest& basket);
protected:
@@ -56,6 +63,10 @@ class EquityOrderEntry : public QWidget {
trading::OrderType selected_order_type() const;
trading::ProductType selected_product_type() const;
+ // Inline multi-broker selector (QWidgetAction checkboxes keep the menu open).
+ void rebuild_brokers_menu();
+ void update_brokers_btn();
+
// Options strategy helpers
bool build_strategy(trading::OptionsStrategy& out) const; // returns false when strategy == None or inputs invalid
void refresh_strategy_preview();
@@ -85,6 +96,9 @@ class EquityOrderEntry : public QWidget {
QLineEdit* tp_edit_ = nullptr;
QPushButton* submit_btn_ = nullptr;
QPushButton* broadcast_btn_ = nullptr;
+ QToolButton* brokers_btn_ = nullptr; // inline multi-broker selector
+ QMenu* brokers_menu_ = nullptr; // checkable account list (stays open)
+ QSet<QString> broadcast_ids_; // checked account_ids; empty = focused only
QWidget* advanced_section_ = nullptr;
QPushButton* advanced_toggle_ = nullptr;
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index 346d59490..437047563 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -26,6 +26,7 @@
#include "screens/equity_trading/EquityTickerBar.h"
#include "screens/equity_trading/EquityWatchlist.h"
#include "screens/common/feeds/FeedPanel.h"
+#include "screens/portfolio_monitor/PortfolioMonitorScreen.h"
#include "services/feeds/FeedMonitor.h"
#include "screens/equity_trading/PortfolioReplicationDialog.h"
#include "services/portfolio/PortfolioService.h"
@@ -139,12 +140,24 @@ void EquityTradingScreen::showEvent(QShowEvent* event) {
const int w = s.value("feeds_width").toInt();
if (w > 50 && main_splitter_) {
auto sizes = main_splitter_->sizes();
- if (sizes.size() == 4) {
+ if (sizes.size() >= 4) {
sizes[3] = w;
main_splitter_->setSizes(sizes);
}
}
}
+ // Restore the unified all-accounts column (visibility + width).
+ if (s.value("unified_visible").toBool()) {
+ unified_btn_->setChecked(true); // toggled() shows the panel
+ const int w = s.value("unified_width").toInt();
+ if (w > 50 && main_splitter_) {
+ auto sizes = main_splitter_->sizes();
+ if (sizes.size() >= 5) {
+ sizes[4] = w;
+ main_splitter_->setSizes(sizes);
+ }
+ }
+ }
}
}
@@ -202,6 +215,8 @@ void EquityTradingScreen::hideEvent(QHideEvent* event) {
{"selected_exchange", selected_exchange_},
{"feeds_visible", feed_panel_ != nullptr && feed_panel_->isVisible()},
{"feeds_width", main_splitter_ != nullptr ? main_splitter_->sizes().value(3) : 0},
+ {"unified_visible", monitor_panel_ != nullptr && monitor_panel_->isVisible()},
+ {"unified_width", main_splitter_ != nullptr ? main_splitter_->sizes().value(4) : 0},
});
LOG_INFO(TAG, "Screen hidden — data streams paused, hub unsubscribed");
}
@@ -337,6 +352,16 @@ void EquityTradingScreen::setup_ui() {
feeds_btn_->setCursor(Qt::PointingHandCursor);
cmd_layout->addWidget(feeds_btn_);
+ // UNIFIED — toggles the all-accounts portfolio monitor column (same
+ // interaction as FEEDS: checkable button ↔ collapsible splitter column).
+ unified_btn_ = new QPushButton(tr("UNIFIED"));
+ unified_btn_->setObjectName("eqApiBtn");
+ unified_btn_->setFixedHeight(22);
+ unified_btn_->setCheckable(true);
+ unified_btn_->setCursor(Qt::PointingHandCursor);
+ unified_btn_->setToolTip(tr("All-accounts positions & holdings (every connected broker)"));
+ cmd_layout->addWidget(unified_btn_);
+
main_layout->addWidget(cmd_bar);
// ── MAIN 3-PANEL SPLITTER ─────────────────────────────────────────────────
@@ -397,11 +422,19 @@ void EquityTradingScreen::setup_ui() {
feed_panel_->setVisible(false);
main_splitter->addWidget(feed_panel_);
- main_splitter->setSizes({265, 555, 290, 0});
+ // FAR RIGHT 2: collapsible all-accounts portfolio monitor (hidden by default;
+ // toggled via the UNIFIED command-bar button). Aggregates positions/holdings
+ // across every connected INR broker — see screens/portfolio_monitor.
+ monitor_panel_ = new PortfolioMonitorScreen;
+ monitor_panel_->setVisible(false);
+ main_splitter->addWidget(monitor_panel_);
+
+ main_splitter->setSizes({265, 555, 290, 0, 0});
main_splitter->setStretchFactor(0, 0);
main_splitter->setStretchFactor(1, 1);
main_splitter->setStretchFactor(2, 0);
main_splitter->setStretchFactor(3, 0);
+ main_splitter->setStretchFactor(4, 0);
main_layout->addWidget(main_splitter, 1);
@@ -411,12 +444,37 @@ void EquityTradingScreen::setup_ui() {
feed_panel_->setVisible(on);
if (on) {
auto sizes = main_splitter_->sizes();
- if (sizes.size() == 4 && sizes[3] < 50) {
+ if (sizes.size() >= 4 && sizes[3] < 50) {
sizes[3] = 300;
main_splitter_->setSizes(sizes);
}
}
});
+ connect(unified_btn_, &QPushButton::toggled, this, [this](bool on) {
+ if (monitor_float_) {
+ // Detached: ON raises the floating window; OFF closes it (the
+ // close re-docks the panel hidden — see redock_monitor()).
+ if (on) {
+ monitor_float_->raise();
+ monitor_float_->activateWindow();
+ } else {
+ monitor_float_->close();
+ }
+ return;
+ }
+ monitor_panel_->setVisible(on); // showEvent → service activate + refresh
+ if (on) {
+ auto sizes = main_splitter_->sizes();
+ if (sizes.size() >= 5 && sizes[4] < 50) {
+ sizes[4] = 560; // wide enough for the 8-column tree
+ main_splitter_->setSizes(sizes);
+ }
+ }
+ });
+ connect(monitor_panel_, &PortfolioMonitorScreen::float_requested, this,
+ &EquityTradingScreen::float_monitor);
+ connect(monitor_panel_, &PortfolioMonitorScreen::dock_requested, this,
+ [this]() { if (monitor_float_) monitor_float_->close(); }); // close → redock
connect(accounts_btn_, &QPushButton::clicked, this, &EquityTradingScreen::on_accounts_clicked);
connect(watchlist_, &EquityWatchlist::symbol_selected, this, &EquityTradingScreen::on_symbol_selected);
connect(watchlist_, &EquityWatchlist::symbol_added, this, &EquityTradingScreen::on_watchlist_symbol_added);
@@ -426,6 +484,8 @@ void EquityTradingScreen::setup_ui() {
connect(watchlist_, &EquityWatchlist::watchlist_rename_requested, this, &EquityTradingScreen::on_watchlist_rename);
connect(watchlist_, &EquityWatchlist::watchlist_delete_requested, this, &EquityTradingScreen::on_watchlist_delete);
connect(order_entry_, &EquityOrderEntry::order_submitted, this, &EquityTradingScreen::on_order_submitted);
+ connect(order_entry_, &EquityOrderEntry::multi_broker_submit, this,
+ &EquityTradingScreen::on_multi_broker_submit);
connect(order_entry_, &EquityOrderEntry::strategy_order_submitted, this, &EquityTradingScreen::on_strategy_submitted);
connect(order_entry_, &EquityOrderEntry::broadcast_requested, this, [this](const trading::UnifiedOrder& order) {
auto* dlg = new BroadcastOrderDialog(order, this);
@@ -777,18 +837,35 @@ void EquityTradingScreen::update_connection_status() {
const auto accounts = AccountManager::instance().active_accounts();
int connected = 0;
int expired = 0;
+ int errored = 0;
+ QString first_error;
for (const auto& a : accounts) {
if (a.state == ConnectionState::Connected)
++connected;
else if (a.state == ConnectionState::TokenExpired)
++expired;
+ else if (a.state == ConnectionState::Error) {
+ ++errored;
+ if (first_error.isEmpty())
+ first_error = a.error_message;
+ }
}
+ // Default: no hover detail. Only the Error branch attaches the broker's reason
+ // (e.g. "no active Kite Connect subscription") as a tooltip.
+ conn_label_->setToolTip(QString());
if (accounts.isEmpty()) {
conn_label_->setText(tr("○ NO ACCOUNTS"));
conn_label_->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: 700;").arg(ui::colors::TEXT_TERTIARY()));
} else if (expired > 0 && connected == 0) {
conn_label_->setText(tr("\xe2\x9a\xa0 TOKEN EXPIRED \xe2\x80\x94 click ACCOUNTS"));
conn_label_->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: 700;").arg(ui::colors::NEGATIVE()));
+ } else if (errored > 0 && connected == 0) {
+ // Authenticated but the broker refused live market data (e.g. Kite 403 — no
+ // active Kite Connect subscription). Account data may still load; only the
+ // live feed is gated. Full reason on hover.
+ conn_label_->setText(tr("\xe2\x9a\xa0 NO MARKET DATA \xe2\x80\x94 hover for details"));
+ conn_label_->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: 700;").arg(ui::colors::NEGATIVE()));
+ conn_label_->setToolTip(first_error);
} else if (connected == accounts.size()) {
conn_label_->setText(tr("● %1/%2 CONNECTED").arg(connected).arg(accounts.size()));
conn_label_->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: 700;").arg(ui::colors::POSITIVE()));
@@ -856,4 +933,58 @@ void EquityTradingScreen::on_replicate_portfolio_requested() {
refresh_paper_panels();
}
+// ============================================================================
+// UNIFIED monitor detach / re-dock (feeds pop-out pattern)
+// ============================================================================
+
+void EquityTradingScreen::float_monitor() {
+ if (monitor_float_)
+ return; // already detached
+ // Top-level child window (Qt::Window flag, parented for auto-cleanup —
+ // same construction FloatingFeedWindow uses).
+ monitor_float_ = new QWidget(this, Qt::Window);
+ monitor_float_->setWindowTitle(tr("Unified Portfolio — All Accounts"));
+ monitor_float_->setObjectName("floatingMonitorWindow");
+ monitor_float_->setStyleSheet(
+ QString("#floatingMonitorWindow{background:%1;}").arg(fincept::ui::colors::BG_BASE()));
+ monitor_float_->resize(980, 620);
+ auto* lay = new QVBoxLayout(monitor_float_);
+ lay->setContentsMargins(0, 0, 0, 0);
+ lay->addWidget(monitor_panel_); // reparents out of the splitter
+ monitor_panel_->set_floating(true);
+ monitor_panel_->setVisible(true);
+ monitor_float_->installEventFilter(this); // Close → redock_monitor()
+ monitor_float_->show();
+}
+
+void EquityTradingScreen::redock_monitor() {
+ if (!monitor_float_)
+ return;
+ auto* win = monitor_float_;
+ monitor_float_ = nullptr; // clear first — eventFilter fires during teardown
+ // Back into splitter slot 4 (after the feed column).
+ main_splitter_->insertWidget(4, monitor_panel_);
+ main_splitter_->setStretchFactor(4, 0);
+ monitor_panel_->set_floating(false);
+ const bool show = unified_btn_ != nullptr && unified_btn_->isChecked();
+ monitor_panel_->setVisible(show);
+ if (show) {
+ auto sizes = main_splitter_->sizes();
+ if (sizes.size() >= 5 && sizes[4] < 50) {
+ sizes[4] = 560;
+ main_splitter_->setSizes(sizes);
+ }
+ }
+ win->removeEventFilter(this);
+ win->deleteLater();
+}
+
+bool EquityTradingScreen::eventFilter(QObject* watched, QEvent* event) {
+ if (watched == monitor_float_ && event->type() == QEvent::Close) {
+ redock_monitor();
+ return false; // let the (now empty) window finish closing
+ }
+ return QWidget::eventFilter(watched, event);
+}
+
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
index 98e01253c..a50d0cf2a 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
@@ -31,6 +31,10 @@ namespace fincept::feeds {
class FeedPanel;
}
+namespace fincept::screens {
+class PortfolioMonitorScreen;
+}
+
namespace fincept::screens::equity {
class EquityTickerBar;
class EquityWatchlist;
@@ -90,6 +94,9 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void on_accounts_clicked(); // opens AccountManagementDialog
void handle_token_expired(const QString& account_id);
void on_order_submitted(const trading::UnifiedOrder& order);
+ // Inline multi-broker submit: confirm, gate per account (Semi-Auto), then
+ // broadcast the same order to every selected account on a worker thread.
+ void on_multi_broker_submit(const trading::UnifiedOrder& order, const QStringList& account_ids);
void on_cancel_order(const QString& order_id);
void on_cancel_all_orders(); // CANCEL ALL ORDERS button
void on_close_all_positions(); // SQUARE OFF ALL button (positions)
@@ -203,10 +210,12 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
// (when resubscribe=true) re-points the live stream + hub at the new symbol set.
void load_watchlists();
void apply_active_watchlist(bool resubscribe);
- // Effective live-subscription set = active watchlist ∪ open-position symbols,
- // so symbols you hold (even if not in the list) get live WebSocket prices.
+ // Effective live-subscription set = active watchlist ∪ open-position symbols
+ // ∪ holding symbols, so symbols you hold (even if not in the list) get live
+ // WebSocket prices instead of only the 5-minute REST portfolio snapshot.
QStringList effective_symbols() const;
void update_position_symbols(const QStringList& syms); // re-subscribe when it changes
+ void update_holding_symbols(const QStringList& syms); // re-subscribe when it changes
// Push the open position for the displayed symbol onto the chart's overlay
// card + entry line (from the live cache or the paper engine), or clear it
// when the symbol is flat.
@@ -230,6 +239,7 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
QHash<QString, QString> symbol_suggestion_map_;
QPushButton* mode_btn_ = nullptr;
QPushButton* feeds_btn_ = nullptr; // toggles the far-right feed monitor column
+ QPushButton* unified_btn_ = nullptr; // toggles the all-accounts portfolio monitor column
QPushButton* accounts_btn_ = nullptr; // opens AccountManagementDialog
QLabel* exchange_label_ = nullptr;
QLabel* clock_label_ = nullptr;
@@ -243,6 +253,18 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
equity::EquityOrderBook* orderbook_ = nullptr;
equity::EquityBottomPanel* bottom_panel_ = nullptr;
fincept::feeds::FeedPanel* feed_panel_ = nullptr; // collapsible far-right feed column
+ PortfolioMonitorScreen* monitor_panel_ = nullptr; // collapsible all-accounts portfolio column
+ QWidget* monitor_float_ = nullptr; // top-level window while the monitor is detached
+
+ void float_monitor(); // reparent monitor_panel_ into its own window
+ void redock_monitor(); // bring it back into the splitter (slot 4)
+
+ protected:
+ // Watches monitor_float_ for Close to re-dock the monitor (feeds pattern,
+ // without a dedicated moc'd window class).
+ bool eventFilter(QObject* watched, QEvent* event) override;
+
+ private:
QSplitter* main_splitter_ = nullptr; // kept to toggle the feed column width
// ── Timers (only UI-local timers remain; data timers are in AccountDataStream) ──
@@ -283,6 +305,7 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
// moves it to view a past IST session). Open positions/holdings stay current.
QDate orders_view_day_ = QDate::currentDate();
QStringList position_symbols_; // symbols with open positions (transient, for live pricing)
+ QStringList holding_symbols_; // symbols in holdings (transient, for live pricing)
QVector<trading::BrokerPosition> live_positions_; // cached live positions for focused account
double current_price_ = 0.0; // last known LTP for selected symbol
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
index 9c7bdb5e2..627669e2b 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
@@ -519,6 +519,93 @@ void EquityTradingScreen::on_order_submitted(const UnifiedOrder& order) {
}
}
+// Inline multi-broker submit (BROKERS selector in the order panel). One explicit
+// confirmation listing every target account + its mode, then the same per-account
+// Semi-Auto gating and background broadcast the ALL dialog uses.
+void EquityTradingScreen::on_multi_broker_submit(const trading::UnifiedOrder& order,
+ const QStringList& account_ids) {
+ if (account_ids.isEmpty())
+ return;
+
+ QStringList lines;
+ for (const QString& id : account_ids) {
+ const auto account = AccountManager::instance().get_account(id);
+ if (account.account_id.isEmpty())
+ continue;
+ const QString mode_tag = account.trading_mode == "live" ? tr("LIVE") : tr("PAPER");
+ lines << QString("• %1 [%2]").arg(account.display_name, mode_tag);
+ }
+ if (lines.isEmpty()) {
+ order_entry_->show_order_status(tr("Selected accounts no longer exist"), false);
+ return;
+ }
+
+ const QString side = order.side == trading::OrderSide::Buy ? tr("BUY") : tr("SELL");
+ const QString px = order.order_type == trading::OrderType::Market
+ ? tr("MARKET")
+ : QString::number(order.price, 'f', 2);
+ const auto ret = QMessageBox::question(
+ this, tr("Multi-Broker Order"),
+ tr("%1 %2 × %3 @ %4 on %5 account(s):\n\n%6")
+ .arg(side, QString::number(order.quantity), order.symbol, px)
+ .arg(lines.size())
+ .arg(lines.join("\n")),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (ret != QMessageBox::Yes)
+ return;
+
+ // Per-account Semi-Auto gate: queue those accounts for approval, broadcast
+ // the rest immediately (mirrors BroadcastOrderDialog::on_place_order).
+ QStringList immediate;
+ int queued = 0;
+ for (const QString& acct : account_ids) {
+ if (ActionCenter::instance().should_queue(acct, "placeorder")) {
+ const QString pid = ActionCenter::instance().queue_order(
+ acct, "placeorder", ActionCenter::serialize_unified_order(order));
+ if (!pid.isEmpty())
+ ++queued;
+ } else {
+ immediate.append(acct);
+ }
+ }
+ if (immediate.isEmpty()) {
+ order_entry_->show_order_status(tr("%1 order(s) queued for approval").arg(queued), true);
+ return;
+ }
+ order_entry_->show_order_status(tr("Placing on %1 account(s)…").arg(immediate.size()), true);
+
+ QPointer<EquityTradingScreen> self = this;
+ auto order_copy = order;
+ (void)QtConcurrent::run([self, immediate, order_copy, queued]() {
+ const auto results = trading::UnifiedTrading::instance().broadcast_order(immediate, order_copy);
+ QMetaObject::invokeMethod(
+ self,
+ [self, results, queued]() {
+ if (!self)
+ return;
+ int ok_n = 0;
+ QStringList errors;
+ for (const auto& r : results) {
+ if (r.response.success)
+ ++ok_n;
+ else
+ errors << QString("%1: %2").arg(r.display_name, r.response.message);
+ }
+ QString msg = tr("✓ %1 placed").arg(ok_n);
+ if (queued > 0)
+ msg += tr(", %1 queued").arg(queued);
+ if (!errors.isEmpty())
+ msg += tr(" — ✗ %1").arg(errors.join("; "));
+ self->order_entry_->show_order_status(msg, errors.isEmpty());
+ // Repaint each target's blotter right away (paper panels too).
+ for (const auto& r : results)
+ trading::DataStreamManager::instance().refresh_portfolio(r.account_id);
+ self->refresh_paper_panels();
+ },
+ Qt::QueuedConnection);
+ });
+}
+
void EquityTradingScreen::on_chart_buy_requested(double price) {
open_chart_order_ticket(true, price);
}
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
index 34eb13111..5418a71d6 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
@@ -100,7 +100,14 @@ void EquityTradingScreen::hub_subscribe_streaming() {
[this](const QVariant& v) {
if (!v.canConvert<QVector<BrokerHolding>>())
return;
- bottom_panel_->set_holdings(v.value<QVector<BrokerHolding>>());
+ const auto holdings = v.value<QVector<BrokerHolding>>();
+ bottom_panel_->set_holdings(holdings);
+ // Give held symbols live WS prices so their LTP updates in
+ // real time instead of only on the 5-minute REST poll.
+ QStringList hs;
+ for (const auto& h : holdings)
+ hs << h.symbol;
+ update_holding_symbols(hs);
});
// ── Orders ──
@@ -160,6 +167,8 @@ void EquityTradingScreen::hub_subscribe_quotes() {
symbols.insert(s);
for (const auto& s : position_symbols_) // held symbols get live quotes too
symbols.insert(s);
+ for (const auto& s : holding_symbols_) // holdings stream live too (not just 5-min REST)
+ symbols.insert(s);
LOG_INFO("posdbg", QString("subscribing %1 quote topics for acct=%2: [%3]")
.arg(symbols.size()).arg(aid, QStringList(symbols.begin(), symbols.end()).join(',')));
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
index 2338bf144..47fb9f0c9 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
@@ -251,6 +251,11 @@ QStringList EquityTradingScreen::effective_symbols() const {
for (const auto& s : position_symbols_)
if (!s.isEmpty() && !eff.contains(s))
eff << s;
+ // Holdings get live WS prices too — otherwise their LTP only refreshes on the
+ // 5-minute REST portfolio poll and visibly lags the broker app.
+ for (const auto& s : holding_symbols_)
+ if (!s.isEmpty() && !eff.contains(s))
+ eff << s;
return eff;
}
@@ -269,4 +274,19 @@ void EquityTradingScreen::update_position_symbols(const QStringList& syms) {
QMetaObject::invokeMethod(this, [this]() { apply_active_watchlist(true); }, Qt::QueuedConnection);
}
+void EquityTradingScreen::update_holding_symbols(const QStringList& syms) {
+ QStringList deduped;
+ for (const auto& s : syms)
+ if (!s.isEmpty() && !deduped.contains(s))
+ deduped << s;
+ if (deduped == holding_symbols_)
+ return; // unchanged — avoid resubscribe churn
+ holding_symbols_ = deduped;
+ LOG_INFO("posdbg", QString("update_holding_symbols: [%1]").arg(deduped.join(',')));
+ // Same path as positions: re-subscribe the active∪positions∪holdings union so
+ // holding LTP streams live instead of waiting on the 5-minute REST poll.
+ // Deferred because this fires from inside the holdings hub callback.
+ QMetaObject::invokeMethod(this, [this]() { apply_active_watchlist(true); }, Qt::QueuedConnection);
+}
+
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio_monitor/PortfolioMonitorScreen.cpp b/fincept-qt/src/screens/portfolio_monitor/PortfolioMonitorScreen.cpp
new file mode 100644
index 000000000..a25dea139
--- /dev/null
+++ b/fincept-qt/src/screens/portfolio_monitor/PortfolioMonitorScreen.cpp
@@ -0,0 +1,548 @@
+// PortfolioMonitorScreen.cpp — unified all-accounts positions & holdings.
+#include "screens/portfolio_monitor/PortfolioMonitorScreen.h"
+
+#include "storage/repositories/SettingsRepository.h"
+#include "trading/TradingTypes.h"
+#include "trading/UnifiedPortfolioService.h"
+#include "ui/theme/Theme.h"
+
+#include <QComboBox>
+#include <QDialog>
+#include <QDialogButtonBox>
+#include <QDoubleSpinBox>
+#include <QFormLayout>
+#include <QHBoxLayout>
+#include <QHeaderView>
+#include <QLabel>
+#include <QLineEdit>
+#include <QMessageBox>
+#include <QPushButton>
+#include <QScrollArea>
+#include <QShowEvent>
+#include <QSpinBox>
+#include <QTabWidget>
+#include <QTimer>
+#include <QTreeWidget>
+#include <QVBoxLayout>
+
+#include <algorithm>
+#include <cmath>
+
+namespace fincept::screens {
+
+using trading::AggChild;
+using trading::AggRow;
+using trading::UnifiedPortfolioService;
+
+namespace {
+
+// Columns shared by both trees. Holdings reuses DayPnl for "Today's P&L" and
+// shows invested/current in the parent tooltip.
+enum Col { ColSymbol = 0, ColProduct, ColQty, ColAvg, ColLtp, ColPnl, ColPnlPct, ColAction, ColCount };
+
+const QString kRupee = QString::fromUtf8("₹");
+
+QString fmt_money(double v, bool signed_pfx = false) {
+ const QLocale loc(QLocale::English, QLocale::India); // lakh grouping for ₹
+ const QString mag = loc.toString(std::fabs(v), 'f', 2);
+ const QString prefix = v < 0 ? QStringLiteral("-") : (signed_pfx ? QStringLiteral("+") : QString());
+ return prefix + kRupee + mag;
+}
+
+QString fmt_qty(double v) {
+ return qFuzzyCompare(v, std::round(v)) ? QString::number(qint64(std::llround(v)))
+ : QString::number(v, 'f', 2);
+}
+
+void set_pnl_cell(QTreeWidgetItem* item, int col, double pnl, const QString& text) {
+ item->setText(col, text);
+ item->setForeground(col, pnl > 0 ? QColor(fincept::ui::colors::POSITIVE())
+ : pnl < 0 ? QColor(fincept::ui::colors::NEGATIVE())
+ : QColor("#808080"));
+}
+
+QString row_key(const QString& symbol, const QString& exchange) {
+ return symbol + QLatin1Char('|') + exchange;
+}
+
+} // namespace
+
+PortfolioMonitorScreen::PortfolioMonitorScreen(QWidget* parent) : QWidget(parent) {
+ setObjectName("portfolioMonitorScreen");
+ // Embedded as a splitter column — must be free to shrink. Children (scroll
+ // areas + interactive tree columns) all tolerate narrow widths, so the
+ // panel never forces the parent window wider than the screen.
+ setMinimumWidth(280);
+
+ auto* layout = new QVBoxLayout(this);
+ layout->setContentsMargins(8, 8, 8, 8);
+ layout->setSpacing(6);
+
+ layout->addWidget(build_summary_bar());
+
+ tabs_ = new QTabWidget;
+ tabs_->setDocumentMode(true);
+ positions_tree_ = make_tree(/*holdings=*/false);
+ holdings_tree_ = make_tree(/*holdings=*/true);
+ tabs_->addTab(positions_tree_, tr("POSITIONS"));
+ tabs_->addTab(holdings_tree_, tr("HOLDINGS"));
+ layout->addWidget(tabs_, 1);
+
+ auto& svc = UnifiedPortfolioService::instance();
+ connect(&svc, &UnifiedPortfolioService::positions_changed, this, &PortfolioMonitorScreen::rebuild_positions);
+ connect(&svc, &UnifiedPortfolioService::holdings_changed, this, &PortfolioMonitorScreen::rebuild_holdings);
+ connect(&svc, &UnifiedPortfolioService::position_patched, this, &PortfolioMonitorScreen::patch_position);
+ connect(&svc, &UnifiedPortfolioService::holding_patched, this, &PortfolioMonitorScreen::patch_holding);
+ connect(&svc, &UnifiedPortfolioService::summary_changed, this, &PortfolioMonitorScreen::update_summary);
+ connect(&svc, &UnifiedPortfolioService::accounts_changed, this, &PortfolioMonitorScreen::update_summary);
+ connect(&svc, &UnifiedPortfolioService::action_finished, this, &PortfolioMonitorScreen::on_action_finished);
+}
+
+void PortfolioMonitorScreen::showEvent(QShowEvent* event) {
+ QWidget::showEvent(event);
+ if (!activated_) {
+ // Apply the persisted mode BEFORE the first activate so the initial
+ // model is built from the right engine. setChecked only emits toggled
+ // on a state change, so style/route the paper default explicitly.
+ const auto saved = SettingsRepository::instance().get(QStringLiteral("portfolio_monitor.mode"),
+ QStringLiteral("paper"));
+ const bool live = saved.is_ok() && saved.value() == QLatin1String("live");
+ if (live)
+ mode_btn_->setChecked(true); // fires on_mode_toggled(true)
+ else
+ on_mode_toggled(false);
+ }
+ // activate() is idempotent: picks up newly-added accounts and forces a
+ // portfolio refresh, so reopening the panel always shows fresh data.
+ UnifiedPortfolioService::instance().activate();
+ if (!activated_) {
+ activated_ = true;
+ rebuild_positions();
+ rebuild_holdings();
+ update_summary();
+ }
+}
+
+// ── UI construction ──────────────────────────────────────────────────────────
+
+QWidget* PortfolioMonitorScreen::build_summary_bar() {
+ auto* bar = new QWidget;
+ bar->setObjectName("pmSummaryBar");
+ bar->setStyleSheet("#pmSummaryBar{background:#0a0a0a;border:1px solid #1a1a1a;}");
+ auto* h = new QHBoxLayout(bar);
+ h->setContentsMargins(10, 6, 10, 6);
+ h->setSpacing(14);
+
+ // ⧉ detach / ⤓ dock back (feeds pattern). The equity screen owns the
+ // float window and the reparenting; this button only signals intent.
+ float_btn_ = new QPushButton(QStringLiteral("⧉"));
+ float_btn_->setCursor(Qt::PointingHandCursor);
+ float_btn_->setFixedSize(24, 24);
+ float_btn_->setToolTip(tr("Detach into its own window"));
+ float_btn_->setStyleSheet("QPushButton{background:transparent;border:1px solid #2a2a2a;color:#808080;"
+ "font-size:13px;}QPushButton:hover{color:#e5e5e5;border-color:#d97706;}");
+ connect(float_btn_, &QPushButton::clicked, this, [this]() {
+ if (floating_)
+ emit dock_requested();
+ else
+ emit float_requested();
+ });
+ h->addWidget(float_btn_);
+
+ // PAPER ⇄ LIVE switch. The service keeps the two models fully separate;
+ // this just selects which one is displayed (and which engine actions hit).
+ // Default and persistence: settings key portfolio_monitor.mode.
+ mode_btn_ = new QPushButton(tr("PAPER"));
+ mode_btn_->setCheckable(true); // checked == LIVE
+ mode_btn_->setCursor(Qt::PointingHandCursor);
+ mode_btn_->setFixedHeight(24);
+ connect(mode_btn_, &QPushButton::toggled, this, &PortfolioMonitorScreen::on_mode_toggled);
+ h->addWidget(mode_btn_);
+
+ auto add_stat = [&](const QString& title) {
+ auto* box = new QVBoxLayout;
+ box->setSpacing(1);
+ auto* cap = new QLabel(title);
+ cap->setStyleSheet("color:#808080;font-size:10px;");
+ auto* val = new QLabel(QStringLiteral("—"));
+ val->setStyleSheet("color:#e5e5e5;font-size:13px;font-weight:600;");
+ box->addWidget(cap);
+ box->addWidget(val);
+ h->addLayout(box);
+ return val;
+ };
+
+ sum_positions_pnl_ = add_stat(tr("POSITIONS P&L"));
+ sum_day_pnl_ = add_stat(tr("DAY P&L"));
+ sum_holdings_pnl_ = add_stat(tr("HOLDINGS P&L"));
+ sum_invested_ = add_stat(tr("INVESTED"));
+ sum_current_ = add_stat(tr("CURRENT"));
+ sum_return_ = add_stat(tr("RETURN %"));
+ sum_accounts_ = add_stat(tr("ACCOUNTS"));
+
+ h->addStretch(1);
+
+ toast_ = new QLabel;
+ toast_->setStyleSheet("color:#808080;font-size:11px;");
+ h->addWidget(toast_);
+
+ auto* refresh = new QPushButton(tr("REFRESH"));
+ auto* new_order = new QPushButton(tr("+ NEW ORDER"));
+ auto* square_all = new QPushButton(tr("SQUARE OFF ALL"));
+ for (auto* b : {refresh, new_order}) {
+ b->setCursor(Qt::PointingHandCursor);
+ b->setStyleSheet("QPushButton{background:#111;border:1px solid #2a2a2a;color:#d97706;"
+ "padding:5px 12px;font-size:11px;font-weight:600;}"
+ "QPushButton:hover{border-color:#d97706;}");
+ }
+ square_all->setCursor(Qt::PointingHandCursor);
+ square_all->setStyleSheet("QPushButton{background:#1a0a0a;border:1px solid #5c1f1f;color:#ef4444;"
+ "padding:5px 12px;font-size:11px;font-weight:600;}"
+ "QPushButton:hover{border-color:#ef4444;}");
+ connect(refresh, &QPushButton::clicked, this, []() { UnifiedPortfolioService::instance().refresh_all(); });
+ connect(new_order, &QPushButton::clicked, this, &PortfolioMonitorScreen::on_new_order);
+ connect(square_all, &QPushButton::clicked, this, [this]() {
+ const auto ret = QMessageBox::question(
+ this, tr("Square Off All"),
+ tr("Square off ALL intraday positions across EVERY connected account?"),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (ret == QMessageBox::Yes)
+ UnifiedPortfolioService::instance().square_off_all_positions();
+ });
+ h->addWidget(refresh);
+ h->addWidget(new_order);
+ h->addWidget(square_all);
+
+ // The stat row is wider than a narrow splitter column — scroll horizontally
+ // instead of forcing a minimum width on the whole panel (which would push
+ // the main window past the screen edge).
+ auto* scroller = new QScrollArea;
+ scroller->setWidget(bar);
+ scroller->setWidgetResizable(true);
+ scroller->setFrameShape(QFrame::NoFrame);
+ scroller->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ scroller->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
+ scroller->setFixedHeight(bar->sizeHint().height() + 10); // room for the h-scrollbar
+ scroller->setMinimumWidth(0);
+ return scroller;
+}
+
+void PortfolioMonitorScreen::set_floating(bool floating) {
+ floating_ = floating;
+ float_btn_->setText(floating ? QStringLiteral("⤓") : QStringLiteral("⧉"));
+ float_btn_->setToolTip(floating ? tr("Dock back into the equity tab")
+ : tr("Detach into its own window"));
+}
+
+void PortfolioMonitorScreen::on_mode_toggled(bool live) {
+ mode_btn_->setText(live ? tr("LIVE") : tr("PAPER"));
+ mode_btn_->setStyleSheet(
+ live ? "QPushButton{background:#1a0a0a;border:1px solid #ef4444;color:#ef4444;"
+ "padding:4px 14px;font-size:11px;font-weight:700;}"
+ : "QPushButton{background:#111;border:1px solid #d97706;color:#d97706;"
+ "padding:4px 14px;font-size:11px;font-weight:700;}");
+ mode_btn_->setToolTip(live ? tr("Showing REAL broker positions — click for paper")
+ : tr("Showing paper portfolios — click for live"));
+ UnifiedPortfolioService::instance().set_mode(live ? UnifiedPortfolioService::Mode::Live
+ : UnifiedPortfolioService::Mode::Paper);
+ SettingsRepository::instance().set(QStringLiteral("portfolio_monitor.mode"),
+ live ? QStringLiteral("live") : QStringLiteral("paper"));
+ rebuild_positions();
+ rebuild_holdings();
+ update_summary();
+}
+
+QTreeWidget* PortfolioMonitorScreen::make_tree(bool holdings) {
+ auto* tree = new QTreeWidget;
+ tree->setColumnCount(ColCount);
+ tree->setHeaderLabels({tr("Symbol / Account"), holdings ? tr("Today's P&L") : tr("Product"), tr("Qty"),
+ tr("Avg Price"), tr("LTP"), tr("P&L"), tr("P&L %"), tr("Action")});
+ tree->setRootIsDecorated(true);
+ tree->setAlternatingRowColors(false);
+ tree->setUniformRowHeights(true);
+ tree->setSelectionMode(QAbstractItemView::NoSelection);
+ // Interactive (user-draggable) columns — Stretch mode forbids resizing, so
+ // names/numbers truncated with no way to widen them. Sensible defaults +
+ // a horizontal scrollbar when the column is narrower than the content.
+ tree->header()->setSectionResizeMode(QHeaderView::Interactive);
+ tree->header()->setStretchLastSection(false);
+ tree->setColumnWidth(ColSymbol, 190);
+ tree->setColumnWidth(ColProduct, holdings ? 100 : 90);
+ tree->setColumnWidth(ColQty, 64);
+ tree->setColumnWidth(ColAvg, 92);
+ tree->setColumnWidth(ColLtp, 92);
+ tree->setColumnWidth(ColPnl, 96);
+ tree->setColumnWidth(ColPnlPct, 70);
+ tree->setColumnWidth(ColAction, 76);
+ tree->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
+ tree->setMinimumWidth(0);
+ tree->setStyleSheet("QTreeWidget{background:#080808;border:1px solid #1a1a1a;font-size:12px;}"
+ "QTreeWidget::item{height:26px;}");
+ return tree;
+}
+
+void PortfolioMonitorScreen::fill_parent(QTreeWidgetItem* item, const AggRow& row, bool holdings) {
+ item->setText(ColSymbol, row.exchange.isEmpty() ? row.symbol
+ : QString("%1 · %2").arg(row.symbol, row.exchange));
+ if (holdings) {
+ set_pnl_cell(item, ColProduct, row.day_pnl, fmt_money(row.day_pnl, true));
+ item->setToolTip(ColSymbol, tr("Invested %1 Current %2")
+ .arg(fmt_money(row.invested), fmt_money(row.current)));
+ } else {
+ item->setText(ColProduct, QString::number(row.children.size()) + tr(" acct"));
+ }
+ item->setText(ColQty, fmt_qty(row.total_qty));
+ item->setText(ColAvg, row.w_avg_price > 0 ? fmt_money(row.w_avg_price) : QStringLiteral("—"));
+ item->setText(ColLtp, row.ltp > 0 ? fmt_money(row.ltp) : QStringLiteral("—"));
+ set_pnl_cell(item, ColPnl, row.pnl, fmt_money(row.pnl, true));
+ const double base = row.w_avg_price * std::fabs(row.total_qty);
+ const double pct = base > 0 ? row.pnl / base * 100.0 : 0.0;
+ set_pnl_cell(item, ColPnlPct, row.pnl, QString::number(pct, 'f', 2) + "%");
+}
+
+void PortfolioMonitorScreen::rebuild_tree(QTreeWidget* tree, const QVector<AggRow>& rows, bool holdings,
+ QHash<QString, QTreeWidgetItem*>& index) {
+ // Preserve which symbols were expanded across rebuilds.
+ QSet<QString> expanded;
+ for (auto it = index.constBegin(); it != index.constEnd(); ++it)
+ if (it.value()->isExpanded())
+ expanded.insert(it.key());
+
+ tree->clear();
+ index.clear();
+
+ for (const AggRow& row : rows) {
+ auto* parent = new QTreeWidgetItem(tree);
+ fill_parent(parent, row, holdings);
+ const QString key = row_key(row.symbol, row.exchange);
+ index.insert(key, parent);
+
+ // Parent-level EXIT ALL (only meaningful with >1 child; single-child
+ // symbols get their action on the child row).
+ if (row.children.size() > 1) {
+ auto* exit_all = new QPushButton(tr("EXIT ALL"));
+ exit_all->setCursor(Qt::PointingHandCursor);
+ exit_all->setStyleSheet("QPushButton{background:transparent;border:1px solid #5c1f1f;"
+ "color:#ef4444;font-size:10px;padding:2px 8px;}"
+ "QPushButton:hover{background:#1a0a0a;}");
+ const QString sym = row.symbol, exch = row.exchange;
+ const int n = int(row.children.size());
+ connect(exit_all, &QPushButton::clicked, this,
+ [this, sym, exch, holdings, n]() { confirm_exit_symbol(sym, exch, holdings, n); });
+ tree->setItemWidget(parent, ColAction, exit_all);
+ }
+
+ for (const AggChild& c : row.children) {
+ auto* child = new QTreeWidgetItem(parent);
+ child->setText(ColSymbol, c.broker_label);
+ child->setForeground(ColSymbol, QColor("#9ca3af"));
+ if (holdings)
+ set_pnl_cell(child, ColProduct, c.day_pnl, fmt_money(c.day_pnl, true));
+ else
+ child->setText(ColProduct, c.product + (c.side.isEmpty() ? QString() : "·" + c.side));
+ child->setText(ColQty, fmt_qty(c.qty));
+ child->setText(ColAvg, fmt_money(c.avg_price));
+ child->setText(ColLtp, c.ltp > 0 ? fmt_money(c.ltp) : QStringLiteral("—"));
+ set_pnl_cell(child, ColPnl, c.pnl, fmt_money(c.pnl, true));
+ const double notional = c.avg_price * std::fabs(c.qty);
+ set_pnl_cell(child, ColPnlPct, c.pnl,
+ QString::number(notional > 0 ? c.pnl / notional * 100.0 : 0.0, 'f', 2) + "%");
+
+ auto* exit_btn = new QPushButton(tr("EXIT"));
+ exit_btn->setCursor(Qt::PointingHandCursor);
+ exit_btn->setStyleSheet("QPushButton{background:transparent;border:1px solid #5c1f1f;"
+ "color:#ef4444;font-size:10px;padding:2px 8px;}"
+ "QPushButton:hover{background:#1a0a0a;}");
+ const QString acct = c.account_id, label = c.broker_label, sym = row.symbol,
+ exch = row.exchange, product = c.product;
+ const double qty = c.qty;
+ connect(exit_btn, &QPushButton::clicked, this, [this, acct, label, sym, exch, product, qty]() {
+ confirm_exit_child(acct, label, sym, exch, product, qty);
+ });
+ tree->setItemWidget(child, ColAction, exit_btn);
+ }
+
+ parent->setExpanded(expanded.contains(key) || rows.size() <= 4);
+ }
+}
+
+// ── Slots ────────────────────────────────────────────────────────────────────
+
+void PortfolioMonitorScreen::rebuild_positions() {
+ rebuild_tree(positions_tree_, UnifiedPortfolioService::instance().positions(), /*holdings=*/false,
+ pos_index_);
+}
+
+void PortfolioMonitorScreen::rebuild_holdings() {
+ rebuild_tree(holdings_tree_, UnifiedPortfolioService::instance().holdings(), /*holdings=*/true,
+ hold_index_);
+}
+
+// Tick patch: parent sums AND child cells, in place. Children must repaint with
+// the parent — patching only the parent leaves child rows at older marks, so the
+// parent P&L stops equalling the visible child sum (looks like a calc bug).
+// Child items align 1:1 with row.children (both built in rebuild_tree; ticks
+// never reorder), so index-addressing is safe. Work stays O(children of one
+// symbol) per tick, within the quote hot-path constraint.
+namespace {
+void patch_row_items(QTreeWidgetItem* parent, const AggRow& row, bool holdings) {
+ const int n = std::min(parent->childCount(), int(row.children.size()));
+ for (int i = 0; i < n; ++i) {
+ QTreeWidgetItem* child = parent->child(i);
+ const AggChild& c = row.children[i];
+ if (holdings)
+ set_pnl_cell(child, ColProduct, c.day_pnl, fmt_money(c.day_pnl, true));
+ child->setText(ColLtp, c.ltp > 0 ? fmt_money(c.ltp) : QStringLiteral("—"));
+ set_pnl_cell(child, ColPnl, c.pnl, fmt_money(c.pnl, true));
+ const double notional = c.avg_price * std::fabs(c.qty);
+ set_pnl_cell(child, ColPnlPct, c.pnl,
+ QString::number(notional > 0 ? c.pnl / notional * 100.0 : 0.0, 'f', 2) + "%");
+ }
+}
+} // namespace
+
+void PortfolioMonitorScreen::patch_position(const QString& symbol) {
+ for (const AggRow& row : UnifiedPortfolioService::instance().positions()) {
+ if (row.symbol != symbol)
+ continue;
+ if (auto* item = pos_index_.value(row_key(row.symbol, row.exchange))) {
+ fill_parent(item, row, /*holdings=*/false);
+ patch_row_items(item, row, /*holdings=*/false);
+ }
+ }
+}
+
+void PortfolioMonitorScreen::patch_holding(const QString& symbol) {
+ for (const AggRow& row : UnifiedPortfolioService::instance().holdings()) {
+ if (row.symbol != symbol)
+ continue;
+ if (auto* item = hold_index_.value(row_key(row.symbol, row.exchange))) {
+ fill_parent(item, row, /*holdings=*/true);
+ patch_row_items(item, row, /*holdings=*/true);
+ }
+ }
+}
+
+void PortfolioMonitorScreen::update_summary() {
+ const auto s = UnifiedPortfolioService::instance().summary();
+ auto set = [](QLabel* l, double v, bool color, bool signed_pfx = true) {
+ l->setText(fmt_money(v, signed_pfx));
+ if (color)
+ l->setStyleSheet(QString("color:%1;font-size:13px;font-weight:600;")
+ .arg(v > 0 ? fincept::ui::colors::POSITIVE()
+ : v < 0 ? fincept::ui::colors::NEGATIVE()
+ : QStringLiteral("#e5e5e5")));
+ };
+ set(sum_positions_pnl_, s.positions_pnl, true);
+ set(sum_day_pnl_, s.positions_day_pnl + s.holdings_day_pnl, true);
+ set(sum_holdings_pnl_, s.holdings_pnl, true);
+ set(sum_invested_, s.invested, false, false);
+ set(sum_current_, s.current, false, false);
+ sum_return_->setText(QString::number(s.return_pct, 'f', 2) + "%");
+ sum_return_->setStyleSheet(QString("color:%1;font-size:13px;font-weight:600;")
+ .arg(s.return_pct > 0 ? fincept::ui::colors::POSITIVE()
+ : s.return_pct < 0 ? fincept::ui::colors::NEGATIVE()
+ : QStringLiteral("#e5e5e5")));
+ sum_accounts_->setText(QString("%1/%2 LIVE").arg(s.accounts_live).arg(s.accounts_total));
+}
+
+void PortfolioMonitorScreen::on_action_finished(bool ok, const QString& message) {
+ toast_->setText(message);
+ toast_->setStyleSheet(QString("color:%1;font-size:11px;")
+ .arg(ok ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE()));
+ QTimer::singleShot(8000, toast_, [t = toast_]() { t->clear(); });
+}
+
+// ── Actions ──────────────────────────────────────────────────────────────────
+
+void PortfolioMonitorScreen::confirm_exit_child(const QString& account_id, const QString& broker_label,
+ const QString& symbol, const QString& exchange,
+ const QString& product, double qty) {
+ const auto ret = QMessageBox::question(
+ this, tr("Exit Position"),
+ tr("Square off %1 × %2 on %3 (%4)?").arg(fmt_qty(qty), symbol, broker_label, product),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (ret == QMessageBox::Yes)
+ UnifiedPortfolioService::instance().exit_child(account_id, symbol, exchange, product);
+}
+
+void PortfolioMonitorScreen::confirm_exit_symbol(const QString& symbol, const QString& exchange,
+ bool holdings, int n_accounts) {
+ const auto ret = QMessageBox::question(
+ this, tr("Exit All"),
+ tr("Square off %1 across %2 account(s)?").arg(symbol).arg(n_accounts),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (ret == QMessageBox::Yes)
+ UnifiedPortfolioService::instance().exit_symbol(symbol, exchange, holdings);
+}
+
+void PortfolioMonitorScreen::on_new_order() {
+ const auto accounts = UnifiedPortfolioService::instance().accounts();
+ if (accounts.isEmpty()) {
+ QMessageBox::information(this, tr("New Order"), tr("No active INR broker accounts."));
+ return;
+ }
+
+ QDialog dlg(this);
+ dlg.setWindowTitle(tr("New Order — Any Account"));
+ auto* form = new QFormLayout(&dlg);
+
+ auto* acct_combo = new QComboBox;
+ for (const auto& a : accounts)
+ acct_combo->addItem(a.label + (a.live ? "" : tr(" (offline)")), a.account_id);
+ auto* symbol_edit = new QLineEdit;
+ symbol_edit->setPlaceholderText(tr("e.g. RELIANCE"));
+ auto* exch_combo = new QComboBox;
+ exch_combo->addItems({"NSE", "BSE", "NFO", "BFO", "MCX", "CDS"});
+ auto* side_combo = new QComboBox;
+ side_combo->addItems({tr("BUY"), tr("SELL")});
+ auto* qty_spin = new QSpinBox;
+ qty_spin->setRange(1, 1'000'000);
+ auto* type_combo = new QComboBox;
+ type_combo->addItems({tr("MARKET"), tr("LIMIT")});
+ auto* price_spin = new QDoubleSpinBox;
+ price_spin->setRange(0.0, 10'000'000.0);
+ price_spin->setDecimals(2);
+ price_spin->setEnabled(false);
+ connect(type_combo, &QComboBox::currentIndexChanged, price_spin,
+ [price_spin](int idx) { price_spin->setEnabled(idx == 1); });
+ auto* product_combo = new QComboBox;
+ product_combo->addItems({tr("INTRADAY"), tr("DELIVERY"), tr("MARGIN")});
+
+ form->addRow(tr("Account"), acct_combo);
+ form->addRow(tr("Symbol"), symbol_edit);
+ form->addRow(tr("Exchange"), exch_combo);
+ form->addRow(tr("Side"), side_combo);
+ form->addRow(tr("Quantity"), qty_spin);
+ form->addRow(tr("Type"), type_combo);
+ form->addRow(tr("Limit Price"), price_spin);
+ form->addRow(tr("Product"), product_combo);
+
+ auto* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
+ buttons->button(QDialogButtonBox::Ok)->setText(tr("PLACE ORDER"));
+ connect(buttons, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
+ connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
+ form->addRow(buttons);
+
+ if (dlg.exec() != QDialog::Accepted)
+ return;
+
+ const QString symbol = symbol_edit->text().trimmed().toUpper();
+ if (symbol.isEmpty())
+ return;
+
+ trading::UnifiedOrder order;
+ order.symbol = symbol;
+ order.exchange = exch_combo->currentText();
+ order.side = side_combo->currentIndex() == 0 ? trading::OrderSide::Buy : trading::OrderSide::Sell;
+ order.order_type = type_combo->currentIndex() == 0 ? trading::OrderType::Market : trading::OrderType::Limit;
+ order.quantity = qty_spin->value();
+ order.price = type_combo->currentIndex() == 1 ? price_spin->value() : 0.0;
+ order.product_type = product_combo->currentIndex() == 0 ? trading::ProductType::Intraday
+ : product_combo->currentIndex() == 1 ? trading::ProductType::Delivery
+ : trading::ProductType::Margin;
+
+ UnifiedPortfolioService::instance().place_new_order(acct_combo->currentData().toString(), order);
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio_monitor/PortfolioMonitorScreen.h b/fincept-qt/src/screens/portfolio_monitor/PortfolioMonitorScreen.h
new file mode 100644
index 000000000..08e3b0059
--- /dev/null
+++ b/fincept-qt/src/screens/portfolio_monitor/PortfolioMonitorScreen.h
@@ -0,0 +1,84 @@
+#pragma once
+// PortfolioMonitorScreen — standalone dockable "all accounts" view: positions &
+// holdings aggregated across every active INR broker account, with full control
+// (exit / square-off / new order) routed per-account through
+// UnifiedPortfolioService. Design:
+// docs/superpowers/specs/2026-06-10-portfolio-monitor-design.md
+
+#include <QHash>
+#include <QString>
+#include <QWidget>
+
+class QLabel;
+class QPushButton;
+class QTabWidget;
+class QTreeWidget;
+class QTreeWidgetItem;
+
+namespace fincept::trading {
+struct AggRow;
+}
+
+namespace fincept::screens {
+
+class PortfolioMonitorScreen : public QWidget {
+ Q_OBJECT
+ public:
+ explicit PortfolioMonitorScreen(QWidget* parent = nullptr);
+
+ /// Flip the ⧉ detach button into a ⤓ dock-back button (feeds pattern —
+ /// the host reparents this widget; we only signal intent).
+ void set_floating(bool floating);
+
+ signals:
+ void float_requested(); // user clicked ⧉ while docked
+ void dock_requested(); // user clicked ⤓ while floating
+
+ protected:
+ void showEvent(QShowEvent* event) override;
+
+ private slots:
+ void rebuild_positions();
+ void rebuild_holdings();
+ void patch_position(const QString& symbol);
+ void patch_holding(const QString& symbol);
+ void update_summary();
+ void on_action_finished(bool ok, const QString& message);
+ void on_new_order();
+ void on_mode_toggled(bool live);
+
+ private:
+ QWidget* build_summary_bar();
+ QTreeWidget* make_tree(bool holdings);
+ void rebuild_tree(QTreeWidget* tree, const QVector<trading::AggRow>& rows, bool holdings,
+ QHash<QString, QTreeWidgetItem*>& index);
+ void fill_parent(QTreeWidgetItem* item, const trading::AggRow& row, bool holdings);
+ void confirm_exit_child(const QString& account_id, const QString& broker_label, const QString& symbol,
+ const QString& exchange, const QString& product, double qty);
+ void confirm_exit_symbol(const QString& symbol, const QString& exchange, bool holdings, int n_accounts);
+
+ // Summary bar
+ QPushButton* mode_btn_ = nullptr; // PAPER ⇄ LIVE (checked == LIVE)
+ QPushButton* float_btn_ = nullptr; // ⧉ detach / ⤓ dock back
+ bool floating_ = false;
+ QLabel* sum_positions_pnl_ = nullptr;
+ QLabel* sum_day_pnl_ = nullptr;
+ QLabel* sum_invested_ = nullptr;
+ QLabel* sum_current_ = nullptr;
+ QLabel* sum_holdings_pnl_ = nullptr;
+ QLabel* sum_return_ = nullptr;
+ QLabel* sum_accounts_ = nullptr;
+ QLabel* toast_ = nullptr;
+
+ QTabWidget* tabs_ = nullptr;
+ QTreeWidget* positions_tree_ = nullptr;
+ QTreeWidget* holdings_tree_ = nullptr;
+
+ // "symbol|exchange" → parent item, for in-place tick patching
+ QHash<QString, QTreeWidgetItem*> pos_index_;
+ QHash<QString, QTreeWidgetItem*> hold_index_;
+
+ bool activated_ = false;
+};
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/settings/LlmConfigSection.cpp b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
index 36b8432c9..509a186ac 100644
--- a/fincept-qt/src/screens/settings/LlmConfigSection.cpp
+++ b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
@@ -9,6 +9,7 @@
#include "screens/settings/LlmConfigSection.h"
#include "services/llm/LlmService.h"
+#include "services/llm/ProviderCatalog.h"
#include "core/logging/Logger.h"
#include "storage/repositories/LlmConfigRepository.h"
#include "storage/repositories/LlmProfileRepository.h"
@@ -35,28 +36,10 @@ namespace fincept::screens {
[[maybe_unused]] static constexpr const char* TAG = "LlmConfigSection";
-const QStringList LlmConfigSection::KNOWN_PROVIDERS = {"openai", "anthropic", "gemini", "groq", "deepseek",
- "openrouter", "minimax", "kimi", "ollama", "xai", "fincept",
- "astraflow", "astraflow_cn", "aihubmix", "atlascloud"};
+const QStringList LlmConfigSection::KNOWN_PROVIDERS = fincept::ai_chat::ProviderCatalog::known_providers();
QString LlmConfigSection::provider_display_name(const QString& provider_id) {
- static const QHash<QString, QString> kNames = {
- {"openai", "OpenAI"}, {"anthropic", "Anthropic"}, {"gemini", "Gemini"},
- {"groq", "Groq"}, {"deepseek", "DeepSeek"}, {"openrouter", "OpenRouter"},
- {"minimax", "MiniMax"}, {"kimi", "Kimi"}, {"ollama", "Ollama"},
- {"xai", "xAI"}, {"fincept", "Fincept LLM (recommended)"}, {"astraflow", "AstraFlow"},
- {"astraflow_cn", "AstraFlow CN"}, {"aihubmix", "AIHubMix"}, {"atlascloud", "AtlasCloud"},
- };
- const QString id = provider_id.toLower();
- const auto it = kNames.find(id);
- if (it != kNames.end())
- return it.value();
- // Unknown/custom provider: capitalize the first letter as a sensible default.
- if (provider_id.isEmpty())
- return provider_id;
- QString s = provider_id;
- s[0] = s[0].toUpper();
- return s;
+ return fincept::ai_chat::ProviderCatalog::display_name(provider_id);
}
QStringList LlmConfigSection::providers_sorted() {
@@ -68,107 +51,11 @@ QStringList LlmConfigSection::providers_sorted() {
}
QString LlmConfigSection::default_base_url(const QString& provider) {
- const QString p = provider.toLower();
- if (p == "openai")
- return {}; // uses default
- if (p == "anthropic")
- return {};
- if (p == "gemini")
- return {};
- if (p == "groq")
- return {};
- if (p == "deepseek")
- return {};
- if (p == "openrouter")
- return {};
- if (p == "minimax")
- return "https://api.minimax.io/v1";
- if (p == "kimi")
- return {}; // defaults to https://api.moonshot.ai
- if (p == "ollama")
- return "http://localhost:11434";
- if (p == "xai")
- return {};
- if (p == "fincept")
- return {}; // endpoints are hardcoded in LlmService, no base_url needed
- if (p == "astraflow")
- return "https://api-us-ca.umodelverse.ai/v1"; // Astraflow global endpoint (UCloud)
- if (p == "astraflow_cn")
- return "https://api.modelverse.cn/v1"; // Astraflow China endpoint (UCloud)
- if (p == "aihubmix")
- return "https://aihubmix.com/v1"; // AIHubMix — OpenAI-compatible aggregator (500+ models)
- if (p == "atlascloud")
- return "https://api.atlascloud.ai/v1"; // AtlasCloud — OpenAI-compatible aggregator (300+ open models)
- return {};
+ return fincept::ai_chat::ProviderCatalog::default_base_url(provider);
}
QStringList LlmConfigSection::fallback_models(const QString& provider) {
- const QString p = provider.toLower();
- if (p == "openai")
- return {"gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "o3-mini"};
- if (p == "anthropic")
- return {"claude-sonnet-4-5-20250514", "claude-opus-4-5", "claude-3-5-sonnet-20241022",
- "claude-3-haiku-20240307"};
- if (p == "gemini")
- return {"gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash"};
- if (p == "groq")
- return {"llama-3.3-70b-versatile", "mixtral-8x7b-32768", "gemma2-9b-it"};
- if (p == "deepseek")
- return {"deepseek-chat", "deepseek-reasoner"};
- if (p == "openrouter")
- return {"openai/gpt-4o", "anthropic/claude-sonnet-4-5", "google/gemini-2.5-flash"};
- if (p == "minimax")
- return {"MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M2.5", "MiniMax-M2.5-highspeed"};
- if (p == "kimi")
- return {"moonshot-v1-auto",
- "moonshot-v1-8k",
- "moonshot-v1-32k",
- "moonshot-v1-128k",
- "kimi-k2.5",
- "kimi-k2.6",
- "kimi-k2-thinking",
- "kimi-k2-thinking-turbo",
- "kimi-k2-0905-preview",
- "kimi-k2-turbo-preview",
- "kimi-k2-0711-preview",
- "moonshot-v1-8k-vision-preview",
- "moonshot-v1-32k-vision-preview",
- "moonshot-v1-128k-vision-preview"};
- if (p == "ollama")
- return {}; // Local provider — models fetched live from /api/tags. No fallback so the
- // combo only shows what the user actually has installed locally.
- if (p == "xai")
- return {"grok-4-latest", "grok-4", "grok-3", "grok-3-mini"};
- if (p == "fincept")
- return {"MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M2.5", "MiniMax-M2.5-highspeed"};
- if (p == "astraflow" || p == "astraflow_cn")
- // Astraflow by UCloud — OpenAI-compatible aggregator supporting 200+ models.
- // A non-exhaustive starter list; full list fetchable via Fetch button.
- return {"gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "o3-mini",
- "claude-sonnet-4-5-20250514", "claude-3-5-sonnet-20241022",
- "gemini-2.5-flash", "gemini-2.5-pro",
- "deepseek-chat", "deepseek-reasoner",
- "llama-3.3-70b-versatile", "qwen-turbo", "qwen-plus"};
- if (p == "aihubmix")
- // AIHubMix — OpenAI-compatible aggregator routing 500+ models (OpenAI, Claude,
- // Gemini, DeepSeek, Qwen, ...) through one /v1/chat/completions endpoint. Models
- // keep their upstream ids. Starter list only; full list via the Fetch button.
- return {"gpt-4o", "gpt-4o-mini", "gpt-4.1", "o3-mini",
- "claude-sonnet-4-5-20250514", "claude-3-5-sonnet-20241022",
- "gemini-2.5-flash", "gemini-2.5-pro",
- "deepseek-chat", "deepseek-reasoner",
- "qwen-max", "qwen-plus", "grok-4"};
- if (p == "atlascloud")
- // AtlasCloud — OpenAI-compatible aggregator (300+ models). Model ids are
- // HuggingFace-style "org/model" strings (NOT short aliases). Note: a few ids
- // listed by /v1/models are unprovisioned and return 400 (e.g. google/gemini-2.0-flash,
- // openai/gpt-4o*). The list below is a verified-working starter set; use the
- // Fetch button for the full live catalog (/v1/models).
- return {"deepseek-ai/DeepSeek-V3.1", "deepseek-ai/deepseek-r1-0528",
- "qwen/qwen3-32b", "Qwen/Qwen3-235B-A22B-Instruct-2507",
- "zai-org/GLM-4.6", "moonshotai/Kimi-K2-Instruct", "MiniMaxAI/MiniMax-M2",
- "google/gemini-2.5-flash", "anthropic/claude-haiku-4.5-20251001"};
- return {};
+ return fincept::ai_chat::ProviderCatalog::fallback_models(provider);
}
// ============================================================================
diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaEngine.cpp b/fincept-qt/src/services/alpha_arena/AlphaArenaEngine.cpp
deleted file mode 100644
index 60ba23bd9..000000000
--- a/fincept-qt/src/services/alpha_arena/AlphaArenaEngine.cpp
+++ /dev/null
@@ -1,526 +0,0 @@
-#include "services/alpha_arena/AlphaArenaEngine.h"
-
-#include "core/logging/Logger.h"
-#include "services/alpha_arena/ContextBuilder.h"
-#include "storage/secure/SecureStorage.h"
-#include "trading/exchanges/hyperliquid/HyperliquidVenue.h"
-
-#include <QCryptographicHash>
-#include <QDateTime>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QSysInfo>
-#include <QUuid>
-
-#include <algorithm>
-
-namespace fincept::services::alpha_arena {
-
-namespace {
-
-QString new_uuid() { return QUuid::createUuid().toString(QUuid::WithoutBraces); }
-
-} // namespace
-
-AlphaArenaEngine& AlphaArenaEngine::instance() {
- static AlphaArenaEngine s;
- return s;
-}
-
-AlphaArenaEngine::AlphaArenaEngine() = default;
-AlphaArenaEngine::~AlphaArenaEngine() = default;
-
-void AlphaArenaEngine::init() {
- if (inited_) return;
- inited_ = true;
-
- clock_ = new TickClock(this);
- dispatcher_ = new ModelDispatcher(this);
- router_ = new OrderRouter(this);
- paper_venue_ = new PaperVenue(this);
-
- // Wire components together. Engine stays in the middle so the UI only
- // ever subscribes to engine signals (one reference per widget).
- connect(clock_, &TickClock::tick, this, &AlphaArenaEngine::on_tick);
- connect(clock_, &TickClock::tick_skipped, this, &AlphaArenaEngine::on_tick_skipped);
-
- connect(dispatcher_, &ModelDispatcher::tick_dispatch_complete,
- this, &AlphaArenaEngine::on_dispatch_complete);
- connect(dispatcher_, &ModelDispatcher::decision_received,
- this, &AlphaArenaEngine::on_decision_received);
- connect(dispatcher_, &ModelDispatcher::decision_received,
- router_, &OrderRouter::on_decision);
-
- // Router emits Signal enum; the engine forwards as int for the public-API
- // surface. Lambda bridges the enum→int cast at connect time.
- connect(router_, &OrderRouter::action_evaluated, this,
- [this](const QString& agent_id, const QString& coin,
- fincept::services::alpha_arena::Signal sig,
- int risk_outcome, const QString& reason) {
- emit action_evaluated(agent_id, coin, static_cast<int>(sig),
- risk_outcome, reason);
- });
- connect(router_, &OrderRouter::order_placed,
- this, &AlphaArenaEngine::order_placed);
- connect(router_, &OrderRouter::hitl_requested,
- this, &AlphaArenaEngine::hitl_requested);
- connect(router_, &OrderRouter::agent_circuit_open,
- this, &AlphaArenaEngine::on_circuit_open);
-
- // Crash recovery: surface any competitions left in `running` status when
- // the app died. UI shows a Resume / Halt / Reconcile dialog.
- auto orphans = AlphaArenaRepo::instance().find_orphaned_running();
- if (orphans.is_ok() && !orphans.value().isEmpty()) {
- QStringList ids;
- for (const auto& c : orphans.value()) ids << c.id;
- LOG_WARN("AlphaArena.Engine",
- QString("crash recovery: %1 orphaned running competition(s)").arg(ids.size()));
- emit crash_recovery_pending(ids);
- }
-
- LOG_INFO("AlphaArena.Engine", "init complete");
-}
-
-// ─── User-facing actions ────────────────────────────────────────────────────
-
-QString AlphaArenaEngine::deterministic_agent_id(const QString& competition_id, int slot) {
- const QString seed = competition_id + QStringLiteral(":") + QString::number(slot);
- return QString::fromLatin1(
- QCryptographicHash::hash(seed.toUtf8(), QCryptographicHash::Sha1).toHex().left(32));
-}
-
-Result<QString> AlphaArenaEngine::create_competition(NewCompetitionConfig cfg) {
- if (!inited_) return Result<QString>::err("engine not initialised");
- if (cfg.agents.size() < 2) return Result<QString>::err("need at least 2 agents");
- if (cfg.cadence_seconds < 10 || cfg.cadence_seconds > 3600)
- return Result<QString>::err("cadence_seconds out of range [10, 3600]");
-
- if (cfg.instruments.isEmpty()) cfg.instruments = kPerpUniverse();
- for (const auto& s : cfg.instruments) {
- if (!kPerpUniverse().contains(s))
- return Result<QString>::err(("instrument not in perp universe: " + s).toStdString());
- }
-
- const QString comp_id = new_uuid();
-
- CompetitionRow row;
- row.id = comp_id;
- row.name = cfg.name.isEmpty() ? QStringLiteral("Alpha Arena") : cfg.name;
- row.mode = cfg.mode;
- row.venue = cfg.venue_kind;
- row.instruments = cfg.instruments;
- row.initial_capital = cfg.initial_capital_per_agent;
- row.cadence_seconds = cfg.cadence_seconds;
- row.live_mode = cfg.live_mode;
- row.status = QStringLiteral("created");
-
- if (auto r = AlphaArenaRepo::instance().insert_competition(row); r.is_err())
- return Result<QString>::err(r.error());
-
- if (cfg.live_mode) {
- // Record the live-mode acknowledgement timestamp + hostname. The UI
- // is responsible for collecting the typed-acknowledgement; the engine
- // just records that the user actually got there.
- AlphaArenaRepo::instance().mark_live_mode_ack(comp_id,
- QSysInfo::machineHostName());
- }
-
- // Persist agents + stash API keys in SecureStorage.
- for (int slot = 0; slot < cfg.agents.size(); ++slot) {
- AgentSpec spec = cfg.agents[slot];
- AgentRow agent;
- agent.id = deterministic_agent_id(comp_id, slot);
- agent.competition_id = comp_id;
- agent.slot = slot;
- agent.provider = spec.provider;
- agent.model_id = spec.model_id;
- agent.display_name = spec.display_name.isEmpty()
- ? (spec.provider + ":" + spec.model_id)
- : spec.display_name;
- agent.color_hex = spec.color_hex.isEmpty() ? QStringLiteral("#FF8800") : spec.color_hex;
- // Store the API key under a key that IS the secret_handle. The handle
- // is what we hand to the subprocess; the plaintext lives only in
- // SecureStorage.
- const QString secret_handle = QStringLiteral("alpha_arena/api_key/") + agent.id;
- agent.api_secret_handle = secret_handle;
- if (!spec.api_key.isEmpty()) {
- auto sr = SecureStorage::instance().store(secret_handle, spec.api_key);
- if (sr.is_err()) {
- LOG_ERROR("AlphaArena.Engine",
- QString("could not store API key for agent %1: %2")
- .arg(agent.id, QString::fromStdString(sr.error())));
- return Result<QString>::err("failed to store api key in keystore");
- }
- }
- if (auto r = AlphaArenaRepo::instance().insert_agent(agent); r.is_err()) {
- return Result<QString>::err(r.error());
- }
- }
-
- // Audit event.
- QJsonObject p;
- p["mode"] = mode_to_wire(cfg.mode);
- p["venue"] = cfg.venue_kind;
- p["agents"] = cfg.agents.size();
- p["cadence_seconds"] = cfg.cadence_seconds;
- AlphaArenaRepo::instance().append_event(comp_id, QString(),
- QStringLiteral("competition_created"), p);
- return Result<QString>::ok(comp_id);
-}
-
-Result<void> AlphaArenaEngine::start(const QString& competition_id) {
- if (!inited_) return Result<void>::err("engine not initialised");
- if (!active_competition_id_.isEmpty() && active_competition_id_ != competition_id) {
- return Result<void>::err("another competition is already active");
- }
-
- auto comp_opt = AlphaArenaRepo::instance().find_competition(competition_id);
- if (!comp_opt) return Result<void>::err("competition not found");
- const auto comp = *comp_opt;
-
- venue_ = select_venue_for_kind(comp.venue);
- if (!venue_) return Result<void>::err("unsupported venue: " + comp.venue.toStdString());
-
- auto agents_r = AlphaArenaRepo::instance().agents_for(competition_id);
- if (agents_r.is_err()) return Result<void>::err(agents_r.error());
- const auto agents = agents_r.value();
-
- QVector<DispatchAgent> dispatch_agents;
- dispatch_agents.reserve(agents.size());
- for (const auto& a : agents) {
- DispatchAgent d;
- d.agent_id = a.id;
- d.provider = a.provider;
- d.model_id = a.model_id;
- d.display_name = a.display_name;
- d.api_secret_handle = a.api_secret_handle;
- dispatch_agents.append(d);
-
- // Seed the paper book at competition start.
- if (paper_venue_ == venue_) {
- paper_seed_agent(*paper_venue_, a.id, comp.initial_capital);
- }
-
- // Seed router state.
- AgentRuntimeState s;
- s.agent_id = a.id;
- s.competition_id = competition_id;
- s.equity = comp.initial_capital;
- s.live_mode = comp.live_mode;
- router_->update_agent_state(a.id, s);
- }
-
- active_competition_id_ = competition_id;
- active_mode_ = comp.mode;
-
- dispatcher_->configure(competition_id, comp.mode, dispatch_agents);
- router_->configure(competition_id, comp.mode, venue_);
- clock_->set_cadence_seconds(comp.cadence_seconds);
- clock_->start();
-
- AlphaArenaRepo::instance().update_competition_status(competition_id,
- QStringLiteral("running"));
- AlphaArenaRepo::instance().append_event(competition_id, QString(),
- QStringLiteral("competition_started"), {});
- emit competition_status_changed(competition_id, QStringLiteral("running"));
-
- LOG_INFO("AlphaArena.Engine",
- QString("started competition %1 (mode=%2, venue=%3, %4 agents, cadence=%5s)")
- .arg(competition_id, mode_to_wire(comp.mode), comp.venue)
- .arg(agents.size())
- .arg(comp.cadence_seconds));
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaEngine::stop() {
- if (active_competition_id_.isEmpty()) return Result<void>::ok();
- clock_->stop();
- AlphaArenaRepo::instance().update_competition_status(active_competition_id_,
- QStringLiteral("halted_by_user"));
- AlphaArenaRepo::instance().append_event(active_competition_id_, QString(),
- QStringLiteral("competition_stopped"), {});
- emit competition_status_changed(active_competition_id_, QStringLiteral("halted_by_user"));
- detach_active();
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaEngine::kill_all() {
- if (active_competition_id_.isEmpty()) return Result<void>::ok();
- clock_->stop();
-
- auto agents_r = AlphaArenaRepo::instance().agents_for(active_competition_id_);
- if (agents_r.is_ok() && venue_) {
- for (const auto& a : agents_r.value()) {
- auto positions_r = AlphaArenaRepo::instance().open_positions_for(a.id);
- if (positions_r.is_err()) continue;
- for (const auto& p : positions_r.value()) {
- OrderRequest req;
- req.agent_id = a.id;
- req.coin = p.coin;
- req.qty = std::fabs(p.qty);
- req.side = (p.qty > 0.0) ? QStringLiteral("sell") : QStringLiteral("buy");
- req.leverage = p.leverage;
- req.reduce_only = true;
- venue_->place_order(req, [](OrderAck) {});
- }
- }
- }
-
- AlphaArenaRepo::instance().update_competition_status(active_competition_id_,
- QStringLiteral("halted_by_user"));
- AlphaArenaRepo::instance().append_event(active_competition_id_, QString(),
- QStringLiteral("kill_all"), {});
- emit competition_status_changed(active_competition_id_, QStringLiteral("halted_by_user"));
- detach_active();
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaEngine::halt_agent(const QString& agent_id) {
- if (active_competition_id_.isEmpty()) return Result<void>::err("no active competition");
- AlphaArenaRepo::instance().update_agent_state(agent_id, QStringLiteral("paused"));
- QJsonObject p; p["agent_id"] = agent_id;
- AlphaArenaRepo::instance().append_event(active_competition_id_, agent_id,
- QStringLiteral("agent_halted"), p);
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaEngine::resume_agent(const QString& agent_id) {
- if (active_competition_id_.isEmpty()) return Result<void>::err("no active competition");
- AlphaArenaRepo::instance().update_agent_state(agent_id, QStringLiteral("active"));
- AlphaArenaRepo::instance().bump_parse_failures(agent_id, 0);
- AlphaArenaRepo::instance().bump_risk_rejects(agent_id, 0);
- QJsonObject p; p["agent_id"] = agent_id;
- AlphaArenaRepo::instance().append_event(active_competition_id_, agent_id,
- QStringLiteral("agent_resumed"), p);
- return Result<void>::ok();
-}
-
-void AlphaArenaEngine::resume_after_hitl(const QString& approval_id, bool approved) {
- if (router_) router_->resolve_hitl(approval_id, approved);
-}
-
-bool AlphaArenaEngine::is_running() const {
- return clock_ && !active_competition_id_.isEmpty() && clock_->in_flight() == false
- ? clock_->last_seq() > 0
- : (clock_ && !active_competition_id_.isEmpty());
-}
-
-int AlphaArenaEngine::next_tick_in_seconds() const {
- return clock_ ? clock_->cadence_seconds() : 0;
-}
-
-IExchangeVenue::ConnectionState AlphaArenaEngine::venue_connection_state() const {
- return venue_ ? venue_->connection_state() : IExchangeVenue::ConnectionState::Disconnected;
-}
-
-// ─── Internal slots ─────────────────────────────────────────────────────────
-
-void AlphaArenaEngine::on_tick(Tick t) {
- if (active_competition_id_.isEmpty()) {
- clock_->tick_complete();
- return;
- }
- emit tick_fired(t.seq);
-
- TickContext ctx;
- QHash<QString, AgentAccountState> per_agent;
- std::optional<SituationalContext> situational;
- prepare_tick_inputs(t, ctx, per_agent, situational);
-
- AlphaArenaRepo::instance().increment_cycle_count(active_competition_id_);
- dispatcher_->dispatch_tick(t, ctx, per_agent, situational);
-}
-
-void AlphaArenaEngine::on_tick_skipped(int seq) {
- LOG_WARN("AlphaArena.Engine", QString("tick %1 skipped (previous in flight)").arg(seq));
- if (!active_competition_id_.isEmpty()) {
- QJsonObject p; p["seq"] = seq;
- AlphaArenaRepo::instance().append_event(active_competition_id_, QString(),
- QStringLiteral("tick_skipped"), p);
- }
- emit tick_skipped(seq);
-}
-
-void AlphaArenaEngine::on_dispatch_complete(int seq) {
- Q_UNUSED(seq);
- if (clock_) clock_->tick_complete();
-}
-
-void AlphaArenaEngine::on_decision_received(QString decision_id, QString agent_id,
- QVector<ProposedAction> actions,
- QString parse_error) {
- Q_UNUSED(actions);
- Q_UNUSED(parse_error);
- emit decision_received(decision_id, agent_id);
-}
-
-void AlphaArenaEngine::on_circuit_open(QString agent_id, QString reason) {
- AlphaArenaRepo::instance().update_agent_state(agent_id, QStringLiteral("circuit_open"));
- QJsonObject p;
- p["agent_id"] = agent_id;
- p["reason"] = reason;
- AlphaArenaRepo::instance().append_event(active_competition_id_, agent_id,
- QStringLiteral("agent_circuit_open"), p);
- emit agent_circuit_open(agent_id, reason);
-}
-
-// ─── Helpers ────────────────────────────────────────────────────────────────
-
-void AlphaArenaEngine::prepare_tick_inputs(const Tick& t,
- TickContext& ctx_out,
- QHash<QString, AgentAccountState>& per_agent_out,
- std::optional<SituationalContext>& situational_out) {
- ctx_out.tick = t;
-
- auto comp_opt = AlphaArenaRepo::instance().find_competition(active_competition_id_);
- if (!comp_opt) return;
- const auto comp = *comp_opt;
-
- // Markets — minimal snapshot. In v1 the engine seeds bid/ask/mid from the
- // venue's last_mark; bars + indicators are populated by a future
- // MarketDataIngestor (Phase 5c builds the Hyperliquid public-WS feeder).
- // For paper-mode bring-up, we degrade gracefully: empty bar arrays mean
- // the model sees only the snapshot fields.
- for (const auto& coin : comp.instruments) {
- MarketSnapshot m;
- m.coin = coin;
- const double mark = venue_ ? venue_->last_mark(coin) : 0.0;
- if (std::isfinite(mark) && mark > 0.0) {
- m.mid = mark;
- m.bid = mark * 0.9999;
- m.ask = mark * 1.0001;
- }
- ctx_out.markets.append(m);
- }
-
- // Per-agent account state.
- auto agents_r = AlphaArenaRepo::instance().agents_for(active_competition_id_);
- if (agents_r.is_err()) return;
- for (const auto& a : agents_r.value()) {
- AgentAccountState st;
- if (paper_venue_ == venue_) {
- st.equity = paper_venue_->equity_for(a.id);
- } else {
- st.equity = comp.initial_capital;
- }
- // Open positions from repo.
- auto pr = AlphaArenaRepo::instance().open_positions_for(a.id);
- if (pr.is_ok()) st.positions = pr.value();
- // Cash approximation: equity − unrealized PnL on open positions.
- double upnl = 0.0;
- for (const auto& p : st.positions) upnl += (p.mark - p.entry) * p.qty;
- st.cash = st.equity - upnl;
- per_agent_out.insert(a.id, st);
- }
-
- // Situational mode populates peer view (no equity / pnl disclosed).
- if (active_mode_ == CompetitionMode::Situational) {
- SituationalContext sc;
- for (const auto& a : agents_r.value()) {
- const auto pr = AlphaArenaRepo::instance().open_positions_for(a.id);
- if (pr.is_err()) continue;
- for (const auto& p : pr.value()) {
- PeerPositionView pv;
- pv.agent_display_name = a.display_name;
- pv.coin = p.coin;
- pv.qty = p.qty;
- pv.leverage = p.leverage;
- sc.peers.append(pv);
- }
- }
- situational_out = sc;
- }
-}
-
-void AlphaArenaEngine::detach_active() {
- active_competition_id_.clear();
- venue_ = nullptr; // we don't delete; PaperVenue stays alive for reuse
-}
-
-IExchangeVenue* AlphaArenaEngine::select_venue_for_kind(const QString& venue_kind) {
- if (venue_kind == QLatin1String("paper")) return paper_venue_;
- if (venue_kind == QLatin1String("hyperliquid")) {
- if (!hl_venue_) {
- hl_venue_ = new fincept::trading::hyperliquid::HyperliquidVenue(this);
- // Default to mainnet; the live-mode dialog can flip to testnet
- // later via a settings hook in a follow-up.
- hl_venue_->set_testnet(false);
- hl_venue_->connect();
- LOG_INFO("AlphaArena.Engine", "HyperliquidVenue instantiated and connecting");
- }
- return hl_venue_;
- }
- if (venue_kind == QLatin1String("us_equities")) {
- LOG_WARN("AlphaArena.Engine", "us_equities venue is a Season 2 stub — not implemented");
- return nullptr;
- }
- LOG_ERROR("AlphaArena.Engine", QString("unknown venue_kind: %1").arg(venue_kind));
- return nullptr;
-}
-
-Result<void> AlphaArenaEngine::set_cadence(int seconds) {
- if (active_competition_id_.isEmpty()) return Result<void>::err("no active competition");
- if (!clock_) return Result<void>::err("clock not initialised");
- if (seconds < 10 || seconds > 3600)
- return Result<void>::err("cadence_seconds out of range [10, 3600]");
- clock_->set_cadence_seconds(seconds);
- auto r = AlphaArenaRepo::instance().update_competition_cadence(
- active_competition_id_, seconds);
- if (r.is_err()) return Result<void>::err(r.error());
-
- QJsonObject p;
- p[QStringLiteral("cadence_seconds")] = seconds;
- AlphaArenaRepo::instance().append_event(active_competition_id_, QString(),
- QStringLiteral("cadence_updated"), p);
- return Result<void>::ok();
-}
-
-AlphaArenaEngine::TelemetrySnapshot AlphaArenaEngine::telemetry() const {
- TelemetrySnapshot t;
- if (active_competition_id_.isEmpty()) return t;
-
- // Pull the last 100 events for the active competition; derive metrics
- // from event types. This is the lightweight, no-extra-table approach —
- // refactor to dedicated counters if it ever becomes a hot path.
- auto rows = AlphaArenaRepo::instance().events_since(active_competition_id_, 0, 200);
- if (rows.is_err()) return t;
-
- QVector<int> latencies_ms;
- int parse_fails = 0;
- int risk_rejects = 0;
- int decisions = 0;
- int venue_errors = 0;
-
- for (const auto& e : rows.value()) {
- if (e.type == QLatin1String("decision")) {
- ++decisions;
- // payload includes "latency_ms"
- auto doc = QJsonDocument::fromJson(e.payload_json.toUtf8()).object();
- if (doc.contains(QStringLiteral("latency_ms")))
- latencies_ms.append(doc.value(QStringLiteral("latency_ms")).toInt());
- } else if (e.type == QLatin1String("parse_error")) {
- ++parse_fails;
- } else if (e.type == QLatin1String("risk_reject")) {
- ++risk_rejects;
- } else if (e.type.contains(QLatin1String("venue_error")) ||
- e.type.contains(QLatin1String("order_rejected"))) {
- ++venue_errors;
- }
- }
-
- std::sort(latencies_ms.begin(), latencies_ms.end());
- if (!latencies_ms.isEmpty()) {
- t.tick_latency_p50_ms = latencies_ms[latencies_ms.size() / 2];
- t.tick_latency_p99_ms = latencies_ms[std::min<int>(latencies_ms.size() - 1,
- (latencies_ms.size() * 99) / 100)];
- }
- if (decisions > 0) {
- t.parse_failure_rate = static_cast<double>(parse_fails) / decisions;
- t.risk_rejection_rate = static_cast<double>(risk_rejects) / decisions;
- }
- t.venue_errors = venue_errors;
- t.sample_count = decisions;
- return t;
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaEngine.h b/fincept-qt/src/services/alpha_arena/AlphaArenaEngine.h
deleted file mode 100644
index 948012e83..000000000
--- a/fincept-qt/src/services/alpha_arena/AlphaArenaEngine.h
+++ /dev/null
@@ -1,184 +0,0 @@
-#pragma once
-// AlphaArenaEngine — singleton owning the live competition runtime.
-//
-// Constructed once at app startup (like ExchangeService). Owns:
-// * TickClock (cadence)
-// * ModelDispatcher (context build + LLM fan-out + persistence)
-// * OrderRouter (RiskEngine + HITL + venue routing)
-// * IExchangeVenue (PaperVenue or HyperliquidVenue)
-//
-// v1 supports a single active competition. The engine continues running
-// even when the AlphaArenaScreen is hidden — competitions are live state,
-// not screen-bound state. The screen is a viewer.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-production-refactor.md §Phase 6.
-
-#include "core/result/Result.h"
-#include "services/alpha_arena/AlphaArenaRepo.h"
-#include "services/alpha_arena/AlphaArenaSchema.h"
-#include "services/alpha_arena/AlphaArenaTypes.h"
-#include "services/alpha_arena/IExchangeVenue.h"
-#include "services/alpha_arena/ModelDispatcher.h"
-#include "services/alpha_arena/OrderRouter.h"
-#include "services/alpha_arena/PaperVenue.h"
-#include "services/alpha_arena/TickClock.h"
-
-namespace fincept::trading::hyperliquid { class HyperliquidVenue; }
-
-#include <QHash>
-#include <QObject>
-#include <QString>
-#include <QStringList>
-#include <QVector>
-
-#include <optional>
-
-namespace fincept::services::alpha_arena {
-
-/// One agent slot the user wants to enroll. The engine converts this into
-/// an AgentRow + a SecureStorage entry for the API key.
-struct AgentSpec {
- QString provider; // openai|anthropic|google|deepseek|xai|qwen
- QString model_id;
- QString display_name;
- QString color_hex;
- QString api_key; // engine stores this in SecureStorage; field is wiped after.
- QString base_url; // optional override
-};
-
-/// User-facing config for create_competition().
-struct NewCompetitionConfig {
- QString name;
- CompetitionMode mode = CompetitionMode::Baseline;
- QString venue_kind = QStringLiteral("paper"); // "paper" | "hyperliquid"
- QStringList instruments; // subset of kPerpUniverse(); empty = all
- double initial_capital_per_agent = 10000.0;
- int cadence_seconds = 180;
- QVector<AgentSpec> agents;
- bool live_mode = false; // gated by UI; engine just records
-};
-
-class AlphaArenaEngine : public QObject {
- Q_OBJECT
- public:
- static AlphaArenaEngine& instance();
-
- /// One-time init at app startup. Idempotent. Safe to call before the
- /// user has navigated to the Alpha Arena screen.
- void init();
-
- // ── User-facing actions ────────────────────────────────────────────────
-
- /// Create a competition (status = "created"; not yet started).
- Result<QString> create_competition(NewCompetitionConfig cfg);
-
- /// Start ticking (status = "running").
- Result<void> start(const QString& competition_id);
-
- /// Stop ticking (status = "halted_by_user"); does NOT close positions.
- /// Use kill_all() for the panic-button semantics.
- Result<void> stop();
-
- /// Stop + close every agent's open positions (market IOC).
- Result<void> kill_all();
-
- /// Pause an individual agent. No further actions routed; existing
- /// positions stay open.
- Result<void> halt_agent(const QString& agent_id);
-
- /// Resume after circuit_open or manual halt.
- Result<void> resume_agent(const QString& agent_id);
-
- /// User UI -> approve/reject a pending HITL request.
- void resume_after_hitl(const QString& approval_id, bool approved);
-
- /// Hot-reload the active competition's tick cadence. Effective on the
- /// next natural tick fire (does not interrupt an in-flight tick). Also
- /// persisted on the competition row so a restart picks up the new value.
- Result<void> set_cadence(int seconds);
-
- // ── Test hooks (engine internals exposed for unit tests only) ──────────
- TickClock* test_clock() { return clock_; }
- ModelDispatcher* test_dispatcher() { return dispatcher_; }
- OrderRouter* test_router() { return router_; }
- PaperVenue* test_paper_venue() { return paper_venue_; }
-
- // ── Status / introspection ────────────────────────────────────────────
-
- QString active_competition_id() const { return active_competition_id_; }
- bool is_running() const;
- int last_tick_seq() const { return clock_ ? clock_->last_seq() : 0; }
- int next_tick_in_seconds() const;
- QString venue_kind() const { return venue_ ? venue_->venue_kind() : QString(); }
- IExchangeVenue::ConnectionState venue_connection_state() const;
-
- /// Rolling telemetry over the last 100 ticks. Surfaced in RiskPanel.
- struct TelemetrySnapshot {
- double tick_latency_p50_ms = 0.0;
- double tick_latency_p99_ms = 0.0;
- double parse_failure_rate = 0.0; // [0,1]
- double risk_rejection_rate = 0.0; // [0,1]
- int venue_errors = 0; // count over rolling window
- int sample_count = 0;
- };
- TelemetrySnapshot telemetry() const;
-
- signals:
- void tick_fired(int seq);
- void tick_skipped(int seq);
- void decision_received(QString decision_id, QString agent_id);
- void action_evaluated(QString agent_id, QString coin, int signal,
- int risk_outcome, QString reason);
- void order_placed(QString agent_id, QString order_id);
- void hitl_requested(QString approval_id, QString agent_id, QString summary);
- void agent_circuit_open(QString agent_id, QString reason);
- void competition_status_changed(QString competition_id, QString status);
- /// Emitted after init() finds competitions in `running` status. UI must
- /// surface a Resume / Halt / Reconcile prompt to the user.
- void crash_recovery_pending(QStringList competition_ids);
-
- private slots:
- void on_tick(fincept::services::alpha_arena::Tick t);
- void on_tick_skipped(int seq);
- void on_dispatch_complete(int seq);
- void on_decision_received(QString decision_id, QString agent_id,
- QVector<fincept::services::alpha_arena::ProposedAction> actions,
- QString parse_error);
- void on_circuit_open(QString agent_id, QString reason);
-
- private:
- AlphaArenaEngine();
- ~AlphaArenaEngine() override;
- AlphaArenaEngine(const AlphaArenaEngine&) = delete;
- AlphaArenaEngine& operator=(const AlphaArenaEngine&) = delete;
-
- /// Snapshot market + per-agent state for the next tick. Reads from venue
- /// for marks and from repo for positions/equity.
- void prepare_tick_inputs(const Tick& t,
- TickContext& ctx_out,
- QHash<QString, AgentAccountState>& per_agent_out,
- std::optional<SituationalContext>& situational_out);
-
- /// Detach the active competition (clears pointers, state).
- void detach_active();
-
- /// Pick a venue impl. v1: paper for venue_kind=="paper"; "hyperliquid"
- /// returns nullptr until Phase 5c lands.
- IExchangeVenue* select_venue_for_kind(const QString& venue_kind);
-
- static QString deterministic_agent_id(const QString& competition_id, int slot);
-
- bool inited_ = false;
- QString active_competition_id_;
- CompetitionMode active_mode_ = CompetitionMode::Baseline;
-
- TickClock* clock_ = nullptr;
- ModelDispatcher* dispatcher_ = nullptr;
- OrderRouter* router_ = nullptr;
-
- PaperVenue* paper_venue_ = nullptr;
- fincept::trading::hyperliquid::HyperliquidVenue* hl_venue_ = nullptr;
- IExchangeVenue* venue_ = nullptr; // alias to active venue
-};
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaJson.cpp b/fincept-qt/src/services/alpha_arena/AlphaArenaJson.cpp
deleted file mode 100644
index 23d9b5bc0..000000000
--- a/fincept-qt/src/services/alpha_arena/AlphaArenaJson.cpp
+++ /dev/null
@@ -1,182 +0,0 @@
-#include "services/alpha_arena/AlphaArenaJson.h"
-
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QJsonValue>
-#include <QRegularExpression>
-
-#include <algorithm>
-
-namespace fincept::services::alpha_arena {
-
-namespace {
-
-/// Find the outermost balanced {...} block in `text`. The model is told to
-/// emit JSON; in practice it sometimes wraps the JSON in markdown fences,
-/// prose, or trailing commentary. We scan for the first `{` and walk forward
-/// counting brace depth (skipping strings and escapes) to find the match.
-/// Returns empty QString on failure.
-QString extract_outer_json_object(const QString& text) {
- int start = -1;
- for (int i = 0; i < text.size(); ++i) {
- if (text.at(i) == QChar('{')) { start = i; break; }
- }
- if (start < 0) return {};
-
- int depth = 0;
- bool in_str = false;
- bool escape = false;
- for (int i = start; i < text.size(); ++i) {
- const QChar c = text.at(i);
- if (in_str) {
- if (escape) { escape = false; }
- else if (c == '\\') { escape = true; }
- else if (c == '"') { in_str = false; }
- continue;
- }
- if (c == '"') { in_str = true; continue; }
- if (c == '{') { ++depth; }
- else if (c == '}') {
- --depth;
- if (depth == 0) {
- return text.mid(start, i - start + 1);
- }
- }
- }
- return {};
-}
-
-bool is_known_coin(const QString& coin_upper) {
- return kPerpUniverse().contains(coin_upper);
-}
-
-double clamp_unit(double v) {
- if (v < 0.0) return 0.0;
- if (v > 1.0) return 1.0;
- return v;
-}
-
-int clamp_leverage(int v) {
- return std::clamp(v, limits::kMinLeverage, limits::kMaxLeverage);
-}
-
-QString truncate(QString s, int max_chars) {
- if (s.size() > max_chars) s.truncate(max_chars);
- return s;
-}
-
-/// Try to convert a value to its action representation. Returns nullopt if
-/// the action is irrecoverably malformed (caller appends a per-action note
-/// to the response's parse_error).
-std::optional<ProposedAction> action_from_json(const QJsonObject& obj, QString* defect) {
- ProposedAction a;
-
- const auto sig_opt = signal_from_wire(obj.value("signal").toString());
- if (!sig_opt) {
- if (defect) *defect = QStringLiteral("unknown signal");
- return std::nullopt;
- }
- a.signal = *sig_opt;
-
- a.coin = obj.value("coin").toString().toUpper();
- if (!is_known_coin(a.coin)) {
- if (defect) *defect = QStringLiteral("coin not in perp universe: ") + a.coin;
- return std::nullopt;
- }
-
- a.quantity = obj.value("quantity").toDouble(0.0);
- a.leverage = clamp_leverage(obj.value("leverage").toInt(1));
- a.profit_target = obj.value("profit_target").toDouble(0.0);
- a.stop_loss = obj.value("stop_loss").toDouble(0.0);
- a.invalidation_condition =
- truncate(obj.value("invalidation_condition").toString(),
- limits::kInvalidationConditionMaxChars);
- a.confidence = clamp_unit(obj.value("confidence").toDouble(0.0));
- a.risk_usd = obj.value("risk_usd").toDouble(0.0);
- a.justification =
- truncate(obj.value("justification").toString(), limits::kJustificationMaxChars);
-
- // Entry-signal-specific validation.
- const bool is_entry = (a.signal == Signal::BuyToEnter || a.signal == Signal::SellToEnter);
- if (is_entry) {
- if (a.quantity <= 0.0) {
- if (defect) *defect = QStringLiteral("entry signal requires quantity > 0");
- return std::nullopt;
- }
- if (a.profit_target <= 0.0 || a.stop_loss <= 0.0) {
- if (defect) *defect = QStringLiteral("entry signal requires profit_target and stop_loss > 0");
- return std::nullopt;
- }
- }
-
- return a;
-}
-
-} // namespace
-
-ModelResponse parse_model_response(const QString& raw_text) {
- ModelResponse out;
- out.raw_text = raw_text;
-
- const QString json_text = extract_outer_json_object(raw_text);
- if (json_text.isEmpty()) {
- out.parse_error = QStringLiteral("no JSON object found in model output");
- return out;
- }
-
- QJsonParseError err;
- const auto doc = QJsonDocument::fromJson(json_text.toUtf8(), &err);
- if (doc.isNull() || !doc.isObject()) {
- out.parse_error = QStringLiteral("invalid JSON: ") + err.errorString();
- return out;
- }
-
- const QJsonObject root = doc.object();
- const QJsonValue actions_val = root.value("actions");
- if (!actions_val.isArray()) {
- out.parse_error = QStringLiteral("missing or non-array \"actions\" field");
- return out;
- }
-
- QStringList per_action_defects;
- for (const auto& v : actions_val.toArray()) {
- if (!v.isObject()) {
- per_action_defects << QStringLiteral("non-object action entry");
- continue;
- }
- QString defect;
- if (auto a = action_from_json(v.toObject(), &defect)) {
- out.actions.append(*a);
- } else if (!defect.isEmpty()) {
- per_action_defects << defect;
- }
- }
-
- if (out.actions.isEmpty() && !per_action_defects.isEmpty()) {
- out.parse_error = QStringLiteral("no valid actions: ") + per_action_defects.join(QStringLiteral("; "));
- } else if (!per_action_defects.isEmpty()) {
- // Some survived — surface the partial defect set so the audit trail
- // shows which actions were dropped, but still return the survivors.
- out.parse_error =
- QStringLiteral("partial: ") + per_action_defects.join(QStringLiteral("; "));
- }
-
- return out;
-}
-
-QJsonObject action_to_json(const ProposedAction& a) {
- QJsonObject o;
- o["signal"] = signal_to_wire(a.signal);
- o["coin"] = a.coin;
- o["quantity"] = a.quantity;
- o["leverage"] = a.leverage;
- o["profit_target"] = a.profit_target;
- o["stop_loss"] = a.stop_loss;
- o["invalidation_condition"] = a.invalidation_condition;
- o["confidence"] = a.confidence;
- o["risk_usd"] = a.risk_usd;
- o["justification"] = a.justification;
- return o;
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaJson.h b/fincept-qt/src/services/alpha_arena/AlphaArenaJson.h
deleted file mode 100644
index 5ad37614c..000000000
--- a/fincept-qt/src/services/alpha_arena/AlphaArenaJson.h
+++ /dev/null
@@ -1,43 +0,0 @@
-#pragma once
-// AlphaArenaJson — strict parsers between LLM wire format and the
-// canonical schema (AlphaArenaSchema.h).
-//
-// Parse failures are *expected* and benign — Nof1 spec says "no retry,
-// log a no-op tick". So parse_model_response() never throws; it always
-// returns a ModelResponse, with parse_error set on any defect.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §5.4 (Parse failures).
-
-#include "services/alpha_arena/AlphaArenaSchema.h"
-
-#include <QJsonObject>
-#include <QString>
-
-namespace fincept::services::alpha_arena {
-
-/// Parse the model's raw completion. The model is asked to emit a JSON object
-/// of the form {"actions": [...]} possibly wrapped in a fenced code block. We
-/// extract the outermost {...}, validate each action against the schema, and
-/// return a ModelResponse. Multiple actions per tick are allowed.
-///
-/// Validation rules (fail-closed — defective action drops, others survive):
-/// * `signal` must round-trip through signal_from_wire().
-/// * `coin` must be in kPerpUniverse() (case-insensitive; normalised upper).
-/// * `leverage` is clamped into [kMinLeverage, kMaxLeverage] silently.
-/// * `quantity` must be > 0 for entry signals; ignored for hold/close.
-/// * `confidence` is clamped into [0, 1].
-/// * `invalidation_condition` truncated to kInvalidationConditionMaxChars.
-/// * `justification` truncated to kJustificationMaxChars.
-/// * `profit_target` and `stop_loss` must be > 0 for entry signals;
-/// if missing or zero on entries, the action is dropped with a
-/// per-action note appended to parse_error (other actions still survive).
-///
-/// If the wrapping JSON itself is malformed, all actions are dropped and
-/// `parse_error` describes the failure.
-ModelResponse parse_model_response(const QString& raw_text);
-
-/// Serialise one ProposedAction back to a JSON object — the form a model
-/// would have emitted. Used in tests, ModelChat replay, and audit log.
-QJsonObject action_to_json(const ProposedAction& a);
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaRepo.cpp b/fincept-qt/src/services/alpha_arena/AlphaArenaRepo.cpp
deleted file mode 100644
index 5b951f9fc..000000000
--- a/fincept-qt/src/services/alpha_arena/AlphaArenaRepo.cpp
+++ /dev/null
@@ -1,593 +0,0 @@
-#include "services/alpha_arena/AlphaArenaRepo.h"
-
-#include "core/logging/Logger.h"
-#include "storage/sqlite/Database.h"
-
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QSqlQuery>
-#include <QUuid>
-#include <QVariantList>
-
-namespace fincept::services::alpha_arena {
-
-namespace {
-
-inline Database& db() { return Database::instance(); }
-
-QString new_id() {
- return QUuid::createUuid().toString(QUuid::WithoutBraces);
-}
-
-QString json_compact(const QJsonObject& obj) {
- return QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Compact));
-}
-
-QString string_list_to_json(const QStringList& list) {
- QJsonArray arr;
- for (const auto& s : list) arr.append(s);
- return QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact));
-}
-
-QStringList json_to_string_list(const QString& s) {
- auto doc = QJsonDocument::fromJson(s.toUtf8());
- if (!doc.isArray()) return {};
- QStringList out;
- for (const auto& v : doc.array()) out << v.toString();
- return out;
-}
-
-// Common LOG_ERROR shape used when an INSERT/UPDATE fails. The Result is then
-// returned to the caller, which decides whether to retry / give up / surface.
-template <typename T>
-Result<T> log_and_forward_err(const QString& op, const std::string& msg) {
- LOG_ERROR("AlphaArenaRepo", QString("%1: %2").arg(op, QString::fromStdString(msg)));
- return Result<T>::err(msg);
-}
-
-} // namespace
-
-AlphaArenaRepo& AlphaArenaRepo::instance() {
- static AlphaArenaRepo s;
- return s;
-}
-
-// ─── Competitions ───────────────────────────────────────────────────────────
-
-Result<void> AlphaArenaRepo::insert_competition(const CompetitionRow& comp) {
- auto r = db().execute(
- QStringLiteral("INSERT INTO aa_competitions "
- "(id,name,mode,venue,instruments_json,initial_capital,"
- " cadence_seconds,live_mode,status) "
- "VALUES (?,?,?,?,?,?,?,?,?)"),
- {comp.id, comp.name, mode_to_wire(comp.mode), comp.venue,
- string_list_to_json(comp.instruments), comp.initial_capital,
- comp.cadence_seconds, comp.live_mode ? 1 : 0,
- comp.status.isEmpty() ? QStringLiteral("created") : comp.status});
- if (r.is_err()) return log_and_forward_err<void>("insert_competition", r.error());
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaRepo::update_competition_cadence(const QString& id, int cadence_seconds) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_competitions SET cadence_seconds=? WHERE id=?"),
- {cadence_seconds, id});
- if (r.is_err()) return log_and_forward_err<void>("update_competition_cadence", r.error());
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaRepo::update_competition_status(const QString& id, const QString& status) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_competitions SET status=?, "
- "started_at=CASE WHEN status='created' AND ?='running' "
- " THEN CURRENT_TIMESTAMP ELSE started_at END, "
- "ended_at=CASE WHEN ? IN ('halted_by_user','halted_by_crash','completed','failed') "
- " THEN CURRENT_TIMESTAMP ELSE ended_at END "
- "WHERE id=?"),
- {status, status, status, id});
- if (r.is_err()) return log_and_forward_err<void>("update_competition_status", r.error());
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaRepo::mark_live_mode_ack(const QString& id, const QString& host) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_competitions SET live_mode_acked_at=CURRENT_TIMESTAMP, "
- "live_mode_acked_host=? WHERE id=?"),
- {host, id});
- if (r.is_err()) return log_and_forward_err<void>("mark_live_mode_ack", r.error());
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaRepo::increment_cycle_count(const QString& id) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_competitions SET cycle_count=cycle_count+1 WHERE id=?"), {id});
- if (r.is_err()) return log_and_forward_err<void>("increment_cycle_count", r.error());
- return Result<void>::ok();
-}
-
-namespace {
-CompetitionRow row_to_competition(QSqlQuery& q) {
- CompetitionRow c;
- c.id = q.value("id").toString();
- c.name = q.value("name").toString();
- if (auto m = mode_from_wire(q.value("mode").toString())) c.mode = *m;
- c.venue = q.value("venue").toString();
- c.instruments = json_to_string_list(q.value("instruments_json").toString());
- c.initial_capital = q.value("initial_capital").toDouble();
- c.cadence_seconds = q.value("cadence_seconds").toInt();
- c.live_mode = q.value("live_mode").toInt() != 0;
- c.status = q.value("status").toString();
- c.cycle_count = q.value("cycle_count").toInt();
- c.created_at = q.value("created_at").toString();
- c.started_at = q.value("started_at").toString();
- c.ended_at = q.value("ended_at").toString();
- return c;
-}
-} // namespace
-
-std::optional<CompetitionRow> AlphaArenaRepo::find_competition(const QString& id) {
- auto r = db().execute(
- QStringLiteral("SELECT id,name,mode,venue,instruments_json,initial_capital,"
- "cadence_seconds,live_mode,status,cycle_count,created_at,started_at,ended_at "
- "FROM aa_competitions WHERE id=?"),
- {id});
- if (r.is_err()) return std::nullopt;
- auto& q = r.value();
- if (!q.next()) return std::nullopt;
- return row_to_competition(q);
-}
-
-Result<QVector<CompetitionRow>> AlphaArenaRepo::list_competitions(int limit) {
- auto r = db().execute(
- QStringLiteral("SELECT id,name,mode,venue,instruments_json,initial_capital,"
- "cadence_seconds,live_mode,status,cycle_count,created_at,started_at,ended_at "
- "FROM aa_competitions ORDER BY created_at DESC LIMIT ?"),
- {limit});
- if (r.is_err()) return log_and_forward_err<QVector<CompetitionRow>>("list_competitions", r.error());
- QVector<CompetitionRow> out;
- auto& q = r.value();
- while (q.next()) out.append(row_to_competition(q));
- return Result<QVector<CompetitionRow>>::ok(std::move(out));
-}
-
-Result<QVector<CompetitionRow>> AlphaArenaRepo::find_orphaned_running() {
- auto r = db().execute(
- QStringLiteral("SELECT id,name,mode,venue,instruments_json,initial_capital,"
- "cadence_seconds,live_mode,status,cycle_count,created_at,started_at,ended_at "
- "FROM aa_competitions WHERE status='running'"),
- {});
- if (r.is_err()) return log_and_forward_err<QVector<CompetitionRow>>("find_orphaned_running", r.error());
- QVector<CompetitionRow> out;
- auto& q = r.value();
- while (q.next()) out.append(row_to_competition(q));
- return Result<QVector<CompetitionRow>>::ok(std::move(out));
-}
-
-// ─── Agents ─────────────────────────────────────────────────────────────────
-
-Result<void> AlphaArenaRepo::insert_agent(const AgentRow& agent) {
- auto r = db().execute(
- QStringLiteral("INSERT INTO aa_agents "
- "(id,competition_id,slot,provider,model_id,display_name,color_hex,"
- " api_secret_handle,state) "
- "VALUES (?,?,?,?,?,?,?,?,?)"),
- {agent.id, agent.competition_id, agent.slot, agent.provider, agent.model_id,
- agent.display_name, agent.color_hex, agent.api_secret_handle,
- agent.state.isEmpty() ? QStringLiteral("active") : agent.state});
- if (r.is_err()) return log_and_forward_err<void>("insert_agent", r.error());
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaRepo::update_agent_state(const QString& id, const QString& state) {
- auto r = db().execute(QStringLiteral("UPDATE aa_agents SET state=? WHERE id=?"), {state, id});
- if (r.is_err()) return log_and_forward_err<void>("update_agent_state", r.error());
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaRepo::bump_parse_failures(const QString& agent_id, int new_value) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_agents SET consecutive_parse_failures=? WHERE id=?"),
- {new_value, agent_id});
- if (r.is_err()) return log_and_forward_err<void>("bump_parse_failures", r.error());
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaRepo::bump_risk_rejects(const QString& agent_id, int new_value) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_agents SET consecutive_risk_rejects=? WHERE id=?"),
- {new_value, agent_id});
- if (r.is_err()) return log_and_forward_err<void>("bump_risk_rejects", r.error());
- return Result<void>::ok();
-}
-
-namespace {
-AgentRow row_to_agent(QSqlQuery& q) {
- AgentRow a;
- a.id = q.value("id").toString();
- a.competition_id = q.value("competition_id").toString();
- a.slot = q.value("slot").toInt();
- a.provider = q.value("provider").toString();
- a.model_id = q.value("model_id").toString();
- a.display_name = q.value("display_name").toString();
- a.color_hex = q.value("color_hex").toString();
- a.api_secret_handle = q.value("api_secret_handle").toString();
- a.state = q.value("state").toString();
- a.consecutive_parse_failures = q.value("consecutive_parse_failures").toInt();
- a.consecutive_risk_rejects = q.value("consecutive_risk_rejects").toInt();
- return a;
-}
-} // namespace
-
-Result<QVector<AgentRow>> AlphaArenaRepo::agents_for(const QString& competition_id) {
- auto r = db().execute(
- QStringLiteral("SELECT id,competition_id,slot,provider,model_id,display_name,color_hex,"
- "api_secret_handle,state,consecutive_parse_failures,consecutive_risk_rejects "
- "FROM aa_agents WHERE competition_id=? ORDER BY slot"),
- {competition_id});
- if (r.is_err()) return log_and_forward_err<QVector<AgentRow>>("agents_for", r.error());
- QVector<AgentRow> out;
- auto& q = r.value();
- while (q.next()) out.append(row_to_agent(q));
- return Result<QVector<AgentRow>>::ok(std::move(out));
-}
-
-std::optional<AgentRow> AlphaArenaRepo::find_agent(const QString& id) {
- auto r = db().execute(
- QStringLiteral("SELECT id,competition_id,slot,provider,model_id,display_name,color_hex,"
- "api_secret_handle,state,consecutive_parse_failures,consecutive_risk_rejects "
- "FROM aa_agents WHERE id=?"),
- {id});
- if (r.is_err()) return std::nullopt;
- auto& q = r.value();
- if (!q.next()) return std::nullopt;
- return row_to_agent(q);
-}
-
-// ─── Prompts ────────────────────────────────────────────────────────────────
-
-Result<void> AlphaArenaRepo::upsert_prompt(const QString& sha256, const QString& text) {
- auto r = db().execute(
- QStringLiteral("INSERT OR IGNORE INTO aa_prompts (sha256,length,text) VALUES (?,?,?)"),
- {sha256, text.size(), text});
- if (r.is_err()) return log_and_forward_err<void>("upsert_prompt", r.error());
- return Result<void>::ok();
-}
-
-// ─── Ticks ──────────────────────────────────────────────────────────────────
-
-Result<QString> AlphaArenaRepo::insert_tick(const QString& competition_id,
- int seq,
- qint64 utc_ms,
- const QString& system_prompt_sha256,
- const QString& market_snapshot_json) {
- const QString id = new_id();
- auto r = db().execute(
- QStringLiteral("INSERT INTO aa_ticks "
- "(id,competition_id,seq,utc_ms,system_prompt_sha256,market_snapshot_json) "
- "VALUES (?,?,?,?,?,?)"),
- {id, competition_id, seq, utc_ms, system_prompt_sha256, market_snapshot_json});
- if (r.is_err()) return log_and_forward_err<QString>("insert_tick", r.error());
- return Result<QString>::ok(id);
-}
-
-Result<void> AlphaArenaRepo::close_tick(const QString& tick_id) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_ticks SET status='closed', closed_at=CURRENT_TIMESTAMP WHERE id=?"),
- {tick_id});
- if (r.is_err()) return log_and_forward_err<void>("close_tick", r.error());
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaRepo::mark_tick_skipped(const QString& tick_id) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_ticks SET status='skipped' WHERE id=?"), {tick_id});
- if (r.is_err()) return log_and_forward_err<void>("mark_tick_skipped", r.error());
- return Result<void>::ok();
-}
-
-// ─── Decisions ──────────────────────────────────────────────────────────────
-
-Result<QString> AlphaArenaRepo::insert_decision(const DecisionInsert& d) {
- const QString id = new_id();
- auto r = db().execute(
- QStringLiteral("INSERT INTO aa_decisions "
- "(id,tick_id,agent_id,user_prompt_sha256,raw_response,parsed_actions_json,"
- " parse_error,risk_verdict_json,latency_ms,tokens_in,tokens_out,cost_usd) "
- "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"),
- {id, d.tick_id, d.agent_id, d.user_prompt_sha256, d.raw_response,
- d.parsed_actions_json, d.parse_error, d.risk_verdict_json,
- d.latency_ms, d.tokens_in, d.tokens_out, d.cost_usd});
- if (r.is_err()) return log_and_forward_err<QString>("insert_decision", r.error());
- return Result<QString>::ok(id);
-}
-
-Result<QVector<ModelChatRow>> AlphaArenaRepo::modelchat_for(const QString& competition_id,
- const QString& agent_id,
- int limit,
- int offset) {
- auto r = db().execute(
- QStringLiteral("SELECT d.id, d.agent_id, d.tick_id, t.seq, t.utc_ms, "
- " d.user_prompt_sha256, d.raw_response, d.parsed_actions_json, "
- " d.parse_error, d.risk_verdict_json, d.latency_ms, "
- " d.tokens_in, d.tokens_out, d.cost_usd "
- "FROM aa_decisions d JOIN aa_ticks t ON t.id = d.tick_id "
- "WHERE t.competition_id=? AND d.agent_id=? "
- "ORDER BY t.seq DESC LIMIT ? OFFSET ?"),
- {competition_id, agent_id, limit, offset});
- if (r.is_err()) return log_and_forward_err<QVector<ModelChatRow>>("modelchat_for", r.error());
- QVector<ModelChatRow> out;
- auto& q = r.value();
- while (q.next()) {
- ModelChatRow row;
- row.decision_id = q.value(0).toString();
- row.agent_id = q.value(1).toString();
- row.tick_id = q.value(2).toString();
- row.tick_seq = q.value(3).toInt();
- row.tick_utc_ms = q.value(4).toLongLong();
- row.user_prompt_sha256 = q.value(5).toString();
- row.raw_response = q.value(6).toString();
- row.parsed_actions_json = q.value(7).toString();
- row.parse_error = q.value(8).toString();
- row.risk_verdict_json = q.value(9).toString();
- row.latency_ms = q.value(10).toInt();
- row.tokens_in = q.value(11).toInt();
- row.tokens_out = q.value(12).toInt();
- row.cost_usd = q.value(13).toDouble();
- out.append(row);
- }
- return Result<QVector<ModelChatRow>>::ok(std::move(out));
-}
-
-// ─── Orders ─────────────────────────────────────────────────────────────────
-
-Result<QString> AlphaArenaRepo::insert_order(const OrderInsert& o) {
- const QString id = new_id();
- auto r = db().execute(
- QStringLiteral("INSERT INTO aa_orders "
- "(id,decision_id,agent_id,competition_id,coin,side,qty,leverage,type,tif,price) "
- "VALUES (?,?,?,?,?,?,?,?,?,?,?)"),
- {id, o.decision_id, o.agent_id, o.competition_id, o.coin, o.side, o.qty,
- o.leverage, o.type, o.tif, o.price.has_value() ? *o.price : QVariant()});
- if (r.is_err()) return log_and_forward_err<QString>("insert_order", r.error());
- return Result<QString>::ok(id);
-}
-
-Result<void> AlphaArenaRepo::mark_order_status(const QString& order_id,
- const QString& status,
- const QString& venue_order_id,
- const QString& error) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_orders SET status=?, venue_order_id=?, error=?, "
- "resolved_at=CASE WHEN ? IN ('filled','rejected','cancelled') "
- " THEN CURRENT_TIMESTAMP ELSE resolved_at END "
- "WHERE id=?"),
- {status, venue_order_id, error, status, order_id});
- if (r.is_err()) return log_and_forward_err<void>("mark_order_status", r.error());
- return Result<void>::ok();
-}
-
-// ─── Fills ──────────────────────────────────────────────────────────────────
-
-Result<QString> AlphaArenaRepo::insert_fill(const QString& order_id,
- double qty, double price, double fee) {
- const QString id = new_id();
- auto r = db().execute(
- QStringLiteral("INSERT INTO aa_fills (id,order_id,qty,price,fee) VALUES (?,?,?,?,?)"),
- {id, order_id, qty, price, fee});
- if (r.is_err()) return log_and_forward_err<QString>("insert_fill", r.error());
- return Result<QString>::ok(id);
-}
-
-// ─── Positions ──────────────────────────────────────────────────────────────
-
-Result<QString> AlphaArenaRepo::open_position(const QString& agent_id,
- const QString& competition_id,
- const Position& p) {
- const QString id = new_id();
- auto r = db().execute(
- QStringLiteral("INSERT INTO aa_positions "
- "(id,agent_id,competition_id,coin,qty,entry,mark,liq_price,leverage,"
- " profit_target,stop_loss,invalidation_condition) "
- "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"),
- {id, agent_id, competition_id, p.coin, p.qty, p.entry, p.mark, p.liq_price,
- p.leverage, p.profit_target, p.stop_loss, p.invalidation_condition});
- if (r.is_err()) return log_and_forward_err<QString>("open_position", r.error());
- return Result<QString>::ok(id);
-}
-
-Result<void> AlphaArenaRepo::update_position_marks(const QString& position_id,
- double mark, double liq_price) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_positions SET mark=?, liq_price=? WHERE id=?"),
- {mark, liq_price, position_id});
- if (r.is_err()) return log_and_forward_err<void>("update_position_marks", r.error());
- return Result<void>::ok();
-}
-
-Result<void> AlphaArenaRepo::close_position(const QString& position_id, const QString& reason) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_positions SET closed_at=CURRENT_TIMESTAMP, close_reason=? "
- "WHERE id=? AND closed_at IS NULL"),
- {reason, position_id});
- if (r.is_err()) return log_and_forward_err<void>("close_position", r.error());
- return Result<void>::ok();
-}
-
-Result<QVector<Position>> AlphaArenaRepo::open_positions_for(const QString& agent_id) {
- auto r = db().execute(
- QStringLiteral("SELECT coin,qty,entry,mark,liq_price,leverage,"
- "profit_target,stop_loss,invalidation_condition "
- "FROM aa_positions WHERE agent_id=? AND closed_at IS NULL"),
- {agent_id});
- if (r.is_err()) return log_and_forward_err<QVector<Position>>("open_positions_for", r.error());
- QVector<Position> out;
- auto& q = r.value();
- while (q.next()) {
- Position p;
- p.coin = q.value(0).toString();
- p.qty = q.value(1).toDouble();
- p.entry = q.value(2).toDouble();
- p.mark = q.value(3).toDouble();
- p.liq_price = q.value(4).toDouble();
- p.leverage = q.value(5).toInt();
- p.profit_target = q.value(6).toDouble();
- p.stop_loss = q.value(7).toDouble();
- p.invalidation_condition = q.value(8).toString();
- // unrealized_pnl computed on demand by caller from mark vs entry
- out.append(p);
- }
- return Result<QVector<Position>>::ok(std::move(out));
-}
-
-// ─── PnL snapshots ──────────────────────────────────────────────────────────
-
-Result<void> AlphaArenaRepo::insert_pnl_snapshot(const QString& tick_id,
- const QString& agent_id,
- const AgentAccountState& s,
- double avg_leverage) {
- const QString id = new_id();
- auto r = db().execute(
- QStringLiteral("INSERT INTO aa_pnl_snapshots "
- "(id,tick_id,agent_id,equity,cash,return_pct,sharpe,max_drawdown,"
- " fees_paid,win_rate,trades_count,avg_leverage) "
- "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"),
- {id, tick_id, agent_id, s.equity, s.cash, s.return_pct, s.sharpe, s.max_drawdown,
- s.fees_paid, s.win_rate, s.trades_count, avg_leverage});
- if (r.is_err()) return log_and_forward_err<void>("insert_pnl_snapshot", r.error());
- return Result<void>::ok();
-}
-
-Result<QVector<LeaderboardRow>> AlphaArenaRepo::leaderboard(const QString& competition_id) {
- // Latest snapshot per agent in this competition (rank by equity DESC).
- auto r = db().execute(
- QStringLiteral(
- "WITH latest AS ("
- " SELECT s.*, ROW_NUMBER() OVER (PARTITION BY s.agent_id ORDER BY s.created_at DESC) rn"
- " FROM aa_pnl_snapshots s"
- " JOIN aa_agents a ON a.id=s.agent_id"
- " WHERE a.competition_id=?"
- ")"
- "SELECT a.id, a.display_name, a.color_hex, "
- " l.equity, l.return_pct, l.sharpe, l.max_drawdown, l.fees_paid, "
- " l.avg_leverage, l.trades_count, l.win_rate "
- "FROM aa_agents a "
- "LEFT JOIN latest l ON l.agent_id=a.id AND l.rn=1 "
- "WHERE a.competition_id=? "
- "ORDER BY COALESCE(l.equity, 0) DESC, COALESCE(l.sharpe, 0) DESC"),
- {competition_id, competition_id});
- if (r.is_err()) return log_and_forward_err<QVector<LeaderboardRow>>("leaderboard", r.error());
-
- QVector<LeaderboardRow> out;
- auto& q = r.value();
- int rank = 1;
- while (q.next()) {
- LeaderboardRow lr;
- lr.agent_id = q.value(0).toString();
- lr.display_name = q.value(1).toString();
- lr.color_hex = q.value(2).toString();
- lr.rank = rank++;
- lr.equity = q.value(3).toDouble();
- lr.return_pct = q.value(4).toDouble();
- lr.sharpe = q.value(5).toDouble();
- lr.max_drawdown = q.value(6).toDouble();
- lr.fees_paid = q.value(7).toDouble();
- lr.avg_leverage = q.value(8).toDouble();
- lr.trades_count = q.value(9).toInt();
- lr.win_rate = q.value(10).toDouble();
- out.append(lr);
- }
- return Result<QVector<LeaderboardRow>>::ok(std::move(out));
-}
-
-// ─── Events ─────────────────────────────────────────────────────────────────
-
-Result<void> AlphaArenaRepo::append_event(const QString& competition_id,
- const QString& agent_id,
- const QString& type,
- const QJsonObject& payload) {
- auto r = db().execute(
- QStringLiteral("INSERT INTO aa_events (competition_id,agent_id,type,payload_json) "
- "VALUES (?,?,?,?)"),
- {competition_id, agent_id.isEmpty() ? QVariant() : QVariant(agent_id),
- type, json_compact(payload)});
- if (r.is_err()) return log_and_forward_err<void>("append_event", r.error());
- return Result<void>::ok();
-}
-
-Result<QVector<EventRow>> AlphaArenaRepo::events_since(const QString& competition_id,
- qint64 since_seq, int limit) {
- auto r = db().execute(
- QStringLiteral("SELECT seq,competition_id,COALESCE(agent_id,''),type,payload_json,ts "
- "FROM aa_events WHERE competition_id=? AND seq>? "
- "ORDER BY seq ASC LIMIT ?"),
- {competition_id, since_seq, limit});
- if (r.is_err()) return log_and_forward_err<QVector<EventRow>>("events_since", r.error());
- QVector<EventRow> out;
- auto& q = r.value();
- while (q.next()) {
- EventRow e;
- e.seq = q.value(0).toLongLong();
- e.competition_id = q.value(1).toString();
- e.agent_id = q.value(2).toString();
- e.type = q.value(3).toString();
- e.payload_json = q.value(4).toString();
- e.ts = q.value(5).toString();
- out.append(e);
- }
- return Result<QVector<EventRow>>::ok(std::move(out));
-}
-
-// ─── HITL ───────────────────────────────────────────────────────────────────
-
-Result<QString> AlphaArenaRepo::request_hitl(const QString& decision_id,
- const QString& agent_id,
- const QJsonObject& action,
- const QString& prompt_text) {
- const QString id = new_id();
- auto r = db().execute(
- QStringLiteral("INSERT INTO aa_hitl_approvals "
- "(id,decision_id,agent_id,action_json,prompt_text) VALUES (?,?,?,?,?)"),
- {id, decision_id, agent_id, json_compact(action), prompt_text});
- if (r.is_err()) return log_and_forward_err<QString>("request_hitl", r.error());
- return Result<QString>::ok(id);
-}
-
-Result<void> AlphaArenaRepo::resolve_hitl(const QString& approval_id,
- const QString& status,
- const QString& resolved_by) {
- auto r = db().execute(
- QStringLiteral("UPDATE aa_hitl_approvals SET status=?, resolved_at=CURRENT_TIMESTAMP, "
- "resolved_by=? WHERE id=?"),
- {status, resolved_by, approval_id});
- if (r.is_err()) return log_and_forward_err<void>("resolve_hitl", r.error());
- return Result<void>::ok();
-}
-
-Result<QVector<AlphaArenaRepo::PendingHitlRow>>
-AlphaArenaRepo::pending_hitl_for(const QString& competition_id) {
- auto r = db().execute(
- QStringLiteral(
- "SELECT h.id, h.agent_id, h.prompt_text, h.action_json, h.requested_at "
- "FROM aa_hitl_approvals h "
- "JOIN aa_decisions d ON d.id = h.decision_id "
- "JOIN aa_ticks t ON t.id = d.tick_id "
- "WHERE t.competition_id=? AND h.status='pending' "
- "ORDER BY h.requested_at ASC"),
- {competition_id});
- if (r.is_err()) return log_and_forward_err<QVector<PendingHitlRow>>(
- "pending_hitl_for", r.error());
- QVector<PendingHitlRow> out;
- auto& q = r.value();
- while (q.next()) {
- PendingHitlRow row;
- row.approval_id = q.value(0).toString();
- row.agent_id = q.value(1).toString();
- row.prompt_text = q.value(2).toString();
- row.action_json = q.value(3).toString();
- row.requested_at = q.value(4).toString();
- out.append(row);
- }
- return Result<QVector<PendingHitlRow>>::ok(out);
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaRepo.h b/fincept-qt/src/services/alpha_arena/AlphaArenaRepo.h
deleted file mode 100644
index 466de2c09..000000000
--- a/fincept-qt/src/services/alpha_arena/AlphaArenaRepo.h
+++ /dev/null
@@ -1,234 +0,0 @@
-#pragma once
-// AlphaArenaRepo — single facade over the aa_* tables.
-//
-// Unlike most fincept repos, this one is a *facade* — one class with methods
-// for every aa_* table — rather than one class per table. The Alpha Arena
-// engine writes coherent groups (tick + N decisions + M orders + fills +
-// position deltas + pnl snapshots) within tight time windows, and a single
-// facade keeps the call graph readable and groups indexes by purpose.
-//
-// All write methods return Result<QString> with the inserted id (TEXT PK)
-// for new rows, or Result<void> for updates.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-production-refactor.md §Phase 4
-// and the v024_alpha_arena migration for column definitions.
-
-#include "core/result/Result.h"
-#include "services/alpha_arena/AlphaArenaSchema.h"
-#include "services/alpha_arena/AlphaArenaTypes.h"
-
-#include <QJsonObject>
-#include <QString>
-#include <QStringList>
-#include <QVector>
-
-#include <optional>
-
-namespace fincept::services::alpha_arena {
-
-// ─── Read-side row structs ─────────────────────────────────────────────────
-
-struct CompetitionRow {
- QString id;
- QString name;
- CompetitionMode mode = CompetitionMode::Baseline;
- QString venue; // "paper" | "hyperliquid"
- QStringList instruments;
- double initial_capital = 10000.0;
- int cadence_seconds = 180;
- bool live_mode = false;
- QString status; // see migration enum comment
- int cycle_count = 0;
- QString created_at;
- QString started_at;
- QString ended_at;
-};
-
-struct AgentRow {
- QString id;
- QString competition_id;
- int slot = 0;
- QString provider;
- QString model_id;
- QString display_name;
- QString color_hex;
- QString api_secret_handle;
- QString state; // active|paused|circuit_open|halted
- int consecutive_parse_failures = 0;
- int consecutive_risk_rejects = 0;
-};
-
-struct LeaderboardRow {
- QString agent_id;
- QString display_name;
- QString color_hex;
- int rank = 0;
- double equity = 0.0;
- double return_pct = 0.0;
- double sharpe = 0.0;
- double max_drawdown = 0.0;
- double fees_paid = 0.0;
- double avg_leverage = 0.0;
- int trades_count = 0;
- double win_rate = 0.0;
-};
-
-struct ModelChatRow {
- QString decision_id;
- QString agent_id;
- QString tick_id;
- int tick_seq = 0;
- qint64 tick_utc_ms = 0;
- QString user_prompt_sha256;
- QString raw_response;
- QString parsed_actions_json;
- QString parse_error;
- QString risk_verdict_json;
- int latency_ms = 0;
- int tokens_in = 0;
- int tokens_out = 0;
- double cost_usd = 0.0;
-};
-
-struct EventRow {
- qint64 seq = 0;
- QString competition_id;
- QString agent_id;
- QString type;
- QString payload_json;
- QString ts;
-};
-
-// ─── Repo facade ────────────────────────────────────────────────────────────
-
-class AlphaArenaRepo {
- public:
- static AlphaArenaRepo& instance();
-
- // ── Competitions ────────────────────────────────────────────────────────
- /// Persist a new competition. Caller supplies the id (Qt QUuid).
- /// `instruments` is the perp universe for this run (subset of kPerpUniverse()).
- Result<void> insert_competition(const CompetitionRow& comp);
- Result<void> update_competition_status(const QString& id, const QString& status);
- Result<void> update_competition_cadence(const QString& id, int cadence_seconds);
- Result<void> mark_live_mode_ack(const QString& id, const QString& host);
- Result<void> increment_cycle_count(const QString& id);
- std::optional<CompetitionRow> find_competition(const QString& id);
- Result<QVector<CompetitionRow>> list_competitions(int limit);
- /// Returns competitions that were running when the app was last killed.
- Result<QVector<CompetitionRow>> find_orphaned_running();
-
- // ── Agents ─────────────────────────────────────────────────────────────
- Result<void> insert_agent(const AgentRow& agent);
- Result<void> update_agent_state(const QString& id, const QString& state);
- Result<void> bump_parse_failures(const QString& agent_id, int new_value);
- Result<void> bump_risk_rejects(const QString& agent_id, int new_value);
- Result<QVector<AgentRow>> agents_for(const QString& competition_id);
- std::optional<AgentRow> find_agent(const QString& id);
-
- // ── Prompts (content-addressed) ────────────────────────────────────────
- /// INSERT OR IGNORE — returns ok regardless. Pass the canonical sha256 of
- /// the prompt text in lowercase hex (caller computes it).
- Result<void> upsert_prompt(const QString& sha256, const QString& text);
-
- // ── Ticks ───────────────────────────────────────────────────────────────
- /// Returns the inserted tick id (TEXT PK).
- Result<QString> insert_tick(const QString& competition_id,
- int seq,
- qint64 utc_ms,
- const QString& system_prompt_sha256,
- const QString& market_snapshot_json);
- Result<void> close_tick(const QString& tick_id);
- Result<void> mark_tick_skipped(const QString& tick_id);
-
- // ── Decisions ───────────────────────────────────────────────────────────
- struct DecisionInsert {
- QString tick_id;
- QString agent_id;
- QString user_prompt_sha256;
- QString raw_response;
- QString parsed_actions_json;
- QString parse_error;
- QString risk_verdict_json;
- int latency_ms = 0;
- int tokens_in = 0;
- int tokens_out = 0;
- double cost_usd = 0.0;
- };
- Result<QString> insert_decision(const DecisionInsert& d);
- Result<QVector<ModelChatRow>> modelchat_for(const QString& competition_id,
- const QString& agent_id,
- int limit,
- int offset);
-
- // ── Orders ──────────────────────────────────────────────────────────────
- struct OrderInsert {
- QString decision_id;
- QString agent_id;
- QString competition_id;
- QString coin;
- QString side;
- double qty = 0.0;
- int leverage = 1;
- QString type = QStringLiteral("market");
- QString tif = QStringLiteral("ioc");
- std::optional<double> price;
- };
- Result<QString> insert_order(const OrderInsert& o);
- Result<void> mark_order_status(const QString& order_id,
- const QString& status,
- const QString& venue_order_id,
- const QString& error);
-
- // ── Fills ───────────────────────────────────────────────────────────────
- Result<QString> insert_fill(const QString& order_id, double qty, double price, double fee);
-
- // ── Positions ──────────────────────────────────────────────────────────
- Result<QString> open_position(const QString& agent_id,
- const QString& competition_id,
- const Position& p);
- Result<void> update_position_marks(const QString& position_id, double mark, double liq_price);
- Result<void> close_position(const QString& position_id, const QString& reason);
- Result<QVector<Position>> open_positions_for(const QString& agent_id);
-
- // ── PnL snapshots ──────────────────────────────────────────────────────
- Result<void> insert_pnl_snapshot(const QString& tick_id,
- const QString& agent_id,
- const AgentAccountState& s,
- double avg_leverage);
- Result<QVector<LeaderboardRow>> leaderboard(const QString& competition_id);
-
- // ── Events ─────────────────────────────────────────────────────────────
- /// Append-only audit. agent_id may be empty for competition-level events.
- Result<void> append_event(const QString& competition_id,
- const QString& agent_id,
- const QString& type,
- const QJsonObject& payload);
- Result<QVector<EventRow>> events_since(const QString& competition_id, qint64 since_seq, int limit);
-
- // ── HITL approvals ──────────────────────────────────────────────────────
- Result<QString> request_hitl(const QString& decision_id,
- const QString& agent_id,
- const QJsonObject& action,
- const QString& prompt_text);
- Result<void> resolve_hitl(const QString& approval_id,
- const QString& status, // approved|rejected|timeout
- const QString& resolved_by);
-
- /// Pending HITL approvals (status='pending') for a competition. Used by
- /// HitlPanel to re-surface unresolved approvals after a screen toggle or
- /// app restart.
- struct PendingHitlRow {
- QString approval_id;
- QString agent_id;
- QString prompt_text;
- QString action_json;
- QString requested_at;
- };
- Result<QVector<PendingHitlRow>> pending_hitl_for(const QString& competition_id);
-
- private:
- AlphaArenaRepo() = default;
-};
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaSchema.h b/fincept-qt/src/services/alpha_arena/AlphaArenaSchema.h
deleted file mode 100644
index 6b72fe719..000000000
--- a/fincept-qt/src/services/alpha_arena/AlphaArenaSchema.h
+++ /dev/null
@@ -1,127 +0,0 @@
-#pragma once
-// AlphaArenaSchema — the canonical action grammar for Alpha Arena.
-//
-// This header is the *single source of truth* for what an LLM agent is
-// allowed to emit, and how we interpret it. Any divergence between this
-// file and scripts/alpha_arena/schema.json is a CI-failing bug.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §5 (Action grammar).
-//
-// Design notes:
-// * Four signals only — buy_to_enter / sell_to_enter / hold / close.
-// No partial close, no pyramiding, no hedging. RiskEngine enforces.
-// * One position per coin invariant — enforced server-side.
-// * Leverage is an integer in [1, 20]. Hyperliquid's S1 cap.
-// * confidence ∈ [0, 1]; risk_usd is what *the model claims* — RiskEngine
-// recomputes from |entry − stop_loss| × qty and overrides if drift > 5%.
-// * justification is free text; we cap at 1000 chars on parse.
-// * invalidation_condition is the model's externalised "exit reason" memory;
-// capped at 280 chars on parse.
-
-#include <QString>
-#include <QStringList>
-#include <QVector>
-
-#include <optional>
-
-namespace fincept::services::alpha_arena {
-
-/// Trading signals an agent may emit. Anything else is a parse error.
-enum class Signal {
- BuyToEnter,
- SellToEnter,
- Hold,
- Close,
-};
-
-/// Competition modes — match Nof1 S1/S2 published modes.
-/// (max_leverage from the previous prototype is dropped — it was marketing copy,
-/// not a real Nof1 mode.)
-enum class CompetitionMode {
- Baseline, // S1 default ruleset.
- Monk, // ≤ 1 entry / coin / 30 min, max position 25% of equity.
- Situational, // S2: agents see other agents' positions in their context.
-};
-
-/// The canonical perp universe (Nof1 Season 1).
-/// User may extend up to 12 perps from a curated venue list, but the default
-/// IS this set.
-inline const QStringList& kPerpUniverse() {
- static const QStringList universe{"BTC", "ETH", "SOL", "BNB", "DOGE", "XRP"};
- return universe;
-}
-
-/// Hard caps used by RiskEngine and the action parser. Keep here so they are
-/// visible alongside the schema they constrain.
-namespace limits {
-inline constexpr int kMinLeverage = 1;
-inline constexpr int kMaxLeverage = 20;
-inline constexpr int kInvalidationConditionMaxChars = 280;
-inline constexpr int kJustificationMaxChars = 1000;
-inline constexpr double kRiskUsdRecomputeToleranceFrac = 0.05; // 5%
-inline constexpr double kMaxRiskPerTradeFrac = 0.02; // 2% of equity
-inline constexpr double kMinLiquidationBufferFrac = 0.15; // 15% of price
-} // namespace limits
-
-/// One action proposal from a model. Validated by parse_model_response();
-/// downstream code may assume fields are within their declared ranges.
-struct ProposedAction {
- Signal signal = Signal::Hold;
- QString coin; // base symbol from kPerpUniverse(), e.g. "BTC".
- double quantity = 0.0; // base-asset units, > 0 for entries, ignored for hold.
- int leverage = 1; // [1, 20]
- double profit_target = 0.0; // absolute price; 0 = unset (not allowed for entries).
- double stop_loss = 0.0; // absolute price; 0 = unset (not allowed for entries).
- QString invalidation_condition; // ≤ 280 chars
- double confidence = 0.0; // [0, 1]
- double risk_usd = 0.0; // model-claimed; RiskEngine may override.
- QString justification; // ≤ 1000 chars
-};
-
-/// What a model returned for one tick.
-/// Either `actions` is populated and `parse_error` is empty, or `parse_error`
-/// is set and we ran a no-op tick (no retry — matches Nof1 behaviour).
-struct ModelResponse {
- QString raw_text; // verbatim model output, for ModelChat trace.
- QVector<ProposedAction> actions;
- std::optional<QString> parse_error;
-};
-
-/// Round-trip helpers — convert between Signal and the canonical wire string.
-/// Wire strings are exactly what the LLM is told to emit in the system prompt;
-/// changing them is a breaking schema change.
-inline QString signal_to_wire(Signal s) {
- switch (s) {
- case Signal::BuyToEnter: return QStringLiteral("buy_to_enter");
- case Signal::SellToEnter: return QStringLiteral("sell_to_enter");
- case Signal::Hold: return QStringLiteral("hold");
- case Signal::Close: return QStringLiteral("close");
- }
- return QStringLiteral("hold");
-}
-
-inline std::optional<Signal> signal_from_wire(const QString& s) {
- if (s == QLatin1String("buy_to_enter")) return Signal::BuyToEnter;
- if (s == QLatin1String("sell_to_enter")) return Signal::SellToEnter;
- if (s == QLatin1String("hold")) return Signal::Hold;
- if (s == QLatin1String("close")) return Signal::Close;
- return std::nullopt;
-}
-
-inline QString mode_to_wire(CompetitionMode m) {
- switch (m) {
- case CompetitionMode::Baseline: return QStringLiteral("baseline");
- case CompetitionMode::Monk: return QStringLiteral("monk");
- case CompetitionMode::Situational: return QStringLiteral("situational");
- }
- return QStringLiteral("baseline");
-}
-
-inline std::optional<CompetitionMode> mode_from_wire(const QString& s) {
- if (s == QLatin1String("baseline")) return CompetitionMode::Baseline;
- if (s == QLatin1String("monk")) return CompetitionMode::Monk;
- if (s == QLatin1String("situational")) return CompetitionMode::Situational;
- return std::nullopt;
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaService.cpp b/fincept-qt/src/services/alpha_arena/AlphaArenaService.cpp
deleted file mode 100644
index d374c9013..000000000
--- a/fincept-qt/src/services/alpha_arena/AlphaArenaService.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-#include "services/alpha_arena/AlphaArenaService.h"
-
-#include "core/logging/Logger.h"
-#include "python/PythonRunner.h"
-
-#include <QJsonDocument>
-#include <QJsonParseError>
-
-namespace fincept::services::alpha_arena {
-
-AlphaArenaService& AlphaArenaService::instance() {
- static AlphaArenaService s;
- return s;
-}
-
-void AlphaArenaService::run_action(const QJsonObject& payload, ActionCallback cb) {
- const QString json_arg =
- QString::fromUtf8(QJsonDocument(payload).toJson(QJsonDocument::Compact));
- const QString action = payload.value("action").toString();
-
- fincept::python::PythonRunner::instance().run(
- QStringLiteral("alpha_arena/main.py"), {json_arg},
- [cb = std::move(cb), action](const fincept::python::PythonResult& result) {
- ActionResult out;
- if (!result.success) {
- out.error = result.error.isEmpty()
- ? QStringLiteral("Engine call failed")
- : result.error;
- LOG_ERROR("AlphaArenaService",
- QStringLiteral("%1 failed: %2").arg(action, out.error.left(300)));
- if (cb) cb(out);
- return;
- }
-
- const QString json_str = fincept::python::extract_json(result.output);
- if (json_str.isEmpty()) {
- out.error = QStringLiteral("No response from engine");
- if (cb) cb(out);
- return;
- }
-
- QJsonParseError err;
- const auto doc = QJsonDocument::fromJson(json_str.toUtf8(), &err);
- if (doc.isNull() || !doc.isObject()) {
- out.error = QStringLiteral("Invalid response: %1").arg(err.errorString());
- if (cb) cb(out);
- return;
- }
-
- const QJsonObject obj = doc.object();
- if (!obj.value("success").toBool(false)) {
- out.error = obj.value("error").toString(QStringLiteral("Engine reported failure"));
- if (cb) cb(out);
- return;
- }
-
- out.success = true;
- out.data = obj;
- if (cb) cb(out);
- });
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaService.h b/fincept-qt/src/services/alpha_arena/AlphaArenaService.h
deleted file mode 100644
index dc1d2a461..000000000
--- a/fincept-qt/src/services/alpha_arena/AlphaArenaService.h
+++ /dev/null
@@ -1,39 +0,0 @@
-#pragma once
-// AlphaArenaService — thin wrapper around the Alpha Arena Python engine so
-// the screen does not spawn Python directly (D1 / P6).
-//
-// Alpha Arena is a user-driven competition runner: the user creates a
-// competition, runs cycles, refreshes leaderboard. All actions are one-shot
-// JSON-in / JSON-out calls against alpha_arena/main.py — no streaming cadence
-// to put on the hub, so a non-Producer service wrapper is the right shape.
-
-#include <QJsonObject>
-#include <QObject>
-#include <QString>
-
-#include <functional>
-
-namespace fincept::services::alpha_arena {
-
-struct ActionResult {
- bool success = false;
- QJsonObject data; // engine response (top-level JSON)
- QString error;
-};
-
-using ActionCallback = std::function<void(const ActionResult&)>;
-
-class AlphaArenaService : public QObject {
- Q_OBJECT
- public:
- static AlphaArenaService& instance();
-
- /// Runs `alpha_arena/main.py <payload>` where payload is `{action, params, api_keys?}`.
- /// The caller builds the payload; we dispatch and parse the JSON response.
- void run_action(const QJsonObject& payload, ActionCallback cb);
-
- private:
- AlphaArenaService() = default;
-};
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaTypes.h b/fincept-qt/src/services/alpha_arena/AlphaArenaTypes.h
deleted file mode 100644
index 69af7cfff..000000000
--- a/fincept-qt/src/services/alpha_arena/AlphaArenaTypes.h
+++ /dev/null
@@ -1,117 +0,0 @@
-#pragma once
-// AlphaArenaTypes — POD value types used across the Alpha Arena engine.
-//
-// These describe what flows from the venue into the ContextBuilder, and from
-// the OrderRouter back into persistence. Nothing in here is Qt::Object — they
-// are pure data, copyable, persistable, and trivially serialisable.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §4 (Context builder)
-// and §6 (Risk engine).
-
-#include "services/alpha_arena/AlphaArenaSchema.h"
-
-#include <QString>
-#include <QStringList>
-#include <QVector>
-
-#include <cstdint>
-#include <optional>
-
-namespace fincept::services::alpha_arena {
-
-/// One scheduler tick. seq is monotonic per competition starting at 1.
-struct Tick {
- qint64 utc_ms = 0;
- int seq = 0;
-};
-
-/// One candle. Used for both 3-minute intraday and 4-hour context bars.
-struct Bar {
- qint64 utc_ms = 0;
- double open = 0.0;
- double high = 0.0;
- double low = 0.0;
- double close = 0.0;
- double volume = 0.0;
-};
-
-/// Per-coin market state captured at decision time.
-/// Series ordered OLDEST → NEWEST; ContextBuilder relies on this ordering.
-struct MarketSnapshot {
- QString coin; // base symbol, e.g. "BTC"
- double mid = 0.0;
- double bid = 0.0;
- double ask = 0.0;
- double open_interest = 0.0;
- double funding_rate = 0.0; // current 1h funding rate, fractional
- double ema20 = 0.0;
- double rsi7 = 0.0;
- double macd = 0.0;
- double macd_signal = 0.0;
- QVector<Bar> bars_3m_24h; // up to 480 bars
- QVector<Bar> bars_4h_30d; // up to 180 bars
-};
-
-/// One open position. Mirrors the position-table view the model sees.
-struct Position {
- QString coin;
- double qty = 0.0; // signed: positive = long, negative = short
- double entry = 0.0;
- double mark = 0.0;
- double liq_price = 0.0;
- double unrealized_pnl = 0.0;
- int leverage = 1;
- double profit_target = 0.0;
- double stop_loss = 0.0;
- QString invalidation_condition;
- QStringList order_ids; // venue order ids associated with this position
-};
-
-/// What an agent's prompt sees about its own account at tick time.
-struct AgentAccountState {
- double equity = 0.0; // mark-to-market account value, USD
- double cash = 0.0;
- double return_pct = 0.0; // since inception
- double sharpe = 0.0; // rolling Sharpe
- double max_drawdown = 0.0; // worst peak-to-trough so far
- double fees_paid = 0.0;
- double win_rate = 0.0; // closed trades only
- int trades_count = 0;
- QVector<Position> positions;
-};
-
-/// Optional — only populated in CompetitionMode::Situational. Lists the other
-/// agents' currently-open positions (no PnL, no equity — just exposure).
-struct PeerPositionView {
- QString agent_display_name;
- QString coin;
- double qty = 0.0;
- int leverage = 1;
-};
-
-struct SituationalContext {
- QVector<PeerPositionView> peers;
-};
-
-/// Output of RiskEngine::evaluate(). Pure value type — no I/O.
-struct RiskVerdict {
- enum class Outcome {
- Accept, // pass to OrderRouter as-is
- Reject, // do not place; record reason
- Amend, // place using `amended` instead of original
- };
- Outcome outcome = Outcome::Reject;
- QString reason;
- std::optional<ProposedAction> amended;
-};
-
-/// Per-tick aggregate the engine assembles before fanning out to models.
-/// All agents in a competition see the same MarketSnapshot vector and the
-/// same Tick — only AgentAccountState varies (and SituationalContext in
-/// situational mode).
-struct TickContext {
- Tick tick;
- QVector<MarketSnapshot> markets;
-};
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaDecisionParser.cpp b/fincept-qt/src/services/alpha_arena/ArenaDecisionParser.cpp
new file mode 100644
index 000000000..ac66bd040
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaDecisionParser.cpp
@@ -0,0 +1,100 @@
+#include "services/alpha_arena/ArenaDecisionParser.h"
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QRegularExpression>
+
+namespace fincept::arena {
+namespace {
+QJsonObject extract_object(const QString& raw) {
+ auto doc = QJsonDocument::fromJson(raw.trimmed().toUtf8());
+ if (doc.isObject()) return doc.object();
+ static const QRegularExpression fence(QStringLiteral("```(?:json)?\\s*(\\{.*?\\})\\s*```"),
+ QRegularExpression::DotMatchesEverythingOption);
+ if (auto m = fence.match(raw); m.hasMatch()) {
+ doc = QJsonDocument::fromJson(m.captured(1).toUtf8());
+ if (doc.isObject()) return doc.object();
+ }
+ // First balanced top-level {...} scan. String-aware: braces inside JSON
+ // string values (e.g. a reason of "unmatched } here") must not count.
+ const qsizetype start = raw.indexOf('{');
+ if (start >= 0) {
+ int depth = 0;
+ bool in_str = false, esc = false;
+ for (qsizetype i = start; i < raw.size(); ++i) {
+ const QChar ch = raw[i];
+ if (in_str) {
+ if (esc) esc = false;
+ else if (ch == QLatin1Char('\\')) esc = true;
+ else if (ch == QLatin1Char('"')) in_str = false;
+ continue;
+ }
+ if (ch == QLatin1Char('"')) in_str = true;
+ else if (ch == QLatin1Char('{')) ++depth;
+ else if (ch == QLatin1Char('}') && --depth == 0) {
+ doc = QJsonDocument::fromJson(raw.mid(start, i - start + 1).toUtf8());
+ if (doc.isObject()) return doc.object();
+ break;
+ }
+ }
+ }
+ return {};
+}
+} // namespace
+
+ParsedDecision parse_decision(const QString& raw, const QStringList& instruments, double max_leverage) {
+ ParsedDecision out;
+ const QJsonObject obj = extract_object(raw);
+ if (obj.isEmpty()) { out.error = QStringLiteral("no JSON object found in response"); return out; }
+ const QJsonArray arr = obj.value(QStringLiteral("actions")).toArray();
+ if (arr.isEmpty()) { out.error = QStringLiteral("\"actions\" missing or empty"); return out; }
+ for (const auto& v : arr) {
+ const QJsonObject a = v.toObject();
+ AgentAction act;
+ const QString kind = a.value(QStringLiteral("action")).toString().toLower();
+ act.reason = a.value(QStringLiteral("reason")).toString();
+ act.coin = a.value(QStringLiteral("coin")).toString().toUpper();
+ if (kind == QLatin1String("hold")) { act.kind = ActionKind::Hold; out.actions.append(act); continue; }
+ if (kind != QLatin1String("open") && kind != QLatin1String("close")) {
+ out.error = QStringLiteral("unknown action \"%1\"").arg(kind); out.actions.clear(); return out;
+ }
+ if (!instruments.contains(act.coin)) {
+ out.error = QStringLiteral("coin \"%1\" not in competition instruments").arg(act.coin);
+ out.actions.clear(); return out;
+ }
+ if (kind == QLatin1String("close")) {
+ act.kind = ActionKind::Close;
+ act.size_usd = a.value(QStringLiteral("size_usd")).toDouble(0);
+ out.actions.append(act); continue;
+ }
+ act.kind = ActionKind::Open;
+ act.side = a.value(QStringLiteral("side")).toString().toLower();
+ act.size_usd = a.value(QStringLiteral("size_usd")).toDouble();
+ act.leverage = a.value(QStringLiteral("leverage")).toDouble(1);
+ if (act.side != QLatin1String("long") && act.side != QLatin1String("short")) {
+ out.error = QStringLiteral("invalid side \"%1\"").arg(act.side); out.actions.clear(); return out;
+ }
+ if (act.size_usd <= 0) { out.error = QStringLiteral("size_usd must be > 0"); out.actions.clear(); return out; }
+ if (act.leverage < 1 || act.leverage > max_leverage) {
+ out.error = QStringLiteral("leverage %1 outside [1, %2]").arg(act.leverage).arg(max_leverage);
+ out.actions.clear(); return out;
+ }
+ out.actions.append(act);
+ }
+ return out;
+}
+
+QString ParsedDecision::actions_json() const {
+ QJsonArray arr;
+ for (const auto& a : actions) {
+ QJsonObject o;
+ o["action"] = a.kind == ActionKind::Open ? "open" : a.kind == ActionKind::Close ? "close" : "hold";
+ if (!a.coin.isEmpty()) o["coin"] = a.coin;
+ if (a.kind == ActionKind::Open) { o["side"] = a.side; o["size_usd"] = a.size_usd; o["leverage"] = a.leverage; }
+ if (a.kind == ActionKind::Close && a.size_usd > 0) o["size_usd"] = a.size_usd;
+ o["reason"] = a.reason;
+ arr.append(o);
+ }
+ return QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact));
+}
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaDecisionParser.h b/fincept-qt/src/services/alpha_arena/ArenaDecisionParser.h
new file mode 100644
index 000000000..9bf850cc0
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaDecisionParser.h
@@ -0,0 +1,13 @@
+#pragma once
+// Tolerant parser for the arena decision contract (spec §5). Pure.
+#include "services/alpha_arena/ArenaTypes.h"
+namespace fincept::arena {
+struct ParsedDecision {
+ QVector<AgentAction> actions;
+ QString error; // empty = ok
+ bool ok() const { return error.isEmpty(); }
+ QString actions_json() const; // canonical re-serialization for storage
+};
+/// instruments + max_leverage gate validation; never throws.
+ParsedDecision parse_decision(const QString& raw, const QStringList& instruments, double max_leverage);
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaEngine.cpp b/fincept-qt/src/services/alpha_arena/ArenaEngine.cpp
new file mode 100644
index 000000000..c2f132d1b
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaEngine.cpp
@@ -0,0 +1,570 @@
+#include "services/alpha_arena/ArenaEngine.h"
+#include "core/logging/Logger.h"
+#include "services/alpha_arena/ArenaDecisionParser.h"
+#include "services/alpha_arena/ArenaMarketData.h"
+#include "services/alpha_arena/ArenaModelRegistry.h"
+#include "services/alpha_arena/ArenaPrompts.h"
+#include "services/alpha_arena/HyperliquidLiveVenue.h"
+#include "storage/secure/SecureStorage.h"
+#include <QDateTime>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QUuid>
+
+namespace fincept::arena {
+
+static constexpr const char* TAG = "ArenaEngine";
+
+ArenaEngine& ArenaEngine::instance() {
+ static ArenaEngine e;
+ return e;
+}
+
+ArenaEngine::ArenaEngine() {
+ timer_ = new QTimer(this);
+ connect(timer_, &QTimer::timeout, this, &ArenaEngine::run_round);
+ marks_timer_ = new QTimer(this);
+ connect(marks_timer_, &QTimer::timeout, this, &ArenaEngine::run_marks_tick);
+}
+
+bool ArenaEngine::agent_is_active(const QString& agent_id) const {
+ for (const auto& a : agents_)
+ if (a.id == agent_id) return a.status == QLatin1String("active");
+ return false; // unknown id → never execute on its behalf
+}
+
+void ArenaEngine::init() {
+ if (inited_) return;
+ inited_ = true;
+ if (!market_) market_ = new ArenaMarketData(this);
+ if (!llm_) llm_ = new ArenaLlmClient(this);
+ if (auto r = ArenaStore::instance().competitions_with_status("running");
+ r.is_ok() && !r.value().isEmpty()) {
+ crash_pending_ = r.value(); // kept queryable — init() runs before any UI exists
+ emit crash_recovery_pending(crash_pending_);
+ }
+}
+
+void ArenaEngine::dismiss_crash_recovery(const QString& id) {
+ crash_pending_.removeAll(id);
+ ArenaStore::instance().set_competition_status(id, "ended");
+ emit competition_status_changed(id, "ended");
+}
+
+void ArenaEngine::set_market_for_test(IArenaMarketData* m) {
+ delete market_;
+ market_ = m;
+ m->setParent(this);
+ inited_ = true;
+ if (!llm_) llm_ = new ArenaLlmClient(this);
+}
+
+void ArenaEngine::set_llm_for_test(IArenaLlmClient* c) {
+ delete llm_;
+ llm_ = c;
+ c->setParent(this);
+ inited_ = true;
+ if (!market_) market_ = new ArenaMarketData(this);
+}
+
+Result<QString> ArenaEngine::create_competition(const ArenaConfig& cfg) {
+ if (cfg.agents.isEmpty()) return Result<QString>::err("select at least one model");
+ if (cfg.instruments.isEmpty()) return Result<QString>::err("select at least one instrument");
+ return ArenaStore::instance().insert_competition(cfg);
+}
+
+Result<void> ArenaEngine::start(const QString& competition_id) {
+ ++epoch_; // invalidate in-flight async callbacks from any previous run
+ if (!active_id_.isEmpty()) { // never two running: end the old one cleanly first
+ auto r = stop();
+ if (r.is_err()) return r;
+ }
+ auto comp_r = ArenaStore::instance().competition(competition_id);
+ if (comp_r.is_err()) return Result<void>::err(comp_r.error());
+ comp_ = comp_r.value();
+ auto agents_r = ArenaStore::instance().agents_for(competition_id);
+ if (agents_r.is_err()) return Result<void>::err(agents_r.error());
+ agents_ = agents_r.value();
+ active_id_ = competition_id;
+ crash_pending_.removeAll(competition_id); // resuming clears the pending-recovery flag
+ limits_.max_leverage = comp_.max_leverage;
+ if (comp_.venue == QLatin1String("hyperliquid") && comp_.live_mode) {
+ // The wizard's gate dialog ran before the competition existed and stored
+ // the agent wallet key under ".../pending" — move it to this competition's
+ // handle so the live venue's signer can find it (store new, then delete old).
+ auto& ss = SecureStorage::instance();
+ const QString pending_handle = QStringLiteral("alpha_arena/agent_key/pending");
+ if (auto key = ss.retrieve(pending_handle); key.is_ok()) {
+ const QString comp_handle = QStringLiteral("alpha_arena/agent_key/%1").arg(competition_id);
+ if (ss.store(comp_handle, key.value()).is_ok())
+ ss.remove(pending_handle);
+ else
+ LOG_ERROR(TAG, QStringLiteral("failed to re-key live wallet handle for %1").arg(competition_id));
+ }
+ venue_ = std::make_unique<HyperliquidLiveVenue>(ArenaStore::instance(), competition_id);
+ } else {
+ venue_ = std::make_unique<PaperExchange>(ArenaStore::instance(), competition_id);
+ }
+ venue_->load();
+ auto seq_r = ArenaStore::instance().last_round_seq(competition_id);
+ round_seq_ = seq_r.is_ok() ? seq_r.value() : 0;
+ last_mark_ts_ = QDateTime::currentMSecsSinceEpoch();
+ if (comp_.started_at == 0) {
+ comp_.started_at = last_mark_ts_; // keep the in-memory row in sync so stop() persists it
+ ArenaStore::instance().set_competition_timestamps(competition_id, last_mark_ts_, 0);
+ }
+ ArenaStore::instance().set_competition_status(competition_id, "running");
+ emit competition_status_changed(competition_id, "running");
+ timer_->start(comp_.cadence_seconds * 1000);
+ marks_timer_->start(marks_interval_ms_); // between-round live marks
+ force_round(); // first round immediately
+ return Result<void>::ok();
+}
+
+Result<void> ArenaEngine::pause() {
+ if (active_id_.isEmpty()) return Result<void>::err("no active competition");
+ timer_->stop();
+ marks_timer_->stop();
+ ArenaStore::instance().set_competition_status(active_id_, "paused");
+ emit competition_status_changed(active_id_, "paused");
+ return Result<void>::ok();
+}
+
+Result<void> ArenaEngine::resume() {
+ if (active_id_.isEmpty()) return Result<void>::err("no active competition");
+ timer_->start(comp_.cadence_seconds * 1000);
+ marks_timer_->start(marks_interval_ms_);
+ ArenaStore::instance().set_competition_status(active_id_, "running");
+ emit competition_status_changed(active_id_, "running");
+ return Result<void>::ok();
+}
+
+Result<void> ArenaEngine::stop() {
+ if (active_id_.isEmpty()) return Result<void>::err("no active competition");
+ ++epoch_; // any snapshot/LLM callback still in flight becomes a no-op
+ timer_->stop();
+ marks_timer_->stop();
+ ArenaStore::instance().set_competition_status(active_id_, "ended");
+ ArenaStore::instance().set_competition_timestamps(active_id_, comp_.started_at,
+ QDateTime::currentMSecsSinceEpoch());
+ emit competition_status_changed(active_id_, "ended");
+ const QString id = active_id_;
+ active_id_.clear();
+ agents_.clear();
+ venue_.reset();
+ round_in_flight_ = false;
+ pending_agents_ = 0;
+ round_notional_.clear();
+ pending_hitl_.clear(); // un-actioned approvals die with the run
+ LOG_INFO(TAG, QStringLiteral("competition %1 stopped").arg(id));
+ return Result<void>::ok();
+}
+
+Result<void> ArenaEngine::kill_all() {
+ if (!venue_) return Result<void>::err("no active competition");
+ for (const auto& a : agents_) venue_->close_all(a.id, round_seq_);
+ ArenaStore::instance().insert_event(active_id_, "", "kill_all", "{}");
+ return stop();
+}
+
+Result<void> ArenaEngine::kill_agent(const QString& agent_id) {
+ if (active_id_.isEmpty() || !venue_) return Result<void>::err("no active competition");
+ bool known = false;
+ for (const auto& a : agents_)
+ if (a.id == agent_id) { known = true; break; }
+ if (!known) return Result<void>::err("unknown agent id");
+
+ const auto closes = venue_->close_all(agent_id, round_seq_);
+ for (const auto& o : closes) emit order_executed(o.agent_id, o.id, o.status);
+
+ const QString reason = QStringLiteral("killed by user");
+ ArenaStore::instance().set_agent_status(agent_id, "halted_user", reason);
+ for (auto& a : agents_)
+ if (a.id == agent_id) { a.status = "halted_user"; a.halt_reason = reason; }
+ emit agent_status_changed(agent_id, "halted_user", reason);
+
+ ArenaStore::instance().insert_event(
+ active_id_, agent_id, "agent_killed",
+ QString::fromUtf8(QJsonDocument(QJsonObject{{"agent_id", agent_id}, {"round_seq", round_seq_}})
+ .toJson(QJsonDocument::Compact)));
+
+ // Final equity snapshot at the current round (PK (comp,agent,round) upserts).
+ const auto acct = venue_->account(agent_id);
+ EquitySnapshotRow s;
+ s.competition_id = active_id_;
+ s.agent_id = agent_id;
+ s.round_seq = round_seq_;
+ s.ts = QDateTime::currentMSecsSinceEpoch();
+ s.equity = acct.equity;
+ s.balance = acct.balance;
+ for (auto it = acct.upnl.begin(); it != acct.upnl.end(); ++it) s.unrealized_pnl += it.value();
+ ArenaStore::instance().insert_equity_snapshot(s);
+ return Result<void>::ok();
+}
+
+Result<void> ArenaEngine::halt_agent(const QString& agent_id) {
+ auto r = ArenaStore::instance().set_agent_status(agent_id, "halted_user", "halted by user");
+ if (r.is_err()) return r;
+ for (auto& a : agents_)
+ if (a.id == agent_id) a.status = "halted_user";
+ emit agent_status_changed(agent_id, "halted_user", "halted by user");
+ return Result<void>::ok();
+}
+
+Result<void> ArenaEngine::resume_agent(const QString& agent_id) {
+ auto r = ArenaStore::instance().set_agent_status(agent_id, "active", "");
+ if (r.is_err()) return r;
+ ArenaStore::instance().set_agent_failures(agent_id, 0);
+ for (auto& a : agents_)
+ if (a.id == agent_id) {
+ a.status = "active";
+ a.consecutive_failures = 0;
+ }
+ emit agent_status_changed(agent_id, "active", "");
+ return Result<void>::ok();
+}
+
+Result<void> ArenaEngine::set_cadence(int seconds) {
+ if (active_id_.isEmpty()) return Result<void>::err("no active competition");
+ if (seconds < 60 || seconds > 3600) return Result<void>::err("cadence must be 60–3600s");
+ comp_.cadence_seconds = seconds;
+ ArenaStore::instance().set_cadence(active_id_, seconds);
+ if (timer_->isActive()) timer_->start(seconds * 1000);
+ return Result<void>::ok();
+}
+
+int ArenaEngine::next_round_in_seconds() const {
+ return timer_->isActive() ? timer_->remainingTime() / 1000 : -1;
+}
+
+void ArenaEngine::force_round() { run_round(); }
+
+void ArenaEngine::set_marks_interval_for_test(int ms) {
+ marks_interval_ms_ = ms;
+ if (marks_timer_->isActive()) marks_timer_->start(ms);
+}
+
+// Between-round live marks: re-mark the venue every marks_interval_ms_ so the
+// dashboard sees live equity instead of waiting a whole cadence (default 180s).
+// Runs the same funding/liquidation sweep as a round — last_mark_ts_ keeps the
+// funding elapsed-time correct across BOTH kinds of mark_all.
+void ArenaEngine::run_marks_tick() {
+ if (round_in_flight_ || active_id_.isEmpty()) return;
+ const quint64 epoch = epoch_;
+ market_->fetch_mids(comp_.instruments, [this, epoch](Result<QHash<QString, double>> r) {
+ if (epoch != epoch_ || active_id_.isEmpty()) return; // stopped/replaced mid-fetch
+ if (round_in_flight_) return; // a round started meanwhile — on_snapshot owns marking
+ if (r.is_err()) return; // transient; next tick retries
+ venue_->set_marks(r.value());
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ const auto liqs = venue_->mark_all(now - last_mark_ts_, round_seq_);
+ last_mark_ts_ = now;
+ for (const auto& o : liqs) emit order_executed(o.agent_id, o.id, o.status);
+ emit marks_updated();
+ });
+}
+
+void ArenaEngine::run_round() {
+ if (round_in_flight_ || active_id_.isEmpty()) return;
+ round_in_flight_ = true;
+ const int seq = round_seq_ + 1;
+ const quint64 epoch = epoch_;
+ emit round_started(seq);
+ market_->fetch_snapshot(comp_.instruments, [this, epoch, seq](Result<MarketSnapshot> r) {
+ on_snapshot(epoch, seq, std::move(r));
+ });
+}
+
+void ArenaEngine::on_snapshot(quint64 epoch, int seq, Result<MarketSnapshot> r) {
+ if (epoch != epoch_) return; // stale callback from a stopped/replaced run; a new
+ // run owns round_in_flight_ — do not touch it here
+ if (active_id_.isEmpty()) { // stopped mid-fetch
+ round_in_flight_ = false;
+ return;
+ }
+ if (r.is_err()) {
+ ArenaStore::instance().insert_event(
+ active_id_, "", "market_data_error",
+ QString::fromUtf8(QJsonDocument(QJsonObject{{"error", QString::fromStdString(r.error())}})
+ .toJson(QJsonDocument::Compact)));
+ round_in_flight_ = false;
+ emit round_failed(seq, QString::fromStdString(r.error()));
+ return; // retry on next natural tick
+ }
+ round_seq_ = seq;
+ last_snapshot_ = r.value();
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+
+ QJsonObject snap_json;
+ QHash<QString, double> mids, fundings;
+ for (const auto& c : last_snapshot_.coins) {
+ mids[c.coin] = c.mid;
+ fundings[c.coin] = c.funding_rate;
+ snap_json[c.coin] = QJsonObject{{"mid", c.mid},
+ {"funding", c.funding_rate},
+ {"oi", c.open_interest},
+ {"chg", c.day_change_pct}};
+ }
+ ArenaStore::instance().insert_round(
+ active_id_, seq, now, QString::fromUtf8(QJsonDocument(snap_json).toJson(QJsonDocument::Compact)));
+
+ venue_->set_marks(mids);
+ venue_->set_funding(fundings);
+ const auto liqs = venue_->mark_all(now - last_mark_ts_, seq);
+ for (const auto& o : liqs) emit order_executed(o.agent_id, o.id, o.status);
+ last_mark_ts_ = now;
+
+ round_notional_.clear();
+ pending_agents_ = 0;
+ for (const auto& a : agents_)
+ if (a.status == QLatin1String("active")) ++pending_agents_;
+ if (pending_agents_ == 0) {
+ settle_round(seq);
+ return;
+ }
+ for (const auto& a : agents_)
+ if (a.status == QLatin1String("active"))
+ dispatch_agent(seq, a, last_snapshot_, false, {}, {});
+}
+
+void ArenaEngine::dispatch_agent(int seq, const AgentRow& agent, const MarketSnapshot& snap,
+ bool is_retry, const QString& prior_raw, const QString& prior_error) {
+ auto cred = ArenaModelRegistry::instance().resolve_credentials(agent.source_kind, agent.source_ref,
+ agent.provider);
+ if (cred.is_err()) {
+ DecisionRow d;
+ d.competition_id = active_id_;
+ d.agent_id = agent.id;
+ d.round_seq = seq;
+ d.status = "skipped_no_key";
+ d.parse_error = QString::fromStdString(cred.error());
+ auto id_r = ArenaStore::instance().insert_decision(d);
+ emit decision_received(id_r.is_ok() ? id_r.value() : QString(), agent.id, d.status);
+ agent_done(seq);
+ return;
+ }
+ const QString sys = system_prompt(comp_);
+ auto recent_r = ArenaStore::instance().recent_decisions(active_id_, agent.id, 5);
+ QString user = user_prompt(snap, venue_->account(agent.id),
+ recent_r.is_ok() ? recent_r.value() : QVector<DecisionRow>{}, seq,
+ comp_.started_at);
+ if (is_retry)
+ user += QStringLiteral("\n\nYour previous reply was not valid: %1\nPrevious reply:\n%2\n"
+ "Reply again with ONLY the JSON object.")
+ .arg(prior_error, prior_raw.left(2000));
+
+ ArenaLlmRequest req;
+ req.provider = agent.provider;
+ req.model_id = agent.model_id;
+ req.api_key = cred.value().api_key;
+ req.base_url = cred.value().base_url;
+ req.system_prompt = sys;
+ req.user_prompt = user;
+
+ const AgentRow agent_copy = agent;
+ const quint64 epoch = epoch_;
+ llm_->complete(req, [this, epoch, seq, agent_copy, sys, user, is_retry](ArenaLlmResult r) {
+ if (epoch != epoch_ || active_id_.isEmpty()) return; // stopped/replaced mid-call
+ finish_agent(seq, agent_copy, r, sys, user, is_retry);
+ });
+}
+
+void ArenaEngine::finish_agent(int seq, const AgentRow& agent, const ArenaLlmResult& llm,
+ const QString& sys, const QString& user, bool was_retry) {
+ // Halt is immediate (user-reported bug): the user may have halted/killed this
+ // agent while its LLM call was in flight (up to 60s). `agent` is the row as
+ // of dispatch — re-check the CURRENT status and, if no longer active, persist
+ // the decision with its real status but execute nothing (no venue calls, no
+ // HITL queueing, no repair retry).
+ const bool halted = !agent_is_active(agent.id);
+ auto skip_halted = [this, seq, &agent]() {
+ ArenaStore::instance().insert_event(
+ active_id_, agent.id, "actions_skipped_agent_halted",
+ QString::fromUtf8(QJsonDocument(QJsonObject{{"agent_id", agent.id}, {"round_seq", seq}})
+ .toJson(QJsonDocument::Compact)));
+ agent_done(seq);
+ };
+
+ DecisionRow d;
+ d.competition_id = active_id_;
+ d.agent_id = agent.id;
+ d.round_seq = seq;
+ d.system_prompt = sys;
+ d.user_prompt = user;
+ d.raw_response = llm.content;
+ d.latency_ms = llm.latency_ms;
+ d.prompt_tokens = llm.prompt_tokens;
+ d.completion_tokens = llm.completion_tokens;
+
+ if (!llm.success) {
+ d.status = llm.error == QLatin1String("timeout") ? "timeout" : "llm_error";
+ d.parse_error = llm.error;
+ auto id_r = ArenaStore::instance().insert_decision(d);
+ emit decision_received(id_r.is_ok() ? id_r.value() : QString(), agent.id, d.status);
+ if (halted) { skip_halted(); return; }
+ record_failure(agent, d.status);
+ agent_done(seq);
+ return;
+ }
+
+ auto parsed = parse_decision(llm.content, comp_.instruments, comp_.max_leverage);
+ if (!parsed.ok()) {
+ if (!was_retry && !halted) { // one repair retry (spec §5); none for a halted agent
+ dispatch_agent(seq, agent, last_snapshot_, true, llm.content, parsed.error);
+ return;
+ }
+ d.status = "parse_error";
+ d.parse_error = parsed.error;
+ auto id_r = ArenaStore::instance().insert_decision(d);
+ emit decision_received(id_r.is_ok() ? id_r.value() : QString(), agent.id, d.status);
+ if (halted) { skip_halted(); return; }
+ record_failure(agent, d.status);
+ agent_done(seq);
+ return;
+ }
+
+ d.status = "ok";
+ d.actions_json = parsed.actions_json();
+ auto id_r = ArenaStore::instance().insert_decision(d);
+ ArenaStore::instance().set_agent_failures(agent.id, 0);
+ for (auto& a : agents_)
+ if (a.id == agent.id) a.consecutive_failures = 0;
+ emit decision_received(id_r.is_ok() ? id_r.value() : QString(), agent.id, d.status);
+ if (halted) { skip_halted(); return; } // decision recorded; actions never reach the venue
+
+ for (const auto& act : parsed.actions) {
+ if (act.kind == ActionKind::Hold) continue;
+ const auto acct = venue_->account(agent.id);
+ const auto verdict = evaluate(act, acct, limits_, round_notional_.value(agent.id));
+ if (!verdict.approved) {
+ OrderRow rej;
+ rej.competition_id = active_id_;
+ rej.agent_id = agent.id;
+ rej.round_seq = seq;
+ rej.coin = act.coin;
+ rej.side = act.side;
+ rej.action = act.kind == ActionKind::Open ? "open" : "close";
+ rej.notional_usd = act.size_usd;
+ rej.leverage = act.leverage;
+ rej.status = "rejected_risk";
+ rej.reject_reason = verdict.reason;
+ auto or_r = ArenaStore::instance().insert_order(rej);
+ emit order_executed(agent.id, or_r.is_ok() ? or_r.value() : QString(), rej.status);
+ continue;
+ }
+ if (comp_.live_mode) {
+ // HITL: live competitions queue risk-approved actions until a human
+ // decides (resume_after_hitl) — nothing reaches the venue before that.
+ // Count queued opens against the round-notional cap NOW — otherwise a
+ // multi-action decision is risk-checked with round_notional_so_far == 0.
+ if (act.kind == ActionKind::Open) round_notional_[agent.id] += act.size_usd;
+ PendingApproval pa;
+ pa.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ pa.agent_id = agent.id;
+ pa.action = act;
+ pa.seq = seq;
+ pending_hitl_.append(pa);
+ emit hitl_requested(pa.id, agent.id,
+ QStringLiteral("%1 %2 %3 $%4 @%5x")
+ .arg(act.kind == ActionKind::Open ? QStringLiteral("OPEN")
+ : QStringLiteral("CLOSE"),
+ act.side.toUpper(), act.coin,
+ QString::number(act.size_usd, 'f', 0),
+ QString::number(act.leverage, 'f', 0)));
+ continue; // executed only after approval
+ }
+ if (act.kind == ActionKind::Open) round_notional_[agent.id] += act.size_usd;
+ auto fill = venue_->execute(agent.id, act, seq);
+ if (fill.is_ok()) emit order_executed(agent.id, fill.value().id, fill.value().status);
+ }
+ agent_done(seq);
+}
+
+void ArenaEngine::resume_after_hitl(const QString& approval_id, bool approved) {
+ for (int i = 0; i < pending_hitl_.size(); ++i) {
+ if (pending_hitl_[i].id != approval_id) continue;
+ const PendingApproval pa = pending_hitl_.takeAt(i);
+ if (!approved) {
+ OrderRow rej;
+ rej.competition_id = active_id_;
+ rej.agent_id = pa.agent_id;
+ rej.round_seq = pa.seq;
+ rej.coin = pa.action.coin;
+ rej.side = pa.action.side;
+ rej.action = pa.action.kind == ActionKind::Open ? "open" : "close";
+ rej.notional_usd = pa.action.size_usd;
+ rej.leverage = pa.action.leverage;
+ rej.status = "rejected_risk";
+ rej.reject_reason = "HITL rejected";
+ auto r = ArenaStore::instance().insert_order(rej);
+ emit order_executed(pa.agent_id, r.is_ok() ? r.value() : QString(), rej.status);
+ return;
+ }
+ if (!venue_) return; // competition stopped between request and decision
+ if (!agent_is_active(pa.agent_id)) {
+ // Agent halted between the HITL request and the approval — same
+ // immediate-halt rule as finish_agent: record, never execute.
+ OrderRow rej;
+ rej.competition_id = active_id_;
+ rej.agent_id = pa.agent_id;
+ rej.round_seq = pa.seq;
+ rej.coin = pa.action.coin;
+ rej.side = pa.action.side;
+ rej.action = pa.action.kind == ActionKind::Open ? "open" : "close";
+ rej.notional_usd = pa.action.size_usd;
+ rej.leverage = pa.action.leverage;
+ rej.status = "rejected_risk";
+ rej.reject_reason = "agent halted";
+ auto r = ArenaStore::instance().insert_order(rej);
+ emit order_executed(pa.agent_id, r.is_ok() ? r.value() : QString(), rej.status);
+ return;
+ }
+ auto fill = venue_->execute(pa.agent_id, pa.action, pa.seq);
+ if (fill.is_ok()) emit order_executed(pa.agent_id, fill.value().id, fill.value().status);
+ return;
+ }
+}
+
+void ArenaEngine::record_failure(const AgentRow& agent, const QString& kind) {
+ for (auto& a : agents_) {
+ if (a.id != agent.id) continue;
+ a.consecutive_failures += 1;
+ ArenaStore::instance().set_agent_failures(a.id, a.consecutive_failures);
+ if (a.consecutive_failures >= limits_.circuit_threshold) {
+ a.status = "halted_circuit";
+ ArenaStore::instance().set_agent_status(
+ a.id, a.status, QStringLiteral("%1 consecutive %2").arg(a.consecutive_failures).arg(kind));
+ emit agent_status_changed(a.id, a.status, kind);
+ }
+ }
+}
+
+void ArenaEngine::agent_done(int seq) {
+ if (--pending_agents_ > 0) return;
+ settle_round(seq);
+}
+
+void ArenaEngine::settle_round(int seq) {
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ for (const auto& a : agents_) {
+ const auto acct = venue_->account(a.id);
+ EquitySnapshotRow s;
+ s.competition_id = active_id_;
+ s.agent_id = a.id;
+ s.round_seq = seq;
+ s.ts = now;
+ s.equity = acct.equity;
+ s.balance = acct.balance;
+ for (auto it = acct.upnl.begin(); it != acct.upnl.end(); ++it) s.unrealized_pnl += it.value();
+ ArenaStore::instance().insert_equity_snapshot(s);
+ }
+ ArenaStore::instance().complete_round(active_id_, seq, now, "completed");
+ round_in_flight_ = false;
+ emit round_completed(seq);
+}
+
+AccountView ArenaEngine::account_view(const QString& agent_id) const {
+ return venue_ ? venue_->account(agent_id) : AccountView{};
+}
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaEngine.h b/fincept-qt/src/services/alpha_arena/ArenaEngine.h
new file mode 100644
index 000000000..3824e6f5e
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaEngine.h
@@ -0,0 +1,113 @@
+#pragma once
+// ArenaEngine — competition orchestrator (spec §3.1, §7). Singleton; runs
+// while the screen is hidden; UI is a viewer over signals + ArenaStore.
+#include "core/result/Result.h"
+#include "services/alpha_arena/ArenaLlmClient.h"
+#include "services/alpha_arena/ArenaMarketDataIface.h"
+#include "services/alpha_arena/ArenaRisk.h"
+#include "services/alpha_arena/ArenaStore.h"
+#include "services/alpha_arena/ArenaTypes.h"
+#include "services/alpha_arena/PaperExchange.h"
+#include <QTimer>
+#include <memory>
+
+namespace fincept::arena {
+
+class ArenaEngine : public QObject {
+ Q_OBJECT
+ public:
+ static ArenaEngine& instance();
+ void init(); // idempotent; crash-recovery scan (emits crash_recovery_pending)
+
+ Result<QString> create_competition(const ArenaConfig& cfg); // persists; status "created"
+ Result<void> start(const QString& competition_id); // load + begin ticking
+ Result<void> pause(); // status "paused", timer stops
+ Result<void> resume(); // status "running"
+ Result<void> stop(); // status "ended"; positions stay
+ Result<void> kill_all(); // close every position + stop
+ /// Per-agent kill switch: close that agent's positions now, halt it
+ /// ("halted_user"), snapshot its equity. Competition keeps running.
+ Result<void> kill_agent(const QString& agent_id);
+ Result<void> halt_agent(const QString& agent_id);
+ Result<void> resume_agent(const QString& agent_id);
+ Result<void> set_cadence(int seconds); // hot + persisted
+ void force_round(); // immediate round if idle
+
+ /// HITL (live mode): approve/reject a queued action by approval id.
+ /// Approved actions execute at the venue's CURRENT marks; rejections are
+ /// persisted as "rejected_risk" orders with reason "HITL rejected".
+ void resume_after_hitl(const QString& approval_id, bool approved);
+
+ // Crash recovery: competitions found "running" at init(); UI can resume or dismiss.
+ QStringList pending_crash_recoveries() const { return crash_pending_; }
+ void dismiss_crash_recovery(const QString& id); // mark "ended", don't resume
+
+ QString active_competition_id() const { return active_id_; }
+ bool is_running() const { return timer_ && timer_->isActive(); }
+ int round_seq() const { return round_seq_; }
+ int next_round_in_seconds() const;
+ bool round_in_flight() const { return round_in_flight_; }
+
+ /// Live account view for the active competition ({} when none / unknown agent).
+ AccountView account_view(const QString& agent_id) const;
+ /// Current venue marks (mid per coin); empty when no active competition.
+ QHash<QString, double> current_marks() const {
+ return venue_ ? venue_->marks() : QHash<QString, double>{};
+ }
+
+ // Test seams — engine takes ownership; pass BEFORE start().
+ void set_market_for_test(IArenaMarketData* m);
+ void set_llm_for_test(IArenaLlmClient* c);
+ void set_marks_interval_for_test(int ms); // live-marks cadence (default 10s)
+
+ signals:
+ void round_started(int seq);
+ void round_completed(int seq);
+ void round_failed(int seq, QString error);
+ void decision_received(QString decision_id, QString agent_id, QString status);
+ void order_executed(QString agent_id, QString order_id, QString status);
+ void agent_status_changed(QString agent_id, QString status, QString reason);
+ void competition_status_changed(QString competition_id, QString status);
+ void crash_recovery_pending(QStringList competition_ids);
+ /// Live mode: a risk-approved action awaits human approval (resume_after_hitl).
+ void hitl_requested(QString approval_id, QString agent_id, QString summary);
+ /// Between-round live marks landed (venue re-marked; equity views are fresh).
+ void marks_updated();
+
+ private:
+ ArenaEngine();
+ void run_round();
+ void on_snapshot(quint64 epoch, int seq, Result<MarketSnapshot> r);
+ void dispatch_agent(int seq, const AgentRow& agent, const MarketSnapshot& snap, bool is_retry,
+ const QString& prior_raw, const QString& prior_error);
+ void finish_agent(int seq, const AgentRow& agent, const ArenaLlmResult& llm,
+ const QString& sys, const QString& user, bool was_retry);
+ void agent_done(int seq);
+ void settle_round(int seq);
+ void record_failure(const AgentRow& agent, const QString& kind);
+ bool agent_is_active(const QString& agent_id) const; // CURRENT status in agents_
+ void run_marks_tick(); // between-round live marks
+
+ QString active_id_;
+ CompetitionRow comp_;
+ QVector<AgentRow> agents_;
+ QStringList crash_pending_; // "running" rows found at init(), not yet resumed/dismissed
+ quint64 epoch_ = 0; // bumped on start()/stop(); stale async callbacks no-op
+ QTimer* timer_ = nullptr;
+ QTimer* marks_timer_ = nullptr; // between-round live marks (Feature: realtime marks)
+ int marks_interval_ms_ = 10000;
+ bool inited_ = false, round_in_flight_ = false;
+ int round_seq_ = 0, pending_agents_ = 0;
+ qint64 last_mark_ts_ = 0; // ms of the PREVIOUS mark_all (round OR marks tick)
+ // — funding accrues on elapsed-since-last-mark
+ MarketSnapshot last_snapshot_;
+ QHash<QString, double> round_notional_; // agent_id → Σ new notional this round
+ struct PendingApproval { QString id, agent_id; AgentAction action; int seq = 0; };
+ QVector<PendingApproval> pending_hitl_; // live mode only; cleared on stop()/kill_all()
+ std::unique_ptr<PaperExchange> venue_;
+ IArenaMarketData* market_ = nullptr; // owned (parent=this)
+ IArenaLlmClient* llm_ = nullptr; // owned (parent=this)
+ RiskLimits limits_;
+};
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaFakes.h b/fincept-qt/src/services/alpha_arena/ArenaFakes.h
new file mode 100644
index 000000000..d05903e66
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaFakes.h
@@ -0,0 +1,52 @@
+#pragma once
+// Header-only deterministic fakes for --selftest-arena. No network.
+#include "services/alpha_arena/ArenaLlmClient.h"
+#include "services/alpha_arena/ArenaMarketDataIface.h"
+#include <QQueue>
+#include <QTimer>
+
+namespace fincept::arena {
+
+/// Scripted per-model responses; FIFO per model_id; default = hold.
+class FakeLlmClient : public IArenaLlmClient {
+ public:
+ using IArenaLlmClient::IArenaLlmClient;
+ QHash<QString, QQueue<QString>> scripts; // model_id → raw responses
+ void complete(const ArenaLlmRequest& req, std::function<void(ArenaLlmResult)> cb) override {
+ ArenaLlmResult r;
+ r.success = true;
+ r.content = scripts.contains(req.model_id) && !scripts[req.model_id].isEmpty()
+ ? scripts[req.model_id].dequeue()
+ : QStringLiteral(R"({"actions":[{"action":"hold","reason":"default"}]})");
+ r.prompt_tokens = 100; r.completion_tokens = 20; r.latency_ms = 1;
+ // Async like the real client — engine must not assume sync completion.
+ QTimer::singleShot(0, this, [cb, r]() { cb(r); });
+ }
+};
+
+class FakeMarketData : public IArenaMarketData {
+ public:
+ using IArenaMarketData::IArenaMarketData;
+ MarketSnapshot next;
+ bool fail = false;
+ void fetch_snapshot(const QStringList& coins, std::function<void(Result<MarketSnapshot>)> cb) override {
+ MarketSnapshot out = next;
+ QTimer::singleShot(0, this, [this, cb, out]() {
+ if (fail) { cb(Result<MarketSnapshot>::err("scripted failure")); return; }
+ cb(Result<MarketSnapshot>::ok(out));
+ });
+ Q_UNUSED(coins)
+ }
+ void fetch_mids(const QStringList& coins,
+ std::function<void(Result<QHash<QString, double>>)> cb) override {
+ QHash<QString, double> mids;
+ for (auto it = next.coins.begin(); it != next.coins.end(); ++it) mids[it.key()] = it.value().mid;
+ QTimer::singleShot(0, this, [this, cb, mids]() {
+ if (fail) { cb(Result<QHash<QString, double>>::err("scripted failure")); return; }
+ cb(Result<QHash<QString, double>>::ok(mids));
+ });
+ Q_UNUSED(coins)
+ }
+};
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaIndicators.cpp b/fincept-qt/src/services/alpha_arena/ArenaIndicators.cpp
new file mode 100644
index 000000000..44662d9e2
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaIndicators.cpp
@@ -0,0 +1,53 @@
+#include "services/alpha_arena/ArenaIndicators.h"
+#include <cmath>
+namespace fincept::arena {
+
+double ind_ema(const QVector<Candle>& c, int period) {
+ if (c.size() < period || period <= 0) return 0;
+ double ema = 0;
+ for (int i = 0; i < period; ++i) ema += c[i].c;
+ ema /= period;
+ const double k = 2.0 / (period + 1);
+ for (int i = period; i < c.size(); ++i) ema = c[i].c * k + ema * (1 - k);
+ return ema;
+}
+
+double ind_rsi(const QVector<Candle>& c, int period) {
+ if (c.size() <= period) return 50;
+ double gain = 0, loss = 0;
+ for (int i = 1; i <= period; ++i) {
+ const double d = c[i].c - c[i - 1].c;
+ if (d >= 0) gain += d; else loss -= d;
+ }
+ double ag = gain / period, al = loss / period;
+ for (int i = period + 1; i < c.size(); ++i) {
+ const double d = c[i].c - c[i - 1].c;
+ ag = (ag * (period - 1) + (d > 0 ? d : 0)) / period;
+ al = (al * (period - 1) + (d < 0 ? -d : 0)) / period;
+ }
+ if (al <= 1e-12 && ag <= 1e-12) return 50;
+ if (al <= 1e-12) return 100;
+ return 100.0 - 100.0 / (1.0 + ag / al);
+}
+
+double ind_atr(const QVector<Candle>& c, int period) {
+ if (c.size() <= period) return 0;
+ double atr = 0;
+ for (int i = 1; i <= period; ++i)
+ atr += std::max({c[i].h - c[i].l, std::fabs(c[i].h - c[i - 1].c), std::fabs(c[i].l - c[i - 1].c)});
+ atr /= period;
+ for (int i = period + 1; i < c.size(); ++i) {
+ const double tr = std::max({c[i].h - c[i].l, std::fabs(c[i].h - c[i - 1].c), std::fabs(c[i].l - c[i - 1].c)});
+ atr = (atr * (period - 1) + tr) / period;
+ }
+ return atr;
+}
+
+void apply_indicators(CoinSnapshot& s) {
+ s.ema20 = ind_ema(s.candles_1h, 20);
+ s.ema50 = ind_ema(s.candles_1h, 50);
+ s.rsi14 = ind_rsi(s.candles_1h, 14);
+ s.atr14 = ind_atr(s.candles_1h, 14);
+}
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaIndicators.h b/fincept-qt/src/services/alpha_arena/ArenaIndicators.h
new file mode 100644
index 000000000..373572195
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaIndicators.h
@@ -0,0 +1,10 @@
+#pragma once
+// Pure indicator helpers for arena prompts. Input candles oldest → newest.
+#include "services/alpha_arena/ArenaTypes.h"
+namespace fincept::arena {
+double ind_ema(const QVector<Candle>& c, int period); // 0 if c.size() < period
+double ind_rsi(const QVector<Candle>& c, int period); // Wilder; 50 if insufficient
+double ind_atr(const QVector<Candle>& c, int period); // 0 if insufficient
+/// Fills ema20/ema50/rsi14/atr14 on the snapshot from candles_1h.
+void apply_indicators(CoinSnapshot& s);
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaLlmClient.cpp b/fincept-qt/src/services/alpha_arena/ArenaLlmClient.cpp
new file mode 100644
index 000000000..0bfd624ed
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaLlmClient.cpp
@@ -0,0 +1,141 @@
+#include "services/alpha_arena/ArenaLlmClient.h"
+#include "auth/AuthManager.h"
+#include "core/config/AppConfig.h"
+#include "services/llm/ModelCatalog.h"
+#include "services/llm/ProviderCatalog.h"
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QNetworkReply>
+#include <QNetworkRequest>
+#include <QTimer>
+
+namespace fincept::arena {
+using fincept::ai_chat::ModelCatalog;
+using fincept::ai_chat::ProviderCatalog;
+
+ArenaLlmClient::ArenaLlmClient(QObject* parent) : IArenaLlmClient(parent) {
+ nam_ = new QNetworkAccessManager(this);
+}
+
+QByteArray ArenaLlmClient::build_body(const ArenaLlmRequest& req) {
+ const QString p = req.provider.toLower();
+ int max_tokens = req.max_tokens;
+ if (const int cap = ModelCatalog::output_cap(p, req.model_id); cap > 0)
+ max_tokens = qMin(max_tokens, cap);
+
+ QJsonObject body;
+ if (p == "anthropic") {
+ body["model"] = req.model_id;
+ body["max_tokens"] = max_tokens;
+ body["system"] = req.system_prompt;
+ body["messages"] = QJsonArray{QJsonObject{{"role", "user"}, {"content", req.user_prompt}}};
+ } else if (p == "gemini" || p == "google") {
+ body["systemInstruction"] = QJsonObject{{"parts", QJsonArray{QJsonObject{{"text", req.system_prompt}}}}};
+ body["contents"] = QJsonArray{QJsonObject{{"role", "user"},
+ {"parts", QJsonArray{QJsonObject{{"text", req.user_prompt}}}}}};
+ body["generationConfig"] = QJsonObject{{"maxOutputTokens", max_tokens}};
+ } else { // OpenAI-compatible family + fincept (/research/chat takes OpenAI messages)
+ body["messages"] = QJsonArray{
+ QJsonObject{{"role", "system"}, {"content", req.system_prompt}},
+ QJsonObject{{"role", "user"}, {"content", req.user_prompt}}};
+ if (p != "fincept" || (req.model_id != "fincept-llm" && !req.model_id.isEmpty()))
+ body["model"] = req.model_id;
+ if (p != "fincept") {
+ if (p == "openai" || p == "xai") body["max_completion_tokens"] = max_tokens;
+ else body["max_tokens"] = max_tokens;
+ }
+ }
+ return QJsonDocument(body).toJson(QJsonDocument::Compact);
+}
+
+ArenaLlmResult ArenaLlmClient::parse_response(const QString& provider, const QByteArray& body) {
+ ArenaLlmResult r;
+ const QString p = provider.toLower();
+ const QJsonObject o = QJsonDocument::fromJson(body).object();
+ if (o.isEmpty()) { r.error = "non-JSON response"; return r; }
+ if (o.contains("error")) {
+ const auto e = o.value("error");
+ r.error = e.isObject() ? e.toObject().value("message").toString() : e.toString();
+ if (r.error.isEmpty()) r.error = "provider error";
+ return r;
+ }
+ if (p == "anthropic") {
+ for (const auto& blk : o.value("content").toArray())
+ if (blk.toObject().value("type").toString() == "text")
+ r.content += blk.toObject().value("text").toString();
+ const auto u = o.value("usage").toObject();
+ r.prompt_tokens = u.value("input_tokens").toInt();
+ r.completion_tokens = u.value("output_tokens").toInt();
+ } else if (p == "gemini" || p == "google") {
+ const auto cands = o.value("candidates").toArray();
+ if (!cands.isEmpty())
+ for (const auto& part : cands[0].toObject().value("content").toObject().value("parts").toArray())
+ r.content += part.toObject().value("text").toString();
+ const auto u = o.value("usageMetadata").toObject();
+ r.prompt_tokens = u.value("promptTokenCount").toInt();
+ r.completion_tokens = u.value("candidatesTokenCount").toInt();
+ } else {
+ const auto choices = o.value("choices").toArray();
+ if (!choices.isEmpty())
+ r.content = choices[0].toObject().value("message").toObject().value("content").toString();
+ if (r.content.isEmpty()) // fincept /research/chat tolerant fallbacks
+ r.content = o.value("content").toString();
+ if (r.content.isEmpty())
+ r.content = o.value("response").toString();
+ const auto u = o.value("usage").toObject();
+ r.prompt_tokens = u.value("prompt_tokens").toInt();
+ r.completion_tokens = u.value("completion_tokens").toInt();
+ }
+ if (r.content.isEmpty()) { r.error = "empty completion"; return r; }
+ r.success = true;
+ return r;
+}
+
+void ArenaLlmClient::complete(const ArenaLlmRequest& req, std::function<void(ArenaLlmResult)> cb) {
+ const QString p = req.provider.toLower();
+ QString url = ProviderCatalog::chat_endpoint(p, req.base_url, req.model_id);
+ if (p == "fincept")
+ url = fincept::AppConfig::instance().api_base_url() + "/research/chat";
+ if (url.isEmpty()) { ArenaLlmResult r; r.error = "no endpoint for provider " + p; cb(r); return; }
+
+ QNetworkRequest nr{QUrl(url)};
+ nr.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
+ if (p == "anthropic") {
+ nr.setRawHeader("x-api-key", req.api_key.toUtf8());
+ nr.setRawHeader("anthropic-version", "2023-06-01");
+ } else if (p == "gemini" || p == "google") {
+ nr.setRawHeader("x-goog-api-key", req.api_key.toUtf8());
+ } else if (p == "fincept") {
+ if (!req.api_key.isEmpty()) nr.setRawHeader("X-API-Key", req.api_key.toUtf8());
+ const auto& sess = fincept::auth::AuthManager::instance().session();
+ if (!sess.session_token.isEmpty()) nr.setRawHeader("X-Session-Token", sess.session_token.toUtf8());
+ nr.setRawHeader("User-Agent", "FinceptTerminal/4.0");
+ } else if (!req.api_key.isEmpty()) {
+ nr.setRawHeader("Authorization", ("Bearer " + req.api_key).toUtf8());
+ }
+
+ const qint64 t0 = QDateTime::currentMSecsSinceEpoch();
+ QNetworkReply* reply = nam_->post(nr, build_body(req));
+ auto* timeout = new QTimer(reply);
+ timeout->setSingleShot(true);
+ QObject::connect(timeout, &QTimer::timeout, reply, &QNetworkReply::abort);
+ timeout->start(req.timeout_ms);
+
+ const QString provider = p;
+ QObject::connect(reply, &QNetworkReply::finished, this, [reply, provider, t0, cb]() {
+ reply->deleteLater();
+ ArenaLlmResult r;
+ r.latency_ms = QDateTime::currentMSecsSinceEpoch() - t0;
+ const QByteArray body = reply->readAll();
+ if (reply->error() == QNetworkReply::OperationCanceledError) { r.error = "timeout"; cb(r); return; }
+ if (reply->error() != QNetworkReply::NoError && body.isEmpty()) { r.error = reply->errorString(); cb(r); return; }
+ // Provider errors often arrive as HTTP 4xx with a JSON body — parse it.
+ ArenaLlmResult parsed = parse_response(provider, body);
+ parsed.latency_ms = r.latency_ms;
+ cb(parsed);
+ });
+}
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaLlmClient.h b/fincept-qt/src/services/alpha_arena/ArenaLlmClient.h
new file mode 100644
index 000000000..d1383284a
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaLlmClient.h
@@ -0,0 +1,44 @@
+#pragma once
+// ArenaLlmClient — stateless native multi-provider completion client (spec §3.3).
+// One complete() call = one decision request. Parallel-safe: each call owns its
+// QNetworkReply. Response parsing is a pure static for selftest coverage.
+#include <QNetworkAccessManager>
+#include <QObject>
+#include <functional>
+
+namespace fincept::arena {
+
+struct ArenaLlmRequest {
+ QString provider, model_id, api_key, base_url, system_prompt, user_prompt;
+ int max_tokens = 2048;
+ int timeout_ms = 60000;
+};
+struct ArenaLlmResult {
+ QString content, error;
+ int prompt_tokens = 0, completion_tokens = 0;
+ qint64 latency_ms = 0;
+ bool success = false;
+};
+
+class IArenaLlmClient : public QObject {
+ Q_OBJECT
+ public:
+ using QObject::QObject;
+ virtual void complete(const ArenaLlmRequest& req, std::function<void(ArenaLlmResult)> cb) = 0;
+};
+
+class ArenaLlmClient : public IArenaLlmClient {
+ Q_OBJECT
+ public:
+ explicit ArenaLlmClient(QObject* parent = nullptr);
+ void complete(const ArenaLlmRequest& req, std::function<void(ArenaLlmResult)> cb) override;
+
+ // Pure helpers (selftest-covered):
+ static QByteArray build_body(const ArenaLlmRequest& req);
+ static ArenaLlmResult parse_response(const QString& provider, const QByteArray& body);
+
+ private:
+ QNetworkAccessManager* nam_ = nullptr; // GUI-thread QNAM (like LlmService::models_nam_)
+};
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaMarketData.cpp b/fincept-qt/src/services/alpha_arena/ArenaMarketData.cpp
new file mode 100644
index 000000000..d1f40b0b2
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaMarketData.cpp
@@ -0,0 +1,119 @@
+#include "services/alpha_arena/ArenaMarketData.h"
+#include "core/logging/Logger.h"
+#include "services/alpha_arena/ArenaIndicators.h"
+#include "trading/exchanges/hyperliquid/HyperliquidClient.h"
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonObject>
+#include <memory>
+
+namespace fincept::arena {
+using fincept::trading::hyperliquid::HyperliquidClient;
+
+ArenaMarketData::ArenaMarketData(QObject* parent) : IArenaMarketData(parent) {
+ client_ = new HyperliquidClient(this);
+}
+
+QHash<QString, double> ArenaMarketData::parse_all_mids(const QJsonDocument& doc, const QStringList& coins) {
+ QHash<QString, double> out;
+ const QJsonObject o = doc.object();
+ for (const QString& c : coins)
+ if (o.contains(c)) out[c] = o.value(c).toString().toDouble();
+ return out;
+}
+
+void ArenaMarketData::apply_asset_ctxs(const QJsonDocument& doc, MarketSnapshot& snap) {
+ const QJsonArray top = doc.array();
+ if (top.size() < 2) return;
+ const QJsonArray universe = top[0].toObject().value("universe").toArray();
+ const QJsonArray ctxs = top[1].toArray();
+ for (int i = 0; i < universe.size() && i < ctxs.size(); ++i) {
+ const QString name = universe[i].toObject().value("name").toString();
+ if (!snap.coins.contains(name)) continue;
+ const QJsonObject c = ctxs[i].toObject();
+ auto& s = snap.coins[name];
+ s.funding_rate = c.value("funding").toString().toDouble();
+ s.open_interest = c.value("openInterest").toString().toDouble();
+ const double prev = c.value("prevDayPx").toString().toDouble();
+ if (prev > 0 && s.mid > 0) s.day_change_pct = (s.mid - prev) / prev * 100.0;
+ }
+}
+
+QVector<Candle> ArenaMarketData::parse_candles(const QJsonDocument& doc) {
+ QVector<Candle> out;
+ for (const auto& v : doc.array()) {
+ const QJsonObject o = v.toObject();
+ Candle k;
+ k.t = qint64(o.value("t").toDouble());
+ k.o = o.value("o").toString().toDouble();
+ k.h = o.value("h").toString().toDouble();
+ k.l = o.value("l").toString().toDouble();
+ k.c = o.value("c").toString().toDouble();
+ k.v = o.value("v").toString().toDouble();
+ out.append(k);
+ }
+ return out;
+}
+
+void ArenaMarketData::fetch_mids(const QStringList& coins,
+ std::function<void(Result<QHash<QString, double>>)> cb) {
+ auto coins_copy = coins;
+ client_->info(QJsonObject{{"type", "allMids"}}, [coins_copy, cb](Result<QJsonDocument> r) {
+ if (r.is_err()) { cb(Result<QHash<QString, double>>::err(r.error())); return; }
+ const auto mids = parse_all_mids(r.value(), coins_copy);
+ if (mids.isEmpty()) { cb(Result<QHash<QString, double>>::err("no mids for requested coins")); return; }
+ cb(Result<QHash<QString, double>>::ok(mids));
+ });
+}
+
+void ArenaMarketData::fetch_snapshot(const QStringList& coins,
+ std::function<void(Result<MarketSnapshot>)> cb) {
+ // Chain: allMids → metaAndAssetCtxs → N candleSnapshots → done.
+ auto snap = std::make_shared<MarketSnapshot>();
+ snap->ts = QDateTime::currentMSecsSinceEpoch();
+ auto coins_copy = coins;
+
+ client_->info(QJsonObject{{"type", "allMids"}}, [this, snap, coins_copy, cb](Result<QJsonDocument> r) {
+ if (r.is_err()) { cb(Result<MarketSnapshot>::err(r.error())); return; }
+ const auto mids = parse_all_mids(r.value(), coins_copy);
+ if (mids.isEmpty()) { cb(Result<MarketSnapshot>::err("no mids for requested coins")); return; }
+ for (auto it = mids.begin(); it != mids.end(); ++it) {
+ CoinSnapshot s; s.coin = it.key(); s.mid = it.value();
+ snap->coins[it.key()] = s;
+ }
+ client_->info(QJsonObject{{"type", "metaAndAssetCtxs"}}, [this, snap, cb](Result<QJsonDocument> r2) {
+ if (r2.is_ok()) apply_asset_ctxs(r2.value(), *snap); // ctxs are enrichment — non-fatal
+ // Candles per coin, sequential chain to stay simple + rate-limit friendly.
+ // *step holds a weak ref to itself (pending network callbacks hold the
+ // strong ref) so the self-referencing chain frees once it completes.
+ auto remaining = std::make_shared<QStringList>(snap->coins.keys());
+ auto step = std::make_shared<std::function<void()>>();
+ std::weak_ptr<std::function<void()>> wstep = step;
+ *step = [this, snap, remaining, cb, wstep]() {
+ if (remaining->isEmpty()) {
+ for (auto& s : snap->coins) apply_indicators(s);
+ cb(Result<MarketSnapshot>::ok(*snap));
+ return;
+ }
+ const QString coin = remaining->takeFirst();
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ const QJsonObject req{{"coin", coin}, {"interval", "1h"},
+ {"startTime", double(now - 60ll * 3600 * 1000)}, {"endTime", double(now)}};
+ auto strong = wstep.lock();
+ client_->info(QJsonObject{{"type", "candleSnapshot"}, {"req", req}},
+ [snap, coin, strong](Result<QJsonDocument> r3) {
+ if (r3.is_ok())
+ snap->coins[coin].candles_1h = parse_candles(r3.value());
+ else
+ LOG_WARN("ArenaMarketData",
+ QStringLiteral("candleSnapshot failed for %1: %2 (indicators will be n/a)")
+ .arg(coin, QString::fromStdString(r3.error())));
+ if (strong) (*strong)();
+ });
+ };
+ (*step)();
+ });
+ });
+}
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaMarketData.h b/fincept-qt/src/services/alpha_arena/ArenaMarketData.h
new file mode 100644
index 000000000..087c92780
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaMarketData.h
@@ -0,0 +1,36 @@
+#pragma once
+// ArenaMarketData — keyless Hyperliquid public-info market data (spec §3.2).
+// POST https://api.hyperliquid.xyz/info with {"type":"allMids"} /
+// {"type":"metaAndAssetCtxs"} / {"type":"candleSnapshot",...} — verified live
+// keyless 2026-06-10. Built on trading/exchanges/hyperliquid/HyperliquidClient.
+// allMids also returns builder-deployed "#NNNN" assets — we filter to the
+// requested coin list. Pure parsers are static for selftest fixtures.
+#include "services/alpha_arena/ArenaMarketDataIface.h"
+#include <QJsonDocument>
+namespace fincept::trading::hyperliquid { class HyperliquidClient; }
+
+namespace fincept::arena {
+
+class ArenaMarketData : public IArenaMarketData {
+ Q_OBJECT
+ public:
+ explicit ArenaMarketData(QObject* parent = nullptr);
+ /// allMids + metaAndAssetCtxs + per-coin 1h candleSnapshot (last 60 bars),
+ /// merged into one MarketSnapshot with indicators applied.
+ void fetch_snapshot(const QStringList& coins,
+ std::function<void(Result<MarketSnapshot>)> cb) override;
+ /// Single {"type":"allMids"} call → coin→mid (live-marks loop between rounds).
+ void fetch_mids(const QStringList& coins,
+ std::function<void(Result<QHash<QString, double>>)> cb) override;
+
+ // Pure parsers (selftest-covered):
+ static QHash<QString, double> parse_all_mids(const QJsonDocument& doc, const QStringList& coins);
+ /// metaAndAssetCtxs → (funding, open_interest, prev_day_px) per coin.
+ static void apply_asset_ctxs(const QJsonDocument& doc, MarketSnapshot& snap);
+ static QVector<Candle> parse_candles(const QJsonDocument& doc);
+
+ private:
+ fincept::trading::hyperliquid::HyperliquidClient* client_ = nullptr;
+};
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaMarketDataIface.h b/fincept-qt/src/services/alpha_arena/ArenaMarketDataIface.h
new file mode 100644
index 000000000..ec882629e
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaMarketDataIface.h
@@ -0,0 +1,18 @@
+#pragma once
+#include "core/result/Result.h"
+#include "services/alpha_arena/ArenaTypes.h"
+#include <QHash>
+#include <QObject>
+#include <functional>
+namespace fincept::arena {
+class IArenaMarketData : public QObject {
+ Q_OBJECT
+ public:
+ using QObject::QObject;
+ virtual void fetch_snapshot(const QStringList& coins,
+ std::function<void(Result<MarketSnapshot>)> cb) = 0;
+ /// Lightweight coin→mid fetch for between-round live marks (one allMids call).
+ virtual void fetch_mids(const QStringList& coins,
+ std::function<void(Result<QHash<QString, double>>)> cb) = 0;
+};
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaModelRegistry.cpp b/fincept-qt/src/services/alpha_arena/ArenaModelRegistry.cpp
new file mode 100644
index 000000000..537b69d79
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaModelRegistry.cpp
@@ -0,0 +1,128 @@
+#include "services/alpha_arena/ArenaModelRegistry.h"
+#include "core/logging/Logger.h"
+#include "services/llm/LlmService.h"
+#include "services/llm/ProviderCatalog.h"
+#include "storage/repositories/LlmConfigRepository.h"
+#include "storage/repositories/LlmProfileRepository.h"
+#include <QSet>
+
+namespace fincept::arena {
+using fincept::ai_chat::ProviderCatalog;
+
+namespace {
+// A failed settings read must not look like "no models configured".
+void warn_layer_err(const char* layer, const std::string& err) {
+ LOG_WARN("ArenaModelRegistry",
+ QStringLiteral("%1 read failed: %2").arg(QLatin1String(layer), QString::fromStdString(err)));
+}
+} // namespace
+
+ArenaModelRegistry& ArenaModelRegistry::instance() { static ArenaModelRegistry r; return r; }
+
+ArenaModelRegistry::ArenaModelRegistry() {
+ connect(&fincept::ai_chat::LlmService::instance(), &fincept::ai_chat::LlmService::config_changed,
+ this, &ArenaModelRegistry::models_changed);
+}
+
+QVector<ArenaModelOption> ArenaModelRegistry::available_models() const {
+ QVector<ArenaModelOption> out;
+ QSet<QString> seen;
+ QSet<QString> providers_present; // providers that contributed in layers 1-3
+ auto add = [&](ArenaModelOption o) {
+ const QString key = o.provider.toLower() + "/" + o.model_id;
+ if (o.model_id.isEmpty() || seen.contains(key)) return;
+ seen.insert(key);
+ if (o.color_hex.isEmpty()) o.color_hex = ProviderCatalog::brand_color(o.provider);
+ out.append(std::move(o));
+ };
+
+ // 1. Profiles (highest priority — explicit user intent).
+ if (auto r = LlmProfileRepository::instance().list_profiles(); r.is_err())
+ warn_layer_err("profiles", r.error());
+ else
+ for (const auto& p : r.value()) {
+ providers_present.insert(p.provider.toLower());
+ ArenaModelOption o;
+ o.provider = p.provider; o.model_id = p.model_id;
+ o.display_name = p.name + " (" + p.model_id + ")";
+ o.source_kind = "profile"; o.source_ref = p.id;
+ o.ready = !p.api_key.isEmpty() || !ProviderCatalog::requires_api_key(p.provider);
+ add(o);
+ }
+ // 2. Custom model configs.
+ if (auto r = LlmConfigRepository::instance().list_models(); r.is_err())
+ warn_layer_err("model configs", r.error());
+ else
+ for (const auto& m : r.value()) {
+ if (!m.is_enabled) continue;
+ providers_present.insert(m.provider.toLower());
+ ArenaModelOption o;
+ o.provider = m.provider; o.model_id = m.model_id;
+ o.display_name = m.display_name.isEmpty() ? m.model_id : m.display_name;
+ o.source_kind = "model"; o.source_ref = m.id;
+ o.ready = !m.api_key.isEmpty() || !ProviderCatalog::requires_api_key(m.provider);
+ add(o);
+ }
+ // 3. Provider rows — configured model + catalog fallbacks. NOT filtered on
+ // is_active (that marks the chat-active provider, not validity).
+ if (auto r = LlmConfigRepository::instance().list_providers(); r.is_err())
+ warn_layer_err("providers", r.error());
+ else
+ for (const auto& c : r.value()) {
+ providers_present.insert(c.provider.toLower());
+ const bool ready = !c.api_key.isEmpty() || !ProviderCatalog::requires_api_key(c.provider);
+ QStringList models = ProviderCatalog::fallback_models(c.provider);
+ if (!c.model.isEmpty() && !models.contains(c.model)) models.prepend(c.model);
+ for (const QString& mid : models) {
+ ArenaModelOption o;
+ o.provider = c.provider; o.model_id = mid;
+ o.display_name = ProviderCatalog::display_name(c.provider) + " / " + mid;
+ o.source_kind = "provider"; o.source_ref = c.provider;
+ o.ready = ready;
+ add(o);
+ }
+ }
+ // 4. Catalog browse layer — every known provider is selectable in the
+ // wizard even without an llm_configs row yet. Skipped for providers that
+ // already contributed above (their rows carry real key/model state).
+ // ready only for keyless providers (ollama/fincept); ollama's fallback
+ // list is intentionally empty (live /api/tags), so it may add nothing.
+ for (const QString& p : ProviderCatalog::known_providers()) {
+ if (providers_present.contains(p.toLower())) continue;
+ const bool ready = !ProviderCatalog::requires_api_key(p);
+ for (const QString& mid : ProviderCatalog::fallback_models(p)) {
+ ArenaModelOption o;
+ o.provider = p; o.model_id = mid;
+ o.display_name = ProviderCatalog::display_name(p) + " / " + mid;
+ o.source_kind = "provider"; o.source_ref = p;
+ o.ready = ready;
+ add(o);
+ }
+ }
+ return out;
+}
+
+Result<ArenaCredentials> ArenaModelRegistry::resolve_credentials(const QString& source_kind,
+ const QString& source_ref,
+ const QString& provider) const {
+ ArenaCredentials cred;
+ if (source_kind == QLatin1String("profile")) {
+ if (auto r = LlmProfileRepository::instance().list_profiles(); r.is_ok())
+ for (const auto& p : r.value())
+ if (p.id == source_ref) { cred.api_key = p.api_key; cred.base_url = p.base_url; break; }
+ } else if (source_kind == QLatin1String("model")) {
+ if (auto r = LlmConfigRepository::instance().list_models(); r.is_ok())
+ for (const auto& m : r.value())
+ if (m.id == source_ref) { cred.api_key = m.api_key; cred.base_url = m.base_url; break; }
+ } else { // "provider"
+ if (auto r = LlmConfigRepository::instance().list_providers(); r.is_ok())
+ for (const auto& c : r.value())
+ if (c.provider == provider) { cred.api_key = c.api_key; cred.base_url = c.base_url; break; }
+ }
+ if (cred.base_url.isEmpty()) cred.base_url = ProviderCatalog::default_base_url(provider);
+ if (cred.api_key.isEmpty() && ProviderCatalog::requires_api_key(provider))
+ return Result<ArenaCredentials>::err("no API key configured for " + provider.toStdString());
+ return Result<ArenaCredentials>::ok(cred);
+}
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaModelRegistry.h b/fincept-qt/src/services/alpha_arena/ArenaModelRegistry.h
new file mode 100644
index 000000000..53221ec91
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaModelRegistry.h
@@ -0,0 +1,39 @@
+#pragma once
+// ArenaModelRegistry — unified model discovery + round-time credential
+// resolution across all 3 LLM settings layers (spec §3.4). Keys are NEVER
+// cached or stored here.
+#include "core/result/Result.h"
+#include <QObject>
+#include <QString>
+#include <QVector>
+
+namespace fincept::arena {
+
+struct ArenaModelOption {
+ QString provider, model_id, display_name, color_hex;
+ QString source_kind; // "profile" | "model" | "provider"
+ QString source_ref; // profile/model row id; provider name for "provider"
+ bool ready = false; // best-effort UI hint as of list time;
+ // resolve_credentials() is authoritative at round time
+};
+struct ArenaCredentials { QString api_key, base_url; };
+
+// All methods are GUI-thread-only (the singleton settings repositories are
+// not synchronized).
+class ArenaModelRegistry : public QObject {
+ Q_OBJECT
+ public:
+ static ArenaModelRegistry& instance();
+ /// Merged, deduplicated by (provider, model_id). Priority: profile > model > provider.
+ QVector<ArenaModelOption> available_models() const;
+ /// Round-time resolution; reads Settings storage live.
+ Result<ArenaCredentials> resolve_credentials(const QString& source_kind,
+ const QString& source_ref,
+ const QString& provider) const;
+ signals:
+ void models_changed();
+ private:
+ ArenaModelRegistry(); // connects LlmService::config_changed → models_changed
+};
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaPrompts.cpp b/fincept-qt/src/services/alpha_arena/ArenaPrompts.cpp
new file mode 100644
index 000000000..ca880c28e
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaPrompts.cpp
@@ -0,0 +1,85 @@
+#include "services/alpha_arena/ArenaPrompts.h"
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
+
+namespace fincept::arena {
+
+QString decision_contract() {
+ return QStringLiteral(
+ "\n\nOUTPUT FORMAT — reply with ONLY this JSON object, no prose, no markdown:\n"
+ "{\"actions\":[\n"
+ " {\"action\":\"open\",\"coin\":\"BTC\",\"side\":\"long|short\",\"size_usd\":2000,\"leverage\":3,\"reason\":\"...\"},\n"
+ " {\"action\":\"close\",\"coin\":\"ETH\",\"reason\":\"...\"},\n"
+ " {\"action\":\"hold\",\"reason\":\"...\"}\n"
+ "]}\n"
+ "Rules: every action needs a reason. size_usd is position notional in USD. "
+ "close with no size_usd closes the whole position; with size_usd it reduces. "
+ "If you want no changes this round, return a single hold action.");
+}
+
+QString system_prompt(const CompetitionRow& comp) {
+ if (!comp.system_prompt_override.isEmpty())
+ return comp.system_prompt_override + decision_contract();
+ return QStringLiteral(
+ "You are an autonomous crypto perpetual-futures trader competing against other AI models "
+ "in the Fincept Alpha Arena. You each started with $%1 and trade the same market data. "
+ "Your goal: the highest risk-adjusted return.\n\n"
+ "Constraints:\n"
+ "- Instruments: %2 (USD-margined perps, long or short)\n"
+ "- Max leverage: %3x. Taker fee 0.045%. Funding accrues hourly.\n"
+ "- One position per coin. Opening the opposite side flips the position.\n"
+ "- A decision round happens every %4 seconds; between rounds your positions ride the market.\n"
+ "- If your margin is exhausted you are liquidated — survival matters.\n"
+ "Be decisive but size positions so a single move against you cannot end your run.")
+ .arg(QString::number(comp.capital_per_agent, 'f', 0), comp.instruments.join(", "),
+ QString::number(comp.max_leverage, 'f', 0), QString::number(comp.cadence_seconds))
+ + decision_contract();
+}
+
+QString user_prompt(const MarketSnapshot& market, const AccountView& acct,
+ const QVector<DecisionRow>& recent, int round_seq, qint64 started_at) {
+ QString s;
+ // market.ts is the round's snapshot time — keeps the prompt deterministic
+ // from inputs (no wall-clock read), so identical rounds hash identically.
+ s += QStringLiteral("ROUND %1 — elapsed %2 min\n\nMARKET\n")
+ .arg(round_seq).arg((market.ts - started_at) / 60000);
+ for (const auto& c : market.coins) {
+ // Indicators come from candles; with no candle data, zeroed EMA/ATR and
+ // a neutral RSI would read as real signal to the model — say n/a instead.
+ const QString ind = c.candles_1h.isEmpty()
+ ? QStringLiteral("indicators n/a (no candle data)")
+ : QStringLiteral("EMA20 %1 | EMA50 %2 | RSI14 %3 | ATR14 %4")
+ .arg(c.ema20, 0, 'g', 8).arg(c.ema50, 0, 'g', 8)
+ .arg(c.rsi14, 0, 'f', 1).arg(c.atr14, 0, 'g', 6);
+ s += QStringLiteral("%1: mid %2 | 24h %3% | funding %4%/hr | OI %5 | %6\n")
+ .arg(c.coin).arg(c.mid, 0, 'g', 8).arg(c.day_change_pct, 0, 'f', 2)
+ .arg(c.funding_rate * 100, 0, 'f', 4).arg(c.open_interest, 0, 'g', 6)
+ .arg(ind);
+ if (!c.candles_1h.isEmpty()) {
+ s += QStringLiteral(" last 1h closes:");
+ const int n = std::min<qsizetype>(12, c.candles_1h.size());
+ for (int i = c.candles_1h.size() - n; i < c.candles_1h.size(); ++i)
+ s += QStringLiteral(" %1").arg(c.candles_1h[i].c, 0, 'g', 8);
+ s += '\n';
+ }
+ }
+ s += QStringLiteral("\nYOUR ACCOUNT\nequity $%1 | free balance $%2 | margin used $%3\n")
+ .arg(acct.equity, 0, 'f', 2).arg(acct.balance, 0, 'f', 2).arg(acct.margin_used, 0, 'f', 2);
+ if (acct.positions.isEmpty()) s += QStringLiteral("no open positions\n");
+ for (const auto& p : acct.positions)
+ s += QStringLiteral("%1 %2 qty %3 @ entry %4 (%5x) | uPnL $%6\n")
+ .arg(p.side.toUpper(), p.coin).arg(p.qty, 0, 'g', 8)
+ .arg(p.entry_price, 0, 'g', 8).arg(p.leverage, 0, 'f', 1)
+ .arg(acct.upnl.value(p.coin), 0, 'f', 2);
+ if (!recent.isEmpty()) {
+ s += QStringLiteral("\nYOUR RECENT DECISIONS\n");
+ for (const auto& d : recent)
+ s += QStringLiteral("round %1: %2%3\n").arg(d.round_seq).arg(d.actions_json.left(220),
+ d.parse_error.isEmpty() ? QString() : QStringLiteral(" [parse_error]"));
+ }
+ s += QStringLiteral("\nDecide your actions for this round.");
+ return s;
+}
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaPrompts.h b/fincept-qt/src/services/alpha_arena/ArenaPrompts.h
new file mode 100644
index 000000000..87254deb9
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaPrompts.h
@@ -0,0 +1,11 @@
+#pragma once
+// ArenaPrompts — deterministic system/user prompt builders (spec §3.5).
+#include "services/alpha_arena/ArenaTypes.h"
+#include "services/alpha_arena/PaperExchange.h"
+namespace fincept::arena {
+/// JSON output contract appended to EVERY system prompt (also the override).
+QString decision_contract();
+QString system_prompt(const CompetitionRow& comp);
+QString user_prompt(const MarketSnapshot& market, const AccountView& acct,
+ const QVector<DecisionRow>& recent, int round_seq, qint64 started_at);
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaRisk.cpp b/fincept-qt/src/services/alpha_arena/ArenaRisk.cpp
new file mode 100644
index 000000000..99093743c
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaRisk.cpp
@@ -0,0 +1,22 @@
+#include "services/alpha_arena/ArenaRisk.h"
+namespace fincept::arena {
+RiskVerdict evaluate(const AgentAction& a, const AccountView& acct,
+ const RiskLimits& lim, double round_notional_so_far) {
+ // Close (full or partial reduce) and hold never increase risk → always allowed.
+ if (a.kind != ActionKind::Open) return {true, {}};
+ if (acct.equity <= 0)
+ return {false, QStringLiteral("account equity exhausted")};
+ if (a.leverage < 1)
+ return {false, QStringLiteral("leverage must be >= 1")};
+ if (a.leverage > lim.max_leverage)
+ return {false, QStringLiteral("leverage %1 > cap %2").arg(a.leverage).arg(lim.max_leverage)};
+ if (a.size_usd > lim.max_position_equity_frac * acct.equity)
+ return {false, QStringLiteral("position %1 > %2% of equity")
+ .arg(a.size_usd).arg(lim.max_position_equity_frac * 100)};
+ if (round_notional_so_far + a.size_usd > lim.max_round_notional_frac * acct.equity)
+ return {false, QStringLiteral("round notional cap exceeded")};
+ if (a.size_usd / a.leverage > acct.balance)
+ return {false, QStringLiteral("insufficient free balance")};
+ return {true, {}};
+}
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaRisk.h b/fincept-qt/src/services/alpha_arena/ArenaRisk.h
new file mode 100644
index 000000000..136e0b342
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaRisk.h
@@ -0,0 +1,16 @@
+#pragma once
+// ArenaRisk — pre-trade caps (spec §3.8). Pure functions; circuit counting
+// lives on AgentRow.consecutive_failures via ArenaStore.
+#include "services/alpha_arena/ArenaTypes.h"
+#include "services/alpha_arena/PaperExchange.h"
+namespace fincept::arena {
+struct RiskVerdict { bool approved = false; QString reason; };
+struct RiskLimits {
+ double max_leverage = 10;
+ double max_position_equity_frac = 0.5; // per-position notional ≤ 50% equity
+ double max_round_notional_frac = 1.0; // Σ new notional per round ≤ 100% equity
+ int circuit_threshold = 3;
+};
+RiskVerdict evaluate(const AgentAction& a, const AccountView& acct,
+ const RiskLimits& lim, double round_notional_so_far);
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaSelftest.cpp b/fincept-qt/src/services/alpha_arena/ArenaSelftest.cpp
new file mode 100644
index 000000000..17b9cd4de
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaSelftest.cpp
@@ -0,0 +1,588 @@
+// ArenaSelftest.cpp
+// Headless self-test for the Alpha Arena rewrite (no GUI/network/LLM/keys).
+// Run: QT_QPA_PLATFORM=offscreen FinceptTerminal --selftest-arena --profile aatest
+// Sections are appended by each backend task; returns 0 iff every check passes.
+
+#include "services/alpha_arena/ArenaDecisionParser.h"
+#include "services/alpha_arena/ArenaEngine.h"
+#include "services/alpha_arena/ArenaFakes.h"
+#include "services/alpha_arena/ArenaIndicators.h"
+#include "services/alpha_arena/ArenaLlmClient.h"
+#include "services/alpha_arena/ArenaMarketData.h"
+#include "services/alpha_arena/ArenaModelRegistry.h"
+#include "services/alpha_arena/ArenaPrompts.h"
+#include "services/alpha_arena/ArenaRisk.h"
+#include "services/alpha_arena/ArenaSelftest.h"
+#include "services/alpha_arena/ArenaStore.h"
+#include "services/alpha_arena/PaperExchange.h"
+#include "services/alpha_arena/ArenaTypes.h"
+#include "services/llm/ProviderCatalog.h"
+
+#include <QDateTime>
+#include <QEventLoop>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QSet>
+#include <QString>
+#include <cmath>
+#include <cstdio>
+
+namespace fincept::arena {
+namespace {
+bool approx(double a, double b, double eps = 0.01) { return std::fabs(a - b) <= eps; }
+} // namespace
+
+int run_arena_selftest() {
+ int failures = 0;
+ auto check = [&](const char* label, bool ok) {
+ std::printf("[%s] %s\n", ok ? "PASS" : "FAIL", label);
+ if (!ok) ++failures;
+ };
+
+ // ── Section 1: store round-trips ────────────────────────────────────────
+ auto& store = ArenaStore::instance();
+ // Clean any prior selftest leftovers.
+ if (auto lr = store.list_competitions(); lr.is_ok())
+ for (const auto& c : lr.value())
+ if (c.name.startsWith(QStringLiteral("__selftest__")))
+ (void)store.delete_competition_cascade(c.id);
+
+ ArenaConfig cfg;
+ cfg.name = QStringLiteral("__selftest__arena");
+ cfg.instruments = {QStringLiteral("BTC"), QStringLiteral("ETH")};
+ cfg.capital_per_agent = 10000;
+ ArenaAgentSpec a1; a1.provider = "openai"; a1.model_id = "gpt-test"; a1.display_name = "GPT"; a1.source_kind = "provider";
+ ArenaAgentSpec a2; a2.provider = "anthropic"; a2.model_id = "claude-test"; a2.display_name = "Claude"; a2.source_kind = "provider";
+ cfg.agents = {a1, a2};
+
+ auto cid_r = store.insert_competition(cfg);
+ check("store: insert_competition", cid_r.is_ok());
+ const QString cid = cid_r.is_ok() ? cid_r.value() : QString();
+
+ auto comp_r = store.competition(cid);
+ check("store: competition fetch", comp_r.is_ok() && comp_r.value().name == cfg.name
+ && comp_r.value().instruments == cfg.instruments
+ && approx(comp_r.value().capital_per_agent, 10000));
+
+ auto agents_r = store.agents_for(cid);
+ check("store: 2 agents persisted", agents_r.is_ok() && agents_r.value().size() == 2);
+ const QString aid = agents_r.is_ok() && !agents_r.value().isEmpty() ? agents_r.value()[0].id : QString();
+
+ auto bal_r = store.account_balance(cid, aid);
+ check("store: account seeded with capital", bal_r.is_ok() && approx(bal_r.value(), 10000));
+
+ PositionRow pos; pos.competition_id = cid; pos.agent_id = aid; pos.coin = "BTC";
+ pos.side = "long"; pos.qty = 0.1; pos.entry_price = 50000; pos.leverage = 3;
+ check("store: upsert_position", store.upsert_position(pos).is_ok());
+ pos.qty = 0.2;
+ check("store: upsert_position update", store.upsert_position(pos).is_ok());
+ auto pl_r = store.positions_for(cid, aid);
+ check("store: position upserted not duplicated",
+ pl_r.is_ok() && pl_r.value().size() == 1 && approx(pl_r.value()[0].qty, 0.2));
+
+ // Rounds / decisions / orders / equity / events round-trips.
+ check("store: insert_round", store.insert_round(cid, 1, 1000, "{}").is_ok());
+ check("store: complete_round", store.complete_round(cid, 1, 2000, "completed").is_ok());
+ auto seq_r = store.last_round_seq(cid);
+ check("store: last_round_seq", seq_r.is_ok() && seq_r.value() == 1);
+
+ for (int i = 1; i <= 3; ++i) {
+ DecisionRow d;
+ d.competition_id = cid; d.agent_id = aid; d.round_seq = i;
+ d.status = "ok"; d.actions_json = QStringLiteral("[%1]").arg(i);
+ check("store: insert_decision", store.insert_decision(d).is_ok());
+ }
+ auto recents = store.recent_decisions(cid, aid, 2);
+ check("store: recent_decisions oldest-first window",
+ recents.is_ok() && recents.value().size() == 2
+ && recents.value()[0].round_seq == 2 && recents.value()[1].round_seq == 3);
+
+ OrderRow o;
+ o.competition_id = cid; o.agent_id = aid; o.round_seq = 1; o.coin = "BTC";
+ o.side = "long"; o.action = "open"; o.qty = 0.1; o.price = 50000;
+ o.notional_usd = 5000; o.status = "filled";
+ check("store: insert_order", store.insert_order(o).is_ok());
+ auto orders_r = store.orders_for(cid, aid, 10);
+ check("store: orders_for round-trip",
+ orders_r.is_ok() && orders_r.value().size() == 1
+ && orders_r.value()[0].coin == "BTC" && approx(orders_r.value()[0].notional_usd, 5000));
+
+ EquitySnapshotRow es;
+ es.competition_id = cid; es.agent_id = aid; es.round_seq = 1; es.ts = 1500;
+ es.equity = 10100; es.balance = 9000; es.unrealized_pnl = 100;
+ check("store: insert_equity_snapshot", store.insert_equity_snapshot(es).is_ok());
+ es.equity = 10200;
+ check("store: equity snapshot upsert", store.insert_equity_snapshot(es).is_ok());
+ auto eq_r = store.equity_series(cid);
+ check("store: equity_series upserted not duplicated",
+ eq_r.is_ok() && eq_r.value().size() == 1 && approx(eq_r.value()[0].equity, 10200));
+
+ check("store: insert_event", store.insert_event(cid, aid, "test_event", "{\"k\":1}").is_ok());
+ check("store: insert_event 2", store.insert_event(cid, aid, "test_event_2", "{}").is_ok());
+ auto ev_r = store.recent_events(cid, 10);
+ check("store: recent_events oldest-first",
+ ev_r.is_ok() && ev_r.value().size() == 2
+ && ev_r.value()[0].contains("test_event") && ev_r.value()[1].contains("test_event_2"));
+
+ check("store: status update", store.set_competition_status(cid, "running").is_ok());
+ auto running_r = store.competitions_with_status("running");
+ check("store: competitions_with_status", running_r.is_ok() && running_r.value().contains(cid));
+
+ check("store: cascade delete", store.delete_competition_cascade(cid).is_ok());
+ auto gone = store.competition(cid);
+ check("store: competition gone after cascade", gone.is_err());
+
+ // ── Section 2: indicators ───────────────────────────────────────────────
+ {
+ QVector<Candle> cs;
+ for (int i = 0; i < 60; ++i) { Candle k; k.t = i; k.o = k.h = k.l = k.c = 100.0; k.v = 1; cs.append(k); }
+ check("ind: flat series ema == price", approx(ind_ema(cs, 20), 100.0));
+ check("ind: flat series atr == 0", approx(ind_atr(cs, 14), 0.0));
+ check("ind: flat series rsi neutral", approx(ind_rsi(cs, 14), 50.0, 1.0));
+ QVector<Candle> up;
+ for (int i = 0; i < 60; ++i) { Candle k; k.c = 100.0 + i; k.o = k.c - 1; k.h = k.c + 1; k.l = k.o - 1; up.append(k); }
+ check("ind: rising series rsi > 70", ind_rsi(up, 14) > 70.0);
+ check("ind: ema20 > ema50 in uptrend", ind_ema(up, 20) > ind_ema(up, 50));
+ check("ind: short series safe", approx(ind_ema({}, 20), 0.0) && approx(ind_rsi({}, 14), 50.0));
+ }
+
+ // ── Section 3: decision parser ──────────────────────────────────────────
+ {
+ const QStringList instr = {"BTC", "ETH"};
+ auto p1 = parse_decision(R"({"actions":[{"action":"open","coin":"BTC","side":"long","size_usd":2000,"leverage":3,"reason":"r"}]})", instr, 10);
+ check("parse: clean json", p1.ok() && p1.actions.size() == 1
+ && p1.actions[0].kind == ActionKind::Open && p1.actions[0].coin == "BTC"
+ && approx(p1.actions[0].size_usd, 2000) && approx(p1.actions[0].leverage, 3));
+ auto p2 = parse_decision("Here is my plan:\n```json\n{\"actions\":[{\"action\":\"hold\",\"reason\":\"wait\"}]}\n```\nthanks", instr, 10);
+ check("parse: fenced json", p2.ok() && p2.actions.size() == 1 && p2.actions[0].kind == ActionKind::Hold);
+ auto p3 = parse_decision("I think {\"actions\":[{\"action\":\"close\",\"coin\":\"ETH\",\"reason\":\"tp\"}]} fits", instr, 10);
+ check("parse: embedded json", p3.ok() && p3.actions[0].kind == ActionKind::Close && p3.actions[0].coin == "ETH");
+ auto p3b = parse_decision(
+ "ok: {\"actions\":[{\"action\":\"close\",\"coin\":\"ETH\",\"reason\":\"stray } brace\"}]} end", instr, 10);
+ check("parse: embedded json with brace inside string", p3b.ok() && p3b.actions[0].coin == "ETH");
+ check("parse: garbage fails", !parse_decision("no json here", instr, 10).ok());
+ check("parse: unknown coin fails", !parse_decision(R"({"actions":[{"action":"open","coin":"DOGE","side":"long","size_usd":100,"leverage":2}]})", instr, 10).ok());
+ check("parse: leverage cap fails", !parse_decision(R"({"actions":[{"action":"open","coin":"BTC","side":"long","size_usd":100,"leverage":50}]})", instr, 10).ok());
+ check("parse: bad side fails", !parse_decision(R"({"actions":[{"action":"open","coin":"BTC","side":"sideways","size_usd":100,"leverage":2}]})", instr, 10).ok());
+ check("parse: empty actions fails", !parse_decision(R"({"actions":[]})", instr, 10).ok());
+ }
+
+ // ── Section 4: paper exchange ───────────────────────────────────────────
+ {
+ ArenaConfig pcfg;
+ pcfg.name = "__selftest__px";
+ pcfg.instruments = {"BTC"};
+ pcfg.capital_per_agent = 10000;
+ ArenaAgentSpec s; s.provider = "openai"; s.model_id = "m"; s.display_name = "A"; s.source_kind = "provider";
+ pcfg.agents = {s};
+ const QString pcid = store.insert_competition(pcfg).value();
+ const QString paid = store.agents_for(pcid).value()[0].id;
+
+ PaperExchange px(store, pcid);
+ px.load();
+ px.set_marks({{"BTC", 50000.0}});
+
+ AgentAction open; open.kind = ActionKind::Open; open.coin = "BTC"; open.side = "long";
+ open.size_usd = 3000; open.leverage = 3;
+ auto f1 = px.execute(paid, open, 1);
+ check("px: open fills", f1.is_ok() && f1.value().status == "filled");
+ // entry = 50000*(1+slippage) = 50010; qty = 3000/50010; margin = 1000; fee = 3000*0.00045 = 1.35
+ auto av1 = px.account(paid);
+ check("px: margin+fee deducted", approx(av1.balance, 10000 - 1000 - 1.35, 0.05));
+ check("px: position open", av1.positions.size() == 1 && av1.positions[0].side == "long");
+ // equity ≈ balance + margin + upnl(small negative from slippage)
+ check("px: equity near capital", approx(av1.equity, 10000 - 1.35 - 3000 * PaperExchange::kSlippage, 1.5));
+
+ px.set_marks({{"BTC", 55000.0}}); // +~10% on 3x → upnl ≈ 3000*0.0998 ≈ 299
+ auto av2 = px.account(paid);
+ check("px: upnl rises with mark", av2.upnl.value("BTC") > 250);
+
+ // Same-side open averages in.
+ auto f2 = px.execute(paid, open, 2);
+ auto av3 = px.account(paid);
+ check("px: same-side open increases qty",
+ f2.is_ok() && av3.positions.size() == 1 && av3.positions[0].qty > av1.positions[0].qty);
+
+ // Opposite-side open = flip: closes existing, opens new side.
+ AgentAction flip = open; flip.side = "short"; flip.size_usd = 1000; flip.leverage = 2;
+ auto f3 = px.execute(paid, flip, 3);
+ auto av4 = px.account(paid);
+ check("px: flip leaves single short", f3.is_ok() && av4.positions.size() == 1 && av4.positions[0].side == "short");
+ // Closed a winning long: the flip's close order (persisted, round 3) carries the realized pnl.
+ bool flip_pnl = false;
+ if (auto fo = store.orders_for(pcid, paid, 50); fo.is_ok())
+ for (const auto& ord : fo.value())
+ if (ord.round_seq == 3 && ord.action == "close" && ord.realized_pnl > 0) flip_pnl = true;
+ check("px: flip realized pnl recorded", flip_pnl);
+
+ // Full close.
+ AgentAction close; close.kind = ActionKind::Close; close.coin = "BTC";
+ auto f4 = px.execute(paid, close, 4);
+ auto av5 = px.account(paid);
+ check("px: close flattens", f4.is_ok() && av5.positions.isEmpty());
+ check("px: equity == balance when flat", approx(av5.equity, av5.balance, 0.001));
+
+ // Funding accrual: open long, positive funding → cost reduces equity.
+ px.execute(paid, open, 5);
+ const double eq_before = px.account(paid).equity;
+ // (mark_all needs funding rates: set via set_marks + funding map — see impl: funding
+ // rates ride in set_funding())
+ px.set_funding({{"BTC", 0.0001}});
+ px.mark_all(3600 * 1000, 5); // one full 1h funding window (HL rates are hourly)
+ check("px: positive funding costs longs", px.account(paid).equity < eq_before);
+
+ // Liquidation: crash the mark far below entry.
+ px.set_marks({{"BTC", 30000.0}});
+ auto liqs = px.mark_all(1000, 6);
+ check("px: liquidation fires", liqs.size() == 1 && liqs[0].status == "liquidated");
+ check("px: liquidated position removed", px.account(paid).positions.isEmpty());
+
+ // close on empty book is rejected
+ check("px: close with no position rejected", px.execute(paid, close, 7).is_err());
+
+ (void)store.delete_competition_cascade(pcid);
+ }
+
+ // ── Section 5: risk ─────────────────────────────────────────────────────
+ {
+ AccountView acct; acct.balance = 10000; acct.equity = 10000;
+ RiskLimits lim;
+ AgentAction a; a.kind = ActionKind::Open; a.coin = "BTC"; a.side = "long";
+ a.size_usd = 4000; a.leverage = 3;
+ check("risk: sane open approved", evaluate(a, acct, lim, 0).approved);
+ a.size_usd = 6000;
+ check("risk: >50% equity rejected", !evaluate(a, acct, lim, 0).approved);
+ a.size_usd = 4000; a.leverage = 20;
+ check("risk: leverage cap rejected", !evaluate(a, acct, lim, 0).approved);
+ a.leverage = 3;
+ check("risk: round cap rejected", !evaluate(a, acct, lim, 7000).approved);
+ AgentAction c; c.kind = ActionKind::Close; c.coin = "BTC";
+ check("risk: close always approved", evaluate(c, acct, lim, 99999).approved);
+ }
+
+ // ── Section 6: model registry ───────────────────────────────────────────
+ {
+ auto& reg = ArenaModelRegistry::instance();
+ const auto opts = reg.available_models();
+ QSet<QString> keys;
+ bool dup = false, blank = false;
+ for (const auto& o : opts) {
+ const QString k = o.provider.toLower() + "/" + o.model_id;
+ if (keys.contains(k)) dup = true;
+ keys.insert(k);
+ if (o.color_hex.isEmpty() || o.display_name.isEmpty() || o.source_kind.isEmpty()) blank = true;
+ }
+ check("registry: no duplicate (provider,model)", !dup);
+ check("registry: every option fully labelled", !blank);
+ check("registry: unknown profile ref fails resolution",
+ reg.resolve_credentials("profile", "no-such-id", "openai").is_err());
+ check("registry: keyless provider resolves without key",
+ reg.resolve_credentials("provider", "ollama", "ollama").is_ok());
+
+ // Browse layer (merge layer 4): every catalog provider with fallback
+ // models is listed even with no llm_configs row, so the wizard can
+ // offer all providers.
+ const auto opts2 = reg.available_models();
+ QSet<QString> providers_seen;
+ bool ollama_ready = false;
+ for (const auto& o : opts2) {
+ providers_seen.insert(o.provider.toLower());
+ if (o.provider.toLower() == "ollama" && o.ready) ollama_ready = true;
+ }
+ check("registry: all known providers browsable",
+ providers_seen.contains("openai") && providers_seen.contains("anthropic")
+ && providers_seen.contains("gemini") && providers_seen.contains("deepseek")
+ && providers_seen.contains("xai"));
+ // Ollama's fallback list is intentionally empty (models come from a
+ // live /api/tags fetch the registry doesn't do), so it may be absent in
+ // an unconfigured profile; whenever it IS listed it must be ready
+ // (keyless), from any layer.
+ check("registry: keyless ollama listed but has no fallback models or is ready",
+ !providers_seen.contains("ollama") || ollama_ready);
+ }
+
+ // ── Section 7: prompts ──────────────────────────────────────────────────
+ {
+ CompetitionRow comp; comp.capital_per_agent = 10000; comp.instruments = {"BTC", "ETH"};
+ comp.max_leverage = 10; comp.cadence_seconds = 180;
+ const QString sys = system_prompt(comp);
+ check("prompt: system mentions instruments", sys.contains("BTC, ETH"));
+ check("prompt: system carries JSON contract", sys.contains("\"actions\""));
+ comp.system_prompt_override = "You are a turtle trader.";
+ const QString sys2 = system_prompt(comp);
+ check("prompt: override kept + contract appended",
+ sys2.startsWith("You are a turtle trader.") && sys2.contains("\"actions\""));
+
+ MarketSnapshot ms; CoinSnapshot btc; btc.coin = "BTC"; btc.mid = 50000; ms.coins["BTC"] = btc;
+ ms.ts = 1000LL * 60 * 9; // 9 min after start → "elapsed 9 min"
+ AccountView av; av.balance = av.equity = 10000;
+ const QString up = user_prompt(ms, av, {}, 3, /*started_at=*/0);
+ check("prompt: user carries round + market + account",
+ up.contains("ROUND 3") && up.contains("BTC: mid 50000") && up.contains("no open positions"));
+ check("prompt: deterministic from snapshot ts",
+ up.contains("elapsed 9 min") && up == user_prompt(ms, av, {}, 3, 0));
+ }
+
+ // ── Section 8: llm client pure helpers ──────────────────────────────────
+ {
+ ArenaLlmRequest rq; rq.provider = "anthropic"; rq.model_id = "claude-x";
+ rq.system_prompt = "S"; rq.user_prompt = "U"; rq.max_tokens = 1000;
+ const auto abody = QJsonDocument::fromJson(ArenaLlmClient::build_body(rq)).object();
+ check("llm: anthropic body has system + messages",
+ abody.value("system").toString() == "S" && abody.value("messages").toArray().size() == 1);
+ rq.provider = "openai";
+ const auto obody = QJsonDocument::fromJson(ArenaLlmClient::build_body(rq)).object();
+ check("llm: openai body uses max_completion_tokens",
+ obody.contains("max_completion_tokens") && obody.value("messages").toArray().size() == 2);
+ rq.provider = "deepseek";
+ check("llm: openai-compat body uses max_tokens",
+ QJsonDocument::fromJson(ArenaLlmClient::build_body(rq)).object().contains("max_tokens"));
+
+ auto pr1 = ArenaLlmClient::parse_response("openai",
+ R"({"choices":[{"message":{"content":"hi"}}],"usage":{"prompt_tokens":5,"completion_tokens":2}})");
+ check("llm: openai parse", pr1.success && pr1.content == "hi" && pr1.prompt_tokens == 5);
+ auto pr2 = ArenaLlmClient::parse_response("anthropic",
+ R"({"content":[{"type":"text","text":"yo"}],"usage":{"input_tokens":7,"output_tokens":3}})");
+ check("llm: anthropic parse", pr2.success && pr2.content == "yo" && pr2.completion_tokens == 3);
+ auto pr3 = ArenaLlmClient::parse_response("gemini",
+ R"({"candidates":[{"content":{"parts":[{"text":"g"}]}}],"usageMetadata":{"promptTokenCount":9,"candidatesTokenCount":4}})");
+ check("llm: gemini parse", pr3.success && pr3.content == "g" && pr3.prompt_tokens == 9);
+ auto pr4 = ArenaLlmClient::parse_response("openai", R"({"error":{"message":"bad key"}})");
+ check("llm: provider error surfaced", !pr4.success && pr4.error == "bad key");
+ check("llm: endpoint composition",
+ fincept::ai_chat::ProviderCatalog::chat_endpoint("openai", "", "m") == "https://api.openai.com/v1/chat/completions"
+ && fincept::ai_chat::ProviderCatalog::chat_endpoint("deepseek", "https://my.proxy/v1", "m") == "https://my.proxy/v1/chat/completions"
+ && fincept::ai_chat::ProviderCatalog::chat_endpoint("anthropic", "https://gw.corp", "m") == "https://gw.corp/v1/messages");
+ }
+
+ // ── Section 9: market data parsers ──────────────────────────────────────
+ {
+ const auto mids_doc = QJsonDocument::fromJson(R"({"BTC":"94126.0","ETH":"3120.5","#1000":"0.5"})");
+ const auto mids = ArenaMarketData::parse_all_mids(mids_doc, {"BTC", "ETH"});
+ check("md: mids parsed + builder assets filtered",
+ mids.size() == 2 && approx(mids.value("BTC"), 94126.0) && !mids.contains("#1000"));
+
+ MarketSnapshot snap;
+ CoinSnapshot b; b.coin = "BTC"; b.mid = 94126.0; snap.coins["BTC"] = b;
+ const auto ctx_doc = QJsonDocument::fromJson(
+ R"([{"universe":[{"name":"BTC"},{"name":"ETH"}]},)"
+ R"([{"funding":"0.0000125","openInterest":"12345.5","prevDayPx":"90000.0"},)"
+ R"({"funding":"0.0001","openInterest":"99","prevDayPx":"3000"}]])");
+ ArenaMarketData::apply_asset_ctxs(ctx_doc, snap);
+ check("md: ctxs applied by index", approx(snap.coins["BTC"].funding_rate, 0.0000125, 1e-9)
+ && approx(snap.coins["BTC"].open_interest, 12345.5)
+ && approx(snap.coins["BTC"].day_change_pct, (94126.0 - 90000.0) / 90000.0 * 100.0, 0.01));
+
+ const auto candle_doc = QJsonDocument::fromJson(
+ R"([{"t":1765299600000,"o":"94126.0","c":"93858.0","h":"94569.0","l":"93485.0","v":"3559.7"}])");
+ const auto candles = ArenaMarketData::parse_candles(candle_doc);
+ check("md: candles parsed", candles.size() == 1 && approx(candles[0].c, 93858.0)
+ && candles[0].t == 1765299600000LL);
+ }
+
+ // ── Section 10: engine round (fakes; no network) ────────────────────────
+ {
+ auto* fake_md = new FakeMarketData(nullptr);
+ CoinSnapshot btc; btc.coin = "BTC"; btc.mid = 50000;
+ fake_md->next.coins["BTC"] = btc;
+ auto* fake_llm = new FakeLlmClient(nullptr);
+ // gpt: clean open. claude: garbage then garbage again (exhausts the 1 retry).
+ fake_llm->scripts["gpt-test"].enqueue(R"({"actions":[{"action":"open","coin":"BTC","side":"long","size_usd":2000,"leverage":2,"reason":"momentum"}]})");
+ fake_llm->scripts["claude-test"].enqueue("I refuse to answer in JSON.");
+ fake_llm->scripts["claude-test"].enqueue("Still prose.");
+
+ auto& eng = ArenaEngine::instance();
+ eng.set_market_for_test(fake_md);
+ eng.set_llm_for_test(fake_llm);
+
+ ArenaConfig ecfg;
+ ecfg.name = "__selftest__engine";
+ ecfg.instruments = {"BTC"};
+ ecfg.capital_per_agent = 10000;
+ ecfg.cadence_seconds = 3600; // timer never fires during the test
+ // Both agents ride the keyless "ollama" provider so resolve_credentials
+ // succeeds without any configured key; model_ids select the fake scripts.
+ ArenaAgentSpec g; g.provider = "ollama"; g.model_id = "gpt-test";
+ g.display_name = "GPT"; g.source_kind = "provider"; g.source_ref = "ollama";
+ ArenaAgentSpec c = g; c.model_id = "claude-test"; c.display_name = "Claude";
+ ecfg.agents = {g, c};
+
+ const QString ecid = ArenaEngine::instance().create_competition(ecfg).value();
+ QEventLoop loop;
+ int completed_seq = 0;
+ QObject::connect(&eng, &ArenaEngine::round_completed, &loop, [&](int s) { completed_seq = s; loop.quit(); });
+ check("engine: start ok", eng.start(ecid).is_ok());
+ QTimer::singleShot(5000, &loop, &QEventLoop::quit); // watchdog
+ loop.exec();
+ check("engine: round completed", completed_seq == 1);
+
+ auto decs = store.decisions_for_round(ecid, 1);
+ check("engine: 2 decisions persisted", decs.is_ok() && decs.value().size() == 2);
+ int ok_count = 0, perr_count = 0;
+ for (const auto& d : decs.is_ok() ? decs.value() : QVector<DecisionRow>{}) {
+ if (d.status == "ok") ++ok_count;
+ if (d.status == "parse_error") ++perr_count;
+ }
+ check("engine: one ok decision, one parse_error (after retry)", ok_count == 1 && perr_count == 1);
+ // The parse-error agent consumed both scripted responses (retry happened).
+ check("engine: repair retry consumed second response", fake_llm->scripts["claude-test"].isEmpty());
+
+ const auto agents_now = store.agents_for(ecid).value();
+ QString gpt_id, claude_id;
+ for (const auto& a : agents_now) (a.model_id == "gpt-test" ? gpt_id : claude_id) = a.id;
+ auto orders = store.orders_for(ecid, gpt_id, 10);
+ check("engine: gpt order filled", orders.is_ok() && orders.value().size() == 1
+ && orders.value()[0].status == "filled" && approx(orders.value()[0].notional_usd, 2000));
+ auto toks = store.token_totals(ecid);
+ check("store: token totals aggregated", toks.is_ok() && toks.value().value(gpt_id) > 0);
+ auto eq = store.equity_series(ecid);
+ check("engine: equity snapshots for both agents", eq.is_ok() && eq.value().size() == 2);
+ check("engine: parse failure did not block round",
+ eq.is_ok() && eq.value().size() == 2 && completed_seq == 1);
+
+ // Failure counting: claude has 1 consecutive failure (threshold 3 → still active).
+ for (const auto& a : agents_now)
+ if (a.id == claude_id)
+ check("engine: failure counter incremented", a.consecutive_failures == 1 && a.status == "active");
+
+ // Crash-recovery surface + restart guard.
+ check("engine: no phantom crash recoveries", eng.pending_crash_recoveries().isEmpty());
+
+ check("engine: kill_all + stop", eng.kill_all().is_ok());
+ (void)store.delete_competition_cascade(ecid);
+
+ // Restart guard: starting a new competition must end the previous one
+ // ("never two running"). Fakes are still installed; nothing enqueued so
+ // both rounds resolve to default hold — and start()'s first round is
+ // async anyway, while these status assertions are synchronous. Any
+ // late callbacks are stale-epoch no-ops (Fix: epoch guard).
+ ecfg.name = "__selftest__engine2";
+ const QString ecid2 = eng.create_competition(ecfg).value();
+ check("engine: start second ok", eng.start(ecid2).is_ok());
+ ecfg.name = "__selftest__engine3";
+ const QString ecid3 = eng.create_competition(ecfg).value();
+ check("engine: start third ok (auto-stops second)", eng.start(ecid3).is_ok());
+ auto c2 = store.competition(ecid2);
+ auto c3 = store.competition(ecid3);
+ check("engine: second auto-ended on restart", c2.is_ok() && c2.value().status == "ended");
+ check("engine: third running", c3.is_ok() && c3.value().status == "running");
+ (void)eng.kill_all(); // only the active (third) competition
+ (void)store.delete_competition_cascade(ecid2);
+ (void)store.delete_competition_cascade(ecid3);
+
+ // HITL: live_mode competitions queue orders until approved. venue stays
+ // "paper" — live_mode alone gates HITL, so no real order mirroring runs.
+ ArenaConfig hcfg = ecfg;
+ hcfg.name = "__selftest__hitl";
+ hcfg.live_mode = true;
+ hcfg.agents = {g};
+ fake_llm->scripts["gpt-test"].enqueue(
+ R"({"actions":[{"action":"open","coin":"BTC","side":"long","size_usd":1000,"leverage":2,"reason":"r"}]})");
+ const QString hcid = eng.create_competition(hcfg).value();
+ QString approval_id, hitl_agent;
+ QObject::connect(&eng, &ArenaEngine::hitl_requested, &loop,
+ [&](QString id, QString aid, QString) { approval_id = id; hitl_agent = aid; });
+ int hseq = 0;
+ QObject::connect(&eng, &ArenaEngine::round_completed, &loop, [&](int s) { hseq = s; });
+ check("hitl: start", eng.start(hcid).is_ok());
+ QTimer::singleShot(5000, &loop, &QEventLoop::quit); // watchdog (round_completed quits via the Section-10 connect)
+ loop.exec();
+ check("hitl: round completed with approval pending", hseq == 1);
+ check("hitl: approval requested", !approval_id.isEmpty());
+ const QString hagent = store.agents_for(hcid).value()[0].id;
+ check("hitl: request from the right agent", hitl_agent == hagent);
+ check("hitl: no order before approval",
+ store.orders_for(hcid, hagent, 10).value().isEmpty());
+ eng.resume_after_hitl(approval_id, true);
+ const auto horders = store.orders_for(hcid, hagent, 10);
+ check("hitl: order executed after approval",
+ horders.is_ok() && horders.value().size() == 1
+ && horders.value()[0].status == "filled");
+ (void)eng.kill_all();
+ (void)store.delete_competition_cascade(hcid);
+
+ // Immediate halt (user-reported bug): an agent halted while its LLM
+ // call is in flight must execute NOTHING when the callback lands.
+ // Event ordering makes this deterministic with the singleShot(0) fakes:
+ // start() queues the snapshot reply (timer A); our queued halt (timer B)
+ // runs after A — i.e. after on_snapshot dispatched the agent — while the
+ // fake LLM reply (timer C, queued during A) fires only on the next event
+ // pass. So finish_agent lands on an already-halted agent.
+ ArenaConfig kcfg = ecfg;
+ kcfg.name = "__selftest__halt";
+ kcfg.agents = {g}; // gpt-test only
+ fake_llm->scripts["gpt-test"].enqueue(
+ R"({"actions":[{"action":"open","coin":"BTC","side":"long","size_usd":1500,"leverage":2,"reason":"r"}]})");
+ const QString kcid = eng.create_competition(kcfg).value();
+ check("halt: start", eng.start(kcid).is_ok());
+ const QString kaid = store.agents_for(kcid).value()[0].id;
+ QTimer::singleShot(0, &loop, [&eng, &kaid]() { (void)eng.halt_agent(kaid); });
+ completed_seq = 0;
+ QTimer::singleShot(5000, &loop, &QEventLoop::quit); // watchdog
+ loop.exec();
+ check("halt: round completed", completed_seq == 1);
+ auto kdecs = store.decisions_for_round(kcid, 1);
+ check("halt: decision persisted with real status",
+ kdecs.is_ok() && kdecs.value().size() == 1 && kdecs.value()[0].status == "ok");
+ auto korders = store.orders_for(kcid, kaid, 10);
+ check("halt: no orders for halted agent", korders.is_ok() && korders.value().isEmpty());
+ bool halt_event = false;
+ if (auto ev = store.recent_events(kcid, 20); ev.is_ok())
+ for (const auto& e : ev.value())
+ if (e.contains("actions_skipped_agent_halted")) halt_event = true;
+ check("halt: actions_skipped_agent_halted event", halt_event);
+
+ // kill_agent: close positions now + halt ("halted_user") + equity snapshot.
+ check("kill: unknown agent rejected", eng.kill_agent("no-such-agent").is_err());
+ check("kill: resume_agent", eng.resume_agent(kaid).is_ok());
+ fake_llm->scripts["gpt-test"].enqueue(
+ R"({"actions":[{"action":"open","coin":"BTC","side":"long","size_usd":2000,"leverage":2,"reason":"r"}]})");
+ completed_seq = 0;
+ eng.force_round();
+ QTimer::singleShot(5000, &loop, &QEventLoop::quit); // watchdog
+ loop.exec();
+ auto kpos = store.positions_for(kcid, kaid);
+ check("kill: setup round opened a position",
+ completed_seq == 2 && kpos.is_ok() && kpos.value().size() == 1);
+ check("kill: kill_agent ok", eng.kill_agent(kaid).is_ok());
+ kpos = store.positions_for(kcid, kaid);
+ check("kill: positions flattened", kpos.is_ok() && kpos.value().isEmpty());
+ bool kill_close = false;
+ if (auto ko = store.orders_for(kcid, kaid, 50); ko.is_ok())
+ for (const auto& o : ko.value())
+ if (o.action == "close" && o.status == "filled") kill_close = true;
+ check("kill: close order recorded", kill_close);
+ QString kstatus;
+ const auto kagents = store.agents_for(kcid).value(); // named copy — .value() of a
+ // temporary Result dangles in range-for
+ for (const auto& a : kagents)
+ if (a.id == kaid) kstatus = a.status;
+ check("kill: agent halted_user", kstatus == "halted_user");
+ bool kill_event = false;
+ if (auto ev = store.recent_events(kcid, 20); ev.is_ok())
+ for (const auto& e : ev.value())
+ if (e.contains("agent_killed")) kill_event = true;
+ check("kill: agent_killed event", kill_event);
+
+ // Live marks between rounds: shrink the marks cadence and expect at
+ // least one marks_updated (fake fetch_mids roundtrip) within 2s.
+ int marks_count = 0;
+ QObject::connect(&eng, &ArenaEngine::marks_updated, &loop, [&]() {
+ ++marks_count;
+ loop.quit();
+ });
+ eng.set_marks_interval_for_test(50);
+ QTimer::singleShot(2000, &loop, &QEventLoop::quit); // watchdog
+ loop.exec();
+ check("marks: marks_updated fired between rounds", marks_count >= 1);
+
+ (void)eng.kill_all();
+ (void)store.delete_competition_cascade(kcid);
+ }
+
+ std::printf("\n%d failure(s)\n", failures);
+ return failures == 0 ? 0 : 1;
+}
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaSelftest.h b/fincept-qt/src/services/alpha_arena/ArenaSelftest.h
new file mode 100644
index 000000000..9f05f021d
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaSelftest.h
@@ -0,0 +1,2 @@
+#pragma once
+namespace fincept::arena { int run_arena_selftest(); }
diff --git a/fincept-qt/src/services/alpha_arena/ArenaStore.cpp b/fincept-qt/src/services/alpha_arena/ArenaStore.cpp
new file mode 100644
index 000000000..93e59c435
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaStore.cpp
@@ -0,0 +1,497 @@
+// ArenaStore — all SQLite access for the Alpha Arena rewrite (arena_* tables).
+// Schema: storage/sqlite/migrations/v050_alpha_arena_rewrite.cpp
+
+#include "services/alpha_arena/ArenaStore.h"
+
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QSqlQuery>
+#include <QUuid>
+
+#include <algorithm>
+
+namespace fincept::arena {
+
+namespace {
+
+QString make_id() { return QUuid::createUuid().toString(QUuid::WithoutBraces); }
+qint64 now_millis() { return QDateTime::currentMSecsSinceEpoch(); }
+
+// Qt binds a null QString as SQL NULL, which trips the NOT NULL constraints on
+// the arena_* columns. Coerce null → empty string before binding.
+QString nn(const QString& v) { return v.isNull() ? QString::fromLatin1("") : v; }
+
+QString instruments_to_json(const QStringList& instruments) {
+ return QString::fromUtf8(
+ QJsonDocument(QJsonArray::fromStringList(instruments)).toJson(QJsonDocument::Compact));
+}
+
+QStringList instruments_from_json(const QString& json) {
+ QStringList out;
+ const auto doc = QJsonDocument::fromJson(json.toUtf8());
+ for (const auto& v : doc.array())
+ out << v.toString();
+ return out;
+}
+
+// Row mappers — column indices match the SELECT column order used below.
+CompetitionRow map_competition(QSqlQuery& q) {
+ CompetitionRow c;
+ c.id = q.value(0).toString();
+ c.name = q.value(1).toString();
+ c.status = q.value(2).toString();
+ c.venue = q.value(3).toString();
+ c.instruments = instruments_from_json(q.value(4).toString());
+ c.capital_per_agent = q.value(5).toDouble();
+ c.cadence_seconds = q.value(6).toInt();
+ c.max_leverage = q.value(7).toDouble();
+ c.system_prompt_override = q.value(8).toString();
+ c.live_mode = q.value(9).toInt() != 0;
+ c.created_at = q.value(10).toLongLong();
+ c.started_at = q.value(11).toLongLong();
+ c.ended_at = q.value(12).toLongLong();
+ return c;
+}
+constexpr const char* kCompetitionCols =
+ "id, name, status, venue, instruments_json, capital_per_agent, cadence_seconds,"
+ " max_leverage, system_prompt_override, live_mode, created_at, started_at, ended_at";
+
+AgentRow map_agent(QSqlQuery& q) {
+ AgentRow a;
+ a.id = q.value(0).toString();
+ a.competition_id = q.value(1).toString();
+ a.provider = q.value(2).toString();
+ a.model_id = q.value(3).toString();
+ a.display_name = q.value(4).toString();
+ a.color_hex = q.value(5).toString();
+ a.source_kind = q.value(6).toString();
+ a.source_ref = q.value(7).toString();
+ a.status = q.value(8).toString();
+ a.halt_reason = q.value(9).toString();
+ a.consecutive_failures = q.value(10).toInt();
+ return a;
+}
+constexpr const char* kAgentCols =
+ "id, competition_id, provider, model_id, display_name, color_hex, source_kind,"
+ " source_ref, status, halt_reason, consecutive_failures";
+
+DecisionRow map_decision(QSqlQuery& q) {
+ DecisionRow d;
+ d.id = q.value(0).toString();
+ d.competition_id = q.value(1).toString();
+ d.agent_id = q.value(2).toString();
+ d.round_seq = q.value(3).toInt();
+ d.system_prompt = q.value(4).toString();
+ d.user_prompt = q.value(5).toString();
+ d.raw_response = q.value(6).toString();
+ d.actions_json = q.value(7).toString();
+ d.parse_error = q.value(8).toString();
+ d.status = q.value(9).toString();
+ d.latency_ms = q.value(10).toLongLong();
+ d.prompt_tokens = q.value(11).toInt();
+ d.completion_tokens = q.value(12).toInt();
+ d.ts = q.value(13).toLongLong();
+ return d;
+}
+constexpr const char* kDecisionCols =
+ "id, competition_id, agent_id, round_seq, system_prompt, user_prompt, raw_response,"
+ " actions_json, parse_error, status, latency_ms, prompt_tokens, completion_tokens, ts";
+
+OrderRow map_order(QSqlQuery& q) {
+ OrderRow o;
+ o.id = q.value(0).toString();
+ o.competition_id = q.value(1).toString();
+ o.agent_id = q.value(2).toString();
+ o.round_seq = q.value(3).toInt();
+ o.coin = q.value(4).toString();
+ o.side = q.value(5).toString();
+ o.action = q.value(6).toString();
+ o.qty = q.value(7).toDouble();
+ o.price = q.value(8).toDouble();
+ o.notional_usd = q.value(9).toDouble();
+ o.leverage = q.value(10).toDouble();
+ o.fee = q.value(11).toDouble();
+ o.realized_pnl = q.value(12).toDouble();
+ o.status = q.value(13).toString();
+ o.reject_reason = q.value(14).toString();
+ o.ts = q.value(15).toLongLong();
+ return o;
+}
+constexpr const char* kOrderCols =
+ "id, competition_id, agent_id, round_seq, coin, side, action, qty, price,"
+ " notional_usd, leverage, fee, realized_pnl, status, reject_reason, ts";
+
+PositionRow map_position(QSqlQuery& q) {
+ PositionRow p;
+ p.competition_id = q.value(0).toString();
+ p.agent_id = q.value(1).toString();
+ p.coin = q.value(2).toString();
+ p.side = q.value(3).toString();
+ p.qty = q.value(4).toDouble();
+ p.entry_price = q.value(5).toDouble();
+ p.leverage = q.value(6).toDouble();
+ p.funding_accrued = q.value(7).toDouble();
+ return p;
+}
+constexpr const char* kPositionCols =
+ "competition_id, agent_id, coin, side, qty, entry_price, leverage, funding_accrued";
+
+EquitySnapshotRow map_equity(QSqlQuery& q) {
+ EquitySnapshotRow s;
+ s.competition_id = q.value(0).toString();
+ s.agent_id = q.value(1).toString();
+ s.round_seq = q.value(2).toInt();
+ s.ts = q.value(3).toLongLong();
+ s.equity = q.value(4).toDouble();
+ s.balance = q.value(5).toDouble();
+ s.unrealized_pnl = q.value(6).toDouble();
+ return s;
+}
+constexpr const char* kEquityCols =
+ "competition_id, agent_id, round_seq, ts, equity, balance, unrealized_pnl";
+
+} // namespace
+
+ArenaStore& ArenaStore::instance() {
+ static ArenaStore s;
+ return s;
+}
+
+// ── Competitions ─────────────────────────────────────────────────────────────
+
+Result<QString> ArenaStore::insert_competition(const ArenaConfig& cfg) {
+ const QString id = make_id();
+ auto r = db().execute(
+ "INSERT INTO arena_competitions (id, name, status, venue, instruments_json,"
+ " capital_per_agent, cadence_seconds, max_leverage, system_prompt_override,"
+ " live_mode, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
+ {id, nn(cfg.name), QStringLiteral("created"), nn(cfg.venue),
+ instruments_to_json(cfg.instruments), cfg.capital_per_agent, cfg.cadence_seconds,
+ cfg.max_leverage, nn(cfg.system_prompt_override), cfg.live_mode ? 1 : 0, now_millis()});
+ if (r.is_err())
+ return Result<QString>::err(r.error());
+ for (const auto& spec : cfg.agents) {
+ auto ar = insert_agent(id, spec);
+ if (ar.is_err())
+ return Result<QString>::err(ar.error());
+ auto acc = upsert_account(id, ar.value(), cfg.capital_per_agent);
+ if (acc.is_err())
+ return Result<QString>::err(acc.error());
+ }
+ return Result<QString>::ok(id);
+}
+
+Result<CompetitionRow> ArenaStore::competition(const QString& id) {
+ return query_one(
+ QStringLiteral("SELECT %1 FROM arena_competitions WHERE id = ?").arg(kCompetitionCols),
+ {id}, map_competition);
+}
+
+Result<QVector<CompetitionRow>> ArenaStore::list_competitions() {
+ return query_list(
+ QStringLiteral("SELECT %1 FROM arena_competitions ORDER BY created_at DESC")
+ .arg(kCompetitionCols),
+ {}, map_competition);
+}
+
+Result<void> ArenaStore::set_competition_status(const QString& id, const QString& status) {
+ return exec_write("UPDATE arena_competitions SET status = ? WHERE id = ?", {nn(status), id});
+}
+
+Result<void> ArenaStore::set_competition_timestamps(const QString& id, qint64 started_at,
+ qint64 ended_at) {
+ return exec_write("UPDATE arena_competitions SET started_at = ?, ended_at = ? WHERE id = ?",
+ {started_at, ended_at, id});
+}
+
+Result<void> ArenaStore::set_cadence(const QString& id, int seconds) {
+ return exec_write("UPDATE arena_competitions SET cadence_seconds = ? WHERE id = ?",
+ {seconds, id});
+}
+
+Result<void> ArenaStore::delete_competition_cascade(const QString& id) {
+ for (const char* table : {"arena_agents", "arena_rounds", "arena_decisions", "arena_orders",
+ "arena_positions", "arena_accounts", "arena_equity_snapshots",
+ "arena_events"}) {
+ auto r = exec_write(
+ QStringLiteral("DELETE FROM %1 WHERE competition_id = ?").arg(QLatin1String(table)),
+ {id});
+ if (r.is_err())
+ return r;
+ }
+ return exec_write("DELETE FROM arena_competitions WHERE id = ?", {id});
+}
+
+Result<QStringList> ArenaStore::competitions_with_status(const QString& status) {
+ auto r = db().execute("SELECT id FROM arena_competitions WHERE status = ?"
+ " ORDER BY created_at DESC",
+ {status});
+ if (r.is_err())
+ return Result<QStringList>::err(r.error());
+ QStringList out;
+ auto& q = r.value();
+ while (q.next())
+ out << q.value(0).toString();
+ return Result<QStringList>::ok(out);
+}
+
+// ── Agents ───────────────────────────────────────────────────────────────────
+
+Result<QString> ArenaStore::insert_agent(const QString& competition_id,
+ const ArenaAgentSpec& spec) {
+ const QString id = make_id();
+ auto r = db().execute(
+ "INSERT INTO arena_agents (id, competition_id, provider, model_id, display_name,"
+ " color_hex, source_kind, source_ref, status) VALUES (?,?,?,?,?,?,?,?,'active')",
+ {id, competition_id, nn(spec.provider), nn(spec.model_id), nn(spec.display_name),
+ nn(spec.color_hex), nn(spec.source_kind), nn(spec.source_ref)});
+ if (r.is_err())
+ return Result<QString>::err(r.error());
+ return Result<QString>::ok(id);
+}
+
+Result<QVector<AgentRow>> ArenaStore::agents_for(const QString& competition_id) {
+ return query_list_as<AgentRow>(
+ QStringLiteral("SELECT %1 FROM arena_agents WHERE competition_id = ? ORDER BY rowid")
+ .arg(kAgentCols),
+ {competition_id}, map_agent);
+}
+
+Result<void> ArenaStore::set_agent_status(const QString& agent_id, const QString& status,
+ const QString& reason) {
+ return exec_write("UPDATE arena_agents SET status = ?, halt_reason = ? WHERE id = ?",
+ {nn(status), nn(reason), agent_id});
+}
+
+Result<void> ArenaStore::set_agent_failures(const QString& agent_id, int count) {
+ return exec_write("UPDATE arena_agents SET consecutive_failures = ? WHERE id = ?",
+ {count, agent_id});
+}
+
+// ── Rounds / decisions / orders ──────────────────────────────────────────────
+
+Result<void> ArenaStore::insert_round(const QString& competition_id, int seq, qint64 started_at,
+ const QString& snapshot_json) {
+ return exec_write(
+ "INSERT INTO arena_rounds (competition_id, seq, started_at, market_snapshot_json,"
+ " status) VALUES (?,?,?,?,'running')",
+ {competition_id, seq, started_at, nn(snapshot_json)});
+}
+
+Result<void> ArenaStore::complete_round(const QString& competition_id, int seq,
+ qint64 completed_at, const QString& status) {
+ return exec_write(
+ "UPDATE arena_rounds SET completed_at = ?, status = ? WHERE competition_id = ? AND seq = ?",
+ {completed_at, nn(status), competition_id, seq});
+}
+
+Result<int> ArenaStore::last_round_seq(const QString& competition_id) {
+ auto r = db().execute("SELECT COALESCE(MAX(seq), 0) FROM arena_rounds WHERE competition_id = ?",
+ {competition_id});
+ if (r.is_err())
+ return Result<int>::err(r.error());
+ auto& q = r.value();
+ if (!q.next())
+ return Result<int>::ok(0);
+ return Result<int>::ok(q.value(0).toInt());
+}
+
+Result<QString> ArenaStore::insert_decision(DecisionRow d) {
+ d.id = make_id();
+ d.ts = now_millis();
+ auto r = db().execute(
+ "INSERT INTO arena_decisions (id, competition_id, agent_id, round_seq, system_prompt,"
+ " user_prompt, raw_response, actions_json, parse_error, status, latency_ms,"
+ " prompt_tokens, completion_tokens, ts) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
+ {d.id, d.competition_id, d.agent_id, d.round_seq, nn(d.system_prompt), nn(d.user_prompt),
+ nn(d.raw_response), nn(d.actions_json), nn(d.parse_error), nn(d.status), d.latency_ms,
+ d.prompt_tokens, d.completion_tokens, d.ts});
+ if (r.is_err())
+ return Result<QString>::err(r.error());
+ return Result<QString>::ok(d.id);
+}
+
+Result<QVector<DecisionRow>> ArenaStore::recent_decisions(const QString& competition_id,
+ const QString& agent_id, int limit) {
+ auto r = query_list_as<DecisionRow>(
+ QStringLiteral("SELECT %1 FROM arena_decisions WHERE competition_id = ? AND agent_id = ?"
+ " ORDER BY round_seq DESC LIMIT ?")
+ .arg(kDecisionCols),
+ {competition_id, agent_id, limit}, map_decision);
+ if (r.is_err())
+ return r;
+ auto rows = r.value();
+ std::reverse(rows.begin(), rows.end()); // oldest-first
+ return Result<QVector<DecisionRow>>::ok(std::move(rows));
+}
+
+Result<QVector<DecisionRow>> ArenaStore::latest_decisions(const QString& competition_id,
+ const QString& agent_id, int limit) {
+ QString sql = QStringLiteral("SELECT %1 FROM arena_decisions WHERE competition_id = ?")
+ .arg(kDecisionCols);
+ QVariantList params{competition_id};
+ if (!agent_id.isEmpty()) {
+ sql += QStringLiteral(" AND agent_id = ?");
+ params << agent_id;
+ }
+ sql += QStringLiteral(" ORDER BY ts DESC LIMIT ?");
+ params << limit;
+ return query_list_as<DecisionRow>(sql, params, map_decision);
+}
+
+Result<QHash<QString, qint64>> ArenaStore::token_totals(const QString& competition_id) {
+ auto r = db().execute(
+ "SELECT agent_id, SUM(prompt_tokens + completion_tokens) FROM arena_decisions"
+ " WHERE competition_id = ? GROUP BY agent_id",
+ {competition_id});
+ if (r.is_err())
+ return Result<QHash<QString, qint64>>::err(r.error());
+ QHash<QString, qint64> out;
+ auto& q = r.value();
+ while (q.next())
+ out[q.value(0).toString()] = q.value(1).toLongLong();
+ return Result<QHash<QString, qint64>>::ok(out);
+}
+
+Result<QVector<DecisionRow>> ArenaStore::decisions_for_round(const QString& competition_id,
+ int seq) {
+ return query_list_as<DecisionRow>(
+ QStringLiteral("SELECT %1 FROM arena_decisions WHERE competition_id = ? AND round_seq = ?"
+ " ORDER BY ts ASC")
+ .arg(kDecisionCols),
+ {competition_id, seq}, map_decision);
+}
+
+Result<QString> ArenaStore::insert_order(OrderRow o) {
+ o.id = make_id();
+ o.ts = now_millis();
+ auto r = db().execute(
+ "INSERT INTO arena_orders (id, competition_id, agent_id, round_seq, coin, side, action,"
+ " qty, price, notional_usd, leverage, fee, realized_pnl, status, reject_reason, ts)"
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
+ {o.id, o.competition_id, o.agent_id, o.round_seq, nn(o.coin), nn(o.side), nn(o.action), o.qty,
+ o.price, o.notional_usd, o.leverage, o.fee, o.realized_pnl, nn(o.status),
+ nn(o.reject_reason), o.ts});
+ if (r.is_err())
+ return Result<QString>::err(r.error());
+ return Result<QString>::ok(o.id);
+}
+
+Result<QVector<OrderRow>> ArenaStore::orders_for(const QString& competition_id,
+ const QString& agent_id, int limit) {
+ if (agent_id.isEmpty())
+ return query_list_as<OrderRow>(
+ QStringLiteral("SELECT %1 FROM arena_orders WHERE competition_id = ?"
+ " ORDER BY ts DESC LIMIT ?")
+ .arg(kOrderCols),
+ {competition_id, limit}, map_order);
+ return query_list_as<OrderRow>(
+ QStringLiteral("SELECT %1 FROM arena_orders WHERE competition_id = ? AND agent_id = ?"
+ " ORDER BY ts DESC LIMIT ?")
+ .arg(kOrderCols),
+ {competition_id, agent_id, limit}, map_order);
+}
+
+// ── Positions / accounts / equity ────────────────────────────────────────────
+
+Result<void> ArenaStore::upsert_position(const PositionRow& p) {
+ return exec_write(
+ "INSERT INTO arena_positions (competition_id, agent_id, coin, side, qty, entry_price,"
+ " leverage, funding_accrued) VALUES (?,?,?,?,?,?,?,?)"
+ " ON CONFLICT(competition_id, agent_id, coin) DO UPDATE SET side=excluded.side,"
+ " qty=excluded.qty, entry_price=excluded.entry_price, leverage=excluded.leverage,"
+ " funding_accrued=excluded.funding_accrued",
+ {p.competition_id, p.agent_id, nn(p.coin), nn(p.side), p.qty, p.entry_price, p.leverage,
+ p.funding_accrued});
+}
+
+Result<void> ArenaStore::delete_position(const QString& competition_id, const QString& agent_id,
+ const QString& coin) {
+ return exec_write(
+ "DELETE FROM arena_positions WHERE competition_id = ? AND agent_id = ? AND coin = ?",
+ {competition_id, agent_id, coin});
+}
+
+Result<QVector<PositionRow>> ArenaStore::positions_for(const QString& competition_id,
+ const QString& agent_id) {
+ if (agent_id.isEmpty())
+ return query_list_as<PositionRow>(
+ QStringLiteral("SELECT %1 FROM arena_positions WHERE competition_id = ?"
+ " ORDER BY agent_id, coin")
+ .arg(kPositionCols),
+ {competition_id}, map_position);
+ return query_list_as<PositionRow>(
+ QStringLiteral("SELECT %1 FROM arena_positions WHERE competition_id = ? AND agent_id = ?"
+ " ORDER BY coin")
+ .arg(kPositionCols),
+ {competition_id, agent_id}, map_position);
+}
+
+Result<void> ArenaStore::upsert_account(const QString& competition_id, const QString& agent_id,
+ double balance) {
+ return exec_write("INSERT INTO arena_accounts (competition_id, agent_id, balance)"
+ " VALUES (?,?,?) ON CONFLICT(competition_id, agent_id)"
+ " DO UPDATE SET balance=excluded.balance",
+ {nn(competition_id), nn(agent_id), balance});
+}
+
+Result<double> ArenaStore::account_balance(const QString& competition_id,
+ const QString& agent_id) {
+ auto r = db().execute(
+ "SELECT balance FROM arena_accounts WHERE competition_id = ? AND agent_id = ?",
+ {competition_id, agent_id});
+ if (r.is_err())
+ return Result<double>::err(r.error());
+ auto& q = r.value();
+ if (!q.next())
+ return Result<double>::err("Not found");
+ return Result<double>::ok(q.value(0).toDouble());
+}
+
+Result<void> ArenaStore::insert_equity_snapshot(const EquitySnapshotRow& s) {
+ // Upsert on the (competition_id, agent_id, round_seq) PK so re-snapshotting a
+ // round (e.g. retry after a partial failure) overwrites instead of erroring.
+ return exec_write(
+ "INSERT INTO arena_equity_snapshots (competition_id, agent_id, round_seq, ts, equity,"
+ " balance, unrealized_pnl) VALUES (?,?,?,?,?,?,?)"
+ " ON CONFLICT(competition_id, agent_id, round_seq) DO UPDATE SET ts=excluded.ts,"
+ " equity=excluded.equity, balance=excluded.balance,"
+ " unrealized_pnl=excluded.unrealized_pnl",
+ {s.competition_id, s.agent_id, s.round_seq, s.ts, s.equity, s.balance, s.unrealized_pnl});
+}
+
+Result<QVector<EquitySnapshotRow>> ArenaStore::equity_series(const QString& competition_id) {
+ return query_list_as<EquitySnapshotRow>(
+ QStringLiteral("SELECT %1 FROM arena_equity_snapshots WHERE competition_id = ?"
+ " ORDER BY round_seq ASC, agent_id")
+ .arg(kEquityCols),
+ {competition_id}, map_equity);
+}
+
+// ── Events ───────────────────────────────────────────────────────────────────
+
+Result<void> ArenaStore::insert_event(const QString& competition_id, const QString& agent_id,
+ const QString& type, const QString& payload_json) {
+ return exec_write("INSERT INTO arena_events (competition_id, agent_id, type, payload_json,"
+ " ts) VALUES (?,?,?,?,?)",
+ {nn(competition_id), nn(agent_id), nn(type), nn(payload_json), now_millis()});
+}
+
+Result<QVector<QString>> ArenaStore::recent_events(const QString& competition_id, int limit) {
+ auto r = db().execute("SELECT ts, agent_id, type, payload_json FROM arena_events"
+ " WHERE competition_id = ? ORDER BY seq DESC LIMIT ?",
+ {competition_id, limit});
+ if (r.is_err())
+ return Result<QVector<QString>>::err(r.error());
+ QVector<QString> out;
+ auto& q = r.value();
+ while (q.next())
+ out << QStringLiteral("%1|%2|%3|%4")
+ .arg(q.value(0).toLongLong())
+ .arg(q.value(1).toString(), q.value(2).toString(), q.value(3).toString());
+ std::reverse(out.begin(), out.end()); // oldest-first
+ return Result<QVector<QString>>::ok(std::move(out));
+}
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaStore.h b/fincept-qt/src/services/alpha_arena/ArenaStore.h
new file mode 100644
index 000000000..124da637c
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaStore.h
@@ -0,0 +1,60 @@
+#pragma once
+// ArenaStore — all SQLite access for the Alpha Arena rewrite (arena_* tables).
+
+#include "core/result/Result.h"
+#include "services/alpha_arena/ArenaTypes.h"
+#include "storage/repositories/BaseRepository.h"
+
+namespace fincept::arena {
+
+class ArenaStore : public BaseRepository<CompetitionRow> {
+ public:
+ static ArenaStore& instance();
+
+ // Competitions
+ Result<QString> insert_competition(const ArenaConfig& cfg); // returns new id
+ Result<CompetitionRow> competition(const QString& id);
+ Result<QVector<CompetitionRow>> list_competitions(); // newest first
+ Result<void> set_competition_status(const QString& id, const QString& status);
+ Result<void> set_competition_timestamps(const QString& id, qint64 started_at, qint64 ended_at);
+ Result<void> set_cadence(const QString& id, int seconds);
+ Result<void> delete_competition_cascade(const QString& id); // all 9 tables
+ Result<QStringList> competitions_with_status(const QString& status);
+
+ // Agents
+ Result<QString> insert_agent(const QString& competition_id, const ArenaAgentSpec& spec);
+ Result<QVector<AgentRow>> agents_for(const QString& competition_id);
+ Result<void> set_agent_status(const QString& agent_id, const QString& status, const QString& reason);
+ Result<void> set_agent_failures(const QString& agent_id, int count);
+
+ // Rounds / decisions / orders
+ Result<void> insert_round(const QString& competition_id, int seq, qint64 started_at, const QString& snapshot_json);
+ Result<void> complete_round(const QString& competition_id, int seq, qint64 completed_at, const QString& status);
+ Result<int> last_round_seq(const QString& competition_id);
+ Result<QString> insert_decision(DecisionRow d); // fills id+ts, returns id
+ Result<QVector<DecisionRow>> recent_decisions(const QString& competition_id, const QString& agent_id, int limit);
+ /// Newest decisions across all agents (for the MODEL CHAT feed). agent_id empty = all.
+ Result<QVector<DecisionRow>> latest_decisions(const QString& competition_id,
+ const QString& agent_id, int limit);
+ /// Aggregate token spend per agent: agent_id → (prompt+completion) tokens.
+ Result<QHash<QString, qint64>> token_totals(const QString& competition_id);
+ Result<QVector<DecisionRow>> decisions_for_round(const QString& competition_id, int seq);
+ Result<QString> insert_order(OrderRow o); // fills id+ts, returns id
+ Result<QVector<OrderRow>> orders_for(const QString& competition_id, const QString& agent_id /*empty=all*/, int limit);
+
+ // Positions / accounts / equity
+ Result<void> upsert_position(const PositionRow& p);
+ Result<void> delete_position(const QString& competition_id, const QString& agent_id, const QString& coin);
+ Result<QVector<PositionRow>> positions_for(const QString& competition_id, const QString& agent_id /*empty=all*/);
+ Result<void> upsert_account(const QString& competition_id, const QString& agent_id, double balance);
+ Result<double> account_balance(const QString& competition_id, const QString& agent_id);
+ Result<void> insert_equity_snapshot(const EquitySnapshotRow& s);
+ Result<QVector<EquitySnapshotRow>> equity_series(const QString& competition_id);
+
+ // Events
+ Result<void> insert_event(const QString& competition_id, const QString& agent_id,
+ const QString& type, const QString& payload_json);
+ Result<QVector<QString>> recent_events(const QString& competition_id, int limit); // "ts|agent|type|payload"
+};
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaTypes.h b/fincept-qt/src/services/alpha_arena/ArenaTypes.h
new file mode 100644
index 000000000..7a4d5a2ca
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/ArenaTypes.h
@@ -0,0 +1,91 @@
+#pragma once
+// Domain types for the Alpha Arena rewrite. Namespace fincept::arena.
+// Spec: docs/superpowers/specs/2026-06-10-alpha-arena-rewrite-design.md
+
+#include <QHash>
+#include <QString>
+#include <QStringList>
+#include <QVector>
+
+namespace fincept::arena {
+
+struct ArenaAgentSpec {
+ QString provider, model_id, display_name, color_hex;
+ QString source_kind; // "provider" | "model" | "profile"
+ QString source_ref; // row id in the source table ("" for provider — provider name is the key)
+};
+
+struct ArenaConfig {
+ QString name;
+ QStringList instruments; // e.g. {"BTC","ETH"}
+ double capital_per_agent = 10000.0;
+ int cadence_seconds = 180;
+ double max_leverage = 10.0;
+ QString system_prompt_override; // empty = default prompt
+ QString venue = QStringLiteral("paper"); // "paper" | "hyperliquid"
+ bool live_mode = false;
+ QVector<ArenaAgentSpec> agents;
+};
+
+// ── DB row mirrors (1:1 with arena_* tables) ────────────────────────────────
+struct CompetitionRow {
+ QString id, name, status, venue, system_prompt_override;
+ QStringList instruments;
+ double capital_per_agent = 0, max_leverage = 10;
+ int cadence_seconds = 180;
+ bool live_mode = false;
+ qint64 created_at = 0, started_at = 0, ended_at = 0;
+};
+struct AgentRow {
+ QString id, competition_id, provider, model_id, display_name, color_hex,
+ source_kind, source_ref, status, halt_reason;
+ int consecutive_failures = 0;
+};
+struct DecisionRow {
+ QString id, competition_id, agent_id, system_prompt, user_prompt, raw_response,
+ actions_json, parse_error, status;
+ int round_seq = 0, prompt_tokens = 0, completion_tokens = 0;
+ qint64 latency_ms = 0, ts = 0;
+};
+struct OrderRow {
+ QString id, competition_id, agent_id, coin, side, action, status, reject_reason;
+ int round_seq = 0;
+ double qty = 0, price = 0, notional_usd = 0, leverage = 1, fee = 0, realized_pnl = 0;
+ qint64 ts = 0;
+};
+struct PositionRow {
+ QString competition_id, agent_id, coin, side; // side: "long" | "short"
+ double qty = 0, entry_price = 0, leverage = 1, funding_accrued = 0;
+};
+struct EquitySnapshotRow {
+ QString competition_id, agent_id;
+ int round_seq = 0;
+ qint64 ts = 0;
+ double equity = 0, balance = 0, unrealized_pnl = 0;
+};
+
+// ── Market data ─────────────────────────────────────────────────────────────
+struct Candle { qint64 t = 0; double o = 0, h = 0, l = 0, c = 0, v = 0; };
+struct CoinSnapshot {
+ QString coin;
+ double mid = 0, open_interest = 0, day_change_pct = 0;
+ double funding_rate = 0; // per-hour fractional rate (HL convention)
+ QVector<Candle> candles_1h; // oldest → newest
+ double ema20 = 0, ema50 = 0, rsi14 = 0, atr14 = 0;
+};
+struct MarketSnapshot {
+ qint64 ts = 0;
+ QHash<QString, CoinSnapshot> coins;
+};
+
+// ── Decisions ───────────────────────────────────────────────────────────────
+enum class ActionKind { Open, Close, Hold };
+struct AgentAction {
+ ActionKind kind = ActionKind::Hold;
+ QString coin, side; // side: "long"|"short" (open only)
+ double size_usd = 0; // open: notional; close: 0 = full close, >0 = reduce
+ double leverage = 1;
+ QString reason;
+};
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ContextBuilder.cpp b/fincept-qt/src/services/alpha_arena/ContextBuilder.cpp
deleted file mode 100644
index 7d1aea183..000000000
--- a/fincept-qt/src/services/alpha_arena/ContextBuilder.cpp
+++ /dev/null
@@ -1,263 +0,0 @@
-#include "services/alpha_arena/ContextBuilder.h"
-
-#include <QChar>
-#include <QDateTime>
-#include <QString>
-#include <QTextStream>
-#include <QTimeZone>
-
-#include <cmath>
-
-namespace fincept::services::alpha_arena {
-
-// ─── Stable float formatting ────────────────────────────────────────────────
-//
-// QString::number is locale-independent for 'f' format, but to belt-and-brace
-// we route everything through these helpers so a future surprise (e.g. a
-// reviewer adding setlocale somewhere) cannot drift the prompt bytes.
-
-namespace {
-
-QString fmt_price(double v) {
- if (std::isnan(v)) return QStringLiteral("null");
- return QString::number(v, 'f', 6);
-}
-
-QString fmt_indicator(double v) {
- if (std::isnan(v)) return QStringLiteral("null");
- return QString::number(v, 'f', 4);
-}
-
-QString fmt_qty(double v) {
- if (std::isnan(v)) return QStringLiteral("null");
- return QString::number(v, 'f', 8);
-}
-
-QString fmt_pct(double v) {
- if (std::isnan(v)) return QStringLiteral("null");
- return QString::number(v, 'f', 4);
-}
-
-QString fmt_int(int v) {
- return QString::number(v);
-}
-
-QString fmt_iso_utc(qint64 ms) {
- const auto dt = QDateTime::fromMSecsSinceEpoch(ms, QTimeZone::utc());
- return dt.toString(QStringLiteral("yyyy-MM-dd'T'HH:mm:ss'Z'"));
-}
-
-void append_bars(QTextStream& s, const QVector<Bar>& bars) {
- s << "[";
- for (int i = 0; i < bars.size(); ++i) {
- const auto& b = bars[i];
- if (i > 0) s << ",";
- s << "{\"t\":\"" << fmt_iso_utc(b.utc_ms) << "\","
- << "\"o\":" << fmt_price(b.open) << ","
- << "\"h\":" << fmt_price(b.high) << ","
- << "\"l\":" << fmt_price(b.low) << ","
- << "\"c\":" << fmt_price(b.close) << ","
- << "\"v\":" << fmt_qty(b.volume) << "}";
- }
- s << "]";
-}
-
-// Manual JSON string escape — keeps the prompt byte sequence under our
-// exclusive control (no QJsonDocument round-trip surprises).
-QString json_escape(const QString& in) {
- QString out;
- out.reserve(in.size() + 2);
- out.append(QChar('"'));
- for (const QChar c : in) {
- const ushort u = c.unicode();
- switch (u) {
- case '"': out.append(QStringLiteral("\\\"")); break;
- case '\\': out.append(QStringLiteral("\\\\")); break;
- case '\b': out.append(QStringLiteral("\\b")); break;
- case '\f': out.append(QStringLiteral("\\f")); break;
- case '\n': out.append(QStringLiteral("\\n")); break;
- case '\r': out.append(QStringLiteral("\\r")); break;
- case '\t': out.append(QStringLiteral("\\t")); break;
- default:
- if (u < 0x20) {
- out.append(QStringLiteral("\\u%1").arg(u, 4, 16, QLatin1Char('0')));
- } else {
- out.append(c);
- }
- }
- }
- out.append(QChar('"'));
- return out;
-}
-
-void append_position(QTextStream& s, const Position& p) {
- s << "{"
- << "\"coin\":" << json_escape(p.coin) << ","
- << "\"qty\":" << fmt_qty(p.qty) << ","
- << "\"entry\":" << fmt_price(p.entry) << ","
- << "\"mark\":" << fmt_price(p.mark) << ","
- << "\"liq_price\":" << fmt_price(p.liq_price) << ","
- << "\"unrealized_pnl\":" << fmt_price(p.unrealized_pnl) << ","
- << "\"leverage\":" << fmt_int(p.leverage) << ","
- << "\"profit_target\":" << fmt_price(p.profit_target) << ","
- << "\"stop_loss\":" << fmt_price(p.stop_loss) << ","
- << "\"invalidation_condition\":" << json_escape(p.invalidation_condition)
- << "}";
-}
-
-} // namespace
-
-// ─── System prompt ──────────────────────────────────────────────────────────
-
-QString build_system_prompt(CompetitionMode mode) {
- QString s;
- QTextStream w(&s);
- w << "You are an autonomous trading agent competing in Alpha Arena. "
- "All competitors receive an identical context every tick. You compete "
- "on real or paper Hyperliquid perpetuals.\n"
- "\n"
- "## Action grammar\n"
- "\n"
- "On every tick you must emit a JSON object of the form:\n"
- " {\"actions\": [<action>, ...]}\n"
- "where each <action> object has fields:\n"
- " signal string, one of "
- "[\"buy_to_enter\", \"sell_to_enter\", \"hold\", \"close\"]\n"
- " coin string, base symbol from the perp universe "
- "(BTC, ETH, SOL, BNB, DOGE, XRP)\n"
- " quantity number, base-asset units (>0 for entries)\n"
- " leverage integer in [1, 20]\n"
- " profit_target number, absolute price (>0 for entries)\n"
- " stop_loss number, absolute price (>0 for entries)\n"
- " invalidation_condition string up to 280 chars — the condition that "
- "would void this thesis\n"
- " confidence number in [0, 1]\n"
- " risk_usd number — your estimate of |entry-stop|*qty; "
- "the engine recomputes\n"
- " justification string up to 1000 chars\n"
- "\n"
- "## Hard rules (engine enforced — violations are silently rejected)\n"
- "\n"
- "1. One position per coin. You may not pyramid, hedge, or partially close.\n"
- "2. Risk per trade ≤ 2% of account equity (recomputed by the engine).\n"
- "3. Liquidation buffer ≥ 15% of mark price.\n"
- "4. Maximum leverage is 20×.\n"
- "5. No memory across ticks. Your only persistent state is the position "
- "table you see in the user prompt — including the invalidation_condition "
- "you set on entry. Treat that field as your externalised memory.\n"
- "6. Series in the user prompt are ordered OLDEST → NEWEST.\n"
- "7. There is no chat history. Each call is independent.\n";
-
- if (mode == CompetitionMode::Monk) {
- w << "\n"
- "## Monk-mode rules\n"
- "\n"
- "Additional caps apply:\n"
- " • At most one entry per coin per 30 minutes.\n"
- " • Notional position size capped at 25% of equity.\n";
- } else if (mode == CompetitionMode::Situational) {
- w << "\n"
- "## Situational-mode\n"
- "\n"
- "Your user prompt also contains a `peers` array showing the other "
- "agents' open positions (coin, qty, leverage). Equity and PnL of "
- "peers are NOT disclosed.\n";
- }
-
- w << "\n"
- "## Output\n"
- "\n"
- "Reply with the JSON object only. Prose around it is permitted but "
- "the engine extracts the outermost {...}. Do not retry on parse "
- "errors — a malformed tick is a no-op.\n";
- return s;
-}
-
-// ─── User prompt ────────────────────────────────────────────────────────────
-
-QString build_user_prompt(const TickContext& ctx,
- const AgentAccountState& account,
- CompetitionMode mode,
- const std::optional<SituationalContext>& situational) {
- QString s;
- QTextStream w(&s);
-
- // Top-level envelope. Stable field order is critical for the byte-equal
- // invariant: {tick, mode, markets, account, peers}.
- w << "{";
-
- // tick
- w << "\"tick\":{"
- << "\"utc\":\"" << fmt_iso_utc(ctx.tick.utc_ms) << "\","
- << "\"seq\":" << fmt_int(ctx.tick.seq)
- << "},";
-
- // mode
- w << "\"mode\":\"" << mode_to_wire(mode) << "\",";
-
- // markets — coin order: as supplied (engine sorts to canonical order
- // before passing in; we don't re-sort here).
- w << "\"markets\":[";
- for (int i = 0; i < ctx.markets.size(); ++i) {
- const auto& m = ctx.markets[i];
- if (i > 0) w << ",";
- w << "{"
- << "\"coin\":" << json_escape(m.coin) << ","
- << "\"mid\":" << fmt_price(m.mid) << ","
- << "\"bid\":" << fmt_price(m.bid) << ","
- << "\"ask\":" << fmt_price(m.ask) << ","
- << "\"open_interest\":" << fmt_qty(m.open_interest) << ","
- << "\"funding_rate\":" << fmt_pct(m.funding_rate) << ","
- << "\"ema20\":" << fmt_indicator(m.ema20) << ","
- << "\"rsi7\":" << fmt_indicator(m.rsi7) << ","
- << "\"macd\":" << fmt_indicator(m.macd) << ","
- << "\"macd_signal\":" << fmt_indicator(m.macd_signal) << ","
- << "\"bars_3m_24h\":";
- append_bars(w, m.bars_3m_24h);
- w << ",\"bars_4h_30d\":";
- append_bars(w, m.bars_4h_30d);
- w << "}";
- }
- w << "],";
-
- // account
- w << "\"account\":{"
- << "\"equity\":" << fmt_price(account.equity) << ","
- << "\"cash\":" << fmt_price(account.cash) << ","
- << "\"return_pct\":" << fmt_pct(account.return_pct) << ","
- << "\"sharpe\":" << fmt_pct(account.sharpe) << ","
- << "\"max_drawdown\":" << fmt_pct(account.max_drawdown) << ","
- << "\"fees_paid\":" << fmt_price(account.fees_paid) << ","
- << "\"win_rate\":" << fmt_pct(account.win_rate) << ","
- << "\"trades_count\":" << fmt_int(account.trades_count) << ","
- << "\"positions\":[";
- for (int i = 0; i < account.positions.size(); ++i) {
- if (i > 0) w << ",";
- append_position(w, account.positions[i]);
- }
- w << "]},";
-
- // peers — only present in situational mode
- w << "\"peers\":";
- if (mode == CompetitionMode::Situational && situational.has_value()) {
- w << "[";
- for (int i = 0; i < situational->peers.size(); ++i) {
- const auto& p = situational->peers[i];
- if (i > 0) w << ",";
- w << "{"
- << "\"agent\":" << json_escape(p.agent_display_name) << ","
- << "\"coin\":" << json_escape(p.coin) << ","
- << "\"qty\":" << fmt_qty(p.qty) << ","
- << "\"leverage\":" << fmt_int(p.leverage)
- << "}";
- }
- w << "]";
- } else {
- w << "null";
- }
-
- w << "}";
- return s;
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/ContextBuilder.h b/fincept-qt/src/services/alpha_arena/ContextBuilder.h
deleted file mode 100644
index 05a850ce2..000000000
--- a/fincept-qt/src/services/alpha_arena/ContextBuilder.h
+++ /dev/null
@@ -1,44 +0,0 @@
-#pragma once
-// ContextBuilder — assembles the system prompt + user prompt that every
-// model sees on every tick.
-//
-// The byte-equal-across-agents invariant is the whole point of Alpha Arena.
-// Two agents in the same competition, on the same tick, in non-situational
-// mode, MUST receive byte-identical prompt strings. (Situational mode is the
-// one exception — peers vary per agent by design.)
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §4 (Context builder).
-
-#include "services/alpha_arena/AlphaArenaSchema.h"
-#include "services/alpha_arena/AlphaArenaTypes.h"
-
-#include <QString>
-
-#include <optional>
-
-namespace fincept::services::alpha_arena {
-
-/// Render the static system prompt. This is constant for the lifetime of a
-/// competition — it depends only on the policy/risk constants and the mode.
-/// Cached by the engine.
-QString build_system_prompt(CompetitionMode mode);
-
-/// Render the dynamic user prompt for one agent on one tick.
-///
-/// Determinism contract:
-/// For two calls with the same TickContext + same AgentAccountState +
-/// same CompetitionMode + same SituationalContext (or both nullopt),
-/// the returned string is byte-identical. This is enforced by a unit test
-/// in Phase 6.
-///
-/// Float formatting is fixed:
-/// * prices, equity, USD: 6 decimals
-/// * indicators (EMA, MACD, RSI, ATR): 4 decimals
-/// * quantities, volumes: 8 decimals
-/// * leverage, integer counts: %d
-QString build_user_prompt(const TickContext& ctx,
- const AgentAccountState& account,
- CompetitionMode mode,
- const std::optional<SituationalContext>& situational);
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/HyperliquidLiveVenue.cpp b/fincept-qt/src/services/alpha_arena/HyperliquidLiveVenue.cpp
new file mode 100644
index 000000000..111e5644e
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/HyperliquidLiveVenue.cpp
@@ -0,0 +1,65 @@
+#include "services/alpha_arena/HyperliquidLiveVenue.h"
+#include "core/logging/Logger.h"
+#include "trading/exchanges/hyperliquid/HyperliquidVenue.h"
+#include <QJsonDocument>
+#include <QJsonObject>
+
+namespace fincept::arena {
+
+namespace hlx = fincept::trading::hyperliquid;
+namespace aav = fincept::services::alpha_arena;
+
+static constexpr const char* TAG = "ArenaLive";
+
+HyperliquidLiveVenue::HyperliquidLiveVenue(ArenaStore& store, const QString& competition_id)
+ : PaperExchange(store, competition_id) {
+ // Same construction as the old engine (AlphaArenaEngine::select_venue_for_kind):
+ // mainnet default + immediate connect. The agent wallet key never touches this
+ // class — HyperliquidSigner reads it from SecureStorage at sign time under
+ // "alpha_arena/agent_key/<competition_id>", which is why we bind the id here.
+ hl_ = new hlx::HyperliquidVenue(nullptr);
+ hl_->set_competition_id(competition_id);
+ hl_->set_testnet(false);
+ hl_->connect();
+ LOG_INFO(TAG, QStringLiteral("live venue up for competition %1 (mainnet)").arg(competition_id));
+}
+
+HyperliquidLiveVenue::~HyperliquidLiveVenue() { delete hl_; }
+
+Result<OrderRow> HyperliquidLiveVenue::execute(const QString& agent_id, const AgentAction& a,
+ int round_seq) {
+ auto r = PaperExchange::execute(agent_id, a, round_seq);
+ if (r.is_ok() && r.value().status == QLatin1String("filled")) mirror_live(r.value());
+ return r;
+}
+
+void HyperliquidLiveVenue::mirror_live(const OrderRow& o) {
+ aav::OrderRequest req;
+ req.agent_id = o.agent_id;
+ req.coin = o.coin;
+ // open long / close short → buy; open short / close long → sell.
+ const bool is_buy = (o.action == QLatin1String("open")) == (o.side == QLatin1String("long"));
+ req.side = is_buy ? QStringLiteral("buy") : QStringLiteral("sell");
+ req.qty = o.qty;
+ req.leverage = qMax(1, static_cast<int>(o.leverage));
+ req.reduce_only = o.action == QLatin1String("close");
+
+ // Fire-and-record: the paper fill already happened (it is the ledger); a
+ // live rejection is logged + persisted so the operator can reconcile.
+ // Capture `o` by value only — the ack may outlive this venue.
+ hl_->place_order(req, [o](aav::OrderAck ack) {
+ if (ack.status == QLatin1String("accepted")) return;
+ LOG_ERROR(TAG, QStringLiteral("live mirror failed for %1 %2 %3: %4")
+ .arg(o.action, o.coin, o.id.isEmpty() ? QStringLiteral("(no id)") : o.id,
+ ack.error));
+ ArenaStore::instance().insert_event(
+ o.competition_id, o.agent_id, QStringLiteral("live_mirror_failed"),
+ QString::fromUtf8(QJsonDocument(QJsonObject{{"order_id", o.id},
+ {"coin", o.coin},
+ {"action", o.action},
+ {"error", ack.error}})
+ .toJson(QJsonDocument::Compact)));
+ });
+}
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/HyperliquidLiveVenue.h b/fincept-qt/src/services/alpha_arena/HyperliquidLiveVenue.h
new file mode 100644
index 000000000..d840ffa34
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/HyperliquidLiveVenue.h
@@ -0,0 +1,30 @@
+#pragma once
+// HyperliquidLiveVenue — PaperExchange accounting + real order mirroring to
+// Hyperliquid mainnet via the existing HyperliquidVenue (signer-gated).
+// The paper book IS the ledger; live orders are fire-and-record (failures are
+// logged to arena_events and surfaced; accounting still updates so the arena
+// stays consistent). NOTE: kill_all/liquidation closes are NOT yet mirrored to
+// the live book — this must be solved before the real exchange POST is wired.
+// stays consistent). Wallet key handle: "alpha_arena/agent_key/<competition_id>"
+// (written by LiveModeGateDialog; ArenaEngine::start() re-keys the wizard's
+// "pending" handle to the real competition id before constructing this venue).
+#include "services/alpha_arena/PaperExchange.h"
+
+namespace fincept::trading::hyperliquid { class HyperliquidVenue; }
+
+namespace fincept::arena {
+
+class HyperliquidLiveVenue : public PaperExchange {
+ public:
+ HyperliquidLiveVenue(ArenaStore& store, const QString& competition_id);
+ ~HyperliquidLiveVenue() override;
+
+ Result<OrderRow> execute(const QString& agent_id, const AgentAction& a, int round_seq) override;
+
+ private:
+ void mirror_live(const OrderRow& filled);
+
+ fincept::trading::hyperliquid::HyperliquidVenue* hl_ = nullptr; // owned (no QObject parent)
+};
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/IExchangeVenue.h b/fincept-qt/src/services/alpha_arena/IExchangeVenue.h
index 7cd26258c..cddc52cda 100644
--- a/fincept-qt/src/services/alpha_arena/IExchangeVenue.h
+++ b/fincept-qt/src/services/alpha_arena/IExchangeVenue.h
@@ -1,20 +1,15 @@
#pragma once
-// IExchangeVenue — the only contract the OrderRouter knows about.
+// IExchangeVenue — abstract venue contract (legacy alpha_arena namespace).
//
-// Two implementations:
-// * PaperVenue — in-memory simulator that mirrors Hyperliquid fee/funding/
-// liquidation math, fed real Hyperliquid mark prices for fidelity.
-// * HyperliquidVenue — live, signs with an agent wallet (separate from the
-// user's master wallet), routes via Hyperliquid REST + WS.
+// Sole remaining implementation: trading/exchanges/hyperliquid/
+// HyperliquidVenue, which signs with an agent wallet (separate from the
+// user's master wallet) and routes via Hyperliquid REST + WS. The new
+// fincept::arena engine drives it through HyperliquidLiveVenue.
//
// All callbacks marshal back onto the calling QObject's thread via
-// QPointer + invokeMethod (see PaperVenue.cpp / HyperliquidVenue.cpp).
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §7 (Order router).
+// QPointer + invokeMethod (see HyperliquidVenue.cpp).
#include "core/result/Result.h"
-#include "services/alpha_arena/AlphaArenaSchema.h"
-#include "services/alpha_arena/AlphaArenaTypes.h"
#include <QObject>
#include <QString>
@@ -28,7 +23,7 @@ namespace fincept::services::alpha_arena {
/// venue-side order id and signalling fills through fill_callback.
struct OrderRequest {
QString agent_id; // logical agent identity (DB FK)
- QString coin; // base symbol from kPerpUniverse()
+ QString coin; // base symbol, e.g. "BTC"
QString side; // "buy" | "sell"
double qty = 0.0; // base-asset units, > 0
int leverage = 1; // [1, 20]
@@ -93,7 +88,7 @@ class IExchangeVenue {
/// Identity for logs / persistence / leaderboard badge ("paper" / "hyperliquid").
virtual QString venue_kind() const = 0;
- /// Connection state. Always "connected" for PaperVenue.
+ /// Connection state.
enum class ConnectionState { Disconnected, Connecting, Connected, Degraded };
virtual ConnectionState connection_state() const = 0;
@@ -111,7 +106,7 @@ class IExchangeVenue {
/// Install/replace event sinks. Sinks are called on the venue's thread;
/// implementations are responsible for marshalling into the callee's
- /// thread (see PaperVenue::install_marshalled).
+ /// thread.
virtual void on_fill(std::function<void(FillEvent)> cb) = 0;
virtual void on_funding(std::function<void(FundingEvent)> cb) = 0;
virtual void on_liquidation(std::function<void(LiquidationEvent)> cb) = 0;
diff --git a/fincept-qt/src/services/alpha_arena/Indicators.cpp b/fincept-qt/src/services/alpha_arena/Indicators.cpp
deleted file mode 100644
index 2f4a6d74a..000000000
--- a/fincept-qt/src/services/alpha_arena/Indicators.cpp
+++ /dev/null
@@ -1,142 +0,0 @@
-#include "services/alpha_arena/Indicators.h"
-
-#include <cmath>
-#include <limits>
-
-namespace fincept::services::alpha_arena {
-
-namespace {
-constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
-} // namespace
-
-QVector<double> ema(const QVector<double>& values, int period) {
- const int n = values.size();
- QVector<double> out(n, kNaN);
- if (period <= 0 || n < period) return out;
-
- // Seed with SMA of the first `period` values, exactly as pandas-ta does.
- double sum = 0.0;
- for (int i = 0; i < period; ++i) sum += values[i];
- out[period - 1] = sum / period;
-
- const double alpha = 2.0 / (period + 1);
- for (int i = period; i < n; ++i) {
- out[i] = alpha * values[i] + (1.0 - alpha) * out[i - 1];
- }
- return out;
-}
-
-QVector<double> rsi_wilder(const QVector<double>& closes, int period) {
- const int n = closes.size();
- QVector<double> out(n, kNaN);
- if (period <= 0 || n <= period) return out;
-
- // Seed average gain/loss from the first `period` deltas.
- double gain_sum = 0.0;
- double loss_sum = 0.0;
- for (int i = 1; i <= period; ++i) {
- const double d = closes[i] - closes[i - 1];
- if (d > 0) gain_sum += d;
- else if (d < 0) loss_sum -= d;
- }
- double avg_gain = gain_sum / period;
- double avg_loss = loss_sum / period;
-
- auto rsi_from = [](double g, double l) {
- if (l == 0.0) return 100.0;
- const double rs = g / l;
- return 100.0 - 100.0 / (1.0 + rs);
- };
-
- out[period] = rsi_from(avg_gain, avg_loss);
-
- // Wilder smoothing for the rest.
- const double inv = 1.0 / period;
- for (int i = period + 1; i < n; ++i) {
- const double d = closes[i] - closes[i - 1];
- const double up = (d > 0) ? d : 0.0;
- const double dn = (d < 0) ? -d : 0.0;
- avg_gain = (avg_gain * (period - 1) + up) * inv;
- avg_loss = (avg_loss * (period - 1) + dn) * inv;
- out[i] = rsi_from(avg_gain, avg_loss);
- }
- return out;
-}
-
-MacdSeries macd(const QVector<double>& closes,
- int fast_period,
- int slow_period,
- int signal_period) {
- const int n = closes.size();
- MacdSeries s;
- s.macd.resize(n);
- s.signal.resize(n);
- s.hist.resize(n);
- s.macd.fill(kNaN);
- s.signal.fill(kNaN);
- s.hist.fill(kNaN);
- if (fast_period <= 0 || slow_period <= 0 || signal_period <= 0) return s;
- if (n < slow_period) return s;
-
- const auto fast = ema(closes, fast_period);
- const auto slow = ema(closes, slow_period);
- for (int i = 0; i < n; ++i) {
- if (std::isnan(fast[i]) || std::isnan(slow[i])) continue;
- s.macd[i] = fast[i] - slow[i];
- }
-
- // Signal is EMA of MACD, but only over the defined region. We seed at the
- // first index where macd is defined and we have `signal_period` macd
- // points; that matches pandas-ta's behaviour.
- int first_macd = -1;
- for (int i = 0; i < n; ++i) {
- if (!std::isnan(s.macd[i])) { first_macd = i; break; }
- }
- if (first_macd < 0 || first_macd + signal_period > n) return s;
-
- double sum = 0.0;
- for (int i = first_macd; i < first_macd + signal_period; ++i) sum += s.macd[i];
- const int seed = first_macd + signal_period - 1;
- s.signal[seed] = sum / signal_period;
- s.hist[seed] = s.macd[seed] - s.signal[seed];
-
- const double alpha = 2.0 / (signal_period + 1);
- for (int i = seed + 1; i < n; ++i) {
- s.signal[i] = alpha * s.macd[i] + (1.0 - alpha) * s.signal[i - 1];
- s.hist[i] = s.macd[i] - s.signal[i];
- }
- return s;
-}
-
-QVector<double> atr_wilder(const QVector<double>& highs,
- const QVector<double>& lows,
- const QVector<double>& closes,
- int period) {
- const int n = closes.size();
- QVector<double> out(n, kNaN);
- if (period <= 0 || n <= period) return out;
- if (highs.size() != n || lows.size() != n) return out;
-
- // True range series.
- QVector<double> tr(n, 0.0);
- tr[0] = highs[0] - lows[0];
- for (int i = 1; i < n; ++i) {
- const double a = highs[i] - lows[i];
- const double b = std::fabs(highs[i] - closes[i - 1]);
- const double c = std::fabs(lows[i] - closes[i - 1]);
- tr[i] = std::max(a, std::max(b, c));
- }
-
- // Seed with simple average of first `period` TRs.
- double seed_sum = 0.0;
- for (int i = 0; i < period; ++i) seed_sum += tr[i];
- out[period - 1] = seed_sum / period;
-
- // Wilder smoothing.
- for (int i = period; i < n; ++i) {
- out[i] = (out[i - 1] * (period - 1) + tr[i]) / period;
- }
- return out;
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/Indicators.h b/fincept-qt/src/services/alpha_arena/Indicators.h
deleted file mode 100644
index 6b746e470..000000000
--- a/fincept-qt/src/services/alpha_arena/Indicators.h
+++ /dev/null
@@ -1,44 +0,0 @@
-#pragma once
-// Indicators — minimal, allocation-light technical indicator helpers.
-//
-// These are the only indicators the Alpha Arena prompt exposes (per Nof1
-// Season 1): EMA, MACD, RSI (Wilder), ATR. Implementations are validated
-// against pandas-ta within 1e-6 in the test suite (Phase 3 exit criterion).
-//
-// All functions return a vector of doubles aligned with the input. Positions
-// where the indicator is undefined (warmup) are filled with quiet NaN —
-// callers should `std::isnan()`-check before formatting into prompts.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §4.4 (Indicators).
-
-#include <QVector>
-
-namespace fincept::services::alpha_arena {
-
-/// Exponential moving average. period must be ≥ 1.
-/// Output[i] is NaN for i < period - 1; output[period - 1] = SMA(values[0..period-1]).
-QVector<double> ema(const QVector<double>& values, int period);
-
-/// Wilder's RSI. period must be ≥ 1. Returns NaN until period bars are seen.
-QVector<double> rsi_wilder(const QVector<double>& closes, int period);
-
-/// Result of macd(): three series of equal length to `closes`.
-struct MacdSeries {
- QVector<double> macd;
- QVector<double> signal;
- QVector<double> hist;
-};
-
-/// MACD with EMA-based signal line. Defaults match TradingView/pandas-ta.
-MacdSeries macd(const QVector<double>& closes,
- int fast_period = 12,
- int slow_period = 26,
- int signal_period = 9);
-
-/// Wilder ATR. highs/lows/closes must have equal length. period must be ≥ 1.
-QVector<double> atr_wilder(const QVector<double>& highs,
- const QVector<double>& lows,
- const QVector<double>& closes,
- int period);
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/ModelDispatcher.cpp b/fincept-qt/src/services/alpha_arena/ModelDispatcher.cpp
deleted file mode 100644
index 76d259597..000000000
--- a/fincept-qt/src/services/alpha_arena/ModelDispatcher.cpp
+++ /dev/null
@@ -1,302 +0,0 @@
-#include "services/alpha_arena/ModelDispatcher.h"
-
-#include "core/logging/Logger.h"
-#include "python/PythonRunner.h"
-#include "services/alpha_arena/AlphaArenaJson.h"
-#include "services/alpha_arena/ContextBuilder.h"
-
-#include <QCryptographicHash>
-#include <QDir>
-#include <QFile>
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QMetaObject>
-#include <QPointer>
-#include <QStandardPaths>
-#include <QUuid>
-
-namespace fincept::services::alpha_arena {
-
-namespace {
-
-QString sha256_hex(const QString& s) {
- return QString::fromLatin1(
- QCryptographicHash::hash(s.toUtf8(), QCryptographicHash::Sha256).toHex());
-}
-
-/// Where to write the per-tick request files. Subprocess deletes after read.
-QString tmp_request_dir() {
- QString dir = QStandardPaths::writableLocation(QStandardPaths::TempLocation) +
- QStringLiteral("/fincept-aa");
- QDir().mkpath(dir);
- return dir;
-}
-
-/// Build a name unique-per-run-but-Qt-LocalServer-safe.
-QString new_pipe_name(const QString& comp_id, int seq) {
- return QStringLiteral("fincept-aa-%1-%2-%3")
- .arg(comp_id.left(8))
- .arg(seq)
- .arg(QUuid::createUuid().toString(QUuid::WithoutBraces).left(8));
-}
-
-QJsonArray actions_to_json_array(const QVector<ProposedAction>& actions) {
- QJsonArray arr;
- for (const auto& a : actions) arr.append(action_to_json(a));
- return arr;
-}
-
-QString market_snapshot_json(const QVector<MarketSnapshot>& markets) {
- QJsonArray arr;
- for (const auto& m : markets) {
- QJsonObject o;
- o["coin"] = m.coin;
- o["mid"] = m.mid;
- o["bid"] = m.bid;
- o["ask"] = m.ask;
- o["funding_rate"] = m.funding_rate;
- // Bars omitted from this snapshot — they live in the prompt rows
- // via the prompt sha256. Keep the snapshot light for the audit log.
- arr.append(o);
- }
- return QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact));
-}
-
-} // namespace
-
-ModelDispatcher::ModelDispatcher(QObject* parent)
- : QObject(parent), secrets_(new SecretRedemptionServer(this)) {}
-
-void ModelDispatcher::configure(const QString& competition_id,
- CompetitionMode mode,
- const QVector<DispatchAgent>& agents) {
- competition_id_ = competition_id;
- mode_ = mode;
- agents_ = agents;
- LOG_INFO("AlphaArena.Dispatch",
- QString("configured comp=%1 mode=%2 agents=%3")
- .arg(competition_id, mode_to_wire(mode))
- .arg(agents.size()));
-}
-
-void ModelDispatcher::set_stub_response_provider(StubResponseProvider p) {
- stub_provider_ = std::move(p);
-}
-
-void ModelDispatcher::dispatch_tick(Tick t,
- TickContext ctx,
- QHash<QString, AgentAccountState> per_agent_state,
- std::optional<SituationalContext> situational) {
- if (competition_id_.isEmpty() || agents_.isEmpty()) {
- LOG_WARN("AlphaArena.Dispatch", "tick fired with no configured competition");
- emit tick_dispatch_complete(t.seq);
- return;
- }
-
- // 1. Build & persist the system prompt (idempotent — prompt content-addressed).
- const QString system_prompt = build_system_prompt(mode_);
- const QString sys_sha = sha256_hex(system_prompt);
- AlphaArenaRepo::instance().upsert_prompt(sys_sha, system_prompt);
-
- // 2. Persist the tick row.
- const auto tick_r = AlphaArenaRepo::instance().insert_tick(
- competition_id_, t.seq, t.utc_ms, sys_sha, market_snapshot_json(ctx.markets));
- if (tick_r.is_err()) {
- LOG_ERROR("AlphaArena.Dispatch",
- QString("insert_tick failed: %1").arg(QString::fromStdString(tick_r.error())));
- emit tick_dispatch_complete(t.seq);
- return;
- }
- const QString tick_id = tick_r.value();
- tick_ids_.insert(t.seq, tick_id);
-
- // 3. Open a per-tick SecretRedemptionServer.
- const QString pipe_name = new_pipe_name(competition_id_, t.seq);
- if (!secrets_->start(pipe_name)) {
- LOG_ERROR("AlphaArena.Dispatch", "failed to start secret IPC server — aborting tick");
- AlphaArenaRepo::instance().mark_tick_skipped(tick_id);
- emit tick_dispatch_complete(t.seq);
- return;
- }
-
- // 4. Per-agent: build user prompt, write request file, spawn subprocess.
- outstanding_.insert(t.seq, agents_.size());
-
- for (const auto& agent : agents_) {
- // Per-agent state — fall back to a zero-equity stub if the engine
- // hasn't supplied one (e.g. seed cycle).
- AgentAccountState state;
- if (auto it = per_agent_state.constFind(agent.agent_id); it != per_agent_state.constEnd()) {
- state = it.value();
- }
-
- const QString user_prompt = build_user_prompt(ctx, state, mode_, situational);
- const QString user_sha = sha256_hex(user_prompt);
- AlphaArenaRepo::instance().upsert_prompt(user_sha, user_prompt);
-
- // Test-only short-circuit: if a stub provider is installed, build the
- // decision directly off its return value and emit synchronously.
- // Skips the request-file + subprocess path entirely.
- if (stub_provider_) {
- const QString raw = stub_provider_(agent.agent_id, system_prompt, user_prompt);
- AlphaArenaRepo::DecisionInsert d;
- d.tick_id = tick_id;
- d.agent_id = agent.agent_id;
- d.user_prompt_sha256 = user_sha;
- d.raw_response = raw;
- d.risk_verdict_json = QStringLiteral("[]");
- ModelResponse parsed = parse_model_response(raw);
- if (parsed.parse_error.has_value()) d.parse_error = *parsed.parse_error;
- d.parsed_actions_json = QString::fromUtf8(
- QJsonDocument(actions_to_json_array(parsed.actions))
- .toJson(QJsonDocument::Compact));
- const auto dr = AlphaArenaRepo::instance().insert_decision(d);
- const QString dec_id = dr.is_ok() ? dr.value() : QString();
- QJsonObject p;
- p[QStringLiteral("decision_id")] = dec_id;
- p[QStringLiteral("latency_ms")] = 0;
- p[QStringLiteral("parse_error")] = d.parse_error;
- AlphaArenaRepo::instance().append_event(competition_id_, agent.agent_id,
- QStringLiteral("decision"), p);
- emit decision_received(dec_id, agent.agent_id, parsed.actions, d.parse_error);
- outstanding_[t.seq]--;
- if (outstanding_[t.seq] == 0) {
- close_secret_server_when_done();
- AlphaArenaRepo::instance().close_tick(tick_id);
- outstanding_.remove(t.seq);
- tick_ids_.remove(t.seq);
- emit tick_dispatch_complete(t.seq);
- }
- continue;
- }
-
- // Write request file. Notice: API key is NOT in this file. Only the
- // secret_handle (SecureStorage key) is — and the subprocess fetches
- // the plaintext via the IPC server.
- QJsonObject model_obj;
- model_obj["provider"] = agent.provider;
- model_obj["id"] = agent.model_id;
- if (!agent.base_url.isEmpty()) model_obj["base_url"] = agent.base_url;
-
- QJsonObject req;
- req["system_prompt"] = system_prompt;
- req["user_prompt"] = user_prompt;
- req["model"] = model_obj;
- req["temperature"] = 0.1;
- req["max_output_tokens"] = 4096;
- req["secret_handle"] = agent.api_secret_handle;
- req["secret_pipe"] = pipe_name;
-
- const QString req_path = tmp_request_dir() +
- QStringLiteral("/req-%1-%2.json")
- .arg(t.seq)
- .arg(QUuid::createUuid().toString(QUuid::WithoutBraces).left(8));
- QFile f(req_path);
- if (!f.open(QIODevice::WriteOnly)) {
- LOG_ERROR("AlphaArena.Dispatch",
- QString("could not write request file %1").arg(req_path));
- // Persist a parse-error decision so the audit row exists.
- AlphaArenaRepo::DecisionInsert d;
- d.tick_id = tick_id;
- d.agent_id = agent.agent_id;
- d.user_prompt_sha256 = user_sha;
- d.parse_error = QStringLiteral("could not write request file");
- const auto dr = AlphaArenaRepo::instance().insert_decision(d);
- const QString dec_id = dr.is_ok() ? dr.value() : QString();
- emit decision_received(dec_id, agent.agent_id, {}, d.parse_error);
- outstanding_[t.seq]--;
- if (outstanding_[t.seq] == 0) close_secret_server_when_done();
- continue;
- }
- f.write(QJsonDocument(req).toJson(QJsonDocument::Compact));
- f.close();
-
- // Subprocess. We capture *only* the data we need — no `this` raw —
- // and the engine guarantees ModelDispatcher outlives any tick.
- QPointer<ModelDispatcher> self = this;
- const QString agent_id = agent.agent_id;
- const QString display_name = agent.display_name;
- const int seq = t.seq;
- const QString user_sha_capture = user_sha;
- const QString comp_id = competition_id_;
-
- fincept::python::PythonRunner::instance().run(
- QStringLiteral("alpha_arena/llm_call.py"),
- {req_path},
- [self, tick_id, agent_id, display_name, seq, user_sha_capture, comp_id]
- (const fincept::python::PythonResult& result) {
- if (!self) return;
-
- AlphaArenaRepo::DecisionInsert d;
- d.tick_id = tick_id;
- d.agent_id = agent_id;
- d.user_prompt_sha256 = user_sha_capture;
-
- ModelResponse parsed;
- if (!result.success) {
- d.parse_error = result.error.isEmpty()
- ? QStringLiteral("subprocess failed")
- : result.error;
- } else {
- const QString out_json = fincept::python::extract_json(result.output);
- auto doc = QJsonDocument::fromJson(out_json.toUtf8());
- if (!doc.isObject()) {
- d.parse_error = QStringLiteral("subprocess returned non-JSON");
- } else {
- const auto obj = doc.object();
- if (obj.contains("error")) {
- d.parse_error =
- QStringLiteral("subprocess: ") + obj.value("error").toString();
- } else {
- d.raw_response = obj.value("response_text").toString();
- d.latency_ms = obj.value("latency_ms").toInt();
- d.tokens_in = obj.value("tokens_in").toInt();
- d.tokens_out = obj.value("tokens_out").toInt();
- d.cost_usd = obj.value("cost_usd").toDouble();
- parsed = parse_model_response(d.raw_response);
- if (parsed.parse_error.has_value()) {
- d.parse_error = *parsed.parse_error;
- }
- d.parsed_actions_json = QString::fromUtf8(
- QJsonDocument(actions_to_json_array(parsed.actions))
- .toJson(QJsonDocument::Compact));
- }
- }
- }
-
- const auto dr = AlphaArenaRepo::instance().insert_decision(d);
- const QString dec_id = dr.is_ok() ? dr.value() : QString();
-
- // Telemetry event for RiskPanel — captures latency, parse status,
- // token usage. Always written, regardless of parse success.
- {
- QJsonObject p;
- p[QStringLiteral("decision_id")] = dec_id;
- p[QStringLiteral("latency_ms")] = d.latency_ms;
- p[QStringLiteral("tokens_in")] = d.tokens_in;
- p[QStringLiteral("tokens_out")] = d.tokens_out;
- p[QStringLiteral("parse_error")] = d.parse_error;
- AlphaArenaRepo::instance().append_event(comp_id, agent_id,
- QStringLiteral("decision"), p);
- }
-
- emit self->decision_received(dec_id, agent_id, parsed.actions, d.parse_error);
-
- self->outstanding_[seq]--;
- if (self->outstanding_[seq] == 0) {
- self->close_secret_server_when_done();
- AlphaArenaRepo::instance().close_tick(tick_id);
- self->outstanding_.remove(seq);
- self->tick_ids_.remove(seq);
- emit self->tick_dispatch_complete(seq);
- }
- });
- }
-}
-
-void ModelDispatcher::close_secret_server_when_done() {
- secrets_->stop();
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/ModelDispatcher.h b/fincept-qt/src/services/alpha_arena/ModelDispatcher.h
deleted file mode 100644
index 9eff52c16..000000000
--- a/fincept-qt/src/services/alpha_arena/ModelDispatcher.h
+++ /dev/null
@@ -1,105 +0,0 @@
-#pragma once
-// ModelDispatcher — turns a Tick into per-agent decisions.
-//
-// On every tick:
-// 1. Build the system prompt (cached, mode-dependent only) and per-agent
-// user prompts (canonical, byte-equal across agents in non-situational
-// mode).
-// 2. Persist tick metadata + content-addressed prompt rows.
-// 3. For each agent, write a request file (path-only argv; no secret) and
-// spawn `scripts/alpha_arena/llm_call.py` via PythonRunner. The
-// subprocess redeems the API key from the SecretRedemptionServer.
-// 4. Parse the response into ProposedActions, persist the decision row,
-// and emit `decision_received(decision_id, agent_id, actions)` for the
-// OrderRouter to consume. Parse failures land as a no-op decision row
-// with parse_error set (per Nof1 spec — no retry).
-//
-// The dispatcher does NOT call the venue. It is a pure prompt-and-parse
-// stage. OrderRouter is downstream.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §4 (Context builder)
-// and §12 (Backend topology).
-
-#include "services/alpha_arena/AlphaArenaRepo.h"
-#include "services/alpha_arena/AlphaArenaSchema.h"
-#include "services/alpha_arena/AlphaArenaTypes.h"
-#include "services/alpha_arena/SecretRedemptionServer.h"
-
-#include <QHash>
-#include <QObject>
-#include <QString>
-
-#include <functional>
-#include <optional>
-
-namespace fincept::services::alpha_arena {
-
-struct DispatchAgent {
- QString agent_id;
- QString provider; // openai|anthropic|google|deepseek|xai|qwen
- QString model_id;
- QString base_url; // optional override
- QString api_secret_handle; // SecureStorage key
- QString display_name;
-};
-
-class ModelDispatcher : public QObject {
- Q_OBJECT
- public:
- explicit ModelDispatcher(QObject* parent = nullptr);
-
- /// Configure dispatch for the active competition. Replaces any prior
- /// state. Pass an empty list to halt dispatch.
- void configure(const QString& competition_id,
- CompetitionMode mode,
- const QVector<DispatchAgent>& agents);
-
- /// Test-only hook: when set, ModelDispatcher routes prompts through this
- /// callback instead of spawning the Python subprocess. The callback gets
- /// the agent_id + system prompt + user prompt, returns the canned raw
- /// response text. Tests use this to drive the engine deterministically.
- using StubResponseProvider = std::function<QString(QString agent_id,
- QString system_prompt,
- QString user_prompt)>;
- void set_stub_response_provider(StubResponseProvider p);
-
- public slots:
- /// Triggered by AlphaArenaEngine on TickClock::tick. Per-agent state
- /// (positions, equity, etc.) and the market snapshot are supplied by
- /// the engine, which has read them from the repo / venue immediately
- /// before this call.
- void dispatch_tick(fincept::services::alpha_arena::Tick t,
- fincept::services::alpha_arena::TickContext ctx,
- QHash<QString, fincept::services::alpha_arena::AgentAccountState> per_agent_state,
- std::optional<fincept::services::alpha_arena::SituationalContext> situational);
-
- signals:
- /// Emitted once per agent per tick after the response (or timeout/parse
- /// error) is persisted. `decision_id` is the aa_decisions row id; the
- /// row carries parsed_actions_json and parse_error.
- void decision_received(QString decision_id, QString agent_id,
- QVector<fincept::services::alpha_arena::ProposedAction> actions,
- QString parse_error);
-
- /// All agents have responded (or timed out) for this tick. The engine
- /// listens for this to call TickClock::tick_complete().
- void tick_dispatch_complete(int seq);
-
- private:
- void start_secret_server_for_tick(int seq);
- void close_secret_server_when_done();
-
- QString competition_id_;
- CompetitionMode mode_ = CompetitionMode::Baseline;
- QVector<DispatchAgent> agents_;
-
- SecretRedemptionServer* secrets_ = nullptr;
- StubResponseProvider stub_provider_;
-
- /// Per-tick state — number of outstanding agent calls. When it hits 0,
- /// we close the SecretRedemptionServer and emit tick_dispatch_complete.
- QHash<int /*seq*/, int> outstanding_;
- QHash<int /*seq*/, QString /*tick_id*/> tick_ids_;
-};
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/OrderRouter.cpp b/fincept-qt/src/services/alpha_arena/OrderRouter.cpp
deleted file mode 100644
index 4c65bc496..000000000
--- a/fincept-qt/src/services/alpha_arena/OrderRouter.cpp
+++ /dev/null
@@ -1,324 +0,0 @@
-#include "services/alpha_arena/OrderRouter.h"
-
-#include "core/logging/Logger.h"
-#include "services/alpha_arena/AlphaArenaJson.h"
-#include "storage/repositories/SettingsRepository.h"
-
-#include <QDateTime>
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QPointer>
-
-namespace fincept::services::alpha_arena {
-
-namespace {
-
-// HITL trip points — an autonomous trade at/above either threshold requires
-// human confirmation. User-tunable via SettingsRepository (keys below); the
-// literals are the safe defaults applied when unset.
-constexpr double kDefaultHitlNotionalUsd = 1000.0;
-constexpr int kDefaultHitlMaxLeverage = 10;
-
-double hitl_notional_threshold() {
- auto r = fincept::SettingsRepository::instance().get(QStringLiteral("alpha_arena.hitl.notional_usd"));
- bool ok = false;
- if (r.is_ok()) {
- const double d = r.value().toDouble(&ok);
- if (ok)
- return d;
- }
- return kDefaultHitlNotionalUsd;
-}
-
-int hitl_leverage_threshold() {
- auto r = fincept::SettingsRepository::instance().get(QStringLiteral("alpha_arena.hitl.max_leverage"));
- bool ok = false;
- if (r.is_ok()) {
- const int v = r.value().toInt(&ok);
- if (ok)
- return v;
- }
- return kDefaultHitlMaxLeverage;
-}
-
-QString verdict_reason_json(const QVector<RiskVerdict>& verdicts) {
- QJsonArray arr;
- for (const auto& v : verdicts) {
- QJsonObject o;
- o["outcome"] = static_cast<int>(v.outcome);
- o["reason"] = v.reason;
- if (v.amended.has_value()) o["amended"] = action_to_json(*v.amended);
- arr.append(o);
- }
- return QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact));
-}
-
-QString hitl_summary(const ProposedAction& a) {
- return QStringLiteral("%1 %2 %3 @ %4× — risk_usd %5")
- .arg(signal_to_wire(a.signal), a.coin)
- .arg(a.quantity, 0, 'f', 4)
- .arg(a.leverage)
- .arg(a.risk_usd, 0, 'f', 2);
-}
-
-} // namespace
-
-OrderRouter::OrderRouter(QObject* parent) : QObject(parent) {}
-
-void OrderRouter::configure(const QString& competition_id,
- CompetitionMode mode,
- IExchangeVenue* venue) {
- competition_id_ = competition_id;
- mode_ = mode;
- venue_ = venue;
-
- // Hook the venue's fill stream so we can persist fills + update positions.
- if (venue_) {
- QPointer<OrderRouter> self = this;
- venue_->on_fill([self](FillEvent f) {
- if (!self) return;
- const auto fr = AlphaArenaRepo::instance().insert_fill(
- f.venue_order_id, f.qty, f.price, f.fee);
- if (fr.is_err()) {
- LOG_ERROR("AlphaArena.OrderRouter",
- QString("insert_fill failed: %1")
- .arg(QString::fromStdString(fr.error())));
- }
- // Mark the order as filled; venue_order_id is the FK we have here,
- // not the aa_orders.id, so we update by venue_order_id.
- // (Simpler than carrying an order_id round-trip across processes.)
- // NOTE: aa_orders.venue_order_id is set at place_order time so a
- // SET ... WHERE venue_order_id=? is unambiguous.
- // We don't have a repo helper for that yet — append an event so
- // the audit log captures the fill, and the UI can derive state.
- QJsonObject p;
- p["coin"] = f.coin;
- p["side"] = f.side;
- p["qty"] = f.qty;
- p["price"] = f.price;
- p["fee"] = f.fee;
- p["venue_order_id"] = f.venue_order_id;
- AlphaArenaRepo::instance().append_event(self->competition_id_, f.agent_id,
- QStringLiteral("fill"), p);
- });
- venue_->on_liquidation([self](LiquidationEvent e) {
- if (!self) return;
- QJsonObject p;
- p["coin"] = e.coin;
- p["exit_price"] = e.exit_price;
- p["realized_pnl_usd"] = e.realized_pnl_usd;
- AlphaArenaRepo::instance().append_event(self->competition_id_, e.agent_id,
- QStringLiteral("liquidation"), p);
- });
- venue_->on_funding([self](FundingEvent f) {
- if (!self) return;
- QJsonObject p;
- p["coin"] = f.coin;
- p["amount_usd"] = f.amount_usd;
- AlphaArenaRepo::instance().append_event(self->competition_id_, f.agent_id,
- QStringLiteral("funding"), p);
- });
- }
-}
-
-void OrderRouter::update_agent_state(const QString& agent_id, const AgentRuntimeState& state) {
- agents_.insert(agent_id, state);
-}
-
-bool OrderRouter::needs_hitl(const ProposedAction& a, const AgentRuntimeState& agent) const {
- if (!agent.live_mode) return false;
- if (a.signal != Signal::BuyToEnter && a.signal != Signal::SellToEnter) return false;
- const double notional = a.quantity * (venue_ ? venue_->last_mark(a.coin) : 0.0);
- return notional >= hitl_notional_threshold() || a.leverage >= hitl_leverage_threshold();
-}
-
-void OrderRouter::on_decision(QString decision_id, QString agent_id,
- QVector<ProposedAction> actions,
- QString parse_error) {
- // Pull (or default-init) the agent's state.
- auto it = agents_.find(agent_id);
- if (it == agents_.end()) {
- LOG_WARN("AlphaArena.OrderRouter",
- QString("decision for unconfigured agent %1 — ignoring").arg(agent_id));
- return;
- }
- AgentRuntimeState& agent = it.value();
-
- // Update circuit on parse failure (no actions at all).
- const bool tick_parse_failure = !parse_error.isEmpty() && actions.isEmpty();
- if (tick_parse_failure) {
- QJsonObject p;
- p[QStringLiteral("decision_id")] = decision_id;
- p[QStringLiteral("error")] = parse_error;
- AlphaArenaRepo::instance().append_event(competition_id_, agent_id,
- QStringLiteral("parse_error"), p);
- }
-
- // Run RiskEngine on every action.
- QVector<RiskVerdict> verdicts;
- verdicts.reserve(actions.size());
- bool any_rejected = false;
-
- for (const auto& a : actions) {
- AgentRiskState rs;
- rs.equity = agent.equity;
- rs.existing_qty_in_coin = agent.open_positions.value(a.coin, 0.0);
- rs.last_entry_utc_ms_on_coin = agent.last_entry_per_coin.value(a.coin, 0);
- rs.now_utc_ms = QDateTime::currentMSecsSinceEpoch();
- rs.mark_price = venue_ ? venue_->last_mark(a.coin) : 0.0;
- const auto v = evaluate_action(a, rs, mode_);
- verdicts.append(v);
- if (v.outcome == RiskVerdict::Outcome::Reject) {
- QJsonObject p;
- p[QStringLiteral("decision_id")] = decision_id;
- p[QStringLiteral("coin")] = a.coin;
- p[QStringLiteral("signal")] = signal_to_wire(a.signal);
- p[QStringLiteral("reason")] = v.reason;
- AlphaArenaRepo::instance().append_event(competition_id_, agent_id,
- QStringLiteral("risk_reject"), p);
- }
- emit action_evaluated(agent_id, a.coin, a.signal,
- static_cast<int>(v.outcome), v.reason);
- if (v.outcome == RiskVerdict::Outcome::Reject) any_rejected = true;
- }
-
- // Persist verdicts onto the decision row (best-effort — failure is logged
- // but doesn't block routing).
- {
- // Use a direct UPDATE since insert_decision was called earlier.
- // We don't have a repo helper specifically for the verdict update, so
- // write through Database directly. Not great, but localised.
- QJsonArray arr;
- for (const auto& v : verdicts) {
- QJsonObject o;
- o["outcome"] = static_cast<int>(v.outcome);
- o["reason"] = v.reason;
- arr.append(o);
- }
- // verdict_reason_json() is an alternate compact form, retained as a
- // helper for future logging tooling — silence "unused" with a cast.
- (void)&verdict_reason_json;
- }
-
- // Advance the agent's circuit. Caller already set max_drawdown via state.
- const auto new_circuit = advance_circuit(agent.circuit, tick_parse_failure,
- any_rejected, agent.circuit.max_drawdown_frac);
- if (!agent.circuit.open && new_circuit.open) {
- emit agent_circuit_open(agent_id,
- QStringLiteral("parse_fails=%1, risk_rejects=%2, drawdown=%3")
- .arg(new_circuit.consecutive_parse_failures)
- .arg(new_circuit.consecutive_risk_rejects)
- .arg(new_circuit.max_drawdown_frac, 0, 'f', 4));
- }
- agent.circuit = new_circuit;
- if (new_circuit.open) return; // halted — drop the actions
-
- // Route accepted/amended actions.
- for (int i = 0; i < actions.size(); ++i) {
- const auto& v = verdicts[i];
- if (v.outcome == RiskVerdict::Outcome::Reject) continue;
- const ProposedAction routed = (v.outcome == RiskVerdict::Outcome::Amend && v.amended)
- ? *v.amended
- : actions[i];
-
- if (needs_hitl(routed, agent)) {
- // Persist the request, surface to UI, wait for resolve_hitl().
- QJsonObject action_json = action_to_json(routed);
- const auto rr = AlphaArenaRepo::instance().request_hitl(
- decision_id, agent_id, action_json,
- QStringLiteral("Live trade requires approval: ") + hitl_summary(routed));
- if (rr.is_err()) {
- LOG_ERROR("AlphaArena.OrderRouter",
- QString("request_hitl failed: %1")
- .arg(QString::fromStdString(rr.error())));
- continue;
- }
- const QString approval_id = rr.value();
- pending_hitl_.insert(approval_id, {decision_id, routed, agent_id});
- emit hitl_requested(approval_id, agent_id, hitl_summary(routed));
- continue;
- }
-
- route_to_venue(decision_id, routed, agent);
- }
-}
-
-void OrderRouter::resolve_hitl(QString approval_id, bool approved) {
- auto it = pending_hitl_.find(approval_id);
- if (it == pending_hitl_.end()) {
- LOG_WARN("AlphaArena.OrderRouter",
- QString("resolve_hitl on unknown id %1").arg(approval_id));
- return;
- }
- const PendingHitl pending = it.value();
- pending_hitl_.erase(it);
-
- AlphaArenaRepo::instance().resolve_hitl(approval_id,
- approved ? QStringLiteral("approved") : QStringLiteral("rejected"),
- QStringLiteral("user"));
-
- if (!approved) return;
-
- auto agent_it = agents_.find(pending.agent_id);
- if (agent_it == agents_.end()) return;
- route_to_venue(pending.decision_id, pending.action, agent_it.value());
-}
-
-void OrderRouter::route_to_venue(const QString& decision_id,
- const ProposedAction& a,
- const AgentRuntimeState& agent) {
- if (!venue_) return;
-
- const bool is_buy = (a.signal == Signal::BuyToEnter)
- || (a.signal == Signal::Close && agent.open_positions.value(a.coin, 0.0) < 0.0);
- OrderRequest req;
- req.agent_id = agent.agent_id;
- req.coin = a.coin;
- req.side = is_buy ? QStringLiteral("buy") : QStringLiteral("sell");
- // Close uses |existing_qty|; entries use the model's stated qty.
- if (a.signal == Signal::Close) {
- req.qty = std::fabs(agent.open_positions.value(a.coin, 0.0));
- req.reduce_only = true;
- } else {
- req.qty = a.quantity;
- req.profit_target = a.profit_target;
- req.stop_loss = a.stop_loss;
- }
- req.leverage = a.leverage;
-
- AlphaArenaRepo::OrderInsert oi;
- oi.decision_id = decision_id;
- oi.agent_id = agent.agent_id;
- oi.competition_id = competition_id_;
- oi.coin = a.coin;
- oi.side = req.side;
- oi.qty = req.qty;
- oi.leverage = req.leverage;
- const auto orow = AlphaArenaRepo::instance().insert_order(oi);
- if (orow.is_err()) {
- LOG_ERROR("AlphaArena.OrderRouter",
- QString("insert_order failed: %1").arg(QString::fromStdString(orow.error())));
- return;
- }
- const QString order_id = orow.value();
- emit order_placed(agent.agent_id, order_id);
-
- QPointer<OrderRouter> self = this;
- const QString agent_id = agent.agent_id;
- const QString comp_id = competition_id_;
- venue_->place_order(req, [self, order_id, agent_id, comp_id](OrderAck ack) {
- if (!self) return;
- AlphaArenaRepo::instance().mark_order_status(order_id, ack.status,
- ack.venue_order_id, ack.error);
- if (ack.status == QLatin1String("rejected")) {
- QJsonObject p;
- p[QStringLiteral("order_id")] = order_id;
- p[QStringLiteral("error")] = ack.error;
- AlphaArenaRepo::instance().append_event(comp_id, agent_id,
- QStringLiteral("venue_error"), p);
- }
- });
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/OrderRouter.h b/fincept-qt/src/services/alpha_arena/OrderRouter.h
deleted file mode 100644
index 053cd0aa2..000000000
--- a/fincept-qt/src/services/alpha_arena/OrderRouter.h
+++ /dev/null
@@ -1,110 +0,0 @@
-#pragma once
-// OrderRouter — runs RiskEngine on each ProposedAction and routes accepted
-// (or amended) actions to the venue. Persists every step of the journey to
-// the repo: risk verdict, order row, fill row, position row.
-//
-// HITL gate is implemented inline here (rather than its own QObject) because
-// the only state it carries is the pending-approval queue, which is also
-// persisted in `aa_hitl_approvals`. The C++-side queue is just a fast path
-// for the UI; the DB row is the source of truth.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §6 (Risk engine), §7
-// (Order router), §6.6 (HITL).
-
-#include "services/alpha_arena/AlphaArenaRepo.h"
-#include "services/alpha_arena/AlphaArenaSchema.h"
-#include "services/alpha_arena/AlphaArenaTypes.h"
-#include "services/alpha_arena/IExchangeVenue.h"
-#include "services/alpha_arena/RiskEngine.h"
-
-#include <QHash>
-#include <QObject>
-#include <QString>
-
-namespace fincept::services::alpha_arena {
-
-/// Per-agent state the router keeps in memory. Persisted derivatives are in
-/// aa_agents / aa_positions; this is the hot copy used by RiskEngine on the
-/// next decision.
-struct AgentRuntimeState {
- QString agent_id;
- QString competition_id;
- double equity = 0.0;
- QHash<QString /*coin*/, double /*signed qty*/> open_positions;
- QHash<QString /*coin*/, qint64 /*utc_ms*/> last_entry_per_coin;
- CircuitState circuit;
- bool live_mode = false;
-};
-
-class OrderRouter : public QObject {
- Q_OBJECT
- public:
- explicit OrderRouter(QObject* parent = nullptr);
-
- /// Configure the router for the active competition. Must be called
- /// before any decision_received signal can be processed.
- void configure(const QString& competition_id,
- CompetitionMode mode,
- IExchangeVenue* venue);
-
- /// Engine pushes the latest agent state on each tick (after building the
- /// account view from the venue + repo). Replaces internal state.
- void update_agent_state(const QString& agent_id, const AgentRuntimeState& state);
-
- /// HITL approvals pending in the C++ runtime. UI subscribes to this.
- int pending_hitl_count() const { return pending_hitl_.size(); }
-
- public slots:
- /// Called by ModelDispatcher when an agent's tick completes.
- /// `actions` may be empty (parse error, hold-only, etc.).
- void on_decision(QString decision_id, QString agent_id,
- QVector<fincept::services::alpha_arena::ProposedAction> actions,
- QString parse_error);
-
- /// User resolves a HITL approval from the UI.
- void resolve_hitl(QString approval_id, bool approved);
-
- signals:
- /// One verdict per action emitted; carries enough info for the UI to
- /// render the RISK and AUDIT panels live.
- void action_evaluated(QString agent_id, QString coin,
- fincept::services::alpha_arena::Signal signal,
- int risk_outcome, // RiskVerdict::Outcome cast to int
- QString reason);
-
- /// Order placed (after risk + HITL). The fill arrives via the venue.
- void order_placed(QString agent_id, QString order_id);
-
- /// Per-agent kill-switch tripped. Engine should halt the agent on receipt.
- void agent_circuit_open(QString agent_id, QString reason);
-
- /// HITL approval requested; UI surfaces a modal/tray notification.
- void hitl_requested(QString approval_id, QString agent_id, QString summary);
-
- private:
- /// Decide whether an action needs HITL approval.
- /// Rule (live mode only): notional ≥ $1000 OR leverage ≥ 10×.
- bool needs_hitl(const ProposedAction& a, const AgentRuntimeState& agent) const;
-
- /// Place an order with the venue, persist the order row, wire fill cb.
- void route_to_venue(const QString& decision_id,
- const ProposedAction& a,
- const AgentRuntimeState& agent);
-
- QString competition_id_;
- CompetitionMode mode_ = CompetitionMode::Baseline;
- IExchangeVenue* venue_ = nullptr; // not owned — Engine owns
-
- QHash<QString /*agent_id*/, AgentRuntimeState> agents_;
-
- /// Pending HITL approvals: approval_id -> (decision_id, action, agent_id).
- /// Resolved by user via resolve_hitl().
- struct PendingHitl {
- QString decision_id;
- ProposedAction action;
- QString agent_id;
- };
- QHash<QString, PendingHitl> pending_hitl_;
-};
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/PaperExchange.cpp b/fincept-qt/src/services/alpha_arena/PaperExchange.cpp
new file mode 100644
index 000000000..99c7f7b56
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/PaperExchange.cpp
@@ -0,0 +1,210 @@
+// PaperExchange — isolated-margin perp simulator per agent (see PaperExchange.h).
+#include "services/alpha_arena/PaperExchange.h"
+#include "core/logging/Logger.h"
+#include <QDateTime>
+#include <cmath>
+
+namespace fincept::arena {
+namespace {
+// I2: store writes are best-effort in the hot path, but failures must be visible.
+template <typename T>
+void log_store_err(const Result<T>& r, const char* what) {
+ if (r.is_err())
+ LOG_WARN("PaperExchange", QStringLiteral("store %1 failed: %2")
+ .arg(QString::fromUtf8(what), QString::fromStdString(r.error())));
+}
+} // namespace
+
+PaperExchange::PaperExchange(ArenaStore& store, QString competition_id)
+ : store_(store), competition_id_(std::move(competition_id)) {}
+
+void PaperExchange::load() {
+ balances_.clear(); positions_.clear();
+ auto agents = store_.agents_for(competition_id_);
+ if (agents.is_err()) return;
+ for (const auto& a : agents.value()) {
+ auto b = store_.account_balance(competition_id_, a.id);
+ balances_[a.id] = b.is_ok() ? b.value() : 0.0;
+ auto ps = store_.positions_for(competition_id_, a.id);
+ positions_[a.id] = ps.is_ok() ? ps.value() : QVector<PositionRow>{};
+ }
+}
+
+void PaperExchange::set_marks(const QHash<QString, double>& mids) { for (auto it = mids.begin(); it != mids.end(); ++it) marks_[it.key()] = it.value(); }
+void PaperExchange::set_funding(const QHash<QString, double>& rates) { funding_rates_ = rates; }
+
+double PaperExchange::position_upnl(const PositionRow& p, double mk) const {
+ const double dir = p.side == QLatin1String("long") ? 1.0 : -1.0;
+ return (mk - p.entry_price) * p.qty * dir - p.funding_accrued;
+}
+
+AccountView PaperExchange::account(const QString& agent_id) const {
+ AccountView v;
+ v.balance = balances_.value(agent_id, 0.0);
+ v.equity = v.balance;
+ v.positions = positions_.value(agent_id);
+ for (const auto& p : v.positions) {
+ const double margin = p.qty * p.entry_price / p.leverage;
+ const double up = position_upnl(p, mark(p.coin));
+ v.margin_used += margin;
+ v.upnl[p.coin] = up;
+ v.equity += margin + up;
+ }
+ return v;
+}
+
+Result<OrderRow> PaperExchange::execute(const QString& agent_id, const AgentAction& a, int round_seq) {
+ if (a.kind == ActionKind::Hold) return Result<OrderRow>::err("hold is not an order");
+ const double mk = mark(a.coin);
+ if (mk <= 0) return Result<OrderRow>::err("no mark price for " + a.coin.toStdString());
+ auto& book = positions_[agent_id];
+ int idx = -1;
+ for (int i = 0; i < book.size(); ++i) if (book[i].coin == a.coin) { idx = i; break; }
+
+ if (a.kind == ActionKind::Close) {
+ if (idx < 0) return Result<OrderRow>::err("no open position in " + a.coin.toStdString());
+ const double notional_at_mark = book[idx].qty * mk;
+ const double fraction = a.size_usd > 0 ? std::min(1.0, a.size_usd / notional_at_mark) : 1.0;
+ OrderRow o = close_position(agent_id, book[idx], fraction, round_seq, "filled", a.reason);
+ if (book[idx].qty * mk < 0.01) book.removeAt(idx); // sub-cent residual = dust
+ persist(agent_id);
+ return Result<OrderRow>::ok(o);
+ }
+
+ // Open path.
+ if (a.size_usd <= 0 || a.leverage < 1)
+ return Result<OrderRow>::err("invalid order parameters");
+
+ const double fill = mk * (a.side == QLatin1String("long") ? 1.0 + kSlippage : 1.0 - kSlippage);
+ const double qty = a.size_usd / fill;
+ const double margin = a.size_usd / a.leverage;
+ const double fee = a.size_usd * kTakerFee;
+
+ // Opposite side present → flip (full close first). C1: the flip is atomic —
+ // reject up-front if the new leg won't be affordable after the close credit,
+ // so a rejection leaves balances/positions/store completely untouched.
+ if (idx >= 0 && book[idx].side != a.side) {
+ const PositionRow& p = book[idx];
+ const double cfill = mk * (p.side == QLatin1String("long") ? 1.0 - kSlippage : 1.0 + kSlippage);
+ const double cdir = p.side == QLatin1String("long") ? 1.0 : -1.0;
+ const double crealized = (cfill - p.entry_price) * p.qty * cdir - p.funding_accrued;
+ const double cmargin_back = p.qty * p.entry_price / p.leverage;
+ const double cfee = p.qty * cfill * kTakerFee;
+ const double projected = balances_[agent_id] + (cmargin_back + crealized - cfee);
+ if (projected < margin + fee)
+ return Result<OrderRow>::err("insufficient balance for flip");
+ close_position(agent_id, book[idx], 1.0, round_seq, "filled", QStringLiteral("flip"));
+ book.removeAt(idx); idx = -1;
+ }
+ if (balances_[agent_id] < margin + fee)
+ return Result<OrderRow>::err("insufficient balance");
+ balances_[agent_id] -= margin + fee;
+
+ if (idx >= 0) { // same-side increase: weighted entry, summed margin via recomputed leverage
+ PositionRow& p = book[idx];
+ const double old_margin = p.qty * p.entry_price / p.leverage;
+ const double new_qty = p.qty + qty;
+ p.entry_price = (p.entry_price * p.qty + fill * qty) / new_qty;
+ p.qty = new_qty;
+ p.leverage = (p.qty * p.entry_price) / (old_margin + margin);
+ } else {
+ PositionRow p; p.competition_id = competition_id_; p.agent_id = agent_id;
+ p.coin = a.coin; p.side = a.side; p.qty = qty; p.entry_price = fill; p.leverage = a.leverage;
+ book.append(p);
+ }
+ persist(agent_id);
+
+ OrderRow o; o.competition_id = competition_id_; o.agent_id = agent_id; o.round_seq = round_seq;
+ o.coin = a.coin; o.side = a.side; o.action = "open"; o.qty = qty; o.price = fill;
+ o.notional_usd = a.size_usd; o.leverage = a.leverage; o.fee = fee; o.status = "filled";
+ log_store_err(store_.insert_order(o), "insert_order(open)");
+ return Result<OrderRow>::ok(o);
+}
+
+OrderRow PaperExchange::close_position(const QString& agent_id, PositionRow& p, double fraction,
+ int round_seq, const QString& status, const QString& reason) {
+ const double mk = mark(p.coin);
+ if (mk <= 0) { // defense-in-depth: never close/liquidate at a non-positive mark.
+ // Callers all guard mk<=0 already; if one slips through, reject without
+ // mutating balances/positions and without persisting anything.
+ OrderRow rej;
+ rej.competition_id = competition_id_; rej.agent_id = agent_id; rej.round_seq = round_seq;
+ rej.coin = p.coin; rej.side = p.side; rej.action = "close";
+ rej.status = "rejected_risk"; rej.reject_reason = "no mark price";
+ return rej;
+ }
+ const double fill = mk * (p.side == QLatin1String("long") ? 1.0 - kSlippage : 1.0 + kSlippage);
+ const double close_qty = p.qty * fraction;
+ const double dir = p.side == QLatin1String("long") ? 1.0 : -1.0;
+ const double realized = (fill - p.entry_price) * close_qty * dir - p.funding_accrued * fraction;
+ const double margin_back = close_qty * p.entry_price / p.leverage;
+ const double fee = close_qty * fill * kTakerFee;
+ const double credit = status == QLatin1String("liquidated")
+ ? std::max(0.0, margin_back + realized - fee)
+ : margin_back + realized - fee;
+ balances_[agent_id] += credit;
+ p.qty -= close_qty;
+ p.funding_accrued *= (1.0 - fraction);
+
+ OrderRow o; o.competition_id = competition_id_; o.agent_id = agent_id; o.round_seq = round_seq;
+ o.coin = p.coin; o.side = p.side; o.action = "close"; o.qty = close_qty; o.price = fill;
+ o.notional_usd = close_qty * fill; o.leverage = p.leverage; o.fee = fee;
+ o.realized_pnl = realized; o.status = status; o.reject_reason = reason;
+ log_store_err(store_.insert_order(o), "insert_order(close)");
+ return o;
+}
+
+QVector<OrderRow> PaperExchange::mark_all(qint64 elapsed_ms, int round_seq) {
+ QVector<OrderRow> liquidations;
+ const double window = double(elapsed_ms) / double(3600 * 1000); // funding per 1h (HL rates are hourly)
+ for (auto it = positions_.begin(); it != positions_.end(); ++it) {
+ auto& book = it.value();
+ for (qsizetype i = book.size() - 1; i >= 0; --i) {
+ PositionRow& p = book[i];
+ const double mk = mark(p.coin);
+ if (mk <= 0) continue;
+ const double dir = p.side == QLatin1String("long") ? 1.0 : -1.0;
+ p.funding_accrued += funding_rates_.value(p.coin, 0.0) * p.qty * mk * window * dir;
+ const double margin = p.qty * p.entry_price / p.leverage;
+ if (margin + position_upnl(p, mk) <= kMaintMarginRate * p.qty * mk) {
+ liquidations.append(close_position(it.key(), p, 1.0, round_seq,
+ QStringLiteral("liquidated"), QStringLiteral("maintenance margin")));
+ book.removeAt(i);
+ }
+ }
+ persist(it.key());
+ }
+ return liquidations;
+}
+
+QVector<OrderRow> PaperExchange::close_all(const QString& agent_id, int round_seq) {
+ QVector<OrderRow> out;
+ auto& book = positions_[agent_id];
+ for (qsizetype i = book.size() - 1; i >= 0; --i) {
+ if (mark(book[i].coin) <= 0) { // no mark → leave the position open, never close at 0
+ LOG_WARN("PaperExchange", QStringLiteral("close_all: no mark for %1, leaving position open")
+ .arg(book[i].coin));
+ continue;
+ }
+ out.append(close_position(agent_id, book[i], 1.0, round_seq, "filled", QStringLiteral("kill_all")));
+ book.removeAt(i);
+ }
+ persist(agent_id);
+ return out;
+}
+
+void PaperExchange::persist(const QString& agent_id) {
+ log_store_err(store_.upsert_account(competition_id_, agent_id, balances_.value(agent_id, 0.0)),
+ "upsert_account");
+ // Replace stored positions for this agent: delete-all then upsert current.
+ auto stored = store_.positions_for(competition_id_, agent_id);
+ if (stored.is_ok())
+ for (const auto& sp : stored.value()) {
+ bool still = false;
+ for (const auto& p : positions_.value(agent_id)) if (p.coin == sp.coin) { still = true; break; }
+ if (!still) log_store_err(store_.delete_position(competition_id_, agent_id, sp.coin), "delete_position");
+ }
+ for (const auto& p : positions_.value(agent_id)) log_store_err(store_.upsert_position(p), "upsert_position");
+}
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/PaperExchange.h b/fincept-qt/src/services/alpha_arena/PaperExchange.h
new file mode 100644
index 000000000..2971a3a08
--- /dev/null
+++ b/fincept-qt/src/services/alpha_arena/PaperExchange.h
@@ -0,0 +1,57 @@
+#pragma once
+// PaperExchange — isolated-margin perp simulator per agent, marked from live
+// mids, persisted via ArenaStore (crash-safe). HL-style taker fee + funding.
+// Contract: execute()/close_all() must only run after mark_all() at the current
+// round's marks — the liquidation sweep is what keeps close credits non-negative.
+#include "core/result/Result.h"
+#include "services/alpha_arena/ArenaStore.h"
+#include "services/alpha_arena/ArenaTypes.h"
+
+namespace fincept::arena {
+
+struct AccountView {
+ double balance = 0; // free collateral
+ double equity = 0; // balance + Σ(position margin + uPnL − funding)
+ double margin_used = 0;
+ QVector<PositionRow> positions;
+ QHash<QString, double> upnl; // per coin (net of funding)
+};
+
+class PaperExchange {
+ public:
+ static constexpr double kTakerFee = 0.00045; // 4.5 bps
+ static constexpr double kSlippage = 0.0002; // 2 bps
+ static constexpr double kMaintMarginRate = 0.025;
+
+ PaperExchange(ArenaStore& store, QString competition_id);
+ virtual ~PaperExchange() = default; // engine deletes HyperliquidLiveVenue through this base
+ void load(); // agents' accounts+positions from store
+ void set_marks(const QHash<QString, double>& mids);
+ /// Rates are PER-HOUR fractional (Hyperliquid convention); longs pay positive funding.
+ void set_funding(const QHash<QString, double>& rates);
+ /// Funding + liquidation sweep. Returns liquidation order rows (persisted).
+ /// elapsed_ms = ms since the PREVIOUS mark_all; funding double-accrues if misused.
+ QVector<OrderRow> mark_all(qint64 elapsed_ms, int round_seq);
+ /// Execute one parsed+risk-approved action at current mark. Persists order+position+account.
+ /// Virtual: HyperliquidLiveVenue overrides to mirror paper fills to the live venue.
+ virtual Result<OrderRow> execute(const QString& agent_id, const AgentAction& a, int round_seq);
+ QVector<OrderRow> close_all(const QString& agent_id, int round_seq);
+ AccountView account(const QString& agent_id) const;
+ QHash<QString, double> marks() const { return marks_; } // current mids (ticker/UI)
+
+ private:
+ double mark(const QString& coin) const { return marks_.value(coin, 0.0); }
+ double position_upnl(const PositionRow& p, double mk) const;
+ OrderRow close_position(const QString& agent_id, PositionRow& p, double fraction,
+ int round_seq, const QString& status, const QString& reason);
+ void persist(const QString& agent_id);
+
+ ArenaStore& store_;
+ QString competition_id_;
+ QHash<QString, double> marks_;
+ QHash<QString, double> funding_rates_;
+ QHash<QString, double> balances_; // agent_id → free balance
+ QHash<QString, QVector<PositionRow>> positions_; // agent_id → open positions
+};
+
+} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/PaperVenue.cpp b/fincept-qt/src/services/alpha_arena/PaperVenue.cpp
deleted file mode 100644
index da76c1f33..000000000
--- a/fincept-qt/src/services/alpha_arena/PaperVenue.cpp
+++ /dev/null
@@ -1,254 +0,0 @@
-#include "services/alpha_arena/PaperVenue.h"
-
-#include "core/logging/Logger.h"
-
-#include <QDateTime>
-#include <QString>
-#include <QTimer>
-
-#include <cmath>
-
-namespace fincept::services::alpha_arena {
-
-namespace {
-
-/// Hyperliquid taker fee, S1.
-constexpr double kTakerFee = 0.00045;
-/// 5bps slippage each side.
-constexpr double kSlippageBps = 0.0005;
-/// Simulated round-trip latency (ms).
-constexpr int kSimLatencyMs = 200;
-
-inline double sign(double x) { return (x > 0) - (x < 0); }
-
-QString gen_venue_order_id(quint64 seq) {
- return QStringLiteral("paper-%1").arg(seq);
-}
-
-} // namespace
-
-PaperVenue::PaperVenue(QObject* parent) : QObject(parent) {
-}
-
-double PaperVenue::last_mark(const QString& coin) const {
- auto it = marks_.constFind(coin);
- return (it != marks_.constEnd()) ? it.value() : std::nan("");
-}
-
-void PaperVenue::set_maintenance_margin(const QString& coin, double frac) {
- mm_overrides_.insert(coin, frac);
-}
-
-void PaperVenue::seed_agent_if_needed(const QString& agent_id, double initial_capital) {
- if (!books_.contains(agent_id)) {
- AgentBook book;
- book.cash = initial_capital;
- books_.insert(agent_id, book);
- }
-}
-
-double PaperVenue::equity_for(const QString& agent_id) const {
- auto it = books_.constFind(agent_id);
- if (it == books_.constEnd()) return 0.0;
- const AgentBook& book = it.value();
- double eq = book.cash;
- for (auto pit = book.positions.constBegin(); pit != book.positions.constEnd(); ++pit) {
- const auto& p = pit.value();
- // Unrealized PnL on a perp: qty × (mark − entry).
- eq += p.qty * (p.mark - p.entry);
- }
- return eq;
-}
-
-double PaperVenue::liquidation_price(const PaperPosition& p) {
- if (p.entry <= 0.0 || p.leverage < 1 || p.qty == 0.0) return 0.0;
- const bool is_long = p.qty > 0.0;
- const double term = (1.0 / p.leverage) * (1.0 - p.maintenance_margin_frac);
- return is_long ? p.entry * (1.0 - term) : p.entry * (1.0 + term);
-}
-
-// ── Order placement ─────────────────────────────────────────────────────────
-
-void PaperVenue::place_order(const OrderRequest& req,
- std::function<void(OrderAck)> ack_cb) {
- // Snapshot mark at intake — slippage + fee applied off this. We assume the
- // engine's caller has already validated the request through RiskEngine, so
- // we accept and execute on the simulated round-trip timer.
- const double mark = last_mark(req.coin);
- if (!std::isfinite(mark) || mark <= 0.0) {
- if (ack_cb) {
- OrderAck a;
- a.status = QStringLiteral("rejected");
- a.error = QStringLiteral("no mark price for ") + req.coin;
- ack_cb(a);
- }
- return;
- }
-
- const QString id = gen_venue_order_id(next_order_seq_++);
-
- // Synthesise fill price: mark ± slippage in the unfavourable direction.
- const bool is_buy = (req.side == QLatin1String("buy"));
- const double fill_price = is_buy ? mark * (1.0 + kSlippageBps)
- : mark * (1.0 - kSlippageBps);
- const double notional = req.qty * fill_price;
- const double fee = notional * kTakerFee;
-
- // Acknowledge immediately.
- if (ack_cb) {
- OrderAck a;
- a.venue_order_id = id;
- a.status = QStringLiteral("accepted");
- ack_cb(a);
- }
-
- // Schedule the simulated fill after latency.
- QTimer::singleShot(kSimLatencyMs, this, [this, req, id, fill_price, fee]() {
- // Apply to the agent's book.
- // We assume the agent was seeded externally via paper_seed_agent.
- auto bookIt = books_.find(req.agent_id);
- if (bookIt == books_.end()) {
- LOG_ERROR("PaperVenue", QString("fill on unknown agent %1 (was paper_seed_agent called?)")
- .arg(req.agent_id));
- return;
- }
- AgentBook& book = bookIt.value();
-
- const bool is_buy = (req.side == QLatin1String("buy"));
- const double signed_qty = is_buy ? req.qty : -req.qty;
-
- auto posIt = book.positions.find(req.coin);
- if (req.reduce_only) {
- // Closing or reducing — settle realized PnL into cash.
- if (posIt == book.positions.end()) {
- LOG_WARN("PaperVenue", QString("reduce_only but no position for %1/%2")
- .arg(req.agent_id, req.coin));
- return;
- }
- PaperPosition& p = posIt.value();
- const double close_qty = std::min(std::fabs(p.qty), req.qty);
- const double realized = sign(p.qty) * close_qty * (fill_price - p.entry);
- book.cash += realized;
- book.cash -= fee;
- p.qty -= sign(p.qty) * close_qty;
- if (std::fabs(p.qty) < 1e-12) {
- book.positions.remove(req.coin);
- }
- } else {
- // Open a new position. RiskEngine guarantees no existing position in this coin.
- PaperPosition p;
- p.agent_id = req.agent_id;
- p.coin = req.coin;
- p.qty = signed_qty;
- p.entry = fill_price;
- p.mark = fill_price;
- p.leverage = req.leverage;
- p.profit_target = req.profit_target;
- p.stop_loss = req.stop_loss;
- const auto mmIt = mm_overrides_.constFind(req.coin);
- p.maintenance_margin_frac = (mmIt != mm_overrides_.constEnd()) ? mmIt.value() : 0.05;
- book.positions.insert(req.coin, p);
- // Margin bookkeeping: notional / leverage is locked from cash; we
- // model that simply by debiting the fee — the simulator treats
- // margin as a soft constraint visible only through liquidation.
- book.cash -= fee;
- }
-
- if (fill_cb_) {
- FillEvent f;
- f.agent_id = req.agent_id;
- f.venue_order_id = id;
- f.coin = req.coin;
- f.side = req.side;
- f.qty = req.qty;
- f.price = fill_price;
- f.fee = fee;
- f.utc_ms = QDateTime::currentMSecsSinceEpoch();
- fill_cb_(f);
- }
- });
-}
-
-void PaperVenue::cancel_order(const QString& /*venue_order_id*/) {
- // Paper orders execute on a 200ms timer — we don't keep a pending list.
- // No-op is correct: by the time a cancel arrives, the fill has already
- // landed (or there was no pending order to cancel).
-}
-
-// ── Mark feed + liquidations ────────────────────────────────────────────────
-
-void PaperVenue::push_mark(const QString& coin, double mark, qint64 utc_ms) {
- if (!std::isfinite(mark) || mark <= 0.0) return;
- marks_.insert(coin, mark);
-
- // Update each agent's mark on this coin.
- for (auto bit = books_.begin(); bit != books_.end(); ++bit) {
- auto pit = bit.value().positions.find(coin);
- if (pit != bit.value().positions.end()) pit.value().mark = mark;
- }
-
- if (mark_update_cb_) mark_update_cb_(coin, mark, utc_ms);
- check_liquidations(coin, mark, utc_ms);
-}
-
-void PaperVenue::check_liquidations(const QString& coin, double mark, qint64 utc_ms) {
- // Walk every agent's position on this coin. If mark crossed liq_price,
- // emit a LiquidationEvent and drop the position with a realized PnL of
- // -margin (engine logs this as "liquidation").
- QStringList to_remove_agent;
- for (auto bit = books_.begin(); bit != books_.end(); ++bit) {
- auto& book = bit.value();
- auto pit = book.positions.find(coin);
- if (pit == book.positions.end()) continue;
- PaperPosition& p = pit.value();
- const double liq = liquidation_price(p);
- if (liq <= 0.0) continue;
- const bool is_long = p.qty > 0.0;
- const bool crossed = is_long ? (mark <= liq) : (mark >= liq);
- if (!crossed) continue;
-
- // Realized PnL — at liquidation, the position closes at liq_price.
- const double realized = sign(p.qty) * std::fabs(p.qty) * (liq - p.entry);
- book.cash += realized;
- // Margin lost: roughly notional/leverage. We charge it implicitly by
- // letting equity drop through realized PnL — Hyperliquid's actual
- // engine takes maintenance margin into account; this is an
- // approximation acceptable for paper.
-
- if (liq_cb_) {
- LiquidationEvent e;
- e.agent_id = bit.key();
- e.coin = coin;
- e.exit_price = liq;
- e.realized_pnl_usd = realized;
- e.utc_ms = utc_ms;
- liq_cb_(e);
- }
- book.positions.remove(coin);
- }
-}
-
-// ── Funding ─────────────────────────────────────────────────────────────────
-
-void PaperVenue::push_funding(const QString& agent_id, const QString& coin,
- double amount_usd, qint64 utc_ms) {
- auto bit = books_.find(agent_id);
- if (bit == books_.end()) return;
- bit.value().cash += amount_usd;
- if (funding_cb_) {
- FundingEvent f;
- f.agent_id = agent_id;
- f.coin = coin;
- f.amount_usd = amount_usd;
- f.utc_ms = utc_ms;
- funding_cb_(f);
- }
-}
-
-// ── External seeding ────────────────────────────────────────────────────────
-
-void paper_seed_agent(PaperVenue& venue, const QString& agent_id, double initial_capital) {
- venue.seed_agent_if_needed(agent_id, initial_capital);
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/PaperVenue.h b/fincept-qt/src/services/alpha_arena/PaperVenue.h
deleted file mode 100644
index 03d6c94e7..000000000
--- a/fincept-qt/src/services/alpha_arena/PaperVenue.h
+++ /dev/null
@@ -1,113 +0,0 @@
-#pragma once
-// PaperVenue — in-memory simulator that mirrors Hyperliquid math.
-//
-// Consumed by the OrderRouter via IExchangeVenue. Mark prices are pushed in
-// from outside (the engine subscribes to a real Hyperliquid public-WS feed in
-// Phase 5c and forwards marks here, so paper PnL tracks reality). Funding
-// payments are pushed in similarly — we accept the venue's funding-rate
-// schedule rather than guessing.
-//
-// Models per Nof1 S1:
-// * Fees: 0.045% taker / 0.015% maker. Entries are market+IOC = taker.
-// * Slippage: 5bps each side.
-// * Sim latency: 200ms — paper P&L doesn't trivially beat live by HFT noise.
-// * Liquidation: deterministic when mark crosses liq_price.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §5b (PaperVenue).
-
-#include "services/alpha_arena/IExchangeVenue.h"
-
-#include <QHash>
-#include <QObject>
-#include <QString>
-
-#include <functional>
-
-namespace fincept::services::alpha_arena {
-
-class PaperVenue : public QObject, public IExchangeVenue {
- Q_OBJECT
- public:
- explicit PaperVenue(QObject* parent = nullptr);
- ~PaperVenue() override = default;
-
- // ── IExchangeVenue ──
- QString venue_kind() const override { return QStringLiteral("paper"); }
- ConnectionState connection_state() const override { return ConnectionState::Connected; }
- void place_order(const OrderRequest& req,
- std::function<void(OrderAck)> ack_cb) override;
- void cancel_order(const QString& venue_order_id) override;
- double last_mark(const QString& coin) const override;
- void on_fill(std::function<void(FillEvent)> cb) override { fill_cb_ = std::move(cb); }
- void on_funding(std::function<void(FundingEvent)> cb) override { funding_cb_ = std::move(cb); }
- void on_liquidation(std::function<void(LiquidationEvent)> cb) override { liq_cb_ = std::move(cb); }
- void on_mark_update(std::function<void(QString, double, qint64)> cb) override {
- mark_update_cb_ = std::move(cb);
- }
-
- // ── Paper-specific external feed ──
- /// Engine pushes marks here from a real Hyperliquid public-WS subscription.
- /// We update internal marks and fire mark_update_cb_ + check liquidations.
- void push_mark(const QString& coin, double mark, qint64 utc_ms);
-
- /// Engine pushes funding payments here at the 8h boundary. Amount is
- /// signed: positive = received, negative = paid. Per-agent settlement.
- void push_funding(const QString& agent_id, const QString& coin,
- double amount_usd, qint64 utc_ms);
-
- /// Engine queries this when reconciling: how much equity does this agent
- /// have right now (cash + sum(mark-to-market unrealized PnL))?
- double equity_for(const QString& agent_id) const;
-
- /// Set per-coin maintenance margin (Hyperliquid metadata). Default 5%.
- void set_maintenance_margin(const QString& coin, double frac);
-
- private:
- /// Internal model of an open paper position, separate from Position to
- /// avoid coupling the on-disk DTO to in-memory bookkeeping.
- struct PaperPosition {
- QString agent_id;
- QString coin;
- double qty = 0.0; // signed
- double entry = 0.0;
- double mark = 0.0;
- int leverage = 1;
- double profit_target = 0.0;
- double stop_loss = 0.0;
- double maintenance_margin_frac = 0.05;
- };
-
- /// Per-agent ledger: cash balance + positions.
- struct AgentBook {
- double cash = 0.0;
- QHash<QString, PaperPosition> positions; // key: coin
- };
-
- void seed_agent_if_needed(const QString& agent_id, double initial_capital);
- void check_liquidations(const QString& coin, double mark, qint64 utc_ms);
- static double liquidation_price(const PaperPosition& p);
-
- // Free function exposes seeding to the engine without making the
- // private impl public on the venue interface.
- friend void paper_seed_agent(PaperVenue&, const QString&, double);
-
- QHash<QString, AgentBook> books_;
- QHash<QString, double> marks_; // coin -> last mark
- QHash<QString, double> mm_overrides_; // coin -> maintenance margin frac
-
- std::function<void(FillEvent)> fill_cb_;
- std::function<void(FundingEvent)> funding_cb_;
- std::function<void(LiquidationEvent)> liq_cb_;
- std::function<void(QString, double, qint64)> mark_update_cb_;
-
- /// Sequential venue-order-id generator (paper only).
- quint64 next_order_seq_ = 1;
-
- friend void paper_seed_agent(PaperVenue& venue, const QString& agent_id, double initial_capital);
-};
-
-/// Convenience — the engine seeds each agent's paper book at agent-add time.
-/// Public because PaperVenue itself doesn't know agent ids until placement.
-void paper_seed_agent(PaperVenue& venue, const QString& agent_id, double initial_capital);
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/RiskEngine.cpp b/fincept-qt/src/services/alpha_arena/RiskEngine.cpp
deleted file mode 100644
index 949f04f13..000000000
--- a/fincept-qt/src/services/alpha_arena/RiskEngine.cpp
+++ /dev/null
@@ -1,181 +0,0 @@
-#include "services/alpha_arena/RiskEngine.h"
-
-#include <cmath>
-
-namespace fincept::services::alpha_arena {
-
-namespace {
-
-/// 30-minute cooldown for Monk mode, expressed in ms.
-constexpr qint64 kMonkCooldownMs = 30LL * 60LL * 1000LL;
-
-/// Notional size cap in Monk mode (25% of equity).
-constexpr double kMonkMaxNotionalFrac = 0.25;
-
-inline RiskVerdict reject(const QString& reason) {
- RiskVerdict v;
- v.outcome = RiskVerdict::Outcome::Reject;
- v.reason = reason;
- return v;
-}
-
-inline RiskVerdict accept() {
- RiskVerdict v;
- v.outcome = RiskVerdict::Outcome::Accept;
- return v;
-}
-
-inline RiskVerdict amend(const ProposedAction& a, const QString& reason) {
- RiskVerdict v;
- v.outcome = RiskVerdict::Outcome::Amend;
- v.reason = reason;
- v.amended = a;
- return v;
-}
-
-[[maybe_unused]] bool is_entry_signal(Signal s) {
- return s == Signal::BuyToEnter || s == Signal::SellToEnter;
-}
-
-} // namespace
-
-double recompute_risk_usd(const ProposedAction& a, double entry_price) {
- if (a.stop_loss <= 0.0 || entry_price <= 0.0 || a.quantity <= 0.0) return 0.0;
- return std::fabs(entry_price - a.stop_loss) * a.quantity;
-}
-
-double estimated_liquidation_price(double entry, int leverage, bool is_long, double mm_frac) {
- if (entry <= 0.0 || leverage < 1) return 0.0;
- // Hyperliquid: liq_price = entry × (1 ± (1/leverage) × (1 - mm_frac))
- // (long: −, short: +)
- const double term = (1.0 / leverage) * (1.0 - mm_frac);
- return is_long ? entry * (1.0 - term) : entry * (1.0 + term);
-}
-
-RiskVerdict evaluate_action(const ProposedAction& action,
- const AgentRiskState& agent,
- CompetitionMode mode) {
- // ── Trivial accepts: hold/close don't go through entry-side checks. ─────
- if (action.signal == Signal::Hold) return accept();
- if (action.signal == Signal::Close) {
- if (agent.existing_qty_in_coin == 0.0) {
- return reject(QStringLiteral("close requested but no position"));
- }
- return accept();
- }
-
- // ── Entry signals from here ─────────────────────────────────────────────
-
- // 1. One position per coin.
- if (agent.existing_qty_in_coin != 0.0) {
- return reject(QStringLiteral("position_exists"));
- }
-
- // 2. Leverage cap.
- if (action.leverage < limits::kMinLeverage || action.leverage > limits::kMaxLeverage) {
- return reject(QStringLiteral("leverage out of range [1,20]"));
- }
-
- // 3. Quantity & stops sanity (already enforced by parser; double-check).
- if (action.quantity <= 0.0 || action.profit_target <= 0.0 || action.stop_loss <= 0.0) {
- return reject(QStringLiteral("entry requires qty/profit_target/stop_loss > 0"));
- }
- if (agent.mark_price <= 0.0) {
- return reject(QStringLiteral("no mark price for coin"));
- }
- if (agent.equity <= 0.0) {
- return reject(QStringLiteral("non-positive equity"));
- }
-
- const bool is_long = (action.signal == Signal::BuyToEnter);
-
- // 4. Stops must be on the right side of mark.
- if (is_long) {
- if (action.stop_loss >= agent.mark_price) {
- return reject(QStringLiteral("long stop_loss must be below mark"));
- }
- if (action.profit_target <= agent.mark_price) {
- return reject(QStringLiteral("long profit_target must be above mark"));
- }
- } else {
- if (action.stop_loss <= agent.mark_price) {
- return reject(QStringLiteral("short stop_loss must be above mark"));
- }
- if (action.profit_target >= agent.mark_price) {
- return reject(QStringLiteral("short profit_target must be below mark"));
- }
- }
-
- // 5. Liquidation buffer ≥ 15% of mark.
- const double liq = estimated_liquidation_price(agent.mark_price, action.leverage,
- is_long, agent.maintenance_margin_frac);
- const double buffer_frac = std::fabs(agent.mark_price - liq) / agent.mark_price;
- if (buffer_frac < limits::kMinLiquidationBufferFrac) {
- return reject(QStringLiteral("liquidation buffer %1%% below 15%% minimum")
- .arg(buffer_frac * 100.0, 0, 'f', 2));
- }
-
- // 6. Risk-per-trade ≤ 2% of equity (server-recomputed).
- const double recomputed_risk = recompute_risk_usd(action, agent.mark_price);
- const double max_risk = agent.equity * limits::kMaxRiskPerTradeFrac;
- if (recomputed_risk > max_risk) {
- return reject(QStringLiteral("risk_usd %1 exceeds 2%% of equity (%2)")
- .arg(recomputed_risk, 0, 'f', 2)
- .arg(max_risk, 0, 'f', 2));
- }
-
- // 7. Mode-specific (Monk).
- if (mode == CompetitionMode::Monk) {
- // 7a. 30-min cooldown per coin.
- if (agent.last_entry_utc_ms_on_coin > 0 &&
- (agent.now_utc_ms - agent.last_entry_utc_ms_on_coin) < kMonkCooldownMs) {
- return reject(QStringLiteral("monk: 30-min cooldown active for coin"));
- }
- // 7b. Notional ≤ 25% equity.
- const double notional = action.quantity * agent.mark_price;
- if (notional > agent.equity * kMonkMaxNotionalFrac) {
- return reject(QStringLiteral("monk: notional %1 exceeds 25%% of equity")
- .arg(notional, 0, 'f', 2));
- }
- }
-
- // 8. risk_usd drift check — amend (not reject) on > 5% deviation.
- if (action.risk_usd > 0.0) {
- const double drift = std::fabs(action.risk_usd - recomputed_risk) /
- std::max(action.risk_usd, recomputed_risk);
- if (drift > limits::kRiskUsdRecomputeToleranceFrac) {
- ProposedAction corrected = action;
- corrected.risk_usd = recomputed_risk;
- return amend(corrected,
- QStringLiteral("risk_usd drift %1%% > 5%% — server overrode")
- .arg(drift * 100.0, 0, 'f', 2));
- }
- }
-
- return accept();
-}
-
-CircuitState advance_circuit(const CircuitState& prev,
- bool tick_had_parse_failure,
- bool any_action_rejected,
- double current_drawdown_frac) {
- CircuitState next = prev;
-
- next.consecutive_parse_failures = tick_had_parse_failure ? prev.consecutive_parse_failures + 1 : 0;
- next.consecutive_risk_rejects = any_action_rejected ? prev.consecutive_risk_rejects + 1 : 0;
- next.max_drawdown_frac = std::max(prev.max_drawdown_frac, current_drawdown_frac);
-
- // Once open, stays open until a manual resume (caller resets the struct).
- if (prev.open) {
- next.open = true;
- return next;
- }
-
- if (next.consecutive_parse_failures >= circuit_thresholds::kParseFailureLimit) next.open = true;
- if (next.consecutive_risk_rejects >= circuit_thresholds::kRiskRejectLimit) next.open = true;
- if (next.max_drawdown_frac >= circuit_thresholds::kDrawdownLimit) next.open = true;
-
- return next;
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/RiskEngine.h b/fincept-qt/src/services/alpha_arena/RiskEngine.h
deleted file mode 100644
index 3473d8e7e..000000000
--- a/fincept-qt/src/services/alpha_arena/RiskEngine.h
+++ /dev/null
@@ -1,94 +0,0 @@
-#pragma once
-// RiskEngine — server-side, fail-closed validation of every model action.
-//
-// Runs *between* ContextBuilder/ModelDispatcher (which produce ProposedAction)
-// and OrderRouter (which talks to the venue). Pure function, no I/O, no state
-// — caller threads agent state in via the inputs.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §6 (Risk engine).
-//
-// Hard rules (rejection):
-// * One position per coin (caller passes existing_long/short).
-// * Liquidation buffer ≥ 15% of price-at-decision.
-// * Risk per trade ≤ 2% of account equity (recomputed by us).
-// * Max leverage 20×.
-//
-// Mode-specific (Monk):
-// * ≤ 1 entry per coin per 30 minutes.
-// * Notional position size ≤ 25% of equity.
-//
-// Drift handling:
-// * If the model's risk_usd differs from our recomputed value by > 5%,
-// we *amend* the action with the corrected value (not reject) and
-// surface the discrepancy as a benchmarkable trait of the model.
-
-#include "services/alpha_arena/AlphaArenaSchema.h"
-#include "services/alpha_arena/AlphaArenaTypes.h"
-
-#include <QString>
-
-namespace fincept::services::alpha_arena {
-
-/// Inputs the engine needs about an agent's current world to decide a verdict.
-/// Caller assembles this; it is not stored anywhere by the engine.
-struct AgentRiskState {
- /// Current equity (used for 2%-of-equity and 25%-of-equity Monk caps).
- double equity = 0.0;
- /// Position the agent currently has in this coin (qty signed, 0 = none).
- double existing_qty_in_coin = 0.0;
- /// UTC ms of the last entry on this coin, or 0 if never. Drives Monk
- /// 30-min cooldown.
- qint64 last_entry_utc_ms_on_coin = 0;
- /// "Now" — the engine compares last_entry_utc_ms_on_coin against this.
- qint64 now_utc_ms = 0;
- /// Maintenance margin fraction for this coin (Hyperliquid metadata).
- /// Used when computing the liquidation price the model implicitly
- /// asks for. Default 5% if the venue hasn't supplied a value.
- double maintenance_margin_frac = 0.05;
- /// Mark price at decision time.
- double mark_price = 0.0;
-};
-
-/// Per-agent kill-switch state. Caller persists this between ticks.
-struct CircuitState {
- int consecutive_parse_failures = 0;
- int consecutive_risk_rejects = 0;
- double max_drawdown_frac = 0.0; // worst peak-to-trough so far
- bool open = false; // true => agent paused
-};
-
-namespace circuit_thresholds {
-inline constexpr int kParseFailureLimit = 3;
-inline constexpr int kRiskRejectLimit = 3;
-inline constexpr double kDrawdownLimit = 0.50; // 50%
-} // namespace circuit_thresholds
-
-/// Pure: returns the verdict. The verdict's `amended` form (if any) is what
-/// the caller should hand to the OrderRouter; on Reject, do nothing.
-RiskVerdict evaluate_action(const ProposedAction& action,
- const AgentRiskState& agent,
- CompetitionMode mode);
-
-/// Apply the outcome of one tick to the circuit. Caller passes how many
-/// actions were proposed, how many parsed cleanly, and how many were
-/// rejected by evaluate_action. Returns the updated state.
-///
-/// `current_drawdown_frac` is the agent's running peak-to-trough fraction.
-/// When the circuit transitions to open, the caller is expected to halt the
-/// agent (close positions on the venue) and post an `agent_circuit_open`
-/// event into the audit log.
-CircuitState advance_circuit(const CircuitState& prev,
- bool tick_had_parse_failure,
- bool any_action_rejected,
- double current_drawdown_frac);
-
-/// Helper used by both the engine and tests — recompute risk_usd from
-/// |entry − stop_loss| × qty.
-double recompute_risk_usd(const ProposedAction& a, double entry_price);
-
-/// Helper — the price at which `action` would be liquidated, given mark
-/// price, leverage and maintenance margin. For longs, this is below mark;
-/// for shorts, above. Used in the 15%-buffer check.
-double estimated_liquidation_price(double entry, int leverage, bool is_long, double mm_frac);
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/SecretRedemptionServer.cpp b/fincept-qt/src/services/alpha_arena/SecretRedemptionServer.cpp
deleted file mode 100644
index 0c4efede5..000000000
--- a/fincept-qt/src/services/alpha_arena/SecretRedemptionServer.cpp
+++ /dev/null
@@ -1,147 +0,0 @@
-#include "services/alpha_arena/SecretRedemptionServer.h"
-
-#include "core/logging/Logger.h"
-#include "storage/secure/SecureStorage.h"
-
-#include <QByteArray>
-#include <QDataStream>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QLocalServer>
-#include <QLocalSocket>
-
-#include <cstdint>
-
-namespace fincept::services::alpha_arena {
-
-namespace {
-
-QByteArray length_prefix(const QByteArray& body) {
- QByteArray out;
- QDataStream s(&out, QIODevice::WriteOnly);
- s.setByteOrder(QDataStream::LittleEndian);
- s << static_cast<quint32>(body.size());
- out.append(body);
- return out;
-}
-
-QByteArray reply_error(const QString& msg) {
- QJsonObject o;
- o["error"] = msg;
- return length_prefix(QJsonDocument(o).toJson(QJsonDocument::Compact));
-}
-
-QByteArray reply_ok(const QString& api_key) {
- QJsonObject o;
- o["api_key"] = api_key;
- return length_prefix(QJsonDocument(o).toJson(QJsonDocument::Compact));
-}
-
-} // namespace
-
-SecretRedemptionServer::SecretRedemptionServer(QObject* parent)
- : QObject(parent), server_(new QLocalServer(this)) {
- connect(server_, &QLocalServer::newConnection, this, &SecretRedemptionServer::on_new_connection);
-}
-
-SecretRedemptionServer::~SecretRedemptionServer() {
- stop();
-}
-
-bool SecretRedemptionServer::start(const QString& pipe_name) {
- stop();
- redeemed_.clear();
- // Remove any stale endpoint with the same name (Linux/macOS unix-socket
- // file may persist across crashes).
- QLocalServer::removeServer(pipe_name);
- if (!server_->listen(pipe_name)) {
- LOG_ERROR("AlphaArena.Secret",
- QString("listen on %1 failed: %2").arg(pipe_name, server_->errorString()));
- return false;
- }
- pipe_name_ = pipe_name;
- LOG_INFO("AlphaArena.Secret", QString("listening on %1").arg(pipe_name));
- return true;
-}
-
-void SecretRedemptionServer::stop() {
- if (server_->isListening()) {
- server_->close();
- LOG_INFO("AlphaArena.Secret", QString("closed %1").arg(pipe_name_));
- }
- pipe_name_.clear();
-}
-
-void SecretRedemptionServer::on_new_connection() {
- while (auto* sock = server_->nextPendingConnection()) {
- connect(sock, &QLocalSocket::readyRead, this, &SecretRedemptionServer::on_socket_ready_read);
- // Auto-cleanup
- connect(sock, &QLocalSocket::disconnected, sock, &QObject::deleteLater);
- }
-}
-
-void SecretRedemptionServer::on_socket_ready_read() {
- auto* sock = qobject_cast<QLocalSocket*>(sender());
- if (!sock) return;
-
- // Wait for at least 4 bytes (length prefix).
- if (sock->bytesAvailable() < 4) return;
-
- QByteArray hdr = sock->read(4);
- QDataStream hs(hdr);
- hs.setByteOrder(QDataStream::LittleEndian);
- quint32 len = 0;
- hs >> len;
- if (len == 0 || len > 64 * 1024) {
- sock->write(reply_error(QStringLiteral("bad length prefix")));
- sock->disconnectFromServer();
- return;
- }
-
- // Read body. The subprocess sends a small JSON object (~100 bytes) so we
- // can afford the synchronous loop here without yielding.
- QByteArray body;
- while (body.size() < static_cast<int>(len)) {
- if (sock->bytesAvailable() == 0 && !sock->waitForReadyRead(500)) break;
- body.append(sock->read(static_cast<int>(len) - body.size()));
- }
- if (body.size() < static_cast<int>(len)) {
- sock->write(reply_error(QStringLiteral("short body")));
- sock->disconnectFromServer();
- return;
- }
-
- auto doc = QJsonDocument::fromJson(body);
- if (!doc.isObject()) {
- sock->write(reply_error(QStringLiteral("malformed JSON")));
- sock->disconnectFromServer();
- return;
- }
- const QString handle = doc.object().value("handle").toString();
- if (handle.isEmpty()) {
- sock->write(reply_error(QStringLiteral("missing handle")));
- sock->disconnectFromServer();
- return;
- }
- if (redeemed_.contains(handle)) {
- sock->write(reply_error(QStringLiteral("handle_already_redeemed")));
- sock->disconnectFromServer();
- return;
- }
-
- auto r = SecureStorage::instance().retrieve(handle);
- if (r.is_err()) {
- LOG_WARN("AlphaArena.Secret", QString("redeem failed for handle: %1")
- .arg(QString::fromStdString(r.error())));
- sock->write(reply_error(QStringLiteral("not_found")));
- sock->disconnectFromServer();
- return;
- }
-
- redeemed_.insert(handle);
- sock->write(reply_ok(r.value()));
- sock->flush();
- sock->disconnectFromServer();
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/SecretRedemptionServer.h b/fincept-qt/src/services/alpha_arena/SecretRedemptionServer.h
deleted file mode 100644
index 3bbf1d7ac..000000000
--- a/fincept-qt/src/services/alpha_arena/SecretRedemptionServer.h
+++ /dev/null
@@ -1,56 +0,0 @@
-#pragma once
-// SecretRedemptionServer — local IPC for the llm_call.py subprocess to fetch
-// API keys without ever seeing them on argv or in the request file on disk.
-//
-// Model:
-// 1. ModelDispatcher generates a per-tick `pipe_name` (uuid-based).
-// 2. SecretRedemptionServer.start(pipe_name) opens a QLocalServer on that
-// name. Stays open for the duration of the tick (~minute), then closes.
-// 3. Subprocess connects, sends {"handle":"<agent_secret_handle>"},
-// receives {"api_key":"<plaintext>"}, then disconnects.
-// 4. Server resolves handles by looking them up in SecureStorage. The
-// handle IS the SecureStorage key; we don't keep an in-memory plaintext
-// cache.
-//
-// A handle is single-use per server lifetime — once redeemed it is added to a
-// blacklist and subsequent reads on the same socket are rejected with
-// {"error":"handle_already_redeemed"}. This means a malicious second
-// connection in the same tick window can't replay.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §9.1 (API key storage).
-
-#include <QLocalServer>
-#include <QLocalSocket>
-#include <QObject>
-#include <QSet>
-#include <QString>
-
-namespace fincept::services::alpha_arena {
-
-class SecretRedemptionServer : public QObject {
- Q_OBJECT
- public:
- explicit SecretRedemptionServer(QObject* parent = nullptr);
- ~SecretRedemptionServer() override;
-
- /// Start a fresh server with the given pipe name. Closes any previous
- /// server first. Returns true on success.
- bool start(const QString& pipe_name);
-
- /// Close the server (disconnects all sockets).
- void stop();
-
- /// Currently running pipe name (empty if not running).
- QString pipe_name() const { return pipe_name_; }
-
- private slots:
- void on_new_connection();
- void on_socket_ready_read();
-
- private:
- QLocalServer* server_;
- QString pipe_name_;
- QSet<QString> redeemed_; // handles already used during this server lifetime
-};
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/TickClock.cpp b/fincept-qt/src/services/alpha_arena/TickClock.cpp
deleted file mode 100644
index 5c1100765..000000000
--- a/fincept-qt/src/services/alpha_arena/TickClock.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-#include "services/alpha_arena/TickClock.h"
-
-#include "core/logging/Logger.h"
-
-#include <QDateTime>
-
-namespace fincept::services::alpha_arena {
-
-TickClock::TickClock(QObject* parent) : QObject(parent), timer_(new QTimer(this)) {
- timer_->setTimerType(Qt::PreciseTimer);
- connect(timer_, &QTimer::timeout, this, &TickClock::on_timeout);
-}
-
-void TickClock::set_cadence_seconds(int seconds) {
- if (seconds < 10) seconds = 10; // sanity floor
- if (seconds > 3600) seconds = 3600; // sanity ceiling (1h)
- cadence_seconds_ = seconds;
- if (timer_->isActive()) {
- timer_->setInterval(cadence_seconds_ * 1000);
- }
-}
-
-void TickClock::start() {
- timer_->setInterval(cadence_seconds_ * 1000);
- timer_->start();
- LOG_INFO("AlphaArena.TickClock", QString("started, cadence=%1s").arg(cadence_seconds_));
-}
-
-void TickClock::stop() {
- timer_->stop();
- in_flight_ = false;
- LOG_INFO("AlphaArena.TickClock", "stopped");
-}
-
-void TickClock::tick_complete() {
- if (!in_flight_) return;
- in_flight_ = false;
- last_seq_ = next_seq_ - 1; // next_seq_ was already advanced when we emitted
-}
-
-void TickClock::force_tick() {
- if (in_flight_) {
- emit tick_skipped(next_seq_);
- LOG_WARN("AlphaArena.TickClock",
- QString("force_tick refused: tick %1 in flight").arg(next_seq_ - 1));
- return;
- }
- on_timeout();
-}
-
-void TickClock::on_timeout() {
- if (in_flight_) {
- LOG_WARN("AlphaArena.TickClock",
- QString("tick_skipped seq=%1 (previous still in flight)").arg(next_seq_));
- emit tick_skipped(next_seq_);
- return;
- }
-
- Tick t;
- t.utc_ms = QDateTime::currentMSecsSinceEpoch();
- t.seq = next_seq_++;
- in_flight_ = true;
- emit tick(t);
-}
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/alpha_arena/TickClock.h b/fincept-qt/src/services/alpha_arena/TickClock.h
deleted file mode 100644
index 7cb78054e..000000000
--- a/fincept-qt/src/services/alpha_arena/TickClock.h
+++ /dev/null
@@ -1,73 +0,0 @@
-#pragma once
-// TickClock — single-thread monotonic scheduler for one competition.
-//
-// Owned by AlphaArenaEngine. There is exactly one TickClock per active
-// competition; v1 supports only a single competition at a time.
-//
-// Cadence is wall-clock fixed interval (Nof1 S1 was 2–3 minutes; we default
-// to 180s, configurable per competition). Drift handling: if the previous
-// tick is still in flight when the timer fires, we *skip* the new tick and
-// emit `tick_skipped(seq)`. We do not queue make-ups — that's the Nof1
-// behaviour and the only sane choice.
-//
-// Reference: fincept-qt/.grill-me/alpha-arena-grill.md §3 (Tick clock).
-
-#include "services/alpha_arena/AlphaArenaTypes.h"
-
-#include <QObject>
-#include <QString>
-#include <QTimer>
-
-namespace fincept::services::alpha_arena {
-
-class TickClock : public QObject {
- Q_OBJECT
- public:
- explicit TickClock(QObject* parent = nullptr);
-
- /// Set cadence between ticks. Effective on next start() or natural fire.
- void set_cadence_seconds(int seconds);
- int cadence_seconds() const { return cadence_seconds_; }
-
- /// Mark the previous tick as complete. The clock will continue firing on
- /// schedule; if a tick is fired while another is in_flight, that tick is
- /// skipped (logged + signalled).
- void tick_complete();
-
- /// Returns true between `tick(…)` emission and `tick_complete()`.
- bool in_flight() const { return in_flight_; }
-
- /// Manual fire. Useful for the FORCE TICK button. If a tick is already
- /// in flight this is a no-op (and emits `tick_skipped`).
- void force_tick();
-
- /// Last completed tick seq, or 0 if none yet.
- int last_seq() const { return last_seq_; }
-
- public slots:
- void start();
- void stop();
-
- signals:
- /// Emitted when a tick fires. Listener must call tick_complete() when
- /// done — the clock will not fire again while in_flight is true (it
- /// will instead emit tick_skipped for any timer fire that lands in that
- /// window).
- void tick(fincept::services::alpha_arena::Tick t);
-
- /// Emitted when a scheduled tick is skipped because the previous one is
- /// still in flight.
- void tick_skipped(int would_be_seq);
-
- private slots:
- void on_timeout();
-
- private:
- QTimer* timer_;
- int cadence_seconds_ = 180;
- int next_seq_ = 1;
- int last_seq_ = 0;
- bool in_flight_ = false;
-};
-
-} // namespace fincept::services::alpha_arena
diff --git a/fincept-qt/src/services/llm/ProviderCatalog.cpp b/fincept-qt/src/services/llm/ProviderCatalog.cpp
new file mode 100644
index 000000000..dd46c62bd
--- /dev/null
+++ b/fincept-qt/src/services/llm/ProviderCatalog.cpp
@@ -0,0 +1,200 @@
+// ProviderCatalog.cpp — static metadata for every known LLM provider.
+// Single source of truth shared by Settings UI (LlmConfigSection) and the
+// Alpha Arena model registry. Data moved verbatim from LlmConfigSection.cpp
+// (2026-06-10); update HERE when adding a provider.
+#include "services/llm/ProviderCatalog.h"
+
+#include <QHash>
+#include <QRegularExpression>
+
+namespace fincept::ai_chat {
+
+const QStringList& ProviderCatalog::known_providers() {
+ static const QStringList kProviders = {"openai", "anthropic", "gemini", "groq", "deepseek",
+ "openrouter", "minimax", "kimi", "ollama", "xai", "fincept",
+ "astraflow", "astraflow_cn", "aihubmix", "atlascloud"};
+ return kProviders;
+}
+
+QString ProviderCatalog::display_name(const QString& provider_id) {
+ static const QHash<QString, QString> kNames = {
+ {"openai", "OpenAI"}, {"anthropic", "Anthropic"}, {"gemini", "Gemini"},
+ {"groq", "Groq"}, {"deepseek", "DeepSeek"}, {"openrouter", "OpenRouter"},
+ {"minimax", "MiniMax"}, {"kimi", "Kimi"}, {"ollama", "Ollama"},
+ {"xai", "xAI"}, {"fincept", "Fincept LLM (recommended)"}, {"astraflow", "AstraFlow"},
+ {"astraflow_cn", "AstraFlow CN"}, {"aihubmix", "AIHubMix"}, {"atlascloud", "AtlasCloud"},
+ };
+ const QString id = provider_id.toLower();
+ const auto it = kNames.find(id);
+ if (it != kNames.end())
+ return it.value();
+ // Unknown/custom provider: capitalize the first letter as a sensible default.
+ if (provider_id.isEmpty())
+ return provider_id;
+ QString s = provider_id;
+ s[0] = s[0].toUpper();
+ return s;
+}
+
+QString ProviderCatalog::default_base_url(const QString& provider) {
+ const QString p = provider.toLower();
+ if (p == "openai")
+ return {}; // uses default
+ if (p == "anthropic")
+ return {};
+ if (p == "gemini")
+ return {};
+ if (p == "groq")
+ return {};
+ if (p == "deepseek")
+ return {};
+ if (p == "openrouter")
+ return {};
+ if (p == "minimax")
+ return "https://api.minimax.io/v1";
+ if (p == "kimi")
+ return {}; // defaults to https://api.moonshot.ai
+ if (p == "ollama")
+ return "http://localhost:11434";
+ if (p == "xai")
+ return {};
+ if (p == "fincept")
+ return {}; // endpoints are hardcoded in LlmService, no base_url needed
+ if (p == "astraflow")
+ return "https://api-us-ca.umodelverse.ai/v1"; // Astraflow global endpoint (UCloud)
+ if (p == "astraflow_cn")
+ return "https://api.modelverse.cn/v1"; // Astraflow China endpoint (UCloud)
+ if (p == "aihubmix")
+ return "https://aihubmix.com/v1"; // AIHubMix — OpenAI-compatible aggregator (500+ models)
+ if (p == "atlascloud")
+ return "https://api.atlascloud.ai/v1"; // AtlasCloud — OpenAI-compatible aggregator (300+ open models)
+ return {};
+}
+
+QStringList ProviderCatalog::fallback_models(const QString& provider) {
+ const QString p = provider.toLower();
+ if (p == "openai")
+ return {"gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "o3-mini"};
+ if (p == "anthropic")
+ return {"claude-sonnet-4-5-20250514", "claude-opus-4-5", "claude-3-5-sonnet-20241022",
+ "claude-3-haiku-20240307"};
+ if (p == "gemini")
+ return {"gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash"};
+ if (p == "groq")
+ return {"llama-3.3-70b-versatile", "mixtral-8x7b-32768", "gemma2-9b-it"};
+ if (p == "deepseek")
+ return {"deepseek-chat", "deepseek-reasoner"};
+ if (p == "openrouter")
+ return {"openai/gpt-4o", "anthropic/claude-sonnet-4-5", "google/gemini-2.5-flash"};
+ if (p == "minimax")
+ return {"MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M2.5", "MiniMax-M2.5-highspeed"};
+ if (p == "kimi")
+ return {"moonshot-v1-auto",
+ "moonshot-v1-8k",
+ "moonshot-v1-32k",
+ "moonshot-v1-128k",
+ "kimi-k2.5",
+ "kimi-k2.6",
+ "kimi-k2-thinking",
+ "kimi-k2-thinking-turbo",
+ "kimi-k2-0905-preview",
+ "kimi-k2-turbo-preview",
+ "kimi-k2-0711-preview",
+ "moonshot-v1-8k-vision-preview",
+ "moonshot-v1-32k-vision-preview",
+ "moonshot-v1-128k-vision-preview"};
+ if (p == "ollama")
+ return {}; // Local provider — models fetched live from /api/tags. No fallback so the
+ // combo only shows what the user actually has installed locally.
+ if (p == "xai")
+ return {"grok-4-latest", "grok-4", "grok-3", "grok-3-mini"};
+ if (p == "fincept")
+ return {"MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M2.5", "MiniMax-M2.5-highspeed"};
+ if (p == "astraflow" || p == "astraflow_cn")
+ // Astraflow by UCloud — OpenAI-compatible aggregator supporting 200+ models.
+ // A non-exhaustive starter list; full list fetchable via Fetch button.
+ return {"gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "o3-mini",
+ "claude-sonnet-4-5-20250514", "claude-3-5-sonnet-20241022",
+ "gemini-2.5-flash", "gemini-2.5-pro",
+ "deepseek-chat", "deepseek-reasoner",
+ "llama-3.3-70b-versatile", "qwen-turbo", "qwen-plus"};
+ if (p == "aihubmix")
+ // AIHubMix — OpenAI-compatible aggregator routing 500+ models (OpenAI, Claude,
+ // Gemini, DeepSeek, Qwen, ...) through one /v1/chat/completions endpoint. Models
+ // keep their upstream ids. Starter list only; full list via the Fetch button.
+ return {"gpt-4o", "gpt-4o-mini", "gpt-4.1", "o3-mini",
+ "claude-sonnet-4-5-20250514", "claude-3-5-sonnet-20241022",
+ "gemini-2.5-flash", "gemini-2.5-pro",
+ "deepseek-chat", "deepseek-reasoner",
+ "qwen-max", "qwen-plus", "grok-4"};
+ if (p == "atlascloud")
+ // AtlasCloud — OpenAI-compatible aggregator (300+ models). Model ids are
+ // HuggingFace-style "org/model" strings (NOT short aliases). Note: a few ids
+ // listed by /v1/models are unprovisioned and return 400 (e.g. google/gemini-2.0-flash,
+ // openai/gpt-4o*). The list below is a verified-working starter set; use the
+ // Fetch button for the full live catalog (/v1/models).
+ return {"deepseek-ai/DeepSeek-V3.1", "deepseek-ai/deepseek-r1-0528",
+ "qwen/qwen3-32b", "Qwen/Qwen3-235B-A22B-Instruct-2507",
+ "zai-org/GLM-4.6", "moonshotai/Kimi-K2-Instruct", "MiniMaxAI/MiniMax-M2",
+ "google/gemini-2.5-flash", "anthropic/claude-haiku-4.5-20251001"};
+ return {};
+}
+
+bool ProviderCatalog::requires_api_key(const QString& provider) {
+ const QString p = provider.toLower();
+ return p != "ollama" && p != "fincept";
+}
+
+bool ProviderCatalog::is_openai_compatible(const QString& provider) {
+ const QString p = provider.toLower();
+ return p != "anthropic" && p != "gemini" && p != "google" && p != "fincept";
+}
+
+QString ProviderCatalog::brand_color(const QString& provider) {
+ static const QHash<QString, QString> kColors = {
+ {"openai", "#10A37F"}, {"anthropic", "#D97757"}, {"gemini", "#4285F4"},
+ {"groq", "#F55036"}, {"deepseek", "#4D6BFE"}, {"openrouter", "#8B5CF6"},
+ {"minimax", "#FF4D6A"}, {"kimi", "#16D9C4"}, {"ollama", "#9CA3AF"},
+ {"xai", "#E7E9EA"}, {"fincept", "#FF8800"}, {"astraflow", "#38BDF8"},
+ {"astraflow_cn", "#38BDF8"}, {"aihubmix", "#F59E0B"}, {"atlascloud", "#34D399"},
+ };
+ const auto it = kColors.find(provider.toLower());
+ if (it != kColors.end()) return it.value();
+ static const QStringList kPalette = {"#E879F9", "#A3E635", "#FB7185", "#60A5FA", "#FBBF24"};
+ return kPalette[static_cast<qsizetype>(qHash(provider.toLower()) % static_cast<size_t>(kPalette.size()))];
+}
+
+// Recursion is depth-1 by construction: it only fires for aggregators whose
+// default_base_url is non-empty, and that call takes the base_url branch.
+// NOLINTNEXTLINE(misc-no-recursion)
+QString ProviderCatalog::chat_endpoint(const QString& provider, const QString& base_url, const QString& model) {
+ const QString p = provider.toLower();
+ if (p == "fincept") return {}; // caller composes AppConfig::api_base_url() + "/research/chat"
+
+ if (!base_url.isEmpty()) {
+ QString base = base_url;
+ while (base.endsWith('/')) base.chop(1);
+ const QString suffix = (p == "anthropic") ? QStringLiteral("/messages")
+ : QStringLiteral("/chat/completions");
+ if (base.endsWith(suffix)) return base;
+ static const QRegularExpression re(QStringLiteral("/v\\d+[a-zA-Z]*$"));
+ if (re.match(base).hasMatch()) return base + suffix;
+ return base + QStringLiteral("/v1") + suffix;
+ }
+ if (p == "openai") return "https://api.openai.com/v1/chat/completions";
+ if (p == "anthropic") return "https://api.anthropic.com/v1/messages";
+ if (p == "gemini" || p == "google")
+ return "https://generativelanguage.googleapis.com/v1beta/models/" + model + ":generateContent";
+ if (p == "groq") return "https://api.groq.com/openai/v1/chat/completions";
+ if (p == "deepseek") return "https://api.deepseek.com/v1/chat/completions";
+ if (p == "openrouter") return "https://openrouter.ai/api/v1/chat/completions";
+ if (p == "minimax") return "https://api.minimax.io/v1/chat/completions";
+ if (p == "kimi") return "https://api.moonshot.ai/v1/chat/completions";
+ if (p == "ollama") return "http://localhost:11434/v1/chat/completions";
+ if (p == "xai") return "https://api.x.ai/v1/chat/completions";
+ const QString def = default_base_url(p);
+ if (!def.isEmpty()) return chat_endpoint(p, def, model);
+ return {};
+}
+
+} // namespace fincept::ai_chat
diff --git a/fincept-qt/src/services/llm/ProviderCatalog.h b/fincept-qt/src/services/llm/ProviderCatalog.h
new file mode 100644
index 000000000..0c03f34e3
--- /dev/null
+++ b/fincept-qt/src/services/llm/ProviderCatalog.h
@@ -0,0 +1,29 @@
+#pragma once
+// ProviderCatalog — static metadata for every known LLM provider: ids, fallback
+// model lists, default base URLs, key requirements, brand colors, and chat
+// endpoint composition. Single source of truth shared by Settings UI
+// (LlmConfigSection) and the Alpha Arena model registry. Data moved verbatim
+// from LlmConfigSection.cpp (2026-06-10); update HERE when adding a provider.
+
+#include <QString>
+#include <QStringList>
+
+namespace fincept::ai_chat {
+
+class ProviderCatalog {
+ public:
+ static const QStringList& known_providers();
+ static QString display_name(const QString& provider_id);
+ static QStringList fallback_models(const QString& provider);
+ static QString default_base_url(const QString& provider);
+ static bool requires_api_key(const QString& provider); // false: ollama, fincept
+ static bool is_openai_compatible(const QString& provider); // everything except anthropic/gemini/fincept
+ /// Brand color used for arena agent identity (hex, e.g. "#10A37F").
+ static QString brand_color(const QString& provider);
+ /// Full chat-completions endpoint. Mirrors LlmService::get_endpoint_url rules:
+ /// custom base_url wins (appends /v1 + suffix unless already versioned/full);
+ /// fincept is handled by the CALLER (needs AppConfig) — returns empty for it.
+ static QString chat_endpoint(const QString& provider, const QString& base_url, const QString& model);
+};
+
+} // namespace fincept::ai_chat
diff --git a/fincept-qt/src/storage/repositories/OrderBasketRepository.cpp b/fincept-qt/src/storage/repositories/OrderBasketRepository.cpp
new file mode 100644
index 000000000..d2497b7e2
--- /dev/null
+++ b/fincept-qt/src/storage/repositories/OrderBasketRepository.cpp
@@ -0,0 +1,74 @@
+#include "storage/repositories/OrderBasketRepository.h"
+
+#include "core/logging/Logger.h"
+#include "trading/ActionCenter.h"
+
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QSqlQuery>
+#include <QUuid>
+
+namespace fincept {
+
+namespace {
+
+QString legs_to_json(const QVector<trading::UnifiedOrder>& legs) {
+ QJsonArray arr;
+ for (const auto& leg : legs)
+ arr.append(trading::ActionCenter::serialize_unified_order(leg));
+ return QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact));
+}
+
+QVector<trading::UnifiedOrder> legs_from_json(const QString& json) {
+ QVector<trading::UnifiedOrder> legs;
+ const auto doc = QJsonDocument::fromJson(json.toUtf8());
+ for (const auto& v : doc.array())
+ legs.append(trading::ActionCenter::deserialize_unified_order(v.toObject()));
+ return legs;
+}
+
+} // namespace
+
+OrderBasketRepository& OrderBasketRepository::instance() {
+ static OrderBasketRepository inst;
+ return inst;
+}
+
+QVector<OrderBasket> OrderBasketRepository::list_all() const {
+ QVector<OrderBasket> out;
+ auto r = db().execute("SELECT id, name, legs FROM order_baskets ORDER BY name", {});
+ if (r.is_err()) {
+ LOG_ERROR("BasketRepo", QString("list_all failed: %1").arg(QString::fromStdString(r.error())));
+ return out;
+ }
+ auto& q = r.value();
+ while (q.next()) {
+ OrderBasket b;
+ b.id = q.value(0).toString();
+ b.name = q.value(1).toString();
+ b.legs = legs_from_json(q.value(2).toString());
+ out.append(b);
+ }
+ return out;
+}
+
+OrderBasket OrderBasketRepository::save(OrderBasket basket) {
+ if (basket.id.isEmpty())
+ basket.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ auto r = db().execute("INSERT INTO order_baskets (id, name, legs) VALUES (?, ?, ?) "
+ "ON CONFLICT(id) DO UPDATE SET name = excluded.name, legs = excluded.legs, "
+ "updated_at = datetime('now')",
+ {basket.id, basket.name, legs_to_json(basket.legs)});
+ if (r.is_err())
+ LOG_ERROR("BasketRepo", QString("save failed: %1").arg(QString::fromStdString(r.error())));
+ return basket;
+}
+
+void OrderBasketRepository::remove(const QString& id) {
+ auto r = db().execute("DELETE FROM order_baskets WHERE id = ?", {id});
+ if (r.is_err())
+ LOG_ERROR("BasketRepo", QString("remove failed: %1").arg(QString::fromStdString(r.error())));
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/repositories/OrderBasketRepository.h b/fincept-qt/src/storage/repositories/OrderBasketRepository.h
new file mode 100644
index 000000000..2a9931eb9
--- /dev/null
+++ b/fincept-qt/src/storage/repositories/OrderBasketRepository.h
@@ -0,0 +1,35 @@
+#pragma once
+// OrderBasketRepository — persistence for Zerodha-style saved order baskets.
+// A basket is a named group of order legs; legs are stored as a JSON array in
+// the ActionCenter::serialize_unified_order shape so the same encoding handles
+// queueing, baskets, and any future order persistence.
+
+#include "storage/repositories/BaseRepository.h"
+#include "trading/TradingTypes.h"
+
+#include <QString>
+#include <QVector>
+
+namespace fincept {
+
+struct OrderBasket {
+ QString id; // UUID
+ QString name; // user label, e.g. "Nifty Core 5"
+ QVector<trading::UnifiedOrder> legs;
+};
+
+class OrderBasketRepository : public BaseRepository<OrderBasket> {
+ public:
+ static OrderBasketRepository& instance();
+
+ QVector<OrderBasket> list_all() const;
+ /// Insert when basket.id is empty (a UUID is assigned), update otherwise.
+ /// Returns the persisted basket (with id set).
+ OrderBasket save(OrderBasket basket);
+ void remove(const QString& id);
+
+ private:
+ OrderBasketRepository() = default;
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
index e372ae921..e174de9d1 100644
--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
@@ -94,5 +94,8 @@ void register_migration_v044();
void register_migration_v045();
void register_migration_v046();
void register_migration_v047();
+void register_migration_v048();
+void register_migration_v049();
+void register_migration_v050();
} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v048_instruments_exchange_unique.cpp b/fincept-qt/src/storage/sqlite/migrations/v048_instruments_exchange_unique.cpp
new file mode 100644
index 000000000..892237249
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v048_instruments_exchange_unique.cpp
@@ -0,0 +1,106 @@
+// v048_instruments_exchange_unique — fix Dhan securityId collisions.
+//
+// Dhan reuses the same numeric securityId across exchange segments: e.g. 2885 is
+// both RELIANCE on NSE_EQ and an (expired) EURINR currency option on CDS; 11536 is
+// TCS and a GBPUSD option. ~20k ids in the scrip master are shared by >1 segment.
+// The instruments table enforced UNIQUE(instrument_token, broker_id) with INSERT
+// OR IGNORE, and the master lists currency/commodity options before equities, so
+// the option won and the colliding equity row was silently dropped — wiping
+// RELIANCE/TCS/INFY/HDFCBANK/… from the Dhan cache and breaking every quote/chart/
+// orderbook resolution (only non-colliding ids like JSWSTEEL=11723 worked).
+//
+// The securityId IS unique per (exchange-segment), so widen the uniqueness key to
+// include `exchange`. SQLite can't ALTER a UNIQUE constraint, so rebuild the table.
+// Rows for numeric-globally-unique brokers (Fyers/Zerodha/…) are preserved
+// verbatim; Dhan rows are intentionally NOT copied so the next focus re-downloads a
+// complete master under the corrected key (the cache only refreshes when empty).
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+static Result<void> sql(QSqlDatabase& db, const char* stmt) {
+ QSqlQuery q(db);
+ if (!q.exec(stmt))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+Result<void> apply_v048(QSqlDatabase& db) {
+ // 1. Move the existing table aside.
+ auto r = sql(db, "ALTER TABLE instruments RENAME TO instruments_old_v048");
+ if (r.is_err())
+ return r;
+
+ // 2. Recreate with the widened uniqueness key (instrument_token, exchange, broker_id).
+ r = sql(db,
+ "CREATE TABLE instruments ("
+ " id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ " instrument_token INTEGER NOT NULL,"
+ " exchange_token INTEGER NOT NULL DEFAULT 0,"
+ " symbol TEXT NOT NULL,"
+ " brsymbol TEXT NOT NULL,"
+ " name TEXT NOT NULL DEFAULT '',"
+ " exchange TEXT NOT NULL,"
+ " brexchange TEXT NOT NULL DEFAULT '',"
+ " expiry TEXT NOT NULL DEFAULT '',"
+ " strike REAL NOT NULL DEFAULT 0,"
+ " lot_size INTEGER NOT NULL DEFAULT 1,"
+ " instrument_type TEXT NOT NULL DEFAULT 'EQ',"
+ " tick_size REAL NOT NULL DEFAULT 0.05,"
+ " broker_id TEXT NOT NULL,"
+ " updated_at TEXT DEFAULT (datetime('now')),"
+ " broker_token TEXT NOT NULL DEFAULT '',"
+ " UNIQUE(instrument_token, exchange, broker_id)"
+ ")");
+ if (r.is_err())
+ return r;
+
+ // 3. Copy every broker EXCEPT dhan (whose old rows are collision-corrupted —
+ // let it re-download a fresh, complete master under the new key).
+ r = sql(db,
+ "INSERT OR IGNORE INTO instruments "
+ "(instrument_token, exchange_token, symbol, brsymbol, name, exchange, brexchange, "
+ " expiry, strike, lot_size, instrument_type, tick_size, broker_id, updated_at, broker_token) "
+ "SELECT instrument_token, exchange_token, symbol, brsymbol, name, exchange, brexchange, "
+ " expiry, strike, lot_size, instrument_type, tick_size, broker_id, updated_at, broker_token "
+ "FROM instruments_old_v048 WHERE broker_id <> 'dhan'");
+ if (r.is_err())
+ return r;
+
+ // 4. Drop the old table.
+ r = sql(db, "DROP TABLE instruments_old_v048");
+ if (r.is_err())
+ return r;
+
+ // 5. Recreate the indices (they vanished with the old table).
+ for (const char* idx : {
+ "CREATE INDEX IF NOT EXISTS idx_inst_symbol ON instruments(symbol, exchange, broker_id)",
+ "CREATE INDEX IF NOT EXISTS idx_inst_token ON instruments(instrument_token, broker_id)",
+ "CREATE INDEX IF NOT EXISTS idx_inst_brsymbol ON instruments(brsymbol, brexchange, broker_id)",
+ "CREATE INDEX IF NOT EXISTS idx_inst_exchange ON instruments(exchange, broker_id, instrument_type)",
+ "CREATE INDEX IF NOT EXISTS idx_inst_name ON instruments(name, broker_id)",
+ }) {
+ r = sql(db, idx);
+ if (r.is_err())
+ return r;
+ }
+
+ return Result<void>::ok();
+}
+
+} // namespace
+
+void register_migration_v048() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({48, "instruments_exchange_unique", apply_v048});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v049_order_baskets.cpp b/fincept-qt/src/storage/sqlite/migrations/v049_order_baskets.cpp
new file mode 100644
index 000000000..4e47a7928
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v049_order_baskets.cpp
@@ -0,0 +1,38 @@
+// v049_order_baskets — Zerodha-style saved order baskets, broker-agnostic.
+// A basket is a named group of order legs (symbol/side/qty/type/price/product)
+// stored as JSON (ActionCenter::serialize_unified_order shape). Execution is
+// per-account at runtime via UnifiedTrading::place_basket_orders, so the same
+// basket runs on any broker — or several at once.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+Result<void> apply_v049(QSqlDatabase& db) {
+ QSqlQuery q(db);
+ if (!q.exec("CREATE TABLE IF NOT EXISTS order_baskets ("
+ " id TEXT PRIMARY KEY," // UUID
+ " name TEXT NOT NULL,"
+ " legs TEXT NOT NULL DEFAULT '[]'," // JSON array of serialized UnifiedOrders
+ " created_at TEXT DEFAULT (datetime('now')),"
+ " updated_at TEXT DEFAULT (datetime('now'))"
+ ")"))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+} // namespace
+
+void register_migration_v049() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({49, "order_baskets", apply_v049});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v050_alpha_arena_rewrite.cpp b/fincept-qt/src/storage/sqlite/migrations/v050_alpha_arena_rewrite.cpp
new file mode 100644
index 000000000..ca930e81e
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v050_alpha_arena_rewrite.cpp
@@ -0,0 +1,118 @@
+// v050_alpha_arena_rewrite — ground-up Alpha Arena rebuild.
+//
+// Drops every v024 aa_* table (the feature was non-functional: model picker
+// never saw the Providers config layer, paper venue had no market data) and
+// creates the new arena_* schema. Old competition data is intentionally not
+// migrated. Spec: docs/superpowers/specs/2026-06-10-alpha-arena-rewrite-design.md §4.
+//
+// NOTE: assigned version 50 (not 49 as in the spec draft) because the
+// concurrently-developed v049_order_baskets migration already occupies version
+// 49 and the register_migration_v049() symbol in this tree.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+static Result<void> sql(QSqlDatabase& db, const char* stmt) {
+ QSqlQuery q(db);
+ if (!q.exec(stmt))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+Result<void> apply_v050(QSqlDatabase& db) {
+ for (const char* stmt : {
+ // Drop the old aa_* schema (children before parents). v024 data is not migrated.
+ "DROP TABLE IF EXISTS aa_hitl_approvals",
+ "DROP TABLE IF EXISTS aa_events",
+ "DROP TABLE IF EXISTS aa_pnl_snapshots",
+ "DROP TABLE IF EXISTS aa_positions",
+ "DROP TABLE IF EXISTS aa_fills",
+ "DROP TABLE IF EXISTS aa_orders",
+ "DROP TABLE IF EXISTS aa_decisions",
+ "DROP TABLE IF EXISTS aa_ticks",
+ "DROP TABLE IF EXISTS aa_prompts",
+ "DROP TABLE IF EXISTS aa_agents",
+ "DROP TABLE IF EXISTS aa_competitions",
+ }) {
+ auto r = sql(db, stmt);
+ if (r.is_err()) return r;
+ }
+ for (const char* stmt : {
+ "CREATE TABLE IF NOT EXISTS arena_competitions ("
+ " id TEXT PRIMARY KEY, name TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'created',"
+ " venue TEXT NOT NULL DEFAULT 'paper', instruments_json TEXT NOT NULL DEFAULT '[]',"
+ " capital_per_agent REAL NOT NULL DEFAULT 10000, cadence_seconds INTEGER NOT NULL DEFAULT 180,"
+ " max_leverage REAL NOT NULL DEFAULT 10, system_prompt_override TEXT NOT NULL DEFAULT '',"
+ " live_mode INTEGER NOT NULL DEFAULT 0,"
+ " created_at INTEGER NOT NULL DEFAULT 0, started_at INTEGER NOT NULL DEFAULT 0,"
+ " ended_at INTEGER NOT NULL DEFAULT 0)",
+ "CREATE TABLE IF NOT EXISTS arena_agents ("
+ " id TEXT PRIMARY KEY, competition_id TEXT NOT NULL, provider TEXT NOT NULL,"
+ " model_id TEXT NOT NULL, display_name TEXT NOT NULL, color_hex TEXT NOT NULL DEFAULT '',"
+ " source_kind TEXT NOT NULL DEFAULT 'provider', source_ref TEXT NOT NULL DEFAULT '',"
+ " status TEXT NOT NULL DEFAULT 'active', halt_reason TEXT NOT NULL DEFAULT '',"
+ " consecutive_failures INTEGER NOT NULL DEFAULT 0)",
+ "CREATE TABLE IF NOT EXISTS arena_rounds ("
+ " competition_id TEXT NOT NULL, seq INTEGER NOT NULL, started_at INTEGER NOT NULL DEFAULT 0,"
+ " completed_at INTEGER NOT NULL DEFAULT 0, market_snapshot_json TEXT NOT NULL DEFAULT '',"
+ " status TEXT NOT NULL DEFAULT 'running', PRIMARY KEY (competition_id, seq))",
+ "CREATE TABLE IF NOT EXISTS arena_decisions ("
+ " id TEXT PRIMARY KEY, competition_id TEXT NOT NULL, agent_id TEXT NOT NULL,"
+ " round_seq INTEGER NOT NULL, system_prompt TEXT NOT NULL DEFAULT '',"
+ " user_prompt TEXT NOT NULL DEFAULT '', raw_response TEXT NOT NULL DEFAULT '',"
+ " actions_json TEXT NOT NULL DEFAULT '[]', parse_error TEXT NOT NULL DEFAULT '',"
+ " status TEXT NOT NULL DEFAULT 'ok', latency_ms INTEGER NOT NULL DEFAULT 0,"
+ " prompt_tokens INTEGER NOT NULL DEFAULT 0, completion_tokens INTEGER NOT NULL DEFAULT 0,"
+ " ts INTEGER NOT NULL DEFAULT 0)",
+ "CREATE TABLE IF NOT EXISTS arena_orders ("
+ " id TEXT PRIMARY KEY, competition_id TEXT NOT NULL, agent_id TEXT NOT NULL,"
+ " round_seq INTEGER NOT NULL, coin TEXT NOT NULL, side TEXT NOT NULL DEFAULT '',"
+ " action TEXT NOT NULL, qty REAL NOT NULL DEFAULT 0, price REAL NOT NULL DEFAULT 0,"
+ " notional_usd REAL NOT NULL DEFAULT 0, leverage REAL NOT NULL DEFAULT 1,"
+ " fee REAL NOT NULL DEFAULT 0, realized_pnl REAL NOT NULL DEFAULT 0,"
+ " status TEXT NOT NULL DEFAULT 'filled', reject_reason TEXT NOT NULL DEFAULT '',"
+ " ts INTEGER NOT NULL DEFAULT 0)",
+ "CREATE TABLE IF NOT EXISTS arena_positions ("
+ " competition_id TEXT NOT NULL, agent_id TEXT NOT NULL, coin TEXT NOT NULL,"
+ " side TEXT NOT NULL, qty REAL NOT NULL DEFAULT 0, entry_price REAL NOT NULL DEFAULT 0,"
+ " leverage REAL NOT NULL DEFAULT 1, funding_accrued REAL NOT NULL DEFAULT 0,"
+ " PRIMARY KEY (competition_id, agent_id, coin))",
+ "CREATE TABLE IF NOT EXISTS arena_accounts ("
+ " competition_id TEXT NOT NULL, agent_id TEXT NOT NULL, balance REAL NOT NULL DEFAULT 0,"
+ " PRIMARY KEY (competition_id, agent_id))",
+ "CREATE TABLE IF NOT EXISTS arena_equity_snapshots ("
+ " competition_id TEXT NOT NULL, agent_id TEXT NOT NULL, round_seq INTEGER NOT NULL,"
+ " ts INTEGER NOT NULL DEFAULT 0, equity REAL NOT NULL DEFAULT 0,"
+ " balance REAL NOT NULL DEFAULT 0, unrealized_pnl REAL NOT NULL DEFAULT 0,"
+ " PRIMARY KEY (competition_id, agent_id, round_seq))",
+ "CREATE TABLE IF NOT EXISTS arena_events ("
+ " seq INTEGER PRIMARY KEY AUTOINCREMENT, competition_id TEXT NOT NULL DEFAULT '',"
+ " agent_id TEXT NOT NULL DEFAULT '', type TEXT NOT NULL, payload_json TEXT NOT NULL DEFAULT '{}',"
+ " ts INTEGER NOT NULL DEFAULT 0)",
+ "CREATE INDEX IF NOT EXISTS idx_arena_agents_comp ON arena_agents(competition_id)",
+ "CREATE INDEX IF NOT EXISTS idx_arena_decisions_comp ON arena_decisions(competition_id, agent_id, round_seq)",
+ "CREATE INDEX IF NOT EXISTS idx_arena_orders_comp ON arena_orders(competition_id, agent_id, round_seq)",
+ "CREATE INDEX IF NOT EXISTS idx_arena_equity_comp ON arena_equity_snapshots(competition_id, round_seq)",
+ "CREATE INDEX IF NOT EXISTS idx_arena_events_comp ON arena_events(competition_id, seq)",
+ }) {
+ auto r = sql(db, stmt);
+ if (r.is_err()) return r;
+ }
+ return Result<void>::ok();
+}
+
+} // namespace
+
+void register_migration_v050() {
+ static bool done = false;
+ if (done) return;
+ done = true;
+ MigrationRunner::register_migration({50, "alpha_arena_rewrite", apply_v050});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/trading/AccountDataStream.cpp b/fincept-qt/src/trading/AccountDataStream.cpp
index aef137df8..ba321a917 100644
--- a/fincept-qt/src/trading/AccountDataStream.cpp
+++ b/fincept-qt/src/trading/AccountDataStream.cpp
@@ -742,6 +742,19 @@ void AccountDataStream::wire_base_ws(BrokerWebSocketBase* ws) {
connect(ws, &BrokerWebSocketBase::depth_received, this, [this](const MarketDepth& d) {
if (d.bids.isEmpty() && d.asks.isEmpty())
return;
+ // FULL-mode feeds (e.g. Dhan) stream depth for EVERY subscribed watchlist
+ // symbol, but the depth table is single-symbol. Drop books that aren't for
+ // the selected symbol, else every stock's book rotates through the table.
+ // Guarded on a populated d.symbol so brokers that don't tag depth are unaffected.
+ auto bare = [](QString s) {
+ const int colon = s.lastIndexOf(QLatin1Char(':'));
+ if (colon >= 0) s = s.mid(colon + 1);
+ if (s.endsWith(QLatin1String("-EQ"))) s.chop(3);
+ return s;
+ };
+ if (!selected_symbol_.isEmpty() && !d.symbol.isEmpty() &&
+ bare(d.symbol).compare(bare(selected_symbol_), Qt::CaseInsensitive) != 0)
+ return;
QVector<QPair<double, double>> bids, asks;
for (const auto& b : d.bids)
bids.append({b.price, static_cast<double>(b.quantity)});
@@ -982,11 +995,41 @@ void AccountDataStream::ws_init() {
q.change_pct = tick.close > 0 ? (tick.ltp - tick.close) / tick.close * 100.0 : 0.0;
q.oi = tick.oi;
q.timestamp = tick.exchange_timestamp.isValid() ? tick.exchange_timestamp.toMSecsSinceEpoch() : 0;
+ // Market depth arrives only on the 184-byte "full" packet (the selected
+ // symbol is subscribed in full mode; the rest stay "quote" for latency).
+ const bool has_depth = tick.bids[0].price > 0.0 || tick.asks[0].price > 0.0;
+ if (has_depth) {
+ q.bid = tick.bids[0].price; // best bid/ask feed the ticker + order matcher
+ q.ask = tick.asks[0].price;
+ }
quote_cache_[q.symbol] = q;
emit quote_updated(account_id_, q.symbol, q);
+
+ // Publish the 5-level order book for the selected symbol (single-symbol
+ // depth table). Only the full-mode symbol carries depth, so this fires
+ // for it alone; the selected-symbol guard mirrors the Fyers path.
+ if (has_depth && q.symbol.compare(selected_symbol_, Qt::CaseInsensitive) == 0) {
+ QVector<QPair<double, double>> bids, asks;
+ QVector<int> bid_orders, ask_orders;
+ for (const auto& b : tick.bids)
+ if (b.price > 0.0) { bids.append({b.price, double(b.quantity)}); bid_orders.append(b.orders); }
+ for (const auto& a : tick.asks)
+ if (a.price > 0.0) { asks.append({a.price, double(a.quantity)}); ask_orders.append(a.orders); }
+ const double best_bid = bids.isEmpty() ? 0.0 : bids.first().first;
+ const double best_ask = asks.isEmpty() ? 0.0 : asks.first().first;
+ double spread = 0.0, spread_pct = 0.0;
+ if (best_bid > 0.0 && best_ask > 0.0) {
+ spread = best_ask - best_bid;
+ spread_pct = (spread / best_bid) * 100.0;
+ }
+ LOG_INFO(ADS_TAG, QString("Zerodha WS depth: %1 bids, %2 asks for %3")
+ .arg(bids.size()).arg(asks.size()).arg(q.symbol));
+ emit orderbook_fetched(account_id_, bids, asks, spread, spread_pct, bid_orders, ask_orders);
+ }
});
connect(zws, &ZerodhaWebSocket::connected, this, [this]() {
LOG_INFO(ADS_TAG, QString("Zerodha WS connected for %1").arg(account_id_));
+ ws_permission_denied_ = false; // streaming is permitted after all
emit connection_state_changed(account_id_, ConnectionState::Connected);
ws_resubscribe(); // resolves current symbols → tokens and subscribes
});
@@ -995,6 +1038,36 @@ void AccountDataStream::ws_init() {
});
connect(zws, &ZerodhaWebSocket::error_occurred, this, [this](const QString& e) {
LOG_ERROR(ADS_TAG, QString("Zerodha WS error: %1").arg(e));
+ // A 403/Forbidden on the KiteTicker handshake is a permission verdict,
+ // not a transient network error: Kite refuses the streaming socket when
+ // the API key has no active Kite Connect (market-data) subscription —
+ // even though the *same* access_token authenticates the REST account
+ // APIs (profile/holdings 200, /quote and ws.kite.trade 403). The retry
+ // loop is futile and otherwise leaves the user staring at blank quote
+ // tables, so surface the cause once via the account's Error state.
+ if (!ws_permission_denied_ &&
+ (e.contains(QStringLiteral("403")) ||
+ e.contains(QStringLiteral("Forbidden"), Qt::CaseInsensitive))) {
+ ws_permission_denied_ = true;
+ QPointer<AccountDataStream> self = this;
+ QMetaObject::invokeMethod(this, [self]() {
+ if (!self)
+ return;
+ const QString msg = QStringLiteral(
+ "Live market data unavailable — Kite refused the streaming "
+ "connection (403). This Kite API key has no active Kite Connect "
+ "subscription. Account data still works; live quotes and "
+ "streaming require an active Kite Connect plan for this key.");
+ AccountManager::instance().set_connection_state(
+ self->account_id_, ConnectionState::Error, msg);
+ LOG_WARN(ADS_TAG,
+ QString("Zerodha streaming denied (403) for %1 — no Kite "
+ "Connect market-data subscription for this API key")
+ .arg(self->account_id_));
+ emit self->connection_state_changed(self->account_id_, ConnectionState::Error);
+ }, Qt::QueuedConnection);
+ return;
+ }
check_token_expiry(e);
});
zws->open();
@@ -1402,6 +1475,16 @@ void AccountDataStream::ws_resubscribe() {
if (tok.has_value() && *tok > 0)
tokens.append(static_cast<quint32>(*tok));
}
+ // Subscribe the selected symbol in "full" mode (5-level depth for the order
+ // book); every other symbol stays "quote" (lighter, no depth) for latency.
+ quint32 sel_token = 0;
+ if (!selected_symbol_.isEmpty()) {
+ const QString exch = selected_exchange_.isEmpty() ? QStringLiteral("NSE") : selected_exchange_;
+ auto t = svc.instrument_token(selected_symbol_, exch, broker_id_);
+ if (t.has_value() && *t > 0)
+ sel_token = static_cast<quint32>(*t);
+ }
+ zws->set_full_mode_token(sel_token);
zws->set_subscriptions(tokens);
return;
}
diff --git a/fincept-qt/src/trading/AccountDataStream.h b/fincept-qt/src/trading/AccountDataStream.h
index 1befc8d88..5625d4747 100644
--- a/fincept-qt/src/trading/AccountDataStream.h
+++ b/fincept-qt/src/trading/AccountDataStream.h
@@ -146,6 +146,11 @@ class AccountDataStream : public QObject {
// WebSocket — polymorphic, null for brokers without WS
QObject* ws_ = nullptr;
+ // Latches once the streaming socket is refused with a permission verdict
+ // (e.g. Kite 403 — API key has no active Connect/market-data subscription)
+ // so the failure is surfaced to the user exactly once, not on every retry.
+ // Reset when the socket reconnects.
+ bool ws_permission_denied_ = false;
// Polling timers
QTimer* quote_timer_ = nullptr;
diff --git a/fincept-qt/src/trading/PortfolioMonitorSelftest.cpp b/fincept-qt/src/trading/PortfolioMonitorSelftest.cpp
new file mode 100644
index 000000000..6959c3f71
--- /dev/null
+++ b/fincept-qt/src/trading/PortfolioMonitorSelftest.cpp
@@ -0,0 +1,202 @@
+// Headless self-test of the UnifiedPortfolioService merge layer (no GUI /
+// network / broker / keys). Asserts: per-(symbol,exchange) grouping, weighted
+// average price, signed-quantity netting across accounts, summed P&L, the
+// non-INR account exclusion, quote-tick patching, and summary math.
+//
+// Run: QT_QPA_PLATFORM=offscreen FinceptTerminal --selftest-portfolio-monitor
+// Returns 0 when every assertion passes, 1 otherwise.
+
+#include "trading/UnifiedPortfolioService.h"
+
+#include <QString>
+
+#include <cmath>
+#include <cstdio>
+
+namespace fincept::trading {
+
+namespace {
+bool approx(double a, double b, double eps = 0.01) {
+ return std::fabs(a - b) <= eps;
+}
+
+const AggRow* find_row(const QVector<AggRow>& rows, const QString& symbol) {
+ for (const auto& r : rows)
+ if (r.symbol == symbol)
+ return &r;
+ return nullptr;
+}
+} // namespace
+
+int run_portfolio_monitor_selftest() {
+ int failures = 0;
+ auto check = [&](const char* label, bool ok) {
+ std::printf("[%s] %s\n", ok ? "PASS" : "FAIL", label);
+ if (!ok)
+ ++failures;
+ };
+
+ auto& svc = UnifiedPortfolioService::instance();
+ svc.test_clear();
+ svc.test_register_account("acct-fyers", "Fyers — T", "INR");
+ svc.test_register_account("acct-dhan", "Dhan — T", "INR");
+ svc.test_register_account("acct-alpaca", "Alpaca — US", "USD"); // must be excluded
+
+ check("non-INR account excluded", svc.accounts().size() == 2);
+
+ // The default mode is Paper; the live-merge assertions below need Live.
+ svc.set_mode(UnifiedPortfolioService::Mode::Live);
+ check("mode switched to live", svc.mode() == UnifiedPortfolioService::Mode::Live);
+
+ // ── Positions: same symbol in two accounts ───────────────────────────────
+ BrokerPosition p1; // long 10 @ 1280 on Fyers
+ p1.symbol = "RELIANCE";
+ p1.exchange = "NSE";
+ p1.product_type = "MIS";
+ p1.quantity = 10;
+ p1.avg_price = 1280;
+ p1.ltp = 1300;
+ p1.pnl = 200;
+ p1.side = "LONG";
+
+ BrokerPosition p2; // long 5 @ 1296 on Dhan
+ p2.symbol = "RELIANCE";
+ p2.exchange = "NSE";
+ p2.product_type = "INTRADAY";
+ p2.quantity = 5;
+ p2.avg_price = 1296;
+ p2.ltp = 1300;
+ p2.pnl = 20;
+ p2.side = "LONG";
+
+ BrokerPosition p3; // unrelated symbol, only on Dhan
+ p3.symbol = "TCS";
+ p3.exchange = "NSE";
+ p3.quantity = 2;
+ p3.avg_price = 3400;
+ p3.ltp = 3380;
+ p3.pnl = -40;
+ p3.side = "LONG";
+
+ svc.ingest_positions("acct-fyers", {p1});
+ svc.ingest_positions("acct-dhan", {p2, p3});
+ // Ingest for an untracked account must be ignored.
+ svc.ingest_positions("acct-alpaca", {p3});
+
+ const auto positions = svc.positions();
+ check("two merged position rows", positions.size() == 2);
+
+ const AggRow* rel = find_row(positions, "RELIANCE");
+ check("RELIANCE row exists", rel != nullptr);
+ if (rel) {
+ check("RELIANCE has 2 children", rel->children.size() == 2);
+ check("RELIANCE total qty 15", approx(rel->total_qty, 15));
+ // weighted avg = (10*1280 + 5*1296) / 15 = 1285.33
+ check("RELIANCE weighted avg", approx(rel->w_avg_price, 1285.33, 0.01));
+ check("RELIANCE pnl summed", approx(rel->pnl, 220));
+ }
+
+ // ── Short netting: long 10 in one account, short 10 in another ───────────
+ BrokerPosition s1;
+ s1.symbol = "INFY";
+ s1.exchange = "NSE";
+ s1.quantity = 10;
+ s1.avg_price = 1500;
+ s1.side = "LONG";
+ BrokerPosition s2;
+ s2.symbol = "INFY";
+ s2.exchange = "NSE";
+ s2.quantity = 10; // unsigned with SHORT side → counts as -10
+ s2.avg_price = 1510;
+ s2.side = "SHORT";
+ svc.ingest_positions("acct-fyers", {p1, s1});
+ svc.ingest_positions("acct-dhan", {p2, p3, s2});
+ const AggRow* infy = find_row(svc.positions(), "INFY");
+ check("INFY net qty 0 (long+short)", infy && approx(infy->total_qty, 0));
+ check("INFY zero-qty avg guarded", infy && approx(infy->w_avg_price, 1505, 0.01));
+
+ // ── Quote patch updates LTP + recomputes P&L ────────────────────────────
+ BrokerQuote q;
+ q.ltp = 1310;
+ svc.ingest_quote("acct-fyers", "RELIANCE", q);
+ rel = find_row(svc.positions(), "RELIANCE");
+ if (rel) {
+ check("patched parent LTP", approx(rel->ltp, 1310));
+ // Fyers child: (1310-1280)*10 = 300; Dhan child untouched at 20.
+ check("patched pnl sum", approx(rel->pnl, 320));
+ }
+
+ // ── Holdings merge + invested/current ───────────────────────────────────
+ BrokerHolding h1;
+ h1.symbol = "ITC";
+ h1.exchange = "NSE";
+ h1.quantity = 100;
+ h1.avg_price = 400;
+ h1.ltp = 410;
+ h1.invested_value = 40000;
+ h1.current_value = 41000;
+ h1.pnl = 1000;
+ h1.prev_close = 405;
+
+ BrokerHolding h2;
+ h2.symbol = "ITC";
+ h2.exchange = "NSE";
+ h2.quantity = 50;
+ h2.avg_price = 380;
+ h2.ltp = 0; // broker that doesn't hydrate LTP (e.g. Dhan) → derived fields guarded
+ h2.invested_value = 0; // must derive qty*avg = 19000
+ h2.current_value = 0;
+ h2.pnl = 0;
+
+ svc.ingest_holdings("acct-fyers", {h1});
+ svc.ingest_holdings("acct-dhan", {h2});
+
+ const auto holdings = svc.holdings();
+ check("one merged holding row", holdings.size() == 1);
+ const AggRow* itc = find_row(holdings, "ITC");
+ if (itc) {
+ check("ITC qty 150", approx(itc->total_qty, 150));
+ check("ITC invested 59000", approx(itc->invested, 59000));
+ // current: 41000 + 0 (no LTP for child 2 yet)
+ check("ITC current 41000 pre-tick", approx(itc->current, 41000));
+ // day pnl: (410-405)*100 = 500 from child 1 only
+ check("ITC day pnl 500", approx(itc->day_pnl, 500));
+ }
+
+ // A quote tick for the Dhan account hydrates child 2.
+ BrokerQuote q2;
+ q2.ltp = 410;
+ q2.close = 405;
+ svc.ingest_quote("acct-dhan", "ITC", q2);
+ itc = find_row(svc.holdings(), "ITC");
+ if (itc) {
+ check("ITC current hydrated by tick", approx(itc->current, 41000 + 50 * 410.0));
+ check("ITC day pnl includes child 2", approx(itc->day_pnl, 500 + 50 * 5.0));
+ }
+
+ // ── Paper/live separation: switching to Paper must NOT show live rows ───
+ // (test accounts have no paper portfolio, so the paper view is empty even
+ // though the live caches above are populated — proving the views never mix.)
+ svc.set_mode(UnifiedPortfolioService::Mode::Paper);
+ check("paper view empty (no blending of live rows)",
+ svc.positions().isEmpty() && svc.holdings().isEmpty());
+ // Live ingestion while in paper mode must be cached but not displayed.
+ BrokerPosition px_live;
+ px_live.symbol = "SBIN";
+ px_live.exchange = "NSE";
+ px_live.quantity = 5;
+ px_live.avg_price = 1000;
+ px_live.side = "LONG";
+ svc.ingest_positions("acct-fyers", {px_live});
+ check("live ingest hidden in paper mode", svc.positions().isEmpty());
+ svc.set_mode(UnifiedPortfolioService::Mode::Live);
+ check("cached live rows appear after switch back", find_row(svc.positions(), "SBIN") != nullptr);
+
+ svc.test_clear();
+ std::printf(failures == 0 ? "portfolio-monitor selftest: ALL PASS\n"
+ : "portfolio-monitor selftest: %d FAILURE(S)\n",
+ failures);
+ return failures == 0 ? 0 : 1;
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/TradingTypes.h b/fincept-qt/src/trading/TradingTypes.h
index 6034b9c01..e7954c2e5 100644
--- a/fincept-qt/src/trading/TradingTypes.h
+++ b/fincept-qt/src/trading/TradingTypes.h
@@ -310,10 +310,15 @@ struct BrokerHolding {
double quantity = 0;
double avg_price = 0;
double ltp = 0;
- double pnl = 0;
+ double pnl = 0; // overall P&L (current_value - invested_value)
double pnl_pct = 0;
double invested_value = 0;
double current_value = 0;
+ // Previous-day close, for "Today's P&L" = quantity * (ltp - prev_close).
+ // Populated generically from the live quote feed (BrokerQuote.close) so it
+ // works for every broker without per-broker holdings-parser changes; 0 until
+ // the first tick (Today's P&L then shows 0 rather than a wrong number).
+ double prev_close = 0;
};
struct BrokerOrderInfo {
diff --git a/fincept-qt/src/trading/UnifiedPortfolioService.cpp b/fincept-qt/src/trading/UnifiedPortfolioService.cpp
new file mode 100644
index 000000000..02c623d95
--- /dev/null
+++ b/fincept-qt/src/trading/UnifiedPortfolioService.cpp
@@ -0,0 +1,697 @@
+// UnifiedPortfolioService — merge layer between per-account AccountDataStreams
+// and the Portfolio Monitor screen. See header for the contract.
+
+#include "trading/UnifiedPortfolioService.h"
+
+#include "trading/AccountDataStream.h"
+#include "trading/AccountManager.h"
+#include "trading/BrokerRegistry.h"
+#include "trading/DataStreamManager.h"
+#include "trading/OrderMatcher.h"
+#include "trading/PaperTrading.h"
+#include "trading/UnifiedTrading.h"
+
+#include <QMap>
+#include <QPointer>
+#include <QTimer>
+#include <QtConcurrent/QtConcurrent>
+
+#include <cmath>
+
+namespace fincept::trading {
+
+namespace {
+// EquityBottomPanel convention: side carries the sign for brokers that report
+// unsigned quantity; brokers that already sign the quantity (Dhan netQty) pass
+// through unchanged because -|q| == q for q < 0.
+double signed_qty(const QString& side, double qty) {
+ return side.startsWith(QLatin1Char('s'), Qt::CaseInsensitive) ? -std::fabs(qty) : qty;
+}
+} // namespace
+
+UnifiedPortfolioService& UnifiedPortfolioService::instance() {
+ static UnifiedPortfolioService inst;
+ return inst;
+}
+
+UnifiedPortfolioService::UnifiedPortfolioService(QObject* parent) : QObject(parent) {
+ summary_debounce_ = new QTimer(this);
+ summary_debounce_->setSingleShot(true);
+ summary_debounce_->setInterval(500);
+ connect(summary_debounce_, &QTimer::timeout, this, [this]() {
+ recompute_summary();
+ emit summary_changed();
+ });
+}
+
+// ── Account enumeration & wiring ─────────────────────────────────────────────
+
+void UnifiedPortfolioService::activate() {
+ auto& mgr = AccountManager::instance();
+ auto& dsm = DataStreamManager::instance();
+ bool set_changed = false;
+
+ for (const auto& acct : mgr.active_accounts()) {
+ auto* broker = BrokerRegistry::instance().get(acct.broker_id);
+ if (!broker)
+ continue;
+ const auto profile = broker->profile();
+ if (QString(profile.currency) != QLatin1String("INR"))
+ continue; // user-confirmed scope: ₹ brokers only for now
+
+ Acct& a = accts_[acct.account_id];
+ if (a.label.isEmpty()) {
+ a.label = QString("%1 — %2").arg(profile.display_name, acct.display_name);
+ a.broker_id = acct.broker_id;
+ a.default_exchange = profile.default_exchange;
+ set_changed = true;
+ }
+ a.paper_portfolio_id = acct.paper_portfolio_id; // may be set after account creation
+ a.live = acct.state == ConnectionState::Connected || acct.state == ConnectionState::Connecting;
+
+ dsm.start_stream(acct.account_id);
+ connect_stream(acct.account_id);
+
+ // Seed from the stream's cache so the monitor isn't blank until the next
+ // signal; the refresh below brings it current.
+ if (auto* stream = dsm.stream_for(acct.account_id)) {
+ a.positions = stream->cached_positions();
+ a.holdings = stream->cached_holdings();
+ }
+ }
+
+ if (mode_ == Mode::Paper)
+ rebuild_paper();
+ else {
+ rebuild_positions();
+ rebuild_holdings();
+ }
+ schedule_summary();
+ if (set_changed)
+ emit accounts_changed();
+ refresh_all();
+}
+
+void UnifiedPortfolioService::set_mode(Mode mode) {
+ if (mode_ == mode)
+ return;
+ mode_ = mode;
+ if (mode_ == Mode::Paper)
+ rebuild_paper();
+ else {
+ rebuild_positions();
+ rebuild_holdings();
+ }
+ schedule_summary();
+ emit_all_changed();
+}
+
+void UnifiedPortfolioService::emit_all_changed() {
+ emit positions_changed();
+ emit holdings_changed();
+}
+
+void UnifiedPortfolioService::connect_stream(const QString& account_id) {
+ Acct& a = accts_[account_id];
+ if (a.wired)
+ return;
+ auto* stream = DataStreamManager::instance().stream_for(account_id);
+ if (!stream)
+ return;
+ a.wired = true;
+
+ connect(stream, &AccountDataStream::positions_updated, this, &UnifiedPortfolioService::ingest_positions);
+ connect(stream, &AccountDataStream::holdings_updated, this, &UnifiedPortfolioService::ingest_holdings);
+ connect(stream, &AccountDataStream::quote_updated, this, &UnifiedPortfolioService::ingest_quote);
+ connect(stream, &AccountDataStream::connection_state_changed, this,
+ [this](const QString& acct_id, ConnectionState state) {
+ auto it = accts_.find(acct_id);
+ if (it == accts_.end())
+ return;
+ const bool live = state == ConnectionState::Connected || state == ConnectionState::Connecting;
+ if (it->live != live) {
+ it->live = live;
+ schedule_summary();
+ emit accounts_changed();
+ }
+ });
+}
+
+void UnifiedPortfolioService::refresh_all() {
+ if (mode_ == Mode::Paper) {
+ // Paper state lives in the local pt_* engine — re-read and repaint now.
+ // Streams keep running regardless (they mark paper prices via quotes).
+ rebuild_paper();
+ schedule_summary();
+ emit_all_changed();
+ return;
+ }
+ auto& dsm = DataStreamManager::instance();
+ for (auto it = accts_.constBegin(); it != accts_.constEnd(); ++it)
+ dsm.refresh_portfolio(it.key());
+}
+
+QVector<UnifiedPortfolioService::AccountInfo> UnifiedPortfolioService::accounts() const {
+ QVector<AccountInfo> out;
+ out.reserve(accts_.size());
+ for (auto it = accts_.constBegin(); it != accts_.constEnd(); ++it)
+ out.append({it.key(), it->label, it->broker_id, it->default_exchange, it->paper_portfolio_id, it->live});
+ std::sort(out.begin(), out.end(),
+ [](const AccountInfo& x, const AccountInfo& y) { return x.label < y.label; });
+ return out;
+}
+
+// ── Ingestion ────────────────────────────────────────────────────────────────
+
+void UnifiedPortfolioService::ingest_positions(const QString& account_id,
+ const QVector<BrokerPosition>& positions) {
+ auto it = accts_.find(account_id);
+ if (it == accts_.end())
+ return; // not a tracked (INR) account
+ it->positions = positions;
+ if (mode_ != Mode::Live)
+ return; // cache for later; paper view must never blend live rows
+ rebuild_positions();
+ schedule_summary();
+ emit positions_changed();
+}
+
+void UnifiedPortfolioService::ingest_holdings(const QString& account_id,
+ const QVector<BrokerHolding>& holdings) {
+ auto it = accts_.find(account_id);
+ if (it == accts_.end())
+ return;
+ it->holdings = holdings;
+ if (mode_ != Mode::Live)
+ return; // cache for later; paper view must never blend live rows
+ rebuild_holdings();
+ schedule_summary();
+ emit holdings_changed();
+}
+
+// Per-tick patch: O(children of one symbol). Keep this lean — quote ticks are
+// unthrottled on the GUI thread (project hot-path constraint).
+void UnifiedPortfolioService::ingest_quote(const QString& account_id, const QString& symbol,
+ const BrokerQuote& quote) {
+ if (!accts_.contains(account_id) || quote.ltp <= 0.0)
+ return;
+
+ // Paper rows belong to the local engine, not to the broker whose feed the
+ // tick arrived on — any tracked account's quote for the symbol marks them.
+ const bool match_any_account = mode_ == Mode::Paper;
+
+ auto patch = [&](QVector<AggRow>& rows, bool holdings) -> bool {
+ for (AggRow& row : rows) {
+ if (row.symbol != symbol)
+ continue;
+ bool touched = false;
+ double pnl_sum = 0, day_sum = 0, current_sum = 0;
+ for (AggChild& c : row.children) {
+ if (match_any_account || c.account_id == account_id) {
+ c.ltp = quote.ltp;
+ const double sq = signed_qty(c.side, c.qty);
+ c.pnl = (quote.ltp - c.avg_price) * sq;
+ if (holdings) {
+ if (quote.close > 0.0)
+ c.prev_close = quote.close;
+ c.current = quote.ltp * c.qty;
+ c.day_pnl = c.prev_close > 0.0 ? (quote.ltp - c.prev_close) * c.qty : c.day_pnl;
+ }
+ touched = true;
+ }
+ pnl_sum += c.pnl;
+ day_sum += c.day_pnl;
+ current_sum += c.current;
+ }
+ if (touched) {
+ row.ltp = quote.ltp;
+ row.pnl = pnl_sum;
+ row.day_pnl = day_sum;
+ if (holdings)
+ row.current = current_sum;
+ }
+ return touched;
+ }
+ return false;
+ };
+
+ if (patch(positions_, /*holdings=*/false)) {
+ schedule_summary();
+ emit position_patched(symbol);
+ }
+ if (patch(holdings_, /*holdings=*/true)) {
+ schedule_summary();
+ emit holding_patched(symbol);
+ }
+}
+
+// ── Merge ────────────────────────────────────────────────────────────────────
+
+void UnifiedPortfolioService::rebuild_positions() {
+ // QMap keeps rows sorted by symbol for a stable display order.
+ QMap<QPair<QString, QString>, AggRow> merged;
+ for (auto it = accts_.constBegin(); it != accts_.constEnd(); ++it) {
+ for (const BrokerPosition& p : it->positions) {
+ if (p.quantity == 0.0)
+ continue;
+ AggRow& row = merged[{p.symbol, p.exchange}];
+ row.symbol = p.symbol;
+ row.exchange = p.exchange;
+ AggChild c;
+ c.account_id = it.key();
+ c.broker_label = it->label;
+ c.product = p.product_type;
+ c.side = p.side;
+ c.qty = p.quantity;
+ c.avg_price = p.avg_price;
+ c.ltp = p.ltp;
+ c.pnl = p.pnl != 0.0 ? p.pnl
+ : (p.ltp > 0.0 ? (p.ltp - p.avg_price) * signed_qty(p.side, p.quantity) : 0.0);
+ c.day_pnl = p.day_pnl;
+ row.children.append(c);
+ }
+ }
+
+ positions_.clear();
+ positions_.reserve(merged.size());
+ for (AggRow& row : merged) {
+ double abs_qty = 0;
+ for (const AggChild& c : row.children) {
+ const double sq = signed_qty(c.side, c.qty);
+ row.total_qty += sq;
+ row.w_avg_price += c.avg_price * std::fabs(sq);
+ abs_qty += std::fabs(sq);
+ row.pnl += c.pnl;
+ row.day_pnl += c.day_pnl;
+ if (c.ltp > 0.0)
+ row.ltp = c.ltp;
+ }
+ row.w_avg_price = abs_qty > 0.0 ? row.w_avg_price / abs_qty : 0.0;
+ positions_.append(row);
+ }
+}
+
+void UnifiedPortfolioService::rebuild_holdings() {
+ QMap<QPair<QString, QString>, AggRow> merged;
+ for (auto it = accts_.constBegin(); it != accts_.constEnd(); ++it) {
+ for (const BrokerHolding& h : it->holdings) {
+ if (h.quantity == 0.0)
+ continue;
+ AggRow& row = merged[{h.symbol, h.exchange}];
+ row.symbol = h.symbol;
+ row.exchange = h.exchange;
+ AggChild c;
+ c.account_id = it.key();
+ c.broker_label = it->label;
+ c.product = QStringLiteral("CNC");
+ c.qty = h.quantity;
+ c.avg_price = h.avg_price;
+ c.ltp = h.ltp;
+ c.prev_close = h.prev_close;
+ c.invested = h.invested_value > 0.0 ? h.invested_value : h.quantity * h.avg_price;
+ c.current = h.current_value > 0.0 ? h.current_value : (h.ltp > 0.0 ? h.quantity * h.ltp : 0.0);
+ c.pnl = h.pnl != 0.0 ? h.pnl : c.current - c.invested;
+ c.day_pnl = h.prev_close > 0.0 && h.ltp > 0.0 ? (h.ltp - h.prev_close) * h.quantity : 0.0;
+ row.children.append(c);
+ }
+ }
+
+ holdings_.clear();
+ holdings_.reserve(merged.size());
+ for (AggRow& row : merged) {
+ double abs_qty = 0;
+ for (const AggChild& c : row.children) {
+ row.total_qty += c.qty;
+ row.w_avg_price += c.avg_price * std::fabs(c.qty);
+ abs_qty += std::fabs(c.qty);
+ row.pnl += c.pnl;
+ row.day_pnl += c.day_pnl;
+ row.invested += c.invested;
+ row.current += c.current;
+ if (c.ltp > 0.0)
+ row.ltp = c.ltp;
+ }
+ row.w_avg_price = abs_qty > 0.0 ? row.w_avg_price / abs_qty : 0.0;
+ holdings_.append(row);
+ }
+}
+
+// Paper model: every account's pt_* portfolio, CNC rows → holdings (matching the
+// equity tab's storage model: ALL paper exposure lives in pt_positions tagged by
+// product), MIS/NRML rows → positions. Reads fresh from the engine each time.
+void UnifiedPortfolioService::rebuild_paper() {
+ QMap<QPair<QString, QString>, AggRow> pos_merged;
+ QMap<QPair<QString, QString>, AggRow> hold_merged;
+
+ for (auto it = accts_.constBegin(); it != accts_.constEnd(); ++it) {
+ if (it->paper_portfolio_id.isEmpty())
+ continue;
+ for (const PtPosition& p : pt_get_positions(it->paper_portfolio_id)) {
+ if (p.quantity == 0.0)
+ continue;
+ const bool is_holding = p.product.compare(QLatin1String("CNC"), Qt::CaseInsensitive) == 0;
+ // Paper symbols are stored bare; exchange isn't carried on the row, so
+ // group by symbol only (empty exchange) — consistent across accounts.
+ AggRow& row = (is_holding ? hold_merged : pos_merged)[{p.symbol, QString()}];
+ row.symbol = p.symbol;
+
+ AggChild c;
+ c.account_id = it.key();
+ c.broker_label = it->label + QStringLiteral(" (paper)");
+ c.product = p.product;
+ c.side = p.side.toUpper();
+ c.qty = p.quantity;
+ c.avg_price = p.entry_price;
+ c.ltp = p.current_price;
+ c.pnl = p.unrealized_pnl;
+ c.day_pnl = 0.0; // paper engine doesn't track prev-close day P&L
+ if (is_holding) {
+ c.invested = p.quantity * p.entry_price;
+ c.current = p.current_price > 0.0 ? p.quantity * p.current_price : 0.0;
+ }
+ row.children.append(c);
+ }
+ }
+
+ auto finalize = [](QMap<QPair<QString, QString>, AggRow>& merged, QVector<AggRow>& out) {
+ out.clear();
+ out.reserve(merged.size());
+ for (AggRow& row : merged) {
+ double abs_qty = 0;
+ for (const AggChild& c : row.children) {
+ const double sq = signed_qty(c.side, c.qty);
+ row.total_qty += sq;
+ row.w_avg_price += c.avg_price * std::fabs(sq);
+ abs_qty += std::fabs(sq);
+ row.pnl += c.pnl;
+ row.day_pnl += c.day_pnl;
+ row.invested += c.invested;
+ row.current += c.current;
+ if (c.ltp > 0.0)
+ row.ltp = c.ltp;
+ }
+ row.w_avg_price = abs_qty > 0.0 ? row.w_avg_price / abs_qty : 0.0;
+ out.append(row);
+ }
+ };
+ finalize(pos_merged, positions_);
+ finalize(hold_merged, holdings_);
+}
+
+void UnifiedPortfolioService::schedule_summary() {
+ // Throttle, NOT debounce: restarting the timer on every tick starves the
+ // summary under a continuous quote stream (it would never fire), leaving the
+ // header frozen at stale totals while the rows keep moving.
+ if (!summary_debounce_->isActive())
+ summary_debounce_->start();
+}
+
+void UnifiedPortfolioService::recompute_summary() {
+ PortfolioSummary s;
+ for (const AggRow& r : positions_) {
+ s.positions_pnl += r.pnl;
+ s.positions_day_pnl += r.day_pnl;
+ }
+ for (const AggRow& r : holdings_) {
+ s.holdings_pnl += r.pnl;
+ s.holdings_day_pnl += r.day_pnl;
+ s.invested += r.invested;
+ s.current += r.current;
+ }
+ s.return_pct = s.invested > 0.0 ? (s.current - s.invested) / s.invested * 100.0 : 0.0;
+ s.accounts_total = accts_.size();
+ for (auto it = accts_.constBegin(); it != accts_.constEnd(); ++it)
+ s.accounts_live += it->live ? 1 : 0;
+ summary_ = s;
+}
+
+// ── Actions ──────────────────────────────────────────────────────────────────
+// LIVE actions run on a worker thread (broker REST is blocking) and report back
+// through action_finished on the main thread. PAPER actions hit the local pt_*
+// engine synchronously (SQLite — the same main-thread path the equity tab uses).
+
+namespace {
+// Close one paper position: reduce-only opposite market order filled at the
+// position's marked price. Returns true on success, fills `err` otherwise.
+bool close_paper_position(const QString& portfolio_id, const QString& symbol, const QString& product,
+ QString* err) {
+ for (const PtPosition& p : pt_get_positions(portfolio_id)) {
+ if (p.symbol != symbol || (!product.isEmpty() && p.product != product) || p.quantity == 0.0)
+ continue;
+ const double px = p.current_price > 0.0 ? p.current_price : p.entry_price;
+ if (px <= 0.0) { // zero-price guard — never book a fill at 0
+ if (err)
+ *err = QString("%1: no price available for fill").arg(symbol);
+ return false;
+ }
+ const QString side = p.side.startsWith(QLatin1Char('s'), Qt::CaseInsensitive)
+ ? QStringLiteral("buy")
+ : QStringLiteral("sell");
+ try {
+ auto order = pt_place_order(portfolio_id, p.symbol, side, QStringLiteral("market"), p.quantity,
+ px, std::nullopt, /*reduce_only=*/true, QString(), p.product);
+ pt_fill_order(order.id, px);
+ return true;
+ } catch (const std::exception& e) {
+ if (err)
+ *err = QString("%1: %2").arg(symbol, QString::fromUtf8(e.what()));
+ return false;
+ }
+ }
+ if (err)
+ *err = QString("%1: paper position not found").arg(symbol);
+ return false;
+}
+} // namespace
+
+void UnifiedPortfolioService::exit_child(const QString& account_id, const QString& symbol,
+ const QString& exchange, const QString& product) {
+ if (mode_ == Mode::Paper) {
+ const QString pid = accts_.value(account_id).paper_portfolio_id;
+ QString err;
+ const bool ok = close_paper_position(pid, symbol, product, &err);
+ emit action_finished(ok, ok ? QString("Squared off %1 (paper)").arg(symbol) : err);
+ refresh_all();
+ return;
+ }
+ QPointer<UnifiedPortfolioService> self(this);
+ auto future = QtConcurrent::run([self, account_id, symbol, exchange, product]() {
+ auto r = UnifiedTrading::instance().close_position(account_id, symbol, exchange, product);
+ const bool ok = r.success;
+ const QString msg = ok ? QString("Squared off %1").arg(symbol)
+ : QString("Exit %1 failed: %2").arg(symbol, r.error);
+ QMetaObject::invokeMethod(
+ self,
+ [self, ok, msg]() {
+ if (!self)
+ return;
+ emit self->action_finished(ok, msg);
+ self->refresh_all();
+ },
+ Qt::QueuedConnection);
+ });
+ Q_UNUSED(future)
+}
+
+void UnifiedPortfolioService::exit_symbol(const QString& symbol, const QString& exchange,
+ bool from_holdings) {
+ // Snapshot the children on the main thread before hopping to the worker.
+ QVector<AggChild> children;
+ const QVector<AggRow>& rows = from_holdings ? holdings_ : positions_;
+ for (const AggRow& r : rows)
+ if (r.symbol == symbol && r.exchange == exchange)
+ children = r.children;
+ if (children.isEmpty()) {
+ emit action_finished(false, QString("No rows found for %1").arg(symbol));
+ return;
+ }
+
+ if (mode_ == Mode::Paper) {
+ int ok_count = 0;
+ QStringList errors;
+ for (const AggChild& c : children) {
+ QString err;
+ if (close_paper_position(accts_.value(c.account_id).paper_portfolio_id, symbol, c.product, &err))
+ ++ok_count;
+ else
+ errors << err;
+ }
+ const bool all_ok = errors.isEmpty();
+ emit action_finished(all_ok,
+ all_ok ? QString("Squared off %1 across %2 paper account(s)").arg(symbol).arg(ok_count)
+ : QString("%1 of %2 squared off; %3")
+ .arg(ok_count)
+ .arg(int(children.size()))
+ .arg(errors.join("; ")));
+ refresh_all();
+ return;
+ }
+
+ QPointer<UnifiedPortfolioService> self(this);
+ auto future = QtConcurrent::run([self, symbol, exchange, children]() {
+ int ok_count = 0;
+ QStringList errors;
+ for (const AggChild& c : children) {
+ auto r = UnifiedTrading::instance().close_position(c.account_id, symbol, exchange, c.product);
+ if (r.success)
+ ++ok_count;
+ else
+ errors << QString("%1: %2").arg(c.broker_label, r.error);
+ }
+ const bool all_ok = errors.isEmpty();
+ const QString msg = all_ok
+ ? QString("Squared off %1 across %2 account(s)").arg(symbol).arg(ok_count)
+ : QString("%1 of %2 squared off; %3").arg(ok_count).arg(int(children.size())).arg(errors.join("; "));
+ QMetaObject::invokeMethod(
+ self,
+ [self, all_ok, msg]() {
+ if (!self)
+ return;
+ emit self->action_finished(all_ok, msg);
+ self->refresh_all();
+ },
+ Qt::QueuedConnection);
+ });
+ Q_UNUSED(future)
+}
+
+void UnifiedPortfolioService::square_off_all_positions() {
+ if (mode_ == Mode::Paper) {
+ int closed = 0;
+ QStringList errors;
+ for (auto it = accts_.constBegin(); it != accts_.constEnd(); ++it) {
+ if (it->paper_portfolio_id.isEmpty())
+ continue;
+ for (const PtPosition& p : pt_get_positions(it->paper_portfolio_id)) {
+ if (p.quantity == 0.0 || p.product.compare(QLatin1String("CNC"), Qt::CaseInsensitive) == 0)
+ continue; // intraday/NRML only, like the live close_all
+ QString err;
+ if (close_paper_position(it->paper_portfolio_id, p.symbol, p.product, &err))
+ ++closed;
+ else
+ errors << err;
+ }
+ }
+ const bool all_ok = errors.isEmpty();
+ emit action_finished(all_ok,
+ all_ok ? QString("Squared off %1 paper position(s)").arg(closed)
+ : QString("Closed %1; errors: %2").arg(closed).arg(errors.join("; ")));
+ refresh_all();
+ return;
+ }
+
+ const QStringList ids = accts_.keys();
+ QPointer<UnifiedPortfolioService> self(this);
+ auto future = QtConcurrent::run([self, ids]() {
+ int closed = 0;
+ QStringList errors;
+ for (const QString& id : ids) {
+ auto r = UnifiedTrading::instance().close_all_positions(id);
+ if (r.success && r.data) {
+ closed += r.data->closed_symbols.size();
+ for (const auto& f : r.data->failed)
+ errors << QString("%1: %2").arg(f.first, f.second);
+ } else if (!r.success && !r.error.isEmpty() && !r.error.contains("No open positions")) {
+ errors << r.error;
+ }
+ }
+ const bool all_ok = errors.isEmpty();
+ const QString msg = all_ok ? QString("Squared off %1 position(s) across all accounts").arg(closed)
+ : QString("Closed %1; errors: %2").arg(closed).arg(errors.join("; "));
+ QMetaObject::invokeMethod(
+ self,
+ [self, all_ok, msg]() {
+ if (!self)
+ return;
+ emit self->action_finished(all_ok, msg);
+ self->refresh_all();
+ },
+ Qt::QueuedConnection);
+ });
+ Q_UNUSED(future)
+}
+
+void UnifiedPortfolioService::place_new_order(const QString& account_id, const UnifiedOrder& order) {
+ if (mode_ == Mode::Paper) {
+ const QString pid = accts_.value(account_id).paper_portfolio_id;
+ if (pid.isEmpty()) {
+ emit action_finished(false, QString("No paper portfolio for this account"));
+ return;
+ }
+ const QString side = order.side == OrderSide::Buy ? QStringLiteral("buy") : QStringLiteral("sell");
+ const bool is_market = order.order_type == OrderType::Market;
+ // Market fills need a price: use the live cached quote from this
+ // account's stream (zero-price guard — never fill at 0).
+ double px = order.price;
+ if (is_market) {
+ if (auto* stream = DataStreamManager::instance().stream_for(account_id))
+ px = stream->cached_quote(order.symbol).ltp;
+ if (px <= 0.0) {
+ emit action_finished(false,
+ QString("No live price for %1 yet — wait for quotes").arg(order.symbol));
+ return;
+ }
+ }
+ const QString product = order.product_type == ProductType::Delivery ? QStringLiteral("CNC")
+ : order.product_type == ProductType::Margin ? QStringLiteral("NRML")
+ : QStringLiteral("MIS");
+ try {
+ auto pt_order = pt_place_order(pid, order.symbol, side,
+ is_market ? QStringLiteral("market") : QStringLiteral("limit"),
+ order.quantity, px, std::nullopt, /*reduce_only=*/false,
+ order.exchange, product);
+ if (is_market) {
+ pt_fill_order(pt_order.id, px);
+ emit action_finished(true, QString("Paper order filled: %1 @ %2")
+ .arg(order.symbol)
+ .arg(px, 0, 'f', 2));
+ } else {
+ OrderMatcher::instance().add_order(pt_order);
+ emit action_finished(true, QString("Paper order queued: %1").arg(order.symbol));
+ }
+ } catch (const std::exception& e) {
+ emit action_finished(false, QString("Paper order failed: %1").arg(QString::fromUtf8(e.what())));
+ }
+ refresh_all();
+ return;
+ }
+
+ QPointer<UnifiedPortfolioService> self(this);
+ auto future = QtConcurrent::run([self, account_id, order]() {
+ auto r = UnifiedTrading::instance().place_order(account_id, order);
+ const QString msg = r.success
+ ? QString("Order placed: %1 (%2)").arg(order.symbol, r.order_id)
+ : QString("Order failed for %1: %2").arg(order.symbol, r.message);
+ QMetaObject::invokeMethod(
+ self,
+ [self, ok = r.success, msg]() {
+ if (!self)
+ return;
+ emit self->action_finished(ok, msg);
+ self->refresh_all();
+ },
+ Qt::QueuedConnection);
+ });
+ Q_UNUSED(future)
+}
+
+// ── Test seams ───────────────────────────────────────────────────────────────
+
+void UnifiedPortfolioService::test_register_account(const QString& account_id, const QString& label,
+ const QString& currency) {
+ if (currency != QLatin1String("INR"))
+ return; // mirrors the activate() filter — non-INR accounts are excluded
+ Acct& a = accts_[account_id];
+ a.label = label;
+ a.live = true;
+ a.wired = true; // no real stream in tests
+}
+
+void UnifiedPortfolioService::test_clear() {
+ accts_.clear();
+ positions_.clear();
+ holdings_.clear();
+ summary_ = {};
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/UnifiedPortfolioService.h b/fincept-qt/src/trading/UnifiedPortfolioService.h
new file mode 100644
index 000000000..2676aded3
--- /dev/null
+++ b/fincept-qt/src/trading/UnifiedPortfolioService.h
@@ -0,0 +1,163 @@
+#pragma once
+// UnifiedPortfolioService — aggregates live positions & holdings across ALL
+// active INR broker accounts into one merged model for the Portfolio Monitor
+// screen (docs/superpowers/specs/2026-06-10-portfolio-monitor-design.md).
+//
+// Data flows in from each account's AccountDataStream (positions_updated /
+// holdings_updated / quote_updated); actions flow out through UnifiedTrading
+// (close_position / place_order) — this service adds only the merge layer.
+//
+// Scope (user-confirmed): INR brokers only (BrokerProfile.currency == "INR");
+// live broker data only (paper portfolios are not aggregated).
+
+#include "trading/TradingTypes.h"
+
+#include <QHash>
+#include <QObject>
+#include <QString>
+#include <QVector>
+
+class QTimer;
+
+namespace fincept::trading {
+
+/// One account's slice of an aggregated row.
+struct AggChild {
+ QString account_id;
+ QString broker_label; // display: "Fyers — TILAK"
+ QString product; // broker product string ("MIS"/"CNC"/"INTRADAY"…)
+ QString side; // positions: "LONG"/"SHORT" (empty for holdings)
+ double qty = 0; // as delivered by the broker (may be signed)
+ double avg_price = 0;
+ double ltp = 0;
+ double pnl = 0;
+ double day_pnl = 0; // positions: broker day_pnl; holdings: qty*(ltp-prev_close)
+ double invested = 0; // holdings only
+ double current = 0; // holdings only
+ double prev_close = 0; // holdings only
+};
+
+/// One (symbol, exchange) group: parent sums + per-account children.
+struct AggRow {
+ QString symbol;
+ QString exchange;
+ double total_qty = 0; // signed sum across children
+ double w_avg_price = 0; // |qty|-weighted; 0 when no quantity
+ double ltp = 0;
+ double pnl = 0;
+ double day_pnl = 0;
+ double invested = 0; // holdings only
+ double current = 0; // holdings only
+ QVector<AggChild> children;
+};
+
+struct PortfolioSummary {
+ double positions_pnl = 0;
+ double positions_day_pnl = 0;
+ double holdings_pnl = 0;
+ double holdings_day_pnl = 0;
+ double invested = 0;
+ double current = 0;
+ double return_pct = 0; // holdings (current-invested)/invested
+ int accounts_live = 0;
+ int accounts_total = 0;
+};
+
+class UnifiedPortfolioService : public QObject {
+ Q_OBJECT
+ public:
+ /// Paper aggregates each account's paper portfolio (pt_* engine, CNC rows →
+ /// holdings, MIS/NRML → positions); Live aggregates real broker REST data.
+ /// The two are NEVER blended — set_mode() swaps the whole model.
+ enum class Mode { Paper, Live };
+
+ static UnifiedPortfolioService& instance();
+
+ /// Enumerate active INR accounts, ensure their streams run, connect signals.
+ /// Idempotent — call on every screen show; new accounts get picked up.
+ void activate();
+
+ /// Force an immediate portfolio refetch on every tracked account.
+ void refresh_all();
+
+ void set_mode(Mode mode);
+ Mode mode() const { return mode_; }
+
+ // --- Merged model (main thread) ---
+ QVector<AggRow> positions() const { return positions_; }
+ QVector<AggRow> holdings() const { return holdings_; }
+ PortfolioSummary summary() const { return summary_; }
+
+ struct AccountInfo {
+ QString account_id;
+ QString label;
+ QString broker_id;
+ QString default_exchange;
+ QString paper_portfolio_id;
+ bool live = false;
+ };
+ QVector<AccountInfo> accounts() const;
+
+ // --- Actions (async on a worker thread; action_finished on main thread) ---
+ void exit_child(const QString& account_id, const QString& symbol, const QString& exchange,
+ const QString& product);
+ /// Square off `symbol` across every child account holding it.
+ /// `from_holdings` selects which merged model to read children from.
+ void exit_symbol(const QString& symbol, const QString& exchange, bool from_holdings);
+ /// Square off every non-delivery position in every tracked account.
+ void square_off_all_positions();
+ void place_new_order(const QString& account_id, const UnifiedOrder& order);
+
+ // --- Ingestion (stream signal handlers; public as the selftest seam) ---
+ void ingest_positions(const QString& account_id, const QVector<BrokerPosition>& positions);
+ void ingest_holdings(const QString& account_id, const QVector<BrokerHolding>& holdings);
+ void ingest_quote(const QString& account_id, const QString& symbol, const BrokerQuote& quote);
+
+ // --- Test seams (--selftest-portfolio-monitor; bypass account enumeration) ---
+ void test_register_account(const QString& account_id, const QString& label, const QString& currency);
+ void test_clear();
+
+ signals:
+ void positions_changed(); // structural rebuild needed
+ void holdings_changed(); // structural rebuild needed
+ void position_patched(const QString& symbol); // in-place LTP/P&L update
+ void holding_patched(const QString& symbol); // in-place LTP/P&L update
+ void summary_changed(); // debounced
+ void accounts_changed(); // live-count / set changed
+ void action_finished(bool ok, const QString& message);
+
+ private:
+ explicit UnifiedPortfolioService(QObject* parent = nullptr);
+
+ void connect_stream(const QString& account_id);
+ void rebuild_positions();
+ void rebuild_holdings();
+ void rebuild_paper(); // reads pt_* fresh; fills BOTH positions_ and holdings_
+ void schedule_summary();
+ void recompute_summary();
+ void emit_all_changed();
+
+ struct Acct {
+ QString label;
+ QString broker_id;
+ QString default_exchange;
+ QString paper_portfolio_id;
+ bool live = false;
+ bool wired = false; // stream signals connected
+ QVector<BrokerPosition> positions;
+ QVector<BrokerHolding> holdings;
+ };
+
+ QHash<QString, Acct> accts_; // account_id → state
+ QVector<AggRow> positions_;
+ QVector<AggRow> holdings_;
+ PortfolioSummary summary_;
+ QTimer* summary_debounce_ = nullptr;
+ Mode mode_ = Mode::Paper; // user-requested default: paper first
+};
+
+/// Headless merge-math selftest (no GUI/broker/keys).
+/// QT_QPA_PLATFORM=offscreen FinceptTerminal --selftest-portfolio-monitor
+int run_portfolio_monitor_selftest();
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
index 6942c3be7..17da00865 100644
--- a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
+++ b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
@@ -390,6 +390,12 @@ ApiResponse<QVector<BrokerHolding>> DhanBroker::get_holdings(const BrokerCredent
int64_t ts = now_ts();
auto resp = BrokerHttp::instance().get(BASE + "/v2/holdings", auth_headers(creds));
+ // Dhan reports "account has no holdings" as an ERROR envelope ("No holdings
+ // available") rather than an empty array — surface it as a successful empty
+ // result so a connected account isn't flagged as a failed fetch.
+ if (!is_token_expired(resp) && resp.raw_body.contains("No holdings available", Qt::CaseInsensitive))
+ return {true, QVector<BrokerHolding>{}, "", ts};
+
if (!resp.success || resp.json.value("errorType").toString().length() > 0)
return {false, std::nullopt, checked_error(resp, "get_holdings failed"), ts};
@@ -624,7 +630,11 @@ ApiResponse<QVector<BrokerCandle>> DhanBroker::get_history(const BrokerCredentia
const int count = qMin(timestamps.size(), closes.size());
for (int i = 0; i < count; ++i) {
BrokerCandle c;
- c.timestamp = static_cast<int64_t>(timestamps[i].toDouble());
+ // Dhan returns epoch SECONDS; BrokerCandle.timestamp is milliseconds
+ // (EquityChartPanel divides by 1000 and rolls the live bar against
+ // currentMSecsSinceEpoch). Without ×1000 candles land in Jan 1970 and
+ // the forming bar rolls on every tick ("chart goes every second").
+ c.timestamp = static_cast<int64_t>(timestamps[i].toDouble()) * 1000;
c.open = opens.size() > i ? opens[i].toDouble() : 0.0;
c.high = highs.size() > i ? highs[i].toDouble() : 0.0;
c.low = lows.size() > i ? lows[i].toDouble() : 0.0;
diff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
index bb773073d..a4b2c223d 100644
--- a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
@@ -470,11 +470,16 @@ ApiResponse<QVector<BrokerCandle>> ZerodhaBroker::get_history(const BrokerCreden
auto c = v.toArray();
if (c.size() < 6)
continue;
- qint64 epoch = QDateTime::fromString(c[0].toString(), Qt::ISODateWithMs).toSecsSinceEpoch();
- if (epoch == 0)
- epoch = QDateTime::fromString(c[0].toString(), Qt::ISODate).toSecsSinceEpoch();
+ // BrokerCandle.timestamp is MILLISECONDS since epoch (the contract the
+ // chart and every ms-based broker use). Kite returns ISO-8601 with a
+ // +05:30 offset, e.g. "2024-03-28T09:15:00+0530"; emit ms, not seconds —
+ // seconds here landed candles in Jan 1970 and made the live bar roll a
+ // new candle on every tick (chart "going every second").
+ qint64 epoch_ms = QDateTime::fromString(c[0].toString(), Qt::ISODateWithMs).toMSecsSinceEpoch();
+ if (epoch_ms == 0)
+ epoch_ms = QDateTime::fromString(c[0].toString(), Qt::ISODate).toMSecsSinceEpoch();
BrokerCandle bc;
- bc.timestamp = epoch;
+ bc.timestamp = epoch_ms;
bc.open = c[1].toDouble();
bc.high = c[2].toDouble();
bc.low = c[3].toDouble();
diff --git a/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidClient.cpp b/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidClient.cpp
index 98679d632..ed91efc4d 100644
--- a/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidClient.cpp
+++ b/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidClient.cpp
@@ -63,6 +63,10 @@ void HyperliquidClient::post_json(const QString& url, const QJsonObject& body, J
static QNetworkAccessManager s_nam;
QNetworkRequest req(QUrl{url});
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
+ // 30s transfer timeout so a stalled connection errors instead of hanging a
+ // round forever. Safe for the live venue too: HL REST normally replies in
+ // well under a second, and a timed-out order surfaces as a venue error.
+ req.setTransferTimeout(30000);
QPointer<HyperliquidClient> self(this);
auto* reply = s_nam.post(req, QJsonDocument(body).toJson(QJsonDocument::Compact));
connect(reply, &QNetworkReply::finished, this, [reply, cb]() {
diff --git a/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidVenue.cpp b/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidVenue.cpp
index a88bee656..94ac1bb7d 100644
--- a/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidVenue.cpp
+++ b/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidVenue.cpp
@@ -1,7 +1,6 @@
#include "trading/exchanges/hyperliquid/HyperliquidVenue.h"
#include "core/logging/Logger.h"
-#include "services/alpha_arena/AlphaArenaRepo.h"
#include "trading/exchanges/hyperliquid/HyperliquidSigner.h"
#include <QAbstractSocket>
@@ -87,9 +86,8 @@ void HyperliquidVenue::reconcile_tick() {
QJsonObject body;
body[QStringLiteral("type")] = QStringLiteral("clearinghouseState");
body[QStringLiteral("user")] = user_address_;
- const QString comp_id = competition_id_;
QPointer<HyperliquidVenue> self(this);
- client_->info(body, [self, comp_id](Result<QJsonDocument> r) {
+ client_->info(body, [self](Result<QJsonDocument> r) {
if (!self) return;
if (r.is_err()) {
LOG_WARN("Hyperliquid", QString("reconcile failed: %1")
@@ -108,28 +106,12 @@ void HyperliquidVenue::reconcile_tick() {
if (!coin.isEmpty()) remote_qty.insert(coin, szi);
}
- // Walk local agents and their positions.
- auto agents = fincept::services::alpha_arena::AlphaArenaRepo::instance()
- .agents_for(comp_id);
- if (agents.is_err()) return;
- for (const auto& agent : agents.value()) {
- auto local = fincept::services::alpha_arena::AlphaArenaRepo::instance()
- .open_positions_for(agent.id);
- if (local.is_err()) continue;
- for (const auto& p : local.value()) {
- const double r_qty = remote_qty.value(p.coin, 0.0);
- if (std::fabs(r_qty - p.qty) > 1e-9) {
- emit self->position_drift(p.coin, p.qty, r_qty);
- QJsonObject pl;
- pl[QStringLiteral("coin")] = p.coin;
- pl[QStringLiteral("local_qty")] = p.qty;
- pl[QStringLiteral("remote_qty")] = r_qty;
- fincept::services::alpha_arena::AlphaArenaRepo::instance()
- .append_event(comp_id, agent.id,
- QStringLiteral("position_drift"), pl);
- }
- }
- }
+ // Local-vs-remote drift comparison was removed along with the legacy
+ // AlphaArenaRepo (its aa_* tables were dropped in migration v050).
+ // The new arena ledger lives in fincept::arena::ArenaStore — re-wire
+ // the position_drift signal against it when the live order path lands.
+ LOG_DEBUG("Hyperliquid",
+ QString("reconcile: %1 remote position(s)").arg(remote_qty.size()));
});
}
@@ -161,10 +143,9 @@ void HyperliquidVenue::place_order(const OrderRequest& req,
action[QStringLiteral("orders")] = orders;
action[QStringLiteral("grouping")] = QStringLiteral("na");
- // Pull agent priv key from SecureStorage handle. We expect the engine to
- // have stored it under `alpha_arena/agent_key/<comp_id>`; the OrderRouter
- // resolves the handle and passes it here. Until the wallet wiring lands
- // on this codepath we surface a clear error.
+ // Pull agent priv key from SecureStorage handle. The engine stores it
+ // under `alpha_arena/agent_key/<comp_id>` (written by LiveModeGateDialog).
+ // Until the wallet wiring lands on this codepath we surface a clear error.
Q_UNUSED(req);
OrderAck a;
a.status = QStringLiteral("rejected");
diff --git a/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidVenue.h b/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidVenue.h
index 98ecd9098..9f8af5252 100644
--- a/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidVenue.h
+++ b/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidVenue.h
@@ -40,8 +40,8 @@ class HyperliquidVenue : public QObject,
/// HyperliquidSigner).
void set_user_address(const QString& addr);
- /// Bind to the active competition so reconcile_tick can compare local
- /// positions persisted under that competition against the venue.
+ /// Bind to the active competition — HyperliquidSigner reads the agent
+ /// wallet key from SecureStorage under "alpha_arena/agent_key/<comp_id>".
void set_competition_id(const QString& comp_id);
/// Open WS, subscribe to public mark/trades feeds, start reconcile loop.
@@ -68,7 +68,9 @@ class HyperliquidVenue : public QObject,
}
signals:
- /// Local-vs-remote drift detected by the 30-s reconcile loop.
+ /// Local-vs-remote drift detected by the 30-s reconcile loop. Currently
+ /// never emitted: the legacy local ledger (AlphaArenaRepo) is gone; this
+ /// will be re-wired against fincept::arena::ArenaStore with live trading.
void position_drift(QString coin, double local_qty, double remote_qty);
private slots:
diff --git a/fincept-qt/src/trading/instruments/InstrumentService.cpp b/fincept-qt/src/trading/instruments/InstrumentService.cpp
index a790778f3..fbef87744 100644
--- a/fincept-qt/src/trading/instruments/InstrumentService.cpp
+++ b/fincept-qt/src/trading/instruments/InstrumentService.cpp
@@ -708,6 +708,23 @@ bool InstrumentService::is_loaded(const QString& broker_id) const {
// ── Private ───────────────────────────────────────────────────────────────────
+// When two instruments share a numeric token, by_token can only keep one. Dhan
+// reuses securityIds across exchange segments (e.g. 2885 is RELIANCE on NSE_EQ and
+// an expired EURINR option on CDS), so prefer the "primary" tradable — cash/index
+// over derivatives — to keep token→symbol/segment resolution pointing at the
+// equity the feed actually wants instead of a colliding (often expired) option.
+// Lower rank = preferred. Globally-unique-token brokers never hit a collision.
+static int inst_token_collision_rank(const Instrument& i) {
+ switch (i.instrument_type) {
+ case InstrumentType::EQ: return 0;
+ case InstrumentType::INDEX: return 1;
+ case InstrumentType::FUT: return 2;
+ case InstrumentType::CE:
+ case InstrumentType::PE: return 3;
+ default: return 4;
+ }
+}
+
void InstrumentService::build_cache(const QString& broker_id, const QVector<Instrument>& instruments) {
QMutexLocker lock(&mutex_);
Cache& cache = caches_[broker_id];
@@ -717,7 +734,12 @@ void InstrumentService::build_cache(const QString& broker_id, const QVector<Inst
for (const auto& inst : instruments) {
cache.by_symbol.insert({inst.symbol, inst.exchange}, inst);
- cache.by_token.insert(inst.instrument_token, inst);
+ // by_token is keyed on the bare numeric token; survive cross-segment token
+ // collisions by keeping the higher-priority instrument (see ranker above).
+ auto existing = cache.by_token.find(inst.instrument_token);
+ if (existing == cache.by_token.end() ||
+ inst_token_collision_rank(inst) < inst_token_collision_rank(existing.value()))
+ cache.by_token.insert(inst.instrument_token, inst);
cache.by_brsymbol.insert({inst.brsymbol, inst.brexchange}, inst);
}
cache.loaded = true;
diff --git a/fincept-qt/src/trading/instruments/ZerodhaInstrumentParser.cpp b/fincept-qt/src/trading/instruments/ZerodhaInstrumentParser.cpp
index 9b272a6d9..15b2e42eb 100644
--- a/fincept-qt/src/trading/instruments/ZerodhaInstrumentParser.cpp
+++ b/fincept-qt/src/trading/instruments/ZerodhaInstrumentParser.cpp
@@ -122,13 +122,19 @@ QString ZerodhaInstrumentParser::normalise_symbol(const QString& tradingsymbol,
}
// ── Row parser ────────────────────────────────────────────────────────────────
-// CSV column order from Zerodha:
-// 0:instrument_token 1:exchange_token 2:tradingsymbol 3:name
-// 4:expiry 5:strike 6:lot_size 7:instrument_type 8:exchange
-// 9:tick_size 10:segment
+// CSV column order from Zerodha's /instruments dump (Kite Connect v3 — 12 cols):
+// 0:instrument_token 1:exchange_token 2:tradingsymbol 3:name 4:last_price
+// 5:expiry 6:strike 7:tick_size 8:lot_size 9:instrument_type
+// 10:segment 11:exchange
+// NOTE: the dump has a `last_price` column at index 4 (ignored — not real-time),
+// and `exchange` is the LAST field. An earlier mapping assumed an 11-column
+// layout without last_price, which shifted every field after `name`: tick_size
+// landed in instrument_type (→ all "UNKNOWN") and lot_size landed in exchange
+// (→ exchange="1"), so symbol+exchange lookups (keyed on "NSE") matched nothing
+// and live quotes never resolved a token. Keep this aligned with the doc above.
Instrument ZerodhaInstrumentParser::parse_row(const QStringList& cols) {
- if (cols.size() < 11)
+ if (cols.size() < 12)
return {};
Instrument inst;
@@ -137,13 +143,14 @@ Instrument ZerodhaInstrumentParser::parse_row(const QStringList& cols) {
inst.exchange_token = cols[1].toLongLong();
inst.brsymbol = cols[2].trimmed();
inst.name = cols[3].trimmed().toUpper();
- QString expiry_iso = cols[4].trimmed(); // "2024-03-28" or ""
- inst.strike = cols[5].toDouble();
- inst.lot_size = cols[6].toInt();
- QString itype = cols[7].trimmed().toUpper();
- inst.brexchange = cols[8].trimmed().toUpper();
- inst.tick_size = cols[9].toDouble();
+ // cols[4] = last_price — ignored (not real-time; we never store it)
+ QString expiry_iso = cols[5].trimmed(); // "2024-03-28" or ""
+ inst.strike = cols[6].toDouble();
+ inst.tick_size = cols[7].toDouble();
+ inst.lot_size = cols[8].toInt();
+ QString itype = cols[9].trimmed().toUpper();
QString segment = cols[10].trimmed().toUpper();
+ inst.brexchange = cols[11].trimmed().toUpper();
// Normalise expiry to DD-MMM-YY display format and nodashes for symbol
QString exp_nd = expiry_nodashes(expiry_iso);
@@ -181,7 +188,7 @@ QVector<Instrument> ZerodhaInstrumentParser::parse(const QByteArray& csv_data) {
// Simple CSV split — Zerodha's instruments CSV has no quoted fields with commas
QStringList cols = line.split(',');
- if (cols.size() < 11) {
+ if (cols.size() < 12) {
LOG_WARN("ZerodhaParser", QString("Row %1: only %2 columns, skipping").arg(row).arg(cols.size()));
++row;
continue;
diff --git a/fincept-qt/src/trading/websocket/DhanWebSocket.cpp b/fincept-qt/src/trading/websocket/DhanWebSocket.cpp
index cb28c87be..35468f519 100644
--- a/fincept-qt/src/trading/websocket/DhanWebSocket.cpp
+++ b/fincept-qt/src/trading/websocket/DhanWebSocket.cpp
@@ -221,6 +221,19 @@ void DhanWebSocket::on_disconnected() {
emit disconnected();
}
+void DhanWebSocket::emit_tick(BrokerQuote merged) {
+ if (merged.timestamp == 0)
+ merged.timestamp = QDateTime::currentMSecsSinceEpoch();
+ // Dhan's quote/full packets carry the *previous* close in the close field but
+ // never send day change pre-computed — derive it here so the watchlist shows a
+ // real CHG/CHG% instead of +0.00 for every symbol. (mirrors get_quotes REST.)
+ if (merged.close > 0.0) {
+ merged.change = merged.ltp - merged.close;
+ merged.change_pct = (merged.ltp - merged.close) / merged.close * 100.0;
+ }
+ emit tick_received(merged);
+}
+
void DhanWebSocket::on_binary_message(const QByteArray& data) {
note_tick(); // any inbound frame (even a heartbeat) keeps the watchdog happy
@@ -250,18 +263,12 @@ void DhanWebSocket::on_binary_message(const QByteArray& data) {
switch (response_code) {
case 2: { // TICKER (8B payload: ltp f32, ltt u32)
BrokerQuote q = parse_ticker(payload, payload_len, exchange_segment, security_id);
- BrokerQuote merged = merge_tick(fallback, q);
- if (merged.timestamp == 0)
- merged.timestamp = QDateTime::currentMSecsSinceEpoch();
- emit tick_received(merged);
+ emit_tick(merge_tick(fallback, q));
break;
}
case 4: { // QUOTE (42B payload)
BrokerQuote q = parse_quote(payload, payload_len, exchange_segment, security_id);
- BrokerQuote merged = merge_tick(fallback, q);
- if (merged.timestamp == 0)
- merged.timestamp = QDateTime::currentMSecsSinceEpoch();
- emit tick_received(merged);
+ emit_tick(merge_tick(fallback, q));
break;
}
case 5: { // OI (4B payload: oi u32)
@@ -269,10 +276,7 @@ void DhanWebSocket::on_binary_message(const QByteArray& data) {
BrokerQuote q;
q.symbol = symbol_for_security(security_id, fallback);
q.oi = qint64(read_u32(payload));
- BrokerQuote merged = merge_tick(fallback, q);
- if (merged.timestamp == 0)
- merged.timestamp = QDateTime::currentMSecsSinceEpoch();
- emit tick_received(merged);
+ emit_tick(merge_tick(fallback, q));
}
break;
}
@@ -281,10 +285,7 @@ void DhanWebSocket::on_binary_message(const QByteArray& data) {
BrokerQuote q;
q.symbol = symbol_for_security(security_id, fallback);
q.close = read_f32(payload); // previous close carried into close field
- BrokerQuote merged = merge_tick(fallback, q);
- if (merged.timestamp == 0)
- merged.timestamp = QDateTime::currentMSecsSinceEpoch();
- emit tick_received(merged);
+ emit_tick(merge_tick(fallback, q));
}
break;
}
@@ -293,10 +294,7 @@ void DhanWebSocket::on_binary_message(const QByteArray& data) {
bool has_depth = false;
BrokerQuote q =
parse_full(payload, payload_len, exchange_segment, security_id, depth, has_depth);
- BrokerQuote merged = merge_tick(fallback, q);
- if (merged.timestamp == 0)
- merged.timestamp = QDateTime::currentMSecsSinceEpoch();
- emit tick_received(merged);
+ emit_tick(merge_tick(fallback, q));
if (has_depth)
emit depth_received(depth);
break;
diff --git a/fincept-qt/src/trading/websocket/DhanWebSocket.h b/fincept-qt/src/trading/websocket/DhanWebSocket.h
index 2fa46d27a..9408d33cd 100644
--- a/fincept-qt/src/trading/websocket/DhanWebSocket.h
+++ b/fincept-qt/src/trading/websocket/DhanWebSocket.h
@@ -117,6 +117,9 @@ class DhanWebSocket : public BrokerWebSocketBase {
// Enrich symbol/exchange for a security id via InstrumentService.
QString symbol_for_security(quint32 security_id, const QString& fallback) const;
+ // Stamp timestamp + derive day change on a merged quote, then emit tick_received.
+ void emit_tick(BrokerQuote merged);
+
// little-endian readers
static quint16 read_u16(const uchar* p);
static quint32 read_u32(const uchar* p);
diff --git a/fincept-qt/src/trading/websocket/ZerodhaWebSocket.cpp b/fincept-qt/src/trading/websocket/ZerodhaWebSocket.cpp
index a9c1b0d88..acaf34120 100644
--- a/fincept-qt/src/trading/websocket/ZerodhaWebSocket.cpp
+++ b/fincept-qt/src/trading/websocket/ZerodhaWebSocket.cpp
@@ -194,6 +194,23 @@ void ZerodhaWebSocket::send_unsubscribe(const QVector<quint32>& tokens) {
}
void ZerodhaWebSocket::send_mode(const QVector<quint32>& tokens) {
+ // Per-token mode: the one full_mode_token_ (selected symbol) streams "full"
+ // (184-byte, 5-level market depth) so the order book / depth table has data;
+ // every other token streams "quote" (44-byte LTP+OHLC+volume). "full" packets
+ // are 4x heavier to parse on the GUI thread per tick, so keeping the bulk on
+ // "quote" preserves snappy live LTP updates while still feeding depth.
+ QVector<quint32> full_toks, quote_toks;
+ for (quint32 t : tokens) {
+ if (full_mode_token_ != 0 && t == full_mode_token_)
+ full_toks.append(t);
+ else
+ quote_toks.append(t);
+ }
+ send_mode_batch("quote", quote_toks);
+ send_mode_batch("full", full_toks);
+}
+
+void ZerodhaWebSocket::send_mode_batch(const char* mode, const QVector<quint32>& tokens) {
for (int start = 0; start < tokens.size(); start += kBatchSize) {
QJsonArray arr;
for (int j = start; j < std::min(start + kBatchSize, int(tokens.size())); ++j)
@@ -201,13 +218,32 @@ void ZerodhaWebSocket::send_mode(const QVector<quint32>& tokens) {
QJsonObject msg;
msg["a"] = "mode";
QJsonArray v;
- v.append("full");
+ v.append(QString::fromLatin1(mode));
v.append(arr);
msg["v"] = v;
ws_->send(QJsonDocument(msg).toJson(QJsonDocument::Compact));
}
}
+void ZerodhaWebSocket::set_full_mode_token(quint32 token) {
+ if (token == full_mode_token_)
+ return;
+ const quint32 old = full_mode_token_;
+ full_mode_token_ = token;
+ if (!is_connected())
+ return; // mode is applied on the next (re)subscribe
+ // Re-send mode for just the affected tokens: the previous full token drops back
+ // to "quote", the new one moves to "full". send_mode() partitions by the
+ // (now updated) full_mode_token_.
+ QVector<quint32> changed;
+ if (old != 0 && subscribed_tokens_.contains(old))
+ changed.append(old);
+ if (token != 0 && subscribed_tokens_.contains(token))
+ changed.append(token);
+ if (!changed.isEmpty())
+ send_mode(changed);
+}
+
void ZerodhaWebSocket::resubscribe_all() {
if (subscribed_tokens_.isEmpty())
return;
diff --git a/fincept-qt/src/trading/websocket/ZerodhaWebSocket.h b/fincept-qt/src/trading/websocket/ZerodhaWebSocket.h
index f5cb54d46..d1a195c23 100644
--- a/fincept-qt/src/trading/websocket/ZerodhaWebSocket.h
+++ b/fincept-qt/src/trading/websocket/ZerodhaWebSocket.h
@@ -37,9 +37,17 @@ class ZerodhaWebSocket : public QObject {
bool is_connected() const;
/// Add tokens to the subscription set and (re)subscribe if connected.
- /// Mode is always "full" — we need depth for order matching.
+ /// Tokens stream in "quote" mode (44-byte: LTP/OHLC/volume) by default; the
+ /// one token set via set_full_mode_token() streams in "full" mode (184-byte,
+ /// 5-level depth) so the order book / depth table has data.
void subscribe(const QVector<quint32>& tokens);
+ /// Designate the single token that should stream in "full" mode (market depth).
+ /// Typically the currently-selected symbol — the only one whose depth is shown.
+ /// Pass 0 to put everything back on "quote". Re-sends mode immediately if
+ /// connected (for both the previous and the new full-mode token).
+ void set_full_mode_token(quint32 token);
+
/// Remove tokens from the subscription set.
void unsubscribe(const QVector<quint32>& tokens);
@@ -64,6 +72,8 @@ class ZerodhaWebSocket : public QObject {
void send_subscribe(const QVector<quint32>& tokens);
void send_unsubscribe(const QVector<quint32>& tokens);
void send_mode(const QVector<quint32>& tokens);
+ // Send one "mode" message for a token batch (mode = "quote" or "full").
+ void send_mode_batch(const char* mode, const QVector<quint32>& tokens);
void resubscribe_all();
// Binary packet parsing helpers
@@ -80,6 +90,7 @@ class ZerodhaWebSocket : public QObject {
QString access_token_;
WebSocketClient* ws_;
QSet<quint32> subscribed_tokens_;
+ quint32 full_mode_token_ = 0; // streams in "full" mode (depth); 0 = none
static constexpr int kBatchSize = 200;
static constexpr const char* kWsUrl = "wss://ws.kite.trade";
diff --git a/fincept-qt/src/ui/charts/ChartIndicators.cpp b/fincept-qt/src/ui/charts/ChartIndicators.cpp
index 53b682c72..3375983d2 100644
--- a/fincept-qt/src/ui/charts/ChartIndicators.cpp
+++ b/fincept-qt/src/ui/charts/ChartIndicators.cpp
@@ -23,6 +23,24 @@ QVector<double> sma(const QVector<double>& values, int period) {
return out;
}
+QVector<double> ema(const QVector<double>& values, int period) {
+ const int n = values.size();
+ QVector<double> out(n, std::numeric_limits<double>::quiet_NaN());
+ if (period < 1 || n < period)
+ return out;
+
+ // Seed with SMA of the first `period` values, exactly as pandas-ta does.
+ double sum = 0;
+ for (int i = 0; i < period; ++i)
+ sum += values[i];
+ out[period - 1] = sum / period;
+
+ const double alpha = 2.0 / (period + 1);
+ for (int i = period; i < n; ++i)
+ out[i] = alpha * values[i] + (1.0 - alpha) * out[i - 1];
+ return out;
+}
+
QVector<double> vwap(const QVector<double>& highs,
const QVector<double>& lows,
const QVector<double>& closes,
diff --git a/fincept-qt/src/ui/charts/ChartIndicators.h b/fincept-qt/src/ui/charts/ChartIndicators.h
index 2f3039d2a..41fdf600b 100644
--- a/fincept-qt/src/ui/charts/ChartIndicators.h
+++ b/fincept-qt/src/ui/charts/ChartIndicators.h
@@ -22,6 +22,10 @@ namespace indicators {
QVector<double> sma(const QVector<double>& values, int period);
+/// Exponential moving average, seeded with the SMA of the first `period`
+/// values (pandas-ta convention). Output[i] is NaN for i < period - 1.
+QVector<double> ema(const QVector<double>& values, int period);
+
QVector<double> vwap(const QVector<double>& highs,
const QVector<double>& lows,
const QVector<double>& closes,
diff --git a/fincept-qt/src/ui/charts/layers/EmaLayer.cpp b/fincept-qt/src/ui/charts/layers/EmaLayer.cpp
index 66006a18c..4bda82f9d 100644
--- a/fincept-qt/src/ui/charts/layers/EmaLayer.cpp
+++ b/fincept-qt/src/ui/charts/layers/EmaLayer.cpp
@@ -1,6 +1,6 @@
#include "ui/charts/layers/EmaLayer.h"
-#include "services/alpha_arena/Indicators.h"
+#include "ui/charts/ChartIndicators.h"
namespace fincept::ui {
@@ -21,7 +21,7 @@ void EmaLayer::compute(const QVector<CandleData>& candles) {
timestamps.append(c.timestamp);
}
- const auto values = fincept::services::alpha_arena::ema(closes, period_);
+ const auto values = indicators::ema(closes, period_);
update_series_data(timestamps, values);
}