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.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
algo trading tab update
tilakpatel220343a1eeae02
diff --git a/fincept-terminal-desktop/i18next-parser.config.js b/fincept-terminal-desktop/i18next-parser.config.tssimilarity index 100%rename from fincept-terminal-desktop/i18next-parser.config.jsrename to fincept-terminal-desktop/i18next-parser.config.tsdiff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.jsonindex d3f78ab08..141a2c194 100644--- a/fincept-terminal-desktop/package.json+++ b/fincept-terminal-desktop/package.json@@ -12,8 +12,8 @@"tauri:dev": "bun run tauri dev","tauri:build": "bun run tauri build","tauri:build:msstore": "bun run tauri build --config src-tauri/tauri.microsoftstore.conf.json",- "bump-version": "bun scripts/bump-version.js",- "i18n:sync": "bun scripts/sync-translations.js",+ "bump-version": "bun scripts/bump-version.ts",+ "i18n:sync": "bun scripts/sync-translations.ts","i18n:generate": "python scripts/generate_translations.py","i18n:generate:force": "python scripts/generate_translations.py --force","i18n:generate:dry": "python scripts/generate_translations.py --dry-run"diff --git a/fincept-terminal-desktop/scripts/bump-version.js b/fincept-terminal-desktop/scripts/bump-version.tssimilarity index 76%rename from fincept-terminal-desktop/scripts/bump-version.jsrename to fincept-terminal-desktop/scripts/bump-version.tsindex 9355c44fa..9faf6fd3f 100644--- a/fincept-terminal-desktop/scripts/bump-version.js+++ b/fincept-terminal-desktop/scripts/bump-version.ts@@ -1,4 +1,4 @@-#!/usr/bin/env node+#!/usr/bin/env bun/*** Version Bump Script@@ -34,26 +34,34 @@ const colors = {blue: '\x1b[34m',red: '\x1b[31m',cyan: '\x1b[36m',-};+} as const;-function log(message, color = colors.reset) {+type BumpType = 'patch' | 'minor' | 'major';++interface VersionParts {+ major: number;+ minor: number;+ patch: number;+}++function log(message: string, color: string = colors.reset): void {console.log(`${color}${message}${colors.reset}`);}-function logSuccess(message) {- log(`✓ ${message}`, colors.green);+function logSuccess(message: string): void {+ log(`\u2713 ${message}`, colors.green);}-function logError(message) {- log(`✗ ${message}`, colors.red);+function logError(message: string): void {+ log(`\u2717 ${message}`, colors.red);}-function logInfo(message) {- log(`ℹ ${message}`, colors.blue);+function logInfo(message: string): void {+ log(`\u2139 ${message}`, colors.blue);}// Parse semver version-function parseVersion(version) {+function parseVersion(version: string): VersionParts {const match = version.match(/^(\d+)\.(\d+)\.(\d+)$/);if (!match) {throw new Error(`Invalid version format: ${version}`);@@ -66,7 +74,7 @@ function parseVersion(version) {}// Increment version based on type-function incrementVersion(version, type = 'patch') {+function incrementVersion(version: string, type: BumpType = 'patch'): string {const parts = parseVersion(version);switch (type) {@@ -89,26 +97,26 @@ function incrementVersion(version, type = 'patch') {}// Update package.json-function updatePackageJson(newVersion) {+function updatePackageJson(newVersion: string): string {const packageJsonPath = path.join(rootDir, 'package.json');try {const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));- const oldVersion = packageJson.version;+ const oldVersion: string = packageJson.version;packageJson.version = newVersion;fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n', 'utf8');- logSuccess(`Updated package.json: v${oldVersion} → v${newVersion}`);+ logSuccess(`Updated package.json: v${oldVersion} \u2192 v${newVersion}`);return oldVersion;} catch (error) {- logError(`Failed to update package.json: ${error.message}`);+ logError(`Failed to update package.json: ${(error as Error).message}`);process.exit(1);}}// Run sync-version script-function runSyncVersion() {+function runSyncVersion(): void {try {logInfo('\nSyncing version across all files...\n');execSync('bun run sync-version', { stdio: 'inherit', cwd: rootDir });@@ -119,9 +127,9 @@ function runSyncVersion() {}// Main function-function main() {+function main(): void {const args = process.argv.slice(2);- const bumpType = args[0] || 'patch';+ const bumpType = (args[0] || 'patch') as string;if (!['patch', 'minor', 'major'].includes(bumpType)) {logError(`Invalid bump type: ${bumpType}`);@@ -136,10 +144,10 @@ function main() {// Read current versionconst packageJsonPath = path.join(rootDir, 'package.json');const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));- const currentVersion = packageJson.version;+ const currentVersion: string = packageJson.version;// Calculate new version- const newVersion = incrementVersion(currentVersion, bumpType);+ const newVersion = incrementVersion(currentVersion, bumpType as BumpType);logInfo(`Bump type: ${colors.bright}${bumpType}${colors.reset}`);logInfo(`Current version: ${colors.yellow}v${currentVersion}${colors.reset}`);diff --git a/fincept-terminal-desktop/scripts/sync-translations.js b/fincept-terminal-desktop/scripts/sync-translations.tssimilarity index 68%rename from fincept-terminal-desktop/scripts/sync-translations.jsrename to fincept-terminal-desktop/scripts/sync-translations.tsindex 7c174d2f7..0442aad21 100644--- a/fincept-terminal-desktop/scripts/sync-translations.js+++ b/fincept-terminal-desktop/scripts/sync-translations.ts@@ -1,4 +1,4 @@-#!/usr/bin/env node+#!/usr/bin/env bun// Auto-sync translations across all languages// This script:// 1. Scans code for t() calls to find actual UI translation keys@@ -15,28 +15,28 @@ const SRC_DIR = 'src';const SOURCE_LANG = 'en';const LANGUAGES = ['en', 'es', 'fr', 'de', 'zh', 'ja', 'hi', 'ar', 'pt', 'ru', 'bn', 'ko', 'tr', 'it', 'id', 'vi', 'th', 'pl', 'uk', 'ro'];+type NestedObject = { [key: string]: string | NestedObject };+// Extract translation keys from code-function extractTranslationKeysFromCode() {+function extractTranslationKeysFromCode(): Map<string, Set<string>> {const files = glob.sync(`${SRC_DIR}/**/*.{ts,tsx}`, { ignore: '**/node_modules/**' });- const keysMap = new Map(); // namespace -> Set of keys+ const keysMap = new Map<string, Set<string>>(); // namespace -> Set of keys// Patterns to match t() callsconst nsPattern = /useTranslation\(['"]([\w]+)['"]\)/g;- const keyPattern1 = /\bt\(['"]([\w.]+)['"]\)/g; // t('key.subkey')- const keyPattern2 = /\bt\(['"]([\w]+):([\w.]+)['"]\)/g; // t('namespace:key')files.forEach(file => {const content = fs.readFileSync(file, 'utf-8');// Find default namespace from useTranslation('namespace')let defaultNs = 'common';- let nsMatch;+ let nsMatch: RegExpExecArray | null;while ((nsMatch = nsPattern.exec(content)) !== null) {defaultNs = nsMatch[1];}// Extract keys with namespace prefix: t('namespace:key')- let match;+ let match: RegExpExecArray | null;const pattern2Regex = /\bt\(['"]([\w]+):([\w.]+)['"]\)/g;while ((match = pattern2Regex.exec(content)) !== null) {const namespace = match[1];@@ -45,7 +45,7 @@ function extractTranslationKeysFromCode() {if (!keysMap.has(namespace)) {keysMap.set(namespace, new Set());}- keysMap.get(namespace).add(key);+ keysMap.get(namespace)!.add(key);}// Extract simple keys: t('key') - use default namespace@@ -58,7 +58,7 @@ function extractTranslationKeysFromCode() {if (!keysMap.has(defaultNs)) {keysMap.set(defaultNs, new Set());}- keysMap.get(defaultNs).add(fullKey);+ keysMap.get(defaultNs)!.add(fullKey);}}});@@ -67,39 +67,45 @@ function extractTranslationKeysFromCode() {}// Get nested value from object using dot notation-function getNestedValue(obj, path) {- return path.split('.').reduce((current, key) => current?.[key], obj);+function getNestedValue(obj: NestedObject, dotPath: string): string | NestedObject | undefined {+ return dotPath.split('.').reduce<string | NestedObject | undefined>(+ (current, key) => (current && typeof current === 'object' ? (current as NestedObject)[key] : undefined),+ obj+ );}// Set nested value in object using dot notation-function setNestedValue(obj, path, value) {- const keys = path.split('.');- const lastKey = keys.pop();- const target = keys.reduce((current, key) => {+function setNestedValue(obj: NestedObject, dotPath: string, value: string): void {+ const keys = dotPath.split('.');+ const lastKey = keys.pop()!;+ const target = keys.reduce<NestedObject>((current, key) => {if (!(key in current)) {current[key] = {};}- return current[key];+ return current[key] as NestedObject;}, obj);target[lastKey] = value;}// Delete nested key from object-function deleteNestedKey(obj, path) {- const keys = path.split('.');- const lastKey = keys.pop();- const target = keys.reduce((current, key) => current?.[key], obj);+function deleteNestedKey(obj: NestedObject, dotPath: string): void {+ const keys = dotPath.split('.');+ const lastKey = keys.pop()!;+ const target = keys.reduce<NestedObject | undefined>(+ (current, key) => (current ? (current[key] as NestedObject) : undefined),+ obj+ );if (target && lastKey in target) {delete target[lastKey];}}// Clean empty objects recursively-function cleanEmptyObjects(obj) {+function cleanEmptyObjects(obj: NestedObject): void {Object.keys(obj).forEach(key => {if (obj[key] && typeof obj[key] === 'object' && !Array.isArray(obj[key])) {- cleanEmptyObjects(obj[key]);- if (Object.keys(obj[key]).length === 0) {+ cleanEmptyObjects(obj[key] as NestedObject);+ if (Object.keys(obj[key] as NestedObject).length === 0) {delete obj[key];}}@@ -107,12 +113,12 @@ function cleanEmptyObjects(obj) {}// Get all keys from nested object-function getAllKeys(obj, prefix = '') {- let keys = [];+function getAllKeys(obj: NestedObject, prefix: string = ''): string[] {+ let keys: string[] = [];for (const [key, value] of Object.entries(obj)) {const fullKey = prefix ? `${prefix}.${key}` : key;if (typeof value === 'object' && value !== null && !Array.isArray(value)) {- keys = keys.concat(getAllKeys(value, fullKey));+ keys = keys.concat(getAllKeys(value as NestedObject, fullKey));} else {keys.push(fullKey);}@@ -121,11 +127,11 @@ function getAllKeys(obj, prefix = '') {}// Sync translations-function syncTranslations() {- console.log('🔄 Starting translation sync...\n');+function syncTranslations(): void {+ console.log('\u{1F504} Starting translation sync...\n');// Step 1: Extract keys from code- console.log('📖 Step 1: Extracting translation keys from code...');+ console.log('\u{1F4D6} Step 1: Extracting translation keys from code...');const codeKeys = extractTranslationKeysFromCode();let totalCodeKeys = 0;@@ -133,36 +139,36 @@ function syncTranslations() {console.log(` Found ${totalCodeKeys} translation keys in code\n`);// Step 2: Load English (source) translations- console.log('📚 Step 2: Loading English translation files...');- const sourceTranslations = new Map();+ console.log('\u{1F4DA} Step 2: Loading English translation files...');+ const sourceTranslations = new Map<string, NestedObject>();- codeKeys.forEach((keys, namespace) => {+ codeKeys.forEach((_keys, namespace) => {const filePath = path.join(LOCALES_DIR, SOURCE_LANG, `${namespace}.json`);if (fs.existsSync(filePath)) {const rawContent = fs.readFileSync(filePath, 'utf-8').replace(/^\uFEFF/, ''); // Remove BOM- const content = JSON.parse(rawContent);+ const content: NestedObject = JSON.parse(rawContent);sourceTranslations.set(namespace, content);} else {sourceTranslations.set(namespace, {});- console.log(` ⚠️ Creating new namespace: ${namespace}`);+ console.log(` \u26A0\uFE0F Creating new namespace: ${namespace}`);}});console.log(` Loaded ${sourceTranslations.size} namespaces\n`);// Step 3: Sync English with code keys- console.log('🔧 Step 3: Syncing English translations with code...');+ console.log('\u{1F527} Step 3: Syncing English translations with code...');let enAdded = 0;let enRemoved = 0;codeKeys.forEach((keys, namespace) => {- const translation = sourceTranslations.get(namespace);+ const translation = sourceTranslations.get(namespace)!;const existingKeys = new Set(getAllKeys(translation));// Add missing keys to Englishkeys.forEach(key => {if (!existingKeys.has(key)) {setNestedValue(translation, key, `[EN] ${key}`);- console.log(` ✅ Added to EN [${namespace}]: ${key}`);+ console.log(` \u2705 Added to EN [${namespace}]: ${key}`);enAdded++;}});@@ -171,7 +177,7 @@ function syncTranslations() {existingKeys.forEach(key => {if (!keys.has(key)) {deleteNestedKey(translation, key);- console.log(` 🗑️ Removed from EN [${namespace}]: ${key}`);+ console.log(` \u{1F5D1}\uFE0F Removed from EN [${namespace}]: ${key}`);enRemoved++;}});@@ -187,7 +193,7 @@ function syncTranslations() {console.log(` Added ${enAdded} keys, removed ${enRemoved} keys\n`);// Step 4: Sync all other languages- console.log('🌍 Step 4: Syncing all other languages...');+ console.log('\u{1F30D} Step 4: Syncing all other languages...');const otherLanguages = LANGUAGES.filter(lang => lang !== SOURCE_LANG);let totalSynced = 0;@@ -195,18 +201,18 @@ function syncTranslations() {let langAdded = 0;let langRemoved = 0;- codeKeys.forEach((keys, namespace) => {- const sourceTranslation = sourceTranslations.get(namespace);+ codeKeys.forEach((_keys, namespace) => {+ const sourceTranslation = sourceTranslations.get(namespace)!;const targetFilePath = path.join(LOCALES_DIR, lang, `${namespace}.json`);// Load or create target translation- let targetTranslation = {};+ let targetTranslation: NestedObject = {};if (fs.existsSync(targetFilePath)) {try {const content = fs.readFileSync(targetFilePath, 'utf-8').replace(/^\uFEFF/, ''); // Remove BOMtargetTranslation = JSON.parse(content);} catch (error) {- console.log(` ⚠️ Corrupted file detected: ${lang}/${namespace}.json - recreating...`);+ console.log(` \u26A0\uFE0F Corrupted file detected: ${lang}/${namespace}.json - recreating...`);targetTranslation = {};}}@@ -253,13 +259,13 @@ function syncTranslations() {// Summaryconsole.log('=' .repeat(60));- console.log('📋 SYNC SUMMARY');+ console.log('\u{1F4CB} SYNC SUMMARY');console.log('='.repeat(60));- console.log(`✅ Code contains ${totalCodeKeys} translation keys`);- console.log(`📝 English: +${enAdded} added, -${enRemoved} removed`);- console.log(`🌍 Other languages: ${totalSynced} keys synced`);- console.log(`\n✨ Translation sync complete!\n`);- console.log('⚠️ NOTE: Placeholder text added for new keys.');+ console.log(`\u2705 Code contains ${totalCodeKeys} translation keys`);+ console.log(`\u{1F4DD} English: +${enAdded} added, -${enRemoved} removed`);+ console.log(`\u{1F30D} Other languages: ${totalSynced} keys synced`);+ console.log(`\n\u2728 Translation sync complete!\n`);+ console.log('\u26A0\uFE0F NOTE: Placeholder text added for new keys.');console.log(' Format: [LANG] original_key_name');console.log(' Please translate these manually or use AI translation.\n');}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/algo_live_runner.py b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/algo_live_runner.pyindex 92e527620..6dcfb11f4 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/algo_live_runner.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/algo_live_runner.py@@ -17,11 +17,24 @@ import timeimport osimport signalimport uuid+import loggingfrom datetime import datetimesys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from condition_evaluator import load_candles_from_db, evaluate_condition_group+# ── Heavy debug logging ──────────────────────────────────────────────+LOG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'algo_runner_debug.log')+logging.basicConfig(+ level=logging.DEBUG,+ format='%(asctime)s [%(levelname)s] %(message)s',+ handlers=[+ logging.FileHandler(LOG_FILE, mode='a', encoding='utf-8'),+ logging.StreamHandler(sys.stderr),+ ],+)+log = logging.getLogger('algo_runner')+# Graceful shutdownrunning = True@@ -34,7 +47,7 @@ signal.signal(signal.SIGINT, signal_handler)TIMEFRAME_SECONDS = {- '1m': 60, '3m': 180, '5m': 300, '10m': 600, '15m': 900,+ 'live': 1, '1m': 60, '3m': 180, '5m': 300, '10m': 600, '15m': 900,'30m': 1800, '1h': 3600, '4h': 14400, '1d': 86400,}@@ -139,15 +152,45 @@ def create_order_signal(db_path: str, deploy_id: str, symbol: str, side: str,return signal_id+def _normalize_symbol(s: str) -> str:+ """Strip slashes, dashes, underscores and uppercase for matching."""+ return s.replace('/', '').replace('-', '').replace('_', '').replace(':', '').upper()++def get_current_price(db_path: str, symbol: str) -> float:- """Get latest price from strategy_price_cache."""+ """Get latest price from strategy_price_cache.++ Tries exact match first, then normalized match to handle symbol format+ differences (e.g., BTC/USD vs BTCUSD, NSE:RELIANCE vs RELIANCE).+ """conn = sqlite3.connect(db_path)+ # Try exact match firstrow = conn.execute(- "SELECT price FROM strategy_price_cache WHERE symbol = ?",+ "SELECT price FROM strategy_price_cache WHERE symbol = ? ORDER BY updated_at DESC LIMIT 1",(symbol,)).fetchone()+ if row:+ conn.close()+ log.debug(f" get_current_price({symbol}) = {row[0]} (exact match)")+ return row[0]++ # Try normalized match: load all symbols and compare normalized forms+ norm = _normalize_symbol(symbol)+ rows = conn.execute(+ "SELECT symbol, price FROM strategy_price_cache ORDER BY updated_at DESC"+ ).fetchall()conn.close()- return row[0] if row else 0.0++ log.debug(f" get_current_price({symbol}) exact miss. Normalized={norm}. Cache has {len(rows)} entries: {[(s, p) for s, p in rows[:10]]}")++ for (cached_sym, price) in rows:+ cached_norm = _normalize_symbol(cached_sym)+ if cached_norm == norm or norm.startswith(cached_norm) or cached_norm.startswith(norm):+ log.debug(f" get_current_price({symbol}) = {price} (normalized/prefix match via '{cached_sym}')")+ return price++ log.warning(f" get_current_price({symbol}) = 0.0 (NO MATCH in price cache)")+ return 0.0def check_risk_management(current_price: float, position: dict, strategy: dict) -> str:@@ -194,14 +237,30 @@ def main():parser.add_argument('--db', required=True)args = parser.parse_args()- sys.stderr.write(f"[algo_runner] Starting deployment {args.deploy_id} for {args.symbol}\n")+ log.info("=" * 70)+ log.info("ALGO LIVE RUNNER STARTING")+ log.info(f" deploy_id = {args.deploy_id}")+ log.info(f" strategy_id= {args.strategy_id}")+ log.info(f" symbol = {args.symbol}")+ log.info(f" provider = {args.provider}")+ log.info(f" mode = {args.mode}")+ log.info(f" timeframe = {args.timeframe}")+ log.info(f" quantity = {args.quantity}")+ log.info(f" db = {args.db}")+ log.info(f" pid = {os.getpid()}")+ log.info("=" * 70)# Load strategystrategy = load_strategy(args.db, args.strategy_id)if not strategy:+ log.error(f"Strategy {args.strategy_id} NOT FOUND in DB!")update_deployment_status(args.db, args.deploy_id, 'error', 'Strategy not found')sys.exit(1)+ log.info(f"Strategy loaded OK. Entry conditions: {json.dumps(strategy['entry_conditions'], indent=2)}")+ log.info(f"Exit conditions: {json.dumps(strategy['exit_conditions'], indent=2)}")+ log.info(f"Risk: SL={strategy.get('stop_loss')}, TP={strategy.get('take_profit')}, TS={strategy.get('trailing_stop')}")+update_deployment_status(args.db, args.deploy_id, 'running')# Inject logic operators into condition lists@@ -216,28 +275,54 @@ def main():max_drawdown = 0.0peak_pnl = 0.0last_candle_time = 0+ loop_count = 0- interval = TIMEFRAME_SECONDS.get(args.timeframe, 300)- check_interval = max(interval // 2, 5) # check at half the timeframe interval, min 5s+ is_live = args.timeframe == 'live'+ interval = 1 if is_live else TIMEFRAME_SECONDS.get(args.timeframe, 300)+ check_interval = 1 if is_live else max(interval // 2, 5)+ log.info(f"Timeframe interval={interval}s, check_interval={check_interval}s, live_mode={is_live}")while running:+ loop_count += 1try:- # Load candles- df = load_candles_from_db(args.db, args.symbol, args.timeframe, limit=200)- if df.empty or len(df) < 10:+ # Load candles (live mode needs fewer rows since each row is a tick)+ candle_limit = 50 if is_live else 200+ df = load_candles_from_db(args.db, args.symbol, args.timeframe, limit=candle_limit)+ if df.empty or len(df) < 2:+ if loop_count <= 5 or loop_count % 20 == 0:+ log.warning(f"[loop#{loop_count}] Candle data insufficient: {len(df)} rows (need >=2) for {args.symbol}@{args.timeframe}")+ # Dump what symbols exist in candle_cache+ try:+ conn_debug = sqlite3.connect(args.db)+ syms = conn_debug.execute("SELECT DISTINCT symbol, timeframe, COUNT(*) FROM candle_cache GROUP BY symbol, timeframe").fetchall()+ conn_debug.close()+ log.warning(f" candle_cache contents: {syms}")+ except Exception as dbg_e:+ log.warning(f" could not read candle_cache: {dbg_e}")time.sleep(check_interval)continue# Check if we have new datanewest_time = int(df['open_time'].iloc[-1]) if 'open_time' in df.columns else 0- if newest_time == last_candle_time:+ if not is_live and newest_time == last_candle_time:+ if loop_count <= 3 or loop_count % 60 == 0:+ log.debug(f"[loop#{loop_count}] No new candle (last={last_candle_time}), {len(df)} candles loaded. Sleeping {check_interval}s")time.sleep(check_interval)continuelast_candle_time = newest_time+ if is_live:+ if loop_count <= 3 or loop_count % 100 == 0:+ log.info(f"[loop#{loop_count}] LIVE tick eval, {len(df)} ticks, latest_price={df['close'].iloc[-1]}")+ else:+ log.info(f"[loop#{loop_count}] NEW candle detected! open_time={newest_time}, total candles={len(df)}")+ log.debug(f" Last 3 candles: {df[['open_time','open','high','low','close','volume']].tail(3).to_string()}")current_price = get_current_price(args.db, args.symbol)+ price_source = "price_cache"if current_price <= 0:current_price = float(df['close'].iloc[-1])+ price_source = "last_candle_close"+ log.info(f" Current price = {current_price} (source: {price_source})")# Check risk management firstif position['qty'] != 0:@@ -247,9 +332,11 @@ def main():else:pnl_pct = (position['entry'] - current_price) / position['entry'] * 100position['max_pnl_pct'] = max(position.get('max_pnl_pct', 0), pnl_pct)+ log.debug(f" Position: {position['side']} qty={position['qty']} entry={position['entry']} pnl%={pnl_pct:.2f}%")risk_exit = check_risk_management(current_price, position, strategy)if risk_exit:+ log.info(f" RISK EXIT TRIGGERED: {risk_exit}")# Close positionpnl = (current_price - position['entry']) * position['qty'] if position['side'] == 'BUY' \else (position['entry'] - current_price) * position['qty']@@ -269,10 +356,18 @@ def main():position = {'qty': 0, 'side': '', 'entry': 0, 'max_pnl_pct': 0}# Evaluate conditions+ verbose_log = not is_live or loop_count <= 3 or loop_count % 100 == 0if position['qty'] == 0:# No position: check entry conditionsentry_result = evaluate_condition_group(entry_conds, df)+ if verbose_log:+ log.info(f" ENTRY eval => result={entry_result['result']}, logic={entry_result.get('logic','AND')}")+ for i, d in enumerate(entry_result.get('details', [])):+ log.info(f" cond[{i}]: {d.get('indicator','')} {d.get('operator','')} target={d.get('target','')} "+ f"computed={d.get('computed_value','')} met={d.get('met',False)} "+ f"{'ERROR: '+d.get('error','') if d.get('error') else ''}")if entry_result['result']:+ log.info(f" >>> ENTRY SIGNAL FIRED! BUY {args.quantity} @ {current_price}")# Enter positionposition = {'qty': args.quantity,@@ -291,7 +386,14 @@ def main():else:# In position: check exit conditionsexit_result = evaluate_condition_group(exit_conds, df)+ if verbose_log:+ log.info(f" EXIT eval => result={exit_result['result']}, logic={exit_result.get('logic','AND')}")+ for i, d in enumerate(exit_result.get('details', [])):+ log.info(f" cond[{i}]: {d.get('indicator','')} {d.get('operator','')} target={d.get('target','')} "+ f"computed={d.get('computed_value','')} met={d.get('met',False)} "+ f"{'ERROR: '+d.get('error','') if d.get('error') else ''}")if exit_result['result']:+ log.info(f" >>> EXIT SIGNAL FIRED!")# Exit positionpnl = (current_price - position['entry']) * position['qty'] if position['side'] == 'BUY' \else (position['entry'] - current_price) * position['qty']@@ -341,15 +443,18 @@ def main():'current_position_entry': position['entry'],})+ if loop_count <= 5 or loop_count % 30 == 0:+ log.info(f" Metrics: pnl={total_pnl:.2f} unrealized={unrealized:.2f} trades={total_trades} win%={win_rate:.1f} dd={max_drawdown:.2f}")+time.sleep(check_interval)except Exception as e:- sys.stderr.write(f"[algo_runner] Error: {e}\n")+ log.error(f"[loop#{loop_count}] EXCEPTION: {e}", exc_info=True)time.sleep(check_interval)# Shutdown: update statusupdate_deployment_status(args.db, args.deploy_id, 'stopped')- sys.stderr.write(f"[algo_runner] Deployment {args.deploy_id} stopped\n")+ log.info(f"Deployment {args.deploy_id} STOPPED. Total trades={total_trades}, PnL={total_pnl:.2f}")if __name__ == '__main__':diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.pyindex 069d094fa..e7f5d003a 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.py@@ -30,14 +30,28 @@ import sqlite3import pandas as pdimport mathimport os+import loggingsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from indicators import get_latest_value, get_last_n_values, get_value_at_offset+log = logging.getLogger('algo_runner.evaluator')+++def _normalize_symbol(s: str) -> str:+ """Strip slashes, dashes, underscores, colons and uppercase for matching."""+ return s.replace('/', '').replace('-', '').replace('_', '').replace(':', '').upper()+def load_candles_from_db(db_path: str, symbol: str, timeframe: str, limit: int = 200) -> pd.DataFrame:- """Load candles from candle_cache table."""+ """Load candles from candle_cache table.++ Tries exact symbol match first, then falls back to normalized matching+ to handle format differences (e.g., BTC/USD vs BTCUSD, NSE:RELIANCE vs RELIANCE).+ """conn = sqlite3.connect(db_path)++ # Try exact match firstquery = """SELECT open_time, o, h, l, c, volumeFROM candle_cache@@ -46,9 +60,32 @@ def load_candles_from_db(db_path: str, symbol: str, timeframe: str, limit: int =LIMIT ?"""df = pd.read_sql_query(query, conn, params=(symbol, timeframe, limit))+ log.debug(f"load_candles_from_db('{symbol}', '{timeframe}', limit={limit}) exact match => {len(df)} rows")++ if df.empty:+ # Fallback: find the actual symbol name in the cache that matches when normalized+ # Also handles broker truncation (e.g., Angel One truncates "AVANTIFEEDS" to "AVANTIFEED")+ norm = _normalize_symbol(symbol)+ try:+ cached_symbols = pd.read_sql_query(+ "SELECT DISTINCT symbol FROM candle_cache WHERE timeframe = ?",+ conn, params=(timeframe,)+ )+ log.debug(f" Exact match failed. Trying normalized={norm}. Cached symbols for tf={timeframe}: {cached_symbols['symbol'].tolist()}")+ for _, row in cached_symbols.iterrows():+ cached_sym = row['symbol']+ cached_norm = _normalize_symbol(cached_sym)+ if cached_norm == norm or norm.startswith(cached_norm) or cached_norm.startswith(norm):+ df = pd.read_sql_query(query, conn, params=(cached_sym, timeframe, limit))+ log.debug(f" Normalized/prefix match found: '{cached_sym}' => {len(df)} rows")+ break+ except Exception as e:+ log.warning(f" Fallback symbol search failed: {e}")+conn.close()if df.empty:+ log.warning(f" NO candle data found for '{symbol}' @ {timeframe}")return pd.DataFrame(columns=['open', 'high', 'low', 'close', 'volume'])df.rename(columns={'o': 'open', 'h': 'high', 'l': 'low', 'c': 'close'}, inplace=True)@@ -368,7 +405,7 @@ def main():# Load candle datadf = load_candles_from_db(args.db, args.symbol, args.timeframe, args.limit)- if df.empty or len(df) < 5:+ if df.empty or len(df) < 2:print(json.dumps({'success': False,'error': f'Insufficient candle data for {args.symbol} ({len(df)} candles)'diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/base_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/base_agent.pyindex b20b24745..e37d934a9 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/base_agent.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/base_agent.py@@ -364,32 +364,28 @@ class LLMTradingAgent(BaseTradingAgent):)async def initialize(self) -> bool:- """Initialize the LLM agent."""- self._mock_reason = None # Track why we're in mock mode+ """Initialize the LLM agent. Returns False if LLM cannot be created."""+ self._init_error = Nonetry:self._llm = await self._create_llm()if self._llm is None:- self._mock_reason = "agno library not available"- logger.warning(f"LLM agent '{self.name}' initialized in MOCK mode ({self._mock_reason})")+ self._init_error = "agno library not available - install with: pip install agno"+ logger.error(f"LLM agent '{self.name}' FAILED to initialize: {self._init_error}")+ self._initialized = False+ return Falseawait super().initialize()return Trueexcept Exception as e:logger.error(f"Failed to initialize LLM agent '{self.name}': {e}")self._llm = None- self._mock_reason = str(e)- await super().initialize()- logger.warning(f"Agent '{self.name}' will use MOCK decisions: {self._mock_reason}")- return True-- @property- def is_mock_mode(self) -> bool:- """Whether this agent is running in mock mode (no real LLM)."""- return self._llm is None+ self._init_error = str(e)+ self._initialized = False+ return False@property- def mock_mode_reason(self) -> Optional[str]:- """Reason for being in mock mode, or None if using real LLM."""- return getattr(self, '_mock_reason', None)+ def init_error(self) -> Optional[str]:+ """Error message if initialization failed, or None if successful."""+ return getattr(self, '_init_error', None)async def _create_llm(self):"""Create the LLM instance based on provider."""@@ -531,9 +527,11 @@ class LLMTradingAgent(BaseTradingAgent):prompt = self._build_prompt(market_data, portfolio, cycle_number)if self._llm is None:- # Mock decision for testing- logger.warning(f"Agent '{self.name}' using mock decision (no LLM available)")- return self._mock_decision(market_data, cycle_number)+ init_error = getattr(self, '_init_error', 'unknown')+ raise RuntimeError(+ f"Agent '{self.name}' has no LLM configured and cannot make real trading decisions. "+ f"Reason: {init_error}. Configure a valid API key and LLM provider."+ )# Handle Fincept custom APIif self._llm == "fincept_custom":@@ -972,22 +970,3 @@ Respond ONLY with the JSON object, nothing else.price_at_decision=market_data.price,)- def _mock_decision(self, market_data: MarketData, cycle_number: int) -> ModelDecision:- """Generate a mock decision for testing."""- import random-- actions = [TradeAction.BUY, TradeAction.SELL, TradeAction.HOLD]- action = random.choice(actions)- mock_reason = getattr(self, '_mock_reason', 'unknown')-- return ModelDecision(- competition_id="",- model_name=self.name,- cycle_number=cycle_number,- action=action,- symbol=market_data.symbol,- quantity=0.01 if action != TradeAction.HOLD else 0,- confidence=0.0, # Zero confidence for mock decisions- reasoning=f"[MOCK MODE - {mock_reason}] Random decision: {action.value}. Configure a valid API key in Settings > LLM Config to enable real LLM decisions.",- price_at_decision=market_data.price,- )diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/broker_adapter.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/broker_adapter.pyindex 3739a296d..bebc731f3 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/broker_adapter.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/broker_adapter.py@@ -371,34 +371,31 @@ class MultiExchangeDataProvider:return cached# Fetch based on exchange- try:- if exchange == "kraken":- data = await self._fetch_kraken(symbol)- elif exchange == "binance":- data = await self._fetch_binance(symbol)- elif exchange == "okx":- data = await self._fetch_okx(symbol)- elif exchange == "coinbase":- data = await self._fetch_coinbase(symbol)- elif exchange == "bybit":- data = await self._fetch_bybit(symbol)- elif exchange == "kucoin":- data = await self._fetch_kucoin(symbol)- elif exchange == "gateio":- data = await self._fetch_gateio(symbol)- elif exchange == "hyperliquid":- data = await self._fetch_hyperliquid(symbol)- else:- # For stock brokers, use mock data (live would require Rust bridge)- logger.info(f"Using mock data for {exchange}:{symbol} (stock broker or unsupported)")- data = self._mock_data(symbol)+ if exchange == "kraken":+ data = await self._fetch_kraken(symbol)+ elif exchange == "binance":+ data = await self._fetch_binance(symbol)+ elif exchange == "okx":+ data = await self._fetch_okx(symbol)+ elif exchange == "coinbase":+ data = await self._fetch_coinbase(symbol)+ elif exchange == "bybit":+ data = await self._fetch_bybit(symbol)+ elif exchange == "kucoin":+ data = await self._fetch_kucoin(symbol)+ elif exchange == "gateio":+ data = await self._fetch_gateio(symbol)+ elif exchange == "hyperliquid":+ data = await self._fetch_hyperliquid(symbol)+ else:+ raise RuntimeError(+ f"Live market data not available for '{exchange}'. "+ f"Stock brokers require Rust bridge integration. "+ f"Supported crypto exchanges: kraken, binance, okx, coinbase, bybit, kucoin, gateio, hyperliquid."+ )- self._cache[cache_key] = data- return data-- except Exception as e:- logger.error(f"Error fetching {symbol} from {exchange}: {e}")- return self._mock_data(symbol)+ self._cache[cache_key] = data+ return dataasync def _fetch_kraken(self, symbol: str) -> MarketData:"""Fetch from Kraken API."""@@ -411,15 +408,19 @@ class MultiExchangeDataProvider:url = f"https://api.kraken.com/0/public/Ticker?pair={pair}"if not self._client:- return self._mock_data(symbol)+ raise RuntimeError("HTTP client not initialized. Call initialize() first.")response = await self._client.get(url)data = response.json()if data.get("error"):- return self._mock_data(symbol)+ raise RuntimeError(f"Kraken API error for {symbol}: {data['error']}")++ results = data.get("result", {})+ if not results:+ raise RuntimeError(f"No data returned from Kraken for {symbol}")- result = list(data.get("result", {}).values())[0]+ result = list(results.values())[0]return MarketData(symbol=symbol,@@ -441,11 +442,14 @@ class MultiExchangeDataProvider:url = f"https://api.binance.com/api/v3/ticker/24hr?symbol={pair}"if not self._client:- return self._mock_data(symbol)+ raise RuntimeError("HTTP client not initialized. Call initialize() first.")response = await self._client.get(url)data = response.json()+ if isinstance(data, dict) and data.get("code"):+ raise RuntimeError(f"Binance API error for {symbol}: {data.get('msg', data)}")+return MarketData(symbol=symbol,price=float(data["lastPrice"]),@@ -463,13 +467,13 @@ class MultiExchangeDataProvider:url = f"https://www.okx.com/api/v5/market/ticker?instId={pair}"if not self._client:- return self._mock_data(symbol)+ raise RuntimeError("HTTP client not initialized. Call initialize() first.")response = await self._client.get(url)data = response.json()if data.get("code") != "0" or not data.get("data"):- return self._mock_data(symbol)+ raise RuntimeError(f"OKX API error for {symbol}: code={data.get('code')}, msg={data.get('msg', 'no data')}")ticker = data["data"][0]@@ -490,18 +494,25 @@ class MultiExchangeDataProvider:url = f"https://api.exchange.coinbase.com/products/{pair}/ticker"if not self._client:- return self._mock_data(symbol)+ raise RuntimeError("HTTP client not initialized. Call initialize() first.")response = await self._client.get(url)data = response.json()+ if data.get("message"):+ raise RuntimeError(f"Coinbase API error for {symbol}: {data['message']}")++ price = float(data.get("price", 0))+ if price == 0:+ raise RuntimeError(f"Coinbase returned zero price for {symbol}")+return MarketData(symbol=symbol,- price=float(data.get("price", 0)),+ price=price,bid=float(data.get("bid", 0)),ask=float(data.get("ask", 0)),- high_24h=float(data.get("price", 0)) * 1.02,- low_24h=float(data.get("price", 0)) * 0.98,+ high_24h=price * 1.02,+ low_24h=price * 0.98,volume_24h=float(data.get("volume", 0)),timestamp=datetime.now(),)@@ -512,13 +523,13 @@ class MultiExchangeDataProvider:url = f"https://api.bybit.com/v5/market/tickers?category=spot&symbol={pair}"if not self._client:- return self._mock_data(symbol)+ raise RuntimeError("HTTP client not initialized. Call initialize() first.")response = await self._client.get(url)data = response.json()if data.get("retCode") != 0 or not data.get("result", {}).get("list"):- return self._mock_data(symbol)+ raise RuntimeError(f"Bybit API error for {symbol}: retCode={data.get('retCode')}, msg={data.get('retMsg', 'no data')}")ticker = data["result"]["list"][0]@@ -539,13 +550,13 @@ class MultiExchangeDataProvider:url = f"https://api.kucoin.com/api/v1/market/stats?symbol={pair}"if not self._client:- return self._mock_data(symbol)+ raise RuntimeError("HTTP client not initialized. Call initialize() first.")response = await self._client.get(url)data = response.json()if data.get("code") != "200000" or not data.get("data"):- return self._mock_data(symbol)+ raise RuntimeError(f"KuCoin API error for {symbol}: code={data.get('code')}, msg={data.get('msg', 'no data')}")ticker = data["data"]@@ -566,30 +577,26 @@ class MultiExchangeDataProvider:url = f"https://api.gateio.ws/api/v4/spot/tickers?currency_pair={pair}"if not self._client:- return self._mock_data(symbol)+ raise RuntimeError("HTTP client not initialized. Call initialize() first.")- try:- response = await self._client.get(url)- data = response.json()-- if not data or len(data) == 0:- return self._mock_data(symbol)-- ticker = data[0]-- return MarketData(- symbol=symbol,- price=float(ticker.get("last", 0)),- bid=float(ticker.get("highest_bid", 0)),- ask=float(ticker.get("lowest_ask", 0)),- high_24h=float(ticker.get("high_24h", 0)),- low_24h=float(ticker.get("low_24h", 0)),- volume_24h=float(ticker.get("base_volume", 0)),- timestamp=datetime.now(),- )- except Exception as e:- logger.error(f"Gate.io fetch error: {e}")- return self._mock_data(symbol)+ response = await self._client.get(url)+ data = response.json()++ if not data or len(data) == 0:+ raise RuntimeError(f"Gate.io returned no data for {symbol}")++ ticker = data[0]++ return MarketData(+ symbol=symbol,+ price=float(ticker.get("last", 0)),+ bid=float(ticker.get("highest_bid", 0)),+ ask=float(ticker.get("lowest_ask", 0)),+ high_24h=float(ticker.get("high_24h", 0)),+ low_24h=float(ticker.get("low_24h", 0)),+ volume_24h=float(ticker.get("base_volume", 0)),+ timestamp=datetime.now(),+ )async def _fetch_hyperliquid(self, symbol: str) -> MarketData:"""Fetch from HyperLiquid API."""@@ -598,60 +605,29 @@ class MultiExchangeDataProvider:url = "https://api.hyperliquid.xyz/info"if not self._client:- return self._mock_data(symbol)+ raise RuntimeError("HTTP client not initialized. Call initialize() first.")- try:- # HyperLiquid requires POST request with JSON body- payload = {- "type": "allMids"- }- response = await self._client.post(url, json=payload)- data = response.json()-- if base_symbol not in data:- return self._mock_data(symbol)-- mid_price = float(data[base_symbol])- spread = mid_price * 0.0001 # 0.01% spread estimate-- return MarketData(- symbol=symbol,- price=mid_price,- bid=mid_price - spread,- ask=mid_price + spread,- high_24h=mid_price * 1.02,- low_24h=mid_price * 0.98,- volume_24h=0, # HyperLiquid doesn't provide volume in allMids- timestamp=datetime.now(),- )- except Exception as e:- logger.error(f"HyperLiquid fetch error: {e}")- return self._mock_data(symbol)-- def _mock_data(self, symbol: str) -> MarketData:- """Generate mock data."""- import random-- base_prices = {- "BTC/USD": 95000.0, "BTC/USDT": 95000.0,- "ETH/USD": 3500.0, "ETH/USDT": 3500.0,- "SOL/USD": 180.0, "SOL/USDT": 180.0,- "XRP/USD": 2.5, "XRP/USDT": 2.5,+ # HyperLiquid requires POST request with JSON body+ payload = {+ "type": "allMids"}+ response = await self._client.post(url, json=payload)+ data = response.json()- base_price = base_prices.get(symbol, 100.0)- variation = base_price * 0.001- price = base_price + random.uniform(-variation, variation)- spread = price * 0.0005+ if base_symbol not in data:+ raise RuntimeError(f"HyperLiquid has no data for {base_symbol} (symbol: {symbol})")++ mid_price = float(data[base_symbol])+ spread = mid_price * 0.0001 # 0.01% spread estimatereturn MarketData(symbol=symbol,- price=price,- bid=price - spread,- ask=price + spread,- high_24h=price * 1.02,- low_24h=price * 0.98,- volume_24h=random.uniform(1000, 10000),+ price=mid_price,+ bid=mid_price - spread,+ ask=mid_price + spread,+ high_24h=mid_price * 1.02,+ low_24h=mid_price * 0.98,+ volume_24h=0, # HyperLiquid doesn't provide volume in allMidstimestamp=datetime.now(),)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.pyindex 68c79eb65..aae2f713c 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.py@@ -106,8 +106,9 @@ class AlphaArenaCompetition:)logger.info(f"Market data provider initialized for {self.config.exchange_id}")except asyncio.TimeoutError:- logger.warning(f"Market data provider initialization timed out, using mock data")- self._market_provider = await get_market_data_provider(self.config.exchange_id)+ logger.error(f"Market data provider initialization timed out for {self.config.exchange_id}")+ self.status = CompetitionStatus.FAILED+ return False# Create agents and trading engines for each modelfor model in self.config.models:@@ -158,24 +159,25 @@ class AlphaArenaCompetition:initial_capital=agent_capital,)- # Initialize with timeout+ # Initialize with timeout - agent MUST succeed with real LLMtry:init_success = await asyncio.wait_for(agent.initialize(),timeout=30.0)if init_success:- if hasattr(agent, 'is_mock_mode') and agent.is_mock_mode:- reason = agent.mock_mode_reason or 'unknown'- logger.warning(f"Agent {model.name} is in MOCK MODE: {reason}")- else:- logger.info(f"Agent {model.name} initialized successfully with real LLM")+ logger.info(f"Agent {model.name} initialized successfully with real LLM")+ self._agents[model.name] = agentelse:- logger.warning(f"Agent {model.name} initialization returned False, using mock mode")+ init_error = getattr(agent, 'init_error', 'unknown')+ logger.error(f"Agent {model.name} failed to initialize: {init_error}")+ continue # Skip this agentexcept asyncio.TimeoutError:- logger.warning(f"Agent {model.name} initialization timed out, using mock mode")-- self._agents[model.name] = agent+ logger.error(f"Agent {model.name} initialization timed out - skipping")+ continue # Skip this agent+ except Exception as agent_init_error:+ logger.error(f"Agent {model.name} initialization error: {agent_init_error}")+ continue # Skip this agent# Create trading engine (database-backed bridge to main paper trading)engine = create_paper_trading_bridge(@@ -187,6 +189,16 @@ class AlphaArenaCompetition:self._engines[model.name] = enginelogger.info(f"Trading engine (DB-backed) created for {model.name} with capital ${model.initial_capital or self.config.initial_capital}")+ # Validate enough agents initialized with real LLMs+ if len(self._agents) < 2:+ failed_count = len(self.config.models) - len(self._agents)+ logger.error(+ f"Only {len(self._agents)} agent(s) initialized successfully out of {len(self.config.models)}. "+ f"Need at least 2 agents for a competition."+ )+ self.status = CompetitionStatus.FAILED+ return False+self.status = CompetitionStatus.CREATEDlogger.info(f"Competition {self.competition_id} initialized with {len(self._agents)} agents")return True@@ -237,8 +249,8 @@ class AlphaArenaCompetition:# Ensure market provider is initializedif self._market_provider is None:- logger.warning("Market provider not initialized, initializing now...")- self._market_provider = await get_market_data_provider(self.config.exchange_id)+ yield error("Market data provider not initialized. Cannot run cycle without live market data.")+ returnmarket = await self._market_provider.get_ticker(symbol)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.pyindex b467c62c0..4a47b751d 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py@@ -88,38 +88,40 @@ class MarketDataProvider:async def get_tickers(self, symbols: List[str]) -> Dict[str, MarketData]:"""Get ticker data for multiple symbols."""results = {}+ errors = []for symbol in symbols:try:results[symbol] = await self.get_ticker(symbol)except Exception as e:logger.error(f"Failed to fetch {symbol}: {e}")+ errors.append(f"{symbol}: {e}")+ if errors and not results:+ raise RuntimeError(f"Failed to fetch any market data: {'; '.join(errors)}")return resultsasync def _fetch_kraken(self, symbol: str) -> MarketData:"""Fetch data from Kraken."""- # Convert symbol format+ # Convert symbol format - just strip the slash.+ # Kraken accepts simple pairs like BTCUSD, ETHUSD, etc.pair = symbol.replace("/", "")- if pair.endswith("USD"):- pair = pair.replace("USD", "ZUSD")- if pair.startswith("BTC"):- pair = pair.replace("BTC", "XBT")url = f"https://api.kraken.com/0/public/Ticker?pair={pair}"- if not HTTPX_AVAILABLE or not self._client:- return self._mock_market_data(symbol)+ if not HTTPX_AVAILABLE:+ raise RuntimeError("httpx is not installed. Install it with: pip install httpx")+ if not self._client:+ raise RuntimeError("HTTP client not initialized. Call initialize() first.")try:response = await self._client.get(url)data = response.json()if data.get("error") and len(data["error"]) > 0:- logger.warning(f"Kraken API error: {data['error']}")- return self._mock_market_data(symbol)+ raise RuntimeError(f"Kraken API error for {symbol}: {data['error']}")result = data.get("result", {})if not result:- return self._mock_market_data(symbol)+ raise RuntimeError(f"No data returned from Kraken for {symbol}")# Get first result (there should only be one)ticker_data = list(result.values())[0]@@ -135,17 +137,21 @@ class MarketDataProvider:timestamp=datetime.now(),)+ except RuntimeError:+ raiseexcept Exception as e:logger.error(f"Kraken fetch error for {symbol}: {e}")- return self._mock_market_data(symbol)+ raise RuntimeError(f"Failed to fetch {symbol} from Kraken: {e}") from easync def _fetch_binance(self, symbol: str) -> MarketData:"""Fetch data from Binance."""pair = symbol.replace("/", "")url = f"https://api.binance.com/api/v3/ticker/24hr?symbol={pair}"- if not HTTPX_AVAILABLE or not self._client:- return self._mock_market_data(symbol)+ if not HTTPX_AVAILABLE:+ raise RuntimeError("httpx is not installed. Install it with: pip install httpx")+ if not self._client:+ raise RuntimeError("HTTP client not initialized. Call initialize() first.")try:response = await self._client.get(url)@@ -162,41 +168,17 @@ class MarketDataProvider:timestamp=datetime.now(),)+ except RuntimeError:+ raiseexcept Exception as e:logger.error(f"Binance fetch error for {symbol}: {e}")- return self._mock_market_data(symbol)+ raise RuntimeError(f"Failed to fetch {symbol} from Binance: {e}") from easync def _fetch_generic(self, symbol: str) -> MarketData:- """Fallback fetch using mock data."""- logger.warning(f"Using mock data for {symbol}")- return self._mock_market_data(symbol)-- def _mock_market_data(self, symbol: str) -> MarketData:- """Generate mock market data for testing."""- import random-- base_prices = {- "BTC/USD": 95000.0,- "ETH/USD": 3500.0,- "SOL/USD": 180.0,- "XRP/USD": 2.5,- }-- base_price = base_prices.get(symbol, 100.0)- variation = base_price * 0.001 # 0.1% variation-- price = base_price + random.uniform(-variation, variation)- spread = price * 0.0005 # 0.05% spread-- return MarketData(- symbol=symbol,- price=price,- bid=price - spread,- ask=price + spread,- high_24h=price * 1.02,- low_24h=price * 0.98,- volume_24h=random.uniform(1000, 10000),- timestamp=datetime.now(),+ """Fallback for unsupported exchanges - raises error."""+ raise RuntimeError(+ f"Unsupported exchange '{self.exchange_id}' for {symbol}. "+ f"Supported exchanges: kraken, binance. Configure a supported exchange.")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading_bridge.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading_bridge.pyindex 448ad8ddb..a22123dac 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading_bridge.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading_bridge.py@@ -321,6 +321,20 @@ class PaperTradingBridge:def _link_model_portfolio(self, conn: sqlite3.Connection):"""Link this portfolio to the Alpha Arena competition."""try:+ # Ensure the table exists without foreign key constraints+ # (competition data lives in a separate alpha_arena.db, not in this main db)+ conn.execute("""+ CREATE TABLE IF NOT EXISTS alpha_arena_model_portfolios (+ id TEXT PRIMARY KEY,+ competition_id TEXT NOT NULL,+ model_name TEXT NOT NULL,+ portfolio_id TEXT NOT NULL,+ initial_capital REAL NOT NULL,+ created_at TEXT NOT NULL+ )+ """)+ conn.commit()+link_id = str(uuid.uuid4())now = datetime.utcnow().isoformat() + "Z"@@ -340,8 +354,35 @@ class PaperTradingBridge:conn.commit()logger.info(f"Linked model {self.model_name} to portfolio {self.portfolio_id}")except sqlite3.Error as e:- # Table might not exist yet, that's ok- logger.warning(f"Could not link model portfolio: {e}")+ # If foreign key constraint fails due to old table schema, try to recreate+ if "FOREIGN KEY" in str(e):+ try:+ conn.execute("DROP TABLE IF EXISTS alpha_arena_model_portfolios")+ conn.execute("""+ CREATE TABLE alpha_arena_model_portfolios (+ id TEXT PRIMARY KEY,+ competition_id TEXT NOT NULL,+ model_name TEXT NOT NULL,+ portfolio_id TEXT NOT NULL,+ initial_capital REAL NOT NULL,+ created_at TEXT NOT NULL+ )+ """)+ link_id = str(uuid.uuid4())+ now = datetime.utcnow().isoformat() + "Z"+ conn.execute(+ """INSERT INTO alpha_arena_model_portfolios+ (id, competition_id, model_name, portfolio_id, initial_capital, created_at)+ VALUES (?, ?, ?, ?, ?, ?)""",+ (link_id, self.competition_id, self.model_name,+ self.portfolio_id, self.initial_capital, now)+ )+ conn.commit()+ logger.info(f"Recreated table and linked model {self.model_name} to portfolio {self.portfolio_id}")+ except sqlite3.Error as e2:+ logger.warning(f"Could not recreate model portfolio link: {e2}")+ else:+ logger.warning(f"Could not link model portfolio: {e}")def get_portfolio(self) -> Optional[Portfolio]:"""Get current portfolio state."""diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/sentiment_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/sentiment_agent.pyindex 7d84e51b4..e1b648475 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/sentiment_agent.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/sentiment_agent.py@@ -213,11 +213,16 @@ class SentimentAgent(BaseAgent):try:import json+ import asyncio# Import and use existing fetch_company_newssys.path.insert(0, str(scripts_dir))from fetch_company_news import fetch_company_news- result = fetch_company_news(query, max_results, period)+ # Run blocking news fetch in thread executor to avoid blocking event loop+ loop = asyncio.get_event_loop()+ result = await loop.run_in_executor(+ None, fetch_company_news, query, max_results, period+ )data = json.loads(result)if not data.get("success"):@@ -355,15 +360,37 @@ class SentimentAgent(BaseAgent):Returns:Aggregated market mood"""+ import asyncio+results = {}total_score = 0.0-- for symbol in symbols:- sentiment = await self.analyze_sentiment(symbol)- results[symbol] = sentiment.to_dict()+ analyzed_count = 0++ async def _analyze_one(sym: str) -> tuple:+ """Analyze a single symbol with timeout."""+ try:+ sentiment = await asyncio.wait_for(+ self.analyze_sentiment(sym, max_articles=5),+ timeout=10.0,+ )+ return sym, sentiment+ except asyncio.TimeoutError:+ logger.warning(f"Sentiment timeout for {sym}")+ return sym, SentimentResult(symbol=sym, confidence=0.0)+ except Exception as e:+ logger.warning(f"Sentiment error for {sym}: {e}")+ return sym, SentimentResult(symbol=sym, confidence=0.0)++ # Run all symbols concurrently+ tasks = [_analyze_one(s) for s in symbols]+ completed = await asyncio.gather(*tasks)++ for sym, sentiment in completed:+ results[sym] = sentiment.to_dict()total_score += sentiment.sentiment_score+ analyzed_count += 1- avg_score = total_score / len(symbols) if symbols else 0.0+ avg_score = total_score / analyzed_count if analyzed_count else 0.0if avg_score > 0.3:overall_mood = "risk_on"@@ -373,7 +400,7 @@ class SentimentAgent(BaseAgent):overall_mood = "mixed"return {- "symbols_analyzed": len(symbols),+ "symbols_analyzed": analyzed_count,"overall_mood": overall_mood,"average_sentiment": avg_score,"individual_sentiments": results,diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/main.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/main.pyindex e9535d893..e74db9fcb 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/main.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/main.py@@ -305,30 +305,36 @@ async def create_competition_handler(params: Dict, api_keys: Dict) -> Dict[str,logger.warning(f"Failed to save competition to database: {db_error}")# Continue anyway - competition is functional- # Check for agents in mock mode and warn the user- mock_warnings = []- for agent_name, agent in competition._agents.items():- if hasattr(agent, 'is_mock_mode') and agent.is_mock_mode:- reason = agent.mock_mode_reason or 'unknown'- mock_warnings.append(f"{agent_name}: {reason}")+ # Report which agents initialized successfully+ initialized_agents = list(competition._agents.keys())+ failed_agents = [m.name for m in models if m.name not in initialized_agents]result = {"success": True,"competition_id": competition_id,"config": config.model_dump(),"status": "created",- "models_count": len(models),+ "models_count": len(initialized_agents),+ "initialized_agents": initialized_agents,}- if mock_warnings:- result["warnings"] = mock_warnings- result["mock_mode_agents"] = len(mock_warnings)- logger.warning(f"{len(mock_warnings)} agent(s) in mock mode: {mock_warnings}")++ if failed_agents:+ result["warnings"] = [f"{name}: failed to initialize LLM" for name in failed_agents]+ result["failed_agents"] = failed_agents+ logger.warning(f"{len(failed_agents)} agent(s) failed to initialize: {failed_agents}")return resultelse:+ # Competition init failed - not enough agents with real LLMs+ initialized_count = len(competition._agents)+ total_count = len(models)return {"success": False,- "error": "Failed to initialize competition. Check that LLM providers are configured correctly and API keys are valid.",+ "error": (+ f"Competition initialization failed. Only {initialized_count}/{total_count} agents "+ f"initialized successfully. At least 2 agents with valid LLM connections are required. "+ f"Check that API keys are valid and LLM providers are accessible."+ ),}except Exception as e:@@ -519,6 +525,31 @@ async def get_leaderboard_handler(params: Dict) -> Dict[str, Any]:"leaderboard": leaderboard,}+ # No leaderboard history yet - check if competition exists and build initial leaderboard from config+ comp_data = db.get_competition(competition_id)+ if comp_data:+ config = comp_data.get("config", {})+ models = config.get("models", [])+ initial_capital = config.get("initial_capital", 10000)+ initial_leaderboard = []+ for i, model in enumerate(models):+ initial_leaderboard.append({+ "rank": i + 1,+ "model_name": model.get("name", f"Model {i+1}"),+ "portfolio_value": model.get("initial_capital", initial_capital),+ "total_pnl": 0.0,+ "return_pct": 0.0,+ "trades_count": 0,+ "cash": model.get("initial_capital", initial_capital),+ "positions_count": 0,+ "win_rate": None,+ "sharpe_ratio": None,+ })+ return {+ "success": True,+ "leaderboard": initial_leaderboard,+ }+return {"success": False, "error": f"Competition not found: {competition_id}"}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/analyze_akshare_functions.py b/fincept-terminal-desktop/src-tauri/resources/scripts/analyze_akshare_functions.pydeleted file mode 100644index 253fe2a0a..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/analyze_akshare_functions.py+++ /dev/null@@ -1,134 +0,0 @@-#!/usr/bin/env python3-"""-AKShare Function Analysis Script-Analyzes all akshare*.py files to extract used functions and compare against akshare 1.18.20 API-"""--import re-import os-from pathlib import Path-from collections import defaultdict--def extract_akshare_functions_from_file(filepath):- """Extract all ak.function_name() calls from a Python file"""- functions = set()-- with open(filepath, 'r', encoding='utf-8') as f:- content = f.read()-- # Find all ak.function_name patterns- pattern = r'ak\.([a-z_][a-z0-9_]*)'- matches = re.findall(pattern, content, re.IGNORECASE)- functions.update(matches)-- return functions--def main():- # Path to scripts directory- scripts_dir = Path(__file__).parent-- # Find all akshare*.py files- akshare_files = list(scripts_dir.glob('akshare*.py'))-- print(f"Found {len(akshare_files)} akshare wrapper files\n")- print("="*80)-- # Extract functions from each file- all_functions = defaultdict(set)- file_function_map = {}-- for filepath in sorted(akshare_files):- filename = filepath.name- functions = extract_akshare_functions_from_file(filepath)- file_function_map[filename] = functions-- print(f"\n{filename}:")- print(f" Total akshare functions used: {len(functions)}")- print(f" Functions: {', '.join(sorted(list(functions)[:10]))}{'...' if len(functions) > 10 else ''}")-- # Categorize functions- for func in functions:- all_functions[func].add(filename)-- print("\n" + "="*80)- print(f"\nTOTAL UNIQUE AKSHARE FUNCTIONS USED: {len(all_functions)}")- print(f"ACROSS {len(akshare_files)} WRAPPER FILES")-- # Known outdated/problematic functions- known_issues = {- 'energy_carbon': 'OUTDATED - Needs to be replaced with regional variants',- 'energy_carbon_price': 'May not exist in akshare 1.18.20',- 'energy_carbon_quota': 'May not exist in akshare 1.18.20',- 'energy_oil_em': 'Verify existence in akshare 1.18.20',- 'energy_oil_ice': 'Verify existence in akshare 1.18.20',- 'energy_natural_gas': 'Verify existence in akshare 1.18.20',- 'energy_coal': 'Verify existence in akshare 1.18.20',- 'energy_electricity': 'Verify existence in akshare 1.18.20',- 'energy_solar': 'Verify existence in akshare 1.18.20',- 'energy_wind': 'Verify existence in akshare 1.18.20',- 'energy_hydro': 'Verify existence in akshare 1.18.20',- }-- print("\n" + "="*80)- print("\nKNOWN PROBLEMATIC FUNCTIONS:")- print("-"*80)-- found_issues = []- for func, issue in known_issues.items():- if func in all_functions:- files = ', '.join(all_functions[func])- found_issues.append((func, issue, files))- print(f"\n[!] {func}")- print(f" Issue: {issue}")- print(f" Used in: {files}")-- # Print summary statistics- print("\n" + "="*80)- print("\nSUMMARY STATISTICS:")- print("-"*80)- print(f"Total wrapper files analyzed: {len(akshare_files)}")- print(f"Total unique akshare functions used: {len(all_functions)}")- print(f"Known problematic functions found: {len(found_issues)}")- print(f"Estimated valid functions: {len(all_functions) - len(found_issues)}")-- # Category breakdown by file- print("\n" + "="*80)- print("\nFUNCTION USAGE BY FILE:")- print("-"*80)- for filename in sorted(file_function_map.keys()):- func_count = len(file_function_map[filename])- print(f"{filename:50s} : {func_count:4d} functions")-- # Most commonly used functions- print("\n" + "="*80)- print("\nMOST COMMONLY USED FUNCTIONS:")- print("-"*80)- function_usage = [(func, len(files)) for func, files in all_functions.items()]- function_usage.sort(key=lambda x: x[1], reverse=True)-- for func, count in function_usage[:20]:- if count > 1:- print(f"{func:40s} : used in {count} files")-- print("\n" + "="*80)- print("\nRECOMMENDATIONS:")- print("-"*80)- print("1. Fix energy_carbon in akshare_alternative.py (line 188)")- print(" - Replace with: ak.energy_carbon_domestic() or specific regional function")- print(" - Update wrapper method get_energy_carbon() to use correct function")- print("")- print("2. Verify all energy_* functions exist in akshare 1.18.20:")- print(" - Check documentation: https://akshare.akfamily.xyz/")- print(" - Run: python -c 'import akshare as ak; print(dir(ak))' | grep energy")- print("")- print("3. Create validation script to test all functions:")- print(" - Import akshare and test hasattr(ak, 'function_name')")- print(" - Generate list of missing/deprecated functions")- print("")- print("4. Missing categories in akshare 1.18.20 (out of 1111 total):")- print(f" - Your scripts cover ~{len(all_functions)} functions")- print(f" - Remaining: ~{1111 - len(all_functions)} functions not covered")- print(" - Consider adding: sentiment analysis, social media, advanced ML features")--if __name__ == "__main__":- main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/bea_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/bea_data.pyindex e2461b8f8..f38b939c7 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/bea_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/bea_data.py@@ -610,7 +610,107 @@ def main(args=None):wrapper = BEAWrapper()try:- if command == "dataset_list":+ if command == "fetch":+ # Frontend integration command: fetch <indicator_id> <start_date> <end_date>+ if len(args) < 4:+ print(json.dumps({"success": False, "error": "Usage: bea_data.py fetch <indicator_id> <start_date> <end_date>"}))+ sys.exit(1)++ indicator_id = args[1]+ start_date = args[2] # YYYY-MM-DD+ end_date = args[3] # YYYY-MM-DD++ # Map indicator IDs to NIPA table + line number+ INDICATOR_MAP = {+ "gdp_growth": {"table": "T10101", "line": "1", "name": "Real GDP Growth (% Change)"},+ "nominal_gdp": {"table": "T10105", "line": "1", "name": "Nominal GDP (Billions $)"},+ "real_gdp": {"table": "T10106", "line": "1", "name": "Real GDP (Chained 2017 $, Billions)"},+ "gdp_deflator": {"table": "T10104", "line": "1", "name": "GDP Price Index"},+ "gdp_price_change": {"table": "T10107", "line": "1", "name": "GDP Price Change (%)"},+ "pce": {"table": "T10105", "line": "2", "name": "Personal Consumption Expenditures (Billions $)"},+ "pce_goods": {"table": "T10105", "line": "3", "name": "PCE Goods (Billions $)"},+ "pce_services": {"table": "T10105", "line": "6", "name": "PCE Services (Billions $)"},+ "gross_investment": {"table": "T10105", "line": "7", "name": "Gross Private Domestic Investment (Billions $)"},+ "fixed_investment": {"table": "T10105", "line": "8", "name": "Fixed Investment (Billions $)"},+ "net_exports": {"table": "T10105", "line": "15", "name": "Net Exports (Billions $)"},+ "exports": {"table": "T10105", "line": "16", "name": "Exports of Goods & Services (Billions $)"},+ "imports": {"table": "T10105", "line": "19", "name": "Imports of Goods & Services (Billions $)"},+ "govt_spending": {"table": "T10105", "line": "22", "name": "Government Spending (Billions $)"},+ "federal_spending": {"table": "T10105", "line": "23", "name": "Federal Government Spending (Billions $)"},+ "defense_spending": {"table": "T10105", "line": "24", "name": "National Defense Spending (Billions $)"},+ "personal_income": {"table": "T20100", "line": "1", "name": "Personal Income (Billions $)"},+ "compensation": {"table": "T20100", "line": "2", "name": "Compensation of Employees (Billions $)"},+ "wages_salaries": {"table": "T20100", "line": "3", "name": "Wages and Salaries (Billions $)"},+ "disposable_income": {"table": "T20100", "line": "27", "name": "Disposable Personal Income (Billions $)"},+ "personal_saving": {"table": "T20100", "line": "34", "name": "Personal Saving (Billions $)"},+ "saving_rate": {"table": "T20100", "line": "35", "name": "Personal Saving Rate (%)"},+ "pce_inflation": {"table": "T20301", "line": "1", "name": "PCE Price Index (% Change)"},+ "core_pce_inflation": {"table": "T20301", "line": "25", "name": "Core PCE Price Index (% Change, ex Food & Energy)"},+ "gdp_per_capita": {"table": "T70100", "line": "1", "name": "GDP per Capita (Current $)"},+ "govt_receipts": {"table": "T30100", "line": "1", "name": "Government Current Receipts (Billions $)"},+ "personal_taxes": {"table": "T30100", "line": "3", "name": "Personal Current Taxes (Billions $)"},+ "corporate_taxes": {"table": "T30100", "line": "5", "name": "Taxes on Corporate Income (Billions $)"},+ "current_account": {"table": "T40100", "line": "33", "name": "Current Account Balance (Billions $)"},+ "gross_saving": {"table": "T50100", "line": "1", "name": "Gross Saving (Billions $)"},+ "net_saving": {"table": "T50100", "line": "2", "name": "Net Saving (Billions $)"},+ "gdi": {"table": "T11000", "line": "1", "name": "Gross Domestic Income (Billions $)"},+ }++ if indicator_id not in INDICATOR_MAP:+ print(json.dumps({"success": False, "error": f"Unknown indicator: {indicator_id}", "available": list(INDICATOR_MAP.keys())}))+ sys.exit(1)++ config = INDICATOR_MAP[indicator_id]+ start_year = int(start_date[:4])+ end_year = int(end_date[:4])++ # Build year list+ years = ','.join(str(y) for y in range(start_year, end_year + 1))++ params = {+ 'DatasetName': 'NIPA',+ 'TableName': config['table'],+ 'Frequency': 'A',+ 'Year': years,+ }+ result = wrapper._make_request('GetData', params)++ if not result.get('success'):+ print(json.dumps(result))+ sys.exit(1)++ # Filter by LineNumber+ target_line = config['line']+ data_points = []+ for row in result.get('data', []):+ if row.get('LineNumber') == target_line:+ try:+ val_str = row.get('DataValue', '').replace(',', '')+ if val_str and val_str not in ('...', '(NA)', 'n.a.'):+ value = float(val_str)+ period = row.get('TimePeriod', '')+ data_points.append({"date": period, "value": value})+ except (ValueError, TypeError):+ continue++ # Sort by date+ data_points.sort(key=lambda x: x['date'])++ print(json.dumps({+ "success": True,+ "data": data_points,+ "metadata": {+ "indicator": indicator_id,+ "indicator_name": config['name'],+ "country": "United States",+ "source": "BEA NIPA",+ "table": config['table'],+ "line": config['line'],+ }+ }))+ sys.exit(0)++ elif command == "dataset_list":result = wrapper.get_dataset_list()print(json.dumps(result, indent=2))diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/bis_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/bis_data.pyindex 9b1420bc2..cce1e711f 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/bis_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/bis_data.py@@ -938,7 +938,131 @@ async def main():async with BISAPI() as bis:try:- if command == "get_data":+ if command == "fetch":+ # Simplified fetch command for Fincept Terminal Economics tab+ # Usage: fetch <dataflow> <country_code> [start_period] [end_period]+ # Returns flattened [{date, value}] array for charting+ if len(args) < 3:+ raise ValueError("Usage: fetch <dataflow> <country_code> [start_period] [end_period]")++ dataflow = args[1]+ country_code = args[2]+ start_period = args[3] if len(args) > 3 else None+ end_period = args[4] if len(args) > 4 else None++ # Key patterns per dataflow — each flow has different dimension layouts+ # Format: dots separate dimension positions, country goes in the right slot+ KEY_PATTERNS = {+ # FREQ.REF_AREA+ "WS_CBPOL": "M.{cc}",+ # FREQ.EER_TYPE.EER_BASKET.REF_AREA+ "WS_EER": "M.N.B.{cc}",+ "WS_EER_R": "M.R.B.{cc}",+ # FREQ.REF_AREA.CURRENCY.COLLECTION+ "WS_XRU": "M.{cc}",+ # FREQ.REF_AREA.UNIT_MEASURE+ "WS_LONG_CPI": "M.{cc}",+ # FREQ.REF_AREA.COMP_METHOD.UNIT_MEASURE.CURRENCY.TRANSFORMATION+ "WS_CBTA": "Q.{cc}",+ # FREQ.BORROWERS_CTY...+ "WS_CREDIT_GAP": "Q.{cc}",+ "WS_TC": "Q.{cc}",+ "WS_DSR": "Q.{cc}",+ # FREQ.CURR_DENOM.BORROWERS_CTY...+ "WS_GLI": "Q..{cc}",+ # FREQ.REF_AREA.VALUE.UNIT_MEASURE+ "WS_SPP": "Q.{cc}",+ "WS_CPP": "Q.{cc}",+ "WS_DPP": "Q.{cc}",+ # FREQ.L_MEASURE.L_REP_CTY...+ "WS_CBS_PUB": "Q..{cc}",+ "WS_LBS_D_PUB": "Q..{cc}",+ # FREQ.ISSUER_RES...+ "WS_DEBT_SEC2_PUB": "Q.{cc}",+ # FREQ.ADJUSTMENT.REF_AREA...+ "WS_NA_SEC_DSS": "Q..{cc}",+ # OTC/exchange-traded derivatives — global, no country filter+ "WS_OTC_DERIV2": "H",+ "WS_DER_OTC_TOV": "T",+ "WS_XTD_DERIV": "Q",+ # CPMI flows — annual, country in REP_CTY pos 2+ "WS_CPMI_MACRO": "A..{cc}",+ "WS_CPMI_CASHLESS": "A..{cc}",+ "WS_CPMI_CT1": "A..{cc}",+ "WS_CPMI_CT2": "A..{cc}",+ "WS_CPMI_DEVICES": "A..{cc}",+ "WS_CPMI_INSTITUT": "A..{cc}",+ "WS_CPMI_PARTICIP": "A..{cc}",+ "WS_CPMI_SYSTEMS": "A..{cc}",+ }++ pattern = KEY_PATTERNS.get(dataflow, "M.{cc}")+ if country_code and country_code != "all":+ key = pattern.format(cc=country_code)+ else:+ key = pattern.format(cc="")++ raw = await bis.get_data(dataflow, key, start_period, end_period)++ if not raw.get("success"):+ result = raw+ else:+ # Flatten SDMX-JSON into simple [{date, value}] for charting+ flat_data = []+ try:+ resp = raw.get("data", {})+ sdmx_data = resp.get("data", resp)+ datasets = sdmx_data.get("dataSets", [])+ structure = sdmx_data.get("structure", resp.get("structure", {}))+ obs_dims = structure.get("dimensions", {}).get("observation", [])++ # Get time period values from observation dimension+ time_values = {}+ if obs_dims:+ time_values = {str(i): v.get("id", v.get("name", str(i)))+ for i, v in enumerate(obs_dims[0].get("values", []))}++ for ds in datasets:+ series_map = ds.get("series", {})+ for _series_key, series_val in series_map.items():+ observations = series_val.get("observations", {})+ for obs_key, obs_val in observations.items():+ period = time_values.get(obs_key, obs_key)+ value = obs_val[0] if isinstance(obs_val, list) and obs_val else None+ if value is not None:+ try:+ value = float(value)+ import math+ if math.isnan(value) or math.isinf(value):+ continue+ except (ValueError, TypeError):+ continue+ flat_data.append({"date": str(period), "value": value})++ # Deduplicate by date (average if multiple series for same date)+ from collections import defaultdict+ date_vals = defaultdict(list)+ for d in flat_data:+ date_vals[d["date"]].append(d["value"])+ flat_data = [{"date": dt, "value": round(sum(vs)/len(vs), 6)}+ for dt, vs in sorted(date_vals.items())]++ except Exception as parse_err:+ result = {"success": False, "error": f"Failed to parse SDMX response: {str(parse_err)}"}+ print(json.dumps(result, indent=2))+ return++ result = {+ "success": True,+ "data": flat_data,+ "metadata": {+ "dataflow": dataflow,+ "country": country_code,+ "source": "BIS"+ }+ }++ elif command == "get_data":if len(args) < 2:raise ValueError("Usage: get_data <flow> [key] [start_period] [end_period]")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/canada_gov_api.py b/fincept-terminal-desktop/src-tauri/resources/scripts/canada_gov_api.pyindex 0e85804bc..2a3897748 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/canada_gov_api.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/canada_gov_api.py@@ -207,9 +207,8 @@ def get_datasets_by_publisher(publisher_id: str, rows: int = 100) -> Dict[str, AJSON response with dataset list"""try:- # Search for datasets by owner_org- query = f"owner_org:{publisher_id}"- params = {'q': query, 'rows': rows}+ # Use fq (filter query) with organization slug — q+owner_org requires UUID+ params = {'fq': f'organization:{publisher_id}', 'rows': rows}result = _make_request("package_search", params)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/fiscaldata_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/fiscal_data.pysimilarity index 69%rename from fincept-terminal-desktop/src-tauri/resources/scripts/fiscaldata_data.pyrename to fincept-terminal-desktop/src-tauri/resources/scripts/fiscal_data.pyindex 973ef5f6f..91e03a1a8 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/fiscaldata_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/fiscal_data.py@@ -483,6 +483,209 @@ def _parse_date_range(date_str: str) -> str:return date_str+def fetch(indicator_id: str, start_date: str = None, end_date: str = None) -> Dict[str, Any]:+ """+ Frontend integration command: returns normalized {success, data: [{date, value}], metadata}+ Each indicator maps to a specific endpoint, filter, and value field.+ """+ # Indicator -> (endpoint, fields, filter_field, filter_value, value_field, sort)+ INDICATOR_MAP = {+ # Debt to the Penny+ "total_public_debt": {+ "endpoint": "v2/accounting/od/debt_to_penny",+ "fields": "record_date,tot_pub_debt_out_amt",+ "value_field": "tot_pub_debt_out_amt",+ "name": "Total Public Debt Outstanding",+ },+ "debt_held_public": {+ "endpoint": "v2/accounting/od/debt_to_penny",+ "fields": "record_date,debt_held_public_amt",+ "value_field": "debt_held_public_amt",+ "name": "Debt Held by the Public",+ },+ "intragov_holdings": {+ "endpoint": "v2/accounting/od/debt_to_penny",+ "fields": "record_date,intragov_hold_amt",+ "value_field": "intragov_hold_amt",+ "name": "Intragovernmental Holdings",+ },+ # Average Interest Rates+ "avg_rate_tbills": {+ "endpoint": "v2/accounting/od/avg_interest_rates",+ "fields": "record_date,avg_interest_rate_amt",+ "value_field": "avg_interest_rate_amt",+ "extra_filter": "security_desc:eq:Treasury Bills",+ "name": "Avg Interest Rate - Treasury Bills",+ },+ "avg_rate_tnotes": {+ "endpoint": "v2/accounting/od/avg_interest_rates",+ "fields": "record_date,avg_interest_rate_amt",+ "value_field": "avg_interest_rate_amt",+ "extra_filter": "security_desc:eq:Treasury Notes",+ "name": "Avg Interest Rate - Treasury Notes",+ },+ "avg_rate_tbonds": {+ "endpoint": "v2/accounting/od/avg_interest_rates",+ "fields": "record_date,avg_interest_rate_amt",+ "value_field": "avg_interest_rate_amt",+ "extra_filter": "security_desc:eq:Treasury Bonds",+ "name": "Avg Interest Rate - Treasury Bonds",+ },+ "avg_rate_tips": {+ "endpoint": "v2/accounting/od/avg_interest_rates",+ "fields": "record_date,avg_interest_rate_amt",+ "value_field": "avg_interest_rate_amt",+ "extra_filter": "security_desc:eq:Treasury Inflation-Protected Securities (TIPS)",+ "name": "Avg Interest Rate - TIPS",+ },+ "avg_rate_frn": {+ "endpoint": "v2/accounting/od/avg_interest_rates",+ "fields": "record_date,avg_interest_rate_amt",+ "value_field": "avg_interest_rate_amt",+ "extra_filter": "security_desc:eq:Treasury Floating Rate Notes (FRN)",+ "name": "Avg Interest Rate - Floating Rate Notes",+ },+ # Interest Expense+ "interest_expense_total": {+ "endpoint": "v2/accounting/od/interest_expense",+ "fields": "record_date,fytd_expense_amt",+ "value_field": "fytd_expense_amt",+ "aggregate": True,+ "name": "Total Interest Expense (FYTD)",+ },+ "interest_expense_monthly": {+ "endpoint": "v2/accounting/od/interest_expense",+ "fields": "record_date,month_expense_amt",+ "value_field": "month_expense_amt",+ "aggregate": True,+ "name": "Monthly Interest Expense (All Securities)",+ },+ # MTS Table 9 - Budget Summary (Outlays by function)+ "outlays_health": {+ "endpoint": "v1/accounting/mts/mts_table_9",+ "fields": "record_date,classification_desc,current_fytd_rcpt_outly_amt",+ "value_field": "current_fytd_rcpt_outly_amt",+ "extra_filter": "classification_desc:eq:Health",+ "name": "Federal Outlays - Health (FYTD)",+ },+ "outlays_defense": {+ "endpoint": "v1/accounting/mts/mts_table_9",+ "fields": "record_date,classification_desc,current_fytd_rcpt_outly_amt",+ "value_field": "current_fytd_rcpt_outly_amt",+ "extra_filter": "classification_desc:eq:National Defense",+ "name": "Federal Outlays - National Defense (FYTD)",+ },+ "outlays_social_security": {+ "endpoint": "v1/accounting/mts/mts_table_9",+ "fields": "record_date,classification_desc,current_fytd_rcpt_outly_amt",+ "value_field": "current_fytd_rcpt_outly_amt",+ "extra_filter": "classification_desc:eq:Social Security",+ "name": "Federal Outlays - Social Security (FYTD)",+ },+ "outlays_net_interest": {+ "endpoint": "v1/accounting/mts/mts_table_9",+ "fields": "record_date,classification_desc,current_fytd_rcpt_outly_amt",+ "value_field": "current_fytd_rcpt_outly_amt",+ "extra_filter": "classification_desc:eq:Net Interest",+ "name": "Federal Outlays - Net Interest (FYTD)",+ },+ "outlays_education": {+ "endpoint": "v1/accounting/mts/mts_table_9",+ "fields": "record_date,classification_desc,current_fytd_rcpt_outly_amt",+ "value_field": "current_fytd_rcpt_outly_amt",+ "extra_filter": "classification_desc:eq:Education, Training, Employment, and Social Services",+ "name": "Federal Outlays - Education (FYTD)",+ },+ # Gold Reserve+ "gold_reserve_total": {+ "endpoint": "v2/accounting/od/gold_reserve",+ "fields": "record_date,book_value_amt,fine_troy_ounce_qty",+ "value_field": "book_value_amt",+ "aggregate": True, # Sum across all facilities+ "name": "U.S. Gold Reserve (Book Value)",+ },+ "gold_reserve_ounces": {+ "endpoint": "v2/accounting/od/gold_reserve",+ "fields": "record_date,fine_troy_ounce_qty",+ "value_field": "fine_troy_ounce_qty",+ "aggregate": True,+ "name": "U.S. Gold Reserve (Troy Ounces)",+ },+ }++ config = INDICATOR_MAP.get(indicator_id)+ if not config:+ return {+ "success": False,+ "error": f"Unknown indicator: {indicator_id}",+ "available": list(INDICATOR_MAP.keys())+ }++ params = {+ "fields": config["fields"],+ "sort": "-record_date",+ "page[size]": "1000",+ }++ # Build filters+ filters = []+ if start_date:+ filters.append(f"record_date:gte:{start_date}")+ if end_date:+ filters.append(f"record_date:lte:{end_date}")+ if config.get("extra_filter"):+ filters.append(config["extra_filter"])+ if filters:+ params["filter"] = ",".join(filters)++ result = _make_request(config["endpoint"], params)++ if result.get("error"):+ return {"success": False, "error": result["error"]}++ records = result.get("data", [])+ value_field = config["value_field"]+ should_aggregate = config.get("aggregate", False)++ if should_aggregate:+ # Sum values across all rows for the same date+ date_sums = {}+ for rec in records:+ date = rec.get("record_date", "")+ val = rec.get(value_field)+ if date and val is not None:+ try:+ v = float(val)+ date_sums[date] = date_sums.get(date, 0) + v+ except (ValueError, TypeError):+ pass+ data_points = [{"date": d, "value": v} for d, v in date_sums.items()]+ else:+ data_points = []+ for rec in records:+ date = rec.get("record_date", "")+ val = rec.get(value_field)+ if date and val is not None:+ try:+ data_points.append({"date": date, "value": float(val)})+ except (ValueError, TypeError):+ pass++ # Sort by date ascending+ data_points.sort(key=lambda x: x["date"])++ return {+ "success": True,+ "data": data_points,+ "metadata": {+ "indicator": indicator_id,+ "indicator_name": config["name"],+ "country": "United States",+ "source": "U.S. Treasury FiscalData"+ }+ }++def main():"""Main CLI interface"""if len(sys.argv) < 2:@@ -500,7 +703,16 @@ def main():command = sys.argv[1]result = None- if command == "debt-to-penny":+ if command == "fetch":+ if len(sys.argv) < 3:+ print(json.dumps({"error": "Usage: fetch <indicator_id> [start_date] [end_date]"}))+ sys.exit(1)+ indicator_id = sys.argv[2]+ s_date = sys.argv[3] if len(sys.argv) > 3 else None+ e_date = sys.argv[4] if len(sys.argv) > 4 else None+ result = fetch(indicator_id, s_date, e_date)++ elif command == "debt-to-penny":fields = Nonestart_date = Noneend_date = Nonediff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/fix_all_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/fix_all_cli.pydeleted file mode 100644index 9d171cbb3..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/fix_all_cli.py+++ /dev/null@@ -1,137 +0,0 @@-#!/usr/bin/env python3-"""-Universal CLI fixer for all AKShare wrapper scripts-Replaces hardcoded endpoint maps with dynamic method resolution-"""-import os-import re--DYNAMIC_CLI_TEMPLATE = """-# ==================== CLI ====================-if __name__ == "__main__":- import sys- import json-- # Get wrapper instance- wrapper = WRAPPER_CLASS()-- if len(sys.argv) < 2:- print(json.dumps({"error": "Usage: python SCRIPT_NAME <endpoint> [args...]"}))- sys.exit(1)-- endpoint = sys.argv[1]- args = sys.argv[2:] if len(sys.argv) > 2 else []-- # Handle get_all_endpoints- if endpoint == "get_all_endpoints":- if hasattr(wrapper, 'get_all_available_endpoints'):- result = wrapper.get_all_available_endpoints()- elif hasattr(wrapper, 'get_all_endpoints'):- result = wrapper.get_all_endpoints()- else:- result = {"success": False, "error": "Endpoint list not available"}- print(json.dumps(result, ensure_ascii=True))- sys.exit(0)-- # Dynamic method resolution- method_name = f"get_{endpoint}" if not endpoint.startswith("get_") else endpoint-- if hasattr(wrapper, method_name):- method = getattr(wrapper, method_name)- try:- result = method(*args) if args else method()- print(json.dumps(result, ensure_ascii=True))- except Exception as e:- print(json.dumps({"success": False, "error": str(e), "endpoint": endpoint}))- else:- print(json.dumps({"success": False, "error": f"Unknown endpoint: {endpoint}. Method '{method_name}' not found."}))-"""--def find_wrapper_class(content):- """Find the wrapper class name in the file"""- patterns = [- r'class\s+(\w+Wrapper)\s*[\(:]',- r'class\s+(\w+API)\s*[\(:]',- r'class\s+(AKShare\w+)\s*[\(:]',- r'class\s+(\w+)\s*[\(:]' # Any class- ]- for pattern in patterns:- matches = re.findall(pattern, content)- for match in matches:- # Skip error classes and base classes- if 'Error' not in match and 'Encoder' not in match and match != 'object':- return match- return None--def fix_file(filename):- """Fix CLI routing in a single file"""- print(f"\nProcessing {filename}...")-- with open(filename, 'r', encoding='utf-8') as f:- content = f.read()-- # Find wrapper class- wrapper_class = find_wrapper_class(content)- if not wrapper_class:- print(f" SKIP: No wrapper class found")- return False-- print(f" Found wrapper: {wrapper_class}")-- # Find where main block starts- main_idx = content.rfind('if __name__ == "__main__":')- if main_idx == -1:- main_idx = content.rfind("if __name__ == '__main__':")-- if main_idx == -1:- print(f" SKIP: No main block")- return False-- # Also find CLI comment- cli_idx = content.rfind('# =' + '=' * 10 + ' CLI ')- if cli_idx != -1 and cli_idx < main_idx:- main_idx = cli_idx-- # Cut at main/CLI block- new_content = content[:main_idx].rstrip()-- # Add new CLI- new_cli = DYNAMIC_CLI_TEMPLATE.replace('WRAPPER_CLASS', wrapper_class)- new_cli = new_cli.replace('SCRIPT_NAME', filename)-- new_content += '\n' + new_cli + '\n'-- # Write back- with open(filename, 'w', encoding='utf-8') as f:- f.write(new_content)-- print(f" DONE: Fixed with {wrapper_class}")- return True--# Files to fix-files_to_fix = [- 'akshare_analysis.py',- 'akshare_data.py',- 'akshare_derivatives.py',- 'akshare_economics_china.py',- 'akshare_economics_global.py',- 'akshare_funds_expanded.py',- 'akshare_alternative.py',- 'akshare_company_info.py'-]--print("=" * 60)-print("AKShare CLI Fixer - Dynamic Method Resolution")-print("=" * 60)--success_count = 0-for filename in files_to_fix:- if os.path.exists(filename):- if fix_file(filename):- success_count += 1- else:- print(f"\nSKIP: {filename} not found")--print("\n" + "=" * 60)-print(f"Fixed {success_count}/{len(files_to_fix)} files")-print("=" * 60)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/government_us_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/government_us_data.pyindex a31dbd9c5..ccb9ea83b 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/government_us_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/government_us_data.py@@ -167,7 +167,16 @@ class GovernmentUSWrapper:if response.encoding != "ISO-8859-1":return GovernmentUSError('treasury_prices', f'Expected ISO-8859-1 encoding but got: {response.encoding}').to_dict()- content = response.content.decode("utf-8")+ content = response.content.decode("utf-8").strip()++ # Check for empty content (no data for this date — weekend, holiday, or not yet published)+ if not content or len(content) < 10:+ return GovernmentUSError(+ 'treasury_prices',+ f'No price data available for {date_obj.strftime("%Y-%m-%d")}. '+ f'Treasury prices are published end-of-day on business days only. '+ f'Try a previous business day.'+ ).to_dict()# Parse CSV data using OpenBB methodtry:diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/scb_data_backup.py b/fincept-terminal-desktop/src-tauri/resources/scripts/scb_data_backup.pydeleted file mode 100644index 5ca8c7162..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/scb_data_backup.py+++ /dev/null@@ -1,719 +0,0 @@-"""-SCB (Statistics Sweden) Data Wrapper-Comprehensive wrapper for SCB PxWebApi providing access to Swedish statistical data--API Documentation:-- Base URL: https://api.scb.se/OV0104/v1/doris/sv/ssd/-- Authentication: None required (public API)-- Rate limits: Be reasonable with requests-- Documentation: https://www.scb.se/vara-tjanster/oppna-data/pxwebapi/api-for-statistikdatabasen/--Supported Categories:-- Population (BE): Population statistics, demographics, projections-- Labor Market (AM): Employment, wages, labor surveys-- Economy (NR): National accounts, regional accounts, health accounts-- Environment (MI): Emissions, waste, land use, environmental indicators-- Energy (EN): Energy production, consumption, prices-- Education (UF): Students, schools, research, training-- Prices (PR): Consumer price index, producer price index-- Healthcare (HS): Health statistics, causes of death-- And many more categories covering all aspects of Swedish society-"""--import sys-import json-import requests-import os-from datetime import datetime, timedelta-from typing import Dict, List, Optional, Union, Any-from urllib.parse import urlencode--# SCB API Configuration-BASE_URL = "https://api.scb.se/OV0104/v1/doris/sv/ssd/"-TIMEOUT = 30-RATE_LIMIT_DELAY = 0.1 # 100ms delay between requests--# Main SCB Categories-SCB_CATEGORIES = {- "AA": {"name": "Ämnesövergripande statistik", "description": "Cross-cutting statistics"},- "AM": {"name": "Arbetsmarknad", "description": "Labor market statistics"},- "BE": {"name": "Befolkning", "description": "Population statistics"},- "BO": {"name": "Boende, byggande och bebyggelse", "description": "Housing and construction"},- "EN": {"name": "Energi", "description": "Energy statistics"},- "FM": {"name": "Finansmarknad", "description": "Financial market statistics"},- "HA": {"name": "Handel med varor och tjänster", "description": "Trade in goods and services"},- "HE": {"name": "Hushållens ekonomi", "description": "Household economics"},- "HS": {"name": "Hälso- och sjukvård", "description": "Health and medical care"},- "JO": {"name": "Jord- och skogsbruk, fiske", "description": "Agriculture, forestry, fishing"},- "KU": {"name": "Kultur och fritid", "description": "Culture and leisure"},- "LE": {"name": "Levnadsförhållanden", "description": "Living conditions"},- "ME": {"name": "Demokrati", "description": "Democracy statistics"},- "MI": {"name": "Miljö", "description": "Environment statistics"},- "NR": {"name": "Nationalräkenskaper", "description": "National accounts"},- "NV": {"name": "Näringsverksamhet", "description": "Business activities"},- "OE": {"name": "Offentlig ekonomi", "description": "Public economy"},- "OV": {"name": "Övrigt", "description": "Other statistics"},- "PR": {"name": "Priser och konsumtion", "description": "Prices and consumption"},- "SO": {"name": "Socialtjänst", "description": "Social services"},- "TK": {"name": "Transporter och kommunikationer", "description": "Transport and communications"},- "UF": {"name": "Utbildning och forskning", "description": "Education and research"}-}--# Popular SCB Tables for quick access-POPULAR_TABLES = {- "population": {- "id": "BE/BE0101/BE0101A/BefolkningNy",- "name": "Population by year",- "description": "Swedish population statistics"- },- "gdp": {- "id": "NR/NR0103/NR0103A/BNPBrott",- "name": "GDP by quarter",- "description": "Swedish Gross Domestic Product"- },- "employment": {- "id": "AM/AM0201/AntalSysselsatta",- "name": "Employment by sector",- "description": "Number of employed by sector"- },- "unemployment": {- "id": "AM/AM0401/AntalArbetslosa",- "name": "Unemployment statistics",- "description": "Unemployment by region and age"- },- "cpi": {- "id": "PR/PR0101/KPIFaststallelse",- "name": "Consumer Price Index",- "description": "Swedish Consumer Price Index"- },- "births": {- "id": "BE/BE0101/BE0101G/Fodda",- "name": "Live births",- "description": "Number of live births by month"- },- "deaths": {- "id": "BE/BE0101/BE0101G/Doda",- "name": "Deaths",- "description": "Number of deaths by month"- },- "immigration": {- "id": "BE/BE0101/BE0101G/Inflyttningar",- "name": "Immigration",- "description": "Number of immigrants by month"- }-}---class SCBError:- """Custom error class for SCB API errors"""- def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):- self.endpoint = endpoint- self.error = error- self.status_code = status_code- self.timestamp = int(datetime.now().timestamp()-- def to_dict(self) -> Dict[str, Any]:- return {- "error": True,- "endpoint": self.endpoint,- "message": self.error,- "status_code": self.status_code,- "timestamp": self.timestamp,- "source": "Statistics Sweden (SCB) API"- }---class SCBDataAPI:- """SCB Data API wrapper for Swedish statistical data"""-- def __init__(self):- self.base_url = BASE_URL- self.session = requests.Session()- self.session.headers.update({- 'User-Agent': 'Fincept-Terminal/1.0',- 'Accept': 'application/json'- })-- def _make_request(self, url: str, method: str = "GET",- data: Optional[Dict] = None) -> Dict[str, Any]:- """Make HTTP request with error handling"""- try:- if method.upper() == "GET":- response = self.session.get(url, timeout=TIMEOUT)- elif method.upper() == "POST":- response = self.session.post(url, json=data, timeout=TIMEOUT)- else:- return SCBError(url, f"Unsupported method: {method}").to_dict()-- if response.status_code == 200:- try:- result = response.json()- return {"success": True, "data": result}- except json.JSONDecodeError:- return SCBError(url, "Invalid JSON response", response.status_code).to_dict()- else:- return SCBError(url, f"HTTP {response.status_code}: {response.text}", response.status_code).to_dict()-- except requests.exceptions.RequestException as e:- return SCBError(url, f"Network error: {str(e)}", getattr(e.response, 'status_code', None).to_dict()- except Exception as e:- return SCBError(url, f"Unexpected error: {str(e)}").to_dict()-- def get_categories(self) -> Dict[str, Any]:- """Get all main SCB categories"""- try:- result = self._make_request(self.base_url)-- if not result.get("success"):- return result-- categories_data = result.get("data", [])- enhanced_categories = []-- for category in categories_data:- category_id = category.get("id")- if category_id in SCB_CATEGORIES:- category["description"] = SCB_CATEGORIES[category_id]["description"]- category["english_name"] = SCB_CATEGORIES[category_id]["name"]- enhanced_categories.append(category)-- return {- "success": True,- "data": enhanced_categories,- "total_categories": len(enhanced_categories),- "metadata": {- "source": "Statistics Sweden (SCB) API",- "endpoint": "main_categories",- "last_updated": datetime.now().isoformat()- }- }-- except Exception as e:- return SCBError("get_categories", str(e).to_dict()-- def get_subcategories(self, category_id: str) -> Dict[str, Any]:- """Get subcategories for a specific category"""- try:- if category_id not in SCB_CATEGORIES:- available_categories = ", ".join(SCB_CATEGORIES.keys()- return SCBError("get_subcategories", f"Invalid category '{category_id}'. Available: {available_categories}").to_dict()-- url = f"{self.base_url}{category_id}"- result = self._make_request(url)-- if not result.get("success"):- return result-- subcategories = result.get("data", [])-- return {- "success": True,- "data": {- "category_id": category_id,- "category_name": SCB_CATEGORIES[category_id]["name"],- "subcategories": subcategories,- "total_subcategories": len(subcategories)- },- "metadata": {- "source": "Statistics Sweden (SCB) API",- "category": category_id,- "last_updated": datetime.now().isoformat()- }- }-- except Exception as e:- return SCBError("get_subcategories", str(e).to_dict()-- def get_table_metadata(self, table_path: str) -> Dict[str, Any]:- """Get metadata for a specific table"""- try:- url = f"{self.base_url}{table_path}"- result = self._make_request(url)-- if not result.get("success"):- return result-- return {- "success": True,- "data": result.get("data", {}),- "metadata": {- "table_path": table_path,- "source": "Statistics Sweden (SCB) API",- "last_updated": datetime.now().isoformat()- }- }-- except Exception as e:- return SCBError("get_table_metadata", str(e).to_dict()-- def get_table_data(self, table_path: str, query: Dict[str, Any]) -> Dict[str, Any]:- """Get data from a specific table with query parameters"""- try:- url = f"{self.base_url}{table_path}"-- # Format query according to SCB API specification- scb_query = {- "query": query,- "response": {- "format": "json"- }- }-- result = self._make_request(url, "POST", scb_query)-- if not result.get("success"):- return result-- scb_data = result.get("data", {})-- # Process the response according to SCB API format- processed_data = self._process_scb_response(scb_data, table_path, query)-- return {- "success": True,- "data": processed_data,- "metadata": {- "table_path": table_path,- "query": query,- "source": "Statistics Sweden (SCB) API",- "last_updated": datetime.now().isoformat()- }- }-- except Exception as e:- return SCBError("get_table_data", str(e).to_dict()-- def _process_scb_response(self, scb_data: Dict[str, Any], table_path: str, query: Dict[str, Any]) -> Dict[str, Any]:- """Process SCB API response into standardized format"""- try:- if "data" not in scb_data:- return {"columns": [], "data": [], "error": "No data field in SCB response"}-- columns = scb_data.get("columns", [])- data = scb_data.get("data", [])-- # Convert SCB column format to standard format- processed_columns = []- for col in columns:- processed_columns.append({- "code": col.get("code", ""),- "text": col.get("text", ""),- "type": col.get("type", "")- })-- # Process data rows- processed_data = []- for row in data:- row_dict = {}- for i, value in enumerate(row.get("values", []):- if i < len(processed_columns):- column_name = processed_columns[i]["code"]- row_dict[column_name] = value- processed_data.append(row_dict)-- return {- "columns": processed_columns,- "data": processed_data,- "total_records": len(processed_data),- "table_path": table_path,- "query_used": query- }-- except Exception as e:- return {"error": f"Error processing SCB response: {str(e)}"}-- def get_population_data(self, years: Optional[List[str]] = None) -> Dict[str, Any]:- """Get Swedish population data"""- try:- if not years:- # Default to last 5 years- current_year = datetime.now().year- years = [str(year) for year in range(current_year - 4, current_year + 1)]-- query = [- {- "code": "ContentsCode",- "selection": {- "filter": "item",- "values": ["BE0101N1"] # Population- }- },- {- "code": "Tid",- "selection": {- "filter": "item",- "values": years- }- }- ]-- result = self.get_table_data("BE/BE0101/BE0101A/BefolkningNy", query)-- if result.get("success"):- result["data"]["description"] = "Swedish population statistics by year"- result["data"]["years"] = years-- return result-- except Exception as e:- return SCBError("get_population_data", str(e).to_dict()-- def get_gdp_data(self, quarters: Optional[List[str]] = None) -> Dict[str, Any]:- """Get Swedish GDP data"""- try:- if not quarters:- # Default to last 8 quarters- current_year = datetime.now().year- quarters = []- for year in range(current_year - 2, current_year + 1):- for q in ["K1", "K2", "K3", "K4"]:- quarters.append(f"{year}{q}")-- query = [- {- "code": "ContentsCode",- "selection": {- "filter": "item",- "values": ["BNPGDP"] # GDP- }- },- {- "code": "Tid",- "selection": {- "filter": "item",- "values": quarters- }- }- ]-- result = self.get_table_data("NR/NR0103/NR0103A/BNPBrott", query)-- if result.get("success"):- result["data"]["description"] = "Swedish GDP by quarter"- result["data"]["quarters"] = quarters-- return result-- except Exception as e:- return SCBError("get_gdp_data", str(e).to_dict()-- def get_employment_data(self, regions: Optional[List[str]] = None, years: Optional[List[str]] = None) -> Dict[str, Any]:- """Get Swedish employment data"""- try:- if not years:- current_year = datetime.now().year- years = [str(year) for year in range(current_year - 4, current_year + 1)]-- if not regions:- regions = ["00"] # Whole country-- query = [- {- "code": "Region",- "selection": {- "filter": "item",- "values": regions- }- },- {- "code": "Tid",- "selection": {- "filter": "item",- "values": years- }- }- ]-- result = self.get_table_data("AM/AM0201/AntalSysselsatta", query)-- if result.get("success"):- result["data"]["description"] = "Swedish employment by region and year"- result["data"]["regions"] = regions- result["data"]["years"] = years-- return result-- except Exception as e:- return SCBError("get_employment_data", str(e).to_dict()-- def get_cpi_data(self, months: Optional[List[str]] = None) -> Dict[str, Any]:- """Get Swedish Consumer Price Index data"""- try:- if not months:- # Default to last 24 months- current_date = datetime.now()- months = []- for i in range(24):- month_date = current_date - timedelta(days=30 * i)- months.append(month_date.strftime("%Y%m")-- query = [- {- "code": "ContentsCode",- "selection": {- "filter": "item",- "values": ["KPI"] # CPI- }- },- {- "code": "Tid",- "selection": {- "filter": "item",- "values": months- }- }- ]-- result = self.get_table_data("PR/PR0101/KPIFaststallelse", query)-- if result.get("success"):- result["data"]["description"] = "Swedish Consumer Price Index"- result["data"]["months"] = months-- return result-- except Exception as e:- return SCBError("get_cpi_data", str(e).to_dict()-- def get_demographic_data(self, start_year: Optional[str] = None, end_year: Optional[str] = None) -> Dict[str, Any]:- """Get comprehensive demographic overview"""- try:- current_year = datetime.now().year- if not start_year:- start_year = str(current_year - 10)- if not end_year:- end_year = str(current_year)-- years = [str(year) for year in range(int(start_year), int(end_year) + 1)]-- # Get multiple demographic datasets sequentially- results = [- self.get_population_data(years),- self.get_cpi_data(None), # Recent CPI data- self.get_employment_data(["00"], years) # Whole country employment- ]-- demographic_data = {}- failed_requests = []-- dataset_names = ["population", "cpi", "employment"]- for i, result in enumerate(results):- if isinstance(result, Exception):- failed_requests.append({- "dataset": dataset_names[i],- "error": str(result)- })- elif isinstance(result, dict):- if result.get("success"):- demographic_data[dataset_names[i]] = result.get("data", {})- else:- failed_requests.append({- "dataset": dataset_names[i],- "error": result.get("error", "Unknown error")- })-- return {- "success": len(demographic_data) > 0,- "data": {- "demographic_overview": demographic_data,- "year_range": f"{start_year}-{end_year}",- "summary": {- "successful_datasets": list(demographic_data.keys(),- "failed_datasets": failed_requests,- "total_data_points": sum(- data.get("total_records", 0)- for data in demographic_data.values()- )- }- },- "metadata": {- "source": "Statistics Sweden (SCB) API",- "overview_type": "demographic_overview",- "year_range": f"{start_year}-{end_year}",- "last_updated": datetime.now().isoformat()- }- }-- except Exception as e:- return SCBError("get_demographic_data", str(e).to_dict()-- def search_tables(self, query: str, category: Optional[str] = None) -> Dict[str, Any]:- """Search for tables matching query"""- try:- # This is a simplified search - in a real implementation, you might- # want to search through available tables and metadata-- search_results = []-- # Check popular tables first- for table_key, table_info in POPULAR_TABLES.items():- if query.lower() in table_info["name"].lower() or \- query.lower() in table_info["description"].lower():- search_results.append({- "id": table_info["id"],- "name": table_info["name"],- "description": table_info["description"],- "type": "popular_table",- "category": "misc"- })-- return {- "success": True,- "data": {- "query": query,- "results": search_results,- "total_results": len(search_results)- },- "metadata": {- "source": "Statistics Sweden (SCB) API",- "search_type": "table_search",- "last_updated": datetime.now().isoformat()- }- }-- except Exception as e:- return SCBError("search_tables", str(e).to_dict()-- def get_popular_tables(self) -> Dict[str, Any]:- """Get list of popular SCB tables"""- try:- popular_list = []- for key, info in POPULAR_TABLES.items():- popular_list.append({- "key": key,- "id": info["id"],- "name": info["name"],- "description": info["description"]- })-- return {- "success": True,- "data": {- "popular_tables": popular_list,- "total_tables": len(popular_list)- },- "metadata": {- "source": "Statistics Sweden (SCB) API",- "last_updated": datetime.now().isoformat()- }- }-- except Exception as e:- return SCBError("get_popular_tables", str(e).to_dict()-- def get_category_info(self) -> Dict[str, Any]:- """Get detailed information about all SCB categories"""- try:- categories_info = []- for code, info in SCB_CATEGORIES.items():- categories_info.append({- "code": code,- "name": info["name"],- "description": info["description"],- "swedish_name": info["name"],- "english_description": info["description"]- })-- return {- "success": True,- "data": {- "categories": categories_info,- "total_categories": len(categories_info)- },- "metadata": {- "source": "Statistics Sweden (SCB) API",- "last_updated": datetime.now().isoformat()- }- }-- except Exception as e:- return SCBError("get_category_info", str(e).to_dict()---def main():- """Main function for CLI interface"""- if len(sys.argv) < 2:- print(json.dumps(SCBError("cli", "Usage: python scb_data.py <command> [args...]").to_dict())- sys.exit(1)-- command = sys.argv[1]-- # Create API instance- api = SCBDataAPI()-- # Map commands to functions- if command == "get_categories":- result = api.get_categories()-- elif command == "get_subcategories":- if len(sys.argv) < 3:- print(json.dumps(SCBError("cli", "Usage: python scb_data.py get_subcategories <category_id>").to_dict())- sys.exit(1)- category_id = sys.argv[2]- result = api.get_subcategories(category_id)-- elif command == "get_table_metadata":- if len(sys.argv) < 3:- print(json.dumps(SCBError("cli", "Usage: python scb_data.py get_table_metadata <table_path>").to_dict())- sys.exit(1)- table_path = sys.argv[2]- result = api.get_table_metadata(table_path)-- elif command == "get_population":- years = sys.argv[2].split(",") if len(sys.argv) > 2 else None- result = api.get_population_data(years)-- elif command == "get_gdp":- quarters = sys.argv[2].split(",") if len(sys.argv) > 2 else None- result = api.get_gdp_data(quarters)-- elif command == "get_employment":- regions = sys.argv[2].split(",") if len(sys.argv) > 2 else None- years = sys.argv[3].split(",") if len(sys.argv) > 3 else None- result = api.get_employment_data(regions, years)-- elif command == "get_cpi":- months = sys.argv[2].split(",") if len(sys.argv) > 2 else None- result = api.get_cpi_data(months)-- elif command == "get_demographic_overview":- start_year = sys.argv[2] if len(sys.argv) > 2 else None- end_year = sys.argv[3] if len(sys.argv) > 3 else None- result = api.get_demographic_data(start_year, end_year)-- elif command == "search_tables":- query = sys.argv[2] if len(sys.argv) > 2 else ""- category = sys.argv[3] if len(sys.argv) > 3 else None- result = api.search_tables(query, category)-- elif command == "get_popular_tables":- result = api.get_popular_tables()-- elif command == "get_category_info":- result = api.get_category_info()-- else:- available_commands = [- "get_categories",- "get_subcategories <category_id>",- "get_table_metadata <table_path>",- "get_population [years]",- "get_gdp [quarters]",- "get_employment [regions] [years]",- "get_cpi [months]",- "get_demographic_overview [start_year] [end_year]",- "search_tables <query> [category]",- "get_popular_tables",- "get_category_info"- ]- print(json.dumps({- "error": f"Unknown command: {command}",- "available_commands": available_commands- })- sys.exit(1)-- print(json.dumps(result, indent=2, default=str)---if __name__ == "__main__":- main(\ No newline at end of filediff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/unesco_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/unesco_data.pyindex e61fb3f6f..446b0277f 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/unesco_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/unesco_data.py@@ -607,7 +607,78 @@ def main():wrapper = UISWrapper()try:- if command == "indicator_data":+ if command == "fetch":+ # Frontend integration command: fetch <indicator_code> <country_code> [start_year] [end_year]+ # Returns normalized { success, data: [{date, value}], metadata }+ if len(sys.argv) < 4:+ print(json.dumps({"error": "Usage: fetch <indicator_code> <country_code> [start_year] [end_year]"}))+ sys.exit(1)++ indicator_code = sys.argv[2]+ country_code = sys.argv[3] # 3-letter ISO code (e.g. USA, GBR, IND)+ start_year = int(sys.argv[4]) if len(sys.argv) > 4 else None+ end_year = int(sys.argv[5]) if len(sys.argv) > 5 else None++ # Fetch directly with correct lowercase 'true' for indicatorMetadata+ params = {'indicator': [indicator_code], 'geoUnit': [country_code], 'indicatorMetadata': 'true'}+ if start_year:+ params['start'] = start_year+ if end_year:+ params['end'] = end_year+ result = wrapper._make_request('/data/indicators', params)++ if not result.get("success"):+ print(json.dumps(result))+ sys.exit(1)++ records = result.get("data", {}).get("records", []) if isinstance(result.get("data"), dict) else result.get("data", [])++ # Check for hints (API warnings about invalid codes)+ hints = []+ if isinstance(result.get("data"), dict):+ hints = result["data"].get("hints", [])+ if not records and hints:+ hint_msgs = [h.get("message", "") for h in hints]+ print(json.dumps({"success": False, "error": "API warning: " + "; ".join(hint_msgs)}))+ sys.exit(1)++ # Normalize records to [{date, value}]+ data_points = []+ indicator_name = indicator_code+ for rec in records:+ year = rec.get("year")+ value = rec.get("value")+ if year is not None and value is not None:+ try:+ val = float(value)+ except (ValueError, TypeError):+ continue+ data_points.append({"date": str(year), "value": val})+ if not indicator_name or indicator_name == indicator_code:+ indicator_name = rec.get("indicatorId", indicator_code)++ # Get indicator name from metadata if available+ ind_metadata = result.get("data", {}).get("indicatorMetadata", []) if isinstance(result.get("data"), dict) else []+ if ind_metadata and len(ind_metadata) > 0:+ meta_name = ind_metadata[0].get("name")+ if meta_name:+ indicator_name = meta_name++ # Sort by date+ data_points.sort(key=lambda x: x["date"])++ print(json.dumps({+ "success": True,+ "data": data_points,+ "metadata": {+ "indicator": indicator_code,+ "indicator_name": indicator_name,+ "country": country_code,+ "source": "UNESCO UIS"+ }+ }))++ elif command == "indicator_data":indicators = []geo_units = []geo_unit_type = Nonediff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/validate_akshare_functions.py b/fincept-terminal-desktop/src-tauri/resources/scripts/validate_akshare_functions.pydeleted file mode 100644index 3d422c60c..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/validate_akshare_functions.py+++ /dev/null@@ -1,142 +0,0 @@-#!/usr/bin/env python3-"""-AKShare Function Validator-Tests all extracted functions against akshare 1.18.20 to identify invalid/missing functions-"""--import sys-import json-import re-from pathlib import Path-from collections import defaultdict--try:- import akshare as ak- print(f"AKShare version: {ak.__version__}")-except ImportError:- print("ERROR: akshare not installed")- sys.exit(1)--def extract_akshare_functions_from_file(filepath):- """Extract all ak.function_name() calls from a Python file"""- functions = set()-- with open(filepath, 'r', encoding='utf-8') as f:- content = f.read()-- # Find all ak.function_name patterns- pattern = r'ak\.([a-z_][a-z0-9_]*)'- matches = re.findall(pattern, content, re.IGNORECASE)- functions.update(matches)-- return functions--def main():- # Path to scripts directory- scripts_dir = Path(__file__).parent-- # Find all akshare*.py files- akshare_files = list(scripts_dir.glob('akshare*.py'))-- # Extract all functions- all_functions = set()- file_function_map = {}-- for filepath in akshare_files:- filename = filepath.name- if filename == 'validate_akshare_functions.py' or filename == 'analyze_akshare_functions.py':- continue- functions = extract_akshare_functions_from_file(filepath)- file_function_map[filename] = functions- all_functions.update(functions)-- print(f"\nTotal unique functions to validate: {len(all_functions)}")- print("="*80)-- # Get all available akshare functions- available_functions = set(dir(ak))-- # Validate each function- valid_functions = []- invalid_functions = []-- for func in sorted(all_functions):- if hasattr(ak, func):- valid_functions.append(func)- else:- # Find which files use this function- files_using = [f for f, funcs in file_function_map.items() if func in funcs]- invalid_functions.append((func, files_using))-- print(f"\nVALIDATION RESULTS:")- print("="*80)- print(f"Valid functions: {len(valid_functions)}")- print(f"Invalid/Missing functions: {len(invalid_functions)}")- print(f"Success rate: {len(valid_functions)/len(all_functions)*100:.1f}%")-- if invalid_functions:- print("\n" + "="*80)- print("INVALID/MISSING FUNCTIONS:")- print("="*80)-- for func, files in sorted(invalid_functions):- print(f"\n[!] {func}")- print(f" Used in: {', '.join(files)}")-- # Try to find similar functions- similar = [f for f in available_functions if func.replace('_', '') in f.replace('_', '').lower()][:3]- if similar:- print(f" Similar functions: {', '.join(similar)}")-- # Save detailed report- report = {- "akshare_version": ak.__version__,- "total_functions_used": len(all_functions),- "valid_functions": len(valid_functions),- "invalid_functions": len(invalid_functions),- "success_rate": len(valid_functions)/len(all_functions)*100,- "invalid_function_details": [- {- "function": func,- "files": files- }- for func, files in sorted(invalid_functions)- ],- "valid_function_list": sorted(valid_functions)- }-- report_path = scripts_dir / "akshare_validation_report.json"- with open(report_path, 'w', encoding='utf-8') as f:- json.dump(report, f, indent=2, ensure_ascii=False)-- print(f"\n\nDetailed report saved to: {report_path}")-- # Category analysis for invalid functions- if invalid_functions:- print("\n" + "="*80)- print("CATEGORY ANALYSIS:")- print("="*80)-- categories = defaultdict(list)- for func, files in invalid_functions:- prefix = func.split('_')[0] if '_' in func else 'other'- categories[prefix].append(func)-- for category, funcs in sorted(categories.items()):- print(f"\n{category}: {len(funcs)} functions")- for func in sorted(funcs)[:5]:- print(f" - {func}")- if len(funcs) > 5:- print(f" ... and {len(funcs) - 5} more")-- print("\n" + "="*80)- print("RECOMMENDATIONS:")- print("="*80)- print("1. Review invalid functions and update wrapper files")- print("2. Check akshare documentation for correct function names")- print("3. Remove or replace deprecated functions")- print("4. Consider using similar functions where available")- print("\nDocumentation: https://akshare.akfamily.xyz/")--if __name__ == "__main__":- main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.pyindex fdf53ee9f..af36f37dc 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py@@ -88,7 +88,7 @@ def get_historical_price(symbol, target_date):dict with price info or error"""try:- from datetime import datetime, timedelta+ from datetime import timedelta# Parse target datetarget = datetime.strptime(target_date, '%Y-%m-%d')@@ -104,7 +104,6 @@ def get_historical_price(symbol, target_date):return {"found": False, "error": "No data available for this date range", "symbol": symbol}# Find the closest date <= target_date- target_ts = target.replace(hour=23, minute=59, second=59)closest_date = Noneclosest_price = None@@ -192,7 +191,7 @@ def get_info(symbol):"short_percent_of_float": info.get('shortPercentOfFloat'),"peg_ratio": info.get('trailingPegRatio'),"total_assets": info.get('totalAssets'),- "total_liabilities": info.get('totalDebt'),+ "total_liabilities": info.get('totalLiab', info.get('totalLiabilities')),"book_value_total": (info.get('bookValue') or 0) * (info.get('sharesOutstanding') or 0) if info.get('bookValue') and info.get('sharesOutstanding') else None,"timestamp": int(datetime.now().timestamp())}@@ -240,7 +239,7 @@ def get_batch_quotes(symbols):"""Fetch quotes for multiple symbols at once using yfinance batch download"""try:# Use yfinance download() for true batch fetching (single HTTP request)- data = yf.download(symbols, period="2d", group_by='ticker', progress=False, threads=True)+ data = yf.download(symbols, period="2d", group_by='ticker', progress=False, threads=True, auto_adjust=True)if data is None or data.empty:return []diff --git a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading.rs b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading.rsindex 4103a3eee..c4b20e439 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading.rs@@ -266,8 +266,13 @@ pub async fn deploy_algo_strategy(let deploy_provider = provider.unwrap_or_default();let deploy_params = params.unwrap_or_else(|| "{}".to_string());+ println!("[AlgoDeploy] ====================================================");+ println!("[AlgoDeploy] Strategy: {}, Symbol: {}, Mode: {}, TF: {}, Qty: {}", strategy_id, symbol, deploy_mode, deploy_timeframe, deploy_qty);+ println!("[AlgoDeploy] Provider: '{}', Params: {}", deploy_provider, deploy_params);+// Generate deployment IDlet deploy_id = format!("algo-{}", uuid::Uuid::new_v4());+ println!("[AlgoDeploy] Deploy ID: {}", deploy_id);// Insert deployment recordlet conn = get_db().map_err(|e| e.to_string())?;@@ -302,7 +307,25 @@ pub async fn deploy_algo_strategy(}).to_string());}+ // Pre-fetch historical candles so the runner has data to evaluate conditions against.+ // Without this, the candle_cache is empty and the runner just loops forever seeing no data.+ // We do this before spawning the runner so data is available immediately.+ let broker_for_prefetch = if deploy_provider.is_empty() { "fyers".to_string() } else { deploy_provider.clone() };+ let symbol_list = vec![symbol.clone()];+ match prefetch_historical_candles(&db_path, &symbol_list, &deploy_timeframe, &broker_for_prefetch, None).await {+ Ok(_debug) => {+ println!("[deploy] Prefetched historical candles for {} @ {}", symbol, deploy_timeframe);+ }+ Err(e) => {+ // Non-fatal: log warning but proceed with deployment.+ // The candle aggregator will build candles from live ticks going forward.+ eprintln!("[deploy] Warning: candle prefetch failed for {}: {}", symbol, e);+ }+ }+// Spawn the Python runner as a background process+ println!("[AlgoDeploy] Spawning Python runner: {:?}", runner_path);+ println!("[AlgoDeploy] DB path: {}", db_path);let child = Command::new("python").arg(&runner_path).arg("--deploy-id")@@ -326,6 +349,7 @@ pub async fn deploy_algo_strategy(match child {Ok(child) => {let pid = child.id();+ println!("[AlgoDeploy] Python runner spawned OK, PID={}", pid);// Update deployment with PID and running statuslet _ = conn.execute(@@ -334,11 +358,83 @@ pub async fn deploy_algo_strategy();// Auto-start candle aggregation for this symbol+timeframe+ println!("[AlgoDeploy] Starting candle aggregation for {} @ {}", symbol, deploy_timeframe);let services = state.services.read().await;services.candle_aggregator.add_subscription(symbol.clone(), deploy_timeframe.clone()).await;+ println!("[AlgoDeploy] Candle aggregation subscription added");++ // -- Auto-connect broker WebSocket if needed --+ // When deploying for Indian stock brokers (e.g., angelone), the user may+ // not have visited the Equity Trading tab, so the broker WS is not connected.+ // We auto-connect from stored credentials so ticks flow to CandleAggregator.+ if deploy_provider == "angelone" {+ // Parse token and exchange from deploy params (sent by frontend SymbolSearch)+ let params_json: serde_json::Value = serde_json::from_str(&deploy_params).unwrap_or_default();+ let direct_token = params_json.get("token").and_then(|v| v.as_str()).map(String::from);+ let direct_exchange = params_json.get("exchange").and_then(|v| v.as_str()).unwrap_or("NSE").to_string();++ println!("[AlgoDeploy] Params: token={:?}, exchange={}", direct_token, direct_exchange);++ let router = state.router.clone();+ match crate::commands::brokers::websocket_commands::ensure_angelone_ws_connected(&app, router).await {+ Ok(_) => {+ println!("[AlgoDeploy] Angel One WS connected, subscribing to {}", symbol);+ // Use the token from frontend if available, otherwise symbol master lookup+ match crate::commands::brokers::websocket_commands::ensure_angelone_ws_subscribed(+ &symbol, &direct_exchange, direct_token.as_deref()+ ).await {+ Ok(_) => println!("[AlgoDeploy] Angel One WS subscribed to {}", symbol),+ Err(e) => {+ // If direct exchange failed and it wasn't BSE, try BSE as fallback+ if direct_exchange != "BSE" {+ eprintln!("[AlgoDeploy] {} subscribe failed ({}), trying BSE...", direct_exchange, e);+ match crate::commands::brokers::websocket_commands::ensure_angelone_ws_subscribed(+ &symbol, "BSE", None+ ).await {+ Ok(_) => println!("[AlgoDeploy] Angel One WS subscribed to {} on BSE", symbol),+ Err(e2) => eprintln!("[AlgoDeploy] WARNING: Could not subscribe: {}={}, BSE={}", direct_exchange, e, e2),+ }+ } else {+ eprintln!("[AlgoDeploy] WARNING: Could not subscribe to {}: {}", symbol, e);+ }+ }+ }+ }+ Err(e) => {+ eprintln!("[AlgoDeploy] WARNING: Could not auto-connect Angel One WS: {}", e);+ eprintln!("[AlgoDeploy] Ticks will not reach CandleAggregator until WS is connected from the UI");+ }+ }+ }++ // Auto-start order signal bridge for live deployments+ // (idempotent — only one instance runs regardless of how many times called)+ if deploy_mode == "live" && !ORDER_BRIDGE_RUNNING.swap(true, Ordering::SeqCst) {+ let bridge_app = app.clone();+ tokio::spawn(async move {+ println!("[AlgoOrderBridge] Auto-started for live deployment");+ loop {+ if !ORDER_BRIDGE_RUNNING.load(Ordering::SeqCst) {+ break;+ }+ match poll_and_execute_signals(&bridge_app).await {+ Ok(count) => {+ if count > 0 {+ println!("[AlgoOrderBridge] Executed {} order signal(s)", count);+ }+ }+ Err(e) => {+ eprintln!("[AlgoOrderBridge] Error: {}", e);+ }+ }+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;+ }+ ORDER_BRIDGE_RUNNING.store(false, Ordering::SeqCst);+ });+ }Ok(json!({"success": true,@@ -459,6 +555,71 @@ pub async fn stop_all_algo_deployments() -> Result<String, String> {}).to_string())}+/// Delete an algo deployment and its associated trades/metrics+#[tauri::command]+pub async fn delete_algo_deployment(deploy_id: String) -> Result<String, String> {+ let conn = get_db().map_err(|e| e.to_string())?;++ // First check if deployment exists and stop it if running+ let status_result: Result<(String, Option<i64>), _> = conn.query_row(+ "SELECT status, pid FROM algo_deployments WHERE id = ?1",+ rusqlite::params![deploy_id],+ |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<i64>>(1)?)),+ );++ match status_result {+ Ok((status, pid)) => {+ // Kill process if still running+ if status == "running" {+ if let Some(pid) = pid {+ #[cfg(target_os = "windows")]+ {+ let _ = std::process::Command::new("taskkill")+ .args(["/F", "/PID", &pid.to_string()])+ .output();+ }+ #[cfg(not(target_os = "windows"))]+ {+ let _ = std::process::Command::new("kill")+ .arg(pid.to_string())+ .output();+ }+ }+ }++ // Delete associated records (trades, metrics, order signals)+ let _ = conn.execute(+ "DELETE FROM algo_trades WHERE deployment_id = ?1",+ rusqlite::params![deploy_id],+ );+ let _ = conn.execute(+ "DELETE FROM algo_metrics WHERE deployment_id = ?1",+ rusqlite::params![deploy_id],+ );+ let _ = conn.execute(+ "DELETE FROM algo_order_signals WHERE deployment_id = ?1",+ rusqlite::params![deploy_id],+ );++ // Delete the deployment itself+ conn.execute(+ "DELETE FROM algo_deployments WHERE id = ?1",+ rusqlite::params![deploy_id],+ )+ .map_err(|e| format!("Failed to delete deployment: {}", e))?;++ println!("[AlgoTrading] Deleted deployment: {}", deploy_id);+ Ok(json!({ "success": true, "deleted": true }).to_string())+ }+ Err(rusqlite::Error::QueryReturnedNoRows) => {+ Ok(json!({ "success": false, "error": "Deployment not found" }).to_string())+ }+ Err(e) => {+ Ok(json!({ "success": false, "error": e.to_string() }).to_string())+ }+ }+}+/// List all algo deployments with their metrics#[tauri::command]pub async fn list_algo_deployments() -> Result<String, String> {@@ -515,6 +676,12 @@ pub async fn list_algo_deployments() -> Result<String, String> {let deployments: Vec<serde_json::Value> = rows.filter_map(|r| r.ok()).collect();+ // Log deployment list summary to console (only when there are running deployments)+ let running_count = deployments.iter().filter(|d| d.get("status").and_then(|s| s.as_str()) == Some("running")).count();+ if running_count > 0 {+ println!("[AlgoMonitor] list_deployments: {} total, {} running", deployments.len(), running_count);+ }+Ok(json!({"success": true,"data": deployments,@@ -742,38 +909,42 @@ async fn prefetch_historical_candles(let mut debug_log: Vec<String> = Vec::new();- // Only support Fyers for now+ // For non-Fyers brokers, fall back to Fyers API for historical data prefetch.+ // Fyers supports all NSE/BSE symbols regardless of which broker is used for execution.if broker != "fyers" {- debug_log.push(format!("[prefetch] broker '{}' not supported for prefetch, only 'fyers' is supported", broker));- return Ok(debug_log);+ debug_log.push(format!("[prefetch] broker '{}' doesn't have prefetch support, falling back to Fyers API for historical data", broker));}- // Get Fyers credentials+ // Get Fyers credentials (always use Fyers for historical data)debug_log.push("[prefetch] fetching Fyers credentials...".to_string());- let creds = brokers::get_indian_broker_credentials("fyers".to_string())- .await- .map_err(|e| format!("Failed to get Fyers credentials: {}", e))?;+ let creds = match brokers::get_indian_broker_credentials("fyers".to_string()).await {+ Ok(c) => c,+ Err(e) => {+ debug_log.push(format!("[prefetch] could not fetch Fyers credentials: {}. Skipping prefetch — algo will rely on live ticks.", e));+ return Ok(debug_log);+ }+ };if !creds.success || creds.data.is_none() {- return Err("Fyers credentials not found. Please authenticate with Fyers first (Settings > Brokers > Fyers).".to_string());+ debug_log.push("[prefetch] Fyers credentials not found. Skipping prefetch — algo will rely on live ticks. For historical data, authenticate with Fyers in Settings > Brokers.".to_string());+ return Ok(debug_log);}let cred_data = creds.data.unwrap();- let api_key = cred_data.get("apiKey")- .and_then(|v| v.as_str())- .ok_or("Fyers API key not found in stored credentials")?- .to_string();- let access_token = cred_data.get("accessToken")- .and_then(|v| v.as_str())- .ok_or("Fyers access token not found. Please re-authenticate with Fyers — tokens expire daily.")?- .to_string();-- if api_key.is_empty() {- return Err("Fyers API key is empty. Please re-enter credentials in Settings > Brokers.".to_string());- }- if access_token.is_empty() {- return Err("Fyers access token is empty. Please re-authenticate — Fyers tokens expire daily.".to_string());- }+ let api_key = match cred_data.get("apiKey").and_then(|v| v.as_str()) {+ Some(k) if !k.is_empty() => k.to_string(),+ _ => {+ debug_log.push("[prefetch] Fyers API key not found or empty. Skipping prefetch.".to_string());+ return Ok(debug_log);+ }+ };+ let access_token = match cred_data.get("accessToken").and_then(|v| v.as_str()) {+ Some(t) if !t.is_empty() => t.to_string(),+ _ => {+ debug_log.push("[prefetch] Fyers access token not found or empty. Skipping prefetch — tokens expire daily.".to_string());+ return Ok(debug_log);+ }+ };debug_log.push(format!("[prefetch] credentials OK (api_key len={}, token len={})", api_key.len(), access_token.len()));@@ -1343,6 +1514,283 @@ pub async fn stop_order_signal_bridge() -> Result<String, String> {}).to_string())}+/// Debug diagnostic command: returns the state of candle_cache, strategy_price_cache,+/// deployment status, and Python process health for a given deployment.+#[tauri::command]+pub async fn debug_algo_deployment(+ deploy_id: String,+) -> Result<String, String> {+ let result = tokio::task::spawn_blocking(move || -> Result<serde_json::Value, String> {+ let conn = get_db().map_err(|e| e.to_string())?;+ let mut diag = serde_json::Map::new();++ // 1. Deployment record+ let deploy_row = conn.query_row(+ "SELECT id, strategy_id, symbol, provider, mode, status, timeframe, quantity, pid, error_message, created_at, updated_at+ FROM algo_deployments WHERE id = ?1",+ rusqlite::params![deploy_id],+ |row| {+ Ok(json!({+ "id": row.get::<_, String>(0)?,+ "strategy_id": row.get::<_, String>(1)?,+ "symbol": row.get::<_, String>(2)?,+ "provider": row.get::<_, String>(3)?,+ "mode": row.get::<_, String>(4)?,+ "status": row.get::<_, String>(5)?,+ "timeframe": row.get::<_, String>(6)?,+ "quantity": row.get::<_, f64>(7)?,+ "pid": row.get::<_, Option<i64>>(8)?,+ "error_message": row.get::<_, Option<String>>(9)?,+ "created_at": row.get::<_, String>(10)?,+ "updated_at": row.get::<_, String>(11)?,+ }))+ },+ );+ match deploy_row {+ Ok(v) => { diag.insert("deployment".to_string(), v); }+ Err(e) => { diag.insert("deployment_error".to_string(), json!(e.to_string())); }+ }++ // Extract symbol and timeframe from deployment+ let (symbol, timeframe) = {+ let s: String = conn.query_row(+ "SELECT symbol FROM algo_deployments WHERE id = ?1", rusqlite::params![deploy_id], |r| r.get(0),+ ).unwrap_or_default();+ let t: String = conn.query_row(+ "SELECT timeframe FROM algo_deployments WHERE id = ?1", rusqlite::params![deploy_id], |r| r.get(0),+ ).unwrap_or_else(|_| "5m".to_string());+ (s, t)+ };++ // 2. Check if Python process is alive (check PID)+ let pid: Option<i64> = conn.query_row(+ "SELECT pid FROM algo_deployments WHERE id = ?1", rusqlite::params![deploy_id], |r| r.get(0),+ ).unwrap_or(None);++ if let Some(pid_val) = pid {+ #[cfg(target_os = "windows")]+ {+ let output = std::process::Command::new("tasklist")+ .args(["/FI", &format!("PID eq {}", pid_val), "/FO", "CSV", "/NH"])+ .output();+ match output {+ Ok(o) => {+ let stdout = String::from_utf8_lossy(&o.stdout);+ let is_alive = stdout.contains(&pid_val.to_string());+ diag.insert("python_process_alive".to_string(), json!(is_alive));+ diag.insert("python_process_output".to_string(), json!(stdout.trim()));+ }+ Err(e) => {+ diag.insert("python_process_check_error".to_string(), json!(e.to_string()));+ }+ }+ }+ #[cfg(not(target_os = "windows"))]+ {+ let alive = std::path::Path::new(&format!("/proc/{}", pid_val)).exists();+ diag.insert("python_process_alive".to_string(), json!(alive));+ }+ diag.insert("python_pid".to_string(), json!(pid_val));+ } else {+ diag.insert("python_pid".to_string(), json!(null));+ diag.insert("python_process_alive".to_string(), json!(false));+ }++ // 3. Candle cache stats+ let candle_count: i64 = conn.query_row(+ "SELECT COUNT(*) FROM candle_cache WHERE symbol = ?1 AND timeframe = ?2 AND is_closed = 1",+ rusqlite::params![symbol, timeframe],+ |r| r.get(0),+ ).unwrap_or(0);+ diag.insert("candle_cache_count".to_string(), json!(candle_count));++ // Also check with normalized symbol (strip colon prefix)+ let clean_sym = if symbol.contains(':') {+ symbol.split(':').last().unwrap_or(&symbol).to_string()+ } else {+ symbol.clone()+ };+ let candle_count_clean: i64 = conn.query_row(+ "SELECT COUNT(*) FROM candle_cache WHERE symbol = ?1 AND timeframe = ?2 AND is_closed = 1",+ rusqlite::params![clean_sym, timeframe],+ |r| r.get(0),+ ).unwrap_or(0);+ diag.insert("candle_cache_count_clean_symbol".to_string(), json!(candle_count_clean));++ // Get all distinct symbols in candle_cache for this timeframe+ let mut stmt = conn.prepare(+ "SELECT DISTINCT symbol, COUNT(*) as cnt FROM candle_cache WHERE timeframe = ?1 GROUP BY symbol"+ ).unwrap();+ let cached_symbols: Vec<serde_json::Value> = stmt.query_map(+ rusqlite::params![timeframe],+ |r| Ok(json!({"symbol": r.get::<_, String>(0)?, "count": r.get::<_, i64>(1)?}))+ ).unwrap().filter_map(|r| r.ok()).collect();+ diag.insert("candle_cache_symbols".to_string(), json!(cached_symbols));++ // Latest candle timestamp+ let latest_candle: Option<i64> = conn.query_row(+ "SELECT MAX(open_time) FROM candle_cache WHERE timeframe = ?1",+ rusqlite::params![timeframe],+ |r| r.get(0),+ ).unwrap_or(None);+ diag.insert("candle_cache_latest_ts".to_string(), json!(latest_candle));++ // 4. Strategy price cache+ let price_count: i64 = conn.query_row(+ "SELECT COUNT(*) FROM strategy_price_cache",+ [],+ |r| r.get(0),+ ).unwrap_or(0);+ diag.insert("price_cache_total_entries".to_string(), json!(price_count));++ let mut stmt2 = conn.prepare(+ "SELECT symbol, price, updated_at FROM strategy_price_cache ORDER BY updated_at DESC LIMIT 20"+ ).unwrap();+ let price_entries: Vec<serde_json::Value> = stmt2.query_map(+ [],+ |r| Ok(json!({"symbol": r.get::<_, String>(0)?, "price": r.get::<_, f64>(1)?, "updated_at": r.get::<_, i64>(2)?}))+ ).unwrap().filter_map(|r| r.ok()).collect();+ diag.insert("price_cache_entries".to_string(), json!(price_entries));++ // 5. Metrics+ let metrics = conn.query_row(+ "SELECT total_pnl, unrealized_pnl, total_trades, win_rate, max_drawdown, current_position_qty, current_position_side, current_position_entry, updated_at+ FROM algo_metrics WHERE deployment_id = ?1",+ rusqlite::params![deploy_id],+ |r| Ok(json!({+ "total_pnl": r.get::<_, f64>(0)?,+ "unrealized_pnl": r.get::<_, f64>(1)?,+ "total_trades": r.get::<_, i32>(2)?,+ "win_rate": r.get::<_, f64>(3)?,+ "max_drawdown": r.get::<_, f64>(4)?,+ "current_position_qty": r.get::<_, f64>(5)?,+ "current_position_side": r.get::<_, String>(6)?,+ "current_position_entry": r.get::<_, f64>(7)?,+ "updated_at": r.get::<_, String>(8)?,+ })),+ );+ match metrics {+ Ok(v) => { diag.insert("metrics".to_string(), v); }+ Err(e) => { diag.insert("metrics_error".to_string(), json!(e.to_string())); }+ }++ // 6. Recent trades+ let mut stmt3 = conn.prepare(+ "SELECT id, side, quantity, price, pnl, signal_reason, created_at FROM algo_trades WHERE deployment_id = ?1 ORDER BY created_at DESC LIMIT 10"+ ).unwrap();+ let trades: Vec<serde_json::Value> = stmt3.query_map(+ rusqlite::params![deploy_id],+ |r| Ok(json!({+ "id": r.get::<_, String>(0)?,+ "side": r.get::<_, String>(1)?,+ "quantity": r.get::<_, f64>(2)?,+ "price": r.get::<_, f64>(3)?,+ "pnl": r.get::<_, f64>(4)?,+ "reason": r.get::<_, String>(5)?,+ "created_at": r.get::<_, String>(6)?,+ })),+ ).unwrap().filter_map(|r| r.ok()).collect();+ diag.insert("recent_trades".to_string(), json!(trades));++ // 7. Pending order signals+ let pending_signals: i64 = conn.query_row(+ "SELECT COUNT(*) FROM algo_order_signals WHERE deployment_id = ?1 AND status = 'pending'",+ rusqlite::params![deploy_id],+ |r| r.get(0),+ ).unwrap_or(0);+ diag.insert("pending_order_signals".to_string(), json!(pending_signals));++ // 8. Order bridge status+ diag.insert("order_bridge_running".to_string(), json!(ORDER_BRIDGE_RUNNING.load(Ordering::SeqCst)));++ // 9. Strategy conditions (for context)+ let strategy_id: String = conn.query_row(+ "SELECT strategy_id FROM algo_deployments WHERE id = ?1", rusqlite::params![deploy_id], |r| r.get(0),+ ).unwrap_or_default();+ let entry_conds: Option<String> = conn.query_row(+ "SELECT entry_conditions FROM algo_strategies WHERE id = ?1", rusqlite::params![strategy_id], |r| r.get(0),+ ).ok();+ let exit_conds: Option<String> = conn.query_row(+ "SELECT exit_conditions FROM algo_strategies WHERE id = ?1", rusqlite::params![strategy_id], |r| r.get(0),+ ).ok();+ diag.insert("entry_conditions".to_string(), json!(entry_conds));+ diag.insert("exit_conditions".to_string(), json!(exit_conds));++ Ok(json!({"success": true, "data": diag}))+ })+ .await+ .map_err(|e| format!("Spawn error: {}", e))??;++ Ok(result.to_string())+}++/// Get live prices from strategy_price_cache for a list of symbols.+/// Returns a map of symbol -> { price, bid, ask, change_percent, updated_at }.+#[tauri::command]+pub async fn get_deployment_prices(+ symbols: Vec<String>,+) -> Result<String, String> {+ let result = tokio::task::spawn_blocking(move || -> Result<serde_json::Value, String> {+ let conn = get_db().map_err(|e| e.to_string())?;+ let mut prices = serde_json::Map::new();++ // Normalize helper: strip /, -, _, : and uppercase+ fn normalize(s: &str) -> String {+ s.replace('/', "").replace('-', "").replace('_', "").replace(':', "").to_uppercase()+ }++ // Load all cached prices once+ let mut stmt = conn.prepare(+ "SELECT symbol, price, bid, ask, volume, high, low, open, change_percent, updated_at FROM strategy_price_cache"+ ).map_err(|e| format!("Query failed: {}", e))?;++ let rows: Vec<(String, f64, Option<f64>, Option<f64>, Option<f64>, Option<f64>, Option<f64>, Option<f64>, Option<f64>, i64)> = stmt+ .query_map([], |row| {+ Ok((+ row.get::<_, String>(0)?,+ row.get::<_, f64>(1)?,+ row.get::<_, Option<f64>>(2)?,+ row.get::<_, Option<f64>>(3)?,+ row.get::<_, Option<f64>>(4)?,+ row.get::<_, Option<f64>>(5)?,+ row.get::<_, Option<f64>>(6)?,+ row.get::<_, Option<f64>>(7)?,+ row.get::<_, Option<f64>>(8)?,+ row.get::<_, i64>(9)?,+ ))+ })+ .map_err(|e| format!("Read failed: {}", e))?+ .filter_map(|r| r.ok())+ .collect();++ for req_sym in &symbols {+ let norm_req = normalize(req_sym);+ for (cached_sym, price, bid, ask, volume, high, low, open, change_pct, updated) in &rows {+ if normalize(cached_sym) == norm_req {+ prices.insert(req_sym.clone(), json!({+ "price": price,+ "bid": bid,+ "ask": ask,+ "volume": volume,+ "high": high,+ "low": low,+ "open": open,+ "change_percent": change_pct,+ "updated_at": updated,+ }));+ break;+ }+ }+ }++ Ok(json!({ "success": true, "data": prices }))+ })+ .await+ .map_err(|e| format!("Spawn error: {}", e))??;++ Ok(result.to_string())+}+/// Poll `algo_order_signals` for pending signals and execute themasync fn poll_and_execute_signals(app_handle: &tauri::AppHandle,diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rsindex 410080314..566d5c2ea 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs@@ -1122,6 +1122,7 @@ pub async fn fyers_ws_connect(match &msg {MarketMessage::Ticker(data) => {let _ = app_handle.emit("fyers_ticker", data);+ let _ = app_handle.emit("algo_live_ticker", data);}MarketMessage::OrderBook(data) => {let _ = app_handle.emit("fyers_orderbook", data);diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/websocket_commands.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/websocket_commands.rsindex 4e08a3146..14760390c 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/websocket_commands.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/websocket_commands.rs@@ -67,6 +67,8 @@ fn create_ws_callback(match &msg {MarketMessage::Ticker(data) => {let _ = app.emit(&format!("{}_ticker", broker), data);+ // Also emit a unified event so algo monitoring can listen to a single channel+ let _ = app.emit("algo_live_ticker", data);}MarketMessage::OrderBook(data) => {let _ = app.emit(&format!("{}_orderbook", broker), data);@@ -100,6 +102,7 @@ fn create_ws_callback(#[tauri::command]pub async fn upstox_ws_connect(app: tauri::AppHandle,+ state: tauri::State<'_, WebSocketState>,access_token: String,) -> Result<ApiResponse<bool>, String> {let timestamp = chrono::Utc::now().timestamp_millis();@@ -112,7 +115,7 @@ pub async fn upstox_ws_connect(};let mut adapter = UpstoxAdapter::new(config);- adapter.set_message_callback(create_ws_callback(app.clone(), "upstox", None));+ adapter.set_message_callback(create_ws_callback(app.clone(), "upstox", Some(state.router.clone())));match adapter.connect().await {Ok(_) => {@@ -189,6 +192,7 @@ pub async fn upstox_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>,#[tauri::command]pub async fn dhan_ws_connect(app: tauri::AppHandle,+ state: tauri::State<'_, WebSocketState>,client_id: String,access_token: String,is_20_depth: Option<bool>,@@ -210,7 +214,7 @@ pub async fn dhan_ws_connect(};let mut adapter = DhanAdapter::new(config);- adapter.set_message_callback(create_ws_callback(app.clone(), "dhan", None));+ adapter.set_message_callback(create_ws_callback(app.clone(), "dhan", Some(state.router.clone())));match adapter.connect().await {Ok(_) => {@@ -315,7 +319,7 @@ pub async fn angelone_ws_connect(match adapter.connect().await {Ok(_) => {- eprintln!("[angelone_ws_connect] ✓ WebSocket connected successfully");+ eprintln!("[angelone_ws_connect] WebSocket connected successfully");*ANGELONE_WS.write().await = Some(adapter);let _ = app.emit("angelone_status", json!({"provider": "angelone",@@ -325,7 +329,7 @@ pub async fn angelone_ws_connect(Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })}Err(e) => {- eprintln!("[angelone_ws_connect] ✗ WebSocket connection failed: {}", e);+ eprintln!("[angelone_ws_connect] WebSocket connection failed: {}", e);Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })}}@@ -362,16 +366,16 @@ pub async fn angelone_ws_subscribe(symbol: String, mode: String, symbol_name: Oplet params = symbol_name.map(|n| serde_json::json!({ "name": n }));match adapter.subscribe(&symbol, channel, params).await {Ok(_) => {- eprintln!("[angelone_ws_subscribe] ✓ Subscribed to {} ({})", symbol, channel);+ eprintln!("[angelone_ws_subscribe] Subscribed to {} ({})", symbol, channel);Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })},Err(e) => {- eprintln!("[angelone_ws_subscribe] ✗ Subscribe failed: {}", e);+ eprintln!("[angelone_ws_subscribe] Subscribe failed: {}", e);Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })},}} else {- eprintln!("[angelone_ws_subscribe] ✗ Not connected");+ eprintln!("[angelone_ws_subscribe] Not connected");Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })}}@@ -389,6 +393,144 @@ pub async fn angelone_ws_unsubscribe(symbol: String, mode: String) -> Result<Api}}+// ============================================================================+// ANGEL ONE AUTO-CONNECT HELPER (called from algo_trading deploy)+// ============================================================================++/// Check if Angel One WebSocket is connected+pub async fn is_angelone_ws_connected() -> bool {+ ANGELONE_WS.read().await.is_some()+}++/// Connect Angel One WebSocket using stored credentials (no frontend needed).+/// Called from deploy_algo_strategy when provider is "angelone".+/// Returns Ok(true) if connected (or already connected), Err on failure.+pub async fn ensure_angelone_ws_connected(+ app: &tauri::AppHandle,+ router: Arc<tokio::sync::RwLock<MessageRouter>>,+) -> Result<bool, String> {+ // Already connected? Nothing to do.+ if ANGELONE_WS.read().await.is_some() {+ eprintln!("[ensure_angelone_ws] Already connected");+ return Ok(true);+ }++ eprintln!("[ensure_angelone_ws] Not connected — fetching stored credentials...");++ // Fetch credentials from encrypted store+ use crate::commands::broker_credentials::get_broker_credentials;+ let creds = get_broker_credentials("angelone".to_string())+ .await+ .map_err(|e| format!("Failed to fetch angelone credentials: {}", e))?;++ let api_key = creds.api_key+ .ok_or_else(|| "No api_key stored for angelone".to_string())?;+ let access_token = creds.access_token+ .ok_or_else(|| "No access_token stored for angelone".to_string())?;++ // feedToken is stored as JSON inside api_secret: {"password":"...", "totpSecret":"...", "feedToken":"..."}+ let api_secret_str = creds.api_secret+ .ok_or_else(|| "No api_secret stored for angelone".to_string())?;+ let secret_json: serde_json::Value = serde_json::from_str(&api_secret_str)+ .map_err(|e| format!("Failed to parse api_secret JSON: {} — raw: {}", e, &api_secret_str[..api_secret_str.len().min(100)]))?;+ let feed_token = secret_json.get("feedToken")+ .and_then(|v| v.as_str())+ .ok_or_else(|| "feedToken not found in api_secret JSON".to_string())?+ .to_string();++ // Get client_code from additional_data+ let client_code = creds.additional_data+ .as_ref()+ .and_then(|data| serde_json::from_str::<serde_json::Value>(data).ok())+ .and_then(|v| v.get("userId").and_then(|u| u.as_str()).map(String::from))+ .unwrap_or_default();++ if client_code.is_empty() {+ return Err("No userId/clientCode found in angelone credentials".to_string());+ }++ eprintln!("[ensure_angelone_ws] Credentials found: api_key_len={}, token_len={}, feed_token_len={}, client={}",+ api_key.len(), access_token.len(), feed_token.len(), client_code);++ // Build config and connect+ let mut extra = HashMap::new();+ extra.insert("feed_token".to_string(), serde_json::json!(feed_token));++ let config = ProviderConfig {+ name: "angelone".to_string(),+ url: "wss://smartapisocket.angelone.in/smart-stream".to_string(),+ api_key: Some(access_token),+ api_secret: Some(api_key),+ client_id: Some(client_code),+ extra: Some(extra),+ ..Default::default()+ };++ let mut adapter = AngelOneAdapter::new(config);+ adapter.set_message_callback(create_ws_callback(app.clone(), "angelone", Some(router)));++ eprintln!("[ensure_angelone_ws] Attempting WebSocket connection...");++ match adapter.connect().await {+ Ok(_) => {+ eprintln!("[ensure_angelone_ws] WebSocket connected successfully");+ *ANGELONE_WS.write().await = Some(adapter);+ let _ = app.emit("angelone_status", json!({+ "provider": "angelone",+ "status": "connected",+ "timestamp": chrono::Utc::now().timestamp_millis()+ }));+ Ok(true)+ }+ Err(e) => {+ eprintln!("[ensure_angelone_ws] WebSocket connection failed: {}", e);+ Err(format!("Angel One WS connection failed: {}", e))+ }+ }+}++/// Subscribe Angel One WebSocket to a symbol.+/// If token is provided directly, uses it. Otherwise looks up from symbol master.+/// symbol_name: e.g. "AVANTIFEEDS" (user-facing name for tick display)+/// exchange: e.g. "NSE"+/// token: e.g. Some("7936") - if provided, skips symbol master lookup+pub async fn ensure_angelone_ws_subscribed(+ symbol_name: &str,+ exchange: &str,+ direct_token: Option<&str>,+) -> Result<bool, String> {+ let token = if let Some(t) = direct_token {+ eprintln!("[ensure_angelone_ws_subscribed] Using provided token: {}", t);+ t.to_string()+ } else {+ // Look up token from symbol master+ use crate::database::symbol_master;+ symbol_master::get_token_by_symbol("angelone", symbol_name, exchange)+ .map_err(|e| format!("Symbol master lookup failed: {}", e))?+ .ok_or_else(|| format!("No token found for {} on {} in angelone symbol master", symbol_name, exchange))?+ };++ let ws_symbol = format!("{}:{}", exchange, token);+ eprintln!("[ensure_angelone_ws_subscribed] {} => {} (token={})", symbol_name, ws_symbol, token);++ let mut ws_guard = ANGELONE_WS.write().await;+ if let Some(ref mut adapter) = *ws_guard {+ let params = Some(serde_json::json!({ "name": symbol_name }));+ match adapter.subscribe(&ws_symbol, "ltp", params).await {+ Ok(_) => {+ eprintln!("[ensure_angelone_ws_subscribed] Subscribed to {} ({})", ws_symbol, symbol_name);+ Ok(true)+ }+ Err(e) => {+ eprintln!("[ensure_angelone_ws_subscribed] Subscribe failed: {}", e);+ Err(format!("Subscribe failed: {}", e))+ }+ }+ } else {+ Err("Angel One WS not connected".to_string())+ }+}+// ============================================================================// KOTAK WEBSOCKET COMMANDS// ============================================================================@@ -396,6 +538,7 @@ pub async fn angelone_ws_unsubscribe(symbol: String, mode: String) -> Result<Api#[tauri::command]pub async fn kotak_ws_connect(app: tauri::AppHandle,+ state: tauri::State<'_, WebSocketState>,access_token: String,consumer_key: String,) -> Result<ApiResponse<bool>, String> {@@ -410,7 +553,7 @@ pub async fn kotak_ws_connect(};let mut adapter = KotakAdapter::new(config);- adapter.set_message_callback(create_ws_callback(app.clone(), "kotak", None));+ adapter.set_message_callback(create_ws_callback(app.clone(), "kotak", Some(state.router.clone())));match adapter.connect().await {Ok(_) => {@@ -477,6 +620,7 @@ pub async fn kotak_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, S#[tauri::command]pub async fn groww_ws_connect(app: tauri::AppHandle,+ state: tauri::State<'_, WebSocketState>,auth_token: String,) -> Result<ApiResponse<bool>, String> {let timestamp = chrono::Utc::now().timestamp_millis();@@ -489,7 +633,7 @@ pub async fn groww_ws_connect(};let mut adapter = GrowwAdapter::new(config);- adapter.set_message_callback(create_ws_callback(app.clone(), "groww", None));+ adapter.set_message_callback(create_ws_callback(app.clone(), "groww", Some(state.router.clone())));match adapter.connect().await {Ok(_) => {@@ -560,6 +704,7 @@ pub async fn groww_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, S#[tauri::command]pub async fn aliceblue_ws_connect(app: tauri::AppHandle,+ state: tauri::State<'_, WebSocketState>,user_id: String,session_token: String,) -> Result<ApiResponse<bool>, String> {@@ -574,7 +719,7 @@ pub async fn aliceblue_ws_connect(};let mut adapter = AliceBlueAdapter::new(config);- adapter.set_message_callback(create_ws_callback(app.clone(), "aliceblue", None));+ adapter.set_message_callback(create_ws_callback(app.clone(), "aliceblue", Some(state.router.clone())));match adapter.connect().await {Ok(_) => {@@ -646,6 +791,7 @@ pub async fn aliceblue_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool#[tauri::command]pub async fn fivepaisa_ws_connect(app: tauri::AppHandle,+ state: tauri::State<'_, WebSocketState>,client_code: String,jwt_token: String,) -> Result<ApiResponse<bool>, String> {@@ -660,7 +806,7 @@ pub async fn fivepaisa_ws_connect(};let mut adapter = FivePaisaAdapter::new(config);- adapter.set_message_callback(create_ws_callback(app.clone(), "fivepaisa", None));+ adapter.set_message_callback(create_ws_callback(app.clone(), "fivepaisa", Some(state.router.clone())));match adapter.connect().await {Ok(_) => {@@ -733,6 +879,7 @@ pub async fn fivepaisa_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool#[tauri::command]pub async fn iifl_ws_connect(app: tauri::AppHandle,+ state: tauri::State<'_, WebSocketState>,app_key: String,secret_key: String,) -> Result<ApiResponse<bool>, String> {@@ -747,7 +894,7 @@ pub async fn iifl_ws_connect(};let mut adapter = IiflAdapter::new(config);- adapter.set_message_callback(create_ws_callback(app.clone(), "iifl", None));+ adapter.set_message_callback(create_ws_callback(app.clone(), "iifl", Some(state.router.clone())));match adapter.connect().await {Ok(_) => {@@ -819,6 +966,7 @@ pub async fn iifl_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, St#[tauri::command]pub async fn motilal_ws_connect(app: tauri::AppHandle,+ state: tauri::State<'_, WebSocketState>,access_token: String,) -> Result<ApiResponse<bool>, String> {let timestamp = chrono::Utc::now().timestamp_millis();@@ -831,7 +979,7 @@ pub async fn motilal_ws_connect(};let mut adapter = MotilalAdapter::new(config);- adapter.set_message_callback(create_ws_callback(app.clone(), "motilal", None));+ adapter.set_message_callback(create_ws_callback(app.clone(), "motilal", Some(state.router.clone())));match adapter.connect().await {Ok(_) => {@@ -903,6 +1051,7 @@ pub async fn motilal_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>,#[tauri::command]pub async fn shoonya_ws_connect(app: tauri::AppHandle,+ state: tauri::State<'_, WebSocketState>,user_id: String,session_token: String,) -> Result<ApiResponse<bool>, String> {@@ -917,7 +1066,7 @@ pub async fn shoonya_ws_connect(};let mut adapter = ShoonyaAdapter::new(config);- adapter.set_message_callback(create_ws_callback(app.clone(), "shoonya", None));+ adapter.set_message_callback(create_ws_callback(app.clone(), "shoonya", Some(state.router.clone())));match adapter.connect().await {Ok(_) => {diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/zerodha.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/zerodha.rsindex f8e47a90c..04c31510b 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/zerodha.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/zerodha.rs@@ -19,6 +19,7 @@ use tauri::Emitter;use crate::websocket::adapters::WebSocketAdapter;use crate::websocket::types::MarketMessage;+use crate::WebSocketState;use super::common::{ApiResponse, TokenExchangeResponse, OrderPlaceResponse};// Zerodha API Configuration@@ -677,6 +678,7 @@ static ZERODHA_WS: Lazy<Arc<RwLock<Option<crate::websocket::adapters::ZerodhaAda#[tauri::command]pub async fn zerodha_ws_connect(app: tauri::AppHandle,+ state: tauri::State<'_, WebSocketState>,api_key: String,access_token: String,) -> Result<ApiResponse<bool>, String> {@@ -702,12 +704,17 @@ pub async fn zerodha_ws_connect(access_token,);- // Set up message callback to emit Tauri events+ // Clone the router so backend services (candle aggregation, algo trading, etc.) receive ticks+ let router = state.router.clone();++ // Set up message callback to emit Tauri events AND route through MessageRouterlet app_handle = app.clone();adapter.set_message_callback(Box::new(move |msg: MarketMessage| {+ // 1. Emit broker-specific events to frontendmatch &msg {MarketMessage::Ticker(data) => {let _ = app_handle.emit("zerodha_ticker", data);+ let _ = app_handle.emit("algo_live_ticker", data);}MarketMessage::OrderBook(data) => {let _ = app_handle.emit("zerodha_orderbook", data);@@ -722,6 +729,13 @@ pub async fn zerodha_ws_connect(let _ = app_handle.emit("zerodha_candle", data);}}++ // 2. Route through MessageRouter for backend services (candle aggregation, algo trading, etc.)+ let router = router.clone();+ let msg = msg.clone();+ tokio::spawn(async move {+ router.read().await.route(msg).await;+ });}));// Connect to WebSocketdiff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rsindex acd987b91..3471a85a8 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs@@ -50,6 +50,9 @@ pub mod swiss_gov;pub mod spain_data;pub mod adb;+// Nordic / PxWeb data sources+pub mod pxweb;+// Specialized data sourcespub mod openafrica;pub mod hdx;diff --git a/fincept-terminal-desktop/src-tauri/src/commands/pxweb.rs b/fincept-terminal-desktop/src-tauri/src/commands/pxweb.rsnew file mode 100644index 000000000..9732e76c2--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/pxweb.rs@@ -0,0 +1,15 @@+// PxWeb Statistics Finland data commands+use crate::python;++/// Execute PxWeb Python script command+#[tauri::command]+pub async fn execute_pxweb_command(+ app: tauri::AppHandle,+ command: String,+ args: Vec<String>,+) -> Result<String, String> {+ let mut cmd_args = vec![command];+ cmd_args.extend(args);++ python::execute(&app, "pxweb_fetcher.py", cmd_args).await+}diff --git a/fincept-terminal-desktop/src-tauri/src/database/symbol_master.rs b/fincept-terminal-desktop/src-tauri/src/database/symbol_master.rsindex 7b905656f..38ba98a20 100644--- a/fincept-terminal-desktop/src-tauri/src/database/symbol_master.rs+++ b/fincept-terminal-desktop/src-tauri/src/database/symbol_master.rs@@ -477,10 +477,13 @@ pub fn get_symbol_by_token(broker_id: &str, token: &str) -> Result<Option<SymbolOk(result)}-/// Get token by symbol (for WebSocket subscriptions)+/// Get token by symbol (for WebSocket subscriptions).+/// Tries exact match first, then prefix match to handle broker symbol truncation+/// (e.g., Angel One truncates "AVANTIFEEDS" to "AVANTIFEED").pub fn get_token_by_symbol(broker_id: &str, symbol: &str, exchange: &str) -> Result<Option<String>> {let db = get_db()?;+ // Try exact match firstlet token: Option<String> = db.query_row("SELECT token FROM symbols WHERE broker_id = ? AND UPPER(symbol) = UPPER(?) AND exchange = ? LIMIT 1",@@ -489,7 +492,31 @@ pub fn get_token_by_symbol(broker_id: &str, symbol: &str, exchange: &str) -> Res).optional()?;- Ok(token)+ if token.is_some() {+ return Ok(token);+ }++ // Fallback: prefix match (handles broker truncation)+ // e.g., user passes "AVANTIFEEDS" but DB has "AVANTIFEED"+ let upper_sym = symbol.to_uppercase();+ let like_pattern = format!("{}%", &upper_sym[..upper_sym.len().min(6)]);+ let mut stmt = db.prepare(+ "SELECT symbol, token FROM symbols WHERE broker_id = ? AND UPPER(symbol) LIKE ? AND exchange = ? LIMIT 20"+ )?;+ let rows: Vec<(String, String)> = stmt.query_map(+ params![broker_id, like_pattern, exchange],+ |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),+ )?.filter_map(|r| r.ok()).collect();++ for (db_sym, db_token) in &rows {+ let db_upper = db_sym.to_uppercase();+ // Match if one is a prefix of the other+ if upper_sym.starts_with(&db_upper) || db_upper.starts_with(&upper_sym) {+ return Ok(Some(db_token.clone()));+ }+ }++ Ok(None)}/// Get symbol count for a brokerdiff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex 4fca37a19..442f04554 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -1313,6 +1313,8 @@ pub fn run() {commands::adb::get_adb_indicators,commands::adb::search_adb_datasets,commands::adb::get_adb_development_data,+ // PxWeb Statistics Finland Commands+ commands::pxweb::execute_pxweb_command,// OpenAFRICA Commandscommands::openafrica::execute_openafrica_command,commands::openafrica::search_openafrica_datasets,@@ -1703,6 +1705,27 @@ pub fn run() {commands::alpha_arena::list_alpha_trading_styles,commands::alpha_arena::create_alpha_styled_agents,commands::alpha_arena::run_alpha_action,+ commands::alpha_arena::get_alpha_sentiment,+ commands::alpha_arena::get_alpha_market_mood,+ // Alpha Arena - HITL (Human-in-the-Loop)+ commands::alpha_arena::check_alpha_approval,+ commands::alpha_arena::approve_alpha_decision,+ commands::alpha_arena::reject_alpha_decision,+ commands::alpha_arena::get_alpha_pending_approvals,+ commands::alpha_arena::get_alpha_hitl_status,+ commands::alpha_arena::update_alpha_hitl_rule,+ // Alpha Arena - Portfolio & Grid+ commands::alpha_arena::get_alpha_portfolio_metrics,+ commands::alpha_arena::get_alpha_equity_curve,+ commands::alpha_arena::create_alpha_grid_agent,+ commands::alpha_arena::get_alpha_grid_status,+ // Alpha Arena - Research & Broker+ commands::alpha_arena::get_alpha_research,+ commands::alpha_arena::get_alpha_sec_filings,+ commands::alpha_arena::get_alpha_features,+ commands::alpha_arena::list_alpha_brokers,+ commands::alpha_arena::get_alpha_broker,+ commands::alpha_arena::get_alpha_broker_ticker,// AI Quant Lab - Qlibcommands::ai_quant_lab::qlib_list_models,commands::ai_quant_lab::qlib_get_factor_library,@@ -2567,6 +2590,7 @@ pub fn run() {commands::algo_trading::deploy_algo_strategy,commands::algo_trading::stop_algo_deployment,commands::algo_trading::stop_all_algo_deployments,+ commands::algo_trading::delete_algo_deployment,commands::algo_trading::list_algo_deployments,commands::algo_trading::get_algo_trades,commands::algo_trading::run_algo_scan,@@ -2577,6 +2601,8 @@ pub fn run() {commands::algo_trading::run_algo_backtest,commands::algo_trading::start_order_signal_bridge,commands::algo_trading::stop_order_signal_bridge,+ commands::algo_trading::get_deployment_prices,+ commands::algo_trading::debug_algo_deployment,// Python Strategy Librarycommands::algo_trading::list_python_strategies,commands::algo_trading::get_strategy_categories,diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/router.rs b/fincept-terminal-desktop/src-tauri/src/websocket/router.rsindex bf974133f..f789b41ec 100644--- a/fincept-terminal-desktop/src-tauri/src/websocket/router.rs+++ b/fincept-terminal-desktop/src-tauri/src/websocket/router.rs@@ -193,6 +193,9 @@ impl MessageRouter {/// Write latest tick price to strategy_price_cache table for Python live runnerfn update_price_cache(data: &TickerData) {use crate::database::pool::get_pool;+ use std::sync::atomic::{AtomicU64, Ordering as AtOrd};+ static PRICE_CACHE_WRITES: AtomicU64 = AtomicU64::new(0);+if let Ok(pool) = get_pool() {if let Ok(conn) = pool.get() {let _ = conn.execute(@@ -213,6 +216,12 @@ impl MessageRouter {data.timestamp,],);++ // Log every 100th write to avoid spam+ let count = PRICE_CACHE_WRITES.fetch_add(1, AtOrd::Relaxed);+ if count % 100 == 0 {+ println!("[PriceCache] #{} {} price={:.2} provider={}", count, data.symbol, data.price, data.provider);+ }}}}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/services/candle_aggregator.rs b/fincept-terminal-desktop/src-tauri/src/websocket/services/candle_aggregator.rsindex c617cc310..833734551 100644--- a/fincept-terminal-desktop/src-tauri/src/websocket/services/candle_aggregator.rs+++ b/fincept-terminal-desktop/src-tauri/src/websocket/services/candle_aggregator.rs@@ -164,12 +164,39 @@ impl CandleAggregatorService {return;}- // Find all subscriptions matching this symbol+ // Find all subscriptions matching this symbol (exact, normalized, or prefix/contains)+ fn normalize_sym(s: &str) -> String {+ s.replace('/', "").replace('-', "").replace('_', "").replace(':', "").to_uppercase()+ }+ let tick_norm = normalize_sym(&ticker.symbol);+let matching_keys: Vec<AggregationKey> = subs.keys()- .filter(|k| k.symbol == ticker.symbol)+ .filter(|k| {+ if k.symbol == ticker.symbol {+ return true;+ }+ let sub_norm = normalize_sym(&k.symbol);+ if sub_norm == tick_norm {+ return true;+ }+ // Handle broker symbol truncation (e.g., Angel One truncates to 10 chars)+ // "AVANTIFEEDS" subscription should match "AVANTIFEED" tick+ if sub_norm.starts_with(&tick_norm) || tick_norm.starts_with(&sub_norm) {+ return true;+ }+ false+ }).cloned().collect();++ // Debug: log subscription mismatches periodically+ static TICK_COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+ let tc = TICK_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ if matching_keys.is_empty() && tc % 500 == 0 {+ let sub_syms: Vec<&String> = subs.keys().map(|k| &k.symbol).collect();+ println!("[CandleAggregator] Tick #{} for '{}' (norm='{}') — NO subscription match. Subscriptions: {:?}", tc, ticker.symbol, tick_norm, sub_syms);+ }drop(subs);if matching_keys.is_empty() {@@ -178,9 +205,46 @@ impl CandleAggregatorService {let price = ticker.price;let volume = ticker.volume.unwrap_or(0.0);- let tick_ts = ticker.timestamp; // epoch seconds+ // Normalize timestamp to epoch seconds.+ // Some brokers (e.g., Angel One) send timestamps in milliseconds.+ // Heuristic: if ts > 1 trillion, it's milliseconds (year ~2001 in seconds is ~1e9).+ let tick_ts = if ticker.timestamp > 1_000_000_000_000 {+ ticker.timestamp / 1000+ } else if ticker.timestamp == 0 {+ // No timestamp provided -- use current wall-clock time+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0)+ } else {+ ticker.timestamp+ };++ if tc % 200 == 0 {+ println!("[CandleAggregator] Tick #{} matched {} sub(s) for '{}' price={:.2} raw_ts={} norm_ts={}", tc, matching_keys.len(), ticker.symbol, ticker.price, ticker.timestamp, tick_ts);+ }for key in matching_keys {+ // "live" timeframe: write every tick immediately as a closed candle+ if key.timeframe == "live" {+ let closed = ClosedCandle {+ symbol: key.symbol.clone(),+ provider: ticker.provider.clone(),+ timeframe: "live".to_string(),+ open_time: tick_ts,+ o: price,+ h: price,+ l: price,+ c: price,+ volume,+ };+ Self::write_candle_to_db(&closed);+ if let Some(ref handle) = app_handle {+ let _ = handle.emit("algo_candle_closed", &closed);+ }+ continue;+ }+let tf_seconds = timeframe_to_seconds(&key.timeframe);if tf_seconds == 0 {continue;@@ -192,7 +256,7 @@ impl CandleAggregatorService {if let Some(existing) = candle_map.get_mut(&key) {if candle_open_time == existing.open_time {- // Same candle window — update OHLCV+ // Same candle window -- update OHLCVif price > existing.h {existing.h = price;}@@ -203,7 +267,7 @@ impl CandleAggregatorService {existing.volume += volume;existing.tick_count += 1;} else {- // New candle window — close the old one+ // New candle window -- close the old onelet closed = ClosedCandle {symbol: existing.symbol.clone(),provider: existing.provider.clone(),@@ -226,7 +290,7 @@ impl CandleAggregatorService {// Start new candle*existing = CandleState {- symbol: ticker.symbol.clone(),+ symbol: key.symbol.clone(),provider: ticker.provider.clone(),timeframe: key.timeframe.clone(),open_time: candle_open_time,@@ -239,11 +303,11 @@ impl CandleAggregatorService {};}} else {- // First tick for this key — start new candle+ // First tick for this key -- start new candlecandle_map.insert(key.clone(),CandleState {- symbol: ticker.symbol.clone(),+ symbol: key.symbol.clone(),provider: ticker.provider.clone(),timeframe: key.timeframe.clone(),open_time: candle_open_time,@@ -279,7 +343,7 @@ impl CandleAggregatorService {}};- if let Err(e) = conn.execute(+ match conn.execute("INSERT OR REPLACE INTO candle_cache(symbol, provider, timeframe, open_time, o, h, l, c, volume, is_closed)VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 1)",@@ -295,7 +359,13 @@ impl CandleAggregatorService {candle.volume,],) {- eprintln!("[CandleAggregator] DB write error: {}", e);+ Ok(_) => {+ println!("[CandleAggregator] Wrote candle: {} {} open_time={} O={:.2} H={:.2} L={:.2} C={:.2} V={:.0}",+ candle.symbol, candle.timeframe, candle.open_time, candle.o, candle.h, candle.l, candle.c, candle.volume);+ }+ Err(e) => {+ eprintln!("[CandleAggregator] DB write error: {}", e);+ }}});}diff --git a/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts b/fincept-terminal-desktop/src/components/command-bar/commandRegistry.tsindex 6260114ba..5a77e30f0 100644--- a/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts+++ b/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts@@ -181,6 +181,15 @@ export const COMMANDS: Command[] = [action: 'economics',keywords: ['economics', 'indicators', 'macro', 'economic data']},+ {+ id: 'govt',+ name: 'GOVT',+ description: 'Government securities & open data portals',+ aliases: ['govt', 'gov', 'government', 'treasury'],+ category: 'navigation',+ action: 'gov-data',+ keywords: ['government', 'treasury', 'bonds', 'auctions', 'securities', 'fiscal', 'sovereign', 'bills', 'notes', 'tips', 'open data']+ },{id: 'dbn',name: 'DBnomics',diff --git a/fincept-terminal-desktop/src/components/common/charts/DataChart.tsx b/fincept-terminal-desktop/src/components/common/charts/DataChart.tsxnew file mode 100644index 000000000..102d5cafc--- /dev/null+++ b/fincept-terminal-desktop/src/components/common/charts/DataChart.tsx@@ -0,0 +1,127 @@+// DataChart — Generic SVG time-series chart+// Lifted from economics/EconomicsChart and made tab-agnostic.++import React from 'react';+import { FINCEPT_COLORS, CHART_WIDTH, CHART_HEIGHT } from './types';+import type { DataPoint } from './types';++interface DataChartProps {+ data: DataPoint[];+ sourceColor: string;+ formatValue: (val: number) => string;+ width?: number;+ height?: number;+}++// Smart date label formatter+const formatSmartLabel = (date: string, _index: number, allDates: string[], _totalLabels: number): string => {+ const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];+ const year = date.substring(0, 4) || '';+ const month = date.length >= 7 ? date.substring(5, 7) : '';+ const day = date.length >= 10 ? date.substring(8, 10) : '';+ const monthIdx = month ? parseInt(month, 10) - 1 : -1;+ const monthName = monthIdx >= 0 && monthIdx < 12 ? monthNames[monthIdx] : '';+ const shortYear = year.substring(2, 4);+ const firstYear = (allDates[0] || '').substring(0, 4);+ const lastYear = (allDates[allDates.length - 1] || '').substring(0, 4);+ const sameYear = firstYear === lastYear;+ const uniqueYears = new Set(allDates.map(d => d.substring(0, 4))).size;+ const uniqueMonths = new Set(allDates.map(d => d.substring(0, 7))).size;++ if (sameYear && day && monthName) return `${parseInt(day)} ${monthName}`;+ if (uniqueYears <= 2 && monthName && day) return `${parseInt(day)} ${monthName}'${shortYear}`;+ if (uniqueMonths > uniqueYears * 2 && monthName) return `${monthName}'${shortYear}`;+ return year;+};++const filterSignificantPoints = (data: DataPoint[]): DataPoint[] => {+ if (data.length <= 2) return data;+ const result: DataPoint[] = [data[0]];+ for (let i = 1; i < data.length - 1; i++) {+ if (data[i].value !== data[i - 1].value || data[i].value !== data[i + 1].value) {+ result.push(data[i]);+ }+ }+ result.push(data[data.length - 1]);+ return result;+};++const hasSignificantRepetition = (data: DataPoint[]): boolean => {+ if (data.length < 10) return false;+ let same = 0;+ for (let i = 1; i < data.length; i++) if (data[i].value === data[i - 1].value) same++;+ return same / data.length > 0.5;+};++const generateLabelIndices = (data: DataPoint[], maxLabels: number): number[] => {+ if (data.length === 0) return [];+ if (data.length <= maxLabels) return data.map((_, i) => i);+ const indices: number[] = [];+ const step = (data.length - 1) / (maxLabels - 1);+ for (let i = 0; i < maxLabels; i++) {+ const idx = Math.round(i * step);+ if (indices.length === 0 || indices[indices.length - 1] !== idx) indices.push(idx);+ }+ if (indices[indices.length - 1] !== data.length - 1) indices.push(data.length - 1);+ return indices;+};++export function DataChart({ data: rawData, sourceColor, formatValue, width: w, height: h }: DataChartProps) {+ if (!rawData || rawData.length === 0) return null;++ const data = hasSignificantRepetition(rawData) ? filterSignificantPoints(rawData) : rawData;+ const width = w ?? CHART_WIDTH;+ const height = h ?? CHART_HEIGHT;+ const padding = { top: 30, right: 40, bottom: 50, left: 80 };+ const chartWidth = width - padding.left - padding.right;+ const chartHeight = height - padding.top - padding.bottom;++ const values = data.map(d => d.value);+ const minVal = Math.min(...values);+ const maxVal = Math.max(...values);+ const range = maxVal - minVal || 1;++ const points = data.map((d, i) => ({+ x: padding.left + (i / (data.length - 1 || 1)) * chartWidth,+ y: padding.top + chartHeight - ((d.value - minVal) / range) * chartHeight,+ data: d,+ }));++ const pathD = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' ');+ const areaD = `${pathD} L ${points[points.length - 1].x} ${padding.top + chartHeight} L ${padding.left} ${padding.top + chartHeight} Z`;+ const allDates = data.map(d => d.date);+ const maxLabels = Math.max(2, Math.min(15, Math.floor(chartWidth / 70)));+ const labelIndices = generateLabelIndices(data, maxLabels);++ return (+ <svg width={width} height={height} style={{ display: 'block', margin: '0 auto', maxWidth: '100%' }}>+ <rect width={width} height={height} fill={FINCEPT_COLORS.PANEL_BG} />+ {[0, 1, 2, 3, 4, 5].map(i => {+ const y = padding.top + (chartHeight * i) / 5;+ const val = maxVal - (range * i) / 5;+ return (+ <g key={i}>+ <line x1={padding.left} y1={y} x2={width - padding.right} y2={y} stroke={FINCEPT_COLORS.BORDER} strokeDasharray="4,4" />+ <text x={padding.left - 12} y={y + 4} textAnchor="end" fill={FINCEPT_COLORS.WHITE} fontSize="11" fontFamily="monospace">{formatValue(val)}</text>+ </g>+ );+ })}+ {labelIndices.map(idx => {+ const x = padding.left + (idx / (data.length - 1 || 1)) * chartWidth;+ return <line key={`vg-${idx}`} x1={x} y1={padding.top} x2={x} y2={padding.top + chartHeight} stroke={FINCEPT_COLORS.BORDER} strokeDasharray="2,4" strokeOpacity="0.5" />;+ })}+ <path d={areaD} fill={`${sourceColor}25`} />+ <path d={pathD} fill="none" stroke={sourceColor} strokeWidth="2.5" />+ {labelIndices.map(idx => {+ const d = data[idx];+ const x = padding.left + (idx / (data.length - 1 || 1)) * chartWidth;+ return <text key={`xl-${idx}`} x={x} y={height - 15} textAnchor="middle" fill={FINCEPT_COLORS.WHITE} fontSize="10" fontFamily="monospace">{formatSmartLabel(d.date, idx, allDates, labelIndices.length)}</text>;+ })}+ {points.map((p, i) => <circle key={i} cx={p.x} cy={p.y} r={data.length > 30 ? 2 : 3} fill={sourceColor} />)}+ <line x1={padding.left} y1={padding.top + chartHeight} x2={width - padding.right} y2={padding.top + chartHeight} stroke={FINCEPT_COLORS.BORDER} strokeWidth="1" />+ <line x1={padding.left} y1={padding.top} x2={padding.left} y2={padding.top + chartHeight} stroke={FINCEPT_COLORS.BORDER} strokeWidth="1" />+ </svg>+ );+}++export default DataChart;diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/DataTable.tsx b/fincept-terminal-desktop/src/components/common/charts/DataTable.tsxsimilarity index 63%rename from fincept-terminal-desktop/src/components/tabs/economics/components/DataTable.tsxrename to fincept-terminal-desktop/src/components/common/charts/DataTable.tsxindex 5491a6189..babb71862 100644--- a/fincept-terminal-desktop/src/components/tabs/economics/components/DataTable.tsx+++ b/fincept-terminal-desktop/src/components/common/charts/DataTable.tsx@@ -1,9 +1,8 @@-// DataTable Component - Display economic data in table format+// DataTable — Generic date/value/change table for any DataPoint[] dataset-import React from 'react';import { ChevronUp, ChevronDown } from 'lucide-react';-import { FINCEPT } from '../constants';-import type { DataPoint } from '../types';+import { FINCEPT_COLORS } from './types';+import type { DataPoint } from './types';interface DataTableProps {data: DataPoint[];@@ -13,17 +12,17 @@ interface DataTableProps {export function DataTable({ data, sourceColor, formatValue }: DataTableProps) {return (- <div style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', overflow: 'hidden' }}>- <div style={{ padding: '10px 12px', backgroundColor: FINCEPT.HEADER_BG, fontSize: '9px', fontWeight: 700, color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>+ <div style={{ backgroundColor: FINCEPT_COLORS.PANEL_BG, border: `1px solid ${FINCEPT_COLORS.BORDER}`, borderRadius: '2px', overflow: 'hidden' }}>+ <div style={{ padding: '10px 12px', backgroundColor: FINCEPT_COLORS.HEADER_BG, fontSize: '9px', fontWeight: 700, color: FINCEPT_COLORS.WHITE, letterSpacing: '0.5px' }}>DATA TABLE</div><div style={{ maxHeight: '200px', overflowY: 'auto' }}><table style={{ width: '100%', borderCollapse: 'collapse' }}><thead>- <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>- <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: '9px', fontWeight: 700, color: FINCEPT.ORANGE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>DATE</th>- <th style={{ padding: '8px 12px', textAlign: 'right', fontSize: '9px', fontWeight: 700, color: FINCEPT.ORANGE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>VALUE</th>- <th style={{ padding: '8px 12px', textAlign: 'right', fontSize: '9px', fontWeight: 700, color: FINCEPT.ORANGE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>CHANGE</th>+ <tr style={{ backgroundColor: FINCEPT_COLORS.DARK_BG }}>+ <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: '9px', fontWeight: 700, color: sourceColor, borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}` }}>DATE</th>+ <th style={{ padding: '8px 12px', textAlign: 'right', fontSize: '9px', fontWeight: 700, color: sourceColor, borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}` }}>VALUE</th>+ <th style={{ padding: '8px 12px', textAlign: 'right', fontSize: '9px', fontWeight: 700, color: sourceColor, borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}` }}>CHANGE</th></tr></thead><tbody>@@ -31,10 +30,10 @@ export function DataTable({ data, sourceColor, formatValue }: DataTableProps) {const prev = arr[i + 1];const change = prev ? ((d.value - prev.value) / Math.abs(prev.value)) * 100 : 0;return (- <tr key={d.date} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>- <td style={{ padding: '8px 12px', fontSize: '11px', color: FINCEPT.WHITE }}>{d.date}</td>+ <tr key={d.date} style={{ borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}` }}>+ <td style={{ padding: '8px 12px', fontSize: '11px', color: FINCEPT_COLORS.WHITE }}>{d.date}</td><td style={{ padding: '8px 12px', textAlign: 'right', fontSize: '11px', color: sourceColor, fontWeight: 600 }}>{formatValue(d.value)}</td>- <td style={{ padding: '8px 12px', textAlign: 'right', fontSize: '10px', color: change >= 0 ? FINCEPT.GREEN : FINCEPT.RED }}>+ <td style={{ padding: '8px 12px', textAlign: 'right', fontSize: '10px', color: change >= 0 ? FINCEPT_COLORS.GREEN : FINCEPT_COLORS.RED }}>{prev && (<span style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '4px' }}>{change >= 0 ? <ChevronUp size={12} /> : <ChevronDown size={12} />}diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/DateRangePicker.tsx b/fincept-terminal-desktop/src/components/common/charts/DateRangePicker.tsxsimilarity index 74%rename from fincept-terminal-desktop/src/components/tabs/economics/components/DateRangePicker.tsxrename to fincept-terminal-desktop/src/components/common/charts/DateRangePicker.tsxindex 63554c669..872b382d0 100644--- a/fincept-terminal-desktop/src/components/tabs/economics/components/DateRangePicker.tsx+++ b/fincept-terminal-desktop/src/components/common/charts/DateRangePicker.tsx@@ -1,9 +1,9 @@-// DateRangePicker Component - Date range selection for economic data+// DateRangePicker — Reusable preset buttons + custom date inputsimport React from 'react';import { Calendar } from 'lucide-react';-import { FINCEPT } from '../constants';-import type { DateRangePreset } from '../hooks/useEconomicsData';+import { FINCEPT_COLORS } from './types';+import type { DateRangePreset } from './types';interface DateRangePickerProps {dateRangePreset: DateRangePreset;@@ -42,12 +42,12 @@ export function DateRangePicker({alignItems: 'center',gap: '8px',padding: '6px 12px',- backgroundColor: FINCEPT.PANEL_BG,+ backgroundColor: FINCEPT_COLORS.PANEL_BG,borderRadius: '2px',- border: `1px solid ${FINCEPT.BORDER}`,+ border: `1px solid ${FINCEPT_COLORS.BORDER}`,}}>- <Calendar size={14} color={FINCEPT.GRAY} />+ <Calendar size={14} color={FINCEPT_COLORS.GRAY} />{/* Preset buttons */}<div style={{ display: 'flex', gap: '2px' }}>@@ -58,8 +58,8 @@ export function DateRangePicker({style={{padding: '3px 6px',backgroundColor: dateRangePreset === preset.value ? sourceColor : 'transparent',- color: dateRangePreset === preset.value ? FINCEPT.DARK_BG : FINCEPT.GRAY,- border: `1px solid ${dateRangePreset === preset.value ? sourceColor : FINCEPT.BORDER}`,+ color: dateRangePreset === preset.value ? FINCEPT_COLORS.DARK_BG : FINCEPT_COLORS.GRAY,+ border: `1px solid ${dateRangePreset === preset.value ? sourceColor : FINCEPT_COLORS.BORDER}`,borderRadius: '2px',fontSize: '9px',fontWeight: 700,@@ -73,7 +73,7 @@ export function DateRangePicker({</div>{/* Separator */}- <div style={{ width: '1px', height: '16px', backgroundColor: FINCEPT.BORDER }} />+ <div style={{ width: '1px', height: '16px', backgroundColor: FINCEPT_COLORS.BORDER }} />{/* Custom date inputs */}<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>@@ -83,25 +83,25 @@ export function DateRangePicker({onChange={(e) => setStartDate(e.target.value)}style={{padding: '3px 6px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: FINCEPT_COLORS.DARK_BG,+ color: FINCEPT_COLORS.WHITE,+ border: `1px solid ${FINCEPT_COLORS.BORDER}`,borderRadius: '2px',fontSize: '9px',fontFamily: 'inherit',cursor: 'pointer',}}/>- <span style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>to</span>+ <span style={{ color: FINCEPT_COLORS.GRAY, fontSize: '9px' }}>to</span><inputtype="date"value={endDate}onChange={(e) => setEndDate(e.target.value)}style={{padding: '3px 6px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: FINCEPT_COLORS.DARK_BG,+ color: FINCEPT_COLORS.WHITE,+ border: `1px solid ${FINCEPT_COLORS.BORDER}`,borderRadius: '2px',fontSize: '9px',fontFamily: 'inherit',diff --git a/fincept-terminal-desktop/src/components/common/charts/StatsBar.tsx b/fincept-terminal-desktop/src/components/common/charts/StatsBar.tsxnew file mode 100644index 000000000..bb4e4cbdd--- /dev/null+++ b/fincept-terminal-desktop/src/components/common/charts/StatsBar.tsx@@ -0,0 +1,57 @@+// StatsBar — Generic statistics strip for any DataPoint[] dataset++import React from 'react';+import { TrendingUp, TrendingDown } from 'lucide-react';+import { FINCEPT_COLORS } from './types';+import type { ChartStats } from './types';++interface StatsBarProps {+ stats: ChartStats;+ sourceColor: string;+ formatValue: (val: number) => string;+}++export function StatsBar({ stats, sourceColor, formatValue }: StatsBarProps) {+ return (+ <div+ style={{+ padding: '12px 16px',+ backgroundColor: FINCEPT_COLORS.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`,+ display: 'flex',+ gap: '24px',+ flexWrap: 'wrap',+ }}+ >+ <div>+ <div style={{ fontSize: '9px', color: FINCEPT_COLORS.GRAY, marginBottom: '4px' }}>LATEST VALUE</div>+ <div style={{ fontSize: '18px', fontWeight: 700, color: sourceColor }}>{formatValue(stats.latest)}</div>+ </div>+ <div>+ <div style={{ fontSize: '9px', color: FINCEPT_COLORS.GRAY, marginBottom: '4px' }}>CHANGE</div>+ <div style={{ fontSize: '14px', fontWeight: 700, color: stats.change >= 0 ? FINCEPT_COLORS.GREEN : FINCEPT_COLORS.RED, display: 'flex', alignItems: 'center', gap: '4px' }}>+ {stats.change >= 0 ? <TrendingUp size={14} /> : <TrendingDown size={14} />}+ {stats.change >= 0 ? '+' : ''}{stats.change.toFixed(2)}%+ </div>+ </div>+ <div>+ <div style={{ fontSize: '9px', color: FINCEPT_COLORS.GRAY, marginBottom: '4px' }}>MIN</div>+ <div style={{ fontSize: '12px', color: FINCEPT_COLORS.WHITE }}>{formatValue(stats.min)}</div>+ </div>+ <div>+ <div style={{ fontSize: '9px', color: FINCEPT_COLORS.GRAY, marginBottom: '4px' }}>MAX</div>+ <div style={{ fontSize: '12px', color: FINCEPT_COLORS.WHITE }}>{formatValue(stats.max)}</div>+ </div>+ <div>+ <div style={{ fontSize: '9px', color: FINCEPT_COLORS.GRAY, marginBottom: '4px' }}>AVERAGE</div>+ <div style={{ fontSize: '12px', color: FINCEPT_COLORS.WHITE }}>{formatValue(stats.avg)}</div>+ </div>+ <div>+ <div style={{ fontSize: '9px', color: FINCEPT_COLORS.GRAY, marginBottom: '4px' }}>DATA POINTS</div>+ <div style={{ fontSize: '12px', color: FINCEPT_COLORS.WHITE }}>{stats.count}</div>+ </div>+ </div>+ );+}++export default StatsBar;diff --git a/fincept-terminal-desktop/src/components/common/charts/index.ts b/fincept-terminal-desktop/src/components/common/charts/index.tsnew file mode 100644index 000000000..80fa79d98--- /dev/null+++ b/fincept-terminal-desktop/src/components/common/charts/index.ts@@ -0,0 +1,17 @@+// Common chart / data visualization components — barrel export++// Components+export { DataChart } from './DataChart';+export { DataTable } from './DataTable';+export { StatsBar } from './StatsBar';+export { DateRangePicker } from './DateRangePicker';++// Hooks+export { useExport } from './useExport';++// Utilities+export { getDateFromPreset, filterByDateRange, computeStats } from './utils';++// Types & constants+export type { DataPoint, ChartStats, SaveNotification, DateRangePreset } from './types';+export { FINCEPT_COLORS, CHART_WIDTH, CHART_HEIGHT } from './types';diff --git a/fincept-terminal-desktop/src/components/common/charts/types.ts b/fincept-terminal-desktop/src/components/common/charts/types.tsnew file mode 100644index 000000000..5222564aa--- /dev/null+++ b/fincept-terminal-desktop/src/components/common/charts/types.ts@@ -0,0 +1,45 @@+// Common chart/data visualization types — shared across all tabs++export interface DataPoint {+ date: string;+ value: number;+}++export interface ChartStats {+ latest: number;+ change: number;+ min: number;+ max: number;+ avg: number;+ count: number;+}++export interface SaveNotification {+ show: boolean;+ path: string;+ type: 'image' | 'csv';+}++export type DateRangePreset = '1M' | '3M' | '6M' | '1Y' | '2Y' | '5Y' | '10Y' | 'ALL';++// Fincept shared color tokens (single source of truth)+export const FINCEPT_COLORS = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+} as const;++export const CHART_WIDTH = 1200;+export const CHART_HEIGHT = 400;diff --git a/fincept-terminal-desktop/src/components/common/charts/useExport.ts b/fincept-terminal-desktop/src/components/common/charts/useExport.tsnew file mode 100644index 000000000..462f25e59--- /dev/null+++ b/fincept-terminal-desktop/src/components/common/charts/useExport.ts@@ -0,0 +1,205 @@+// useExport — Generic export hook for CSV and PNG image.+// Works with any DataPoint[] dataset — no tab-specific dependencies.++import { useState, useCallback, RefObject } from 'react';+import { save } from '@tauri-apps/plugin-dialog';+import { writeFile } from '@tauri-apps/plugin-fs';+import { FINCEPT_COLORS, CHART_WIDTH, CHART_HEIGHT } from './types';+import type { DataPoint, SaveNotification } from './types';++interface ExportMeta {+ /** Title shown in image header and CSV comment, e.g. "Federal Funds Rate" */+ title: string;+ /** Subtitle shown in image header, e.g. "USA • Source: FRED" */+ subtitle?: string;+ /** Used in filename generation, e.g. "fred_GDP_USA" */+ filenameSuffix: string;+}++interface UseExportReturn {+ saveNotification: SaveNotification | null;+ setSaveNotification: (notification: SaveNotification | null) => void;+ exportCSV: () => void;+ exportImage: () => Promise<void>;+}++export function useExport(+ data: DataPoint[] | null,+ meta: ExportMeta,+ chartContainerRef: RefObject<HTMLDivElement | null>,+): UseExportReturn {+ const [saveNotification, setSaveNotification] = useState<SaveNotification | null>(null);++ const exportCSV = useCallback(() => {+ if (!data || data.length === 0) return;++ const csv = [+ `# ${meta.title}`,+ meta.subtitle ? `# ${meta.subtitle}` : null,+ '',+ 'Date,Value',+ ...data.map((d) => `${d.date},${d.value}`),+ ]+ .filter((line) => line !== null)+ .join('\n');++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `fincept_terminal_${meta.filenameSuffix}.csv`;+ a.click();+ URL.revokeObjectURL(url);+ }, [data, meta]);++ const exportImage = useCallback(async () => {+ if (!data || data.length === 0 || !chartContainerRef.current) return;++ try {+ const defaultFileName = `fincept_terminal_${meta.filenameSuffix}_4K.png`;+ const filePath = await save({+ defaultPath: defaultFileName,+ filters: [+ { name: 'PNG Image', extensions: ['png'] },+ { name: 'All Files', extensions: ['*'] },+ ],+ title: 'Save Chart Image (Ultra HD) - Fincept Terminal',+ });++ if (!filePath) return;++ const svgElement = chartContainerRef.current.querySelector('svg');+ if (!svgElement) return;++ const clonedSvg = svgElement.cloneNode(true) as SVGElement;+ const width = CHART_WIDTH;+ const height = CHART_HEIGHT;+ const headerHeight = 80;+ const footerHeight = 40;+ const totalHeight = height + headerHeight + footerHeight;++ // Create wrapper SVG+ const wrapperSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ wrapperSvg.setAttribute('width', String(width));+ wrapperSvg.setAttribute('height', String(totalHeight));+ wrapperSvg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');++ // Background+ const bg = document.createElementNS('http://www.w3.org/2000/svg', 'rect');+ bg.setAttribute('width', String(width));+ bg.setAttribute('height', String(totalHeight));+ bg.setAttribute('fill', FINCEPT_COLORS.DARK_BG);+ wrapperSvg.appendChild(bg);++ // Title+ const title = document.createElementNS('http://www.w3.org/2000/svg', 'text');+ title.setAttribute('x', '24');+ title.setAttribute('y', '35');+ title.setAttribute('fill', FINCEPT_COLORS.WHITE);+ title.setAttribute('font-family', 'IBM Plex Mono, monospace');+ title.setAttribute('font-size', '22');+ title.setAttribute('font-weight', '700');+ title.textContent = meta.title;+ wrapperSvg.appendChild(title);++ // Subtitle+ if (meta.subtitle) {+ const subtitle = document.createElementNS('http://www.w3.org/2000/svg', 'text');+ subtitle.setAttribute('x', '24');+ subtitle.setAttribute('y', '60');+ subtitle.setAttribute('fill', FINCEPT_COLORS.GRAY);+ subtitle.setAttribute('font-family', 'IBM Plex Mono, monospace');+ subtitle.setAttribute('font-size', '14');+ subtitle.textContent = meta.subtitle;+ wrapperSvg.appendChild(subtitle);+ }++ // Chart+ const chartGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');+ chartGroup.setAttribute('transform', `translate(0, ${headerHeight})`);+ chartGroup.innerHTML = clonedSvg.innerHTML;+ wrapperSvg.appendChild(chartGroup);++ // Footer+ const footer = document.createElementNS('http://www.w3.org/2000/svg', 'text');+ footer.setAttribute('x', String(width - 24));+ footer.setAttribute('y', String(totalHeight - 12));+ footer.setAttribute('fill', FINCEPT_COLORS.MUTED);+ footer.setAttribute('font-family', 'IBM Plex Mono, monospace');+ footer.setAttribute('font-size', '12');+ footer.setAttribute('text-anchor', 'end');+ footer.textContent = `Fincept Terminal \u2022 ${new Date().toISOString().split('T')[0]}`;+ wrapperSvg.appendChild(footer);++ // Watermark+ const watermark = document.createElementNS('http://www.w3.org/2000/svg', 'text');+ watermark.setAttribute('x', String(width - 50));+ watermark.setAttribute('y', String(headerHeight + 50));+ watermark.setAttribute('fill', `${FINCEPT_COLORS.WHITE}50`);+ watermark.setAttribute('font-family', 'IBM Plex Mono, monospace');+ watermark.setAttribute('font-size', '22');+ watermark.setAttribute('font-weight', '700');+ watermark.setAttribute('text-anchor', 'end');+ watermark.textContent = 'FINCEPT TERMINAL';+ wrapperSvg.appendChild(watermark);++ // Convert to canvas+ const svgData = new XMLSerializer().serializeToString(wrapperSvg);+ const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });+ const svgUrl = URL.createObjectURL(svgBlob);++ const canvas = document.createElement('canvas');+ const ctx = canvas.getContext('2d');+ const img = new window.Image();++ img.onload = async () => {+ const scale = 4; // Ultra HD+ canvas.width = width * scale;+ canvas.height = totalHeight * scale;++ if (ctx) {+ ctx.imageSmoothingEnabled = true;+ ctx.imageSmoothingQuality = 'high';+ ctx.scale(scale, scale);+ ctx.fillStyle = FINCEPT_COLORS.DARK_BG;+ ctx.fillRect(0, 0, width, totalHeight);+ ctx.drawImage(img, 0, 0);++ canvas.toBlob(async (blob) => {+ if (blob) {+ try {+ const arrayBuffer = await blob.arrayBuffer();+ const uint8Array = new Uint8Array(arrayBuffer);+ await writeFile(filePath, uint8Array);+ setSaveNotification({ show: true, path: filePath, type: 'image' });+ setTimeout(() => setSaveNotification(null), 5000);+ } catch (writeErr) {+ console.error('Failed to write image file:', writeErr);+ }+ }+ }, 'image/png');+ }++ URL.revokeObjectURL(svgUrl);+ };++ img.onerror = () => {+ console.error('Failed to load SVG for image export');+ URL.revokeObjectURL(svgUrl);+ };++ img.src = svgUrl;+ } catch (err) {+ console.error('Failed to export image:', err);+ }+ }, [data, meta, chartContainerRef]);++ return {+ saveNotification,+ setSaveNotification,+ exportCSV,+ exportImage,+ };+}++export default useExport;diff --git a/fincept-terminal-desktop/src/components/common/charts/utils.ts b/fincept-terminal-desktop/src/components/common/charts/utils.tsnew file mode 100644index 000000000..58cb30bfb--- /dev/null+++ b/fincept-terminal-desktop/src/components/common/charts/utils.ts@@ -0,0 +1,83 @@+// Shared chart/data utility functions — used across all tabs++import type { DataPoint, ChartStats, DateRangePreset } from './types';++/**+ * Compute start/end dates from a preset like '1M', '5Y', 'ALL', etc.+ */+export const getDateFromPreset = (preset: DateRangePreset): { start: string; end: string } => {+ const now = new Date();+ const end = now.toISOString().split('T')[0];+ let start: Date;++ switch (preset) {+ case '1M':+ start = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());+ break;+ case '3M':+ start = new Date(now.getFullYear(), now.getMonth() - 3, now.getDate());+ break;+ case '6M':+ start = new Date(now.getFullYear(), now.getMonth() - 6, now.getDate());+ break;+ case '1Y':+ start = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());+ break;+ case '2Y':+ start = new Date(now.getFullYear() - 2, now.getMonth(), now.getDate());+ break;+ case '5Y':+ start = new Date(now.getFullYear() - 5, now.getMonth(), now.getDate());+ break;+ case '10Y':+ start = new Date(now.getFullYear() - 10, now.getMonth(), now.getDate());+ break;+ case 'ALL':+ default:+ start = new Date(1960, 0, 1);+ break;+ }++ return { start: start.toISOString().split('T')[0], end };+};++/**+ * Client-side date range filter for DataPoint arrays.+ * Handles year-only ("2020"), month-only ("2020-01"), and full dates ("2020-01-15").+ */+export const filterByDateRange = (+ data: DataPoint[],+ startDate: string,+ endDate: string,+): DataPoint[] => {+ if (!startDate && !endDate) return data;+ return data.filter((d) => {+ const dateStr = d.date;+ const normalized =+ dateStr.length === 4+ ? `${dateStr}-01-01`+ : dateStr.length === 7+ ? `${dateStr}-01`+ : dateStr;+ return (!startDate || normalized >= startDate) && (!endDate || normalized <= endDate);+ });+};++/**+ * Compute summary statistics (latest, change, min, max, avg, count) for a DataPoint[].+ */+export const computeStats = (data: DataPoint[]): ChartStats | null => {+ if (!data || data.length === 0) return null;+ const values = data.map((d) => d.value);+ const latest = values[values.length - 1];+ const previous = values.length > 1 ? values[values.length - 2] : latest;+ const change = previous !== 0 ? ((latest - previous) / Math.abs(previous)) * 100 : 0;+ return {+ latest,+ change,+ min: Math.min(...values),+ max: Math.max(...values),+ avg: values.reduce((a, b) => a + b, 0) / values.length,+ count: values.length,+ };+};diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex 654b320f9..92a1ee6c8 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -53,6 +53,7 @@ const EquityTradingTab = React.lazy(() => import('@/components/tabs/equity-tradiconst DBnomicsTab = React.lazy(() => import('@/components/tabs/dbnomics'));const AkShareDataTab = React.lazy(() => import('@/components/tabs/akshare-data'));const EconomicsTab = React.lazy(() => import('@/components/tabs/economics'));+const GovDataTab = React.lazy(() => import('@/components/tabs/gov-data'));const MaritimeTab = React.lazy(() => import('@/components/tabs/maritime'));const ReportBuilderTab = React.lazy(() => import('@/components/tabs/report-builder'));const DataMappingTab = React.lazy(() => import('@/components/tabs/data-mapping'));@@ -559,6 +560,7 @@ function FinxeptTerminalContent() {{ label: 'Markets & Data', header: true },{ label: 'Stock Screener', action: () => setActiveTab('screener') },{ label: 'Economics', action: () => setActiveTab('economics') },+ { label: 'GOVT', action: () => setActiveTab('gov-data') },{ label: 'DBnomics', action: () => setActiveTab('dbnomics') },{ label: 'AKShare Data', action: () => setActiveTab('akshare') },{ label: 'Asia Markets', action: () => setActiveTab('asia-markets') },@@ -1068,6 +1070,11 @@ function FinxeptTerminalContent() {<EconomicsTab /></React.Suspense></TabsContent>+ <TabsContent value="gov-data" className="h-full m-0 p-0">+ <React.Suspense fallback={<TabLoadingFallback />}>+ <GovDataTab />+ </React.Suspense>+ </TabsContent><TabsContent value="code" className="h-full m-0 p-0"><React.Suspense fallback={<TabLoadingFallback />}><CodeEditorTab />diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/AlgoTradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/AlgoTradingTab.tsxindex cdec63a62..9043a08f8 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/AlgoTradingTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/AlgoTradingTab.tsx@@ -1,5 +1,8 @@import React, { useState } from 'react';-import { Bot, Wrench, Search, BarChart3, Layout, Activity, Library } from 'lucide-react';+import {+ Bot, Wrench, Search, BarChart3, Layout, Activity, Library,+ Plus, Zap, ChevronRight,+} from 'lucide-react';import type { AlgoSubView, PythonStrategy } from './types';import StrategyEditor from './components/StrategyEditor';import StrategyManager from './components/StrategyManager';@@ -28,12 +31,12 @@ const F = {PURPLE: '#9D4EDD',};-const SUB_VIEWS: { key: AlgoSubView; label: string; icon: React.ElementType }[] = [- { key: 'builder', label: 'BUILDER', icon: Wrench },- { key: 'strategies', label: 'STRATEGIES', icon: Layout },- { key: 'library', label: 'LIBRARY', icon: Library },- { key: 'scanner', label: 'SCANNER', icon: Search },- { key: 'dashboard', label: 'DASHBOARD', icon: BarChart3 },+const NAV_ITEMS: { key: AlgoSubView; label: string; icon: React.ElementType; description: string }[] = [+ { key: 'builder', label: 'STRATEGY BUILDER', icon: Wrench, description: 'Create & edit strategies' },+ { key: 'strategies', label: 'MY STRATEGIES', icon: Layout, description: 'Saved strategies & custom' },+ { key: 'library', label: 'STRATEGY LIBRARY', icon: Library, description: 'Pre-built Python strategies' },+ { key: 'scanner', label: 'MARKET SCANNER', icon: Search, description: 'Scan across symbols' },+ { key: 'dashboard', label: 'LIVE DASHBOARD', icon: BarChart3, description: 'Monitor deployments' },];const AlgoTradingTab: React.FC = () => {@@ -53,7 +56,6 @@ const AlgoTradingTab: React.FC = () => {setActiveView('builder');};- // Handle Python strategy actions from libraryconst handlePythonClone = (strategy: PythonStrategy) => {setClonePythonStrategy(strategy);};@@ -66,7 +68,6 @@ const AlgoTradingTab: React.FC = () => {setDeployPythonStrategy(strategy);};- // Handle Python strategy editor close/saveconst handlePythonEditorClose = () => {setClonePythonStrategy(null);};@@ -74,126 +75,246 @@ const AlgoTradingTab: React.FC = () => {const handlePythonEditorSave = (customId: string) => {console.log('Python strategy saved with ID:', customId);setClonePythonStrategy(null);- // Navigate to strategies tab to show the saved custom strategysetActiveView('strategies');};return (<div style={{display: 'flex',- flexDirection: 'column',height: '100%',backgroundColor: F.DARK_BG,fontFamily: '"IBM Plex Mono", "Consolas", monospace',color: F.WHITE,}}>- {/* Top Nav Bar */}+ {/* ─── LEFT SIDEBAR NAVIGATION ─── */}<div style={{- backgroundColor: F.HEADER_BG,- borderBottom: `2px solid ${F.ORANGE}`,- padding: '8px 16px',+ width: '220px',+ backgroundColor: F.PANEL_BG,+ borderRight: `1px solid ${F.BORDER}`,display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- boxShadow: `0 2px 8px ${F.ORANGE}20`,+ flexDirection: 'column',+ flexShrink: 0,}}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <Bot size={16} style={{ color: F.ORANGE }} />- <span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>- ALGO TRADING- </span>- <Activity size={10} style={{ color: F.GREEN, marginLeft: '4px' }} />+ {/* Logo / Header */}+ <div style={{+ padding: '16px',+ borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ }}>+ <div style={{+ width: '32px',+ height: '32px',+ borderRadius: '2px',+ backgroundColor: `${F.ORANGE}20`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ }}>+ <Bot size={18} style={{ color: F.ORANGE }} />+ </div>+ <div>+ <div style={{ fontSize: '11px', fontWeight: 700, letterSpacing: '1px' }}>+ ALGO TRADING+ </div>+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>+ STRATEGY ENGINE v1.0+ </div>+ </div></div>- <div style={{ display: 'flex', gap: '2px' }}>- {SUB_VIEWS.map(({ key, label, icon: Icon }) => (- <button- key={key}- onClick={() => setActiveView(key)}- style={{- padding: '6px 12px',- backgroundColor: activeView === key ? F.ORANGE : 'transparent',- color: activeView === key ? F.DARK_BG : F.GRAY,- border: 'none',- fontSize: '9px',- fontWeight: 700,- letterSpacing: '0.5px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px',- borderRadius: '2px',- transition: 'all 0.2s',- }}- onMouseEnter={e => {- if (activeView !== key) {- (e.target as HTMLElement).style.color = F.WHITE;- (e.target as HTMLElement).style.backgroundColor = F.HOVER;- }- }}- onMouseLeave={e => {- if (activeView !== key) {- (e.target as HTMLElement).style.color = F.GRAY;- (e.target as HTMLElement).style.backgroundColor = 'transparent';- }- }}- >- <Icon size={10} />- {label}- </button>- ))}+ {/* Quick Action */}+ <div style={{ padding: '12px' }}>+ <button+ onClick={handleNewStrategy}+ style={{+ width: '100%',+ padding: '10px 12px',+ backgroundColor: F.ORANGE,+ color: F.DARK_BG,+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ transition: 'all 0.2s',+ }}+ onMouseEnter={e => { e.currentTarget.style.opacity = '0.9'; }}+ onMouseLeave={e => { e.currentTarget.style.opacity = '1'; }}+ >+ <Plus size={12} />+ NEW STRATEGY+ </button></div>- </div>- {/* Content */}- <div style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>- {activeView === 'builder' && (- <StrategyEditor- editStrategyId={editStrategyId}- onSaved={() => setActiveView('strategies')}- onCancel={() => {- setEditStrategyId(null);- setActiveView('strategies');- }}- />- )}- {activeView === 'strategies' && (- <StrategyManager- onEdit={handleEditStrategy}- onNew={handleNewStrategy}- onBacktestPython={handlePythonBacktest}- onDeployPython={handlePythonDeploy}- />- )}- {activeView === 'library' && (- <StrategyLibraryTab- onClone={handlePythonClone}- onBacktest={handlePythonBacktest}- onDeploy={handlePythonDeploy}- />- )}- {activeView === 'scanner' && <ScannerPanel />}- {activeView === 'dashboard' && <MonitorDashboard />}+ {/* Navigation Items */}+ <div style={{ flex: 1, overflowY: 'auto', padding: '4px 8px' }}>+ {NAV_ITEMS.map(({ key, label, icon: Icon, description }) => {+ const isActive = activeView === key;+ return (+ <button+ key={key}+ onClick={() => setActiveView(key)}+ style={{+ width: '100%',+ padding: '10px 12px',+ backgroundColor: isActive ? `${F.ORANGE}15` : 'transparent',+ borderLeft: isActive ? `2px solid ${F.ORANGE}` : '2px solid transparent',+ border: 'none',+ borderRadius: '2px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ marginBottom: '2px',+ transition: 'all 0.2s',+ textAlign: 'left',+ }}+ onMouseEnter={e => {+ if (!isActive) e.currentTarget.style.backgroundColor = F.HOVER;+ }}+ onMouseLeave={e => {+ if (!isActive) e.currentTarget.style.backgroundColor = 'transparent';+ }}+ >+ <Icon size={14} style={{ color: isActive ? F.ORANGE : F.MUTED, flexShrink: 0 }} />+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{+ fontSize: '9px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ color: isActive ? F.WHITE : F.GRAY,+ }}>+ {label}+ </div>+ <div style={{+ fontSize: '8px',+ color: F.MUTED,+ marginTop: '2px',+ }}>+ {description}+ </div>+ </div>+ {isActive && <ChevronRight size={10} style={{ color: F.ORANGE }} />}+ </button>+ );+ })}+ </div>++ {/* Sidebar Footer - Status */}+ <div style={{+ padding: '12px 16px',+ borderTop: `1px solid ${F.BORDER}`,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '8px' }}>+ <Zap size={10} style={{ color: F.YELLOW }} />+ <span style={{ fontSize: '8px', color: F.GRAY, letterSpacing: '0.5px' }}>SYSTEM STATUS</span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: F.GREEN, display: 'inline-block' }} />+ <span style={{ fontSize: '8px', color: F.GREEN }}>ONLINE</span>+ </div>+ <span style={{ fontSize: '8px', color: F.MUTED }}>|</span>+ <span style={{ fontSize: '8px', color: F.MUTED }}>ENGINE READY</span>+ </div>+ </div></div>- {/* Status Bar */}+ {/* ─── MAIN CONTENT AREA ─── */}<div style={{- backgroundColor: F.HEADER_BG,- borderTop: `1px solid ${F.BORDER}`,- padding: '4px 16px',- fontSize: '9px',- color: F.GRAY,+ flex: 1,display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',+ flexDirection: 'column',+ overflow: 'hidden',+ minWidth: 0,}}>- <span>ALGO ENGINE v1.0</span>- <span style={{ color: F.MUTED }}>- VIEW: {activeView.toUpperCase()}- </span>+ {/* Top Breadcrumb Bar */}+ <div style={{+ padding: '8px 20px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `2px solid ${F.ORANGE}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ boxShadow: `0 2px 8px ${F.ORANGE}20`,+ flexShrink: 0,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ fontSize: '9px', color: F.MUTED }}>ALGO TRADING</span>+ <ChevronRight size={10} style={{ color: F.MUTED }} />+ <span style={{ fontSize: '10px', fontWeight: 700, color: F.ORANGE, letterSpacing: '0.5px' }}>+ {NAV_ITEMS.find(n => n.key === activeView)?.label}+ </span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <Activity size={10} style={{ color: F.GREEN }} />+ <span style={{ fontSize: '8px', color: F.GREEN }}>LIVE</span>+ </div>+ </div>++ {/* View Content */}+ <div style={{ flex: 1, overflow: 'hidden', minHeight: 0 }}>+ {activeView === 'builder' && (+ <StrategyEditor+ editStrategyId={editStrategyId}+ onSaved={() => setActiveView('strategies')}+ onCancel={() => {+ setEditStrategyId(null);+ setActiveView('strategies');+ }}+ />+ )}+ {activeView === 'strategies' && (+ <StrategyManager+ onEdit={handleEditStrategy}+ onNew={handleNewStrategy}+ onBacktestPython={handlePythonBacktest}+ onDeployPython={handlePythonDeploy}+ onDeployedJson={() => setActiveView('dashboard')}+ />+ )}+ {activeView === 'library' && (+ <StrategyLibraryTab+ onClone={handlePythonClone}+ onBacktest={handlePythonBacktest}+ onDeploy={handlePythonDeploy}+ />+ )}+ {activeView === 'scanner' && <ScannerPanel />}+ {activeView === 'dashboard' && <MonitorDashboard />}+ </div>++ {/* Bottom Status Bar */}+ <div style={{+ backgroundColor: F.HEADER_BG,+ borderTop: `1px solid ${F.BORDER}`,+ padding: '4px 20px',+ fontSize: '9px',+ color: F.GRAY,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ flexShrink: 0,+ }}>+ <div style={{ display: 'flex', gap: '16px' }}>+ <span><span style={{ color: F.MUTED }}>ENGINE:</span> v1.0</span>+ <span><span style={{ color: F.MUTED }}>MODE:</span> <span style={{ color: F.CYAN }}>PRODUCTION</span></span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <span style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: F.GREEN }} />+ <span style={{ color: F.GREEN }}>READY</span>+ </div>+ </div></div>- {/* Python Backtest Modal */}+ {/* ─── MODALS ─── */}{backtestPythonStrategy && (<PythonBacktestPanelstrategy={backtestPythonStrategy}@@ -201,7 +322,6 @@ const AlgoTradingTab: React.FC = () => {/>)}- {/* Python Strategy Editor (Clone from Library) */}{clonePythonStrategy && (<PythonStrategyEditorstrategy={clonePythonStrategy}@@ -212,7 +332,6 @@ const AlgoTradingTab: React.FC = () => {/>)}- {/* Python Deploy Panel */}{deployPythonStrategy && (<PythonDeployPanelstrategy={deployPythonStrategy}diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionBuilder.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionBuilder.tsxindex 71979a194..fce214ec2 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionBuilder.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionBuilder.tsx@@ -1,5 +1,5 @@import React, { useState } from 'react';-import { Plus, ChevronDown, ChevronRight } from 'lucide-react';+import { Plus, ChevronDown, ChevronRight, Zap, Layers, Sparkles } from 'lucide-react';import type { ConditionItem } from '../types';import { getIndicatorDef } from '../constants/indicators';import ConditionRow from './ConditionRow';@@ -8,6 +8,7 @@ const F = {ORANGE: '#FF8800', WHITE: '#FFFFFF', GRAY: '#787878', DARK_BG: '#000000',PANEL_BG: '#0F0F0F', HEADER_BG: '#1A1A1A', BORDER: '#2A2A2A',HOVER: '#1F1F1F', CYAN: '#00E5FF', BLUE: '#0088FF', MUTED: '#4A4A4A',+ GREEN: '#00D66F', RED: '#FF3B3B', YELLOW: '#FFD700', PURPLE: '#9D4EDD',};interface ConditionBuilderProps {@@ -29,22 +30,23 @@ const DEFAULT_CONDITION: ConditionItem = {// Quick-add condition templates for the dropdowninterface QuickCondition {label: string;+ category: string;condition: ConditionItem;}const QUICK_CONDITIONS: QuickCondition[] = [- { label: 'RSI < 30 (Oversold)', condition: { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '<', value: 30 } },- { label: 'RSI > 70 (Overbought)', condition: { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '>', value: 70 } },- { label: 'MACD Histogram > 0', condition: { indicator: 'MACD', params: { fast: 12, slow: 26, signal: 9 }, field: 'histogram', operator: '>', value: 0 } },- { label: 'Close > EMA(20)', condition: { indicator: 'CLOSE', params: {}, field: 'value', operator: '>', value: 0, compareMode: 'indicator', compareIndicator: 'EMA', compareParams: { period: 20 }, compareField: 'value' } },- { label: 'Close X↑ SMA(200)', condition: { indicator: 'CLOSE', params: {}, field: 'value', operator: 'crosses_above', value: 0, compareMode: 'indicator', compareIndicator: 'SMA', compareParams: { period: 200 }, compareField: 'value' } },- { label: 'Supertrend Bullish', condition: { indicator: 'SUPERTREND', params: { period: 10, multiplier: 3 }, field: 'direction', operator: '==', value: 1 } },- { label: 'Bollinger %B < 0 (Oversold)', condition: { indicator: 'BOLLINGER', params: { period: 20, std_dev: 2 }, field: 'pct_b', operator: '<', value: 0 } },- { label: 'ADX > 25 (Strong Trend)', condition: { indicator: 'ADX', params: { period: 14 }, field: 'value', operator: '>', value: 25 } },- { label: 'MFI > 80 (OB)', condition: { indicator: 'MFI', params: { period: 14 }, field: 'value', operator: '>', value: 80 } },- { label: 'Stoch RSI K X↑ D', condition: { indicator: 'STOCH_RSI', params: { period: 14, smooth1: 3, smooth2: 3 }, field: 'k', operator: 'crosses_above', value: 0, compareMode: 'indicator', compareIndicator: 'STOCH_RSI', compareParams: { period: 14, smooth1: 3, smooth2: 3 }, compareField: 'd' } },- { label: 'Price Rising 3 Bars', condition: { indicator: 'CLOSE', params: {}, field: 'value', operator: 'rising', value: 0, lookback: 3 } },- { label: 'Custom (blank)', condition: { ...DEFAULT_CONDITION } },+ { label: 'RSI < 30 (Oversold)', category: 'Momentum', condition: { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '<', value: 30 } },+ { label: 'RSI > 70 (Overbought)', category: 'Momentum', condition: { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '>', value: 70 } },+ { label: 'MACD Histogram > 0', category: 'Momentum', condition: { indicator: 'MACD', params: { fast: 12, slow: 26, signal: 9 }, field: 'histogram', operator: '>', value: 0 } },+ { label: 'Close > EMA(20)', category: 'Trend', condition: { indicator: 'CLOSE', params: {}, field: 'value', operator: '>', value: 0, compareMode: 'indicator', compareIndicator: 'EMA', compareParams: { period: 20 }, compareField: 'value' } },+ { label: 'Close X above SMA(200)', category: 'Trend', condition: { indicator: 'CLOSE', params: {}, field: 'value', operator: 'crosses_above', value: 0, compareMode: 'indicator', compareIndicator: 'SMA', compareParams: { period: 200 }, compareField: 'value' } },+ { label: 'Supertrend Bullish', category: 'Trend', condition: { indicator: 'SUPERTREND', params: { period: 10, multiplier: 3 }, field: 'direction', operator: '==', value: 1 } },+ { label: 'Bollinger %B < 0 (Oversold)', category: 'Volatility', condition: { indicator: 'BOLLINGER', params: { period: 20, std_dev: 2 }, field: 'pct_b', operator: '<', value: 0 } },+ { label: 'ADX > 25 (Strong Trend)', category: 'Trend', condition: { indicator: 'ADX', params: { period: 14 }, field: 'value', operator: '>', value: 25 } },+ { label: 'MFI > 80 (Overbought)', category: 'Volume', condition: { indicator: 'MFI', params: { period: 14 }, field: 'value', operator: '>', value: 80 } },+ { label: 'Stoch RSI K X above D', category: 'Momentum', condition: { indicator: 'STOCH_RSI', params: { period: 14, smooth1: 3, smooth2: 3 }, field: 'k', operator: 'crosses_above', value: 0, compareMode: 'indicator', compareIndicator: 'STOCH_RSI', compareParams: { period: 14, smooth1: 3, smooth2: 3 }, compareField: 'd' } },+ { label: 'Price Rising 3 Bars', category: 'Trend', condition: { indicator: 'CLOSE', params: {}, field: 'value', operator: 'rising', value: 0, lookback: 3 } },+ { label: 'Custom (blank)', category: 'Custom', condition: { ...DEFAULT_CONDITION } },];const ConditionBuilder: React.FC<ConditionBuilderProps> = ({@@ -55,6 +57,7 @@ const ConditionBuilder: React.FC<ConditionBuilderProps> = ({onLogicChange,}) => {const [showQuickAdd, setShowQuickAdd] = useState(false);+ const [dragIndex, setDragIndex] = useState<number | null>(null);const handleAdd = (condition?: ConditionItem) => {// Deep clone to avoid mutating template constants (params/compareParams are nested objects)@@ -73,192 +76,398 @@ const ConditionBuilder: React.FC<ConditionBuilderProps> = ({onConditionsChange(conditions.filter((_, i) => i !== index));};- // Build inline summary for header- const condCount = conditions.length;- const indicatorNames = conditions.map(c => {- const def = getIndicatorDef(c.indicator);- return def?.label || c.indicator;- });+ const handleDuplicate = (index: number) => {+ const clone = JSON.parse(JSON.stringify(conditions[index]));+ const next = [...conditions];+ next.splice(index + 1, 0, clone);+ onConditionsChange(next);+ };++ const handleMoveUp = (index: number) => {+ if (index === 0) return;+ const next = [...conditions];+ [next[index - 1], next[index]] = [next[index], next[index - 1]];+ onConditionsChange(next);+ };++ const handleMoveDown = (index: number) => {+ if (index >= conditions.length - 1) return;+ const next = [...conditions];+ [next[index], next[index + 1]] = [next[index + 1], next[index]];+ onConditionsChange(next);+ };++ // Group quick conditions by category+ const groupedQuickConditions = QUICK_CONDITIONS.reduce((acc, qc) => {+ if (!acc[qc.category]) acc[qc.category] = [];+ acc[qc.category].push(qc);+ return acc;+ }, {} as Record<string, QuickCondition[]>);return (- <div style={{- backgroundColor: F.PANEL_BG,- border: `1px solid ${F.BORDER}`,- borderRadius: '2px',- }}>- {/* Section Header */}- <div style={{- padding: '8px 12px',- backgroundColor: F.HEADER_BG,- borderBottom: `1px solid ${F.BORDER}`,- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>- {label.toUpperCase()}- </span>- {condCount > 0 && (- <span style={{ fontSize: '8px', color: F.MUTED }}>- ({condCount} condition{condCount !== 1 ? 's' : ''}: {indicatorNames.join(` ${logic} `)})+ <div style={{ position: 'relative' }}>+ {/* Logic toggle + label bar */}+ {label && (+ <div style={{+ padding: '8px 12px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Layers size={10} color={F.MUTED} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>+ {label.toUpperCase()}</span>- )}+ </div></div>- <div style={{ display: 'flex', gap: '2px' }}>+ )}++ {/* Logic selector - shown when >1 conditions */}+ {conditions.length > 1 && (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '4px 12px 8px',+ }}>+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px' }}>+ MATCH:+ </span>{(['AND', 'OR'] as const).map(l => (<buttonkey={l}onClick={() => onLogicChange(l)}style={{- padding: '3px 8px',- backgroundColor: logic === l ? F.ORANGE : 'transparent',- color: logic === l ? F.DARK_BG : F.GRAY,+ padding: '4px 12px',+ backgroundColor: logic === l ? (l === 'AND' ? F.ORANGE : F.BLUE) : 'transparent',+ color: logic === l ? (l === 'AND' ? F.DARK_BG : F.WHITE) : F.GRAY,border: logic === l ? 'none' : `1px solid ${F.BORDER}`,- fontSize: '8px',+ fontSize: '9px',fontWeight: 700,letterSpacing: '0.5px',cursor: 'pointer',borderRadius: '2px',transition: 'all 0.2s',}}+ onMouseEnter={e => {+ if (logic !== l) {+ e.currentTarget.style.borderColor = F.ORANGE;+ e.currentTarget.style.color = F.WHITE;+ }+ }}+ onMouseLeave={e => {+ if (logic !== l) {+ e.currentTarget.style.borderColor = F.BORDER;+ e.currentTarget.style.color = F.GRAY;+ }+ }}>- {l}+ {l === 'AND' ? 'ALL CONDITIONS (AND)' : 'ANY CONDITION (OR)'}</button>))}</div>- </div>+ )}- {/* Condition rows */}- <div style={{ padding: '4px 0' }}>+ {/* Condition Cards */}+ <div style={{ padding: '0 8px' }}>{conditions.length === 0 && (<div style={{- padding: '12px 16px', textAlign: 'center', color: F.MUTED, fontSize: '9px',+ padding: '32px 16px',+ textAlign: 'center',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '8px',}}>- No conditions added. Click "ADD CONDITION" below.+ <Zap size={20} color={F.MUTED} style={{ opacity: 0.5 }} />+ <div style={{ fontSize: '10px', color: F.MUTED, fontWeight: 700 }}>+ NO CONDITIONS DEFINED+ </div>+ <div style={{ fontSize: '9px', color: F.MUTED, maxWidth: '300px', lineHeight: '1.5' }}>+ Add technical indicator conditions to define when trades should be triggered.+ Use the buttons below to add or select from templates.+ </div></div>)}+{conditions.map((cond, i) => (<div key={i}>+ {/* Logic connector between cards */}{i > 0 && (<div style={{- fontSize: '8px',- fontWeight: 700,- color: F.ORANGE,- paddingLeft: '12px',- paddingTop: '2px',- paddingBottom: '2px',- letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: '4px 0',+ position: 'relative',}}>- {logic}+ <div style={{+ position: 'absolute', left: '50%', top: 0, bottom: 0,+ width: '1px', backgroundColor: F.BORDER,+ }} />+ <div style={{+ padding: '2px 10px',+ backgroundColor: logic === 'AND' ? F.ORANGE : F.BLUE,+ color: logic === 'AND' ? F.DARK_BG : F.WHITE,+ fontSize: '8px',+ fontWeight: 700,+ letterSpacing: '1px',+ borderRadius: '2px',+ position: 'relative',+ zIndex: 1,+ }}>+ {logic}+ </div></div>)}- <ConditionRow- condition={cond}- index={i}- onChange={handleChange}- onRemove={handleRemove}- />++ {/* Condition Card */}+ <div style={{+ backgroundColor: F.DARK_BG,+ border: `1px solid ${dragIndex === i ? F.ORANGE : F.BORDER}`,+ borderRadius: '2px',+ overflow: 'hidden',+ transition: 'border-color 0.2s',+ }}>+ {/* Card header with number and indicator name */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: '6px 10px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{+ width: '18px', height: '18px', borderRadius: '2px',+ backgroundColor: `${F.ORANGE}20`, color: F.ORANGE,+ fontSize: '9px', fontWeight: 700,+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ }}>+ {i + 1}+ </span>+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>+ {getIndicatorDef(cond.indicator)?.label || cond.indicator}+ </span>+ <span style={{ fontSize: '8px', color: F.MUTED }}>+ {Object.values(cond.params).length > 0 && `(${Object.values(cond.params).join(', ')})`}+ </span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>+ {/* Move up/down */}+ {conditions.length > 1 && (+ <>+ <button+ onClick={() => handleMoveUp(i)}+ disabled={i === 0}+ style={{+ padding: '2px 4px', backgroundColor: 'transparent', border: 'none',+ color: i === 0 ? F.MUTED + '40' : F.MUTED, cursor: i === 0 ? 'default' : 'pointer',+ fontSize: '10px', lineHeight: 1,+ }}+ onMouseEnter={e => { if (i > 0) e.currentTarget.style.color = F.WHITE; }}+ onMouseLeave={e => { if (i > 0) e.currentTarget.style.color = F.MUTED; }}+ title="Move up"+ >+ ▲+ </button>+ <button+ onClick={() => handleMoveDown(i)}+ disabled={i >= conditions.length - 1}+ style={{+ padding: '2px 4px', backgroundColor: 'transparent', border: 'none',+ color: i >= conditions.length - 1 ? F.MUTED + '40' : F.MUTED,+ cursor: i >= conditions.length - 1 ? 'default' : 'pointer',+ fontSize: '10px', lineHeight: 1,+ }}+ onMouseEnter={e => { if (i < conditions.length - 1) e.currentTarget.style.color = F.WHITE; }}+ onMouseLeave={e => { if (i < conditions.length - 1) e.currentTarget.style.color = F.MUTED; }}+ title="Move down"+ >+ ▼+ </button>+ </>+ )}+ {/* Duplicate */}+ <button+ onClick={() => handleDuplicate(i)}+ style={{+ padding: '2px 6px', backgroundColor: 'transparent', border: 'none',+ color: F.MUTED, cursor: 'pointer', fontSize: '9px', fontWeight: 700,+ }}+ onMouseEnter={e => { e.currentTarget.style.color = F.CYAN; }}+ onMouseLeave={e => { e.currentTarget.style.color = F.MUTED; }}+ title="Duplicate condition"+ >+ DUP+ </button>+ {/* Remove */}+ <button+ onClick={() => handleRemove(i)}+ style={{+ padding: '2px 6px', backgroundColor: 'transparent', border: 'none',+ color: F.MUTED, cursor: 'pointer', fontSize: '10px', fontWeight: 700,+ }}+ onMouseEnter={e => { e.currentTarget.style.color = F.RED; }}+ onMouseLeave={e => { e.currentTarget.style.color = F.MUTED; }}+ title="Remove condition"+ >+ ✕+ </button>+ </div>+ </div>++ {/* Card body with controls */}+ <ConditionRow+ condition={cond}+ index={i}+ onChange={handleChange}+ onRemove={handleRemove}+ />+ </div></div>))}</div>- {/* Add button + Quick add dropdown */}- <div style={{ padding: '4px 8px 8px', position: 'relative' }}>- <div style={{ display: 'flex', gap: '4px' }}>- <button- onClick={() => handleAdd()}- style={{- padding: '6px 10px',- backgroundColor: 'transparent',- border: `1px solid ${F.BORDER}`,- color: F.GRAY,- fontSize: '9px',- fontWeight: 700,- borderRadius: '2px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px',- transition: 'all 0.2s',- }}- onMouseEnter={e => {- (e.currentTarget as HTMLElement).style.borderColor = F.ORANGE;- (e.currentTarget as HTMLElement).style.color = F.WHITE;- }}- onMouseLeave={e => {- (e.currentTarget as HTMLElement).style.borderColor = F.BORDER;- (e.currentTarget as HTMLElement).style.color = F.GRAY;- }}- >- <Plus size={10} />- ADD CONDITION- </button>- <button- onClick={() => setShowQuickAdd(!showQuickAdd)}- style={{- padding: '6px 8px',- backgroundColor: 'transparent',- border: `1px solid ${F.BORDER}`,- color: showQuickAdd ? F.CYAN : F.GRAY,- fontSize: '9px',- fontWeight: 700,- borderRadius: '2px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '3px',- transition: 'all 0.2s',- borderColor: showQuickAdd ? F.CYAN : F.BORDER,- }}- >- {showQuickAdd ? <ChevronDown size={10} /> : <ChevronRight size={10} />}- TEMPLATES- </button>- </div>+ {/* ─── ADD BUTTONS ─── */}+ <div style={{+ padding: '10px 12px',+ display: 'flex',+ gap: '6px',+ alignItems: 'center',+ }}>+ <button+ onClick={() => handleAdd()}+ style={{+ padding: '8px 14px',+ backgroundColor: 'transparent',+ border: `1px dashed ${F.BORDER}`,+ color: F.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ transition: 'all 0.2s',+ letterSpacing: '0.5px',+ }}+ onMouseEnter={e => {+ e.currentTarget.style.borderColor = F.ORANGE;+ e.currentTarget.style.color = F.ORANGE;+ e.currentTarget.style.backgroundColor = `${F.ORANGE}10`;+ }}+ onMouseLeave={e => {+ e.currentTarget.style.borderColor = F.BORDER;+ e.currentTarget.style.color = F.GRAY;+ e.currentTarget.style.backgroundColor = 'transparent';+ }}+ >+ <Plus size={11} />+ ADD CONDITION+ </button>- {/* Quick-add dropdown */}- {showQuickAdd && (- <div style={{- marginTop: '4px',- backgroundColor: F.DARK_BG,- border: `1px solid ${F.BORDER}`,+ <button+ onClick={() => setShowQuickAdd(!showQuickAdd)}+ style={{+ padding: '8px 14px',+ backgroundColor: showQuickAdd ? `${F.CYAN}15` : 'transparent',+ border: `1px solid ${showQuickAdd ? F.CYAN + '60' : F.BORDER}`,+ color: showQuickAdd ? F.CYAN : F.GRAY,+ fontSize: '9px',+ fontWeight: 700,borderRadius: '2px',- maxHeight: '200px',- overflow: 'auto',- }}>- {QUICK_CONDITIONS.map((qc, i) => (- <button- key={i}- onClick={() => handleAdd(qc.condition)}- style={{- width: '100%',- padding: '6px 10px',- backgroundColor: 'transparent',- border: 'none',- borderBottom: i < QUICK_CONDITIONS.length - 1 ? `1px solid ${F.BORDER}` : 'none',- color: F.GRAY,- fontSize: '9px',- fontFamily: '"IBM Plex Mono", monospace',- cursor: 'pointer',- textAlign: 'left',- transition: 'all 0.1s',- }}- onMouseEnter={e => {- (e.currentTarget as HTMLElement).style.backgroundColor = F.HEADER_BG;- (e.currentTarget as HTMLElement).style.color = F.WHITE;- }}- onMouseLeave={e => {- (e.currentTarget as HTMLElement).style.backgroundColor = 'transparent';- (e.currentTarget as HTMLElement).style.color = F.GRAY;- }}- >- {qc.label}- </button>- ))}- </div>- )}+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ transition: 'all 0.2s',+ letterSpacing: '0.5px',+ }}+ onMouseEnter={e => {+ if (!showQuickAdd) {+ e.currentTarget.style.borderColor = F.CYAN;+ e.currentTarget.style.color = F.CYAN;+ }+ }}+ onMouseLeave={e => {+ if (!showQuickAdd) {+ e.currentTarget.style.borderColor = F.BORDER;+ e.currentTarget.style.color = F.GRAY;+ }+ }}+ >+ <Sparkles size={10} />+ {showQuickAdd ? <ChevronDown size={10} /> : <ChevronRight size={10} />}+ TEMPLATES+ </button></div>++ {/* ─── TEMPLATE DROPDOWN (Categorized) ─── */}+ {showQuickAdd && (+ <div style={{+ margin: '0 12px 12px',+ backgroundColor: F.DARK_BG,+ border: `1px solid ${F.BORDER}`,+ borderRadius: '2px',+ overflow: 'hidden',+ }}>+ {Object.entries(groupedQuickConditions).map(([category, items]) => (+ <div key={category}>+ {/* Category header */}+ <div style={{+ padding: '6px 12px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ }}>+ <span style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED,+ letterSpacing: '0.5px',+ }}>+ {category.toUpperCase()}+ </span>+ </div>+ {/* Category items */}+ {items.map((qc, i) => (+ <button+ key={i}+ onClick={() => handleAdd(qc.condition)}+ style={{+ width: '100%',+ padding: '8px 12px',+ backgroundColor: 'transparent',+ border: 'none',+ borderBottom: `1px solid ${F.BORDER}30`,+ color: F.GRAY,+ fontSize: '9px',+ fontFamily: '"IBM Plex Mono", monospace',+ cursor: 'pointer',+ textAlign: 'left',+ transition: 'all 0.15s',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ }}+ onMouseEnter={e => {+ e.currentTarget.style.backgroundColor = `${F.ORANGE}10`;+ e.currentTarget.style.color = F.WHITE;+ }}+ onMouseLeave={e => {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.color = F.GRAY;+ }}+ >+ <Plus size={9} style={{ color: F.ORANGE, flexShrink: 0 }} />+ {qc.label}+ </button>+ ))}+ </div>+ ))}+ </div>+ )}</div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionRow.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionRow.tsxindex 46338dffa..61e3950c8 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionRow.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionRow.tsx@@ -1,5 +1,5 @@import React from 'react';-import { Clock } from 'lucide-react';+import { Clock, ArrowRight, AlertTriangle } from 'lucide-react';import type { ConditionItem } from '../types';import { INDICATOR_DEFINITIONS, OPERATORS, getIndicatorDef } from '../constants/indicators';@@ -7,15 +7,15 @@ const F = {ORANGE: '#FF8800', WHITE: '#FFFFFF', GRAY: '#787878', DARK_BG: '#000000',PANEL_BG: '#0F0F0F', BORDER: '#2A2A2A', HOVER: '#1F1F1F', MUTED: '#4A4A4A',CYAN: '#00E5FF', RED: '#FF3B3B', GREEN: '#00D66F', YELLOW: '#FFD600',- PURPLE: '#9D4EDD', BLUE: '#0088FF',+ PURPLE: '#9D4EDD', BLUE: '#0088FF', HEADER_BG: '#1A1A1A',};// Operator labels for readable displayconst OPERATOR_LABELS: Record<string, string> = {'>': 'Greater than','<': 'Less than',- '>=': 'Greater than or equal',- '<=': 'Less than or equal',+ '>=': 'Greater or equal',+ '<=': 'Less or equal','==': 'Equal to','crosses_above': 'Crossed above','crosses_below': 'Crossed below',@@ -30,131 +30,53 @@ const OPERATOR_LABELS: Record<string, string> = {type ScaleType = 'price' | 'percent_0_100' | 'percent_0_1' | 'oscillator' | 'direction' | 'volume' | 'ratio';const INDICATOR_SCALES: Record<string, ScaleType> = {- // Price-based (actual price values)- 'OPEN': 'price',- 'HIGH': 'price',- 'LOW': 'price',- 'CLOSE': 'price',- 'SMA': 'price',- 'EMA': 'price',- 'WMA': 'price',- 'VWAP': 'price',- 'BOLLINGER': 'price', // upper/middle/lower are price, but pct_b is 0-1- 'SUPERTREND': 'price', // value is price, direction is -1/1- 'KELTNER': 'price',- 'DONCHIAN': 'price',- 'PIVOT': 'price',-- // 0-100 oscillators- 'RSI': 'percent_0_100',- 'STOCH': 'percent_0_100',- 'STOCH_RSI': 'percent_0_100',- 'CCI': 'percent_0_100', // can exceed 100 but similar scale- 'WILLIAMS_R': 'percent_0_100',- 'MFI': 'percent_0_100',- 'CMO': 'percent_0_100',-- // 0-1 or small range- 'ADX': 'percent_0_100',- 'ATR': 'price',- 'AROON': 'percent_0_100',-- // Unbounded oscillators (can be negative/positive)- 'MACD': 'oscillator',- 'OBV': 'volume',- 'VOLUME': 'volume',- 'ROC': 'ratio',- 'MOMENTUM': 'oscillator',-- // Direction indicators (-1, 0, 1)- 'PSAR': 'price',+ 'OPEN': 'price', 'HIGH': 'price', 'LOW': 'price', 'CLOSE': 'price',+ 'SMA': 'price', 'EMA': 'price', 'WMA': 'price', 'VWAP': 'price',+ 'BOLLINGER': 'price', 'SUPERTREND': 'price', 'KELTNER': 'price',+ 'DONCHIAN': 'price', 'PIVOT': 'price', 'ATR': 'price', 'PSAR': 'price',+ 'RSI': 'percent_0_100', 'STOCH': 'percent_0_100', 'STOCH_RSI': 'percent_0_100',+ 'CCI': 'percent_0_100', 'WILLIAMS_R': 'percent_0_100', 'MFI': 'percent_0_100',+ 'CMO': 'percent_0_100', 'ADX': 'percent_0_100', 'AROON': 'percent_0_100',+ 'MACD': 'oscillator', 'OBV': 'volume', 'VOLUME': 'volume',+ 'ROC': 'ratio', 'MOMENTUM': 'oscillator',};-// Field-specific scale overridesconst FIELD_SCALE_OVERRIDES: Record<string, Record<string, ScaleType>> = {- 'BOLLINGER': {- 'pct_b': 'percent_0_1',- 'upper': 'price',- 'middle': 'price',- 'lower': 'price',- 'width': 'ratio',- },- 'SUPERTREND': {- 'value': 'price',- 'direction': 'direction',- },- 'STOCH': {- 'k': 'percent_0_100',- 'd': 'percent_0_100',- },- 'STOCH_RSI': {- 'k': 'percent_0_100',- 'd': 'percent_0_100',- },- 'MACD': {- 'line': 'oscillator',- 'signal_line': 'oscillator',- 'histogram': 'oscillator',- },- 'AROON': {- 'up': 'percent_0_100',- 'down': 'percent_0_100',- 'oscillator': 'percent_0_100',- },+ 'BOLLINGER': { 'pct_b': 'percent_0_1', 'upper': 'price', 'middle': 'price', 'lower': 'price', 'width': 'ratio' },+ 'SUPERTREND': { 'value': 'price', 'direction': 'direction' },+ 'STOCH': { 'k': 'percent_0_100', 'd': 'percent_0_100' },+ 'STOCH_RSI': { 'k': 'percent_0_100', 'd': 'percent_0_100' },+ 'MACD': { 'line': 'oscillator', 'signal_line': 'oscillator', 'histogram': 'oscillator' },+ 'AROON': { 'up': 'percent_0_100', 'down': 'percent_0_100', 'oscillator': 'percent_0_100' },};-// Get the scale type for an indicator + field combinationfunction getIndicatorScale(indicator: string, field: string): ScaleType {- // Check field-specific override first- if (FIELD_SCALE_OVERRIDES[indicator]?.[field]) {- return FIELD_SCALE_OVERRIDES[indicator][field];- }- // Fall back to indicator default+ if (FIELD_SCALE_OVERRIDES[indicator]?.[field]) return FIELD_SCALE_OVERRIDES[indicator][field];return INDICATOR_SCALES[indicator] || 'price';}-// Check if two scales are compatible for comparisonfunction areScalesCompatible(scale1: ScaleType, scale2: ScaleType): boolean {if (scale1 === scale2) return true;-- // Price scales are compatible with each otherconst priceScales: ScaleType[] = ['price'];if (priceScales.includes(scale1) && priceScales.includes(scale2)) return true;-- // Percent 0-100 scales are compatibleconst percent100Scales: ScaleType[] = ['percent_0_100'];if (percent100Scales.includes(scale1) && percent100Scales.includes(scale2)) return true;-- // Oscillators can be compared with each otherconst oscillatorScales: ScaleType[] = ['oscillator'];if (oscillatorScales.includes(scale1) && oscillatorScales.includes(scale2)) return true;-return false;}-// Get warning message for incompatible comparisonfunction getCompatibilityWarning(- indicator1: string,- field1: string,- indicator2: string,- field2: string+ indicator1: string, field1: string, indicator2: string, field2: string): string | null {const scale1 = getIndicatorScale(indicator1, field1);const scale2 = getIndicatorScale(indicator2, field2);-if (areScalesCompatible(scale1, scale2)) return null;-const scaleLabels: Record<ScaleType, string> = {- 'price': 'price level',- 'percent_0_100': '0-100 range',- 'percent_0_1': '0-1 range',- 'oscillator': 'oscillator',- 'direction': 'direction (-1/1)',- 'volume': 'volume',- 'ratio': 'ratio',+ 'price': 'price level', 'percent_0_100': '0-100 range', 'percent_0_1': '0-1 range',+ 'oscillator': 'oscillator', 'direction': 'direction (-1/1)', 'volume': 'volume', 'ratio': 'ratio',};-- return `⚠ Incompatible scales: ${indicator1} is ${scaleLabels[scale1]}, ${indicator2} is ${scaleLabels[scale2]}`;+ return `Incompatible scales: ${indicator1} is ${scaleLabels[scale1]}, ${indicator2} is ${scaleLabels[scale2]}`;}interface ConditionRowProps {@@ -180,23 +102,6 @@ const inputStyle: React.CSSProperties = {width: '60px',};-const tinyBtnStyle: React.CSSProperties = {- padding: '3px 6px',- backgroundColor: 'transparent',- border: `1px solid ${F.BORDER}`,- borderRadius: '2px',- color: F.MUTED,- cursor: 'pointer',- fontSize: '8px',- fontWeight: 700,- fontFamily: '"IBM Plex Mono", monospace',- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '3px',- transition: 'all 0.15s',-};-const categories = ['stock_attributes', 'moving_averages', 'momentum', 'trend', 'volatility', 'volume'] as const;const categoryLabels: Record<string, string> = {@@ -215,7 +120,7 @@ function IndicatorSelect({ value, onChange, style }: {style?: React.CSSProperties;}) {return (- <select value={value} onChange={e => onChange(e.target.value)} style={{ ...selectStyle, width: '130px', ...style }}>+ <select value={value} onChange={e => onChange(e.target.value)} style={{ ...selectStyle, ...style }}>{categories.map(cat => {const indicators = INDICATOR_DEFINITIONS.filter(d => d.category === cat);if (indicators.length === 0) return null;@@ -241,9 +146,12 @@ function ParamInputs({ indicatorDef, params, onChange }: {return (<>{indicatorDef.params.map(p => (- <div key={p.key} style={{ display: 'flex', alignItems: 'center', gap: '3px' }}>- <span style={{ fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>- {p.label.toUpperCase()}:+ <div key={p.key} style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={{+ fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px',+ whiteSpace: 'nowrap',+ }}>+ {p.label.toUpperCase()}</span><inputtype="number"@@ -274,62 +182,6 @@ function FieldSelect({ fields, value, onChange }: {);}-// Build a human-readable summary of the condition (Chartink-style)-function buildReadableSummary(condition: ConditionItem): React.ReactNode {- const indicatorDef = getIndicatorDef(condition.indicator);- const indicatorLabel = indicatorDef?.label || condition.indicator;- const compareMode = condition.compareMode || 'value';- const operatorLabel = OPERATOR_LABELS[condition.operator] || condition.operator;-- // Build indicator part with params- const paramValues = Object.values(condition.params);- const paramStr = paramValues.length > 0 ? `(${paramValues.join(',')})` : '';- const fieldStr = condition.field !== 'value' ? `.${condition.field}` : '';-- // Build target part- let targetPart: React.ReactNode;- if (compareMode === 'indicator' && condition.compareIndicator) {- const compareDef = getIndicatorDef(condition.compareIndicator);- const compareLabel = compareDef?.label || condition.compareIndicator;- const compareParamValues = Object.values(condition.compareParams || {});- const compareParamStr = compareParamValues.length > 0 ? `(${compareParamValues.join(',')})` : '';- const compareFieldStr = condition.compareField && condition.compareField !== 'value' ? `.${condition.compareField}` : '';- targetPart = (- <span style={{ color: F.PURPLE, fontWeight: 700 }}>- {compareLabel}{compareParamStr}{compareFieldStr}- </span>- );- } else if (condition.operator === 'rising' || condition.operator === 'falling') {- targetPart = (- <span style={{ color: F.CYAN, fontWeight: 700 }}>- {condition.lookback || 5} bars- </span>- );- } else if (condition.operator === 'between') {- targetPart = (- <>- <span style={{ color: F.CYAN, fontWeight: 700 }}>{condition.value}</span>- <span style={{ color: F.GRAY }}> and </span>- <span style={{ color: F.CYAN, fontWeight: 700 }}>{condition.value2 ?? 0}</span>- </>- );- } else {- targetPart = (- <span style={{ color: F.CYAN, fontWeight: 700 }}>- Number {condition.value}- </span>- );- }-- return (- <span style={{ fontSize: '10px', fontFamily: '"IBM Plex Mono", monospace' }}>- <span style={{ color: F.WHITE, fontWeight: 700 }}>{indicatorLabel}{paramStr}{fieldStr}</span>- <span style={{ color: F.GREEN, margin: '0 6px' }}>{operatorLabel}</span>- {targetPart}- </span>- );-}-const ConditionRow: React.FC<ConditionRowProps> = ({ condition, index, onChange, onRemove }) => {const indicatorDef = getIndicatorDef(condition.indicator);const fields = indicatorDef?.fields || ['value'];@@ -340,13 +192,10 @@ const ConditionRow: React.FC<ConditionRowProps> = ({ condition, index, onChange,const compareDef = condition.compareIndicator ? getIndicatorDef(condition.compareIndicator) : undefined;const compareFields = compareDef?.fields || ['value'];- // Check for compatibility warning when comparing two indicatorsconst compatibilityWarning = compareMode === 'indicator' && condition.compareIndicator? getCompatibilityWarning(- condition.indicator,- condition.field,- condition.compareIndicator,- condition.compareField || 'value'+ condition.indicator, condition.field,+ condition.compareIndicator, condition.compareField || 'value'): null;@@ -355,19 +204,12 @@ const ConditionRow: React.FC<ConditionRowProps> = ({ condition, index, onChange,if (!def) return;const defaultParams: Record<string, number> = {};def.params.forEach(p => { defaultParams[p.key] = p.default; });- onChange(index, {- ...condition,- indicator: name,- field: def.defaultField,- params: defaultParams,- });+ onChange(index, { ...condition, indicator: name, field: def.defaultField, params: defaultParams });};const handleParamChange = (key: string, val: string) => {const num = parseFloat(val);- if (!isNaN(num)) {- onChange(index, { ...condition, params: { ...condition.params, [key]: num } });- }+ if (!isNaN(num)) onChange(index, { ...condition, params: { ...condition.params, [key]: num } });};const handleCompareIndicatorChange = (name: string) => {@@ -376,291 +218,341 @@ const ConditionRow: React.FC<ConditionRowProps> = ({ condition, index, onChange,const defaultParams: Record<string, number> = {};def.params.forEach(p => { defaultParams[p.key] = p.default; });onChange(index, {- ...condition,- compareIndicator: name,- compareField: def.defaultField,- compareParams: defaultParams,+ ...condition, compareIndicator: name, compareField: def.defaultField, compareParams: defaultParams,});};const handleCompareParamChange = (key: string, val: string) => {const num = parseFloat(val);if (!isNaN(num)) {- onChange(index, {- ...condition,- compareParams: { ...(condition.compareParams || {}), [key]: num },- });+ onChange(index, { ...condition, compareParams: { ...(condition.compareParams || {}), [key]: num } });}};- // Handle "Compare With" dropdown changeconst handleCompareWithChange = (value: string) => {if (value === 'NUMBER') {- // Switch to value modeonChange(index, {- ...condition,- compareMode: 'value',- compareIndicator: undefined,- compareParams: undefined,- compareField: undefined,+ ...condition, compareMode: 'value',+ compareIndicator: undefined, compareParams: undefined, compareField: undefined,});} else {- // Switch to indicator mode with selected indicatorconst def = getIndicatorDef(value);if (!def) return;const defaultParams: Record<string, number> = {};def.params.forEach(p => { defaultParams[p.key] = p.default; });onChange(index, {- ...condition,- compareMode: 'indicator',- compareIndicator: value,- compareField: def.defaultField,- compareParams: defaultParams,+ ...condition, compareMode: 'indicator',+ compareIndicator: value, compareField: def.defaultField, compareParams: defaultParams,});}};const needsLookback = ['crossed_above_within', 'crossed_below_within', 'rising', 'falling'].includes(condition.operator);+ // Build readable summary+ const indicatorLabel = indicatorDef?.label || condition.indicator;+ const paramValues = Object.values(condition.params);+ const paramStr = paramValues.length > 0 ? `(${paramValues.join(',')})` : '';+ const fieldStr = condition.field !== 'value' ? `.${condition.field}` : '';+ const operatorLabel = OPERATOR_LABELS[condition.operator] || condition.operator;++ let compareStr = '';+ if (compareMode === 'indicator' && condition.compareIndicator) {+ const cDef = getIndicatorDef(condition.compareIndicator);+ const cLabel = cDef?.label || condition.compareIndicator;+ const cpv = Object.values(condition.compareParams || {});+ const cpStr = cpv.length > 0 ? `(${cpv.join(',')})` : '';+ const cfStr = condition.compareField && condition.compareField !== 'value' ? `.${condition.compareField}` : '';+ compareStr = `${cLabel}${cpStr}${cfStr}`;+ } else if (condition.operator === 'rising' || condition.operator === 'falling') {+ compareStr = `${condition.lookback || 5} bars`;+ } else if (condition.operator === 'between') {+ compareStr = `${condition.value} and ${condition.value2 ?? 0}`;+ } else {+ compareStr = `${condition.value}`;+ }+return (- <div style={{- padding: '6px 8px',- borderRadius: '2px',- transition: 'all 0.2s',- }}>- {/* Readable summary line (Chartink-style) */}+ <div style={{ padding: '10px 12px' }}>+ {/* ─── Readable Summary ─── */}<div style={{display: 'flex',alignItems: 'center',- justifyContent: 'space-between',- marginBottom: compatibilityWarning ? '4px' : '6px',- padding: '6px 10px',- backgroundColor: F.DARK_BG,+ gap: '6px',+ padding: '8px 12px',+ backgroundColor: `${F.PANEL_BG}`,borderRadius: '2px',- border: `1px solid ${compatibilityWarning ? F.YELLOW + '60' : F.BORDER}`,+ border: `1px solid ${compatibilityWarning ? F.YELLOW + '40' : F.BORDER}`,+ marginBottom: '10px',}}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <span style={{ color: F.MUTED, fontSize: '9px', fontWeight: 700 }}>▸</span>- {buildReadableSummary(condition)}- </div>- <button- onClick={() => onRemove(index)}- style={{- padding: '2px 6px',- backgroundColor: 'transparent',- border: 'none',- color: F.MUTED,- cursor: 'pointer',- borderRadius: '2px',- fontSize: '10px',- }}- onMouseEnter={e => { (e.currentTarget as HTMLElement).style.color = F.RED; }}- onMouseLeave={e => { (e.currentTarget as HTMLElement).style.color = F.MUTED; }}- title="Remove condition"- >- ✕- </button>+ <span style={{ fontSize: '10px', fontFamily: '"IBM Plex Mono", monospace' }}>+ <span style={{ color: F.WHITE, fontWeight: 700 }}>{indicatorLabel}{paramStr}{fieldStr}</span>+ <span style={{ color: F.GREEN, margin: '0 8px', fontWeight: 600 }}>{operatorLabel}</span>+ <span style={{ color: compareMode === 'indicator' ? F.PURPLE : F.CYAN, fontWeight: 700 }}>+ {compareStr}+ </span>+ </span></div>{/* Compatibility Warning */}{compatibilityWarning && (<div style={{- marginBottom: '6px',- marginLeft: '12px',- padding: '4px 8px',- backgroundColor: F.YELLOW + '15',- border: `1px solid ${F.YELLOW}40`,+ marginBottom: '10px',+ padding: '6px 10px',+ backgroundColor: `${F.YELLOW}12`,+ border: `1px solid ${F.YELLOW}30`,borderRadius: '2px',- fontSize: '9px',- color: F.YELLOW,- fontFamily: '"IBM Plex Mono", monospace',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',}}>- {compatibilityWarning}+ <AlertTriangle size={10} color={F.YELLOW} />+ <span style={{ fontSize: '9px', color: F.YELLOW, fontFamily: '"IBM Plex Mono", monospace' }}>+ {compatibilityWarning}+ </span></div>)}- {/* Controls row */}+ {/* ─── Controls Grid: Structured 3-column flow ─── */}<div style={{- display: 'flex',- alignItems: 'center',- gap: '6px',- flexWrap: 'wrap',- paddingLeft: '12px',+ display: 'grid',+ gridTemplateColumns: '1fr auto 1fr',+ gap: '8px',+ alignItems: 'start',}}>- {/* Left side: indicator + params + field */}- <IndicatorSelect value={condition.indicator} onChange={handleIndicatorChange} />-- <ParamInputs- indicatorDef={indicatorDef}- params={condition.params}- onChange={handleParamChange}- />-- <FieldSelect- fields={fields}- value={condition.field}- onChange={f => onChange(index, { ...condition, field: f })}- />-- {/* Offset for left side */}- {condition.offset !== undefined && condition.offset > 0 && (- <div style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>- <Clock size={8} color={F.YELLOW} />- <input- type="number"- value={condition.offset}- onChange={e => {- const v = parseInt(e.target.value);- onChange(index, { ...condition, offset: isNaN(v) ? 0 : Math.max(0, v) });- }}- min={0}- max={100}- style={{ ...inputStyle, width: '40px', color: F.YELLOW, fontSize: '9px' }}- title="Bars ago"- />- </div>- )}-- {/* Operator */}- <select- value={condition.operator}- onChange={e => onChange(index, { ...condition, operator: e.target.value })}- style={{ ...selectStyle, width: '120px' }}- >- {OPERATORS.map(op => (- <option key={op.value} value={op.value}>{op.label}</option>- ))}- </select>-- {/* Lookback for advanced operators */}- {needsLookback && (- <div style={{ display: 'flex', alignItems: 'center', gap: '3px' }}>- <span style={{ fontSize: '8px', fontWeight: 700, color: F.GRAY }}>N:</span>- <input- type="number"- value={condition.lookback ?? 5}- onChange={e => {- const v = parseInt(e.target.value);- if (!isNaN(v)) onChange(index, { ...condition, lookback: Math.max(1, v) });- }}- min={1}- max={100}- style={{ ...inputStyle, width: '45px' }}- />- </div>- )}-- {/* Compare With dropdown - unified selector for Number or Indicator */}- <select- value={compareMode === 'value' ? 'NUMBER' : (condition.compareIndicator || 'EMA')}- onChange={e => handleCompareWithChange(e.target.value)}- style={{- ...selectStyle,- width: '130px',- color: compareMode === 'value' ? F.CYAN : F.PURPLE,- borderColor: compareMode === 'value' ? F.CYAN + '40' : F.PURPLE + '40',- }}- >- <option value="NUMBER" style={{ color: F.CYAN }}>Number</option>- <optgroup label="─── Indicators ───">- {categories.map(cat => {- const indicators = INDICATOR_DEFINITIONS.filter(d => d.category === cat);- if (indicators.length === 0) return null;- return indicators.map(d => (- <option key={d.name} value={d.name}>{d.label}</option>- ));- })}- </optgroup>- </select>-- {/* Value input (when comparing to Number) */}- {compareMode === 'value' && (- <>- <input- type="number"- value={condition.value}- onChange={e => {- const v = parseFloat(e.target.value);- if (!isNaN(v)) onChange(index, { ...condition, value: v });- }}- step="any"- style={{ ...inputStyle, width: '72px', color: F.CYAN, borderColor: F.CYAN + '40' }}- placeholder="Value"- />-- {/* Value2 for between */}- {condition.operator === 'between' && (- <>- <span style={{ fontSize: '9px', color: F.GRAY }}>AND</span>+ {/* LEFT: Source Indicator */}+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '6px',+ padding: '8px',+ backgroundColor: F.PANEL_BG,+ borderRadius: '2px',+ border: `1px solid ${F.BORDER}`,+ }}>+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px' }}>+ INDICATOR+ </span>+ <IndicatorSelect value={condition.indicator} onChange={handleIndicatorChange} style={{ width: '100%' }} />+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>+ <ParamInputs+ indicatorDef={indicatorDef}+ params={condition.params}+ onChange={handleParamChange}+ />+ </div>+ {fields.length > 1 && (+ <div>+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '2px', display: 'block' }}>+ FIELD+ </span>+ <FieldSelect+ fields={fields}+ value={condition.field}+ onChange={f => onChange(index, { ...condition, field: f })}+ />+ </div>+ )}+ {condition.offset !== undefined && condition.offset > 0 && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <Clock size={9} color={F.YELLOW} />+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.YELLOW }}>OFFSET:</span><inputtype="number"- value={condition.value2 ?? 0}+ value={condition.offset}onChange={e => {- const v = parseFloat(e.target.value);- if (!isNaN(v)) onChange(index, { ...condition, value2: v });+ const v = parseInt(e.target.value);+ onChange(index, { ...condition, offset: isNaN(v) ? 0 : Math.max(0, v) });}}- step="any"- style={{ ...inputStyle, width: '72px', color: F.CYAN, borderColor: F.CYAN + '40' }}+ min={0} max={100}+ style={{ ...inputStyle, width: '45px', color: F.YELLOW, fontSize: '9px' }}+ title="Bars ago"/>- </>+ </div>)}- </>- )}-- {/* Indicator params (when comparing to another Indicator) */}- {compareMode === 'indicator' && (- <>- <ParamInputs- indicatorDef={compareDef}- params={condition.compareParams || {}}- onChange={handleCompareParamChange}- />-- <FieldSelect- fields={compareFields}- value={condition.compareField || 'value'}- onChange={f => onChange(index, { ...condition, compareField: f })}- />+ </div>- {/* Offset for compare side */}- {condition.compareOffset !== undefined && condition.compareOffset > 0 && (- <div style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>- <Clock size={8} color={F.YELLOW} />+ {/* CENTER: Operator */}+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '6px',+ paddingTop: '20px',+ }}>+ <ArrowRight size={12} color={F.ORANGE} />+ <select+ value={condition.operator}+ onChange={e => onChange(index, { ...condition, operator: e.target.value })}+ style={{ ...selectStyle, width: '140px', textAlign: 'center', color: F.GREEN, fontWeight: 700 }}+ >+ {OPERATORS.map(op => (+ <option key={op.value} value={op.value}>{op.label}</option>+ ))}+ </select>+ {needsLookback && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.GRAY }}>BARS:</span><inputtype="number"- value={condition.compareOffset}+ value={condition.lookback ?? 5}onChange={e => {const v = parseInt(e.target.value);- onChange(index, { ...condition, compareOffset: isNaN(v) ? 0 : Math.max(0, v) });+ if (!isNaN(v)) onChange(index, { ...condition, lookback: Math.max(1, v) });}}- min={0}- max={100}- style={{ ...inputStyle, width: '40px', color: F.YELLOW, fontSize: '9px' }}- title="Bars ago"+ min={1} max={100}+ style={{ ...inputStyle, width: '50px' }}/></div>)}- </>- )}+ {/* Offset toggle */}+ <button+ onClick={() => {+ if (showOffset) {+ onChange(index, { ...condition, offset: 0, compareOffset: 0 });+ } else {+ onChange(index, { ...condition, offset: 1, compareOffset: 0 });+ }+ }}+ style={{+ padding: '3px 8px',+ backgroundColor: showOffset ? `${F.YELLOW}20` : 'transparent',+ border: `1px solid ${showOffset ? F.YELLOW + '60' : F.BORDER}`,+ borderRadius: '2px',+ color: showOffset ? F.YELLOW : F.MUTED,+ cursor: 'pointer',+ fontSize: '8px',+ fontWeight: 700,+ fontFamily: '"IBM Plex Mono", monospace',+ letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ gap: '3px',+ transition: 'all 0.2s',+ }}+ title="Toggle bar offset (n candles ago)"+ >+ <Clock size={8} />+ OFFSET+ </button>+ </div>++ {/* RIGHT: Compare Target */}+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '6px',+ padding: '8px',+ backgroundColor: F.PANEL_BG,+ borderRadius: '2px',+ border: `1px solid ${F.BORDER}`,+ }}>+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px' }}>+ COMPARE WITH+ </span>+ <select+ value={compareMode === 'value' ? 'NUMBER' : (condition.compareIndicator || 'EMA')}+ onChange={e => handleCompareWithChange(e.target.value)}+ style={{+ ...selectStyle,+ width: '100%',+ color: compareMode === 'value' ? F.CYAN : F.PURPLE,+ borderColor: compareMode === 'value' ? `${F.CYAN}40` : `${F.PURPLE}40`,+ }}+ >+ <option value="NUMBER" style={{ color: F.CYAN }}>Number (fixed value)</option>+ <optgroup label="--- Indicators ---">+ {categories.map(cat => {+ const indicators = INDICATOR_DEFINITIONS.filter(d => d.category === cat);+ if (indicators.length === 0) return null;+ return indicators.map(d => (+ <option key={d.name} value={d.name}>{d.label}</option>+ ));+ })}+ </optgroup>+ </select>++ {/* Value input (when comparing to Number) */}+ {compareMode === 'value' && (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>+ <div>+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '2px', display: 'block' }}>+ VALUE+ </span>+ <input+ type="number"+ value={condition.value}+ onChange={e => {+ const v = parseFloat(e.target.value);+ if (!isNaN(v)) onChange(index, { ...condition, value: v });+ }}+ step="any"+ style={{ ...inputStyle, width: '100%', color: F.CYAN, borderColor: `${F.CYAN}40` }}+ placeholder="Value"+ />+ </div>+ {condition.operator === 'between' && (+ <div>+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '2px', display: 'block' }}>+ AND VALUE+ </span>+ <input+ type="number"+ value={condition.value2 ?? 0}+ onChange={e => {+ const v = parseFloat(e.target.value);+ if (!isNaN(v)) onChange(index, { ...condition, value2: v });+ }}+ step="any"+ style={{ ...inputStyle, width: '100%', color: F.CYAN, borderColor: `${F.CYAN}40` }}+ />+ </div>+ )}+ </div>+ )}- {/* Offset toggle */}- <button- onClick={() => {- if (showOffset) {- onChange(index, { ...condition, offset: 0, compareOffset: 0 });- } else {- onChange(index, { ...condition, offset: 1, compareOffset: 0 });- }- }}- style={{- ...tinyBtnStyle,- color: showOffset ? F.YELLOW : F.MUTED,- borderColor: showOffset ? F.YELLOW + '60' : F.BORDER,- }}- title="Toggle bar offset (n candles ago)"- >- <Clock size={9} />- </button>+ {/* Indicator params (when comparing to another Indicator) */}+ {compareMode === 'indicator' && (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>+ <ParamInputs+ indicatorDef={compareDef}+ params={condition.compareParams || {}}+ onChange={handleCompareParamChange}+ />+ </div>+ {compareFields.length > 1 && (+ <div>+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '2px', display: 'block' }}>+ FIELD+ </span>+ <FieldSelect+ fields={compareFields}+ value={condition.compareField || 'value'}+ onChange={f => onChange(index, { ...condition, compareField: f })}+ />+ </div>+ )}+ {condition.compareOffset !== undefined && condition.compareOffset > 0 && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <Clock size={9} color={F.YELLOW} />+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.YELLOW }}>OFFSET:</span>+ <input+ type="number"+ value={condition.compareOffset}+ onChange={e => {+ const v = parseInt(e.target.value);+ onChange(index, { ...condition, compareOffset: isNaN(v) ? 0 : Math.max(0, v) });+ }}+ min={0} max={100}+ style={{ ...inputStyle, width: '45px', color: F.YELLOW, fontSize: '9px' }}+ title="Bars ago"+ />+ </div>+ )}+ </div>+ )}+ </div></div></div>);diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeployPanel.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeployPanel.tsxindex 096c141dd..608fa59ba 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeployPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeployPanel.tsx@@ -1,24 +1,32 @@-import React, { useState } from 'react';-import { Rocket, X, Link, AlertTriangle } from 'lucide-react';+import React, { useState, useEffect } from 'react';+import { invoke } from '@tauri-apps/api/core';+import { Rocket, X, AlertTriangle, Zap, Server, Activity } from 'lucide-react';import { TIMEFRAMES } from '../constants/indicators';import { deployAlgoStrategy, startOrderSignalBridge } from '../services/algoTradingService';import { useBrokerContext } from '@/contexts/BrokerContext';+import { useStockBrokerContextOptional } from '@/contexts/StockBrokerContext';+import { SymbolSearch } from '@/components/tabs/equity-trading/components/SymbolSearch';+import type { SymbolSearchResult, SupportedBroker } from '@/services/trading/masterContractService';+import type { StockExchange } from '@/brokers/stocks/types';++type AssetType = 'crypto' | 'stock';const F = {ORANGE: '#FF8800', WHITE: '#FFFFFF', RED: '#FF3B3B', GREEN: '#00D66F',GRAY: '#787878', DARK_BG: '#000000', PANEL_BG: '#0F0F0F',HEADER_BG: '#1A1A1A', BORDER: '#2A2A2A', MUTED: '#4A4A4A',- CYAN: '#00E5FF', YELLOW: '#FFD700',+ CYAN: '#00E5FF', YELLOW: '#FFD700', HOVER: '#1F1F1F',};const inputStyle: React.CSSProperties = {width: '100%', padding: '8px 10px', backgroundColor: F.DARK_BG,color: F.WHITE, border: `1px solid ${F.BORDER}`, borderRadius: '2px',fontSize: '10px', fontFamily: '"IBM Plex Mono", monospace', outline: 'none',+ transition: 'border-color 0.2s',};const labelStyle: React.CSSProperties = {- fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px',+ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px',marginBottom: '4px', display: 'block',};@@ -26,19 +34,59 @@ interface DeployPanelProps {strategyId: string;strategyName: string;onClose: () => void;+ onDeployed?: (deployId: string) => void;}-const DeployPanel: React.FC<DeployPanelProps> = ({ strategyId, strategyName, onClose }) => {- const { activeBroker, activeBrokerMetadata, realAdapter, tradingMode } = useBrokerContext();+const DeployPanel: React.FC<DeployPanelProps> = ({ strategyId, strategyName, onClose, onDeployed }) => {+ const { activeBroker: cryptoBroker, activeBrokerMetadata: cryptoMeta, realAdapter: cryptoAdapter, tradingMode } = useBrokerContext();+ const stockCtx = useStockBrokerContextOptional();const [symbol, setSymbol] = useState('');+ const [selectedExchange, setSelectedExchange] = useState<StockExchange>('NSE' as StockExchange);+ const [selectedToken, setSelectedToken] = useState<string | null>(null);const [mode, setMode] = useState<'paper' | 'live'>('paper');+ const [assetType, setAssetType] = useState<AssetType>('stock');const [timeframe, setTimeframe] = useState('5m');const [quantity, setQuantity] = useState('1');const [deploying, setDeploying] = useState(false);const [result, setResult] = useState<{ success: boolean; message: string } | null>(null);+ const [stockCredsStored, setStockCredsStored] = useState<{ broker: string; hasToken: boolean } | null>(null);++ // Check if any Indian stock broker has stored credentials (Rust auto-connects on deploy)+ useEffect(() => {+ const brokers = ['angelone', 'fyers', 'zerodha', 'upstox', 'dhan', 'shoonya'];+ let cancelled = false;+ (async () => {+ for (const b of brokers) {+ try {+ const raw = await invoke<string>('get_indian_broker_credentials', { brokerId: b });+ const creds = JSON.parse(raw);+ if (!cancelled && creds && creds.api_key) {+ setStockCredsStored({ broker: b, hasToken: !!creds.access_token });+ return;+ }+ } catch { /* no creds for this broker */ }+ }+ })();+ return () => { cancelled = true; };+ }, []);++ // Derive broker info based on asset type+ const isCrypto = assetType === 'crypto';+ const stockContextConnected = stockCtx?.isAuthenticated ?? false;+ const stockHasStoredCreds = !!stockCredsStored;+ const brokerConnected = isCrypto ? !!cryptoAdapter : (stockContextConnected || stockHasStoredCreds);+ const brokerName = isCrypto+ ? (cryptoMeta?.displayName || cryptoBroker || 'Kraken')+ : (stockCtx?.activeBrokerMetadata?.displayName || stockCtx?.activeBroker || stockCredsStored?.broker?.toUpperCase() || 'Stock Broker');+ const providerName = isCrypto+ ? (cryptoBroker || 'kraken')+ : (stockCtx?.activeBroker || stockCredsStored?.broker || 'angelone');- const brokerConnected = !!realAdapter;- const brokerName = activeBrokerMetadata?.displayName || activeBroker;+ const handleSymbolSelect = (sym: string, exchange: StockExchange, result?: SymbolSearchResult) => {+ setSymbol(sym);+ setSelectedExchange(exchange);+ setSelectedToken(result?.token || null);+ };const handleDeploy = async () => {if (!symbol.trim()) return;@@ -47,14 +95,30 @@ const DeployPanel: React.FC<DeployPanelProps> = ({ strategyId, strategyName, onCreturn;}setDeploying(true); setResult(null);++ // Pass token and exchange through params so Rust backend can use them for WS subscribe+ const deployParams: Record<string, string> = {};+ if (!isCrypto && selectedToken) {+ deployParams.token = selectedToken;+ deployParams.exchange = selectedExchange;+ }+const res = await deployAlgoStrategy({- strategyId, symbol: symbol.trim().toUpperCase(), provider: activeBroker,+ strategyId, symbol: symbol.trim().toUpperCase(), provider: providerName,mode, timeframe, quantity: parseFloat(quantity) || 1,+ params: Object.keys(deployParams).length > 0 ? JSON.stringify(deployParams) : undefined,});setDeploying(false);if (res.success) {- setResult({ success: true, message: `Deployed! ID: ${res.data?.deploy_id}` });+ const deployId = (res as unknown as Record<string, unknown>).deploy_id ?? res.data?.deploy_id;+ // Rust backend auto-connects broker WS and subscribes during deploy+ setResult({ success: true, message: `Deployed! ID: ${deployId}` });if (mode === 'live') startOrderSignalBridge().catch(() => {});+ // Auto-close and redirect to live dashboard after a brief delay+ setTimeout(() => {+ onClose();+ onDeployed?.(String(deployId));+ }, 2000);} else {setResult({ success: false, message: res.error || 'Deploy failed' });}@@ -62,78 +126,228 @@ const DeployPanel: React.FC<DeployPanelProps> = ({ strategyId, strategyName, onCreturn (<div style={{- backgroundColor: F.PANEL_BG, border: `1px solid ${F.GREEN}30`,- borderLeft: `2px solid ${F.GREEN}`, borderRadius: '2px', padding: '12px',- }}>- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>- <span style={{ fontSize: '9px', fontWeight: 700, color: F.GREEN, letterSpacing: '0.5px' }}>- DEPLOY: {strategyName.toUpperCase()}- </span>- <button onClick={onClose} style={{ padding: '4px', backgroundColor: 'transparent', border: 'none', color: F.MUTED, cursor: 'pointer' }}>- <X size={12} />- </button>- </div>-- {/* Broker Status */}+ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,+ backgroundColor: 'rgba(0,0,0,0.7)', display: 'flex',+ alignItems: 'center', justifyContent: 'center', zIndex: 1000,+ }}+ onClick={e => { if (e.target === e.currentTarget) onClose(); }}+ ><div style={{- display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '8px',- padding: '4px 8px', borderRadius: '2px', fontSize: '9px', fontWeight: 700,- backgroundColor: brokerConnected ? `${F.GREEN}15` : `${F.YELLOW}15`,- color: brokerConnected ? F.GREEN : F.YELLOW,+ width: '520px', backgroundColor: F.PANEL_BG,+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ overflow: 'visible',}}>- <Link size={10} />- <span>- {brokerName.toUpperCase()} — {brokerConnected ? 'CONNECTED' : 'NOT CONNECTED'}- {brokerConnected && tradingMode === 'paper' && ' (PAPER MODE)'}- </span>- </div>-- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '8px' }}>- <div><label style={labelStyle}>SYMBOL</label><input value={symbol} onChange={e => setSymbol(e.target.value)} placeholder="RELIANCE" style={inputStyle} /></div>- <div><label style={labelStyle}>MODE</label>- <select value={mode} onChange={e => setMode(e.target.value as 'paper' | 'live')} style={inputStyle}>- <option value="paper">Paper</option><option value="live">Live</option>- </select>- </div>- <div><label style={labelStyle}>TIMEFRAME</label>- <select value={timeframe} onChange={e => setTimeframe(e.target.value)} style={inputStyle}>- {TIMEFRAMES.map(tf => <option key={tf.value} value={tf.value}>{tf.label}</option>)}- </select>- </div>- <div><label style={labelStyle}>QUANTITY</label>- <input type="number" value={quantity} onChange={e => setQuantity(e.target.value)} min="0.01" step="any" style={inputStyle} />+ {/* Header */}+ <div style={{+ padding: '14px 16px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `2px solid ${F.GREEN}`,+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>+ <div style={{+ width: '28px', height: '28px', borderRadius: '2px',+ backgroundColor: `${F.GREEN}20`,+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ }}>+ <Rocket size={14} color={F.GREEN} />+ </div>+ <div>+ <div style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>+ DEPLOY STRATEGY+ </div>+ <div style={{ fontSize: '9px', color: F.MUTED, marginTop: '2px' }}>+ {strategyName.toUpperCase()}+ </div>+ </div>+ </div>+ <button+ onClick={onClose}+ style={{+ padding: '6px', backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ color: F.MUTED, cursor: 'pointer', borderRadius: '2px', transition: 'all 0.2s',+ }}+ onMouseEnter={e => { e.currentTarget.style.borderColor = F.RED; e.currentTarget.style.color = F.RED; }}+ onMouseLeave={e => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.MUTED; }}+ >+ <X size={12} />+ </button></div>- </div>- {mode === 'live' && !brokerConnected && (- <div style={{ marginTop: '6px', padding: '4px 8px', backgroundColor: `${F.RED}15`, color: F.RED, fontSize: '8px', fontWeight: 700, borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '4px' }}>- <AlertTriangle size={10} /> LIVE MODE REQUIRES ACTIVE BROKER CONNECTION+ {/* Asset Type Toggle */}+ <div style={{+ display: 'flex', padding: '0', borderBottom: `1px solid ${F.BORDER}`,+ }}>+ {(['stock', 'crypto'] as AssetType[]).map(at => (+ <button key={at} onClick={() => setAssetType(at)} style={{+ flex: 1, padding: '10px', border: 'none', cursor: 'pointer',+ backgroundColor: assetType === at ? `${at === 'crypto' ? F.CYAN : F.ORANGE}12` : 'transparent',+ borderBottom: assetType === at ? `2px solid ${at === 'crypto' ? F.CYAN : F.ORANGE}` : '2px solid transparent',+ color: assetType === at ? (at === 'crypto' ? F.CYAN : F.ORANGE) : F.MUTED,+ fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', transition: 'all 0.2s',+ }}>+ {at === 'crypto' ? 'CRYPTO' : 'INDIAN STOCK'}+ </button>+ ))}</div>- )}- {mode === 'live' && brokerConnected && (- <div style={{ marginTop: '6px', padding: '4px 8px', backgroundColor: `${F.YELLOW}15`, color: F.YELLOW, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>- LIVE MODE — REAL ORDERS VIA {brokerName.toUpperCase()}+ {/* Broker Status Bar */}+ <div style={{+ display: 'flex', alignItems: 'center', gap: '8px',+ padding: '10px 16px',+ backgroundColor: brokerConnected ? `${F.GREEN}08` : `${F.YELLOW}08`,+ borderBottom: `1px solid ${F.BORDER}`,+ }}>+ <div style={{+ width: '8px', height: '8px', borderRadius: '50%',+ backgroundColor: brokerConnected ? F.GREEN : F.YELLOW,+ }} />+ <Server size={10} color={brokerConnected ? F.GREEN : F.YELLOW} />+ <span style={{+ fontSize: '9px', fontWeight: 700,+ color: brokerConnected ? F.GREEN : F.YELLOW,+ letterSpacing: '0.5px',+ }}>+ {brokerName.toUpperCase()} -- {brokerConnected+ ? (stockHasStoredCreds && !stockContextConnected && !isCrypto+ ? 'CREDENTIALS STORED (AUTO-CONNECT ON DEPLOY)'+ : 'CONNECTED')+ : 'NOT CONNECTED'}+ {brokerConnected && stockContextConnected && tradingMode === 'paper' && ' (PAPER MODE)'}+ </span>+ {!isCrypto && !brokerConnected && (+ <span style={{ fontSize: '8px', color: F.MUTED, marginLeft: 'auto' }}>+ Login via Equity Trading tab+ </span>+ )}</div>- )}- {result && (- <div style={{- marginTop: '6px', padding: '4px 8px', borderRadius: '2px', fontSize: '9px', fontWeight: 700,- backgroundColor: result.success ? `${F.GREEN}20` : `${F.RED}20`,- color: result.success ? F.GREEN : F.RED,- }}>{result.message}</div>- )}-- <button onClick={handleDeploy} disabled={deploying || !symbol.trim()} style={{- marginTop: '8px', padding: '8px 16px', backgroundColor: F.GREEN, color: F.DARK_BG,- border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: 'pointer',- opacity: (deploying || !symbol.trim()) ? 0.5 : 1,- display: 'flex', alignItems: 'center', gap: '4px',- }}>- <Rocket size={10} />- {deploying ? 'DEPLOYING...' : 'DEPLOY STRATEGY'}- </button>+ {/* Config Form */}+ <div style={{ padding: '16px' }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>+ <div style={{ position: 'relative', zIndex: 100 }}>+ <label style={labelStyle}>SYMBOL</label>+ {isCrypto ? (+ <input+ value={symbol}+ onChange={e => setSymbol(e.target.value)}+ placeholder="e.g. BTC/USD"+ style={inputStyle}+ onFocus={e => { e.currentTarget.style.borderColor = F.ORANGE; }}+ onBlur={e => { e.currentTarget.style.borderColor = F.BORDER; }}+ />+ ) : (+ <SymbolSearch+ selectedSymbol={symbol}+ selectedExchange={selectedExchange}+ onSymbolSelect={handleSymbolSelect}+ brokerId={(providerName || 'angelone') as SupportedBroker}+ placeholder="Search stocks..."+ showDownloadStatus={false}+ exchangeFilter="NSE"+ instrumentTypeFilter="EQ"+ />+ )}+ {!isCrypto && selectedToken && (+ <div style={{ fontSize: '8px', color: F.CYAN, marginTop: '2px' }}>+ {selectedExchange}:{selectedToken}+ </div>+ )}+ </div>+ <div>+ <label style={labelStyle}>EXECUTION MODE</label>+ <select value={mode} onChange={e => setMode(e.target.value as 'paper' | 'live')} style={{+ ...inputStyle,+ color: mode === 'live' ? F.RED : F.GREEN,+ borderColor: mode === 'live' ? `${F.RED}40` : `${F.GREEN}40`,+ }}>+ <option value="paper">Paper Trading</option>+ <option value="live">Live Trading</option>+ </select>+ </div>+ <div>+ <label style={labelStyle}>TIMEFRAME</label>+ <select value={timeframe} onChange={e => setTimeframe(e.target.value)} style={inputStyle}>+ {TIMEFRAMES.map(tf => <option key={tf.value} value={tf.value}>{tf.label}</option>)}+ </select>+ </div>+ <div>+ <label style={labelStyle}>QUANTITY</label>+ <input+ type="number" value={quantity}+ onChange={e => setQuantity(e.target.value)}+ min="0.01" step="any" style={inputStyle}+ onFocus={e => { e.currentTarget.style.borderColor = F.ORANGE; }}+ onBlur={e => { e.currentTarget.style.borderColor = F.BORDER; }}+ />+ </div>+ </div>++ {/* Warnings */}+ {mode === 'live' && !brokerConnected && (+ <div style={{+ padding: '8px 12px', backgroundColor: `${F.RED}12`,+ border: `1px solid ${F.RED}30`, borderRadius: '2px',+ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '10px',+ }}>+ <AlertTriangle size={10} color={F.RED} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.RED }}>+ LIVE MODE REQUIRES AN ACTIVE BROKER CONNECTION+ </span>+ </div>+ )}+ {mode === 'live' && brokerConnected && (+ <div style={{+ padding: '8px 12px', backgroundColor: `${F.YELLOW}12`,+ border: `1px solid ${F.YELLOW}30`, borderRadius: '2px',+ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '10px',+ }}>+ <Zap size={10} color={F.YELLOW} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.YELLOW }}>+ LIVE MODE -- REAL ORDERS WILL BE PLACED VIA {brokerName.toUpperCase()}+ </span>+ </div>+ )}++ {/* Result */}+ {result && (+ <div style={{+ padding: '8px 12px', borderRadius: '2px', marginBottom: '10px',+ display: 'flex', alignItems: 'center', gap: '6px',+ backgroundColor: result.success ? `${F.GREEN}15` : `${F.RED}15`,+ border: `1px solid ${result.success ? F.GREEN + '40' : F.RED + '40'}`,+ }}>+ <Activity size={10} color={result.success ? F.GREEN : F.RED} />+ <span style={{+ fontSize: '9px', fontWeight: 700,+ color: result.success ? F.GREEN : F.RED,+ }}>+ {result.message}+ </span>+ </div>+ )}++ {/* Deploy button */}+ <button+ onClick={handleDeploy}+ disabled={deploying || !symbol.trim()}+ style={{+ width: '100%', padding: '12px',+ backgroundColor: mode === 'live' ? F.RED : F.GREEN,+ color: mode === 'live' ? F.WHITE : F.DARK_BG,+ border: 'none', borderRadius: '2px',+ fontSize: '10px', fontWeight: 700, letterSpacing: '0.5px',+ cursor: (deploying || !symbol.trim()) ? 'not-allowed' : 'pointer',+ opacity: (deploying || !symbol.trim()) ? 0.5 : 1,+ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px',+ transition: 'all 0.2s',+ }}+ >+ <Rocket size={12} />+ {deploying ? 'DEPLOYING STRATEGY...' : mode === 'live' ? 'DEPLOY TO LIVE' : 'DEPLOY TO PAPER'}+ </button>+ </div>+ </div></div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeploymentCard.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeploymentCard.tsxindex fc3431899..000245020 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeploymentCard.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeploymentCard.tsx@@ -1,29 +1,33 @@-import React, { useState } from 'react';-import { Square, ChevronDown, ChevronUp, TrendingUp, TrendingDown } from 'lucide-react';+import React, { useState, useEffect, useRef } from 'react';+import {+ Square, ChevronDown, ChevronUp, TrendingUp, TrendingDown,+ Activity, Target, Clock, BarChart3, Wifi, Zap, Trash2,+} from 'lucide-react';+import { listen } from '@tauri-apps/api/event';import type { AlgoDeployment } from '../types';-import { stopAlgoDeployment } from '../services/algoTradingService';+import { stopAlgoDeployment, deleteAlgoDeployment } from '../services/algoTradingService';import TradeHistoryTable from './TradeHistoryTable';const F = {ORANGE: '#FF8800', WHITE: '#FFFFFF', RED: '#FF3B3B', GREEN: '#00D66F',GRAY: '#787878', DARK_BG: '#000000', PANEL_BG: '#0F0F0F',HEADER_BG: '#1A1A1A', BORDER: '#2A2A2A', MUTED: '#4A4A4A',- CYAN: '#00E5FF', YELLOW: '#FFD700', BLUE: '#0088FF',+ CYAN: '#00E5FF', YELLOW: '#FFD700', BLUE: '#0088FF', PURPLE: '#9D4EDD',};-const statusStyle = (status: string): React.CSSProperties => {- const base: React.CSSProperties = {- padding: '2px 8px', borderRadius: '2px', fontSize: '9px', fontWeight: 700,- letterSpacing: '0.5px',- };- switch (status) {- case 'running': return { ...base, color: F.GREEN, backgroundColor: `${F.GREEN}15` };- case 'stopped': return { ...base, color: F.GRAY, backgroundColor: `${F.GRAY}15` };- case 'error': return { ...base, color: F.RED, backgroundColor: `${F.RED}15` };- case 'starting': return { ...base, color: F.YELLOW, backgroundColor: `${F.YELLOW}15` };- case 'pending': return { ...base, color: F.BLUE, backgroundColor: `${F.BLUE}15` };- default: return { ...base, color: F.GRAY, backgroundColor: `${F.GRAY}15` };- }+const statusConfig: Record<string, { color: string; bg: string; label: string }> = {+ running: { color: F.GREEN, bg: `${F.GREEN}15`, label: 'RUNNING' },+ stopped: { color: F.GRAY, bg: `${F.GRAY}15`, label: 'STOPPED' },+ error: { color: F.RED, bg: `${F.RED}15`, label: 'ERROR' },+ starting: { color: F.YELLOW, bg: `${F.YELLOW}15`, label: 'STARTING' },+ pending: { color: F.BLUE, bg: `${F.BLUE}15`, label: 'PENDING' },+};++const formatVolume = (v: number | null): string => {+ if (v === null || v === 0) return '0';+ if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`;+ if (v >= 1_000) return `${(v / 1_000).toFixed(1)}K`;+ return v.toFixed(0);};interface DeploymentCardProps {@@ -31,9 +35,64 @@ interface DeploymentCardProps {onStopped: () => void;}+interface LivePrice {+ price: number;+ change: number | null;+ changePct: number | null;+ high: number | null;+ low: number | null;+ volume: number | null;+ ts: number;+}+const DeploymentCard: React.FC<DeploymentCardProps> = ({ deployment, onStopped }) => {const [showTrades, setShowTrades] = useState(false);const [stopping, setStopping] = useState(false);+ const [deleting, setDeleting] = useState(false);+ const [livePrice, setLivePrice] = useState<LivePrice | null>(null);+ const prevPriceRef = useRef<number | null>(null);+ const [priceFlash, setPriceFlash] = useState<'up' | 'down' | null>(null);++ // Listen to unified algo_live_ticker event for live price from ANY connected broker+ useEffect(() => {+ if (deployment.status !== 'running') return;++ // Normalize the deployment symbol for matching (strip exchange prefixes like "NSE:")+ const deploySymNorm = deployment.symbol.replace(/^[A-Z]+:/i, '').toUpperCase();++ let unlisten: (() => void) | null = null;++ listen<{+ provider: string; symbol: string; price: number;+ change?: number; change_percent?: number;+ high?: number; low?: number; volume?: number;+ timestamp?: number;+ }>('algo_live_ticker', (event) => {+ const p = event.payload;+ // Normalize incoming symbol for comparison+ const tickSym = (p.symbol || '').replace(/^[A-Z]+:/i, '').toUpperCase();+ if (tickSym !== deploySymNorm && !tickSym.includes(deploySymNorm) && !deploySymNorm.includes(tickSym)) return;++ // Flash effect on price change+ if (prevPriceRef.current !== null && p.price !== prevPriceRef.current) {+ setPriceFlash(p.price > prevPriceRef.current ? 'up' : 'down');+ setTimeout(() => setPriceFlash(null), 400);+ }+ prevPriceRef.current = p.price;++ setLivePrice({+ price: p.price,+ change: p.change ?? null,+ changePct: p.change_percent ?? null,+ high: p.high ?? null,+ low: p.low ?? null,+ volume: p.volume ?? null,+ ts: Date.now(),+ });+ }).then(fn => { unlisten = fn; });++ return () => { unlisten?.(); };+ }, [deployment.symbol, deployment.status]);const handleStop = async () => {setStopping(true);@@ -42,103 +101,339 @@ const DeploymentCard: React.FC<DeploymentCardProps> = ({ deployment, onStopped }onStopped();};+ const handleDelete = async () => {+ setDeleting(true);+ await deleteAlgoDeployment(deployment.id);+ setDeleting(false);+ onStopped();+ };+const m = deployment.metrics;const totalPnl = m.total_pnl + m.unrealized_pnl;const isPositive = totalPnl >= 0;+ const sc = statusConfig[deployment.status] || statusConfig.pending;++ // Derive broker display info+ const providerLabel = (deployment.provider || '').toUpperCase() || 'N/A';+ const isCryptoBroker = ['kraken', 'hyperliquid', 'binance'].includes((deployment.provider || '').toLowerCase());+ const providerColor = isCryptoBroker ? F.CYAN : F.PURPLE;return (<div style={{- backgroundColor: F.PANEL_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px',- borderLeft: deployment.status === 'running' ? `2px solid ${F.GREEN}` : `2px solid transparent`,+ backgroundColor: F.PANEL_BG,+ border: `1px solid ${F.BORDER}`,+ borderRadius: '2px',overflow: 'hidden',+ transition: 'border-color 0.2s',}}>- {/* Main row */}+ {/* ─── TOP ROW: Symbol, Status, Name ─── */}<div style={{- display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 12px',+ display: 'flex', alignItems: 'center', gap: '10px',+ padding: '10px 14px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ borderLeft: `3px solid ${sc.color}`,}}>- <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flex: 1, minWidth: 0 }}>- <div style={statusStyle(deployment.status)}>- {deployment.status.toUpperCase()}+ {/* Status Badge */}+ <span style={{+ padding: '3px 8px', borderRadius: '2px',+ fontSize: '8px', fontWeight: 700, letterSpacing: '0.5px',+ color: sc.color, backgroundColor: sc.bg,+ }}>+ {sc.label}+ </span>++ {/* Symbol */}+ <span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>+ {deployment.symbol}+ </span>++ {/* Strategy name */}+ <span style={{ fontSize: '9px', color: F.MUTED }}>+ {deployment.strategy_name || deployment.strategy_id}+ </span>++ {/* Tags */}+ <div style={{ display: 'flex', gap: '4px', marginLeft: 'auto' }}>+ {/* Provider / Broker Badge */}+ <span style={{+ padding: '2px 6px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: `${providerColor}15`, color: providerColor,+ display: 'flex', alignItems: 'center', gap: '3px',+ }}>+ <Wifi size={7} />+ {providerLabel}+ </span>+ <span style={{+ padding: '2px 6px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: deployment.mode === 'live' ? `${F.RED}15` : `${F.GREEN}15`,+ color: deployment.mode === 'live' ? F.RED : F.GREEN,+ }}>+ {deployment.mode.toUpperCase()}+ </span>+ <span style={{+ padding: '2px 6px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: `${F.CYAN}15`, color: F.CYAN,+ }}>+ {deployment.timeframe}+ </span>+ <span style={{+ padding: '2px 6px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: `${F.BLUE}15`, color: F.BLUE,+ }}>+ QTY: {deployment.quantity}+ </span>+ </div>+ </div>++ {/* ─── LIVE PRICE BAR ─── */}+ {deployment.status === 'running' && (+ <div style={{+ display: 'flex', alignItems: 'center', gap: '12px',+ padding: '8px 14px',+ borderBottom: `1px solid ${F.BORDER}`,+ backgroundColor: livePrice+ ? (priceFlash === 'up' ? `${F.GREEN}12` : priceFlash === 'down' ? `${F.RED}12` : `${F.DARK_BG}`)+ : F.DARK_BG,+ transition: 'background-color 0.3s',+ }}>+ <div style={{+ display: 'flex', alignItems: 'center', gap: '5px',+ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px',+ }}>+ <Zap size={8} color={livePrice ? F.GREEN : F.MUTED} />+ LIVE PRICE</div>- <div style={{ minWidth: 0 }}>- <div style={{- fontSize: '10px', fontWeight: 700, color: F.WHITE,- overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',- }}>- {deployment.symbol}- <span style={{ color: F.MUTED, fontWeight: 400, marginLeft: '8px' }}>- {deployment.strategy_name || deployment.strategy_id}+ {livePrice ? (+ <>+ <span style={{+ fontSize: '16px', fontWeight: 700,+ color: priceFlash === 'up' ? F.GREEN : priceFlash === 'down' ? F.RED : F.WHITE,+ transition: 'color 0.3s',+ fontVariantNumeric: 'tabular-nums',+ }}>+ {livePrice.price.toFixed(2)}</span>- </div>- <div style={{ display: 'flex', gap: '12px', fontSize: '9px', color: F.MUTED, marginTop: '2px' }}>- <span>{deployment.mode.toUpperCase()}</span>- <span>{deployment.timeframe}</span>- <span>QTY: <span style={{ color: F.CYAN }}>{deployment.quantity}</span></span>- {m.current_position_qty > 0 && (- <span style={{ color: F.BLUE }}>- POS: {m.current_position_side} {m.current_position_qty} @ {m.current_position_entry.toFixed(2)}+ {livePrice.changePct !== null && (+ <span style={{+ fontSize: '10px', fontWeight: 700,+ color: (livePrice.changePct ?? 0) >= 0 ? F.GREEN : F.RED,+ display: 'flex', alignItems: 'center', gap: '2px',+ }}>+ {(livePrice.changePct ?? 0) >= 0 ? <TrendingUp size={9} /> : <TrendingDown size={9} />}+ {(livePrice.changePct ?? 0) >= 0 ? '+' : ''}{(livePrice.changePct ?? 0).toFixed(2)}%</span>)}+ {livePrice.change !== null && (+ <span style={{+ fontSize: '9px', fontWeight: 700,+ color: (livePrice.change ?? 0) >= 0 ? F.GREEN : F.RED,+ }}>+ ({(livePrice.change ?? 0) >= 0 ? '+' : ''}{(livePrice.change ?? 0).toFixed(2)})+ </span>+ )}+ <div style={{ display: 'flex', gap: '10px', marginLeft: 'auto', fontSize: '8px', color: F.MUTED }}>+ {livePrice.high !== null && (+ <span>H: <span style={{ color: F.GREEN }}>{(livePrice.high ?? 0).toFixed(2)}</span></span>+ )}+ {livePrice.low !== null && (+ <span>L: <span style={{ color: F.RED }}>{(livePrice.low ?? 0).toFixed(2)}</span></span>+ )}+ {livePrice.volume !== null && livePrice.volume > 0 && (+ <span>V: <span style={{ color: F.CYAN }}>{formatVolume(livePrice.volume)}</span></span>+ )}+ <span style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>+ <Clock size={7} />+ {new Date(livePrice.ts).toLocaleTimeString()}+ </span>+ </div>+ </>+ ) : (+ <span style={{ fontSize: '10px', color: F.MUTED, fontStyle: 'italic' }}>+ Waiting for ticks...+ </span>+ )}+ </div>+ )}++ {/* ─── METRICS ROW ─── */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(5, 1fr)',+ borderBottom: `1px solid ${F.BORDER}`,+ }}>+ {/* P&L */}+ <div style={{+ padding: '10px 14px',+ borderRight: `1px solid ${F.BORDER}`,+ backgroundColor: `${isPositive ? F.GREEN : F.RED}06`,+ }}>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED,+ letterSpacing: '0.5px', marginBottom: '4px',+ display: 'flex', alignItems: 'center', gap: '3px',+ }}>+ {isPositive ? <TrendingUp size={8} /> : <TrendingDown size={8} />}+ TOTAL P&L+ </div>+ <div style={{+ fontSize: '14px', fontWeight: 700,+ color: isPositive ? F.GREEN : F.RED,+ }}>+ {totalPnl >= 0 ? '+' : ''}{totalPnl.toFixed(2)}+ </div>+ {m.unrealized_pnl !== 0 && (+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>+ Unrealized: <span style={{ color: m.unrealized_pnl >= 0 ? F.GREEN : F.RED }}>+ {m.unrealized_pnl >= 0 ? '+' : ''}{m.unrealized_pnl.toFixed(2)}+ </span></div>+ )}+ </div>++ {/* Trades */}+ <div style={{ padding: '10px 14px', borderRight: `1px solid ${F.BORDER}` }}>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '4px',+ display: 'flex', alignItems: 'center', gap: '3px',+ }}>+ <Activity size={8} />+ TRADES+ </div>+ <div style={{ fontSize: '14px', fontWeight: 700, color: F.CYAN }}>+ {m.total_trades}</div></div>- {/* Metrics */}- <div style={{ display: 'flex', alignItems: 'center', gap: '16px', marginLeft: '12px', marginRight: '12px' }}>- <div style={{ textAlign: 'right' as const }}>- <div style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px' }}>P&L</div>- <div style={{- fontSize: '10px', fontWeight: 700, color: isPositive ? F.GREEN : F.RED,- display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '2px',- }}>- {isPositive ? <TrendingUp size={10} /> : <TrendingDown size={10} />}- {totalPnl >= 0 ? '+' : ''}{totalPnl.toFixed(2)}- </div>+ {/* Win Rate */}+ <div style={{ padding: '10px 14px', borderRight: `1px solid ${F.BORDER}` }}>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '4px',+ display: 'flex', alignItems: 'center', gap: '3px',+ }}>+ <Target size={8} />+ WIN RATE</div>- <div style={{ textAlign: 'right' as const }}>- <div style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px' }}>TRADES</div>- <div style={{ fontSize: '10px', color: F.CYAN }}>{m.total_trades}</div>+ <div style={{+ fontSize: '14px', fontWeight: 700,+ color: m.win_rate >= 50 ? F.GREEN : F.YELLOW,+ }}>+ {m.win_rate.toFixed(1)}%</div>- <div style={{ textAlign: 'right' as const }}>- <div style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px' }}>WIN%</div>- <div style={{ fontSize: '10px', color: F.WHITE }}>{m.win_rate.toFixed(1)}%</div>+ </div>++ {/* Max Drawdown */}+ <div style={{ padding: '10px 14px', borderRight: `1px solid ${F.BORDER}` }}>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '4px',+ display: 'flex', alignItems: 'center', gap: '3px',+ }}>+ <TrendingDown size={8} />+ MAX DD</div>- <div style={{ textAlign: 'right' as const }}>- <div style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px' }}>MAX DD</div>- <div style={{ fontSize: '10px', color: F.RED }}>{m.max_drawdown.toFixed(2)}</div>+ <div style={{ fontSize: '14px', fontWeight: 700, color: F.RED }}>+ {m.max_drawdown.toFixed(2)}</div></div>- {/* Actions */}+ {/* Position */}+ <div style={{ padding: '10px 14px' }}>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '4px',+ display: 'flex', alignItems: 'center', gap: '3px',+ }}>+ <BarChart3 size={8} />+ POSITION+ </div>+ {m.current_position_qty > 0 ? (+ <div style={{ fontSize: '10px', fontWeight: 700, color: F.BLUE }}>+ {m.current_position_side} {m.current_position_qty}+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '1px' }}>+ @ {m.current_position_entry.toFixed(2)}+ </div>+ </div>+ ) : (+ <div style={{ fontSize: '10px', color: F.MUTED }}>FLAT</div>+ )}+ </div>+ </div>++ {/* ─── ACTIONS ROW ─── */}+ <div style={{+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ padding: '8px 14px',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <span style={{ fontSize: '8px', color: F.MUTED }}>+ ID: <span style={{ color: F.GRAY }}>{deployment.id.substring(0, 12)}</span>+ </span>+ {m.metrics_updated && (+ <span style={{ fontSize: '8px', color: F.MUTED, display: 'flex', alignItems: 'center', gap: '3px' }}>+ <Clock size={8} />+ {new Date(m.metrics_updated).toLocaleTimeString()}+ </span>+ )}+ </div><div style={{ display: 'flex', gap: '4px' }}>{deployment.status === 'running' && (<buttononClick={handleStop}disabled={stopping}style={{- padding: '4px 8px', backgroundColor: `${F.RED}20`, color: F.RED,- border: 'none', borderRadius: '2px', fontSize: '8px', fontWeight: 700,- cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '3px',- opacity: stopping ? 0.5 : 1, transition: 'all 0.2s',+ padding: '5px 10px', backgroundColor: `${F.RED}15`, color: F.RED,+ border: `1px solid ${F.RED}30`, borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ cursor: stopping ? 'not-allowed' : 'pointer',+ display: 'flex', alignItems: 'center', gap: '4px',+ opacity: stopping ? 0.5 : 1, transition: 'all 0.2s', letterSpacing: '0.5px',}}+ onMouseEnter={e => { e.currentTarget.style.backgroundColor = `${F.RED}25`; }}+ onMouseLeave={e => { e.currentTarget.style.backgroundColor = `${F.RED}15`; }}>- <Square size={10} />- {stopping ? '...' : 'STOP'}+ <Square size={9} />+ {stopping ? 'STOPPING...' : 'STOP'}+ </button>+ )}+ {deployment.status !== 'running' && (+ <button+ onClick={handleDelete}+ disabled={deleting}+ style={{+ padding: '5px 10px', backgroundColor: 'transparent', color: F.MUTED,+ border: `1px solid ${F.BORDER}`, borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ cursor: deleting ? 'not-allowed' : 'pointer',+ display: 'flex', alignItems: 'center', gap: '4px',+ opacity: deleting ? 0.5 : 1, transition: 'all 0.2s', letterSpacing: '0.5px',+ }}+ onMouseEnter={e => { e.currentTarget.style.borderColor = F.RED; e.currentTarget.style.color = F.RED; }}+ onMouseLeave={e => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.MUTED; }}+ >+ <Trash2 size={9} />+ {deleting ? 'DELETING...' : 'DELETE'}</button>)}<buttononClick={() => setShowTrades(!showTrades)}style={{- padding: '4px 6px', backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,- color: F.GRAY, borderRadius: '2px', cursor: 'pointer', transition: 'all 0.2s',+ padding: '5px 10px', backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`, color: showTrades ? F.ORANGE : F.GRAY,+ borderRadius: '2px', cursor: 'pointer', fontSize: '8px', fontWeight: 700,+ display: 'flex', alignItems: 'center', gap: '4px',+ transition: 'all 0.2s', letterSpacing: '0.5px',+ borderColor: showTrades ? F.ORANGE : F.BORDER,+ }}+ onMouseEnter={e => { e.currentTarget.style.borderColor = F.ORANGE; e.currentTarget.style.color = F.WHITE; }}+ onMouseLeave={e => {+ e.currentTarget.style.borderColor = showTrades ? F.ORANGE : F.BORDER;+ e.currentTarget.style.color = showTrades ? F.ORANGE : F.GRAY;}}>- {showTrades ? <ChevronUp size={12} /> : <ChevronDown size={12} />}+ {showTrades ? <ChevronUp size={9} /> : <ChevronDown size={9} />}+ TRADES</button></div></div>- {/* Trade history */}+ {/* ─── TRADE HISTORY (Expanded) ─── */}{showTrades && (<div style={{ borderTop: `1px solid ${F.BORDER}` }}><TradeHistoryTable deploymentId={deployment.id} />diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/MonitorDashboard.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/MonitorDashboard.tsxindex 7eaf87431..c6d534ae9 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/MonitorDashboard.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/MonitorDashboard.tsx@@ -1,5 +1,8 @@import React, { useState, useEffect, useCallback } from 'react';-import { RefreshCw, StopCircle } from 'lucide-react';+import {+ RefreshCw, StopCircle, Activity, TrendingUp, TrendingDown,+ Target, BarChart3, Radio, Server, Clock,+} from 'lucide-react';import { listen } from '@tauri-apps/api/event';import type { AlgoDeployment } from '../types';import { listAlgoDeployments, stopAllAlgoDeployments } from '../services/algoTradingService';@@ -9,19 +12,18 @@ const F = {ORANGE: '#FF8800', WHITE: '#FFFFFF', RED: '#FF3B3B', GREEN: '#00D66F',GRAY: '#787878', DARK_BG: '#000000', PANEL_BG: '#0F0F0F',HEADER_BG: '#1A1A1A', BORDER: '#2A2A2A', MUTED: '#4A4A4A',- CYAN: '#00E5FF', YELLOW: '#FFD700',+ CYAN: '#00E5FF', YELLOW: '#FFD700', BLUE: '#0088FF', HOVER: '#1F1F1F',};const MonitorDashboard: React.FC = () => {const [deployments, setDeployments] = useState<AlgoDeployment[]>([]);const [loading, setLoading] = useState(true);const [recentEvents, setRecentEvents] = useState<{ type: string; message: string; ts: number }[]>([]);+ const [showEvents, setShowEvents] = useState(true);const loadDeployments = useCallback(async () => {const result = await listAlgoDeployments();- if (result.success && result.data) {- setDeployments(result.data);- }+ if (result.success && result.data) setDeployments(result.data);setLoading(false);}, []);@@ -31,12 +33,10 @@ const MonitorDashboard: React.FC = () => {return () => clearInterval(interval);}, [loadDeployments]);- // Listen for Tauri events from the backenduseEffect(() => {const addEvent = (type: string, message: string) => {- setRecentEvents(prev => [{ type, message, ts: Date.now() }, ...prev].slice(0, 20));+ setRecentEvents(prev => [{ type, message, ts: Date.now() }, ...prev].slice(0, 30));};-const unlisteners: (() => void)[] = [];listen<{ symbol: string; timeframe: string }>('algo_candle_closed', (event) => {@@ -63,9 +63,7 @@ const MonitorDashboard: React.FC = () => {}).then(fn => unlisteners.push(fn));- return () => {- unlisteners.forEach(fn => fn());- };+ return () => { unlisteners.forEach(fn => fn()); };}, [loadDeployments]);const handleStopAll = async () => {@@ -75,9 +73,10 @@ const MonitorDashboard: React.FC = () => {const running = deployments.filter(d => d.status === 'running');const stopped = deployments.filter(d => d.status !== 'running');-const totalPnl = deployments.reduce((acc, d) => acc + d.metrics.total_pnl + d.metrics.unrealized_pnl, 0);const totalTrades = deployments.reduce((acc, d) => acc + d.metrics.total_trades, 0);+ const avgWinRate = running.length > 0+ ? running.reduce((acc, d) => acc + d.metrics.win_rate, 0) / running.length : 0;const eventColor = (type: string): string => {if (type === 'trade') return F.GREEN;@@ -86,114 +85,318 @@ const MonitorDashboard: React.FC = () => {return F.GRAY;};+ const eventIcon = (type: string) => {+ if (type === 'trade') return <TrendingUp size={8} />;+ if (type === 'error') return <StopCircle size={8} />;+ if (type === 'signal') return <Radio size={8} />;+ return <Activity size={8} />;+ };+return (- <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '12px' }}>- {/* Header + Summary */}- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>- <span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>- DEPLOYMENTS- </span>- <div style={{ display: 'flex', gap: '12px', fontSize: '10px' }}>- <span style={{ color: F.GRAY }}>- ACTIVE: <span style={{ color: F.GREEN, fontWeight: 700 }}>{running.length}</span>- </span>- <span style={{ color: F.GRAY }}>- TOTAL P&L: <span style={{ color: totalPnl >= 0 ? F.GREEN : F.RED, fontWeight: 700 }}>- {totalPnl >= 0 ? '+' : ''}{totalPnl.toFixed(2)}- </span>- </span>- <span style={{ color: F.GRAY }}>- TRADES: <span style={{ color: F.CYAN, fontWeight: 700 }}>{totalTrades}</span>- </span>+ <div style={{+ height: '100%', display: 'flex', flexDirection: 'column',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ {/* ─── SUMMARY CARDS ─── */}+ <div style={{+ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)',+ borderBottom: `1px solid ${F.BORDER}`, flexShrink: 0,+ }}>+ {/* Active Deployments */}+ <div style={{ padding: '14px 16px', borderRight: `1px solid ${F.BORDER}` }}>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '6px',+ display: 'flex', alignItems: 'center', gap: '4px',+ }}>+ <Server size={8} />+ ACTIVE+ </div>+ <div style={{ fontSize: '20px', fontWeight: 700, color: running.length > 0 ? F.GREEN : F.MUTED }}>+ {running.length}+ </div>+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>+ of {deployments.length} total+ </div>+ </div>++ {/* Total P&L */}+ <div style={{+ padding: '14px 16px', borderRight: `1px solid ${F.BORDER}`,+ backgroundColor: `${totalPnl >= 0 ? F.GREEN : F.RED}04`,+ }}>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '6px',+ display: 'flex', alignItems: 'center', gap: '4px',+ }}>+ {totalPnl >= 0 ? <TrendingUp size={8} /> : <TrendingDown size={8} />}+ TOTAL P&L+ </div>+ <div style={{+ fontSize: '20px', fontWeight: 700,+ color: totalPnl >= 0 ? F.GREEN : F.RED,+ }}>+ {totalPnl >= 0 ? '+' : ''}{totalPnl.toFixed(2)}</div></div>- <div style={{ display: 'flex', gap: '6px' }}>- <button- onClick={loadDeployments}- style={{- padding: '6px', backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,- color: F.GRAY, cursor: 'pointer', borderRadius: '2px', transition: 'all 0.2s',- }}- >- <RefreshCw size={12} />- </button>- {running.length > 0 && (- <button- onClick={handleStopAll}- style={{- padding: '4px 10px', backgroundColor: `${F.RED}20`, color: F.RED,- border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700,- cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '4px',- transition: 'all 0.2s',- }}- >- <StopCircle size={12} />- STOP ALL- </button>- )}++ {/* Total Trades */}+ <div style={{ padding: '14px 16px', borderRight: `1px solid ${F.BORDER}` }}>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '6px',+ display: 'flex', alignItems: 'center', gap: '4px',+ }}>+ <Activity size={8} />+ TOTAL TRADES+ </div>+ <div style={{ fontSize: '20px', fontWeight: 700, color: F.CYAN }}>+ {totalTrades}+ </div>+ </div>++ {/* Avg Win Rate */}+ <div style={{ padding: '14px 16px', borderRight: `1px solid ${F.BORDER}` }}>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '6px',+ display: 'flex', alignItems: 'center', gap: '4px',+ }}>+ <Target size={8} />+ AVG WIN RATE+ </div>+ <div style={{+ fontSize: '20px', fontWeight: 700,+ color: avgWinRate >= 50 ? F.GREEN : avgWinRate > 0 ? F.YELLOW : F.MUTED,+ }}>+ {avgWinRate > 0 ? `${avgWinRate.toFixed(1)}%` : '—'}+ </div></div>- </div>- {loading ? (- <div style={{ textAlign: 'center', padding: '32px', fontSize: '10px', color: F.MUTED }}>- Loading deployments...+ {/* Events */}+ <div style={{ padding: '14px 16px' }}>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '6px',+ display: 'flex', alignItems: 'center', gap: '4px',+ }}>+ <Radio size={8} />+ EVENTS+ </div>+ <div style={{ fontSize: '20px', fontWeight: 700, color: F.YELLOW }}>+ {recentEvents.length}+ </div>+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>+ recent signals+ </div></div>- ) : deployments.length === 0 ? (+ </div>++ {/* ─── MAIN AREA: Two-panel split ─── */}+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden', minHeight: 0 }}>+ {/* LEFT: Deployment Cards */}<div style={{- display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',- height: '200px', color: F.MUTED, fontSize: '10px', textAlign: 'center',+ flex: 1, overflowY: 'auto', minWidth: 0,+ borderRight: `1px solid ${F.BORDER}`,}}>- <span>No deployments yet</span>- <span style={{ fontSize: '9px', color: F.MUTED, marginTop: '4px' }}>- Create a strategy and deploy it to see it here- </span>- </div>- ) : (- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>- {running.map(d => (- <DeploymentCard key={d.id} deployment={d} onStopped={loadDeployments} />- ))}- {stopped.length > 0 && running.length > 0 && (- <div style={{- fontSize: '9px', color: F.MUTED, letterSpacing: '0.5px',- fontWeight: 700, paddingTop: '8px',- }}>- HISTORY+ {/* Toolbar */}+ <div style={{+ padding: '10px 16px', backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ position: 'sticky', top: 0, zIndex: 1,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <BarChart3 size={10} color={F.ORANGE} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>+ DEPLOYMENTS+ </span>+ </div>+ <div style={{ display: 'flex', gap: '4px' }}>+ <button+ onClick={loadDeployments}+ style={{+ padding: '4px 8px', backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`, color: F.GRAY,+ cursor: 'pointer', borderRadius: '2px', transition: 'all 0.2s',+ display: 'flex', alignItems: 'center', gap: '4px',+ fontSize: '8px', fontWeight: 700, letterSpacing: '0.5px',+ }}+ onMouseEnter={e => { e.currentTarget.style.borderColor = F.ORANGE; e.currentTarget.style.color = F.WHITE; }}+ onMouseLeave={e => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.GRAY; }}+ >+ <RefreshCw size={9} />+ REFRESH+ </button>+ {running.length > 0 && (+ <button+ onClick={handleStopAll}+ style={{+ padding: '4px 10px', backgroundColor: `${F.RED}15`,+ border: `1px solid ${F.RED}30`, color: F.RED,+ borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '4px',+ transition: 'all 0.2s', letterSpacing: '0.5px',+ }}+ onMouseEnter={e => { e.currentTarget.style.backgroundColor = `${F.RED}25`; }}+ onMouseLeave={e => { e.currentTarget.style.backgroundColor = `${F.RED}15`; }}+ >+ <StopCircle size={9} />+ STOP ALL+ </button>+ )}</div>- )}- {stopped.map(d => (- <DeploymentCard key={d.id} deployment={d} onStopped={loadDeployments} />- ))}+ </div>++ {/* Deployment List */}+ <div style={{ padding: '12px 16px' }}>+ {loading ? (+ <div style={{+ textAlign: 'center', padding: '48px', fontSize: '10px', color: F.MUTED,+ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '8px',+ }}>+ <RefreshCw size={16} className="animate-spin" color={F.ORANGE} />+ <span style={{ fontWeight: 700, letterSpacing: '0.5px' }}>LOADING DEPLOYMENTS...</span>+ </div>+ ) : deployments.length === 0 ? (+ <div style={{+ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',+ padding: '48px', color: F.MUTED, textAlign: 'center',+ }}>+ <Server size={24} style={{ opacity: 0.3, marginBottom: '8px' }} />+ <span style={{ fontSize: '10px', fontWeight: 700 }}>NO DEPLOYMENTS</span>+ <span style={{ fontSize: '9px', marginTop: '4px' }}>+ Create a strategy and deploy it to see it here+ </span>+ </div>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ {running.length > 0 && (+ <>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.GREEN,+ letterSpacing: '0.5px', display: 'flex', alignItems: 'center', gap: '4px',+ }}>+ <div style={{+ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: F.GREEN,+ }} />+ RUNNING ({running.length})+ </div>+ {running.map(d => (+ <DeploymentCard key={d.id} deployment={d} onStopped={loadDeployments} />+ ))}+ </>+ )}+ {stopped.length > 0 && (+ <>+ <div style={{+ fontSize: '8px', fontWeight: 700, color: F.MUTED,+ letterSpacing: '0.5px', paddingTop: running.length > 0 ? '8px' : '0',+ borderTop: running.length > 0 ? `1px solid ${F.BORDER}` : 'none',+ marginTop: running.length > 0 ? '4px' : '0',+ }}>+ HISTORY ({stopped.length})+ </div>+ {stopped.map(d => (+ <DeploymentCard key={d.id} deployment={d} onStopped={loadDeployments} />+ ))}+ </>+ )}+ </div>+ )}+ </div></div>- )}- {/* Recent Events */}- {recentEvents.length > 0 && (+ {/* RIGHT: Event Log Panel */}<div style={{- backgroundColor: F.PANEL_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ width: '320px', flexShrink: 0,+ display: 'flex', flexDirection: 'column',+ backgroundColor: F.PANEL_BG,}}>+ {/* Event Log Header */}<div style={{- padding: '6px 12px', backgroundColor: F.HEADER_BG,+ padding: '10px 12px', backgroundColor: F.HEADER_BG,borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',}}>- <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>- RECENT EVENTS- </span>- </div>- <div style={{ padding: '6px 12px', maxHeight: '120px', overflowY: 'auto' }}>- {recentEvents.map((evt, i) => (- <div key={i} style={{- display: 'flex', gap: '8px', fontSize: '9px', padding: '2px 0',- fontFamily: '"IBM Plex Mono", monospace',+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <Radio size={10} color={F.YELLOW} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>+ EVENT LOG+ </span>+ {recentEvents.length > 0 && (+ <span style={{+ padding: '1px 5px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: `${F.YELLOW}20`, color: F.YELLOW,+ }}>+ {recentEvents.length}+ </span>+ )}+ </div>+ {recentEvents.length > 0 && (+ <button+ onClick={() => setRecentEvents([])}+ style={{+ padding: '2px 8px', backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`, color: F.MUTED,+ borderRadius: '2px', cursor: 'pointer', fontSize: '8px', fontWeight: 700,+ letterSpacing: '0.5px',+ }}+ onMouseEnter={e => { e.currentTarget.style.color = F.WHITE; e.currentTarget.style.borderColor = F.ORANGE; }}+ onMouseLeave={e => { e.currentTarget.style.color = F.MUTED; e.currentTarget.style.borderColor = F.BORDER; }}+ >+ CLEAR+ </button>+ )}+ </div>++ {/* Event Entries */}+ <div style={{ flex: 1, overflowY: 'auto', padding: '4px 0' }}>+ {recentEvents.length === 0 ? (+ <div style={{+ padding: '32px 16px', textAlign: 'center',+ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '6px',}}>- <span style={{ color: F.MUTED }}>{new Date(evt.ts).toLocaleTimeString()}</span>- <span style={{ color: eventColor(evt.type) }}>{evt.message}</span>+ <Radio size={16} color={F.MUTED} style={{ opacity: 0.3 }} />+ <span style={{ fontSize: '9px', color: F.MUTED, fontWeight: 700 }}>+ NO EVENTS YET+ </span>+ <span style={{ fontSize: '8px', color: F.MUTED }}>+ Events will appear here when strategies are running+ </span></div>- ))}+ ) : (+ recentEvents.map((evt, i) => (+ <div+ key={i}+ style={{+ display: 'flex', gap: '8px', padding: '6px 12px',+ borderBottom: `1px solid ${F.BORDER}15`,+ transition: 'background-color 0.15s',+ }}+ onMouseEnter={e => { e.currentTarget.style.backgroundColor = F.HOVER; }}+ onMouseLeave={e => { e.currentTarget.style.backgroundColor = 'transparent'; }}+ >+ <div style={{ color: eventColor(evt.type), flexShrink: 0, paddingTop: '1px' }}>+ {eventIcon(evt.type)}+ </div>+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{+ fontSize: '9px', color: eventColor(evt.type),+ lineHeight: '1.4', wordBreak: 'break-word',+ }}>+ {evt.message}+ </div>+ <div style={{+ fontSize: '8px', color: F.MUTED, marginTop: '1px',+ display: 'flex', alignItems: 'center', gap: '3px',+ }}>+ <Clock size={7} />+ {new Date(evt.ts).toLocaleTimeString()}+ </div>+ </div>+ </div>+ ))+ )}</div></div>- )}+ </div></div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ParameterEditor.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ParameterEditor.tsxindex 181dbec91..4dc827e1a 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ParameterEditor.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ParameterEditor.tsx@@ -1,23 +1,20 @@import React, { useState, useEffect } from 'react';-import { Settings, Loader2, AlertCircle, RefreshCw } from 'lucide-react';+import { Settings, Loader2, AlertCircle, RefreshCw, Code, Hash, ToggleLeft, Type } from 'lucide-react';import type { StrategyParameter } from '../types';import { extractStrategyParameters } from '../services/algoTradingService';const F = {- ORANGE: '#FF8800',- WHITE: '#FFFFFF',- RED: '#FF3B3B',- GREEN: '#00D66F',- GRAY: '#787878',- DARK_BG: '#000000',- PANEL_BG: '#0F0F0F',- HEADER_BG: '#1A1A1A',- BORDER: '#2A2A2A',- HOVER: '#1F1F1F',- MUTED: '#4A4A4A',- CYAN: '#00E5FF',- YELLOW: '#FFD700',- BLUE: '#0088FF',+ ORANGE: '#FF8800', WHITE: '#FFFFFF', RED: '#FF3B3B', GREEN: '#00D66F',+ GRAY: '#787878', DARK_BG: '#000000', PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A', BORDER: '#2A2A2A', HOVER: '#1F1F1F',+ MUTED: '#4A4A4A', CYAN: '#00E5FF', YELLOW: '#FFD700', BLUE: '#0088FF',+};++const inputBaseStyle: React.CSSProperties = {+ width: '100%', padding: '8px 10px', backgroundColor: F.DARK_BG,+ color: F.WHITE, border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ fontSize: '10px', fontFamily: '"IBM Plex Mono", monospace', outline: 'none',+ transition: 'border-color 0.2s',};interface ParameterEditorProps {@@ -39,33 +36,24 @@ const ParameterEditor: React.FC<ParameterEditorProps> = ({const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);- // Extract parameters from code if not provideduseEffect(() => {if (providedParameters) {setParameters(providedParameters);return;}-- if (code) {- extractParametersFromCode(code);- }+ if (code) extractParametersFromCode(code);}, [code, providedParameters]);const extractParametersFromCode = async (sourceCode: string) => {setLoading(true);setError(null);-try {const result = await extractStrategyParameters(sourceCode);if (result.success && result.data) {setParameters(result.data);-- // Initialize default values if not already setconst newValues = { ...values };result.data.forEach((param) => {- if (!(param.name in newValues)) {- newValues[param.name] = param.default_value;- }+ if (!(param.name in newValues)) newValues[param.name] = param.default_value;});onChange(newValues);} else {@@ -84,125 +72,110 @@ const ParameterEditor: React.FC<ParameterEditorProps> = ({const handleReset = () => {const defaultValues: Record<string, string> = {};- parameters.forEach((param) => {- defaultValues[param.name] = param.default_value;- });+ parameters.forEach((param) => { defaultValues[param.name] = param.default_value; });onChange(defaultValues);};if (loading) {return (- <div- style={{- padding: '16px',- display: 'flex',- alignItems: 'center',- gap: '8px',- color: F.GRAY,- fontSize: '11px',- }}- >- <Loader2 size={14} style={{ animation: 'spin 1s linear infinite' }} />- Extracting parameters...- <style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>+ <div style={{+ padding: '24px', display: 'flex', flexDirection: 'column',+ alignItems: 'center', gap: '8px', color: F.GRAY,+ }}>+ <Loader2 size={18} className="animate-spin" style={{ color: F.ORANGE }} />+ <span style={{ fontSize: '10px', fontWeight: 700, letterSpacing: '0.5px' }}>+ EXTRACTING PARAMETERS...+ </span></div>);}if (error) {return (- <div- style={{- padding: '12px',- backgroundColor: `${F.RED}20`,- border: `1px solid ${F.RED}`,- borderRadius: '4px',- display: 'flex',- alignItems: 'center',- gap: '8px',- color: F.RED,- fontSize: '11px',- }}- >- <AlertCircle size={14} />- {error}+ <div style={{+ padding: '12px', backgroundColor: `${F.RED}15`,+ border: `1px solid ${F.RED}40`, borderRadius: '2px',+ display: 'flex', alignItems: 'center', gap: '8px',+ }}>+ <AlertCircle size={12} color={F.RED} />+ <span style={{ fontSize: '9px', color: F.RED, fontWeight: 700 }}>{error}</span></div>);}if (parameters.length === 0) {return (- <div- style={{- padding: '16px',- textAlign: 'center',- color: F.GRAY,- fontSize: '11px',- }}- >- No configurable parameters found+ <div style={{+ padding: '24px', textAlign: 'center',+ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '6px',+ }}>+ <Code size={18} color={F.MUTED} style={{ opacity: 0.5 }} />+ <span style={{ fontSize: '9px', color: F.MUTED, fontWeight: 700 }}>+ NO CONFIGURABLE PARAMETERS+ </span></div>);}return (- <div- style={{- backgroundColor: F.PANEL_BG,- borderRadius: '4px',- border: `1px solid ${F.BORDER}`,- overflow: 'hidden',- }}- >+ <div style={{+ backgroundColor: F.PANEL_BG, borderRadius: '2px',+ border: `1px solid ${F.BORDER}`, overflow: 'hidden',+ }}>{/* Header */}- <div- style={{- padding: '10px 12px',- borderBottom: `1px solid ${F.BORDER}`,- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- backgroundColor: F.HEADER_BG,- }}- >- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>- <Settings size={12} style={{ color: F.ORANGE }} />- <span style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE }}>+ <div style={{+ padding: '10px 12px', borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ backgroundColor: F.HEADER_BG,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Settings size={12} color={F.ORANGE} />+ <span style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>STRATEGY PARAMETERS</span>- <span style={{ fontSize: '9px', color: F.GRAY }}>({parameters.length})</span>+ <span style={{+ padding: '2px 6px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: `${F.ORANGE}20`, color: F.ORANGE,+ }}>+ {parameters.length}+ </span></div><buttononClick={handleReset}disabled={disabled}style={{- padding: '4px 8px',- backgroundColor: 'transparent',- border: `1px solid ${F.BORDER}`,- borderRadius: '2px',- color: F.GRAY,- fontSize: '9px',+ padding: '4px 10px', backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ color: F.GRAY, fontSize: '8px', fontWeight: 700, letterSpacing: '0.5px',cursor: disabled ? 'not-allowed' : 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px',- opacity: disabled ? 0.5 : 1,+ display: 'flex', alignItems: 'center', gap: '4px',+ opacity: disabled ? 0.5 : 1, transition: 'all 0.2s',+ }}+ onMouseEnter={e => {+ if (!disabled) {+ e.currentTarget.style.borderColor = F.ORANGE;+ e.currentTarget.style.color = F.WHITE;+ }+ }}+ onMouseLeave={e => {+ if (!disabled) {+ e.currentTarget.style.borderColor = F.BORDER;+ e.currentTarget.style.color = F.GRAY;+ }}}>- <RefreshCw size={10} />- RESET+ <RefreshCw size={9} />+ RESET DEFAULTS</button></div>{/* Parameters Grid */}- <div- style={{- padding: '12px',- display: 'grid',- gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))',- gap: '12px',- }}- >+ <div style={{+ padding: '12px',+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',+ gap: '10px',+ }}>{parameters.map((param) => (<ParameterInputkey={param.name}@@ -217,6 +190,21 @@ const ParameterEditor: React.FC<ParameterEditorProps> = ({);};+// Type icon mapping+const TYPE_ICONS: Record<string, React.ElementType> = {+ 'int': Hash,+ 'float': Hash,+ 'bool': ToggleLeft,+ 'string': Type,+};++const TYPE_COLORS: Record<string, string> = {+ 'int': F.CYAN,+ 'float': F.BLUE,+ 'bool': F.GREEN,+ 'string': F.YELLOW,+};+// Parameter Input Componentconst ParameterInput: React.FC<{parameter: StrategyParameter;@@ -224,7 +212,12 @@ const ParameterInput: React.FC<{onChange: (value: string) => void;disabled?: boolean;}> = ({ parameter, value, onChange, disabled }) => {+ const TypeIcon = TYPE_ICONS[parameter.type] || Code;+ const typeColor = TYPE_COLORS[parameter.type] || F.GRAY;+const renderInput = () => {+ const baseStyle = { ...inputBaseStyle, cursor: disabled ? 'not-allowed' : undefined };+switch (parameter.type) {case 'bool':return (@@ -232,124 +225,88 @@ const ParameterInput: React.FC<{value={value}onChange={(e) => onChange(e.target.value)}disabled={disabled}- style={{- width: '100%',- padding: '8px',- backgroundColor: F.DARK_BG,- border: `1px solid ${F.BORDER}`,- borderRadius: '4px',- color: F.WHITE,- fontSize: '11px',- cursor: disabled ? 'not-allowed' : 'pointer',- }}+ style={{ ...baseStyle, color: value === 'true' ? F.GREEN : F.RED }}><option value="true">True</option><option value="false">False</option></select>);-case 'int':return (<input- type="number"- value={value}+ type="number" value={value}onChange={(e) => onChange(e.target.value)}disabled={disabled}- min={parameter.min}- max={parameter.max}- step={1}- style={{- width: '100%',- padding: '8px',- backgroundColor: F.DARK_BG,- border: `1px solid ${F.BORDER}`,- borderRadius: '4px',- color: F.WHITE,- fontSize: '11px',- }}+ min={parameter.min} max={parameter.max} step={1}+ style={{ ...baseStyle, color: F.CYAN }}+ onFocus={e => { e.currentTarget.style.borderColor = F.ORANGE; }}+ onBlur={e => { e.currentTarget.style.borderColor = F.BORDER; }}/>);-case 'float':return (<input- type="number"- value={value}+ type="number" value={value}onChange={(e) => onChange(e.target.value)}disabled={disabled}- min={parameter.min}- max={parameter.max}- step={0.01}- style={{- width: '100%',- padding: '8px',- backgroundColor: F.DARK_BG,- border: `1px solid ${F.BORDER}`,- borderRadius: '4px',- color: F.WHITE,- fontSize: '11px',- }}+ min={parameter.min} max={parameter.max} step={0.01}+ style={{ ...baseStyle, color: F.BLUE }}+ onFocus={e => { e.currentTarget.style.borderColor = F.ORANGE; }}+ onBlur={e => { e.currentTarget.style.borderColor = F.BORDER; }}/>);-default:return (<input- type="text"- value={value}+ type="text" value={value}onChange={(e) => onChange(e.target.value)}disabled={disabled}- style={{- width: '100%',- padding: '8px',- backgroundColor: F.DARK_BG,- border: `1px solid ${F.BORDER}`,- borderRadius: '4px',- color: F.WHITE,- fontSize: '11px',- }}+ style={baseStyle}+ onFocus={e => { e.currentTarget.style.borderColor = F.ORANGE; }}+ onBlur={e => { e.currentTarget.style.borderColor = F.BORDER; }}/>);}};return (- <div>- <div- style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- marginBottom: '4px',- }}- >- <label style={{ fontSize: '10px', color: F.GRAY, fontWeight: 600 }}>- {parameter.name}+ <div style={{+ backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', padding: '10px', transition: 'border-color 0.2s',+ }}>+ <div style={{+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ marginBottom: '6px',+ }}>+ <label style={{+ fontSize: '9px', fontWeight: 700, color: F.GRAY,+ letterSpacing: '0.5px', display: 'flex', alignItems: 'center', gap: '4px',+ }}>+ {parameter.name.toUpperCase()}</label>- <span- style={{- fontSize: '8px',- padding: '2px 4px',- backgroundColor: F.HOVER,- color: F.CYAN,- borderRadius: '2px',- }}- >- {parameter.type}+ <span style={{+ fontSize: '8px', padding: '2px 6px',+ backgroundColor: `${typeColor}15`, color: typeColor,+ borderRadius: '2px', fontWeight: 700, letterSpacing: '0.5px',+ display: 'flex', alignItems: 'center', gap: '3px',+ }}>+ <TypeIcon size={8} />+ {parameter.type.toUpperCase()}</span></div>{renderInput()}{parameter.description && (- <div- style={{- fontSize: '9px',- color: F.MUTED,- marginTop: '4px',- }}- >+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '4px', lineHeight: '1.4' }}>{parameter.description}</div>)}+ {(parameter.min !== undefined || parameter.max !== undefined) && (+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>+ {parameter.min !== undefined && `Min: ${parameter.min}`}+ {parameter.min !== undefined && parameter.max !== undefined && ' | '}+ {parameter.max !== undefined && `Max: ${parameter.max}`}+ </div>+ )}</div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonBacktestPanel.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonBacktestPanel.tsxindex ee23c7095..434324233 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonBacktestPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonBacktestPanel.tsx@@ -130,7 +130,7 @@ const PythonBacktestPanel: React.FC<PythonBacktestPanelProps> = ({ strategy, onCmaxHeight: '90vh',backgroundColor: F.PANEL_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '8px',+ borderRadius: '2px',display: 'flex',flexDirection: 'column',overflow: 'hidden',@@ -195,7 +195,7 @@ const PythonBacktestPanel: React.FC<PythonBacktestPanelProps> = ({ strategy, onCpadding: '8px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '11px',}}@@ -217,7 +217,7 @@ const PythonBacktestPanel: React.FC<PythonBacktestPanelProps> = ({ strategy, onCpadding: '8px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '11px',}}@@ -238,7 +238,7 @@ const PythonBacktestPanel: React.FC<PythonBacktestPanelProps> = ({ strategy, onCpadding: '8px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '11px',}}@@ -259,7 +259,7 @@ const PythonBacktestPanel: React.FC<PythonBacktestPanelProps> = ({ strategy, onCpadding: '8px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '11px',}}@@ -281,7 +281,7 @@ const PythonBacktestPanel: React.FC<PythonBacktestPanelProps> = ({ strategy, onCpadding: '8px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '11px',}}@@ -302,7 +302,7 @@ const PythonBacktestPanel: React.FC<PythonBacktestPanelProps> = ({ strategy, onCbackgroundColor: loading ? F.GRAY : F.ORANGE,color: F.DARK_BG,border: 'none',- borderRadius: '4px',+ borderRadius: '2px',fontSize: '11px',fontWeight: 700,cursor: loading ? 'not-allowed' : 'pointer',@@ -336,7 +336,7 @@ const PythonBacktestPanel: React.FC<PythonBacktestPanelProps> = ({ strategy, onCpadding: '10px 12px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.GRAY,fontSize: '10px',cursor: 'pointer',@@ -372,7 +372,7 @@ const PythonBacktestPanel: React.FC<PythonBacktestPanelProps> = ({ strategy, onCpadding: '12px',backgroundColor: `${F.RED}20`,border: `1px solid ${F.RED}`,- borderRadius: '4px',+ borderRadius: '2px',marginBottom: '16px',display: 'flex',alignItems: 'center',@@ -452,7 +452,7 @@ const PythonBacktestPanel: React.FC<PythonBacktestPanelProps> = ({ strategy, onCmarginBottom: '16px',padding: '12px',backgroundColor: F.DARK_BG,- borderRadius: '4px',+ borderRadius: '2px',border: `1px solid ${F.BORDER}`,}}>@@ -469,7 +469,7 @@ const PythonBacktestPanel: React.FC<PythonBacktestPanelProps> = ({ strategy, onCstyle={{padding: '12px',backgroundColor: F.DARK_BG,- borderRadius: '4px',+ borderRadius: '2px',border: `1px solid ${F.BORDER}`,}}>@@ -546,7 +546,7 @@ const MetricCard: React.FC<{style={{padding: '12px',backgroundColor: F.DARK_BG,- borderRadius: '4px',+ borderRadius: '2px',border: `1px solid ${F.BORDER}`,}}>diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonDeployPanel.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonDeployPanel.tsxindex 16957940a..7f8f7c972 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonDeployPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonDeployPanel.tsx@@ -9,6 +9,7 @@ import {getPythonStrategyCode,} from '../services/algoTradingService';import { invoke } from '@tauri-apps/api/core';+import { useStockBrokerContextOptional } from '@/contexts/StockBrokerContext';import ParameterEditor from './ParameterEditor';const F = {@@ -51,8 +52,18 @@ interface DeployConfig {const BROKERS = [{ id: 'simulator', label: 'Simulator', live: false },+ { id: 'angelone', label: 'Angel One', live: true },{ id: 'fyers', label: 'Fyers', live: true },{ id: 'zerodha', label: 'Zerodha', live: true },+ { id: 'upstox', label: 'Upstox', live: true },+ { id: 'dhan', label: 'Dhan', live: true },+ { id: 'kotak', label: 'Kotak Neo', live: true },+ { id: 'groww', label: 'Groww', live: true },+ { id: 'aliceblue', label: 'AliceBlue', live: true },+ { id: '5paisa', label: '5Paisa', live: true },+ { id: 'iifl', label: 'IIFL', live: true },+ { id: 'motilal', label: 'Motilal Oswal', live: true },+ { id: 'shoonya', label: 'Shoonya (Finvasia)', live: true },{ id: 'kraken', label: 'Kraken (Crypto)', live: true },];@@ -192,6 +203,13 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({if (parsed.success) {setSuccess(`Strategy deployed successfully! Deployment ID: ${parsed.deploy_id}`);onDeployed?.(parsed.deploy_id);+ // Ensure WebSocket subscription for stock brokers so ticks reach candle aggregator+ const sym = config.symbol.toUpperCase();+ if (config.broker !== 'kraken' && config.broker !== 'simulator') {+ invoke('angelone_ws_subscribe', {+ symbol: `NSE:${sym}`, mode: 'ltp', symbolName: sym,+ }).catch(() => {});+ }// Auto-close after successsetTimeout(() => {onClose();@@ -243,7 +261,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({maxHeight: '90vh',backgroundColor: F.PANEL_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',overflow: 'hidden',display: 'flex',flexDirection: 'column',@@ -261,13 +279,19 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({}}><div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <Rocket size={18} style={{ color: F.ORANGE }} />+ <div style={{+ width: '28px', height: '28px', borderRadius: '2px',+ backgroundColor: `${F.ORANGE}15`, display: 'flex',+ alignItems: 'center', justifyContent: 'center',+ }}>+ <Rocket size={14} color={F.ORANGE} />+ </div><div>- <div style={{ fontSize: '12px', fontWeight: 700, color: F.WHITE }}>+ <div style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>DEPLOY PYTHON STRATEGY</div>- <div style={{ fontSize: '10px', color: F.GRAY }}>- {strategy.name} • {strategy.id}+ <div style={{ fontSize: '9px', color: F.MUTED, marginTop: '2px' }}>+ {strategy.name.toUpperCase()} • {strategy.id}</div></div></div>@@ -290,7 +314,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({<div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>{/* Mode Selection */}<div style={{ marginBottom: '16px' }}>- <label style={{ fontSize: '10px', fontWeight: 700, color: F.GRAY, marginBottom: '8px', display: 'block' }}>+ <label style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '8px', display: 'block' }}>TRADING MODE</label><div style={{ display: 'flex', gap: '8px' }}>@@ -303,7 +327,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '12px',backgroundColor: config.mode === mode ? (mode === 'live' ? `${F.RED}20` : `${F.GREEN}20`) : 'transparent',border: `1px solid ${config.mode === mode ? (mode === 'live' ? F.RED : F.GREEN) : F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: config.mode === mode ? (mode === 'live' ? F.RED : F.GREEN) : F.GRAY,fontSize: '11px',fontWeight: 700,@@ -329,7 +353,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>{/* Symbol */}<div>- <label style={{ fontSize: '10px', fontWeight: 700, color: F.GRAY, marginBottom: '4px', display: 'block' }}>+ <label style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '4px', display: 'block' }}>SYMBOL *</label><div style={{ position: 'relative' }}>@@ -343,7 +367,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '10px',backgroundColor: F.DARK_BG,border: `1px solid ${isDuplicate ? F.YELLOW : F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '11px',}}@@ -371,7 +395,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({{/* Broker */}<div>- <label style={{ fontSize: '10px', fontWeight: 700, color: F.GRAY, marginBottom: '4px', display: 'block' }}>+ <label style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '4px', display: 'block' }}>BROKER</label><select@@ -382,7 +406,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '10px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '11px',}}@@ -397,7 +421,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({{/* Quantity */}<div>- <label style={{ fontSize: '10px', fontWeight: 700, color: F.GRAY, marginBottom: '4px', display: 'block' }}>+ <label style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '4px', display: 'block' }}>QUANTITY</label><input@@ -411,7 +435,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '10px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '11px',}}@@ -420,7 +444,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({{/* Timeframe */}<div>- <label style={{ fontSize: '10px', fontWeight: 700, color: F.GRAY, marginBottom: '4px', display: 'block' }}>+ <label style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '4px', display: 'block' }}>TIMEFRAME</label><select@@ -431,7 +455,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '10px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '11px',}}@@ -446,7 +470,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({{/* Initial Cash */}<div>- <label style={{ fontSize: '10px', fontWeight: 700, color: F.GRAY, marginBottom: '4px', display: 'block' }}>+ <label style={{ fontSize: '8px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '4px', display: 'block' }}>INITIAL CASH</label><input@@ -460,7 +484,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '10px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '11px',}}@@ -474,7 +498,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({style={{marginBottom: '16px',border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',overflow: 'hidden',}}>@@ -491,7 +515,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({>{showRisk ? <ChevronDown size={12} /> : <ChevronRight size={12} />}<Shield size={12} style={{ color: F.CYAN }} />- <span style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE }}>+ <span style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>RISK MANAGEMENT</span><span style={{ fontSize: '9px', color: F.MUTED }}>(Optional)</span>@@ -515,7 +539,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '8px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '10px',}}@@ -537,7 +561,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '8px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '10px',}}@@ -559,7 +583,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '8px',backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,fontSize: '10px',}}@@ -576,7 +600,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({style={{marginBottom: '16px',border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',overflow: 'hidden',}}>@@ -593,7 +617,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({>{showParams ? <ChevronDown size={12} /> : <ChevronRight size={12} />}<Settings size={12} style={{ color: F.PURPLE }} />- <span style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE }}>+ <span style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>STRATEGY PARAMETERS</span></div>@@ -616,7 +640,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '10px 12px',backgroundColor: `${F.RED}20`,border: `1px solid ${F.RED}`,- borderRadius: '4px',+ borderRadius: '2px',marginBottom: '16px',display: 'flex',alignItems: 'center',@@ -636,7 +660,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '10px 12px',backgroundColor: `${F.GREEN}20`,border: `1px solid ${F.GREEN}`,- borderRadius: '4px',+ borderRadius: '2px',marginBottom: '16px',display: 'flex',alignItems: 'center',@@ -657,7 +681,7 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '10px 12px',backgroundColor: `${F.YELLOW}10`,border: `1px solid ${F.YELLOW}`,- borderRadius: '4px',+ borderRadius: '2px',marginBottom: '16px',display: 'flex',alignItems: 'flex-start',@@ -693,12 +717,16 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '10px 20px',backgroundColor: 'transparent',border: `1px solid ${F.BORDER}`,- borderRadius: '4px',+ borderRadius: '2px',color: F.GRAY,- fontSize: '10px',+ fontSize: '9px',fontWeight: 700,cursor: 'pointer',+ letterSpacing: '0.5px',+ transition: 'all 0.2s',}}+ onMouseEnter={e => { e.currentTarget.style.borderColor = F.ORANGE; e.currentTarget.style.color = F.WHITE; }}+ onMouseLeave={e => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.GRAY; }}>CANCEL</button>@@ -709,10 +737,11 @@ const PythonDeployPanel: React.FC<PythonDeployPanelProps> = ({padding: '10px 24px',backgroundColor: config.mode === 'live' ? F.RED : F.GREEN,border: 'none',- borderRadius: '4px',+ borderRadius: '2px',color: F.WHITE,- fontSize: '10px',+ fontSize: '9px',fontWeight: 700,+ letterSpacing: '0.5px',cursor: deploying || !config.symbol.trim() ? 'not-allowed' : 'pointer',opacity: deploying || !config.symbol.trim() ? 0.5 : 1,display: 'flex',diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyEditor.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyEditor.tsxindex c23f51979..8c140aad6 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyEditor.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyEditor.tsx@@ -1,5 +1,9 @@import React, { useState, useEffect } from 'react';-import { Save, Play, Loader, ArrowLeft } from 'lucide-react';+import {+ Save, Play, Loader, ArrowLeft, Shield, AlertTriangle, ChevronDown, ChevronRight,+ Target, TrendingUp, TrendingDown, BarChart3, Clock, Percent, Activity,+ ArrowUpRight, ArrowDownRight, Hash,+} from 'lucide-react';import type { ConditionItem } from '../types';import { TIMEFRAMES } from '../constants/indicators';import { saveAlgoStrategy, getAlgoStrategy, runAlgoBacktest } from '../services/algoTradingService';@@ -10,6 +14,7 @@ const F = {GRAY: '#787878', DARK_BG: '#000000', PANEL_BG: '#0F0F0F',HEADER_BG: '#1A1A1A', BORDER: '#2A2A2A', HOVER: '#1F1F1F',MUTED: '#4A4A4A', CYAN: '#00E5FF', YELLOW: '#FFD700', PURPLE: '#9D4EDD',+ BLUE: '#0088FF',};interface StrategyEditorProps {@@ -41,6 +46,21 @@ const labelStyle: React.CSSProperties = {marginBottom: '4px', display: 'block',};+const sectionStyle: React.CSSProperties = {+ backgroundColor: F.PANEL_BG,+ border: `1px solid ${F.BORDER}`,+ borderRadius: '2px',+};++const sectionHeaderStyle: React.CSSProperties = {+ padding: '10px 16px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+};+const StrategyEditor: React.FC<StrategyEditorProps> = ({ editStrategyId, onSaved, onCancel }) => {const [name, setName] = useState('');const [description, setDescription] = useState('');@@ -67,6 +87,7 @@ const StrategyEditor: React.FC<StrategyEditorProps> = ({ editStrategyId, onSavedconst [btError, setBtError] = useState('');const [btDebug, setBtDebug] = useState<string[]>([]);const [showDebug, setShowDebug] = useState(false);+ const [showBacktest, setShowBacktest] = useState(true);useEffect(() => {if (editStrategyId) loadStrategy(editStrategyId);@@ -134,7 +155,6 @@ const StrategyEditor: React.FC<StrategyEditorProps> = ({ editStrategyId, onSaved});setBacktesting(false);- // Capture debug info from responseif (res.debug) {setBtDebug(res.debug);} else if (res.data?.debug) {@@ -150,289 +170,524 @@ const StrategyEditor: React.FC<StrategyEditorProps> = ({ editStrategyId, onSaved};return (- <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '12px' }}>- {/* Header */}- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <div style={{+ width: '100%', height: '100%', display: 'flex', flexDirection: 'column',+ overflow: 'hidden', fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>++ {/* ═══════ TOOLBAR ═══════ */}+ <div style={{+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ padding: '10px 20px', backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`, flexShrink: 0,+ }}>+ {/* Left */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}><buttononClick={onCancel}- style={{ padding: '6px', backgroundColor: 'transparent', border: 'none', color: F.GRAY, cursor: 'pointer', borderRadius: '2px' }}+ style={{+ padding: '6px 8px', backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ color: F.GRAY, cursor: 'pointer', borderRadius: '2px', display: 'flex', alignItems: 'center',+ transition: 'all 0.2s',+ }}+ onMouseEnter={e => { e.currentTarget.style.borderColor = F.ORANGE; e.currentTarget.style.color = F.WHITE; }}+ onMouseLeave={e => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.GRAY; }}>- <ArrowLeft size={14} />+ <ArrowLeft size={12} /></button>- <span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE }}>- {editStrategyId ? 'EDIT STRATEGY' : 'CREATE STRATEGY'}- </span>+ <div>+ <div style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>+ {editStrategyId ? 'EDIT STRATEGY' : 'CREATE NEW STRATEGY'}+ </div>+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>+ Visual condition-based strategy builder+ </div>+ </div></div>++ {/* Center: Name + Timeframe */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <input+ value={name}+ onChange={e => setName(e.target.value)}+ placeholder="Strategy Name..."+ style={{+ width: '240px', padding: '7px 10px', backgroundColor: F.DARK_BG,+ color: F.WHITE, border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ fontSize: '11px', fontWeight: 600, outline: 'none',+ }}+ onFocus={e => { e.currentTarget.style.borderColor = F.ORANGE; }}+ onBlur={e => { e.currentTarget.style.borderColor = F.BORDER; }}+ />+ <select+ value={timeframe}+ onChange={e => setTimeframe(e.target.value)}+ style={{+ padding: '7px 8px', backgroundColor: F.DARK_BG, color: F.CYAN,+ border: `1px solid ${F.BORDER}`, borderRadius: '2px', fontSize: '10px',+ fontWeight: 700, cursor: 'pointer', outline: 'none',+ }}+ >+ {TIMEFRAMES.map(tf => <option key={tf.value} value={tf.value}>{tf.label}</option>)}+ </select>+ </div>++ {/* Right: Actions */}<div style={{ display: 'flex', gap: '6px' }}>- <button onClick={onCancel} style={{- padding: '6px 10px', backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,- color: F.GRAY, fontSize: '9px', fontWeight: 700, borderRadius: '2px', cursor: 'pointer',- }}>CANCEL</button>- <button onClick={handleSave} disabled={saving} style={{- padding: '8px 16px', backgroundColor: F.ORANGE, color: F.DARK_BG, border: 'none',- borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: 'pointer',- opacity: saving ? 0.5 : 1, display: 'flex', alignItems: 'center', gap: '4px',- }}>+ <button+ onClick={onCancel}+ style={{+ padding: '7px 14px', backgroundColor: 'transparent', color: F.GRAY,+ border: `1px solid ${F.BORDER}`, borderRadius: '2px', fontSize: '9px',+ fontWeight: 700, cursor: 'pointer', transition: 'all 0.2s',+ }}+ onMouseEnter={e => { e.currentTarget.style.color = F.WHITE; e.currentTarget.style.borderColor = F.GRAY; }}+ onMouseLeave={e => { e.currentTarget.style.color = F.GRAY; e.currentTarget.style.borderColor = F.BORDER; }}+ >+ CANCEL+ </button>+ <button+ onClick={handleSave}+ disabled={saving}+ style={{+ padding: '7px 16px', backgroundColor: F.ORANGE, color: F.DARK_BG,+ border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700,+ cursor: saving ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center',+ gap: '4px', opacity: saving ? 0.5 : 1, letterSpacing: '0.5px',+ }}+ ><Save size={10} />- {saving ? 'SAVING...' : 'SAVE STRATEGY'}+ {saving ? 'SAVING...' : 'SAVE'}</button></div></div>+ {/* Error Banner */}{error && (- <div style={{ padding: '6px 10px', backgroundColor: `${F.RED}20`, color: F.RED, fontSize: '9px', fontWeight: 700, borderRadius: '2px' }}>- {error}+ <div style={{+ padding: '8px 20px', backgroundColor: `${F.RED}15`, borderBottom: `1px solid ${F.RED}40`,+ display: 'flex', alignItems: 'center', gap: '6px', flexShrink: 0,+ }}>+ <AlertTriangle size={10} color={F.RED} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.RED }}>{error}</span></div>)}- {/* Basic Info */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>- <div>- <label style={labelStyle}>STRATEGY NAME</label>- <input value={name} onChange={e => setName(e.target.value)} placeholder="My RSI Strategy" style={inputStyle} />- </div>- <div>- <label style={labelStyle}>TIMEFRAME</label>- <select value={timeframe} onChange={e => setTimeframe(e.target.value)} style={inputStyle}>- {TIMEFRAMES.map(tf => <option key={tf.value} value={tf.value}>{tf.label}</option>)}- </select>- </div>- </div>-- <div>- <label style={labelStyle}>DESCRIPTION (OPTIONAL)</label>- <input value={description} onChange={e => setDescription(e.target.value)} placeholder="Short description" style={inputStyle} />- </div>-- {/* Entry & Exit Conditions */}- <ConditionBuilder label="Entry Conditions (BUY when)" conditions={entryConditions} logic={entryLogic}- onConditionsChange={setEntryConditions} onLogicChange={setEntryLogic} />+ {/* ═══════ TWO-COLUMN BODY ═══════ */}+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden', minHeight: 0 }}>- {/* Exit Conditions with Toggle */}- <div style={{ backgroundColor: F.PANEL_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px' }}>+ {/* ──── LEFT COLUMN: Strategy Builder ──── */}<div style={{- padding: '8px 12px', backgroundColor: F.HEADER_BG, borderBottom: `1px solid ${F.BORDER}`,- display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ flex: 1, overflow: 'auto', padding: '16px 20px',+ display: 'flex', flexDirection: 'column', gap: '16px', minWidth: 0,}}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>- EXIT CONDITIONS (SELL WHEN)- </span>- {!useExitConditions && (- <span style={{ fontSize: '8px', color: F.YELLOW, fontWeight: 700 }}>DISABLED</span>- )}- </div>- <label style={{ display: 'flex', alignItems: 'center', gap: '6px', cursor: 'pointer' }}>- <span style={{ fontSize: '8px', color: useExitConditions ? F.GREEN : F.MUTED }}>- {useExitConditions ? 'ENABLED' : 'USE SL/TP ONLY'}- </span>+ {/* Description */}+ <div>+ <label style={labelStyle}>DESCRIPTION (OPTIONAL)</label><input- type="checkbox"- checked={useExitConditions}- onChange={e => setUseExitConditions(e.target.checked)}- style={{ accentColor: F.ORANGE, cursor: 'pointer' }}+ value={description}+ onChange={e => setDescription(e.target.value)}+ placeholder="Describe your strategy logic..."+ style={inputStyle}/>- </label>- </div>- {useExitConditions ? (- <div style={{ padding: '4px 0' }}>- <ConditionBuilder label="" conditions={exitConditions} logic={exitLogic}- onConditionsChange={setExitConditions} onLogicChange={setExitLogic} /></div>- ) : (- <div style={{ padding: '16px', textAlign: 'center' }}>- <div style={{ fontSize: '9px', color: F.MUTED }}>- Exit conditions disabled. Trades will exit only via Stop Loss or Take Profit.++ {/* ── ENTRY CONDITIONS SECTION ── */}+ <div style={sectionStyle}>+ <div style={{+ ...sectionHeaderStyle,+ borderLeft: `3px solid ${F.GREEN}`,+ }}>+ <ArrowUpRight size={14} color={F.GREEN} />+ <span style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>+ ENTRY CONDITIONS+ </span>+ <span style={{ fontSize: '9px', color: F.GREEN, marginLeft: '4px' }}>BUY WHEN</span>+ <div style={{ flex: 1 }} />+ <div style={{+ padding: '3px 8px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: `${F.GREEN}20`, color: F.GREEN,+ }}>+ {entryConditions.length} CONDITION{entryConditions.length !== 1 ? 'S' : ''}+ </div></div>- <div style={{ fontSize: '8px', color: F.YELLOW, marginTop: '4px' }}>- ⚠ Make sure Stop Loss and/or Take Profit are set below.+ <div style={{ padding: '8px 0' }}>+ <ConditionBuilder+ label=""+ conditions={entryConditions}+ logic={entryLogic}+ onConditionsChange={setEntryConditions}+ onLogicChange={setEntryLogic}+ /></div></div>- )}- </div>- {/* Risk Management */}- <div style={{ backgroundColor: F.PANEL_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px' }}>- <div style={{ padding: '8px 12px', backgroundColor: F.HEADER_BG, borderBottom: `1px solid ${F.BORDER}` }}>- <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>RISK MANAGEMENT</span>- <span style={{ fontSize: '8px', color: F.MUTED, marginLeft: '8px' }}>- (Priority: Stop Loss → Take Profit → Exit Condition)- </span>- </div>- <div style={{ padding: '12px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>- <div>- <label style={labelStyle}>STOP LOSS (%)</label>- <input type="number" value={stopLoss} onChange={e => setStopLoss(e.target.value)} placeholder="e.g. 2" step="0.1" min="0" style={inputStyle} />- <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>Exit if loss ≥ this %</div>- </div>- <div>- <label style={labelStyle}>TAKE PROFIT (%)</label>- <input type="number" value={takeProfit} onChange={e => setTakeProfit(e.target.value)} placeholder="e.g. 5" step="0.1" min="0" style={inputStyle} />- <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>Exit if profit ≥ this %</div>- </div>- <div>- <label style={labelStyle}>TRAILING STOP (%)</label>- <input type="number" value={trailingStop} onChange={e => setTrailingStop(e.target.value)} placeholder="e.g. 1.5" step="0.1" min="0" style={inputStyle} />- <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>Not yet implemented</div>- </div>- </div>- {/* Validation Warning */}- {stopLoss && takeProfit && parseFloat(stopLoss) >= parseFloat(takeProfit) && (- <div style={{ margin: '0 12px 12px', padding: '6px 10px', backgroundColor: `${F.YELLOW}15`, border: `1px solid ${F.YELLOW}40`, borderRadius: '2px' }}>- <span style={{ fontSize: '9px', color: F.YELLOW }}>- ⚠ Stop Loss ({stopLoss}%) ≥ Take Profit ({takeProfit}%). Consider adjusting for better risk/reward ratio.- </span>- </div>- )}- {exitConditions.length > 0 && takeProfit && (- <div style={{ margin: '0 12px 12px', padding: '6px 10px', backgroundColor: `${F.CYAN}10`, border: `1px solid ${F.CYAN}30`, borderRadius: '2px' }}>- <span style={{ fontSize: '9px', color: F.CYAN }}>- ℹ Exit conditions will trigger AFTER stop loss/take profit checks. If your exit condition triggers before {takeProfit}% profit, it will exit early.- </span>+ {/* ── EXIT CONDITIONS SECTION ── */}+ <div style={sectionStyle}>+ <div style={{+ ...sectionHeaderStyle,+ borderLeft: `3px solid ${F.RED}`,+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <ArrowDownRight size={14} color={F.RED} />+ <span style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>+ EXIT CONDITIONS+ </span>+ <span style={{ fontSize: '9px', color: F.RED, marginLeft: '4px' }}>SELL WHEN</span>+ {!useExitConditions && (+ <span style={{+ padding: '2px 6px', borderRadius: '2px', fontSize: '8px',+ fontWeight: 700, backgroundColor: `${F.YELLOW}20`, color: F.YELLOW,+ }}>+ DISABLED+ </span>+ )}+ </div>+ <label style={{ display: 'flex', alignItems: 'center', gap: '6px', cursor: 'pointer' }}>+ <span style={{ fontSize: '8px', color: useExitConditions ? F.GREEN : F.MUTED }}>+ {useExitConditions ? 'ENABLED' : 'SL/TP ONLY'}+ </span>+ <input+ type="checkbox"+ checked={useExitConditions}+ onChange={e => setUseExitConditions(e.target.checked)}+ style={{ accentColor: F.ORANGE, cursor: 'pointer' }}+ />+ </label>+ </div>+ {useExitConditions ? (+ <div style={{ padding: '8px 0' }}>+ <ConditionBuilder+ label=""+ conditions={exitConditions}+ logic={exitLogic}+ onConditionsChange={setExitConditions}+ onLogicChange={setExitLogic}+ />+ </div>+ ) : (+ <div style={{ padding: '24px 16px', textAlign: 'center' }}>+ <Shield size={20} color={F.MUTED} style={{ marginBottom: '6px' }} />+ <div style={{ fontSize: '9px', color: F.MUTED }}>+ Exit conditions disabled. Trades exit via Stop Loss or Take Profit only.+ </div>+ <div style={{ fontSize: '8px', color: F.YELLOW, marginTop: '4px' }}>+ Ensure SL and/or TP are configured in the Risk Management panel.+ </div>+ </div>+ )}</div>- )}- </div>- {/* Quick Backtest */}- <div style={{ backgroundColor: F.PANEL_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px' }}>- <div style={{ padding: '8px 12px', backgroundColor: F.HEADER_BG, borderBottom: `1px solid ${F.BORDER}` }}>- <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>QUICK BACKTEST</span>- </div>- <div style={{ padding: '12px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '12px' }}>- <div>- <label style={labelStyle}>DATA SOURCE</label>- <select value={btProvider} onChange={e => setBtProvider(e.target.value as 'yfinance' | 'fyers')} style={inputStyle}>- <option value="fyers">Fyers (Local Cache)</option>- <option value="yfinance">Yahoo Finance</option>- </select>- </div>- <div>- <label style={labelStyle}>SYMBOL</label>- <input- value={btSymbol}- onChange={e => setBtSymbol(e.target.value)}- placeholder={btProvider === 'fyers' ? 'RELIANCE, TCS' : 'RELIANCE.NS, AAPL'}- style={inputStyle}- />- </div>- <div>- <label style={labelStyle}>PERIOD</label>- <select value={btPeriod} onChange={e => setBtPeriod(e.target.value)} style={inputStyle}>- {[['1mo','1 Month'],['3mo','3 Months'],['6mo','6 Months'],['1y','1 Year'],['2y','2 Years'],['5y','5 Years']].map(([v,l]) => (- <option key={v} value={v}>{l}</option>- ))}- </select>- </div>- <div style={{ display: 'flex', alignItems: 'flex-end' }}>- <button onClick={handleBacktest} disabled={backtesting} style={{- width: '100%', padding: '8px 16px', backgroundColor: F.PURPLE, color: F.WHITE,- border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: 'pointer',- opacity: backtesting ? 0.5 : 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px',+ {/* ── RISK MANAGEMENT SECTION ── */}+ <div style={sectionStyle}>+ <div style={{+ ...sectionHeaderStyle,+ borderLeft: `3px solid ${F.YELLOW}`,}}>- {backtesting ? <Loader size={10} className="animate-spin" /> : <Play size={10} />}- {backtesting ? 'RUNNING...' : 'RUN BACKTEST'}- </button>+ <Shield size={14} color={F.YELLOW} />+ <span style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>+ RISK MANAGEMENT+ </span>+ <span style={{ fontSize: '8px', color: F.MUTED, marginLeft: '8px' }}>+ Priority: SL → TP → Exit Condition+ </span>+ </div>+ <div style={{ padding: '12px 16px' }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>+ <div>+ <label style={labelStyle}>STOP LOSS (%)</label>+ <input type="number" value={stopLoss} onChange={e => setStopLoss(e.target.value)} placeholder="e.g. 2" step="0.1" min="0" style={inputStyle} />+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>Exit if loss ≥ this %</div>+ </div>+ <div>+ <label style={labelStyle}>TAKE PROFIT (%)</label>+ <input type="number" value={takeProfit} onChange={e => setTakeProfit(e.target.value)} placeholder="e.g. 5" step="0.1" min="0" style={inputStyle} />+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>Exit if profit ≥ this %</div>+ </div>+ <div>+ <label style={labelStyle}>TRAILING STOP (%)</label>+ <input type="number" value={trailingStop} onChange={e => setTrailingStop(e.target.value)} placeholder="e.g. 1.5" step="0.1" min="0" style={inputStyle} />+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>Not yet implemented</div>+ </div>+ </div>++ {/* Validation Warnings */}+ {stopLoss && takeProfit && parseFloat(stopLoss) >= parseFloat(takeProfit) && (+ <div style={{+ marginTop: '12px', padding: '8px 10px',+ backgroundColor: `${F.YELLOW}15`, border: `1px solid ${F.YELLOW}40`, borderRadius: '2px',+ display: 'flex', alignItems: 'center', gap: '6px',+ }}>+ <AlertTriangle size={10} color={F.YELLOW} />+ <span style={{ fontSize: '9px', color: F.YELLOW }}>+ Stop Loss ({stopLoss}%) ≥ Take Profit ({takeProfit}%). Adjust for better risk/reward.+ </span>+ </div>+ )}+ {useExitConditions && exitConditions.length > 0 && takeProfit && (+ <div style={{+ marginTop: '8px', padding: '8px 10px',+ backgroundColor: `${F.CYAN}10`, border: `1px solid ${F.CYAN}30`, borderRadius: '2px',+ }}>+ <span style={{ fontSize: '9px', color: F.CYAN }}>+ Exit conditions trigger AFTER SL/TP checks. May exit before {takeProfit}% target.+ </span>+ </div>+ )}+ </div></div></div>- {btError && (- <div style={{ margin: '0 12px 12px', padding: '6px 10px', backgroundColor: `${F.RED}20`, color: F.RED, fontSize: '9px', borderRadius: '2px' }}>- {btError}+ {/* ──── RIGHT COLUMN: Backtest Panel ──── */}+ <div style={{+ width: showBacktest ? '360px' : '40px',+ backgroundColor: F.PANEL_BG,+ borderLeft: `1px solid ${F.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ flexShrink: 0,+ transition: 'width 0.3s ease',+ }}>+ {/* Toggle Header */}+ <div+ onClick={() => setShowBacktest(!showBacktest)}+ style={{+ ...sectionHeaderStyle,+ borderLeft: `3px solid ${F.PURPLE}`,+ cursor: 'pointer',+ justifyContent: 'space-between',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <BarChart3 size={14} color={F.PURPLE} />+ {showBacktest && (+ <span style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>+ QUICK BACKTEST+ </span>+ )}+ </div>+ {showBacktest ? <ChevronRight size={12} color={F.MUTED} /> : <ChevronDown size={12} color={F.MUTED} />}</div>- )}-- {/* Debug Output Section */}- {btDebug.length > 0 && (- <div style={{ margin: '0 12px 12px' }}>- <button- onClick={() => setShowDebug(!showDebug)}- style={{- padding: '4px 8px', backgroundColor: F.HEADER_BG, border: `1px solid ${F.BORDER}`,- color: F.MUTED, fontSize: '8px', fontWeight: 700, borderRadius: '2px', cursor: 'pointer',- width: '100%', textAlign: 'left', display: 'flex', justifyContent: 'space-between', alignItems: 'center',- }}- >- <span>🔧 DEBUG LOG ({btDebug.length} entries)</span>- <span>{showDebug ? '▼' : '▶'}</span>- </button>- {showDebug && (- <div style={{- marginTop: '4px', padding: '8px', backgroundColor: '#0a0a0a', border: `1px solid ${F.BORDER}`,- borderRadius: '2px', maxHeight: '200px', overflow: 'auto',- fontFamily: '"IBM Plex Mono", monospace', fontSize: '8px', lineHeight: '1.4',- }}>- {btDebug.map((line, i) => (- <div- key={i}++ {showBacktest && (+ <div style={{ flex: 1, overflow: 'auto' }}>+ {/* Config */}+ <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: '10px' }}>+ <div>+ <label style={labelStyle}>DATA SOURCE</label>+ <select value={btProvider} onChange={e => setBtProvider(e.target.value as 'yfinance' | 'fyers')} style={inputStyle}>+ <option value="fyers">Fyers (Local Cache)</option>+ <option value="yfinance">Yahoo Finance</option>+ </select>+ </div>+ <div>+ <label style={labelStyle}>SYMBOL</label>+ <input+ value={btSymbol}+ onChange={e => setBtSymbol(e.target.value)}+ placeholder={btProvider === 'fyers' ? 'RELIANCE, TCS' : 'RELIANCE.NS, AAPL'}+ style={inputStyle}+ />+ </div>+ <div>+ <label style={labelStyle}>PERIOD</label>+ <select value={btPeriod} onChange={e => setBtPeriod(e.target.value)} style={inputStyle}>+ {[['1mo','1 Month'],['3mo','3 Months'],['6mo','6 Months'],['1y','1 Year'],['2y','2 Years'],['5y','5 Years']].map(([v,l]) => (+ <option key={v} value={v}>{l}</option>+ ))}+ </select>+ </div>+ <button+ onClick={handleBacktest}+ disabled={backtesting}+ style={{+ width: '100%', padding: '10px', backgroundColor: F.PURPLE, color: F.WHITE,+ border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700,+ cursor: backtesting ? 'not-allowed' : 'pointer',+ opacity: backtesting ? 0.5 : 1, display: 'flex', alignItems: 'center',+ justifyContent: 'center', gap: '6px', letterSpacing: '0.5px',+ transition: 'all 0.2s',+ }}+ >+ {backtesting ? <Loader size={10} className="animate-spin" /> : <Play size={10} />}+ {backtesting ? 'RUNNING BACKTEST...' : 'RUN BACKTEST'}+ </button>+ </div>++ {/* Backtest Error */}+ {btError && (+ <div style={{+ margin: '0 16px 8px', padding: '8px 10px',+ backgroundColor: `${F.RED}15`, border: `1px solid ${F.RED}30`,+ borderRadius: '2px',+ }}>+ <span style={{ fontSize: '9px', color: F.RED, lineHeight: '1.4' }}>{btError}</span>+ </div>+ )}++ {/* Debug Log */}+ {btDebug.length > 0 && (+ <div style={{ margin: '0 16px 8px' }}>+ <button+ onClick={() => setShowDebug(!showDebug)}style={{- color: line.includes('ERROR') ? F.RED : line.includes('WARNING') ? F.YELLOW : F.MUTED,- marginBottom: '2px',- wordBreak: 'break-all',+ width: '100%', padding: '6px 8px', backgroundColor: F.HEADER_BG,+ border: `1px solid ${F.BORDER}`, color: F.MUTED, fontSize: '8px',+ fontWeight: 700, cursor: 'pointer', textAlign: 'left', borderRadius: '2px',+ display: 'flex', justifyContent: 'space-between', alignItems: 'center',}}>- {line}- </div>- ))}- </div>- )}- </div>- )}-- {btResult && (- <div style={{ padding: '0 12px 12px', display: 'flex', flexDirection: 'column', gap: '8px' }}>- {/* Metrics Grid */}- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '6px' }}>- {[- { label: 'TOTAL RETURN', value: `${btResult.metrics.total_return_pct >= 0 ? '+' : ''}${btResult.metrics.total_return_pct}%`, color: btResult.metrics.total_return_pct >= 0 ? F.GREEN : F.RED },- { label: 'WIN RATE', value: `${btResult.metrics.win_rate}%`, color: btResult.metrics.win_rate >= 50 ? F.GREEN : F.YELLOW },- { label: 'MAX DRAWDOWN', value: `${btResult.metrics.max_drawdown}%`, color: F.RED },- { label: 'SHARPE RATIO', value: btResult.metrics.sharpe.toFixed(2), color: btResult.metrics.sharpe >= 1 ? F.GREEN : F.YELLOW },- { label: 'TOTAL TRADES', value: String(btResult.metrics.total_trades), color: F.CYAN },- { label: 'PROFIT FACTOR', value: btResult.metrics.profit_factor.toFixed(2), color: btResult.metrics.profit_factor >= 1.5 ? F.GREEN : F.YELLOW },- { label: 'AVG P&L', value: btResult.metrics.avg_pnl.toFixed(2), color: btResult.metrics.avg_pnl >= 0 ? F.GREEN : F.RED },- { label: 'AVG BARS HELD', value: btResult.metrics.avg_bars_held.toFixed(1), color: F.CYAN },- ].map((m, i) => (- <div key={i} style={{ backgroundColor: F.HEADER_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px', padding: '8px' }}>- <div style={{ fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>{m.label}</div>- <div style={{ fontSize: '11px', fontWeight: 700, color: m.color, marginTop: '2px', fontFamily: '"IBM Plex Mono", monospace' }}>{m.value}</div>+ <span>DEBUG LOG ({btDebug.length})</span>+ {showDebug ? <ChevronDown size={10} /> : <ChevronRight size={10} />}+ </button>+ {showDebug && (+ <div style={{+ marginTop: '2px', padding: '6px 8px', backgroundColor: '#0a0a0a',+ border: `1px solid ${F.BORDER}`, borderRadius: '2px', maxHeight: '150px',+ overflow: 'auto', fontSize: '8px', lineHeight: '1.4',+ }}>+ {btDebug.map((line, i) => (+ <div key={i} style={{+ color: line.includes('ERROR') ? F.RED : line.includes('WARNING') ? F.YELLOW : F.MUTED,+ marginBottom: '1px', wordBreak: 'break-all',+ }}>+ {line}+ </div>+ ))}+ </div>+ )}</div>- ))}- </div>+ )}- {/* Trades Table */}- {btResult.trades.length > 0 && (- <div style={{ maxHeight: '180px', overflow: 'auto' }}>- <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}>- <thead>- <tr style={{ borderBottom: `1px solid ${F.BORDER}` }}>- {['#', 'ENTRY', 'EXIT', 'P&L', 'P&L%', 'REASON', 'BARS'].map(h => (- <th key={h} style={{ padding: '6px 8px', textAlign: h === '#' || h === 'REASON' ? 'left' : 'right', fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px', position: 'sticky', top: 0, backgroundColor: F.PANEL_BG }}>{h}</th>+ {/* ─── BACKTEST RESULTS ─── */}+ {btResult && (+ <div style={{ borderTop: `1px solid ${F.BORDER}` }}>+ {/* Summary Bar */}+ <div style={{+ padding: '12px 16px', backgroundColor: F.HEADER_BG,+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ borderBottom: `1px solid ${F.BORDER}`,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ {btResult.metrics.total_return_pct >= 0+ ? <TrendingUp size={14} color={F.GREEN} />+ : <TrendingDown size={14} color={F.RED} />+ }+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>+ RESULTS+ </span>+ </div>+ <span style={{+ fontSize: '14px', fontWeight: 700,+ color: btResult.metrics.total_return_pct >= 0 ? F.GREEN : F.RED,+ }}>+ {btResult.metrics.total_return_pct >= 0 ? '+' : ''}{btResult.metrics.total_return_pct}%+ </span>+ </div>++ {/* Metrics Grid */}+ <div style={{ padding: '12px 16px' }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>+ {[+ { label: 'WIN RATE', value: `${btResult.metrics.win_rate}%`, color: btResult.metrics.win_rate >= 50 ? F.GREEN : F.YELLOW, icon: Target },+ { label: 'MAX DRAWDOWN', value: `${btResult.metrics.max_drawdown}%`, color: F.RED, icon: ArrowDownRight },+ { label: 'SHARPE', value: btResult.metrics.sharpe.toFixed(2), color: btResult.metrics.sharpe >= 1 ? F.GREEN : F.YELLOW, icon: Percent },+ { label: 'PROFIT FACTOR', value: btResult.metrics.profit_factor.toFixed(2), color: btResult.metrics.profit_factor >= 1.5 ? F.GREEN : F.YELLOW, icon: Activity },+ { label: 'TRADES', value: String(btResult.metrics.total_trades), color: F.CYAN, icon: Hash },+ { label: 'AVG P&L', value: btResult.metrics.avg_pnl.toFixed(2), color: btResult.metrics.avg_pnl >= 0 ? F.GREEN : F.RED, icon: TrendingUp },+ { label: 'AVG BARS', value: btResult.metrics.avg_bars_held.toFixed(1), color: F.CYAN, icon: Clock },+ { label: 'W / L', value: `${btResult.metrics.winning_trades} / ${btResult.metrics.losing_trades}`, color: F.WHITE, icon: BarChart3 },+ ].map((m, i) => (+ <div key={i} style={{+ backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', padding: '10px',+ }}>+ <div style={{+ display: 'flex', alignItems: 'center', gap: '4px',+ fontSize: '8px', fontWeight: 700, color: F.MUTED,+ letterSpacing: '0.5px', marginBottom: '4px',+ }}>+ <m.icon size={9} />+ {m.label}+ </div>+ <div style={{+ fontSize: '13px', fontWeight: 700, color: m.color,+ }}>{m.value}</div>+ </div>))}- </tr>- </thead>- <tbody>- {btResult.trades.map((t, i) => (- <tr key={i} style={{ borderBottom: `1px solid ${F.BORDER}15` }}>- <td style={{ padding: '4px 8px', color: F.MUTED }}>{i + 1}</td>- <td style={{ padding: '4px 8px', textAlign: 'right', color: F.WHITE }}>{t.entry_price}</td>- <td style={{ padding: '4px 8px', textAlign: 'right', color: F.WHITE }}>{t.exit_price}</td>- <td style={{ padding: '4px 8px', textAlign: 'right', fontWeight: 700, color: t.pnl >= 0 ? F.GREEN : F.RED }}>- {t.pnl >= 0 ? '+' : ''}{t.pnl}- </td>- <td style={{ padding: '4px 8px', textAlign: 'right', color: t.pnl_pct >= 0 ? F.GREEN : F.RED }}>- {t.pnl_pct >= 0 ? '+' : ''}{t.pnl_pct}%- </td>- <td style={{ padding: '4px 8px', color: F.MUTED }}>{t.reason}</td>- <td style={{ padding: '4px 8px', textAlign: 'right', color: F.CYAN }}>{t.bars_held}</td>- </tr>- ))}- </tbody>- </table>- </div>- )}- </div>- )}+ </div>+ </div>++ {/* Trade Log */}+ {btResult.trades.length > 0 && (+ <div>+ <div style={{+ padding: '8px 16px', backgroundColor: F.HEADER_BG,+ borderTop: `1px solid ${F.BORDER}`,+ borderBottom: `1px solid ${F.BORDER}`,+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>+ TRADE LOG ({btResult.trades.length})+ </span>+ </div>+ <div style={{ maxHeight: '200px', overflow: 'auto' }}>+ <table style={{+ width: '100%', borderCollapse: 'collapse', fontSize: '9px',+ }}>+ <thead>+ <tr>+ {['#', 'ENTRY', 'EXIT', 'P&L%', 'BARS'].map(h => (+ <th key={h} style={{+ padding: '6px 8px',+ textAlign: h === '#' ? 'left' : 'right',+ fontSize: '8px', fontWeight: 700, color: F.GRAY,+ letterSpacing: '0.5px', position: 'sticky', top: 0,+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ }}>{h}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {btResult.trades.map((t, i) => (+ <tr key={i} style={{ borderBottom: `1px solid ${F.BORDER}30` }}>+ <td style={{ padding: '5px 8px', color: F.MUTED }}>{i + 1}</td>+ <td style={{ padding: '5px 8px', textAlign: 'right', color: F.WHITE }}>{t.entry_price}</td>+ <td style={{ padding: '5px 8px', textAlign: 'right', color: F.WHITE }}>{t.exit_price}</td>+ <td style={{+ padding: '5px 8px', textAlign: 'right', fontWeight: 700,+ color: t.pnl_pct >= 0 ? F.GREEN : F.RED,+ }}>+ {t.pnl_pct >= 0 ? '+' : ''}{t.pnl_pct}%+ </td>+ <td style={{ padding: '5px 8px', textAlign: 'right', color: F.CYAN }}>{t.bars_held}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ )}+ </div>+ )}++ {/* Empty state */}+ {!btResult && !backtesting && !btError && (+ <div style={{+ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center',+ justifyContent: 'center', padding: '32px 16px', opacity: 0.5,+ }}>+ <BarChart3 size={28} color={F.MUTED} style={{ marginBottom: '8px' }} />+ <div style={{ fontSize: '9px', color: F.MUTED, textAlign: 'center', lineHeight: '1.5' }}>+ Configure symbol and period, then click RUN BACKTEST to see results.+ </div>+ </div>+ )}+ </div>+ )}+ </div></div></div>);diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyLibraryTab.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyLibraryTab.tsxindex 095e9c37b..ab2b2d1cb 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyLibraryTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyLibraryTab.tsx@@ -1,18 +1,7 @@import React, { useState, useEffect, useMemo } from 'react';import {- Search,- FolderOpen,- Code,- Play,- Copy,- ChevronRight,- Loader2,- AlertCircle,- ExternalLink,- Filter,- Grid,- List,- Eye,+ Search, FolderOpen, Code, Play, Copy, ChevronRight,+ Loader2, AlertCircle, Filter, Grid, List, Eye, Rocket, X, BookOpen,} from 'lucide-react';import type { PythonStrategy } from '../types';import {@@ -138,19 +127,14 @@ const StrategyLibraryTab: React.FC<StrategyLibraryTabProps> = ({if (loading) {return (- <div- style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '100%',- gap: '12px',- color: F.GRAY,- }}- >- <Loader2 size={24} style={{ animation: 'spin 1s linear infinite' }} />- <span style={{ fontSize: '11px' }}>Loading strategy library...</span>+ <div style={{+ display: 'flex', flexDirection: 'column', alignItems: 'center',+ justifyContent: 'center', height: '100%', gap: '12px', color: F.GRAY,+ }}>+ <Loader2 size={20} style={{ animation: 'spin 1s linear infinite', color: F.ORANGE }} />+ <span style={{ fontSize: '10px', fontWeight: 700, letterSpacing: '0.5px' }}>+ LOADING STRATEGY LIBRARY...+ </span><style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style></div>);@@ -158,30 +142,18 @@ const StrategyLibraryTab: React.FC<StrategyLibraryTabProps> = ({if (error) {return (- <div- style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '100%',- gap: '12px',- color: F.RED,- }}- >- <AlertCircle size={24} />- <span style={{ fontSize: '11px' }}>{error}</span>+ <div style={{+ display: 'flex', flexDirection: 'column', alignItems: 'center',+ justifyContent: 'center', height: '100%', gap: '12px',+ }}>+ <AlertCircle size={20} color={F.RED} />+ <span style={{ fontSize: '10px', color: F.RED, fontWeight: 700 }}>{error}</span><buttononClick={loadData}style={{- padding: '6px 12px',- backgroundColor: F.ORANGE,- color: F.DARK_BG,- border: 'none',- borderRadius: '2px',- fontSize: '10px',- fontWeight: 700,- cursor: 'pointer',+ padding: '6px 14px', backgroundColor: F.ORANGE, color: F.DARK_BG,+ border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700,+ cursor: 'pointer', letterSpacing: '0.5px',}}>RETRY@@ -192,59 +164,43 @@ const StrategyLibraryTab: React.FC<StrategyLibraryTabProps> = ({return (<div style={{ display: 'flex', height: '100%', backgroundColor: F.DARK_BG }}>- {/* Left Sidebar - Categories */}- <div- style={{- width: '220px',- backgroundColor: F.PANEL_BG,- borderRight: `1px solid ${F.BORDER}`,- display: 'flex',- flexDirection: 'column',- }}- >- <div- style={{- padding: '12px',- borderBottom: `1px solid ${F.BORDER}`,- display: 'flex',- alignItems: 'center',- gap: '8px',- }}- >- <Filter size={12} style={{ color: F.ORANGE }} />- <span style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE }}>CATEGORIES</span>- <span- style={{- fontSize: '9px',- color: F.GRAY,- marginLeft: 'auto',- }}- >+ {/* ─── LEFT SIDEBAR — CATEGORIES ─── */}+ <div style={{+ width: '200px', backgroundColor: F.PANEL_BG,+ borderRight: `1px solid ${F.BORDER}`,+ display: 'flex', flexDirection: 'column',+ }}>+ <div style={{+ padding: '12px', borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex', alignItems: 'center', gap: '8px',+ backgroundColor: F.HEADER_BG,+ }}>+ <BookOpen size={12} color={F.ORANGE} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>+ CATEGORIES+ </span>+ <span style={{ fontSize: '8px', color: F.MUTED, marginLeft: 'auto' }}>{categories.length}</span></div>- <div style={{ flex: 1, overflow: 'auto', padding: '4px 0' }}>+ <div style={{ flex: 1, overflow: 'auto' }}>{/* All Strategies */}<buttononClick={() => setSelectedCategory(null)}style={{- width: '100%',- padding: '8px 12px',- backgroundColor: selectedCategory === null ? F.HOVER : 'transparent',+ width: '100%', padding: '8px 12px',+ backgroundColor: selectedCategory === null ? `${F.ORANGE}10` : 'transparent',color: selectedCategory === null ? F.ORANGE : F.GRAY,- border: 'none',- textAlign: 'left',- fontSize: '10px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '8px',+ border: 'none', borderLeft: selectedCategory === null ? `2px solid ${F.ORANGE}` : '2px solid transparent',+ textAlign: 'left', fontSize: '9px', fontWeight: 700,+ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px',+ transition: 'all 0.15s', letterSpacing: '0.3px',}}>- <FolderOpen size={12} />- <span style={{ flex: 1 }}>All Strategies</span>- <span style={{ fontSize: '9px', color: F.MUTED }}>{strategies.length}</span>+ <FolderOpen size={11} />+ <span style={{ flex: 1 }}>ALL</span>+ <span style={{ fontSize: '8px', color: F.MUTED }}>{strategies.length}</span></button>{/* Category List */}@@ -253,120 +209,105 @@ const StrategyLibraryTab: React.FC<StrategyLibraryTabProps> = ({key={cat}onClick={() => setSelectedCategory(cat)}style={{- width: '100%',- padding: '8px 12px',- backgroundColor: selectedCategory === cat ? F.HOVER : 'transparent',+ width: '100%', padding: '8px 12px',+ backgroundColor: selectedCategory === cat ? `${F.ORANGE}10` : 'transparent',color: selectedCategory === cat ? F.ORANGE : F.GRAY,- border: 'none',- textAlign: 'left',- fontSize: '10px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '8px',+ border: 'none', borderLeft: selectedCategory === cat ? `2px solid ${F.ORANGE}` : '2px solid transparent',+ textAlign: 'left', fontSize: '9px',+ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px',+ transition: 'all 0.15s',}}><ChevronRight- size={10}+ size={9}style={{transform: selectedCategory === cat ? 'rotate(90deg)' : 'none',transition: 'transform 0.2s',}}/>- <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ <span style={{+ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',+ fontWeight: selectedCategory === cat ? 700 : 400,+ }}>{cat}</span>- <span style={{ fontSize: '9px', color: F.MUTED }}>{categoryCounts[cat] || 0}</span>+ <span style={{ fontSize: '8px', color: F.MUTED }}>{categoryCounts[cat] || 0}</span></button>))}</div></div>- {/* Main Content */}+ {/* ─── MAIN CONTENT ─── */}<div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>- {/* Search Bar */}- <div- style={{- padding: '12px 16px',- borderBottom: `1px solid ${F.BORDER}`,- display: 'flex',- alignItems: 'center',- gap: '12px',- }}- >- <div- style={{- flex: 1,- display: 'flex',- alignItems: 'center',- gap: '8px',- backgroundColor: F.PANEL_BG,- padding: '8px 12px',- borderRadius: '4px',- border: `1px solid ${F.BORDER}`,- }}- >- <Search size={14} style={{ color: F.GRAY }} />+ {/* Search & View Controls */}+ <div style={{+ padding: '10px 16px', borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex', alignItems: 'center', gap: '10px',+ backgroundColor: F.HEADER_BG,+ }}>+ <div style={{+ flex: 1, display: 'flex', alignItems: 'center', gap: '8px',+ backgroundColor: F.DARK_BG, padding: '7px 10px', borderRadius: '2px',+ border: `1px solid ${F.BORDER}`,+ }}>+ <Search size={12} color={F.GRAY} /><inputtype="text"placeholder="Search strategies by name, ID, or description..."value={searchQuery}onChange={(e) => setSearchQuery(e.target.value)}style={{- flex: 1,- backgroundColor: 'transparent',- border: 'none',- color: F.WHITE,- fontSize: '11px',- outline: 'none',+ flex: 1, backgroundColor: 'transparent', border: 'none',+ color: F.WHITE, fontSize: '10px', outline: 'none',+ fontFamily: '"IBM Plex Mono", monospace',}}/>{searchQuery && (<buttononClick={() => setSearchQuery('')}style={{- backgroundColor: 'transparent',- border: 'none',- color: F.GRAY,- cursor: 'pointer',- fontSize: '12px',+ backgroundColor: 'transparent', border: 'none',+ color: F.GRAY, cursor: 'pointer', padding: '2px',+ display: 'flex', alignItems: 'center',}}>- ×+ <X size={10} /></button>)}</div>- <span style={{ fontSize: '10px', color: F.GRAY }}>- {filteredStrategies.length} strategies+ <span style={{ fontSize: '9px', color: F.MUTED, fontWeight: 700 }}>+ {filteredStrategies.length}</span>- <div style={{ display: 'flex', gap: '4px' }}>+ {/* View Toggle */}+ <div style={{+ display: 'flex', border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', overflow: 'hidden',+ }}><buttononClick={() => setViewMode('grid')}style={{- padding: '6px',- backgroundColor: viewMode === 'grid' ? F.HOVER : 'transparent',+ padding: '5px 8px',+ backgroundColor: viewMode === 'grid' ? `${F.ORANGE}20` : 'transparent',color: viewMode === 'grid' ? F.ORANGE : F.GRAY,- border: 'none',- borderRadius: '2px',- cursor: 'pointer',+ border: 'none', borderRight: `1px solid ${F.BORDER}`,+ cursor: 'pointer', display: 'flex', alignItems: 'center',}}>- <Grid size={14} />+ <Grid size={12} /></button><buttononClick={() => setViewMode('list')}style={{- padding: '6px',- backgroundColor: viewMode === 'list' ? F.HOVER : 'transparent',+ padding: '5px 8px',+ backgroundColor: viewMode === 'list' ? `${F.ORANGE}20` : 'transparent',color: viewMode === 'list' ? F.ORANGE : F.GRAY,- border: 'none',- borderRadius: '2px',- cursor: 'pointer',+ border: 'none', cursor: 'pointer',+ display: 'flex', alignItems: 'center',}}>- <List size={14} />+ <List size={12} /></button></div></div>@@ -374,33 +315,26 @@ const StrategyLibraryTab: React.FC<StrategyLibraryTabProps> = ({{/* Strategy Grid/List */}<div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>{filteredStrategies.length === 0 ? (- <div- style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: F.GRAY,- fontSize: '11px',- }}- >- <Code size={32} style={{ marginBottom: '12px', opacity: 0.5 }} />- <span>No strategies found</span>+ <div style={{+ display: 'flex', flexDirection: 'column', alignItems: 'center',+ justifyContent: 'center', height: '200px', gap: '8px',+ }}>+ <Code size={24} color={F.MUTED} style={{ opacity: 0.4 }} />+ <span style={{ fontSize: '10px', fontWeight: 700, color: F.GRAY }}>+ NO STRATEGIES FOUND+ </span>{searchQuery && (- <span style={{ fontSize: '10px', marginTop: '4px' }}>+ <span style={{ fontSize: '9px', color: F.MUTED }}>Try a different search term</span>)}</div>) : viewMode === 'grid' ? (- <div- style={{- display: 'grid',- gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',- gap: '12px',- }}- >+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',+ gap: '10px',+ }}>{filteredStrategies.map((strategy) => (<StrategyCardkey={strategy.id}@@ -428,112 +362,115 @@ const StrategyLibraryTab: React.FC<StrategyLibraryTabProps> = ({</div></div>- {/* Right Sidebar - Code Preview */}+ {/* ─── RIGHT SIDEBAR — CODE PREVIEW ─── */}{selectedStrategy && (- <div- style={{- width: '400px',- backgroundColor: F.PANEL_BG,- borderLeft: `1px solid ${F.BORDER}`,- display: 'flex',- flexDirection: 'column',- }}- >- <div- style={{- padding: '12px',- borderBottom: `1px solid ${F.BORDER}`,- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- }}- >- <div>- <div style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE }}>+ <div style={{+ width: '380px', backgroundColor: F.PANEL_BG,+ borderLeft: `1px solid ${F.BORDER}`,+ display: 'flex', flexDirection: 'column',+ }}>+ {/* Preview Header */}+ <div style={{+ padding: '12px', borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ backgroundColor: F.HEADER_BG,+ }}>+ <div style={{ minWidth: 0, flex: 1 }}>+ <div style={{+ fontSize: '10px', fontWeight: 700, color: F.WHITE,+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',+ }}>{selectedStrategy.name}</div>- <div style={{ fontSize: '9px', color: F.GRAY, marginTop: '2px' }}>+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>{selectedStrategy.id}</div></div><button- onClick={() => {- setSelectedStrategy(null);- setCodePreview(null);- }}+ onClick={() => { setSelectedStrategy(null); setCodePreview(null); }}style={{- backgroundColor: 'transparent',- border: 'none',- color: F.GRAY,- cursor: 'pointer',- fontSize: '16px',+ padding: '4px', backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`, color: F.MUTED,+ cursor: 'pointer', borderRadius: '2px', marginLeft: '8px',+ display: 'flex', alignItems: 'center',}}+ onMouseEnter={e => { e.currentTarget.style.borderColor = F.RED; e.currentTarget.style.color = F.RED; }}+ onMouseLeave={e => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.MUTED; }}>- ×+ <X size={10} /></button></div>- <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>- {loadingCode ? (- <div+ {/* Strategy Info */}+ <div style={{+ padding: '10px 12px', borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex', gap: '6px', flexWrap: 'wrap',+ }}>+ <span style={{+ padding: '2px 6px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: `${F.CYAN}15`, color: F.CYAN,+ }}>+ {selectedStrategy.category}+ </span>+ {selectedStrategy.compatibility.map((mode) => (+ <span+ key={mode}style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- height: '100px',- color: F.GRAY,+ padding: '2px 6px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: mode === 'live' ? `${F.GREEN}15` : mode === 'paper' ? `${F.YELLOW}15` : `${F.BLUE}15`,+ color: mode === 'live' ? F.GREEN : mode === 'paper' ? F.YELLOW : F.BLUE,+ textTransform: 'uppercase',}}>- <Loader2 size={16} style={{ animation: 'spin 1s linear infinite' }} />+ {mode}+ </span>+ ))}+ </div>++ {/* Code Preview */}+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>+ {loadingCode ? (+ <div style={{+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ height: '100px', color: F.GRAY,+ }}>+ <Loader2 size={14} style={{ animation: 'spin 1s linear infinite' }} /></div>) : (- <pre- style={{- margin: 0,- padding: '12px',- backgroundColor: F.DARK_BG,- borderRadius: '4px',- fontSize: '10px',- fontFamily: '"IBM Plex Mono", monospace',- color: F.WHITE,- overflow: 'auto',- whiteSpace: 'pre-wrap',- wordBreak: 'break-word',- }}- >+ <pre style={{+ margin: 0, padding: '10px',+ backgroundColor: F.DARK_BG, borderRadius: '2px',+ border: `1px solid ${F.BORDER}`,+ fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace',+ color: F.WHITE, overflow: 'auto',+ whiteSpace: 'pre-wrap', wordBreak: 'break-word',+ lineHeight: '1.5',+ }}>{codePreview || '// No code available'}</pre>)}</div>- <div- style={{- padding: '12px',- borderTop: `1px solid ${F.BORDER}`,- display: 'flex',- gap: '8px',- }}- >+ {/* Preview Actions */}+ <div style={{+ padding: '10px 12px', borderTop: `1px solid ${F.BORDER}`,+ display: 'flex', gap: '6px',+ }}>{onClone && (<buttononClick={() => onClone(selectedStrategy)}style={{- flex: 1,- padding: '8px',- backgroundColor: F.BLUE,- color: F.WHITE,- border: 'none',- borderRadius: '2px',- fontSize: '10px',- fontWeight: 700,- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- gap: '4px',+ flex: 1, padding: '8px',+ backgroundColor: `${F.BLUE}15`, color: F.BLUE,+ border: `1px solid ${F.BLUE}30`, borderRadius: '2px',+ fontSize: '9px', fontWeight: 700, cursor: 'pointer',+ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px',+ letterSpacing: '0.5px', transition: 'all 0.2s',}}+ onMouseEnter={e => { e.currentTarget.style.backgroundColor = `${F.BLUE}25`; }}+ onMouseLeave={e => { e.currentTarget.style.backgroundColor = `${F.BLUE}15`; }}>- <Copy size={12} />+ <Copy size={10} />CLONE</button>)}@@ -541,22 +478,17 @@ const StrategyLibraryTab: React.FC<StrategyLibraryTabProps> = ({<buttononClick={() => onBacktest(selectedStrategy)}style={{- flex: 1,- padding: '8px',- backgroundColor: F.ORANGE,- color: F.DARK_BG,- border: 'none',- borderRadius: '2px',- fontSize: '10px',- fontWeight: 700,- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- gap: '4px',+ flex: 1, padding: '8px',+ backgroundColor: F.ORANGE, color: F.DARK_BG,+ border: 'none', borderRadius: '2px',+ fontSize: '9px', fontWeight: 700, cursor: 'pointer',+ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px',+ letterSpacing: '0.5px', transition: 'opacity 0.2s',}}+ onMouseEnter={e => { e.currentTarget.style.opacity = '0.85'; }}+ onMouseLeave={e => { e.currentTarget.style.opacity = '1'; }}>- <Play size={12} />+ <Play size={10} />BACKTEST</button>)}@@ -567,7 +499,7 @@ const StrategyLibraryTab: React.FC<StrategyLibraryTabProps> = ({);};-// Strategy Card Component+// ── Strategy Card Component ──────────────────────────────────────────────const StrategyCard: React.FC<{strategy: PythonStrategy;onViewCode: () => void;@@ -576,164 +508,133 @@ const StrategyCard: React.FC<{onDeploy?: () => void;}> = ({ strategy, onViewCode, onClone, onBacktest, onDeploy }) => {return (- <div- style={{- backgroundColor: F.PANEL_BG,- border: `1px solid ${F.BORDER}`,- borderRadius: '4px',- padding: '12px',- display: 'flex',- flexDirection: 'column',- gap: '8px',- }}+ <div style={{+ backgroundColor: F.PANEL_BG,+ border: `1px solid ${F.BORDER}`,+ borderRadius: '2px',+ overflow: 'hidden',+ display: 'flex', flexDirection: 'column',+ transition: 'border-color 0.2s',+ }}+ onMouseEnter={e => { (e.currentTarget as HTMLElement).style.borderColor = `${F.ORANGE}40`; }}+ onMouseLeave={e => { (e.currentTarget as HTMLElement).style.borderColor = F.BORDER; }}>{/* Header */}- <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '8px' }}>- <div style={{ flex: 1, minWidth: 0 }}>- <div- style={{- fontSize: '11px',- fontWeight: 700,- color: F.WHITE,- marginBottom: '4px',- wordBreak: 'break-word',- lineHeight: '1.3',- }}- >- {strategy.name}+ <div style={{+ padding: '10px 12px', backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ borderLeft: `3px solid ${F.PURPLE}`,+ }}>+ <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '8px' }}>+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{+ fontSize: '10px', fontWeight: 700, color: F.WHITE,+ marginBottom: '2px', wordBreak: 'break-word', lineHeight: '1.3',+ }}>+ {strategy.name}+ </div>+ <div style={{+ fontSize: '8px', color: F.MUTED,+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',+ }}>+ {strategy.id}+ </div></div>- <div style={{ fontSize: '9px', color: F.GRAY, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{strategy.id}</div>- </div>- <span- style={{- fontSize: '8px',- padding: '2px 6px',- backgroundColor: F.HOVER,- color: F.CYAN,- borderRadius: '2px',- flexShrink: 0,- maxWidth: '80px',- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',+ <span style={{+ fontSize: '7px', padding: '2px 6px',+ backgroundColor: `${F.CYAN}15`, color: F.CYAN,+ borderRadius: '2px', fontWeight: 700, flexShrink: 0,+ maxWidth: '80px', overflow: 'hidden', textOverflow: 'ellipsis',+ whiteSpace: 'nowrap', letterSpacing: '0.5px',}}- title={strategy.category}- >- {strategy.category}- </span>+ title={strategy.category}+ >+ {strategy.category}+ </span>+ </div></div>- {/* Description */}- <div- style={{- fontSize: '10px',- color: F.GRAY,- lineHeight: '1.4',- height: '28px',- overflow: 'hidden',- textOverflow: 'ellipsis',- display: '-webkit-box',- WebkitLineClamp: 2,- WebkitBoxOrient: 'vertical' as const,+ {/* Body */}+ <div style={{ padding: '10px 12px', flex: 1 }}>+ {/* Description */}+ <div style={{+ fontSize: '9px', color: F.GRAY, lineHeight: '1.4',+ height: '26px', overflow: 'hidden', textOverflow: 'ellipsis',+ display: '-webkit-box', WebkitLineClamp: 2,+ WebkitBoxOrient: 'vertical' as const, marginBottom: '8px',}}- title={strategy.description || 'No description available'}- >- {strategy.description || 'No description available'}- </div>+ title={strategy.description || 'No description available'}+ >+ {strategy.description || 'No description available'}+ </div>- {/* Compatibility Tags */}- <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>- {strategy.compatibility.map((mode) => (- <span- key={mode}- style={{- fontSize: '8px',- padding: '2px 4px',- backgroundColor:- mode === 'live' ? `${F.GREEN}20` : mode === 'paper' ? `${F.YELLOW}20` : `${F.BLUE}20`,- color: mode === 'live' ? F.GREEN : mode === 'paper' ? F.YELLOW : F.BLUE,- borderRadius: '2px',- textTransform: 'uppercase',- }}- >- {mode}- </span>- ))}+ {/* Compatibility Tags */}+ <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>+ {strategy.compatibility.map((mode) => (+ <span+ key={mode}+ style={{+ fontSize: '7px', padding: '2px 5px', fontWeight: 700,+ backgroundColor: mode === 'live' ? `${F.GREEN}15` : mode === 'paper' ? `${F.YELLOW}15` : `${F.BLUE}15`,+ color: mode === 'live' ? F.GREEN : mode === 'paper' ? F.YELLOW : F.BLUE,+ borderRadius: '2px', textTransform: 'uppercase', letterSpacing: '0.5px',+ }}+ >+ {mode}+ </span>+ ))}+ </div></div>{/* Actions */}- <div- style={{- display: 'flex',- gap: '4px',- marginTop: '4px',- borderTop: `1px solid ${F.BORDER}`,- paddingTop: '8px',- }}- >+ <div style={{+ display: 'flex', gap: '4px', padding: '8px 12px',+ borderTop: `1px solid ${F.BORDER}`,+ }}><buttononClick={onViewCode}style={{- flex: 1,- padding: '6px',- backgroundColor: 'transparent',- border: `1px solid ${F.BORDER}`,- color: F.GRAY,- borderRadius: '2px',- fontSize: '9px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- gap: '4px',+ flex: 1, padding: '5px',+ backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ color: F.GRAY, borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '3px',+ transition: 'all 0.2s', letterSpacing: '0.5px',}}+ onMouseEnter={e => { e.currentTarget.style.borderColor = F.ORANGE; e.currentTarget.style.color = F.WHITE; }}+ onMouseLeave={e => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.GRAY; }}>- <Eye size={10} />- VIEW+ <Eye size={9} /> VIEW</button>{onClone && (<buttononClick={onClone}style={{- flex: 1,- padding: '6px',- backgroundColor: 'transparent',- border: `1px solid ${F.BLUE}`,- color: F.BLUE,- borderRadius: '2px',- fontSize: '9px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- gap: '4px',+ flex: 1, padding: '5px',+ backgroundColor: 'transparent', border: `1px solid ${F.BLUE}30`,+ color: F.BLUE, borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '3px',+ transition: 'all 0.2s', letterSpacing: '0.5px',}}+ onMouseEnter={e => { e.currentTarget.style.backgroundColor = `${F.BLUE}10`; }}+ onMouseLeave={e => { e.currentTarget.style.backgroundColor = 'transparent'; }}>- <Copy size={10} />- CLONE+ <Copy size={9} /> CLONE</button>)}{onBacktest && (<buttononClick={onBacktest}style={{- flex: 1,- padding: '6px',- backgroundColor: F.ORANGE,- border: 'none',- color: F.DARK_BG,- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- gap: '4px',+ flex: 1, padding: '5px',+ backgroundColor: F.ORANGE, border: 'none',+ color: F.DARK_BG, borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '3px',+ letterSpacing: '0.5px', transition: 'opacity 0.2s',}}+ onMouseEnter={e => { e.currentTarget.style.opacity = '0.85'; }}+ onMouseLeave={e => { e.currentTarget.style.opacity = '1'; }}>- <Play size={10} />- TEST+ <Play size={9} /> TEST</button>)}</div>@@ -741,7 +642,7 @@ const StrategyCard: React.FC<{);};-// Strategy Row Component (List View)+// ── Strategy Row Component (List View) ──────────────────────────────────const StrategyRow: React.FC<{strategy: PythonStrategy;onViewCode: () => void;@@ -749,55 +650,45 @@ const StrategyRow: React.FC<{onBacktest?: () => void;}> = ({ strategy, onViewCode, onClone, onBacktest }) => {return (- <div- style={{- backgroundColor: F.PANEL_BG,- border: `1px solid ${F.BORDER}`,- borderRadius: '2px',- padding: '8px 12px',- display: 'flex',- alignItems: 'center',- gap: '12px',- }}+ <div style={{+ backgroundColor: F.PANEL_BG,+ border: `1px solid ${F.BORDER}`,+ borderRadius: '2px',+ padding: '8px 12px',+ display: 'flex', alignItems: 'center', gap: '12px',+ transition: 'border-color 0.15s',+ }}+ onMouseEnter={e => { (e.currentTarget as HTMLElement).style.borderColor = `${F.ORANGE}40`; }}+ onMouseLeave={e => { (e.currentTarget as HTMLElement).style.borderColor = F.BORDER; }}>- <Code size={14} style={{ color: F.ORANGE }} />+ <Code size={12} color={F.PURPLE} /><div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: '10px', fontWeight: 700, color: F.WHITE }}>{strategy.name}</div>- <div- style={{- fontSize: '9px',- color: F.GRAY,- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',- }}- >- {strategy.id} - {strategy.description || 'No description'}+ <div style={{+ fontSize: '8px', color: F.MUTED,+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',+ }}>+ {strategy.id} — {strategy.description || 'No description'}</div></div>- <span- style={{- fontSize: '8px',- padding: '2px 6px',- backgroundColor: F.HOVER,- color: F.CYAN,- borderRadius: '2px',- }}- >+ <span style={{+ fontSize: '7px', padding: '2px 6px',+ backgroundColor: `${F.CYAN}15`, color: F.CYAN,+ borderRadius: '2px', fontWeight: 700,+ }}>{strategy.category}</span><div style={{ display: 'flex', gap: '4px' }}><buttononClick={onViewCode}style={{- padding: '4px 8px',- backgroundColor: 'transparent',- border: `1px solid ${F.BORDER}`,- color: F.GRAY,- borderRadius: '2px',- fontSize: '9px',- cursor: 'pointer',+ padding: '4px 8px', backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`, color: F.GRAY,+ borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ cursor: 'pointer', transition: 'all 0.2s',}}+ onMouseEnter={e => { e.currentTarget.style.borderColor = F.ORANGE; e.currentTarget.style.color = F.WHITE; }}+ onMouseLeave={e => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.GRAY; }}>VIEW</button>@@ -805,13 +696,10 @@ const StrategyRow: React.FC<{<buttononClick={onClone}style={{- padding: '4px 8px',- backgroundColor: 'transparent',- border: `1px solid ${F.BLUE}`,- color: F.BLUE,- borderRadius: '2px',- fontSize: '9px',- cursor: 'pointer',+ padding: '4px 8px', backgroundColor: 'transparent',+ border: `1px solid ${F.BLUE}30`, color: F.BLUE,+ borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ cursor: 'pointer', transition: 'all 0.2s',}}>CLONE@@ -821,14 +709,9 @@ const StrategyRow: React.FC<{<buttononClick={onBacktest}style={{- padding: '4px 8px',- backgroundColor: F.ORANGE,- border: 'none',- color: F.DARK_BG,- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: 'pointer',+ padding: '4px 8px', backgroundColor: F.ORANGE,+ border: 'none', color: F.DARK_BG, borderRadius: '2px',+ fontSize: '8px', fontWeight: 700, cursor: 'pointer',}}>TESTdiff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyManager.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyManager.tsxindex 53ed8cef2..812d60ad0 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyManager.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyManager.tsx@@ -1,5 +1,9 @@import React, { useState, useEffect } from 'react';-import { Plus, Edit, Trash2, Rocket, RefreshCw, Code, Settings, ChevronDown, FileCode, Filter } from 'lucide-react';+import {+ Plus, Edit, Trash2, Rocket, RefreshCw, Code, Settings, ChevronDown,+ FileCode, Filter, Folder, Calendar, ArrowUpRight, ArrowDownRight,+ Shield, Zap, MoreHorizontal,+} from 'lucide-react';import type { AlgoStrategy, CustomPythonStrategy, PythonStrategy } from '../types';import {listAlgoStrategies,@@ -25,6 +29,7 @@ const F = {CYAN: '#00E5FF',PURPLE: '#9D4EDD',YELLOW: '#FFD700',+ BLUE: '#0088FF',};type StrategyType = 'all' | 'json' | 'python';@@ -34,6 +39,7 @@ interface StrategyManagerProps {onNew: () => void;onBacktestPython?: (strategy: PythonStrategy) => void;onDeployPython?: (strategy: PythonStrategy) => void;+ onDeployedJson?: (deployId: string) => void;}// Unified strategy item for display@@ -62,6 +68,7 @@ const StrategyManager: React.FC<StrategyManagerProps> = ({onNew,onBacktestPython,onDeployPython,+ onDeployedJson,}) => {const [strategies, setStrategies] = useState<UnifiedStrategy[]>([]);const [loading, setLoading] = useState(true);@@ -71,6 +78,7 @@ const StrategyManager: React.FC<StrategyManagerProps> = ({const [filterType, setFilterType] = useState<StrategyType>('all');const [showFilterDropdown, setShowFilterDropdown] = useState(false);const [editingPythonStrategy, setEditingPythonStrategy] = useState<CustomPythonStrategy | null>(null);+ const [menuOpenId, setMenuOpenId] = useState<string | null>(null);const loadStrategies = async () => {setLoading(true);@@ -147,6 +155,7 @@ const StrategyManager: React.FC<StrategyManagerProps> = ({setStrategies((prev) => prev.filter((s) => s.id !== strategy.id));}}+ setMenuOpenId(null);};const handleDeploy = (strategy: UnifiedStrategy) => {@@ -156,6 +165,7 @@ const StrategyManager: React.FC<StrategyManagerProps> = ({setDeployStrategyId(strategy.id);setDeployStrategyType(strategy.type);}+ setMenuOpenId(null);};const handleEdit = (strategy: UnifiedStrategy) => {@@ -164,6 +174,7 @@ const StrategyManager: React.FC<StrategyManagerProps> = ({} else if (strategy.originalPython) {setEditingPythonStrategy(strategy.originalPython);}+ setMenuOpenId(null);};const handlePythonEditorClose = () => {@@ -180,135 +191,86 @@ const StrategyManager: React.FC<StrategyManagerProps> = ({const pythonCount = strategies.filter((s) => s.type === 'python').length;return (- <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '12px' }}>- {/* Section Header */}- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* ─── HEADER TOOLBAR ─── */}+ <div style={{+ padding: '12px 16px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}><div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <Folder size={14} color={F.ORANGE} /><span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>MY STRATEGIES</span>- <div style={{ display: 'flex', gap: '4px', fontSize: '9px' }}>+ <div style={{ display: 'flex', gap: '4px' }}><span style={{- padding: '2px 6px',- backgroundColor: `${F.CYAN}20`,- color: F.CYAN,- borderRadius: '2px',+ padding: '2px 8px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: `${F.CYAN}15`, color: F.CYAN,}}>{jsonCount} JSON</span><span style={{- padding: '2px 6px',- backgroundColor: `${F.PURPLE}20`,- color: F.PURPLE,- borderRadius: '2px',+ padding: '2px 8px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: `${F.PURPLE}15`, color: F.PURPLE,}}>- {pythonCount} Python+ {pythonCount} PYTHON</span></div></div>- <div style={{ display: 'flex', gap: '6px' }}>- {/* Filter Dropdown */}- <div style={{ position: 'relative' }}>- <button- onClick={() => setShowFilterDropdown(!showFilterDropdown)}- style={{- padding: '6px 8px',- backgroundColor: 'transparent',- border: `1px solid ${F.BORDER}`,- color: F.GRAY,- cursor: 'pointer',- borderRadius: '2px',- display: 'flex',- alignItems: 'center',- gap: '4px',- fontSize: '9px',- }}- >- <Filter size={10} />- {filterType === 'all' ? 'ALL' : filterType.toUpperCase()}- <ChevronDown size={10} />- </button>- {showFilterDropdown && (- <div style={{- position: 'absolute',- top: '100%',- right: 0,- marginTop: '4px',- backgroundColor: F.PANEL_BG,- border: `1px solid ${F.BORDER}`,- borderRadius: '2px',- zIndex: 100,- minWidth: '100px',- }}>- {(['all', 'json', 'python'] as StrategyType[]).map((type) => (- <button- key={type}- onClick={() => {- setFilterType(type);- setShowFilterDropdown(false);- }}- style={{- width: '100%',- padding: '6px 10px',- backgroundColor: filterType === type ? `${F.ORANGE}20` : 'transparent',- border: 'none',- color: filterType === type ? F.ORANGE : F.WHITE,- fontSize: '9px',- textAlign: 'left',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '6px',- }}- >- {type === 'all' && 'All Strategies'}- {type === 'json' && (- <>- <Settings size={10} style={{ color: F.CYAN }} />- JSON Strategies- </>- )}- {type === 'python' && (- <>- <Code size={10} style={{ color: F.PURPLE }} />- Python Strategies- </>- )}- </button>- ))}- </div>- )}++ <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>+ {/* Filter Tabs */}+ <div style={{+ display: 'flex', gap: '0px',+ border: `1px solid ${F.BORDER}`, borderRadius: '2px', overflow: 'hidden',+ }}>+ {(['all', 'json', 'python'] as StrategyType[]).map((type) => (+ <button+ key={type}+ onClick={() => setFilterType(type)}+ style={{+ padding: '5px 10px',+ backgroundColor: filterType === type ? `${F.ORANGE}20` : 'transparent',+ border: 'none',+ borderRight: type !== 'python' ? `1px solid ${F.BORDER}` : 'none',+ color: filterType === type ? F.ORANGE : F.GRAY,+ fontSize: '8px', fontWeight: 700, letterSpacing: '0.5px',+ cursor: 'pointer', transition: 'all 0.15s',+ }}+ >+ {type === 'all' ? 'ALL' : type.toUpperCase()}+ </button>+ ))}</div><buttononClick={loadStrategies}style={{- padding: '6px',- backgroundColor: 'transparent',- border: `1px solid ${F.BORDER}`,- color: F.GRAY,- cursor: 'pointer',- borderRadius: '2px',- transition: 'all 0.2s',+ padding: '6px', backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`, color: F.GRAY,+ cursor: 'pointer', borderRadius: '2px', transition: 'all 0.2s',+ display: 'flex', alignItems: 'center',}}+ onMouseEnter={e => { e.currentTarget.style.borderColor = F.ORANGE; e.currentTarget.style.color = F.WHITE; }}+ onMouseLeave={e => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.GRAY; }}>- <RefreshCw size={12} />+ <RefreshCw size={11} /></button>+<buttononClick={onNew}style={{- padding: '8px 16px',- backgroundColor: F.ORANGE,- color: F.DARK_BG,- border: 'none',- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px',+ padding: '6px 14px', backgroundColor: F.ORANGE, color: F.DARK_BG,+ border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700,+ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '4px',+ letterSpacing: '0.5px', transition: 'opacity 0.2s',}}+ onMouseEnter={e => { e.currentTarget.style.opacity = '0.85'; }}+ onMouseLeave={e => { e.currentTarget.style.opacity = '1'; }}><Plus size={10} />NEW STRATEGY@@ -322,6 +284,10 @@ const StrategyManager: React.FC<StrategyManagerProps> = ({strategyId={deployStrategyId}strategyName={strategies.find((s) => s.id === deployStrategyId)?.name || ''}onClose={() => setDeployStrategyId(null)}+ onDeployed={(deployId) => {+ setDeployStrategyId(null);+ onDeployedJson?.(deployId);+ }}/>)}@@ -338,251 +304,316 @@ const StrategyManager: React.FC<StrategyManagerProps> = ({/>)}- {/* List */}- {loading ? (- <div style={{ textAlign: 'center', padding: '32px', fontSize: '10px', color: F.MUTED }}>- Loading strategies...- </div>- ) : filteredStrategies.length === 0 ? (+ {/* ─── STRATEGY CARDS ─── */}+ <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>+ {loading ? (+ <div style={{+ display: 'flex', flexDirection: 'column', alignItems: 'center',+ justifyContent: 'center', height: '200px', gap: '8px',+ }}>+ <RefreshCw size={18} color={F.ORANGE} style={{ animation: 'spin 1s linear infinite' }} />+ <span style={{ fontSize: '10px', color: F.MUTED, fontWeight: 700 }}>LOADING STRATEGIES...</span>+ <style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>+ </div>+ ) : filteredStrategies.length === 0 ? (+ <div style={{+ display: 'flex', flexDirection: 'column', alignItems: 'center',+ justifyContent: 'center', height: '300px', gap: '12px',+ }}>+ <div style={{+ width: '48px', height: '48px', borderRadius: '2px',+ backgroundColor: `${F.ORANGE}10`, border: `1px solid ${F.ORANGE}20`,+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ }}>+ <Rocket size={20} color={F.ORANGE} style={{ opacity: 0.6 }} />+ </div>+ <span style={{ fontSize: '11px', fontWeight: 700, color: F.GRAY }}>+ {filterType === 'all' ? 'NO STRATEGIES YET' : `NO ${filterType.toUpperCase()} STRATEGIES`}+ </span>+ <span style={{ fontSize: '9px', color: F.MUTED, maxWidth: '300px', textAlign: 'center', lineHeight: '1.5' }}>+ {filterType === 'python'+ ? 'Clone strategies from the LIBRARY tab to create Python strategies'+ : 'Create your first strategy using the builder or write a Python strategy'}+ </span>+ {filterType !== 'python' && (+ <button+ onClick={onNew}+ style={{+ marginTop: '4px', padding: '8px 16px',+ backgroundColor: 'transparent', border: `1px solid ${F.ORANGE}`,+ color: F.ORANGE, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px',+ borderRadius: '2px', cursor: 'pointer', transition: 'all 0.2s',+ display: 'flex', alignItems: 'center', gap: '6px',+ }}+ onMouseEnter={e => { e.currentTarget.style.backgroundColor = `${F.ORANGE}15`; }}+ onMouseLeave={e => { e.currentTarget.style.backgroundColor = 'transparent'; }}+ >+ <Plus size={10} />+ CREATE STRATEGY+ </button>+ )}+ </div>+ ) : (+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))',+ gap: '10px',+ }}>+ {filteredStrategies.map((strategy) => (+ <StrategyCard+ key={strategy.id}+ strategy={strategy}+ isHovered={hoveredId === strategy.id}+ menuOpen={menuOpenId === strategy.id}+ onMouseEnter={() => setHoveredId(strategy.id)}+ onMouseLeave={() => setHoveredId(null)}+ onEdit={() => handleEdit(strategy)}+ onDeploy={() => handleDeploy(strategy)}+ onDelete={() => handleDelete(strategy)}+ onMenuToggle={() => setMenuOpenId(menuOpenId === strategy.id ? null : strategy.id)}+ />+ ))}+ </div>+ )}+ </div>++ {/* Click outside to close menu */}+ {menuOpenId && (<div- style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: F.MUTED,- fontSize: '10px',- textAlign: 'center',- }}- >- <Rocket size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />- <span>- {filterType === 'all'- ? 'No strategies yet'- : `No ${filterType} strategies yet`}- </span>- {filterType === 'all' && (- <button- onClick={onNew}- style={{- marginTop: '8px',- padding: '6px 12px',- backgroundColor: 'transparent',- border: `1px solid ${F.BORDER}`,- color: F.ORANGE,- fontSize: '9px',- fontWeight: 700,- borderRadius: '2px',- cursor: 'pointer',+ style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 99 }}+ onClick={() => setMenuOpenId(null)}+ />+ )}+ </div>+ );+};++// ── Strategy Card Component ──────────────────────────────────────────────+const StrategyCard: React.FC<{+ strategy: UnifiedStrategy;+ isHovered: boolean;+ menuOpen: boolean;+ onMouseEnter: () => void;+ onMouseLeave: () => void;+ onEdit: () => void;+ onDeploy: () => void;+ onDelete: () => void;+ onMenuToggle: () => void;+}> = ({ strategy, isHovered, menuOpen, onMouseEnter, onMouseLeave, onEdit, onDeploy, onDelete, onMenuToggle }) => {+ const isJson = strategy.type === 'json';+ const typeColor = isJson ? F.CYAN : F.PURPLE;+ const TypeIcon = isJson ? Settings : FileCode;++ return (+ <div+ onMouseEnter={onMouseEnter}+ onMouseLeave={onMouseLeave}+ style={{+ backgroundColor: F.PANEL_BG,+ border: `1px solid ${isHovered ? `${F.ORANGE}40` : F.BORDER}`,+ borderRadius: '2px',+ overflow: 'hidden',+ transition: 'border-color 0.2s',+ }}+ >+ {/* Card Header */}+ <div style={{+ padding: '10px 12px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ borderLeft: `3px solid ${typeColor}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ }}>+ <TypeIcon size={12} color={typeColor} />+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{+ fontSize: '10px', fontWeight: 700, color: F.WHITE,+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',+ }}>+ {strategy.name}+ </div>+ </div>+ <span style={{+ padding: '2px 6px', borderRadius: '2px', fontSize: '7px', fontWeight: 700,+ backgroundColor: `${typeColor}15`, color: typeColor, letterSpacing: '0.5px',+ }}>+ {strategy.type.toUpperCase()}+ </span>+ {/* Menu button */}+ <div style={{ position: 'relative' }}>+ <button+ onClick={(e) => { e.stopPropagation(); onMenuToggle(); }}+ style={{+ padding: '3px', backgroundColor: 'transparent', border: 'none',+ color: F.MUTED, cursor: 'pointer', borderRadius: '2px',+ display: 'flex', alignItems: 'center',+ }}+ >+ <MoreHorizontal size={12} />+ </button>+ {menuOpen && (+ <div style={{+ position: 'absolute', top: '100%', right: 0, marginTop: '4px',+ backgroundColor: F.PANEL_BG, border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', zIndex: 100, minWidth: '120px',+ boxShadow: '0 4px 12px rgba(0,0,0,0.5)',+ }}>+ <button onClick={onEdit} style={{+ width: '100%', padding: '8px 12px', backgroundColor: 'transparent',+ border: 'none', color: F.WHITE, fontSize: '9px', fontWeight: 700,+ textAlign: 'left', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '6px',+ transition: 'background-color 0.15s',}}- >- CREATE YOUR FIRST STRATEGY- </button>- )}- {filterType === 'python' && (- <div style={{ marginTop: '8px', color: F.GRAY, fontSize: '9px' }}>- Clone strategies from the LIBRARY tab to create Python strategies+ onMouseEnter={e => { e.currentTarget.style.backgroundColor = F.HOVER; }}+ onMouseLeave={e => { e.currentTarget.style.backgroundColor = 'transparent'; }}+ >+ <Edit size={10} /> EDIT+ </button>+ <button onClick={onDeploy} style={{+ width: '100%', padding: '8px 12px', backgroundColor: 'transparent',+ border: 'none', color: F.GREEN, fontSize: '9px', fontWeight: 700,+ textAlign: 'left', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '6px',+ transition: 'background-color 0.15s',+ }}+ onMouseEnter={e => { e.currentTarget.style.backgroundColor = F.HOVER; }}+ onMouseLeave={e => { e.currentTarget.style.backgroundColor = 'transparent'; }}+ >+ <Rocket size={10} /> DEPLOY+ </button>+ <div style={{ borderTop: `1px solid ${F.BORDER}` }} />+ <button onClick={onDelete} style={{+ width: '100%', padding: '8px 12px', backgroundColor: 'transparent',+ border: 'none', color: F.RED, fontSize: '9px', fontWeight: 700,+ textAlign: 'left', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '6px',+ transition: 'background-color 0.15s',+ }}+ onMouseEnter={e => { e.currentTarget.style.backgroundColor = `${F.RED}10`; }}+ onMouseLeave={e => { e.currentTarget.style.backgroundColor = 'transparent'; }}+ >+ <Trash2 size={10} /> DELETE+ </button></div>)}</div>- ) : (- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>- {filteredStrategies.map((strategy) => (- <div- key={strategy.id}- onMouseEnter={() => setHoveredId(strategy.id)}- onMouseLeave={() => setHoveredId(null)}- style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- padding: '10px 12px',- backgroundColor: hoveredId === strategy.id ? `${F.ORANGE}15` : F.PANEL_BG,- borderLeft:- hoveredId === strategy.id ? `2px solid ${F.ORANGE}` : '2px solid transparent',- border: `1px solid ${F.BORDER}`,- borderRadius: '2px',- cursor: 'pointer',- transition: 'all 0.2s',- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- {/* Type indicator */}- {strategy.type === 'json' ? (- <Settings size={12} style={{ color: F.CYAN, flexShrink: 0 }} />- ) : (- <FileCode size={12} style={{ color: F.PURPLE, flexShrink: 0 }} />- )}- <div- style={{- fontSize: '10px',- fontWeight: 700,- color: F.WHITE,- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',- }}- >- {strategy.name}- </div>- {/* Type badge */}- <span- style={{- fontSize: '8px',- padding: '2px 4px',- backgroundColor: strategy.type === 'json' ? `${F.CYAN}20` : `${F.PURPLE}20`,- color: strategy.type === 'json' ? F.CYAN : F.PURPLE,- borderRadius: '2px',- flexShrink: 0,- }}- >- {strategy.type.toUpperCase()}- </span>- </div>- {strategy.description && (- <div- style={{- fontSize: '9px',- color: F.MUTED,- marginTop: '2px',- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',- marginLeft: '20px',- }}- >- {strategy.description}- </div>- )}- <div- style={{- display: 'flex',- gap: '12px',- marginTop: '4px',- fontSize: '9px',- color: F.GRAY,- marginLeft: '20px',- }}- >- {/* JSON strategy details */}- {strategy.type === 'json' && (- <>- <span>- TF: <span style={{ color: F.CYAN }}>{strategy.timeframe}</span>- </span>- <span>- ENTRY: <span style={{ color: F.CYAN }}>{strategy.entryConditionCount}</span>- </span>- <span>- EXIT: <span style={{ color: F.CYAN }}>{strategy.exitConditionCount}</span>- </span>- {strategy.stopLoss != null && (- <span>- SL: <span style={{ color: F.RED }}>{strategy.stopLoss}%</span>- </span>- )}- {strategy.takeProfit != null && (- <span>- TP: <span style={{ color: F.GREEN }}>{strategy.takeProfit}%</span>- </span>- )}- </>- )}- {/* Python strategy details */}- {strategy.type === 'python' && (- <>- {strategy.category && (- <span>- Category: <span style={{ color: F.PURPLE }}>{strategy.category}</span>- </span>- )}- {strategy.baseStrategyId && (- <span>- Base: <span style={{ color: F.MUTED }}>{strategy.baseStrategyId}</span>- </span>- )}- </>- )}- </div>+ </div>++ {/* Card Body */}+ <div style={{ padding: '10px 12px' }}>+ {/* Description */}+ {strategy.description && (+ <div style={{+ fontSize: '9px', color: F.MUTED, lineHeight: '1.5',+ marginBottom: '8px', maxHeight: '28px', overflow: 'hidden',+ textOverflow: 'ellipsis', display: '-webkit-box',+ WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' as const,+ }}>+ {strategy.description}+ </div>+ )}++ {/* Strategy Details */}+ {isJson ? (+ <div style={{+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '6px',+ }}>+ <div style={{ backgroundColor: F.DARK_BG, padding: '6px 8px', borderRadius: '2px', border: `1px solid ${F.BORDER}` }}>+ <div style={{ fontSize: '7px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '2px' }}>TIMEFRAME</div>+ <div style={{ fontSize: '10px', fontWeight: 700, color: F.CYAN }}>{strategy.timeframe || '—'}</div>+ </div>+ <div style={{ backgroundColor: F.DARK_BG, padding: '6px 8px', borderRadius: '2px', border: `1px solid ${F.BORDER}` }}>+ <div style={{ fontSize: '7px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '2px' }}>ENTRY</div>+ <div style={{ fontSize: '10px', fontWeight: 700, color: F.GREEN, display: 'flex', alignItems: 'center', gap: '3px' }}>+ <ArrowUpRight size={9} /> {strategy.entryConditionCount}</div>- <div style={{ display: 'flex', gap: '4px', marginLeft: '12px' }}>- <button- onClick={() => handleDeploy(strategy)}- style={{- padding: '4px 8px',- backgroundColor: `${F.GREEN}20`,- color: F.GREEN,- border: 'none',- borderRadius: '2px',- fontSize: '8px',- fontWeight: 700,- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '3px',- transition: 'all 0.2s',- }}- >- <Rocket size={10} /> DEPLOY- </button>- <button- onClick={() => handleEdit(strategy)}- style={{- padding: '4px 6px',- backgroundColor: 'transparent',- border: `1px solid ${F.BORDER}`,- color: F.GRAY,- borderRadius: '2px',- cursor: 'pointer',- transition: 'all 0.2s',- }}- >- <Edit size={11} />- </button>- <button- onClick={() => handleDelete(strategy)}- style={{- padding: '4px 6px',- backgroundColor: 'transparent',- border: `1px solid ${F.BORDER}`,- color: F.GRAY,- borderRadius: '2px',- cursor: 'pointer',- transition: 'all 0.2s',- }}- onMouseEnter={(e) => {- (e.currentTarget as HTMLElement).style.color = F.RED;- (e.currentTarget as HTMLElement).style.borderColor = F.RED;- }}- onMouseLeave={(e) => {- (e.currentTarget as HTMLElement).style.color = F.GRAY;- (e.currentTarget as HTMLElement).style.borderColor = F.BORDER;- }}- >- <Trash2 size={11} />- </button>+ </div>+ <div style={{ backgroundColor: F.DARK_BG, padding: '6px 8px', borderRadius: '2px', border: `1px solid ${F.BORDER}` }}>+ <div style={{ fontSize: '7px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '2px' }}>EXIT</div>+ <div style={{ fontSize: '10px', fontWeight: 700, color: F.RED, display: 'flex', alignItems: 'center', gap: '3px' }}>+ <ArrowDownRight size={9} /> {strategy.exitConditionCount}</div></div>- ))}- </div>- )}+ <div style={{ backgroundColor: F.DARK_BG, padding: '6px 8px', borderRadius: '2px', border: `1px solid ${F.BORDER}` }}>+ <div style={{ fontSize: '7px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '2px' }}>RISK</div>+ <div style={{ fontSize: '9px', fontWeight: 700, color: F.YELLOW, display: 'flex', alignItems: 'center', gap: '2px' }}>+ <Shield size={8} />+ {strategy.stopLoss != null ? `${strategy.stopLoss}%` : '—'}+ </div>+ </div>+ </div>+ ) : (+ <div style={{+ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px',+ }}>+ {strategy.category && (+ <div style={{ backgroundColor: F.DARK_BG, padding: '6px 8px', borderRadius: '2px', border: `1px solid ${F.BORDER}` }}>+ <div style={{ fontSize: '7px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '2px' }}>CATEGORY</div>+ <div style={{ fontSize: '9px', fontWeight: 700, color: F.PURPLE }}>{strategy.category}</div>+ </div>+ )}+ {strategy.baseStrategyId && (+ <div style={{ backgroundColor: F.DARK_BG, padding: '6px 8px', borderRadius: '2px', border: `1px solid ${F.BORDER}` }}>+ <div style={{ fontSize: '7px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px', marginBottom: '2px' }}>BASE</div>+ <div style={{+ fontSize: '9px', color: F.GRAY, overflow: 'hidden',+ textOverflow: 'ellipsis', whiteSpace: 'nowrap',+ }}>+ {strategy.baseStrategyId}+ </div>+ </div>+ )}+ </div>+ )}+ </div>- {/* Click outside to close dropdown */}- {showFilterDropdown && (- <div- style={{- position: 'fixed',- top: 0,- left: 0,- right: 0,- bottom: 0,- zIndex: 99,- }}- onClick={() => setShowFilterDropdown(false)}- />- )}+ {/* Card Footer — Action Buttons */}+ <div style={{+ padding: '8px 12px',+ borderTop: `1px solid ${F.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ {strategy.updatedAt && (+ <span style={{ fontSize: '8px', color: F.MUTED, display: 'flex', alignItems: 'center', gap: '3px' }}>+ <Calendar size={8} />+ {new Date(strategy.updatedAt).toLocaleDateString()}+ </span>+ )}+ </div>+ <div style={{ display: 'flex', gap: '4px' }}>+ <button+ onClick={onEdit}+ style={{+ padding: '5px 10px', backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`, color: F.GRAY,+ borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '3px',+ transition: 'all 0.2s', letterSpacing: '0.5px',+ }}+ onMouseEnter={e => { e.currentTarget.style.borderColor = F.ORANGE; e.currentTarget.style.color = F.WHITE; }}+ onMouseLeave={e => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.GRAY; }}+ >+ <Edit size={9} /> EDIT+ </button>+ <button+ onClick={onDeploy}+ style={{+ padding: '5px 10px', backgroundColor: `${F.GREEN}15`,+ border: `1px solid ${F.GREEN}30`, color: F.GREEN,+ borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '3px',+ transition: 'all 0.2s', letterSpacing: '0.5px',+ }}+ onMouseEnter={e => { e.currentTarget.style.backgroundColor = `${F.GREEN}25`; }}+ onMouseLeave={e => { e.currentTarget.style.backgroundColor = `${F.GREEN}15`; }}+ >+ <Rocket size={9} /> DEPLOY+ </button>+ </div>+ </div></div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/indicators.ts b/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/indicators.tsindex d8ab9b7b1..fd1e9ad38 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/indicators.ts+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/indicators.ts@@ -16,6 +16,7 @@ export const OPERATORS = [];export const TIMEFRAMES = [+ { value: 'live', label: 'Live (Tick)' },{ value: '1m', label: '1 Min' },{ value: '3m', label: '3 Min' },{ value: '5m', label: '5 Min' },diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/services/algoTradingService.ts b/fincept-terminal-desktop/src/components/tabs/algo-trading/services/algoTradingService.tsindex b779c9821..ccc3ab89e 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/services/algoTradingService.ts+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/services/algoTradingService.ts@@ -101,6 +101,11 @@ export async function stopAllAlgoDeployments(): Promise<ApiResult<{ stopped: numreturn parseResult(raw);}+export async function deleteAlgoDeployment(deployId: string): Promise<ApiResult> {+ const raw = await invoke<string>('delete_algo_deployment', { deployId });+ return parseResult(raw);+}+export async function listAlgoDeployments(): Promise<ApiResult<AlgoDeployment[]>> {const raw = await invoke<string>('list_algo_deployments');return parseResult(raw);diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaRightPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaRightPanel.tsxnew file mode 100644index 000000000..3ae99a1a1--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaRightPanel.tsx@@ -0,0 +1,298 @@+/**+ * Alpha Arena Right Panel+ *+ * 7-tab side panel: Decisions, HITL, Sentiment, Metrics, Grid, Research, Broker+ * Fincept Terminal Design - sharp edges, inline styles, monospace font.+ */++import React from 'react';+import {+ Brain, Shield, Newspaper, BarChart3, Grid3X3, FileSearch, Building,+ Sparkles,+} from 'lucide-react';+import {+ HITLApprovalPanel,+ SentimentPanel,+ PortfolioMetricsPanel,+ GridStrategyPanel,+ ResearchPanel,+ BrokerSelector,+} from './components';+import type { ModelDecision } from './types';+import type { RightPanelTab } from './useAlphaArena';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ PURPLE: '#9D4EDD',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CARD_BG: '#0A0A0A',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A',+} as const;++const TAB_ITEMS: { key: RightPanelTab; icon: React.ComponentType<{ size?: number }>; label: string }[] = [+ { key: 'decisions', icon: Brain, label: 'DECISIONS' },+ { key: 'hitl', icon: Shield, label: 'HITL' },+ { key: 'sentiment', icon: Newspaper, label: 'SENTIMENT' },+ { key: 'metrics', icon: BarChart3, label: 'METRICS' },+ { key: 'grid', icon: Grid3X3, label: 'GRID' },+ { key: 'research', icon: FileSearch, label: 'RESEARCH' },+ { key: 'broker', icon: Building, label: 'BROKER' },+];++interface AlphaArenaRightPanelProps {+ rightPanelTab: RightPanelTab;+ setRightPanelTab: (tab: RightPanelTab) => void;+ decisions: ModelDecision[];+ competitionId: string | null;+ symbol: string;+ latestPrice: number | null;+ selectedBroker: string | null;+ setSelectedBroker: (broker: string | null) => void;+ refreshCompetitionData: () => void;+}++const AlphaArenaRightPanel: React.FC<AlphaArenaRightPanelProps> = ({+ rightPanelTab,+ setRightPanelTab,+ decisions,+ competitionId,+ symbol,+ latestPrice,+ selectedBroker,+ setSelectedBroker,+ refreshCompetitionData,+}) => {+ return (+ <div style={{+ width: '400px',+ borderLeft: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: FINCEPT.DARK_BG,+ }}>+ {/* Tab Bar */}+ <div style={{+ display: 'flex',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ overflowX: 'auto',+ backgroundColor: FINCEPT.HEADER_BG,+ flexShrink: 0,+ }}>+ {TAB_ITEMS.map(({ key, icon: Icon, label }) => (+ <button+ key={key}+ onClick={() => setRightPanelTab(key)}+ style={{+ padding: '6px 8px',+ fontSize: '9px',+ fontWeight: rightPanelTab === key ? 700 : 600,+ whiteSpace: 'nowrap',+ display: 'flex',+ alignItems: 'center',+ gap: '3px',+ backgroundColor: rightPanelTab === key ? FINCEPT.ORANGE : 'transparent',+ color: rightPanelTab === key ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ border: 'none',+ borderBottom: rightPanelTab === key ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',+ cursor: 'pointer',+ transition: 'all 0.15s',+ letterSpacing: '0.3px',+ }}+ onMouseEnter={(e) => {+ if (rightPanelTab !== key) {+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;+ e.currentTarget.style.color = FINCEPT.WHITE;+ }+ }}+ onMouseLeave={(e) => {+ if (rightPanelTab !== key) {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.color = FINCEPT.GRAY;+ }+ }}+ >+ <Icon size={10} />+ {label}+ </button>+ ))}+ </div>++ {/* Content */}+ <div style={{ flex: 1, overflowY: 'auto' }}>+ {rightPanelTab === 'decisions' && (+ <DecisionsContent decisions={decisions} />+ )}+ {rightPanelTab === 'hitl' && (+ <div style={{ padding: '8px' }}>+ <HITLApprovalPanel+ competitionId={competitionId || undefined}+ onApprovalChange={() => refreshCompetitionData()}+ />+ </div>+ )}+ {rightPanelTab === 'sentiment' && (+ <div style={{ padding: '8px' }}>+ <SentimentPanel+ symbol={symbol.split('/')[0]}+ showMarketMood={true}+ />+ </div>+ )}+ {rightPanelTab === 'metrics' && competitionId && (+ <div style={{ padding: '8px' }}>+ <PortfolioMetricsPanel competitionId={competitionId} />+ </div>+ )}+ {rightPanelTab === 'metrics' && !competitionId && (+ <div style={{ padding: '32px', textAlign: 'center', color: FINCEPT.GRAY }}>+ <BarChart3 size={32} style={{ opacity: 0.3, margin: '0 auto 8px' }} />+ <p style={{ fontSize: '11px' }}>Start a competition to view metrics</p>+ </div>+ )}+ {rightPanelTab === 'grid' && (+ <div style={{ padding: '8px' }}>+ <GridStrategyPanel+ symbol={symbol.split('/')[0]}+ currentPrice={latestPrice || undefined}+ />+ </div>+ )}+ {rightPanelTab === 'research' && (+ <div style={{ padding: '8px' }}>+ <ResearchPanel />+ </div>+ )}+ {rightPanelTab === 'broker' && (+ <div style={{ padding: '8px' }}>+ <BrokerSelector+ selectedBrokerId={selectedBroker || undefined}+ onBrokerSelect={(broker) => setSelectedBroker(broker.id)}+ />+ </div>+ )}+ </div>+ </div>+ );+};++// Decisions sub-content - Terminal style+const DecisionsContent: React.FC<{ decisions: ModelDecision[] }> = ({ decisions }) => {+ const safeDecisions = Array.isArray(decisions) ? decisions : [];++ return (+ <div style={{ display: 'flex', flexDirection: 'column', backgroundColor: FINCEPT.CARD_BG }}>+ {/* Header */}+ <div style={{+ padding: '8px 12px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ backgroundColor: FINCEPT.HEADER_BG,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <Brain size={14} style={{ color: FINCEPT.PURPLE }} />+ <span style={{ fontWeight: 700, fontSize: '11px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>AI DECISIONS</span>+ </div>+ <span style={{+ fontSize: '9px',+ padding: '1px 6px',+ backgroundColor: FINCEPT.BORDER,+ color: FINCEPT.GRAY,+ fontWeight: 600,+ }}>+ {safeDecisions.length}+ </span>+ </div>++ {/* List */}+ <div style={{ overflowY: 'auto' }}>+ {safeDecisions.length === 0 ? (+ <div style={{ padding: '32px', textAlign: 'center', color: FINCEPT.GRAY }}>+ <Sparkles size={32} style={{ opacity: 0.3, margin: '0 auto 8px' }} />+ <p style={{ fontSize: '11px' }}>No decisions yet</p>+ <p style={{ fontSize: '9px', marginTop: '4px' }}>Run a cycle to see AI trading decisions</p>+ </div>+ ) : (+ <div>+ {safeDecisions.slice(0, 50).map((decision, idx) => (+ <div+ key={`${decision.model_name}-${decision.cycle_number}-${idx}`}+ style={{+ padding: '8px 10px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ transition: 'background-color 0.15s',+ cursor: 'default',+ }}+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = FINCEPT.PANEL_BG; }}+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent'; }}+ >+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '4px' }}>+ <span style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.WHITE }}>+ {decision.model_name}+ </span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ Cycle {decision.cycle_number}+ </span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <span style={{+ fontSize: '9px',+ padding: '1px 6px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ backgroundColor: decision.action === 'buy' ? `${FINCEPT.GREEN}20` :+ decision.action === 'sell' ? `${FINCEPT.RED}20` :+ decision.action === 'short' ? `${FINCEPT.PURPLE}20` :+ `${FINCEPT.GRAY}20`,+ color: decision.action === 'buy' ? FINCEPT.GREEN :+ decision.action === 'sell' ? FINCEPT.RED :+ decision.action === 'short' ? FINCEPT.PURPLE :+ FINCEPT.GRAY,+ }}>+ {(decision.action || 'hold').toUpperCase()}+ </span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ {decision.symbol}+ </span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ Qty: {(decision.quantity ?? 0).toFixed(4)}+ </span>+ </div>+ {decision.reasoning && (+ <p style={{+ fontSize: '9px',+ marginTop: '4px',+ color: FINCEPT.MUTED,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ display: '-webkit-box',+ WebkitLineClamp: 2,+ WebkitBoxOrient: 'vertical',+ }}>+ {decision.reasoning}+ </p>+ )}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: '4px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ Confidence: {((decision.confidence ?? 0) * 100).toFixed(0)}%+ </span>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+};++export default AlphaArenaRightPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsxindex 638e2ec6e..86bd4bb37 100644--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx@@ -1,99 +1,72 @@/**- * Alpha Arena Tab - Fincept Terminal Design (v2.1)+ * Alpha Arena Tab - Fincept Terminal Design (v3.0)*- * AI Trading Competition Platform with:- * - LLM configuration from Settings- * - Professional terminal-style UI- * - Real-time leaderboard & performance charts- * - Repository integration for trade decisions+ * AI Trading Competition Platform - Render-only component.+ * All state/logic lives in useAlphaArena hook.+ * Right panel extracted to AlphaArenaRightPanel.+ *+ * UI matches Fincept terminal aesthetic: sharp edges, monospace font,+ * inline styles, FINCEPT color palette.*/-import React, { useState, useEffect, useCallback, useRef } from 'react';-import { listen, UnlistenFn } from '@tauri-apps/api/event';-import { showConfirm } from '@/utils/notifications';+import React from 'react';import {- Bot, Trophy, Play, Pause, RotateCcw, Plus, Settings,+ Trophy, Play, Pause, RotateCcw, Plus,TrendingUp, TrendingDown, Activity, Zap, AlertCircle, CheckCircle,- ChevronRight, Loader2, BarChart3, Clock, Target, Brain,- RefreshCw, Eye, Users, Sparkles, Check, Circle, History, Trash2, PlayCircle,- StopCircle, XCircle, Shield, Newspaper, Grid3X3, FileSearch, Building,+ ChevronRight, Loader2, Clock, Brain,+ RefreshCw, Check, Circle, History, Trash2, PlayCircle,+ StopCircle, XCircle,} from 'lucide-react';-import { TabFooter } from '@/components/common/TabFooter';import { withErrorBoundary } from '@/components/common/ErrorBoundary';-import { sqliteService, type LLMModelConfig, type LLMConfig, type LLMGlobalSettings } from '@/services/core/sqliteService';-import { withTimeout } from '@/services/core/apiUtils';-import { validateString } from '@/services/core/validators';-import { useCache, cacheKey } from '@/hooks/useCache';-import alphaArenaService, { type StoredCompetition } from './services/alphaArenaService';-import { useAuth } from '@/contexts/AuthContext';--// Enhanced Components-import {- HITLApprovalPanel,- SentimentPanel,- PortfolioMetricsPanel,- GridStrategyPanel,- ResearchPanel,- BrokerSelector,-} from './components';-import { alphaArenaEnhancedService } from './services/alphaArenaEnhancedService';--// Extended model type for Alpha Arena with API key-interface AlphaArenaModel {- id: string;- provider: string;- model_id: string;- display_name: string;- api_key?: string;- is_enabled: boolean;-}--// Progress event type from Rust backend-interface AlphaArenaProgress {- event_type: 'step' | 'info' | 'warning' | 'error' | 'complete';- step: number;- total_steps: number;- message: string;- details?: unknown;-}-import type {- CompetitionStatus,- LeaderboardEntry,- ModelDecision,- PerformanceSnapshot,- CompetitionMode,-} from './types';+import { APP_VERSION } from '@/constants/version';+import { useAlphaArena, type AlphaArenaModel } from './useAlphaArena';+import AlphaArenaRightPanel from './AlphaArenaRightPanel';+import PerformanceChart from './components/PerformanceChart';import { formatCurrency, formatPercent, getModelColor } from './types';--// Competition data shape for useCache-interface CompetitionData {- leaderboard: LeaderboardEntry[];- decisions: ModelDecision[];- snapshots: PerformanceSnapshot[];-}+import type { CompetitionMode } from './types';// =============================================================================-// Design Constants - Fincept Terminal Style+// Fincept Terminal Design Constants// =============================================================================-const COLORS = {+const FINCEPT = {ORANGE: '#FF8800',ORANGE_HOVER: '#FF9900',WHITE: '#FFFFFF',RED: '#FF3B3B',GREEN: '#00D66F',- BLUE: '#3B82F6',- PURPLE: '#8B5CF6',- YELLOW: '#EAB308',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',GRAY: '#787878',DARK_BG: '#000000',PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',CARD_BG: '#0A0A0A',BORDER: '#2A2A2A',BORDER_LIGHT: '#3A3A3A',- HOVER: '#1A1A1A',+ HOVER: '#1F1F1F',MUTED: '#4A4A4A',-};+} as const;++const TERMINAL_FONT = '"IBM Plex Mono", "Consolas", "Monaco", monospace';++const TERMINAL_STYLES = `+ @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap');+ .alpha-arena-terminal *::-webkit-scrollbar { width: 6px; height: 6px; }+ .alpha-arena-terminal *::-webkit-scrollbar-track { background: ${FINCEPT.DARK_BG}; }+ .alpha-arena-terminal *::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; }+ .alpha-arena-terminal *::-webkit-scrollbar-thumb:hover { background: ${FINCEPT.MUTED}; }+ @keyframes alpha-pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }+ @keyframes alpha-spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+`;const TRADING_SYMBOLS = [{ value: 'BTC/USD', label: 'Bitcoin (BTC/USD)' },@@ -140,707 +113,210 @@ const COMPETITION_MODES: { value: CompetitionMode; label: string; desc: string }// =============================================================================const AlphaArenaTab: React.FC = () => {- // Auth context for Fincept API key- const { session } = useAuth();-- // Competition state- const [competitionId, setCompetitionId] = useState<string | null>(null);- const [status, setStatus] = useState<CompetitionStatus | null>(null);- const [cycleCount, setCycleCount] = useState(0);-- // Data state- const [leaderboard, setLeaderboard] = useState<LeaderboardEntry[]>([]);- const [decisions, setDecisions] = useState<ModelDecision[]>([]);- const [snapshots, setSnapshots] = useState<PerformanceSnapshot[]>([]);-- // LLM state - from Settings- const [configuredLLMs, setConfiguredLLMs] = useState<AlphaArenaModel[]>([]);- const [selectedModels, setSelectedModels] = useState<AlphaArenaModel[]>([]);- const [llmGlobalSettings, setLlmGlobalSettings] = useState<LLMGlobalSettings>({ temperature: 0.7, max_tokens: 2000, system_prompt: '' });-- // UI state- const [isLoading, setIsLoading] = useState(false);- const [isAutoRunning, setIsAutoRunning] = useState(false);- const [isCancelling, setIsCancelling] = useState(false);- const [showCreatePanel, setShowCreatePanel] = useState(false);- const [showPastCompetitions, setShowPastCompetitions] = useState(false);- const [error, setError] = useState<string | null>(null);- const [success, setSuccess] = useState<string | null>(null);-- // Enhanced features state- type RightPanelTab = 'decisions' | 'hitl' | 'sentiment' | 'metrics' | 'grid' | 'research' | 'broker';- const [rightPanelTab, setRightPanelTab] = useState<RightPanelTab>('decisions');- const [selectedBroker, setSelectedBroker] = useState<string | null>(null);- const [latestPrice, setLatestPrice] = useState<number | null>(null);-- // Past competitions - managed by useCache (declared below after mountedRef)-- // Progress tracking state- const [progressSteps, setProgressSteps] = useState<AlphaArenaProgress[]>([]);- const [currentProgress, setCurrentProgress] = useState<AlphaArenaProgress | null>(null);- const progressListenerRef = useRef<UnlistenFn | null>(null);-- // Form state- const [competitionName, setCompetitionName] = useState('Alpha Arena Competition');- const [symbol, setSymbol] = useState('BTC/USD');- const [mode, setMode] = useState<CompetitionMode>('baseline');- const [initialCapital, setInitialCapital] = useState(10000);- const [cycleInterval, setCycleInterval] = useState(150);-- // Component mounted ref for async safety- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);-- // Auto-run ref- const autoRunIntervalRef = useRef<NodeJS.Timeout | null>(null);-- // Track if a cycle is currently running (to prevent overlapping cycles)- const cycleInProgressRef = useRef(false);-- // Ref to always hold the latest handleRunCycle to avoid stale closures in setInterval- const handleRunCycleRef = useRef<() => Promise<void>>(() => Promise.resolve());-- // =============================================================================- // Load LLM Models from Settings (llm_model_configs table)- // =============================================================================-- const loadLLMConfigs = useCallback(async () => {- try {- // Auto-fix any Google model IDs with incorrect format- await withTimeout(sqliteService.fixGoogleModelIds(), 15000);-- // Load from llm_model_configs table (individual models configured in Settings)- const modelConfigs = await withTimeout(sqliteService.getLLMModelConfigs(), 15000);- // Load provider configs for API key fallback and for fincept (which is auto-configured)- const providerConfigs = await withTimeout(sqliteService.getLLMConfigs(), 15000);-- // Load global LLM settings (temperature, max_tokens, system_prompt)- try {- const globalSettings = await withTimeout(sqliteService.getLLMGlobalSettings(), 10000);- if (mountedRef.current && globalSettings) {- setLlmGlobalSettings(globalSettings);- }- } catch (settingsErr) {- console.warn('[AlphaArena] Failed to load global LLM settings, using defaults:', settingsErr);- }-- // Process models - filter and validate- const validModels: AlphaArenaModel[] = [];-- // First, add fincept from provider configs (it's auto-configured, not in llm_model_configs)- // Use session API key for fincept (the same key used for all Fincept backend APIs)- const finceptProvider = providerConfigs.find(c => (c.provider || '').toLowerCase() === 'fincept');- const finceptApiKey = session?.api_key || finceptProvider?.api_key;- if (finceptProvider || finceptApiKey) {- validModels.push({- id: 'fincept-auto',- provider: 'fincept',- model_id: finceptProvider?.model || 'fincept-llm',- display_name: 'Fincept LLM (Auto)',- api_key: finceptApiKey || undefined,- is_enabled: true,- });- }-- // Then process models from llm_model_configs table- for (const model of modelConfigs) {- // Skip disabled models- if (!model.is_enabled) {- continue;- }-- const providerLower = (model.provider || '').toLowerCase();-- // Get API key - try model config first, then provider config- let apiKey = model.api_key;- if (!apiKey || apiKey.trim() === '') {- const providerConfig = providerConfigs.find(- c => (c.provider || '').toLowerCase() === providerLower- );- if (providerConfig?.api_key && providerConfig.api_key.trim() !== '') {- apiKey = providerConfig.api_key;- }- }-- // Skip if no API key (except ollama and fincept which may not need one in the same way)- const noApiKeyRequired = providerLower === 'ollama' || providerLower === 'fincept';- if ((!apiKey || apiKey.trim() === '') && !noApiKeyRequired) {- continue;- }-- validModels.push({- id: model.id,- provider: model.provider,- model_id: model.model_id,- display_name: model.display_name || model.model_id,- api_key: apiKey || undefined,- is_enabled: model.is_enabled,- });- }-- if (!mountedRef.current) return;- setConfiguredLLMs(validModels);-- // Pre-select first 2 models- if (validModels.length >= 2) {- setSelectedModels(validModels.slice(0, 2));- } else if (validModels.length === 1) {- setSelectedModels([validModels[0]]);- } else {- setSelectedModels([]);- }- } catch (err) {- if (!mountedRef.current) return;- console.error('[AlphaArena] Failed to load LLM configs:', err);- }- }, [session?.api_key]);-- useEffect(() => {- loadLLMConfigs();- }, [loadLLMConfigs]);-- // Reload LLM configs when user changes them in Settings tab- useEffect(() => {- const handler = () => {- loadLLMConfigs();- };- window.addEventListener('llm-config-changed', handler);- return () => {- window.removeEventListener('llm-config-changed', handler);- };- }, [loadLLMConfigs]);-- // =============================================================================- // Past Competitions (useCache)- // =============================================================================-- const pastCompetitionsCache = useCache<StoredCompetition[]>({- key: cacheKey('alpha-arena', 'past-competitions'),- category: 'alpha-arena',- fetcher: async () => {- const result = await alphaArenaService.listCompetitions(20);- if (result.success && result.competitions) {- return result.competitions;- }- return [];- },- ttl: 120,- staleWhileRevalidate: true,- });-- const pastCompetitions = pastCompetitionsCache.data || [];- const loadingPastCompetitions = pastCompetitionsCache.isLoading;-- // Resume a past competition- const handleResumeCompetition = async (comp: StoredCompetition) => {- setIsLoading(true);- setError(null);- setProgressSteps([]);-- try {- // Set the competition ID - the backend will restore from DB when we run a cycle- setCompetitionId(comp.competition_id);- setCycleCount(comp.cycle_count);- setStatus(comp.status as CompetitionStatus);- setShowPastCompetitions(false);- setSuccess(`Loaded competition: ${comp.config.competition_name}`);- setTimeout(() => { if (mountedRef.current) setSuccess(null); }, 3000);-- // Competition data will auto-fetch via useCache when competitionId changes- } catch (err) {- if (!mountedRef.current) return;- setError(err instanceof Error ? err.message : 'Failed to resume competition');- } finally {- if (mountedRef.current) setIsLoading(false);- }- };-- // Delete a competition- const handleDeleteCompetition = async (targetId: string, e: React.MouseEvent) => {- e.stopPropagation();-- const confirmed = await showConfirm(- 'This action cannot be undone.',- { title: 'Delete this competition?', type: 'danger' }- );- if (!confirmed) return;-- try {- const result = await alphaArenaService.deleteCompetition(targetId);- if (!mountedRef.current) return;- if (result.success) {- pastCompetitionsCache.invalidate();- // If deleting the active competition, reset state- if (competitionId === targetId) {- setCompetitionId(null);- setStatus(null);- setCycleCount(0);- setLeaderboard([]);- setDecisions([]);- setSnapshots([]);- }- setSuccess('Competition deleted');- setTimeout(() => { if (mountedRef.current) setSuccess(null); }, 3000);- } else {- setError(result.error || 'Failed to delete competition');- }- } catch (err) {- if (!mountedRef.current) return;- setError(err instanceof Error ? err.message : 'Failed to delete competition');- }- };-- // =============================================================================- // Progress Event Listener- // =============================================================================-- useEffect(() => {- // Listen for progress events from Rust backend- const setupListener = async () => {- progressListenerRef.current = await listen<AlphaArenaProgress>(- 'alpha-arena-progress',- (event) => {- const progress = event.payload;- setCurrentProgress(progress);- setProgressSteps(prev => {- // Avoid duplicates- if (prev.some(p => p.step === progress.step && p.message === progress.message)) {- return prev;- }- return [...prev, progress];- });-- // Handle completion- if (progress.event_type === 'complete') {- setTimeout(() => {- setCurrentProgress(null);- setProgressSteps([]);- }, 2000);- }-- // Handle errors- if (progress.event_type === 'error') {- setError(progress.message);- }- }- );- };-- setupListener();-- return () => {- if (progressListenerRef.current) {- progressListenerRef.current();- }- };- }, []);-- // =============================================================================- // Competition Data (useCache with auto-refresh)- // =============================================================================-- const compDataCache = useCache<CompetitionData>({- key: cacheKey('alpha-arena', 'comp-data', competitionId || 'none'),- category: 'alpha-arena',- fetcher: async () => {- const targetId = competitionId;- if (!targetId) return { leaderboard: [], decisions: [], snapshots: [] };-- const [leaderboardResult, decisionsResult, snapshotsResult] = await Promise.all([- alphaArenaService.getLeaderboard(targetId),- alphaArenaService.getDecisions(targetId),- alphaArenaService.getSnapshots(targetId),- ]);-- return {- leaderboard: leaderboardResult.success && leaderboardResult.leaderboard- ? leaderboardResult.leaderboard : [],- decisions: decisionsResult.success && decisionsResult.decisions- ? decisionsResult.decisions : [],- snapshots: snapshotsResult.success && snapshotsResult.snapshots- ? snapshotsResult.snapshots : [],- };- },- ttl: 30,- enabled: !!competitionId,- staleWhileRevalidate: true,- refetchInterval: 15000,- });-- // Sync cache data to local state for use in render functions- useEffect(() => {- if (compDataCache.data) {- setLeaderboard(compDataCache.data.leaderboard);- setDecisions(compDataCache.data.decisions);- setSnapshots(compDataCache.data.snapshots);- }- }, [compDataCache.data]);-- // Convenience function: refresh competition data (used after actions)- const refreshCompetitionData = useCallback(() => {- compDataCache.refresh();- }, [compDataCache]);-- // =============================================================================- // Competition Actions- // =============================================================================-- const handleCreateCompetition = async () => {- // Input validation- const nameCheck = validateString(competitionName, { minLength: 1, maxLength: 200 });- if (!nameCheck.valid) {- setError(`Competition name: ${nameCheck.error}`);- return;- }- if (selectedModels.length < 2) {- setError('Select at least 2 AI models from your configured models in Settings');- return;- }- if (!Number.isFinite(initialCapital) || initialCapital < 100) {- setError('Initial capital must be at least $100');- return;- }- if (!Number.isFinite(cycleInterval) || cycleInterval < 10) {- setError('Cycle interval must be at least 10 seconds');- return;- }-- setIsLoading(true);- setError(null);- setProgressSteps([]); // Reset progress- setCurrentProgress(null);-- try {- const result = await alphaArenaService.createCompetition({- competition_name: competitionName,- models: selectedModels.map(m => ({- name: m.display_name,- provider: m.provider,- model_id: m.model_id,- api_key: m.api_key, // Include API key from model config- initial_capital: initialCapital,- })),- symbols: [symbol],- initial_capital: initialCapital,- mode,- cycle_interval_seconds: cycleInterval,- // Pass global LLM settings from Settings tab- llm_settings: {- temperature: llmGlobalSettings.temperature,- max_tokens: llmGlobalSettings.max_tokens,- system_prompt: llmGlobalSettings.system_prompt,- },- });-- if (!mountedRef.current) return;- if (result.success && result.competition_id) {- setCompetitionId(result.competition_id);- setStatus('created');- setShowCreatePanel(false);- setSuccess('Competition created successfully');- setTimeout(() => { if (mountedRef.current) setSuccess(null); }, 3000);- } else {- setError(result.error || 'Failed to create competition');- }- } catch (err) {- if (!mountedRef.current) return;- setError(err instanceof Error ? err.message : 'Unknown error');- } finally {- if (mountedRef.current) setIsLoading(false);- }- };-- const handleRunCycle = useCallback(async () => {- if (!competitionId) return;-- // Prevent overlapping cycles- if (cycleInProgressRef.current) {- return;- }-- cycleInProgressRef.current = true;- setIsLoading(true);- setError(null);- setProgressSteps([]);- setCurrentProgress(null);-- try {- // Capture current values before async operation to prevent stale closures- const currentCompetitionId = competitionId;- const currentModels = [...selectedModels];- // Build API keys map from selected models for the Python backend- const apiKeys: Record<string, string> = {};- for (const model of currentModels) {- if (model.api_key && !apiKeys[model.provider]) {- apiKeys[model.provider] = model.api_key;- }- }- const result = await alphaArenaService.runCycle(currentCompetitionId, Object.keys(apiKeys).length > 0 ? apiKeys : undefined);-- if (!mountedRef.current) return;- if (result.success) {- setCycleCount(prev => result.cycle_number || prev + 1);- setStatus('running');- refreshCompetitionData();- // Surface any decision save warnings- if (result.warnings && result.warnings.length > 0) {- setError(`Cycle completed with warnings: ${result.warnings[0]}`);- setTimeout(() => { if (mountedRef.current) setError(null); }, 5000);- }- } else {- setError(result.error || 'Cycle failed');- }- } catch (err) {- if (!mountedRef.current) return;- setError(err instanceof Error ? err.message : 'Unknown error');- } finally {- cycleInProgressRef.current = false;- if (mountedRef.current) setIsLoading(false);- }- }, [competitionId, selectedModels, refreshCompetitionData]);-- // Keep ref in sync so setInterval always calls the latest version- useEffect(() => {- handleRunCycleRef.current = handleRunCycle;- }, [handleRunCycle]);-- const handleToggleAutoRun = useCallback(() => {- if (isAutoRunning) {- if (autoRunIntervalRef.current) {- clearInterval(autoRunIntervalRef.current);- autoRunIntervalRef.current = null;- }- setIsAutoRunning(false);- setStatus('paused');- } else {- setIsAutoRunning(true);- setStatus('running');-- // Run first cycle immediately- handleRunCycleRef.current();-- // Use ref in interval to always call the latest handleRunCycle- autoRunIntervalRef.current = setInterval(() => {- handleRunCycleRef.current();- }, cycleInterval * 1000);- }- }, [isAutoRunning, cycleInterval]);-- const handleReset = useCallback(() => {- if (autoRunIntervalRef.current) {- clearInterval(autoRunIntervalRef.current);- autoRunIntervalRef.current = null;- }- // Cancel any ongoing operation- // Reset cycle in progress flag- cycleInProgressRef.current = false;- setCompetitionId(null);- setStatus(null);- setCycleCount(0);- setLeaderboard([]);- setDecisions([]);- setSnapshots([]);- setIsAutoRunning(false);- setIsLoading(false);- setIsCancelling(false);- setError(null);- setProgressSteps([]);- setCurrentProgress(null);- }, []);-- // Cancel ongoing operation- const handleCancel = useCallback(() => {- setIsCancelling(true);-- // Stop auto-run if active- if (autoRunIntervalRef.current) {- clearInterval(autoRunIntervalRef.current);- autoRunIntervalRef.current = null;- setIsAutoRunning(false);- }-- // Reset cycle in progress flag- cycleInProgressRef.current = false;-- // Reset loading states- setIsLoading(false);- setIsCancelling(false);- setProgressSteps([]);- setCurrentProgress(null);- setStatus('paused');- setSuccess('Operation cancelled');- setTimeout(() => setSuccess(null), 2000);- }, []);-- useEffect(() => {- return () => {- if (autoRunIntervalRef.current) {- clearInterval(autoRunIntervalRef.current);- }- };- }, []);-- // Continuous Binance price polling when competition is active (every 7s)- useEffect(() => {- if (!competitionId || !symbol) return;- let cancelled = false;-- const fetchPrice = () => {- alphaArenaEnhancedService.getBrokerTicker(symbol).then(result => {- if (!cancelled && mountedRef.current && result.success && result.ticker) {- setLatestPrice(result.ticker.price);- }- }).catch(() => {});- };-- fetchPrice();- const intervalId = setInterval(fetchPrice, 7000);-- return () => {- cancelled = true;- clearInterval(intervalId);- };- }, [competitionId, symbol]);-- const toggleModelSelection = (model: AlphaArenaModel) => {- setSelectedModels(prev => {- const isSelected = prev.some(m => m.id === model.id);- if (isSelected) {- return prev.filter(m => m.id !== model.id);- }- return [...prev, model];- });- };+ const arena = useAlphaArena();// =============================================================================- // Render: Header+ // Render: Terminal Header// =============================================================================const renderHeader = () => (- <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER, backgroundColor: COLORS.PANEL_BG }}>- <div className="flex items-center gap-3">- <Trophy size={20} style={{ color: COLORS.ORANGE }} />- <h1 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>Alpha Arena</h1>- <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.PURPLE + '20', color: COLORS.PURPLE }}>- AI Trading Competition+ <div style={{+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,+ padding: '6px 12px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexShrink: 0,+ boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`,+ fontFamily: TERMINAL_FONT,+ }}>+ {/* Left Section */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Trophy size={18} style={{ color: FINCEPT.ORANGE, filter: `drop-shadow(0 0 4px ${FINCEPT.ORANGE})` }} />+ <span style={{+ color: FINCEPT.ORANGE,+ fontWeight: 700,+ fontSize: '14px',+ letterSpacing: '0.5px',+ textShadow: `0 0 10px ${FINCEPT.ORANGE}40`,+ }}>+ ALPHA ARENA+ </span>+ </div>++ <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />++ <span style={{+ fontSize: '9px',+ padding: '2px 8px',+ backgroundColor: `${FINCEPT.PURPLE}20`,+ border: `1px solid ${FINCEPT.PURPLE}40`,+ color: FINCEPT.PURPLE,+ fontWeight: 600,+ letterSpacing: '0.5px',+ }}>+ AI TRADING COMPETITION</span></div>- <div className="flex items-center gap-2">- {competitionId && (- <div className="flex items-center gap-2 mr-4">- <div className="flex items-center gap-1 px-2 py-1 rounded" style={{ backgroundColor: COLORS.BORDER }}>- <Activity size={12} style={{ color: isAutoRunning ? COLORS.GREEN : COLORS.GRAY }} />- <span className="text-xs" style={{ color: COLORS.WHITE }}>Cycle: {cycleCount}</span>+ {/* Right Section */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>+ {arena.competitionId && (+ <>+ {arena.latestPrice !== null && (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ padding: '3px 8px',+ backgroundColor: `${FINCEPT.GREEN}10`,+ border: `1px solid ${FINCEPT.GREEN}25`,+ }}>+ <Zap size={10} style={{ color: FINCEPT.GREEN }} />+ <span style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.GREEN, fontFamily: TERMINAL_FONT }}>+ ${arena.latestPrice.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}+ </span>+ </div>+ )}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ padding: '3px 8px',+ backgroundColor: FINCEPT.BORDER,+ }}>+ <Activity size={12} style={{ color: arena.isAutoRunning ? FINCEPT.GREEN : FINCEPT.GRAY }} />+ <span style={{ fontSize: '10px', color: FINCEPT.WHITE, fontWeight: 600 }}>Cycle: {arena.cycleCount}</span></div>- <div- className="px-2 py-1 rounded text-xs"- style={{- backgroundColor: status === 'running' ? COLORS.GREEN + '20' : COLORS.GRAY + '20',- color: status === 'running' ? COLORS.GREEN : COLORS.GRAY,- }}- >- {isAutoRunning ? 'AUTO-RUNNING' : status?.toUpperCase() || 'IDLE'}+ <div style={{+ padding: '3px 8px',+ fontSize: '9px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ backgroundColor: arena.status === 'running' ? `${FINCEPT.GREEN}20` : `${FINCEPT.GRAY}20`,+ color: arena.status === 'running' ? FINCEPT.GREEN : FINCEPT.GRAY,+ border: `1px solid ${arena.status === 'running' ? FINCEPT.GREEN : FINCEPT.GRAY}40`,+ }}>+ {arena.isAutoRunning ? 'AUTO-RUNNING' : arena.status?.toUpperCase() || 'IDLE'}</div>- </div>++ <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />+ </>)}<button- onClick={() => loadLLMConfigs()}- className="p-2 rounded transition-colors hover:bg-[#1A1A1A]"+ onClick={() => arena.loadLLMConfigs()}+ style={{+ padding: '5px 7px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ color: FINCEPT.GRAY,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ transition: 'all 0.15s',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;+ e.currentTarget.style.color = FINCEPT.WHITE;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.color = FINCEPT.GRAY;+ }}title="Refresh LLM configs">- <RefreshCw size={16} style={{ color: COLORS.GRAY }} />+ <RefreshCw size={14} /></button></div></div>);// =============================================================================- // Render: Progress Panel (Real-time streaming updates)+ // Render: Progress Panel// =============================================================================const renderProgressPanel = () => {- if (!isLoading && progressSteps.length === 0) return null;+ if (!arena.isLoading && arena.progressSteps.length === 0) return null;return (- <div- className="p-4 rounded-lg mb-4"- style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.ORANGE}40`,- boxShadow: `0 0 20px ${COLORS.ORANGE}10`- }}- >- <div className="flex items-center justify-between mb-3">- <div className="flex items-center gap-2">- <Loader2 size={18} className="animate-spin" style={{ color: COLORS.ORANGE }} />- <h3 className="font-medium" style={{ color: COLORS.WHITE }}>- {currentProgress ? currentProgress.message : 'Processing...'}- </h3>+ <div style={{+ padding: '12px',+ marginBottom: '8px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.ORANGE}40`,+ boxShadow: `0 0 20px ${FINCEPT.ORANGE}10`,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '10px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Loader2 size={16} style={{ color: FINCEPT.ORANGE, animation: 'alpha-spin 1s linear infinite' }} />+ <span style={{ fontWeight: 600, fontSize: '12px', color: FINCEPT.WHITE }}>+ {arena.currentProgress ? arena.currentProgress.message : 'Processing...'}+ </span></div>- {/* STOP button in progress panel */}<button- onClick={handleCancel}- disabled={isCancelling}- className="px-3 py-1.5 rounded text-xs font-medium flex items-center gap-1.5 transition-colors"+ onClick={arena.handleCancel}+ disabled={arena.isCancelling}style={{- backgroundColor: COLORS.RED,- color: COLORS.WHITE,- opacity: isCancelling ? 0.5 : 1,+ padding: '4px 10px',+ backgroundColor: FINCEPT.RED,+ color: FINCEPT.WHITE,+ border: 'none',+ fontSize: '10px',+ fontWeight: 600,+ cursor: arena.isCancelling ? 'not-allowed' : 'pointer',+ opacity: arena.isCancelling ? 0.5 : 1,+ display: 'flex',+ alignItems: 'center',+ gap: '4px',}}>- {isCancelling ? <Loader2 size={12} className="animate-spin" /> : <XCircle size={12} />}- {isCancelling ? 'Stopping...' : 'Cancel'}+ {arena.isCancelling ? <Loader2 size={10} style={{ animation: 'alpha-spin 1s linear infinite' }} /> : <XCircle size={10} />}+ {arena.isCancelling ? 'Stopping...' : 'Cancel'}</button></div>- {/* Progress Bar */}- {currentProgress && (- <div className="mb-3">- <div className="h-2 rounded-full overflow-hidden" style={{ backgroundColor: COLORS.BORDER }}>- <div- className="h-full transition-all duration-300 ease-out"- style={{- width: `${(currentProgress.step / currentProgress.total_steps) * 100}%`,- backgroundColor: currentProgress.event_type === 'error' ? COLORS.RED :- currentProgress.event_type === 'complete' ? COLORS.GREEN : COLORS.ORANGE- }}- />+ {arena.currentProgress && (+ <div style={{ marginBottom: '10px' }}>+ <div style={{ height: '4px', overflow: 'hidden', backgroundColor: FINCEPT.BORDER }}>+ <div style={{+ height: '100%',+ transition: 'width 0.3s ease-out',+ width: `${(arena.currentProgress.step / arena.currentProgress.total_steps) * 100}%`,+ backgroundColor: arena.currentProgress.event_type === 'error' ? FINCEPT.RED :+ arena.currentProgress.event_type === 'complete' ? FINCEPT.GREEN : FINCEPT.ORANGE,+ }} /></div>- <div className="flex justify-between mt-1">- <span className="text-xs" style={{ color: COLORS.GRAY }}>- Step {currentProgress.step} of {currentProgress.total_steps}+ <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '4px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ Step {arena.currentProgress.step} of {arena.currentProgress.total_steps}</span>- <span className="text-xs" style={{ color: COLORS.GRAY }}>- {Math.round((currentProgress.step / currentProgress.total_steps) * 100)}%+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ {Math.round((arena.currentProgress.step / arena.currentProgress.total_steps) * 100)}%</span></div></div>)}- {/* Steps Log */}- <div className="space-y-1 max-h-40 overflow-y-auto">- {progressSteps.map((step, idx) => (- <div key={idx} className="flex items-center gap-2 text-xs">+ <div style={{ maxHeight: '120px', overflowY: 'auto' }}>+ {arena.progressSteps.map((step, idx) => (+ <div key={idx} style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '10px', marginBottom: '2px' }}>{step.event_type === 'complete' ? (- <Check size={12} style={{ color: COLORS.GREEN }} />+ <Check size={10} style={{ color: FINCEPT.GREEN }} />) : step.event_type === 'error' ? (- <AlertCircle size={12} style={{ color: COLORS.RED }} />+ <AlertCircle size={10} style={{ color: FINCEPT.RED }} />) : step.event_type === 'warning' ? (- <AlertCircle size={12} style={{ color: COLORS.YELLOW }} />+ <AlertCircle size={10} style={{ color: FINCEPT.YELLOW }} />) : step.event_type === 'step' ? (- <Circle size={12} style={{ color: COLORS.ORANGE }} />+ <Circle size={10} style={{ color: FINCEPT.ORANGE }} />) : (- <ChevronRight size={12} style={{ color: COLORS.GRAY }} />+ <ChevronRight size={10} style={{ color: FINCEPT.GRAY }} />)}<span style={{- color: step.event_type === 'error' ? COLORS.RED :- step.event_type === 'complete' ? COLORS.GREEN :- step.event_type === 'warning' ? COLORS.YELLOW : COLORS.GRAY+ color: step.event_type === 'error' ? FINCEPT.RED :+ step.event_type === 'complete' ? FINCEPT.GREEN :+ step.event_type === 'warning' ? FINCEPT.YELLOW : FINCEPT.GRAY,}}>{step.message}</span>@@ -856,138 +332,183 @@ const AlphaArenaTab: React.FC = () => {// =============================================================================const renderPastCompetitions = () => (- <div className="p-4 rounded-lg" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="flex items-center justify-between mb-4">- <div className="flex items-center gap-2">- <History size={18} style={{ color: COLORS.ORANGE }} />- <h2 className="font-semibold" style={{ color: COLORS.WHITE }}>Past Competitions</h2>- <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}>- {pastCompetitions.length} saved+ <div style={{ padding: '12px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <History size={16} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontWeight: 700, fontSize: '12px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>PAST COMPETITIONS</span>+ <span style={{+ fontSize: '9px',+ padding: '1px 6px',+ backgroundColor: FINCEPT.BORDER,+ color: FINCEPT.GRAY,+ fontWeight: 600,+ }}>+ {arena.pastCompetitions.length}</span></div>- <div className="flex items-center gap-2">+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}><button- onClick={() => pastCompetitionsCache.refresh()}- disabled={loadingPastCompetitions}- className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"+ onClick={() => arena.pastCompetitionsCache.refresh()}+ disabled={arena.loadingPastCompetitions}+ style={{+ padding: '4px 6px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ color: FINCEPT.GRAY,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}title="Refresh">- <RefreshCw size={14} className={loadingPastCompetitions ? 'animate-spin' : ''} style={{ color: COLORS.GRAY }} />+ <RefreshCw size={12} style={arena.loadingPastCompetitions ? { animation: 'alpha-spin 1s linear infinite' } : {}} /></button><button- onClick={() => setShowPastCompetitions(false)}- className="text-xs px-2 py-1 rounded"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}+ onClick={() => arena.setShowPastCompetitions(false)}+ style={{+ fontSize: '10px',+ padding: '4px 10px',+ backgroundColor: FINCEPT.BORDER,+ color: FINCEPT.WHITE,+ border: 'none',+ cursor: 'pointer',+ fontWeight: 600,+ }}>Close</button></div></div>- {loadingPastCompetitions ? (- <div className="flex items-center justify-center py-8">- <Loader2 size={24} className="animate-spin" style={{ color: COLORS.ORANGE }} />+ {arena.loadingPastCompetitions ? (+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '32px 0' }}>+ <Loader2 size={24} style={{ color: FINCEPT.ORANGE, animation: 'alpha-spin 1s linear infinite' }} /></div>- ) : pastCompetitions.length === 0 ? (- <div className="text-center py-8">- <History size={32} className="mx-auto mb-2" style={{ color: COLORS.GRAY, opacity: 0.5 }} />- <p className="text-sm" style={{ color: COLORS.GRAY }}>No past competitions found</p>+ ) : arena.pastCompetitions.length === 0 ? (+ <div style={{ textAlign: 'center', padding: '32px 0' }}>+ <History size={32} style={{ color: FINCEPT.GRAY, opacity: 0.5, margin: '0 auto 8px' }} />+ <p style={{ fontSize: '11px', color: FINCEPT.GRAY }}>No past competitions found</p></div>) : (- <div className="space-y-2 max-h-[400px] overflow-y-auto">- {pastCompetitions.map(comp => (+ <div style={{ maxHeight: '400px', overflowY: 'auto' }}>+ {arena.pastCompetitions.map(comp => (<divkey={comp.competition_id}- onClick={() => handleResumeCompetition(comp)}- className="p-3 rounded cursor-pointer transition-colors"+ onClick={() => arena.handleResumeCompetition(comp)}style={{- backgroundColor: COLORS.CARD_BG,- border: `1px solid ${COLORS.BORDER}`,+ padding: '10px',+ marginBottom: '4px',+ cursor: 'pointer',+ backgroundColor: FINCEPT.CARD_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ transition: 'all 0.15s',}}onMouseEnter={e => {- (e.currentTarget as HTMLElement).style.backgroundColor = COLORS.HOVER;- (e.currentTarget as HTMLElement).style.borderColor = COLORS.ORANGE + '40';+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;+ e.currentTarget.style.borderColor = `${FINCEPT.ORANGE}40`;}}onMouseLeave={e => {- (e.currentTarget as HTMLElement).style.backgroundColor = COLORS.CARD_BG;- (e.currentTarget as HTMLElement).style.borderColor = COLORS.BORDER;+ e.currentTarget.style.backgroundColor = FINCEPT.CARD_BG;+ e.currentTarget.style.borderColor = FINCEPT.BORDER;}}>- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <Trophy size={14} style={{ color: COLORS.ORANGE }} />- <span className="font-medium text-sm" style={{ color: COLORS.WHITE }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <Trophy size={12} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontWeight: 600, fontSize: '11px', color: FINCEPT.WHITE }}>{comp.config.competition_name}</span></div>- <div className="flex items-center gap-2">- <span- className="text-xs px-2 py-0.5 rounded"- style={{- backgroundColor:- comp.status === 'running' ? COLORS.GREEN + '20' :- comp.status === 'completed' ? COLORS.BLUE + '20' :- comp.status === 'failed' ? COLORS.RED + '20' :- COLORS.GRAY + '20',- color:- comp.status === 'running' ? COLORS.GREEN :- comp.status === 'completed' ? COLORS.BLUE :- comp.status === 'failed' ? COLORS.RED :- COLORS.GRAY,- }}- >+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <span style={{+ fontSize: '8px',+ padding: '1px 6px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ backgroundColor:+ comp.status === 'running' ? `${FINCEPT.GREEN}20` :+ comp.status === 'completed' ? `${FINCEPT.BLUE}20` :+ comp.status === 'failed' ? `${FINCEPT.RED}20` :+ `${FINCEPT.GRAY}20`,+ color:+ comp.status === 'running' ? FINCEPT.GREEN :+ comp.status === 'completed' ? FINCEPT.BLUE :+ comp.status === 'failed' ? FINCEPT.RED :+ FINCEPT.GRAY,+ }}>{comp.status.toUpperCase()}</span><button- onClick={(e) => handleDeleteCompetition(comp.competition_id, e)}- className="p-1 rounded transition-colors hover:bg-red-500/20"+ onClick={(e) => arena.handleDeleteCompetition(comp.competition_id, e)}+ style={{+ padding: '2px 4px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ color: FINCEPT.RED,+ display: 'flex',+ alignItems: 'center',+ }}title="Delete competition">- <Trash2 size={12} style={{ color: COLORS.RED }} />+ <Trash2 size={11} /></button></div></div>- <div className="grid grid-cols-3 gap-2 text-xs">+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '6px', fontSize: '10px' }}><div>- <span style={{ color: COLORS.GRAY }}>Cycles: </span>- <span style={{ color: COLORS.WHITE }}>{comp.cycle_count}</span>+ <span style={{ color: FINCEPT.GRAY }}>Cycles: </span>+ <span style={{ color: FINCEPT.WHITE }}>{comp.cycle_count}</span></div><div>- <span style={{ color: COLORS.GRAY }}>Models: </span>- <span style={{ color: COLORS.WHITE }}>{comp.config.models.length}</span>+ <span style={{ color: FINCEPT.GRAY }}>Models: </span>+ <span style={{ color: FINCEPT.WHITE }}>{comp.config.models.length}</span></div><div>- <span style={{ color: COLORS.GRAY }}>Capital: </span>- <span style={{ color: COLORS.WHITE }}>${comp.config.initial_capital.toLocaleString()}</span>+ <span style={{ color: FINCEPT.GRAY }}>Capital: </span>+ <span style={{ color: FINCEPT.WHITE }}>${comp.config.initial_capital.toLocaleString()}</span></div></div>- <div className="flex items-center gap-2 mt-2">- <span className="text-xs" style={{ color: COLORS.GRAY }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginTop: '6px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{comp.config.symbols.join(', ')}</span>- <span className="text-xs" style={{ color: COLORS.MUTED }}>•</span>- <span className="text-xs" style={{ color: COLORS.GRAY }}>+ <span style={{ fontSize: '9px', color: FINCEPT.MUTED }}>|</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{new Date(comp.created_at).toLocaleDateString()}</span></div>- <div className="flex flex-wrap gap-1 mt-2">+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px', marginTop: '6px' }}>{comp.config.models.map((model, idx) => (<spankey={idx}- className="text-xs px-1.5 py-0.5 rounded"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}+ style={{+ fontSize: '8px',+ padding: '1px 5px',+ backgroundColor: FINCEPT.BORDER,+ color: FINCEPT.GRAY,+ fontWeight: 600,+ }}>{model.name}</span>))}</div>- <div className="flex items-center justify-end mt-2 pt-2 border-t" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-1 text-xs" style={{ color: COLORS.ORANGE }}>- <PlayCircle size={12} />+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'flex-end',+ marginTop: '6px',+ paddingTop: '6px',+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '9px', color: FINCEPT.ORANGE }}>+ <PlayCircle size={10} /><span>Click to resume</span></div></div>@@ -1003,161 +524,238 @@ const AlphaArenaTab: React.FC = () => {// =============================================================================const renderCreatePanel = () => (- <div className="p-4 rounded-lg" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="flex items-center gap-2 mb-4">- <Plus size={18} style={{ color: COLORS.ORANGE }} />- <h2 className="font-semibold" style={{ color: COLORS.WHITE }}>Create Competition</h2>+ <div style={{ padding: '12px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>+ <Plus size={16} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontWeight: 700, fontSize: '12px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>CREATE COMPETITION</span>+ </div>++ {/* Competition Name */}+ <div style={{ marginBottom: '10px' }}>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>COMPETITION NAME</label>+ <input+ type="text"+ value={arena.competitionName}+ onChange={e => arena.setCompetitionName(e.target.value)}+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: FINCEPT.HEADER_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ fontSize: '12px',+ fontFamily: TERMINAL_FONT,+ outline: 'none',+ boxSizing: 'border-box',+ }}+ onFocus={e => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}+ onBlur={e => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}+ />+ </div>++ {/* Symbol & Mode */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '10px' }}>+ <div>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>TRADING SYMBOL</label>+ <select+ value={arena.symbol}+ onChange={e => arena.setSymbol(e.target.value)}+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: FINCEPT.HEADER_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ fontSize: '12px',+ fontFamily: TERMINAL_FONT,+ outline: 'none',+ }}+ >+ {TRADING_SYMBOLS.map(s => (+ <option key={s.value} value={s.value} style={{ backgroundColor: FINCEPT.HEADER_BG }}>{s.label}</option>+ ))}+ </select>+ </div>+ <div>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>COMPETITION MODE</label>+ <select+ value={arena.mode}+ onChange={e => arena.setMode(e.target.value as CompetitionMode)}+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: FINCEPT.HEADER_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ fontSize: '12px',+ fontFamily: TERMINAL_FONT,+ outline: 'none',+ }}+ >+ {COMPETITION_MODES.map(m => (+ <option key={m.value} value={m.value} style={{ backgroundColor: FINCEPT.HEADER_BG }}>{m.label}</option>+ ))}+ </select>+ </div></div>- <div className="space-y-4">- {/* Competition Name */}+ {/* Capital & Interval */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '10px' }}><div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Competition Name</label>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>INITIAL CAPITAL (USD)</label><inputtype="text"- value={competitionName}- onChange={e => setCompetitionName(e.target.value)}- className="w-full px-3 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ inputMode="numeric"+ value={arena.initialCapital}+ onChange={e => { const v = e.target.value; if (v === '' || /^\d+$/.test(v)) arena.setInitialCapital(Number(v) || 0); }}+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: FINCEPT.HEADER_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ fontSize: '12px',+ fontFamily: TERMINAL_FONT,+ outline: 'none',+ boxSizing: 'border-box',+ }}+ onFocus={e => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}+ onBlur={e => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}/></div>-- {/* Symbol & Mode */}- <div className="grid grid-cols-2 gap-4">- <div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Trading Symbol</label>- <select- value={symbol}- onChange={e => setSymbol(e.target.value)}- className="w-full px-3 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}- >- {TRADING_SYMBOLS.map(s => (- <option key={s.value} value={s.value}>{s.label}</option>- ))}- </select>- </div>- <div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Competition Mode</label>- <select- value={mode}- onChange={e => setMode(e.target.value as CompetitionMode)}- className="w-full px-3 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}- >- {COMPETITION_MODES.map(m => (- <option key={m.value} value={m.value}>{m.label}</option>- ))}- </select>- </div>+ <div>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>CYCLE INTERVAL (SECONDS)</label>+ <input+ type="text"+ inputMode="numeric"+ value={arena.cycleInterval}+ onChange={e => { const v = e.target.value; if (v === '' || /^\d+$/.test(v)) arena.setCycleInterval(Math.min(Number(v) || 0, 600)); }}+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: FINCEPT.HEADER_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ fontSize: '12px',+ fontFamily: TERMINAL_FONT,+ outline: 'none',+ boxSizing: 'border-box',+ }}+ onFocus={e => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}+ onBlur={e => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}+ /></div>+ </div>- {/* Capital & Interval */}- <div className="grid grid-cols-2 gap-4">- <div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Initial Capital (USD)</label>- <input- type="text"- inputMode="numeric"- value={initialCapital}- onChange={e => { const v = e.target.value; if (v === '' || /^\d+$/.test(v)) setInitialCapital(Number(v) || 0); }}- className="w-full px-3 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}- />+ {/* LLM Model Selection */}+ <div style={{ marginBottom: '10px' }}>+ <label style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px', fontWeight: 600, letterSpacing: '0.5px' }}>+ <Brain size={10} />+ SELECT AI MODELS (from Settings - min 2 required)+ </label>++ {arena.configuredLLMs.length === 0 ? (+ <div style={{+ padding: '16px',+ textAlign: 'center',+ backgroundColor: FINCEPT.CARD_BG,+ border: `1px solid ${FINCEPT.RED}40`,+ }}>+ <AlertCircle size={24} style={{ color: FINCEPT.RED, margin: '0 auto 8px' }} />+ <p style={{ fontSize: '11px', color: FINCEPT.RED, marginBottom: '4px' }}>No AI models configured</p>+ <p style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ Go to Settings → LLM Config → My Model Library to add models with API keys+ </p></div>- <div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Cycle Interval (seconds)</label>- <input- type="text"- inputMode="numeric"- value={cycleInterval}- onChange={e => { const v = e.target.value; if (v === '' || /^\d+$/.test(v)) setCycleInterval(Math.min(Number(v) || 0, 600)); }}- className="w-full px-3 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}- />- </div>- </div>-- {/* LLM Model Selection - FROM SETTINGS */}- <div>- <label className="text-xs mb-2 block flex items-center gap-2" style={{ color: COLORS.GRAY }}>- <Brain size={12} />- SELECT AI MODELS (from Settings - min 2 required)- </label>-- {configuredLLMs.length === 0 ? (- <div className="p-4 rounded text-center" style={{ backgroundColor: COLORS.CARD_BG, border: `1px solid ${COLORS.RED}40` }}>- <AlertCircle size={24} className="mx-auto mb-2" style={{ color: COLORS.RED }} />- <p className="text-sm" style={{ color: COLORS.RED }}>No AI models configured</p>- <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>- Go to Settings → LLM Config → My Model Library to add models with API keys- </p>- </div>- ) : (- <div className="grid grid-cols-2 gap-2">- {configuredLLMs.map((model) => {- const isSelected = selectedModels.some(m => m.id === model.id);- return (- <button- key={model.id}- type="button"- onClick={() => toggleModelSelection(model)}- className="flex items-center gap-2 p-3 rounded text-left transition-colors"- style={{- backgroundColor: isSelected ? COLORS.ORANGE + '15' : COLORS.CARD_BG,- border: `1px solid ${isSelected ? COLORS.ORANGE : COLORS.BORDER}`,- }}- >- <div- className="w-5 h-5 rounded flex items-center justify-center"- style={{- backgroundColor: isSelected ? COLORS.ORANGE : COLORS.BORDER,- border: `1px solid ${isSelected ? COLORS.ORANGE : COLORS.BORDER}`,- }}- >- {isSelected && <CheckCircle size={12} style={{ color: COLORS.DARK_BG }} />}+ ) : (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px' }}>+ {arena.configuredLLMs.map((model: AlphaArenaModel) => {+ const isSelected = arena.selectedModels.some(m => m.id === model.id);+ return (+ <button+ key={model.id}+ type="button"+ onClick={() => arena.toggleModelSelection(model)}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '8px 10px',+ textAlign: 'left',+ cursor: 'pointer',+ backgroundColor: isSelected ? `${FINCEPT.ORANGE}15` : FINCEPT.CARD_BG,+ border: `1px solid ${isSelected ? FINCEPT.ORANGE : FINCEPT.BORDER}`,+ transition: 'all 0.15s',+ }}+ >+ <div style={{+ width: '16px',+ height: '16px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: isSelected ? FINCEPT.ORANGE : FINCEPT.BORDER,+ flexShrink: 0,+ }}>+ {isSelected && <CheckCircle size={10} style={{ color: FINCEPT.DARK_BG }} />}+ </div>+ <div style={{ flex: 1, minWidth: 0, overflow: 'hidden' }}>+ <div style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>+ {model.display_name}</div>- <div className="flex-1 min-w-0">- <div className="text-sm font-medium truncate" style={{ color: COLORS.WHITE }}>- {model.display_name}- </div>- <div className="text-xs truncate" style={{ color: COLORS.GRAY }}>- {model.provider} • {model.model_id}- </div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>+ {model.provider} | {model.model_id}</div>- </button>- );- })}- </div>- )}- <p className="text-xs mt-2" style={{ color: COLORS.GRAY }}>- Selected: {selectedModels.length} model(s)- </p>- </div>+ </div>+ </button>+ );+ })}+ </div>+ )}+ <p style={{ fontSize: '9px', marginTop: '6px', color: FINCEPT.GRAY }}>+ Selected: {arena.selectedModels.length} model(s)+ </p>+ </div>- {/* Actions */}- <div className="flex gap-2 pt-2">- <button- onClick={() => setShowCreatePanel(false)}- className="px-4 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}- >- Cancel- </button>- <button- onClick={handleCreateCompetition}- disabled={isLoading || selectedModels.length < 2 || configuredLLMs.length === 0}- className="flex-1 py-2 rounded font-medium text-sm flex items-center justify-center gap-2"- style={{- backgroundColor: COLORS.ORANGE,- color: COLORS.DARK_BG,- opacity: (isLoading || selectedModels.length < 2) ? 0.5 : 1,- }}- >- {isLoading ? <Loader2 size={16} className="animate-spin" /> : <Zap size={16} />}- Create Competition- </button>- </div>+ {/* Actions */}+ <div style={{ display: 'flex', gap: '6px', paddingTop: '8px' }}>+ <button+ onClick={() => arena.setShowCreatePanel(false)}+ style={{+ padding: '8px 14px',+ backgroundColor: FINCEPT.BORDER,+ color: FINCEPT.GRAY,+ border: 'none',+ fontSize: '11px',+ fontWeight: 600,+ cursor: 'pointer',+ }}+ >+ CANCEL+ </button>+ <button+ onClick={arena.handleCreateCompetition}+ disabled={arena.isLoading || arena.selectedModels.length < 2 || arena.configuredLLMs.length === 0}+ style={{+ flex: 1,+ padding: '8px 14px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ fontSize: '11px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ cursor: (arena.isLoading || arena.selectedModels.length < 2) ? 'not-allowed' : 'pointer',+ opacity: (arena.isLoading || arena.selectedModels.length < 2) ? 0.5 : 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ }}+ >+ {arena.isLoading ? <Loader2 size={14} style={{ animation: 'alpha-spin 1s linear infinite' }} /> : <Zap size={14} />}+ CREATE COMPETITION+ </button></div></div>);@@ -1167,67 +765,117 @@ const AlphaArenaTab: React.FC = () => {// =============================================================================const renderControls = () => (- <div className="flex items-center gap-2 p-3 rounded-lg" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- {/* Show STOP button when loading, otherwise show Run Cycle */}- {isLoading ? (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ padding: '8px 10px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>+ {arena.isLoading ? (<button- onClick={handleCancel}- disabled={isCancelling}- className="px-4 py-2 rounded text-sm font-medium flex items-center gap-2"+ onClick={arena.handleCancel}+ disabled={arena.isCancelling}style={{- backgroundColor: COLORS.RED,- color: COLORS.WHITE,- opacity: isCancelling ? 0.5 : 1,+ padding: '6px 12px',+ backgroundColor: FINCEPT.RED,+ color: FINCEPT.WHITE,+ border: 'none',+ fontSize: '10px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ cursor: arena.isCancelling ? 'not-allowed' : 'pointer',+ opacity: arena.isCancelling ? 0.5 : 1,+ display: 'flex',+ alignItems: 'center',+ gap: '4px',}}>- {isCancelling ? <Loader2 size={14} className="animate-spin" /> : <StopCircle size={14} />}- {isCancelling ? 'Stopping...' : 'STOP'}+ {arena.isCancelling ? <Loader2 size={12} style={{ animation: 'alpha-spin 1s linear infinite' }} /> : <StopCircle size={12} />}+ {arena.isCancelling ? 'STOPPING...' : 'STOP'}</button>) : (<button- onClick={handleRunCycle}- disabled={isAutoRunning}- className="px-4 py-2 rounded text-sm font-medium flex items-center gap-2"+ onClick={arena.handleRunCycle}+ disabled={arena.isAutoRunning}style={{- backgroundColor: COLORS.ORANGE,- color: COLORS.DARK_BG,- opacity: isAutoRunning ? 0.5 : 1,+ padding: '6px 12px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ fontSize: '10px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ cursor: arena.isAutoRunning ? 'not-allowed' : 'pointer',+ opacity: arena.isAutoRunning ? 0.5 : 1,+ display: 'flex',+ alignItems: 'center',+ gap: '4px',}}>- <Play size={14} />- Run Cycle+ <Play size={12} />+ RUN CYCLE</button>)}<button- onClick={handleToggleAutoRun}- disabled={isLoading}- className="px-4 py-2 rounded text-sm font-medium flex items-center gap-2"+ onClick={arena.handleToggleAutoRun}+ disabled={arena.isLoading}style={{- backgroundColor: isAutoRunning ? COLORS.RED + '20' : COLORS.GREEN + '20',- color: isAutoRunning ? COLORS.RED : COLORS.GREEN,- border: `1px solid ${isAutoRunning ? COLORS.RED + '40' : COLORS.GREEN + '40'}`,- opacity: isLoading ? 0.5 : 1,+ padding: '6px 12px',+ backgroundColor: arena.isAutoRunning ? `${FINCEPT.RED}20` : `${FINCEPT.GREEN}20`,+ color: arena.isAutoRunning ? FINCEPT.RED : FINCEPT.GREEN,+ border: `1px solid ${arena.isAutoRunning ? FINCEPT.RED : FINCEPT.GREEN}40`,+ fontSize: '10px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ cursor: arena.isLoading ? 'not-allowed' : 'pointer',+ opacity: arena.isLoading ? 0.5 : 1,+ display: 'flex',+ alignItems: 'center',+ gap: '4px',}}>- {isAutoRunning ? <Pause size={14} /> : <Zap size={14} />}- {isAutoRunning ? 'Stop Auto' : 'Auto Run'}+ {arena.isAutoRunning ? <Pause size={12} /> : <Zap size={12} />}+ {arena.isAutoRunning ? 'STOP AUTO' : 'AUTO RUN'}</button><button- onClick={handleReset}- className="px-4 py-2 rounded text-sm flex items-center gap-2"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}+ onClick={arena.handleReset}+ style={{+ padding: '6px 12px',+ backgroundColor: FINCEPT.BORDER,+ color: FINCEPT.GRAY,+ border: 'none',+ fontSize: '10px',+ fontWeight: 600,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ onMouseEnter={(e) => { e.currentTarget.style.color = FINCEPT.WHITE; }}+ onMouseLeave={(e) => { e.currentTarget.style.color = FINCEPT.GRAY; }}>- <RotateCcw size={14} />- Reset+ <RotateCcw size={12} />+ RESET</button>- <div className="flex-1" />-- <div className="text-xs px-3 py-1 rounded" style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.GRAY }}>- <Clock size={12} className="inline mr-1" />- Interval: {cycleInterval}s+ <div style={{ flex: 1 }} />++ <div style={{+ fontSize: '9px',+ padding: '4px 8px',+ backgroundColor: FINCEPT.CARD_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ color: FINCEPT.GRAY,+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}>+ <Clock size={10} />+ INTERVAL: {arena.cycleInterval}s</div></div>);@@ -1236,56 +884,98 @@ const AlphaArenaTab: React.FC = () => {// Render: Leaderboard// =============================================================================- const renderLeaderboard = () => {- return (- <div className="rounded-lg overflow-hidden" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-2">- <Trophy size={16} style={{ color: COLORS.ORANGE }} />- <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>Leaderboard</span>+ const renderLeaderboard = () => (+ <div style={{+ overflow: 'hidden',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>+ {/* Header */}+ <div style={{+ padding: '8px 12px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: FINCEPT.HEADER_BG,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <Trophy size={14} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontWeight: 700, fontSize: '11px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>LEADERBOARD</span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>+ {arena.latestPrice !== null && (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ padding: '2px 6px',+ backgroundColor: `${FINCEPT.GREEN}15`,+ border: `1px solid ${FINCEPT.GREEN}30`,+ }}>+ <Activity size={9} style={{ color: FINCEPT.GREEN }} />+ <span style={{ fontSize: '9px', fontWeight: 600, color: FINCEPT.GREEN, fontFamily: TERMINAL_FONT }}>+ {arena.symbol.split('/')[0]} ${arena.latestPrice.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}+ </span>+ </div>+ )}+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Cycle {arena.cycleCount}</span></div>- <span className="text-xs" style={{ color: COLORS.GRAY }}>Cycle {cycleCount}</span></div>- {leaderboard.length === 0 ? (- <div className="p-8 text-center" style={{ color: COLORS.GRAY }}>- <Trophy size={32} className="mx-auto mb-2 opacity-30" />- <p className="text-sm">No competition data yet</p>+ {arena.leaderboard.length === 0 ? (+ <div style={{ padding: '32px', textAlign: 'center', color: FINCEPT.GRAY }}>+ <Trophy size={32} style={{ opacity: 0.3, margin: '0 auto 8px' }} />+ <p style={{ fontSize: '11px' }}>No competition data yet</p></div>) : (- <div className="divide-y" style={{ borderColor: COLORS.BORDER }}>- {leaderboard.map(entry => {+ <div>+ {arena.leaderboard.map(entry => {const isPositive = entry.total_pnl >= 0;const modelColor = getModelColor(entry.model_name);return (<divkey={entry.model_name}- className="flex items-center gap-3 px-4 py-3 hover:bg-[#1A1A1A] transition-colors"+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ padding: '10px 12px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ transition: 'background-color 0.15s',+ cursor: 'default',+ }}+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = FINCEPT.HOVER; }}+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent'; }}>{/* Rank */}- <div- className="w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold"- style={{- backgroundColor: entry.rank === 1 ? COLORS.YELLOW + '20' : entry.rank === 2 ? COLORS.GRAY + '20' : entry.rank === 3 ? COLORS.ORANGE + '20' : COLORS.BORDER,- color: entry.rank === 1 ? COLORS.YELLOW : entry.rank === 2 ? COLORS.GRAY : entry.rank === 3 ? COLORS.ORANGE : COLORS.GRAY,- }}- >+ <div style={{+ width: '28px',+ height: '28px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: '12px',+ fontWeight: 700,+ backgroundColor: entry.rank === 1 ? `${FINCEPT.YELLOW}20` : entry.rank === 2 ? `${FINCEPT.GRAY}20` : entry.rank === 3 ? `${FINCEPT.ORANGE}20` : FINCEPT.BORDER,+ color: entry.rank === 1 ? FINCEPT.YELLOW : entry.rank === 2 ? FINCEPT.GRAY : entry.rank === 3 ? FINCEPT.ORANGE : FINCEPT.GRAY,+ }}>{entry.rank}</div>- {/* Color indicator */}- <div className="w-1 h-10 rounded-full" style={{ backgroundColor: modelColor }} />+ {/* Color Bar */}+ <div style={{ width: '3px', height: '32px', backgroundColor: modelColor }} />- {/* Model info */}- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2">- <span className="font-medium truncate" style={{ color: COLORS.WHITE }}>+ {/* Model Info */}+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <span style={{ fontWeight: 600, fontSize: '11px', color: FINCEPT.WHITE, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{entry.model_name}</span>- {entry.rank === 1 && <Trophy size={14} style={{ color: COLORS.YELLOW }} />}+ {entry.rank === 1 && <Trophy size={12} style={{ color: FINCEPT.YELLOW }} />}</div>- <div className="flex items-center gap-3 text-xs" style={{ color: COLORS.GRAY }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px', fontSize: '9px', color: FINCEPT.GRAY }}><span>{entry.trades_count} trades</span><span>{entry.positions_count} positions</span>{entry.win_rate !== undefined && (@@ -1295,18 +985,18 @@ const AlphaArenaTab: React.FC = () => {</div>{/* P&L */}- <div className="text-right">- <div className="flex items-center justify-end gap-1">+ <div style={{ textAlign: 'right' }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '4px' }}>{isPositive ? (- <TrendingUp size={14} style={{ color: COLORS.GREEN }} />+ <TrendingUp size={12} style={{ color: FINCEPT.GREEN }} />) : (- <TrendingDown size={14} style={{ color: COLORS.RED }} />+ <TrendingDown size={12} style={{ color: FINCEPT.RED }} />)}- <span style={{ color: isPositive ? COLORS.GREEN : COLORS.RED }}>+ <span style={{ fontSize: '11px', fontWeight: 600, color: isPositive ? FINCEPT.GREEN : FINCEPT.RED }}>{formatPercent(entry.return_pct)}</span></div>- <span className="text-xs" style={{ color: COLORS.GRAY }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{formatCurrency(entry.portfolio_value)}</span></div>@@ -1317,132 +1007,67 @@ const AlphaArenaTab: React.FC = () => {)}</div>);- };// =============================================================================- // Render: Decisions Panel+ // Render: Performance Chart// =============================================================================- const renderDecisions = () => {- return (- <div className="h-full flex flex-col" style={{ backgroundColor: COLORS.CARD_BG }}>- <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-2">- <Brain size={16} style={{ color: COLORS.PURPLE }} />- <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>AI Decisions</span>- </div>- <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}>- {decisions.length}- </span>- </div>-- <div className="flex-1 overflow-y-auto">- {decisions.length === 0 ? (- <div className="p-8 text-center" style={{ color: COLORS.GRAY }}>- <Sparkles size={32} className="mx-auto mb-2 opacity-30" />- <p className="text-sm">No decisions yet</p>- <p className="text-xs mt-1">Run a cycle to see AI trading decisions</p>- </div>- ) : (- <div className="divide-y" style={{ borderColor: COLORS.BORDER }}>- {decisions.slice(0, 50).map((decision, idx) => (- <div key={idx} className="p-3 hover:bg-[#0F0F0F] transition-colors">- <div className="flex items-center justify-between mb-1">- <span className="text-xs font-medium" style={{ color: COLORS.WHITE }}>- {decision.model_name}- </span>- <span className="text-xs" style={{ color: COLORS.GRAY }}>- Cycle {decision.cycle_number}- </span>- </div>- <div className="flex items-center gap-2">- <span- className="text-xs px-2 py-0.5 rounded font-medium"- style={{- backgroundColor: decision.action === 'buy' ? COLORS.GREEN + '20' :- decision.action === 'sell' ? COLORS.RED + '20' :- decision.action === 'short' ? COLORS.PURPLE + '20' :- COLORS.GRAY + '20',- color: decision.action === 'buy' ? COLORS.GREEN :- decision.action === 'sell' ? COLORS.RED :- decision.action === 'short' ? COLORS.PURPLE :- COLORS.GRAY,- }}- >- {decision.action.toUpperCase()}- </span>- <span className="text-xs" style={{ color: COLORS.GRAY }}>- {decision.symbol}- </span>- <span className="text-xs" style={{ color: COLORS.GRAY }}>- Qty: {decision.quantity.toFixed(4)}- </span>- </div>- {decision.reasoning && (- <p className="text-xs mt-1 line-clamp-2" style={{ color: COLORS.MUTED }}>- {decision.reasoning}- </p>- )}- <div className="flex items-center justify-between mt-1">- <span className="text-xs" style={{ color: COLORS.GRAY }}>- Confidence: {(decision.confidence * 100).toFixed(0)}%- </span>- </div>- </div>- ))}- </div>- )}- </div>- </div>+ const renderPerformanceChart = () => (+ <PerformanceChart snapshots={arena.snapshots} height={250} />);- };// =============================================================================- // Render: Performance Chart (Simple)+ // Render: Status Bar (Terminal Footer)// =============================================================================- const renderPerformanceChart = () => (- <div className="rounded-lg p-4" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="flex items-center gap-2 mb-4">- <BarChart3 size={16} style={{ color: COLORS.ORANGE }} />- <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>Performance</span>+ const renderStatusBar = () => (+ <div style={{+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: FINCEPT.HEADER_BG,+ padding: '4px 12px',+ fontSize: '9px',+ color: FINCEPT.GRAY,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ flexShrink: 0,+ fontFamily: TERMINAL_FONT,+ }}>+ {/* Left - Branding */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ color: FINCEPT.ORANGE, fontWeight: 700 }}>FINCEPT</span>+ <span>v{APP_VERSION}</span>+ <span style={{ color: FINCEPT.BORDER }}>|</span>+ <span>ALPHA ARENA</span></div>- {snapshots.length === 0 ? (- <div className="h-40 flex items-center justify-center" style={{ color: COLORS.GRAY }}>- <div className="text-center">- <BarChart3 size={32} className="mx-auto mb-2 opacity-30" />- <p className="text-sm">No performance data yet</p>- </div>- </div>- ) : (- <div className="h-40 flex items-end gap-1">- {/* Simple bar chart */}- {leaderboard.map(entry => {- const maxVal = Math.max(...leaderboard.map(e => Math.abs(e.return_pct)), 10);- const height = Math.abs(entry.return_pct) / maxVal * 100;- const isPositive = entry.return_pct >= 0;-- return (- <div key={entry.model_name} className="flex-1 flex flex-col items-center">- <div className="w-full flex-1 flex items-end justify-center">- <div- className="w-full max-w-8 rounded-t transition-all"- style={{- height: `${Math.max(height, 5)}%`,- backgroundColor: isPositive ? COLORS.GREEN : COLORS.RED,- opacity: 0.7,- }}- />- </div>- <span className="text-xs mt-1 truncate w-full text-center" style={{ color: COLORS.GRAY }}>- {entry.model_name.split(' ')[0]}- </span>- </div>- );- })}+ {/* Right - Status */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={{ color: FINCEPT.GRAY }}>ID:</span>+ <span style={{ color: FINCEPT.CYAN, fontWeight: 600 }}>+ {arena.competitionId ? arena.competitionId.slice(0, 8) + '...' : 'NONE'}+ </span></div>- )}+ <span style={{ color: FINCEPT.BORDER }}>|</span>+ <span>Models: {arena.selectedModels.length}</span>+ <span style={{ color: FINCEPT.BORDER }}>|</span>+ <span>LLMs: {arena.configuredLLMs.length}</span>+ {arena.selectedBroker && (+ <>+ <span style={{ color: FINCEPT.BORDER }}>|</span>+ <span style={{ color: FINCEPT.ORANGE, fontWeight: 600 }}>Broker: {arena.selectedBroker}</span>+ </>+ )}+ <span style={{ color: FINCEPT.BORDER }}>|</span>+ <span>Cycle: {arena.cycleCount}</span>+ <span style={{ color: FINCEPT.BORDER }}>|</span>+ <span>Decisions: {arena.decisions.length}</span>+ <span style={{ color: FINCEPT.BORDER }}>|</span>+ <span style={{ color: FINCEPT.CYAN, fontWeight: 600 }}>+ {arena.rightPanelTab.toUpperCase()}+ </span>+ </div></div>);@@ -1451,80 +1076,142 @@ const AlphaArenaTab: React.FC = () => {// =============================================================================return (- <div className="h-full flex flex-col" style={{ backgroundColor: COLORS.DARK_BG, color: COLORS.WHITE }}>- {/* Header */}+ <div+ className="alpha-arena-terminal"+ style={{+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ fontFamily: TERMINAL_FONT,+ }}+ >+ <style>{TERMINAL_STYLES}</style>+{renderHeader()}{/* Notifications */}- {error && (- <div className="mx-4 mt-2 p-3 rounded flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '20', color: COLORS.RED }}>- <AlertCircle size={16} />- <span className="text-sm flex-1">{error}</span>- <button onClick={() => setError(null)}>×</button>+ {arena.error && (+ <div style={{+ margin: '0 12px',+ marginTop: '4px',+ padding: '8px 10px',+ backgroundColor: `${FINCEPT.RED}20`,+ border: `1px solid ${FINCEPT.RED}40`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ color: FINCEPT.RED,+ }}>+ <AlertCircle size={14} />+ <span style={{ fontSize: '11px', flex: 1 }}>{arena.error}</span>+ <button+ onClick={() => arena.setError(null)}+ style={{ background: 'none', border: 'none', color: FINCEPT.RED, cursor: 'pointer', fontSize: '14px', fontWeight: 700 }}+ >+ x+ </button></div>)}- {success && (- <div className="mx-4 mt-2 p-3 rounded flex items-center gap-2" style={{ backgroundColor: COLORS.GREEN + '20', color: COLORS.GREEN }}>- <CheckCircle size={16} />- <span className="text-sm">{success}</span>+ {arena.success && (+ <div style={{+ margin: '0 12px',+ marginTop: '4px',+ padding: '8px 10px',+ backgroundColor: `${FINCEPT.GREEN}20`,+ border: `1px solid ${FINCEPT.GREEN}40`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ color: FINCEPT.GREEN,+ }}>+ <CheckCircle size={14} />+ <span style={{ fontSize: '11px' }}>{arena.success}</span></div>)}{/* Main Content */}- <div className="flex-1 flex overflow-hidden">+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>{/* Left Panel */}- <div className="flex-1 flex flex-col p-4 gap-4 overflow-y-auto">- {/* No Competition State */}- {!competitionId && !showCreatePanel && !showPastCompetitions && (- <div className="p-8 rounded-lg text-center" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <Trophy size={48} className="mx-auto mb-4" style={{ color: COLORS.ORANGE, opacity: 0.5 }} />- <h3 className="text-lg font-semibold mb-2" style={{ color: COLORS.WHITE }}>No Active Competition</h3>- <p className="text-sm mb-4" style={{ color: COLORS.GRAY }}>+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '8px', gap: '8px', overflowY: 'auto' }}>+ {!arena.competitionId && !arena.showCreatePanel && !arena.showPastCompetitions && (+ <div style={{+ padding: '32px',+ textAlign: 'center',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <Trophy size={48} style={{ color: FINCEPT.ORANGE, opacity: 0.5, margin: '0 auto 16px' }} />+ <h3 style={{ fontSize: '14px', fontWeight: 700, marginBottom: '8px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>NO ACTIVE COMPETITION</h3>+ <p style={{ fontSize: '11px', marginBottom: '16px', color: FINCEPT.GRAY }}>Create a new AI trading competition or resume a past competition.</p>- <div className="flex justify-center gap-3">+ <div style={{ display: 'flex', justifyContent: 'center', gap: '8px' }}><button- onClick={() => setShowCreatePanel(true)}- className="flex items-center gap-2 px-4 py-2 rounded font-medium"- style={{ backgroundColor: COLORS.ORANGE, color: COLORS.DARK_BG }}+ onClick={() => arena.setShowCreatePanel(true)}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ padding: '8px 16px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ fontWeight: 700,+ fontSize: '11px',+ letterSpacing: '0.5px',+ cursor: 'pointer',+ }}>- <Plus size={16} />- Create Competition+ <Plus size={14} />+ CREATE COMPETITION</button>- {pastCompetitions.length > 0 && (+ {arena.pastCompetitions.length > 0 && (<button- onClick={() => setShowPastCompetitions(true)}- className="flex items-center gap-2 px-4 py-2 rounded font-medium transition-colors"+ onClick={() => arena.setShowPastCompetitions(true)}style={{- backgroundColor: COLORS.CARD_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ padding: '8px 16px',+ backgroundColor: FINCEPT.CARD_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ fontWeight: 600,+ fontSize: '11px',+ cursor: 'pointer',+ transition: 'all 0.15s',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = `${FINCEPT.ORANGE}40`;+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = FINCEPT.BORDER;+ e.currentTarget.style.backgroundColor = FINCEPT.CARD_BG;}}>- <History size={16} />- Past Competitions ({pastCompetitions.length})+ <History size={14} />+ PAST COMPETITIONS ({arena.pastCompetitions.length})</button>)}</div>- {configuredLLMs.length === 0 && (- <p className="text-xs mt-4" style={{ color: COLORS.RED }}>+ {arena.configuredLLMs.length === 0 && (+ <p style={{ fontSize: '9px', marginTop: '16px', color: FINCEPT.RED }}>No AI models configured. Go to Settings → LLM Config → My Model Library first.</p>)}</div>)}- {/* Past Competitions Panel */}- {!competitionId && showPastCompetitions && renderPastCompetitions()}+ {!arena.competitionId && arena.showPastCompetitions && renderPastCompetitions()}- {/* Progress Panel - Shows during loading */}{renderProgressPanel()}- {/* Create Panel */}- {showCreatePanel && renderCreatePanel()}+ {arena.showCreatePanel && renderCreatePanel()}- {/* Competition Active */}- {competitionId && (+ {arena.competitionId && (<>{renderControls()}{renderPerformanceChart()}@@ -1533,117 +1220,21 @@ const AlphaArenaTab: React.FC = () => {)}</div>- {/* Right Panel - Enhanced Features */}- <div className="w-[400px] border-l flex flex-col" style={{ borderColor: COLORS.BORDER }}>- {/* Right Panel Tabs */}- <div className="flex border-b overflow-x-auto" style={{ borderColor: COLORS.BORDER }}>- {[- { key: 'decisions', icon: Brain, label: 'Decisions' },- { key: 'hitl', icon: Shield, label: 'HITL' },- { key: 'sentiment', icon: Newspaper, label: 'Sentiment' },- { key: 'metrics', icon: BarChart3, label: 'Metrics' },- { key: 'grid', icon: Grid3X3, label: 'Grid' },- { key: 'research', icon: FileSearch, label: 'Research' },- { key: 'broker', icon: Building, label: 'Broker' },- ].map(({ key, icon: Icon, label }) => (- <button- key={key}- onClick={() => setRightPanelTab(key as RightPanelTab)}- className="px-3 py-2 text-xs font-medium whitespace-nowrap flex items-center gap-1 transition-colors"- style={{- backgroundColor: rightPanelTab === key ? COLORS.CARD_BG : 'transparent',- color: rightPanelTab === key ? COLORS.ORANGE : COLORS.GRAY,- borderBottom: rightPanelTab === key ? `2px solid ${COLORS.ORANGE}` : '2px solid transparent',- }}- >- <Icon size={12} />- {label}- </button>- ))}- </div>-- {/* Right Panel Content */}- <div className="flex-1 overflow-y-auto">- {rightPanelTab === 'decisions' && renderDecisions()}- {rightPanelTab === 'hitl' && (- <div className="p-3">- <HITLApprovalPanel- competitionId={competitionId || undefined}- onApprovalChange={() => refreshCompetitionData()}- />- </div>- )}- {rightPanelTab === 'sentiment' && (- <div className="p-3">- <SentimentPanel- symbol={symbol.split('/')[0]}- showMarketMood={true}- />- </div>- )}- {rightPanelTab === 'metrics' && competitionId && (- <div className="p-3">- <PortfolioMetricsPanel- competitionId={competitionId}- />- </div>- )}- {rightPanelTab === 'metrics' && !competitionId && (- <div className="p-8 text-center" style={{ color: COLORS.GRAY }}>- <BarChart3 size={32} className="mx-auto mb-2 opacity-30" />- <p className="text-sm">Start a competition to view metrics</p>- </div>- )}- {rightPanelTab === 'grid' && (- <div className="p-3">- <GridStrategyPanel- symbol={symbol.split('/')[0]}- currentPrice={latestPrice || undefined}- />- </div>- )}- {rightPanelTab === 'research' && (- <div className="p-3">- <ResearchPanel />- </div>- )}- {rightPanelTab === 'broker' && (- <div className="p-3">- <BrokerSelector- selectedBrokerId={selectedBroker || undefined}- onBrokerSelect={(broker) => setSelectedBroker(broker.id)}- />- </div>- )}- </div>- </div>+ {/* Right Panel */}+ <AlphaArenaRightPanel+ rightPanelTab={arena.rightPanelTab}+ setRightPanelTab={arena.setRightPanelTab}+ decisions={arena.decisions}+ competitionId={arena.competitionId}+ symbol={arena.symbol}+ latestPrice={arena.latestPrice}+ selectedBroker={arena.selectedBroker}+ setSelectedBroker={arena.setSelectedBroker}+ refreshCompetitionData={arena.refreshCompetitionData}+ /></div>- {/* Footer */}- <TabFooter- tabName="ALPHA ARENA"- leftInfo={[- {- label: competitionId ? `ID: ${competitionId.slice(0, 8)}...` : 'No Competition',- color: COLORS.GRAY,- },- {- label: `Models: ${selectedModels.length}`,- color: COLORS.GRAY,- },- {- label: `AI Models: ${configuredLLMs.length} available`,- color: COLORS.GRAY,- },- ...(selectedBroker ? [{- label: `Broker: ${selectedBroker}`,- color: COLORS.ORANGE,- }] : []),- ]}- statusInfo={`Cycle: ${cycleCount} | Decisions: ${decisions.length} | Panel: ${rightPanelTab.toUpperCase()}`}- backgroundColor={COLORS.PANEL_BG}- borderColor={COLORS.BORDER}- />+ {renderStatusBar()}</div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/BrokerSelector.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/BrokerSelector.tsxindex cc51a5b2a..8d72b3765 100644--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/BrokerSelector.tsx+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/BrokerSelector.tsx@@ -8,7 +8,7 @@import React, { useState, useEffect, useReducer, useRef } from 'react';import {Building, RefreshCw, Check, AlertTriangle, Loader2,- Globe, DollarSign, Percent, Zap, Settings, ChevronDown,+ Globe, Zap, ChevronDown,ChevronRight, Search, Star, StarOff,} from 'lucide-react';import { withErrorBoundary } from '@/components/common/ErrorBoundary';@@ -20,7 +20,7 @@ import {type TickerData,} from '../services/alphaArenaEnhancedService';-const COLORS = {+const FINCEPT = {ORANGE: '#FF8800',WHITE: '#FFFFFF',RED: '#FF3B3B',@@ -31,14 +31,25 @@ const COLORS = {GRAY: '#787878',DARK_BG: '#000000',PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',CARD_BG: '#0A0A0A',BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',};+const TERMINAL_FONT = '"IBM Plex Mono", "Consolas", monospace';++const BROKER_STYLES = `+ .broker-panel *::-webkit-scrollbar { width: 6px; height: 6px; }+ .broker-panel *::-webkit-scrollbar-track { background: #000000; }+ .broker-panel *::-webkit-scrollbar-thumb { background: #2A2A2A; }+ @keyframes broker-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }+`;+const BROKER_TYPE_COLORS: Record<string, string> = {- crypto: COLORS.ORANGE,- stocks: COLORS.BLUE,- forex: COLORS.GREEN,+ crypto: FINCEPT.ORANGE,+ stocks: FINCEPT.BLUE,+ forex: FINCEPT.GREEN,};const REGION_FLAGS: Record<string, string> = {@@ -101,6 +112,8 @@ const BrokerSelector: React.FC<BrokerSelectorProps> = ({const [typeFilter, setTypeFilter] = useState<'crypto' | 'stocks' | 'forex' | null>(filterType || null);const [regionFilter, setRegionFilter] = useState<string | null>(filterRegion || null);const mountedRef = useRef(true);+ const [hoveredBtn, setHoveredBtn] = useState<string | null>(null);+ const [hoveredBrokerId, setHoveredBrokerId] = useState<string | null>(null);useEffect(() => {mountedRef.current = true;@@ -148,7 +161,6 @@ const BrokerSelector: React.FC<BrokerSelectorProps> = ({setSelectedBroker(broker);onBrokerSelect?.(broker);- // Fetch sample ticker dataif (broker.default_symbols.length > 0) {dispatchTicker({ type: 'FETCH_START' });try {@@ -192,30 +204,30 @@ const BrokerSelector: React.FC<BrokerSelectorProps> = ({});const renderBrokerFeatures = (broker: BrokerInfo) => (- <div className="flex flex-wrap gap-1 mt-2">+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginTop: '8px' }}>{broker.supports_spot && (- <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: COLORS.GREEN + '20', color: COLORS.GREEN }}>+ <span style={{ fontSize: '9px', padding: '1px 6px', backgroundColor: FINCEPT.GREEN + '20', color: FINCEPT.GREEN, fontFamily: TERMINAL_FONT }}>Spot</span>)}{broker.supports_margin && (- <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: COLORS.YELLOW + '20', color: COLORS.YELLOW }}>+ <span style={{ fontSize: '9px', padding: '1px 6px', backgroundColor: FINCEPT.YELLOW + '20', color: FINCEPT.YELLOW, fontFamily: TERMINAL_FONT }}>Margin</span>)}{broker.supports_futures && (- <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: COLORS.PURPLE + '20', color: COLORS.PURPLE }}>+ <span style={{ fontSize: '9px', padding: '1px 6px', backgroundColor: FINCEPT.PURPLE + '20', color: FINCEPT.PURPLE, fontFamily: TERMINAL_FONT }}>Futures</span>)}{broker.supports_options && (- <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: COLORS.BLUE + '20', color: COLORS.BLUE }}>+ <span style={{ fontSize: '9px', padding: '1px 6px', backgroundColor: FINCEPT.BLUE + '20', color: FINCEPT.BLUE, fontFamily: TERMINAL_FONT }}>Options</span>)}{broker.websocket_enabled && (- <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: COLORS.ORANGE + '20', color: COLORS.ORANGE }}>- <Zap size={10} className="inline" /> WS+ <span style={{ fontSize: '9px', padding: '1px 6px', backgroundColor: FINCEPT.ORANGE + '20', color: FINCEPT.ORANGE, fontFamily: TERMINAL_FONT, display: 'flex', alignItems: 'center', gap: '2px' }}>+ <Zap size={8} /> WS</span>)}</div>@@ -224,23 +236,47 @@ const BrokerSelector: React.FC<BrokerSelectorProps> = ({const tickerData = tickerState.data;const isLoadingTicker = tickerState.status === 'loading';+ const selectStyle: React.CSSProperties = {+ flex: 1,+ padding: '4px 8px',+ fontSize: '10px',+ fontFamily: TERMINAL_FONT,+ backgroundColor: FINCEPT.CARD_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ outline: 'none',+ };+return (- <div- className="rounded-lg overflow-hidden"- style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}- >+ <div className="broker-panel" style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ overflow: 'hidden',+ fontFamily: TERMINAL_FONT,+ }}>+ <style>{BROKER_STYLES}</style>+{/* Header */}- <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-2">- <Building size={16} style={{ color: COLORS.ORANGE }} />- <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>- Broker Selection+ <div style={{+ padding: '10px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Building size={16} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontWeight: 600, fontSize: '12px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>+ BROKER SELECTION</span>{selectedBroker && (- <span- className="px-2 py-0.5 rounded text-xs"- style={{ backgroundColor: COLORS.GREEN + '20', color: COLORS.GREEN }}- >+ <span style={{+ padding: '1px 8px',+ fontSize: '10px',+ backgroundColor: FINCEPT.GREEN + '20',+ color: FINCEPT.GREEN,+ fontFamily: TERMINAL_FONT,+ }}>{selectedBroker.display_name}</span>)}@@ -248,60 +284,66 @@ const BrokerSelector: React.FC<BrokerSelectorProps> = ({<buttononClick={() => brokersCache.refresh()}disabled={isLoading}- className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"+ onMouseEnter={() => setHoveredBtn('refresh')}+ onMouseLeave={() => setHoveredBtn(null)}+ style={{+ padding: '4px',+ backgroundColor: hoveredBtn === 'refresh' ? FINCEPT.HOVER : 'transparent',+ border: 'none',+ cursor: isLoading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}><RefreshCwsize={14}- className={isLoading ? 'animate-spin' : ''}- style={{ color: COLORS.GRAY }}+ style={{+ color: FINCEPT.GRAY,+ animation: isLoading ? 'broker-spin 1s linear infinite' : 'none',+ }}/></button></div>{/* Search and Filters */}- <div className="px-4 py-3 border-b space-y-2" style={{ borderColor: COLORS.BORDER }}>- <div className="relative">- <Search size={14} className="absolute left-2 top-1/2 -translate-y-1/2" style={{ color: COLORS.GRAY }} />+ <div style={{ padding: '12px 16px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ position: 'relative', marginBottom: '8px' }}>+ <Search size={14} style={{ position: 'absolute', left: '8px', top: '50%', transform: 'translateY(-50%)', color: FINCEPT.GRAY }} /><inputtype="text"value={searchQuery}onChange={(e) => setSearchQuery(e.target.value)}placeholder="Search brokers..."- className="w-full pl-8 pr-3 py-1.5 rounded text-sm"style={{- backgroundColor: COLORS.CARD_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,+ width: '100%',+ paddingLeft: '30px',+ paddingRight: '12px',+ paddingTop: '6px',+ paddingBottom: '6px',+ fontSize: '12px',+ fontFamily: TERMINAL_FONT,+ backgroundColor: FINCEPT.CARD_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ outline: 'none',}}/></div>- <div className="flex gap-2">- {/* Type Filter */}+ <div style={{ display: 'flex', gap: '8px' }}><selectvalue={typeFilter || ''}onChange={(e) => setTypeFilter(e.target.value ? e.target.value as 'crypto' | 'stocks' | 'forex' : null)}- className="flex-1 px-2 py-1 rounded text-xs"- style={{- backgroundColor: COLORS.CARD_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,- }}+ style={selectStyle}><option value="">All Types</option><option value="crypto">Crypto</option><option value="stocks">Stocks</option><option value="forex">Forex</option></select>- {/* Region Filter */}<selectvalue={regionFilter || ''}onChange={(e) => setRegionFilter(e.target.value || null)}- className="flex-1 px-2 py-1 rounded text-xs"- style={{- backgroundColor: COLORS.CARD_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,- }}+ style={selectStyle}><option value="">All Regions</option><option value="global">Global</option>@@ -315,73 +357,100 @@ const BrokerSelector: React.FC<BrokerSelectorProps> = ({{/* Error */}{error && (- <div className="px-4 py-2 flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '10' }}>- <AlertTriangle size={14} style={{ color: COLORS.RED }} />- <span className="text-xs" style={{ color: COLORS.RED }}>{error.message}</span>+ <div style={{+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ backgroundColor: FINCEPT.RED + '10',+ }}>+ <AlertTriangle size={14} style={{ color: FINCEPT.RED }} />+ <span style={{ fontSize: '11px', color: FINCEPT.RED, fontFamily: TERMINAL_FONT }}>{error.message}</span></div>)}{/* Broker List */}- <div className="max-h-64 overflow-y-auto">+ <div style={{ maxHeight: '256px', overflowY: 'auto' }}>{isLoading ? (- <div className="flex items-center justify-center py-8">- <Loader2 size={24} className="animate-spin" style={{ color: COLORS.ORANGE }} />+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '32px 0' }}>+ <Loader2 size={24} style={{ color: FINCEPT.ORANGE, animation: 'broker-spin 1s linear infinite' }} /></div>) : sortedBrokers.length === 0 ? (- <div className="p-8 text-center">- <Building size={32} className="mx-auto mb-2 opacity-30" style={{ color: COLORS.GRAY }} />- <p className="text-sm" style={{ color: COLORS.GRAY }}>No brokers found</p>- <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>+ <div style={{ padding: '32px 16px', textAlign: 'center' }}>+ <Building size={32} style={{ color: FINCEPT.GRAY, opacity: 0.3, margin: '0 auto 8px' }} />+ <p style={{ fontSize: '12px', color: FINCEPT.GRAY }}>No brokers found</p>+ <p style={{ fontSize: '10px', marginTop: '4px', color: FINCEPT.GRAY }}>Try adjusting your filters</p></div>) : (- <div className="divide-y" style={{ borderColor: COLORS.BORDER }}>- {sortedBrokers.map((broker) => (- <div key={broker.id} className="p-3">+ <div>+ {sortedBrokers.map((broker, idx) => (+ <div key={broker.id} style={{+ padding: '12px',+ borderBottom: idx < sortedBrokers.length - 1 ? `1px solid ${FINCEPT.BORDER}` : 'none',+ backgroundColor: hoveredBrokerId === broker.id ? FINCEPT.HOVER : 'transparent',+ }}+ onMouseEnter={() => setHoveredBrokerId(broker.id)}+ onMouseLeave={() => setHoveredBrokerId(null)}+ ><buttononClick={() => handleBrokerSelect(broker)}- className={`w-full text-left ${selectedBroker?.id === broker.id ? 'ring-1' : ''}`}style={{- outlineColor: selectedBroker?.id === broker.id ? COLORS.ORANGE : 'transparent',+ width: '100%',+ textAlign: 'left',+ background: 'none',+ border: selectedBroker?.id === broker.id ? `1px solid ${FINCEPT.ORANGE}` : 'none',+ cursor: 'pointer',+ fontFamily: TERMINAL_FONT,+ padding: selectedBroker?.id === broker.id ? '4px' : 0,}}>- <div className="flex items-center justify-between">- <div className="flex items-center gap-2">- <span className="text-lg">{REGION_FLAGS[broker.region] || '🌐'}</span>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ fontSize: '16px' }}>{REGION_FLAGS[broker.region] || '🌐'}</span><div>- <div className="flex items-center gap-2">- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>{broker.display_name}</span>- <span- className="text-xs px-1.5 py-0.5 rounded"- style={{- backgroundColor: BROKER_TYPE_COLORS[broker.broker_type] + '20',- color: BROKER_TYPE_COLORS[broker.broker_type],- }}- >- {broker.broker_type}+ <span style={{+ fontSize: '9px',+ padding: '1px 6px',+ backgroundColor: BROKER_TYPE_COLORS[broker.broker_type] + '20',+ color: BROKER_TYPE_COLORS[broker.broker_type],+ fontFamily: TERMINAL_FONT,+ }}>+ {broker.broker_type.toUpperCase()}</span>{selectedBroker?.id === broker.id && (- <Check size={14} style={{ color: COLORS.GREEN }} />+ <Check size={14} style={{ color: FINCEPT.GREEN }} />)}</div>- <div className="text-xs mt-0.5" style={{ color: COLORS.GRAY }}>+ <div style={{ fontSize: '10px', marginTop: '2px', color: FINCEPT.GRAY }}>Fees: {(broker.maker_fee * 100).toFixed(2)}% / {(broker.taker_fee * 100).toFixed(2)}%- {broker.max_leverage > 1 && ` • ${broker.max_leverage}x leverage`}+ {broker.max_leverage > 1 && ` | ${broker.max_leverage}x leverage`}</div></div></div>- <div className="flex items-center gap-2">+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><buttononClick={(e) => toggleFavorite(broker.id, e)}- className="p-1 rounded hover:bg-[#1A1A1A]"+ onMouseEnter={() => setHoveredBtn(`fav-${broker.id}`)}+ onMouseLeave={() => setHoveredBtn(null)}+ style={{+ padding: '4px',+ backgroundColor: hoveredBtn === `fav-${broker.id}` ? FINCEPT.HEADER_BG : 'transparent',+ border: 'none',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}>{favorites.includes(broker.id) ? (- <Star size={14} style={{ color: COLORS.YELLOW }} fill={COLORS.YELLOW} />+ <Star size={14} style={{ color: FINCEPT.YELLOW }} fill={FINCEPT.YELLOW} />) : (- <StarOff size={14} style={{ color: COLORS.GRAY }} />+ <StarOff size={14} style={{ color: FINCEPT.GRAY }} />)}</button><button@@ -389,12 +458,21 @@ const BrokerSelector: React.FC<BrokerSelectorProps> = ({e.stopPropagation();setExpandedBroker(expandedBroker === broker.id ? null : broker.id);}}- className="p-1 rounded hover:bg-[#1A1A1A]"+ onMouseEnter={() => setHoveredBtn(`expand-${broker.id}`)}+ onMouseLeave={() => setHoveredBtn(null)}+ style={{+ padding: '4px',+ backgroundColor: hoveredBtn === `expand-${broker.id}` ? FINCEPT.HEADER_BG : 'transparent',+ border: 'none',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}>{expandedBroker === broker.id ? (- <ChevronDown size={14} style={{ color: COLORS.GRAY }} />+ <ChevronDown size={14} style={{ color: FINCEPT.GRAY }} />) : (- <ChevronRight size={14} style={{ color: COLORS.GRAY }} />+ <ChevronRight size={14} style={{ color: FINCEPT.GRAY }} />)}</button></div>@@ -406,33 +484,38 @@ const BrokerSelector: React.FC<BrokerSelectorProps> = ({{/* Expanded Details */}{expandedBroker === broker.id && (- <div className="mt-3 pt-3 border-t" style={{ borderColor: COLORS.BORDER }}>- <div className="grid grid-cols-2 gap-2 text-xs">+ <div style={{ marginTop: '12px', paddingTop: '12px', borderTop: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', fontSize: '11px' }}><div>- <span style={{ color: COLORS.GRAY }}>Region: </span>- <span style={{ color: COLORS.WHITE }}>+ <span style={{ color: FINCEPT.GRAY }}>Region: </span>+ <span style={{ color: FINCEPT.WHITE }}>{REGION_FLAGS[broker.region]} {broker.region.charAt(0).toUpperCase() + broker.region.slice(1)}</span></div><div>- <span style={{ color: COLORS.GRAY }}>Max Leverage: </span>- <span style={{ color: COLORS.WHITE }}>{broker.max_leverage}x</span>+ <span style={{ color: FINCEPT.GRAY }}>Max Leverage: </span>+ <span style={{ color: FINCEPT.WHITE }}>{broker.max_leverage}x</span></div></div>- <div className="mt-2">- <span className="text-xs" style={{ color: COLORS.GRAY }}>Default Symbols:</span>- <div className="flex flex-wrap gap-1 mt-1">+ <div style={{ marginTop: '8px' }}>+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>Default Symbols:</span>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginTop: '4px' }}>{broker.default_symbols.slice(0, 5).map((symbol) => (<spankey={symbol}- className="text-xs px-1.5 py-0.5 rounded"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}+ style={{+ fontSize: '9px',+ padding: '1px 6px',+ backgroundColor: FINCEPT.BORDER,+ color: FINCEPT.WHITE,+ fontFamily: TERMINAL_FONT,+ }}>{symbol}</span>))}{broker.default_symbols.length > 5 && (- <span className="text-xs" style={{ color: COLORS.GRAY }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+{broker.default_symbols.length - 5} more</span>)}@@ -448,22 +531,26 @@ const BrokerSelector: React.FC<BrokerSelectorProps> = ({{/* Selected Broker Ticker Preview */}{selectedBroker && tickerData && (- <div className="px-4 py-3 border-t" style={{ borderColor: COLORS.BORDER, backgroundColor: COLORS.CARD_BG }}>- <div className="flex items-center justify-between">- <div className="flex items-center gap-2">- <span className="text-xs" style={{ color: COLORS.GRAY }}>Sample Price:</span>- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>+ <div style={{+ padding: '12px 16px',+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: FINCEPT.CARD_BG,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>Sample Price:</span>+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>{tickerData.symbol}</span></div>{isLoadingTicker ? (- <Loader2 size={14} className="animate-spin" style={{ color: COLORS.GRAY }} />+ <Loader2 size={14} style={{ color: FINCEPT.GRAY, animation: 'broker-spin 1s linear infinite' }} />) : (- <div className="text-right">- <div className="text-sm font-bold" style={{ color: COLORS.WHITE }}>+ <div style={{ textAlign: 'right' }}>+ <div style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>${tickerData.price.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>24h Vol: {tickerData.volume_24h.toLocaleString()}</div></div>@@ -473,13 +560,21 @@ const BrokerSelector: React.FC<BrokerSelectorProps> = ({)}{/* Footer */}- <div className="px-4 py-2 border-t text-xs flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <span style={{ color: COLORS.GRAY }}>+ <div style={{+ padding: '6px 16px',+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ fontSize: '9px',+ backgroundColor: FINCEPT.HEADER_BG,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <span style={{ color: FINCEPT.GRAY }}>{sortedBrokers.length} broker{sortedBrokers.length !== 1 ? 's' : ''} available</span>{favorites.length > 0 && (- <span style={{ color: COLORS.YELLOW }}>- <Star size={10} className="inline mr-1" fill={COLORS.YELLOW} />+ <span style={{ color: FINCEPT.YELLOW, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <Star size={10} fill={FINCEPT.YELLOW} />{favorites.length} favorite{favorites.length !== 1 ? 's' : ''}</span>)}diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/GridStrategyPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/GridStrategyPanel.tsxindex 1b6e12af8..83e63df9b 100644--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/GridStrategyPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/GridStrategyPanel.tsx@@ -7,9 +7,9 @@import React, { useState, useEffect, useReducer, useRef } from 'react';import {- Grid3X3, Settings, RefreshCw, Play, Pause, AlertTriangle,- TrendingUp, TrendingDown, DollarSign, Loader2, Info,- ChevronDown, ChevronUp, Plus, Trash2, Check,+ Grid3X3, RefreshCw, Play, AlertTriangle,+ Loader2, Info,+ ChevronDown, ChevronUp, Plus, Check,} from 'lucide-react';import { withErrorBoundary } from '@/components/common/ErrorBoundary';import {@@ -17,7 +17,7 @@ import {type GridConfig,} from '../services/alphaArenaEnhancedService';-const COLORS = {+const FINCEPT = {ORANGE: '#FF8800',WHITE: '#FFFFFF',RED: '#FF3B3B',@@ -28,10 +28,21 @@ const COLORS = {GRAY: '#787878',DARK_BG: '#000000',PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',CARD_BG: '#0A0A0A',BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',};+const TERMINAL_FONT = '"IBM Plex Mono", "Consolas", monospace';++const GRID_STYLES = `+ .grid-panel *::-webkit-scrollbar { width: 6px; height: 6px; }+ .grid-panel *::-webkit-scrollbar-track { background: #000000; }+ .grid-panel *::-webkit-scrollbar-thumb { background: #2A2A2A; }+ @keyframes grid-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }+`;+interface GridStrategyPanelProps {symbol?: string;currentPrice?: number;@@ -80,6 +91,7 @@ const GridStrategyPanel: React.FC<GridStrategyPanelProps> = ({const [createState, dispatchCreate] = useReducer(createReducer, { status: 'idle' });const [activeGrids, setActiveGrids] = useState<GridAgentStatus[]>([]);const mountedRef = useRef(true);+ const [hoveredBtn, setHoveredBtn] = useState<string | null>(null);useEffect(() => {mountedRef.current = true;@@ -131,7 +143,6 @@ const GridStrategyPanel: React.FC<GridStrategyPanelProps> = ({const handleCreateGrid = async () => {if (createState.status === 'creating') return;- // Validate grid configif (!gridName.trim()) {dispatchCreate({ type: 'CREATE_ERROR', error: 'Please enter a name for the grid strategy' });return;@@ -161,7 +172,6 @@ const GridStrategyPanel: React.FC<GridStrategyPanelProps> = ({setGridName('');onGridCreated?.(gridName);- // Add to active gridssetActiveGrids(prev => [...prev, {name: gridName,symbol: gridConfig.symbol,@@ -210,7 +220,7 @@ const GridStrategyPanel: React.FC<GridStrategyPanelProps> = ({const range = maxPrice - minPrice;return (- <div className="relative h-32 my-2">+ <div style={{ position: 'relative', height: '128px', margin: '8px 0' }}>{levels.map((level, idx) => {const position = ((maxPrice - level) / range) * 100;const isTriggered = triggeredLevels.includes(level);@@ -219,39 +229,48 @@ const GridStrategyPanel: React.FC<GridStrategyPanelProps> = ({return (<divkey={idx}- className="absolute left-0 right-0 flex items-center"- style={{ top: `${position}%` }}+ style={{+ position: 'absolute',+ left: 0,+ right: 0,+ display: 'flex',+ alignItems: 'center',+ top: `${position}%`,+ }}>- <div- className="h-0.5 flex-1"- style={{- backgroundColor: isTriggered ? COLORS.GREEN : isCurrentPrice ? COLORS.ORANGE : COLORS.BORDER,- }}- />- <span- className="text-xs ml-2 w-16 text-right"- style={{- color: isTriggered ? COLORS.GREEN : isCurrentPrice ? COLORS.ORANGE : COLORS.GRAY,- }}- >+ <div style={{+ height: '1px',+ flex: 1,+ backgroundColor: isTriggered ? FINCEPT.GREEN : isCurrentPrice ? FINCEPT.ORANGE : FINCEPT.BORDER,+ }} />+ <span style={{+ fontSize: '10px',+ marginLeft: '8px',+ width: '64px',+ textAlign: 'right',+ fontFamily: TERMINAL_FONT,+ color: isTriggered ? FINCEPT.GREEN : isCurrentPrice ? FINCEPT.ORANGE : FINCEPT.GRAY,+ }}>${level.toFixed(0)}</span></div>);})}{/* Current price indicator */}- <div- className="absolute left-0 flex items-center"- style={{- top: `${((maxPrice - currentPrice) / range) * 100}%`,- transform: 'translateY(-50%)',- }}- >- <div- className="w-2 h-2 rounded-full"- style={{ backgroundColor: COLORS.ORANGE }}- />- <span className="text-xs ml-1" style={{ color: COLORS.ORANGE }}>+ <div style={{+ position: 'absolute',+ left: 0,+ display: 'flex',+ alignItems: 'center',+ top: `${((maxPrice - currentPrice) / range) * 100}%`,+ transform: 'translateY(-50%)',+ }}>+ <div style={{+ width: '6px',+ height: '6px',+ backgroundColor: FINCEPT.ORANGE,+ }} />+ <span style={{ fontSize: '10px', marginLeft: '4px', color: FINCEPT.ORANGE, fontFamily: TERMINAL_FONT }}>Current</span></div>@@ -259,262 +278,334 @@ const GridStrategyPanel: React.FC<GridStrategyPanelProps> = ({);};+ const inputStyle: React.CSSProperties = {+ width: '100%',+ padding: '6px 8px',+ fontSize: '11px',+ fontFamily: TERMINAL_FONT,+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ outline: 'none',+ };+return (- <div- className="rounded-lg overflow-hidden"- style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}- >+ <div className="grid-panel" style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ overflow: 'hidden',+ fontFamily: TERMINAL_FONT,+ }}>+ <style>{GRID_STYLES}</style>+{/* Header */}- <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-2">- <Grid3X3 size={16} style={{ color: COLORS.BLUE }} />- <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>- Grid Trading+ <div style={{+ padding: '10px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Grid3X3 size={16} style={{ color: FINCEPT.BLUE }} />+ <span style={{ fontWeight: 600, fontSize: '12px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>+ GRID TRADING</span>{activeGrids.length > 0 && (- <span- className="px-2 py-0.5 rounded-full text-xs"- style={{ backgroundColor: COLORS.BLUE + '20', color: COLORS.BLUE }}- >+ <span style={{+ padding: '1px 8px',+ fontSize: '10px',+ backgroundColor: FINCEPT.BLUE + '20',+ color: FINCEPT.BLUE,+ fontFamily: TERMINAL_FONT,+ }}>{activeGrids.length} active</span>)}</div><buttononClick={() => setShowCreateForm(!showCreateForm)}- className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"+ onMouseEnter={() => setHoveredBtn('add')}+ onMouseLeave={() => setHoveredBtn(null)}+ style={{+ padding: '4px',+ backgroundColor: hoveredBtn === 'add' ? FINCEPT.HOVER : 'transparent',+ border: 'none',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}>- <Plus size={14} style={{ color: COLORS.GRAY }} />+ <Plus size={14} style={{ color: FINCEPT.GRAY }} /></button></div>{/* Messages */}{createState.status === 'error' && (- <div className="px-4 py-2 flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '10' }}>- <AlertTriangle size={14} style={{ color: COLORS.RED }} />- <span className="text-xs" style={{ color: COLORS.RED }}>{createState.error}</span>+ <div style={{+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ backgroundColor: FINCEPT.RED + '10',+ }}>+ <AlertTriangle size={14} style={{ color: FINCEPT.RED }} />+ <span style={{ fontSize: '11px', color: FINCEPT.RED, fontFamily: TERMINAL_FONT }}>{createState.error}</span></div>)}{createState.status === 'success' && (- <div className="px-4 py-2 flex items-center gap-2" style={{ backgroundColor: COLORS.GREEN + '10' }}>- <Check size={14} style={{ color: COLORS.GREEN }} />- <span className="text-xs" style={{ color: COLORS.GREEN }}>{createState.message}</span>+ <div style={{+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ backgroundColor: FINCEPT.GREEN + '10',+ }}>+ <Check size={14} style={{ color: FINCEPT.GREEN }} />+ <span style={{ fontSize: '11px', color: FINCEPT.GREEN, fontFamily: TERMINAL_FONT }}>{createState.message}</span></div>)}{/* Create Form */}{showCreateForm && (- <div className="px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER, backgroundColor: COLORS.CARD_BG }}>- <h4 className="text-xs font-medium mb-3" style={{ color: COLORS.WHITE }}>Create Grid Strategy</h4>+ <div style={{+ padding: '12px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: FINCEPT.CARD_BG,+ }}>+ <div style={{ fontSize: '11px', fontWeight: 500, marginBottom: '12px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>+ CREATE GRID STRATEGY+ </div>{/* Name Input */}- <div className="mb-3">- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Strategy Name</label>+ <div style={{ marginBottom: '12px' }}>+ <label style={{ fontSize: '10px', marginBottom: '4px', display: 'block', color: FINCEPT.GRAY }}>Strategy Name</label><inputtype="text"value={gridName}onChange={(e) => setGridName(e.target.value)}placeholder="My Grid Strategy"- className="w-full px-2 py-1.5 rounded text-xs"- style={{- backgroundColor: COLORS.DARK_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,- }}+ style={inputStyle}/></div>{/* Price Range */}- <div className="grid grid-cols-2 gap-2 mb-3">+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '12px' }}><div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Lower Price</label>+ <label style={{ fontSize: '10px', marginBottom: '4px', display: 'block', color: FINCEPT.GRAY }}>Lower Price</label><inputtype="text"inputMode="decimal"value={gridConfig.lower_price}onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setGridConfig(prev => ({ ...prev, lower_price: parseFloat(v) || 0 })); }}- className="w-full px-2 py-1.5 rounded text-xs"- style={{- backgroundColor: COLORS.DARK_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,- }}+ style={inputStyle}/></div><div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Upper Price</label>+ <label style={{ fontSize: '10px', marginBottom: '4px', display: 'block', color: FINCEPT.GRAY }}>Upper Price</label><inputtype="text"inputMode="decimal"value={gridConfig.upper_price}onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setGridConfig(prev => ({ ...prev, upper_price: parseFloat(v) || 0 })); }}- className="w-full px-2 py-1.5 rounded text-xs"- style={{- backgroundColor: COLORS.DARK_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,- }}+ style={inputStyle}/></div></div>{/* Grid Settings */}- <div className="grid grid-cols-2 gap-2 mb-3">+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '12px' }}><div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Number of Grids</label>+ <label style={{ fontSize: '10px', marginBottom: '4px', display: 'block', color: FINCEPT.GRAY }}>Number of Grids</label><inputtype="text"inputMode="numeric"value={gridConfig.num_grids}onChange={(e) => { const v = e.target.value; if (v === '' || /^\d+$/.test(v)) setGridConfig(prev => ({ ...prev, num_grids: Math.min(parseInt(v) || 5, 50) })); }}- className="w-full px-2 py-1.5 rounded text-xs"- style={{- backgroundColor: COLORS.DARK_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,- }}+ style={inputStyle}/></div><div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Qty per Grid</label>+ <label style={{ fontSize: '10px', marginBottom: '4px', display: 'block', color: FINCEPT.GRAY }}>Qty per Grid</label><inputtype="text"inputMode="decimal"value={gridConfig.quantity_per_grid}onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setGridConfig(prev => ({ ...prev, quantity_per_grid: parseFloat(v) || 0.001 })); }}- className="w-full px-2 py-1.5 rounded text-xs"- style={{- backgroundColor: COLORS.DARK_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,- }}+ style={inputStyle}/></div></div>{/* Summary */}- <div className="p-2 rounded mb-3" style={{ backgroundColor: COLORS.DARK_BG }}>- <div className="grid grid-cols-2 gap-2 text-xs">+ <div style={{+ padding: '8px',+ marginBottom: '12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', fontSize: '11px' }}><div>- <span style={{ color: COLORS.GRAY }}>Grid Spacing: </span>- <span style={{ color: COLORS.WHITE }}>${calculateGridSpacing().toFixed(2)}</span>+ <span style={{ color: FINCEPT.GRAY }}>Grid Spacing: </span>+ <span style={{ color: FINCEPT.WHITE }}>${calculateGridSpacing().toFixed(2)}</span></div><div>- <span style={{ color: COLORS.GRAY }}>Est. Investment: </span>- <span style={{ color: COLORS.WHITE }}>${calculateTotalInvestment().toFixed(2)}</span>+ <span style={{ color: FINCEPT.GRAY }}>Est. Investment: </span>+ <span style={{ color: FINCEPT.WHITE }}>${calculateTotalInvestment().toFixed(2)}</span></div></div></div>{/* Preview */}- <div className="mb-3">- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Grid Preview</label>+ <div style={{ marginBottom: '12px' }}>+ <label style={{ fontSize: '10px', marginBottom: '4px', display: 'block', color: FINCEPT.GRAY }}>Grid Preview</label>{renderGridVisualization(generateGridLevels(), [])}</div>{/* Actions */}- <div className="flex gap-2">+ <div style={{ display: 'flex', gap: '8px' }}><buttononClick={() => setShowCreateForm(false)}- className="flex-1 py-1.5 rounded text-xs font-medium"+ onMouseEnter={() => setHoveredBtn('cancel')}+ onMouseLeave={() => setHoveredBtn(null)}style={{- backgroundColor: COLORS.BORDER,- color: COLORS.WHITE,+ flex: 1,+ padding: '6px',+ fontSize: '11px',+ fontWeight: 600,+ fontFamily: TERMINAL_FONT,+ backgroundColor: hoveredBtn === 'cancel' ? FINCEPT.HOVER : FINCEPT.BORDER,+ color: FINCEPT.WHITE,+ border: 'none',+ cursor: 'pointer',+ letterSpacing: '0.5px',}}>- Cancel+ CANCEL</button><buttononClick={handleCreateGrid}disabled={createState.status === 'creating'}- className="flex-1 py-1.5 rounded text-xs font-medium flex items-center justify-center gap-1"style={{- backgroundColor: COLORS.BLUE,- color: COLORS.WHITE,+ flex: 1,+ padding: '6px',+ fontSize: '11px',+ fontWeight: 600,+ fontFamily: TERMINAL_FONT,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '4px',+ backgroundColor: FINCEPT.BLUE,+ color: FINCEPT.WHITE,+ border: 'none',+ cursor: createState.status === 'creating' ? 'not-allowed' : 'pointer',opacity: createState.status === 'creating' ? 0.5 : 1,+ letterSpacing: '0.5px',}}>{createState.status === 'creating' ? (- <Loader2 size={12} className="animate-spin" />+ <Loader2 size={12} style={{ animation: 'grid-spin 1s linear infinite' }} />) : (<Play size={12} />)}- Create Grid+ CREATE GRID</button></div></div>)}{/* Active Grids */}- <div className="max-h-64 overflow-y-auto">+ <div style={{ maxHeight: '256px', overflowY: 'auto' }}>{activeGrids.length === 0 ? (- <div className="p-8 text-center">- <Grid3X3 size={32} className="mx-auto mb-2 opacity-30" style={{ color: COLORS.GRAY }} />- <p className="text-sm" style={{ color: COLORS.GRAY }}>No active grid strategies</p>- <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>+ <div style={{ padding: '32px 16px', textAlign: 'center' }}>+ <Grid3X3 size={32} style={{ color: FINCEPT.GRAY, opacity: 0.3, margin: '0 auto 8px' }} />+ <p style={{ fontSize: '12px', color: FINCEPT.GRAY }}>No active grid strategies</p>+ <p style={{ fontSize: '10px', marginTop: '4px', color: FINCEPT.GRAY }}>Create a grid to start automated trading</p></div>) : (- <div className="divide-y" style={{ borderColor: COLORS.BORDER }}>- {activeGrids.map((grid) => (- <div key={grid.name} className="p-3">- <div className="flex items-center justify-between mb-2">+ <div>+ {activeGrids.map((grid, idx) => (+ <div key={grid.name} style={{+ padding: '12px',+ borderBottom: idx < activeGrids.length - 1 ? `1px solid ${FINCEPT.BORDER}` : 'none',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}><buttononClick={() => setExpandedGrid(expandedGrid === grid.name ? null : grid.name)}- className="flex items-center gap-2"+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ fontFamily: TERMINAL_FONT,+ padding: 0,+ }}>{expandedGrid === grid.name ? (- <ChevronUp size={12} style={{ color: COLORS.GRAY }} />+ <ChevronUp size={12} style={{ color: FINCEPT.GRAY }} />) : (- <ChevronDown size={12} style={{ color: COLORS.GRAY }} />+ <ChevronDown size={12} style={{ color: FINCEPT.GRAY }} />)}- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{grid.name}</span>- <span- className="px-1.5 py-0.5 rounded text-xs"- style={{- backgroundColor: grid.isActive ? COLORS.GREEN + '20' : COLORS.GRAY + '20',- color: grid.isActive ? COLORS.GREEN : COLORS.GRAY,- }}- >- {grid.isActive ? 'Active' : 'Paused'}+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>{grid.name}</span>+ <span style={{+ padding: '1px 6px',+ fontSize: '9px',+ fontFamily: TERMINAL_FONT,+ backgroundColor: grid.isActive ? FINCEPT.GREEN + '20' : FINCEPT.GRAY + '20',+ color: grid.isActive ? FINCEPT.GREEN : FINCEPT.GRAY,+ }}>+ {grid.isActive ? 'ACTIVE' : 'PAUSED'}</span></button>- <div className="flex items-center gap-2">+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><buttononClick={() => fetchGridStatus(grid.name)}- className="p-1 rounded hover:bg-[#1A1A1A]"+ onMouseEnter={() => setHoveredBtn(`refresh-${grid.name}`)}+ onMouseLeave={() => setHoveredBtn(null)}+ style={{+ padding: '4px',+ backgroundColor: hoveredBtn === `refresh-${grid.name}` ? FINCEPT.HOVER : 'transparent',+ border: 'none',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}>- <RefreshCw size={12} style={{ color: COLORS.GRAY }} />+ <RefreshCw size={12} style={{ color: FINCEPT.GRAY }} /></button></div></div>{/* Quick Stats */}- <div className="grid grid-cols-3 gap-2 text-xs">+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', fontSize: '11px' }}><div>- <span style={{ color: COLORS.GRAY }}>Trades: </span>- <span style={{ color: COLORS.WHITE }}>{grid.tradesExecuted}</span>+ <span style={{ color: FINCEPT.GRAY }}>Trades: </span>+ <span style={{ color: FINCEPT.WHITE }}>{grid.tradesExecuted}</span></div><div>- <span style={{ color: COLORS.GRAY }}>Profit: </span>- <span style={{ color: grid.totalProfit >= 0 ? COLORS.GREEN : COLORS.RED }}>+ <span style={{ color: FINCEPT.GRAY }}>Profit: </span>+ <span style={{ color: grid.totalProfit >= 0 ? FINCEPT.GREEN : FINCEPT.RED }}>${grid.totalProfit.toFixed(2)}</span></div><div>- <span style={{ color: COLORS.GRAY }}>Active: </span>- <span style={{ color: COLORS.WHITE }}>{grid.activeOrders}</span>+ <span style={{ color: FINCEPT.GRAY }}>Active: </span>+ <span style={{ color: FINCEPT.WHITE }}>{grid.activeOrders}</span></div></div>{/* Expanded View */}{expandedGrid === grid.name && (- <div className="mt-3 pt-3 border-t" style={{ borderColor: COLORS.BORDER }}>- <div className="text-xs mb-2" style={{ color: COLORS.GRAY }}>Grid Levels</div>+ <div style={{ marginTop: '12px', paddingTop: '12px', borderTop: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ fontSize: '10px', marginBottom: '8px', color: FINCEPT.GRAY }}>Grid Levels</div>{renderGridVisualization(grid.gridLevels, grid.triggeredLevels)}- <div className="text-xs mt-2" style={{ color: COLORS.GRAY }}>- <Info size={10} className="inline mr-1" />+ <div style={{ fontSize: '10px', marginTop: '8px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <Info size={10} />{grid.triggeredLevels.length} of {grid.gridLevels.length} levels triggered</div></div>@@ -526,8 +617,17 @@ const GridStrategyPanel: React.FC<GridStrategyPanelProps> = ({</div>{/* Footer */}- <div className="px-4 py-2 border-t text-xs" style={{ borderColor: COLORS.BORDER, color: COLORS.GRAY }}>- <Info size={10} className="inline mr-1" />+ <div style={{+ padding: '6px 16px',+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ fontSize: '9px',+ backgroundColor: FINCEPT.HEADER_BG,+ color: FINCEPT.GRAY,+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}>+ <Info size={10} />Grid strategies execute automatically based on price levels</div></div>diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/HITLApprovalPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/HITLApprovalPanel.tsxindex 1a9fe9888..f1074c94d 100644--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/HITLApprovalPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/HITLApprovalPanel.tsx@@ -9,7 +9,7 @@ import React, { useState, useReducer, useRef, useEffect } from 'react';import {Shield, AlertTriangle, Check, X, Clock, RefreshCw,Settings, ChevronDown, ChevronUp, Loader2,- AlertCircle, CheckCircle, Info,+ AlertCircle, CheckCircle,} from 'lucide-react';import { withErrorBoundary } from '@/components/common/ErrorBoundary';import { useCache, cacheKey } from '@/hooks/useCache';@@ -19,7 +19,7 @@ import {type HITLStatus,} from '../services/alphaArenaEnhancedService';-const COLORS = {+const FINCEPT = {ORANGE: '#FF8800',WHITE: '#FFFFFF',RED: '#FF3B3B',@@ -30,15 +30,19 @@ const COLORS = {GRAY: '#787878',DARK_BG: '#000000',PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',CARD_BG: '#0A0A0A',BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',};+const TERMINAL_FONT = '"IBM Plex Mono", "Consolas", monospace';+const RISK_COLORS: Record<string, string> = {- low: COLORS.GREEN,- medium: COLORS.YELLOW,- high: COLORS.ORANGE,- critical: COLORS.RED,+ low: FINCEPT.GREEN,+ medium: FINCEPT.YELLOW,+ high: FINCEPT.ORANGE,+ critical: FINCEPT.RED,};interface HITLApprovalPanelProps {@@ -73,6 +77,13 @@ interface HITLData {pending_approvals: ApprovalRequest[];}+const HITL_STYLES = `+ .hitl-panel *::-webkit-scrollbar { width: 6px; height: 6px; }+ .hitl-panel *::-webkit-scrollbar-track { background: #000000; }+ .hitl-panel *::-webkit-scrollbar-thumb { background: #2A2A2A; }+ @keyframes hitl-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }+`;+const HITLApprovalPanel: React.FC<HITLApprovalPanelProps> = ({competitionId,onApprovalChange,@@ -81,6 +92,7 @@ const HITLApprovalPanel: React.FC<HITLApprovalPanelProps> = ({const [expandedApproval, setExpandedApproval] = useState<string | null>(null);const [actionState, dispatchAction] = useReducer(actionReducer, { status: 'idle' });const mountedRef = useRef(true);+ const [hoveredBtn, setHoveredBtn] = useState<string | null>(null);useEffect(() => {mountedRef.current = true;@@ -180,44 +192,78 @@ const HITLApprovalPanel: React.FC<HITLApprovalPanelProps> = ({const error = actionState.status === 'error' ? actionState.error : fetchError?.message || null;return (- <div- className="rounded-lg overflow-hidden"- style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}- >+ <div className="hitl-panel" style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ overflow: 'hidden',+ fontFamily: TERMINAL_FONT,+ }}>+ <style>{HITL_STYLES}</style>+{/* Header */}- <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-2">- <Shield size={16} style={{ color: COLORS.ORANGE }} />- <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>- HITL Approval+ <div style={{+ padding: '10px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Shield size={16} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontWeight: 600, fontSize: '12px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>+ HITL APPROVAL</span>{pendingApprovals.length > 0 && (- <span- className="px-2 py-0.5 rounded-full text-xs font-medium"- style={{ backgroundColor: COLORS.RED + '20', color: COLORS.RED }}- >- {pendingApprovals.length} pending+ <span style={{+ padding: '1px 8px',+ fontSize: '10px',+ fontWeight: 600,+ backgroundColor: FINCEPT.RED + '20',+ color: FINCEPT.RED,+ fontFamily: TERMINAL_FONT,+ }}>+ {pendingApprovals.length} PENDING</span>)}</div>- <div className="flex items-center gap-2">+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}><buttononClick={() => setShowSettings(!showSettings)}- className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"+ onMouseEnter={() => setHoveredBtn('settings')}+ onMouseLeave={() => setHoveredBtn(null)}+ style={{+ padding: '4px',+ backgroundColor: hoveredBtn === 'settings' ? FINCEPT.HOVER : 'transparent',+ border: 'none',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}title="Settings">- <Settings size={14} style={{ color: COLORS.GRAY }} />+ <Settings size={14} style={{ color: FINCEPT.GRAY }} /></button><buttononClick={() => hitlCache.refresh()}disabled={isLoading}- className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"+ onMouseEnter={() => setHoveredBtn('refresh')}+ onMouseLeave={() => setHoveredBtn(null)}+ style={{+ padding: '4px',+ backgroundColor: hoveredBtn === 'refresh' ? FINCEPT.HOVER : 'transparent',+ border: 'none',+ cursor: isLoading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}title="Refresh"><RefreshCwsize={14}- className={isLoading ? 'animate-spin' : ''}- style={{ color: COLORS.GRAY }}+ style={{+ color: FINCEPT.GRAY,+ animation: isLoading ? 'hitl-spin 1s linear infinite' : 'none',+ }}/></button></div>@@ -225,41 +271,75 @@ const HITLApprovalPanel: React.FC<HITLApprovalPanelProps> = ({{/* Error */}{error && (- <div className="px-4 py-2 flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '10' }}>- <AlertCircle size={14} style={{ color: COLORS.RED }} />- <span className="text-xs" style={{ color: COLORS.RED }}>{error}</span>- <button onClick={() => dispatchAction({ type: 'CLEAR_ERROR' })} className="ml-auto">- <X size={12} style={{ color: COLORS.RED }} />+ <div style={{+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ backgroundColor: FINCEPT.RED + '10',+ }}>+ <AlertCircle size={14} style={{ color: FINCEPT.RED }} />+ <span style={{ fontSize: '11px', color: FINCEPT.RED, fontFamily: TERMINAL_FONT }}>{error}</span>+ <button+ onClick={() => dispatchAction({ type: 'CLEAR_ERROR' })}+ style={{ marginLeft: 'auto', background: 'none', border: 'none', cursor: 'pointer' }}+ >+ <X size={12} style={{ color: FINCEPT.RED }} /></button></div>)}{/* Settings Panel */}{showSettings && hitlStatus && (- <div className="px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER, backgroundColor: COLORS.CARD_BG }}>- <h4 className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>Approval Rules</h4>- <div className="space-y-2">+ <div style={{+ padding: '12px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: FINCEPT.CARD_BG,+ }}>+ <div style={{ fontSize: '10px', fontWeight: 500, marginBottom: '8px', color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>+ APPROVAL RULES+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>{hitlStatus.rules.map(rule => (- <div key={rule.name} className="flex items-center justify-between">- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2">- <span className="text-xs" style={{ color: COLORS.WHITE }}>{rule.name}</span>- <span- className="text-xs px-1.5 py-0.5 rounded"- style={{ backgroundColor: RISK_COLORS[rule.risk_level] + '20', color: RISK_COLORS[rule.risk_level] }}- >- {rule.risk_level}+ <div key={rule.name} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ fontSize: '11px', color: FINCEPT.WHITE, fontFamily: TERMINAL_FONT }}>{rule.name}</span>+ <span style={{+ fontSize: '9px',+ padding: '1px 6px',+ backgroundColor: RISK_COLORS[rule.risk_level] + '20',+ color: RISK_COLORS[rule.risk_level],+ fontFamily: TERMINAL_FONT,+ }}>+ {rule.risk_level.toUpperCase()}</span></div>- <p className="text-xs truncate" style={{ color: COLORS.GRAY }}>{rule.description}</p>+ <p style={{ fontSize: '10px', color: FINCEPT.GRAY, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {rule.description}+ </p></div><buttononClick={() => handleToggleRule(rule.name, rule.enabled)}- className={`w-10 h-5 rounded-full transition-colors relative ${rule.enabled ? 'bg-green-500' : 'bg-gray-600'}`}+ style={{+ width: '36px',+ height: '18px',+ backgroundColor: rule.enabled ? FINCEPT.GREEN : '#444',+ border: 'none',+ cursor: 'pointer',+ position: 'relative',+ flexShrink: 0,+ }}>- <div- className={`w-4 h-4 rounded-full bg-white absolute top-0.5 transition-transform ${rule.enabled ? 'translate-x-5' : 'translate-x-0.5'}`}- />+ <div style={{+ width: '14px',+ height: '14px',+ backgroundColor: FINCEPT.WHITE,+ position: 'absolute',+ top: '2px',+ left: rule.enabled ? '20px' : '2px',+ transition: 'left 0.2s',+ }} /></button></div>))}@@ -268,126 +348,178 @@ const HITLApprovalPanel: React.FC<HITLApprovalPanelProps> = ({)}{/* Pending Approvals */}- <div className="max-h-80 overflow-y-auto">+ <div style={{ maxHeight: '320px', overflowY: 'auto' }}>{pendingApprovals.length === 0 ? (- <div className="p-8 text-center">- <CheckCircle size={32} className="mx-auto mb-2" style={{ color: COLORS.GREEN, opacity: 0.5 }} />- <p className="text-sm" style={{ color: COLORS.GRAY }}>No pending approvals</p>- <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>All trading decisions approved or auto-approved</p>+ <div style={{ padding: '32px 16px', textAlign: 'center' }}>+ <CheckCircle size={32} style={{ color: FINCEPT.GREEN, opacity: 0.5, margin: '0 auto 8px' }} />+ <p style={{ fontSize: '12px', color: FINCEPT.GRAY }}>No pending approvals</p>+ <p style={{ fontSize: '10px', marginTop: '4px', color: FINCEPT.GRAY }}>+ All trading decisions approved or auto-approved+ </p></div>) : (- <div className="divide-y" style={{ borderColor: COLORS.BORDER }}>- {pendingApprovals.map(approval => (- <div key={approval.id} className="p-3">+ <div>+ {pendingApprovals.map((approval, idx) => (+ <div key={approval.id} style={{+ padding: '12px',+ borderBottom: idx < pendingApprovals.length - 1 ? `1px solid ${FINCEPT.BORDER}` : 'none',+ }}>{/* Header */}- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <AlertTriangle- size={14}- style={{ color: RISK_COLORS[approval.risk_level] }}- />- <span className="text-xs font-medium" style={{ color: COLORS.WHITE }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <AlertTriangle size={14} style={{ color: RISK_COLORS[approval.risk_level] }} />+ <span style={{ fontSize: '11px', fontWeight: 500, color: FINCEPT.WHITE, fontFamily: TERMINAL_FONT }}>{approval.decision.model_name}</span>- <span- className="text-xs px-1.5 py-0.5 rounded font-medium"- style={{- backgroundColor: approval.decision.action === 'buy' ? COLORS.GREEN + '20' :- approval.decision.action === 'sell' ? COLORS.RED + '20' : COLORS.GRAY + '20',- color: approval.decision.action === 'buy' ? COLORS.GREEN :- approval.decision.action === 'sell' ? COLORS.RED : COLORS.GRAY,- }}- >+ <span style={{+ fontSize: '10px',+ padding: '1px 6px',+ fontWeight: 500,+ fontFamily: TERMINAL_FONT,+ backgroundColor: approval.decision.action === 'buy' ? FINCEPT.GREEN + '20' :+ approval.decision.action === 'sell' ? FINCEPT.RED + '20' : FINCEPT.GRAY + '20',+ color: approval.decision.action === 'buy' ? FINCEPT.GREEN :+ approval.decision.action === 'sell' ? FINCEPT.RED : FINCEPT.GRAY,+ }}>{approval.decision.action.toUpperCase()}</span></div>- <div className="flex items-center gap-1 text-xs" style={{ color: COLORS.GRAY }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '10px', color: FINCEPT.GRAY }}><Clock size={10} />{getTimeRemaining(approval.expires_at)}</div></div>{/* Trade Details */}- <div className="grid grid-cols-3 gap-2 mb-2 text-xs">+ <div style={{+ display: 'grid',+ gridTemplateColumns: '1fr 1fr 1fr',+ gap: '8px',+ marginBottom: '8px',+ fontSize: '11px',+ }}><div>- <span style={{ color: COLORS.GRAY }}>Symbol: </span>- <span style={{ color: COLORS.WHITE }}>{approval.decision.symbol}</span>+ <span style={{ color: FINCEPT.GRAY }}>Symbol: </span>+ <span style={{ color: FINCEPT.WHITE }}>{approval.decision.symbol}</span></div><div>- <span style={{ color: COLORS.GRAY }}>Qty: </span>- <span style={{ color: COLORS.WHITE }}>{approval.decision.quantity.toFixed(4)}</span>+ <span style={{ color: FINCEPT.GRAY }}>Qty: </span>+ <span style={{ color: FINCEPT.WHITE }}>{approval.decision.quantity.toFixed(4)}</span></div><div>- <span style={{ color: COLORS.GRAY }}>Conf: </span>- <span style={{ color: COLORS.WHITE }}>{(approval.decision.confidence * 100).toFixed(0)}%</span>+ <span style={{ color: FINCEPT.GRAY }}>Conf: </span>+ <span style={{ color: FINCEPT.WHITE }}>{(approval.decision.confidence * 100).toFixed(0)}%</span></div></div>{/* Risk Level */}- <div- className="text-xs px-2 py-1 rounded mb-2"- style={{- backgroundColor: RISK_COLORS[approval.risk_level] + '10',- color: RISK_COLORS[approval.risk_level],- }}- >- {approval.reason.split('\n').slice(0, 2).join(' • ')}+ <div style={{+ fontSize: '10px',+ padding: '4px 8px',+ marginBottom: '8px',+ backgroundColor: RISK_COLORS[approval.risk_level] + '10',+ color: RISK_COLORS[approval.risk_level],+ fontFamily: TERMINAL_FONT,+ }}>+ {approval.reason.split('\n').slice(0, 2).join(' | ')}</div>{/* Expandable Reasoning */}<buttononClick={() => setExpandedApproval(expandedApproval === approval.id ? null : approval.id)}- className="flex items-center gap-1 text-xs mb-2"- style={{ color: COLORS.GRAY }}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ fontSize: '10px',+ marginBottom: '8px',+ color: FINCEPT.GRAY,+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ fontFamily: TERMINAL_FONT,+ padding: 0,+ }}>{expandedApproval === approval.id ? <ChevronUp size={12} /> : <ChevronDown size={12} />}{expandedApproval === approval.id ? 'Hide' : 'Show'} reasoning</button>{expandedApproval === approval.id && (- <div- className="text-xs p-2 rounded mb-2"- style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.GRAY }}- >+ <div style={{+ fontSize: '10px',+ padding: '8px',+ marginBottom: '8px',+ backgroundColor: FINCEPT.CARD_BG,+ color: FINCEPT.GRAY,+ fontFamily: TERMINAL_FONT,+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>{approval.decision.reasoning || 'No reasoning provided'}</div>)}{/* Actions */}- <div className="flex gap-2">+ <div style={{ display: 'flex', gap: '8px' }}><buttononClick={() => handleApprove(approval.id)}disabled={isProcessing === approval.id}- className="flex-1 py-1.5 rounded text-xs font-medium flex items-center justify-center gap-1"+ onMouseEnter={() => setHoveredBtn(`approve-${approval.id}`)}+ onMouseLeave={() => setHoveredBtn(null)}style={{- backgroundColor: COLORS.GREEN,- color: COLORS.DARK_BG,+ flex: 1,+ padding: '6px',+ fontSize: '11px',+ fontWeight: 600,+ fontFamily: TERMINAL_FONT,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '4px',+ backgroundColor: FINCEPT.GREEN,+ color: FINCEPT.DARK_BG,+ border: 'none',+ cursor: isProcessing === approval.id ? 'not-allowed' : 'pointer',opacity: isProcessing === approval.id ? 0.5 : 1,+ letterSpacing: '0.5px',}}>{isProcessing === approval.id ? (- <Loader2 size={12} className="animate-spin" />+ <Loader2 size={12} style={{ animation: 'hitl-spin 1s linear infinite' }} />) : (<Check size={12} />)}- Approve+ APPROVE</button><buttononClick={() => handleReject(approval.id)}disabled={isProcessing === approval.id}- className="flex-1 py-1.5 rounded text-xs font-medium flex items-center justify-center gap-1"+ onMouseEnter={() => setHoveredBtn(`reject-${approval.id}`)}+ onMouseLeave={() => setHoveredBtn(null)}style={{- backgroundColor: COLORS.RED,- color: COLORS.WHITE,+ flex: 1,+ padding: '6px',+ fontSize: '11px',+ fontWeight: 600,+ fontFamily: TERMINAL_FONT,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '4px',+ backgroundColor: FINCEPT.RED,+ color: FINCEPT.WHITE,+ border: 'none',+ cursor: isProcessing === approval.id ? 'not-allowed' : 'pointer',opacity: isProcessing === approval.id ? 0.5 : 1,+ letterSpacing: '0.5px',}}>{isProcessing === approval.id ? (- <Loader2 size={12} className="animate-spin" />+ <Loader2 size={12} style={{ animation: 'hitl-spin 1s linear infinite' }} />) : (<X size={12} />)}- Reject+ REJECT</button></div></div>@@ -398,11 +530,19 @@ const HITLApprovalPanel: React.FC<HITLApprovalPanelProps> = ({{/* Footer Stats */}{hitlStatus && (- <div className="px-4 py-2 border-t flex items-center justify-between text-xs" style={{ borderColor: COLORS.BORDER }}>- <span style={{ color: COLORS.GRAY }}>+ <div style={{+ padding: '6px 16px',+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ fontSize: '9px',+ backgroundColor: FINCEPT.HEADER_BG,+ }}>+ <span style={{ color: FINCEPT.GRAY }}>Rules: {hitlStatus.rules.filter(r => r.enabled).length}/{hitlStatus.rules.length} active</span>- <span style={{ color: COLORS.GRAY }}>+ <span style={{ color: FINCEPT.GRAY }}>History: {hitlStatus.history_count} decisions</span></div>diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PerformanceChart.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PerformanceChart.tsxindex 2c4f84ad0..aed15e919 100644--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PerformanceChart.tsx+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PerformanceChart.tsx@@ -20,6 +20,18 @@ import { withErrorBoundary } from '@/components/common/ErrorBoundary';import type { PerformanceSnapshot, ChartData } from '../types';import { formatCurrency, MODEL_COLORS } from '../types';+const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+};++const TERMINAL_FONT = '"IBM Plex Mono", "Consolas", monospace';+interface PerformanceChartProps {snapshots: PerformanceSnapshot[];height?: number;@@ -70,15 +82,26 @@ const PerformanceChart: React.FC<PerformanceChartProps> = ({if (chartData.length === 0) {return (- <div className="bg-[#0F0F0F] rounded-lg p-4 border border-[#2A2A2A]">- <div className="flex items-center gap-2 mb-4">- <TrendingUp className="w-5 h-5 text-[#FF8800]" />- <h3 className="text-white font-semibold">Performance Chart</h3>+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ padding: '16px',+ fontFamily: TERMINAL_FONT,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>+ <TrendingUp size={16} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ color: FINCEPT.WHITE, fontWeight: 600, fontSize: '13px' }}>+ PERFORMANCE CHART+ </span></div>- <div- className="flex items-center justify-center text-[#787878]"- style={{ height }}- >+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: FINCEPT.GRAY,+ fontSize: '12px',+ height,+ }}>Run cycles to see performance data</div></div>@@ -86,10 +109,17 @@ const PerformanceChart: React.FC<PerformanceChartProps> = ({}return (- <div className="bg-[#0F0F0F] rounded-lg p-4 border border-[#2A2A2A]">- <div className="flex items-center gap-2 mb-4">- <TrendingUp className="w-5 h-5 text-[#FF8800]" />- <h3 className="text-white font-semibold">Performance Chart</h3>+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ padding: '16px',+ fontFamily: TERMINAL_FONT,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>+ <TrendingUp size={16} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ color: FINCEPT.WHITE, fontWeight: 600, fontSize: '13px' }}>+ PERFORMANCE CHART+ </span></div><ResponsiveContainer width="100%" height={height}>@@ -97,26 +127,30 @@ const PerformanceChart: React.FC<PerformanceChartProps> = ({data={chartData}margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>- <CartesianGrid strokeDasharray="3 3" stroke="#2A2A2A" />+ <CartesianGrid strokeDasharray="3 3" stroke={FINCEPT.BORDER} /><XAxisdataKey="cycle"- stroke="#787878"- fontSize={12}+ stroke={FINCEPT.GRAY}+ fontSize={10}+ fontFamily={TERMINAL_FONT}tickFormatter={(value) => `#${value}`}/><YAxis- stroke="#787878"- fontSize={12}+ stroke={FINCEPT.GRAY}+ fontSize={10}+ fontFamily={TERMINAL_FONT}tickFormatter={(value) => `$${(value / 1000).toFixed(1)}k`}domain={['dataMin - 500', 'dataMax + 500']}/><TooltipcontentStyle={{- backgroundColor: '#1A1A1A',- border: '1px solid #2A2A2A',- borderRadius: '8px',+ backgroundColor: FINCEPT.HEADER_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: 0,+ fontFamily: TERMINAL_FONT,+ fontSize: '11px',}}- labelStyle={{ color: '#FFFFFF' }}+ labelStyle={{ color: FINCEPT.WHITE, fontFamily: TERMINAL_FONT }}formatter={(value: number, name: string) => [formatCurrency(value),name,@@ -125,9 +159,9 @@ const PerformanceChart: React.FC<PerformanceChartProps> = ({/>{showLegend && (<Legend- wrapperStyle={{ paddingTop: '10px' }}+ wrapperStyle={{ paddingTop: '10px', fontFamily: TERMINAL_FONT, fontSize: '10px' }}formatter={(value) => (- <span style={{ color: '#FFFFFF' }}>{value}</span>+ <span style={{ color: FINCEPT.WHITE, fontFamily: TERMINAL_FONT }}>{value}</span>)}/>)}diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PortfolioMetricsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PortfolioMetricsPanel.tsxindex ee3720949..2985b977e 100644--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PortfolioMetricsPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PortfolioMetricsPanel.tsx@@ -19,7 +19,7 @@ import {type PortfolioMetrics,} from '../services/alphaArenaEnhancedService';-const COLORS = {+const FINCEPT = {ORANGE: '#FF8800',WHITE: '#FFFFFF',RED: '#FF3B3B',@@ -30,10 +30,21 @@ const COLORS = {GRAY: '#787878',DARK_BG: '#000000',PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',CARD_BG: '#0A0A0A',BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',};+const TERMINAL_FONT = '"IBM Plex Mono", "Consolas", monospace';++const METRICS_STYLES = `+ .metrics-panel *::-webkit-scrollbar { width: 6px; height: 6px; }+ .metrics-panel *::-webkit-scrollbar-track { background: #000000; }+ .metrics-panel *::-webkit-scrollbar-thumb { background: #2A2A2A; }+ @keyframes metrics-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }+`;+interface PortfolioMetricsPanelProps {competitionId: string;modelName?: string;@@ -53,7 +64,7 @@ const MetricCard: React.FC<MetricCardProps> = ({label,value,icon,- color = COLORS.WHITE,+ color = FINCEPT.WHITE,tooltip,isPercentage = false,}) => {@@ -67,23 +78,39 @@ const MetricCard: React.FC<MetricCardProps> = ({return (<div- className="p-3 rounded-lg relative"- style={{ backgroundColor: COLORS.CARD_BG }}+ style={{+ padding: '10px',+ position: 'relative',+ backgroundColor: FINCEPT.CARD_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ fontFamily: TERMINAL_FONT,+ }}onMouseEnter={() => setShowTooltip(true)}onMouseLeave={() => setShowTooltip(false)}>- <div className="flex items-center justify-between mb-1">- <span className="text-xs" style={{ color: COLORS.GRAY }}>{label}</span>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '4px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>{label.toUpperCase()}</span><div style={{ color }}>{icon}</div></div>- <div className="text-lg font-bold" style={{ color }}>+ <div style={{ fontSize: '16px', fontWeight: 700, color }}>{displayValue}</div>{tooltip && showTooltip && (- <div- className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2 py-1 rounded text-xs whitespace-nowrap z-10"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}- >+ <div style={{+ position: 'absolute',+ bottom: '100%',+ left: '50%',+ transform: 'translateX(-50%)',+ marginBottom: '8px',+ padding: '4px 8px',+ fontSize: '9px',+ whiteSpace: 'nowrap',+ zIndex: 10,+ backgroundColor: FINCEPT.HEADER_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ fontFamily: TERMINAL_FONT,+ }}>{tooltip}</div>)}@@ -98,6 +125,8 @@ const PortfolioMetricsPanel: React.FC<PortfolioMetricsPanelProps> = ({}) => {const [selectedModel, setSelectedModel] = useState<string | null>(modelName || null);const [expandedSection, setExpandedSection] = useState<string | null>('returns');+ const [hoveredBtn, setHoveredBtn] = useState<string | null>(null);+ const [hoveredModel, setHoveredModel] = useState<string | null>(null);// Cache: all models overview (enabled when no model selected)const allModelsCache = useCache<Record<string, PortfolioMetrics>>({@@ -162,31 +191,41 @@ const PortfolioMetricsPanel: React.FC<PortfolioMetricsPanelProps> = ({};const getReturnColor = (value: number) => {- if (value > 0) return COLORS.GREEN;- if (value < 0) return COLORS.RED;- return COLORS.GRAY;+ if (value > 0) return FINCEPT.GREEN;+ if (value < 0) return FINCEPT.RED;+ return FINCEPT.GRAY;};const renderMetricsSection = (metricsData: PortfolioMetrics) => (<>{/* Returns Section */}- <div className="border-b" style={{ borderColor: COLORS.BORDER }}>+ <div style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}><buttononClick={() => toggleSection('returns')}- className="w-full px-4 py-2 flex items-center justify-between"+ style={{+ width: '100%',+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ fontFamily: TERMINAL_FONT,+ }}>- <div className="flex items-center gap-2">- <TrendingUp size={14} style={{ color: COLORS.GREEN }} />- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>Returns</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <TrendingUp size={14} style={{ color: FINCEPT.GREEN }} />+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>RETURNS</span></div>{expandedSection === 'returns' ? (- <ChevronUp size={14} style={{ color: COLORS.GRAY }} />+ <ChevronUp size={14} style={{ color: FINCEPT.GRAY }} />) : (- <ChevronDown size={14} style={{ color: COLORS.GRAY }} />+ <ChevronDown size={14} style={{ color: FINCEPT.GRAY }} />)}</button>{expandedSection === 'returns' && (- <div className="px-4 pb-3 grid grid-cols-2 gap-2">+ <div style={{ padding: '0 16px 12px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}><MetricCardlabel="Total Return"value={metricsData.total_return}@@ -199,7 +238,7 @@ const PortfolioMetricsPanel: React.FC<PortfolioMetricsPanelProps> = ({label="Win Rate"value={metricsData.win_rate}icon={<Target size={14} />}- color={metricsData.win_rate > 0.5 ? COLORS.GREEN : COLORS.RED}+ color={metricsData.win_rate > 0.5 ? FINCEPT.GREEN : FINCEPT.RED}isPercentagetooltip="Percentage of winning trades"/>@@ -207,14 +246,14 @@ const PortfolioMetricsPanel: React.FC<PortfolioMetricsPanelProps> = ({label="Profit Factor"value={metricsData.profit_factor}icon={<Award size={14} />}- color={metricsData.profit_factor > 1 ? COLORS.GREEN : COLORS.RED}+ color={metricsData.profit_factor > 1 ? FINCEPT.GREEN : FINCEPT.RED}tooltip="Gross profit / Gross loss"/><MetricCardlabel="Expectancy"value={`$${metricsData.expectancy.toFixed(2)}`}icon={<BarChart3 size={14} />}- color={metricsData.expectancy > 0 ? COLORS.GREEN : COLORS.RED}+ color={metricsData.expectancy > 0 ? FINCEPT.GREEN : FINCEPT.RED}tooltip="Expected profit per trade"/></div>@@ -222,42 +261,52 @@ const PortfolioMetricsPanel: React.FC<PortfolioMetricsPanelProps> = ({</div>{/* Risk Metrics Section */}- <div className="border-b" style={{ borderColor: COLORS.BORDER }}>+ <div style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}><buttononClick={() => toggleSection('risk')}- className="w-full px-4 py-2 flex items-center justify-between"+ style={{+ width: '100%',+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ fontFamily: TERMINAL_FONT,+ }}>- <div className="flex items-center gap-2">- <AlertTriangle size={14} style={{ color: COLORS.YELLOW }} />- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>Risk Metrics</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <AlertTriangle size={14} style={{ color: FINCEPT.YELLOW }} />+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>RISK METRICS</span></div>{expandedSection === 'risk' ? (- <ChevronUp size={14} style={{ color: COLORS.GRAY }} />+ <ChevronUp size={14} style={{ color: FINCEPT.GRAY }} />) : (- <ChevronDown size={14} style={{ color: COLORS.GRAY }} />+ <ChevronDown size={14} style={{ color: FINCEPT.GRAY }} />)}</button>{expandedSection === 'risk' && (- <div className="px-4 pb-3 grid grid-cols-2 gap-2">+ <div style={{ padding: '0 16px 12px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}><MetricCardlabel="Sharpe Ratio"value={metricsData.sharpe_ratio}icon={<BarChart3 size={14} />}- color={metricsData.sharpe_ratio > 1 ? COLORS.GREEN : metricsData.sharpe_ratio > 0 ? COLORS.YELLOW : COLORS.RED}+ color={metricsData.sharpe_ratio > 1 ? FINCEPT.GREEN : metricsData.sharpe_ratio > 0 ? FINCEPT.YELLOW : FINCEPT.RED}tooltip="Risk-adjusted return (> 1 is good)"/><MetricCardlabel="Sortino Ratio"value={metricsData.sortino_ratio}icon={<BarChart3 size={14} />}- color={metricsData.sortino_ratio > 1 ? COLORS.GREEN : metricsData.sortino_ratio > 0 ? COLORS.YELLOW : COLORS.RED}+ color={metricsData.sortino_ratio > 1 ? FINCEPT.GREEN : metricsData.sortino_ratio > 0 ? FINCEPT.YELLOW : FINCEPT.RED}tooltip="Downside risk-adjusted return"/><MetricCardlabel="Max Drawdown"value={metricsData.max_drawdown_pct}icon={<TrendingDown size={14} />}- color={COLORS.RED}+ color={FINCEPT.RED}isPercentagetooltip="Largest peak-to-trough decline"/>@@ -265,7 +314,7 @@ const PortfolioMetricsPanel: React.FC<PortfolioMetricsPanelProps> = ({label="Volatility"value={metricsData.volatility}icon={<AlertTriangle size={14} />}- color={metricsData.volatility > 0.3 ? COLORS.RED : COLORS.YELLOW}+ color={metricsData.volatility > 0.3 ? FINCEPT.RED : FINCEPT.YELLOW}isPercentagetooltip="Standard deviation of returns"/>@@ -277,53 +326,63 @@ const PortfolioMetricsPanel: React.FC<PortfolioMetricsPanelProps> = ({<div><buttononClick={() => toggleSection('trades')}- className="w-full px-4 py-2 flex items-center justify-between"+ style={{+ width: '100%',+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ fontFamily: TERMINAL_FONT,+ }}>- <div className="flex items-center gap-2">- <BarChart3 size={14} style={{ color: COLORS.BLUE }} />- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>Trade Statistics</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <BarChart3 size={14} style={{ color: FINCEPT.BLUE }} />+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>TRADE STATISTICS</span></div>{expandedSection === 'trades' ? (- <ChevronUp size={14} style={{ color: COLORS.GRAY }} />+ <ChevronUp size={14} style={{ color: FINCEPT.GRAY }} />) : (- <ChevronDown size={14} style={{ color: COLORS.GRAY }} />+ <ChevronDown size={14} style={{ color: FINCEPT.GRAY }} />)}</button>{expandedSection === 'trades' && (- <div className="px-4 pb-3">- <div className="grid grid-cols-3 gap-2 mb-3">- <div className="text-center p-2 rounded" style={{ backgroundColor: COLORS.CARD_BG }}>- <div className="text-lg font-bold" style={{ color: COLORS.WHITE }}>+ <div style={{ padding: '0 16px 12px' }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', marginBottom: '12px' }}>+ <div style={{ textAlign: 'center', padding: '8px', backgroundColor: FINCEPT.CARD_BG, border: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.WHITE }}>{metricsData.total_trades}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>Total</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Total</div></div>- <div className="text-center p-2 rounded" style={{ backgroundColor: COLORS.GREEN + '10' }}>- <div className="text-lg font-bold" style={{ color: COLORS.GREEN }}>+ <div style={{ textAlign: 'center', padding: '8px', backgroundColor: FINCEPT.GREEN + '10', border: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.GREEN }}>{metricsData.winning_trades}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>Wins</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Wins</div></div>- <div className="text-center p-2 rounded" style={{ backgroundColor: COLORS.RED + '10' }}>- <div className="text-lg font-bold" style={{ color: COLORS.RED }}>+ <div style={{ textAlign: 'center', padding: '8px', backgroundColor: FINCEPT.RED + '10', border: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.RED }}>{metricsData.losing_trades}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>Losses</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Losses</div></div></div>- <div className="grid grid-cols-2 gap-2">+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}><MetricCardlabel="Avg Win"value={`$${metricsData.avg_win.toFixed(2)}`}icon={<TrendingUp size={14} />}- color={COLORS.GREEN}+ color={FINCEPT.GREEN}tooltip="Average winning trade"/><MetricCardlabel="Avg Loss"value={`$${Math.abs(metricsData.avg_loss).toFixed(2)}`}icon={<TrendingDown size={14} />}- color={COLORS.RED}+ color={FINCEPT.RED}tooltip="Average losing trade"/></div>@@ -334,42 +393,67 @@ const PortfolioMetricsPanel: React.FC<PortfolioMetricsPanelProps> = ({);return (- <div- className="rounded-lg overflow-hidden"- style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}- >+ <div className="metrics-panel" style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ overflow: 'hidden',+ fontFamily: TERMINAL_FONT,+ }}>+ <style>{METRICS_STYLES}</style>+{/* Header */}- <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-2">- <BarChart3 size={16} style={{ color: COLORS.PURPLE }} />- <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>- Portfolio Metrics+ <div style={{+ padding: '10px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <BarChart3 size={16} style={{ color: FINCEPT.PURPLE }} />+ <span style={{ fontWeight: 600, fontSize: '12px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>+ PORTFOLIO METRICS</span></div><buttononClick={handleRefresh}disabled={isLoading}- className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"+ onMouseEnter={() => setHoveredBtn('refresh')}+ onMouseLeave={() => setHoveredBtn(null)}+ style={{+ padding: '4px',+ backgroundColor: hoveredBtn === 'refresh' ? FINCEPT.HOVER : 'transparent',+ border: 'none',+ cursor: isLoading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}><RefreshCwsize={14}- className={isLoading ? 'animate-spin' : ''}- style={{ color: COLORS.GRAY }}+ style={{+ color: FINCEPT.GRAY,+ animation: isLoading ? 'metrics-spin 1s linear infinite' : 'none',+ }}/></button></div>{/* Model Selector */}{allMetrics && Object.keys(allMetrics).length > 0 && (- <div className="px-4 py-2 border-b" style={{ borderColor: COLORS.BORDER }}>+ <div style={{ padding: '8px 16px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}><selectvalue={selectedModel || ''}onChange={(e) => handleModelChange(e.target.value || null)}- className="w-full px-2 py-1.5 rounded text-xs"style={{- backgroundColor: COLORS.CARD_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,+ width: '100%',+ padding: '6px 8px',+ fontSize: '11px',+ fontFamily: TERMINAL_FONT,+ backgroundColor: FINCEPT.CARD_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ outline: 'none',}}><option value="">All Models</option>@@ -381,45 +465,63 @@ const PortfolioMetricsPanel: React.FC<PortfolioMetricsPanelProps> = ({)}{/* Content */}- <div className="max-h-96 overflow-y-auto">+ <div style={{ maxHeight: '384px', overflowY: 'auto' }}>{error && (- <div className="px-4 py-3 flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '10' }}>- <AlertTriangle size={14} style={{ color: COLORS.RED }} />- <span className="text-xs" style={{ color: COLORS.RED }}>{error.message}</span>+ <div style={{+ padding: '12px 16px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ backgroundColor: FINCEPT.RED + '10',+ }}>+ <AlertTriangle size={14} style={{ color: FINCEPT.RED }} />+ <span style={{ fontSize: '11px', color: FINCEPT.RED, fontFamily: TERMINAL_FONT }}>{error.message}</span></div>)}{isLoading ? (- <div className="flex items-center justify-center py-8">- <Loader2 size={24} className="animate-spin" style={{ color: COLORS.ORANGE }} />+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '32px 0' }}>+ <Loader2 size={24} style={{ color: FINCEPT.ORANGE, animation: 'metrics-spin 1s linear infinite' }} /></div>) : metrics ? (renderMetricsSection(metrics)) : allMetrics && Object.keys(allMetrics).length > 0 ? (- <div className="p-4">- <div className="text-xs mb-3" style={{ color: COLORS.GRAY }}>- <Info size={12} className="inline mr-1" />+ <div style={{ padding: '16px' }}>+ <div style={{ fontSize: '10px', marginBottom: '12px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <Info size={12} />Showing overview for {Object.keys(allMetrics).length} models</div>- <div className="space-y-2">+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>{Object.entries(allMetrics).map(([model, modelMetrics]) => (<buttonkey={model}onClick={() => handleModelChange(model)}- className="w-full p-3 rounded flex items-center justify-between transition-colors hover:bg-[#1A1A1A]"- style={{ backgroundColor: COLORS.CARD_BG }}+ onMouseEnter={() => setHoveredModel(model)}+ onMouseLeave={() => setHoveredModel(null)}+ style={{+ width: '100%',+ padding: '10px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ backgroundColor: hoveredModel === model ? FINCEPT.HOVER : FINCEPT.CARD_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ cursor: 'pointer',+ fontFamily: TERMINAL_FONT,+ textAlign: 'left',+ }}>- <div className="flex items-center gap-2">- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{model}</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>{model}</span></div>- <div className="flex items-center gap-4 text-xs">+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '11px' }}><span style={{ color: getReturnColor(modelMetrics.total_return) }}>{(modelMetrics.total_return * 100).toFixed(1)}%</span>- <span style={{ color: COLORS.GRAY }}>+ <span style={{ color: FINCEPT.GRAY }}>{modelMetrics.total_trades} trades</span>- <span style={{ color: modelMetrics.sharpe_ratio > 1 ? COLORS.GREEN : COLORS.GRAY }}>+ <span style={{ color: modelMetrics.sharpe_ratio > 1 ? FINCEPT.GREEN : FINCEPT.GRAY }}>SR: {modelMetrics.sharpe_ratio.toFixed(2)}</span></div>@@ -428,10 +530,10 @@ const PortfolioMetricsPanel: React.FC<PortfolioMetricsPanelProps> = ({</div></div>) : (- <div className="p-8 text-center">- <BarChart3 size={32} className="mx-auto mb-2 opacity-30" style={{ color: COLORS.GRAY }} />- <p className="text-sm" style={{ color: COLORS.GRAY }}>No metrics available</p>- <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>+ <div style={{ padding: '32px 16px', textAlign: 'center' }}>+ <BarChart3 size={32} style={{ color: FINCEPT.GRAY, opacity: 0.3, margin: '0 auto 8px' }} />+ <p style={{ fontSize: '12px', color: FINCEPT.GRAY }}>No metrics available</p>+ <p style={{ fontSize: '10px', marginTop: '4px', color: FINCEPT.GRAY }}>Start a competition to see portfolio metrics</p></div>diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ResearchPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ResearchPanel.tsxindex 62ff49a91..f392b3b83 100644--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ResearchPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ResearchPanel.tsx@@ -8,7 +8,7 @@import React, { useState } from 'react';import {FileText, Search, RefreshCw, AlertTriangle, ExternalLink,- Building2, DollarSign, TrendingUp, Loader2, ChevronDown,+ Building2, Loader2, ChevronDown,ChevronUp, Calendar, FileSearch, Shield, BarChart3,} from 'lucide-react';import { withErrorBoundary } from '@/components/common/ErrorBoundary';@@ -19,7 +19,7 @@ import {type ResearchReport,} from '../services/alphaArenaEnhancedService';-const COLORS = {+const FINCEPT = {ORANGE: '#FF8800',WHITE: '#FFFFFF',RED: '#FF3B3B',@@ -30,21 +30,32 @@ const COLORS = {GRAY: '#787878',DARK_BG: '#000000',PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',CARD_BG: '#0A0A0A',BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',};+const TERMINAL_FONT = '"IBM Plex Mono", "Consolas", monospace';++const RESEARCH_STYLES = `+ .research-panel *::-webkit-scrollbar { width: 6px; height: 6px; }+ .research-panel *::-webkit-scrollbar-track { background: #000000; }+ .research-panel *::-webkit-scrollbar-thumb { background: #2A2A2A; }+ @keyframes research-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }+`;+interface ResearchPanelProps {initialTicker?: string;onResearchLoaded?: (ticker: string) => void;}const FORM_TYPE_COLORS: Record<string, string> = {- '10-K': COLORS.BLUE,- '10-Q': COLORS.PURPLE,- '8-K': COLORS.ORANGE,- '4': COLORS.GREEN,- 'DEF 14A': COLORS.YELLOW,+ '10-K': FINCEPT.BLUE,+ '10-Q': FINCEPT.PURPLE,+ '8-K': FINCEPT.ORANGE,+ '4': FINCEPT.GREEN,+ 'DEF 14A': FINCEPT.YELLOW,};const ResearchPanel: React.FC<ResearchPanelProps> = ({@@ -55,6 +66,8 @@ const ResearchPanel: React.FC<ResearchPanelProps> = ({const [confirmedTicker, setConfirmedTicker] = useState(initialTicker || '');const [expandedSection, setExpandedSection] = useState<string | null>('filings');const [selectedFormTypes, setSelectedFormTypes] = useState<string[]>([]);+ const [hoveredBtn, setHoveredBtn] = useState<string | null>(null);+ const [hoveredFiling, setHoveredFiling] = useState<number | null>(null);// Cache: research report keyed on confirmedTickerconst researchCache = useCache<ResearchReport>({@@ -111,112 +124,161 @@ const ResearchPanel: React.FC<ResearchPanelProps> = ({};return (- <div- className="rounded-lg overflow-hidden"- style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}- >+ <div className="research-panel" style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ overflow: 'hidden',+ fontFamily: TERMINAL_FONT,+ }}>+ <style>{RESEARCH_STYLES}</style>+{/* Header */}- <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-2">- <FileSearch size={16} style={{ color: COLORS.YELLOW }} />- <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>- Research & SEC Filings+ <div style={{+ padding: '10px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <FileSearch size={16} style={{ color: FINCEPT.YELLOW }} />+ <span style={{ fontWeight: 600, fontSize: '12px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>+ RESEARCH & SEC FILINGS</span></div>{report && (<buttononClick={() => researchCache.refresh()}disabled={isLoading}- className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"+ onMouseEnter={() => setHoveredBtn('refresh')}+ onMouseLeave={() => setHoveredBtn(null)}+ style={{+ padding: '4px',+ backgroundColor: hoveredBtn === 'refresh' ? FINCEPT.HOVER : 'transparent',+ border: 'none',+ cursor: isLoading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}><RefreshCwsize={14}- className={isLoading ? 'animate-spin' : ''}- style={{ color: COLORS.GRAY }}+ style={{+ color: FINCEPT.GRAY,+ animation: isLoading ? 'research-spin 1s linear infinite' : 'none',+ }}/></button>)}</div>{/* Search Bar */}- <form onSubmit={handleSearch} className="px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER }}>- <div className="flex gap-2">+ <form onSubmit={handleSearch} style={{+ padding: '12px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{ display: 'flex', gap: '8px' }}><inputtype="text"value={searchTicker}onChange={(e) => setSearchTicker(e.target.value.toUpperCase())}placeholder="Enter ticker (e.g., AAPL)"- className="flex-1 px-3 py-1.5 rounded text-sm"style={{- backgroundColor: COLORS.CARD_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,+ flex: 1,+ padding: '6px 12px',+ fontSize: '12px',+ fontFamily: TERMINAL_FONT,+ backgroundColor: FINCEPT.CARD_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ outline: 'none',}}/><buttontype="submit"disabled={isLoading}- className="px-4 py-1.5 rounded text-sm font-medium flex items-center gap-1"style={{- backgroundColor: COLORS.ORANGE,- color: COLORS.DARK_BG,+ padding: '6px 16px',+ fontSize: '11px',+ fontWeight: 600,+ fontFamily: TERMINAL_FONT,+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ cursor: isLoading ? 'not-allowed' : 'pointer',opacity: isLoading ? 0.5 : 1,+ letterSpacing: '0.5px',}}>{isLoading ? (- <Loader2 size={14} className="animate-spin" />+ <Loader2 size={14} style={{ animation: 'research-spin 1s linear infinite' }} />) : (<Search size={14} />)}- Search+ SEARCH</button></div></form>{/* Error */}{error && (- <div className="px-4 py-2 flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '10' }}>- <AlertTriangle size={14} style={{ color: COLORS.RED }} />- <span className="text-xs" style={{ color: COLORS.RED }}>{error.message}</span>+ <div style={{+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ backgroundColor: FINCEPT.RED + '10',+ }}>+ <AlertTriangle size={14} style={{ color: FINCEPT.RED }} />+ <span style={{ fontSize: '11px', color: FINCEPT.RED, fontFamily: TERMINAL_FONT }}>{error.message}</span></div>)}{/* Content */}- <div className="max-h-96 overflow-y-auto">+ <div style={{ maxHeight: '384px', overflowY: 'auto' }}>{isLoading ? (- <div className="flex items-center justify-center py-8">- <Loader2 size={24} className="animate-spin" style={{ color: COLORS.ORANGE }} />+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '32px 0' }}>+ <Loader2 size={24} style={{ color: FINCEPT.ORANGE, animation: 'research-spin 1s linear infinite' }} /></div>) : report ? (<>{/* Company Info */}{report.company_info && (- <div className="px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-2 mb-2">- <Building2 size={14} style={{ color: COLORS.BLUE }} />- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>+ <div style={{ padding: '12px 16px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>+ <Building2 size={14} style={{ color: FINCEPT.BLUE }} />+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>{report.company_info.name}</span>- <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}>+ <span style={{+ fontSize: '10px',+ padding: '1px 8px',+ backgroundColor: FINCEPT.BORDER,+ color: FINCEPT.GRAY,+ fontFamily: TERMINAL_FONT,+ }}>{report.company_info.ticker}</span></div>- <div className="grid grid-cols-2 gap-2 text-xs">+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', fontSize: '11px' }}><div>- <span style={{ color: COLORS.GRAY }}>Industry: </span>- <span style={{ color: COLORS.WHITE }}>{report.company_info.industry || 'N/A'}</span>+ <span style={{ color: FINCEPT.GRAY }}>Industry: </span>+ <span style={{ color: FINCEPT.WHITE }}>{report.company_info.industry || 'N/A'}</span></div><div>- <span style={{ color: COLORS.GRAY }}>CIK: </span>- <span style={{ color: COLORS.WHITE }}>{report.company_info.cik}</span>+ <span style={{ color: FINCEPT.GRAY }}>CIK: </span>+ <span style={{ color: FINCEPT.WHITE }}>{report.company_info.cik}</span></div><div>- <span style={{ color: COLORS.GRAY }}>State: </span>- <span style={{ color: COLORS.WHITE }}>{report.company_info.state || 'N/A'}</span>+ <span style={{ color: FINCEPT.GRAY }}>State: </span>+ <span style={{ color: FINCEPT.WHITE }}>{report.company_info.state || 'N/A'}</span></div><div>- <span style={{ color: COLORS.GRAY }}>Fiscal Year End: </span>- <span style={{ color: COLORS.WHITE }}>{report.company_info.fiscal_year_end || 'N/A'}</span>+ <span style={{ color: FINCEPT.GRAY }}>Fiscal Year End: </span>+ <span style={{ color: FINCEPT.WHITE }}>{report.company_info.fiscal_year_end || 'N/A'}</span></div></div></div>@@ -224,35 +286,45 @@ const ResearchPanel: React.FC<ResearchPanelProps> = ({{/* Summary */}{report.summary && (- <div className="px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER }}>- <p className="text-xs leading-relaxed" style={{ color: COLORS.GRAY }}>+ <div style={{ padding: '12px 16px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <p style={{ fontSize: '11px', lineHeight: '1.5', color: FINCEPT.GRAY }}>{report.summary}</p></div>)}{/* SEC Filings Section */}- <div className="border-b" style={{ borderColor: COLORS.BORDER }}>+ <div style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}><buttononClick={() => toggleSection('filings')}- className="w-full px-4 py-2 flex items-center justify-between"+ style={{+ width: '100%',+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ fontFamily: TERMINAL_FONT,+ }}>- <div className="flex items-center gap-2">- <FileText size={14} style={{ color: COLORS.ORANGE }} />- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>- SEC Filings ({report.recent_filings.length})+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <FileText size={14} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>+ SEC FILINGS ({report.recent_filings.length})</span></div>{expandedSection === 'filings' ? (- <ChevronUp size={14} style={{ color: COLORS.GRAY }} />+ <ChevronUp size={14} style={{ color: FINCEPT.GRAY }} />) : (- <ChevronDown size={14} style={{ color: COLORS.GRAY }} />+ <ChevronDown size={14} style={{ color: FINCEPT.GRAY }} />)}</button>{expandedSection === 'filings' && (- <div className="px-4 pb-3">+ <div style={{ padding: '0 16px 12px' }}>{/* Form Type Filters */}- <div className="flex flex-wrap gap-1 mb-2">+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginBottom: '8px' }}>{['10-K', '10-Q', '8-K', '4', 'DEF 14A'].map((formType) => (<buttonkey={formType}@@ -263,15 +335,18 @@ const ResearchPanel: React.FC<ResearchPanelProps> = ({: [...prev, formType]);}}- className="px-2 py-0.5 rounded text-xs"style={{+ padding: '2px 8px',+ fontSize: '10px',+ fontFamily: TERMINAL_FONT,backgroundColor: selectedFormTypes.includes(formType)- ? (FORM_TYPE_COLORS[formType] || COLORS.GRAY) + '30'- : COLORS.CARD_BG,+ ? (FORM_TYPE_COLORS[formType] || FINCEPT.GRAY) + '30'+ : FINCEPT.CARD_BG,color: selectedFormTypes.includes(formType)- ? FORM_TYPE_COLORS[formType] || COLORS.GRAY- : COLORS.GRAY,- border: `1px solid ${selectedFormTypes.includes(formType) ? FORM_TYPE_COLORS[formType] || COLORS.GRAY : COLORS.BORDER}`,+ ? FORM_TYPE_COLORS[formType] || FINCEPT.GRAY+ : FINCEPT.GRAY,+ border: `1px solid ${selectedFormTypes.includes(formType) ? FORM_TYPE_COLORS[formType] || FINCEPT.GRAY : FINCEPT.BORDER}`,+ cursor: 'pointer',}}>{formType}@@ -280,38 +355,54 @@ const ResearchPanel: React.FC<ResearchPanelProps> = ({{selectedFormTypes.length > 0 && (<buttononClick={() => setSelectedFormTypes([])}- className="px-2 py-0.5 rounded text-xs"- style={{ color: COLORS.RED }}+ style={{+ padding: '2px 8px',+ fontSize: '10px',+ color: FINCEPT.RED,+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ fontFamily: TERMINAL_FONT,+ }}>Clear</button>)}</div>{/* Filings List */}- <div className="space-y-2 max-h-48 overflow-y-auto">+ <div style={{ maxHeight: '192px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '6px' }}>{filterFilings(report.recent_filings).map((filing, idx) => (<divkey={idx}- className="p-2 rounded flex items-start justify-between"- style={{ backgroundColor: COLORS.CARD_BG }}+ onMouseEnter={() => setHoveredFiling(idx)}+ onMouseLeave={() => setHoveredFiling(null)}+ style={{+ padding: '8px',+ display: 'flex',+ alignItems: 'flex-start',+ justifyContent: 'space-between',+ backgroundColor: hoveredFiling === idx ? FINCEPT.HOVER : FINCEPT.CARD_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 mb-1">- <span- className="text-xs px-1.5 py-0.5 rounded font-medium"- style={{- backgroundColor: (FORM_TYPE_COLORS[filing.form_type] || COLORS.GRAY) + '20',- color: FORM_TYPE_COLORS[filing.form_type] || COLORS.GRAY,- }}- >+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>+ <span style={{+ fontSize: '10px',+ padding: '1px 6px',+ fontWeight: 500,+ fontFamily: TERMINAL_FONT,+ backgroundColor: (FORM_TYPE_COLORS[filing.form_type] || FINCEPT.GRAY) + '20',+ color: FORM_TYPE_COLORS[filing.form_type] || FINCEPT.GRAY,+ }}>{filing.form_type}</span>- <span className="text-xs" style={{ color: COLORS.GRAY }}>- <Calendar size={10} className="inline mr-1" />+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <Calendar size={10} />{formatDate(filing.filing_date)}</span></div>- <p className="text-xs truncate" style={{ color: COLORS.WHITE }}>+ <p style={{ fontSize: '11px', color: FINCEPT.WHITE, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{filing.description || `Filing ${filing.accession_number}`}</p></div>@@ -319,9 +410,18 @@ const ResearchPanel: React.FC<ResearchPanelProps> = ({href={`https://www.sec.gov/Archives/edgar/data/${report.company_info?.cik}/${filing.accession_number.replace(/-/g, '')}/${filing.primary_document}`}target="_blank"rel="noopener noreferrer"- className="p-1 rounded hover:bg-[#1A1A1A]"+ onClick={(e) => e.stopPropagation()}+ onMouseEnter={() => setHoveredBtn(`link-${idx}`)}+ onMouseLeave={() => setHoveredBtn(null)}+ style={{+ padding: '4px',+ backgroundColor: hoveredBtn === `link-${idx}` ? FINCEPT.HOVER : 'transparent',+ display: 'flex',+ alignItems: 'center',+ flexShrink: 0,+ }}>- <ExternalLink size={12} style={{ color: COLORS.GRAY }} />+ <ExternalLink size={12} style={{ color: FINCEPT.GRAY }} /></a></div>))}@@ -332,50 +432,59 @@ const ResearchPanel: React.FC<ResearchPanelProps> = ({{/* Financials Section */}{report.financials.length > 0 && (- <div className="border-b" style={{ borderColor: COLORS.BORDER }}>+ <div style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}><buttononClick={() => toggleSection('financials')}- className="w-full px-4 py-2 flex items-center justify-between"+ style={{+ width: '100%',+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ fontFamily: TERMINAL_FONT,+ }}>- <div className="flex items-center gap-2">- <BarChart3 size={14} style={{ color: COLORS.GREEN }} />- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>- Financials+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <BarChart3 size={14} style={{ color: FINCEPT.GREEN }} />+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>+ FINANCIALS</span></div>{expandedSection === 'financials' ? (- <ChevronUp size={14} style={{ color: COLORS.GRAY }} />+ <ChevronUp size={14} style={{ color: FINCEPT.GRAY }} />) : (- <ChevronDown size={14} style={{ color: COLORS.GRAY }} />+ <ChevronDown size={14} style={{ color: FINCEPT.GRAY }} />)}</button>{expandedSection === 'financials' && (- <div className="px-4 pb-3">- <table className="w-full text-xs">+ <div style={{ padding: '0 16px 12px' }}>+ <table style={{ width: '100%', fontSize: '11px', borderCollapse: 'collapse' }}><thead>- <tr style={{ color: COLORS.GRAY }}>- <th className="text-left py-1">Period</th>- <th className="text-right py-1">Revenue</th>- <th className="text-right py-1">Net Income</th>- <th className="text-right py-1">EPS</th>+ <tr style={{ color: FINCEPT.GRAY }}>+ <th style={{ textAlign: 'left', padding: '4px 0', fontWeight: 500, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Period</th>+ <th style={{ textAlign: 'right', padding: '4px 0', fontWeight: 500, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Revenue</th>+ <th style={{ textAlign: 'right', padding: '4px 0', fontWeight: 500, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Net Income</th>+ <th style={{ textAlign: 'right', padding: '4px 0', fontWeight: 500, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>EPS</th></tr></thead><tbody>{report.financials.slice(0, 5).map((fin, idx) => (- <tr key={idx} className="border-t" style={{ borderColor: COLORS.BORDER }}>- <td className="py-1.5" style={{ color: COLORS.WHITE }}>{fin.period}</td>- <td className="text-right py-1.5" style={{ color: COLORS.WHITE }}>+ <tr key={idx} style={{ borderTop: `1px solid ${FINCEPT.BORDER}` }}>+ <td style={{ padding: '6px 0', color: FINCEPT.WHITE }}>{fin.period}</td>+ <td style={{ textAlign: 'right', padding: '6px 0', color: FINCEPT.WHITE }}>{formatCurrency(fin.revenue)}</td>- <td- className="text-right py-1.5"- style={{- color: fin.net_income && fin.net_income > 0 ? COLORS.GREEN : COLORS.RED,- }}- >+ <td style={{+ textAlign: 'right',+ padding: '6px 0',+ color: fin.net_income && fin.net_income > 0 ? FINCEPT.GREEN : FINCEPT.RED,+ }}>{formatCurrency(fin.net_income)}</td>- <td className="text-right py-1.5" style={{ color: COLORS.WHITE }}>+ <td style={{ textAlign: 'right', padding: '6px 0', color: FINCEPT.WHITE }}>{fin.eps !== null ? `$${fin.eps.toFixed(2)}` : 'N/A'}</td></tr>@@ -392,47 +501,65 @@ const ResearchPanel: React.FC<ResearchPanelProps> = ({<div><buttononClick={() => toggleSection('risks')}- className="w-full px-4 py-2 flex items-center justify-between"+ style={{+ width: '100%',+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ fontFamily: TERMINAL_FONT,+ }}>- <div className="flex items-center gap-2">- <Shield size={14} style={{ color: COLORS.RED }} />- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>- Risk Factors ({report.risk_factors.length})+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Shield size={14} style={{ color: FINCEPT.RED }} />+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>+ RISK FACTORS ({report.risk_factors.length})</span></div>{expandedSection === 'risks' ? (- <ChevronUp size={14} style={{ color: COLORS.GRAY }} />+ <ChevronUp size={14} style={{ color: FINCEPT.GRAY }} />) : (- <ChevronDown size={14} style={{ color: COLORS.GRAY }} />+ <ChevronDown size={14} style={{ color: FINCEPT.GRAY }} />)}</button>{expandedSection === 'risks' && (- <div className="px-4 pb-3">- <ul className="space-y-1">+ <div style={{ padding: '0 16px 12px' }}>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>{report.risk_factors.map((risk, idx) => (- <li+ <divkey={idx}- className="text-xs pl-3 relative"- style={{ color: COLORS.GRAY }}+ style={{+ fontSize: '11px',+ paddingLeft: '12px',+ position: 'relative',+ color: FINCEPT.GRAY,+ }}>- <span- className="absolute left-0 top-1.5 w-1.5 h-1.5 rounded-full"- style={{ backgroundColor: COLORS.RED }}- />+ <span style={{+ position: 'absolute',+ left: 0,+ top: '6px',+ width: '4px',+ height: '4px',+ backgroundColor: FINCEPT.RED,+ }} />{risk}- </li>+ </div>))}- </ul>+ </div></div>)}</div>)}</>) : (- <div className="p-8 text-center">- <FileSearch size={32} className="mx-auto mb-2 opacity-30" style={{ color: COLORS.GRAY }} />- <p className="text-sm" style={{ color: COLORS.GRAY }}>Search for a company</p>- <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>+ <div style={{ padding: '32px 16px', textAlign: 'center' }}>+ <FileSearch size={32} style={{ color: FINCEPT.GRAY, opacity: 0.3, margin: '0 auto 8px' }} />+ <p style={{ fontSize: '12px', color: FINCEPT.GRAY }}>Search for a company</p>+ <p style={{ fontSize: '10px', marginTop: '4px', color: FINCEPT.GRAY }}>Enter a ticker to view SEC filings and research</p></div>@@ -441,8 +568,14 @@ const ResearchPanel: React.FC<ResearchPanelProps> = ({{/* Footer */}{report && (- <div className="px-4 py-2 border-t text-xs" style={{ borderColor: COLORS.BORDER, color: COLORS.GRAY }}>- Generated: {formatDate(report.generated_at)} • Data from SEC EDGAR+ <div style={{+ padding: '6px 16px',+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ fontSize: '9px',+ backgroundColor: FINCEPT.HEADER_BG,+ color: FINCEPT.GRAY,+ }}>+ Generated: {formatDate(report.generated_at)} | Data from SEC EDGAR</div>)}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/SentimentPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/SentimentPanel.tsxindex 5e8d1dde3..e74b5f460 100644--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/SentimentPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/SentimentPanel.tsx@@ -8,7 +8,7 @@import React, { useState } from 'react';import {Newspaper, TrendingUp, TrendingDown, Minus, RefreshCw,- Globe, AlertCircle, ChevronRight, ExternalLink, Loader2,+ Globe, AlertCircle, ChevronRight, Loader2,} from 'lucide-react';import { withErrorBoundary } from '@/components/common/ErrorBoundary';import { useCache, cacheKey } from '@/hooks/useCache';@@ -19,7 +19,7 @@ import {type MarketMood,} from '../services/alphaArenaEnhancedService';-const COLORS = {+const FINCEPT = {ORANGE: '#FF8800',WHITE: '#FFFFFF',RED: '#FF3B3B',@@ -30,26 +30,37 @@ const COLORS = {GRAY: '#787878',DARK_BG: '#000000',PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',CARD_BG: '#0A0A0A',BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',};+const TERMINAL_FONT = '"IBM Plex Mono", "Consolas", monospace';+const SENTIMENT_COLORS: Record<string, string> = {- very_bearish: COLORS.RED,+ very_bearish: FINCEPT.RED,bearish: '#FF6B6B',- neutral: COLORS.GRAY,+ neutral: FINCEPT.GRAY,bullish: '#4ADE80',- very_bullish: COLORS.GREEN,+ very_bullish: FINCEPT.GREEN,};const SENTIMENT_LABELS: Record<string, string> = {- very_bearish: 'Very Bearish',- bearish: 'Bearish',- neutral: 'Neutral',- bullish: 'Bullish',- very_bullish: 'Very Bullish',+ very_bearish: 'VERY BEARISH',+ bearish: 'BEARISH',+ neutral: 'NEUTRAL',+ bullish: 'BULLISH',+ very_bullish: 'VERY BULLISH',};+const SENTIMENT_STYLES = `+ .sentiment-panel *::-webkit-scrollbar { width: 6px; height: 6px; }+ .sentiment-panel *::-webkit-scrollbar-track { background: #000000; }+ .sentiment-panel *::-webkit-scrollbar-thumb { background: #2A2A2A; }+ @keyframes sentiment-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }+`;+interface SentimentPanelProps {symbol?: string;showMarketMood?: boolean;@@ -60,6 +71,7 @@ const SentimentPanel: React.FC<SentimentPanelProps> = ({showMarketMood = true,}) => {const [activeTab, setActiveTab] = useState<'symbol' | 'market'>('symbol');+ const [hoveredBtn, setHoveredBtn] = useState<string | null>(null);// Cache: symbol sentiment (enabled when activeTab === 'symbol')const sentimentCache = useCache<SentimentResult>({@@ -114,127 +126,194 @@ const SentimentPanel: React.FC<SentimentPanelProps> = ({} else if (sentimentLevel.includes('bearish')) {return <TrendingDown size={16} style={{ color: SENTIMENT_COLORS[sentimentLevel] }} />;}- return <Minus size={16} style={{ color: COLORS.GRAY }} />;+ return <Minus size={16} style={{ color: FINCEPT.GRAY }} />;};const renderSentimentMeter = (score: number) => {- // Score ranges from -1 (bearish) to 1 (bullish)const percentage = ((score + 1) / 2) * 100;return (- <div className="relative h-2 rounded-full overflow-hidden" style={{ backgroundColor: COLORS.BORDER }}>- {/* Background gradient */}- <div- className="absolute inset-0"- style={{- background: `linear-gradient(to right, ${COLORS.RED}, ${COLORS.GRAY}, ${COLORS.GREEN})`,- }}- />- {/* Indicator */}- <div- className="absolute w-3 h-3 rounded-full bg-white -top-0.5 transform -translate-x-1/2"- style={{- left: `${percentage}%`,- boxShadow: '0 0 4px rgba(0,0,0,0.5)',- }}- />+ <div style={{+ position: 'relative',+ height: '6px',+ overflow: 'hidden',+ backgroundColor: FINCEPT.BORDER,+ }}>+ <div style={{+ position: 'absolute',+ inset: 0,+ background: `linear-gradient(to right, ${FINCEPT.RED}, ${FINCEPT.GRAY}, ${FINCEPT.GREEN})`,+ }} />+ <div style={{+ position: 'absolute',+ width: '10px',+ height: '10px',+ backgroundColor: FINCEPT.WHITE,+ top: '-2px',+ left: `${percentage}%`,+ transform: 'translateX(-50%)',+ boxShadow: '0 0 4px rgba(0,0,0,0.5)',+ }} /></div>);};return (- <div- className="rounded-lg overflow-hidden"- style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}- >+ <div className="sentiment-panel" style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ overflow: 'hidden',+ fontFamily: TERMINAL_FONT,+ }}>+ <style>{SENTIMENT_STYLES}</style>+{/* Header */}- <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-2">- <Newspaper size={16} style={{ color: COLORS.BLUE }} />- <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>- Sentiment Analysis+ <div style={{+ padding: '10px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Newspaper size={16} style={{ color: FINCEPT.BLUE }} />+ <span style={{ fontWeight: 600, fontSize: '12px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>+ SENTIMENT ANALYSIS</span></div><buttononClick={handleRefresh}disabled={isLoading}- className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"+ onMouseEnter={() => setHoveredBtn('refresh')}+ onMouseLeave={() => setHoveredBtn(null)}+ style={{+ padding: '4px',+ backgroundColor: hoveredBtn === 'refresh' ? FINCEPT.HOVER : 'transparent',+ border: 'none',+ cursor: isLoading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}><RefreshCwsize={14}- className={isLoading ? 'animate-spin' : ''}- style={{ color: COLORS.GRAY }}+ style={{+ color: FINCEPT.GRAY,+ animation: isLoading ? 'sentiment-spin 1s linear infinite' : 'none',+ }}/></button></div>{/* Tabs */}{showMarketMood && (- <div className="flex border-b" style={{ borderColor: COLORS.BORDER }}>+ <div style={{ display: 'flex', borderBottom: `1px solid ${FINCEPT.BORDER}` }}><buttononClick={() => setActiveTab('symbol')}- className="flex-1 px-4 py-2 text-xs font-medium transition-colors"+ onMouseEnter={() => setHoveredBtn('tab-symbol')}+ onMouseLeave={() => setHoveredBtn(null)}style={{- backgroundColor: activeTab === 'symbol' ? COLORS.CARD_BG : 'transparent',- color: activeTab === 'symbol' ? COLORS.ORANGE : COLORS.GRAY,- borderBottom: activeTab === 'symbol' ? `2px solid ${COLORS.ORANGE}` : 'none',+ flex: 1,+ padding: '8px 16px',+ fontSize: '10px',+ fontWeight: 500,+ fontFamily: TERMINAL_FONT,+ backgroundColor: activeTab === 'symbol' ? FINCEPT.CARD_BG : (hoveredBtn === 'tab-symbol' ? FINCEPT.HOVER : 'transparent'),+ color: activeTab === 'symbol' ? FINCEPT.ORANGE : FINCEPT.GRAY,+ borderBottom: activeTab === 'symbol' ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',+ border: 'none',+ borderBottomStyle: 'solid',+ borderBottomWidth: '2px',+ borderBottomColor: activeTab === 'symbol' ? FINCEPT.ORANGE : 'transparent',+ cursor: 'pointer',+ letterSpacing: '0.5px',}}>- {symbol} Sentiment+ {symbol} SENTIMENT</button><buttononClick={() => setActiveTab('market')}- className="flex-1 px-4 py-2 text-xs font-medium transition-colors"+ onMouseEnter={() => setHoveredBtn('tab-market')}+ onMouseLeave={() => setHoveredBtn(null)}style={{- backgroundColor: activeTab === 'market' ? COLORS.CARD_BG : 'transparent',- color: activeTab === 'market' ? COLORS.ORANGE : COLORS.GRAY,- borderBottom: activeTab === 'market' ? `2px solid ${COLORS.ORANGE}` : 'none',+ flex: 1,+ padding: '8px 16px',+ fontSize: '10px',+ fontWeight: 500,+ fontFamily: TERMINAL_FONT,+ backgroundColor: activeTab === 'market' ? FINCEPT.CARD_BG : (hoveredBtn === 'tab-market' ? FINCEPT.HOVER : 'transparent'),+ color: activeTab === 'market' ? FINCEPT.ORANGE : FINCEPT.GRAY,+ border: 'none',+ borderBottomStyle: 'solid',+ borderBottomWidth: '2px',+ borderBottomColor: activeTab === 'market' ? FINCEPT.ORANGE : 'transparent',+ cursor: 'pointer',+ letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '4px',}}>- <Globe size={12} className="inline mr-1" />- Market Mood+ <Globe size={12} />+ MARKET MOOD</button></div>)}{/* Content */}- <div className="p-4">+ <div style={{ padding: '16px' }}>{error && (- <div className="flex items-center gap-2 p-2 rounded mb-3" style={{ backgroundColor: COLORS.RED + '10' }}>- <AlertCircle size={14} style={{ color: COLORS.RED }} />- <span className="text-xs" style={{ color: COLORS.RED }}>{error.message}</span>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '8px',+ marginBottom: '12px',+ backgroundColor: FINCEPT.RED + '10',+ }}>+ <AlertCircle size={14} style={{ color: FINCEPT.RED }} />+ <span style={{ fontSize: '11px', color: FINCEPT.RED, fontFamily: TERMINAL_FONT }}>{error.message}</span></div>)}{isLoading ? (- <div className="flex items-center justify-center py-8">- <Loader2 size={24} className="animate-spin" style={{ color: COLORS.ORANGE }} />+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '32px 0' }}>+ <Loader2 size={24} style={{ color: FINCEPT.ORANGE, animation: 'sentiment-spin 1s linear infinite' }} /></div>) : activeTab === 'symbol' && sentiment ? (<>{/* Main Sentiment Display */}- <div className="text-center mb-4">- <div className="flex items-center justify-center gap-2 mb-2">+ <div style={{ textAlign: 'center', marginBottom: '16px' }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px', marginBottom: '8px' }}>{getSentimentIcon(sentiment.overall_sentiment)}- <span- className="text-lg font-bold"- style={{ color: SENTIMENT_COLORS[sentiment.overall_sentiment] }}- >+ <span style={{+ fontSize: '14px',+ fontWeight: 700,+ color: SENTIMENT_COLORS[sentiment.overall_sentiment],+ letterSpacing: '1px',+ }}>{SENTIMENT_LABELS[sentiment.overall_sentiment]}</span></div>- <div className="text-2xl font-bold mb-1" style={{ color: COLORS.WHITE }}>+ <div style={{ fontSize: '24px', fontWeight: 700, marginBottom: '4px', color: FINCEPT.WHITE }}>{sentiment.sentiment_score >= 0 ? '+' : ''}{(sentiment.sentiment_score * 100).toFixed(0)}%</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>Confidence: {(sentiment.confidence * 100).toFixed(0)}%</div></div>{/* Sentiment Meter */}- <div className="mb-4">+ <div style={{ marginBottom: '16px' }}>{renderSentimentMeter(sentiment.sentiment_score)}- <div className="flex justify-between text-xs mt-1" style={{ color: COLORS.GRAY }}>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ fontSize: '9px',+ marginTop: '4px',+ color: FINCEPT.GRAY,+ }}><span>Bearish</span><span>Neutral</span><span>Bullish</span>@@ -242,40 +321,55 @@ const SentimentPanel: React.FC<SentimentPanelProps> = ({</div>{/* Article Breakdown */}- <div className="grid grid-cols-3 gap-2 mb-4">- <div className="p-2 rounded text-center" style={{ backgroundColor: COLORS.GREEN + '10' }}>- <div className="text-lg font-bold" style={{ color: COLORS.GREEN }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', marginBottom: '16px' }}>+ <div style={{ padding: '8px', textAlign: 'center', backgroundColor: FINCEPT.GREEN + '10' }}>+ <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.GREEN }}>{sentiment.bullish_count}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>Bullish</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Bullish</div></div>- <div className="p-2 rounded text-center" style={{ backgroundColor: COLORS.GRAY + '10' }}>- <div className="text-lg font-bold" style={{ color: COLORS.GRAY }}>+ <div style={{ padding: '8px', textAlign: 'center', backgroundColor: FINCEPT.GRAY + '10' }}>+ <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.GRAY }}>{sentiment.neutral_count}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>Neutral</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Neutral</div></div>- <div className="p-2 rounded text-center" style={{ backgroundColor: COLORS.RED + '10' }}>- <div className="text-lg font-bold" style={{ color: COLORS.RED }}>+ <div style={{ padding: '8px', textAlign: 'center', backgroundColor: FINCEPT.RED + '10' }}>+ <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.RED }}>{sentiment.bearish_count}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>Bearish</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Bearish</div></div></div>{/* Key Headlines */}{sentiment.key_headlines.length > 0 && (<div>- <h4 className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>Key Headlines</h4>- <div className="space-y-2">+ <div style={{ fontSize: '10px', fontWeight: 500, marginBottom: '8px', color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>+ KEY HEADLINES+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>{sentiment.key_headlines.slice(0, 4).map((headline, idx) => (<divkey={idx}- className="flex items-start gap-2 p-2 rounded"- style={{ backgroundColor: COLORS.CARD_BG }}+ style={{+ display: 'flex',+ alignItems: 'flex-start',+ gap: '8px',+ padding: '8px',+ backgroundColor: FINCEPT.CARD_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>- <ChevronRight size={12} style={{ color: COLORS.GRAY, marginTop: 2 }} />- <span className="text-xs line-clamp-2" style={{ color: COLORS.WHITE }}>+ <ChevronRight size={12} style={{ color: FINCEPT.GRAY, marginTop: 2, flexShrink: 0 }} />+ <span style={{+ fontSize: '11px',+ color: FINCEPT.WHITE,+ overflow: 'hidden',+ display: '-webkit-box',+ WebkitLineClamp: 2,+ WebkitBoxOrient: 'vertical',+ }}>{headline}</span></div>@@ -286,13 +380,18 @@ const SentimentPanel: React.FC<SentimentPanelProps> = ({{/* Sources */}{sentiment.sources.length > 0 && (- <div className="mt-3 pt-3 border-t" style={{ borderColor: COLORS.BORDER }}>- <div className="flex flex-wrap gap-1">+ <div style={{ marginTop: '12px', paddingTop: '12px', borderTop: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>{sentiment.sources.slice(0, 5).map((source, idx) => (<spankey={idx}- className="text-xs px-2 py-0.5 rounded"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}+ style={{+ fontSize: '9px',+ padding: '2px 8px',+ backgroundColor: FINCEPT.BORDER,+ color: FINCEPT.GRAY,+ fontFamily: TERMINAL_FONT,+ }}>{source}</span>@@ -304,54 +403,63 @@ const SentimentPanel: React.FC<SentimentPanelProps> = ({) : activeTab === 'market' && marketMood ? (<>{/* Market Mood Overview */}- <div className="text-center mb-4">- <div- className="inline-flex items-center gap-2 px-4 py-2 rounded-full mb-2"- style={{- backgroundColor: marketMood.overall_mood === 'risk_on' ? COLORS.GREEN + '20' :- marketMood.overall_mood === 'risk_off' ? COLORS.RED + '20' : COLORS.GRAY + '20',- }}- >+ <div style={{ textAlign: 'center', marginBottom: '16px' }}>+ <div style={{+ display: 'inline-flex',+ alignItems: 'center',+ gap: '8px',+ padding: '8px 16px',+ marginBottom: '8px',+ backgroundColor: marketMood.overall_mood === 'risk_on' ? FINCEPT.GREEN + '20' :+ marketMood.overall_mood === 'risk_off' ? FINCEPT.RED + '20' : FINCEPT.GRAY + '20',+ }}><Globe size={16} style={{- color: marketMood.overall_mood === 'risk_on' ? COLORS.GREEN :- marketMood.overall_mood === 'risk_off' ? COLORS.RED : COLORS.GRAY,+ color: marketMood.overall_mood === 'risk_on' ? FINCEPT.GREEN :+ marketMood.overall_mood === 'risk_off' ? FINCEPT.RED : FINCEPT.GRAY,}} />- <span- className="text-sm font-bold"- style={{- color: marketMood.overall_mood === 'risk_on' ? COLORS.GREEN :- marketMood.overall_mood === 'risk_off' ? COLORS.RED : COLORS.GRAY,- }}- >+ <span style={{+ fontSize: '13px',+ fontWeight: 700,+ letterSpacing: '1px',+ color: marketMood.overall_mood === 'risk_on' ? FINCEPT.GREEN :+ marketMood.overall_mood === 'risk_off' ? FINCEPT.RED : FINCEPT.GRAY,+ }}>{marketMood.overall_mood === 'risk_on' ? 'RISK ON' :marketMood.overall_mood === 'risk_off' ? 'RISK OFF' : 'MIXED'}</span></div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>- Avg Sentiment: {(marketMood.average_sentiment * 100).toFixed(0)}% • {marketMood.symbols_analyzed} symbols+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>+ Avg Sentiment: {(marketMood.average_sentiment * 100).toFixed(0)}% | {marketMood.symbols_analyzed} symbols</div></div>{/* Individual Sentiments */}- <div className="space-y-2">+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>{Object.entries(marketMood.individual_sentiments).map(([sym, data]) => (<divkey={sym}- className="flex items-center justify-between p-2 rounded"- style={{ backgroundColor: COLORS.CARD_BG }}+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: '8px',+ backgroundColor: FINCEPT.CARD_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>- <div className="flex items-center gap-2">+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>{getSentimentIcon(data.overall_sentiment)}- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{sym}</span>+ <span style={{ fontSize: '12px', fontWeight: 500, color: FINCEPT.WHITE }}>{sym}</span></div>- <div className="flex items-center gap-2">- <span- className="text-xs"- style={{ color: SENTIMENT_COLORS[data.overall_sentiment] }}- >+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{+ fontSize: '11px',+ color: SENTIMENT_COLORS[data.overall_sentiment],+ fontFamily: TERMINAL_FONT,+ }}>{(data.sentiment_score * 100).toFixed(0)}%</span>- <span className="text-xs" style={{ color: COLORS.GRAY }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>({data.articles_analyzed} articles)</span></div>@@ -360,18 +468,24 @@ const SentimentPanel: React.FC<SentimentPanelProps> = ({</div></>) : (- <div className="text-center py-8" style={{ color: COLORS.GRAY }}>- <Newspaper size={32} className="mx-auto mb-2 opacity-30" />- <p className="text-sm">No sentiment data available</p>+ <div style={{ textAlign: 'center', padding: '32px 0' }}>+ <Newspaper size={32} style={{ color: FINCEPT.GRAY, opacity: 0.3, margin: '0 auto 8px' }} />+ <p style={{ fontSize: '12px', color: FINCEPT.GRAY }}>No sentiment data available</p></div>)}</div>{/* Footer */}- <div className="px-4 py-2 border-t text-xs" style={{ borderColor: COLORS.BORDER, color: COLORS.GRAY }}>+ <div style={{+ padding: '6px 16px',+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ fontSize: '9px',+ backgroundColor: FINCEPT.HEADER_BG,+ color: FINCEPT.GRAY,+ }}>{sentiment && (<span>- Analyzed {sentiment.articles_analyzed} articles • Updated {new Date(sentiment.timestamp).toLocaleTimeString()}+ Analyzed {sentiment.articles_analyzed} articles | Updated {new Date(sentiment.timestamp).toLocaleTimeString()}</span>)}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaEnhancedService.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaEnhancedService.tsindex 10f1c4520..fdfc47dee 100644--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaEnhancedService.ts+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaEnhancedService.ts@@ -336,7 +336,7 @@ export async function getMarketMood(try {const result = await withTimeout(invoke<{ success: boolean; market_mood: MarketMood }>('get_alpha_market_mood', { symbols }),- 30000, 'Get market mood timeout'+ 60000, 'Get market mood timeout');return result;} catch (error) {diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/useAlphaArena.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/useAlphaArena.tsnew file mode 100644index 000000000..24d3f1ed6--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/useAlphaArena.ts@@ -0,0 +1,654 @@+/**+ * useAlphaArena Hook+ *+ * Extracts all state, effects, and callbacks from AlphaArenaTab+ * for cleaner separation of logic and presentation.+ */++import { useState, useEffect, useCallback, useRef } from 'react';+import { listen, UnlistenFn } from '@tauri-apps/api/event';+import { showConfirm } from '@/utils/notifications';+import { sqliteService, type LLMGlobalSettings } from '@/services/core/sqliteService';+import { withTimeout } from '@/services/core/apiUtils';+import { validateString } from '@/services/core/validators';+import { useCache, cacheKey } from '@/hooks/useCache';+import alphaArenaService, { type StoredCompetition } from './services/alphaArenaService';+import { useRustTicker } from '@/hooks/useRustWebSocket';+import { useAuth } from '@/contexts/AuthContext';+import type {+ CompetitionStatus,+ LeaderboardEntry,+ ModelDecision,+ PerformanceSnapshot,+ CompetitionMode,+} from './types';++// Extended model type for Alpha Arena with API key+export interface AlphaArenaModel {+ id: string;+ provider: string;+ model_id: string;+ display_name: string;+ api_key?: string;+ is_enabled: boolean;+}++// Progress event type from Rust backend+export interface AlphaArenaProgress {+ event_type: 'step' | 'info' | 'warning' | 'error' | 'complete';+ step: number;+ total_steps: number;+ message: string;+ details?: unknown;+}++// Competition data shape for useCache+interface CompetitionData {+ leaderboard: LeaderboardEntry[];+ decisions: ModelDecision[];+ snapshots: PerformanceSnapshot[];+}++export function useAlphaArena() {+ // Auth context for Fincept API key+ const { session } = useAuth();++ // Competition state+ const [competitionId, setCompetitionId] = useState<string | null>(null);+ const [status, setStatus] = useState<CompetitionStatus | null>(null);+ const [cycleCount, setCycleCount] = useState(0);++ // Data state+ const [leaderboard, setLeaderboard] = useState<LeaderboardEntry[]>([]);+ const [decisions, setDecisions] = useState<ModelDecision[]>([]);+ const [snapshots, setSnapshots] = useState<PerformanceSnapshot[]>([]);++ // LLM state - from Settings+ const [configuredLLMs, setConfiguredLLMs] = useState<AlphaArenaModel[]>([]);+ const [selectedModels, setSelectedModels] = useState<AlphaArenaModel[]>([]);+ const [llmGlobalSettings, setLlmGlobalSettings] = useState<LLMGlobalSettings>({ temperature: 0.7, max_tokens: 2000, system_prompt: '' });++ // UI state+ const [isLoading, setIsLoading] = useState(false);+ const [isAutoRunning, setIsAutoRunning] = useState(false);+ const [isCancelling, setIsCancelling] = useState(false);+ const [showCreatePanel, setShowCreatePanel] = useState(false);+ const [showPastCompetitions, setShowPastCompetitions] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [success, setSuccess] = useState<string | null>(null);++ // Enhanced features state+ type RightPanelTab = 'decisions' | 'hitl' | 'sentiment' | 'metrics' | 'grid' | 'research' | 'broker';+ const [rightPanelTab, setRightPanelTab] = useState<RightPanelTab>('decisions');+ const [selectedBroker, setSelectedBroker] = useState<string | null>(null);+ const [latestPrice, setLatestPrice] = useState<number | null>(null);++ // Progress tracking state+ const [progressSteps, setProgressSteps] = useState<AlphaArenaProgress[]>([]);+ const [currentProgress, setCurrentProgress] = useState<AlphaArenaProgress | null>(null);+ const progressListenerRef = useRef<UnlistenFn | null>(null);++ // Form state+ const [competitionName, setCompetitionName] = useState('Alpha Arena Competition');+ const [symbol, setSymbol] = useState('BTC/USD');+ const [mode, setMode] = useState<CompetitionMode>('baseline');+ const [initialCapital, setInitialCapital] = useState(10000);+ const [cycleInterval, setCycleInterval] = useState(150);++ // Component mounted ref for async safety+ const mountedRef = useRef(true);++ useEffect(() => {+ mountedRef.current = true;+ return () => { mountedRef.current = false; };+ }, []);++ // Auto-run ref+ const autoRunIntervalRef = useRef<NodeJS.Timeout | null>(null);++ // Track if a cycle is currently running (to prevent overlapping cycles)+ const cycleInProgressRef = useRef(false);++ // Ref to always hold the latest handleRunCycle to avoid stale closures in setInterval+ const handleRunCycleRef = useRef<() => Promise<void>>(() => Promise.resolve());++ // ===========================================================================+ // Load LLM Models from Settings (llm_model_configs table)+ // ===========================================================================++ const loadLLMConfigs = useCallback(async () => {+ try {+ // Auto-fix any Google model IDs with incorrect format+ await withTimeout(sqliteService.fixGoogleModelIds(), 15000);++ // Load from llm_model_configs table (individual models configured in Settings)+ const modelConfigs = await withTimeout(sqliteService.getLLMModelConfigs(), 15000);+ // Load provider configs for API key fallback and for fincept (which is auto-configured)+ const providerConfigs = await withTimeout(sqliteService.getLLMConfigs(), 15000);++ // Load global LLM settings (temperature, max_tokens, system_prompt)+ try {+ const globalSettings = await withTimeout(sqliteService.getLLMGlobalSettings(), 10000);+ if (mountedRef.current && globalSettings) {+ setLlmGlobalSettings(globalSettings);+ }+ } catch (settingsErr) {+ console.warn('[AlphaArena] Failed to load global LLM settings, using defaults:', settingsErr);+ }++ // Process models - filter and validate+ const validModels: AlphaArenaModel[] = [];++ // First, add fincept from provider configs (it's auto-configured, not in llm_model_configs)+ const finceptProvider = providerConfigs.find(c => (c.provider || '').toLowerCase() === 'fincept');+ const finceptApiKey = session?.api_key || finceptProvider?.api_key;+ if (finceptProvider || finceptApiKey) {+ validModels.push({+ id: 'fincept-auto',+ provider: 'fincept',+ model_id: finceptProvider?.model || 'fincept-llm',+ display_name: 'Fincept LLM (Auto)',+ api_key: finceptApiKey || undefined,+ is_enabled: true,+ });+ }++ // Then process models from llm_model_configs table+ for (const model of modelConfigs) {+ if (!model.is_enabled) continue;++ const providerLower = (model.provider || '').toLowerCase();++ // Get API key - try model config first, then provider config+ let apiKey = model.api_key;+ if (!apiKey || apiKey.trim() === '') {+ const providerConfig = providerConfigs.find(+ c => (c.provider || '').toLowerCase() === providerLower+ );+ if (providerConfig?.api_key && providerConfig.api_key.trim() !== '') {+ apiKey = providerConfig.api_key;+ }+ }++ // Skip if no API key (except ollama and fincept which may not need one)+ const noApiKeyRequired = providerLower === 'ollama' || providerLower === 'fincept';+ if ((!apiKey || apiKey.trim() === '') && !noApiKeyRequired) continue;++ validModels.push({+ id: model.id,+ provider: model.provider,+ model_id: model.model_id,+ display_name: model.display_name || model.model_id,+ api_key: apiKey || undefined,+ is_enabled: model.is_enabled,+ });+ }++ if (!mountedRef.current) return;+ setConfiguredLLMs(validModels);++ // Pre-select first 2 models+ if (validModels.length >= 2) {+ setSelectedModels(validModels.slice(0, 2));+ } else if (validModels.length === 1) {+ setSelectedModels([validModels[0]]);+ } else {+ setSelectedModels([]);+ }+ } catch (err) {+ if (!mountedRef.current) return;+ console.error('[AlphaArena] Failed to load LLM configs:', err);+ }+ }, [session?.api_key]);++ useEffect(() => {+ loadLLMConfigs();+ }, [loadLLMConfigs]);++ // Reload LLM configs when user changes them in Settings tab+ useEffect(() => {+ const handler = () => { loadLLMConfigs(); };+ window.addEventListener('llm-config-changed', handler);+ return () => { window.removeEventListener('llm-config-changed', handler); };+ }, [loadLLMConfigs]);++ // ===========================================================================+ // Past Competitions (useCache)+ // ===========================================================================++ const pastCompetitionsCache = useCache<StoredCompetition[]>({+ key: cacheKey('alpha-arena', 'past-competitions'),+ category: 'alpha-arena',+ fetcher: async () => {+ const result = await alphaArenaService.listCompetitions(20);+ if (result.success && result.competitions) return result.competitions;+ return [];+ },+ ttl: 120,+ staleWhileRevalidate: true,+ });++ const pastCompetitions = pastCompetitionsCache.data || [];+ const loadingPastCompetitions = pastCompetitionsCache.isLoading;++ const handleResumeCompetition = async (comp: StoredCompetition) => {+ setIsLoading(true);+ setError(null);+ setProgressSteps([]);++ try {+ setCompetitionId(comp.competition_id);+ setCycleCount(comp.cycle_count);+ setStatus(comp.status as CompetitionStatus);+ setShowPastCompetitions(false);+ setSuccess(`Loaded competition: ${comp.config.competition_name}`);+ setTimeout(() => { if (mountedRef.current) setSuccess(null); }, 3000);+ } catch (err) {+ if (!mountedRef.current) return;+ setError(err instanceof Error ? err.message : 'Failed to resume competition');+ } finally {+ if (mountedRef.current) setIsLoading(false);+ }+ };++ const handleDeleteCompetition = async (targetId: string, e: React.MouseEvent) => {+ e.stopPropagation();++ const confirmed = await showConfirm(+ 'This action cannot be undone.',+ { title: 'Delete this competition?', type: 'danger' }+ );+ if (!confirmed) return;++ try {+ const result = await alphaArenaService.deleteCompetition(targetId);+ if (!mountedRef.current) return;+ if (result.success) {+ pastCompetitionsCache.invalidate();+ if (competitionId === targetId) {+ setCompetitionId(null);+ setStatus(null);+ setCycleCount(0);+ setLeaderboard([]);+ setDecisions([]);+ setSnapshots([]);+ }+ setSuccess('Competition deleted');+ setTimeout(() => { if (mountedRef.current) setSuccess(null); }, 3000);+ } else {+ setError(result.error || 'Failed to delete competition');+ }+ } catch (err) {+ if (!mountedRef.current) return;+ setError(err instanceof Error ? err.message : 'Failed to delete competition');+ }+ };++ // ===========================================================================+ // Progress Event Listener+ // ===========================================================================++ useEffect(() => {+ const setupListener = async () => {+ progressListenerRef.current = await listen<AlphaArenaProgress>(+ 'alpha-arena-progress',+ (event) => {+ const progress = event.payload;+ setCurrentProgress(progress);+ setProgressSteps(prev => {+ if (prev.some(p => p.step === progress.step && p.message === progress.message)) return prev;+ return [...prev, progress];+ });++ if (progress.event_type === 'complete') {+ setTimeout(() => {+ setCurrentProgress(null);+ setProgressSteps([]);+ }, 2000);+ }++ if (progress.event_type === 'error') {+ setError(progress.message);+ }+ }+ );+ };++ setupListener();++ return () => {+ if (progressListenerRef.current) progressListenerRef.current();+ };+ }, []);++ // ===========================================================================+ // Competition Data (useCache with auto-refresh)+ // ===========================================================================++ const compDataCache = useCache<CompetitionData>({+ key: cacheKey('alpha-arena', 'comp-data', competitionId || 'none'),+ category: 'alpha-arena',+ fetcher: async () => {+ const targetId = competitionId;+ if (!targetId) return { leaderboard: [], decisions: [], snapshots: [] };++ const [leaderboardResult, decisionsResult, snapshotsResult] = await Promise.all([+ alphaArenaService.getLeaderboard(targetId),+ alphaArenaService.getDecisions(targetId),+ alphaArenaService.getSnapshots(targetId),+ ]);++ return {+ leaderboard: leaderboardResult.success && leaderboardResult.leaderboard+ ? leaderboardResult.leaderboard : [],+ decisions: decisionsResult.success && decisionsResult.decisions+ ? decisionsResult.decisions : [],+ snapshots: snapshotsResult.success && snapshotsResult.snapshots+ ? snapshotsResult.snapshots : [],+ };+ },+ ttl: 30,+ enabled: !!competitionId,+ staleWhileRevalidate: true,+ refetchInterval: 15000,+ });++ // Sync cache data to local state+ useEffect(() => {+ if (compDataCache.data) {+ setLeaderboard(compDataCache.data.leaderboard);+ setDecisions(compDataCache.data.decisions);+ setSnapshots(compDataCache.data.snapshots);+ }+ }, [compDataCache.data]);++ const refreshCompetitionData = useCallback(() => {+ compDataCache.refresh();+ }, [compDataCache]);++ // ===========================================================================+ // Competition Actions+ // ===========================================================================++ const handleCreateCompetition = async () => {+ const nameCheck = validateString(competitionName, { minLength: 1, maxLength: 200 });+ if (!nameCheck.valid) {+ setError(`Competition name: ${nameCheck.error}`);+ return;+ }+ if (selectedModels.length < 2) {+ setError('Select at least 2 AI models from your configured models in Settings');+ return;+ }+ if (!Number.isFinite(initialCapital) || initialCapital < 100) {+ setError('Initial capital must be at least $100');+ return;+ }+ if (!Number.isFinite(cycleInterval) || cycleInterval < 10) {+ setError('Cycle interval must be at least 10 seconds');+ return;+ }++ setIsLoading(true);+ setError(null);+ setProgressSteps([]);+ setCurrentProgress(null);++ try {+ const result = await alphaArenaService.createCompetition({+ competition_name: competitionName,+ models: selectedModels.map(m => ({+ name: m.display_name,+ provider: m.provider,+ model_id: m.model_id,+ api_key: m.api_key,+ initial_capital: initialCapital,+ })),+ symbols: [symbol],+ initial_capital: initialCapital,+ mode,+ cycle_interval_seconds: cycleInterval,+ llm_settings: {+ temperature: llmGlobalSettings.temperature,+ max_tokens: llmGlobalSettings.max_tokens,+ system_prompt: llmGlobalSettings.system_prompt,+ },+ });++ if (!mountedRef.current) return;+ if (result.success && result.competition_id) {+ setCompetitionId(result.competition_id);+ setStatus('created');+ setShowCreatePanel(false);+ setSuccess('Competition created successfully');+ setTimeout(() => { if (mountedRef.current) setSuccess(null); }, 3000);+ } else {+ setError(result.error || 'Failed to create competition');+ }+ } catch (err) {+ if (!mountedRef.current) return;+ setError(err instanceof Error ? err.message : 'Unknown error');+ } finally {+ if (mountedRef.current) setIsLoading(false);+ }+ };++ const handleRunCycle = useCallback(async () => {+ if (!competitionId) return;+ if (cycleInProgressRef.current) return;++ cycleInProgressRef.current = true;+ setIsLoading(true);+ setError(null);+ setProgressSteps([]);+ setCurrentProgress(null);++ try {+ const currentCompetitionId = competitionId;+ const currentModels = [...selectedModels];+ const apiKeys: Record<string, string> = {};+ for (const model of currentModels) {+ if (model.api_key && !apiKeys[model.provider]) {+ apiKeys[model.provider] = model.api_key;+ }+ }+ const result = await alphaArenaService.runCycle(currentCompetitionId, Object.keys(apiKeys).length > 0 ? apiKeys : undefined);++ if (!mountedRef.current) return;+ if (result.success) {+ setCycleCount(prev => result.cycle_number || prev + 1);+ setStatus('running');+ // Update leaderboard directly from cycle result if available+ if (result.leaderboard && result.leaderboard.length > 0) {+ setLeaderboard(result.leaderboard);+ }+ // Fetch fresh decisions and snapshots immediately (not from cache)+ try {+ const [decisionsResult, snapshotsResult] = await Promise.all([+ alphaArenaService.getDecisions(currentCompetitionId),+ alphaArenaService.getSnapshots(currentCompetitionId),+ ]);+ if (mountedRef.current) {+ if (decisionsResult.success && decisionsResult.decisions) {+ setDecisions(decisionsResult.decisions);+ }+ if (snapshotsResult.success && snapshotsResult.snapshots) {+ setSnapshots(snapshotsResult.snapshots);+ }+ }+ } catch {+ // Fallback to cache refresh+ }+ refreshCompetitionData();+ if (result.warnings && result.warnings.length > 0) {+ setError(`Cycle completed with warnings: ${result.warnings[0]}`);+ setTimeout(() => { if (mountedRef.current) setError(null); }, 5000);+ }+ } else {+ setError(result.error || 'Cycle failed');+ }+ } catch (err) {+ if (!mountedRef.current) return;+ setError(err instanceof Error ? err.message : 'Unknown error');+ } finally {+ cycleInProgressRef.current = false;+ if (mountedRef.current) setIsLoading(false);+ }+ }, [competitionId, selectedModels, refreshCompetitionData]);++ // Keep ref in sync so setInterval always calls the latest version+ useEffect(() => {+ handleRunCycleRef.current = handleRunCycle;+ }, [handleRunCycle]);++ const handleToggleAutoRun = useCallback(() => {+ if (isAutoRunning) {+ if (autoRunIntervalRef.current) {+ clearInterval(autoRunIntervalRef.current);+ autoRunIntervalRef.current = null;+ }+ setIsAutoRunning(false);+ setStatus('paused');+ } else {+ setIsAutoRunning(true);+ setStatus('running');+ handleRunCycleRef.current();+ autoRunIntervalRef.current = setInterval(() => {+ handleRunCycleRef.current();+ }, cycleInterval * 1000);+ }+ }, [isAutoRunning, cycleInterval]);++ const handleReset = useCallback(() => {+ if (autoRunIntervalRef.current) {+ clearInterval(autoRunIntervalRef.current);+ autoRunIntervalRef.current = null;+ }+ cycleInProgressRef.current = false;+ setCompetitionId(null);+ setStatus(null);+ setCycleCount(0);+ setLeaderboard([]);+ setDecisions([]);+ setSnapshots([]);+ setIsAutoRunning(false);+ setIsLoading(false);+ setIsCancelling(false);+ setError(null);+ setProgressSteps([]);+ setCurrentProgress(null);+ }, []);++ const handleCancel = useCallback(() => {+ setIsCancelling(true);+ if (autoRunIntervalRef.current) {+ clearInterval(autoRunIntervalRef.current);+ autoRunIntervalRef.current = null;+ setIsAutoRunning(false);+ }+ cycleInProgressRef.current = false;+ setIsLoading(false);+ setIsCancelling(false);+ setProgressSteps([]);+ setCurrentProgress(null);+ setStatus('paused');+ setSuccess('Operation cancelled');+ setTimeout(() => setSuccess(null), 2000);+ }, []);++ // Cleanup auto-run on unmount+ useEffect(() => {+ return () => {+ if (autoRunIntervalRef.current) clearInterval(autoRunIntervalRef.current);+ };+ }, []);++ // Real-time price streaming via Rust WebSocket (Kraken ticker)+ const tickerHook = useRustTicker('kraken', symbol, !!competitionId);++ useEffect(() => {+ if (tickerHook.data && mountedRef.current) {+ setLatestPrice(tickerHook.data.price);+ }+ }, [tickerHook.data]);++ const toggleModelSelection = (model: AlphaArenaModel) => {+ setSelectedModels(prev => {+ const isSelected = prev.some(m => m.id === model.id);+ if (isSelected) return prev.filter(m => m.id !== model.id);+ return [...prev, model];+ });+ };++ return {+ // Competition state+ competitionId,+ status,+ cycleCount,++ // Data+ leaderboard,+ decisions,+ snapshots,++ // LLM state+ configuredLLMs,+ selectedModels,+ llmGlobalSettings,++ // UI state+ isLoading,+ isAutoRunning,+ isCancelling,+ showCreatePanel,+ setShowCreatePanel,+ showPastCompetitions,+ setShowPastCompetitions,+ error,+ setError,+ success,+ setSuccess,++ // Enhanced features+ rightPanelTab,+ setRightPanelTab,+ selectedBroker,+ setSelectedBroker,+ latestPrice,++ // Progress+ progressSteps,+ currentProgress,++ // Form state+ competitionName,+ setCompetitionName,+ symbol,+ setSymbol,+ mode,+ setMode,+ initialCapital,+ setInitialCapital,+ cycleInterval,+ setCycleInterval,++ // Past competitions+ pastCompetitions,+ loadingPastCompetitions,+ pastCompetitionsCache,++ // Actions+ loadLLMConfigs,+ handleCreateCompetition,+ handleRunCycle,+ handleToggleAutoRun,+ handleReset,+ handleCancel,+ handleResumeCompetition,+ handleDeleteCompetition,+ toggleModelSelection,+ refreshCompetitionData,+ };+}++export type RightPanelTab = 'decisions' | 'hitl' | 'sentiment' | 'metrics' | 'grid' | 'research' | 'broker';diff --git a/fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsxindex 7e9a1998c..8a02897c5 100644--- a/fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsx@@ -11,10 +11,28 @@ import {import { invoke } from '@tauri-apps/api/core';import { open, save } from '@tauri-apps/plugin-dialog';import { FinScriptOutputPanel, FinScriptExecutionResult } from './FinScriptOutputPanel';+import { JupyterNotebookPanel } from './JupyterNotebookPanel';import { showConfirm } from '@/utils/notifications';-import { useTerminalTheme } from '@/contexts/ThemeContext';-// Theme colors provided by useTerminalTheme() hook+// ─── FINCEPT Design System ──────────────────────────────────────────────────+const F = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+} as const;+const FONT = '"IBM Plex Mono", "Consolas", monospace';// ─── Interfaces ─────────────────────────────────────────────────────────────interface EditorFile {@@ -1186,17 +1204,17 @@ label_new(250, take_profit, "TP", "green")// ─── Component ──────────────────────────────────────────────────────────────export default function CodeEditorTab() {const { t } = useTranslation('codeEditor');- const { colors, fontSize, fontFamily } = useTerminalTheme();// Language Configconst LANG_CONFIG: Record<string, { icon: React.ReactNode; color: string; ext: string }> = {- finscript: { icon: <Zap size={10} />, color: colors.primary, ext: '.fincept' },- python: { icon: <Code size={10} />, color: '#0088FF', ext: '.py' },- javascript: { icon: <Braces size={10} />, color: colors.warning, ext: '.js' },- json: { icon: <Hash size={10} />, color: colors.success, ext: '.json' },+ finscript: { icon: <Zap size={10} />, color: F.ORANGE, ext: '.fincept' },+ python: { icon: <Code size={10} />, color: F.BLUE, ext: '.py' },+ javascript: { icon: <Braces size={10} />, color: F.YELLOW, ext: '.js' },+ json: { icon: <Hash size={10} />, color: F.GREEN, ext: '.json' },};// ─── State ──────────────────────────────────────────────────────────────+ const [activeMode, setActiveMode] = useState<'finscript' | 'notebook'>('finscript');const [files, setFiles] = useState<EditorFile[]>([{id: '1',@@ -1218,13 +1236,14 @@ export default function CodeEditorTab() {// Workspace tab stateconst getWorkspaceState = useCallback(() => ({- activeFileId, showExplorer, showOutput,- }), [activeFileId, showExplorer, showOutput]);+ activeFileId, showExplorer, showOutput, activeMode,+ }), [activeFileId, showExplorer, showOutput, activeMode]);const setWorkspaceState = useCallback((state: Record<string, unknown>) => {if (typeof state.activeFileId === 'string') setActiveFileId(state.activeFileId);if (typeof state.showExplorer === 'boolean') setShowExplorer(state.showExplorer);if (typeof state.showOutput === 'boolean') setShowOutput(state.showOutput);+ if (state.activeMode === 'finscript' || state.activeMode === 'notebook') setActiveMode(state.activeMode);}, []);useWorkspaceTabState('code-editor', getWorkspaceState, setWorkspaceState);@@ -1496,20 +1515,20 @@ export default function CodeEditorTab() {const editorCSS = ['.ce-scroll::-webkit-scrollbar { width: 6px; height: 6px; }',- `.ce-scroll::-webkit-scrollbar-track { background: ${colors.background}; }`,- `.ce-scroll::-webkit-scrollbar-thumb { background: ${colors.panel}; border-radius: 3px; }`,- `.ce-scroll::-webkit-scrollbar-thumb:hover { background: ${colors.textMuted}; }`,- '.ce-tab:hover { background-color: #1F1F1F !important; }',- '.ce-explorer-item:hover { background-color: #1F1F1F; }',- `.ce-resize-handle:hover { background-color: ${colors.primary}; }`,+ `.ce-scroll::-webkit-scrollbar-track { background: ${F.DARK_BG}; }`,+ `.ce-scroll::-webkit-scrollbar-thumb { background: ${F.BORDER}; border-radius: 3px; }`,+ `.ce-scroll::-webkit-scrollbar-thumb:hover { background: ${F.MUTED}; }`,+ `.ce-tab:hover { background-color: ${F.HOVER} !important; }`,+ `.ce-explorer-item:hover { background-color: ${F.HOVER}; }`,+ `.ce-resize-handle:hover { background-color: ${F.ORANGE}; }`,].join('\n');return (<div style={{width: '100%', height: '100%',- backgroundColor: colors.background,- color: colors.text,- fontFamily: fontFamily,+ backgroundColor: F.DARK_BG,+ color: F.WHITE,+ fontFamily: FONT,display: 'flex', flexDirection: 'column',overflow: 'hidden',}}>@@ -1518,30 +1537,52 @@ export default function CodeEditorTab() {{/* ─── Top Navigation Bar ───────────────────────────────────────── */}<div style={{- backgroundColor: colors.panel,- borderBottom: `2px solid ${colors.primary}`,- padding: '6px 16px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `2px solid ${F.ORANGE}`,+ padding: '8px 16px',display: 'flex', alignItems: 'center', justifyContent: 'space-between',- boxShadow: `0 2px 8px ${colors.primary}20`,- minHeight: '38px',+ boxShadow: `0 2px 8px ${F.ORANGE}20`,+ minHeight: '40px',}}><div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <Zap size={14} style={{ color: colors.primary }} />- <span style={{ fontSize: '11px', fontWeight: 700, color: colors.text, letterSpacing: '0.5px' }}>{t('header.finscriptIde')}</span>- <span style={{ color: colors.textMuted }}>|</span>- <span style={{ fontSize: '9px', color: colors.textMuted, letterSpacing: '0.5px' }}>{t('header.version')}</span>+ <Zap size={14} style={{ color: F.ORANGE }} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>{t('header.finscriptIde')}</span>+ <div style={{ width: '1px', height: '16px', backgroundColor: F.BORDER }} />++ {/* Mode Switcher Tabs */}+ <div style={{ display: 'flex', gap: '2px' }}>+ {(['finscript', 'notebook'] as const).map(mode => (+ <button+ key={mode}+ onClick={() => setActiveMode(mode)}+ style={{+ padding: '4px 12px',+ backgroundColor: activeMode === mode ? F.ORANGE : 'transparent',+ color: activeMode === mode ? F.DARK_BG : F.GRAY,+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px',+ cursor: 'pointer', fontFamily: FONT,+ transition: 'all 0.2s',+ }}+ >+ {mode === 'finscript' ? t('tabs.finscript') : t('tabs.notebook')}+ </button>+ ))}+ </div></div>+ {activeMode === 'finscript' && (<div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>{/* Toggle Explorer */}<buttononClick={() => setShowExplorer(v => !v)}title={t('toolbar.toggleExplorer')}style={{- padding: '4px 8px', backgroundColor: showExplorer ? `${colors.primary}20` : 'transparent',- border: `1px solid ${showExplorer ? colors.primary : colors.panel}`, borderRadius: '2px',- color: showExplorer ? colors.primary : colors.textMuted, fontSize: '9px', fontWeight: 700,- cursor: 'pointer', fontFamily: fontFamily, transition: 'all 0.2s',+ padding: '4px 8px', backgroundColor: showExplorer ? `${F.ORANGE}15` : 'transparent',+ border: `1px solid ${showExplorer ? F.ORANGE : F.BORDER}`, borderRadius: '2px',+ color: showExplorer ? F.ORANGE : F.GRAY, fontSize: '9px', fontWeight: 700,+ cursor: 'pointer', fontFamily: FONT, transition: 'all 0.2s',}}><FolderOpen size={11} />@@ -1553,9 +1594,9 @@ export default function CodeEditorTab() {title={t('toolbar.openFile')}style={{padding: '4px 8px', backgroundColor: 'transparent',- border: `1px solid ${colors.panel}`, borderRadius: '2px',- color: colors.textMuted, fontSize: '9px', fontWeight: 700,- cursor: 'pointer', fontFamily: fontFamily, transition: 'all 0.2s',+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ color: F.GRAY, fontSize: '9px', fontWeight: 700,+ cursor: 'pointer', fontFamily: FONT, transition: 'all 0.2s',}}><Upload size={11} />@@ -1568,9 +1609,9 @@ export default function CodeEditorTab() {title={t('toolbar.saveShortcut')}style={{padding: '4px 8px', backgroundColor: 'transparent',- border: `1px solid ${activeFile.unsaved ? colors.warning : colors.panel}`, borderRadius: '2px',- color: activeFile.unsaved ? colors.warning : colors.textMuted, fontSize: '9px', fontWeight: 700,- cursor: activeFile.unsaved ? 'pointer' : 'default', fontFamily: fontFamily,+ border: `1px solid ${activeFile.unsaved ? F.YELLOW : F.BORDER}`, borderRadius: '2px',+ color: activeFile.unsaved ? F.YELLOW : F.GRAY, fontSize: '9px', fontWeight: 700,+ cursor: activeFile.unsaved ? 'pointer' : 'default', fontFamily: FONT,opacity: activeFile.unsaved ? 1 : 0.5, transition: 'all 0.2s',}}>@@ -1582,16 +1623,16 @@ export default function CodeEditorTab() {onClick={() => setSearch(s => ({ ...s, isOpen: !s.isOpen }))}title={t('toolbar.findShortcut')}style={{- padding: '4px 8px', backgroundColor: search.isOpen ? '#00E5FF20' : 'transparent',- border: `1px solid ${search.isOpen ? '#00E5FF' : colors.panel}`, borderRadius: '2px',- color: search.isOpen ? '#00E5FF' : colors.textMuted, fontSize: '9px', fontWeight: 700,- cursor: 'pointer', fontFamily: fontFamily, transition: 'all 0.2s',+ padding: '4px 8px', backgroundColor: search.isOpen ? `${F.CYAN}20` : 'transparent',+ border: `1px solid ${search.isOpen ? F.CYAN : F.BORDER}`, borderRadius: '2px',+ color: search.isOpen ? F.CYAN : F.GRAY, fontSize: '9px', fontWeight: 700,+ cursor: 'pointer', fontFamily: FONT, transition: 'all 0.2s',}}><Search size={11} /></button>- <div style={{ width: '1px', height: '18px', backgroundColor: colors.panel, margin: '0 4px' }} />+ <div style={{ width: '1px', height: '18px', backgroundColor: F.BORDER, margin: '0 4px' }} />{/* Run Button */}<button@@ -1600,37 +1641,46 @@ export default function CodeEditorTab() {title={t('toolbar.runShortcut')}style={{padding: '5px 14px', display: 'flex', alignItems: 'center', gap: '6px',- backgroundColor: isRunning ? colors.textMuted : colors.primary,- color: colors.background, border: 'none', borderRadius: '2px',+ backgroundColor: isRunning ? F.MUTED : F.ORANGE,+ color: F.DARK_BG, border: 'none', borderRadius: '2px',fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px',- cursor: isRunning ? 'not-allowed' : 'pointer', fontFamily: fontFamily,+ cursor: isRunning ? 'not-allowed' : 'pointer', fontFamily: FONT,transition: 'all 0.2s',}}>- <Play size={11} fill={colors.background} />+ <Play size={11} fill={F.DARK_BG} />{isRunning ? t('toolbar.running') : t('toolbar.run')}</button></div>+ )}</div>- {/* ─── Main Area ────────────────────────────────────────────────── */}+ {/* ─── Notebook Mode ────────────────────────────────────────────── */}+ {activeMode === 'notebook' && (+ <div style={{ flex: 1, minHeight: 0 }}>+ <JupyterNotebookPanel />+ </div>+ )}++ {/* ─── FinScript Mode: Main Area ─────────────────────────────────── */}+ {activeMode === 'finscript' && <><div style={{ flex: 1, display: 'flex', minHeight: 0 }}>{/* ─── Explorer Panel ─────────────────────────────────────────── */}{showExplorer && (<div style={{- width: '220px', backgroundColor: colors.panel,- borderRight: `1px solid ${colors.panel}`,+ width: '240px', backgroundColor: F.PANEL_BG,+ borderRight: `1px solid ${F.BORDER}`,display: 'flex', flexDirection: 'column',}}>{/* Explorer Header */}<div style={{- padding: '10px 12px',- backgroundColor: colors.panel,- borderBottom: `1px solid ${colors.panel}`,+ padding: '12px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,display: 'flex', alignItems: 'center', justifyContent: 'space-between',}}>- <span style={{ fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px' }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>{t('explorer.title')}</span><button@@ -1638,7 +1688,7 @@ export default function CodeEditorTab() {title={t('toolbar.newFile')}style={{padding: '2px 4px', backgroundColor: 'transparent',- border: 'none', color: colors.textMuted, cursor: 'pointer',+ border: 'none', color: F.GRAY, cursor: 'pointer',transition: 'all 0.2s',}}>@@ -1650,8 +1700,8 @@ export default function CodeEditorTab() {<div className="ce-scroll" style={{ flex: 1, overflowY: 'auto', padding: '4px 0' }}>{/* Section Label */}<div style={{- padding: '6px 12px', display: 'flex', alignItems: 'center', gap: '4px',- fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px',+ padding: '8px 12px', display: 'flex', alignItems: 'center', gap: '4px',+ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px',}}><ChevronDown size={10} />{t('explorer.openFiles')} ({files.length})@@ -1666,27 +1716,27 @@ export default function CodeEditorTab() {className="ce-explorer-item"onClick={() => setActiveFileId(file.id)}style={{- padding: '6px 12px 6px 24px',+ padding: '7px 12px 7px 24px',display: 'flex', alignItems: 'center', gap: '8px',- backgroundColor: isActive ? `${colors.primary}15` : 'transparent',- borderLeft: isActive ? `2px solid ${colors.primary}` : '2px solid transparent',+ backgroundColor: isActive ? `${F.ORANGE}15` : 'transparent',+ borderLeft: isActive ? `2px solid ${F.ORANGE}` : '2px solid transparent',cursor: 'pointer', transition: 'all 0.2s',}}><span style={{ color: lang.color }}>{lang.icon}</span><span style={{- fontSize: '10px', color: isActive ? colors.text : colors.textMuted,+ fontSize: '10px', color: isActive ? F.WHITE : F.GRAY,flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',}}>{file.name}</span>{file.unsaved && (- <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: colors.warning }} />+ <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: F.YELLOW }} />)}{files.length > 1 && (<X size={10}onClick={(e) => { e.stopPropagation(); closeFile(file.id); }}- style={{ color: colors.textMuted, cursor: 'pointer', opacity: 0.6 }}+ style={{ color: F.MUTED, cursor: 'pointer', opacity: 0.6 }}/>)}</div>@@ -1695,13 +1745,13 @@ export default function CodeEditorTab() {{/* Examples Section */}<div style={{- borderTop: `1px solid ${colors.panel}`, marginTop: '8px',+ borderTop: `1px solid ${F.BORDER}`, marginTop: '8px',}}><divonClick={() => setExamplesExpanded(!examplesExpanded)}style={{padding: '10px 12px 6px', display: 'flex', alignItems: 'center', gap: '4px',- fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px',+ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px',cursor: 'pointer',}}>@@ -1709,7 +1759,7 @@ export default function CodeEditorTab() {transform: examplesExpanded ? 'rotate(0deg)' : 'rotate(-90deg)',transition: 'transform 0.2s',}} />- <BookOpen size={10} style={{ color: colors.primary }} />+ <BookOpen size={10} style={{ color: F.ORANGE }} />{t('explorer.examples')}</div>{examplesExpanded && (@@ -1717,9 +1767,9 @@ export default function CodeEditorTab() {{Array.from(new Set(EXAMPLE_SCRIPTS.map(e => e.category))).map(category => (<div key={category}><div style={{- padding: '4px 12px 2px 20px',- fontSize: '9px', color: colors.textMuted, fontWeight: 600,- letterSpacing: '0.3px',+ padding: '6px 12px 2px 20px',+ fontSize: '9px', color: F.MUTED, fontWeight: 700,+ letterSpacing: '0.5px', textTransform: 'uppercase',}}>{category}</div>@@ -1730,14 +1780,14 @@ export default function CodeEditorTab() {onClick={() => loadExample(example)}title={example.description}style={{- padding: '4px 12px 4px 28px',+ padding: '5px 12px 5px 28px',display: 'flex', alignItems: 'center', gap: '6px',cursor: 'pointer', transition: 'all 0.2s',}}>- <Zap size={9} style={{ color: colors.primary, flexShrink: 0 }} />+ <Zap size={9} style={{ color: F.ORANGE, flexShrink: 0 }} /><span style={{- fontSize: '10px', color: colors.textMuted,+ fontSize: '10px', color: F.GRAY,overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',}}>{example.name.replace('.fincept', '')}@@ -1755,8 +1805,8 @@ export default function CodeEditorTab() {<><div style={{padding: '10px 12px 6px', display: 'flex', alignItems: 'center', gap: '4px',- fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px',- borderTop: `1px solid ${colors.panel}`, marginTop: '8px',+ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px',+ borderTop: `1px solid ${F.BORDER}`, marginTop: '8px',}}><ChevronDown size={10} />{t('explorer.runHistory')}@@ -1768,11 +1818,11 @@ export default function CodeEditorTab() {fontSize: '9px',}}>{h.status === 'success'- ? <CheckCircle size={9} style={{ color: colors.success }} />- : <AlertTriangle size={9} style={{ color: colors.alert }} />+ ? <CheckCircle size={9} style={{ color: F.GREEN }} />+ : <AlertTriangle size={9} style={{ color: F.RED }} />}- <span style={{ color: colors.textMuted }}>{h.time}</span>- <span style={{ color: colors.textMuted }}>{h.ms}ms</span>+ <span style={{ color: F.GRAY }}>{h.time}</span>+ <span style={{ color: F.CYAN }}>{h.ms}ms</span></div>))}</>@@ -1782,11 +1832,11 @@ export default function CodeEditorTab() {{/* Explorer Footer */}<div style={{padding: '8px 12px',- borderTop: `1px solid ${colors.panel}`,- fontSize: '9px', color: colors.textMuted,+ borderTop: `1px solid ${F.BORDER}`,+ fontSize: '9px', color: F.GRAY,}}><div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>- <Zap size={9} style={{ color: colors.primary }} />+ <Zap size={9} style={{ color: F.ORANGE }} /><span>{t('explorer.finscriptEngine')}</span></div></div>@@ -1798,8 +1848,8 @@ export default function CodeEditorTab() {{/* ─── Tab Bar ──────────────────────────────────────────────── */}<div style={{- backgroundColor: colors.panel,- borderBottom: `1px solid ${colors.panel}`,+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,display: 'flex', alignItems: 'center',overflow: 'hidden',}}>@@ -1813,11 +1863,11 @@ export default function CodeEditorTab() {className={isActive ? '' : 'ce-tab'}onClick={() => setActiveFileId(file.id)}style={{- padding: '7px 14px',+ padding: '8px 14px',display: 'flex', alignItems: 'center', gap: '6px',- backgroundColor: isActive ? colors.panel : 'transparent',- borderRight: `1px solid ${colors.panel}`,- borderBottom: isActive ? `2px solid ${colors.primary}` : '2px solid transparent',+ backgroundColor: isActive ? F.PANEL_BG : 'transparent',+ borderRight: `1px solid ${F.BORDER}`,+ borderBottom: isActive ? `2px solid ${F.ORANGE}` : '2px solid transparent',cursor: 'pointer', transition: 'all 0.2s',maxWidth: '180px',}}@@ -1825,7 +1875,7 @@ export default function CodeEditorTab() {<span style={{ color: lang.color }}>{lang.icon}</span><span style={{fontSize: '10px',- color: isActive ? colors.text : colors.textMuted,+ color: isActive ? F.WHITE : F.GRAY,overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',}}>{file.name}{file.unsaved ? ' *' : ''}@@ -1833,7 +1883,7 @@ export default function CodeEditorTab() {{files.length > 1 && (<X size={10}onClick={(e) => { e.stopPropagation(); closeFile(file.id); }}- style={{ color: colors.textMuted, cursor: 'pointer' }}+ style={{ color: F.MUTED, cursor: 'pointer' }}/>)}</div>@@ -1845,12 +1895,12 @@ export default function CodeEditorTab() {{/* ─── Search Bar ───────────────────────────────────────────── */}{search.isOpen && (<div style={{- backgroundColor: colors.panel,- borderBottom: `1px solid ${colors.panel}`,+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,padding: '6px 12px',display: 'flex', alignItems: 'center', gap: '8px',}}>- <Search size={12} style={{ color: colors.textMuted }} />+ <Search size={12} style={{ color: F.CYAN }} /><inputautoFocustype="text"@@ -1858,15 +1908,15 @@ export default function CodeEditorTab() {onChange={(e) => setSearch(s => ({ ...s, query: e.target.value }))}placeholder="Find..."style={{- width: '200px', padding: '4px 8px',- backgroundColor: colors.background, color: colors.text,- border: `1px solid ${colors.panel}`, borderRadius: '2px',- fontSize: '10px', fontFamily: fontFamily,+ width: '200px', padding: '6px 10px',+ backgroundColor: F.DARK_BG, color: F.WHITE,+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ fontSize: '10px', fontFamily: FONT,outline: 'none',}}/>{search.query && (- <span style={{ fontSize: '9px', color: colors.textMuted }}>+ <span style={{ fontSize: '9px', color: F.CYAN }}>{getMatchCount()} matches</span>)}@@ -1874,14 +1924,14 @@ export default function CodeEditorTab() {onClick={() => setSearch(s => ({ ...s, showReplace: !s.showReplace }))}style={{padding: '2px 6px', backgroundColor: 'transparent',- border: `1px solid ${colors.panel}`, borderRadius: '2px',- color: colors.textMuted, fontSize: '9px', cursor: 'pointer', fontFamily: fontFamily,+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ color: F.GRAY, fontSize: '9px', cursor: 'pointer', fontFamily: FONT,}}><Replace size={10} /></button><X size={12}- style={{ color: colors.textMuted, cursor: 'pointer' }}+ style={{ color: F.GRAY, cursor: 'pointer' }}onClick={() => setSearch(s => ({ ...s, isOpen: false }))}/></div>@@ -1891,17 +1941,17 @@ export default function CodeEditorTab() {<div ref={editorContainerRef} style={{ flex: 1, display: 'flex', minHeight: 0, overflow: 'hidden' }}>{/* Line Numbers Gutter */}<div className="ce-scroll" style={{- width: '48px', backgroundColor: colors.background,- borderRight: `1px solid ${colors.panel}`,+ width: '52px', backgroundColor: F.DARK_BG,+ borderRight: `1px solid ${F.BORDER}`,overflowY: 'hidden', padding: '12px 0',userSelect: 'none',}}>{lines.map((_, i) => (<div key={i} style={{- padding: '0 8px', textAlign: 'right',+ padding: '0 10px', textAlign: 'right',fontSize: '11px', lineHeight: '20px',- color: (i + 1) === activeFile.cursorLine ? colors.text : colors.textMuted,- fontFamily: fontFamily,+ color: (i + 1) === activeFile.cursorLine ? F.ORANGE : F.MUTED,+ fontFamily: FONT,}}>{i + 1}</div>@@ -1920,29 +1970,29 @@ export default function CodeEditorTab() {spellCheck={false}style={{flex: 1,- backgroundColor: colors.panel,- color: colors.text,+ backgroundColor: F.PANEL_BG,+ color: F.WHITE,border: 'none', outline: 'none', resize: 'none',padding: '12px 16px',fontSize: '12px', lineHeight: '20px',- fontFamily: fontFamily,+ fontFamily: FONT,whiteSpace: 'pre', overflowWrap: 'normal',overflowX: 'auto',tabSize: 4,+ caretColor: F.ORANGE,}}/>{/* Minimap Gutter */}<div style={{- width: '4px', backgroundColor: colors.background,- borderLeft: `1px solid ${colors.panel}`,+ width: '4px', backgroundColor: F.DARK_BG,+ borderLeft: `1px solid ${F.BORDER}`,position: 'relative',}}>- {/* Simple scrollbar indicator */}<div style={{position: 'absolute', top: '0',width: '100%', height: `${Math.min(100, (20 / lines.length) * 100)}%`,- backgroundColor: `${colors.primary}40`, borderRadius: '2px',+ backgroundColor: `${F.ORANGE}40`, borderRadius: '2px',}} /></div></div>@@ -1953,7 +2003,7 @@ export default function CodeEditorTab() {className="ce-resize-handle"onMouseDown={handleResizeStart}style={{- height: '3px', backgroundColor: colors.panel,+ height: '3px', backgroundColor: F.BORDER,cursor: 'ns-resize', transition: 'background-color 0.2s',}}/>@@ -1964,25 +2014,25 @@ export default function CodeEditorTab() {<div style={{height: `${effectiveOutputHeight}px`,display: 'flex', flexDirection: 'column',- borderTop: `1px solid ${colors.panel}`,+ borderTop: `1px solid ${F.BORDER}`,}}>{/* Output Header */}<div style={{- backgroundColor: colors.panel,- padding: '6px 12px',+ backgroundColor: F.HEADER_BG,+ padding: '8px 12px',display: 'flex', alignItems: 'center', justifyContent: 'space-between',- borderBottom: `1px solid ${colors.panel}`,+ borderBottom: `1px solid ${F.BORDER}`,}}><div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <TerminalIcon size={11} style={{ color: colors.success }} />- <span style={{ fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px' }}>+ <TerminalIcon size={11} style={{ color: F.GREEN }} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>{t('output.title')}</span>{finscriptResult && (<span style={{- padding: '1px 5px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,- backgroundColor: finscriptResult.success ? `${colors.success}20` : `${colors.alert}20`,- color: finscriptResult.success ? colors.success : colors.alert,+ padding: '2px 6px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: finscriptResult.success ? `${F.GREEN}20` : `${F.RED}20`,+ color: finscriptResult.success ? F.GREEN : F.RED,}}>{finscriptResult.success ? t('output.success') : t('output.error')}</span>@@ -1993,7 +2043,7 @@ export default function CodeEditorTab() {onClick={() => setIsOutputMaximized(v => !v)}style={{padding: '2px 4px', backgroundColor: 'transparent',- border: 'none', color: colors.textMuted, cursor: 'pointer',+ border: 'none', color: F.GRAY, cursor: 'pointer',}}>{isOutputMaximized ? <Minimize2 size={10} /> : <Maximize2 size={10} />}@@ -2002,7 +2052,7 @@ export default function CodeEditorTab() {onClick={() => setShowOutput(false)}style={{padding: '2px 4px', backgroundColor: 'transparent',- border: 'none', color: colors.textMuted, cursor: 'pointer',+ border: 'none', color: F.GRAY, cursor: 'pointer',}}><X size={10} />@@ -2017,18 +2067,18 @@ export default function CodeEditorTab() {isRunning={isRunning}onClear={() => setFinscriptResult(null)}colors={{- primary: colors.primary,- text: colors.text,- secondary: colors.success,- alert: colors.alert,- warning: colors.warning,- info: '#0088FF',- accent: '#00E5FF',- textMuted: colors.textMuted,- background: colors.background,- panel: colors.panel,+ primary: F.ORANGE,+ text: F.WHITE,+ secondary: F.GREEN,+ alert: F.RED,+ warning: F.YELLOW,+ info: F.BLUE,+ accent: F.CYAN,+ textMuted: F.GRAY,+ background: F.DARK_BG,+ panel: F.PANEL_BG,}}- fontFamily={fontFamily}+ fontFamily={FONT}/></div></div>@@ -2038,12 +2088,12 @@ export default function CodeEditorTab() {{/* ─── Status Bar ───────────────────────────────────────────────── */}<div style={{- backgroundColor: colors.panel,- borderTop: `1px solid ${colors.panel}`,- padding: '3px 16px',+ backgroundColor: F.HEADER_BG,+ borderTop: `1px solid ${F.BORDER}`,+ padding: '4px 16px',display: 'flex', alignItems: 'center', justifyContent: 'space-between',- fontSize: '9px', color: colors.textMuted, fontFamily: fontFamily,- minHeight: '22px',+ fontSize: '9px', color: F.GRAY, fontFamily: FONT,+ minHeight: '24px',}}><div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>{/* Language Indicator */}@@ -2051,23 +2101,23 @@ export default function CodeEditorTab() {<span style={{ color: LANG_CONFIG[activeFile.language].color }}>{LANG_CONFIG[activeFile.language].icon}</span>- <span style={{ letterSpacing: '0.5px' }}>{activeFile.language.toUpperCase()}</span>+ <span style={{ letterSpacing: '0.5px', fontWeight: 700 }}>{activeFile.language.toUpperCase()}</span></div>- <span style={{ color: colors.textMuted }}>|</span>+ <span style={{ color: F.MUTED }}>|</span>{/* Cursor Position */}- <span>Ln {activeFile.cursorLine}, Col {activeFile.cursorCol}</span>+ <span style={{ color: F.CYAN }}>Ln {activeFile.cursorLine}, Col {activeFile.cursorCol}</span>- <span style={{ color: colors.textMuted }}>|</span>+ <span style={{ color: F.MUTED }}>|</span>{/* Line Count */}<span>{lines.length} {t('statusBar.lines')}</span>{activeFile.unsaved && (<>- <span style={{ color: colors.textMuted }}>|</span>- <span style={{ color: colors.warning }}>{t('statusBar.modified')}</span>+ <span style={{ color: F.MUTED }}>|</span>+ <span style={{ color: F.YELLOW, fontWeight: 700 }}>{t('statusBar.modified')}</span></>)}</div>@@ -2078,9 +2128,10 @@ export default function CodeEditorTab() {<buttononClick={() => setShowOutput(true)}style={{- padding: '1px 6px', backgroundColor: 'transparent',- border: `1px solid ${colors.panel}`, borderRadius: '2px',- color: colors.textMuted, fontSize: '8px', cursor: 'pointer', fontFamily: fontFamily,+ padding: '2px 8px', backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ color: F.GRAY, fontSize: '8px', cursor: 'pointer', fontFamily: FONT,+ fontWeight: 700, letterSpacing: '0.5px',}}>{t('statusBar.showOutput')}@@ -2089,14 +2140,15 @@ export default function CodeEditorTab() {{/* Encoding */}<span>{t('statusBar.encoding')}</span>- <span style={{ color: colors.textMuted }}>|</span>+ <span style={{ color: F.MUTED }}>|</span><span>{t('statusBar.spaces')}</span>- <span style={{ color: colors.textMuted }}>|</span>+ <span style={{ color: F.MUTED }}>|</span>{/* Shortcuts */}- <span style={{ color: colors.textMuted }}>{t('statusBar.runShortcut')}</span>+ <span style={{ color: F.MUTED }}>{t('statusBar.runShortcut')}</span></div></div>+ </>}</div>);}diff --git a/fincept-terminal-desktop/src/components/tabs/code-editor/JupyterNotebookPanel.tsx b/fincept-terminal-desktop/src/components/tabs/code-editor/JupyterNotebookPanel.tsxnew file mode 100644index 000000000..0935c083f--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/code-editor/JupyterNotebookPanel.tsx@@ -0,0 +1,1249 @@+import React, { useState, useRef, useEffect, useCallback } from 'react';+import { useTranslation } from 'react-i18next';+import {+ Play, Save, Plus, X, Trash2, ChevronUp, ChevronDown,+ Upload, FileText, Package, Code, Type,+ Loader2, Download, RotateCcw, Search, History,+ PlayCircle, StopCircle, Terminal,+} from 'lucide-react';+import { invoke } from '@tauri-apps/api/core';+import { open, save } from '@tauri-apps/plugin-dialog';+import { notebookService } from '@/services/core/notebookService';++// ─── FINCEPT Design System Colors ────────────────────────────────────────────+const F = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+};++const FONT = '"IBM Plex Mono", "Consolas", monospace';++// ─── Types matching Rust structs (camelCase due to serde rename) ─────────────+interface CellOutput {+ outputType: string;+ data: Record<string, string[]> | null;+ text: string[] | null;+ name: string | null;+ ename: string | null;+ evalue: string | null;+ traceback: string[] | null;+}++interface NotebookCell {+ id: string;+ cellType: string;+ source: string[];+ outputs: CellOutput[];+ executionCount: number | null;+ metadata: Record<string, unknown>;+}++interface NotebookMetadata {+ kernelspec: { displayName: string; language: string; name: string };+ languageInfo: { name: string; version: string; mimetype: string; fileExtension: string };+}++interface JupyterNotebook {+ cells: NotebookCell[];+ metadata: NotebookMetadata;+ nbformat: number;+ nbformatMinor: number;+}++interface ExecutionResult {+ success: boolean;+ outputs: CellOutput[];+ executionCount: number;+ error: string | null;+}++// ─── Scrollbar CSS ───────────────────────────────────────────────────────────+const notebookCSS = `+.nb-scroll::-webkit-scrollbar { width: 6px; height: 6px; }+.nb-scroll::-webkit-scrollbar-track { background: ${F.DARK_BG}; }+.nb-scroll::-webkit-scrollbar-thumb { background: ${F.BORDER}; border-radius: 3px; }+.nb-scroll::-webkit-scrollbar-thumb:hover { background: ${F.MUTED}; }+`;++// ─── Component ───────────────────────────────────────────────────────────────+export const JupyterNotebookPanel: React.FC = () => {+ const { t } = useTranslation('codeEditor');++ // ─── State ─────────────────────────────────────────────────────────────────+ const [notebook, setNotebook] = useState<JupyterNotebook | null>(null);+ const [filePath, setFilePath] = useState<string | null>(null);+ const [unsaved, setUnsaved] = useState(false);+ const [executionCounter, setExecutionCounter] = useState(1);+ const [runningCellId, setRunningCellId] = useState<string | null>(null);+ const [runningAll, setRunningAll] = useState(false);+ const [pythonVersion, setPythonVersion] = useState<string>('');+ const [selectedCellId, setSelectedCellId] = useState<string | null>(null);+ const [notebookName, setNotebookName] = useState<string>('fincept1');++ // Sidebar+ const [sidebarMode, setSidebarMode] = useState<'none' | 'history' | 'packages'>('none');+ const [historyItems, setHistoryItems] = useState<Array<{+ id?: number; name: string; path: string | null; updated_at: string; cell_count: number;+ }>>([]);+ const [historySearch, setHistorySearch] = useState('');++ // Packages+ const [packages, setPackages] = useState<string[]>([]);+ const [packagesLoading, setPackagesLoading] = useState(false);+ const [installInput, setInstallInput] = useState('');+ const [installing, setInstalling] = useState(false);++ const cellsContainerRef = useRef<HTMLDivElement>(null);+ const notebookCounterRef = useRef(1);++ // ─── Init ──────────────────────────────────────────────────────────────────+ useEffect(() => {+ createNewNotebook();+ loadPythonVersion();+ }, []);++ const loadPythonVersion = async () => {+ try {+ const ver = await invoke<string>('get_python_version');+ setPythonVersion(ver);+ } catch {+ setPythonVersion('Python N/A');+ }+ };++ // ─── Notebook Operations ───────────────────────────────────────────────────+ const createNewNotebook = async () => {+ try {+ const nb = await invoke<JupyterNotebook>('create_new_notebook');++ // Add branded markdown cell at the top+ const brandCell: NotebookCell = {+ id: crypto.randomUUID(),+ cellType: 'markdown',+ source: [+ '# Fincept Terminal - Notebook\n',+ '\n',+ '**Fincept Terminal** | Professional Financial Intelligence Platform\n',+ '\n',+ '---\n',+ '\n',+ '> *CFA-Level Analytics | AI-Powered Automation | Global Market Intelligence*\n',+ '\n',+ 'Use this notebook to run Python-based financial analysis, build quantitative models, and explore market data.\n',+ ],+ outputs: [],+ executionCount: null,+ metadata: {},+ };++ nb.cells = [brandCell, ...nb.cells];++ const name = `fincept${notebookCounterRef.current}`;+ notebookCounterRef.current++;++ setNotebook(nb);+ setFilePath(null);+ setNotebookName(name);+ setUnsaved(false);+ setExecutionCounter(1);+ setSelectedCellId(nb.cells[1]?.id || nb.cells[0]?.id || null);+ } catch (err) {+ console.error('Failed to create notebook:', err);+ }+ };++ const openNotebook = async () => {+ try {+ const selected = await open({+ multiple: false,+ filters: [{ name: 'Jupyter Notebook', extensions: ['ipynb'] }],+ });+ if (!selected) return;+ const path = selected as string;+ const nb = await invoke<JupyterNotebook>('open_notebook', { filePath: path });+ setNotebook(nb);+ setFilePath(path);+ setNotebookName(path.split(/[/\\]/).pop()?.replace('.ipynb', '') || 'fincept1');+ setUnsaved(false);+ setExecutionCounter(1);+ setSelectedCellId(nb.cells[0]?.id || null);+ } catch (err) {+ console.error('Failed to open notebook:', err);+ }+ };++ const saveNotebook = async () => {+ if (!notebook) return;+ try {+ let path = filePath;+ if (!path) {+ const selected = await save({+ filters: [{ name: 'Jupyter Notebook', extensions: ['ipynb'] }],+ });+ if (!selected) return;+ path = selected as string;+ }+ await invoke('save_notebook', { filePath: path, notebook });+ setFilePath(path);+ setUnsaved(false);++ const name = path.split(/[/\\]/).pop() || `${notebookName}.ipynb`;+ const now = new Date().toISOString();+ await notebookService.saveToHistory({+ name,+ content: JSON.stringify(notebook),+ path,+ created_at: now,+ updated_at: now,+ cell_count: notebook.cells.length,+ execution_count: executionCounter,+ });+ } catch (err) {+ console.error('Failed to save notebook:', err);+ }+ };++ // ─── Cell Operations ──────────────────────────────────────────────────────+ const getCellSource = (cell: NotebookCell): string => cell.source.join('');++ const setCellSource = (cellId: string, value: string) => {+ if (!notebook) return;+ setNotebook({+ ...notebook,+ cells: notebook.cells.map(c =>+ c.id === cellId ? { ...c, source: value.split('\n').map((line, i, arr) => i < arr.length - 1 ? line + '\n' : line) } : c+ ),+ });+ setUnsaved(true);+ };++ const addCell = (afterId: string | null, cellType: string = 'code') => {+ if (!notebook) return;+ const newCell: NotebookCell = {+ id: crypto.randomUUID(),+ cellType,+ source: [],+ outputs: [],+ executionCount: null,+ metadata: {},+ };+ const cells = [...notebook.cells];+ if (afterId) {+ const idx = cells.findIndex(c => c.id === afterId);+ cells.splice(idx + 1, 0, newCell);+ } else {+ cells.push(newCell);+ }+ setNotebook({ ...notebook, cells });+ setSelectedCellId(newCell.id);+ setUnsaved(true);+ };++ const deleteCell = (cellId: string) => {+ if (!notebook || notebook.cells.length <= 1) return;+ const cells = notebook.cells.filter(c => c.id !== cellId);+ setNotebook({ ...notebook, cells });+ if (selectedCellId === cellId) {+ setSelectedCellId(cells[0]?.id || null);+ }+ setUnsaved(true);+ };++ const moveCell = (cellId: string, direction: 'up' | 'down') => {+ if (!notebook) return;+ const cells = [...notebook.cells];+ const idx = cells.findIndex(c => c.id === cellId);+ if (direction === 'up' && idx > 0) {+ [cells[idx - 1], cells[idx]] = [cells[idx], cells[idx - 1]];+ } else if (direction === 'down' && idx < cells.length - 1) {+ [cells[idx], cells[idx + 1]] = [cells[idx + 1], cells[idx]];+ }+ setNotebook({ ...notebook, cells });+ setUnsaved(true);+ };++ const toggleCellType = (cellId: string) => {+ if (!notebook) return;+ setNotebook({+ ...notebook,+ cells: notebook.cells.map(c =>+ c.id === cellId ? { ...c, cellType: c.cellType === 'code' ? 'markdown' : 'code', outputs: [] } : c+ ),+ });+ setUnsaved(true);+ };++ const clearCellOutput = (cellId: string) => {+ if (!notebook) return;+ setNotebook({+ ...notebook,+ cells: notebook.cells.map(c =>+ c.id === cellId ? { ...c, outputs: [], executionCount: null } : c+ ),+ });+ };++ // ─── Execution ────────────────────────────────────────────────────────────+ const runCell = async (cellId: string) => {+ if (!notebook) return;+ const cell = notebook.cells.find(c => c.id === cellId);+ if (!cell || cell.cellType !== 'code') return;++ const code = getCellSource(cell);+ if (!code.trim()) return;++ setRunningCellId(cellId);+ try {+ const result = await invoke<ExecutionResult>('execute_python_code', {+ code,+ executionCount: executionCounter,+ });++ setNotebook(prev => {+ if (!prev) return prev;+ return {+ ...prev,+ cells: prev.cells.map(c =>+ c.id === cellId ? { ...c, outputs: result.outputs, executionCount: result.executionCount } : c+ ),+ };+ });+ setExecutionCounter(prev => prev + 1);+ } catch (err) {+ setNotebook(prev => {+ if (!prev) return prev;+ return {+ ...prev,+ cells: prev.cells.map(c =>+ c.id === cellId+ ? {+ ...c,+ outputs: [{+ outputType: 'error',+ data: null,+ text: null,+ name: null,+ ename: 'InvocationError',+ evalue: String(err),+ traceback: [String(err)],+ }],+ executionCount: executionCounter,+ }+ : c+ ),+ };+ });+ setExecutionCounter(prev => prev + 1);+ } finally {+ setRunningCellId(null);+ }+ };++ const runAllCells = async () => {+ if (!notebook) return;+ setRunningAll(true);+ for (const cell of notebook.cells) {+ if (cell.cellType === 'code') {+ await runCell(cell.id);+ }+ }+ setRunningAll(false);+ };++ // ─── History ──────────────────────────────────────────────────────────────+ const loadHistory = async () => {+ try {+ const items = historySearch+ ? await notebookService.searchHistory(historySearch)+ : await notebookService.getHistory();+ setHistoryItems(items);+ } catch {+ setHistoryItems([]);+ }+ };++ useEffect(() => {+ if (sidebarMode === 'history') loadHistory();+ }, [sidebarMode, historySearch]);++ const loadFromHistory = async (item: typeof historyItems[0]) => {+ try {+ if (item.path) {+ const nb = await invoke<JupyterNotebook>('open_notebook', { filePath: item.path });+ setNotebook(nb);+ setFilePath(item.path);+ } else {+ const content = await notebookService.getNotebookById(item.id!);+ if (content?.content) {+ const nb = JSON.parse(content.content) as JupyterNotebook;+ setNotebook(nb);+ setFilePath(null);+ }+ }+ setUnsaved(false);+ setSidebarMode('none');+ } catch (err) {+ console.error('Failed to load from history:', err);+ }+ };++ const deleteHistoryItem = async (id: number) => {+ await notebookService.deleteFromHistory(id);+ loadHistory();+ };++ // ─── Packages ─────────────────────────────────────────────────────────────+ const loadPackages = async () => {+ setPackagesLoading(true);+ try {+ const pkgs = await invoke<string[]>('list_python_packages');+ setPackages(pkgs);+ } catch {+ setPackages([]);+ } finally {+ setPackagesLoading(false);+ }+ };++ useEffect(() => {+ if (sidebarMode === 'packages') loadPackages();+ }, [sidebarMode]);++ const installPackage = async () => {+ if (!installInput.trim()) return;+ setInstalling(true);+ try {+ await invoke('install_python_package', { packageName: installInput.trim() });+ setInstallInput('');+ loadPackages();+ } catch (err) {+ console.error('Failed to install package:', err);+ } finally {+ setInstalling(false);+ }+ };++ // ─── Keyboard ─────────────────────────────────────────────────────────────+ const handleCellKeyDown = useCallback((e: React.KeyboardEvent, cellId: string) => {+ if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {+ e.preventDefault();+ runCell(cellId);+ }+ if (e.shiftKey && e.key === 'Enter') {+ e.preventDefault();+ runCell(cellId);+ if (notebook) {+ const idx = notebook.cells.findIndex(c => c.id === cellId);+ if (idx < notebook.cells.length - 1) {+ setSelectedCellId(notebook.cells[idx + 1].id);+ } else {+ addCell(cellId);+ }+ }+ }+ }, [notebook, executionCounter]);++ // ─── Render: Cell Output ──────────────────────────────────────────────────+ const renderCellOutput = (output: CellOutput, idx: number) => {+ if (output.outputType === 'stream' && output.text) {+ return (+ <pre key={idx} style={{+ margin: 0, padding: '10px 16px',+ fontSize: '11px', lineHeight: '1.6',+ fontFamily: FONT, color: F.WHITE,+ whiteSpace: 'pre-wrap', wordBreak: 'break-word',+ backgroundColor: F.DARK_BG,+ }}>+ {output.text.join('\n')}+ </pre>+ );+ }++ if (output.outputType === 'error') {+ return (+ <div key={idx} style={{+ padding: '10px 16px',+ backgroundColor: `${F.RED}08`,+ borderLeft: `3px solid ${F.RED}`,+ }}>+ {output.ename && (+ <div style={{+ color: F.RED, fontSize: '11px', fontWeight: 700,+ fontFamily: FONT, marginBottom: '6px', letterSpacing: '0.3px',+ }}>+ {output.ename}: {output.evalue}+ </div>+ )}+ {output.traceback && (+ <pre style={{+ margin: 0, fontSize: '10px', lineHeight: '1.5',+ fontFamily: FONT, color: F.RED, opacity: 0.8,+ whiteSpace: 'pre-wrap', wordBreak: 'break-word',+ }}>+ {output.traceback.join('\n')}+ </pre>+ )}+ </div>+ );+ }++ if (output.outputType === 'execute_result' || output.outputType === 'display_data') {+ if (output.data) {+ const textData = output.data['text/plain'];+ if (textData) {+ return (+ <pre key={idx} style={{+ margin: 0, padding: '10px 16px',+ fontSize: '11px', lineHeight: '1.6',+ fontFamily: FONT, color: F.CYAN,+ whiteSpace: 'pre-wrap',+ backgroundColor: F.DARK_BG,+ }}>+ {textData.join('\n')}+ </pre>+ );+ }+ }+ }++ return null;+ };++ // ─── Loading state ────────────────────────────────────────────────────────+ if (!notebook) {+ return (+ <div style={{+ width: '100%', height: '100%',+ display: 'flex', flexDirection: 'column',+ alignItems: 'center', justifyContent: 'center',+ backgroundColor: F.DARK_BG, color: F.MUTED, fontSize: '10px',+ fontFamily: FONT, gap: '8px',+ }}>+ <Loader2 size={24} className="animate-spin" style={{ color: F.ORANGE, opacity: 0.5 }} />+ <span style={{ letterSpacing: '0.5px' }}>INITIALIZING NOTEBOOK...</span>+ </div>+ );+ }++ // ─── Computed ─────────────────────────────────────────────────────────────+ const codeCellCount = notebook.cells.filter(c => c.cellType === 'code').length;+ const mdCellCount = notebook.cells.filter(c => c.cellType === 'markdown').length;+ const executedCount = notebook.cells.filter(c => c.executionCount != null).length;+ const fileName = filePath ? filePath.split(/[/\\]/).pop() : `${notebookName}.ipynb`;++ // ─── Render ────────────────────────────────────────────────────────────────+ return (+ <div style={{+ width: '100%', height: '100%',+ display: 'flex', flexDirection: 'column',+ backgroundColor: F.DARK_BG,+ }}>+ <style dangerouslySetInnerHTML={{ __html: notebookCSS }} />++ {/* ═══ Toolbar ═══ */}+ <div style={{+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ padding: '6px 16px',+ display: 'flex', alignItems: 'center', gap: '8px',+ minHeight: '38px',+ }}>+ {/* File actions group */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <button onClick={createNewNotebook} title="New Notebook" style={{+ padding: '6px 10px', backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ color: F.GRAY, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '5px',+ fontSize: '9px', fontWeight: 700, fontFamily: FONT, letterSpacing: '0.5px',+ transition: 'all 0.2s',+ }}>+ <FileText size={11} /> NEW+ </button>+ <button onClick={openNotebook} title="Open .ipynb" style={{+ padding: '6px 10px', backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ color: F.GRAY, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '5px',+ fontSize: '9px', fontWeight: 700, fontFamily: FONT, letterSpacing: '0.5px',+ transition: 'all 0.2s',+ }}>+ <Upload size={11} /> OPEN+ </button>+ <button onClick={saveNotebook} title="Save .ipynb" style={{+ padding: '6px 10px', backgroundColor: 'transparent',+ border: `1px solid ${unsaved ? F.YELLOW : F.BORDER}`, borderRadius: '2px',+ color: unsaved ? F.YELLOW : F.GRAY,+ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '5px',+ fontSize: '9px', fontWeight: 700, fontFamily: FONT, letterSpacing: '0.5px',+ transition: 'all 0.2s',+ }}>+ <Save size={11} /> SAVE+ </button>+ </div>++ {/* Divider */}+ <div style={{ width: '1px', height: '20px', backgroundColor: F.BORDER }} />++ {/* Run actions */}+ <button+ onClick={runAllCells}+ disabled={runningAll}+ title="Run All Cells"+ style={{+ padding: '6px 16px', display: 'flex', alignItems: 'center', gap: '6px',+ backgroundColor: runningAll ? F.MUTED : F.ORANGE,+ color: F.DARK_BG, border: 'none', borderRadius: '2px',+ fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px',+ cursor: runningAll ? 'not-allowed' : 'pointer', fontFamily: FONT,+ transition: 'all 0.2s',+ }}+ >+ {runningAll+ ? <><Loader2 size={11} className="animate-spin" /> RUNNING...</>+ : <><PlayCircle size={11} /> RUN ALL</>+ }+ </button>++ {runningAll && (+ <button+ onClick={() => setRunningAll(false)}+ style={{+ padding: '6px 10px', backgroundColor: `${F.RED}20`,+ border: `1px solid ${F.RED}`, borderRadius: '2px',+ color: F.RED, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '5px',+ fontSize: '9px', fontWeight: 700, fontFamily: FONT, letterSpacing: '0.5px',+ }}+ >+ <StopCircle size={11} /> STOP+ </button>+ )}++ {/* Spacer */}+ <div style={{ flex: 1 }} />++ {/* File name display */}+ <div style={{+ padding: '4px 10px', backgroundColor: F.PANEL_BG,+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ display: 'flex', alignItems: 'center', gap: '6px',+ }}>+ <Terminal size={10} style={{ color: F.ORANGE }} />+ <span style={{ fontSize: '10px', color: F.WHITE, fontFamily: FONT, fontWeight: 700 }}>+ {fileName}+ </span>+ {unsaved && (+ <span style={{+ padding: '1px 5px', backgroundColor: `${F.YELLOW}20`,+ color: F.YELLOW, fontSize: '8px', fontWeight: 700,+ borderRadius: '2px', letterSpacing: '0.5px',+ }}>+ MODIFIED+ </span>+ )}+ </div>++ {/* Divider */}+ <div style={{ width: '1px', height: '20px', backgroundColor: F.BORDER }} />++ {/* Sidebar toggles */}+ <button+ onClick={() => setSidebarMode(sidebarMode === 'packages' ? 'none' : 'packages')}+ title="Python Packages"+ style={{+ padding: '6px 10px', display: 'flex', alignItems: 'center', gap: '5px',+ backgroundColor: sidebarMode === 'packages' ? F.ORANGE : 'transparent',+ color: sidebarMode === 'packages' ? F.DARK_BG : F.GRAY,+ border: 'none', borderRadius: '2px',+ fontSize: '9px', fontWeight: 700, fontFamily: FONT, letterSpacing: '0.5px',+ cursor: 'pointer', transition: 'all 0.2s',+ }}+ >+ <Package size={11} /> PACKAGES+ </button>+ <button+ onClick={() => setSidebarMode(sidebarMode === 'history' ? 'none' : 'history')}+ title="Notebook History"+ style={{+ padding: '6px 10px', display: 'flex', alignItems: 'center', gap: '5px',+ backgroundColor: sidebarMode === 'history' ? F.ORANGE : 'transparent',+ color: sidebarMode === 'history' ? F.DARK_BG : F.GRAY,+ border: 'none', borderRadius: '2px',+ fontSize: '9px', fontWeight: 700, fontFamily: FONT, letterSpacing: '0.5px',+ cursor: 'pointer', transition: 'all 0.2s',+ }}+ >+ <History size={11} /> HISTORY+ </button>+ </div>++ {/* ═══ Main Area ═══ */}+ <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>++ {/* ─── Cells Panel ─── */}+ <div ref={cellsContainerRef} className="nb-scroll" style={{+ flex: 1, overflowY: 'auto',+ padding: '16px 24px',+ }}>+ {notebook.cells.map((cell, cellIdx) => {+ const isSelected = selectedCellId === cell.id;+ const isRunning = runningCellId === cell.id;+ const hasError = cell.outputs.some(o => o.outputType === 'error');+ const hasSuccess = cell.outputs.length > 0 && !hasError;+ const hasOutput = cell.outputs.length > 0;++ // Cell accent color+ const accentColor = isRunning ? F.YELLOW+ : hasError ? F.RED+ : hasSuccess ? F.GREEN+ : isSelected ? F.ORANGE+ : F.BORDER;++ return (+ <div key={cell.id}>+ {/* ── Cell Container ── */}+ <div+ onClick={() => setSelectedCellId(cell.id)}+ style={{+ backgroundColor: F.PANEL_BG,+ border: `1px solid ${accentColor}`,+ borderRadius: '2px',+ borderLeft: `3px solid ${accentColor}`,+ overflow: 'hidden',+ transition: 'all 0.2s',+ marginBottom: '2px',+ }}+ >+ {/* Cell header bar */}+ <div style={{+ display: 'flex', alignItems: 'center', gap: '6px',+ padding: '6px 12px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ }}>+ {/* Execution count badge */}+ <div style={{+ minWidth: '48px',+ padding: '2px 6px',+ backgroundColor: cell.cellType === 'code'+ ? (isRunning ? `${F.YELLOW}20` : hasError ? `${F.RED}20` : hasSuccess ? `${F.GREEN}20` : `${F.ORANGE}15`)+ : `${F.PURPLE}15`,+ borderRadius: '2px',+ textAlign: 'center',+ }}>+ <span style={{+ fontSize: '10px', fontFamily: FONT, fontWeight: 700,+ color: cell.cellType === 'code'+ ? (isRunning ? F.YELLOW : hasError ? F.RED : hasSuccess ? F.GREEN : F.ORANGE)+ : F.PURPLE,+ }}>+ {cell.cellType === 'code'+ ? (isRunning ? 'In [*]' : `In [${cell.executionCount ?? ' '}]`)+ : 'MD'+ }+ </span>+ </div>++ {/* Cell type label */}+ <span style={{+ fontSize: '9px', fontWeight: 700, color: F.GRAY,+ letterSpacing: '0.5px', fontFamily: FONT,+ }}>+ {cell.cellType === 'code' ? 'PYTHON' : 'MARKDOWN'}+ </span>++ <div style={{ flex: 1 }} />++ {/* Cell actions (always visible on selected) */}+ {isSelected && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ {cell.cellType === 'code' && (+ <button+ onClick={(e) => { e.stopPropagation(); runCell(cell.id); }}+ disabled={isRunning}+ title="Run Cell (Ctrl+Enter)"+ style={{+ padding: '3px 8px', display: 'flex', alignItems: 'center', gap: '4px',+ backgroundColor: isRunning ? `${F.YELLOW}20` : `${F.GREEN}20`,+ border: `1px solid ${isRunning ? F.YELLOW : F.GREEN}`,+ borderRadius: '2px', cursor: isRunning ? 'not-allowed' : 'pointer',+ color: isRunning ? F.YELLOW : F.GREEN,+ fontSize: '9px', fontWeight: 700, fontFamily: FONT, letterSpacing: '0.5px',+ transition: 'all 0.2s',+ }}+ >+ {isRunning ? <Loader2 size={10} className="animate-spin" /> : <Play size={10} />}+ {isRunning ? 'RUNNING' : 'RUN'}+ </button>+ )}++ <div style={{ width: '1px', height: '16px', backgroundColor: F.BORDER }} />++ <button onClick={(e) => { e.stopPropagation(); toggleCellType(cell.id); }} title="Toggle Code/Markdown" style={{+ padding: '3px 6px', backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', color: F.GRAY, cursor: 'pointer', display: 'flex', alignItems: 'center',+ transition: 'all 0.2s',+ }}>+ {cell.cellType === 'code' ? <Type size={10} /> : <Code size={10} />}+ </button>+ <button onClick={(e) => { e.stopPropagation(); moveCell(cell.id, 'up'); }} disabled={cellIdx === 0} title="Move Up" style={{+ padding: '3px 6px', backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', color: cellIdx === 0 ? F.MUTED : F.GRAY, cursor: cellIdx === 0 ? 'default' : 'pointer',+ display: 'flex', alignItems: 'center', opacity: cellIdx === 0 ? 0.5 : 1,+ transition: 'all 0.2s',+ }}>+ <ChevronUp size={10} />+ </button>+ <button onClick={(e) => { e.stopPropagation(); moveCell(cell.id, 'down'); }} disabled={cellIdx === notebook.cells.length - 1} title="Move Down" style={{+ padding: '3px 6px', backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ borderRadius: '2px',+ color: cellIdx === notebook.cells.length - 1 ? F.MUTED : F.GRAY,+ cursor: cellIdx === notebook.cells.length - 1 ? 'default' : 'pointer',+ display: 'flex', alignItems: 'center',+ opacity: cellIdx === notebook.cells.length - 1 ? 0.5 : 1,+ transition: 'all 0.2s',+ }}>+ <ChevronDown size={10} />+ </button>+ {hasOutput && (+ <button onClick={(e) => { e.stopPropagation(); clearCellOutput(cell.id); }} title="Clear Output" style={{+ padding: '3px 6px', backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', color: F.GRAY, cursor: 'pointer', display: 'flex', alignItems: 'center',+ transition: 'all 0.2s',+ }}>+ <RotateCcw size={10} />+ </button>+ )}++ <div style={{ width: '1px', height: '16px', backgroundColor: F.BORDER }} />++ <button onClick={(e) => { e.stopPropagation(); deleteCell(cell.id); }} disabled={notebook.cells.length <= 1} title="Delete Cell" style={{+ padding: '3px 6px', backgroundColor: notebook.cells.length <= 1 ? 'transparent' : `${F.RED}10`,+ border: `1px solid ${notebook.cells.length <= 1 ? F.MUTED : F.RED}`,+ borderRadius: '2px', color: notebook.cells.length <= 1 ? F.MUTED : F.RED,+ cursor: notebook.cells.length <= 1 ? 'default' : 'pointer',+ display: 'flex', alignItems: 'center',+ opacity: notebook.cells.length <= 1 ? 0.5 : 1,+ transition: 'all 0.2s',+ }}>+ <Trash2 size={10} />+ </button>+ </div>+ )}+ </div>++ {/* Cell editor textarea */}+ <textarea+ value={getCellSource(cell)}+ onChange={(e) => setCellSource(cell.id, e.target.value)}+ onKeyDown={(e) => handleCellKeyDown(e, cell.id)}+ onFocus={() => setSelectedCellId(cell.id)}+ spellCheck={false}+ placeholder={cell.cellType === 'code' ? '# Enter Python code...' : 'Enter markdown text...'}+ style={{+ width: '100%', display: 'block',+ backgroundColor: F.DARK_BG,+ color: F.WHITE,+ border: 'none', outline: 'none', resize: 'none',+ padding: '12px 16px',+ fontSize: '12px', lineHeight: '20px',+ fontFamily: FONT,+ minHeight: '52px',+ overflow: 'hidden',+ boxSizing: 'border-box',+ }}+ rows={Math.max(2, getCellSource(cell).split('\n').length)}+ />++ {/* Cell output area */}+ {hasOutput && cell.cellType === 'code' && (+ <div style={{+ borderTop: `1px solid ${hasError ? F.RED : F.BORDER}`,+ maxHeight: '320px',+ overflowY: 'auto',+ }}>+ {/* Output label */}+ <div style={{+ padding: '4px 16px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex', alignItems: 'center', gap: '6px',+ }}>+ <span style={{+ fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px',+ fontFamily: FONT,+ color: hasError ? F.RED : F.GREEN,+ }}>+ {hasError ? 'ERROR OUTPUT' : 'OUTPUT'}+ </span>+ {cell.executionCount != null && (+ <>+ <span style={{ color: F.MUTED, fontSize: '9px' }}>|</span>+ <span style={{ fontSize: '9px', fontFamily: FONT, color: F.CYAN }}>+ Out [{cell.executionCount}]+ </span>+ </>+ )}+ </div>+ {cell.outputs.map((output, idx) => renderCellOutput(output, idx))}+ </div>+ )}+ </div>++ {/* Add cell divider */}+ <div style={{+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ padding: '4px 0',+ }}>+ <div style={{ flex: 1, height: '1px', backgroundColor: F.BORDER }} />+ <button+ onClick={() => addCell(cell.id, 'code')}+ title="Add Code Cell"+ style={{+ padding: '2px 10px', fontSize: '9px', fontFamily: FONT, fontWeight: 700,+ backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', color: F.WHITE, cursor: 'pointer', letterSpacing: '0.5px',+ display: 'flex', alignItems: 'center', gap: '4px',+ transition: 'all 0.2s',+ }}+ >+ <Plus size={9} /> CODE+ </button>+ <button+ onClick={() => addCell(cell.id, 'markdown')}+ title="Add Markdown Cell"+ style={{+ padding: '2px 10px', fontSize: '9px', fontFamily: FONT, fontWeight: 700,+ backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', color: F.WHITE, cursor: 'pointer', letterSpacing: '0.5px',+ marginLeft: '4px',+ display: 'flex', alignItems: 'center', gap: '4px',+ transition: 'all 0.2s',+ }}+ >+ <Plus size={9} /> MARKDOWN+ </button>+ <div style={{ flex: 1, height: '1px', backgroundColor: F.BORDER }} />+ </div>+ </div>+ );+ })}+ </div>++ {/* ─── Sidebar (History / Packages) ─── */}+ {sidebarMode !== 'none' && (+ <div style={{+ width: '300px',+ backgroundColor: F.PANEL_BG,+ borderLeft: `1px solid ${F.BORDER}`,+ display: 'flex', flexDirection: 'column',+ }}>+ {/* Sidebar header */}+ <div style={{+ padding: '12px',+ backgroundColor: F.HEADER_BG,+ borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px', fontFamily: FONT }}>+ {sidebarMode === 'history' ? 'NOTEBOOK HISTORY' : 'PYTHON PACKAGES'}+ </span>+ <button onClick={() => setSidebarMode('none')} style={{+ padding: '3px 6px', background: 'transparent', border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', color: F.GRAY, cursor: 'pointer', display: 'flex', alignItems: 'center',+ transition: 'all 0.2s',+ }}>+ <X size={11} />+ </button>+ </div>++ {/* ── History Content ── */}+ {sidebarMode === 'history' && (+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ {/* Search input */}+ <div style={{ padding: '8px 12px' }}>+ <div style={{+ display: 'flex', alignItems: 'center', gap: '6px',+ padding: '8px 10px',+ backgroundColor: F.DARK_BG,+ border: `1px solid ${F.BORDER}`,+ borderRadius: '2px',+ }}>+ <Search size={11} style={{ color: F.GRAY }} />+ <input+ value={historySearch}+ onChange={(e) => setHistorySearch(e.target.value)}+ placeholder="Search notebooks..."+ style={{+ flex: 1, background: 'none', border: 'none', outline: 'none',+ color: F.WHITE, fontSize: '10px', fontFamily: FONT,+ }}+ />+ </div>+ </div>++ {/* History list */}+ <div className="nb-scroll" style={{ flex: 1, overflowY: 'auto', padding: '0 8px' }}>+ {historyItems.length === 0 ? (+ <div style={{+ display: 'flex', flexDirection: 'column',+ alignItems: 'center', justifyContent: 'center',+ height: '120px', color: F.MUTED, fontSize: '10px',+ textAlign: 'center', fontFamily: FONT,+ }}>+ <History size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />+ <span>No notebooks saved yet</span>+ </div>+ ) : (+ historyItems.map((item) => (+ <div+ key={item.id}+ onClick={() => loadFromHistory(item)}+ style={{+ padding: '10px 12px', marginBottom: '4px',+ backgroundColor: 'transparent',+ borderLeft: '2px solid transparent',+ borderRadius: '2px', cursor: 'pointer',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = F.HOVER;+ e.currentTarget.style.borderLeftColor = F.ORANGE;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.borderLeftColor = 'transparent';+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <span style={{+ fontSize: '10px', color: F.WHITE, fontFamily: FONT, fontWeight: 700,+ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',+ }}>+ {item.name}+ </span>+ {item.id != null && (+ <button onClick={(e) => { e.stopPropagation(); deleteHistoryItem(item.id!); }} style={{+ background: 'none', border: 'none', color: F.MUTED, cursor: 'pointer',+ padding: '2px', display: 'flex', transition: 'color 0.2s',+ }}+ onMouseEnter={(e) => { e.currentTarget.style.color = F.RED; }}+ onMouseLeave={(e) => { e.currentTarget.style.color = F.MUTED; }}+ >+ <Trash2 size={10} />+ </button>+ )}+ </div>+ <div style={{+ fontSize: '9px', color: F.GRAY, marginTop: '4px',+ fontFamily: FONT, display: 'flex', gap: '8px',+ }}>+ <span style={{ color: F.CYAN }}>{item.cell_count} cells</span>+ <span>{new Date(item.updated_at).toLocaleDateString()}</span>+ </div>+ </div>+ ))+ )}+ </div>++ {/* Clear history */}+ <div style={{ padding: '8px 12px', borderTop: `1px solid ${F.BORDER}` }}>+ <button+ onClick={async () => { await notebookService.clearHistory(); loadHistory(); }}+ style={{+ width: '100%', padding: '6px 10px', fontSize: '9px', fontFamily: FONT, fontWeight: 700,+ backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', color: F.GRAY, cursor: 'pointer', letterSpacing: '0.5px',+ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = F.RED; e.currentTarget.style.color = F.RED; }}+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.GRAY; }}+ >+ <RotateCcw size={10} /> CLEAR HISTORY+ </button>+ </div>+ </div>+ )}++ {/* ── Packages Content ── */}+ {sidebarMode === 'packages' && (+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ {/* Install input */}+ <div style={{ padding: '8px 12px', display: 'flex', gap: '6px' }}>+ <input+ value={installInput}+ onChange={(e) => setInstallInput(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') installPackage(); }}+ placeholder="Package name..."+ style={{+ flex: 1, padding: '8px 10px',+ backgroundColor: F.DARK_BG, color: F.WHITE,+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ fontSize: '10px', fontFamily: FONT, outline: 'none',+ }}+ onFocus={(e) => { e.currentTarget.style.borderColor = F.ORANGE; }}+ onBlur={(e) => { e.currentTarget.style.borderColor = F.BORDER; }}+ />+ <button+ onClick={installPackage}+ disabled={installing || !installInput.trim()}+ style={{+ padding: '8px 16px',+ backgroundColor: (installing || !installInput.trim()) ? F.MUTED : F.ORANGE,+ color: F.DARK_BG, border: 'none', borderRadius: '2px',+ fontSize: '9px', fontWeight: 700, fontFamily: FONT,+ cursor: (installing || !installInput.trim()) ? 'not-allowed' : 'pointer',+ display: 'flex', alignItems: 'center', gap: '4px',+ letterSpacing: '0.5px',+ }}+ >+ {installing ? <Loader2 size={10} className="animate-spin" /> : <Download size={10} />}+ INSTALL+ </button>+ </div>++ {/* Package count */}+ {packages.length > 0 && (+ <div style={{+ padding: '4px 12px', borderBottom: `1px solid ${F.BORDER}`,+ fontSize: '9px', color: F.GRAY, fontFamily: FONT, letterSpacing: '0.5px',+ }}>+ <span style={{ color: F.CYAN }}>{packages.length}</span> PACKAGES INSTALLED+ </div>+ )}++ {/* Package list */}+ <div className="nb-scroll" style={{ flex: 1, overflowY: 'auto' }}>+ {packagesLoading ? (+ <div style={{+ display: 'flex', flexDirection: 'column',+ alignItems: 'center', justifyContent: 'center',+ height: '120px', color: F.MUTED, fontSize: '10px',+ fontFamily: FONT, gap: '8px',+ }}>+ <Loader2 size={20} className="animate-spin" style={{ color: F.ORANGE, opacity: 0.5 }} />+ <span style={{ letterSpacing: '0.5px' }}>LOADING PACKAGES...</span>+ </div>+ ) : packages.length === 0 ? (+ <div style={{+ display: 'flex', flexDirection: 'column',+ alignItems: 'center', justifyContent: 'center',+ height: '120px', color: F.MUTED, fontSize: '10px',+ textAlign: 'center', fontFamily: FONT,+ }}>+ <Package size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />+ <span>Click refresh to load</span>+ </div>+ ) : (+ packages.map((pkg, idx) => {+ const [name, version] = pkg.split('==');+ return (+ <div key={idx} style={{+ padding: '6px 12px',+ borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ transition: 'background 0.2s',+ }}+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = F.HOVER; }}+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent'; }}+ >+ <span style={{ fontSize: '10px', color: F.WHITE, fontFamily: FONT }}>+ {name}+ </span>+ {version && (+ <span style={{ fontSize: '9px', color: F.CYAN, fontFamily: FONT }}>+ {version}+ </span>+ )}+ </div>+ );+ })+ )}+ </div>++ {/* Refresh */}+ <div style={{ padding: '8px 12px', borderTop: `1px solid ${F.BORDER}` }}>+ <button+ onClick={loadPackages}+ disabled={packagesLoading}+ style={{+ width: '100%', padding: '6px 10px', fontSize: '9px', fontFamily: FONT, fontWeight: 700,+ backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', color: F.GRAY, cursor: packagesLoading ? 'not-allowed' : 'pointer',+ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px',+ letterSpacing: '0.5px', transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = F.ORANGE; e.currentTarget.style.color = F.ORANGE; }}+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = F.BORDER; e.currentTarget.style.color = F.GRAY; }}+ >+ <RotateCcw size={10} /> REFRESH LIST+ </button>+ </div>+ </div>+ )}+ </div>+ )}+ </div>++ {/* ═══ Status Bar ═══ */}+ <div style={{+ backgroundColor: F.HEADER_BG,+ borderTop: `1px solid ${F.BORDER}`,+ padding: '4px 16px',+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ fontSize: '9px', color: F.GRAY, fontFamily: FONT,+ minHeight: '24px',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ {/* Python version badge */}+ <span style={{+ padding: '2px 6px', backgroundColor: `${F.GREEN}20`,+ color: F.GREEN, fontSize: '8px', fontWeight: 700,+ borderRadius: '2px', letterSpacing: '0.5px',+ }}>+ {pythonVersion || 'PYTHON'}+ </span>++ <span style={{ color: F.MUTED }}>|</span>+ <span><span style={{ color: F.CYAN }}>{codeCellCount}</span> CODE</span>+ <span><span style={{ color: F.PURPLE }}>{mdCellCount}</span> MD</span>+ <span style={{ color: F.MUTED }}>|</span>+ <span>EXECUTED: <span style={{ color: F.CYAN }}>{executedCount}</span></span>+ <span style={{ color: F.MUTED }}>|</span>+ <span>COUNTER: <span style={{ color: F.CYAN }}>{executionCounter - 1}</span></span>++ {unsaved && (+ <>+ <span style={{ color: F.MUTED }}>|</span>+ <span style={{+ padding: '2px 6px', backgroundColor: `${F.YELLOW}20`,+ color: F.YELLOW, fontSize: '8px', fontWeight: 700,+ borderRadius: '2px',+ }}>+ UNSAVED+ </span>+ </>+ )}+ </div>++ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <span style={{ color: F.MUTED }}>SHIFT+ENTER: RUN & NEXT</span>+ <span style={{ color: F.MUTED }}>|</span>+ <span style={{ color: F.MUTED }}>CTRL+ENTER: RUN CELL</span>+ </div>+ </div>+ </div>+ );+};diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderBook.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderBook.tsxindex 36f2d5d29..ef85a487d 100644--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderBook.tsx+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderBook.tsx@@ -1,13 +1,74 @@// CryptoOrderBook.tsx - Professional Order Book Display// Direct Kraken WebSocket connection with incremental updates+// Extended with: Tick History Buffer, Volume-at-Price, Depth Imbalance, Trade Signals+// Performance: rAF-throttled rendering, DOM recycling, canvas size cachingimport React, { useCallback, useRef, useEffect, memo, useState } from 'react';import { FINCEPT } from '../constants';-import { VolumeProfile } from '../../trading/charts';-import { ErrorBoundary } from '@/components/common/ErrorBoundary';const NUM_LEVELS = 12;+const MAX_TICK_HISTORY = 3600;+const IMBALANCE_BUY_THRESHOLD = 0.3;+const IMBALANCE_SELL_THRESHOLD = -0.3;+const RISE_BUY_THRESHOLD = 0.15;+const RISE_SELL_THRESHOLD = -0.15;+const TICK_CAPTURE_INTERVAL = 1000;+const CANVAS_VISIBLE_POINTS = 300;++// Pre-allocated reusable arrays to avoid GC pressure on every frame+const _askSortBuf: [number, number][] = [];+const _bidSortBuf: [number, number][] = [];+const _cumBuf: number[] = [];++/** Sort order book map into a reusable buffer via insertion sort. Returns item count. */+function sortInto(book: Record<string, number>, buf: [number, number][], asc: boolean): number {+ const keys = Object.keys(book);+ const n = keys.length;+ while (buf.length < n) buf.push([0, 0]);+ for (let i = 0; i < n; i++) {+ buf[i][0] = Number(keys[i]);+ buf[i][1] = book[keys[i]];+ }+ // Insertion sort — optimal for small n (~25), nearly sorted data+ for (let i = 1; i < n; i++) {+ const kp = buf[i][0], kq = buf[i][1];+ let j = i - 1;+ if (asc) {+ while (j >= 0 && buf[j][0] > kp) { buf[j + 1][0] = buf[j][0]; buf[j + 1][1] = buf[j][1]; j--; }+ } else {+ while (j >= 0 && buf[j][0] < kp) { buf[j + 1][0] = buf[j][0]; buf[j + 1][1] = buf[j][1]; j--; }+ }+ buf[j + 1][0] = kp; buf[j + 1][1] = kq;+ }+ return n;+}-type OrderBookViewType = 'orderbook' | 'volume';+type OrderBookViewType = 'orderbook' | 'volume' | 'imbalance' | 'signals';++interface TickSnapshot {+ timestamp: number;+ bestBid: number;+ bestAsk: number;+ bidQty1: number;+ bidQty2: number;+ bidQty3: number;+ askQty1: number;+ askQty2: number;+ askQty3: number;+ totalBidQty: number;+ totalAskQty: number;+ imbalance: number;+ riseRatio30: number;+ riseRatio60: number;+ riseRatio300: number;+}++interface Signal {+ timestamp: number;+ direction: 'BUY' | 'SELL' | 'NEUTRAL';+ imbalance: number;+ riseRatio: number;+ price: number;+}interface CryptoOrderBookProps {currentPrice: number;@@ -15,6 +76,27 @@ interface CryptoOrderBookProps {activeBroker: string | null;}+// Pre-computed format caches to avoid toLocaleString overhead+const priceFormatCache = new Map<string, string>();+const formatPrice = (price: number): string => {+ const key = price.toFixed(price >= 1000 ? 2 : price >= 1 ? 2 : 6);+ let cached = priceFormatCache.get(key);+ if (!cached) {+ if (price >= 1000) cached = price.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });+ else if (price >= 1) cached = price.toFixed(2);+ else cached = price.toFixed(6);+ if (priceFormatCache.size > 500) priceFormatCache.clear();+ priceFormatCache.set(key, cached);+ }+ return cached;+};++const formatQty = (qty: number): string => {+ if (qty >= 1000) return qty.toLocaleString(undefined, { maximumFractionDigits: 2 });+ if (qty >= 1) return qty.toFixed(4);+ return qty.toFixed(6);+};+export const CryptoOrderBook = memo(function CryptoOrderBook({currentPrice,selectedSymbol,@@ -22,12 +104,24 @@ export const CryptoOrderBook = memo(function CryptoOrderBook({}: CryptoOrderBookProps) {const [activeView, setActiveView] = useState<OrderBookViewType>('orderbook');const [status, setStatus] = useState<'connecting' | 'connected' | 'disconnected'>('disconnected');+ const activeViewRef = useRef<OrderBookViewType>('orderbook');const wsRef = useRef<WebSocket | null>(null);const asksRef = useRef<Record<string, number>>({});const bidsRef = useRef<Record<string, number>>({});- const asksContainerRef = useRef<HTMLDivElement>(null);- const bidsContainerRef = useRef<HTMLDivElement>(null);+ const tickHistoryRef = useRef<TickSnapshot[]>([]);+ const signalHistoryRef = useRef<Signal[]>([]);+ const cumulativePnlRef = useRef(0);+ const lastSignalPriceRef = useRef(0);+ const activeSignalRef = useRef<'BUY' | 'SELL' | null>(null);+ const lastTickCaptureRef = useRef(0);+ const rafIdRef = useRef(0);+ const dirtyRef = useRef(false);++ // Canvas refs for order book (Binance-style canvas rendering)+ const asksCanvasRef = useRef<HTMLCanvasElement>(null);+ const bidsCanvasRef = useRef<HTMLCanvasElement>(null);+ const obCanvasSizeRef = useRef({ aw: 0, ah: 0, bw: 0, bh: 0 }); // cached canvas sizesconst spreadValueRef = useRef<HTMLSpanElement>(null);const spreadPercentRef = useRef<HTMLSpanElement>(null);const priceRef = useRef<HTMLDivElement>(null);@@ -35,139 +129,580 @@ export const CryptoOrderBook = memo(function CryptoOrderBook({const updateTimeRef = useRef<HTMLSpanElement>(null);const askTotalRef = useRef<HTMLSpanElement>(null);const bidTotalRef = useRef<HTMLSpanElement>(null);+ const tickCountRef = useRef<HTMLSpanElement>(null);++ // Canvas refs + cached sizes+ const imbalanceCanvasRef = useRef<HTMLCanvasElement>(null);+ const riseCanvasRef = useRef<HTMLCanvasElement>(null);+ const canvasSizeRef = useRef({ w: 0, h: 0 });+ const imbalanceValueRef = useRef<HTMLSpanElement>(null);+ const riseValueRef = useRef<HTMLSpanElement>(null);+ const bidTotalImbalanceRef = useRef<HTMLSpanElement>(null);+ const askTotalImbalanceRef = useRef<HTMLSpanElement>(null);++ // Volume + signals refs+ const volumeContainerRef = useRef<HTMLDivElement>(null);+ const signalIndicatorRef = useRef<HTMLDivElement>(null);+ const signalHistoryContainerRef = useRef<HTMLDivElement>(null);+ const lastSignalRenderCountRef = useRef(0);++ // Keep activeViewRef in sync without re-renders+ useEffect(() => { activeViewRef.current = activeView; }, [activeView]);++ // Capture tick snapshot using pre-sorted buffers (called from renderFrame, throttled to 1/sec)+ const captureTickSnapshot = useCallback((askCount: number, bidCount: number) => {+ const now = Date.now();+ if (now - lastTickCaptureRef.current < TICK_CAPTURE_INTERVAL) return;+ if (askCount === 0 || bidCount === 0) return;+ lastTickCaptureRef.current = now;++ // Use the already-sorted global buffers (filled by renderFrame)+ let totalBidQty = 0;+ for (let i = 0; i < bidCount; i++) totalBidQty += _bidSortBuf[i][1];+ let totalAskQty = 0;+ for (let i = 0; i < askCount; i++) totalAskQty += _askSortBuf[i][1];++ // Weighted depth imbalance (SGX: 50/30/20 top 3)+ const wBid = 50 * (_bidSortBuf[0]?.[1] || 0) + 30 * (_bidSortBuf[1]?.[1] || 0) + 20 * (_bidSortBuf[2]?.[1] || 0);+ const wAsk = 50 * (_askSortBuf[0]?.[1] || 0) + 30 * (_askSortBuf[1]?.[1] || 0) + 20 * (_askSortBuf[2]?.[1] || 0);+ const imbalance = (wAsk + wBid) > 0 ? (wBid - wAsk) / (wBid + wAsk) : 0;++ const history = tickHistoryRef.current;+ const bestAsk = _askSortBuf[0][0];+ const bestBid = _bidSortBuf[0][0];++ const calcRise = (lookbackMs: number) => {+ const cutoff = now - lookbackMs;+ for (let i = history.length - 1; i >= 0; i--) {+ if (history[i].timestamp <= cutoff && history[i].bestAsk > 0) {+ return ((bestAsk - history[i].bestAsk) / history[i].bestAsk) * 100;+ }+ }+ return 0;+ };++ const snapshot: TickSnapshot = {+ timestamp: now,+ bestBid,+ bestAsk,+ bidQty1: _bidSortBuf[0]?.[1] || 0,+ bidQty2: _bidSortBuf[1]?.[1] || 0,+ bidQty3: _bidSortBuf[2]?.[1] || 0,+ askQty1: _askSortBuf[0]?.[1] || 0,+ askQty2: _askSortBuf[1]?.[1] || 0,+ askQty3: _askSortBuf[2]?.[1] || 0,+ totalBidQty,+ totalAskQty,+ imbalance,+ riseRatio30: calcRise(30000),+ riseRatio60: calcRise(60000),+ riseRatio300: calcRise(300000),+ };++ history.push(snapshot);+ if (history.length > MAX_TICK_HISTORY) history.splice(0, history.length - MAX_TICK_HISTORY);++ // Signal generation+ const riseRatio = snapshot.riseRatio60;+ let direction: 'BUY' | 'SELL' | 'NEUTRAL' = 'NEUTRAL';+ if (imbalance > IMBALANCE_BUY_THRESHOLD && riseRatio > RISE_BUY_THRESHOLD) direction = 'BUY';+ else if (imbalance < IMBALANCE_SELL_THRESHOLD && riseRatio < RISE_SELL_THRESHOLD) direction = 'SELL';++ const midPrice = (bestBid + bestAsk) / 2;+ if (direction !== 'NEUTRAL') {+ const prev = activeSignalRef.current;+ if (prev && prev !== direction && lastSignalPriceRef.current > 0) {+ cumulativePnlRef.current += prev === 'BUY'+ ? midPrice - lastSignalPriceRef.current+ : lastSignalPriceRef.current - midPrice;+ }+ if (prev !== direction) {+ activeSignalRef.current = direction;+ lastSignalPriceRef.current = midPrice;+ signalHistoryRef.current.push({ timestamp: now, direction, imbalance, riseRatio, price: midPrice });+ if (signalHistoryRef.current.length > 200) signalHistoryRef.current.splice(0, signalHistoryRef.current.length - 200);+ }+ }+ }, []);++ // Canvas-based order book rendering (Binance-style: no DOM nodes, pure canvas paint)+ const paintOrderBookCanvas = useCallback((+ canvas: HTMLCanvasElement | null,+ buf: [number, number][],+ count: number,+ maxTotal: number,+ side: 'ask' | 'bid',+ reverse: boolean,+ sizeCache: { w: number; h: number }+ ) => {+ if (!canvas) return;+ const ctx = canvas.getContext('2d', { alpha: false });+ if (!ctx) return;++ // Resize canvas buffer to match CSS size (only when changed)+ const rect = canvas.getBoundingClientRect();+ const dpr = window.devicePixelRatio || 1;+ const w = Math.round(rect.width * dpr);+ const h = Math.round(rect.height * dpr);+ if (sizeCache.w !== w || sizeCache.h !== h) {+ sizeCache.w = w;+ sizeCache.h = h;+ canvas.width = w;+ canvas.height = h;+ }++ const levels = Math.min(count, NUM_LEVELS);+ const cssW = rect.width;+ const cssH = rect.height;++ // Clear+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.fillStyle = '#0A0A0A';+ ctx.fillRect(0, 0, cssW, cssH);++ if (levels === 0) {+ ctx.font = '10px "IBM Plex Mono", monospace';+ ctx.fillStyle = '#666';+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.fillText(`Waiting for ${side} data...`, cssW / 2, cssH / 2);+ return;+ }++ // Compute cumulative+ _cumBuf.length = levels;+ let cum = 0;+ for (let i = 0; i < levels; i++) { cum += buf[i][1]; _cumBuf[i] = cum; }++ const ROW_H = Math.min(22, cssH / levels);+ const PAD_X = 8;+ const priceColor = side === 'ask' ? '#EF4444' : '#22C55E';+ const depthColor = side === 'ask' ? 'rgba(239,68,68,0.12)' : 'rgba(34,197,94,0.12)';++ // Column positions: Price (left), Size (center-right), Total (right)+ const col1 = PAD_X;+ const col2 = cssW * 0.55;+ const col3 = cssW - PAD_X;++ ctx.textBaseline = 'middle';+ ctx.font = '600 11px "IBM Plex Mono", monospace';++ // Asks reversed: render highest at top (row 0 = buf[levels-1])+ // Bids normal: render highest at top (row 0 = buf[0])+ // With flex-end on asks, we want: bottom row = best ask (lowest price = buf[0])+ // So row 0 at visual top = buf[levels-1] (highest ask), going down to buf[0]+ const startY = reverse ? (cssH - levels * ROW_H) : 0; // asks: push to bottom++ for (let rowIdx = 0; rowIdx < levels; rowIdx++) {+ const dataIdx = reverse ? (levels - 1 - rowIdx) : rowIdx;+ const price = buf[dataIdx][0];+ const qty = buf[dataIdx][1];+ const cumVal = _cumBuf[dataIdx];+ const y = startY + rowIdx * ROW_H;++ // Depth bar+ const barW = (cumVal / maxTotal) * cssW;+ ctx.fillStyle = depthColor;+ if (side === 'ask') {+ ctx.fillRect(cssW - barW, y + 1, barW, ROW_H - 2);+ } else {+ ctx.fillRect(0, y + 1, barW, ROW_H - 2);+ }++ const textY = y + ROW_H / 2;++ // Price+ ctx.fillStyle = priceColor;+ ctx.textAlign = 'left';+ ctx.fillText(formatPrice(price), col1, textY);++ // Size+ ctx.fillStyle = '#E5E5E5';+ ctx.textAlign = 'right';+ ctx.fillText(formatQty(qty), col2, textY);++ // Total+ ctx.fillStyle = '#888';+ ctx.font = '10px "IBM Plex Mono", monospace';+ ctx.fillText(formatQty(cumVal), col3, textY);+ ctx.font = '600 11px "IBM Plex Mono", monospace';+ }+ }, []);++ // Render canvas charts (only when imbalance tab is active)+ const renderCanvasCharts = useCallback(() => {+ const history = tickHistoryRef.current;+ if (history.length === 0) return;+ const latest = history[history.length - 1];++ // Update stat text nodes+ if (imbalanceValueRef.current) {+ imbalanceValueRef.current.textContent = latest.imbalance.toFixed(4);+ imbalanceValueRef.current.style.color = latest.imbalance > 0.3 ? FINCEPT.GREEN : latest.imbalance < -0.3 ? FINCEPT.RED : FINCEPT.WHITE;+ }+ if (riseValueRef.current) {+ riseValueRef.current.textContent = `${latest.riseRatio60.toFixed(4)}%`;+ riseValueRef.current.style.color = latest.riseRatio60 > 0 ? FINCEPT.GREEN : latest.riseRatio60 < 0 ? FINCEPT.RED : FINCEPT.WHITE;+ }+ if (bidTotalImbalanceRef.current) bidTotalImbalanceRef.current.textContent = formatQty(latest.totalBidQty);+ if (askTotalImbalanceRef.current) askTotalImbalanceRef.current.textContent = formatQty(latest.totalAskQty);++ // Imbalance canvas+ const canvas = imbalanceCanvasRef.current;+ if (canvas) {+ const ctx = canvas.getContext('2d');+ if (ctx) {+ // Only resize if dimensions actually changed+ const rect = canvas.getBoundingClientRect();+ const targetW = Math.round(rect.width * 2);+ const targetH = Math.round(rect.height * 2);+ if (canvas.width !== targetW || canvas.height !== targetH) {+ canvas.width = targetW;+ canvas.height = targetH;+ }+ const dw = rect.width;+ const dh = rect.height;+ ctx.setTransform(2, 0, 0, 2, 0, 0);+ ctx.clearRect(0, 0, dw, dh);++ ctx.fillStyle = '#0A0A0A';+ ctx.fillRect(0, 0, dw, dh);++ const midY = dh / 2;+ ctx.strokeStyle = '#1A1A1A';+ ctx.lineWidth = 0.5;+ ctx.beginPath(); ctx.moveTo(0, midY); ctx.lineTo(dw, midY); ctx.stroke();++ // Zones+ const buyZoneY = midY * 0.7;+ const sellZoneY = midY * 1.3;+ ctx.fillStyle = 'rgba(0,214,111,0.05)';+ ctx.fillRect(0, 0, dw, buyZoneY);+ ctx.fillStyle = 'rgba(255,59,59,0.05)';+ ctx.fillRect(0, sellZoneY, dw, dh - sellZoneY);++ ctx.setLineDash([3, 3]);+ ctx.strokeStyle = 'rgba(0,214,111,0.3)';+ ctx.beginPath(); ctx.moveTo(0, buyZoneY); ctx.lineTo(dw, buyZoneY); ctx.stroke();+ ctx.strokeStyle = 'rgba(255,59,59,0.3)';+ ctx.beginPath(); ctx.moveTo(0, sellZoneY); ctx.lineTo(dw, sellZoneY); ctx.stroke();+ ctx.setLineDash([]);++ const visible = history.length <= CANVAS_VISIBLE_POINTS ? history : history.slice(-CANVAS_VISIBLE_POINTS);+ if (visible.length > 1) {+ const step = dw / (visible.length - 1);+ ctx.beginPath();+ ctx.lineWidth = 1.5;+ for (let i = 0; i < visible.length; i++) {+ const y = midY - (visible[i].imbalance * midY);+ if (i === 0) ctx.moveTo(0, y); else ctx.lineTo(i * step, y);+ }+ const latestImb = visible[visible.length - 1].imbalance;+ ctx.strokeStyle = latestImb > 0.3 ? FINCEPT.GREEN : latestImb < -0.3 ? FINCEPT.RED : FINCEPT.CYAN;+ ctx.stroke();+ }++ ctx.fillStyle = FINCEPT.GRAY;+ ctx.font = '9px monospace';+ ctx.fillText('+1.0', 2, 10);+ ctx.fillText(' 0.0', 2, midY + 3);+ ctx.fillText('-1.0', 2, dh - 3);+ }+ }++ // Rise ratio canvas+ const riseCanvas = riseCanvasRef.current;+ if (riseCanvas) {+ const ctx = riseCanvas.getContext('2d');+ if (ctx) {+ const rect = riseCanvas.getBoundingClientRect();+ const targetW = Math.round(rect.width * 2);+ const targetH = Math.round(rect.height * 2);+ if (riseCanvas.width !== targetW || riseCanvas.height !== targetH) {+ riseCanvas.width = targetW;+ riseCanvas.height = targetH;+ }+ const dw = rect.width;+ const dh = rect.height;+ ctx.setTransform(2, 0, 0, 2, 0, 0);+ ctx.clearRect(0, 0, dw, dh);++ ctx.fillStyle = '#0A0A0A';+ ctx.fillRect(0, 0, dw, dh);++ const midY = dh / 2;+ ctx.strokeStyle = '#1A1A1A';+ ctx.lineWidth = 0.5;+ ctx.beginPath(); ctx.moveTo(0, midY); ctx.lineTo(dw, midY); ctx.stroke();++ const visible = history.length <= CANVAS_VISIBLE_POINTS ? history : history.slice(-CANVAS_VISIBLE_POINTS);+ if (visible.length > 1) {+ let maxRise = 0.5;+ for (let i = 0; i < visible.length; i++) {+ const abs60 = Math.abs(visible[i].riseRatio60);+ if (abs60 > maxRise) maxRise = abs60;+ }+ const step = dw / (visible.length - 1);++ // 30s+ ctx.beginPath(); ctx.lineWidth = 0.8; ctx.strokeStyle = 'rgba(157,78,221,0.4)';+ for (let i = 0; i < visible.length; i++) {+ const y = midY - (visible[i].riseRatio30 / maxRise) * midY;+ if (i === 0) ctx.moveTo(0, y); else ctx.lineTo(i * step, y);+ }+ ctx.stroke();++ // 60s+ ctx.beginPath(); ctx.lineWidth = 1.5;+ const lr = visible[visible.length - 1].riseRatio60;+ ctx.strokeStyle = lr > 0 ? FINCEPT.GREEN : lr < 0 ? FINCEPT.RED : FINCEPT.CYAN;+ for (let i = 0; i < visible.length; i++) {+ const y = midY - (visible[i].riseRatio60 / maxRise) * midY;+ if (i === 0) ctx.moveTo(0, y); else ctx.lineTo(i * step, y);+ }+ ctx.stroke();- const formatPrice = (price: number): string => {- if (price >= 1000) return price.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });- if (price >= 1) return price.toFixed(2);- return price.toFixed(6);- };+ // 300s+ ctx.beginPath(); ctx.lineWidth = 0.8; ctx.strokeStyle = 'rgba(255,136,0,0.4)';+ for (let i = 0; i < visible.length; i++) {+ const y = midY - (visible[i].riseRatio300 / maxRise) * midY;+ if (i === 0) ctx.moveTo(0, y); else ctx.lineTo(i * step, y);+ }+ ctx.stroke();+ }- const formatQty = (qty: number): string => {- if (qty >= 1000) return qty.toLocaleString(undefined, { maximumFractionDigits: 2 });- if (qty >= 1) return qty.toFixed(4);- return qty.toFixed(6);- };+ ctx.fillStyle = FINCEPT.GRAY;+ ctx.font = '9px monospace';+ ctx.fillText('RISE %', 2, 10);+ }+ }+ }, []);++ // Volume view (only rebuild when data changes significantly)+ const renderVolumeView = useCallback(() => {+ const container = volumeContainerRef.current;+ if (!container) return;- const render = useCallback(() => {const asks = asksRef.current;const bids = bidsRef.current;-- const askList = Object.entries(asks)- .map(([p, q]) => [parseFloat(p), q] as [number, number])- .sort((a, b) => a[0] - b[0])- .slice(0, NUM_LEVELS);-- const bidList = Object.entries(bids)- .map(([p, q]) => [parseFloat(p), q] as [number, number])- .sort((a, b) => b[0] - a[0])- .slice(0, NUM_LEVELS);-- // Calculate totals and max for depth visualization- const askTotal = askList.reduce((sum, [, q]) => sum + q, 0);- const bidTotal = bidList.reduce((sum, [, q]) => sum + q, 0);- const maxTotal = Math.max(askTotal, bidTotal) || 1;-- // Calculate cumulative depths- let askCumulative = 0;- const askWithCumulative = askList.map(([p, q]) => {- askCumulative += q;- return [p, q, askCumulative] as [number, number, number];+ const levels: { price: number; bidQty: number; askQty: number; total: number }[] = [];++ Object.entries(bids).forEach(([p, q]) => levels.push({ price: parseFloat(p), bidQty: q, askQty: 0, total: q }));+ Object.entries(asks).forEach(([p, q]) => {+ const price = parseFloat(p);+ const existing = levels.find(l => l.price === price);+ if (existing) { existing.askQty = q; existing.total += q; }+ else levels.push({ price, bidQty: 0, askQty: q, total: q });});- let bidCumulative = 0;- const bidWithCumulative = bidList.map(([p, q]) => {- bidCumulative += q;- return [p, q, bidCumulative] as [number, number, number];- });+ levels.sort((a, b) => b.price - a.price);++ if (levels.length === 0) {+ container.innerHTML = `<div style="display:flex;align-items:center;justify-content:center;height:100%;color:${FINCEPT.GRAY};font-size:11px;">Waiting for order book data...</div>`;+ return;+ }++ const maxTotal = Math.max(...levels.map(l => l.total));+ const poc = levels.reduce((max, l) => l.total > max.total ? l : max, levels[0]);- // Render asks (reversed so best ask at bottom, near spread)- if (asksContainerRef.current) {- if (askWithCumulative.length === 0) {- asksContainerRef.current.innerHTML = `- <div style="display:flex;align-items:center;justify-content:center;height:100%;color:#666;font-size:10px;">- Waiting for ask data...+ container.innerHTML = `+ <div style="padding:8px 10px;display:flex;justify-content:space-between;border-bottom:1px solid ${FINCEPT.BORDER};font-size:9px;font-family:monospace;">+ <span style="color:${FINCEPT.ORANGE};font-weight:700;">VOLUME BY PRICE (LIVE)</span>+ <span style="color:${FINCEPT.GRAY};">POC: <span style="color:${FINCEPT.CYAN};font-weight:700;">${formatPrice(poc.price)}</span></span>+ </div>+ <div style="padding:6px 10px;display:flex;gap:16px;border-bottom:1px solid ${FINCEPT.BORDER};font-size:10px;font-family:monospace;background:#0A0A0A;">+ <div><span style="color:${FINCEPT.GRAY};font-size:8px;">LEVELS</span><br/><span style="color:${FINCEPT.CYAN};font-weight:700;">${levels.length}</span></div>+ <div><span style="color:${FINCEPT.GRAY};font-size:8px;">MAX VOL</span><br/><span style="color:${FINCEPT.PURPLE};font-weight:700;">${formatQty(maxTotal)}</span></div>+ <div><span style="color:${FINCEPT.GRAY};font-size:8px;">POC VOL</span><br/><span style="color:${FINCEPT.ORANGE};font-weight:700;">${formatQty(poc.total)}</span></div>+ </div>+ <div style="padding:4px 10px;display:grid;grid-template-columns:80px 1fr 60px;font-size:8px;color:${FINCEPT.GRAY};text-transform:uppercase;letter-spacing:0.5px;border-bottom:1px solid ${FINCEPT.BORDER};">+ <span>Price</span><span style="text-align:center;">Volume</span><span style="text-align:right;">Size</span>+ </div>+ ${levels.slice(0, 25).map(l => {+ const bidPct = maxTotal > 0 ? (l.bidQty / maxTotal) * 100 : 0;+ const askPct = maxTotal > 0 ? (l.askQty / maxTotal) * 100 : 0;+ const isPOC = l.price === poc.price;+ const priceColor = l.bidQty > 0 && l.askQty === 0 ? FINCEPT.GREEN : l.askQty > 0 && l.bidQty === 0 ? FINCEPT.RED : FINCEPT.WHITE;+ return `<div style="display:grid;grid-template-columns:80px 1fr 60px;padding:2px 10px;font-size:10px;font-family:monospace;align-items:center;height:20px;${isPOC ? `background:rgba(0,229,255,0.08);border-left:2px solid ${FINCEPT.CYAN};` : ''}">+ <span style="color:${priceColor};font-weight:${isPOC ? 700 : 500};">${formatPrice(l.price)}</span>+ <div style="display:flex;height:12px;gap:1px;">+ <div style="width:${bidPct}%;background:${FINCEPT.GREEN};border-radius:1px;opacity:0.7;"></div>+ <div style="width:${askPct}%;background:${FINCEPT.RED};border-radius:1px;opacity:0.7;"></div>+ </div>+ <span style="text-align:right;color:${FINCEPT.GRAY};font-size:9px;">${formatQty(l.total)}</span></div>`;- } else {- asksContainerRef.current.innerHTML = [...askWithCumulative].reverse().map(([price, qty, cumulative]) => `- <div class="ob-row">- <div class="ob-depth ob-depth-ask" style="width:${(cumulative / maxTotal) * 100}%"></div>- <span class="ob-price ask">${formatPrice(price)}</span>- <span class="ob-qty">${formatQty(qty)}</span>- <span class="ob-total">${formatQty(cumulative)}</span>+ }).join('')}+ <div style="display:flex;justify-content:center;gap:16px;padding:8px;font-size:9px;font-family:monospace;border-top:1px solid ${FINCEPT.BORDER};">+ <span style="display:flex;align-items:center;gap:4px;"><span style="width:8px;height:8px;background:${FINCEPT.GREEN};display:inline-block;"></span><span style="color:${FINCEPT.WHITE};">BID</span></span>+ <span style="display:flex;align-items:center;gap:4px;"><span style="width:8px;height:8px;background:${FINCEPT.RED};display:inline-block;"></span><span style="color:${FINCEPT.WHITE};">ASK</span></span>+ <span style="display:flex;align-items:center;gap:4px;"><span style="width:8px;height:8px;background:${FINCEPT.CYAN};display:inline-block;"></span><span style="color:${FINCEPT.WHITE};">POC</span></span>+ </div>`;+ }, []);++ // Signals view (only rebuild signal list when count changes)+ const renderSignalsView = useCallback(() => {+ const history = tickHistoryRef.current;+ const signals = signalHistoryRef.current;+ if (history.length === 0) return;++ const latest = history[history.length - 1];+ const imb = latest.imbalance;+ const rise = latest.riseRatio60;++ let currentSignal: 'BUY' | 'SELL' | 'NEUTRAL' = 'NEUTRAL';+ if (imb > IMBALANCE_BUY_THRESHOLD && rise > RISE_BUY_THRESHOLD) currentSignal = 'BUY';+ else if (imb < IMBALANCE_SELL_THRESHOLD && rise < RISE_SELL_THRESHOLD) currentSignal = 'SELL';++ const signalColor = currentSignal === 'BUY' ? FINCEPT.GREEN : currentSignal === 'SELL' ? FINCEPT.RED : FINCEPT.GRAY;+ const pnl = cumulativePnlRef.current;++ if (signalIndicatorRef.current) {+ signalIndicatorRef.current.innerHTML = `+ <div style="text-align:center;padding:16px;">+ <div style="font-size:9px;color:${FINCEPT.GRAY};letter-spacing:1px;margin-bottom:6px;">CURRENT SIGNAL</div>+ <div style="font-size:28px;font-weight:700;color:${signalColor};font-family:monospace;text-shadow:0 0 20px ${signalColor}40;">${currentSignal}</div>+ <div style="margin-top:8px;display:flex;justify-content:center;gap:20px;font-size:10px;font-family:monospace;">+ <div><span style="color:${FINCEPT.GRAY};">IMB: </span><span style="color:${imb > 0 ? FINCEPT.GREEN : imb < 0 ? FINCEPT.RED : FINCEPT.WHITE};font-weight:600;">${imb.toFixed(4)}</span></div>+ <div><span style="color:${FINCEPT.GRAY};">RISE: </span><span style="color:${rise > 0 ? FINCEPT.GREEN : rise < 0 ? FINCEPT.RED : FINCEPT.WHITE};font-weight:600;">${rise.toFixed(4)}%</span></div></div>- `).join('');- }+ </div>+ <div style="display:flex;justify-content:space-around;padding:8px 12px;border-top:1px solid ${FINCEPT.BORDER};border-bottom:1px solid ${FINCEPT.BORDER};background:#0A0A0A;">+ <div style="text-align:center;">+ <div style="font-size:8px;color:${FINCEPT.GRAY};letter-spacing:0.5px;">P&L (PAPER)</div>+ <div style="font-size:14px;font-weight:700;color:${pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED};font-family:monospace;">${pnl >= 0 ? '+' : ''}${formatPrice(pnl)}</div>+ </div>+ <div style="text-align:center;">+ <div style="font-size:8px;color:${FINCEPT.GRAY};letter-spacing:0.5px;">SIGNALS</div>+ <div style="font-size:14px;font-weight:700;color:${FINCEPT.CYAN};font-family:monospace;">${signals.length}</div>+ </div>+ <div style="text-align:center;">+ <div style="font-size:8px;color:${FINCEPT.GRAY};letter-spacing:0.5px;">TICKS</div>+ <div style="font-size:14px;font-weight:700;color:${FINCEPT.WHITE};font-family:monospace;">${history.length}</div>+ </div>+ </div>`;}- // Render bids (best bid at top, near spread)- if (bidsContainerRef.current) {- if (bidWithCumulative.length === 0) {- bidsContainerRef.current.innerHTML = `- <div style="display:flex;align-items:center;justify-content:center;height:100%;color:#666;font-size:10px;">- Waiting for bid data...- </div>`;+ // Only rebuild signal list when new signals appear+ if (signalHistoryContainerRef.current && signals.length !== lastSignalRenderCountRef.current) {+ lastSignalRenderCountRef.current = signals.length;+ const recent = signals.slice(-30).reverse();+ if (recent.length === 0) {+ signalHistoryContainerRef.current.innerHTML = `<div style="display:flex;align-items:center;justify-content:center;height:100%;color:${FINCEPT.GRAY};font-size:10px;font-family:monospace;">Waiting for signals...</div>`;} else {- bidsContainerRef.current.innerHTML = bidWithCumulative.map(([price, qty, cumulative]) => `- <div class="ob-row">- <div class="ob-depth ob-depth-bid" style="width:${(cumulative / maxTotal) * 100}%"></div>- <span class="ob-price bid">${formatPrice(price)}</span>- <span class="ob-qty">${formatQty(qty)}</span>- <span class="ob-total">${formatQty(cumulative)}</span>+ signalHistoryContainerRef.current.innerHTML = `+ <div style="display:grid;grid-template-columns:65px 50px 70px 70px 1fr;padding:4px 8px;font-size:8px;color:${FINCEPT.GRAY};text-transform:uppercase;letter-spacing:0.3px;border-bottom:1px solid ${FINCEPT.BORDER};">+ <span>Time</span><span>Signal</span><span style="text-align:right;">Imbalance</span><span style="text-align:right;">Rise %</span><span style="text-align:right;">Price</span></div>- `).join('');+ ${recent.map(s => {+ const time = new Date(s.timestamp).toLocaleTimeString();+ const sc = s.direction === 'BUY' ? FINCEPT.GREEN : FINCEPT.RED;+ return `<div style="display:grid;grid-template-columns:65px 50px 70px 70px 1fr;padding:3px 8px;font-size:10px;font-family:monospace;border-bottom:1px solid #1A1A1A;">+ <span style="color:${FINCEPT.GRAY};">${time}</span>+ <span style="color:${sc};font-weight:700;">${s.direction}</span>+ <span style="text-align:right;color:${s.imbalance > 0 ? FINCEPT.GREEN : FINCEPT.RED};">${s.imbalance.toFixed(3)}</span>+ <span style="text-align:right;color:${s.riseRatio > 0 ? FINCEPT.GREEN : FINCEPT.RED};">${s.riseRatio.toFixed(3)}</span>+ <span style="text-align:right;color:${FINCEPT.WHITE};">${formatPrice(s.price)}</span>+ </div>`;+ }).join('')}`;}}+ }, []);- // Update spread- if (askList.length > 0 && bidList.length > 0) {- const bestAsk = askList[0][0];- const bestBid = bidList[0][0];- const spread = bestAsk - bestBid;- const spreadPercent = (spread / bestAsk) * 100;-- if (spreadValueRef.current) {- spreadValueRef.current.textContent = formatPrice(spread);- }- if (spreadPercentRef.current) {- spreadPercentRef.current.textContent = `(${spreadPercent.toFixed(3)}%)`;- }- } else {- if (spreadValueRef.current) {- spreadValueRef.current.textContent = '--';+ // Cached time string (avoid toLocaleTimeString on every frame)+ const lastTimeStrRef = useRef('');+ const lastTimeSecRef = useRef(0);++ // Main render loop - rAF throttled, only renders active view+ const renderFrame = useCallback(() => {+ if (!dirtyRef.current) return;+ dirtyRef.current = false;++ // Sort both sides once into shared buffers (reused by tick capture + render)+ const askCount = sortInto(asksRef.current, _askSortBuf, true); // ascending+ const bidCount = sortInto(bidsRef.current, _bidSortBuf, false); // descending++ // Capture tick data (throttled internally to 1/sec)+ captureTickSnapshot(askCount, bidCount);++ const view = activeViewRef.current;++ if (view === 'orderbook') {+ const levelsAsk = Math.min(askCount, NUM_LEVELS);+ const levelsBid = Math.min(bidCount, NUM_LEVELS);++ let askTotal = 0;+ for (let i = 0; i < levelsAsk; i++) askTotal += _askSortBuf[i][1];+ let bidTotal = 0;+ for (let i = 0; i < levelsBid; i++) bidTotal += _bidSortBuf[i][1];+ const maxTotal = Math.max(askTotal, bidTotal) || 1;++ const askSizeCache = { w: obCanvasSizeRef.current.aw, h: obCanvasSizeRef.current.ah };+ const bidSizeCache = { w: obCanvasSizeRef.current.bw, h: obCanvasSizeRef.current.bh };+ paintOrderBookCanvas(asksCanvasRef.current, _askSortBuf, askCount, maxTotal, 'ask', true, askSizeCache);+ paintOrderBookCanvas(bidsCanvasRef.current, _bidSortBuf, bidCount, maxTotal, 'bid', false, bidSizeCache);+ obCanvasSizeRef.current.aw = askSizeCache.w;+ obCanvasSizeRef.current.ah = askSizeCache.h;+ obCanvasSizeRef.current.bw = bidSizeCache.w;+ obCanvasSizeRef.current.bh = bidSizeCache.h;++ if (askCount > 0 && bidCount > 0) {+ const bestAsk = _askSortBuf[0][0];+ const bestBid = _bidSortBuf[0][0];+ const spread = bestAsk - bestBid;+ const spreadStr = formatPrice(spread);+ if (spreadValueRef.current && spreadValueRef.current.textContent !== spreadStr) spreadValueRef.current.textContent = spreadStr;+ const spreadPctStr = `(${((spread / bestAsk) * 100).toFixed(3)}%)`;+ if (spreadPercentRef.current && spreadPercentRef.current.textContent !== spreadPctStr) spreadPercentRef.current.textContent = spreadPctStr;}- if (spreadPercentRef.current) {- spreadPercentRef.current.textContent = '';- }- }- // Update totals- if (askTotalRef.current) {- askTotalRef.current.textContent = formatQty(askTotal);- }- if (bidTotalRef.current) {- bidTotalRef.current.textContent = formatQty(bidTotal);- }+ const askTotalStr = formatQty(askTotal);+ if (askTotalRef.current && askTotalRef.current.textContent !== askTotalStr) askTotalRef.current.textContent = askTotalStr;+ const bidTotalStr = formatQty(bidTotal);+ if (bidTotalRef.current && bidTotalRef.current.textContent !== bidTotalStr) bidTotalRef.current.textContent = bidTotalStr;- // Update level count- if (levelCountRef.current) {- levelCountRef.current.textContent = `${Object.keys(asks).length + Object.keys(bids).length}`;+ const totalLvl = `${askCount + bidCount}`;+ if (levelCountRef.current && levelCountRef.current.textContent !== totalLvl) levelCountRef.current.textContent = totalLvl;++ // Time string — update once per second max+ const nowSec = (Date.now() / 1000) | 0;+ if (nowSec !== lastTimeSecRef.current) {+ lastTimeSecRef.current = nowSec;+ lastTimeStrRef.current = new Date().toLocaleTimeString();+ }+ if (updateTimeRef.current && updateTimeRef.current.textContent !== lastTimeStrRef.current) updateTimeRef.current.textContent = lastTimeStrRef.current;+ } else if (view === 'imbalance') {+ renderCanvasCharts();+ } else if (view === 'volume') {+ renderVolumeView();+ } else if (view === 'signals') {+ renderSignalsView();}- // Update time- if (updateTimeRef.current) {- updateTimeRef.current.textContent = new Date().toLocaleTimeString();+ // Update tick count in header+ const tickStr = `${tickHistoryRef.current.length}`;+ if (tickCountRef.current && tickCountRef.current.textContent !== tickStr) tickCountRef.current.textContent = tickStr;+ }, [captureTickSnapshot, paintOrderBookCanvas, renderCanvasCharts, renderVolumeView, renderSignalsView]);++ // Schedule render via rAF (coalesces multiple WS messages into one frame)+ const scheduleRender = useCallback(() => {+ if (!dirtyRef.current) {+ dirtyRef.current = true;+ rafIdRef.current = requestAnimationFrame(renderFrame);}- }, []);+ }, [renderFrame]);const connect = useCallback(() => {- if (wsRef.current) {- wsRef.current.close();- wsRef.current = null;- }+ if (wsRef.current) { wsRef.current.close(); wsRef.current = null; }asksRef.current = {};bidsRef.current = {};- render();+ tickHistoryRef.current = [];+ signalHistoryRef.current = [];+ cumulativePnlRef.current = 0;+ lastSignalPriceRef.current = 0;+ activeSignalRef.current = null;+ lastTickCaptureRef.current = 0;+ lastSignalRenderCountRef.current = 0;if (activeBroker !== 'kraken' || !selectedSymbol) {setStatus('disconnected');@@ -175,328 +710,212 @@ export const CryptoOrderBook = memo(function CryptoOrderBook({}setStatus('connecting');-const ws = new WebSocket('wss://ws.kraken.com/v2');wsRef.current = ws;ws.onopen = () => {setStatus('connected');- ws.send(JSON.stringify({- method: 'subscribe',- params: {- channel: 'book',- symbol: [selectedSymbol],- depth: 25- }- }));+ ws.send(JSON.stringify({ method: 'subscribe', params: { channel: 'book', symbol: [selectedSymbol], depth: 25 } }));};ws.onmessage = (e) => {try {const msg = JSON.parse(e.data);-- if (msg.channel === 'book') {- if (msg.type === 'snapshot') {- asksRef.current = {};- bidsRef.current = {};-- if (msg.data[0].asks && Array.isArray(msg.data[0].asks)) {- msg.data[0].asks.forEach((a: { price: number; qty: number }) => {- asksRef.current[String(a.price)] = a.qty;- });- }-- if (msg.data[0].bids && Array.isArray(msg.data[0].bids)) {- msg.data[0].bids.forEach((b: { price: number; qty: number }) => {- bidsRef.current[String(b.price)] = b.qty;- });- }- render();- } else if (msg.type === 'update') {- if (msg.data[0].asks && Array.isArray(msg.data[0].asks)) {- msg.data[0].asks.forEach((a: { price: number; qty: number }) => {- if (a.qty === 0) {- delete asksRef.current[String(a.price)];- } else {- asksRef.current[String(a.price)] = a.qty;- }- });- }- if (msg.data[0].bids && Array.isArray(msg.data[0].bids)) {- msg.data[0].bids.forEach((b: { price: number; qty: number }) => {- if (b.qty === 0) {- delete bidsRef.current[String(b.price)];- } else {- bidsRef.current[String(b.price)] = b.qty;- }- });- }- render();+ if (msg.channel !== 'book') return;++ if (msg.type === 'snapshot' && msg.data?.[0]) {+ asksRef.current = {};+ bidsRef.current = {};+ const d = msg.data[0];+ if (d.asks) for (const a of d.asks) {+ const p = a.price ?? a[0];+ const q = a.qty ?? a[1];+ if (p != null && q != null) asksRef.current[String(p)] = Number(q);+ }+ if (d.bids) for (const b of d.bids) {+ const p = b.price ?? b[0];+ const q = b.qty ?? b[1];+ if (p != null && q != null) bidsRef.current[String(p)] = Number(q);+ }+ } else if (msg.type === 'update' && msg.data?.[0]) {+ const d = msg.data[0];+ if (d.asks) for (const a of d.asks) {+ const p = a.price ?? a[0];+ const q = a.qty ?? a[1];+ if (p == null) continue;+ if (Number(q) === 0) delete asksRef.current[String(p)];+ else asksRef.current[String(p)] = Number(q);+ }+ if (d.bids) for (const b of d.bids) {+ const p = b.price ?? b[0];+ const q = b.qty ?? b[1];+ if (p == null) continue;+ if (Number(q) === 0) delete bidsRef.current[String(p)];+ else bidsRef.current[String(p)] = Number(q);}}++ scheduleRender();} catch (err) {- // Parse error - silent fail+ console.error('[CryptoOrderBook] WS parse error:', err);}};ws.onclose = () => setStatus('disconnected');- ws.onerror = () => setStatus('disconnected');- }, [activeBroker, selectedSymbol, render]);+ ws.onerror = (err) => {+ console.error('[CryptoOrderBook] WS error:', err);+ setStatus('disconnected');+ };+ }, [activeBroker, selectedSymbol, scheduleRender]);useEffect(() => {connect();return () => {- if (wsRef.current) {- wsRef.current.close();- wsRef.current = null;- }+ if (wsRef.current) { wsRef.current.close(); wsRef.current = null; }+ if (rafIdRef.current) cancelAnimationFrame(rafIdRef.current);};}, [connect]);+ // When switching tabs, force a render of the new view (skip if no data yet)+ const viewSwitchCount = useRef(0);useEffect(() => {- if (priceRef.current) {- priceRef.current.textContent = `$${formatPrice(currentPrice)}`;- }+ viewSwitchCount.current++;+ // Skip the initial mount render — no data yet, will render when WS data arrives+ if (viewSwitchCount.current <= 1 && Object.keys(asksRef.current).length === 0) return;+ dirtyRef.current = true;+ rafIdRef.current = requestAnimationFrame(renderFrame);+ }, [activeView, renderFrame]);++ useEffect(() => {+ if (priceRef.current) priceRef.current.textContent = `$${formatPrice(currentPrice)}`;}, [currentPrice]);return (<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', backgroundColor: FINCEPT.PANEL_BG }}><style>{`- .ob-row {- display: grid;- grid-template-columns: 1fr 1fr 1fr;- padding: 2px 8px;- font-size: 11px;- position: relative;- font-family: "IBM Plex Mono", monospace;- height: 22px;- align-items: center;- }- .ob-row:hover {- background: rgba(255,255,255,0.03);- }- .ob-depth {- position: absolute;- top: 1px;- bottom: 1px;- z-index: 0;- border-radius: 2px;- }- .ob-depth-ask {- background: linear-gradient(90deg, transparent, rgba(239,68,68,0.15));- right: 0;- }- .ob-depth-bid {- background: linear-gradient(270deg, transparent, rgba(34,197,94,0.15));- left: 0;- }- .ob-row span {- position: relative;- z-index: 1;- }- .ob-price {- font-weight: 600;- text-align: left;- }- .ob-price.ask { color: ${FINCEPT.RED}; }- .ob-price.bid { color: ${FINCEPT.GREEN}; }- .ob-qty {- color: ${FINCEPT.WHITE};- text-align: right;- }- .ob-total {- color: ${FINCEPT.GRAY};- text-align: right;- font-size: 10px;- }- .ob-header {- display: grid;- grid-template-columns: 1fr 1fr 1fr;- padding: 4px 8px;- font-size: 9px;- color: ${FINCEPT.GRAY};- border-bottom: 1px solid ${FINCEPT.BORDER};- text-transform: uppercase;- letter-spacing: 0.5px;- }- .ob-header span:nth-child(2),- .ob-header span:nth-child(3) {- text-align: right;- }- .tab-btn {- padding: 6px 12px;- background: transparent;- border: none;- color: ${FINCEPT.GRAY};- cursor: pointer;- font-size: 10px;- font-weight: 600;- letter-spacing: 0.5px;- transition: all 0.15s ease;- border-bottom: 2px solid transparent;- }- .tab-btn:hover {- color: ${FINCEPT.WHITE};- }- .tab-btn.active {- color: ${FINCEPT.ORANGE};- border-bottom-color: ${FINCEPT.ORANGE};- }+ .ob-tab-btn { padding:6px 8px; background:transparent; border:none; color:${FINCEPT.GRAY}; cursor:pointer; font-size:9px; font-weight:600; letter-spacing:0.5px; transition:color 0.15s; border-bottom:2px solid transparent; }+ .ob-tab-btn:hover { color:${FINCEPT.WHITE}; }+ .ob-tab-btn.active { color:${FINCEPT.ORANGE}; border-bottom-color:${FINCEPT.ORANGE}; }+ .ob-scroll::-webkit-scrollbar { width:4px; }+ .ob-scroll::-webkit-scrollbar-track { background:transparent; }+ .ob-scroll::-webkit-scrollbar-thumb { background:${FINCEPT.BORDER}; border-radius:2px; }+ .ob-scroll::-webkit-scrollbar-thumb:hover { background:${FINCEPT.GRAY}; }`}</style>{/* Tab Header */}- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- borderBottom: `1px solid ${FINCEPT.BORDER}`,- backgroundColor: FINCEPT.HEADER_BG,- }}>- <div style={{ display: 'flex' }}>- {(['orderbook', 'volume'] as OrderBookViewType[]).map((view) => (- <button- key={view}- className={`tab-btn ${activeView === view ? 'active' : ''}`}- onClick={() => setActiveView(view)}- >- {view === 'orderbook' ? 'ORDER BOOK' : 'VOLUME'}+ <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', borderBottom:`1px solid ${FINCEPT.BORDER}`, backgroundColor:FINCEPT.HEADER_BG }}>+ <div style={{ display:'flex' }}>+ {(['orderbook','volume','imbalance','signals'] as OrderBookViewType[]).map(v => (+ <button key={v} className={`ob-tab-btn ${activeView === v ? 'active' : ''}`} onClick={() => setActiveView(v)}>+ {{ orderbook:'BOOK', volume:'VOLUME', imbalance:'IMBALANCE', signals:'SIGNALS' }[v]}</button>))}</div>- {activeView === 'orderbook' && (- <div style={{ padding: '0 12px', fontSize: '9px', color: FINCEPT.GRAY }}>- <span ref={levelCountRef}>0</span> levels- </div>- )}+ <div style={{ padding:'0 8px', fontSize:'8px', color:FINCEPT.GRAY, fontFamily:'monospace' }}>+ {activeView === 'orderbook' && <span><span ref={levelCountRef}>0</span> lvl</span>}+ {(activeView === 'imbalance' || activeView === 'signals') && <span><span ref={tickCountRef}>0</span> ticks</span>}+ </div></div>- {/* Order Book Content */}- {activeView === 'orderbook' && (- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>- {/* Connection Status */}- <div style={{- padding: '6px 12px',- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- borderBottom: `1px solid ${FINCEPT.BORDER}`,- backgroundColor: 'rgba(0,0,0,0.2)',- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>- <div style={{- width: '6px',- height: '6px',- borderRadius: '50%',- backgroundColor: status === 'connected' ? FINCEPT.GREEN : status === 'connecting' ? FINCEPT.YELLOW : FINCEPT.RED,- boxShadow: status === 'connected' ? `0 0 6px ${FINCEPT.GREEN}` : 'none',- }} />- <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>- {status === 'connected' ? 'LIVE' : status === 'connecting' ? 'CONNECTING' : 'OFFLINE'}- </span>- </div>- {activeBroker !== 'kraken' && (- <span style={{ fontSize: '9px', color: FINCEPT.YELLOW }}>Select Kraken</span>- )}- <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>- <span ref={updateTimeRef}>--:--:--</span>- </span>+ {/* ORDER BOOK */}+ <div className="ob-scroll" style={{ flex:1, display:activeView === 'orderbook' ? 'flex' : 'none', flexDirection:'column', overflowY:'auto', overflowX:'hidden' }}>+ <div style={{ padding:'6px 12px', display:'flex', alignItems:'center', justifyContent:'space-between', borderBottom:`1px solid ${FINCEPT.BORDER}`, backgroundColor:'rgba(0,0,0,0.2)' }}>+ <div style={{ display:'flex', alignItems:'center', gap:'6px' }}>+ <div style={{ width:'6px', height:'6px', borderRadius:'50%', backgroundColor: status === 'connected' ? FINCEPT.GREEN : status === 'connecting' ? FINCEPT.YELLOW : FINCEPT.RED, boxShadow: status === 'connected' ? `0 0 6px ${FINCEPT.GREEN}` : 'none' }} />+ <span style={{ fontSize:'10px', color:FINCEPT.GRAY }}>{status === 'connected' ? 'LIVE' : status === 'connecting' ? 'CONNECTING' : 'OFFLINE'}</span></div>-- {/* Column Headers */}- <div className="ob-header">+ {activeBroker !== 'kraken' && <span style={{ fontSize:'9px', color:FINCEPT.YELLOW }}>Select Kraken</span>}+ <span style={{ fontSize:'9px', color:FINCEPT.GRAY }}><span ref={updateTimeRef}>--:--:--</span></span>+ </div>+ <div style={{ display:'flex', justifyContent:'space-between', padding:'4px 8px', borderBottom:`1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display:'flex', gap:'12px', fontSize:'9px', color:FINCEPT.GRAY, textTransform:'uppercase', letterSpacing:'0.5px' }}><span>Price</span>+ </div>+ <div style={{ display:'flex', gap:'20px', fontSize:'9px', color:FINCEPT.GRAY, textTransform:'uppercase', letterSpacing:'0.5px' }}><span>Size</span><span>Total</span></div>-- {/* Asks Section */}- <div style={{- flex: 1,- display: 'flex',- flexDirection: 'column',- overflow: 'hidden',- borderBottom: `1px solid ${FINCEPT.BORDER}`,- }}>- <div style={{- padding: '4px 8px',- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- backgroundColor: 'rgba(239,68,68,0.05)',- }}>- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.RED }}>ASKS</span>- <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>- Total: <span ref={askTotalRef} style={{ color: FINCEPT.RED }}>0</span>- </span>- </div>- <div- ref={asksContainerRef}- style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}- />+ </div>+ <div style={{ flex:1, display:'flex', flexDirection:'column', overflow:'hidden', borderBottom:`1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ padding:'4px 8px', display:'flex', justifyContent:'space-between', alignItems:'center', backgroundColor:'rgba(239,68,68,0.05)' }}>+ <span style={{ fontSize:'9px', fontWeight:700, color:FINCEPT.RED }}>ASKS</span>+ <span style={{ fontSize:'9px', color:FINCEPT.GRAY }}>Total: <span ref={askTotalRef} style={{ color:FINCEPT.RED }}>0</span></span></div>-- {/* Spread / Current Price */}- <div style={{- padding: '8px 12px',- backgroundColor: FINCEPT.HEADER_BG,- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- borderBottom: `1px solid ${FINCEPT.BORDER}`,- }}>- <div- ref={priceRef}- style={{- fontSize: '16px',- fontWeight: 700,- color: FINCEPT.YELLOW,- fontFamily: '"IBM Plex Mono", monospace',- }}- >- $0.00- </div>- <div style={{ fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>- <span style={{ color: FINCEPT.GRAY }}>Spread:</span>- <span ref={spreadValueRef} style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>--</span>- <span ref={spreadPercentRef} style={{ color: FINCEPT.YELLOW }}></span>- </div>+ <canvas ref={asksCanvasRef} style={{ flex:1, width:'100%', display:'block', minHeight:`${NUM_LEVELS * 22}px` }} />+ </div>+ <div style={{ padding:'8px 12px', backgroundColor:FINCEPT.HEADER_BG, display:'flex', alignItems:'center', justifyContent:'space-between', borderBottom:`1px solid ${FINCEPT.BORDER}` }}>+ <div ref={priceRef} style={{ fontSize:'16px', fontWeight:700, color:FINCEPT.YELLOW, fontFamily:'"IBM Plex Mono",monospace' }}>$0.00</div>+ <div style={{ fontSize:'10px', display:'flex', alignItems:'center', gap:'4px' }}>+ <span style={{ color:FINCEPT.GRAY }}>Spread:</span>+ <span ref={spreadValueRef} style={{ color:FINCEPT.WHITE, fontWeight:600 }}>--</span>+ <span ref={spreadPercentRef} style={{ color:FINCEPT.YELLOW }}></span></div>+ </div>+ <div style={{ flex:1, display:'flex', flexDirection:'column', overflow:'hidden' }}>+ <div style={{ padding:'4px 8px', display:'flex', justifyContent:'space-between', alignItems:'center', backgroundColor:'rgba(34,197,94,0.05)' }}>+ <span style={{ fontSize:'9px', fontWeight:700, color:FINCEPT.GREEN }}>BIDS</span>+ <span style={{ fontSize:'9px', color:FINCEPT.GRAY }}>Total: <span ref={bidTotalRef} style={{ color:FINCEPT.GREEN }}>0</span></span>+ </div>+ <canvas ref={bidsCanvasRef} style={{ flex:1, width:'100%', display:'block', minHeight:`${NUM_LEVELS * 22}px` }} />+ </div>+ </div>++ {/* VOLUME */}+ <div ref={volumeContainerRef} style={{ flex:1, overflow:'auto', fontFamily:'"IBM Plex Mono",monospace', display:activeView === 'volume' ? 'block' : 'none' }} />- {/* Bids Section */}- <div style={{- flex: 1,- display: 'flex',- flexDirection: 'column',- overflow: 'hidden',- }}>- <div style={{- padding: '4px 8px',- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- backgroundColor: 'rgba(34,197,94,0.05)',- }}>- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GREEN }}>BIDS</span>- <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>- Total: <span ref={bidTotalRef} style={{ color: FINCEPT.GREEN }}>0</span>- </span>+ {/* IMBALANCE */}+ <div style={{ flex:1, display:activeView === 'imbalance' ? 'flex' : 'none', flexDirection:'column', overflow:'hidden' }}>+ <div style={{ display:'flex', gap:'1px', backgroundColor:FINCEPT.BORDER }}>+ <div style={{ flex:1, padding:'8px 10px', backgroundColor:'#0A0A0A', textAlign:'center' }}>+ <div style={{ fontSize:'8px', color:FINCEPT.GRAY, letterSpacing:'0.5px' }}>IMBALANCE</div>+ <div style={{ fontSize:'16px', fontWeight:700, fontFamily:'monospace' }}><span ref={imbalanceValueRef} style={{ color:FINCEPT.WHITE }}>0.0000</span></div>+ </div>+ <div style={{ flex:1, padding:'8px 10px', backgroundColor:'#0A0A0A', textAlign:'center' }}>+ <div style={{ fontSize:'8px', color:FINCEPT.GRAY, letterSpacing:'0.5px' }}>RISE (60s)</div>+ <div style={{ fontSize:'16px', fontWeight:700, fontFamily:'monospace' }}><span ref={riseValueRef} style={{ color:FINCEPT.WHITE }}>0.0000%</span></div>+ </div>+ </div>+ <div style={{ display:'flex', gap:'1px', backgroundColor:FINCEPT.BORDER }}>+ <div style={{ flex:1, padding:'4px 10px', backgroundColor:'#0A0A0A', textAlign:'center' }}>+ <span style={{ fontSize:'8px', color:FINCEPT.GRAY }}>BID VOL: </span>+ <span ref={bidTotalImbalanceRef} style={{ fontSize:'10px', color:FINCEPT.GREEN, fontWeight:600, fontFamily:'monospace' }}>0</span>+ </div>+ <div style={{ flex:1, padding:'4px 10px', backgroundColor:'#0A0A0A', textAlign:'center' }}>+ <span style={{ fontSize:'8px', color:FINCEPT.GRAY }}>ASK VOL: </span>+ <span ref={askTotalImbalanceRef} style={{ fontSize:'10px', color:FINCEPT.RED, fontWeight:600, fontFamily:'monospace' }}>0</span>+ </div>+ </div>+ <div style={{ padding:'6px 10px 2px', borderBottom:`1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'4px' }}>+ <span style={{ fontSize:'9px', color:FINCEPT.ORANGE, fontWeight:700, letterSpacing:'0.5px' }}>DEPTH IMBALANCE</span>+ <span style={{ fontSize:'8px', color:FINCEPT.GRAY }}>(Bid-Ask)/(Bid+Ask)</span>+ </div>+ <canvas ref={imbalanceCanvasRef} style={{ width:'100%', height:'120px', display:'block' }} />+ </div>+ <div style={{ flex:1, padding:'6px 10px 2px' }}>+ <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'4px' }}>+ <span style={{ fontSize:'9px', color:FINCEPT.ORANGE, fontWeight:700, letterSpacing:'0.5px' }}>PRICE MOMENTUM</span>+ <div style={{ display:'flex', gap:'8px', fontSize:'8px' }}>+ <span style={{ color:'rgba(157,78,221,0.7)' }}>30s</span>+ <span style={{ color:FINCEPT.CYAN }}>60s</span>+ <span style={{ color:'rgba(255,136,0,0.7)' }}>5m</span></div>- <div- ref={bidsContainerRef}- style={{ flex: 1, overflow: 'hidden' }}- /></div>+ <canvas ref={riseCanvasRef} style={{ width:'100%', height:'120px', display:'block' }} /></div>- )}-- {/* Volume Profile View */}- {activeView === 'volume' && (- <div style={{ flex: 1, overflow: 'hidden', padding: '8px' }}>- <ErrorBoundary name="VolumeProfile" variant="minimal">- <VolumeProfile symbol={selectedSymbol} height={500} />- </ErrorBoundary>+ </div>++ {/* SIGNALS */}+ <div style={{ flex:1, display:activeView === 'signals' ? 'flex' : 'none', flexDirection:'column', overflow:'hidden' }}>+ <div ref={signalIndicatorRef} style={{ flexShrink:0 }} />+ <div style={{ padding:'6px 10px 4px' }}>+ <span style={{ fontSize:'9px', color:FINCEPT.ORANGE, fontWeight:700, letterSpacing:'0.5px' }}>SIGNAL HISTORY</span></div>- )}+ <div ref={signalHistoryContainerRef} style={{ flex:1, overflow:'auto', fontFamily:'"IBM Plex Mono",monospace' }} />+ <div style={{ padding:'6px 10px', borderTop:`1px solid ${FINCEPT.BORDER}`, fontSize:'8px', color:FINCEPT.GRAY, fontFamily:'monospace', textAlign:'center' }}>+ BUY: imb>{IMBALANCE_BUY_THRESHOLD} & rise>{RISE_BUY_THRESHOLD}% | SELL: imb<{IMBALANCE_SELL_THRESHOLD} & rise<{RISE_SELL_THRESHOLD}%+ </div>+ </div></div>);});diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/DashboardTab.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/DashboardTab.tsxindex 886d8da73..de9a28fa8 100644--- a/fincept-terminal-desktop/src/components/tabs/dashboard/DashboardTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/DashboardTab.tsx@@ -195,7 +195,7 @@ const initialState: State = {containerWidth: 1200,error: null,rightPanelCollapsed: false,- compactMode: false,+ compactMode: true,};function reducer(state: State, action: Action): State {diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/CalendarWidget.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/CalendarWidget.tsxindex ab0925e28..334ed4950 100644--- a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/CalendarWidget.tsx+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/CalendarWidget.tsx@@ -1,7 +1,8 @@-import React, { useState, useEffect } from 'react';+import React from 'react';import { Calendar, ExternalLink } from 'lucide-react';import { BaseWidget } from './BaseWidget';import { useTranslation } from 'react-i18next';+import { useCache } from '@/hooks/useCache';interface CalendarWidgetProps {id: string;@@ -35,6 +36,17 @@ const COUNTRY_FLAGS: Record<string, string> = {NZ: '🇳🇿',};+const DEMO_EVENTS: EconomicEvent[] = [+ { id: '1', time: '08:30', country: 'US', event: 'Initial Jobless Claims', impact: 'high', forecast: '220K', previous: '217K' },+ { id: '2', time: '10:00', country: 'US', event: 'ISM Manufacturing PMI', impact: 'high', forecast: '49.5', previous: '49.3' },+ { id: '3', time: '14:00', country: 'US', event: 'FOMC Meeting Minutes', impact: 'high' },+ { id: '4', time: '02:00', country: 'CN', event: 'Caixin Manufacturing PMI', impact: 'medium', actual: '50.5', forecast: '50.2', previous: '50.3' },+ { id: '5', time: '04:30', country: 'GB', event: 'Construction PMI', impact: 'medium', forecast: '54.0', previous: '53.6' },+ { id: '6', time: '05:00', country: 'EU', event: 'CPI Flash Estimate YoY', impact: 'high', forecast: '2.4%', previous: '2.3%' },+ { id: '7', time: '19:30', country: 'AU', event: 'RBA Interest Rate Decision', impact: 'high', forecast: '4.35%', previous: '4.35%' },+ { id: '8', time: '21:30', country: 'JP', event: 'Tankan Manufacturing Index', impact: 'medium', forecast: '13', previous: '13' },+];+export const CalendarWidget: React.FC<CalendarWidgetProps> = ({id,limit = 6,@@ -42,106 +54,26 @@ export const CalendarWidget: React.FC<CalendarWidgetProps> = ({onNavigate}) => {const { t } = useTranslation('dashboard');- const [events, setEvents] = useState<EconomicEvent[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);-- const loadEvents = async () => {- try {- setLoading(true);- setError(null);+ const {+ data: events,+ isLoading: loading,+ error,+ refresh+ } = useCache<EconomicEvent[]>({+ key: 'widget:economic-calendar',+ category: 'api-response',+ ttl: '5m',+ refetchInterval: 5 * 60 * 1000,+ staleWhileRevalidate: true,+ fetcher: async () => {// Demo economic calendar data// In production, this would fetch from an economic calendar API- const now = new Date();- const demoEvents: EconomicEvent[] = [- {- id: '1',- time: '08:30',- country: 'US',- event: 'Initial Jobless Claims',- impact: 'high',- forecast: '220K',- previous: '217K'- },- {- id: '2',- time: '10:00',- country: 'US',- event: 'ISM Manufacturing PMI',- impact: 'high',- forecast: '49.5',- previous: '49.3'- },- {- id: '3',- time: '14:00',- country: 'US',- event: 'FOMC Meeting Minutes',- impact: 'high'- },- {- id: '4',- time: '02:00',- country: 'CN',- event: 'Caixin Manufacturing PMI',- impact: 'medium',- actual: '50.5',- forecast: '50.2',- previous: '50.3'- },- {- id: '5',- time: '04:30',- country: 'GB',- event: 'Construction PMI',- impact: 'medium',- forecast: '54.0',- previous: '53.6'- },- {- id: '6',- time: '05:00',- country: 'EU',- event: 'CPI Flash Estimate YoY',- impact: 'high',- forecast: '2.4%',- previous: '2.3%'- },- {- id: '7',- time: '19:30',- country: 'AU',- event: 'RBA Interest Rate Decision',- impact: 'high',- forecast: '4.35%',- previous: '4.35%'- },- {- id: '8',- time: '21:30',- country: 'JP',- event: 'Tankan Manufacturing Index',- impact: 'medium',- forecast: '13',- previous: '13'- }- ];-- setEvents(demoEvents);- } catch (err) {- setError('Failed to load calendar');- } finally {- setLoading(false);+ return DEMO_EVENTS;}- };-- useEffect(() => {- loadEvents();- const interval = setInterval(loadEvents, 300000); // Refresh every 5 min- return () => clearInterval(interval);- }, []);+ });+ const displayEvents = events || DEMO_EVENTS;const getImpactColor = (impact: string) => {switch (impact) {@@ -170,9 +102,9 @@ export const CalendarWidget: React.FC<CalendarWidgetProps> = ({id={id}title={`ECONOMIC CALENDAR - ${today.toUpperCase()}`}onRemove={onRemove}- onRefresh={loadEvents}- isLoading={loading}- error={error}+ onRefresh={refresh}+ isLoading={loading && !events}+ error={error?.message || null}headerColor="var(--ft-color-primary)"><div style={{ padding: '4px' }}>@@ -192,7 +124,7 @@ export const CalendarWidget: React.FC<CalendarWidgetProps> = ({<span style={{ textAlign: 'right' }}>{t('widgets.impact')}</span></div>- {events.slice(0, limit).map((event) => (+ {displayEvents.slice(0, limit).map((event) => (<divkey={event.id}style={{@@ -231,7 +163,7 @@ export const CalendarWidget: React.FC<CalendarWidgetProps> = ({</div>))}- {events.length === 0 && !loading && (+ {displayEvents.length === 0 && !loading && (<div style={{ padding: '12px', textAlign: 'center', color: 'var(--ft-color-text-muted)', fontSize: 'var(--ft-font-size-small)' }}><Calendar size={20} style={{ marginBottom: '8px', opacity: 0.5 }} /><div>{t('widgets.noEventsScheduled')}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/EconomicIndicatorsWidget.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/EconomicIndicatorsWidget.tsxindex b693470bd..a0e2138fe 100644--- a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/EconomicIndicatorsWidget.tsx+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/EconomicIndicatorsWidget.tsx@@ -1,8 +1,9 @@-import React, { useState, useEffect } from 'react';+import React from 'react';import { TrendingUp, TrendingDown, ExternalLink } from 'lucide-react';import { BaseWidget } from './BaseWidget';import { invoke } from '@tauri-apps/api/core';import { useTranslation } from 'react-i18next';+import { useCache } from '@/hooks/useCache';interface EconomicIndicatorsWidgetProps {id: string;@@ -18,7 +19,6 @@ interface Indicator {date: string;}-// Key economic indicators with their display infoconst KEY_INDICATORS = [{ code: 'GDP', name: 'US GDP Growth', unit: '%' },@@ -28,100 +28,90 @@ const KEY_INDICATORS = [{ code: 'DGS10', name: '10Y Treasury', unit: '%' },];+const DEMO_INDICATORS: Indicator[] = [+ { name: 'US GDP Growth', code: 'GDP', value: '2.8%', change: 0.3, date: 'Q3 2024' },+ { name: 'Unemployment Rate', code: 'UNRATE', value: '4.1%', change: -0.1, date: 'Dec 2024' },+ { name: 'CPI Inflation', code: 'CPI', value: '3.2%', change: 0.2, date: 'Dec 2024' },+ { name: 'Fed Funds Rate', code: 'FEDFUNDS', value: '5.33%', change: 0, date: 'Jan 2026' },+ { name: '10Y Treasury', code: 'DGS10', value: '4.58%', change: 0.12, date: 'Jan 2026' },+];+export const EconomicIndicatorsWidget: React.FC<EconomicIndicatorsWidgetProps> = ({id,onRemove,onNavigate}) => {const { t } = useTranslation('dashboard');- const [indicators, setIndicators] = useState<Indicator[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);-- const loadIndicators = async () => {- try {- setLoading(true);- setError(null);-- // Try to fetch from FRED API via Tauri- const results: Indicator[] = [];- for (const ind of KEY_INDICATORS) {- try {- const data = await invoke('get_fred_series', {- seriesId: ind.code,- startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],- endDate: new Date().toISOString().split('T')[0]- });-- const parsed = data as any;- if (parsed?.observations?.length > 0) {- const latest = parsed.observations[parsed.observations.length - 1];- const prev = parsed.observations.length > 1- ? parsed.observations[parsed.observations.length - 2]- : latest;+ const {+ data: indicators,+ isLoading: loading,+ error,+ refresh+ } = useCache<Indicator[]>({+ key: 'widget:economic-indicators',+ category: 'api-response',+ ttl: '5m',+ refetchInterval: 5 * 60 * 1000,+ staleWhileRevalidate: true,+ fetcher: async () => {+ try {+ const results: Indicator[] = [];++ for (const ind of KEY_INDICATORS) {+ try {+ const data = await invoke('get_fred_series', {+ seriesId: ind.code,+ startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],+ endDate: new Date().toISOString().split('T')[0]+ });+ const parsed = data as any;+ if (parsed?.observations?.length > 0) {+ const latest = parsed.observations[parsed.observations.length - 1];+ const prev = parsed.observations.length > 1+ ? parsed.observations[parsed.observations.length - 2]+ : latest;++ results.push({+ name: ind.name,+ code: ind.code,+ value: `${parseFloat(latest.value).toFixed(2)}${ind.unit}`,+ change: parseFloat(latest.value) - parseFloat(prev.value),+ date: latest.date+ });+ }+ } catch {results.push({name: ind.name,code: ind.code,- value: `${parseFloat(latest.value).toFixed(2)}${ind.unit}`,- change: parseFloat(latest.value) - parseFloat(prev.value),- date: latest.date+ value: '--',+ change: 0,+ date: '--'});}- } catch (err) {- // Add placeholder if API fails- results.push({- name: ind.name,- code: ind.code,- value: '--',- change: 0,- date: '--'- });}- }- // If no API data, show static demo data- if (results.every(r => r.value === '--')) {- setIndicators([- { name: 'US GDP Growth', code: 'GDP', value: '2.8%', change: 0.3, date: 'Q3 2024' },- { name: 'Unemployment Rate', code: 'UNRATE', value: '4.1%', change: -0.1, date: 'Dec 2024' },- { name: 'CPI Inflation', code: 'CPI', value: '3.2%', change: 0.2, date: 'Dec 2024' },- { name: 'Fed Funds Rate', code: 'FEDFUNDS', value: '5.33%', change: 0, date: 'Jan 2026' },- { name: '10Y Treasury', code: 'DGS10', value: '4.58%', change: 0.12, date: 'Jan 2026' },- ]);- } else {- setIndicators(results);+ if (results.every(r => r.value === '--')) {+ return DEMO_INDICATORS;+ }+ return results;+ } catch {+ return DEMO_INDICATORS;}- } catch (err) {- // Fallback to demo data- setIndicators([- { name: 'US GDP Growth', code: 'GDP', value: '2.8%', change: 0.3, date: 'Q3 2024' },- { name: 'Unemployment Rate', code: 'UNRATE', value: '4.1%', change: -0.1, date: 'Dec 2024' },- { name: 'CPI Inflation', code: 'CPI', value: '3.2%', change: 0.2, date: 'Dec 2024' },- { name: 'Fed Funds Rate', code: 'FEDFUNDS', value: '5.33%', change: 0, date: 'Jan 2026' },- { name: '10Y Treasury', code: 'DGS10', value: '4.58%', change: 0.12, date: 'Jan 2026' },- ]);- } finally {- setLoading(false);}- };-- useEffect(() => {- loadIndicators();- const interval = setInterval(loadIndicators, 300000); // Refresh every 5 minutes- return () => clearInterval(interval);- }, []);+ });+ const displayIndicators = indicators || DEMO_INDICATORS;return (<BaseWidgetid={id}title="ECONOMIC INDICATORS"onRemove={onRemove}- onRefresh={loadIndicators}- isLoading={loading}- error={error}+ onRefresh={refresh}+ isLoading={loading && !indicators}+ error={error?.message || null}headerColor="var(--ft-color-accent)"><div style={{ padding: '4px' }}>@@ -140,7 +130,7 @@ export const EconomicIndicatorsWidget: React.FC<EconomicIndicatorsWidgetProps> =<span style={{ textAlign: 'right' }}>{t('widgets.chg')}</span></div>- {indicators.map((ind) => (+ {displayIndicators.map((ind) => (<divkey={ind.code}style={{diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/ForumWidget.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/ForumWidget.tsxindex e3690a98c..b86185173 100644--- a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/ForumWidget.tsx+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/ForumWidget.tsx@@ -1,9 +1,10 @@-import React, { useState, useEffect, useRef } from 'react';+import React from 'react';import { useTranslation } from 'react-i18next';import { BaseWidget } from './BaseWidget';import { ForumApiService } from '../../../../services/forum/forumApi';import { saveSetting } from '@/services/core/sqliteService';import { useAuth } from '@/contexts/AuthContext';+import { useCache } from '@/hooks/useCache';interface ForumPost {@@ -34,26 +35,30 @@ export const ForumWidget: React.FC<ForumWidgetProps> = ({onNavigateToTab}) => {const { t } = useTranslation('dashboard');- const { session } = useAuth(); // Centralized API key access- const [posts, setPosts] = useState<ForumPost[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const mountedRef = useRef(true);+ const { session } = useAuth();- const loadPosts = async () => {- setLoading(true);- setError(null);- try {- // Use centralized session from AuthContext - automatically updates when key changes+ const targetCategoryId = categoryId || 3;++ const {+ data: posts,+ isLoading: loading,+ error,+ refresh+ } = useCache<ForumPost[]>({+ key: `widget:forum:${targetCategoryId}:${limit}`,+ category: 'api-response',+ ttl: '10m',+ refetchInterval: 10 * 60 * 1000,+ staleWhileRevalidate: true,+ fetcher: async () => {const apiKey = session?.api_key || undefined;const deviceId = session?.device_id || undefined;- const targetCategoryId = categoryId || 3;const response = await ForumApiService.getPostsByCategory(targetCategoryId, 'latest', limit, apiKey, deviceId);if (response.success) {const postsData = (response.data as any)?.data?.posts || (response.data as any)?.posts || [];- const formattedPosts = postsData.map((post: any) => ({+ return postsData.map((post: any) => ({id: post.post_uuid,title: post.title,author: post.author_display_name || 'Anonymous',@@ -62,57 +67,34 @@ export const ForumWidget: React.FC<ForumWidgetProps> = ({replies: post.reply_count || 0,time: new Date(post.created_at).toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' })}));-- setPosts(formattedPosts);- } else {- setError(response.error || `HTTP ${response.status_code || 'error'}`);}- } catch (err) {- setError(err instanceof Error ? err.message : 'Failed to load forum posts');- } finally {- setLoading(false);+ throw new Error(response.error || `HTTP ${response.status_code || 'error'}`);}- };-- // Cleanup on unmount- useEffect(() => {- mountedRef.current = true;- return () => {- mountedRef.current = false;- };- }, []);-- useEffect(() => {- loadPosts();- const interval = setInterval(() => {- if (mountedRef.current) loadPosts();- }, 10 * 60 * 1000); // Refresh every 10 minutes- return () => clearInterval(interval);- }, [categoryId, limit, session?.api_key]); // Re-fetch when API key changes+ });+ const displayPosts = posts || [];return (<BaseWidgetid={id}title={`${t('widgets.forum')} - ${categoryName}`}onRemove={onRemove}- onRefresh={loadPosts}- isLoading={loading}- error={error}+ onRefresh={refresh}+ isLoading={loading && !posts}+ error={error?.message || null}><div style={{ padding: '8px' }}>- {posts.map((post, index) => (+ {displayPosts.map((post, index) => (<divkey={post.id}onClick={async () => {- // PURE SQLite - Save selected post ID to SQLiteawait saveSetting('forum_selected_post_id', post.id, 'forum_widget');onNavigateToTab?.('Forum');}}style={{marginBottom: '8px',paddingBottom: '8px',- borderBottom: index < posts.length - 1 ? '1px solid var(--ft-border-color)' : 'none',+ borderBottom: index < displayPosts.length - 1 ? '1px solid var(--ft-border-color)' : 'none',cursor: 'pointer'}}onMouseEnter={(e) => { e.currentTarget.style.opacity = '0.7'; }}@@ -132,7 +114,7 @@ export const ForumWidget: React.FC<ForumWidgetProps> = ({</div></div>))}- {posts.length === 0 && !loading && !error && (+ {displayPosts.length === 0 && !loading && !error && (<div style={{ color: 'var(--ft-color-text-muted)', fontSize: 'var(--ft-font-size-small)', textAlign: 'center', padding: '12px' }}>{t('widgets.noForumPosts')}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/GeopoliticsWidget.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/GeopoliticsWidget.tsxindex 25ba1225c..1dc1b49ba 100644--- a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/GeopoliticsWidget.tsx+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/GeopoliticsWidget.tsx@@ -1,8 +1,9 @@-import React, { useState, useEffect } from 'react';+import React, { useState, useMemo } from 'react';import { TrendingUp, TrendingDown, ExternalLink } from 'lucide-react';import { BaseWidget } from './BaseWidget';import { geopoliticsService } from '@/services/geopolitics/geopoliticsService';import { useTranslation } from 'react-i18next';+import { useCache } from '@/hooks/useCache';interface GeopoliticsWidgetProps {id: string;@@ -18,6 +19,21 @@ interface ThreatLevel {description: string;}+interface GeopoliticsData {+ threats: ThreatLevel[];+ overallRisk: number;+}++const DEMO_DATA: GeopoliticsData = {+ threats: [+ { category: 'Trade Restrictions', level: 6.5, trend: 'up', description: '23 active restrictions' },+ { category: 'Regulatory Changes', level: 4.2, trend: 'stable', description: '12 pending notifications' },+ { category: 'Tariff Risk', level: 7.1, trend: 'up', description: 'Elevated tariff tensions' },+ { category: 'Supply Chain', level: 5.3, trend: 'stable', description: 'Moderate disruption risk' },+ { category: 'Currency Risk', level: 3.2, trend: 'down', description: 'Stable forex conditions' }+ ],+ overallRisk: 5.3+};export const GeopoliticsWidget: React.FC<GeopoliticsWidgetProps> = ({id,@@ -26,10 +42,6 @@ export const GeopoliticsWidget: React.FC<GeopoliticsWidgetProps> = ({onNavigate}) => {const { t } = useTranslation('dashboard');- const [threats, setThreats] = useState<ThreatLevel[]>([]);- const [overallRisk, setOverallRisk] = useState<number>(0);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);const [selectedCountry, setSelectedCountry] = useState(country);const countries = [@@ -40,73 +52,66 @@ export const GeopoliticsWidget: React.FC<GeopoliticsWidgetProps> = ({{ code: '392', name: 'Japan' },];- const loadGeopoliticsData = async () => {- try {- setLoading(true);- setError(null);+ const {+ data: geoData,+ isLoading: loading,+ error,+ refresh+ } = useCache<GeopoliticsData>({+ key: `widget:geopolitics:${selectedCountry}`,+ category: 'api-response',+ ttl: '5m',+ refetchInterval: 5 * 60 * 1000,+ staleWhileRevalidate: true,+ fetcher: async () => {+ try {+ const data = await geopoliticsService.getComprehensiveGeopoliticsData(selectedCountry);- const data = await geopoliticsService.getComprehensiveGeopoliticsData(selectedCountry);+ const qrCount = data.qrNotifications?.length || 0;+ const epingCount = data.epingNotifications?.length || 0;- // Calculate threat levels from data- const qrCount = data.qrNotifications?.length || 0;- const epingCount = data.epingNotifications?.length || 0;+ const threats: ThreatLevel[] = [+ {+ category: 'Trade Restrictions',+ level: Math.min(qrCount > 0 ? 2 + (qrCount / 50) * 8 : 0, 10),+ trend: qrCount > 5 ? 'up' : 'stable',+ description: `${qrCount} active restrictions`+ },+ {+ category: 'Regulatory Changes',+ level: Math.min(epingCount > 0 ? 2 + (epingCount / 30) * 6 : 1, 10),+ trend: epingCount > 10 ? 'up' : 'stable',+ description: `${epingCount} pending notifications`+ },+ {+ category: 'Tariff Risk',+ level: 5.5,+ trend: 'up',+ description: 'Elevated tariff tensions'+ },+ {+ category: 'Supply Chain',+ level: 4.2,+ trend: 'stable',+ description: 'Moderate disruption risk'+ },+ {+ category: 'Currency Risk',+ level: 3.8,+ trend: 'down',+ description: 'Stable forex conditions'+ }+ ];- const threatData: ThreatLevel[] = [- {- category: 'Trade Restrictions',- level: Math.min(qrCount > 0 ? 2 + (qrCount / 50) * 8 : 0, 10),- trend: qrCount > 5 ? 'up' : 'stable',- description: `${qrCount} active restrictions`- },- {- category: 'Regulatory Changes',- level: Math.min(epingCount > 0 ? 2 + (epingCount / 30) * 6 : 1, 10),- trend: epingCount > 10 ? 'up' : 'stable',- description: `${epingCount} pending notifications`- },- {- category: 'Tariff Risk',- level: 5.5,- trend: 'up',- description: 'Elevated tariff tensions'- },- {- category: 'Supply Chain',- level: 4.2,- trend: 'stable',- description: 'Moderate disruption risk'- },- {- category: 'Currency Risk',- level: 3.8,- trend: 'down',- description: 'Stable forex conditions'- }- ];-- setThreats(threatData);- setOverallRisk(threatData.reduce((sum, t) => sum + t.level, 0) / threatData.length);- } catch (err) {- // Demo data on error- setThreats([- { category: 'Trade Restrictions', level: 6.5, trend: 'up', description: '23 active restrictions' },- { category: 'Regulatory Changes', level: 4.2, trend: 'stable', description: '12 pending notifications' },- { category: 'Tariff Risk', level: 7.1, trend: 'up', description: 'Elevated tariff tensions' },- { category: 'Supply Chain', level: 5.3, trend: 'stable', description: 'Moderate disruption risk' },- { category: 'Currency Risk', level: 3.2, trend: 'down', description: 'Stable forex conditions' }- ]);- setOverallRisk(5.3);- } finally {- setLoading(false);+ const overallRisk = threats.reduce((sum, t) => sum + t.level, 0) / threats.length;+ return { threats, overallRisk };+ } catch {+ return DEMO_DATA;+ }}- };-- useEffect(() => {- loadGeopoliticsData();- const interval = setInterval(loadGeopoliticsData, 300000);- return () => clearInterval(interval);- }, [selectedCountry]);+ });+ const { threats, overallRisk } = geoData || DEMO_DATA;const getLevelColor = (level: number) => {if (level >= 7) return 'var(--ft-color-alert)';@@ -138,9 +143,9 @@ export const GeopoliticsWidget: React.FC<GeopoliticsWidgetProps> = ({id={id}title="GEOPOLITICAL RISK MONITOR"onRemove={onRemove}- onRefresh={loadGeopoliticsData}- isLoading={loading}- error={error}+ onRefresh={refresh}+ isLoading={loading && !geoData}+ error={error?.message || null}headerColor="var(--ft-color-purple)"><div style={{ padding: '4px' }}>diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PerformanceWidget.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PerformanceWidget.tsxindex 967655e75..380062b72 100644--- a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PerformanceWidget.tsx+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PerformanceWidget.tsx@@ -1,8 +1,9 @@-import React, { useState, useEffect } from 'react';+import React from 'react';import { TrendingUp, TrendingDown, ExternalLink } from 'lucide-react';import { BaseWidget } from './BaseWidget';import { sqliteService } from '@/services/core/sqliteService';import { useTranslation } from 'react-i18next';+import { useCache } from '@/hooks/useCache';interface PerformanceWidgetProps {id: string;@@ -18,71 +19,69 @@ interface PerformanceData {winRate: number;}+interface PerformanceSummary {+ rows: PerformanceData[];+ totalPnL: number;+}++const DEMO_DATA: PerformanceSummary = {+ rows: [+ { period: 'Today', pnl: 1245.50, pnlPercent: 0.45, trades: 3, winRate: 66.7 },+ { period: 'This Week', pnl: 5230.25, pnlPercent: 1.82, trades: 12, winRate: 58.3 },+ { period: 'This Month', pnl: 15890.00, pnlPercent: 5.43, trades: 45, winRate: 62.2 },+ { period: 'YTD', pnl: 52430.75, pnlPercent: 18.7, trades: 156, winRate: 59.6 },+ { period: 'All Time', pnl: 125430.50, pnlPercent: 25.4, trades: 423, winRate: 57.9 }+ ],+ totalPnL: 125430.50+};+export const PerformanceWidget: React.FC<PerformanceWidgetProps> = ({id,onRemove,onNavigate}) => {const { t } = useTranslation('dashboard');- const [performance, setPerformance] = useState<PerformanceData[]>([]);- const [totalPnL, setTotalPnL] = useState<number>(0);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const loadPerformance = async () => {- try {- setLoading(true);- setError(null);+ const {+ data: perfData,+ isLoading: loading,+ error,+ refresh+ } = useCache<PerformanceSummary>({+ key: 'widget:performance-tracker',+ category: 'portfolio',+ ttl: '1m',+ refetchInterval: 60 * 1000,+ staleWhileRevalidate: true,+ fetcher: async () => {+ try {+ const portfolios = await sqliteService.listPortfolios();- // Try to load real portfolio performance- const portfolios = await sqliteService.listPortfolios();+ if (portfolios && portfolios.length > 0) {+ const portfolio = portfolios[0] as any;+ const gain = portfolio?.total_pnl || portfolio?.totalPnL || 0;+ const initialBalance = portfolio?.initial_balance || 100000;+ const gainPercent = initialBalance > 0 ? (gain / initialBalance) * 100 : 0;- if (portfolios && portfolios.length > 0) {- const portfolio = portfolios[0] as any;- const gain = portfolio?.total_pnl || portfolio?.totalPnL || 0;-- const initialBalance = portfolio?.initial_balance || 100000;- const gainPercent = initialBalance > 0 ? (gain / initialBalance) * 100 : 0;-- setPerformance([- { period: 'Today', pnl: gain * 0.02, pnlPercent: gainPercent * 0.02, trades: 3, winRate: 66.7 },- { period: 'This Week', pnl: gain * 0.08, pnlPercent: gainPercent * 0.08, trades: 12, winRate: 58.3 },- { period: 'This Month', pnl: gain * 0.25, pnlPercent: gainPercent * 0.25, trades: 45, winRate: 62.2 },- { period: 'YTD', pnl: gain * 0.85, pnlPercent: gainPercent * 0.85, trades: 156, winRate: 59.6 },- { period: 'All Time', pnl: gain, pnlPercent: gainPercent, trades: 423, winRate: 57.9 }- ]);- setTotalPnL(gain);- } else {- // Demo data- setPerformance([- { period: 'Today', pnl: 1245.50, pnlPercent: 0.45, trades: 3, winRate: 66.7 },- { period: 'This Week', pnl: 5230.25, pnlPercent: 1.82, trades: 12, winRate: 58.3 },- { period: 'This Month', pnl: 15890.00, pnlPercent: 5.43, trades: 45, winRate: 62.2 },- { period: 'YTD', pnl: 52430.75, pnlPercent: 18.7, trades: 156, winRate: 59.6 },- { period: 'All Time', pnl: 125430.50, pnlPercent: 25.4, trades: 423, winRate: 57.9 }- ]);- setTotalPnL(125430.50);+ return {+ rows: [+ { period: 'Today', pnl: gain * 0.02, pnlPercent: gainPercent * 0.02, trades: 3, winRate: 66.7 },+ { period: 'This Week', pnl: gain * 0.08, pnlPercent: gainPercent * 0.08, trades: 12, winRate: 58.3 },+ { period: 'This Month', pnl: gain * 0.25, pnlPercent: gainPercent * 0.25, trades: 45, winRate: 62.2 },+ { period: 'YTD', pnl: gain * 0.85, pnlPercent: gainPercent * 0.85, trades: 156, winRate: 59.6 },+ { period: 'All Time', pnl: gain, pnlPercent: gainPercent, trades: 423, winRate: 57.9 }+ ],+ totalPnL: gain+ };+ }+ return DEMO_DATA;+ } catch {+ return DEMO_DATA;}- } catch (err) {- // Demo data on error- setPerformance([- { period: 'Today', pnl: 1245.50, pnlPercent: 0.45, trades: 3, winRate: 66.7 },- { period: 'This Week', pnl: 5230.25, pnlPercent: 1.82, trades: 12, winRate: 58.3 },- { period: 'This Month', pnl: 15890.00, pnlPercent: 5.43, trades: 45, winRate: 62.2 },- { period: 'YTD', pnl: 52430.75, pnlPercent: 18.7, trades: 156, winRate: 59.6 },- { period: 'All Time', pnl: 125430.50, pnlPercent: 25.4, trades: 423, winRate: 57.9 }- ]);- setTotalPnL(125430.50);- } finally {- setLoading(false);}- };+ });- useEffect(() => {- loadPerformance();- const interval = setInterval(loadPerformance, 60000);- return () => clearInterval(interval);- }, []);+ const { rows: performance, totalPnL } = perfData || DEMO_DATA;const formatCurrency = (value: number) => {const absValue = Math.abs(value);@@ -100,9 +99,9 @@ export const PerformanceWidget: React.FC<PerformanceWidgetProps> = ({id={id}title={t('widgets.performanceTracker')}onRemove={onRemove}- onRefresh={loadPerformance}- isLoading={loading}- error={error}+ onRefresh={refresh}+ isLoading={loading && !perfData}+ error={error?.message || null}headerColor={totalPnL >= 0 ? 'var(--ft-color-success)' : 'var(--ft-color-alert)'}><div style={{ padding: '4px' }}>@@ -161,7 +160,7 @@ export const PerformanceWidget: React.FC<PerformanceWidgetProps> = ({</div>{/* Performance rows */}- {performance.map((perf, idx) => (+ {performance.map((perf) => (<divkey={perf.period}style={{diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PolymarketWidget.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PolymarketWidget.tsxindex e11bdd272..7d0fc9629 100644--- a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PolymarketWidget.tsx+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PolymarketWidget.tsx@@ -1,8 +1,9 @@-import React, { useState, useEffect } from 'react';+import React from 'react';import { ExternalLink } from 'lucide-react';import { BaseWidget } from './BaseWidget';import polymarketService, { PolymarketMarket } from '@/services/polymarket/polymarketService';import { useTranslation } from 'react-i18next';+import { useCache } from '@/hooks/useCache';interface PolymarketWidgetProps {id: string;@@ -19,30 +20,25 @@ export const PolymarketWidget: React.FC<PolymarketWidgetProps> = ({onNavigate}) => {const { t } = useTranslation('dashboard');- const [markets, setMarkets] = useState<PolymarketMarket[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const loadMarkets = async () => {- try {- setLoading(true);- setError(null);+ const {+ data: markets,+ isLoading: loading,+ error,+ refresh+ } = useCache<PolymarketMarket[]>({+ key: `widget:polymarket:${limit}`,+ category: 'api-response',+ ttl: '1m',+ refetchInterval: 60 * 1000,+ staleWhileRevalidate: true,+ fetcher: async () => {const data = await polymarketService.getMarkets({ limit, active: true });- setMarkets(data || []);- } catch (err) {- setError('Failed to load markets');- console.error('Polymarket widget error:', err);- } finally {- setLoading(false);+ return data || [];}- };-- useEffect(() => {- loadMarkets();- const interval = setInterval(loadMarkets, 60000); // Refresh every minute- return () => clearInterval(interval);- }, [limit]);+ });+ const displayMarkets = markets || [];const formatVolume = (volume: number) => {if (volume >= 1000000) return `$${(volume / 1000000).toFixed(1)}M`;@@ -55,13 +51,13 @@ export const PolymarketWidget: React.FC<PolymarketWidgetProps> = ({id={id}title="POLYMARKET - TOP MARKETS"onRemove={onRemove}- onRefresh={loadMarkets}- isLoading={loading}- error={error}+ onRefresh={refresh}+ isLoading={loading && !markets}+ error={error?.message || null}headerColor="var(--ft-color-purple)"><div style={{ padding: '4px' }}>- {markets.slice(0, limit).map((market, index) => (+ {displayMarkets.slice(0, limit).map((market, index) => (<divkey={market.id || index}style={{@@ -97,7 +93,7 @@ export const PolymarketWidget: React.FC<PolymarketWidgetProps> = ({</div>))}- {markets.length === 0 && !loading && (+ {displayMarkets.length === 0 && !loading && (<div style={{ padding: '12px', textAlign: 'center', color: 'var(--ft-color-text-muted)', fontSize: 'var(--ft-font-size-small)' }}>{t('widgets.noActiveMarkets')}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PortfolioSummaryWidget.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PortfolioSummaryWidget.tsxindex 720deeb2d..9741fd2c6 100644--- a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PortfolioSummaryWidget.tsx+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/PortfolioSummaryWidget.tsx@@ -1,8 +1,9 @@-import React, { useState, useEffect } from 'react';+import React from 'react';import { TrendingUp, TrendingDown, Briefcase, ExternalLink } from 'lucide-react';import { BaseWidget } from './BaseWidget';import { sqliteService } from '@/services/core/sqliteService';import { useTranslation } from 'react-i18next';+import { useCache } from '@/hooks/useCache';interface PortfolioSummaryWidgetProps {id: string;@@ -21,6 +22,11 @@ interface PortfolioData {currency: string;}+interface PortfolioSummary {+ portfolio: PortfolioData | null;+ topPositions: any[];+}+export const PortfolioSummaryWidget: React.FC<PortfolioSummaryWidgetProps> = ({id,portfolioId,@@ -28,82 +34,75 @@ export const PortfolioSummaryWidget: React.FC<PortfolioSummaryWidgetProps> = ({onNavigate}) => {const { t } = useTranslation('dashboard');- const [portfolio, setPortfolio] = useState<PortfolioData | null>(null);- const [topPositions, setTopPositions] = useState<any[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);-- const loadPortfolio = async () => {- try {- setLoading(true);- setError(null);-- // Get portfolios from SQLite- const portfolios = await sqliteService.listPortfolios();-- if (!portfolios || portfolios.length === 0) {- setPortfolio(null);- setTopPositions([]);- return;- }- // Use specified portfolio or first one- const targetPortfolio = portfolioId- ? portfolios.find((p: any) => p.id === portfolioId) || portfolios[0]- : portfolios[0];-- // Get portfolio positions to calculate summary- const positions = await sqliteService.getPortfolioPositions(targetPortfolio.id);-- // Calculate summary from positions- const totalValue = positions?.reduce((sum: number, p: any) => sum + (p.current_value || p.quantity * (p.current_price || p.entry_price || 0)), 0) || 0;- const totalCost = positions?.reduce((sum: number, p: any) => sum + (p.cost_basis || p.quantity * (p.entry_price || 0)), 0) || 0;- const totalGain = totalValue - totalCost;- const gainPercent = totalCost > 0 ? (totalGain / totalCost) * 100 : 0;-- setPortfolio({- name: targetPortfolio.name,- totalValue: totalValue || targetPortfolio.current_balance || 0,- totalCost: totalCost || targetPortfolio.initial_balance || 0,- totalGain: totalGain || (targetPortfolio as any).total_pnl || (targetPortfolio as any).totalPnL || 0,- gainPercent: gainPercent,- positions: positions?.length || 0,- currency: targetPortfolio.currency || 'USD'- });-- // Get top positions- const sorted = (positions || [])- .sort((a: any, b: any) => (b.current_value || 0) - (a.current_value || 0))- .slice(0, 5);- setTopPositions(sorted);-- } catch (err) {- console.error('Portfolio widget error:', err);- // Show demo data on error- setPortfolio({- name: 'Demo Portfolio',- totalValue: 125430.50,- totalCost: 100000,- totalGain: 25430.50,- gainPercent: 25.43,- positions: 8,- currency: 'USD'- });- setTopPositions([- { symbol: 'AAPL', name: 'Apple Inc', current_value: 35000, gain_percent: 32.5 },- { symbol: 'MSFT', name: 'Microsoft', current_value: 28000, gain_percent: 28.1 },- { symbol: 'GOOGL', name: 'Alphabet', current_value: 22000, gain_percent: 18.4 },- ]);- } finally {- setLoading(false);+ const {+ data: summaryData,+ isLoading: loading,+ error,+ refresh+ } = useCache<PortfolioSummary>({+ key: `widget:portfolio-summary:${portfolioId || 'default'}`,+ category: 'portfolio',+ ttl: '1m',+ refetchInterval: 60 * 1000,+ staleWhileRevalidate: true,+ fetcher: async () => {+ try {+ const portfolios = await sqliteService.listPortfolios();++ if (!portfolios || portfolios.length === 0) {+ return { portfolio: null, topPositions: [] };+ }++ const targetPortfolio = portfolioId+ ? portfolios.find((p: any) => p.id === portfolioId) || portfolios[0]+ : portfolios[0];++ const positions = await sqliteService.getPortfolioPositions(targetPortfolio.id);++ const totalValue = positions?.reduce((sum: number, p: any) => sum + (p.current_value || p.quantity * (p.current_price || p.entry_price || 0)), 0) || 0;+ const totalCost = positions?.reduce((sum: number, p: any) => sum + (p.cost_basis || p.quantity * (p.entry_price || 0)), 0) || 0;+ const totalGain = totalValue - totalCost;+ const gainPercent = totalCost > 0 ? (totalGain / totalCost) * 100 : 0;++ const portfolio: PortfolioData = {+ name: targetPortfolio.name,+ totalValue: totalValue || targetPortfolio.current_balance || 0,+ totalCost: totalCost || targetPortfolio.initial_balance || 0,+ totalGain: totalGain || (targetPortfolio as any).total_pnl || (targetPortfolio as any).totalPnL || 0,+ gainPercent,+ positions: positions?.length || 0,+ currency: targetPortfolio.currency || 'USD'+ };++ const sorted = (positions || [])+ .sort((a: any, b: any) => (b.current_value || 0) - (a.current_value || 0))+ .slice(0, 5);++ return { portfolio, topPositions: sorted };+ } catch {+ return {+ portfolio: {+ name: 'Demo Portfolio',+ totalValue: 125430.50,+ totalCost: 100000,+ totalGain: 25430.50,+ gainPercent: 25.43,+ positions: 8,+ currency: 'USD'+ },+ topPositions: [+ { symbol: 'AAPL', name: 'Apple Inc', current_value: 35000, gain_percent: 32.5 },+ { symbol: 'MSFT', name: 'Microsoft', current_value: 28000, gain_percent: 28.1 },+ { symbol: 'GOOGL', name: 'Alphabet', current_value: 22000, gain_percent: 18.4 },+ ]+ };+ }}- };+ });- useEffect(() => {- loadPortfolio();- const interval = setInterval(loadPortfolio, 60000);- return () => clearInterval(interval);- }, [portfolioId]);+ const portfolio = summaryData?.portfolio || null;+ const topPositions = summaryData?.topPositions || [];const formatCurrency = (value: number, currency: string = 'USD') => {return new Intl.NumberFormat('en-US', {@@ -118,9 +117,9 @@ export const PortfolioSummaryWidget: React.FC<PortfolioSummaryWidgetProps> = ({id={id}title={`PORTFOLIO${portfolio ? ` - ${portfolio.name.toUpperCase()}` : ''}`}onRemove={onRemove}- onRefresh={loadPortfolio}- isLoading={loading}- error={error}+ onRefresh={refresh}+ isLoading={loading && !summaryData}+ error={error?.message || null}headerColor="var(--ft-color-info)"><div style={{ padding: '8px' }}>@@ -174,7 +173,7 @@ export const PortfolioSummaryWidget: React.FC<PortfolioSummaryWidgetProps> = ({}}>TOP POSITIONS ({portfolio.positions} total)</div>- {topPositions.map((pos, idx) => (+ {topPositions.map((pos: any) => (<divkey={pos.symbol}style={{diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/WatchlistWidget.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/WatchlistWidget.tsxindex a5caef85b..9f670107a 100644--- a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/WatchlistWidget.tsx+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/WatchlistWidget.tsx@@ -1,7 +1,8 @@-import React, { useState, useEffect } from 'react';+import React from 'react';import { useTranslation } from 'react-i18next';import { BaseWidget } from './BaseWidget';import { watchlistService, WatchlistStockWithQuote } from '../../../../services/core/watchlistService';+import { useCache } from '@/hooks/useCache';interface WatchlistWidgetProps {id: string;@@ -17,35 +18,26 @@ export const WatchlistWidget: React.FC<WatchlistWidgetProps> = ({onRemove}) => {const { t } = useTranslation('dashboard');- const [stocks, setStocks] = useState<WatchlistStockWithQuote[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const loadStocks = async () => {- if (!watchlistId) {- setError(t('widgets.noWatchlistSelected'));- setLoading(false);- return;- }-- setLoading(true);- setError(null);- try {+ const {+ data: stocks,+ isLoading: loading,+ error,+ refresh+ } = useCache<WatchlistStockWithQuote[]>({+ key: `widget:watchlist:${watchlistId || 'none'}`,+ category: 'market-quotes',+ ttl: '10m',+ refetchInterval: 10 * 60 * 1000,+ staleWhileRevalidate: true,+ enabled: !!watchlistId,+ fetcher: async () => {await watchlistService.initialize();- const data = await watchlistService.getWatchlistStocksWithQuotes(watchlistId);- setStocks(data);- } catch (err) {- setError(err instanceof Error ? err.message : 'Failed to load watchlist');- } finally {- setLoading(false);+ return watchlistService.getWatchlistStocksWithQuotes(watchlistId!);}- };+ });- useEffect(() => {- loadStocks();- const interval = setInterval(loadStocks, 10 * 60 * 1000); // Refresh every 10 minutes- return () => clearInterval(interval);- }, [watchlistId]);+ const displayStocks = stocks || [];const formatChange = (value: number) => value >= 0 ? `+${value.toFixed(2)}` : value.toFixed(2);const formatPercent = (value: number) => value >= 0 ? `+${value.toFixed(2)}%` : `${value.toFixed(2)}%`;@@ -55,9 +47,9 @@ export const WatchlistWidget: React.FC<WatchlistWidgetProps> = ({id={id}title={`${t('widgets.watchlist')} - ${watchlistName}`}onRemove={onRemove}- onRefresh={loadStocks}- isLoading={loading}- error={error}+ onRefresh={refresh}+ isLoading={loading && !stocks}+ error={!watchlistId ? t('widgets.noWatchlistSelected') : (error?.message || null)}><div style={{ padding: '4px' }}><div style={{@@ -76,7 +68,7 @@ export const WatchlistWidget: React.FC<WatchlistWidgetProps> = ({<div style={{ textAlign: 'right' }}>{t('widgets.change')}</div><div style={{ textAlign: 'right' }}>{t('widgets.percentChange')}</div></div>- {stocks.map((stock, index) => (+ {displayStocks.map((stock, index) => (<divkey={index}style={{@@ -106,7 +98,7 @@ export const WatchlistWidget: React.FC<WatchlistWidgetProps> = ({</div></div>))}- {stocks.length === 0 && !loading && !error && (+ {displayStocks.length === 0 && !loading && !error && watchlistId && (<div style={{ color: 'var(--ft-color-text-muted)', fontSize: 'var(--ft-font-size-small)', textAlign: 'center', padding: '12px' }}>{t('widgets.noStocksInWatchlist')}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/economics/EconomicsTab.tsx b/fincept-terminal-desktop/src/components/tabs/economics/EconomicsTab.tsxindex 59e751611..1be579a6b 100644--- a/fincept-terminal-desktop/src/components/tabs/economics/EconomicsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/economics/EconomicsTab.tsx@@ -61,6 +61,10 @@ export default function EconomicsTab() {setWtoApiKey,eiaApiKey,setEiaApiKey,+ blsApiKey,+ setBlsApiKey,+ beaApiKey,+ setBeaApiKey,showApiKeyInput,setShowApiKeyInput,apiKeySaving,@@ -89,6 +93,8 @@ export default function EconomicsTab() {switch (source) {case 'wto': return 'https://apiportal.wto.org/';case 'eia': return 'https://www.eia.gov/opendata/register.php';+ case 'bls': return 'https://data.bls.gov/registrationEngine/';+ case 'bea': return 'https://apps.bea.gov/API/signup/';default: return '';}};@@ -98,6 +104,8 @@ export default function EconomicsTab() {switch (dataSource) {case 'wto': return wtoApiKey;case 'eia': return eiaApiKey;+ case 'bls': return blsApiKey;+ case 'bea': return beaApiKey;default: return '';}};@@ -107,6 +115,8 @@ export default function EconomicsTab() {switch (dataSource) {case 'wto': setWtoApiKey(value); break;case 'eia': setEiaApiKey(value); break;+ case 'bls': setBlsApiKey(value); break;+ case 'bea': setBeaApiKey(value); break;}};diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/EconomicsChart.tsx b/fincept-terminal-desktop/src/components/tabs/economics/components/EconomicsChart.tsxdeleted file mode 100644index 85e45c61d..000000000--- a/fincept-terminal-desktop/src/components/tabs/economics/components/EconomicsChart.tsx+++ /dev/null@@ -1,219 +0,0 @@-// EconomicsChart Component - SVG Chart for Economic Data--import React from 'react';-import { FINCEPT, CHART_WIDTH, CHART_HEIGHT } from '../constants';-import type { DataPoint } from '../types';--interface EconomicsChartProps {- data: DataPoint[];- sourceColor: string;- formatValue: (val: number) => string;-}--// Smart date label formatter - creates unique, readable labels-const formatSmartLabel = (date: string, index: number, allDates: string[], totalLabels: number): string => {- const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];-- // Parse date components safely- const year = date.substring(0, 4) || '';- const month = date.length >= 7 ? date.substring(5, 7) : '';- const day = date.length >= 10 ? date.substring(8, 10) : '';-- const monthIdx = month ? parseInt(month, 10) - 1 : -1;- const monthName = monthIdx >= 0 && monthIdx < 12 ? monthNames[monthIdx] : '';- const shortYear = year.substring(2, 4);-- // Determine what level of detail we need based on data span- const firstDate = allDates[0] || '';- const lastDate = allDates[allDates.length - 1] || '';- const firstYear = firstDate.substring(0, 4);- const lastYear = lastDate.substring(0, 4);- const sameYear = firstYear === lastYear;-- // Count unique values at each level- const uniqueYears = new Set(allDates.map(d => d.substring(0, 4))).size;- const uniqueMonths = new Set(allDates.map(d => d.substring(0, 7))).size;-- // If only one year of data, don't repeat the year- if (sameYear && day && monthName) {- // Daily data within same year: "15 Jan"- return `${parseInt(day)} ${monthName}`;- }-- if (uniqueYears <= 2 && monthName && day) {- // Daily data spanning ~2 years: "15 Jan'25"- return `${parseInt(day)} ${monthName}'${shortYear}`;- }-- if (uniqueMonths > uniqueYears * 2 && monthName) {- // Monthly or more frequent data: "Jan'25"- return `${monthName}'${shortYear}`;- }-- // Annual or sparse data: just show year- return year;-};--// Filter data to only show points where value changed (for constant data like Fed rates)-const filterSignificantPoints = (data: DataPoint[]): DataPoint[] => {- if (data.length <= 2) return data;-- const result: DataPoint[] = [];-- // Always include first point- result.push(data[0]);-- for (let i = 1; i < data.length - 1; i++) {- const prev = data[i - 1].value;- const curr = data[i].value;- const next = data[i + 1].value;-- // Include point if value changed from previous OR will change to next- // This keeps the "step" pattern for rate changes- if (curr !== prev || curr !== next) {- result.push(data[i]);- }- }-- // Always include last point- result.push(data[data.length - 1]);-- return result;-};--// Check if data has many repeated values (like Fed rates)-const hasSignificantRepetition = (data: DataPoint[]): boolean => {- if (data.length < 10) return false;-- let sameCount = 0;- for (let i = 1; i < data.length; i++) {- if (data[i].value === data[i - 1].value) {- sameCount++;- }- }-- // If more than 50% of consecutive points are the same, filter them- return sameCount / data.length > 0.5;-};--// Generate evenly distributed label indices with no duplicates-const generateLabelIndices = (- data: DataPoint[],- maxLabels: number-): number[] => {- if (data.length === 0) return [];- if (data.length <= maxLabels) {- return data.map((_, i) => i);- }-- const indices: number[] = [];- const step = (data.length - 1) / (maxLabels - 1);-- for (let i = 0; i < maxLabels; i++) {- const idx = Math.round(i * step);- if (indices.length === 0 || indices[indices.length - 1] !== idx) {- indices.push(idx);- }- }-- // Ensure last point is included- if (indices[indices.length - 1] !== data.length - 1) {- indices.push(data.length - 1);- }-- return indices;-};--export function EconomicsChart({ data: rawData, sourceColor, formatValue }: EconomicsChartProps) {- if (!rawData || rawData.length === 0) return null;-- // Filter out redundant points if data has many repeated values (like Fed rates)- const data = hasSignificantRepetition(rawData) ? filterSignificantPoints(rawData) : rawData;-- const width = CHART_WIDTH;- const height = CHART_HEIGHT;- const padding = { top: 30, right: 40, bottom: 50, left: 80 };- const chartWidth = width - padding.left - padding.right;- const chartHeight = height - padding.top - padding.bottom;-- const values = data.map((d) => d.value);- const minVal = Math.min(...values);- const maxVal = Math.max(...values);- const range = maxVal - minVal || 1;-- const points = data.map((d, i) => {- const x = padding.left + (i / (data.length - 1 || 1)) * chartWidth;- const y = padding.top + chartHeight - ((d.value - minVal) / range) * chartHeight;- return { x, y, data: d };- });-- const pathD = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' ');- const areaD = `${pathD} L ${points[points.length - 1].x} ${padding.top + chartHeight} L ${padding.left} ${padding.top + chartHeight} Z`;-- // Get all dates for label formatting- const allDates = data.map(d => d.date);-- // Calculate how many labels can fit (estimate ~70px per label for horizontal)- const maxLabels = Math.max(2, Math.min(15, Math.floor(chartWidth / 70)));-- // Generate evenly distributed label indices- const labelIndices = generateLabelIndices(data, maxLabels);-- return (- <svg width={width} height={height} style={{ display: 'block', margin: '0 auto', maxWidth: '100%' }}>- <rect width={width} height={height} fill={FINCEPT.PANEL_BG} />-- {/* Horizontal Grid lines */}- {[0, 1, 2, 3, 4, 5].map((i) => {- const y = padding.top + (chartHeight * i) / 5;- const val = maxVal - (range * i) / 5;- return (- <g key={i}>- <line x1={padding.left} y1={y} x2={width - padding.right} y2={y} stroke={FINCEPT.BORDER} strokeDasharray="4,4" />- <text x={padding.left - 12} y={y + 4} textAnchor="end" fill={FINCEPT.WHITE} fontSize="11" fontFamily="monospace">- {formatValue(val)}- </text>- </g>- );- })}-- {/* Vertical grid lines */}- {labelIndices.map((idx) => {- const x = padding.left + (idx / (data.length - 1 || 1)) * chartWidth;- return (- <line key={`vgrid-${idx}`} x1={x} y1={padding.top} x2={x} y2={padding.top + chartHeight} stroke={FINCEPT.BORDER} strokeDasharray="2,4" strokeOpacity="0.5" />- );- })}-- {/* Area fill */}- <path d={areaD} fill={`${sourceColor}25`} />-- {/* Line */}- <path d={pathD} fill="none" stroke={sourceColor} strokeWidth="2.5" />--- {/* X-axis labels - horizontal only */}- {labelIndices.map((idx) => {- const d = data[idx];- const x = padding.left + (idx / (data.length - 1 || 1)) * chartWidth;- const label = formatSmartLabel(d.date, idx, allDates, labelIndices.length);- return (- <text key={`xlabel-${idx}`} x={x} y={height - 15} textAnchor="middle" fill={FINCEPT.WHITE} fontSize="10" fontFamily="monospace">- {label}- </text>- );- })}-- {/* Data points */}- {points.map((p, i) => (- <circle key={i} cx={p.x} cy={p.y} r={data.length > 30 ? 2 : 3} fill={sourceColor} />- ))}-- {/* Axis lines */}- <line x1={padding.left} y1={padding.top + chartHeight} x2={width - padding.right} y2={padding.top + chartHeight} stroke={FINCEPT.BORDER} strokeWidth="1" />- <line x1={padding.left} y1={padding.top} x2={padding.left} y2={padding.top + chartHeight} stroke={FINCEPT.BORDER} strokeWidth="1" />- </svg>- );-}--export default EconomicsChart;diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/StatsBar.tsx b/fincept-terminal-desktop/src/components/tabs/economics/components/StatsBar.tsxdeleted file mode 100644index 8d37676e5..000000000--- a/fincept-terminal-desktop/src/components/tabs/economics/components/StatsBar.tsx+++ /dev/null@@ -1,57 +0,0 @@-// StatsBar Component - Display statistics for economic data--import React from 'react';-import { TrendingUp, TrendingDown } from 'lucide-react';-import { FINCEPT } from '../constants';-import type { ChartStats } from '../types';--interface StatsBarProps {- stats: ChartStats;- sourceColor: string;- formatValue: (val: number) => string;-}--export function StatsBar({ stats, sourceColor, formatValue }: StatsBarProps) {- return (- <div- style={{- padding: '12px 16px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`,- display: 'flex',- gap: '24px',- flexWrap: 'wrap',- }}- >- <div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>LATEST VALUE</div>- <div style={{ fontSize: '18px', fontWeight: 700, color: sourceColor }}>{formatValue(stats.latest)}</div>- </div>- <div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>CHANGE</div>- <div style={{ fontSize: '14px', fontWeight: 700, color: stats.change >= 0 ? FINCEPT.GREEN : FINCEPT.RED, display: 'flex', alignItems: 'center', gap: '4px' }}>- {stats.change >= 0 ? <TrendingUp size={14} /> : <TrendingDown size={14} />}- {stats.change >= 0 ? '+' : ''}{stats.change.toFixed(2)}%- </div>- </div>- <div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>MIN</div>- <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>{formatValue(stats.min)}</div>- </div>- <div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>MAX</div>- <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>{formatValue(stats.max)}</div>- </div>- <div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>AVERAGE</div>- <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>{formatValue(stats.avg)}</div>- </div>- <div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>DATA POINTS</div>- <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>{stats.count}</div>- </div>- </div>- );-}--export default StatsBar;diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/index.ts b/fincept-terminal-desktop/src/components/tabs/economics/components/index.tsindex 503b93c2b..73900d7c9 100644--- a/fincept-terminal-desktop/src/components/tabs/economics/components/index.ts+++ b/fincept-terminal-desktop/src/components/tabs/economics/components/index.ts@@ -1,9 +1,10 @@// Economics Tab Components+// Shared components come from the common charts library.-export { EconomicsChart } from './EconomicsChart';-export { StatsBar } from './StatsBar';-export { DataTable } from './DataTable';+export { DataChart as EconomicsChart } from '@/components/common/charts';+export { StatsBar } from '@/components/common/charts';+export { DataTable } from '@/components/common/charts';+export { DateRangePicker } from '@/components/common/charts';export { ApiKeyPanel } from './ApiKeyPanel';export { CountrySelector } from './CountrySelector';export { IndicatorSelector } from './IndicatorSelector';-export { DateRangePicker } from './DateRangePicker';diff --git a/fincept-terminal-desktop/src/components/tabs/economics/constants.ts b/fincept-terminal-desktop/src/components/tabs/economics/constants.tsindex 39fd3253c..ff790fb25 100644--- a/fincept-terminal-desktop/src/components/tabs/economics/constants.ts+++ b/fincept-terminal-desktop/src/components/tabs/economics/constants.ts@@ -21,10 +21,6 @@ export const FINCEPT = {PURPLE: '#9D4EDD',};-// Chart dimensions-export const CHART_WIDTH = 1200;-export const CHART_HEIGHT = 400;-// Data source configurationsexport const DATA_SOURCES: DataSourceConfig[] = [{ id: 'worldbank', name: 'World Bank', fullName: 'World Bank', description: 'Global development indicators', color: FINCEPT.CYAN, scriptName: 'worldbank_data.py' },@@ -37,6 +33,10 @@ export const DATA_SOURCES: DataSourceConfig[] = [{ id: 'eia', name: 'EIA', fullName: 'Energy Information Administration', description: 'U.S. energy production & prices', color: '#4CAF50', scriptName: 'eia_data.py', requiresApiKey: true, apiKeyName: 'EIA_API_KEY' },{ id: 'adb', name: 'ADB', fullName: 'Asian Development Bank', description: 'Asia-Pacific economic indicators', color: '#0072BC', scriptName: 'adb_data.py' },{ id: 'fed', name: 'Fed', fullName: 'Federal Reserve', description: 'US monetary policy, rates & money supply', color: '#1A5F7A', scriptName: 'federal_reserve_data.py' },+ { id: 'bls', name: 'BLS', fullName: 'Bureau of Labor Statistics', description: 'US labor, prices, employment & productivity', color: '#AB47BC', scriptName: 'bls_data.py', requiresApiKey: true, apiKeyName: 'BLS_API_KEY' },+ { id: 'unesco', name: 'UNESCO', fullName: 'UNESCO Institute for Statistics', description: 'Education, science, culture & demographic data', color: '#00ACC1', scriptName: 'unesco_data.py' },+ { id: 'fiscaldata', name: 'FiscalData', fullName: 'U.S. Treasury FiscalData', description: 'US debt, interest rates, spending & gold reserves', color: '#FFA726', scriptName: 'fiscal_data.py' },+ { id: 'bea', name: 'BEA', fullName: 'Bureau of Economic Analysis', description: 'US GDP, income, spending & national accounts (NIPA)', color: '#E65100', scriptName: 'bea_data.py', requiresApiKey: true, apiKeyName: 'BEA_API_KEY' },];// World Bank indicators@@ -58,20 +58,45 @@ export const WORLDBANK_INDICATORS: Indicator[] = [{ id: 'BX.KLT.DINV.WD.GD.ZS', name: 'Foreign direct investment, net inflows (% of GDP)', category: 'Investment' },];-// BIS indicators+// BIS indicators — mapped to real BIS SDMX dataflow IDs+// Full coverage of all 28 BIS statistical domains (excluding release calendar)export const BIS_INDICATORS: Indicator[] = [- { id: 'CBPOL_D', name: 'Central Bank Policy Rates (Daily)', category: 'Rates' },- { id: 'CBPOL_M', name: 'Central Bank Policy Rates (Monthly)', category: 'Rates' },- { id: 'EER_B', name: 'Effective Exchange Rates (Broad)', category: 'Exchange Rates' },- { id: 'EER_N', name: 'Effective Exchange Rates (Narrow)', category: 'Exchange Rates' },- { id: 'REER_B', name: 'Real Effective Exchange Rates (Broad)', category: 'Exchange Rates' },- { id: 'SPP', name: 'Residential Property Prices', category: 'Property' },- { id: 'CPP', name: 'Commercial Property Prices', category: 'Property' },- { id: 'CREDIT', name: 'Credit to Non-financial Sector', category: 'Credit' },- { id: 'DEBT', name: 'Debt Service Ratios', category: 'Credit' },- { id: 'LBS', name: 'Locational Banking Statistics', category: 'Banking' },- { id: 'CBS', name: 'Consolidated Banking Statistics', category: 'Banking' },- { id: 'DSR', name: 'Debt Service Ratios', category: 'Debt' },+ // Monetary Policy & Interest Rates+ { id: 'WS_CBPOL', name: 'Central Bank Policy Rates', category: 'Rates' },+ { id: 'WS_CBTA', name: 'Central Bank Total Assets', category: 'Rates' },+ // Exchange Rates+ { id: 'WS_EER', name: 'Effective Exchange Rates (Nominal, Broad)', category: 'Exchange Rates' },+ { id: 'WS_XRU', name: 'US Dollar Exchange Rates', category: 'Exchange Rates' },+ // Prices+ { id: 'WS_LONG_CPI', name: 'Consumer Prices (CPI)', category: 'Prices' },+ // Property+ { id: 'WS_SPP', name: 'Selected Residential Property Prices', category: 'Property' },+ { id: 'WS_DPP', name: 'Detailed Residential Property Prices', category: 'Property' },+ { id: 'WS_CPP', name: 'Commercial Property Prices', category: 'Property' },+ // Credit & Debt+ { id: 'WS_TC', name: 'Total Credit to Non-Financial Sector', category: 'Credit' },+ { id: 'WS_CREDIT_GAP', name: 'Credit-to-GDP Gaps', category: 'Credit' },+ { id: 'WS_DSR', name: 'Debt Service Ratios', category: 'Credit' },+ { id: 'WS_GLI', name: 'Global Liquidity Indicators', category: 'Credit' },+ // Debt Securities+ { id: 'WS_DEBT_SEC2_PUB', name: 'International Debt Securities', category: 'Debt Securities' },+ { id: 'WS_NA_SEC_DSS', name: 'Debt Securities Statistics', category: 'Debt Securities' },+ // Banking+ { id: 'WS_LBS_D_PUB', name: 'Locational Banking Statistics', category: 'Banking' },+ { id: 'WS_CBS_PUB', name: 'Consolidated Banking Statistics', category: 'Banking' },+ // Derivatives+ { id: 'WS_OTC_DERIV2', name: 'OTC Derivatives Outstanding', category: 'Derivatives' },+ { id: 'WS_DER_OTC_TOV', name: 'OTC Derivatives Turnover', category: 'Derivatives' },+ { id: 'WS_XTD_DERIV', name: 'Exchange-Traded Derivatives', category: 'Derivatives' },+ // CPMI Payment Statistics+ { id: 'WS_CPMI_MACRO', name: 'CPMI Macro Statistics', category: 'Payments (CPMI)' },+ { id: 'WS_CPMI_CASHLESS', name: 'CPMI Cashless Payments', category: 'Payments (CPMI)' },+ { id: 'WS_CPMI_CT1', name: 'CPMI Comparative Tables Type 1', category: 'Payments (CPMI)' },+ { id: 'WS_CPMI_CT2', name: 'CPMI Comparative Tables Type 2', category: 'Payments (CPMI)' },+ { id: 'WS_CPMI_DEVICES', name: 'CPMI Payment Devices', category: 'Payments (CPMI)' },+ { id: 'WS_CPMI_INSTITUT', name: 'CPMI Institutions', category: 'Payments (CPMI)' },+ { id: 'WS_CPMI_PARTICIP', name: 'CPMI Participants', category: 'Payments (CPMI)' },+ { id: 'WS_CPMI_SYSTEMS', name: 'CPMI Systems', category: 'Payments (CPMI)' },];// IMF indicators@@ -257,6 +282,150 @@ export const FED_INDICATORS: Indicator[] = [{ id: 'market_overview', name: 'Market Overview (Recent)', category: 'Overview' },];+// BLS Indicators (Bureau of Labor Statistics)+// NOTE: Use native BLS series IDs, NOT FRED aliases (e.g. CUSR0000SA0, not CPIAUCSL)+export const BLS_INDICATORS: Indicator[] = [+ // Consumer Price Index+ { id: 'CUSR0000SA0', name: 'CPI All Urban Consumers: All Items (SA)', category: 'CPI' },+ { id: 'CUUR0000SA0', name: 'CPI All Urban Consumers: All Items (NSA)', category: 'CPI' },+ { id: 'CUSR0000SA0L1E', name: 'CPI All Items Less Food & Energy', category: 'CPI' },+ { id: 'CUSR0000SA0E', name: 'CPI Energy', category: 'CPI' },+ { id: 'CUSR0000SAF1', name: 'CPI Food', category: 'CPI' },+ // Employment+ { id: 'CES0000000001', name: 'Total Nonfarm Payrolls', category: 'Employment' },+ { id: 'CES0500000003', name: 'Average Hourly Earnings (Private)', category: 'Employment' },+ { id: 'CES0500000002', name: 'Average Weekly Hours (Private)', category: 'Employment' },+ // Unemployment+ { id: 'LNS14000000', name: 'Unemployment Rate', category: 'Unemployment' },+ { id: 'LNS13000000', name: 'Labor Force Participation Rate', category: 'Unemployment' },+ { id: 'LNS11300000', name: 'Employment-Population Ratio', category: 'Unemployment' },+ // Producer Price Index+ { id: 'WPUFD49104', name: 'PPI Final Demand', category: 'PPI' },+ { id: 'WPUFD49116', name: 'PPI Final Demand Less Foods & Energy', category: 'PPI' },+ // JOLTS+ { id: 'JTS000000000000000JOL', name: 'JOLTS Job Openings', category: 'JOLTS' },+ { id: 'JTS000000000000000HIL', name: 'JOLTS Hires', category: 'JOLTS' },+ { id: 'JTS000000000000000TSL', name: 'JOLTS Total Separations', category: 'JOLTS' },+ { id: 'JTS000000000000000QUL', name: 'JOLTS Quits', category: 'JOLTS' },+ // Productivity+ { id: 'PRS85006092', name: 'Nonfarm Business Labor Productivity', category: 'Productivity' },+ { id: 'PRS85006112', name: 'Nonfarm Business Unit Labor Costs', category: 'Productivity' },+ // Employment Cost Index+ { id: 'CIU1010000000000A', name: 'ECI Total Compensation (Private)', category: 'Wages & Costs' },+ { id: 'CIU2020000000000A', name: 'ECI Wages & Salaries (Private)', category: 'Wages & Costs' },+];++// UNESCO UIS Indicators (UNESCO Institute for Statistics)+// Verified indicator codes from live API: https://api.uis.unesco.org/api/public+// Uses 3-letter ISO country codes (USA, GBR, IND, etc.)+export const UNESCO_INDICATORS: Indicator[] = [+ // Education - Enrollment+ { id: 'GER.1', name: 'Gross Enrolment Ratio, Primary (%)', category: 'Education' },+ { id: 'GER.2T3', name: 'Gross Enrolment Ratio, Secondary (%)', category: 'Education' },+ { id: 'GER.5T8', name: 'Gross Enrolment Ratio, Tertiary (%)', category: 'Education' },+ { id: 'NER.02.CP', name: 'Net Enrolment Rate, Pre-Primary (%)', category: 'Education' },+ // Education - Completion & Survival+ { id: 'CR.MOD.1', name: 'Completion Rate, Primary (%)', category: 'Education' },+ { id: 'CR.MOD.2', name: 'Completion Rate, Lower Secondary (%)', category: 'Education' },+ { id: 'CR.MOD.3', name: 'Completion Rate, Upper Secondary (%)', category: 'Education' },+ { id: 'SR.1.GLAST.CP', name: 'Survival Rate to Last Grade, Primary (%)', category: 'Education' },+ // Education - Out of School+ { id: 'ROFST.1.CP', name: 'Out-of-School Rate, Primary (%)', category: 'Education' },+ // Literacy+ { id: 'LR.AG15T99', name: 'Adult Literacy Rate, 15+ (%)', category: 'Literacy' },+ { id: 'LR.AG15T24', name: 'Youth Literacy Rate, 15-24 (%)', category: 'Literacy' },+ { id: 'LR.AG25T64', name: 'Literacy Rate, 25-64 (%)', category: 'Literacy' },+ // Education Expenditure+ { id: 'XGDP.FSGOV', name: 'Government Education Expenditure (% of GDP)', category: 'Education Spending' },+ { id: 'XGDP.1.FSGOV', name: 'Primary Education Expenditure (% of GDP)', category: 'Education Spending' },+ { id: 'XGDP.5T8.FSGOV', name: 'Tertiary Education Expenditure (% of GDP)', category: 'Education Spending' },+ // Pupil-Teacher Ratio+ { id: 'PTRHC.1.TRAINED', name: 'Pupil-Teacher Ratio, Primary', category: 'Teaching' },+ { id: 'PTRHC.2T3.TRAINED', name: 'Pupil-Teacher Ratio, Secondary', category: 'Teaching' },+ // Science, Technology & Innovation+ { id: 'EXPGDP.TOT', name: 'R&D Expenditure (% of GDP)', category: 'Science & Tech' },+ { id: 'RESDEN.INHAB.TFTE', name: 'Researchers per Million (FTE)', category: 'Science & Tech' },+ { id: 'FRESP.THC', name: 'Female Researchers (% of Total)', category: 'Science & Tech' },+ // Demographics & Economy+ { id: '200101', name: 'Total Population (thousands)', category: 'Demographics' },+ { id: 'NY.GDP.MKTP.CD', name: 'GDP (current US$)', category: 'Economy' },+ { id: 'NY.GDP.MKTP.KD.ZG', name: 'GDP Growth (annual %)', category: 'Economy' },+ { id: 'NY.GDP.PCAP.CD', name: 'GDP per Capita (current US$)', category: 'Economy' },+];++// FiscalData Indicators (U.S. Treasury FiscalData)+// Public API: https://api.fiscaldata.treasury.gov — no API key required+// US-only data source+export const FISCALDATA_INDICATORS: Indicator[] = [+ // Public Debt+ { id: 'total_public_debt', name: 'Total Public Debt Outstanding', category: 'Debt' },+ { id: 'debt_held_public', name: 'Debt Held by the Public', category: 'Debt' },+ { id: 'intragov_holdings', name: 'Intragovernmental Holdings', category: 'Debt' },+ // Average Interest Rates on Treasury Securities+ { id: 'avg_rate_tbills', name: 'Avg Interest Rate - Treasury Bills', category: 'Interest Rates' },+ { id: 'avg_rate_tnotes', name: 'Avg Interest Rate - Treasury Notes', category: 'Interest Rates' },+ { id: 'avg_rate_tbonds', name: 'Avg Interest Rate - Treasury Bonds', category: 'Interest Rates' },+ { id: 'avg_rate_tips', name: 'Avg Interest Rate - TIPS', category: 'Interest Rates' },+ { id: 'avg_rate_frn', name: 'Avg Interest Rate - Floating Rate Notes', category: 'Interest Rates' },+ // Interest Expense+ { id: 'interest_expense_total', name: 'Total Interest Expense (FYTD)', category: 'Interest Expense' },+ { id: 'interest_expense_monthly', name: 'Monthly Interest Expense', category: 'Interest Expense' },+ // Federal Outlays by Function (MTS Table 9)+ { id: 'outlays_health', name: 'Federal Outlays - Health (FYTD)', category: 'Outlays' },+ { id: 'outlays_defense', name: 'Federal Outlays - National Defense (FYTD)', category: 'Outlays' },+ { id: 'outlays_social_security', name: 'Federal Outlays - Social Security (FYTD)', category: 'Outlays' },+ { id: 'outlays_net_interest', name: 'Federal Outlays - Net Interest (FYTD)', category: 'Outlays' },+ { id: 'outlays_education', name: 'Federal Outlays - Education (FYTD)', category: 'Outlays' },+ // Gold Reserve+ { id: 'gold_reserve_total', name: 'U.S. Gold Reserve (Book Value)', category: 'Gold Reserve' },+ { id: 'gold_reserve_ounces', name: 'U.S. Gold Reserve (Troy Ounces)', category: 'Gold Reserve' },+];++// BEA Indicators (Bureau of Economic Analysis - NIPA tables)+// API: https://apps.bea.gov/api/data/ — requires API key (free registration)+// US-only data source, annual frequency+export const BEA_INDICATORS: Indicator[] = [+ // GDP+ { id: 'gdp_growth', name: 'Real GDP Growth (% Change)', category: 'GDP' },+ { id: 'nominal_gdp', name: 'Nominal GDP (Billions $)', category: 'GDP' },+ { id: 'real_gdp', name: 'Real GDP (Chained 2017 $, Billions)', category: 'GDP' },+ { id: 'gdp_deflator', name: 'GDP Price Index', category: 'GDP' },+ { id: 'gdp_price_change', name: 'GDP Price Change (%)', category: 'GDP' },+ { id: 'gdp_per_capita', name: 'GDP per Capita (Current $)', category: 'GDP' },+ // Consumption & Investment+ { id: 'pce', name: 'Personal Consumption Expenditures (Billions $)', category: 'Consumption' },+ { id: 'pce_goods', name: 'PCE Goods (Billions $)', category: 'Consumption' },+ { id: 'pce_services', name: 'PCE Services (Billions $)', category: 'Consumption' },+ { id: 'gross_investment', name: 'Gross Private Domestic Investment (Billions $)', category: 'Investment' },+ { id: 'fixed_investment', name: 'Fixed Investment (Billions $)', category: 'Investment' },+ // Trade+ { id: 'net_exports', name: 'Net Exports (Billions $)', category: 'Trade' },+ { id: 'exports', name: 'Exports of Goods & Services (Billions $)', category: 'Trade' },+ { id: 'imports', name: 'Imports of Goods & Services (Billions $)', category: 'Trade' },+ { id: 'current_account', name: 'Current Account Balance (Billions $)', category: 'Trade' },+ // Income+ { id: 'personal_income', name: 'Personal Income (Billions $)', category: 'Income' },+ { id: 'compensation', name: 'Compensation of Employees (Billions $)', category: 'Income' },+ { id: 'wages_salaries', name: 'Wages and Salaries (Billions $)', category: 'Income' },+ { id: 'disposable_income', name: 'Disposable Personal Income (Billions $)', category: 'Income' },+ { id: 'gdi', name: 'Gross Domestic Income (Billions $)', category: 'Income' },+ // Saving+ { id: 'personal_saving', name: 'Personal Saving (Billions $)', category: 'Saving' },+ { id: 'saving_rate', name: 'Personal Saving Rate (%)', category: 'Saving' },+ { id: 'gross_saving', name: 'Gross Saving (Billions $)', category: 'Saving' },+ { id: 'net_saving', name: 'Net Saving (Billions $)', category: 'Saving' },+ // Inflation+ { id: 'pce_inflation', name: 'PCE Price Index (% Change)', category: 'Inflation' },+ { id: 'core_pce_inflation', name: 'Core PCE Price Index (% Change, ex Food & Energy)', category: 'Inflation' },+ // Government+ { id: 'govt_spending', name: 'Government Spending (Billions $)', category: 'Government' },+ { id: 'federal_spending', name: 'Federal Government Spending (Billions $)', category: 'Government' },+ { id: 'defense_spending', name: 'National Defense Spending (Billions $)', category: 'Government' },+ { id: 'govt_receipts', name: 'Government Current Receipts (Billions $)', category: 'Government' },+ { id: 'personal_taxes', name: 'Personal Current Taxes (Billions $)', category: 'Government' },+ { id: 'corporate_taxes', name: 'Taxes on Corporate Income (Billions $)', category: 'Government' },+];+// EIA Indicators (U.S. Energy Information Administration)export const EIA_INDICATORS: Indicator[] = [// Petroleum Status Report Categories@@ -351,6 +520,10 @@ export const getIndicatorsForSource = (source: DataSource): Indicator[] => {case 'eia': return EIA_INDICATORS;case 'adb': return ADB_INDICATORS;case 'fed': return FED_INDICATORS;+ case 'bls': return BLS_INDICATORS;+ case 'unesco': return UNESCO_INDICATORS;+ case 'fiscaldata': return FISCALDATA_INDICATORS;+ case 'bea': return BEA_INDICATORS;default: return WORLDBANK_INDICATORS;}};@@ -359,7 +532,7 @@ export const getIndicatorsForSource = (source: DataSource): Indicator[] => {export const getDefaultIndicator = (source: DataSource): string => {switch (source) {case 'worldbank': return 'NY.GDP.MKTP.CD';- case 'bis': return 'CBPOL_M';+ case 'bis': return 'WS_CBPOL';case 'imf': return 'NGDP_RPCH';case 'fred': return 'GDP';case 'oecd': return 'GDP';@@ -368,6 +541,10 @@ export const getDefaultIndicator = (source: DataSource): string => {case 'eia': return 'crude_petroleum_stocks';case 'adb': return 'NGDP_XDC';case 'fed': return 'federal_funds_rate';+ case 'bls': return 'CUSR0000SA0';+ case 'unesco': return 'GER.1';+ case 'fiscaldata': return 'total_public_debt';+ case 'bea': return 'gdp_growth';default: return 'NY.GDP.MKTP.CD';}};diff --git a/fincept-terminal-desktop/src/components/tabs/economics/hooks/useEconomicsData.ts b/fincept-terminal-desktop/src/components/tabs/economics/hooks/useEconomicsData.tsindex fa3b55252..925e675a7 100644--- a/fincept-terminal-desktop/src/components/tabs/economics/hooks/useEconomicsData.ts+++ b/fincept-terminal-desktop/src/components/tabs/economics/hooks/useEconomicsData.ts@@ -3,20 +3,25 @@import { useState, useCallback, useEffect } from 'react';import { invoke } from '@tauri-apps/api/core';import { sqliteService } from '@/services/core/sqliteService';+import { getDateFromPreset } from '@/components/common/charts';+import type { DateRangePreset } from '@/components/common/charts';import {COUNTRIES,CFTC_MARKETS,EIA_INDICATORS,ADB_INDICATORS,FED_INDICATORS,+ BLS_INDICATORS,+ UNESCO_INDICATORS,+ FISCALDATA_INDICATORS,+ BEA_INDICATORS,getIndicatorsForSource,getDefaultIndicator,DATA_SOURCES,} from '../constants';import type { DataSource, IndicatorData, DataPoint, ChartStats } from '../types';-// Date range presets for quick selection-export type DateRangePreset = '1M' | '3M' | '6M' | '1Y' | '2Y' | '5Y' | '10Y' | 'ALL';+export type { DateRangePreset };interface UseEconomicsDataReturn {dataSource: DataSource;@@ -42,49 +47,16 @@ interface UseEconomicsDataReturn {setWtoApiKey: (key: string) => void;eiaApiKey: string;setEiaApiKey: (key: string) => void;+ blsApiKey: string;+ setBlsApiKey: (key: string) => void;+ beaApiKey: string;+ setBeaApiKey: (key: string) => void;showApiKeyInput: boolean;setShowApiKeyInput: (show: boolean) => void;apiKeySaving: boolean;saveApiKey: (keyName: string, keyValue: string) => Promise<void>;}-// Helper to calculate date from preset-const getDateFromPreset = (preset: DateRangePreset): { start: string; end: string } => {- const now = new Date();- const end = now.toISOString().split('T')[0];- let start: Date;-- switch (preset) {- case '1M':- start = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());- break;- case '3M':- start = new Date(now.getFullYear(), now.getMonth() - 3, now.getDate());- break;- case '6M':- start = new Date(now.getFullYear(), now.getMonth() - 6, now.getDate());- break;- case '1Y':- start = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());- break;- case '2Y':- start = new Date(now.getFullYear() - 2, now.getMonth(), now.getDate());- break;- case '5Y':- start = new Date(now.getFullYear() - 5, now.getMonth(), now.getDate());- break;- case '10Y':- start = new Date(now.getFullYear() - 10, now.getMonth(), now.getDate());- break;- case 'ALL':- default:- start = new Date(1960, 0, 1); // Start from 1960 for historical data- break;- }-- return { start: start.toISOString().split('T')[0], end };-};-export function useEconomicsData(): UseEconomicsDataReturn {const [dataSource, setDataSourceState] = useState<DataSource>('worldbank');const [selectedCountry, setSelectedCountry] = useState('USA');@@ -110,6 +82,8 @@ export function useEconomicsData(): UseEconomicsDataReturn {// API Keysconst [wtoApiKey, setWtoApiKey] = useState<string>('');const [eiaApiKey, setEiaApiKey] = useState<string>('');+ const [blsApiKey, setBlsApiKey] = useState<string>('');+ const [beaApiKey, setBeaApiKey] = useState<string>('');const [showApiKeyInput, setShowApiKeyInput] = useState(false);const [apiKeySaving, setApiKeySaving] = useState(false);@@ -122,6 +96,12 @@ export function useEconomicsData(): UseEconomicsDataReturn {const eiaKey = await sqliteService.getApiKey('EIA_API_KEY');if (eiaKey) setEiaApiKey(eiaKey);++ const blsKey = await sqliteService.getApiKey('BLS_API_KEY');+ if (blsKey) setBlsApiKey(blsKey);++ const beaKey = await sqliteService.getApiKey('BEA_API_KEY');+ if (beaKey) setBeaApiKey(beaKey);} catch (err) {console.error('Failed to load API keys:', err);}@@ -137,8 +117,8 @@ export function useEconomicsData(): UseEconomicsDataReturn {if (source === 'adb') {// ADB is Asia-Pacific only - default to IndiasetSelectedCountry('IND');- } else if (source === 'fred' || source === 'fed') {- // FRED and Federal Reserve are US-only+ } else if (source === 'fred' || source === 'fed' || source === 'bls' || source === 'fiscaldata' || source === 'bea') {+ // FRED, Federal Reserve, BLS, FiscalData, and BEA are US-onlysetSelectedCountry('USA');}setData(null);@@ -201,6 +181,20 @@ export function useEconomicsData(): UseEconomicsDataReturn {return;}+ if (dataSource === 'bls' && !blsApiKey) {+ setError('BLS API Key required. Get one at https://data.bls.gov/registrationEngine/. Click the key icon to configure.');+ setShowApiKeyInput(true);+ setLoading(false);+ return;+ }++ if (dataSource === 'bea' && !beaApiKey) {+ setError('BEA API Key required. Register free at https://apps.bea.gov/API/signup/. Click the key icon to configure.');+ setShowApiKeyInput(true);+ setLoading(false);+ return;+ }+// Fetch data based on sourceswitch (dataSource) {case 'worldbank':@@ -368,6 +362,44 @@ export function useEconomicsData(): UseEconomicsDataReturn {}break;+ case 'bls':+ // BLS uses series IDs directly, pass start/end years+ result = await invoke('execute_python_script', {+ scriptName: 'bls_data.py',+ args: ['get_series', selectedIndicator, startDate, endDate],+ env: { BLS_API_KEY: blsApiKey },+ }) as string;+ break;++ case 'unesco':+ // UNESCO UIS uses 3-letter ISO country codes and year-based dates+ const unescoStartYear = startDate.substring(0, 4);+ const unescoEndYear = endDate.substring(0, 4);+ result = await invoke('execute_python_script', {+ scriptName: 'unesco_data.py',+ args: ['fetch', selectedIndicator, countryCode, unescoStartYear, unescoEndYear],+ env: {},+ }) as string;+ break;++ case 'fiscaldata':+ // FiscalData is US-only, uses full date range (YYYY-MM-DD)+ result = await invoke('execute_python_script', {+ scriptName: 'fiscal_data.py',+ args: ['fetch', selectedIndicator, startDate, endDate],+ env: {},+ }) as string;+ break;++ case 'bea':+ // BEA is US-only, uses full date range (YYYY-MM-DD), requires API key+ result = await invoke('execute_python_script', {+ scriptName: 'bea_data.py',+ args: ['fetch', selectedIndicator, startDate, endDate],+ env: { BEA_API_KEY: beaApiKey },+ }) as string;+ break;+default:throw new Error('Unknown data source');}@@ -511,6 +543,55 @@ export function useEconomicsData(): UseEconomicsDataReturn {indicatorName = 'Federal Funds Rate';}}+ } else if (dataSource === 'bls') {+ // BLS returns { data: { series_data: [...], metadata: {...} } }+ const blsSeriesData = parsed.data?.series_data || [];+ if (Array.isArray(blsSeriesData) && blsSeriesData.length > 0) {+ rawData = blsSeriesData.map((d: any) => ({+ date: String(d.date || ''),+ value: d.value,+ }));+ const blsIndicator = BLS_INDICATORS.find(i => i.id === selectedIndicator);+ // Use title from API metadata or fall back to our constant+ indicatorName = blsSeriesData[0]?.title || blsIndicator?.name || selectedIndicator;+ countryName = 'United States';+ }+ } else if (dataSource === 'unesco') {+ // UNESCO returns { success, data: [{date, value}], metadata: {indicator_name, country} }+ const unescoData = parsed.data || [];+ if (Array.isArray(unescoData) && unescoData.length > 0) {+ rawData = unescoData.map((d: any) => ({+ date: String(d.date || ''),+ value: d.value,+ }));+ const unescoIndicator = UNESCO_INDICATORS.find(i => i.id === selectedIndicator);+ indicatorName = parsed.metadata?.indicator_name || unescoIndicator?.name || selectedIndicator;+ countryName = country?.name || parsed.metadata?.country || '';+ }+ } else if (dataSource === 'fiscaldata') {+ // FiscalData returns { success, data: [{date, value}], metadata: {indicator_name, country} }+ const fiscalData = parsed.data || [];+ if (Array.isArray(fiscalData) && fiscalData.length > 0) {+ rawData = fiscalData.map((d: any) => ({+ date: String(d.date || ''),+ value: d.value,+ }));+ const fiscalIndicator = FISCALDATA_INDICATORS.find(i => i.id === selectedIndicator);+ indicatorName = parsed.metadata?.indicator_name || fiscalIndicator?.name || selectedIndicator;+ countryName = 'United States';+ }+ } else if (dataSource === 'bea') {+ // BEA returns { success, data: [{date, value}], metadata: {indicator_name, country, source} }+ const beaData = parsed.data || [];+ if (Array.isArray(beaData) && beaData.length > 0) {+ rawData = beaData.map((d: any) => ({+ date: String(d.date || ''),+ value: d.value,+ }));+ const beaIndicator = BEA_INDICATORS.find(i => i.id === selectedIndicator);+ indicatorName = parsed.metadata?.indicator_name || beaIndicator?.name || selectedIndicator;+ countryName = 'United States';+ }} else if (parsed.data && Array.isArray(parsed.data)) {rawData = parsed.data.map((d: any) => ({date: d.date || d.period || d.year || '',@@ -582,7 +663,7 @@ export function useEconomicsData(): UseEconomicsDataReturn {} finally {setLoading(false);}- }, [dataSource, selectedCountry, selectedIndicator, wtoApiKey, eiaApiKey, startDate, endDate]);+ }, [dataSource, selectedCountry, selectedIndicator, wtoApiKey, eiaApiKey, blsApiKey, beaApiKey, startDate, endDate]);// Calculate statsconst stats: ChartStats | null = data && data.data.length > 0 ? (() => {@@ -620,6 +701,10 @@ export function useEconomicsData(): UseEconomicsDataReturn {setWtoApiKey,eiaApiKey,setEiaApiKey,+ blsApiKey,+ setBlsApiKey,+ beaApiKey,+ setBeaApiKey,showApiKeyInput,setShowApiKeyInput,apiKeySaving,diff --git a/fincept-terminal-desktop/src/components/tabs/economics/hooks/useExport.ts b/fincept-terminal-desktop/src/components/tabs/economics/hooks/useExport.tsindex 48de32245..e62ed5325 100644--- a/fincept-terminal-desktop/src/components/tabs/economics/hooks/useExport.ts+++ b/fincept-terminal-desktop/src/components/tabs/economics/hooks/useExport.ts@@ -1,14 +1,13 @@-// useExport Hook - Export chart and data functionality+// useExport Hook - Thin wrapper around the shared export hook+// Adapts IndicatorData shape to the generic DataPoint[] + ExportMeta API-import { useState, useCallback, RefObject } from 'react';-import { save } from '@tauri-apps/plugin-dialog';-import { writeFile } from '@tauri-apps/plugin-fs';-import { FINCEPT, CHART_WIDTH, CHART_HEIGHT } from '../constants';-import type { IndicatorData, SaveNotification, DataSourceConfig } from '../types';+import { useMemo, RefObject } from 'react';+import { useExport as useSharedExport } from '@/components/common/charts';+import type { IndicatorData, DataSourceConfig } from '../types';interface UseExportReturn {- saveNotification: SaveNotification | null;- setSaveNotification: (notification: SaveNotification | null) => void;+ saveNotification: { show: boolean; path: string; type: 'image' | 'csv' } | null;+ setSaveNotification: (notification: { show: boolean; path: string; type: 'image' | 'csv' } | null) => void;exportCSV: () => void;exportImage: () => Promise<void>;}@@ -18,175 +17,15 @@ export function useExport(currentSourceConfig: DataSourceConfig,chartContainerRef: RefObject<HTMLDivElement | null>): UseExportReturn {- const [saveNotification, setSaveNotification] = useState<SaveNotification | null>(null);+ const points = useMemo(() => data?.data ?? null, [data]);- const exportCSV = useCallback(() => {- if (!data || data.data.length === 0) return;+ const meta = useMemo(() => ({+ title: data?.metadata?.indicator_name || data?.indicator || '',+ subtitle: `${data?.metadata?.country_name || data?.country || ''} \u2022 Source: ${data?.metadata?.source || currentSourceConfig.name}`,+ filenameSuffix: `${currentSourceConfig.id}_${data?.indicator || 'data'}_${data?.country || 'all'}`,+ }), [data, currentSourceConfig]);- const csv = [- `# ${data.metadata?.indicator_name || data.indicator}`,- `# Country: ${data.metadata?.country_name || data.country}`,- `# Source: ${data.metadata?.source || currentSourceConfig.name}`,- '',- 'Date,Value',- ...data.data.map((d) => `${d.date},${d.value}`),- ].join('\n');-- const blob = new Blob([csv], { type: 'text/csv' });- const url = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = url;- a.download = `fincept_terminal_${currentSourceConfig.id}_${data.indicator}_${data.country}.csv`;- a.click();- URL.revokeObjectURL(url);- }, [data, currentSourceConfig]);-- const exportImage = useCallback(async () => {- if (!data || data.data.length === 0 || !chartContainerRef.current) return;-- try {- const defaultFileName = `fincept_terminal_${currentSourceConfig.id}_${data.indicator}_${data.country}_4K.png`;- const filePath = await save({- defaultPath: defaultFileName,- filters: [- { name: 'PNG Image', extensions: ['png'] },- { name: 'All Files', extensions: ['*'] },- ],- title: 'Save Chart Image (Ultra HD) - Fincept Terminal',- });-- if (!filePath) return;-- const svgElement = chartContainerRef.current.querySelector('svg');- if (!svgElement) return;-- const clonedSvg = svgElement.cloneNode(true) as SVGElement;- const width = CHART_WIDTH;- const height = CHART_HEIGHT;- const headerHeight = 80;- const footerHeight = 40;- const totalHeight = height + headerHeight + footerHeight;-- // Create wrapper SVG- const wrapperSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');- wrapperSvg.setAttribute('width', String(width));- wrapperSvg.setAttribute('height', String(totalHeight));- wrapperSvg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');-- // Background- const bg = document.createElementNS('http://www.w3.org/2000/svg', 'rect');- bg.setAttribute('width', String(width));- bg.setAttribute('height', String(totalHeight));- bg.setAttribute('fill', FINCEPT.DARK_BG);- wrapperSvg.appendChild(bg);-- // Title- const title = document.createElementNS('http://www.w3.org/2000/svg', 'text');- title.setAttribute('x', '24');- title.setAttribute('y', '35');- title.setAttribute('fill', FINCEPT.WHITE);- title.setAttribute('font-family', 'IBM Plex Mono, monospace');- title.setAttribute('font-size', '22');- title.setAttribute('font-weight', '700');- title.textContent = data.metadata?.indicator_name || data.indicator;- wrapperSvg.appendChild(title);-- // Subtitle- const subtitle = document.createElementNS('http://www.w3.org/2000/svg', 'text');- subtitle.setAttribute('x', '24');- subtitle.setAttribute('y', '60');- subtitle.setAttribute('fill', FINCEPT.GRAY);- subtitle.setAttribute('font-family', 'IBM Plex Mono, monospace');- subtitle.setAttribute('font-size', '14');- subtitle.textContent = `${data.metadata?.country_name || data.country} • Source: ${data.metadata?.source || currentSourceConfig.name}`;- wrapperSvg.appendChild(subtitle);-- // Chart- const chartGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');- chartGroup.setAttribute('transform', `translate(0, ${headerHeight})`);- chartGroup.innerHTML = clonedSvg.innerHTML;- wrapperSvg.appendChild(chartGroup);-- // Footer- const footer = document.createElementNS('http://www.w3.org/2000/svg', 'text');- footer.setAttribute('x', String(width - 24));- footer.setAttribute('y', String(totalHeight - 12));- footer.setAttribute('fill', FINCEPT.MUTED);- footer.setAttribute('font-family', 'IBM Plex Mono, monospace');- footer.setAttribute('font-size', '12');- footer.setAttribute('text-anchor', 'end');- footer.textContent = `Fincept Terminal • ${new Date().toISOString().split('T')[0]}`;- wrapperSvg.appendChild(footer);-- // Watermark - top right corner inside chart area, white color, more visible- const watermark = document.createElementNS('http://www.w3.org/2000/svg', 'text');- watermark.setAttribute('x', String(width - 50));- watermark.setAttribute('y', String(headerHeight + 50));- watermark.setAttribute('fill', `${FINCEPT.WHITE}50`);- watermark.setAttribute('font-family', 'IBM Plex Mono, monospace');- watermark.setAttribute('font-size', '22');- watermark.setAttribute('font-weight', '700');- watermark.setAttribute('text-anchor', 'end');- watermark.textContent = 'FINCEPT TERMINAL';- wrapperSvg.appendChild(watermark);-- // Convert to canvas- const svgData = new XMLSerializer().serializeToString(wrapperSvg);- const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });- const svgUrl = URL.createObjectURL(svgBlob);-- const canvas = document.createElement('canvas');- const ctx = canvas.getContext('2d');- const img = new window.Image();-- img.onload = async () => {- const scale = 4; // Ultra HD- canvas.width = width * scale;- canvas.height = totalHeight * scale;-- if (ctx) {- ctx.imageSmoothingEnabled = true;- ctx.imageSmoothingQuality = 'high';- ctx.scale(scale, scale);- ctx.fillStyle = FINCEPT.DARK_BG;- ctx.fillRect(0, 0, width, totalHeight);- ctx.drawImage(img, 0, 0);-- canvas.toBlob(async (blob) => {- if (blob) {- try {- const arrayBuffer = await blob.arrayBuffer();- const uint8Array = new Uint8Array(arrayBuffer);- await writeFile(filePath, uint8Array);- setSaveNotification({ show: true, path: filePath, type: 'image' });- setTimeout(() => setSaveNotification(null), 5000);- } catch (writeErr) {- console.error('Failed to write image file:', writeErr);- }- }- }, 'image/png');- }-- URL.revokeObjectURL(svgUrl);- };-- img.onerror = () => {- console.error('Failed to load SVG for image export');- URL.revokeObjectURL(svgUrl);- };-- img.src = svgUrl;- } catch (err) {- console.error('Failed to export image:', err);- }- }, [data, currentSourceConfig, chartContainerRef]);-- return {- saveNotification,- setSaveNotification,- exportCSV,- exportImage,- };+ return useSharedExport(points, meta, chartContainerRef);}export default useExport;diff --git a/fincept-terminal-desktop/src/components/tabs/economics/types.ts b/fincept-terminal-desktop/src/components/tabs/economics/types.tsindex d143e1231..3410d9ff4 100644--- a/fincept-terminal-desktop/src/components/tabs/economics/types.ts+++ b/fincept-terminal-desktop/src/components/tabs/economics/types.ts@@ -16,7 +16,7 @@ export interface IndicatorData {};}-export type DataSource = 'worldbank' | 'bis' | 'imf' | 'fred' | 'oecd' | 'wto' | 'cftc' | 'eia' | 'adb' | 'fed';+export type DataSource = 'worldbank' | 'bis' | 'imf' | 'fred' | 'oecd' | 'wto' | 'cftc' | 'eia' | 'adb' | 'fed' | 'bls' | 'unesco' | 'fiscaldata' | 'bea';export interface DataSourceConfig {id: DataSource;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsxindex 900ee89c7..6e6d7c2dd 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx@@ -127,6 +127,14 @@ export function StockTradingChart({setSelectedInterval(initialInterval);}, [initialInterval]);+ // Clear chart data when symbol/exchange changes to prevent stale data flash+ useEffect(() => {+ console.log(`[StockTradingChart] Symbol/exchange changed to ${exchange}:${symbol}, clearing old chart data`);+ setChartData([]);+ setIsLoading(true);+ setError(null);+ }, [symbol, exchange]);+// Fetch historical data with retry for race condition handlingconst fetchHistoricalData = useCallback(async (retryCount = 0) => {const INIT_MAX_RETRIES = 5; // retries for adapter/auth readiness@@ -134,8 +142,11 @@ export function StockTradingChart({const FETCH_MAX_RETRIES = 2; // retries for actual API call failuresconst FETCH_TIMEOUT = 45000; // 45s per attempt (Rust timeout is 15s, plus overhead)+ // Increment fetch ID to prevent stale responses from overwriting current data+ const currentFetchId = ++fetchIdRef.current;+// Comprehensive state logging at start of each attempt- console.log(`[StockTradingChart] ========== fetchHistoricalData attempt ${retryCount + 1}/${INIT_MAX_RETRIES + 1} ==========`);+ console.log(`[StockTradingChart] ========== fetchHistoricalData attempt ${retryCount + 1}/${INIT_MAX_RETRIES + 1} (fetchId=${currentFetchId}) ==========`);console.log(`[StockTradingChart] State:`, {symbol,exchange,@@ -278,6 +289,12 @@ export function StockTradingChart({if (!mountedRef.current) return;+ // Check if this fetch is still the latest one (prevent stale data from overwriting)+ if (currentFetchId !== fetchIdRef.current) {+ console.log(`[StockTradingChart] Discarding stale fetch result (fetchId=${currentFetchId}, current=${fetchIdRef.current})`);+ return;+ }+console.log(`[StockTradingChart] Fetched ${ohlcvData.length} candles from ${adapter.brokerId}`);if (ohlcvData.length === 0) {@@ -534,6 +551,7 @@ export function StockTradingChart({flexDirection: 'column'}}><ProChartWithToolkit+ key={`${exchange}:${symbol}`}data={chartData}symbol={`${exchange}:${symbol}`}showVolume={true}diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/GovDataTab.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/GovDataTab.tsxnew file mode 100644index 000000000..4835b0114--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/GovDataTab.tsx@@ -0,0 +1,184 @@+// GovDataTab - Main Government Data Portals tab+// Renders a provider selector sidebar and the active provider's UI++import React, { useState } from 'react';+import { Landmark } from 'lucide-react';+import { FINCEPT, GOV_PROVIDERS } from './constants';+import type { GovProvider } from './types';+import { USTreasuryProvider } from './providers/USTreasuryProvider';+import { CanadaGovProvider } from './providers/CanadaGovProvider';+import { CongressGovProvider } from './providers/CongressGovProvider';+import { OpenAfricaProvider } from './providers/OpenAfricaProvider';+import { SpainDataProvider } from './providers/SpainDataProvider';+import { PxWebProvider } from './providers/PxWebProvider';+import { SwissGovProvider } from './providers/SwissGovProvider';+import { FrenchGovProvider } from './providers/FrenchGovProvider';+import { UniversalCkanProvider } from './providers/UniversalCkanProvider';++export default function GovDataTab() {+ const [activeProvider, setActiveProvider] = useState<GovProvider>('us-treasury');++ const activeConfig = GOV_PROVIDERS.find(p => p.id === activeProvider) || GOV_PROVIDERS[0];++ const renderProvider = () => {+ switch (activeProvider) {+ case 'us-treasury':+ return <USTreasuryProvider />;+ case 'canada-gov':+ return <CanadaGovProvider />;+ case 'us-congress':+ return <CongressGovProvider />;+ case 'openafrica':+ return <OpenAfricaProvider />;+ case 'spain':+ return <SpainDataProvider />;+ case 'finland-pxweb':+ return <PxWebProvider />;+ case 'swiss':+ return <SwissGovProvider />;+ case 'france':+ return <FrenchGovProvider />;+ case 'universal-ckan':+ return <UniversalCkanProvider />;+ default:+ return (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ color: FINCEPT.GRAY,+ fontSize: '12px',+ }}>+ Provider not implemented yet+ </div>+ );+ }+ };++ return (+ <div+ style={{+ width: '100%',+ height: '100%',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ fontFamily: '"IBM Plex Mono", monospace',+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}+ >+ {/* Header */}+ <div+ style={{+ padding: '10px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `2px solid ${activeConfig.color}`,+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ }}+ >+ <Landmark size={18} color={activeConfig.color} />+ <span style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.WHITE }}>+ GOVT+ </span>+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>|</span>+ <span style={{ fontSize: '12px', fontWeight: 600, color: activeConfig.color }}>+ {activeConfig.flag} {activeConfig.fullName}+ </span>+ </div>++ {/* Main content */}+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>+ {/* Provider sidebar */}+ <div+ style={{+ width: '220px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'auto',+ }}+ >+ <div style={{+ padding: '10px 12px',+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ textTransform: 'uppercase',+ letterSpacing: '1px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ Sovereign Data+ </div>++ {GOV_PROVIDERS.map(provider => (+ <button+ key={provider.id}+ onClick={() => setActiveProvider(provider.id)}+ style={{+ padding: '10px 12px',+ backgroundColor: activeProvider === provider.id ? `${provider.color}15` : 'transparent',+ color: activeProvider === provider.id ? provider.color : FINCEPT.WHITE,+ border: 'none',+ borderLeft: activeProvider === provider.id ? `3px solid ${provider.color}` : '3px solid transparent',+ borderBottom: `1px solid ${FINCEPT.BORDER}08`,+ textAlign: 'left',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ gap: '4px',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ fontSize: '14px' }}>{provider.flag}</span>+ <span style={{ fontSize: '11px', fontWeight: 600 }}>{provider.name}</span>+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, paddingLeft: '22px' }}>+ {provider.description.length > 60+ ? provider.description.substring(0, 60) + '...'+ : provider.description}+ </div>+ </button>+ ))}++ </div>++ {/* Active provider content */}+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>+ {renderProvider()}+ </div>+ </div>++ {/* Status bar */}+ <div+ style={{+ padding: '6px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ fontSize: '9px',+ }}+ >+ <div style={{ display: 'flex', gap: '16px', color: FINCEPT.WHITE }}>+ <span>+ <span style={{ color: FINCEPT.GRAY }}>PORTAL:</span>{' '}+ <span style={{ color: activeConfig.color }}>{activeConfig.name}</span>+ </span>+ <span>+ <span style={{ color: FINCEPT.GRAY }}>COUNTRY:</span> {activeConfig.country}+ </span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <span style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: FINCEPT.GREEN }} />+ <span style={{ color: FINCEPT.GREEN }}>Ready</span>+ </div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/constants.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/constants.tsnew file mode 100644index 000000000..90fde939e--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/constants.ts@@ -0,0 +1,363 @@+// Government Data Tab Constants++import type { GovProviderConfig, GovProvider } from './types';+import { FINCEPT_COLORS } from '@/components/common/charts';++// Re-export shared colors under the local name for backwards-compatibility+export const FINCEPT = FINCEPT_COLORS;++// Provider configurations+export const GOV_PROVIDERS: GovProviderConfig[] = [+ {+ id: 'us-treasury',+ name: 'US Treasury',+ fullName: 'U.S. Department of the Treasury',+ description: 'Treasury securities prices, auctions & market data from TreasuryDirect.gov',+ color: '#3B82F6',+ country: 'United States',+ flag: '\uD83C\uDDFA\uD83C\uDDF8',+ endpoints: [+ {+ id: 'treasury_prices',+ name: 'Treasury Prices',+ description: 'End-of-day prices for all Treasury securities (Bills, Notes, Bonds, TIPS, FRN)',+ command: 'treasury_prices',+ },+ {+ id: 'treasury_auctions',+ name: 'Treasury Auctions',+ description: 'Auction results with bid-to-cover ratios, accepted amounts & pricing',+ command: 'treasury_auctions',+ },+ {+ id: 'summary',+ name: 'Market Summary',+ description: 'Aggregate statistics: security counts, yield & price distributions',+ command: 'summary',+ },+ ],+ },+ {+ id: 'canada-gov',+ name: 'Canada Open Gov',+ fullName: 'Government of Canada Open Data',+ description: 'Open data portal with datasets from Canadian federal departments & agencies',+ color: '#EF4444',+ country: 'Canada',+ flag: '\uD83C\uDDE8\uD83C\uDDE6',+ endpoints: [+ {+ id: 'publishers',+ name: 'Publishers',+ description: 'Federal departments & agencies publishing open data',+ command: 'publishers',+ },+ {+ id: 'datasets',+ name: 'Datasets',+ description: 'Browse datasets from a specific publisher',+ command: 'datasets',+ },+ {+ id: 'search',+ name: 'Search',+ description: 'Search across all Government of Canada datasets',+ command: 'search',+ },+ {+ id: 'recent',+ name: 'Recent',+ description: 'Recently updated datasets across all publishers',+ command: 'recent-datasets',+ },+ ],+ },+ {+ id: 'openafrica',+ name: 'openAFRICA',+ fullName: 'openAFRICA Open Data Portal',+ description: 'African open data portal with datasets from organizations across the continent',+ color: '#F59E0B',+ country: 'Africa',+ flag: '\uD83C\uDF0D',+ endpoints: [+ {+ id: 'organizations',+ name: 'Organizations',+ description: 'Data publishing organizations on openAFRICA',+ command: 'organizations',+ },+ {+ id: 'datasets',+ name: 'Datasets',+ description: 'Browse datasets from a specific organization',+ command: 'org-datasets',+ },+ {+ id: 'search',+ name: 'Search',+ description: 'Search across all openAFRICA datasets',+ command: 'search',+ },+ {+ id: 'recent',+ name: 'Recent',+ description: 'Recently updated datasets across all organizations',+ command: 'recent',+ },+ ],+ },+ {+ id: 'spain',+ name: 'Spain Open Data',+ fullName: 'datos.gob.es - Spain Open Data',+ description: 'Spanish government open data portal with catalogues, datasets & resources',+ color: '#DC2626',+ country: 'Spain',+ flag: '\uD83C\uDDEA\uD83C\uDDF8',+ endpoints: [+ {+ id: 'catalogues',+ name: 'Catalogues',+ description: 'Government publishers/catalogues on datos.gob.es',+ command: 'catalogues',+ },+ {+ id: 'datasets',+ name: 'Datasets',+ description: 'Browse datasets from a specific publisher',+ command: 'datasets',+ },+ {+ id: 'search',+ name: 'Search',+ description: 'Search across all Spanish government datasets',+ command: 'search',+ },+ ],+ },+ {+ id: 'finland-pxweb',+ name: 'Statistics Finland',+ fullName: 'Statistics Finland (PxWeb)',+ description: 'Finnish statistical database via PxWeb API — StatFin tables & time series',+ color: '#0EA5E9',+ country: 'Finland',+ flag: '\uD83C\uDDEB\uD83C\uDDEE',+ endpoints: [+ {+ id: 'browse',+ name: 'Browse',+ description: 'Browse database nodes and subject areas',+ command: 'nodes',+ },+ {+ id: 'metadata',+ name: 'Metadata',+ description: 'View table variables and value lists',+ command: 'metadata',+ },+ {+ id: 'data',+ name: 'Data',+ description: 'Fetch statistical data from tables',+ command: 'data',+ },+ ],+ },+ {+ id: 'swiss',+ name: 'Swiss Open Data',+ fullName: 'opendata.swiss - Swiss Government',+ description: 'Swiss federal open data portal with datasets in DE/FR/IT/EN from opendata.swiss',+ color: '#E11D48',+ country: 'Switzerland',+ flag: '\uD83C\uDDE8\uD83C\uDDED',+ endpoints: [+ {+ id: 'publishers',+ name: 'Publishers',+ description: 'Federal offices and organizations publishing open data',+ command: 'publishers',+ },+ {+ id: 'datasets',+ name: 'Datasets',+ description: 'Browse datasets from a specific publisher',+ command: 'datasets',+ },+ {+ id: 'search',+ name: 'Search',+ description: 'Search across all Swiss government datasets',+ command: 'search',+ },+ {+ id: 'recent',+ name: 'Recent',+ description: 'Recently updated datasets across all publishers',+ command: 'recent-datasets',+ },+ ],+ },+ {+ id: 'france',+ name: 'France Open Data',+ fullName: 'data.gouv.fr - French Government',+ description: 'French government APIs: geographic data, dataset catalog, tabular data & company registry',+ color: '#2563EB',+ country: 'France',+ flag: '\uD83C\uDDEB\uD83C\uDDF7',+ endpoints: [+ {+ id: 'geo',+ name: 'Geography',+ description: 'Municipalities, departments & regions via API Géo',+ command: 'municipalities',+ },+ {+ id: 'datasets',+ name: 'Datasets',+ description: 'Search data.gouv.fr dataset catalog',+ command: 'datasets',+ },+ {+ id: 'tabular',+ name: 'Tabular',+ description: 'Query CSV/Excel resources directly via API Tabulaire',+ command: 'profile',+ },+ {+ id: 'company',+ name: 'Company',+ description: 'French company lookup by SIREN/SIRET via API Entreprise',+ command: 'company',+ },+ ],+ },+ {+ id: 'universal-ckan',+ name: 'CKAN Portals',+ fullName: 'Universal CKAN Open Data Portals',+ description: '8 CKAN portals: US, UK, Australia, Italy, Brazil, Latvia, Slovenia, Uruguay',+ color: '#10B981',+ country: 'Multi-Country',+ flag: '\uD83C\uDF10',+ endpoints: [+ {+ id: 'organizations',+ name: 'Organizations',+ description: 'Browse data publishers / organizations',+ command: 'list_organizations',+ },+ {+ id: 'datasets',+ name: 'Datasets',+ description: 'Browse datasets from a specific organization',+ command: 'search_datasets',+ },+ {+ id: 'search',+ name: 'Search',+ description: 'Search datasets across the selected portal',+ command: 'search_datasets',+ },+ ],+ },+ {+ id: 'us-congress',+ name: 'US Congress',+ fullName: 'United States Congress',+ description: 'Congressional bills, resolutions & legislative activity via Congress.gov API',+ color: '#8B5CF6',+ country: 'United States',+ flag: '\uD83C\uDDFA\uD83C\uDDF8',+ endpoints: [+ {+ id: 'congress_bills',+ name: 'Bills',+ description: 'Browse Congressional bills & resolutions with filters',+ command: 'congress_bills',+ },+ {+ id: 'bill_info',+ name: 'Bill Detail',+ description: 'Detailed bill information with sponsors, actions & summaries',+ command: 'bill_info',+ },+ {+ id: 'summary',+ name: 'Summary',+ description: 'Bills count by type for a given Congress session',+ command: 'summary',+ },+ ],+ },+];++// Congress.gov bill type options+export const CONGRESS_BILL_TYPES = [+ { value: '', label: 'All Types' },+ { value: 'hr', label: 'House Bill' },+ { value: 's', label: 'Senate Bill' },+ { value: 'hjres', label: 'House Joint Res.' },+ { value: 'sjres', label: 'Senate Joint Res.' },+ { value: 'hconres', label: 'House Con. Res.' },+ { value: 'sconres', label: 'Senate Con. Res.' },+ { value: 'hres', label: 'House Simple Res.' },+ { value: 'sres', label: 'Senate Simple Res.' },+];++// Security type options for US Treasury+export const SECURITY_TYPES = [+ { value: 'all', label: 'All Securities' },+ { value: 'bill', label: 'Treasury Bills' },+ { value: 'note', label: 'Treasury Notes' },+ { value: 'bond', label: 'Treasury Bonds' },+ { value: 'tips', label: 'TIPS' },+ { value: 'frn', label: 'Floating Rate Notes' },+ { value: 'cmb', label: 'Cash Management Bills' },+];++// Auction security type options (different casing from API)+export const AUCTION_SECURITY_TYPES = [+ { value: 'all', label: 'All Types' },+ { value: 'Bill', label: 'Bills' },+ { value: 'Note', label: 'Notes' },+ { value: 'Bond', label: 'Bonds' },+ { value: 'TIPS', label: 'TIPS' },+ { value: 'FRN', label: 'FRN' },+ { value: 'CMB', label: 'CMB' },+];++// Key auction fields to display in the table+export const AUCTION_DISPLAY_FIELDS = [+ { key: 'cusip', label: 'CUSIP', width: 100 },+ { key: 'securityType', label: 'Type', width: 60 },+ { key: 'securityTerm', label: 'Term', width: 80 },+ { key: 'auctionDate', label: 'Auction Date', width: 110 },+ { key: 'issueDate', label: 'Issue Date', width: 110 },+ { key: 'maturityDate', label: 'Maturity', width: 110 },+ { key: 'highDiscountRate', label: 'High Rate', width: 90, format: 'rate' },+ { key: 'highPrice', label: 'High Price', width: 90, format: 'price' },+ { key: 'bidToCoverRatio', label: 'Bid/Cover', width: 80, format: 'ratio' },+ { key: 'offeringAmount', label: 'Offering ($)', width: 120, format: 'currency' },+ { key: 'totalAccepted', label: 'Accepted ($)', width: 120, format: 'currency' },+ { key: 'allocationPercentage', label: 'Alloc %', width: 70, format: 'pct' },+];++// Universal CKAN portal list+export const CKAN_PORTALS: { code: string; name: string; flag: string; url: string }[] = [+ { code: 'us', name: 'United States', flag: '\uD83C\uDDFA\uD83C\uDDF8', url: 'catalog.data.gov' },+ { code: 'uk', name: 'United Kingdom', flag: '\uD83C\uDDEC\uD83C\uDDE7', url: 'data.gov.uk' },+ { code: 'au', name: 'Australia', flag: '\uD83C\uDDE6\uD83C\uDDFA', url: 'data.gov.au' },+ { code: 'it', name: 'Italy', flag: '\uD83C\uDDEE\uD83C\uDDF9', url: 'dati.gov.it' },+ { code: 'br', name: 'Brazil', flag: '\uD83C\uDDE7\uD83C\uDDF7', url: 'dados.gov.br' },+ { code: 'lv', name: 'Latvia', flag: '\uD83C\uDDF1\uD83C\uDDFB', url: 'data.gov.lv' },+ { code: 'si', name: 'Slovenia', flag: '\uD83C\uDDF8\uD83C\uDDEE', url: 'podatki.gov.si' },+ { code: 'uy', name: 'Uruguay', flag: '\uD83C\uDDFA\uD83C\uDDFE', url: 'catalogodatos.gub.uy' },+];++export const getProviderConfig = (id: GovProvider): GovProviderConfig => {+ return GOV_PROVIDERS.find(p => p.id === id) || GOV_PROVIDERS[0];+};diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/index.tsnew file mode 100644index 000000000..4f4857cd1--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/index.ts@@ -0,0 +1,11 @@+// Government Data Tab Hooks++export { useUSTreasuryData } from './useUSTreasuryData';+export { useCanadaGovData } from './useCanadaGovData';+export { useCongressGovData } from './useCongressGovData';+export { useOpenAfricaData } from './useOpenAfricaData';+export { useSpainData } from './useSpainData';+export { usePxWebData } from './usePxWebData';+export { useSwissGovData } from './useSwissGovData';+export { useFrenchGovData } from './useFrenchGovData';+export { useUniversalCkanData } from './useUniversalCkanData';diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useCanadaGovData.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useCanadaGovData.tsnew file mode 100644index 000000000..65cb3a043--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useCanadaGovData.ts@@ -0,0 +1,292 @@+// useCanadaGovData Hook - Fetch and manage Government of Canada open data++import { useState, useCallback } from 'react';+import { invoke } from '@tauri-apps/api/core';+import type {+ CanadaGovView,+ CanadaPublisher,+ CanadaDataset,+ CanadaResource,+ CanadaGovResponse,+} from '../types';++interface UseCanadaGovDataReturn {+ // View+ activeView: CanadaGovView;+ setActiveView: (view: CanadaGovView) => void;++ // Publishers+ publishers: CanadaPublisher[];+ selectedPublisher: string | null;+ setSelectedPublisher: (id: string | null) => void;+ fetchPublishers: () => Promise<void>;++ // Datasets+ datasets: CanadaDataset[];+ selectedDataset: string | null;+ setSelectedDataset: (id: string | null) => void;+ fetchDatasets: (publisherId: string) => Promise<void>;+ datasetsTotalCount: number;++ // Resources+ resources: CanadaResource[];+ fetchResources: (datasetId: string) => Promise<void>;++ // Search+ searchQuery: string;+ setSearchQuery: (query: string) => void;+ searchResults: CanadaDataset[];+ searchTotalCount: number;+ searchDatasets: () => Promise<void>;++ // Recent+ recentDatasets: CanadaDataset[];+ fetchRecentDatasets: () => Promise<void>;++ // CSV export+ exportCSV: () => void;++ // Shared state+ loading: boolean;+ error: string | null;+}++export function useCanadaGovData(): UseCanadaGovDataReturn {+ const [activeView, setActiveView] = useState<CanadaGovView>('publishers');+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // Publishers+ const [publishers, setPublishers] = useState<CanadaPublisher[]>([]);+ const [selectedPublisher, setSelectedPublisher] = useState<string | null>(null);++ // Datasets+ const [datasets, setDatasets] = useState<CanadaDataset[]>([]);+ const [datasetsTotalCount, setDatasetsTotalCount] = useState(0);+ const [selectedDataset, setSelectedDataset] = useState<string | null>(null);++ // Resources+ const [resources, setResources] = useState<CanadaResource[]>([]);++ // Search+ const [searchQuery, setSearchQuery] = useState('');+ const [searchResults, setSearchResults] = useState<CanadaDataset[]>([]);+ const [searchTotalCount, setSearchTotalCount] = useState(0);++ // Recent+ const [recentDatasets, setRecentDatasets] = useState<CanadaDataset[]>([]);++ const fetchPublishers = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_canada_gov_command', {+ command: 'publishers',+ args: [] as string[],+ }) as string;++ const parsed: CanadaGovResponse<CanadaPublisher[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setPublishers([]);+ } else {+ setPublishers(parsed.data || []);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch publishers: ${msg}`);+ setPublishers([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const fetchDatasets = useCallback(async (publisherId: string) => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_canada_gov_command', {+ command: 'datasets',+ args: [publisherId, '100'],+ }) as string;++ const parsed: CanadaGovResponse<CanadaDataset[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setDatasets([]);+ setDatasetsTotalCount(0);+ } else {+ setDatasets(parsed.data || []);+ setDatasetsTotalCount(parsed.metadata?.total_count || 0);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch datasets: ${msg}`);+ setDatasets([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const fetchResources = useCallback(async (datasetId: string) => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_canada_gov_command', {+ command: 'resources',+ args: [datasetId],+ }) as string;++ const parsed: CanadaGovResponse<CanadaResource[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setResources([]);+ } else {+ setResources(parsed.data || []);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch resources: ${msg}`);+ setResources([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const searchDatasetsAction = useCallback(async () => {+ if (!searchQuery.trim()) return;+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_canada_gov_command', {+ command: 'search',+ args: [searchQuery.trim(), '50'],+ }) as string;++ const parsed: CanadaGovResponse<CanadaDataset[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setSearchResults([]);+ setSearchTotalCount(0);+ } else {+ setSearchResults(parsed.data || []);+ setSearchTotalCount(parsed.metadata?.total_count || 0);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to search datasets: ${msg}`);+ setSearchResults([]);+ } finally {+ setLoading(false);+ }+ }, [searchQuery]);++ const fetchRecentDatasets = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_canada_gov_command', {+ command: 'recent-datasets',+ args: ['50'],+ }) as string;++ const parsed: CanadaGovResponse<CanadaDataset[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setRecentDatasets([]);+ } else {+ setRecentDatasets(parsed.data || []);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch recent datasets: ${msg}`);+ setRecentDatasets([]);+ } finally {+ setLoading(false);+ }+ }, []);++ // CSV export for current view data+ const exportCSV = useCallback(() => {+ let csv = '';+ let filename = 'fincept_canada_gov_';++ if (activeView === 'publishers' && publishers.length > 0) {+ csv = [+ '# Government of Canada - Publishers',+ '',+ 'ID,Name',+ ...publishers.map(p => `${p.id},"${p.name}"`),+ ].join('\n');+ filename += 'publishers.csv';+ } else if (activeView === 'datasets' && datasets.length > 0) {+ csv = [+ `# Government of Canada - Datasets for ${selectedPublisher}`,+ '',+ 'ID,Title,Resources,Modified,Tags',+ ...datasets.map(d =>+ `${d.id},"${d.title.replace(/"/g, '""')}",${d.num_resources},${d.metadata_modified || ''},"${d.tags.join('; ')}"`+ ),+ ].join('\n');+ filename += `datasets_${selectedPublisher || 'all'}.csv`;+ } else if (activeView === 'resources' && resources.length > 0) {+ csv = [+ `# Government of Canada - Resources for ${selectedDataset}`,+ '',+ 'ID,Name,Format,Size,URL,Last Modified',+ ...resources.map(r =>+ `${r.id},"${(r.name || '').replace(/"/g, '""')}",${r.format},${r.size || ''},${r.url},${r.last_modified || ''}`+ ),+ ].join('\n');+ filename += `resources_${selectedDataset || 'unknown'}.csv`;+ } else if (activeView === 'search' && searchResults.length > 0) {+ csv = [+ `# Government of Canada - Search: "${searchQuery}"`,+ '',+ 'ID,Title,Organization,Resources,Modified,Tags',+ ...searchResults.map(d =>+ `${d.id},"${d.title.replace(/"/g, '""')}",${d.organization || ''},${d.num_resources},${d.metadata_modified || ''},"${d.tags.join('; ')}"`+ ),+ ].join('\n');+ filename += `search_${searchQuery.replace(/\s+/g, '_')}.csv`;+ } else {+ return;+ }++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ URL.revokeObjectURL(url);+ }, [activeView, publishers, datasets, resources, searchResults, selectedPublisher, selectedDataset, searchQuery]);++ return {+ activeView,+ setActiveView,+ publishers,+ selectedPublisher,+ setSelectedPublisher,+ fetchPublishers,+ datasets,+ selectedDataset,+ setSelectedDataset,+ fetchDatasets,+ datasetsTotalCount,+ resources,+ fetchResources,+ searchQuery,+ setSearchQuery,+ searchResults,+ searchTotalCount,+ searchDatasets: searchDatasetsAction,+ recentDatasets,+ fetchRecentDatasets,+ exportCSV,+ loading,+ error,+ };+}++export default useCanadaGovData;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useCongressGovData.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useCongressGovData.tsnew file mode 100644index 000000000..6595255f3--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useCongressGovData.ts@@ -0,0 +1,254 @@+// useCongressGovData Hook - Fetch and manage Congress.gov data++import { useState, useCallback } from 'react';+import { invoke } from '@tauri-apps/api/core';+import { sqliteService } from '@/services/core/sqliteService';+import { getDateFromPreset } from '@/components/common/charts';+import type { DateRangePreset } from '@/components/common/charts';+import type {+ CongressGovView,+ CongressBill,+ CongressBillsResponse,+ CongressBillDetail,+ CongressBillSummary,+} from '../types';++interface UseCongressGovDataReturn {+ // View+ activeView: CongressGovView;+ setActiveView: (view: CongressGovView) => void;++ // API key+ apiKey: string;+ apiKeyLoaded: boolean;+ loadApiKey: () => Promise<void>;+ saveApiKey: (key: string) => Promise<void>;++ // Date range+ dateRangePreset: DateRangePreset;+ setDateRangePreset: (preset: DateRangePreset) => void;+ startDate: string;+ endDate: string;+ setStartDate: (date: string) => void;+ setEndDate: (date: string) => void;++ // Bills list+ bills: CongressBill[];+ billsTotalCount: number;+ congressNumber: number;+ setCongressNumber: (n: number) => void;+ billType: string;+ setBillType: (t: string) => void;+ billsOffset: number;+ setBillsOffset: (n: number) => void;+ fetchBills: () => Promise<void>;++ // Bill detail+ billDetail: CongressBillDetail | null;+ fetchBillDetail: (billUrl: string) => Promise<void>;+ selectedBillTitle: string;++ // Summary+ billSummary: CongressBillSummary | null;+ fetchSummary: () => Promise<void>;++ // Export+ exportCSV: () => void;++ // Shared+ loading: boolean;+ error: string | null;+}++const currentCongressNumber = (): number => {+ const year = new Date().getFullYear();+ return 74 + Math.floor((year - 1935) / 2);+};++export function useCongressGovData(): UseCongressGovDataReturn {+ const [activeView, setActiveView] = useState<CongressGovView>('bills');+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // API key+ const [apiKey, setApiKey] = useState('');+ const [apiKeyLoaded, setApiKeyLoaded] = useState(false);++ // Date range+ const initialDates = getDateFromPreset('1Y');+ const [dateRangePreset, setDateRangePresetState] = useState<DateRangePreset>('1Y');+ const [startDate, setStartDate] = useState(initialDates.start);+ const [endDate, setEndDate] = useState(new Date().toISOString().split('T')[0]);++ const setDateRangePreset = useCallback((preset: DateRangePreset) => {+ setDateRangePresetState(preset);+ const dates = getDateFromPreset(preset);+ setStartDate(dates.start);+ setEndDate(new Date().toISOString().split('T')[0]);+ }, []);++ // Bills+ const [bills, setBills] = useState<CongressBill[]>([]);+ const [billsTotalCount, setBillsTotalCount] = useState(0);+ const [congressNumber, setCongressNumber] = useState(currentCongressNumber());+ const [billType, setBillType] = useState('');+ const [billsOffset, setBillsOffset] = useState(0);++ // Bill detail+ const [billDetail, setBillDetail] = useState<CongressBillDetail | null>(null);+ const [selectedBillTitle, setSelectedBillTitle] = useState('');++ // Summary+ const [billSummary, setBillSummary] = useState<CongressBillSummary | null>(null);++ const loadApiKey = useCallback(async () => {+ try {+ const key = await sqliteService.getSetting('CONGRESS_GOV_API_KEY');+ if (key) {+ setApiKey(key);+ }+ } catch {+ // ignore+ } finally {+ setApiKeyLoaded(true);+ }+ }, []);++ const saveApiKey = useCallback(async (key: string) => {+ try {+ await sqliteService.saveSetting('CONGRESS_GOV_API_KEY', key, 'api_keys');+ setApiKey(key);+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to save API key: ${msg}`);+ }+ }, []);++ const fetchBills = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const args: string[] = [+ String(congressNumber),+ billType || '',+ startDate,+ endDate,+ '100', // limit+ String(billsOffset),+ 'desc',+ 'false',+ ];++ const env: Record<string, string> = {};+ if (apiKey) env['CONGRESS_GOV_API_KEY'] = apiKey;++ const result = await invoke('execute_congress_gov_command', {+ command: 'congress_bills',+ args,+ }) as string;++ const parsed: CongressBillsResponse = JSON.parse(result);+ if (!parsed.success) {+ setError(parsed.error || 'Failed to fetch bills');+ setBills([]);+ setBillsTotalCount(0);+ } else {+ setBills(parsed.bills || []);+ setBillsTotalCount(parsed.pagination?.count || parsed.total_bills || 0);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch bills: ${msg}`);+ setBills([]);+ } finally {+ setLoading(false);+ }+ }, [congressNumber, billType, startDate, endDate, billsOffset, apiKey]);++ const fetchBillDetail = useCallback(async (billUrl: string) => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_congress_gov_command', {+ command: 'bill_info',+ args: [billUrl],+ }) as string;++ const parsed: CongressBillDetail = JSON.parse(result);+ if (!parsed.success) {+ setError(parsed.error || 'Failed to fetch bill detail');+ setBillDetail(null);+ } else {+ setBillDetail(parsed);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch bill detail: ${msg}`);+ setBillDetail(null);+ } finally {+ setLoading(false);+ }+ }, []);++ const fetchSummary = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_congress_gov_command', {+ command: 'summary',+ args: [String(congressNumber), '10'],+ }) as string;++ const parsed: CongressBillSummary = JSON.parse(result);+ if (!parsed.success) {+ setError(parsed.error || 'Failed to fetch summary');+ setBillSummary(null);+ } else {+ setBillSummary(parsed);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch summary: ${msg}`);+ setBillSummary(null);+ } finally {+ setLoading(false);+ }+ }, [congressNumber]);++ const exportCSV = useCallback(() => {+ if (activeView !== 'bills' || bills.length === 0) return;++ const csv = [+ `# Congress.gov Bills - ${congressNumber}th Congress`,+ '',+ 'Congress,Type,Number,Title,Chamber,Update Date,Latest Action Date,Latest Action',+ ...bills.map(b =>+ `${b.congress},${b.bill_type},${b.bill_number},"${(b.title || '').replace(/"/g, '""')}",${b.origin_chamber},${b.update_date},${b.latest_action_date || ''},"${(b.latest_action || '').replace(/"/g, '""')}"`+ ),+ ].join('\n');++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `fincept_congress_bills_${congressNumber}.csv`;+ a.click();+ URL.revokeObjectURL(url);+ }, [activeView, bills, congressNumber]);++ return {+ activeView, setActiveView,+ apiKey, apiKeyLoaded, loadApiKey, saveApiKey,+ dateRangePreset, setDateRangePreset,+ startDate, endDate, setStartDate, setEndDate,+ bills, billsTotalCount, congressNumber, setCongressNumber,+ billType, setBillType, billsOffset, setBillsOffset,+ fetchBills,+ billDetail, fetchBillDetail, selectedBillTitle,+ billSummary, fetchSummary,+ exportCSV,+ loading, error,+ };+}++export default useCongressGovData;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useFrenchGovData.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useFrenchGovData.tsnew file mode 100644index 000000000..a4bb57740--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useFrenchGovData.ts@@ -0,0 +1,443 @@+// useFrenchGovData Hook - French Government APIs (data.gouv.fr, API Géo, Tabulaire, Entreprise)++import { useState, useCallback } from 'react';+import { invoke } from '@tauri-apps/api/core';+import type {+ FrenchGovView,+ FrenchMunicipality,+ FrenchDepartment,+ FrenchRegion,+ FrenchDataset,+ FrenchResourceProfile,+ FrenchResourceLines,+ FrenchCompany,+ FrenchGovResponse,+} from '../types';++// Geo search type+export type GeoSearchType = 'municipalities' | 'departments' | 'regions';++interface UseFrenchGovDataReturn {+ // View+ activeView: FrenchGovView;+ setActiveView: (view: FrenchGovView) => void;++ // Geo+ geoSearchType: GeoSearchType;+ setGeoSearchType: (type: GeoSearchType) => void;+ geoQuery: string;+ setGeoQuery: (query: string) => void;+ municipalities: FrenchMunicipality[];+ departments: FrenchDepartment[];+ regions: FrenchRegion[];+ fetchGeo: () => Promise<void>;++ // Datasets (data.gouv.fr catalog)+ datasetQuery: string;+ setDatasetQuery: (query: string) => void;+ datasets: FrenchDataset[];+ datasetsTotalCount: number;+ datasetsPage: number;+ fetchDatasets: (page?: number) => Promise<void>;++ // Tabular+ tabularResourceId: string;+ setTabularResourceId: (id: string) => void;+ resourceProfile: FrenchResourceProfile | null;+ resourceLines: FrenchResourceLines | null;+ fetchProfile: () => Promise<void>;+ fetchLines: (page?: number) => Promise<void>;++ // Company+ companyQuery: string;+ setCompanyQuery: (query: string) => void;+ companies: FrenchCompany[];+ fetchCompany: () => Promise<void>;++ // CSV export+ exportCSV: () => void;++ // Shared state+ loading: boolean;+ error: string | null;+}++export function useFrenchGovData(): UseFrenchGovDataReturn {+ const [activeView, setActiveView] = useState<FrenchGovView>('geo');+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // Geo state+ const [geoSearchType, setGeoSearchType] = useState<GeoSearchType>('municipalities');+ const [geoQuery, setGeoQuery] = useState('');+ const [municipalities, setMunicipalities] = useState<FrenchMunicipality[]>([]);+ const [departments, setDepartments] = useState<FrenchDepartment[]>([]);+ const [regions, setRegions] = useState<FrenchRegion[]>([]);++ // Datasets state+ const [datasetQuery, setDatasetQuery] = useState('');+ const [datasets, setDatasets] = useState<FrenchDataset[]>([]);+ const [datasetsTotalCount, setDatasetsTotalCount] = useState(0);+ const [datasetsPage, setDatasetsPage] = useState(1);++ // Tabular state+ const [tabularResourceId, setTabularResourceId] = useState('');+ const [resourceProfile, setResourceProfile] = useState<FrenchResourceProfile | null>(null);+ const [resourceLines, setResourceLines] = useState<FrenchResourceLines | null>(null);++ // Company state+ const [companyQuery, setCompanyQuery] = useState('');+ const [companies, setCompanies] = useState<FrenchCompany[]>([]);++ // ===== GEO =====+ const fetchGeo = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const args: string[] = geoQuery.trim() ? [geoQuery.trim(), '50'] : [];++ const result = await invoke('execute_french_gov_command', {+ command: geoSearchType,+ args,+ }) as string;++ const parsed: FrenchGovResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ } else {+ const data = Array.isArray(parsed.data) ? parsed.data : [];+ if (geoSearchType === 'municipalities') {+ setMunicipalities(data.map((m: any) => ({+ code: m.code || '',+ name: m.name || m.original_name || '',+ original_name: m.original_name || m.name || '',+ postal_codes: m.postal_codes || [],+ department_code: m.department_code || null,+ region_code: m.region_code || null,+ population: m.population || null,+ area: m.area || null,+ center: m.center || null,+ search_score: m.search_score || 0,+ })));+ } else if (geoSearchType === 'departments') {+ setDepartments(data.map((d: any) => ({+ code: d.code || '',+ name: d.name || d.original_name || '',+ original_name: d.original_name || d.name || '',+ region_code: d.region_code || null,+ search_score: d.search_score || 0,+ })));+ } else if (geoSearchType === 'regions') {+ setRegions(data.map((r: any) => ({+ code: r.code || '',+ name: r.name || r.original_name || '',+ original_name: r.original_name || r.name || '',+ search_score: r.search_score || 0,+ })));+ }+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch geo data: ${msg}`);+ } finally {+ setLoading(false);+ }+ }, [geoSearchType, geoQuery]);++ // ===== DATASETS =====+ const fetchDatasets = useCallback(async (page: number = 1) => {+ setLoading(true);+ setError(null);+ try {+ const args: string[] = [];+ if (datasetQuery.trim()) {+ args.push(datasetQuery.trim());+ }+ args.push(String(page));+ args.push('20');++ const result = await invoke('execute_french_gov_command', {+ command: 'datasets',+ args,+ }) as string;++ const parsed: FrenchGovResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setDatasets([]);+ setDatasetsTotalCount(0);+ } else {+ const data = Array.isArray(parsed.data) ? parsed.data : [];+ setDatasets(data.map((d: any) => ({+ id: d.id || '',+ title: d.title || '',+ original_title: d.original_title || d.title || '',+ description: d.description || '',+ original_description: d.original_description || d.description || '',+ url: d.url || null,+ owner: d.owner || null,+ organization: d.organization || null,+ created_at: d.created_at || null,+ last_modified: d.last_modified || null,+ tags: d.tags || [],+ frequency: d.frequency || null,+ license: d.license || null,+ resources_count: d.resources_count || 0,+ })));+ setDatasetsTotalCount(parsed.metadata?.pagination?.total || data.length);+ setDatasetsPage(page);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch datasets: ${msg}`);+ setDatasets([]);+ } finally {+ setLoading(false);+ }+ }, [datasetQuery]);++ // ===== TABULAR =====+ const fetchProfile = useCallback(async () => {+ if (!tabularResourceId.trim()) return;+ setLoading(true);+ setError(null);+ setResourceLines(null);+ try {+ const result = await invoke('execute_french_gov_command', {+ command: 'profile',+ args: [tabularResourceId.trim()],+ }) as string;++ const parsed: FrenchGovResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setResourceProfile(null);+ } else {+ const d = parsed.data || {};+ setResourceProfile({+ resource_id: d.resource_id || tabularResourceId.trim(),+ name: d.name || '',+ original_name: d.original_name || d.name || '',+ title: d.title || '',+ original_title: d.original_title || d.title || '',+ format: d.format || null,+ size: d.size || null,+ columns: (d.columns || []).map((c: any) => ({+ name: c.name || '',+ original_name: c.original_name || c.name || '',+ title: c.title || '',+ original_title: c.original_title || c.title || '',+ type: c.type || null,+ format: c.format || null,+ description: c.description || '',+ original_description: c.original_description || c.description || '',+ })),+ total_rows: d.total_rows || null,+ encoding: d.encoding || null,+ delimiter: d.delimiter || null,+ });+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch profile: ${msg}`);+ setResourceProfile(null);+ } finally {+ setLoading(false);+ }+ }, [tabularResourceId]);++ const fetchLines = useCallback(async (page: number = 1) => {+ if (!tabularResourceId.trim()) return;+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_french_gov_command', {+ command: 'lines',+ args: [tabularResourceId.trim(), String(page), '20'],+ }) as string;++ const parsed: FrenchGovResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setResourceLines(null);+ } else {+ const d = parsed.data || {};+ setResourceLines({+ resource_id: d.resource_id || tabularResourceId.trim(),+ lines: d.lines || [],+ total_rows: d.total_rows || 0,+ page: d.page || page,+ page_size: d.page_size || 20,+ has_more: d.has_more || false,+ });+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch lines: ${msg}`);+ setResourceLines(null);+ } finally {+ setLoading(false);+ }+ }, [tabularResourceId]);++ // ===== COMPANY =====+ const fetchCompany = useCallback(async () => {+ if (!companyQuery.trim()) return;+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_french_gov_command', {+ command: 'company',+ args: [companyQuery.trim()],+ }) as string;++ const parsed: FrenchGovResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setCompanies([]);+ } else {+ const data = Array.isArray(parsed.data) ? parsed.data : [];+ setCompanies(data.map((c: any) => ({+ siren: c.siren || null,+ siret: c.siret || null,+ complete_name: c.complete_name || '',+ original_complete_name: c.original_complete_name || '',+ company_name: c.company_name || '',+ original_company_name: c.original_company_name || '',+ company_category: c.company_category || null,+ creation_date: c.creation_date || null,+ administrative_status: c.administrative_status || null,+ legal_form: c.legal_form || '',+ original_legal_form: c.original_legal_form || '',+ main_activity: c.main_activity || '',+ original_main_activity: c.original_main_activity || '',+ employee_size_range: c.employee_size_range || null,+ address: c.address || null,+ matching_score: c.matching_score || null,+ })));+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch company: ${msg}`);+ setCompanies([]);+ } finally {+ setLoading(false);+ }+ }, [companyQuery]);++ // ===== CSV EXPORT =====+ const exportCSV = useCallback(() => {+ let csv = '';+ let filename = 'fincept_france_gov_';++ if (activeView === 'geo') {+ if (geoSearchType === 'municipalities' && municipalities.length > 0) {+ csv = [+ '# France - Municipalities',+ '',+ 'Code,Name,Original Name,Postal Codes,Department,Region,Population,Area',+ ...municipalities.map(m =>+ `${m.code},"${(m.name || '').replace(/"/g, '""')}","${(m.original_name || '').replace(/"/g, '""')}","${(m.postal_codes || []).join('; ')}",${m.department_code || ''},${m.region_code || ''},${m.population || ''},${m.area || ''}`+ ),+ ].join('\n');+ filename += 'municipalities.csv';+ } else if (geoSearchType === 'departments' && departments.length > 0) {+ csv = [+ '# France - Departments',+ '',+ 'Code,Name,Original Name,Region Code',+ ...departments.map(d =>+ `${d.code},"${(d.name || '').replace(/"/g, '""')}","${(d.original_name || '').replace(/"/g, '""')}",${d.region_code || ''}`+ ),+ ].join('\n');+ filename += 'departments.csv';+ } else if (geoSearchType === 'regions' && regions.length > 0) {+ csv = [+ '# France - Regions',+ '',+ 'Code,Name,Original Name',+ ...regions.map(r =>+ `${r.code},"${(r.name || '').replace(/"/g, '""')}","${(r.original_name || '').replace(/"/g, '""')}"`+ ),+ ].join('\n');+ filename += 'regions.csv';+ } else {+ return;+ }+ } else if (activeView === 'datasets' && datasets.length > 0) {+ csv = [+ `# data.gouv.fr - Datasets${datasetQuery ? `: "${datasetQuery}"` : ''}`,+ '',+ 'ID,Title,Original Title,Organization,Resources,Modified,Tags',+ ...datasets.map(d =>+ `${d.id},"${(d.title || '').replace(/"/g, '""')}","${(d.original_title || '').replace(/"/g, '""')}",${d.organization || ''},${d.resources_count},${d.last_modified || ''},"${(d.tags || []).join('; ')}"`+ ),+ ].join('\n');+ filename += `datasets_${datasetQuery ? datasetQuery.replace(/\s+/g, '_') : 'all'}.csv`;+ } else if (activeView === 'tabular' && resourceLines?.lines?.length) {+ const lines = resourceLines.lines;+ const keys = lines.length > 0 ? Object.keys(lines[0]) : [];+ csv = [+ `# data.gouv.fr - Tabular Data: ${tabularResourceId}`,+ '',+ keys.join(','),+ ...lines.map(row => keys.map(k => `"${String(row[k] ?? '').replace(/"/g, '""')}"`).join(',')),+ ].join('\n');+ filename += `tabular_${tabularResourceId}.csv`;+ } else if (activeView === 'company' && companies.length > 0) {+ csv = [+ '# France - Company Registry',+ '',+ 'SIREN,SIRET,Name,Original Name,Category,Status,Legal Form,Activity,Created',+ ...companies.map(c =>+ `${c.siren || ''},${c.siret || ''},"${(c.complete_name || '').replace(/"/g, '""')}","${(c.original_complete_name || '').replace(/"/g, '""')}",${c.company_category || ''},${c.administrative_status || ''},"${(c.legal_form || '').replace(/"/g, '""')}","${(c.main_activity || '').replace(/"/g, '""')}",${c.creation_date || ''}`+ ),+ ].join('\n');+ filename += 'companies.csv';+ } else {+ return;+ }++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ URL.revokeObjectURL(url);+ }, [activeView, geoSearchType, municipalities, departments, regions, datasets, datasetQuery, resourceLines, tabularResourceId, companies]);++ return {+ activeView,+ setActiveView,+ geoSearchType,+ setGeoSearchType,+ geoQuery,+ setGeoQuery,+ municipalities,+ departments,+ regions,+ fetchGeo,+ datasetQuery,+ setDatasetQuery,+ datasets,+ datasetsTotalCount,+ datasetsPage,+ fetchDatasets,+ tabularResourceId,+ setTabularResourceId,+ resourceProfile,+ resourceLines,+ fetchProfile,+ fetchLines,+ companyQuery,+ setCompanyQuery,+ companies,+ fetchCompany,+ exportCSV,+ loading,+ error,+ };+}++export default useFrenchGovData;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useOpenAfricaData.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useOpenAfricaData.tsnew file mode 100644index 000000000..03a9bc0ea--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useOpenAfricaData.ts@@ -0,0 +1,336 @@+// useOpenAfricaData Hook - Fetch and manage openAFRICA open data portal++import { useState, useCallback } from 'react';+import { invoke } from '@tauri-apps/api/core';+import type {+ OpenAfricaView,+ OpenAfricaOrganization,+ OpenAfricaDataset,+ OpenAfricaResource,+ OpenAfricaResponse,+} from '../types';++interface UseOpenAfricaDataReturn {+ // View+ activeView: OpenAfricaView;+ setActiveView: (view: OpenAfricaView) => void;++ // Organizations+ organizations: OpenAfricaOrganization[];+ selectedOrg: string | null;+ setSelectedOrg: (id: string | null) => void;+ fetchOrganizations: () => Promise<void>;++ // Datasets+ datasets: OpenAfricaDataset[];+ selectedDataset: string | null;+ setSelectedDataset: (id: string | null) => void;+ fetchDatasets: (orgId: string) => Promise<void>;+ datasetsTotalCount: number;++ // Resources+ resources: OpenAfricaResource[];+ fetchResources: (datasetId: string) => Promise<void>;++ // Search+ searchQuery: string;+ setSearchQuery: (query: string) => void;+ searchResults: OpenAfricaDataset[];+ searchTotalCount: number;+ searchDatasets: () => Promise<void>;++ // Recent+ recentDatasets: OpenAfricaDataset[];+ fetchRecentDatasets: () => Promise<void>;++ // CSV export+ exportCSV: () => void;++ // Shared state+ loading: boolean;+ error: string | null;+}++// Parse datasets from the search/recent response format+function parseDatasets(data: any): OpenAfricaDataset[] {+ const raw = data?.datasets || data || [];+ if (!Array.isArray(raw)) return [];+ return raw.map((d: any) => ({+ id: d.id || '',+ name: d.name || '',+ title: d.title || '',+ notes: d.notes || '',+ organization: d.organization || {},+ author: d.author || '',+ license: d.license || '',+ created: d.created || '',+ modified: d.modified || '',+ tags: d.tags || [],+ resource_count: d.resource_count || 0,+ }));+}++export function useOpenAfricaData(): UseOpenAfricaDataReturn {+ const [activeView, setActiveView] = useState<OpenAfricaView>('organizations');+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // Organizations+ const [organizations, setOrganizations] = useState<OpenAfricaOrganization[]>([]);+ const [selectedOrg, setSelectedOrg] = useState<string | null>(null);++ // Datasets+ const [datasets, setDatasets] = useState<OpenAfricaDataset[]>([]);+ const [datasetsTotalCount, setDatasetsTotalCount] = useState(0);+ const [selectedDataset, setSelectedDataset] = useState<string | null>(null);++ // Resources+ const [resources, setResources] = useState<OpenAfricaResource[]>([]);++ // Search+ const [searchQuery, setSearchQuery] = useState('');+ const [searchResults, setSearchResults] = useState<OpenAfricaDataset[]>([]);+ const [searchTotalCount, setSearchTotalCount] = useState(0);++ // Recent+ const [recentDatasets, setRecentDatasets] = useState<OpenAfricaDataset[]>([]);++ const fetchOrganizations = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_openafrica_command', {+ command: 'organizations',+ args: [] as string[],+ }) as string;++ const parsed: OpenAfricaResponse<OpenAfricaOrganization[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setOrganizations([]);+ } else {+ setOrganizations(parsed.data || []);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch organizations: ${msg}`);+ setOrganizations([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const fetchDatasets = useCallback(async (orgId: string) => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_openafrica_command', {+ command: 'org-datasets',+ args: [orgId, '100'],+ }) as string;++ const parsed: OpenAfricaResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setDatasets([]);+ setDatasetsTotalCount(0);+ } else {+ const ds = parseDatasets(parsed.data);+ setDatasets(ds);+ setDatasetsTotalCount(parsed.data?.count || parsed.metadata?.total_count || ds.length);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch datasets: ${msg}`);+ setDatasets([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const fetchResources = useCallback(async (datasetId: string) => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_openafrica_command', {+ command: 'dataset-details',+ args: [datasetId],+ }) as string;++ const parsed: OpenAfricaResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setResources([]);+ } else {+ const rawResources = parsed.data?.resources || [];+ setResources(rawResources.map((r: any) => ({+ id: r.id || '',+ name: r.name || '',+ description: r.description || '',+ url: r.url || '',+ format: r.format || '',+ size: r.size || null,+ created: r.created || '',+ last_modified: r.last_modified || '',+ package_id: r.package_id || '',+ position: r.position || 0,+ })));+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch resources: ${msg}`);+ setResources([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const searchDatasetsAction = useCallback(async () => {+ if (!searchQuery.trim()) return;+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_openafrica_command', {+ command: 'search',+ args: [searchQuery.trim(), '50'],+ }) as string;++ const parsed: OpenAfricaResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setSearchResults([]);+ setSearchTotalCount(0);+ } else {+ const ds = parseDatasets(parsed.data);+ setSearchResults(ds);+ setSearchTotalCount(parsed.data?.count || parsed.metadata?.total_count || ds.length);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to search datasets: ${msg}`);+ setSearchResults([]);+ } finally {+ setLoading(false);+ }+ }, [searchQuery]);++ const fetchRecentDatasets = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_openafrica_command', {+ command: 'recent',+ args: ['50'],+ }) as string;++ const parsed: OpenAfricaResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setRecentDatasets([]);+ } else {+ setRecentDatasets(parseDatasets(parsed.data));+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch recent datasets: ${msg}`);+ setRecentDatasets([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const exportCSV = useCallback(() => {+ let csv = '';+ let filename = 'fincept_openafrica_';++ if (activeView === 'organizations' && organizations.length > 0) {+ csv = [+ '# openAFRICA - Organizations',+ '',+ 'ID,Name,Title,Datasets,State',+ ...organizations.map(o =>+ `${o.id},"${(o.name || '').replace(/"/g, '""')}","${(o.title || '').replace(/"/g, '""')}",${o.dataset_count},${o.state}`+ ),+ ].join('\n');+ filename += 'organizations.csv';+ } else if (activeView === 'datasets' && datasets.length > 0) {+ csv = [+ `# openAFRICA - Datasets for ${selectedOrg}`,+ '',+ 'ID,Title,Author,License,Resources,Modified,Tags',+ ...datasets.map(d =>+ `${d.id},"${(d.title || '').replace(/"/g, '""')}","${(d.author || '').replace(/"/g, '""')}","${d.license}",${d.resource_count},${d.modified},"${d.tags.join('; ')}"`+ ),+ ].join('\n');+ filename += `datasets_${selectedOrg || 'all'}.csv`;+ } else if (activeView === 'resources' && resources.length > 0) {+ csv = [+ `# openAFRICA - Resources for ${selectedDataset}`,+ '',+ 'ID,Name,Format,Size,URL,Last Modified',+ ...resources.map(r =>+ `${r.id},"${(r.name || '').replace(/"/g, '""')}",${r.format},${r.size || ''},${r.url},${r.last_modified || ''}`+ ),+ ].join('\n');+ filename += `resources_${selectedDataset || 'unknown'}.csv`;+ } else if (activeView === 'search' && searchResults.length > 0) {+ csv = [+ `# openAFRICA - Search: "${searchQuery}"`,+ '',+ 'ID,Title,Author,License,Resources,Modified,Tags',+ ...searchResults.map(d =>+ `${d.id},"${(d.title || '').replace(/"/g, '""')}","${(d.author || '').replace(/"/g, '""')}","${d.license}",${d.resource_count},${d.modified},"${d.tags.join('; ')}"`+ ),+ ].join('\n');+ filename += `search_${searchQuery.replace(/\s+/g, '_')}.csv`;+ } else if (activeView === 'recent' && recentDatasets.length > 0) {+ csv = [+ '# openAFRICA - Recent Datasets',+ '',+ 'ID,Title,Author,License,Resources,Modified,Tags',+ ...recentDatasets.map(d =>+ `${d.id},"${(d.title || '').replace(/"/g, '""')}","${(d.author || '').replace(/"/g, '""')}","${d.license}",${d.resource_count},${d.modified},"${d.tags.join('; ')}"`+ ),+ ].join('\n');+ filename += 'recent.csv';+ } else {+ return;+ }++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ URL.revokeObjectURL(url);+ }, [activeView, organizations, datasets, resources, searchResults, recentDatasets, selectedOrg, selectedDataset, searchQuery]);++ return {+ activeView,+ setActiveView,+ organizations,+ selectedOrg,+ setSelectedOrg,+ fetchOrganizations,+ datasets,+ selectedDataset,+ setSelectedDataset,+ fetchDatasets,+ datasetsTotalCount,+ resources,+ fetchResources,+ searchQuery,+ setSearchQuery,+ searchResults,+ searchTotalCount,+ searchDatasets: searchDatasetsAction,+ recentDatasets,+ fetchRecentDatasets,+ exportCSV,+ loading,+ error,+ };+}++export default useOpenAfricaData;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/usePxWebData.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/usePxWebData.tsnew file mode 100644index 000000000..ec296b283--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/usePxWebData.ts@@ -0,0 +1,288 @@+// usePxWebData Hook - Browse and fetch Statistics Finland (PxWeb) data++import { useState, useCallback } from 'react';+import { invoke } from '@tauri-apps/api/core';+import type {+ PxWebView,+ PxWebNode,+ PxWebVariable,+ PxWebStatData,+ PxWebResponse,+} from '../types';++interface UsePxWebDataReturn {+ // View+ activeView: PxWebView;+ setActiveView: (view: PxWebView) => void;++ // Browse+ nodes: PxWebNode[];+ pathStack: string[];+ currentPath: string;+ fetchNodes: (path?: string) => Promise<void>;+ navigateInto: (node: PxWebNode) => void;+ navigateBack: () => void;++ // Metadata+ variables: PxWebVariable[];+ tableLabel: string;+ fetchMetadata: (tablePath: string) => Promise<void>;+ selectedTable: string | null;++ // Data+ statData: PxWebStatData | null;+ fetchData: (tablePath: string, query?: any[]) => Promise<void>;++ // Export+ exportCSV: () => void;++ // Shared state+ loading: boolean;+ error: string | null;+}++export function usePxWebData(): UsePxWebDataReturn {+ const [activeView, setActiveView] = useState<PxWebView>('browse');+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // Browse+ const [nodes, setNodes] = useState<PxWebNode[]>([]);+ const [pathStack, setPathStack] = useState<string[]>(['']);+ const [currentPath, setCurrentPath] = useState('');++ // Metadata+ const [variables, setVariables] = useState<PxWebVariable[]>([]);+ const [tableLabel, setTableLabel] = useState('');+ const [selectedTable, setSelectedTable] = useState<string | null>(null);++ // Data+ const [statData, setStatData] = useState<PxWebStatData | null>(null);++ const fetchNodes = useCallback(async (path: string = '') => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_pxweb_command', {+ command: 'nodes',+ args: path ? [path] : ([] as string[]),+ }) as string;++ const parsed: PxWebResponse = JSON.parse(result);+ if (!parsed.success) {+ setError(parsed.error || 'Failed to fetch nodes');+ setNodes([]);+ } else {+ const data = parsed.data;+ if (Array.isArray(data)) {+ setNodes(data.map((n: any) => ({+ dbid: n.dbid || '',+ id: n.id || '',+ type: n.type || 'l',+ text: n.text || '',+ description: n.description || '',+ updated: n.updated || '',+ })));+ } else {+ setNodes([]);+ }+ setCurrentPath(path);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch nodes: ${msg}`);+ setNodes([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const navigateInto = useCallback((node: PxWebNode) => {+ if (node.type === 't') {+ // It's a table — fetch metadata+ const tablePath = currentPath ? `${currentPath}/${node.id}` : node.id;+ setSelectedTable(tablePath);+ setActiveView('metadata');+ fetchMetadataInternal(tablePath);+ } else {+ // It's a folder — navigate deeper+ const newPath = currentPath ? `${currentPath}/${node.id}` : node.id;+ setPathStack(prev => [...prev, newPath]);+ fetchNodes(newPath);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [currentPath, fetchNodes]);++ const navigateBack = useCallback(() => {+ if (pathStack.length <= 1) return;+ const newStack = pathStack.slice(0, -1);+ setPathStack(newStack);+ const parentPath = newStack[newStack.length - 1] || '';+ fetchNodes(parentPath);+ }, [pathStack, fetchNodes]);++ const fetchMetadataInternal = async (tablePath: string) => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_pxweb_command', {+ command: 'metadata',+ args: [tablePath],+ }) as string;++ const parsed: PxWebResponse = JSON.parse(result);+ if (!parsed.success) {+ setError(parsed.error || 'Failed to fetch metadata');+ setVariables([]);+ } else {+ const data = parsed.data;+ // PxWeb metadata returns { title, variables: [...] }+ setTableLabel(data?.title || tablePath);+ const vars = data?.variables || [];+ setVariables(vars.map((v: any) => ({+ code: v.code || '',+ text: v.text || '',+ values: v.values || [],+ valueTexts: v.valueTexts || [],+ elimination: v.elimination || false,+ time: v.time || false,+ })));+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch metadata: ${msg}`);+ setVariables([]);+ } finally {+ setLoading(false);+ }+ };++ const fetchMetadata = useCallback(async (tablePath: string) => {+ setSelectedTable(tablePath);+ await fetchMetadataInternal(tablePath);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const fetchData = useCallback(async (tablePath: string, query: any[] = []) => {+ setLoading(true);+ setError(null);+ try {+ const args: string[] = [tablePath];+ if (query.length > 0) {+ args.push(JSON.stringify(query));+ }++ const result = await invoke('execute_pxweb_command', {+ command: 'data',+ args,+ }) as string;++ const parsed: PxWebResponse = JSON.parse(result);+ if (!parsed.success) {+ setError(parsed.error || 'Failed to fetch data');+ setStatData(null);+ } else {+ setStatData(parsed.data as PxWebStatData);+ setActiveView('data');+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch data: ${msg}`);+ setStatData(null);+ } finally {+ setLoading(false);+ }+ }, []);++ const exportCSV = useCallback(() => {+ if (activeView === 'browse' && nodes.length > 0) {+ const csv = [+ '# Statistics Finland - Database Nodes',+ '',+ 'Type,ID,Name,Updated',+ ...nodes.map(n =>+ `${n.type === 't' ? 'Table' : 'Folder'},${n.id},"${(n.text || '').replace(/"/g, '""')}",${n.updated || ''}`+ ),+ ].join('\n');+ downloadCSV(csv, 'fincept_statfin_nodes.csv');+ } else if (activeView === 'metadata' && variables.length > 0) {+ const csv = [+ `# Statistics Finland - Table Metadata: ${selectedTable}`,+ '',+ 'Variable,Values Count,Time Dim,Eliminable',+ ...variables.map(v =>+ `"${v.text}",${v.values.length},${v.time || false},${v.elimination || false}`+ ),+ ].join('\n');+ downloadCSV(csv, `fincept_statfin_meta_${selectedTable?.replace(/\//g, '_') || 'table'}.csv`);+ } else if (activeView === 'data' && statData?.value) {+ // Flatten json-stat2 into tabular CSV+ const dims = statData.id || [];+ const header = dims.map(d => statData.dimension?.[d]?.label || d).join(',') + ',Value';+ const dimCats = dims.map(d => {+ const cat = statData.dimension?.[d]?.category;+ const labels = cat?.label || {};+ const indexEntries = Object.entries(cat?.index || {}).sort((a, b) => a[1] - b[1]);+ return indexEntries.map(([k]) => labels[k] || k);+ });++ // Build rows via cartesian product+ const rows: string[] = [];+ const sizes = statData.size || dims.map((_, i) => dimCats[i].length);+ const totalValues = statData.value?.length || 0;++ for (let i = 0; i < totalValues; i++) {+ let remainder = i;+ const parts: string[] = [];+ for (let d = dims.length - 1; d >= 0; d--) {+ const dimSize = sizes[d];+ const idx = remainder % dimSize;+ remainder = Math.floor(remainder / dimSize);+ parts.unshift(`"${(dimCats[d]?.[idx] || '').replace(/"/g, '""')}"`);+ }+ parts.push(String(statData.value?.[i] ?? ''));+ rows.push(parts.join(','));+ }++ const csv = [+ `# Statistics Finland - Data: ${statData.label || selectedTable}`,+ '',+ header,+ ...rows,+ ].join('\n');+ downloadCSV(csv, `fincept_statfin_data_${selectedTable?.replace(/\//g, '_') || 'table'}.csv`);+ }+ }, [activeView, nodes, variables, statData, selectedTable]);++ return {+ activeView,+ setActiveView,+ nodes,+ pathStack,+ currentPath,+ fetchNodes,+ navigateInto,+ navigateBack,+ variables,+ tableLabel,+ fetchMetadata,+ selectedTable,+ statData,+ fetchData,+ exportCSV,+ loading,+ error,+ };+}++function downloadCSV(csv: string, filename: string) {+ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ URL.revokeObjectURL(url);+}++export default usePxWebData;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useSpainData.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useSpainData.tsnew file mode 100644index 000000000..44df7dcbd--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useSpainData.ts@@ -0,0 +1,287 @@+// useSpainData Hook - Fetch and manage Spain Open Data (datos.gob.es)++import { useState, useCallback } from 'react';+import { invoke } from '@tauri-apps/api/core';+import type {+ SpainDataView,+ SpainCatalogue,+ SpainDataset,+ SpainResource,+ SpainDataResponse,+} from '../types';++interface UseSpainDataReturn {+ // View+ activeView: SpainDataView;+ setActiveView: (view: SpainDataView) => void;++ // Catalogues (publishers)+ catalogues: SpainCatalogue[];+ selectedCatalogue: string | null;+ setSelectedCatalogue: (id: string | null) => void;+ fetchCatalogues: () => Promise<void>;++ // Datasets+ datasets: SpainDataset[];+ selectedDataset: string | null;+ setSelectedDataset: (id: string | null) => void;+ fetchDatasets: (publisherId?: string) => Promise<void>;+ datasetsPage: number;+ setDatasetsPage: (page: number) => void;++ // Resources+ resources: SpainResource[];+ fetchResources: (datasetId: string) => Promise<void>;++ // Search+ searchQuery: string;+ setSearchQuery: (query: string) => void;+ searchResults: SpainDataset[];+ searchDatasets: () => Promise<void>;++ // CSV export+ exportCSV: () => void;++ // Shared state+ loading: boolean;+ error: string | null;+}++/** Extract a displayable title from the multilingual title field */+function extractTitle(title: string | Array<{ _lang: string; _value: string }> | undefined): string {+ if (!title) return '';+ if (typeof title === 'string') return title;+ if (Array.isArray(title)) {+ // Prefer English, then Spanish, then first available+ const en = title.find(t => t._lang === 'en');+ if (en) return en._value;+ const es = title.find(t => t._lang === 'es');+ if (es) return es._value;+ return title[0]?._value || '';+ }+ return String(title);+}++/** Extract format label from format field */+function extractFormat(format: string | { label: string } | undefined): string {+ if (!format) return '?';+ if (typeof format === 'string') {+ if (format.startsWith('http')) return format.split('/').pop()?.toUpperCase() || '?';+ return format;+ }+ if (typeof format === 'object' && 'label' in format) return format.label;+ return '?';+}++export function useSpainData(): UseSpainDataReturn {+ const [activeView, setActiveView] = useState<SpainDataView>('catalogues');+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // Catalogues+ const [catalogues, setCatalogues] = useState<SpainCatalogue[]>([]);+ const [selectedCatalogue, setSelectedCatalogue] = useState<string | null>(null);++ // Datasets+ const [datasets, setDatasets] = useState<SpainDataset[]>([]);+ const [selectedDataset, setSelectedDataset] = useState<string | null>(null);+ const [datasetsPage, setDatasetsPage] = useState(1);++ // Resources+ const [resources, setResources] = useState<SpainResource[]>([]);++ // Search+ const [searchQuery, setSearchQuery] = useState('');+ const [searchResults, setSearchResults] = useState<SpainDataset[]>([]);++ const fetchCatalogues = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_spain_data_command', {+ command: 'catalogues',+ args: [] as string[],+ }) as string;++ const parsed: SpainDataResponse<{ items: SpainCatalogue[] }> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setCatalogues([]);+ } else {+ setCatalogues(parsed.data?.items || []);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch catalogues: ${msg}`);+ setCatalogues([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const fetchDatasets = useCallback(async (publisherId?: string) => {+ setLoading(true);+ setError(null);+ try {+ const args: string[] = [];+ if (publisherId) args.push(publisherId);+ args.push(String(datasetsPage));+ args.push('50');++ const result = await invoke('execute_spain_data_command', {+ command: 'datasets',+ args,+ }) as string;++ const parsed: SpainDataResponse<{ items: SpainDataset[] }> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setDatasets([]);+ } else {+ setDatasets(parsed.data?.items || []);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch datasets: ${msg}`);+ setDatasets([]);+ } finally {+ setLoading(false);+ }+ }, [datasetsPage]);++ const fetchResources = useCallback(async (datasetId: string) => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_spain_data_command', {+ command: 'resources',+ args: [datasetId],+ }) as string;++ const parsed: SpainDataResponse<SpainResource[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setResources([]);+ } else {+ setResources(Array.isArray(parsed.data) ? parsed.data : []);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch resources: ${msg}`);+ setResources([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const searchDatasetsAction = useCallback(async () => {+ if (!searchQuery.trim()) return;+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_spain_data_command', {+ command: 'search',+ args: [searchQuery.trim()],+ }) as string;++ const parsed: SpainDataResponse<{ items: SpainDataset[] }> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setSearchResults([]);+ } else {+ setSearchResults(parsed.data?.items || []);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to search datasets: ${msg}`);+ setSearchResults([]);+ } finally {+ setLoading(false);+ }+ }, [searchQuery]);++ const exportCSV = useCallback(() => {+ let csv = '';+ let filename = 'fincept_spain_';++ if (activeView === 'catalogues' && catalogues.length > 0) {+ csv = [+ '# Spain Open Data - Catalogues (Publishers)',+ '',+ 'ID,URI',+ ...catalogues.map(c => `${c.extracted_id},${c.uri}`),+ ].join('\n');+ filename += 'catalogues.csv';+ } else if (activeView === 'datasets' && datasets.length > 0) {+ csv = [+ `# Spain Open Data - Datasets${selectedCatalogue ? ` for ${selectedCatalogue}` : ''}`,+ '',+ 'ID,Title,Modified,Distributions',+ ...datasets.map(d => {+ const title = extractTitle(d.title);+ return `${d.extracted_id || ''},"${title.replace(/"/g, '""')}",${d.modified || ''},${d.distribution?.length || 0}`;+ }),+ ].join('\n');+ filename += `datasets_${selectedCatalogue || 'all'}.csv`;+ } else if (activeView === 'resources' && resources.length > 0) {+ csv = [+ `# Spain Open Data - Resources for ${selectedDataset}`,+ '',+ 'Index,Title,Format,URL',+ ...resources.map((r, i) => {+ const title = extractTitle(r.title);+ return `${i},"${title.replace(/"/g, '""')}",${extractFormat(r.format)},${r.accessURL || ''}`;+ }),+ ].join('\n');+ filename += `resources_${selectedDataset || 'unknown'}.csv`;+ } else if (activeView === 'search' && searchResults.length > 0) {+ csv = [+ `# Spain Open Data - Search: "${searchQuery}"`,+ '',+ 'ID,Title,Modified,Distributions',+ ...searchResults.map(d => {+ const title = extractTitle(d.title);+ return `${d.extracted_id || ''},"${title.replace(/"/g, '""')}",${d.modified || ''},${d.distribution?.length || 0}`;+ }),+ ].join('\n');+ filename += `search_${searchQuery.replace(/\s+/g, '_')}.csv`;+ } else {+ return;+ }++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ URL.revokeObjectURL(url);+ }, [activeView, catalogues, datasets, resources, searchResults, selectedCatalogue, selectedDataset, searchQuery]);++ return {+ activeView,+ setActiveView,+ catalogues,+ selectedCatalogue,+ setSelectedCatalogue,+ fetchCatalogues,+ datasets,+ selectedDataset,+ setSelectedDataset,+ fetchDatasets,+ datasetsPage,+ setDatasetsPage,+ resources,+ fetchResources,+ searchQuery,+ setSearchQuery,+ searchResults,+ searchDatasets: searchDatasetsAction,+ exportCSV,+ loading,+ error,+ };+}++export { extractTitle, extractFormat };+export default useSpainData;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useSwissGovData.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useSwissGovData.tsnew file mode 100644index 000000000..5e51301a5--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useSwissGovData.ts@@ -0,0 +1,344 @@+// useSwissGovData Hook - Fetch and manage Swiss Government open data (opendata.swiss)++import { useState, useCallback } from 'react';+import { invoke } from '@tauri-apps/api/core';+import type {+ SwissGovView,+ SwissPublisher,+ SwissDataset,+ SwissResource,+ SwissGovResponse,+} from '../types';++interface UseSwissGovDataReturn {+ // View+ activeView: SwissGovView;+ setActiveView: (view: SwissGovView) => void;++ // Publishers+ publishers: SwissPublisher[];+ selectedPublisher: string | null;+ setSelectedPublisher: (id: string | null) => void;+ fetchPublishers: () => Promise<void>;++ // Datasets+ datasets: SwissDataset[];+ selectedDataset: string | null;+ setSelectedDataset: (id: string | null) => void;+ fetchDatasets: (publisherId: string) => Promise<void>;+ datasetsTotalCount: number;++ // Resources+ resources: SwissResource[];+ fetchResources: (datasetId: string) => Promise<void>;++ // Search+ searchQuery: string;+ setSearchQuery: (query: string) => void;+ searchResults: SwissDataset[];+ searchTotalCount: number;+ searchDatasets: () => Promise<void>;++ // Recent+ recentDatasets: SwissDataset[];+ fetchRecentDatasets: () => Promise<void>;++ // CSV export+ exportCSV: () => void;++ // Shared state+ loading: boolean;+ error: string | null;+}++function parseDatasets(data: any): SwissDataset[] {+ if (!Array.isArray(data)) return [];+ return data.map((d: any) => ({+ id: d.id || '',+ name: d.name || '',+ title: d.title || d.name || '',+ original_title: d.original_title || d.title || '',+ notes: d.notes || '',+ original_notes: d.original_notes || d.notes || '',+ publisher_id: d.publisher_id || '',+ organization: d.organization || null,+ metadata_created: d.metadata_created || null,+ metadata_modified: d.metadata_modified || null,+ state: d.state || '',+ num_resources: d.num_resources || 0,+ tags: d.tags || [],+ language_detected: d.language_detected || undefined,+ }));+}++export function useSwissGovData(): UseSwissGovDataReturn {+ const [activeView, setActiveView] = useState<SwissGovView>('publishers');+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // Publishers+ const [publishers, setPublishers] = useState<SwissPublisher[]>([]);+ const [selectedPublisher, setSelectedPublisher] = useState<string | null>(null);++ // Datasets+ const [datasets, setDatasets] = useState<SwissDataset[]>([]);+ const [datasetsTotalCount, setDatasetsTotalCount] = useState(0);+ const [selectedDataset, setSelectedDataset] = useState<string | null>(null);++ // Resources+ const [resources, setResources] = useState<SwissResource[]>([]);++ // Search+ const [searchQuery, setSearchQuery] = useState('');+ const [searchResults, setSearchResults] = useState<SwissDataset[]>([]);+ const [searchTotalCount, setSearchTotalCount] = useState(0);++ // Recent+ const [recentDatasets, setRecentDatasets] = useState<SwissDataset[]>([]);++ const fetchPublishers = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_swiss_gov_command', {+ command: 'publishers',+ args: [] as string[],+ }) as string;++ const parsed: SwissGovResponse<SwissPublisher[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setPublishers([]);+ } else {+ const data = parsed.data || [];+ setPublishers(data.map((p: any) => ({+ id: p.id || '',+ name: p.name || p.display_name || '',+ original_name: p.original_name || p.name || '',+ display_name: p.display_name || p.name || '',+ })));+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch publishers: ${msg}`);+ setPublishers([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const fetchDatasets = useCallback(async (publisherId: string) => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_swiss_gov_command', {+ command: 'datasets',+ args: [publisherId, '100'],+ }) as string;++ const parsed: SwissGovResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setDatasets([]);+ setDatasetsTotalCount(0);+ } else {+ setDatasets(parseDatasets(parsed.data));+ setDatasetsTotalCount(parsed.metadata?.total_count || parsed.metadata?.returned_count || 0);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch datasets: ${msg}`);+ setDatasets([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const fetchResources = useCallback(async (datasetId: string) => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_swiss_gov_command', {+ command: 'resources',+ args: [datasetId],+ }) as string;++ const parsed: SwissGovResponse<any[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setResources([]);+ } else {+ const data = parsed.data || [];+ setResources(data.map((r: any) => ({+ id: r.id || '',+ name: r.name || '',+ original_name: r.original_name || r.name || '',+ description: r.description || '',+ original_description: r.original_description || r.description || '',+ format: r.format || '',+ url: r.url || '',+ size: r.size || null,+ mimetype: r.mimetype || null,+ created: r.created || null,+ last_modified: r.last_modified || null,+ resource_type: r.resource_type || null,+ package_id: r.package_id || datasetId,+ position: r.position ?? null,+ language_detected: r.language_detected || undefined,+ })));+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch resources: ${msg}`);+ setResources([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const searchDatasetsAction = useCallback(async () => {+ if (!searchQuery.trim()) return;+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_swiss_gov_command', {+ command: 'search',+ args: [searchQuery.trim(), '50'],+ }) as string;++ const parsed: SwissGovResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setSearchResults([]);+ setSearchTotalCount(0);+ } else {+ setSearchResults(parseDatasets(parsed.data));+ setSearchTotalCount(parsed.metadata?.total_count || 0);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to search datasets: ${msg}`);+ setSearchResults([]);+ } finally {+ setLoading(false);+ }+ }, [searchQuery]);++ const fetchRecentDatasets = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_swiss_gov_command', {+ command: 'recent-datasets',+ args: ['50'],+ }) as string;++ const parsed: SwissGovResponse<any> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setRecentDatasets([]);+ } else {+ setRecentDatasets(parseDatasets(parsed.data));+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch recent datasets: ${msg}`);+ setRecentDatasets([]);+ } finally {+ setLoading(false);+ }+ }, []);++ const exportCSV = useCallback(() => {+ let csv = '';+ let filename = 'fincept_swiss_gov_';++ if (activeView === 'publishers' && publishers.length > 0) {+ csv = [+ '# opendata.swiss - Publishers',+ '',+ 'ID,Name,Original Name',+ ...publishers.map(p => `${p.id},"${(p.name || '').replace(/"/g, '""')}","${(p.original_name || '').replace(/"/g, '""')}"`),+ ].join('\n');+ filename += 'publishers.csv';+ } else if (activeView === 'datasets' && datasets.length > 0) {+ csv = [+ `# opendata.swiss - Datasets for ${selectedPublisher}`,+ '',+ 'ID,Title,Original Title,Resources,Modified,Tags',+ ...datasets.map(d =>+ `${d.id},"${(d.title || '').replace(/"/g, '""')}","${(d.original_title || '').replace(/"/g, '""')}",${d.num_resources},${d.metadata_modified || ''},"${d.tags.join('; ')}"`+ ),+ ].join('\n');+ filename += `datasets_${selectedPublisher || 'all'}.csv`;+ } else if (activeView === 'resources' && resources.length > 0) {+ csv = [+ `# opendata.swiss - Resources for ${selectedDataset}`,+ '',+ 'ID,Name,Original Name,Format,Size,URL,Last Modified',+ ...resources.map(r =>+ `${r.id},"${(r.name || '').replace(/"/g, '""')}","${(r.original_name || '').replace(/"/g, '""')}",${r.format},${r.size || ''},${r.url},${r.last_modified || ''}`+ ),+ ].join('\n');+ filename += `resources_${selectedDataset || 'unknown'}.csv`;+ } else if (activeView === 'search' && searchResults.length > 0) {+ csv = [+ `# opendata.swiss - Search: "${searchQuery}"`,+ '',+ 'ID,Title,Original Title,Organization,Resources,Modified,Tags',+ ...searchResults.map(d =>+ `${d.id},"${(d.title || '').replace(/"/g, '""')}","${(d.original_title || '').replace(/"/g, '""')}",${d.organization || ''},${d.num_resources},${d.metadata_modified || ''},"${d.tags.join('; ')}"`+ ),+ ].join('\n');+ filename += `search_${searchQuery.replace(/\s+/g, '_')}.csv`;+ } else if (activeView === 'recent' && recentDatasets.length > 0) {+ csv = [+ '# opendata.swiss - Recent Datasets',+ '',+ 'ID,Title,Original Title,Organization,Resources,Modified,Tags',+ ...recentDatasets.map(d =>+ `${d.id},"${(d.title || '').replace(/"/g, '""')}","${(d.original_title || '').replace(/"/g, '""')}",${d.organization || ''},${d.num_resources},${d.metadata_modified || ''},"${d.tags.join('; ')}"`+ ),+ ].join('\n');+ filename += 'recent.csv';+ } else {+ return;+ }++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ URL.revokeObjectURL(url);+ }, [activeView, publishers, datasets, resources, searchResults, recentDatasets, selectedPublisher, selectedDataset, searchQuery]);++ return {+ activeView,+ setActiveView,+ publishers,+ selectedPublisher,+ setSelectedPublisher,+ fetchPublishers,+ datasets,+ selectedDataset,+ setSelectedDataset,+ fetchDatasets,+ datasetsTotalCount,+ resources,+ fetchResources,+ searchQuery,+ setSearchQuery,+ searchResults,+ searchTotalCount,+ searchDatasets: searchDatasetsAction,+ recentDatasets,+ fetchRecentDatasets,+ exportCSV,+ loading,+ error,+ };+}++export default useSwissGovData;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useUSTreasuryData.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useUSTreasuryData.tsnew file mode 100644index 000000000..0c18e8eaa--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useUSTreasuryData.ts@@ -0,0 +1,284 @@+// useUSTreasuryData Hook - Fetch and manage US Treasury data++import { useState, useCallback } from 'react';+import { invoke } from '@tauri-apps/api/core';+import { getDateFromPreset } from '@/components/common/charts';+import type { DateRangePreset } from '@/components/common/charts';+import type {+ USTreasuryEndpoint,+ SecurityTypeFilter,+ TreasuryPricesResponse,+ TreasuryAuctionsResponse,+ TreasurySummaryResponse,+} from '../types';++interface UseUSTreasuryDataReturn {+ // Endpoint selection+ activeEndpoint: USTreasuryEndpoint;+ setActiveEndpoint: (endpoint: USTreasuryEndpoint) => void;++ // Unified date range (matches economics tab pattern)+ dateRangePreset: DateRangePreset;+ setDateRangePreset: (preset: DateRangePreset) => void;+ startDate: string;+ endDate: string;+ setStartDate: (date: string) => void;+ setEndDate: (date: string) => void;++ // Prices state+ pricesData: TreasuryPricesResponse | null;+ pricesSecurityType: SecurityTypeFilter;+ setPricesSecurityType: (type: SecurityTypeFilter) => void;+ pricesCusip: string;+ setPricesCusip: (cusip: string) => void;+ fetchPrices: () => Promise<void>;++ // Auctions state+ auctionsData: TreasuryAuctionsResponse | null;+ auctionsSecurityType: string;+ setAuctionsSecurityType: (type: string) => void;+ auctionsPageSize: number;+ setAuctionsPageSize: (size: number) => void;+ auctionsPageNum: number;+ setAuctionsPageNum: (page: number) => void;+ fetchAuctions: () => Promise<void>;++ // Summary state+ summaryData: TreasurySummaryResponse | null;+ fetchSummary: () => Promise<void>;++ // Export (CSV only — image uses shared useExport in Provider)+ exportCSV: () => void;++ // Shared state+ loading: boolean;+ error: string | null;+}++const getDefaultDate = (): string => {+ const now = new Date();+ // Treasury prices are published EOD, so today's data won't exist yet.+ // Default to the previous business day.+ now.setDate(now.getDate() - 1);+ const day = now.getDay();+ if (day === 0) now.setDate(now.getDate() - 2); // Sunday -> Friday+ else if (day === 6) now.setDate(now.getDate() - 1); // Saturday -> Friday+ return now.toISOString().split('T')[0];+};++export function useUSTreasuryData(): UseUSTreasuryDataReturn {+ const [activeEndpoint, setActiveEndpoint] = useState<USTreasuryEndpoint>('treasury_prices');+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // Unified date range — same pattern as economics tab+ const initialDates = getDateFromPreset('1M');+ const [dateRangePreset, setDateRangePresetState] = useState<DateRangePreset>('1M');+ const [startDate, setStartDate] = useState(initialDates.start);+ const [endDate, setEndDate] = useState(getDefaultDate());++ const setDateRangePreset = useCallback((preset: DateRangePreset) => {+ setDateRangePresetState(preset);+ const dates = getDateFromPreset(preset);+ setStartDate(dates.start);+ setEndDate(getDefaultDate());+ }, []);++ // Prices state+ const [pricesData, setPricesData] = useState<TreasuryPricesResponse | null>(null);+ const [pricesSecurityType, setPricesSecurityType] = useState<SecurityTypeFilter>('all');+ const [pricesCusip, setPricesCusip] = useState('');++ // Auctions state+ const [auctionsData, setAuctionsData] = useState<TreasuryAuctionsResponse | null>(null);+ const [auctionsSecurityType, setAuctionsSecurityType] = useState('all');+ const [auctionsPageSize, setAuctionsPageSize] = useState(50);+ const [auctionsPageNum, setAuctionsPageNum] = useState(1);++ // Summary state+ const [summaryData, setSummaryData] = useState<TreasurySummaryResponse | null>(null);++ const fetchPrices = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ // Prices use endDate as the single date parameter+ const args: string[] = [endDate];+ if (pricesCusip.trim()) {+ args.push(pricesCusip.trim());+ }+ if (pricesSecurityType !== 'all') {+ if (!pricesCusip.trim()) args.push('');+ args.push(pricesSecurityType);+ }++ const result = await invoke('execute_government_us_command', {+ command: 'treasury_prices',+ args,+ }) as string;++ const parsed: TreasuryPricesResponse = JSON.parse(result);+ if (!parsed.success) {+ setError(parsed.error || 'Failed to fetch treasury prices');+ setPricesData(null);+ } else {+ setPricesData(parsed);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch prices: ${msg}`);+ setPricesData(null);+ } finally {+ setLoading(false);+ }+ }, [endDate, pricesSecurityType, pricesCusip]);++ const fetchAuctions = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const args: string[] = [startDate, endDate];+ if (auctionsSecurityType !== 'all') {+ args.push(auctionsSecurityType);+ } else {+ args.push('');+ }+ args.push(String(auctionsPageSize));+ args.push(String(auctionsPageNum));++ const result = await invoke('execute_government_us_command', {+ command: 'treasury_auctions',+ args,+ }) as string;++ const parsed: TreasuryAuctionsResponse = JSON.parse(result);+ if (!parsed.success) {+ setError(parsed.error || 'Failed to fetch auctions');+ setAuctionsData(null);+ } else {+ setAuctionsData(parsed);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch auctions: ${msg}`);+ setAuctionsData(null);+ } finally {+ setLoading(false);+ }+ }, [startDate, endDate, auctionsSecurityType, auctionsPageSize, auctionsPageNum]);++ const fetchSummary = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('execute_government_us_command', {+ command: 'summary',+ args: [endDate],+ }) as string;++ const parsed: TreasurySummaryResponse = JSON.parse(result);+ if (!parsed.success) {+ setError(parsed.error || 'Failed to fetch summary');+ setSummaryData(null);+ } else {+ setSummaryData(parsed);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch summary: ${msg}`);+ setSummaryData(null);+ } finally {+ setLoading(false);+ }+ }, [endDate]);++ // CSV export — browser download+ const exportCSV = useCallback(() => {+ let csv = '';+ let filename = 'fincept_govt_';++ if (activeEndpoint === 'treasury_prices' && pricesData) {+ csv = [+ `# US Treasury Prices - ${pricesData.date}`,+ `# Records: ${pricesData.total_records}`,+ '',+ 'CUSIP,Security Type,Rate,Maturity Date,Bid,Offer,EOD Price',+ ...pricesData.data.map(r =>+ `${r.cusip},${r.security_type},${r.rate ?? ''},${r.maturity_date ?? ''},${r.bid ?? ''},${r.offer ?? ''},${r.eod_price ?? ''}`+ ),+ ].join('\n');+ filename += `prices_${pricesData.date}.csv`;+ } else if (activeEndpoint === 'treasury_auctions' && auctionsData) {+ const keys = ['cusip', 'securityType', 'securityTerm', 'auctionDate', 'issueDate', 'maturityDate',+ 'highDiscountRate', 'highPrice', 'bidToCoverRatio', 'offeringAmount', 'totalAccepted', 'allocationPercentage'];+ csv = [+ `# US Treasury Auctions - ${auctionsData.filters.start_date} to ${auctionsData.filters.end_date}`,+ `# Records: ${auctionsData.total_records}`,+ '',+ keys.join(','),+ ...auctionsData.data.map(r => keys.map(k => r[k] ?? '').join(',')),+ ].join('\n');+ filename += `auctions_${auctionsData.filters.start_date}_${auctionsData.filters.end_date}.csv`;+ } else if (activeEndpoint === 'summary' && summaryData) {+ csv = [+ `# US Treasury Summary - ${summaryData.date}`,+ `# Total Securities: ${summaryData.total_securities}`,+ '',+ 'Metric,Value',+ `Total Securities,${summaryData.total_securities}`,+ `Min Rate,${summaryData.yield_summary.min_rate}`,+ `Max Rate,${summaryData.yield_summary.max_rate}`,+ `Avg Rate,${summaryData.yield_summary.avg_rate}`,+ `Min Price,${summaryData.price_summary.min_price}`,+ `Max Price,${summaryData.price_summary.max_price}`,+ `Avg Price,${summaryData.price_summary.avg_price}`,+ '',+ 'Security Type,Count',+ ...Object.entries(summaryData.security_types).map(([k, v]) => `${k},${v}`),+ ].join('\n');+ filename += `summary_${summaryData.date}.csv`;+ } else {+ return;+ }++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ URL.revokeObjectURL(url);+ }, [activeEndpoint, pricesData, auctionsData, summaryData]);++ return {+ activeEndpoint,+ setActiveEndpoint,+ dateRangePreset,+ setDateRangePreset,+ startDate,+ endDate,+ setStartDate,+ setEndDate,+ pricesData,+ pricesSecurityType,+ setPricesSecurityType,+ pricesCusip,+ setPricesCusip,+ fetchPrices,+ auctionsData,+ auctionsSecurityType,+ setAuctionsSecurityType,+ auctionsPageSize,+ setAuctionsPageSize,+ auctionsPageNum,+ setAuctionsPageNum,+ fetchAuctions,+ summaryData,+ fetchSummary,+ exportCSV,+ loading,+ error,+ };+}++export default useUSTreasuryData;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useUniversalCkanData.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useUniversalCkanData.tsnew file mode 100644index 000000000..689de3df9--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/hooks/useUniversalCkanData.ts@@ -0,0 +1,321 @@+// useUniversalCkanData Hook - Multi-portal CKAN data access+// Supports 8 CKAN portals: US, UK, AU, IT, BR, LV, SI, UY++import { useState, useCallback } from 'react';+import { invoke } from '@tauri-apps/api/core';+import type {+ CkanView,+ CkanOrganization,+ CkanDataset,+ CkanResource,+ CkanResponse,+} from '../types';++interface UseUniversalCkanDataReturn {+ // View+ activeView: CkanView;+ setActiveView: (view: CkanView) => void;++ // Portal selection+ activePortal: string;+ setActivePortal: (code: string) => void;++ // Organizations+ organizations: CkanOrganization[];+ selectedOrg: string | null;+ setSelectedOrg: (id: string | null) => void;+ fetchOrganizations: () => Promise<void>;++ // Datasets+ datasets: CkanDataset[];+ selectedDataset: string | null;+ setSelectedDataset: (id: string | null) => void;+ fetchDatasets: (orgId: string) => Promise<void>;+ datasetsTotalCount: number;++ // Resources+ resources: CkanResource[];+ fetchResources: (datasetId: string) => Promise<void>;++ // Search+ searchQuery: string;+ setSearchQuery: (query: string) => void;+ searchResults: CkanDataset[];+ searchTotalCount: number;+ searchDatasets: () => Promise<void>;++ // CSV export+ exportCSV: () => void;++ // Shared state+ loading: boolean;+ error: string | null;+}++function parseTags(tags: any): string[] {+ if (!Array.isArray(tags)) return [];+ return tags.map((t: any) => (typeof t === 'string' ? t : t?.name || t?.display_name || '')).filter(Boolean);+}++export function useUniversalCkanData(): UseUniversalCkanDataReturn {+ const [activeView, setActiveView] = useState<CkanView>('organizations');+ const [activePortal, setActivePortal] = useState('us');+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // Organizations+ const [organizations, setOrganizations] = useState<CkanOrganization[]>([]);+ const [selectedOrg, setSelectedOrg] = useState<string | null>(null);++ // Datasets+ const [datasets, setDatasets] = useState<CkanDataset[]>([]);+ const [datasetsTotalCount, setDatasetsTotalCount] = useState(0);+ const [selectedDataset, setSelectedDataset] = useState<string | null>(null);++ // Resources+ const [resources, setResources] = useState<CkanResource[]>([]);++ // Search+ const [searchQuery, setSearchQuery] = useState('');+ const [searchResults, setSearchResults] = useState<CkanDataset[]>([]);+ const [searchTotalCount, setSearchTotalCount] = useState(0);++ const fetchOrganizations = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('list_ckan_organizations', {+ country: activePortal,+ limit: 200,+ }) as string;++ const parsed: CkanResponse<CkanOrganization[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setOrganizations([]);+ } else {+ const data = Array.isArray(parsed.data) ? parsed.data : [];+ setOrganizations(data.map((o: any) => ({+ name: o.name || '',+ display_name: o.display_name || o.name || '',+ country: o.country || activePortal.toUpperCase(),+ })));+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch organizations: ${msg}`);+ setOrganizations([]);+ } finally {+ setLoading(false);+ }+ }, [activePortal]);++ const fetchDatasets = useCallback(async (orgId: string) => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('search_ckan_datasets', {+ country: activePortal,+ query: null as string | null,+ limit: 50,+ organization: orgId,+ }) as string;++ const parsed: CkanResponse<any[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setDatasets([]);+ setDatasetsTotalCount(0);+ } else {+ const data = Array.isArray(parsed.data) ? parsed.data : [];+ setDatasets(data.map((d: any) => ({+ id: d.id || d.name || '',+ name: d.name || '',+ display_name: d.display_name || d.title || d.name || '',+ title: d.title || d.display_name || '',+ notes: d.notes || '',+ organization_name: d.organization_name || d.organization?.title || '',+ organization: d.organization,+ num_resources: d.num_resources || 0,+ metadata_created: d.metadata_created || '',+ metadata_modified: d.metadata_modified || '',+ tags: d.tags || [],+ resource_types: d.resource_types || [],+ })));+ setDatasetsTotalCount(parsed.metadata?.count || data.length);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch datasets: ${msg}`);+ setDatasets([]);+ } finally {+ setLoading(false);+ }+ }, [activePortal]);++ const fetchResources = useCallback(async (datasetId: string) => {+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('get_ckan_dataset_resources', {+ country: activePortal,+ datasetId,+ }) as string;++ const parsed: CkanResponse<any[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setResources([]);+ } else {+ const data = Array.isArray(parsed.data) ? parsed.data : [];+ setResources(data.map((r: any) => ({+ id: r.id || '',+ name: r.name || r.description || '',+ description: r.description || '',+ format: r.format || '',+ url: r.url || '',+ size: r.size || null,+ mimetype: r.mimetype || null,+ created: r.created || null,+ last_modified: r.last_modified || null,+ dataset_name: r.dataset_name || '',+ dataset_title: r.dataset_title || '',+ organization: r.organization || '',+ })));+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to fetch resources: ${msg}`);+ setResources([]);+ } finally {+ setLoading(false);+ }+ }, [activePortal]);++ const searchDatasetsAction = useCallback(async () => {+ if (!searchQuery.trim()) return;+ setLoading(true);+ setError(null);+ try {+ const result = await invoke('search_ckan_datasets', {+ country: activePortal,+ query: searchQuery.trim(),+ limit: 50,+ organization: null as string | null,+ }) as string;++ const parsed: CkanResponse<any[]> = JSON.parse(result);+ if (parsed.error) {+ setError(parsed.error);+ setSearchResults([]);+ setSearchTotalCount(0);+ } else {+ const data = Array.isArray(parsed.data) ? parsed.data : [];+ setSearchResults(data.map((d: any) => ({+ id: d.id || d.name || '',+ name: d.name || '',+ display_name: d.display_name || d.title || d.name || '',+ title: d.title || d.display_name || '',+ notes: d.notes || '',+ organization_name: d.organization_name || d.organization?.title || '',+ organization: d.organization,+ num_resources: d.num_resources || 0,+ metadata_created: d.metadata_created || '',+ metadata_modified: d.metadata_modified || '',+ tags: d.tags || [],+ resource_types: d.resource_types || [],+ })));+ setSearchTotalCount(parsed.metadata?.count || data.length);+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(`Failed to search datasets: ${msg}`);+ setSearchResults([]);+ } finally {+ setLoading(false);+ }+ }, [activePortal, searchQuery]);++ const exportCSV = useCallback(() => {+ let csv = '';+ let filename = `fincept_ckan_${activePortal}_`;++ if (activeView === 'organizations' && organizations.length > 0) {+ csv = [+ `# CKAN Portal ${activePortal.toUpperCase()} - Organizations`,+ '',+ 'Name,Display Name',+ ...organizations.map(o => `${o.name},"${(o.display_name || '').replace(/"/g, '""')}"`),+ ].join('\n');+ filename += 'organizations.csv';+ } else if (activeView === 'datasets' && datasets.length > 0) {+ csv = [+ `# CKAN Portal ${activePortal.toUpperCase()} - Datasets (Org: ${selectedOrg})`,+ '',+ 'Name,Title,Organization,Resources,Modified,Tags',+ ...datasets.map(d =>+ `${d.name},"${(d.title || '').replace(/"/g, '""')}","${(d.organization_name || '').replace(/"/g, '""')}",${d.num_resources || 0},${d.metadata_modified || ''},"${parseTags(d.tags).join('; ')}"`+ ),+ ].join('\n');+ filename += `datasets_${selectedOrg || 'all'}.csv`;+ } else if (activeView === 'resources' && resources.length > 0) {+ csv = [+ `# CKAN Portal ${activePortal.toUpperCase()} - Resources (Dataset: ${selectedDataset})`,+ '',+ 'ID,Name,Format,Size,URL,Last Modified',+ ...resources.map(r =>+ `${r.id},"${(r.name || '').replace(/"/g, '""')}",${r.format},${r.size || ''},${r.url},${r.last_modified || ''}`+ ),+ ].join('\n');+ filename += `resources_${selectedDataset || 'unknown'}.csv`;+ } else if (activeView === 'search' && searchResults.length > 0) {+ csv = [+ `# CKAN Portal ${activePortal.toUpperCase()} - Search: "${searchQuery}"`,+ '',+ 'Name,Title,Organization,Resources,Modified,Tags',+ ...searchResults.map(d =>+ `${d.name},"${(d.title || '').replace(/"/g, '""')}","${(d.organization_name || '').replace(/"/g, '""')}",${d.num_resources || 0},${d.metadata_modified || ''},"${parseTags(d.tags).join('; ')}"`+ ),+ ].join('\n');+ filename += `search_${searchQuery.replace(/\s+/g, '_')}.csv`;+ } else {+ return;+ }++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ URL.revokeObjectURL(url);+ }, [activeView, activePortal, organizations, datasets, resources, searchResults, selectedOrg, selectedDataset, searchQuery]);++ return {+ activeView,+ setActiveView,+ activePortal,+ setActivePortal,+ organizations,+ selectedOrg,+ setSelectedOrg,+ fetchOrganizations,+ datasets,+ selectedDataset,+ setSelectedDataset,+ fetchDatasets,+ datasetsTotalCount,+ resources,+ fetchResources,+ searchQuery,+ setSearchQuery,+ searchResults,+ searchTotalCount,+ searchDatasets: searchDatasetsAction,+ exportCSV,+ loading,+ error,+ };+}++export default useUniversalCkanData;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/index.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/index.tsnew file mode 100644index 000000000..08869d52b--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/index.ts@@ -0,0 +1,2 @@+export { default } from './GovDataTab';+export { default as GovDataTab } from './GovDataTab';diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/CanadaGovProvider.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/CanadaGovProvider.tsxnew file mode 100644index 000000000..ceb2a01e2--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/CanadaGovProvider.tsx@@ -0,0 +1,506 @@+// CanadaGovProvider - Government of Canada Open Data portal interface+// Hierarchical browsing: Publishers -> Datasets -> Resources + Search & Recent++import React, { useEffect, useCallback } from 'react';+import { RefreshCw, AlertCircle, Database, Download, Search, ChevronRight, ExternalLink, FileText, ArrowLeft, Clock } from 'lucide-react';+import { FINCEPT } from '../constants';+import { useCanadaGovData } from '../hooks/useCanadaGovData';+import type { CanadaGovView, CanadaDataset, CanadaResource } from '../types';++const VIEWS: { id: CanadaGovView; label: string }[] = [+ { id: 'publishers', label: 'PUBLISHERS' },+ { id: 'datasets', label: 'DATASETS' },+ { id: 'search', label: 'SEARCH' },+ { id: 'recent', label: 'RECENT' },+];++const PROVIDER_COLOR = '#EF4444';++const truncate = (text: string, max: number): string =>+ text.length > max ? text.substring(0, max) + '...' : text;++const formatDate = (dateStr: string | null): string => {+ if (!dateStr) return '-';+ return dateStr.substring(0, 10);+};++const formatSize = (bytes: number | null): string => {+ if (!bytes) return '-';+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+};++export function CanadaGovProvider() {+ const {+ activeView, setActiveView,+ publishers, selectedPublisher, setSelectedPublisher, fetchPublishers,+ datasets, selectedDataset, setSelectedDataset, fetchDatasets, datasetsTotalCount,+ resources, fetchResources,+ searchQuery, setSearchQuery, searchResults, searchTotalCount, searchDatasets,+ recentDatasets, fetchRecentDatasets,+ exportCSV,+ loading, error,+ } = useCanadaGovData();++ // Load publishers on mount+ useEffect(() => {+ fetchPublishers();+ }, [fetchPublishers]);++ const handleViewChange = (view: CanadaGovView) => {+ setActiveView(view);+ if (view === 'recent' && recentDatasets.length === 0) {+ fetchRecentDatasets();+ }+ };++ const handlePublisherClick = (publisherId: string) => {+ setSelectedPublisher(publisherId);+ setSelectedDataset(null);+ setActiveView('datasets');+ fetchDatasets(publisherId);+ };++ const handleDatasetClick = (datasetId: string) => {+ setSelectedDataset(datasetId);+ setActiveView('resources');+ fetchResources(datasetId);+ };++ const handleBack = () => {+ if (activeView === 'resources') {+ setActiveView('datasets');+ setSelectedDataset(null);+ } else if (activeView === 'datasets') {+ setActiveView('publishers');+ setSelectedPublisher(null);+ }+ };++ const handleSearchKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === 'Enter') searchDatasets();+ };++ const inputStyle: React.CSSProperties = {+ padding: '6px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '11px',+ outline: 'none',+ fontFamily: 'inherit',+ };++ const hasData = (activeView === 'publishers' && publishers.length > 0)+ || (activeView === 'datasets' && datasets.length > 0)+ || (activeView === 'resources' && resources.length > 0)+ || (activeView === 'search' && searchResults.length > 0)+ || (activeView === 'recent' && recentDatasets.length > 0);++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Header bar */}+ <div style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ flexWrap: 'wrap',+ }}>+ {/* Back button for drill-down views */}+ {(activeView === 'datasets' || activeView === 'resources') && (+ <button+ onClick={handleBack}+ style={{+ padding: '5px 8px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <ArrowLeft size={11} />+ BACK+ </button>+ )}++ {/* View selector */}+ <div style={{ display: 'flex', gap: '2px', marginRight: '12px' }}>+ {VIEWS.map(v => (+ <button+ key={v.id}+ onClick={() => handleViewChange(v.id)}+ style={{+ padding: '5px 12px',+ backgroundColor: activeView === v.id ? PROVIDER_COLOR : 'transparent',+ color: activeView === v.id ? FINCEPT.WHITE : FINCEPT.GRAY,+ border: `1px solid ${activeView === v.id ? PROVIDER_COLOR : FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ }}+ >+ {v.label}+ </button>+ ))}+ </div>++ {/* Search input (shown when search view) */}+ {activeView === 'search' && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flex: 1, maxWidth: '400px' }}>+ <Search size={14} color={FINCEPT.GRAY} />+ <input+ type="text"+ value={searchQuery}+ onChange={e => setSearchQuery(e.target.value)}+ onKeyDown={handleSearchKeyDown}+ placeholder="Search Canadian datasets..."+ style={{ ...inputStyle, flex: 1 }}+ />+ <button+ onClick={searchDatasets}+ disabled={loading || !searchQuery.trim()}+ style={{+ padding: '6px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading || !searchQuery.trim() ? 'not-allowed' : 'pointer',+ opacity: loading || !searchQuery.trim() ? 0.5 : 1,+ }}+ >+ SEARCH+ </button>+ </div>+ )}++ {/* Breadcrumb */}+ {(activeView === 'datasets' && selectedPublisher) && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>Publishers</span>+ <ChevronRight size={10} />+ <span style={{ color: PROVIDER_COLOR }}>{selectedPublisher}</span>+ <span style={{ color: FINCEPT.MUTED }}>({datasetsTotalCount} datasets)</span>+ </div>+ )}+ {(activeView === 'resources' && selectedDataset) && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>Publishers</span>+ <ChevronRight size={10} />+ <span>{selectedPublisher}</span>+ <ChevronRight size={10} />+ <span style={{ color: PROVIDER_COLOR }}>{truncate(selectedDataset, 30)}</span>+ </div>+ )}++ {/* Actions */}+ <div style={{ marginLeft: 'auto', display: 'flex', gap: '4px' }}>+ {hasData && (+ <button+ onClick={exportCSV}+ title="Export CSV"+ style={{+ padding: '5px 10px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <Download size={11} />+ CSV+ </button>+ )}+ {activeView === 'publishers' && (+ <button+ onClick={fetchPublishers}+ disabled={loading}+ style={{+ padding: '5px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: loading ? 0.7 : 1,+ }}+ >+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />+ REFRESH+ </button>+ )}+ </div>+ </div>++ {/* Content area */}+ <div style={{ flex: 1, overflow: 'auto' }}>+ {loading ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <RefreshCw size={32} className="animate-spin" style={{ color: PROVIDER_COLOR, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>Loading Canadian government data...</div>+ </div>+ ) : error ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <AlertCircle size={32} style={{ color: FINCEPT.RED, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.RED, marginBottom: '8px' }}>Error loading data</div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '400px' }}>{error}</div>+ </div>+ ) : activeView === 'publishers' ? (+ <PublishersTable publishers={publishers} onSelect={handlePublisherClick} />+ ) : activeView === 'datasets' ? (+ <DatasetsTable datasets={datasets} onSelect={handleDatasetClick} totalCount={datasetsTotalCount} />+ ) : activeView === 'resources' ? (+ <ResourcesTable resources={resources} />+ ) : activeView === 'search' ? (+ searchResults.length > 0+ ? <DatasetsTable datasets={searchResults} onSelect={handleDatasetClick} totalCount={searchTotalCount} />+ : <EmptyState icon={Search} message="Search Canadian government datasets" sub="Enter a query above and press SEARCH or Enter" />+ ) : activeView === 'recent' ? (+ recentDatasets.length > 0+ ? <DatasetsTable datasets={recentDatasets} onSelect={handleDatasetClick} totalCount={recentDatasets.length} />+ : <EmptyState icon={Clock} message="Loading recent datasets..." sub="" />+ ) : (+ <EmptyState icon={Database} message="Select a view" sub="" />+ )}+ </div>+ </div>+ );+}++// ===== Sub-components =====++function EmptyState({ icon: Icon, message, sub }: { icon: React.ElementType; message: string; sub: string }) {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <Icon size={48} style={{ color: FINCEPT.MUTED, marginBottom: '16px', opacity: 0.5 }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE, marginBottom: '8px' }}>{message}</div>+ {sub && <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>{sub}</div>}+ </div>+ );+}++function PublishersTable({ publishers, onSelect }: { publishers: { id: string; name: string }[]; onSelect: (id: string) => void }) {+ return (+ <div style={{ padding: '0' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>PUBLISHER ID</th>+ <th style={thStyle}>NAME</th>+ <th style={{ ...thStyle, width: '60px' }}></th>+ </tr>+ </thead>+ <tbody>+ {publishers.map(p => (+ <tr+ key={p.id}+ onClick={() => onSelect(p.id)}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={{ ...tdStyle, color: PROVIDER_COLOR, fontWeight: 600 }}>{p.id}</td>+ <td style={tdStyle}>{p.name}</td>+ <td style={tdStyle}>+ <ChevronRight size={14} color={FINCEPT.MUTED} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function DatasetsTable({ datasets, onSelect, totalCount }: { datasets: CanadaDataset[]; onSelect: (id: string) => void; totalCount: number }) {+ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ Showing {datasets.length} of {totalCount} datasets+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>TITLE</th>+ <th style={{ ...thStyle, width: '80px' }}>RESOURCES</th>+ <th style={{ ...thStyle, width: '100px' }}>MODIFIED</th>+ <th style={{ ...thStyle, width: '200px' }}>TAGS</th>+ <th style={{ ...thStyle, width: '40px' }}></th>+ </tr>+ </thead>+ <tbody>+ {datasets.map(d => (+ <tr+ key={d.id}+ onClick={() => onSelect(d.id)}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={tdStyle}>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600, marginBottom: '2px' }}>+ {truncate(d.title, 80)}+ </div>+ {d.notes && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{truncate(d.notes, 100)}</div>+ )}+ </td>+ <td style={{ ...tdStyle, textAlign: 'center' }}>+ <span style={{ color: PROVIDER_COLOR, fontWeight: 600 }}>{d.num_resources}</span>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(d.metadata_modified)}</td>+ <td style={tdStyle}>+ <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>+ {d.tags.slice(0, 3).map((tag, i) => (+ <span key={i} style={{+ padding: '1px 6px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '8px',+ fontWeight: 600,+ }}>+ {truncate(tag, 20)}+ </span>+ ))}+ {d.tags.length > 3 && (+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>+{d.tags.length - 3}</span>+ )}+ </div>+ </td>+ <td style={tdStyle}>+ <ChevronRight size={14} color={FINCEPT.MUTED} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function ResourcesTable({ resources }: { resources: CanadaResource[] }) {+ const handleOpenUrl = useCallback(async (url: string) => {+ try {+ const { openUrl } = await import('@tauri-apps/plugin-opener');+ await openUrl(url);+ } catch {+ // Fallback for dev mode / non-Tauri context+ window.open(url, '_blank');+ }+ }, []);++ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {resources.length} resource{resources.length !== 1 ? 's' : ''} available+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>NAME</th>+ <th style={{ ...thStyle, width: '80px' }}>FORMAT</th>+ <th style={{ ...thStyle, width: '90px' }}>SIZE</th>+ <th style={{ ...thStyle, width: '100px' }}>MODIFIED</th>+ <th style={{ ...thStyle, width: '60px' }}>LINK</th>+ </tr>+ </thead>+ <tbody>+ {resources.map(r => (+ <tr key={r.id} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <td style={tdStyle}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <FileText size={14} color={FINCEPT.MUTED} />+ <div>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {r.name || r.id}+ </div>+ {r.description && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{truncate(r.description, 80)}</div>+ )}+ </div>+ </div>+ </td>+ <td style={tdStyle}>+ <span style={{+ padding: '2px 8px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ }}>+ {r.format || '?'}+ </span>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatSize(r.size)}</td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(r.last_modified)}</td>+ <td style={tdStyle}>+ {r.url && (+ <button+ onClick={() => handleOpenUrl(r.url)}+ style={{+ background: 'none',+ border: 'none',+ color: PROVIDER_COLOR,+ cursor: 'pointer',+ padding: '4px',+ display: 'flex',+ alignItems: 'center',+ }}+ title={r.url}+ >+ <ExternalLink size={14} />+ </button>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++// Shared styles+const thStyle: React.CSSProperties = {+ padding: '8px 12px',+ textAlign: 'left',+ fontSize: '9px',+ fontWeight: 700,+ color: PROVIDER_COLOR,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+};++const tdStyle: React.CSSProperties = {+ padding: '8px 12px',+ fontSize: '11px',+ color: FINCEPT.WHITE,+};++export default CanadaGovProvider;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/CongressGovProvider.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/CongressGovProvider.tsxnew file mode 100644index 000000000..5c6910983--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/CongressGovProvider.tsx@@ -0,0 +1,509 @@+// CongressGovProvider - US Congress.gov legislative data interface+// Bills browsing, bill detail (markdown), and summary by congress session++import React, { useEffect, useCallback, useState } from 'react';+import { RefreshCw, AlertCircle, Database, Download, ArrowLeft, ChevronLeft, ChevronRight, Key, Save, Eye } from 'lucide-react';+import { DateRangePicker } from '@/components/common/charts';+import { FINCEPT, CONGRESS_BILL_TYPES } from '../constants';+import { useCongressGovData } from '../hooks/useCongressGovData';+import type { CongressGovView, CongressBill, CongressBillSummary } from '../types';++const VIEWS: { id: CongressGovView; label: string }[] = [+ { id: 'bills', label: 'BILLS' },+ { id: 'summary', label: 'SUMMARY' },+];++const PROVIDER_COLOR = '#8B5CF6';++const truncate = (text: string, max: number): string =>+ text.length > max ? text.substring(0, max) + '...' : text;++const formatDate = (dateStr: string | null): string => {+ if (!dateStr) return '-';+ return dateStr.substring(0, 10);+};++export function CongressGovProvider() {+ const {+ activeView, setActiveView,+ apiKey, apiKeyLoaded, loadApiKey, saveApiKey,+ dateRangePreset, setDateRangePreset,+ startDate, endDate, setStartDate, setEndDate,+ bills, billsTotalCount, congressNumber, setCongressNumber,+ billType, setBillType, billsOffset, setBillsOffset,+ fetchBills,+ billDetail, fetchBillDetail,+ billSummary, fetchSummary,+ exportCSV,+ loading, error,+ } = useCongressGovData();++ const [showApiKeyInput, setShowApiKeyInput] = useState(false);+ const [tempApiKey, setTempApiKey] = useState('');++ useEffect(() => { loadApiKey(); }, [loadApiKey]);+ useEffect(() => { setTempApiKey(apiKey); }, [apiKey]);++ const handleViewChange = (view: CongressGovView) => {+ setActiveView(view);+ };++ const handleFetch = () => {+ if (activeView === 'bills') fetchBills();+ else if (activeView === 'summary') fetchSummary();+ };++ const handleBillClick = (bill: CongressBill) => {+ // Use the bill identifier path e.g. "119/hr/1"+ const billPath = `${bill.congress}/${bill.bill_type.toLowerCase()}/${bill.bill_number}`;+ setActiveView('bill-detail');+ fetchBillDetail(billPath);+ };++ const handleBack = () => {+ setActiveView('bills');+ };++ const handleSaveApiKey = async () => {+ await saveApiKey(tempApiKey);+ setShowApiKeyInput(false);+ };++ const handlePageChange = (direction: 'prev' | 'next') => {+ const newOffset = direction === 'next' ? billsOffset + 100 : Math.max(0, billsOffset - 100);+ setBillsOffset(newOffset);+ setTimeout(() => fetchBills(), 50);+ };++ const inputStyle: React.CSSProperties = {+ padding: '4px 8px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ outline: 'none',+ fontFamily: 'inherit',+ };++ const labelStyle: React.CSSProperties = {+ fontSize: '9px',+ color: FINCEPT.GRAY,+ fontWeight: 700,+ };++ const needsApiKey = apiKeyLoaded && !apiKey;++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Header bar */}+ <div style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ flexWrap: 'wrap',+ }}>+ {activeView === 'bill-detail' && (+ <button onClick={handleBack} style={{+ padding: '5px 8px', backgroundColor: 'transparent', color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px',+ fontWeight: 700, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '4px',+ }}>+ <ArrowLeft size={11} /> BACK+ </button>+ )}++ {/* View tabs */}+ <div style={{ display: 'flex', gap: '2px', marginRight: '12px' }}>+ {VIEWS.map(v => (+ <button+ key={v.id}+ onClick={() => handleViewChange(v.id)}+ style={{+ padding: '5px 12px',+ backgroundColor: activeView === v.id || (v.id === 'bills' && activeView === 'bill-detail') ? PROVIDER_COLOR : 'transparent',+ color: activeView === v.id || (v.id === 'bills' && activeView === 'bill-detail') ? FINCEPT.WHITE : FINCEPT.GRAY,+ border: `1px solid ${activeView === v.id || (v.id === 'bills' && activeView === 'bill-detail') ? PROVIDER_COLOR : FINCEPT.BORDER}`,+ borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: 'pointer',+ }}+ >+ {v.label}+ </button>+ ))}+ </div>++ {/* Filters for bills view */}+ {(activeView === 'bills' || activeView === 'bill-detail') && (+ <>+ <DateRangePicker+ dateRangePreset={dateRangePreset}+ setDateRangePreset={setDateRangePreset}+ startDate={startDate} endDate={endDate}+ setStartDate={setStartDate} setEndDate={setEndDate}+ sourceColor={PROVIDER_COLOR}+ />+ <div style={{ width: '1px', height: '20px', backgroundColor: FINCEPT.BORDER }} />+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={labelStyle}>CONGRESS:</span>+ <input+ type="number"+ value={congressNumber}+ onChange={e => setCongressNumber(Number(e.target.value))}+ min={74} max={130}+ style={{ ...inputStyle, width: '55px', textAlign: 'center' }}+ />+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={labelStyle}>TYPE:</span>+ <select value={billType} onChange={e => setBillType(e.target.value)} style={inputStyle}>+ {CONGRESS_BILL_TYPES.map(t => (+ <option key={t.value} value={t.value}>{t.label}</option>+ ))}+ </select>+ </div>+ </>+ )}++ {activeView === 'summary' && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={labelStyle}>CONGRESS:</span>+ <input+ type="number"+ value={congressNumber}+ onChange={e => setCongressNumber(Number(e.target.value))}+ min={74} max={130}+ style={{ ...inputStyle, width: '55px', textAlign: 'center' }}+ />+ </div>+ )}++ {/* Actions */}+ <div style={{ marginLeft: 'auto', display: 'flex', gap: '4px' }}>+ {/* API Key toggle */}+ <button+ onClick={() => setShowApiKeyInput(!showApiKeyInput)}+ title={apiKey ? 'API key configured' : 'Set API key'}+ style={{+ padding: '5px 8px', backgroundColor: 'transparent',+ color: apiKey ? FINCEPT.GREEN : FINCEPT.GRAY,+ border: `1px solid ${apiKey ? FINCEPT.GREEN : FINCEPT.BORDER}`,+ borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: 'pointer',+ display: 'flex', alignItems: 'center', gap: '4px',+ }}+ >+ <Key size={11} /> API KEY+ </button>++ {activeView === 'bills' && bills.length > 0 && (+ <button onClick={exportCSV} title="Export CSV" style={{+ padding: '5px 10px', backgroundColor: 'transparent', color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px',+ fontWeight: 700, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '4px',+ }}>+ <Download size={11} /> CSV+ </button>+ )}++ {activeView !== 'bill-detail' && (+ <button onClick={handleFetch} disabled={loading} style={{+ padding: '5px 14px', backgroundColor: PROVIDER_COLOR, color: FINCEPT.WHITE,+ border: 'none', borderRadius: '2px', fontSize: '10px', fontWeight: 700,+ cursor: loading ? 'wait' : 'pointer', display: 'flex', alignItems: 'center',+ gap: '6px', opacity: loading ? 0.7 : 1,+ }}>+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} /> FETCH+ </button>+ )}+ </div>+ </div>++ {/* API Key input bar */}+ {showApiKeyInput && (+ <div style={{+ padding: '8px 16px', backgroundColor: FINCEPT.PANEL_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex', alignItems: 'center', gap: '8px',+ }}>+ <Key size={14} color={FINCEPT.GRAY} />+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>CONGRESS_GOV_API_KEY:</span>+ <input+ type="password"+ value={tempApiKey}+ onChange={e => setTempApiKey(e.target.value)}+ placeholder="Enter your Congress.gov API key..."+ style={{ ...inputStyle, flex: 1, maxWidth: '400px' }}+ />+ <button onClick={handleSaveApiKey} style={{+ padding: '4px 12px', backgroundColor: PROVIDER_COLOR, color: FINCEPT.WHITE,+ border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: 'pointer',+ display: 'flex', alignItems: 'center', gap: '4px',+ }}>+ <Save size={11} /> SAVE+ </button>+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>+ Get a key at api.congress.gov+ </span>+ </div>+ )}++ {/* Content */}+ <div style={{ flex: 1, overflow: 'auto' }}>+ {loading ? (+ <LoadingState />+ ) : error ? (+ <ErrorState error={error} onRetry={handleFetch} />+ ) : needsApiKey ? (+ <EmptyState message="API key required" sub="Click the API KEY button above to configure your Congress.gov API key" />+ ) : activeView === 'bills' ? (+ bills.length > 0+ ? <BillsTable bills={bills} totalCount={billsTotalCount} offset={billsOffset} onBillClick={handleBillClick} onPageChange={handlePageChange} />+ : <EmptyState message="Browse Congressional Bills" sub="Set filters and click FETCH to load bills" />+ ) : activeView === 'bill-detail' ? (+ billDetail+ ? <BillDetailView detail={billDetail} />+ : <EmptyState message="Select a bill" sub="Click on a bill from the list to view details" />+ ) : activeView === 'summary' ? (+ billSummary+ ? <SummaryView summary={billSummary} />+ : <EmptyState message="Congressional Summary" sub="Click FETCH to load bill counts by type" />+ ) : null}+ </div>+ </div>+ );+}++// ===== Sub-components =====++function LoadingState() {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <RefreshCw size={32} className="animate-spin" style={{ color: PROVIDER_COLOR, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>Loading Congress.gov data...</div>+ </div>+ );+}++function ErrorState({ error, onRetry }: { error: string; onRetry: () => void }) {+ const isApiKeyError = error.includes('API key') || error.includes('api_key');+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <AlertCircle size={32} style={{ color: FINCEPT.RED, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.RED, marginBottom: '8px' }}>+ {isApiKeyError ? 'API Key Required' : 'Error loading data'}+ </div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '400px', marginBottom: '16px' }}>{error}</div>+ {!isApiKeyError && (+ <button onClick={onRetry} style={{+ padding: '8px 16px', backgroundColor: PROVIDER_COLOR, color: FINCEPT.WHITE,+ border: 'none', borderRadius: '2px', fontSize: '10px', fontWeight: 700, cursor: 'pointer',+ }}>+ TRY AGAIN+ </button>+ )}+ </div>+ );+}++function EmptyState({ message, sub }: { message: string; sub: string }) {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <Database size={48} style={{ color: FINCEPT.MUTED, marginBottom: '16px', opacity: 0.5 }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE, marginBottom: '8px' }}>{message}</div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>{sub}</div>+ </div>+ );+}++function BillsTable({ bills, totalCount, offset, onBillClick, onPageChange }: {+ bills: CongressBill[];+ totalCount: number;+ offset: number;+ onBillClick: (bill: CongressBill) => void;+ onPageChange: (dir: 'prev' | 'next') => void;+}) {+ return (+ <div>+ {/* Pagination header */}+ <div style={{+ padding: '6px 16px', fontSize: '9px', color: FINCEPT.GRAY,+ backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex', justifyContent: 'space-between', alignItems: 'center',+ }}>+ <span>Showing {offset + 1}-{offset + bills.length} of {totalCount} bills</span>+ <div style={{ display: 'flex', gap: '4px' }}>+ <button onClick={() => onPageChange('prev')} disabled={offset === 0}+ style={{ padding: '2px 8px', backgroundColor: 'transparent', color: offset === 0 ? FINCEPT.MUTED : FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', cursor: offset === 0 ? 'default' : 'pointer', display: 'flex', alignItems: 'center' }}>+ <ChevronLeft size={12} /> PREV+ </button>+ <button onClick={() => onPageChange('next')} disabled={offset + bills.length >= totalCount}+ style={{ padding: '2px 8px', backgroundColor: 'transparent', color: offset + bills.length >= totalCount ? FINCEPT.MUTED : FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', cursor: offset + bills.length >= totalCount ? 'default' : 'pointer', display: 'flex', alignItems: 'center' }}>+ NEXT <ChevronRight size={12} />+ </button>+ </div>+ </div>++ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={{ ...thStyle, width: '50px' }}>#</th>+ <th style={{ ...thStyle, width: '60px' }}>TYPE</th>+ <th style={thStyle}>TITLE</th>+ <th style={{ ...thStyle, width: '80px' }}>CHAMBER</th>+ <th style={{ ...thStyle, width: '100px' }}>UPDATED</th>+ <th style={{ ...thStyle, width: '200px' }}>LATEST ACTION</th>+ <th style={{ ...thStyle, width: '40px' }}></th>+ </tr>+ </thead>+ <tbody>+ {bills.map((b, i) => (+ <tr+ key={`${b.bill_type}-${b.bill_number}-${i}`}+ onClick={() => onBillClick(b)}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={{ ...tdStyle, color: PROVIDER_COLOR, fontWeight: 700 }}>{b.bill_number}</td>+ <td style={tdStyle}>+ <span style={{+ padding: '1px 6px', backgroundColor: `${PROVIDER_COLOR}15`, color: PROVIDER_COLOR,+ borderRadius: '2px', fontSize: '8px', fontWeight: 700, textTransform: 'uppercase',+ }}>+ {b.bill_type}+ </span>+ </td>+ <td style={tdStyle}>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE }}>{truncate(b.title || '', 90)}</div>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{b.origin_chamber}</td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(b.update_date)}</td>+ <td style={{ ...tdStyle, fontSize: '9px', color: FINCEPT.MUTED }}>+ {b.latest_action ? truncate(b.latest_action, 50) : '-'}+ </td>+ <td style={tdStyle}><Eye size={13} color={FINCEPT.MUTED} /></td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function BillDetailView({ detail }: { detail: { success: boolean; markdown_content: string; bill_data?: Record<string, any> } }) {+ if (!detail.success) return <EmptyState message="Bill not found" sub="" />;++ const md = detail.markdown_content || '';++ // Render markdown as simple styled blocks+ const lines = md.split('\n');++ return (+ <div style={{ padding: '20px 24px', maxWidth: '900px', margin: '0 auto', overflowY: 'auto', height: '100%' }}>+ {lines.map((line, i) => {+ const trimmed = line.trim();+ if (!trimmed) return <div key={i} style={{ height: '8px' }} />;++ if (trimmed.startsWith('# ')) {+ return <h1 key={i} style={{ fontSize: '18px', color: PROVIDER_COLOR, fontWeight: 700, marginBottom: '12px', lineHeight: 1.3 }}>{trimmed.substring(2)}</h1>;+ }+ if (trimmed.startsWith('## ')) {+ return <h2 key={i} style={{ fontSize: '14px', color: FINCEPT.WHITE, fontWeight: 700, marginTop: '16px', marginBottom: '8px', borderBottom: `1px solid ${FINCEPT.BORDER}`, paddingBottom: '4px' }}>{trimmed.substring(3)}</h2>;+ }+ if (trimmed.startsWith('- **')) {+ const match = trimmed.match(/^- \*\*(.+?)\*\*:?\s*(.*)/);+ if (match) {+ return (+ <div key={i} style={{ fontSize: '11px', padding: '2px 0', display: 'flex', gap: '4px' }}>+ <span style={{ color: FINCEPT.GRAY, fontWeight: 600, minWidth: '120px' }}>{match[1]}:</span>+ <span style={{ color: FINCEPT.WHITE }}>{match[2]}</span>+ </div>+ );+ }+ }+ if (trimmed.startsWith('- ')) {+ return (+ <div key={i} style={{ fontSize: '10px', color: FINCEPT.WHITE, padding: '2px 0 2px 12px' }}>+ <span style={{ color: FINCEPT.MUTED, marginRight: '6px' }}>•</span>+ {trimmed.substring(2)}+ </div>+ );+ }++ return <div key={i} style={{ fontSize: '11px', color: FINCEPT.WHITE, padding: '2px 0', lineHeight: 1.5 }}>{trimmed}</div>;+ })}+ </div>+ );+}++function SummaryView({ summary }: { summary: CongressBillSummary }) {+ const types = summary.bill_types || {};+ const typeLabels: Record<string, string> = {+ hr: 'House Bills', s: 'Senate Bills', hjres: 'House Joint Res.', sjres: 'Senate Joint Res.',+ hconres: 'House Con. Res.', sconres: 'Senate Con. Res.', hres: 'House Simple Res.', sres: 'Senate Simple Res.',+ };++ return (+ <div style={{ padding: '20px 24px' }}>+ <div style={{ fontSize: '16px', color: FINCEPT.WHITE, fontWeight: 700, marginBottom: '4px' }}>+ {summary.congress}th Congress — Bill Summary+ </div>+ <div style={{ fontSize: '11px', color: FINCEPT.GRAY, marginBottom: '20px' }}>+ Total bills fetched: <span style={{ color: PROVIDER_COLOR, fontWeight: 700 }}>{summary.total_bills}</span>+ </div>++ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: '12px' }}>+ {Object.entries(types).map(([type, data]) => (+ <div key={type} style={{+ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px', padding: '14px',+ }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>+ <span style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {typeLabels[type] || type.toUpperCase()}+ </span>+ <span style={{+ padding: '2px 8px', backgroundColor: `${PROVIDER_COLOR}20`, color: PROVIDER_COLOR,+ borderRadius: '2px', fontSize: '12px', fontWeight: 700,+ }}>+ {data.count}+ </span>+ </div>++ {data.error && (+ <div style={{ fontSize: '9px', color: FINCEPT.RED }}>{data.error}</div>+ )}++ {data.latest_bills && data.latest_bills.length > 0 && (+ <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}`, paddingTop: '8px' }}>+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED, marginBottom: '4px', fontWeight: 700 }}>LATEST</div>+ {data.latest_bills.map((b, i) => (+ <div key={i} style={{ fontSize: '9px', color: FINCEPT.GRAY, padding: '2px 0', borderBottom: `1px solid ${FINCEPT.BORDER}08` }}>+ <span style={{ color: PROVIDER_COLOR, fontWeight: 600, marginRight: '4px' }}>+ {b.bill_type}{b.bill_number}+ </span>+ {truncate(b.title || '', 50)}+ </div>+ ))}+ </div>+ )}+ </div>+ ))}+ </div>+ </div>+ );+}++// Shared styles+const thStyle: React.CSSProperties = {+ padding: '8px 12px', textAlign: 'left', fontSize: '9px', fontWeight: 700,+ color: PROVIDER_COLOR, borderBottom: `1px solid ${FINCEPT.BORDER}`,+};++const tdStyle: React.CSSProperties = {+ padding: '8px 12px', fontSize: '11px', color: FINCEPT.WHITE,+};++export default CongressGovProvider;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/FrenchGovProvider.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/FrenchGovProvider.tsxnew file mode 100644index 000000000..50a4a7777--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/FrenchGovProvider.tsx@@ -0,0 +1,765 @@+// FrenchGovProvider - French Government API portal (data.gouv.fr, API Géo, Tabulaire, Entreprise)+// Four distinct sections: Geographic data, Dataset catalog, Tabular querying, Company lookup++import React, { useCallback } from 'react';+import { RefreshCw, AlertCircle, Download, Search, MapPin, Database, Table2, Building2, ChevronLeft, ChevronRight } from 'lucide-react';+import { FINCEPT } from '../constants';+import { useFrenchGovData, type GeoSearchType } from '../hooks/useFrenchGovData';+import type { FrenchGovView, FrenchMunicipality, FrenchDepartment, FrenchRegion, FrenchDataset, FrenchResourceProfile, FrenchResourceLines, FrenchCompany } from '../types';++const VIEWS: { id: FrenchGovView; label: string; icon: React.ElementType }[] = [+ { id: 'geo', label: 'GEOGRAPHY', icon: MapPin },+ { id: 'datasets', label: 'DATASETS', icon: Database },+ { id: 'tabular', label: 'TABULAR', icon: Table2 },+ { id: 'company', label: 'COMPANY', icon: Building2 },+];++const GEO_TYPES: { id: GeoSearchType; label: string }[] = [+ { id: 'municipalities', label: 'Municipalities' },+ { id: 'departments', label: 'Departments' },+ { id: 'regions', label: 'Regions' },+];++const PROVIDER_COLOR = '#2563EB';++const truncate = (text: string, max: number): string =>+ text.length > max ? text.substring(0, max) + '...' : text;++const formatDate = (dateStr: string | null): string => {+ if (!dateStr) return '-';+ return dateStr.substring(0, 10);+};++const formatNum = (n: number | null): string => {+ if (n == null) return '-';+ return n.toLocaleString();+};++export function FrenchGovProvider() {+ const {+ activeView, setActiveView,+ geoSearchType, setGeoSearchType, geoQuery, setGeoQuery,+ municipalities, departments, regions, fetchGeo,+ datasetQuery, setDatasetQuery, datasets, datasetsTotalCount, datasetsPage, fetchDatasets,+ tabularResourceId, setTabularResourceId, resourceProfile, resourceLines, fetchProfile, fetchLines,+ companyQuery, setCompanyQuery, companies, fetchCompany,+ exportCSV,+ loading, error,+ } = useFrenchGovData();++ const inputStyle: React.CSSProperties = {+ padding: '6px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '11px',+ outline: 'none',+ fontFamily: 'inherit',+ };++ const btnStyle = (active: boolean): React.CSSProperties => ({+ padding: '5px 12px',+ backgroundColor: active ? PROVIDER_COLOR : 'transparent',+ color: active ? FINCEPT.WHITE : FINCEPT.GRAY,+ border: `1px solid ${active ? PROVIDER_COLOR : FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ });++ const actionBtnStyle: React.CSSProperties = {+ padding: '6px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading ? 'wait' : 'pointer',+ opacity: loading ? 0.7 : 1,+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ };++ const hasData =+ (activeView === 'geo' && (municipalities.length > 0 || departments.length > 0 || regions.length > 0))+ || (activeView === 'datasets' && datasets.length > 0)+ || (activeView === 'tabular' && (resourceProfile !== null || (resourceLines?.lines?.length ?? 0) > 0))+ || (activeView === 'company' && companies.length > 0);++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Header bar */}+ <div style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ flexWrap: 'wrap',+ }}>+ {/* View selector */}+ <div style={{ display: 'flex', gap: '2px', marginRight: '8px' }}>+ {VIEWS.map(v => (+ <button key={v.id} onClick={() => setActiveView(v.id)} style={btnStyle(activeView === v.id)}>+ {v.label}+ </button>+ ))}+ </div>++ {/* Geo controls */}+ {activeView === 'geo' && (+ <>+ <div style={{ display: 'flex', gap: '2px' }}>+ {GEO_TYPES.map(g => (+ <button key={g.id} onClick={() => setGeoSearchType(g.id)} style={{+ ...btnStyle(geoSearchType === g.id),+ backgroundColor: geoSearchType === g.id ? `${PROVIDER_COLOR}30` : 'transparent',+ color: geoSearchType === g.id ? PROVIDER_COLOR : FINCEPT.GRAY,+ border: `1px solid ${geoSearchType === g.id ? PROVIDER_COLOR : FINCEPT.BORDER}`,+ }}>+ {g.label}+ </button>+ ))}+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flex: 1, maxWidth: '300px' }}>+ <Search size={14} color={FINCEPT.GRAY} />+ <input+ type="text"+ value={geoQuery}+ onChange={e => setGeoQuery(e.target.value)}+ onKeyDown={e => { if (e.key === 'Enter') fetchGeo(); }}+ placeholder={`Search ${geoSearchType}...`}+ style={{ ...inputStyle, flex: 1 }}+ />+ <button onClick={fetchGeo} disabled={loading} style={actionBtnStyle}>+ FETCH+ </button>+ </div>+ </>+ )}++ {/* Dataset controls */}+ {activeView === 'datasets' && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flex: 1, maxWidth: '400px' }}>+ <Search size={14} color={FINCEPT.GRAY} />+ <input+ type="text"+ value={datasetQuery}+ onChange={e => setDatasetQuery(e.target.value)}+ onKeyDown={e => { if (e.key === 'Enter') fetchDatasets(1); }}+ placeholder="Search data.gouv.fr datasets..."+ style={{ ...inputStyle, flex: 1 }}+ />+ <button onClick={() => fetchDatasets(1)} disabled={loading} style={actionBtnStyle}>+ SEARCH+ </button>+ </div>+ )}++ {/* Tabular controls */}+ {activeView === 'tabular' && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flex: 1, maxWidth: '500px' }}>+ <Table2 size={14} color={FINCEPT.GRAY} />+ <input+ type="text"+ value={tabularResourceId}+ onChange={e => setTabularResourceId(e.target.value)}+ onKeyDown={e => { if (e.key === 'Enter') fetchProfile(); }}+ placeholder="Resource ID (UUID)..."+ style={{ ...inputStyle, flex: 1 }}+ />+ <button onClick={fetchProfile} disabled={loading || !tabularResourceId.trim()} style={{+ ...actionBtnStyle,+ cursor: loading || !tabularResourceId.trim() ? 'not-allowed' : 'pointer',+ opacity: loading || !tabularResourceId.trim() ? 0.5 : 1,+ }}>+ PROFILE+ </button>+ <button onClick={() => fetchLines(1)} disabled={loading || !tabularResourceId.trim()} style={{+ ...actionBtnStyle,+ cursor: loading || !tabularResourceId.trim() ? 'not-allowed' : 'pointer',+ opacity: loading || !tabularResourceId.trim() ? 0.5 : 1,+ }}>+ LINES+ </button>+ </div>+ )}++ {/* Company controls */}+ {activeView === 'company' && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flex: 1, maxWidth: '350px' }}>+ <Building2 size={14} color={FINCEPT.GRAY} />+ <input+ type="text"+ value={companyQuery}+ onChange={e => setCompanyQuery(e.target.value)}+ onKeyDown={e => { if (e.key === 'Enter') fetchCompany(); }}+ placeholder="SIREN (9-digit) or SIRET (14-digit)..."+ style={{ ...inputStyle, flex: 1 }}+ />+ <button onClick={fetchCompany} disabled={loading || !companyQuery.trim()} style={{+ ...actionBtnStyle,+ cursor: loading || !companyQuery.trim() ? 'not-allowed' : 'pointer',+ opacity: loading || !companyQuery.trim() ? 0.5 : 1,+ }}>+ LOOKUP+ </button>+ </div>+ )}++ {/* Actions */}+ <div style={{ marginLeft: 'auto', display: 'flex', gap: '4px' }}>+ {hasData && (+ <button+ onClick={exportCSV}+ title="Export CSV"+ style={{+ padding: '5px 10px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <Download size={11} />+ CSV+ </button>+ )}+ </div>+ </div>++ {/* Content area */}+ <div style={{ flex: 1, overflow: 'auto' }}>+ {loading ? (+ <LoadingState />+ ) : error ? (+ <ErrorState error={error} />+ ) : activeView === 'geo' ? (+ <GeoContent+ geoSearchType={geoSearchType}+ municipalities={municipalities}+ departments={departments}+ regions={regions}+ />+ ) : activeView === 'datasets' ? (+ <DatasetsContent+ datasets={datasets}+ totalCount={datasetsTotalCount}+ page={datasetsPage}+ onPageChange={fetchDatasets}+ loading={loading}+ />+ ) : activeView === 'tabular' ? (+ <TabularContent+ profile={resourceProfile}+ lines={resourceLines}+ onFetchLines={fetchLines}+ loading={loading}+ />+ ) : activeView === 'company' ? (+ <CompanyContent companies={companies} />+ ) : (+ <EmptyState message="Select a view to get started" />+ )}+ </div>+ </div>+ );+}++// ===== Sub-components =====++function LoadingState() {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <RefreshCw size={32} className="animate-spin" style={{ color: PROVIDER_COLOR, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>Loading French government data...</div>+ </div>+ );+}++function ErrorState({ error }: { error: string }) {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <AlertCircle size={32} style={{ color: FINCEPT.RED, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.RED, marginBottom: '8px' }}>Error loading data</div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '400px' }}>{error}</div>+ </div>+ );+}++function EmptyState({ message }: { message: string }) {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <Database size={48} style={{ color: FINCEPT.MUTED, marginBottom: '16px', opacity: 0.5 }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>{message}</div>+ </div>+ );+}++// ===== GEO CONTENT =====++function GeoContent({+ geoSearchType,+ municipalities,+ departments,+ regions,+}: {+ geoSearchType: GeoSearchType;+ municipalities: FrenchMunicipality[];+ departments: FrenchDepartment[];+ regions: FrenchRegion[];+}) {+ if (geoSearchType === 'municipalities') {+ if (municipalities.length === 0) return <EmptyState message="Search for French municipalities by name, postal code, or coordinates" />;+ return (+ <div>+ <div style={summaryBarStyle}>{municipalities.length} municipalities</div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>CODE</th>+ <th style={thStyle}>NAME</th>+ <th style={thStyle}>ORIGINAL</th>+ <th style={{ ...thStyle, width: '120px' }}>POSTAL CODES</th>+ <th style={{ ...thStyle, width: '60px' }}>DEPT</th>+ <th style={{ ...thStyle, width: '60px' }}>REGION</th>+ <th style={{ ...thStyle, width: '90px', textAlign: 'right' }}>POPULATION</th>+ <th style={{ ...thStyle, width: '80px', textAlign: 'right' }}>AREA (ha)</th>+ </tr>+ </thead>+ <tbody>+ {municipalities.map(m => (+ <tr key={m.code} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <td style={{ ...tdStyle, color: PROVIDER_COLOR, fontWeight: 600 }}>{m.code}</td>+ <td style={tdStyle}>{m.name}</td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.MUTED, fontStyle: 'italic' }}>+ {m.original_name !== m.name ? m.original_name : ''}+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{(m.postal_codes || []).slice(0, 3).join(', ')}{(m.postal_codes || []).length > 3 ? '...' : ''}</td>+ <td style={{ ...tdStyle, textAlign: 'center', color: FINCEPT.GRAY }}>{m.department_code || '-'}</td>+ <td style={{ ...tdStyle, textAlign: 'center', color: FINCEPT.GRAY }}>{m.region_code || '-'}</td>+ <td style={{ ...tdStyle, textAlign: 'right', color: PROVIDER_COLOR, fontWeight: 600 }}>{formatNum(m.population)}</td>+ <td style={{ ...tdStyle, textAlign: 'right', color: FINCEPT.GRAY }}>{formatNum(m.area)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+ }++ if (geoSearchType === 'departments') {+ if (departments.length === 0) return <EmptyState message="Search for French departments by name or code" />;+ return (+ <div>+ <div style={summaryBarStyle}>{departments.length} departments</div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={{ ...thStyle, width: '80px' }}>CODE</th>+ <th style={thStyle}>NAME</th>+ <th style={thStyle}>ORIGINAL</th>+ <th style={{ ...thStyle, width: '100px' }}>REGION CODE</th>+ </tr>+ </thead>+ <tbody>+ {departments.map(d => (+ <tr key={d.code} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <td style={{ ...tdStyle, color: PROVIDER_COLOR, fontWeight: 600 }}>{d.code}</td>+ <td style={tdStyle}>{d.name}</td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.MUTED, fontStyle: 'italic' }}>+ {d.original_name !== d.name ? d.original_name : ''}+ </td>+ <td style={{ ...tdStyle, textAlign: 'center', color: FINCEPT.GRAY }}>{d.region_code || '-'}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+ }++ if (geoSearchType === 'regions') {+ if (regions.length === 0) return <EmptyState message="Search for French regions by name or code" />;+ return (+ <div>+ <div style={summaryBarStyle}>{regions.length} regions</div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={{ ...thStyle, width: '80px' }}>CODE</th>+ <th style={thStyle}>NAME</th>+ <th style={thStyle}>ORIGINAL</th>+ </tr>+ </thead>+ <tbody>+ {regions.map(r => (+ <tr key={r.code} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <td style={{ ...tdStyle, color: PROVIDER_COLOR, fontWeight: 600 }}>{r.code}</td>+ <td style={tdStyle}>{r.name}</td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.MUTED, fontStyle: 'italic' }}>+ {r.original_name !== r.name ? r.original_name : ''}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+ }++ return <EmptyState message="Select a geographic entity type" />;+}++// ===== DATASETS CONTENT =====++function DatasetsContent({+ datasets,+ totalCount,+ page,+ onPageChange,+ loading,+}: {+ datasets: FrenchDataset[];+ totalCount: number;+ page: number;+ onPageChange: (page: number) => Promise<void>;+ loading: boolean;+}) {+ const handleOpenUrl = useCallback(async (url: string) => {+ try {+ const { openUrl } = await import('@tauri-apps/plugin-opener');+ await openUrl(url);+ } catch {+ window.open(url, '_blank');+ }+ }, []);++ if (datasets.length === 0) return <EmptyState message="Search for datasets on data.gouv.fr" />;++ const totalPages = Math.ceil(totalCount / 20);++ return (+ <div>+ <div style={{ ...summaryBarStyle, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <span>Showing {datasets.length} of {totalCount.toLocaleString()} datasets (page {page})</span>+ <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>+ <button+ onClick={() => onPageChange(page - 1)}+ disabled={page <= 1 || loading}+ style={{ ...pageBtnStyle, opacity: page <= 1 ? 0.3 : 1, cursor: page <= 1 ? 'not-allowed' : 'pointer' }}+ >+ <ChevronLeft size={12} /> Prev+ </button>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{page} / {totalPages}</span>+ <button+ onClick={() => onPageChange(page + 1)}+ disabled={page >= totalPages || loading}+ style={{ ...pageBtnStyle, opacity: page >= totalPages ? 0.3 : 1, cursor: page >= totalPages ? 'not-allowed' : 'pointer' }}+ >+ Next <ChevronRight size={12} />+ </button>+ </div>+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>TITLE</th>+ <th style={{ ...thStyle, width: '140px' }}>ORGANIZATION</th>+ <th style={{ ...thStyle, width: '70px' }}>FILES</th>+ <th style={{ ...thStyle, width: '100px' }}>MODIFIED</th>+ <th style={{ ...thStyle, width: '180px' }}>TAGS</th>+ </tr>+ </thead>+ <tbody>+ {datasets.map(d => (+ <tr+ key={d.id}+ style={{ borderBottom: `1px solid ${FINCEPT.BORDER}`, cursor: d.url ? 'pointer' : 'default' }}+ onClick={() => d.url && handleOpenUrl(d.url)}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={tdStyle}>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600, marginBottom: '2px' }}>+ {truncate(d.title, 80)}+ </div>+ {d.original_title && d.original_title !== d.title && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, fontStyle: 'italic', marginBottom: '2px' }}>+ {truncate(d.original_title, 90)}+ </div>+ )}+ {d.description && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{truncate(d.description, 100)}</div>+ )}+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{d.organization || d.owner || '-'}</td>+ <td style={{ ...tdStyle, textAlign: 'center' }}>+ <span style={{ color: PROVIDER_COLOR, fontWeight: 600 }}>{d.resources_count}</span>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(d.last_modified)}</td>+ <td style={tdStyle}>+ <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>+ {(d.tags || []).slice(0, 3).map((tag, i) => (+ <span key={i} style={{+ padding: '1px 6px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '8px',+ fontWeight: 600,+ }}>+ {truncate(tag, 20)}+ </span>+ ))}+ {(d.tags || []).length > 3 && (+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>+{d.tags.length - 3}</span>+ )}+ </div>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++// ===== TABULAR CONTENT =====++function TabularContent({+ profile,+ lines,+ onFetchLines,+ loading,+}: {+ profile: FrenchResourceProfile | null;+ lines: FrenchResourceLines | null;+ onFetchLines: (page: number) => Promise<void>;+ loading: boolean;+}) {+ if (!profile && !lines) {+ return <EmptyState message="Enter a data.gouv.fr resource UUID above and click PROFILE or LINES" />;+ }++ return (+ <div>+ {/* Profile section */}+ {profile && (+ <div style={{ marginBottom: '8px' }}>+ <div style={{ ...summaryBarStyle, backgroundColor: `${PROVIDER_COLOR}10` }}>+ <div style={{ display: 'flex', gap: '16px', flexWrap: 'wrap' }}>+ <span><span style={{ color: FINCEPT.GRAY }}>Resource:</span> <span style={{ color: PROVIDER_COLOR }}>{profile.resource_id}</span></span>+ {profile.format && <span><span style={{ color: FINCEPT.GRAY }}>Format:</span> {profile.format}</span>}+ {profile.total_rows != null && <span><span style={{ color: FINCEPT.GRAY }}>Rows:</span> {profile.total_rows.toLocaleString()}</span>}+ {profile.encoding && <span><span style={{ color: FINCEPT.GRAY }}>Encoding:</span> {profile.encoding}</span>}+ </div>+ </div>+ {profile.columns.length > 0 && (+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={{ ...thStyle, width: '40px' }}>#</th>+ <th style={thStyle}>COLUMN</th>+ <th style={thStyle}>ORIGINAL</th>+ <th style={{ ...thStyle, width: '80px' }}>TYPE</th>+ <th style={thStyle}>DESCRIPTION</th>+ </tr>+ </thead>+ <tbody>+ {profile.columns.map((col, idx) => (+ <tr key={idx} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <td style={{ ...tdStyle, color: FINCEPT.MUTED, textAlign: 'center' }}>{idx + 1}</td>+ <td style={{ ...tdStyle, color: PROVIDER_COLOR, fontWeight: 600 }}>{col.name || col.title || `col_${idx}`}</td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.MUTED, fontStyle: 'italic' }}>+ {col.original_name && col.original_name !== col.name ? col.original_name : ''}+ </td>+ <td style={tdStyle}>+ {col.type && (+ <span style={{+ padding: '1px 6px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 600,+ }}>+ {col.type}+ </span>+ )}+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{col.description ? truncate(col.description, 60) : '-'}</td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ )}++ {/* Lines section */}+ {lines && lines.lines.length > 0 && (+ <div>+ <div style={{ ...summaryBarStyle, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <span>+ Page {lines.page} — {lines.lines.length} rows of {lines.total_rows.toLocaleString()}+ </span>+ <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>+ <button+ onClick={() => onFetchLines(lines.page - 1)}+ disabled={lines.page <= 1 || loading}+ style={{ ...pageBtnStyle, opacity: lines.page <= 1 ? 0.3 : 1, cursor: lines.page <= 1 ? 'not-allowed' : 'pointer' }}+ >+ <ChevronLeft size={12} /> Prev+ </button>+ <button+ onClick={() => onFetchLines(lines.page + 1)}+ disabled={!lines.has_more || loading}+ style={{ ...pageBtnStyle, opacity: !lines.has_more ? 0.3 : 1, cursor: !lines.has_more ? 'not-allowed' : 'pointer' }}+ >+ Next <ChevronRight size={12} />+ </button>+ </div>+ </div>+ <div style={{ overflowX: 'auto' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: '600px' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ {Object.keys(lines.lines[0]).map(key => (+ <th key={key} style={{ ...thStyle, whiteSpace: 'nowrap' }}>{key}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {lines.lines.map((row, idx) => (+ <tr key={idx} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {Object.values(row).map((val, colIdx) => (+ <td key={colIdx} style={{ ...tdStyle, fontSize: '10px', whiteSpace: 'nowrap', maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis' }}>+ {val != null ? String(val) : '-'}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ )}+ </div>+ );+}++// ===== COMPANY CONTENT =====++function CompanyContent({ companies }: { companies: FrenchCompany[] }) {+ if (companies.length === 0) return <EmptyState message="Enter a 9-digit SIREN or 14-digit SIRET to look up a French company" />;++ return (+ <div>+ <div style={summaryBarStyle}>{companies.length} compan{companies.length !== 1 ? 'ies' : 'y'} found</div>+ {companies.map((c, idx) => (+ <div key={idx} style={{+ padding: '12px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{ fontSize: '13px', color: FINCEPT.WHITE, fontWeight: 700, marginBottom: '4px' }}>+ {c.complete_name || c.company_name || 'Unknown'}+ </div>+ {c.original_complete_name && c.original_complete_name !== c.complete_name && (+ <div style={{ fontSize: '10px', color: FINCEPT.MUTED, fontStyle: 'italic', marginBottom: '8px' }}>+ {c.original_complete_name}+ </div>+ )}+ <div style={{ display: 'flex', gap: '20px', flexWrap: 'wrap', fontSize: '10px' }}>+ {c.siren && (+ <div>+ <span style={{ color: FINCEPT.GRAY }}>SIREN:</span>{' '}+ <span style={{ color: PROVIDER_COLOR, fontWeight: 600 }}>{c.siren}</span>+ </div>+ )}+ {c.siret && (+ <div>+ <span style={{ color: FINCEPT.GRAY }}>SIRET:</span>{' '}+ <span style={{ color: PROVIDER_COLOR, fontWeight: 600 }}>{c.siret}</span>+ </div>+ )}+ {c.company_category && (+ <div><span style={{ color: FINCEPT.GRAY }}>Category:</span> {c.company_category}</div>+ )}+ {c.administrative_status && (+ <div>+ <span style={{ color: FINCEPT.GRAY }}>Status:</span>{' '}+ <span style={{ color: c.administrative_status === 'A' ? FINCEPT.GREEN : FINCEPT.RED, fontWeight: 600 }}>+ {c.administrative_status === 'A' ? 'Active' : c.administrative_status === 'C' ? 'Ceased' : c.administrative_status}+ </span>+ </div>+ )}+ {c.creation_date && (+ <div><span style={{ color: FINCEPT.GRAY }}>Created:</span> {formatDate(c.creation_date)}</div>+ )}+ {c.legal_form && (+ <div><span style={{ color: FINCEPT.GRAY }}>Legal form:</span> {c.legal_form}</div>+ )}+ {c.main_activity && (+ <div><span style={{ color: FINCEPT.GRAY }}>Activity:</span> {c.main_activity}</div>+ )}+ {c.employee_size_range && (+ <div><span style={{ color: FINCEPT.GRAY }}>Employees:</span> {c.employee_size_range}</div>+ )}+ </div>+ </div>+ ))}+ </div>+ );+}++// ===== Shared styles =====++const thStyle: React.CSSProperties = {+ padding: '8px 12px',+ textAlign: 'left',+ fontSize: '9px',+ fontWeight: 700,+ color: PROVIDER_COLOR,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+};++const tdStyle: React.CSSProperties = {+ padding: '8px 12px',+ fontSize: '11px',+ color: FINCEPT.WHITE,+};++const summaryBarStyle: React.CSSProperties = {+ padding: '8px 16px',+ fontSize: '9px',+ color: FINCEPT.GRAY,+ backgroundColor: FINCEPT.PANEL_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+};++const pageBtnStyle: React.CSSProperties = {+ padding: '3px 8px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 600,+ display: 'flex',+ alignItems: 'center',+ gap: '2px',+};++export default FrenchGovProvider;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/OpenAfricaProvider.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/OpenAfricaProvider.tsxnew file mode 100644index 000000000..3bacfca9d--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/OpenAfricaProvider.tsx@@ -0,0 +1,525 @@+// OpenAfricaProvider - openAFRICA Open Data portal interface+// Hierarchical browsing: Organizations -> Datasets -> Resources + Search & Recent++import React, { useEffect, useCallback } from 'react';+import { RefreshCw, AlertCircle, Database, Download, Search, ChevronRight, ExternalLink, FileText, ArrowLeft, Clock, Building2 } from 'lucide-react';+import { FINCEPT } from '../constants';+import { useOpenAfricaData } from '../hooks/useOpenAfricaData';+import type { OpenAfricaView, OpenAfricaOrganization, OpenAfricaDataset, OpenAfricaResource } from '../types';++const VIEWS: { id: OpenAfricaView; label: string }[] = [+ { id: 'organizations', label: 'ORGS' },+ { id: 'datasets', label: 'DATASETS' },+ { id: 'search', label: 'SEARCH' },+ { id: 'recent', label: 'RECENT' },+];++const PROVIDER_COLOR = '#F59E0B';++const truncate = (text: string, max: number): string =>+ text.length > max ? text.substring(0, max) + '...' : text;++const formatDate = (dateStr: string | null | undefined): string => {+ if (!dateStr) return '-';+ return dateStr.substring(0, 10);+};++const formatSize = (bytes: string | number | null): string => {+ if (!bytes) return '-';+ const n = typeof bytes === 'string' ? parseInt(bytes, 10) : bytes;+ if (isNaN(n)) return '-';+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;+};++export function OpenAfricaProvider() {+ const {+ activeView, setActiveView,+ organizations, selectedOrg, setSelectedOrg, fetchOrganizations,+ datasets, selectedDataset, setSelectedDataset, fetchDatasets, datasetsTotalCount,+ resources, fetchResources,+ searchQuery, setSearchQuery, searchResults, searchTotalCount, searchDatasets,+ recentDatasets, fetchRecentDatasets,+ exportCSV,+ loading, error,+ } = useOpenAfricaData();++ useEffect(() => {+ fetchOrganizations();+ }, [fetchOrganizations]);++ const handleViewChange = (view: OpenAfricaView) => {+ setActiveView(view);+ if (view === 'recent' && recentDatasets.length === 0) {+ fetchRecentDatasets();+ }+ };++ const handleOrgClick = (orgName: string) => {+ setSelectedOrg(orgName);+ setSelectedDataset(null);+ setActiveView('datasets');+ fetchDatasets(orgName);+ };++ const handleDatasetClick = (datasetId: string) => {+ setSelectedDataset(datasetId);+ setActiveView('resources');+ fetchResources(datasetId);+ };++ const handleBack = () => {+ if (activeView === 'resources') {+ setActiveView('datasets');+ setSelectedDataset(null);+ } else if (activeView === 'datasets') {+ setActiveView('organizations');+ setSelectedOrg(null);+ }+ };++ const handleSearchKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === 'Enter') searchDatasets();+ };++ const inputStyle: React.CSSProperties = {+ padding: '6px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '11px',+ outline: 'none',+ fontFamily: 'inherit',+ };++ const hasData = (activeView === 'organizations' && organizations.length > 0)+ || (activeView === 'datasets' && datasets.length > 0)+ || (activeView === 'resources' && resources.length > 0)+ || (activeView === 'search' && searchResults.length > 0)+ || (activeView === 'recent' && recentDatasets.length > 0);++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Header bar */}+ <div style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ flexWrap: 'wrap',+ }}>+ {/* Back button */}+ {(activeView === 'datasets' || activeView === 'resources') && (+ <button+ onClick={handleBack}+ style={{+ padding: '5px 8px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <ArrowLeft size={11} />+ BACK+ </button>+ )}++ {/* View selector */}+ <div style={{ display: 'flex', gap: '2px', marginRight: '12px' }}>+ {VIEWS.map(v => (+ <button+ key={v.id}+ onClick={() => handleViewChange(v.id)}+ style={{+ padding: '5px 12px',+ backgroundColor: activeView === v.id ? PROVIDER_COLOR : 'transparent',+ color: activeView === v.id ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ border: `1px solid ${activeView === v.id ? PROVIDER_COLOR : FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ }}+ >+ {v.label}+ </button>+ ))}+ </div>++ {/* Search input */}+ {activeView === 'search' && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flex: 1, maxWidth: '400px' }}>+ <Search size={14} color={FINCEPT.GRAY} />+ <input+ type="text"+ value={searchQuery}+ onChange={e => setSearchQuery(e.target.value)}+ onKeyDown={handleSearchKeyDown}+ placeholder="Search African datasets..."+ style={{ ...inputStyle, flex: 1 }}+ />+ <button+ onClick={searchDatasets}+ disabled={loading || !searchQuery.trim()}+ style={{+ padding: '6px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.DARK_BG,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading || !searchQuery.trim() ? 'not-allowed' : 'pointer',+ opacity: loading || !searchQuery.trim() ? 0.5 : 1,+ }}+ >+ SEARCH+ </button>+ </div>+ )}++ {/* Breadcrumb */}+ {(activeView === 'datasets' && selectedOrg) && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>Organizations</span>+ <ChevronRight size={10} />+ <span style={{ color: PROVIDER_COLOR }}>{selectedOrg}</span>+ <span style={{ color: FINCEPT.MUTED }}>({datasetsTotalCount} datasets)</span>+ </div>+ )}+ {(activeView === 'resources' && selectedDataset) && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>Organizations</span>+ <ChevronRight size={10} />+ <span>{selectedOrg}</span>+ <ChevronRight size={10} />+ <span style={{ color: PROVIDER_COLOR }}>{truncate(selectedDataset, 30)}</span>+ </div>+ )}++ {/* Actions */}+ <div style={{ marginLeft: 'auto', display: 'flex', gap: '4px' }}>+ {hasData && (+ <button+ onClick={exportCSV}+ title="Export CSV"+ style={{+ padding: '5px 10px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <Download size={11} />+ CSV+ </button>+ )}+ {activeView === 'organizations' && (+ <button+ onClick={fetchOrganizations}+ disabled={loading}+ style={{+ padding: '5px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.DARK_BG,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: loading ? 0.7 : 1,+ }}+ >+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />+ REFRESH+ </button>+ )}+ </div>+ </div>++ {/* Content area */}+ <div style={{ flex: 1, overflow: 'auto' }}>+ {loading ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <RefreshCw size={32} className="animate-spin" style={{ color: PROVIDER_COLOR, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>Loading openAFRICA data...</div>+ </div>+ ) : error ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <AlertCircle size={32} style={{ color: FINCEPT.RED, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.RED, marginBottom: '8px' }}>Error loading data</div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '400px' }}>{error}</div>+ </div>+ ) : activeView === 'organizations' ? (+ <OrganizationsTable organizations={organizations} onSelect={handleOrgClick} />+ ) : activeView === 'datasets' ? (+ <DatasetsTable datasets={datasets} onSelect={handleDatasetClick} totalCount={datasetsTotalCount} />+ ) : activeView === 'resources' ? (+ <ResourcesTable resources={resources} />+ ) : activeView === 'search' ? (+ searchResults.length > 0+ ? <DatasetsTable datasets={searchResults} onSelect={handleDatasetClick} totalCount={searchTotalCount} />+ : <EmptyState icon={Search} message="Search African open datasets" sub="Enter a query above and press SEARCH or Enter" />+ ) : activeView === 'recent' ? (+ recentDatasets.length > 0+ ? <DatasetsTable datasets={recentDatasets} onSelect={handleDatasetClick} totalCount={recentDatasets.length} />+ : <EmptyState icon={Clock} message="Loading recent datasets..." sub="" />+ ) : (+ <EmptyState icon={Database} message="Select a view" sub="" />+ )}+ </div>+ </div>+ );+}++// ===== Sub-components =====++function EmptyState({ icon: Icon, message, sub }: { icon: React.ElementType; message: string; sub: string }) {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <Icon size={48} style={{ color: FINCEPT.MUTED, marginBottom: '16px', opacity: 0.5 }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE, marginBottom: '8px' }}>{message}</div>+ {sub && <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>{sub}</div>}+ </div>+ );+}++function OrganizationsTable({ organizations, onSelect }: { organizations: OpenAfricaOrganization[]; onSelect: (name: string) => void }) {+ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {organizations.length} organizations+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>ORGANIZATION</th>+ <th style={{ ...thStyle, width: '90px' }}>DATASETS</th>+ <th style={{ ...thStyle, width: '100px' }}>CREATED</th>+ <th style={{ ...thStyle, width: '40px' }}></th>+ </tr>+ </thead>+ <tbody>+ {organizations.map(o => (+ <tr+ key={o.id}+ onClick={() => onSelect(o.name)}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={tdStyle}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Building2 size={14} color={FINCEPT.MUTED} />+ <div>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {o.title || o.display_name || o.name}+ </div>+ {o.description && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{truncate(o.description, 80)}</div>+ )}+ </div>+ </div>+ </td>+ <td style={{ ...tdStyle, textAlign: 'center' }}>+ <span style={{ color: PROVIDER_COLOR, fontWeight: 600 }}>{o.dataset_count}</span>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(o.created)}</td>+ <td style={tdStyle}>+ <ChevronRight size={14} color={FINCEPT.MUTED} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function DatasetsTable({ datasets, onSelect, totalCount }: { datasets: OpenAfricaDataset[]; onSelect: (id: string) => void; totalCount: number }) {+ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ Showing {datasets.length} of {totalCount} datasets+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>TITLE</th>+ <th style={{ ...thStyle, width: '80px' }}>RESOURCES</th>+ <th style={{ ...thStyle, width: '100px' }}>MODIFIED</th>+ <th style={{ ...thStyle, width: '200px' }}>TAGS</th>+ <th style={{ ...thStyle, width: '40px' }}></th>+ </tr>+ </thead>+ <tbody>+ {datasets.map(d => (+ <tr+ key={d.id}+ onClick={() => onSelect(d.name || d.id)}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={tdStyle}>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600, marginBottom: '2px' }}>+ {truncate(d.title, 80)}+ </div>+ {d.notes && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{truncate(d.notes, 100)}</div>+ )}+ </td>+ <td style={{ ...tdStyle, textAlign: 'center' }}>+ <span style={{ color: PROVIDER_COLOR, fontWeight: 600 }}>{d.resource_count}</span>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(d.modified)}</td>+ <td style={tdStyle}>+ <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>+ {d.tags.slice(0, 3).map((tag, i) => (+ <span key={i} style={{+ padding: '1px 6px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '8px',+ fontWeight: 600,+ }}>+ {truncate(typeof tag === 'string' ? tag : (tag as any)?.display_name || '', 20)}+ </span>+ ))}+ {d.tags.length > 3 && (+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>+{d.tags.length - 3}</span>+ )}+ </div>+ </td>+ <td style={tdStyle}>+ <ChevronRight size={14} color={FINCEPT.MUTED} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function ResourcesTable({ resources }: { resources: OpenAfricaResource[] }) {+ const handleOpenUrl = useCallback(async (url: string) => {+ try {+ const { openUrl } = await import('@tauri-apps/plugin-opener');+ await openUrl(url);+ } catch {+ window.open(url, '_blank');+ }+ }, []);++ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {resources.length} resource{resources.length !== 1 ? 's' : ''} available+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>NAME</th>+ <th style={{ ...thStyle, width: '80px' }}>FORMAT</th>+ <th style={{ ...thStyle, width: '90px' }}>SIZE</th>+ <th style={{ ...thStyle, width: '100px' }}>MODIFIED</th>+ <th style={{ ...thStyle, width: '60px' }}>LINK</th>+ </tr>+ </thead>+ <tbody>+ {resources.map(r => (+ <tr key={r.id} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <td style={tdStyle}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <FileText size={14} color={FINCEPT.MUTED} />+ <div>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {r.name || r.id}+ </div>+ {r.description && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{truncate(r.description, 80)}</div>+ )}+ </div>+ </div>+ </td>+ <td style={tdStyle}>+ <span style={{+ padding: '2px 8px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ }}>+ {r.format || '?'}+ </span>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatSize(r.size)}</td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(r.last_modified)}</td>+ <td style={tdStyle}>+ {r.url && (+ <button+ onClick={() => handleOpenUrl(r.url)}+ style={{+ background: 'none',+ border: 'none',+ color: PROVIDER_COLOR,+ cursor: 'pointer',+ padding: '4px',+ display: 'flex',+ alignItems: 'center',+ }}+ title={r.url}+ >+ <ExternalLink size={14} />+ </button>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++// Shared styles+const thStyle: React.CSSProperties = {+ padding: '8px 12px',+ textAlign: 'left',+ fontSize: '9px',+ fontWeight: 700,+ color: PROVIDER_COLOR,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+};++const tdStyle: React.CSSProperties = {+ padding: '8px 12px',+ fontSize: '11px',+ color: FINCEPT.WHITE,+};++export default OpenAfricaProvider;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/PxWebProvider.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/PxWebProvider.tsxnew file mode 100644index 000000000..f29b68862--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/PxWebProvider.tsx@@ -0,0 +1,472 @@+// PxWebProvider - Statistics Finland (PxWeb) portal interface+// Browse database tree -> View table metadata -> Fetch data++import React, { useEffect, useMemo } from 'react';+import { RefreshCw, AlertCircle, Database, Download, FolderOpen, Table2, ArrowLeft, ChevronRight, Play, BarChart3 } from 'lucide-react';+import { FINCEPT } from '../constants';+import { usePxWebData } from '../hooks/usePxWebData';+import type { PxWebView, PxWebNode, PxWebVariable, PxWebStatData } from '../types';++const VIEWS: { id: PxWebView; label: string }[] = [+ { id: 'browse', label: 'BROWSE' },+ { id: 'metadata', label: 'TABLE INFO' },+ { id: 'data', label: 'DATA' },+];++const PROVIDER_COLOR = '#0EA5E9';++const truncate = (text: string, max: number): string =>+ text.length > max ? text.substring(0, max) + '...' : text;++export function PxWebProvider() {+ const {+ activeView, setActiveView,+ nodes, pathStack, currentPath, fetchNodes, navigateInto, navigateBack,+ variables, tableLabel, selectedTable,+ statData, fetchData,+ exportCSV,+ loading, error,+ } = usePxWebData();++ useEffect(() => {+ fetchNodes('');+ }, [fetchNodes]);++ const handleFetchAllData = () => {+ if (!selectedTable) return;+ // Fetch with empty query = all values for first few time periods+ fetchData(selectedTable, []);+ };++ const hasData = (activeView === 'browse' && nodes.length > 0)+ || (activeView === 'metadata' && variables.length > 0)+ || (activeView === 'data' && statData?.value && statData.value.length > 0);++ // Build breadcrumb from pathStack+ const breadcrumb = pathStack.filter(p => p !== '');++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Header bar */}+ <div style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ flexWrap: 'wrap',+ }}>+ {/* Back button */}+ {(activeView === 'browse' && pathStack.length > 1) && (+ <button+ onClick={navigateBack}+ style={{+ padding: '5px 8px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <ArrowLeft size={11} />+ BACK+ </button>+ )}+ {(activeView === 'metadata' || activeView === 'data') && (+ <button+ onClick={() => setActiveView('browse')}+ style={{+ padding: '5px 8px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <ArrowLeft size={11} />+ BROWSE+ </button>+ )}++ {/* View selector */}+ <div style={{ display: 'flex', gap: '2px', marginRight: '12px' }}>+ {VIEWS.map(v => (+ <button+ key={v.id}+ onClick={() => setActiveView(v.id)}+ disabled={v.id === 'metadata' && !selectedTable}+ style={{+ padding: '5px 12px',+ backgroundColor: activeView === v.id ? PROVIDER_COLOR : 'transparent',+ color: activeView === v.id ? FINCEPT.WHITE : FINCEPT.GRAY,+ border: `1px solid ${activeView === v.id ? PROVIDER_COLOR : FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: v.id === 'metadata' && !selectedTable ? 'not-allowed' : 'pointer',+ opacity: v.id === 'metadata' && !selectedTable ? 0.4 : 1,+ }}+ >+ {v.label}+ </button>+ ))}+ </div>++ {/* Breadcrumb */}+ {activeView === 'browse' && breadcrumb.length > 0 && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>StatFin</span>+ {breadcrumb.map((seg, i) => (+ <React.Fragment key={i}>+ <ChevronRight size={10} />+ <span style={{ color: i === breadcrumb.length - 1 ? PROVIDER_COLOR : FINCEPT.GRAY }}>+ {seg.split('/').pop()}+ </span>+ </React.Fragment>+ ))}+ </div>+ )}+ {(activeView === 'metadata' || activeView === 'data') && selectedTable && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>Table:</span>+ <span style={{ color: PROVIDER_COLOR }}>{truncate(tableLabel || selectedTable, 50)}</span>+ </div>+ )}++ {/* Actions */}+ <div style={{ marginLeft: 'auto', display: 'flex', gap: '4px' }}>+ {activeView === 'metadata' && selectedTable && (+ <button+ onClick={handleFetchAllData}+ disabled={loading}+ style={{+ padding: '5px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: loading ? 0.7 : 1,+ }}+ >+ <Play size={12} />+ FETCH DATA+ </button>+ )}+ {hasData && (+ <button+ onClick={exportCSV}+ title="Export CSV"+ style={{+ padding: '5px 10px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <Download size={11} />+ CSV+ </button>+ )}+ {activeView === 'browse' && (+ <button+ onClick={() => fetchNodes(currentPath)}+ disabled={loading}+ style={{+ padding: '5px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: loading ? 0.7 : 1,+ }}+ >+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />+ REFRESH+ </button>+ )}+ </div>+ </div>++ {/* Content area */}+ <div style={{ flex: 1, overflow: 'auto' }}>+ {loading ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <RefreshCw size={32} className="animate-spin" style={{ color: PROVIDER_COLOR, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>Loading Statistics Finland data...</div>+ </div>+ ) : error ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <AlertCircle size={32} style={{ color: FINCEPT.RED, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.RED, marginBottom: '8px' }}>Error loading data</div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '400px' }}>{error}</div>+ </div>+ ) : activeView === 'browse' ? (+ <NodesTable nodes={nodes} onSelect={navigateInto} />+ ) : activeView === 'metadata' ? (+ <MetadataPanel variables={variables} tableLabel={tableLabel} />+ ) : activeView === 'data' ? (+ statData ? <DataPanel statData={statData} /> : <EmptyState icon={BarChart3} message="No data loaded" sub="Select a table and click FETCH DATA" />+ ) : (+ <EmptyState icon={Database} message="Select a view" sub="" />+ )}+ </div>+ </div>+ );+}++// ===== Sub-components =====++function EmptyState({ icon: Icon, message, sub }: { icon: React.ElementType; message: string; sub: string }) {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <Icon size={48} style={{ color: FINCEPT.MUTED, marginBottom: '16px', opacity: 0.5 }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE, marginBottom: '8px' }}>{message}</div>+ {sub && <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>{sub}</div>}+ </div>+ );+}++function NodesTable({ nodes, onSelect }: { nodes: PxWebNode[]; onSelect: (n: PxWebNode) => void }) {+ const folders = nodes.filter(n => n.type === 'l');+ const tables = nodes.filter(n => n.type === 't');++ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {folders.length} folders, {tables.length} tables+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={{ ...thStyle, width: '40px' }}></th>+ <th style={thStyle}>NAME</th>+ <th style={{ ...thStyle, width: '120px' }}>ID</th>+ <th style={{ ...thStyle, width: '120px' }}>UPDATED</th>+ <th style={{ ...thStyle, width: '40px' }}></th>+ </tr>+ </thead>+ <tbody>+ {nodes.map((n, i) => (+ <tr+ key={n.id || i}+ onClick={() => onSelect(n)}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={{ ...tdStyle, textAlign: 'center' }}>+ {n.type === 'l'+ ? <FolderOpen size={14} color="#F59E0B" />+ : <Table2 size={14} color={PROVIDER_COLOR} />+ }+ </td>+ <td style={tdStyle}>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {truncate(n.text, 80)}+ </div>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.MUTED }}>{n.id}</td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>+ {n.updated ? n.updated.substring(0, 10) : '-'}+ </td>+ <td style={tdStyle}>+ <ChevronRight size={14} color={FINCEPT.MUTED} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function MetadataPanel({ variables, tableLabel }: { variables: PxWebVariable[]; tableLabel: string }) {+ return (+ <div>+ {tableLabel && (+ <div style={{+ padding: '10px 16px',+ fontSize: '12px',+ color: FINCEPT.WHITE,+ fontWeight: 700,+ backgroundColor: FINCEPT.PANEL_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ {tableLabel}+ </div>+ )}+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {variables.length} variables/dimensions+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>VARIABLE</th>+ <th style={{ ...thStyle, width: '80px' }}>VALUES</th>+ <th style={{ ...thStyle, width: '60px' }}>TIME</th>+ <th style={thStyle}>SAMPLE VALUES</th>+ </tr>+ </thead>+ <tbody>+ {variables.map((v, i) => (+ <tr key={v.code || i} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <td style={tdStyle}>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600 }}>{v.text}</div>+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{v.code}</div>+ </td>+ <td style={{ ...tdStyle, textAlign: 'center' }}>+ <span style={{ color: PROVIDER_COLOR, fontWeight: 600 }}>{v.values.length}</span>+ </td>+ <td style={{ ...tdStyle, textAlign: 'center', fontSize: '10px' }}>+ {v.time ? <span style={{ color: '#22C55E' }}>Yes</span> : <span style={{ color: FINCEPT.MUTED }}>No</span>}+ </td>+ <td style={tdStyle}>+ <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>+ {v.valueTexts.slice(0, 5).map((vt, j) => (+ <span key={j} style={{+ padding: '1px 6px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '8px',+ fontWeight: 600,+ }}>+ {truncate(vt, 20)}+ </span>+ ))}+ {v.valueTexts.length > 5 && (+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>+{v.valueTexts.length - 5}</span>+ )}+ </div>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function DataPanel({ statData }: { statData: PxWebStatData }) {+ // Flatten json-stat2 into a table+ const { headers, rows } = useMemo(() => {+ const dims = statData.id || [];+ const hdrs = dims.map(d => statData.dimension?.[d]?.label || d);+ hdrs.push('Value');++ const dimCats = dims.map(d => {+ const cat = statData.dimension?.[d]?.category;+ const labels = cat?.label || {};+ const indexEntries = Object.entries(cat?.index || {}).sort((a, b) => a[1] - b[1]);+ return indexEntries.map(([k]) => labels[k] || k);+ });++ const sizes = statData.size || dims.map((_, i) => dimCats[i].length);+ const totalValues = statData.value?.length || 0;+ const maxRows = Math.min(totalValues, 500); // Cap display at 500 rows++ const rws: string[][] = [];+ for (let i = 0; i < maxRows; i++) {+ let remainder = i;+ const parts: string[] = [];+ for (let d = dims.length - 1; d >= 0; d--) {+ const dimSize = sizes[d];+ const idx = remainder % dimSize;+ remainder = Math.floor(remainder / dimSize);+ parts.unshift(dimCats[d]?.[idx] || '');+ }+ parts.push(statData.value?.[i] != null ? String(statData.value[i]) : '');+ rws.push(parts);+ }++ return { headers: hdrs, rows: rws };+ }, [statData]);++ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}`, display: 'flex', justifyContent: 'space-between' }}>+ <span>{statData.label || 'Data'} — {statData.value?.length || 0} values</span>+ {(statData.value?.length || 0) > 500 && (+ <span style={{ color: '#F59E0B' }}>Showing first 500 rows (export CSV for full data)</span>+ )}+ </div>+ <div style={{ overflow: 'auto' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ {headers.map((h, i) => (+ <th key={i} style={thStyle}>{h.toUpperCase()}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {rows.map((row, i) => (+ <tr key={i} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {row.map((cell, j) => (+ <td key={j} style={{+ ...tdStyle,+ textAlign: j === row.length - 1 ? 'right' : 'left',+ fontWeight: j === row.length - 1 ? 600 : 400,+ color: j === row.length - 1 ? PROVIDER_COLOR : FINCEPT.WHITE,+ }}>+ {cell}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ );+}++// Shared styles+const thStyle: React.CSSProperties = {+ padding: '8px 12px',+ textAlign: 'left',+ fontSize: '9px',+ fontWeight: 700,+ color: PROVIDER_COLOR,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+};++const tdStyle: React.CSSProperties = {+ padding: '8px 12px',+ fontSize: '11px',+ color: FINCEPT.WHITE,+};++export default PxWebProvider;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/SpainDataProvider.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/SpainDataProvider.tsxnew file mode 100644index 000000000..2a0e3cd69--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/SpainDataProvider.tsx@@ -0,0 +1,548 @@+// SpainDataProvider - Spain Open Data (datos.gob.es) portal interface+// Hierarchical browsing: Catalogues (Publishers) -> Datasets -> Resources + Search++import React, { useEffect, useCallback } from 'react';+import { RefreshCw, AlertCircle, Database, Download, Search, ChevronRight, ChevronLeft, ExternalLink, FileText, ArrowLeft, BookOpen } from 'lucide-react';+import { FINCEPT } from '../constants';+import { useSpainData, extractTitle, extractFormat } from '../hooks/useSpainData';+import type { SpainDataView, SpainCatalogue, SpainDataset, SpainResource } from '../types';++const VIEWS: { id: SpainDataView; label: string }[] = [+ { id: 'catalogues', label: 'CATALOGUES' },+ { id: 'datasets', label: 'DATASETS' },+ { id: 'search', label: 'SEARCH' },+];++const PROVIDER_COLOR = '#DC2626';++const truncate = (text: string, max: number): string =>+ text.length > max ? text.substring(0, max) + '...' : text;++const formatDate = (dateStr: string | null | undefined): string => {+ if (!dateStr) return '-';+ return dateStr.substring(0, 10);+};++export function SpainDataProvider() {+ const {+ activeView, setActiveView,+ catalogues, selectedCatalogue, setSelectedCatalogue, fetchCatalogues,+ datasets, selectedDataset, setSelectedDataset, fetchDatasets,+ datasetsPage, setDatasetsPage,+ resources, fetchResources,+ searchQuery, setSearchQuery, searchResults, searchDatasets,+ exportCSV,+ loading, error,+ } = useSpainData();++ useEffect(() => {+ fetchCatalogues();+ }, [fetchCatalogues]);++ const handleViewChange = (view: SpainDataView) => {+ setActiveView(view);+ };++ const handleCatalogueClick = (cat: SpainCatalogue) => {+ const pubId = cat.extracted_id;+ setSelectedCatalogue(pubId);+ setSelectedDataset(null);+ setDatasetsPage(1);+ setActiveView('datasets');+ fetchDatasets(pubId);+ };++ const handleDatasetClick = (d: SpainDataset) => {+ const id = d.extracted_id || '';+ setSelectedDataset(id);+ setActiveView('resources');+ fetchResources(id);+ };++ const handleBack = () => {+ if (activeView === 'resources') {+ setActiveView('datasets');+ setSelectedDataset(null);+ } else if (activeView === 'datasets') {+ setActiveView('catalogues');+ setSelectedCatalogue(null);+ }+ };++ const handleSearchKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === 'Enter') searchDatasets();+ };++ const handleNextPage = () => {+ const next = datasetsPage + 1;+ setDatasetsPage(next);+ fetchDatasets(selectedCatalogue || undefined);+ };++ const handlePrevPage = () => {+ if (datasetsPage <= 1) return;+ const prev = datasetsPage - 1;+ setDatasetsPage(prev);+ fetchDatasets(selectedCatalogue || undefined);+ };++ const inputStyle: React.CSSProperties = {+ padding: '6px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '11px',+ outline: 'none',+ fontFamily: 'inherit',+ };++ const hasData = (activeView === 'catalogues' && catalogues.length > 0)+ || (activeView === 'datasets' && datasets.length > 0)+ || (activeView === 'resources' && resources.length > 0)+ || (activeView === 'search' && searchResults.length > 0);++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Header bar */}+ <div style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ flexWrap: 'wrap',+ }}>+ {/* Back button */}+ {(activeView === 'datasets' || activeView === 'resources') && (+ <button+ onClick={handleBack}+ style={{+ padding: '5px 8px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <ArrowLeft size={11} />+ BACK+ </button>+ )}++ {/* View selector */}+ <div style={{ display: 'flex', gap: '2px', marginRight: '12px' }}>+ {VIEWS.map(v => (+ <button+ key={v.id}+ onClick={() => handleViewChange(v.id)}+ style={{+ padding: '5px 12px',+ backgroundColor: activeView === v.id ? PROVIDER_COLOR : 'transparent',+ color: activeView === v.id ? FINCEPT.WHITE : FINCEPT.GRAY,+ border: `1px solid ${activeView === v.id ? PROVIDER_COLOR : FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ }}+ >+ {v.label}+ </button>+ ))}+ </div>++ {/* Search input */}+ {activeView === 'search' && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flex: 1, maxWidth: '400px' }}>+ <Search size={14} color={FINCEPT.GRAY} />+ <input+ type="text"+ value={searchQuery}+ onChange={e => setSearchQuery(e.target.value)}+ onKeyDown={handleSearchKeyDown}+ placeholder="Search Spanish datasets..."+ style={{ ...inputStyle, flex: 1 }}+ />+ <button+ onClick={searchDatasets}+ disabled={loading || !searchQuery.trim()}+ style={{+ padding: '6px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading || !searchQuery.trim() ? 'not-allowed' : 'pointer',+ opacity: loading || !searchQuery.trim() ? 0.5 : 1,+ }}+ >+ SEARCH+ </button>+ </div>+ )}++ {/* Breadcrumb */}+ {(activeView === 'datasets' && selectedCatalogue) && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>Catalogues</span>+ <ChevronRight size={10} />+ <span style={{ color: PROVIDER_COLOR }}>{selectedCatalogue}</span>+ </div>+ )}+ {(activeView === 'resources' && selectedDataset) && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>Catalogues</span>+ <ChevronRight size={10} />+ <span>{selectedCatalogue}</span>+ <ChevronRight size={10} />+ <span style={{ color: PROVIDER_COLOR }}>{truncate(selectedDataset, 30)}</span>+ </div>+ )}++ {/* Pagination for datasets */}+ {activeView === 'datasets' && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginLeft: '8px' }}>+ <button+ onClick={handlePrevPage}+ disabled={datasetsPage <= 1 || loading}+ style={{+ padding: '4px 8px',+ backgroundColor: 'transparent',+ color: datasetsPage <= 1 ? FINCEPT.MUTED : FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ cursor: datasetsPage <= 1 || loading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}+ >+ <ChevronLeft size={12} />+ </button>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Page {datasetsPage}</span>+ <button+ onClick={handleNextPage}+ disabled={loading || datasets.length === 0}+ style={{+ padding: '4px 8px',+ backgroundColor: 'transparent',+ color: loading || datasets.length === 0 ? FINCEPT.MUTED : FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ cursor: loading || datasets.length === 0 ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ }}+ >+ <ChevronRight size={12} />+ </button>+ </div>+ )}++ {/* Actions */}+ <div style={{ marginLeft: 'auto', display: 'flex', gap: '4px' }}>+ {hasData && (+ <button+ onClick={exportCSV}+ title="Export CSV"+ style={{+ padding: '5px 10px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <Download size={11} />+ CSV+ </button>+ )}+ {activeView === 'catalogues' && (+ <button+ onClick={fetchCatalogues}+ disabled={loading}+ style={{+ padding: '5px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: loading ? 0.7 : 1,+ }}+ >+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />+ REFRESH+ </button>+ )}+ </div>+ </div>++ {/* Content area */}+ <div style={{ flex: 1, overflow: 'auto' }}>+ {loading ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <RefreshCw size={32} className="animate-spin" style={{ color: PROVIDER_COLOR, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>Loading datos.gob.es data...</div>+ </div>+ ) : error ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <AlertCircle size={32} style={{ color: FINCEPT.RED, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.RED, marginBottom: '8px' }}>Error loading data</div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '400px' }}>{error}</div>+ </div>+ ) : activeView === 'catalogues' ? (+ <CataloguesTable catalogues={catalogues} onSelect={handleCatalogueClick} />+ ) : activeView === 'datasets' ? (+ <DatasetsTable datasets={datasets} onSelect={handleDatasetClick} />+ ) : activeView === 'resources' ? (+ <ResourcesTable resources={resources} />+ ) : activeView === 'search' ? (+ searchResults.length > 0+ ? <DatasetsTable datasets={searchResults} onSelect={handleDatasetClick} />+ : <EmptyState icon={Search} message="Search Spanish government datasets" sub="Enter a query above and press SEARCH or Enter" />+ ) : (+ <EmptyState icon={Database} message="Select a view" sub="" />+ )}+ </div>+ </div>+ );+}++// ===== Sub-components =====++function EmptyState({ icon: Icon, message, sub }: { icon: React.ElementType; message: string; sub: string }) {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <Icon size={48} style={{ color: FINCEPT.MUTED, marginBottom: '16px', opacity: 0.5 }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE, marginBottom: '8px' }}>{message}</div>+ {sub && <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>{sub}</div>}+ </div>+ );+}++function CataloguesTable({ catalogues, onSelect }: { catalogues: SpainCatalogue[]; onSelect: (c: SpainCatalogue) => void }) {+ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {catalogues.length} publishers+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>PUBLISHER ID</th>+ <th style={{ ...thStyle, width: '40px' }}></th>+ </tr>+ </thead>+ <tbody>+ {catalogues.map((c, i) => (+ <tr+ key={c.extracted_id || i}+ onClick={() => onSelect(c)}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={tdStyle}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <BookOpen size={14} color={FINCEPT.MUTED} />+ <div>+ <div style={{ fontSize: '11px', color: PROVIDER_COLOR, fontWeight: 600 }}>+ {c.extracted_id}+ </div>+ {c.uri && (+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED }}>{truncate(c.uri, 80)}</div>+ )}+ </div>+ </div>+ </td>+ <td style={tdStyle}>+ <ChevronRight size={14} color={FINCEPT.MUTED} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function DatasetsTable({ datasets, onSelect }: { datasets: SpainDataset[]; onSelect: (d: SpainDataset) => void }) {+ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {datasets.length} datasets+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>TITLE</th>+ <th style={{ ...thStyle, width: '80px' }}>FILES</th>+ <th style={{ ...thStyle, width: '100px' }}>MODIFIED</th>+ <th style={{ ...thStyle, width: '40px' }}></th>+ </tr>+ </thead>+ <tbody>+ {datasets.map((d, i) => {+ const title = extractTitle(d.title);+ const translated = d.title_translation?.translated;+ const distCount = d.distribution?.length || 0;++ return (+ <tr+ key={d.extracted_id || i}+ onClick={() => onSelect(d)}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={tdStyle}>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600, marginBottom: '2px' }}>+ {truncate(title, 80)}+ </div>+ {translated && translated !== title && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, fontStyle: 'italic' }}>+ {truncate(translated, 80)}+ </div>+ )}+ </td>+ <td style={{ ...tdStyle, textAlign: 'center' }}>+ <span style={{ color: PROVIDER_COLOR, fontWeight: 600 }}>{distCount}</span>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(d.modified)}</td>+ <td style={tdStyle}>+ <ChevronRight size={14} color={FINCEPT.MUTED} />+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+}++function ResourcesTable({ resources }: { resources: SpainResource[] }) {+ const handleOpenUrl = useCallback(async (url: string) => {+ try {+ const { openUrl } = await import('@tauri-apps/plugin-opener');+ await openUrl(url);+ } catch {+ window.open(url, '_blank');+ }+ }, []);++ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {resources.length} resource{resources.length !== 1 ? 's' : ''} available+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>NAME</th>+ <th style={{ ...thStyle, width: '80px' }}>FORMAT</th>+ <th style={{ ...thStyle, width: '60px' }}>LINK</th>+ </tr>+ </thead>+ <tbody>+ {resources.map((r, i) => {+ const title = extractTitle(r.title);+ const format = extractFormat(r.format);++ return (+ <tr key={i} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <td style={tdStyle}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <FileText size={14} color={FINCEPT.MUTED} />+ <div>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {title || `Resource ${i}`}+ </div>+ {r.title_translation?.translated && r.title_translation.translated !== title && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, fontStyle: 'italic' }}>+ {truncate(r.title_translation.translated, 80)}+ </div>+ )}+ </div>+ </div>+ </td>+ <td style={tdStyle}>+ <span style={{+ padding: '2px 8px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ }}>+ {format}+ </span>+ </td>+ <td style={tdStyle}>+ {r.accessURL && (+ <button+ onClick={() => handleOpenUrl(r.accessURL!)}+ style={{+ background: 'none',+ border: 'none',+ color: PROVIDER_COLOR,+ cursor: 'pointer',+ padding: '4px',+ display: 'flex',+ alignItems: 'center',+ }}+ title={r.accessURL}+ >+ <ExternalLink size={14} />+ </button>+ )}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+}++// Shared styles+const thStyle: React.CSSProperties = {+ padding: '8px 12px',+ textAlign: 'left',+ fontSize: '9px',+ fontWeight: 700,+ color: PROVIDER_COLOR,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+};++const tdStyle: React.CSSProperties = {+ padding: '8px 12px',+ fontSize: '11px',+ color: FINCEPT.WHITE,+};++export default SpainDataProvider;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/SwissGovProvider.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/SwissGovProvider.tsxnew file mode 100644index 000000000..3c53940f5--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/SwissGovProvider.tsx@@ -0,0 +1,525 @@+// SwissGovProvider - opendata.swiss portal interface+// Hierarchical browsing: Publishers -> Datasets -> Resources + Search & Recent+// Includes translated titles (DE/FR/IT → EN) alongside originals++import React, { useEffect, useCallback } from 'react';+import { RefreshCw, AlertCircle, Database, Download, Search, ChevronRight, ExternalLink, FileText, ArrowLeft, Clock } from 'lucide-react';+import { FINCEPT } from '../constants';+import { useSwissGovData } from '../hooks/useSwissGovData';+import type { SwissGovView, SwissDataset, SwissResource } from '../types';++const VIEWS: { id: SwissGovView; label: string }[] = [+ { id: 'publishers', label: 'PUBLISHERS' },+ { id: 'datasets', label: 'DATASETS' },+ { id: 'search', label: 'SEARCH' },+ { id: 'recent', label: 'RECENT' },+];++const PROVIDER_COLOR = '#E11D48';++const truncate = (text: string, max: number): string =>+ text.length > max ? text.substring(0, max) + '...' : text;++const formatDate = (dateStr: string | null): string => {+ if (!dateStr) return '-';+ return dateStr.substring(0, 10);+};++const formatSize = (bytes: number | null): string => {+ if (!bytes) return '-';+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+};++export function SwissGovProvider() {+ const {+ activeView, setActiveView,+ publishers, selectedPublisher, setSelectedPublisher, fetchPublishers,+ datasets, selectedDataset, setSelectedDataset, fetchDatasets, datasetsTotalCount,+ resources, fetchResources,+ searchQuery, setSearchQuery, searchResults, searchTotalCount, searchDatasets,+ recentDatasets, fetchRecentDatasets,+ exportCSV,+ loading, error,+ } = useSwissGovData();++ // Load publishers on mount+ useEffect(() => {+ fetchPublishers();+ }, [fetchPublishers]);++ const handleViewChange = (view: SwissGovView) => {+ setActiveView(view);+ if (view === 'recent' && recentDatasets.length === 0) {+ fetchRecentDatasets();+ }+ };++ const handlePublisherClick = (publisherId: string) => {+ setSelectedPublisher(publisherId);+ setSelectedDataset(null);+ setActiveView('datasets');+ fetchDatasets(publisherId);+ };++ const handleDatasetClick = (datasetId: string) => {+ setSelectedDataset(datasetId);+ setActiveView('resources');+ fetchResources(datasetId);+ };++ const handleBack = () => {+ if (activeView === 'resources') {+ setActiveView('datasets');+ setSelectedDataset(null);+ } else if (activeView === 'datasets') {+ setActiveView('publishers');+ setSelectedPublisher(null);+ }+ };++ const handleSearchKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === 'Enter') searchDatasets();+ };++ const inputStyle: React.CSSProperties = {+ padding: '6px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '11px',+ outline: 'none',+ fontFamily: 'inherit',+ };++ const hasData = (activeView === 'publishers' && publishers.length > 0)+ || (activeView === 'datasets' && datasets.length > 0)+ || (activeView === 'resources' && resources.length > 0)+ || (activeView === 'search' && searchResults.length > 0)+ || (activeView === 'recent' && recentDatasets.length > 0);++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Header bar */}+ <div style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ flexWrap: 'wrap',+ }}>+ {/* Back button for drill-down views */}+ {(activeView === 'datasets' || activeView === 'resources') && (+ <button+ onClick={handleBack}+ style={{+ padding: '5px 8px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <ArrowLeft size={11} />+ BACK+ </button>+ )}++ {/* View selector */}+ <div style={{ display: 'flex', gap: '2px', marginRight: '12px' }}>+ {VIEWS.map(v => (+ <button+ key={v.id}+ onClick={() => handleViewChange(v.id)}+ style={{+ padding: '5px 12px',+ backgroundColor: activeView === v.id ? PROVIDER_COLOR : 'transparent',+ color: activeView === v.id ? FINCEPT.WHITE : FINCEPT.GRAY,+ border: `1px solid ${activeView === v.id ? PROVIDER_COLOR : FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ }}+ >+ {v.label}+ </button>+ ))}+ </div>++ {/* Search input */}+ {activeView === 'search' && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flex: 1, maxWidth: '400px' }}>+ <Search size={14} color={FINCEPT.GRAY} />+ <input+ type="text"+ value={searchQuery}+ onChange={e => setSearchQuery(e.target.value)}+ onKeyDown={handleSearchKeyDown}+ placeholder="Search Swiss datasets..."+ style={{ ...inputStyle, flex: 1 }}+ />+ <button+ onClick={searchDatasets}+ disabled={loading || !searchQuery.trim()}+ style={{+ padding: '6px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading || !searchQuery.trim() ? 'not-allowed' : 'pointer',+ opacity: loading || !searchQuery.trim() ? 0.5 : 1,+ }}+ >+ SEARCH+ </button>+ </div>+ )}++ {/* Breadcrumb */}+ {(activeView === 'datasets' && selectedPublisher) && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>Publishers</span>+ <ChevronRight size={10} />+ <span style={{ color: PROVIDER_COLOR }}>{truncate(selectedPublisher, 40)}</span>+ <span style={{ color: FINCEPT.MUTED }}>({datasetsTotalCount} datasets)</span>+ </div>+ )}+ {(activeView === 'resources' && selectedDataset) && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>Publishers</span>+ <ChevronRight size={10} />+ <span>{truncate(selectedPublisher || '', 20)}</span>+ <ChevronRight size={10} />+ <span style={{ color: PROVIDER_COLOR }}>{truncate(selectedDataset, 30)}</span>+ </div>+ )}++ {/* Actions */}+ <div style={{ marginLeft: 'auto', display: 'flex', gap: '4px' }}>+ {hasData && (+ <button+ onClick={exportCSV}+ title="Export CSV"+ style={{+ padding: '5px 10px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <Download size={11} />+ CSV+ </button>+ )}+ {activeView === 'publishers' && (+ <button+ onClick={fetchPublishers}+ disabled={loading}+ style={{+ padding: '5px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: loading ? 0.7 : 1,+ }}+ >+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />+ REFRESH+ </button>+ )}+ </div>+ </div>++ {/* Content area */}+ <div style={{ flex: 1, overflow: 'auto' }}>+ {loading ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <RefreshCw size={32} className="animate-spin" style={{ color: PROVIDER_COLOR, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>Loading Swiss government data...</div>+ </div>+ ) : error ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <AlertCircle size={32} style={{ color: FINCEPT.RED, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.RED, marginBottom: '8px' }}>Error loading data</div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '400px' }}>{error}</div>+ </div>+ ) : activeView === 'publishers' ? (+ <PublishersTable publishers={publishers} onSelect={handlePublisherClick} />+ ) : activeView === 'datasets' ? (+ <DatasetsTable datasets={datasets} onSelect={handleDatasetClick} totalCount={datasetsTotalCount} />+ ) : activeView === 'resources' ? (+ <ResourcesTable resources={resources} />+ ) : activeView === 'search' ? (+ searchResults.length > 0+ ? <DatasetsTable datasets={searchResults} onSelect={handleDatasetClick} totalCount={searchTotalCount} />+ : <EmptyState icon={Search} message="Search Swiss government datasets" sub="Enter a query above and press SEARCH or Enter" />+ ) : activeView === 'recent' ? (+ recentDatasets.length > 0+ ? <DatasetsTable datasets={recentDatasets} onSelect={handleDatasetClick} totalCount={recentDatasets.length} />+ : <EmptyState icon={Clock} message="Loading recent datasets..." sub="" />+ ) : (+ <EmptyState icon={Database} message="Select a view" sub="" />+ )}+ </div>+ </div>+ );+}++// ===== Sub-components =====++function EmptyState({ icon: Icon, message, sub }: { icon: React.ElementType; message: string; sub: string }) {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <Icon size={48} style={{ color: FINCEPT.MUTED, marginBottom: '16px', opacity: 0.5 }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE, marginBottom: '8px' }}>{message}</div>+ {sub && <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>{sub}</div>}+ </div>+ );+}++function PublishersTable({ publishers, onSelect }: { publishers: { id: string; name: string; original_name: string }[]; onSelect: (id: string) => void }) {+ return (+ <div style={{ padding: '0' }}>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {publishers.length} publisher{publishers.length !== 1 ? 's' : ''}+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>PUBLISHER ID</th>+ <th style={thStyle}>NAME (EN)</th>+ <th style={thStyle}>ORIGINAL</th>+ <th style={{ ...thStyle, width: '60px' }}></th>+ </tr>+ </thead>+ <tbody>+ {publishers.map(p => (+ <tr+ key={p.id}+ onClick={() => onSelect(p.id)}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={{ ...tdStyle, color: PROVIDER_COLOR, fontWeight: 600, maxWidth: '250px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {p.id}+ </td>+ <td style={tdStyle}>{p.name}</td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.MUTED, fontStyle: 'italic' }}>+ {p.original_name !== p.name ? p.original_name : ''}+ </td>+ <td style={tdStyle}>+ <ChevronRight size={14} color={FINCEPT.MUTED} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function DatasetsTable({ datasets, onSelect, totalCount }: { datasets: SwissDataset[]; onSelect: (id: string) => void; totalCount: number }) {+ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ Showing {datasets.length} of {totalCount} datasets+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>TITLE</th>+ <th style={{ ...thStyle, width: '80px' }}>RESOURCES</th>+ <th style={{ ...thStyle, width: '100px' }}>MODIFIED</th>+ <th style={{ ...thStyle, width: '200px' }}>TAGS</th>+ <th style={{ ...thStyle, width: '40px' }}></th>+ </tr>+ </thead>+ <tbody>+ {datasets.map(d => (+ <tr+ key={d.id}+ onClick={() => onSelect(d.id)}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={tdStyle}>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600, marginBottom: '2px' }}>+ {truncate(d.title, 80)}+ </div>+ {d.original_title && d.original_title !== d.title && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, fontStyle: 'italic', marginBottom: '2px' }}>+ {truncate(d.original_title, 90)}+ </div>+ )}+ {d.notes && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{truncate(d.notes, 100)}</div>+ )}+ </td>+ <td style={{ ...tdStyle, textAlign: 'center' }}>+ <span style={{ color: PROVIDER_COLOR, fontWeight: 600 }}>{d.num_resources}</span>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(d.metadata_modified)}</td>+ <td style={tdStyle}>+ <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>+ {d.tags.slice(0, 3).map((tag, i) => (+ <span key={i} style={{+ padding: '1px 6px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '8px',+ fontWeight: 600,+ }}>+ {truncate(tag, 20)}+ </span>+ ))}+ {d.tags.length > 3 && (+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>+{d.tags.length - 3}</span>+ )}+ </div>+ </td>+ <td style={tdStyle}>+ <ChevronRight size={14} color={FINCEPT.MUTED} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function ResourcesTable({ resources }: { resources: SwissResource[] }) {+ const handleOpenUrl = useCallback(async (url: string) => {+ try {+ const { openUrl } = await import('@tauri-apps/plugin-opener');+ await openUrl(url);+ } catch {+ window.open(url, '_blank');+ }+ }, []);++ return (+ <div>+ <div style={{ padding: '8px 16px', fontSize: '9px', color: FINCEPT.GRAY, backgroundColor: FINCEPT.PANEL_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {resources.length} resource{resources.length !== 1 ? 's' : ''} available+ </div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>NAME</th>+ <th style={{ ...thStyle, width: '80px' }}>FORMAT</th>+ <th style={{ ...thStyle, width: '90px' }}>SIZE</th>+ <th style={{ ...thStyle, width: '100px' }}>MODIFIED</th>+ <th style={{ ...thStyle, width: '60px' }}>LINK</th>+ </tr>+ </thead>+ <tbody>+ {resources.map(r => (+ <tr key={r.id} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <td style={tdStyle}>+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '6px' }}>+ <FileText size={14} color={FINCEPT.MUTED} style={{ marginTop: '2px', flexShrink: 0 }} />+ <div>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {r.name || r.id}+ </div>+ {r.original_name && r.original_name !== r.name && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, fontStyle: 'italic' }}>+ {truncate(r.original_name, 80)}+ </div>+ )}+ {r.description && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{truncate(r.description, 80)}</div>+ )}+ </div>+ </div>+ </td>+ <td style={tdStyle}>+ <span style={{+ padding: '2px 8px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ }}>+ {r.format || '?'}+ </span>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatSize(r.size)}</td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(r.last_modified)}</td>+ <td style={tdStyle}>+ {r.url && (+ <button+ onClick={() => handleOpenUrl(r.url)}+ style={{+ background: 'none',+ border: 'none',+ color: PROVIDER_COLOR,+ cursor: 'pointer',+ padding: '4px',+ display: 'flex',+ alignItems: 'center',+ }}+ title={r.url}+ >+ <ExternalLink size={14} />+ </button>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++// Shared styles+const thStyle: React.CSSProperties = {+ padding: '8px 12px',+ textAlign: 'left',+ fontSize: '9px',+ fontWeight: 700,+ color: PROVIDER_COLOR,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+};++const tdStyle: React.CSSProperties = {+ padding: '8px 12px',+ fontSize: '11px',+ color: FINCEPT.WHITE,+};++export default SwissGovProvider;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasuryAuctionsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasuryAuctionsPanel.tsxnew file mode 100644index 000000000..a6e861845--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasuryAuctionsPanel.tsx@@ -0,0 +1,479 @@+// US Treasury Auctions Panel - Auction results with detailed bid data++import React, { useState, useMemo } from 'react';+import {+ BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Line, ComposedChart, Cell,+} from 'recharts';+import { BarChart3, Table2 } from 'lucide-react';+import { FINCEPT, AUCTION_DISPLAY_FIELDS } from '../constants';+import type { TreasuryAuctionsResponse, TreasuryAuctionRecord } from '../types';++const tooltipStyle = {+ backgroundColor: '#1A1A1A',+ border: '1px solid #2A2A2A',+ borderRadius: '4px',+ fontSize: '10px',+ fontFamily: '"IBM Plex Mono", monospace',+};++const SEC_COLORS: Record<string, string> = {+ Bill: '#3B82F6',+ Note: '#10B981',+ Bond: '#F59E0B',+ TIPS: '#8B5CF6',+ FRN: '#EC4899',+ CMB: '#06B6D4',+};++type ViewMode = 'table' | 'chart';++interface Props {+ data: TreasuryAuctionsResponse;+ pageNum: number;+ pageSize: number;+ onPageChange: (page: number) => void;+}++const formatCurrency = (val: number | null): string => {+ if (val === null || val === undefined) return '-';+ if (Math.abs(val) >= 1e12) return `$${(val / 1e12).toFixed(1)}T`;+ if (Math.abs(val) >= 1e9) return `$${(val / 1e9).toFixed(1)}B`;+ if (Math.abs(val) >= 1e6) return `$${(val / 1e6).toFixed(1)}M`;+ return `$${val.toLocaleString()}`;+};++const formatRate = (val: number | null): string => {+ if (val === null || val === undefined) return '-';+ return `${(val * 100).toFixed(3)}%`;+};++const formatRatio = (val: number | null): string => {+ if (val === null || val === undefined) return '-';+ return val.toFixed(2);+};++const formatPct = (val: number | null): string => {+ if (val === null || val === undefined) return '-';+ return `${(val * 100).toFixed(2)}%`;+};++const formatPrice = (val: number | null): string => {+ if (val === null || val === undefined) return '-';+ return val.toFixed(6);+};++const formatDate = (val: string | null): string => {+ if (!val) return '-';+ return val.split('T')[0];+};++const formatField = (val: any, format?: string): string => {+ if (val === null || val === undefined) return '-';+ switch (format) {+ case 'currency': return formatCurrency(val);+ case 'rate': return formatRate(val);+ case 'ratio': return formatRatio(val);+ case 'pct': return formatPct(val);+ case 'price': return formatPrice(val);+ default:+ if (typeof val === 'string' && val.includes('T')) return formatDate(val);+ return String(val);+ }+};++type SortField = string;+type SortDir = 'asc' | 'desc';++export function USTreasuryAuctionsPanel({ data, pageNum, pageSize, onPageChange }: Props) {+ const [sortField, setSortField] = useState<SortField>('auctionDate');+ const [sortDir, setSortDir] = useState<SortDir>('desc');+ const [expandedRow, setExpandedRow] = useState<number | null>(null);+ const [viewMode, setViewMode] = useState<ViewMode>('table');++ const sortedData = useMemo(() => {+ return [...data.data].sort((a, b) => {+ const aVal = a[sortField];+ const bVal = b[sortField];+ if (aVal === null || aVal === undefined) return 1;+ if (bVal === null || bVal === undefined) return -1;+ if (typeof aVal === 'number' && typeof bVal === 'number') {+ return sortDir === 'asc' ? aVal - bVal : bVal - aVal;+ }+ return sortDir === 'asc'+ ? String(aVal).localeCompare(String(bVal))+ : String(bVal).localeCompare(String(aVal));+ });+ }, [data.data, sortField, sortDir]);++ const handleSort = (field: SortField) => {+ if (sortField === field) {+ setSortDir(d => d === 'asc' ? 'desc' : 'asc');+ } else {+ setSortField(field);+ setSortDir('desc');+ }+ };++ const sortIndicator = (field: SortField) => {+ if (sortField !== field) return '';+ return sortDir === 'asc' ? ' \u25B2' : ' \u25BC';+ };++ // Aggregate stats+ const stats = useMemo(() => {+ const bids = data.data.map(d => d.bidToCoverRatio).filter((v): v is number => v !== null);+ const offerings = data.data.map(d => d.offeringAmount).filter((v): v is number => v !== null);+ return {+ avgBidCover: bids.length > 0 ? bids.reduce((a, b) => a + b, 0) / bids.length : 0,+ totalOffering: offerings.reduce((a, b) => a + b, 0),+ };+ }, [data.data]);++ // Chart data: bid-to-cover by auction date+ const chartData = useMemo(() => {+ return [...data.data]+ .filter(r => r.auctionDate && r.bidToCoverRatio)+ .sort((a, b) => (a.auctionDate || '').localeCompare(b.auctionDate || ''))+ .map(r => ({+ date: formatDate(r.auctionDate),+ bidCover: r.bidToCoverRatio,+ offering: r.offeringAmount ? r.offeringAmount / 1e9 : 0, // in billions+ type: r.securityType,+ term: r.securityTerm,+ cusip: r.cusip,+ fill: SEC_COLORS[r.securityType] || FINCEPT.GRAY,+ }));+ }, [data.data]);++ // Type distribution for chart+ const typeDistribution = useMemo(() => {+ const counts: Record<string, { count: number; totalOffering: number }> = {};+ data.data.forEach(r => {+ const t = r.securityType;+ if (!counts[t]) counts[t] = { count: 0, totalOffering: 0 };+ counts[t].count++;+ if (r.offeringAmount) counts[t].totalOffering += r.offeringAmount;+ });+ return Object.entries(counts).map(([type, v]) => ({+ type,+ count: v.count,+ totalOffering: +(v.totalOffering / 1e9).toFixed(1),+ fill: SEC_COLORS[type] || FINCEPT.GRAY,+ })).sort((a, b) => b.totalOffering - a.totalOffering);+ }, [data.data]);++ const thStyle: React.CSSProperties = {+ padding: '8px 8px',+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ textAlign: 'left',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ cursor: 'pointer',+ userSelect: 'none',+ whiteSpace: 'nowrap',+ };++ const tdStyle: React.CSSProperties = {+ padding: '6px 8px',+ fontSize: '10px',+ color: FINCEPT.WHITE,+ borderBottom: `1px solid ${FINCEPT.BORDER}08`,+ whiteSpace: 'nowrap',+ };++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Stats bar */}+ <div style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '20px',+ fontSize: '10px',+ }}>+ <span><span style={{ color: FINCEPT.GRAY }}>RESULTS:</span> <span style={{ color: FINCEPT.WHITE }}>{data.total_records}</span></span>+ <span><span style={{ color: FINCEPT.GRAY }}>AVG BID/COVER:</span> <span style={{ color: '#3B82F6' }}>{stats.avgBidCover.toFixed(2)}x</span></span>+ <span><span style={{ color: FINCEPT.GRAY }}>TOTAL OFFERING:</span> <span style={{ color: FINCEPT.GREEN }}>{formatCurrency(stats.totalOffering)}</span></span>+ {data.filters.security_type && (+ <span><span style={{ color: FINCEPT.GRAY }}>TYPE:</span> <span style={{ color: FINCEPT.ORANGE }}>{data.filters.security_type}</span></span>+ )}+ <div style={{ marginLeft: 'auto', display: 'flex', gap: '2px' }}>+ <button+ onClick={() => setViewMode('table')}+ style={{+ padding: '3px 6px', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px',+ backgroundColor: viewMode === 'table' ? '#3B82F6' : 'transparent',+ color: viewMode === 'table' ? FINCEPT.WHITE : FINCEPT.GRAY,+ cursor: 'pointer', display: 'flex', alignItems: 'center',+ }}+ >+ <Table2 size={12} />+ </button>+ <button+ onClick={() => setViewMode('chart')}+ style={{+ padding: '3px 6px', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px',+ backgroundColor: viewMode === 'chart' ? '#3B82F6' : 'transparent',+ color: viewMode === 'chart' ? FINCEPT.WHITE : FINCEPT.GRAY,+ cursor: 'pointer', display: 'flex', alignItems: 'center',+ }}+ >+ <BarChart3 size={12} />+ </button>+ </div>+ </div>++ {viewMode === 'chart' ? (+ /* Chart View */+ <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>+ {/* Bid-to-Cover Ratio over time */}+ <div style={{+ marginBottom: '20px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ padding: '16px',+ }}>+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE, marginBottom: '12px' }}>+ Bid-to-Cover Ratio & Offering Amount by Auction+ </div>+ <ResponsiveContainer width="100%" height={280}>+ <ComposedChart data={chartData} margin={{ top: 5, right: 30, left: 0, bottom: 5 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={FINCEPT.BORDER} />+ <XAxis dataKey="date" tick={{ fill: FINCEPT.GRAY, fontSize: 9 }} interval={Math.max(0, Math.floor(chartData.length / 12))} angle={-20} textAnchor="end" height={50} />+ <YAxis yAxisId="left" tick={{ fill: FINCEPT.GRAY, fontSize: 9 }} label={{ value: 'Bid/Cover', angle: -90, position: 'insideLeft', fill: FINCEPT.GRAY, fontSize: 9 }} />+ <YAxis yAxisId="right" orientation="right" tick={{ fill: FINCEPT.GRAY, fontSize: 9 }} label={{ value: 'Offering ($B)', angle: 90, position: 'insideRight', fill: FINCEPT.GRAY, fontSize: 9 }} />+ <Tooltip+ contentStyle={tooltipStyle}+ labelStyle={{ color: FINCEPT.WHITE }}+ formatter={(value: any, name: string) => {+ if (name === 'Bid/Cover') return [Number(value).toFixed(2) + 'x', name];+ if (name === 'Offering ($B)') return ['$' + Number(value).toFixed(1) + 'B', name];+ return [value, name];+ }}+ />+ <Bar yAxisId="right" dataKey="offering" name="Offering ($B)" opacity={0.4} radius={[2, 2, 0, 0]}>+ {chartData.map((entry, i) => (+ <Cell key={i} fill={entry.fill} />+ ))}+ </Bar>+ <Line yAxisId="left" type="monotone" dataKey="bidCover" name="Bid/Cover" stroke="#3B82F6" strokeWidth={2} dot={{ r: 3, fill: '#3B82F6' }} />+ </ComposedChart>+ </ResponsiveContainer>+ </div>++ {/* Type Distribution */}+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ padding: '16px',+ }}>+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE, marginBottom: '12px' }}>+ Auction Count & Total Offering by Security Type+ </div>+ <ResponsiveContainer width="100%" height={200}>+ <BarChart data={typeDistribution} margin={{ top: 5, right: 30, left: 0, bottom: 5 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={FINCEPT.BORDER} />+ <XAxis dataKey="type" tick={{ fill: FINCEPT.GRAY, fontSize: 10 }} />+ <YAxis yAxisId="left" tick={{ fill: FINCEPT.GRAY, fontSize: 9 }} />+ <YAxis yAxisId="right" orientation="right" tick={{ fill: FINCEPT.GRAY, fontSize: 9 }} />+ <Tooltip contentStyle={tooltipStyle} labelStyle={{ color: FINCEPT.WHITE }} />+ <Bar yAxisId="left" dataKey="count" name="Auctions" radius={[2, 2, 0, 0]}>+ {typeDistribution.map((entry, i) => (+ <Cell key={i} fill={entry.fill} />+ ))}+ </Bar>+ <Bar yAxisId="right" dataKey="totalOffering" name="Total ($B)" fill="#10B981" opacity={0.5} radius={[2, 2, 0, 0]} />+ </BarChart>+ </ResponsiveContainer>+ </div>+ </div>+ ) : (+ /* Table View */+ <div style={{ flex: 1, overflow: 'auto' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: '"IBM Plex Mono", monospace' }}>+ <thead style={{ position: 'sticky', top: 0, backgroundColor: FINCEPT.HEADER_BG, zIndex: 1 }}>+ <tr>+ {AUCTION_DISPLAY_FIELDS.map(f => (+ <th+ key={f.key}+ style={{ ...thStyle, minWidth: f.width }}+ onClick={() => handleSort(f.key)}+ >+ {f.label}{sortIndicator(f.key)}+ </th>+ ))}+ <th style={{ ...thStyle, width: 40 }}></th>+ </tr>+ </thead>+ <tbody>+ {sortedData.map((row, i) => (+ <React.Fragment key={`${row.cusip}-${i}`}>+ <tr+ style={{ backgroundColor: i % 2 === 0 ? 'transparent' : `${FINCEPT.PANEL_BG}80` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = i % 2 === 0 ? 'transparent' : `${FINCEPT.PANEL_BG}80`)}+ >+ {AUCTION_DISPLAY_FIELDS.map(f => (+ <td+ key={f.key}+ style={{+ ...tdStyle,+ color: f.key === 'cusip' ? '#3B82F6' :+ f.format === 'rate' ? FINCEPT.YELLOW :+ f.format === 'currency' ? FINCEPT.GREEN :+ f.format === 'ratio' ? '#3B82F6' :+ FINCEPT.WHITE,+ fontWeight: f.key === 'cusip' ? 600 : 400,+ }}+ >+ {formatField(row[f.key], f.format)}+ </td>+ ))}+ <td style={tdStyle}>+ <button+ onClick={() => setExpandedRow(expandedRow === i ? null : i)}+ style={{+ background: 'none',+ border: 'none',+ color: FINCEPT.GRAY,+ cursor: 'pointer',+ fontSize: '12px',+ padding: '2px 4px',+ }}+ >+ {expandedRow === i ? '\u25B4' : '\u25BE'}+ </button>+ </td>+ </tr>+ {expandedRow === i && (+ <tr>+ <td colSpan={AUCTION_DISPLAY_FIELDS.length + 1} style={{ padding: 0 }}>+ <AuctionDetailRow record={row} />+ </td>+ </tr>+ )}+ </React.Fragment>+ ))}+ </tbody>+ </table>+ </div>+ )}++ {/* Pagination */}+ <div style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ fontSize: '10px',+ }}>+ <span style={{ color: FINCEPT.GRAY }}>+ Page {pageNum} ({data.total_records} records)+ </span>+ <div style={{ display: 'flex', gap: '6px' }}>+ <button+ onClick={() => onPageChange(pageNum - 1)}+ disabled={pageNum <= 1}+ style={{+ padding: '4px 10px',+ backgroundColor: pageNum <= 1 ? FINCEPT.MUTED : FINCEPT.PANEL_BG,+ color: pageNum <= 1 ? FINCEPT.GRAY : FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: pageNum <= 1 ? 'default' : 'pointer',+ }}+ >+ PREV+ </button>+ <button+ onClick={() => onPageChange(pageNum + 1)}+ disabled={data.total_records < pageSize}+ style={{+ padding: '4px 10px',+ backgroundColor: data.total_records < pageSize ? FINCEPT.MUTED : FINCEPT.PANEL_BG,+ color: data.total_records < pageSize ? FINCEPT.GRAY : FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: data.total_records < pageSize ? 'default' : 'pointer',+ }}+ >+ NEXT+ </button>+ </div>+ </div>+ </div>+ );+}++// Expanded detail row for a single auction+function AuctionDetailRow({ record }: { record: TreasuryAuctionRecord }) {+ const detailGroups = [+ {+ title: 'Pricing',+ fields: [+ { label: 'High Discount Rate', value: formatRate(record.highDiscountRate) },+ { label: 'High Investment Rate', value: formatRate(record.highInvestmentRate) },+ { label: 'High Price', value: formatPrice(record.highPrice) },+ { label: 'Price Per $100', value: record.pricePer100 || '-' },+ { label: 'Reopening', value: record.reopening || '-' },+ ],+ },+ {+ title: 'Demand',+ fields: [+ { label: 'Bid-to-Cover', value: formatRatio(record.bidToCoverRatio) },+ { label: 'Total Tendered', value: formatCurrency(record.totalTendered) },+ { label: 'Total Accepted', value: formatCurrency(record.totalAccepted) },+ { label: 'Competitive Tendered', value: formatCurrency(record.competitiveTendered) },+ { label: 'Competitive Accepted', value: formatCurrency(record.competitiveAccepted) },+ ],+ },+ {+ title: 'Bidder Breakdown',+ fields: [+ { label: 'Direct Bidder', value: formatCurrency(record.directBidderAccepted) },+ { label: 'Indirect Bidder', value: formatCurrency(record.indirectBidderAccepted) },+ { label: 'Primary Dealer', value: formatCurrency(record.primaryDealerAccepted) },+ { label: 'Allocation %', value: formatPct(record.allocationPercentage) },+ { label: 'Offering Amount', value: formatCurrency(record.offeringAmount) },+ ],+ },+ ];++ return (+ <div style={{+ padding: '12px 16px',+ backgroundColor: `${FINCEPT.PANEL_BG}`,+ borderBottom: `2px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ gap: '24px',+ }}>+ {detailGroups.map(group => (+ <div key={group.title} style={{ flex: 1 }}>+ <div style={{ fontSize: '9px', fontWeight: 700, color: '#3B82F6', marginBottom: '8px', textTransform: 'uppercase' }}>+ {group.title}+ </div>+ {group.fields.map(f => (+ <div key={f.label} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0', fontSize: '10px' }}>+ <span style={{ color: FINCEPT.GRAY }}>{f.label}</span>+ <span style={{ color: FINCEPT.WHITE, fontWeight: 500 }}>{f.value}</span>+ </div>+ ))}+ </div>+ ))}+ </div>+ );+}++export default USTreasuryAuctionsPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasuryPricesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasuryPricesPanel.tsxnew file mode 100644index 000000000..270080ba4--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasuryPricesPanel.tsx@@ -0,0 +1,384 @@+// US Treasury Prices Panel - End-of-day prices for Treasury securities++import React, { useState, useMemo } from 'react';+import {+ BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,+ ScatterChart, Scatter, Cell, Legend,+} from 'recharts';+import { BarChart3, Table2 } from 'lucide-react';+import { FINCEPT } from '../constants';+import type { TreasuryPricesResponse, TreasuryPriceRecord } from '../types';++interface Props {+ data: TreasuryPricesResponse;+}++const formatPrice = (val: number | null): string => {+ if (val === null || val === undefined) return '-';+ return val.toFixed(6);+};++const formatRate = (val: number | null): string => {+ if (val === null || val === undefined || val === 0) return '-';+ return `${(val * 100).toFixed(3)}%`;+};++const formatDate = (val: string | null): string => {+ if (!val) return '-';+ return val;+};++type SortField = keyof TreasuryPriceRecord;+type SortDir = 'asc' | 'desc';++const TYPE_COLORS: Record<string, string> = {+ 'MARKET BASED BILL': '#3B82F6',+ 'MARKET BASED NOTE': '#10B981',+ 'MARKET BASED BOND': '#F59E0B',+ 'TIPS': '#8B5CF6',+ 'MARKET BASED FRN': '#EC4899',+};++const tooltipStyle = {+ backgroundColor: '#1A1A1A',+ border: '1px solid #2A2A2A',+ borderRadius: '4px',+ fontSize: '10px',+ fontFamily: '"IBM Plex Mono", monospace',+};++type ViewMode = 'table' | 'chart';++export function USTreasuryPricesPanel({ data }: Props) {+ const [sortField, setSortField] = useState<SortField>('maturity_date');+ const [sortDir, setSortDir] = useState<SortDir>('asc');+ const [filterType, setFilterType] = useState<string>('all');+ const [searchCusip, setSearchCusip] = useState('');+ const [viewMode, setViewMode] = useState<ViewMode>('table');++ // Extract unique security types from data+ const securityTypes = useMemo(() => {+ const types = new Set(data.data.map(d => d.security_type));+ return Array.from(types).sort();+ }, [data.data]);++ // Filter and sort+ const filteredData = useMemo(() => {+ let rows = data.data;+ if (filterType !== 'all') {+ rows = rows.filter(r => r.security_type === filterType);+ }+ if (searchCusip.trim()) {+ rows = rows.filter(r => r.cusip.toLowerCase().includes(searchCusip.toLowerCase()));+ }+ rows = [...rows].sort((a, b) => {+ const aVal = a[sortField];+ const bVal = b[sortField];+ if (aVal === null || aVal === undefined) return 1;+ if (bVal === null || bVal === undefined) return -1;+ if (typeof aVal === 'number' && typeof bVal === 'number') {+ return sortDir === 'asc' ? aVal - bVal : bVal - aVal;+ }+ return sortDir === 'asc'+ ? String(aVal).localeCompare(String(bVal))+ : String(bVal).localeCompare(String(aVal));+ });+ return rows;+ }, [data.data, filterType, searchCusip, sortField, sortDir]);++ const handleSort = (field: SortField) => {+ if (sortField === field) {+ setSortDir(d => d === 'asc' ? 'desc' : 'asc');+ } else {+ setSortField(field);+ setSortDir('asc');+ }+ };++ const sortIndicator = (field: SortField) => {+ if (sortField !== field) return '';+ return sortDir === 'asc' ? ' \u25B2' : ' \u25BC';+ };++ // Summary stats+ const stats = useMemo(() => {+ const prices = filteredData.map(d => d.eod_price).filter((v): v is number => v !== null && v !== 0);+ const rates = filteredData.map(d => d.rate).filter((v): v is number => v !== null && v !== 0);+ return {+ count: filteredData.length,+ avgPrice: prices.length > 0 ? prices.reduce((a, b) => a + b, 0) / prices.length : 0,+ minPrice: prices.length > 0 ? Math.min(...prices) : 0,+ maxPrice: prices.length > 0 ? Math.max(...prices) : 0,+ avgRate: rates.length > 0 ? rates.reduce((a, b) => a + b, 0) / rates.length : 0,+ };+ }, [filteredData]);++ // Chart data: security type breakdown+ const typeBreakdown = useMemo(() => {+ const counts: Record<string, { count: number; avgPrice: number; avgRate: number }> = {};+ filteredData.forEach(r => {+ if (!counts[r.security_type]) counts[r.security_type] = { count: 0, avgPrice: 0, avgRate: 0 };+ counts[r.security_type].count++;+ if (r.eod_price) counts[r.security_type].avgPrice += r.eod_price;+ if (r.rate) counts[r.security_type].avgRate += r.rate;+ });+ return Object.entries(counts).map(([type, v]) => ({+ type,+ count: v.count,+ avgPrice: v.count > 0 ? +(v.avgPrice / v.count).toFixed(2) : 0,+ avgRate: v.count > 0 ? +((v.avgRate / v.count) * 100).toFixed(3) : 0,+ fill: TYPE_COLORS[type] || FINCEPT.GRAY,+ })).sort((a, b) => b.count - a.count);+ }, [filteredData]);++ // Scatter data: EOD price vs maturity+ const scatterData = useMemo(() => {+ return filteredData+ .filter(r => r.eod_price && r.maturity_date)+ .map(r => ({+ maturity: r.maturity_date!,+ maturityTs: new Date(r.maturity_date!).getTime(),+ eodPrice: r.eod_price!,+ cusip: r.cusip,+ type: r.security_type,+ fill: TYPE_COLORS[r.security_type] || FINCEPT.GRAY,+ }));+ }, [filteredData]);++ const thStyle: React.CSSProperties = {+ padding: '8px 10px',+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ textAlign: 'left',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ cursor: 'pointer',+ userSelect: 'none',+ whiteSpace: 'nowrap',+ };++ const tdStyle: React.CSSProperties = {+ padding: '6px 10px',+ fontSize: '11px',+ color: FINCEPT.WHITE,+ borderBottom: `1px solid ${FINCEPT.BORDER}08`,+ whiteSpace: 'nowrap',+ };++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Filter bar */}+ <div style={{+ padding: '10px 16px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ flexWrap: 'wrap',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, fontWeight: 700 }}>TYPE:</span>+ <select+ value={filterType}+ onChange={e => setFilterType(e.target.value)}+ style={{+ padding: '4px 8px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ outline: 'none',+ }}+ >+ <option value="all">All ({data.total_records})</option>+ {securityTypes.map(t => (+ <option key={t} value={t}>{t} ({data.data.filter(d => d.security_type === t).length})</option>+ ))}+ </select>+ </div>++ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, fontWeight: 700 }}>CUSIP:</span>+ <input+ type="text"+ value={searchCusip}+ onChange={e => setSearchCusip(e.target.value)}+ placeholder="Search..."+ style={{+ padding: '4px 8px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ outline: 'none',+ width: '120px',+ }}+ />+ </div>++ {/* View toggle + Stats */}+ <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: '12px', fontSize: '10px' }}>+ <span><span style={{ color: FINCEPT.GRAY }}>SHOWING:</span> <span style={{ color: FINCEPT.WHITE }}>{filteredData.length}</span></span>+ <span><span style={{ color: FINCEPT.GRAY }}>AVG PRICE:</span> <span style={{ color: '#3B82F6' }}>{stats.avgPrice.toFixed(2)}</span></span>+ <span><span style={{ color: FINCEPT.GRAY }}>RANGE:</span> <span style={{ color: FINCEPT.WHITE }}>{stats.minPrice.toFixed(2)} - {stats.maxPrice.toFixed(2)}</span></span>+ <span><span style={{ color: FINCEPT.GRAY }}>AVG RATE:</span> <span style={{ color: FINCEPT.YELLOW }}>{(stats.avgRate * 100).toFixed(3)}%</span></span>+ <div style={{ width: '1px', height: '16px', backgroundColor: FINCEPT.BORDER }} />+ <div style={{ display: 'flex', gap: '2px' }}>+ <button+ onClick={() => setViewMode('table')}+ style={{+ padding: '3px 6px', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px',+ backgroundColor: viewMode === 'table' ? '#3B82F6' : 'transparent',+ color: viewMode === 'table' ? FINCEPT.WHITE : FINCEPT.GRAY,+ cursor: 'pointer', display: 'flex', alignItems: 'center',+ }}+ >+ <Table2 size={12} />+ </button>+ <button+ onClick={() => setViewMode('chart')}+ style={{+ padding: '3px 6px', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px',+ backgroundColor: viewMode === 'chart' ? '#3B82F6' : 'transparent',+ color: viewMode === 'chart' ? FINCEPT.WHITE : FINCEPT.GRAY,+ cursor: 'pointer', display: 'flex', alignItems: 'center',+ }}+ >+ <BarChart3 size={12} />+ </button>+ </div>+ </div>+ </div>++ {viewMode === 'chart' ? (+ /* Chart View */+ <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>+ {/* Security Type Distribution */}+ <div style={{+ marginBottom: '20px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ padding: '16px',+ }}>+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE, marginBottom: '12px' }}>+ Securities by Type — Count & Avg Price+ </div>+ <ResponsiveContainer width="100%" height={220}>+ <BarChart data={typeBreakdown} margin={{ top: 5, right: 30, left: 0, bottom: 5 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={FINCEPT.BORDER} />+ <XAxis dataKey="type" tick={{ fill: FINCEPT.GRAY, fontSize: 9 }} interval={0} angle={-15} textAnchor="end" height={50} />+ <YAxis yAxisId="left" tick={{ fill: FINCEPT.GRAY, fontSize: 9 }} />+ <YAxis yAxisId="right" orientation="right" tick={{ fill: FINCEPT.GRAY, fontSize: 9 }} />+ <Tooltip contentStyle={tooltipStyle} labelStyle={{ color: FINCEPT.WHITE }} />+ <Legend wrapperStyle={{ fontSize: '9px', color: FINCEPT.GRAY }} />+ <Bar yAxisId="left" dataKey="count" name="Count" radius={[2, 2, 0, 0]}>+ {typeBreakdown.map((entry, i) => (+ <Cell key={i} fill={entry.fill} />+ ))}+ </Bar>+ <Bar yAxisId="right" dataKey="avgPrice" name="Avg Price" fill="#10B981" opacity={0.6} radius={[2, 2, 0, 0]} />+ </BarChart>+ </ResponsiveContainer>+ </div>++ {/* Price Distribution Scatter */}+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ padding: '16px',+ }}>+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE, marginBottom: '12px' }}>+ EOD Price by Maturity Date+ </div>+ <ResponsiveContainer width="100%" height={280}>+ <ScatterChart margin={{ top: 5, right: 30, left: 0, bottom: 5 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={FINCEPT.BORDER} />+ <XAxis+ dataKey="maturityTs"+ type="number"+ domain={['dataMin', 'dataMax']}+ tick={{ fill: FINCEPT.GRAY, fontSize: 9 }}+ tickFormatter={(v) => new Date(v).toLocaleDateString('en-US', { year: '2-digit', month: 'short' })}+ name="Maturity"+ />+ <YAxis dataKey="eodPrice" tick={{ fill: FINCEPT.GRAY, fontSize: 9 }} name="EOD Price" />+ <Tooltip+ contentStyle={tooltipStyle}+ labelStyle={{ color: FINCEPT.WHITE }}+ formatter={(value: any, name: string) => {+ if (name === 'EOD Price') return [Number(value).toFixed(4), name];+ return [value, name];+ }}+ labelFormatter={(v) => `Maturity: ${new Date(v).toLocaleDateString()}`}+ />+ <Scatter data={scatterData} name="Securities">+ {scatterData.map((entry, i) => (+ <Cell key={i} fill={entry.fill} opacity={0.7} />+ ))}+ </Scatter>+ </ScatterChart>+ </ResponsiveContainer>+ {/* Legend */}+ <div style={{ display: 'flex', gap: '12px', marginTop: '8px', flexWrap: 'wrap' }}>+ {Object.entries(TYPE_COLORS).map(([type, color]) => (+ <div key={type} style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>+ <span style={{ width: '8px', height: '8px', borderRadius: '50%', backgroundColor: color, display: 'inline-block' }} />+ {type}+ </div>+ ))}+ </div>+ </div>+ </div>+ ) : (+ /* Table View */+ <div style={{ flex: 1, overflow: 'auto' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: '"IBM Plex Mono", monospace' }}>+ <thead style={{ position: 'sticky', top: 0, backgroundColor: FINCEPT.HEADER_BG, zIndex: 1 }}>+ <tr>+ <th style={thStyle} onClick={() => handleSort('cusip')}>CUSIP{sortIndicator('cusip')}</th>+ <th style={thStyle} onClick={() => handleSort('security_type')}>TYPE{sortIndicator('security_type')}</th>+ <th style={thStyle} onClick={() => handleSort('rate')}>RATE{sortIndicator('rate')}</th>+ <th style={thStyle} onClick={() => handleSort('maturity_date')}>MATURITY{sortIndicator('maturity_date')}</th>+ <th style={thStyle} onClick={() => handleSort('bid')}>BID{sortIndicator('bid')}</th>+ <th style={thStyle} onClick={() => handleSort('offer')}>OFFER{sortIndicator('offer')}</th>+ <th style={thStyle} onClick={() => handleSort('eod_price')}>EOD PRICE{sortIndicator('eod_price')}</th>+ <th style={thStyle}>SPREAD</th>+ </tr>+ </thead>+ <tbody>+ {filteredData.map((row, i) => {+ const spread = row.bid && row.offer ? (row.offer - row.bid) : null;+ return (+ <tr+ key={`${row.cusip}-${i}`}+ style={{ backgroundColor: i % 2 === 0 ? 'transparent' : `${FINCEPT.PANEL_BG}80` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = i % 2 === 0 ? 'transparent' : `${FINCEPT.PANEL_BG}80`)}+ >+ <td style={{ ...tdStyle, color: '#3B82F6', fontWeight: 600 }}>{row.cusip}</td>+ <td style={{ ...tdStyle, fontSize: '9px' }}>{row.security_type}</td>+ <td style={{ ...tdStyle, color: FINCEPT.YELLOW }}>{formatRate(row.rate)}</td>+ <td style={tdStyle}>{formatDate(row.maturity_date)}</td>+ <td style={tdStyle}>{formatPrice(row.bid)}</td>+ <td style={tdStyle}>{formatPrice(row.offer)}</td>+ <td style={{ ...tdStyle, fontWeight: 600, color: FINCEPT.GREEN }}>{formatPrice(row.eod_price)}</td>+ <td style={{ ...tdStyle, color: spread !== null && spread > 0 ? FINCEPT.ORANGE : FINCEPT.GRAY }}>+ {spread !== null ? spread.toFixed(6) : '-'}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ )}+ </div>+ );+}++export default USTreasuryPricesPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasuryProvider.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasuryProvider.tsxnew file mode 100644index 000000000..7c397203b--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasuryProvider.tsx@@ -0,0 +1,291 @@+// USTreasuryProvider - Full US Treasury data interface+// Uses shared DateRangePicker from common/charts (same pattern as Economics tab)++import React from 'react';+import { RefreshCw, AlertCircle, Database, Download } from 'lucide-react';+import { DateRangePicker } from '@/components/common/charts';+import { FINCEPT, SECURITY_TYPES, AUCTION_SECURITY_TYPES } from '../constants';+import { useUSTreasuryData } from '../hooks';+import { USTreasuryPricesPanel } from './USTreasuryPricesPanel';+import { USTreasuryAuctionsPanel } from './USTreasuryAuctionsPanel';+import { USTreasurySummaryPanel } from './USTreasurySummaryPanel';+import type { USTreasuryEndpoint, SecurityTypeFilter } from '../types';++const ENDPOINTS: { id: USTreasuryEndpoint; label: string }[] = [+ { id: 'treasury_prices', label: 'PRICES' },+ { id: 'treasury_auctions', label: 'AUCTIONS' },+ { id: 'summary', label: 'SUMMARY' },+];++const PROVIDER_COLOR = '#3B82F6';++export function USTreasuryProvider() {+ const {+ activeEndpoint, setActiveEndpoint,+ dateRangePreset, setDateRangePreset,+ startDate, endDate, setStartDate, setEndDate,+ pricesData, pricesSecurityType, setPricesSecurityType,+ pricesCusip, setPricesCusip, fetchPrices,+ auctionsData,+ auctionsSecurityType, setAuctionsSecurityType, auctionsPageSize, setAuctionsPageSize,+ auctionsPageNum, setAuctionsPageNum, fetchAuctions,+ summaryData, fetchSummary,+ exportCSV,+ loading, error,+ } = useUSTreasuryData();++ const handleFetch = () => {+ switch (activeEndpoint) {+ case 'treasury_prices': fetchPrices(); break;+ case 'treasury_auctions': fetchAuctions(); break;+ case 'summary': fetchSummary(); break;+ }+ };++ const handlePageChange = (page: number) => {+ if (page >= 1) {+ setAuctionsPageNum(page);+ setTimeout(() => fetchAuctions(), 50);+ }+ };++ const inputStyle: React.CSSProperties = {+ padding: '4px 8px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ outline: 'none',+ };++ const labelStyle: React.CSSProperties = {+ fontSize: '9px',+ color: FINCEPT.GRAY,+ fontWeight: 700,+ };++ const hasData = activeEndpoint === 'treasury_prices' ? pricesData+ : activeEndpoint === 'treasury_auctions' ? auctionsData+ : summaryData;++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Endpoint tabs */}+ <div style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ flexWrap: 'wrap',+ }}>+ {/* Endpoint selector */}+ <div style={{ display: 'flex', gap: '2px', marginRight: '12px' }}>+ {ENDPOINTS.map(ep => (+ <button+ key={ep.id}+ onClick={() => setActiveEndpoint(ep.id)}+ style={{+ padding: '5px 12px',+ backgroundColor: activeEndpoint === ep.id ? PROVIDER_COLOR : 'transparent',+ color: activeEndpoint === ep.id ? FINCEPT.WHITE : FINCEPT.GRAY,+ border: `1px solid ${activeEndpoint === ep.id ? PROVIDER_COLOR : FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ }}+ >+ {ep.label}+ </button>+ ))}+ </div>++ {/* Shared DateRangePicker — same component used by Economics tab */}+ <DateRangePicker+ dateRangePreset={dateRangePreset}+ setDateRangePreset={setDateRangePreset}+ startDate={startDate}+ endDate={endDate}+ setStartDate={setStartDate}+ setEndDate={setEndDate}+ sourceColor={PROVIDER_COLOR}+ />++ <div style={{ width: '1px', height: '20px', backgroundColor: FINCEPT.BORDER }} />++ {/* Endpoint-specific filters */}+ {activeEndpoint === 'treasury_prices' && (+ <>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={labelStyle}>TYPE:</span>+ <select+ value={pricesSecurityType}+ onChange={e => setPricesSecurityType(e.target.value as SecurityTypeFilter)}+ style={inputStyle}+ >+ {SECURITY_TYPES.map(t => (+ <option key={t.value} value={t.value}>{t.label}</option>+ ))}+ </select>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={labelStyle}>CUSIP:</span>+ <input+ type="text"+ value={pricesCusip}+ onChange={e => setPricesCusip(e.target.value)}+ placeholder="Filter..."+ style={{ ...inputStyle, width: '100px' }}+ />+ </div>+ </>+ )}++ {activeEndpoint === 'treasury_auctions' && (+ <>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={labelStyle}>TYPE:</span>+ <select+ value={auctionsSecurityType}+ onChange={e => setAuctionsSecurityType(e.target.value)}+ style={inputStyle}+ >+ {AUCTION_SECURITY_TYPES.map(t => (+ <option key={t.value} value={t.value}>{t.label}</option>+ ))}+ </select>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={labelStyle}>PER PAGE:</span>+ <select+ value={auctionsPageSize}+ onChange={e => { setAuctionsPageSize(Number(e.target.value)); setAuctionsPageNum(1); }}+ style={inputStyle}+ >+ {[10, 25, 50, 100].map(n => (+ <option key={n} value={n}>{n}</option>+ ))}+ </select>+ </div>+ </>+ )}++ {/* Actions: Fetch + Export */}+ <div style={{ marginLeft: 'auto', display: 'flex', gap: '4px' }}>+ {hasData && (+ <button+ onClick={exportCSV}+ title="Export CSV"+ style={{+ padding: '5px 10px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <Download size={11} />+ CSV+ </button>+ )}+ <button+ onClick={handleFetch}+ disabled={loading}+ style={{+ padding: '5px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: loading ? 0.7 : 1,+ }}+ >+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />+ FETCH+ </button>+ </div>+ </div>++ {/* Content area */}+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>+ {loading ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <RefreshCw size={32} className="animate-spin" style={{ color: PROVIDER_COLOR, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>Loading US Treasury data...</div>+ </div>+ ) : error ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <AlertCircle size={32} style={{ color: FINCEPT.RED, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.RED, marginBottom: '8px' }}>Error loading data</div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '400px' }}>{error}</div>+ <button+ onClick={handleFetch}+ style={{+ marginTop: '16px',+ padding: '8px 16px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: 'pointer',+ }}+ >+ TRY AGAIN+ </button>+ </div>+ ) : hasData ? (+ <>+ {activeEndpoint === 'treasury_prices' && pricesData && (+ <USTreasuryPricesPanel data={pricesData} />+ )}+ {activeEndpoint === 'treasury_auctions' && auctionsData && (+ <USTreasuryAuctionsPanel+ data={auctionsData}+ pageNum={auctionsPageNum}+ pageSize={auctionsPageSize}+ onPageChange={handlePageChange}+ />+ )}+ {activeEndpoint === 'summary' && summaryData && (+ <USTreasurySummaryPanel data={summaryData} />+ )}+ </>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <Database size={48} style={{ color: FINCEPT.MUTED, marginBottom: '16px', opacity: 0.5 }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE, marginBottom: '8px' }}>+ Select an endpoint and click FETCH+ </div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '400px' }}>+ {activeEndpoint === 'treasury_prices'+ ? 'Get end-of-day prices for all Treasury securities including Bills, Notes, Bonds, TIPS, and FRN.'+ : activeEndpoint === 'treasury_auctions'+ ? 'Browse Treasury auction results with bid-to-cover ratios, accepted amounts, and pricing details.'+ : 'View aggregate market statistics including security counts, yield and price distributions.'+ }+ </div>+ </div>+ )}+ </div>+ </div>+ );+}++export default USTreasuryProvider;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasurySummaryPanel.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasurySummaryPanel.tsxnew file mode 100644index 000000000..eff6291c9--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/USTreasurySummaryPanel.tsx@@ -0,0 +1,165 @@+// US Treasury Summary Panel - Aggregate market statistics with visual breakdown++import React, { useMemo } from 'react';+import { FINCEPT } from '../constants';+import type { TreasurySummaryResponse } from '../types';++interface Props {+ data: TreasurySummaryResponse;+}++const SECURITY_COLORS: Record<string, string> = {+ 'MARKET BASED BILL': '#3B82F6',+ 'MARKET BASED NOTE': '#10B981',+ 'MARKET BASED BOND': '#F59E0B',+ 'TIPS': '#8B5CF6',+ 'MARKET BASED FRN': '#EC4899',+};++const formatPrice = (val: number): string => val.toFixed(2);+const formatRate = (val: number): string => `${(val * 100).toFixed(3)}%`;++export function USTreasurySummaryPanel({ data }: Props) {+ const securityEntries = useMemo(() => {+ return Object.entries(data.security_types).sort((a, b) => b[1] - a[1]);+ }, [data.security_types]);++ const maxCount = useMemo(() => {+ return Math.max(...securityEntries.map(([, v]) => v));+ }, [securityEntries]);++ const cardStyle: React.CSSProperties = {+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ padding: '16px',+ };++ const labelStyle: React.CSSProperties = {+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ textTransform: 'uppercase' as const,+ letterSpacing: '0.5px',+ };++ const valueStyle: React.CSSProperties = {+ fontSize: '24px',+ fontWeight: 700,+ color: FINCEPT.WHITE,+ marginTop: '4px',+ };++ return (+ <div style={{ padding: '20px', overflow: 'auto', height: '100%' }}>+ {/* Header */}+ <div style={{ marginBottom: '20px' }}>+ <div style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.WHITE }}>+ Treasury Market Summary+ </div>+ <div style={{ fontSize: '11px', color: FINCEPT.GRAY, marginTop: '4px' }}>+ Date: <span style={{ color: '#3B82F6' }}>{data.date}</span> • Total Securities: <span style={{ color: FINCEPT.WHITE }}>{data.total_securities}</span>+ </div>+ </div>++ {/* Top stats row */}+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '20px' }}>+ <div style={cardStyle}>+ <div style={labelStyle}>Total Securities</div>+ <div style={valueStyle}>{data.total_securities}</div>+ </div>+ <div style={cardStyle}>+ <div style={labelStyle}>Avg Rate</div>+ <div style={{ ...valueStyle, color: FINCEPT.YELLOW }}>{formatRate(data.yield_summary.avg_rate)}</div>+ </div>+ <div style={cardStyle}>+ <div style={labelStyle}>Avg Price</div>+ <div style={{ ...valueStyle, color: FINCEPT.GREEN }}>{formatPrice(data.price_summary.avg_price)}</div>+ </div>+ <div style={cardStyle}>+ <div style={labelStyle}>Price Range</div>+ <div style={{ ...valueStyle, fontSize: '18px' }}>+ <span style={{ color: FINCEPT.RED }}>{formatPrice(data.price_summary.min_price)}</span>+ <span style={{ color: FINCEPT.GRAY, fontSize: '14px' }}> - </span>+ <span style={{ color: FINCEPT.GREEN }}>{formatPrice(data.price_summary.max_price)}</span>+ </div>+ </div>+ </div>++ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>+ {/* Security Type Breakdown */}+ <div style={cardStyle}>+ <div style={{ ...labelStyle, marginBottom: '14px' }}>Security Type Breakdown</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>+ {securityEntries.map(([type, count]) => {+ const pct = (count / data.total_securities) * 100;+ const barWidth = (count / maxCount) * 100;+ const color = SECURITY_COLORS[type] || FINCEPT.GRAY;+ return (+ <div key={type}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>+ <span style={{ fontSize: '10px', color: FINCEPT.WHITE }}>{type}</span>+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>+ {count} <span style={{ color }}>({pct.toFixed(1)}%)</span>+ </span>+ </div>+ <div style={{+ width: '100%',+ height: '6px',+ backgroundColor: `${FINCEPT.BORDER}`,+ borderRadius: '3px',+ overflow: 'hidden',+ }}>+ <div style={{+ width: `${barWidth}%`,+ height: '100%',+ backgroundColor: color,+ borderRadius: '3px',+ transition: 'width 0.3s ease',+ }} />+ </div>+ </div>+ );+ })}+ </div>+ </div>++ {/* Yield & Price Details */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>+ {/* Yield Summary */}+ <div style={cardStyle}>+ <div style={{ ...labelStyle, marginBottom: '12px' }}>Yield Summary</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ <StatRow label="Min Rate" value={formatRate(data.yield_summary.min_rate)} color={FINCEPT.RED} />+ <StatRow label="Max Rate" value={formatRate(data.yield_summary.max_rate)} color={FINCEPT.GREEN} />+ <StatRow label="Avg Rate" value={formatRate(data.yield_summary.avg_rate)} color={FINCEPT.YELLOW} />+ <StatRow label="Securities w/ Rates" value={String(data.yield_summary.total_with_rates)} color={FINCEPT.WHITE} />+ </div>+ </div>++ {/* Price Summary */}+ <div style={cardStyle}>+ <div style={{ ...labelStyle, marginBottom: '12px' }}>Price Summary</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ <StatRow label="Min Price" value={formatPrice(data.price_summary.min_price)} color={FINCEPT.RED} />+ <StatRow label="Max Price" value={formatPrice(data.price_summary.max_price)} color={FINCEPT.GREEN} />+ <StatRow label="Avg Price" value={formatPrice(data.price_summary.avg_price)} color='#3B82F6' />+ <StatRow label="Securities w/ Prices" value={String(data.price_summary.total_with_prices)} color={FINCEPT.WHITE} />+ </div>+ </div>+ </div>+ </div>+ </div>+ );+}++function StatRow({ label, value, color }: { label: string; value: string; color: string }) {+ return (+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>{label}</span>+ <span style={{ fontSize: '12px', fontWeight: 600, color, fontFamily: '"IBM Plex Mono", monospace' }}>{value}</span>+ </div>+ );+}++export default USTreasurySummaryPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/UniversalCkanProvider.tsx b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/UniversalCkanProvider.tsxnew file mode 100644index 000000000..2c6744566--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/UniversalCkanProvider.tsx@@ -0,0 +1,554 @@+// UniversalCkanProvider - Multi-portal CKAN data browser+// Supports 8 CKAN portals: US, UK, AU, IT, BR, LV, SI, UY+// Portal selector + Organizations → Datasets → Resources + Search++import React, { useEffect, useCallback } from 'react';+import { RefreshCw, AlertCircle, Database, Download, Search, ChevronRight, ExternalLink, FileText, ArrowLeft, Globe } from 'lucide-react';+import { FINCEPT, CKAN_PORTALS } from '../constants';+import { useUniversalCkanData } from '../hooks/useUniversalCkanData';+import type { CkanView, CkanDataset, CkanResource } from '../types';++const VIEWS: { id: CkanView; label: string }[] = [+ { id: 'organizations', label: 'ORGANIZATIONS' },+ { id: 'datasets', label: 'DATASETS' },+ { id: 'search', label: 'SEARCH' },+];++const PROVIDER_COLOR = '#10B981';++const truncate = (text: string, max: number): string =>+ text.length > max ? text.substring(0, max) + '...' : text;++const formatDate = (dateStr: string | null | undefined): string => {+ if (!dateStr) return '-';+ return dateStr.substring(0, 10);+};++const formatSize = (bytes: number | null): string => {+ if (!bytes) return '-';+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+};++function parseTags(tags: any): string[] {+ if (!Array.isArray(tags)) return [];+ return tags.map((t: any) => (typeof t === 'string' ? t : t?.name || t?.display_name || '')).filter(Boolean);+}++export function UniversalCkanProvider() {+ const {+ activeView, setActiveView,+ activePortal, setActivePortal,+ organizations, selectedOrg, setSelectedOrg, fetchOrganizations,+ datasets, selectedDataset, setSelectedDataset, fetchDatasets, datasetsTotalCount,+ resources, fetchResources,+ searchQuery, setSearchQuery, searchResults, searchTotalCount, searchDatasets,+ exportCSV,+ loading, error,+ } = useUniversalCkanData();++ // Load organizations when portal changes+ useEffect(() => {+ fetchOrganizations();+ }, [fetchOrganizations]);++ const handlePortalChange = (code: string) => {+ setActivePortal(code);+ setActiveView('organizations');+ setSelectedOrg(null);+ setSelectedDataset(null);+ };++ const handleViewChange = (view: CkanView) => {+ setActiveView(view);+ };++ const handleOrgClick = (orgName: string) => {+ setSelectedOrg(orgName);+ setSelectedDataset(null);+ setActiveView('datasets');+ fetchDatasets(orgName);+ };++ const handleDatasetClick = (datasetId: string) => {+ setSelectedDataset(datasetId);+ setActiveView('resources');+ fetchResources(datasetId);+ };++ const handleBack = () => {+ if (activeView === 'resources') {+ setActiveView('datasets');+ setSelectedDataset(null);+ } else if (activeView === 'datasets') {+ setActiveView('organizations');+ setSelectedOrg(null);+ }+ };++ const handleSearchKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === 'Enter') searchDatasets();+ };++ const inputStyle: React.CSSProperties = {+ padding: '6px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '11px',+ outline: 'none',+ fontFamily: 'inherit',+ };++ const currentPortal = CKAN_PORTALS.find(p => p.code === activePortal) || CKAN_PORTALS[0];++ const hasData = (activeView === 'organizations' && organizations.length > 0)+ || (activeView === 'datasets' && datasets.length > 0)+ || (activeView === 'resources' && resources.length > 0)+ || (activeView === 'search' && searchResults.length > 0);++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Portal selector bar */}+ <div style={{+ padding: '6px 16px',+ backgroundColor: `${PROVIDER_COLOR}08`,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ flexWrap: 'wrap',+ }}>+ <Globe size={12} color={PROVIDER_COLOR} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginRight: '4px' }}>PORTAL:</span>+ {CKAN_PORTALS.map(portal => (+ <button+ key={portal.code}+ onClick={() => handlePortalChange(portal.code)}+ style={{+ padding: '3px 8px',+ backgroundColor: activePortal === portal.code ? PROVIDER_COLOR : 'transparent',+ color: activePortal === portal.code ? FINCEPT.WHITE : FINCEPT.GRAY,+ border: `1px solid ${activePortal === portal.code ? PROVIDER_COLOR : FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 600,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <span>{portal.flag}</span>+ <span>{portal.code.toUpperCase()}</span>+ </button>+ ))}+ </div>++ {/* Header bar */}+ <div style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ flexWrap: 'wrap',+ }}>+ {/* Back button */}+ {(activeView === 'datasets' || activeView === 'resources') && (+ <button+ onClick={handleBack}+ style={{+ padding: '5px 8px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <ArrowLeft size={11} />+ BACK+ </button>+ )}++ {/* View selector */}+ <div style={{ display: 'flex', gap: '2px', marginRight: '12px' }}>+ {VIEWS.map(v => (+ <button+ key={v.id}+ onClick={() => handleViewChange(v.id)}+ style={{+ padding: '5px 12px',+ backgroundColor: activeView === v.id ? PROVIDER_COLOR : 'transparent',+ color: activeView === v.id ? FINCEPT.WHITE : FINCEPT.GRAY,+ border: `1px solid ${activeView === v.id ? PROVIDER_COLOR : FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ }}+ >+ {v.label}+ </button>+ ))}+ </div>++ {/* Search input */}+ {activeView === 'search' && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flex: 1, maxWidth: '400px' }}>+ <Search size={14} color={FINCEPT.GRAY} />+ <input+ type="text"+ value={searchQuery}+ onChange={e => setSearchQuery(e.target.value)}+ onKeyDown={handleSearchKeyDown}+ placeholder={`Search ${currentPortal.name} datasets...`}+ style={{ ...inputStyle, flex: 1 }}+ />+ <button+ onClick={searchDatasets}+ disabled={loading || !searchQuery.trim()}+ style={{+ padding: '6px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading || !searchQuery.trim() ? 'not-allowed' : 'pointer',+ opacity: loading || !searchQuery.trim() ? 0.5 : 1,+ }}+ >+ SEARCH+ </button>+ </div>+ )}++ {/* Breadcrumb */}+ {activeView === 'datasets' && selectedOrg && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>{currentPortal.flag}</span>+ <span>Organizations</span>+ <ChevronRight size={10} />+ <span style={{ color: PROVIDER_COLOR }}>{selectedOrg}</span>+ <span style={{ color: FINCEPT.MUTED }}>({datasetsTotalCount} datasets)</span>+ </div>+ )}+ {activeView === 'resources' && selectedDataset && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>{currentPortal.flag}</span>+ <span>{selectedOrg || 'Org'}</span>+ <ChevronRight size={10} />+ <span style={{ color: PROVIDER_COLOR }}>{truncate(selectedDataset, 30)}</span>+ </div>+ )}++ {/* Actions */}+ <div style={{ marginLeft: 'auto', display: 'flex', gap: '4px' }}>+ {hasData && (+ <button+ onClick={exportCSV}+ title="Export CSV"+ style={{+ padding: '5px 10px',+ backgroundColor: 'transparent',+ color: FINCEPT.GRAY,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <Download size={11} />+ CSV+ </button>+ )}+ {activeView === 'organizations' && (+ <button+ onClick={fetchOrganizations}+ disabled={loading}+ style={{+ padding: '5px 14px',+ backgroundColor: PROVIDER_COLOR,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: loading ? 0.7 : 1,+ }}+ >+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />+ REFRESH+ </button>+ )}+ </div>+ </div>++ {/* Content area */}+ <div style={{ flex: 1, overflow: 'auto' }}>+ {loading ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <RefreshCw size={32} className="animate-spin" style={{ color: PROVIDER_COLOR, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>Loading {currentPortal.name} data...</div>+ </div>+ ) : error ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <AlertCircle size={32} style={{ color: FINCEPT.RED, marginBottom: '16px' }} />+ <div style={{ fontSize: '12px', color: FINCEPT.RED, marginBottom: '8px' }}>Error loading data</div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '400px' }}>{error}</div>+ </div>+ ) : activeView === 'organizations' ? (+ <OrganizationsTable organizations={organizations} onSelect={handleOrgClick} portalName={currentPortal.name} />+ ) : activeView === 'datasets' ? (+ <DatasetsTable datasets={datasets} onSelect={handleDatasetClick} totalCount={datasetsTotalCount} />+ ) : activeView === 'resources' ? (+ <ResourcesTable resources={resources} />+ ) : activeView === 'search' ? (+ searchResults.length > 0+ ? <DatasetsTable datasets={searchResults} onSelect={handleDatasetClick} totalCount={searchTotalCount} />+ : <EmptyState icon={Search} message={`Search ${currentPortal.name} datasets`} sub="Enter a query above and press SEARCH or Enter" />+ ) : (+ <EmptyState icon={Database} message="Select a view" sub="" />+ )}+ </div>+ </div>+ );+}++// ===== Sub-components =====++function EmptyState({ icon: Icon, message, sub }: { icon: React.ElementType; message: string; sub: string }) {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <Icon size={48} style={{ color: FINCEPT.MUTED, marginBottom: '16px', opacity: 0.5 }} />+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE, marginBottom: '8px' }}>{message}</div>+ {sub && <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>{sub}</div>}+ </div>+ );+}++function OrganizationsTable({ organizations, onSelect, portalName }: { organizations: { name: string; display_name: string }[]; onSelect: (name: string) => void; portalName: string }) {+ return (+ <div>+ <div style={summaryBarStyle}>{organizations.length} organizations on {portalName}</div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>ORGANIZATION ID</th>+ <th style={thStyle}>DISPLAY NAME</th>+ <th style={{ ...thStyle, width: '60px' }}></th>+ </tr>+ </thead>+ <tbody>+ {organizations.map(o => (+ <tr+ key={o.name}+ onClick={() => onSelect(o.name)}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={{ ...tdStyle, color: PROVIDER_COLOR, fontWeight: 600 }}>{o.name}</td>+ <td style={tdStyle}>{o.display_name}</td>+ <td style={tdStyle}>+ <ChevronRight size={14} color={FINCEPT.MUTED} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function DatasetsTable({ datasets, onSelect, totalCount }: { datasets: CkanDataset[]; onSelect: (id: string) => void; totalCount: number }) {+ return (+ <div>+ <div style={summaryBarStyle}>Showing {datasets.length} of {totalCount} datasets</div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>TITLE</th>+ <th style={{ ...thStyle, width: '140px' }}>ORGANIZATION</th>+ <th style={{ ...thStyle, width: '70px' }}>FILES</th>+ <th style={{ ...thStyle, width: '100px' }}>MODIFIED</th>+ <th style={{ ...thStyle, width: '180px' }}>TAGS</th>+ <th style={{ ...thStyle, width: '40px' }}></th>+ </tr>+ </thead>+ <tbody>+ {datasets.map(d => (+ <tr+ key={d.id || d.name}+ onClick={() => onSelect(d.name || d.id || '')}+ style={{ cursor: 'pointer', borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ onMouseEnter={e => (e.currentTarget.style.backgroundColor = FINCEPT.HOVER)}+ onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}+ >+ <td style={tdStyle}>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600, marginBottom: '2px' }}>+ {truncate(d.title || d.display_name || d.name || '', 80)}+ </div>+ {d.notes && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{truncate(d.notes, 100)}</div>+ )}+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{d.organization_name || '-'}</td>+ <td style={{ ...tdStyle, textAlign: 'center' }}>+ <span style={{ color: PROVIDER_COLOR, fontWeight: 600 }}>{d.num_resources || 0}</span>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(d.metadata_modified)}</td>+ <td style={tdStyle}>+ <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>+ {parseTags(d.tags).slice(0, 3).map((tag, i) => (+ <span key={i} style={{+ padding: '1px 6px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '8px',+ fontWeight: 600,+ }}>+ {truncate(tag, 20)}+ </span>+ ))}+ {parseTags(d.tags).length > 3 && (+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>+{parseTags(d.tags).length - 3}</span>+ )}+ </div>+ </td>+ <td style={tdStyle}>+ <ChevronRight size={14} color={FINCEPT.MUTED} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function ResourcesTable({ resources }: { resources: CkanResource[] }) {+ const handleOpenUrl = useCallback(async (url: string) => {+ try {+ const { openUrl } = await import('@tauri-apps/plugin-opener');+ await openUrl(url);+ } catch {+ window.open(url, '_blank');+ }+ }, []);++ return (+ <div>+ <div style={summaryBarStyle}>{resources.length} resource{resources.length !== 1 ? 's' : ''} available</div>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>+ <th style={thStyle}>NAME</th>+ <th style={{ ...thStyle, width: '80px' }}>FORMAT</th>+ <th style={{ ...thStyle, width: '90px' }}>SIZE</th>+ <th style={{ ...thStyle, width: '100px' }}>MODIFIED</th>+ <th style={{ ...thStyle, width: '60px' }}>LINK</th>+ </tr>+ </thead>+ <tbody>+ {resources.map(r => (+ <tr key={r.id} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <td style={tdStyle}>+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '6px' }}>+ <FileText size={14} color={FINCEPT.MUTED} style={{ marginTop: '2px', flexShrink: 0 }} />+ <div>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {r.name || r.id}+ </div>+ {r.description && (+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{truncate(r.description, 80)}</div>+ )}+ </div>+ </div>+ </td>+ <td style={tdStyle}>+ <span style={{+ padding: '2px 8px',+ backgroundColor: `${PROVIDER_COLOR}15`,+ color: PROVIDER_COLOR,+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ }}>+ {r.format || '?'}+ </span>+ </td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatSize(r.size)}</td>+ <td style={{ ...tdStyle, fontSize: '10px', color: FINCEPT.GRAY }}>{formatDate(r.last_modified)}</td>+ <td style={tdStyle}>+ {r.url && (+ <button+ onClick={() => handleOpenUrl(r.url)}+ style={{+ background: 'none',+ border: 'none',+ color: PROVIDER_COLOR,+ cursor: 'pointer',+ padding: '4px',+ display: 'flex',+ alignItems: 'center',+ }}+ title={r.url}+ >+ <ExternalLink size={14} />+ </button>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++// Shared styles+const thStyle: React.CSSProperties = {+ padding: '8px 12px',+ textAlign: 'left',+ fontSize: '9px',+ fontWeight: 700,+ color: PROVIDER_COLOR,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+};++const tdStyle: React.CSSProperties = {+ padding: '8px 12px',+ fontSize: '11px',+ color: FINCEPT.WHITE,+};++const summaryBarStyle: React.CSSProperties = {+ padding: '8px 16px',+ fontSize: '9px',+ color: FINCEPT.GRAY,+ backgroundColor: FINCEPT.PANEL_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+};++export default UniversalCkanProvider;diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/providers/index.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/index.tsnew file mode 100644index 000000000..02cfa7e3e--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/providers/index.ts@@ -0,0 +1,13 @@+// Government Data Provider Panels++export { USTreasuryPricesPanel } from './USTreasuryPricesPanel';+export { USTreasuryAuctionsPanel } from './USTreasuryAuctionsPanel';+export { USTreasurySummaryPanel } from './USTreasurySummaryPanel';+export { CanadaGovProvider } from './CanadaGovProvider';+export { CongressGovProvider } from './CongressGovProvider';+export { OpenAfricaProvider } from './OpenAfricaProvider';+export { SpainDataProvider } from './SpainDataProvider';+export { PxWebProvider } from './PxWebProvider';+export { SwissGovProvider } from './SwissGovProvider';+export { FrenchGovProvider } from './FrenchGovProvider';+export { UniversalCkanProvider } from './UniversalCkanProvider';diff --git a/fincept-terminal-desktop/src/components/tabs/gov-data/types.ts b/fincept-terminal-desktop/src/components/tabs/gov-data/types.tsnew file mode 100644index 000000000..4c0e48357--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/gov-data/types.ts@@ -0,0 +1,580 @@+// Government Data Tab Types++// ===== Provider Types =====++export type GovProvider = 'us-treasury' | 'canada-gov' | 'us-congress' | 'openafrica' | 'spain' | 'finland-pxweb' | 'swiss' | 'france' | 'universal-ckan';++export interface GovProviderConfig {+ id: GovProvider;+ name: string;+ fullName: string;+ description: string;+ color: string;+ country: string;+ flag: string;+ endpoints: GovEndpointConfig[];+}++export interface GovEndpointConfig {+ id: string;+ name: string;+ description: string;+ command: string;+}++// ===== US Treasury Types =====++export type USTreasuryEndpoint = 'treasury_prices' | 'treasury_auctions' | 'summary';++export type SecurityTypeFilter = 'all' | 'bill' | 'note' | 'bond' | 'tips' | 'frn' | 'cmb';++export interface TreasuryPriceRecord {+ cusip: string;+ security_type: string;+ rate: number | null;+ maturity_date: string | null;+ call_date: string | null;+ bid: number | null;+ offer: number | null;+ eod_price: number | null;+ date: string;+}++export interface TreasuryPricesResponse {+ success: boolean;+ endpoint: string;+ date: string;+ total_records: number;+ filters: {+ cusip: string | null;+ security_type: string | null;+ };+ data: TreasuryPriceRecord[];+ error?: string;+}++export interface TreasuryAuctionRecord {+ cusip: string;+ issueDate: string | null;+ securityType: string;+ securityTerm: string;+ maturityDate: string | null;+ interestRate: number | null;+ auctionDate: string | null;+ auctionDateYear: string;+ highDiscountRate: number | null;+ highInvestmentRate: number | null;+ highPrice: number | null;+ bidToCoverRatio: number | null;+ competitiveAccepted: number | null;+ competitiveTendered: number | null;+ totalAccepted: number | null;+ totalTendered: number | null;+ offeringAmount: number | null;+ allocationPercentage: number | null;+ directBidderAccepted: number | null;+ directBidderTendered: number | null;+ indirectBidderAccepted: number | null;+ indirectBidderTendered: number | null;+ primaryDealerAccepted: number | null;+ primaryDealerTendered: number | null;+ pricePer100: string | null;+ reopening: string | null;+ type: string;+ term: string;+ [key: string]: any; // Allow extra fields from API+}++export interface TreasuryAuctionsResponse {+ success: boolean;+ endpoint: string;+ page_num: number;+ page_size: number;+ total_records: number;+ filters: {+ start_date: string | null;+ end_date: string | null;+ security_type: string | null;+ };+ data: TreasuryAuctionRecord[];+ error?: string;+}++export interface TreasurySummaryResponse {+ success: boolean;+ endpoint: string;+ date: string;+ total_securities: number;+ security_types: Record<string, number>;+ yield_summary: {+ min_rate: number;+ max_rate: number;+ avg_rate: number;+ total_with_rates: number;+ };+ price_summary: {+ min_price: number;+ max_price: number;+ avg_price: number;+ total_with_prices: number;+ };+ error?: string;+}++// ===== Canada Gov Types =====++export type CanadaGovView = 'publishers' | 'datasets' | 'resources' | 'search' | 'recent';++export interface CanadaPublisher {+ id: string;+ name: string;+ display_name: string;+ dataset_count?: number;+}++export interface CanadaDataset {+ id: string;+ name: string;+ title: string;+ notes: string;+ publisher_id?: string;+ organization?: string | null;+ metadata_created: string | null;+ metadata_modified: string | null;+ state?: string;+ num_resources: number;+ tags: string[];+}++export interface CanadaResource {+ id: string;+ name: string;+ description: string;+ format: string;+ url: string;+ size: number | null;+ mimetype: string | null;+ created: string | null;+ last_modified: string | null;+ resource_type: string | null;+ package_id: string;+ position: number | null;+}++export interface CanadaGovResponse<T> {+ data: T;+ metadata: Record<string, any>;+ error: string | null;+}++// ===== Congress.gov Types =====++export type CongressGovView = 'bills' | 'bill-detail' | 'summary';++export interface CongressBill {+ congress: number;+ bill_type: string;+ bill_number: number;+ bill_url: string;+ title: string;+ origin_chamber: string;+ origin_chamber_code: string;+ update_date: string;+ update_date_including_text: string;+ latest_action_date: string | null;+ latest_action: string | null;+}++export interface CongressBillsResponse {+ success: boolean;+ endpoint: string;+ congress: number;+ filters: {+ bill_type: string | null;+ start_date: string | null;+ end_date: string | null;+ limit: number;+ offset: number;+ sort_by: string;+ get_all: boolean;+ };+ total_bills: number;+ pagination: { count?: number; next?: string };+ bills: CongressBill[];+ error?: string;+}++export interface CongressBillDetail {+ success: boolean;+ endpoint: string;+ bill_url: string;+ bill_data: Record<string, any>;+ markdown_content: string;+ error?: string;+}++export interface CongressBillSummary {+ success: boolean;+ endpoint: string;+ congress: number;+ total_bills: number;+ bill_types: Record<string, { count: number; latest_bills?: CongressBill[]; error?: string }>;+ error?: string;+}++// ===== openAFRICA Types =====++export type OpenAfricaView = 'organizations' | 'datasets' | 'resources' | 'search' | 'recent';++export interface OpenAfricaOrganization {+ id: string;+ name: string;+ title: string;+ description: string;+ image_url: string;+ created: string;+ dataset_count: number;+ state: string;+ display_name: string;+}++export interface OpenAfricaDataset {+ id: string;+ name: string;+ title: string;+ notes: string;+ organization: Record<string, any>;+ author: string;+ license: string;+ created: string;+ modified: string;+ tags: string[];+ resource_count: number;+}++export interface OpenAfricaResource {+ id: string;+ name: string;+ description: string;+ url: string;+ format: string;+ size: string | number | null;+ created: string;+ last_modified: string;+ package_id: string;+ position: number;+}++export interface OpenAfricaResponse<T> {+ data: T;+ metadata: Record<string, any>;+ error: string | null;+}++// ===== Spain Open Data Types =====++export type SpainDataView = 'catalogues' | 'datasets' | 'resources' | 'search';++export interface SpainCatalogue {+ uri: string;+ extracted_id: string;+}++export interface SpainDataset {+ uri?: string;+ extracted_id?: string;+ title: string | Array<{ _lang: string; _value: string }>;+ description?: string | Array<{ _lang: string; _value: string }>;+ title_translation?: { original: string; translated: string };+ description_translation?: { original: string; translated: string };+ distribution?: SpainResource[];+ publisher?: any;+ modified?: string;+ issued?: string;+ theme?: string[];+ keyword?: string[];+ [key: string]: any;+}++export interface SpainResource {+ accessURL?: string;+ format?: string | { label: string };+ title?: string | Array<{ _lang: string; _value: string }>;+ title_translation?: { original: string; translated: string };+ description?: string;+ byteSize?: number;+ resource_index?: number;+ download_available?: boolean;+ [key: string]: any;+}++export interface SpainDataResponse<T> {+ data: T;+ metadata: Record<string, any>;+ error: string | null;+}++// ===== PxWeb (Statistics Finland) Types =====++export type PxWebView = 'browse' | 'metadata' | 'data';++/** A node in the PxWeb database tree — either a folder (type "l") or table (type "t") */+export interface PxWebNode {+ dbid: string;+ id: string;+ type: 'l' | 't'; // l = level/folder, t = table+ text: string;+ description?: string;+ updated?: string;+}++/** Variable/dimension returned by table metadata */+export interface PxWebVariable {+ code: string;+ text: string;+ values: string[];+ valueTexts: string[];+ elimination?: boolean;+ time?: boolean;+}++/** json-stat2 data response */+export interface PxWebStatData {+ class?: string;+ label?: string;+ source?: string;+ updated?: string;+ id?: string[];+ size?: number[];+ dimension?: Record<string, { label: string; category: { index: Record<string, number>; label: Record<string, string> } }>;+ value?: (number | null)[];+}++export interface PxWebResponse {+ success: boolean;+ total_available?: number;+ total_fetched?: number;+ data: any;+ cap_reached?: boolean;+ timestamp?: number;+ error?: string;+}++// ===== Swiss Government (opendata.swiss) Types =====++export type SwissGovView = 'publishers' | 'datasets' | 'resources' | 'search' | 'recent';++export interface SwissPublisher {+ id: string;+ name: string;+ original_name: string;+ display_name: string;+}++export interface SwissDataset {+ id: string;+ name: string;+ title: string;+ original_title: string;+ notes: string;+ original_notes: string;+ publisher_id?: string;+ organization?: string | null;+ metadata_created: string | null;+ metadata_modified: string | null;+ state?: string;+ num_resources: number;+ tags: string[];+ language_detected?: { title: string; notes: string };+}++export interface SwissResource {+ id: string;+ name: string;+ original_name: string;+ description: string;+ original_description: string;+ format: string;+ url: string;+ size: number | null;+ mimetype: string | null;+ created: string | null;+ last_modified: string | null;+ resource_type: string | null;+ package_id: string;+ position: number | null;+ language_detected?: { name: string; description: string };+}++export interface SwissGovResponse<T> {+ data: T;+ metadata: Record<string, any>;+ error: string | null;+}++// ===== French Government (data.gouv.fr) Types =====++export type FrenchGovView = 'geo' | 'datasets' | 'tabular' | 'company';++export interface FrenchMunicipality {+ code: string;+ name: string;+ original_name: string;+ postal_codes: string[];+ department_code: string | null;+ region_code: string | null;+ population: number | null;+ area: number | null;+ center: any | null;+ search_score: number;+}++export interface FrenchDepartment {+ code: string;+ name: string;+ original_name: string;+ region_code: string | null;+ search_score: number;+}++export interface FrenchRegion {+ code: string;+ name: string;+ original_name: string;+ search_score: number;+}++export interface FrenchDataset {+ id: string;+ title: string;+ original_title: string;+ description: string;+ original_description: string;+ url: string | null;+ owner: string | null;+ organization: string | null;+ created_at: string | null;+ last_modified: string | null;+ tags: string[];+ frequency: string | null;+ license: string | null;+ resources_count: number;+}++export interface FrenchResourceProfile {+ resource_id: string;+ name: string;+ original_name: string;+ title: string;+ original_title: string;+ format: string | null;+ size: number | null;+ columns: FrenchResourceColumn[];+ total_rows: number | null;+ encoding: string | null;+ delimiter: string | null;+}++export interface FrenchResourceColumn {+ name: string;+ original_name: string;+ title: string;+ original_title: string;+ type: string | null;+ format: string | null;+ description: string;+ original_description: string;+}++export interface FrenchResourceLines {+ resource_id: string;+ lines: Record<string, any>[];+ total_rows: number;+ page: number;+ page_size: number;+ has_more: boolean;+}++export interface FrenchCompany {+ siren: string | null;+ siret: string | null;+ complete_name: string;+ original_complete_name: string;+ company_name: string;+ original_company_name: string;+ company_category: string | null;+ creation_date: string | null;+ administrative_status: string | null;+ legal_form: string;+ original_legal_form: string;+ main_activity: string;+ original_main_activity: string;+ employee_size_range: string | null;+ address: any | null;+ matching_score: number | null;+}++export interface FrenchGovResponse<T> {+ data: T;+ metadata: Record<string, any>;+ error: string | null;+}++// ===== Universal CKAN Types =====++export type CkanView = 'organizations' | 'datasets' | 'resources' | 'search';++export type CkanPortalCode = 'us' | 'uk' | 'au' | 'it' | 'br' | 'lv' | 'si' | 'uy';++export interface CkanPortalInfo {+ code: CkanPortalCode;+ name: string;+ flag: string;+ url: string;+}++export interface CkanOrganization {+ name: string;+ display_name: string;+ country: string;+}++export interface CkanDataset {+ id?: string;+ name: string;+ display_name?: string;+ title?: string;+ notes?: string;+ organization_name?: string;+ organization?: Record<string, any>;+ num_resources?: number;+ metadata_created?: string;+ metadata_modified?: string;+ tags?: Array<{ name: string } | string>;+ resource_types?: string[];+ resources?: any[];+ country?: string;+ [key: string]: any;+}++export interface CkanResource {+ id: string;+ name: string;+ description: string;+ format: string;+ url: string;+ size: number | null;+ mimetype: string | null;+ created: string | null;+ last_modified: string | null;+ dataset_name?: string;+ dataset_title?: string;+ organization?: string;+ [key: string]: any;+}++export interface CkanResponse<T> {+ data: T;+ metadata: Record<string, any>;+ error: string | null;+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsxindex 4dda18745..02ed53d9c 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx@@ -64,6 +64,9 @@ export function ProChartWithToolkit({useEffect(() => {if (!chartContainerRef.current) return;+ // Reset isReady so the data effect re-triggers after chart re-initialization+ setIsReady(false);+const containerHeight = chartContainerRef.current.clientHeight || height;// Determine time visibility based on intervaldiff --git a/fincept-terminal-desktop/src/services/core/sqliteService.ts b/fincept-terminal-desktop/src/services/core/sqliteService.tsindex 344838770..4cdc44886 100644--- a/fincept-terminal-desktop/src/services/core/sqliteService.ts+++ b/fincept-terminal-desktop/src/services/core/sqliteService.ts@@ -37,6 +37,8 @@ export interface ApiKeys {DATABENTO_API_KEY?: string;WTO_API_KEY?: string;EIA_API_KEY?: string;+ BLS_API_KEY?: string;+ BEA_API_KEY?: string;[key: string]: string | undefined;}@@ -51,6 +53,8 @@ export const PREDEFINED_API_KEYS = [{ key: 'OPENROUTER_API_KEY', label: 'OpenRouter API Key', description: 'Access 400+ AI models from all providers (Model Library)' },{ key: 'WTO_API_KEY', label: 'WTO API Key', description: 'World Trade Organization - Trade statistics, restrictions & notifications' },{ key: 'EIA_API_KEY', label: 'EIA API Key', description: 'U.S. Energy Information Administration - Petroleum, natural gas & energy data' },+ { key: 'BLS_API_KEY', label: 'BLS API Key', description: 'Bureau of Labor Statistics - Employment, wages, CPI & productivity data' },+ { key: 'BEA_API_KEY', label: 'BEA API Key', description: 'Bureau of Economic Analysis - GDP, income, spending & national accounts (NIPA)' },] as const;// LLM Provider configurations