Skip to content

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

version v3.3 update

tilakpatel22979a6087a975
diff --git a/fincept-terminal-desktop/bun.lock b/fincept-terminal-desktop/bun.lock
index a67949e5b..bc020145a 100644
--- a/fincept-terminal-desktop/bun.lock
+++ b/fincept-terminal-desktop/bun.lock
@@ -82,6 +82,7 @@
"jsonata": "^2.1.0",
"jsonpath": "^1.1.1",
"jsonpath-plus": "^10.3.0",
+ "katex": "^0.16.28",
"langchain": "^0.3.34",
"libphonenumber-js": "^1.12.33",
"lightweight-charts": "^5.0.9",
@@ -122,6 +123,7 @@
"@types/d3": "^7.4.3",
"@types/jmespath": "^0.15.2",
"@types/jsonpath": "^0.2.4",
+ "@types/katex": "^0.16.8",
"@types/node": "^24.5.2",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
@@ -896,6 +898,8 @@
"@types/jsonpath": ["@types/[email protected]", "", {}, "sha512-K3hxB8Blw0qgW6ExKgMbXQv2UPZBoE2GqLpVY+yr7nMD2Pq86lsuIzyAaiQ7eMqFL5B6di6pxSkogLJEyEHoGA=="],
+ "@types/katex": ["@types/[email protected]", "", {}, "sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg=="],
+
"@types/mapbox__point-geometry": ["@types/[email protected]", "", {}, "sha512-mUWlSxAmYLfwnRBmgYV86tgYmMIICX4kza8YnE/eIlywGe2XoOxlpVnXWwir92xRLjwyarqwpu2EJKD2pk0IUA=="],
"@types/mapbox__vector-tile": ["@types/[email protected]", "", { "dependencies": { "@types/geojson": "*", "@types/mapbox__point-geometry": "*", "@types/pbf": "*" } }, "sha512-bpd8dRn9pr6xKvuEBQup8pwQfD4VUyqO/2deGjfpe6AwC8YRlyEipvefyRJUSiCJTZuCb8Pl1ciVV5ekqJ96Bg=="],
@@ -1854,6 +1858,8 @@
"jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],
+ "katex": ["[email protected]", "", { "dependencies": { "commander": "^8.3.0" }, "bin": { "katex": "cli.js" } }, "sha512-YHzO7721WbmAL6Ov1uzN/l5mY5WWWhJBSW+jq4tkfZfsxmo1hu6frS0EOswvjBUnWE6NtjEs48SFn5CQESRLZg=="],
+
"kdbush": ["[email protected]", "", {}, "sha512-WbCVYJ27Sz8zi9Q7Q0xHC+05iwkm3Znipc2XTlrnJbsHMYktW4hPhXUE8Ys1engBrvffoSCqbil1JQAa7clRpA=="],
"kind-of": ["[email protected]", "", {}, "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw=="],
@@ -2906,6 +2912,8 @@
"jsonwebtoken/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q=="],
+ "katex/commander": ["[email protected]", "", {}, "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww=="],
+
"langchain/@langchain/openai": ["@langchain/[email protected]", "", { "dependencies": { "js-tiktoken": "^1.0.12", "openai": "5.12.2", "zod": "^3.25.32" }, "peerDependencies": { "@langchain/core": ">=0.3.68 <0.4.0" } }, "sha512-v9INBOjE0w6ZrUE7kP9UkRyNsV7daH7aPeSOsPEJ35044UI3udPHwNduQ8VmaOUsD26OvSdg1b1GDhrqWLMaRw=="],
"langsmith/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q=="],
diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.json
index 623e59fb7..b30f6a400 100644
--- a/fincept-terminal-desktop/package.json
+++ b/fincept-terminal-desktop/package.json
@@ -12,12 +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",
- "sync-version": "bun scripts/sync-version.js",
"bump-version": "bun scripts/bump-version.js",
- "i18n:audit": "bun scripts/audit-translations.js",
"i18n:sync": "bun scripts/sync-translations.js",
- "i18n:translate": "bun scripts/translate-auto.js",
- "i18n:update": "bun scripts/sync-translations.js && bun scripts/translate-auto.js",
"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"
@@ -100,6 +96,7 @@
"jsonata": "^2.1.0",
"jsonpath": "^1.1.1",
"jsonpath-plus": "^10.3.0",
+ "katex": "^0.16.28",
"langchain": "^0.3.34",
"libphonenumber-js": "^1.12.33",
"lightweight-charts": "^5.0.9",
@@ -143,6 +140,7 @@
"@types/d3": "^7.4.3",
"@types/jmespath": "^0.15.2",
"@types/jsonpath": "^0.2.4",
+ "@types/katex": "^0.16.8",
"@types/node": "^24.5.2",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
diff --git a/fincept-terminal-desktop/public/locales/en/chat.json b/fincept-terminal-desktop/public/locales/en/chat.json
index aae49c696..cce5fe65e 100644
--- a/fincept-terminal-desktop/public/locales/en/chat.json
+++ b/fincept-terminal-desktop/public/locales/en/chat.json
@@ -11,16 +11,47 @@
},
"messages": {
"thinking": "Thinking...",
- "typing": "AI is typing..."
+ "typing": "AI is typing...",
+ "empty": "(Empty message)"
},
"history": {
"clearAll": "CLEAR ALL",
"sessions": "SESSIONS",
- "deleteAll": "Delete all sessions"
+ "deleteAll": "Delete all sessions",
+ "search": "Search sessions..."
},
"panel": {
"dataContexts": "DATA CONTEXTS",
"quickPrompts": "QUICK PROMPTS",
"systemInfo": "SYSTEM INFO"
+ },
+ "llm": {
+ "selectProvider": "SELECT LLM PROVIDER",
+ "noProvider": "NO PROVIDER",
+ "active": "ACTIVE",
+ "model": "Model",
+ "provider": "PROVIDER",
+ "temperature": "TEMP",
+ "maxTokens": "MAX TOKENS",
+ "streaming": "STREAMING",
+ "mcpTools": "MCP TOOLS",
+ "apiKey": "API KEY",
+ "systemPrompt": "SYSTEM PROMPT",
+ "configured": "CONFIGURED",
+ "notConfigured": "NOT CONFIGURED"
+ },
+ "status": {
+ "initializing": "STATUS: INITIALIZING...",
+ "ready": "STATUS: READY",
+ "loading": "STATUS: LOADING MESSAGES...",
+ "error": "ERROR",
+ "switching": "STATUS: SWITCHING LLM PROVIDER..."
+ },
+ "buttons": {
+ "edit": "Edit",
+ "save": "Save",
+ "cancel": "Cancel",
+ "reset": "Reset to Default",
+ "configure": "Configure MCP"
}
}
diff --git a/fincept-terminal-desktop/public/locales/en/codeEditor.json b/fincept-terminal-desktop/public/locales/en/codeEditor.json
index 32a35b63e..c2ae7f590 100644
--- a/fincept-terminal-desktop/public/locales/en/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/en/codeEditor.json
@@ -1,17 +1,24 @@
{
"title": "CODE EDITOR",
"header": {
- "packages": "PACKAGES"
+ "packages": "PACKAGES",
+ "finscriptIde": "FINSCRIPT IDE",
+ "version": "v1.0"
},
"toolbar": {
"newFile": "NEW FILE",
"new": "NEW",
"open": "OPEN",
"save": "SAVE",
- "run": "RUN CODE",
+ "run": "RUN",
"running": "RUNNING...",
"runAll": "RUN ALL",
- "history": "HISTORY"
+ "history": "HISTORY",
+ "toggleExplorer": "Toggle Explorer (Ctrl+B)",
+ "openFile": "Open File",
+ "saveShortcut": "Save (Ctrl+S)",
+ "findShortcut": "Find (Ctrl+F)",
+ "runShortcut": "Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
@@ -25,5 +32,55 @@
"title": "NOTEBOOK HISTORY",
"loading": "Loading history...",
"empty": "No notebook history yet"
+ },
+ "explorer": {
+ "title": "EXPLORER",
+ "openFiles": "OPEN FILES",
+ "examples": "EXAMPLES",
+ "runHistory": "RUN HISTORY",
+ "finscriptEngine": "FinScript Engine"
+ },
+ "output": {
+ "title": "OUTPUT",
+ "success": "SUCCESS",
+ "error": "ERROR",
+ "executing": "EXECUTING FINSCRIPT...",
+ "noOutput": "No output yet",
+ "pressToRun": "Press Ctrl+Enter to run",
+ "completed": "COMPLETED",
+ "failed": "FAILED",
+ "signals": "signals",
+ "clear": "CLEAR",
+ "errors": "ERRORS",
+ "signalsSection": "SIGNALS",
+ "outputSection": "OUTPUT",
+ "charts": "CHARTS"
+ },
+ "chart": {
+ "ohlc": "OHLC",
+ "histogram": "Histogram",
+ "line": "Line",
+ "points": "points"
+ },
+ "statusBar": {
+ "modified": "MODIFIED",
+ "showOutput": "SHOW OUTPUT",
+ "encoding": "UTF-8",
+ "spaces": "4 Spaces",
+ "runShortcut": "Ctrl+Enter: Run",
+ "lines": "lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "Close file without saving?",
+ "unsavedChanges": "You have unsaved changes."
+ },
+ "categories": {
+ "gettingStarted": "Getting Started",
+ "technicalAnalysis": "Technical Analysis",
+ "strategies": "Strategies",
+ "dataStructures": "Data Structures",
+ "visualization": "Visualization",
+ "automation": "Automation",
+ "advanced": "Advanced"
}
}
diff --git a/fincept-terminal-desktop/public/locales/en/common.json b/fincept-terminal-desktop/public/locales/en/common.json
index 43c8366d6..bc075c241 100644
--- a/fincept-terminal-desktop/public/locales/en/common.json
+++ b/fincept-terminal-desktop/public/locales/en/common.json
@@ -19,6 +19,9 @@
"yes": "Yes",
"no": "No",
"ok": "OK",
+ "or": "or",
+ "note": "Note",
+ "settings": "Settings",
"confirm": "Confirm",
"language": "Language",
"selectLanguage": "Select Language",
diff --git a/fincept-terminal-desktop/public/locales/en/geopolitics.json b/fincept-terminal-desktop/public/locales/en/geopolitics.json
index 72867242d..8330811d9 100644
--- a/fincept-terminal-desktop/public/locales/en/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/en/geopolitics.json
@@ -1,6 +1,74 @@
{
"title": "GEOPOLITICS",
+ "header": {
+ "prefix": "GEO>",
+ "title": "GEOPOLITICAL CONFLICT MONITOR",
+ "events": "EVENTS"
+ },
+ "status": {
+ "stale": "STALE",
+ "loading": "LOADING...",
+ "complete": "Complete",
+ "error": "ERROR:"
+ },
+ "filters": {
+ "country": "Country...",
+ "cities": "Cities...",
+ "citiesSelected": "{{count}} cities",
+ "category": "Category...",
+ "apply": "APPLY",
+ "clear": "CLEAR",
+ "clearAllCities": "Clear all cities",
+ "selectedLabel": "Selected:"
+ },
"messages": {
- "loading": "Loading geopolitical data..."
+ "loading": "Loading geopolitical data...",
+ "noEventsFilter": "No events found for: {{filters}}",
+ "noEventsGeneral": "No events found with valid coordinates. Try filtering by country (e.g., Ukraine, Syria, Israel)",
+ "retry": "RETRY",
+ "eventsCount": "{{count}} events"
+ },
+ "panel": {
+ "title": "INFO PANEL",
+ "expand": "Expand panel",
+ "collapse": "Collapse panel",
+ "eventsLoaded": "EVENTS LOADED",
+ "onMapVisualization": "on map visualization",
+ "topCategories": "TOP CATEGORIES",
+ "topCountries": "TOP COUNTRIES",
+ "eventDetails": "EVENT DETAILS",
+ "close": "CLOSE"
+ },
+ "eventDetails": {
+ "country": "Country:",
+ "city": "City:",
+ "keywords": "Keywords:",
+ "coords": "Coords:",
+ "date": "Date:",
+ "source": "Source:",
+ "viewArticle": "View Article"
+ },
+ "legend": {
+ "title": "EVENT CATEGORIES",
+ "armedConflict": "Armed Conflict",
+ "terrorism": "Terrorism",
+ "protests": "Protests",
+ "civilianViolence": "Civilian Violence",
+ "riots": "Riots",
+ "politicalViolence": "Political Violence",
+ "crisis": "Crisis",
+ "explosions": "Explosions",
+ "strategic": "Strategic",
+ "unclassified": "Unclassified"
+ },
+ "footer": {
+ "tabName": "GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "EVENTS",
+ "labelEngine": "ENGINE",
+ "engineValue": "DECK.GL v9.2",
+ "labelSource": "SOURCE",
+ "sourceValue": "NEWS-EVENTS API",
+ "labelSelected": "SELECTED",
+ "statusInfo": "REAL-TIME GLOBAL INTELLIGENCE | AUTO-REFRESH: 5MIN | {{time}}"
}
}
diff --git a/fincept-terminal-desktop/public/locales/en/news.json b/fincept-terminal-desktop/public/locales/en/news.json
index 78d133c61..c24013c85 100644
--- a/fincept-terminal-desktop/public/locales/en/news.json
+++ b/fincept-terminal-desktop/public/locales/en/news.json
@@ -19,7 +19,13 @@
},
"messages": {
"loadingFeeds": "Loading news feeds...",
- "breaking": "BREAKING"
+ "breaking": "BREAKING",
+ "loadingFeedsModal": "Loading feeds...",
+ "failedToLoad": "Failed to load RSS feeds",
+ "noCustomFeeds": "No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "All feeds have been deleted. Add a new feed or restore defaults.",
+ "allDefaultFeedsDeleted": "You have deleted all {{count}} default feeds. Click below to restore them.",
+ "defaultFeedsInfo": "Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
"feeds": {
"primary": "PRIMARY NEWS FEED",
@@ -28,5 +34,57 @@
},
"analytics": {
"title": "REAL-TIME NEWS ANALYTICS"
+ },
+ "rssSettings": {
+ "title": "RSS FEED SETTINGS",
+ "subtitle": "MANAGE YOUR NEWS SOURCES",
+ "close": "CLOSE",
+ "myFeeds": "MY FEEDS",
+ "defaultFeeds": "DEFAULT FEEDS",
+ "noFeedsAvailable": "NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "ADD NEW FEED",
+ "addNewRssFeed": "ADD NEW RSS FEED",
+ "editRssFeed": "EDIT RSS FEED",
+ "restoreDefaults": "RESTORE DEFAULTS",
+ "restoreAll": "RESTORE ALL",
+ "restoreAllDefaultFeeds": "RESTORE ALL DEFAULT FEEDS",
+ "displayName": "DISPLAY NAME",
+ "sourceName": "SOURCE NAME (SHORT)",
+ "feedUrl": "RSS FEED URL",
+ "category": "CATEGORY",
+ "region": "REGION",
+ "required": "*",
+ "testUrl": "TEST URL",
+ "testing": "TESTING...",
+ "valid": "VALID",
+ "cancel": "CANCEL",
+ "saving": "SAVING...",
+ "addFeed": "ADD FEED",
+ "updateFeed": "UPDATE FEED",
+ "on": "ON",
+ "off": "OFF",
+ "default": "DEFAULT",
+ "total": "TOTAL",
+ "active": "ACTIVE",
+ "custom": "CUSTOM",
+ "placeholders": {
+ "displayName": "e.g., Bloomberg Markets",
+ "sourceName": "e.g., BLOOMBERG",
+ "feedUrl": "https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "Name is required",
+ "sourceRequired": "Source name is required",
+ "invalidUrl": "Please enter a valid URL",
+ "invalidRss": "URL does not appear to be a valid RSS feed",
+ "testFailed": "Failed to test URL",
+ "addFailed": "Failed to add feed",
+ "updateFailed": "Failed to update feed"
+ },
+ "confirmDelete": {
+ "title": "Delete this RSS feed?",
+ "message": "This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/en/portfolio.json b/fincept-terminal-desktop/public/locales/en/portfolio.json
index 379a4cbeb..b6997e508 100644
--- a/fincept-terminal-desktop/public/locales/en/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/en/portfolio.json
@@ -11,7 +11,12 @@
"totalValue": "TOTAL VALUE",
"dayPnl": "DAY P&L",
"totalPnl": "TOTAL P&L",
- "positions": "POSITIONS"
+ "positions": "POSITIONS",
+ "portfolioSummary": "PORTFOLIO SUMMARY",
+ "unrealizedPnl": "UNREALIZED P&L",
+ "costBasis": "COST BASIS",
+ "dayChange": "DAY CHANGE",
+ "topHoldings": "TOP HOLDINGS"
},
"views": {
"positions": "POSITIONS",
@@ -25,20 +30,32 @@
"reports": "REPORTS",
"alerts": "ALERTS",
"sectors": "SECTORS",
- "help": "HELP"
+ "help": "HELP",
+ "indices": "INDICES",
+ "risk": "RISK",
+ "optimization": "OPTIMIZATION",
+ "quantstats": "QUANTSTATS"
},
"sidebar": {
"portfolios": "PORTFOLIOS",
"loading": "Loading portfolios...",
"noPortfolios": "No portfolios yet.",
- "clickCreate": "Click NEW PORTFOLIO to create one.",
+ "clickCreate": "Click NEW to create one.",
"owner": "Owner",
"currency": "Currency"
},
"content": {
"selectOrCreate": "Select a portfolio or create a new one to get started",
"loadingData": "Loading portfolio data...",
- "comingSoon": "view coming soon..."
+ "comingSoon": "view coming soon...",
+ "selectPortfolio": "Select a portfolio"
+ },
+ "actions": {
+ "buy": "BUY",
+ "sell": "SELL",
+ "new": "NEW",
+ "refresh": "REFRESH",
+ "export": "EXPORT"
},
"modals": {
"createNew": "CREATE NEW PORTFOLIO",
@@ -55,6 +72,158 @@
"add": "ADD",
"sell": "SELL"
},
+ "positions": {
+ "currentPositions": "CURRENT POSITIONS",
+ "symbol": "SYMBOL",
+ "qty": "QTY",
+ "avgPrice": "AVG PRICE",
+ "current": "CURRENT",
+ "mktValue": "MKT VALUE",
+ "costBasis": "COST BASIS",
+ "pnl": "P&L",
+ "dayChange": "DAY CHANGE",
+ "weight": "WEIGHT",
+ "noPositions": "No positions yet. Click BUY to add your first position.",
+ "total": "TOTAL"
+ },
+ "history": {
+ "transactionHistory": "TRANSACTION HISTORY",
+ "date": "DATE",
+ "symbol": "SYMBOL",
+ "type": "TYPE",
+ "qty": "QTY",
+ "price": "PRICE",
+ "total": "TOTAL",
+ "notes": "NOTES",
+ "noTransactions": "No transactions yet"
+ },
+ "analytics": {
+ "dashboard": "PORTFOLIO ANALYTICS DASHBOARD",
+ "advancedMetrics": "ADVANCED PORTFOLIO METRICS (Python-Powered)",
+ "optimizeWeights": "OPTIMIZE WEIGHTS",
+ "optimizing": "OPTIMIZING...",
+ "sharpeRatio": "SHARPE RATIO",
+ "volatility": "VOLATILITY",
+ "var95": "VaR (95%)",
+ "maxDrawdown": "MAX DRAWDOWN",
+ "annualReturn": "ANNUAL RETURN",
+ "optimizedAllocation": "OPTIMIZED ALLOCATION (Max Sharpe Ratio)",
+ "totalValue": "TOTAL VALUE",
+ "totalPnl": "TOTAL P&L",
+ "dayChange": "DAY CHANGE",
+ "positions": "POSITIONS",
+ "topGainers": "TOP GAINERS",
+ "topLosers": "TOP LOSERS",
+ "largestPositions": "LARGEST POSITIONS",
+ "allocationBreakdown": "ALLOCATION BREAKDOWN",
+ "noData": "No data"
+ },
+ "sectors": {
+ "sectorAllocation": "SECTOR ALLOCATION",
+ "loadingSectorData": "Loading sector data from API...",
+ "noSectorData": "No sector data available. Add holdings with sector information.",
+ "sectorBreakdown": "SECTOR BREAKDOWN",
+ "sector": "SECTOR",
+ "value": "VALUE",
+ "weight": "WEIGHT",
+ "holdings": "HOLDINGS",
+ "diversificationMetrics": "DIVERSIFICATION METRICS",
+ "totalSectors": "Total Sectors",
+ "largestSector": "Largest Sector",
+ "concentrationRisk": "Concentration Risk",
+ "diversification": "Diversification",
+ "high": "HIGH",
+ "medium": "MEDIUM",
+ "low": "LOW",
+ "good": "GOOD",
+ "moderate": "MODERATE",
+ "poor": "POOR"
+ },
+ "performance": {
+ "performanceChart": "PERFORMANCE CHART",
+ "loading": "Loading performance data...",
+ "noData": "Not enough data for performance chart",
+ "totalReturn": "TOTAL RETURN",
+ "dayChange": "DAY CHANGE",
+ "weekChange": "7D CHANGE",
+ "monthChange": "30D CHANGE",
+ "portfolioValue": "Portfolio Value"
+ },
+ "risk": {
+ "riskMetrics": "RISK METRICS & ANALYTICS",
+ "limitedData": "(LIMITED DATA)",
+ "insufficientData": "[WARN] INSUFFICIENT HISTORICAL DATA:",
+ "insufficientDataDesc": "Risk metrics require at least 5 days of portfolio snapshots for accurate calculations.",
+ "currentDataPoints": "Current data points:",
+ "metricsShownPreliminary": "Metrics shown are preliminary.",
+ "overallRisk": "OVERALL RISK",
+ "marketSensitivity": "MARKET SENSITIVITY",
+ "volatility": "VOLATILITY",
+ "riskAdjustedReturns": "RISK-ADJUSTED RETURNS",
+ "downsideRiskMetrics": "DOWNSIDE RISK METRICS",
+ "sharpeRatio": "SHARPE RATIO",
+ "beta": "BETA",
+ "maxDrawdown": "MAX DRAWDOWN",
+ "valueAtRisk": "VALUE AT RISK (95%)",
+ "compositeRiskScore": "COMPOSITE RISK SCORE",
+ "riskManagementRecommendations": "RISK MANAGEMENT RECOMMENDATIONS",
+ "disclaimer": "DISCLAIMER:",
+ "low": "LOW",
+ "moderate": "MODERATE",
+ "high": "HIGH",
+ "veryHigh": "VERY HIGH",
+ "defensive": "DEFENSIVE",
+ "neutral": "NEUTRAL",
+ "aggressive": "AGGRESSIVE"
+ },
+ "reports": {
+ "taxReports": "TAX REPORTS & STATEMENTS",
+ "totalTaxLiability": "TOTAL TAX LIABILITY",
+ "longTermGains": "LONG-TERM GAINS",
+ "shortTermGains": "SHORT-TERM GAINS",
+ "unrealizedGains": "UNREALIZED GAINS",
+ "taxBreakdown": "TAX BREAKDOWN (FIFO METHOD)",
+ "category": "CATEGORY",
+ "gains": "GAINS",
+ "taxRate": "TAX RATE",
+ "taxDue": "TAX DUE",
+ "totalTaxDue": "TOTAL TAX DUE",
+ "transactionSummary": "TRANSACTION SUMMARY",
+ "totalTransactions": "Total Transactions:",
+ "buyTransactions": "Buy Transactions:",
+ "sellTransactions": "Sell Transactions:",
+ "currentPositions": "Current Positions:",
+ "dividendIncome": "DIVIDEND INCOME",
+ "totalDividends": "Total Dividends (YTD):",
+ "portfolioYield": "Portfolio Yield:",
+ "exportOptions": "EXPORT OPTIONS",
+ "exportTaxReport": "EXPORT TAX REPORT (PDF)",
+ "exportTransactions": "EXPORT TRANSACTIONS (CSV)",
+ "exportHoldings": "EXPORT HOLDINGS (XLSX)"
+ },
+ "alerts": {
+ "priceAlerts": "PRICE ALERTS & NOTIFICATIONS",
+ "featureTitle": "PRICE ALERTS FEATURE",
+ "notImplemented": "This feature is not yet implemented.",
+ "willAllowYou": "Price alerts will allow you to set notifications for:",
+ "plannedFeatures": "PLANNED FEATURES",
+ "priceTargetAlerts": "Price target alerts",
+ "stopLossNotifications": "Stop loss notifications",
+ "takeProfitAlerts": "Take profit alerts",
+ "customPriceConditions": "Custom price conditions",
+ "volumeSpikeAlerts": "Volume spike alerts",
+ "notificationChannels": "NOTIFICATION CHANNELS",
+ "desktopNotifications": "Desktop notifications",
+ "emailAlerts": "Email alerts",
+ "smsNotifications": "SMS notifications (Premium)",
+ "pushNotifications": "Push notifications",
+ "dailyWeeklySummaries": "Daily/weekly summaries",
+ "suggestedAlerts": "SUGGESTED ALERTS FOR YOUR POSITIONS (PREVIEW)",
+ "stopLoss": "Stop Loss (10%):",
+ "takeProfit": "Take Profit (20%):",
+ "comingSoon": "COMING SOON",
+ "implementationStatus": "IMPLEMENTATION STATUS"
+ },
"status": {
"version": "Fincept Portfolio Manager v2.1.0 | Real-time tracking with yfinance integration",
"lastUpdated": "Last Updated",
diff --git a/fincept-terminal-desktop/public/locales/en/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/en/surfaceAnalytics.json
new file mode 100644
index 000000000..85a572a64
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/en/surfaceAnalytics.json
@@ -0,0 +1,294 @@
+{
+ "title": "SURFACE ANALYTICS",
+ "initializing": "INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequired": "DATABENTO API KEY REQUIRED",
+ "apiKeyDescription": "Surface Analytics requires a Databento API key to fetch real-time options data, historical prices, and market information. Databento provides institutional-grade market data for professional financial analysis.",
+ "apiKeyRequiredStatus": "API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "configureApiKey": "CONFIGURE API KEY",
+ "getApiKey": "GET API KEY",
+ "useDemoData": "USE DEMO DATA",
+ "syntheticData": "synthetic data for visualization",
+ "paidServiceNotice": "Databento is a paid service. API calls consume data credits. Review their pricing at databento.com/pricing before proceeding.",
+ "features": {
+ "volatility": "Volatility Surfaces",
+ "volatilityDesc": "Options IV analysis",
+ "correlation": "Correlation Matrix",
+ "correlationDesc": "Multi-asset correlations",
+ "yieldCurves": "Yield Curves",
+ "yieldCurvesDesc": "Treasury rate evolution",
+ "pca": "PCA Factors",
+ "pcaDesc": "Factor decomposition"
+ },
+ "charts": {
+ "volatility": "VOL SURFACE",
+ "correlation": "CORRELATION",
+ "yieldCurve": "YIELD CURVE",
+ "pca": "PCA FACTORS"
+ },
+ "demoData": "DEMO DATA",
+ "demoDataSynthetic": "DEMO DATA (synthetic)",
+ "synthetic": "SYNTHETIC",
+ "manual": "MANUAL",
+ "error": "ERROR",
+ "ready": "READY",
+ "metrics": "Metrics",
+ "updated": "Updated",
+ "clickRefresh": "Click REFRESH to load data",
+ "refresh": "REFRESH",
+ "noApiKey": "NO API KEY",
+ "lastUpdate": "LAST UPDATE",
+ "loadingData": "LOADING DATA...",
+ "noDataLoaded": "NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "IV SURFACE METRICS",
+ "correlationMetrics": "CORRELATION METRICS",
+ "yieldCurveMetrics": "YIELD CURVE METRICS",
+ "pcaFactorMetrics": "PCA FACTOR METRICS",
+ "dataInfo": "DATA INFO",
+ "source": "SOURCE",
+ "frequency": "FREQUENCY",
+ "quality": "QUALITY",
+ "correlationScale": "CORRELATION SCALE",
+ "strongPositive": "Strong Positive (0.7-1.0)",
+ "neutral": "Neutral (0.3-0.7)",
+ "strongNegative": "Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "IV INTERPRETATION",
+ "highIv": "High IV = Expensive Options",
+ "lowIv": "Low IV = Cheap Options",
+ "skew": "Skew = Put/Call IV Diff",
+ "termStructure": "Term Structure = Time Effect",
+ "pcaInterpretation": "PCA INTERPRETATION",
+ "pc1": "PC1 = Market Factor",
+ "pc2": "PC2 = Size/Value Factor",
+ "pc3": "PC3 = Sector Rotation",
+ "higherVar": "Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "STRIKE",
+ "dte": "DTE",
+ "iv": "IV",
+ "correlation": "CORRELATION",
+ "maturity": "MATURITY",
+ "yield": "YIELD",
+ "loading": "LOADING",
+ "strikePrice": "STRIKE PRICE",
+ "daysToExpiry": "DAYS TO EXPIRY",
+ "impliedVol": "IMPLIED VOL (%)",
+ "assetPairIndex": "ASSET PAIR INDEX",
+ "timeDays": "TIME (DAYS)",
+ "correlationCoeff": "CORRELATION COEFF",
+ "maturityMonths": "MATURITY (MONTHS)",
+ "historicalDays": "HISTORICAL DAYS",
+ "yieldPercent": "YIELD (%)",
+ "principalComponent": "PRINCIPAL COMPONENT",
+ "assetIndex": "ASSET INDEX",
+ "factorLoading": "FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "DAY ROLLING",
+ "yieldCurve": "U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "FAILED TO LOAD DATA",
+ "authFailed": "AUTHENTICATION FAILED",
+ "authFailedHelp": "Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "ACCESS DENIED",
+ "accessDeniedHelp": "Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "DATA TIMEFRAME",
+ "schema": "Schema",
+ "description": "Description",
+ "recordsPerDay": "Records/Day",
+ "highFrequencyWarning": "High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "Data Volume"
+ },
+ "settings": {
+ "title": "SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "DATABENTO API KEY",
+ "configured": "CONFIGURED",
+ "invalidFormat": "INVALID FORMAT",
+ "apiKeyConfigured": "API key is configured (db-*****)",
+ "remove": "REMOVE",
+ "enterApiKey": "Enter your Databento API key (db-*****)",
+ "save": "SAVE",
+ "saving": "SAVING...",
+ "getApiKeyFrom": "Get your API key from",
+ "dashboardApiKeys": "Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "CORRELATION ASSETS",
+ "addSymbol": "Add symbol (e.g., AAPL)",
+ "resetToDefaults": "Reset to defaults",
+ "historicalDateRange": "HISTORICAL DATE RANGE",
+ "start": "Start",
+ "end": "End",
+ "autoRefreshInterval": "AUTO REFRESH INTERVAL",
+ "manualOnly": "Manual Only",
+ "every1min": "Every 1 minute",
+ "every5min": "Every 5 minutes",
+ "every15min": "Every 15 minutes",
+ "every1hour": "Every 1 hour",
+ "browseDatasets": "BROWSE DATASETS",
+ "costEstimator": "COST ESTIMATOR",
+ "referenceData": "REFERENCE DATA",
+ "orderBook": "ORDER BOOK",
+ "liveStreaming": "LIVE STREAMING",
+ "active": "ACTIVE",
+ "futuresCme": "FUTURES (CME GLOBEX)",
+ "batchDownloads": "BATCH DOWNLOADS",
+ "additionalSchemas": "ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "TRADES, IMBALANCE, STATUS",
+ "cancel": "CANCEL",
+ "saveChanges": "SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "BATCH DOWNLOADS",
+ "newBatchJob": "NEW BATCH JOB",
+ "dataset": "Dataset",
+ "schema": "Schema",
+ "symbolsCommaSeparated": "Symbols (comma-separated)",
+ "startDate": "Start Date",
+ "endDate": "End Date",
+ "encoding": "Encoding",
+ "compression": "Compression",
+ "submitJob": "SUBMIT JOB",
+ "noBatchJobs": "No batch jobs found. Click + to create one.",
+ "records": "records",
+ "download": "Download",
+ "files": "FILES",
+ "jobsExpireNotice": "Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "Configure Databento API key for batch downloads"
+ },
+ "additionalSchemas": {
+ "title": "ADDITIONAL SCHEMAS",
+ "trades": "Trades",
+ "imbalance": "Imbalance",
+ "statistics": "Statistics",
+ "status": "Status",
+ "time": "TIME",
+ "symbol": "SYMBOL",
+ "price": "PRICE",
+ "size": "SIZE",
+ "side": "SIDE",
+ "refPrice": "REF PRICE",
+ "type": "TYPE",
+ "action": "ACTION",
+ "reason": "REASON",
+ "clickRefreshTrades": "Click refresh to load trades data",
+ "clickRefreshImbalance": "Click refresh to load imbalance data (available at market open/close)",
+ "clickRefreshStatistics": "Click refresh to load statistics (trading halts, circuit breakers)",
+ "clickRefreshStatus": "Click refresh to load trading status (halts, Reg SHO)",
+ "regShoRestrictions": "Some symbols have Reg SHO restrictions",
+ "symbols": "Symbols",
+ "configureApiKey": "Configure Databento API key for additional schemas"
+ },
+ "futures": {
+ "title": "FUTURES (CME GLOBEX)",
+ "popular": "Popular",
+ "clickSymbolToView": "Click a futures symbol to view term structure",
+ "marketStructure": "Market Structure",
+ "contango": "CONTANGO",
+ "backwardation": "BACKWARDATION",
+ "contract": "CONTRACT",
+ "price": "PRICE",
+ "volume": "VOLUME",
+ "spread": "SPREAD",
+ "front": "FRONT",
+ "availableContracts": "Available Contracts",
+ "configureApiKey": "Configure Databento API key for futures data"
+ },
+ "liveStream": {
+ "title": "LIVE STREAM",
+ "connected": "CONNECTED",
+ "msgs": "msgs",
+ "dataset": "Dataset",
+ "schema": "Schema",
+ "symbol": "Symbol",
+ "custom": "Custom...",
+ "startStream": "Start Stream",
+ "connecting": "Connecting...",
+ "stopStream": "Stop Stream",
+ "clear": "Clear",
+ "stopAll": "Stop All",
+ "waitingForData": "Waiting for data...",
+ "clickStartStream": "Click Start Stream to begin receiving live data",
+ "live": "Live",
+ "messages": "messages",
+ "buffer": "Buffer",
+ "configureApiKey": "Configure Databento API key for live streaming"
+ },
+ "orderBook": {
+ "title": "ORDER BOOK",
+ "top": "TOP",
+ "tenLevel": "10-LVL",
+ "spread": "Spread",
+ "clickRefresh": "Click refresh to load order book data",
+ "bidSize": "BID SIZE",
+ "bid": "BID",
+ "ask": "ASK",
+ "askSize": "ASK SIZE",
+ "totalBid": "Total Bid",
+ "totalAsk": "Total Ask",
+ "configureApiKey": "Configure Databento API key to view order book"
+ },
+ "referenceData": {
+ "title": "REFERENCE DATA",
+ "securityMaster": "SECURITY MASTER",
+ "corporateActions": "CORPORATE ACTIONS",
+ "adjustments": "ADJUSTMENTS",
+ "symbols": "SYMBOLS",
+ "more": "more",
+ "clickRefreshSecurity": "Click refresh to load security master data",
+ "clickRefreshCorporate": "Click refresh to load corporate actions",
+ "clickRefreshAdjustments": "Click refresh to load adjustment factors",
+ "exchange": "Exchange",
+ "currency": "Currency",
+ "sector": "Sector",
+ "industry": "Industry",
+ "marketCap": "Market Cap",
+ "type": "Type",
+ "dividend": "DIVIDEND",
+ "split": "SPLIT",
+ "spinoff": "SPINOFF",
+ "merger": "MERGER",
+ "date": "DATE",
+ "splitFactor": "SPLIT",
+ "dividendFactor": "DIVIDEND",
+ "cumulative": "CUMULATIVE",
+ "showingRecords": "Showing {{shown}} of {{total}} records",
+ "configureApiKey": "Configure Databento API key to access reference data"
+ },
+ "costEstimator": {
+ "title": "COST ESTIMATOR",
+ "estimate": "ESTIMATE",
+ "dataset": "Dataset",
+ "schema": "Schema",
+ "symbols": "Symbols",
+ "range": "Range",
+ "notSelected": "Not selected",
+ "none": "None",
+ "highFrequencyWarning": "High-frequency data schema - may incur significant costs",
+ "estimateReady": "ESTIMATE READY",
+ "records": "RECORDS",
+ "estimatedCost": "ESTIMATED COST",
+ "free": "FREE"
+ },
+ "datasetBrowser": {
+ "title": "AVAILABLE DATASETS",
+ "loadingDetails": "Loading details...",
+ "from": "From",
+ "to": "To",
+ "schemas": "Schemas",
+ "noDatasets": "No datasets available",
+ "select": "SELECT",
+ "selected": "SELECTED",
+ "configureApiKey": "Configure Databento API key to browse datasets"
+ }
+}
diff --git a/fincept-terminal-desktop/scripts/audit-translations.js b/fincept-terminal-desktop/scripts/audit-translations.js
deleted file mode 100644
index 3080b94f7..000000000
--- a/fincept-terminal-desktop/scripts/audit-translations.js
+++ /dev/null
@@ -1,218 +0,0 @@
-#!/usr/bin/env node
-// Translation audit script - finds missing and unused translation keys
-
-import fs from 'fs';
-import path from 'path';
-import { glob } from 'glob';
-
-const LOCALES_DIR = 'public/locales';
-const SRC_DIR = 'src';
-const LANGUAGES = ['en', 'es', 'fr', 'de', 'zh', 'ja', 'hi', 'ar', 'pt', 'ru', 'bn', 'ko', 'tr', 'it', 'id', 'vi', 'th', 'pl', 'uk', 'ro'];
-const NAMESPACES = [
- 'common', 'auth', 'dashboard', 'settings', 'tabs', 'chat', 'economics',
- 'equityResearch', 'forum', 'geopolitics', 'loginAudit', 'maritime', 'markets',
- 'news', 'portfolio', 'profile', 'screener', 'trading', 'watchlist', 'dataMapping',
- 'dataSources', 'docs', 'notes', 'support', 'nodeEditor', 'reportBuilder',
- 'alphaArena', 'codeEditor', 'agentConfig', 'dbnomics', 'excel', 'marketplace', 'backtesting'
-];
-
-// Extract all translation keys from code
-function extractKeysFromCode() {
- const files = glob.sync(`${SRC_DIR}/**/*.{ts,tsx}`, { ignore: '**/node_modules/**' });
- const usedKeys = new Map(); // namespace -> Set of keys
-
- // Regex patterns to match t() calls
- const patterns = [
- /t\(['"]([^:'"]+):([^'"]+)['"]\)/g, // t('namespace:key')
- /t\(['"]([^'"]+)['"]\)/g, // t('key') - uses default namespace
- ];
-
- files.forEach(file => {
- const content = fs.readFileSync(file, 'utf-8');
-
- // Pattern 1: t('namespace:key')
- let match;
- const pattern1 = /t\(['"]([^:'"]+):([^'"]+)['"]/g;
- while ((match = pattern1.exec(content)) !== null) {
- const namespace = match[1];
- const key = match[2];
- if (!usedKeys.has(namespace)) {
- usedKeys.set(namespace, new Set());
- }
- usedKeys.get(namespace).add(key);
- }
-
- // Pattern 2: t('key') - common namespace
- const pattern2 = /t\(['"]([^:'"]+)['"]/g;
- while ((match = pattern2.exec(content)) !== null) {
- const key = match[1];
- if (!key.includes(':')) { // Make sure it's not already caught
- if (!usedKeys.has('common')) {
- usedKeys.set('common', new Set());
- }
- usedKeys.get('common').add(key);
- }
- }
- });
-
- return usedKeys;
-}
-
-// Get all keys from translation files
-function getTranslationKeys(lang = 'en') {
- const keys = new Map(); // namespace -> Set of keys
-
- NAMESPACES.forEach(namespace => {
- const filePath = path.join(LOCALES_DIR, lang, `${namespace}.json`);
- if (fs.existsSync(filePath)) {
- const content = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
- keys.set(namespace, new Set(extractAllKeys(content)));
- }
- });
-
- return keys;
-}
-
-// Recursively extract all keys from nested JSON
-function extractAllKeys(obj, prefix = '') {
- let keys = [];
-
- 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(extractAllKeys(value, fullKey));
- } else {
- keys.push(fullKey);
- }
- }
-
- return keys;
-}
-
-// Find hardcoded strings (simple heuristic)
-function findHardcodedStrings() {
- const files = glob.sync(`${SRC_DIR}/**/*.{ts,tsx}`, { ignore: '**/node_modules/**' });
- const suspiciousStrings = [];
-
- // Look for JSX text that might need translation
- const jsxTextPattern = />\s*([A-Z][A-Za-z\s]{3,30})\s*</g;
-
- files.forEach(file => {
- const content = fs.readFileSync(file, 'utf-8');
- let match;
-
- while ((match = jsxTextPattern.exec(content)) !== null) {
- const text = match[1].trim();
- // Skip common words and check if it's likely a label
- if (text.split(' ').length <= 5 && !text.includes('const') && !text.includes('function')) {
- suspiciousStrings.push({ file: path.relative(process.cwd(), file), text });
- }
- }
- });
-
- return suspiciousStrings.slice(0, 50); // Limit to first 50
-}
-
-// Main audit function
-function audit() {
- console.log('🔍 Starting translation audit...\n');
-
- const usedKeys = extractKeysFromCode();
- const translationKeys = getTranslationKeys('en');
-
- console.log('📊 STATISTICS');
- console.log('='.repeat(60));
- console.log(`Languages: ${LANGUAGES.length}`);
- console.log(`Namespaces: ${NAMESPACES.length}`);
-
- let totalUsed = 0;
- let totalAvailable = 0;
- usedKeys.forEach(keys => totalUsed += keys.size);
- translationKeys.forEach(keys => totalAvailable += keys.size);
-
- console.log(`Translation keys in code: ${totalUsed}`);
- console.log(`Translation keys in files: ${totalAvailable}\n`);
-
- // Find missing keys (used in code but not in translation files)
- console.log('❌ MISSING TRANSLATIONS (used in code, not in translation files)');
- console.log('='.repeat(60));
- let missingCount = 0;
-
- usedKeys.forEach((keys, namespace) => {
- const translatedKeys = translationKeys.get(namespace) || new Set();
- const missing = [...keys].filter(key => !translatedKeys.has(key));
-
- if (missing.length > 0) {
- console.log(`\n[${namespace}] - ${missing.length} missing keys:`);
- missing.forEach(key => console.log(` - ${key}`));
- missingCount += missing.length;
- }
- });
-
- if (missingCount === 0) {
- console.log('✅ No missing keys found!\n');
- } else {
- console.log(`\n⚠️ Total missing: ${missingCount} keys\n`);
- }
-
- // Find unused keys (in translation files but not used in code)
- console.log('🗑️ UNUSED TRANSLATIONS (in files, not used in code)');
- console.log('='.repeat(60));
- let unusedCount = 0;
-
- translationKeys.forEach((keys, namespace) => {
- const usedInCode = usedKeys.get(namespace) || new Set();
- const unused = [...keys].filter(key => !usedInCode.has(key));
-
- if (unused.length > 0) {
- console.log(`\n[${namespace}] - ${unused.length} unused keys:`);
- unused.slice(0, 10).forEach(key => console.log(` - ${key}`));
- if (unused.length > 10) {
- console.log(` ... and ${unused.length - 10} more`);
- }
- unusedCount += unused.length;
- }
- });
-
- if (unusedCount === 0) {
- console.log('✅ No unused keys found!\n');
- } else {
- console.log(`\n📝 Total unused: ${unusedCount} keys (consider removing or they may be dynamic)\n`);
- }
-
- // Find potentially hardcoded strings
- console.log('🔤 POTENTIALLY HARDCODED STRINGS (sample)');
- console.log('='.repeat(60));
- const hardcoded = findHardcodedStrings();
-
- if (hardcoded.length > 0) {
- const grouped = {};
- hardcoded.forEach(({ file, text }) => {
- if (!grouped[file]) grouped[file] = [];
- grouped[file].push(text);
- });
-
- Object.entries(grouped).slice(0, 10).forEach(([file, texts]) => {
- console.log(`\n${file}:`);
- texts.forEach(text => console.log(` - "${text}"`));
- });
- console.log('\n⚠️ Review these strings to see if they need translation');
- } else {
- console.log('✅ No obvious hardcoded strings found!\n');
- }
-
- // Summary
- console.log('\n' + '='.repeat(60));
- console.log('📋 SUMMARY');
- console.log('='.repeat(60));
- console.log(`✅ Translation coverage: ${totalAvailable} keys across ${NAMESPACES.length} namespaces`);
- console.log(`🔍 Keys used in code: ${totalUsed}`);
- console.log(`❌ Missing translations: ${missingCount}`);
- console.log(`🗑️ Unused translations: ${unusedCount}`);
- console.log(`🔤 Potential hardcoded strings found: ${hardcoded.length}`);
- console.log('\n✨ Audit complete!\n');
-}
-
-// Run audit
-audit();
diff --git a/fincept-terminal-desktop/scripts/extract-hardcoded.js b/fincept-terminal-desktop/scripts/extract-hardcoded.js
deleted file mode 100644
index a6b37e27e..000000000
--- a/fincept-terminal-desktop/scripts/extract-hardcoded.js
+++ /dev/null
@@ -1,227 +0,0 @@
-#!/usr/bin/env node
-// Extract hardcoded strings from React components and generate translation keys
-
-import fs from 'fs';
-import path from 'path';
-import { glob } from 'glob';
-
-const SRC_DIR = 'src';
-const LOCALES_DIR = 'public/locales/en';
-
-// Patterns to find hardcoded strings in JSX
-const patterns = [
- // JSX text content: >Some Text<
- />\s*([A-Z][A-Za-z0-9\s\-\.,'!?:]+)\s*</g,
- // Placeholder attributes: placeholder="text"
- /placeholder=["']([^"']+)["']/g,
- // Title attributes: title="text"
- /title=["']([^"']+)["']/g,
- // Alert/confirm calls: alert("text") or confirm("text")
- /(?:alert|confirm)\(["']([^"']+)["']\)/g,
- // setError calls: setError("text") or setError('text')
- /setError\(["']([^"']+)["']\)/g,
-];
-
-// Strings to ignore (code patterns, not UI text)
-const ignorePatterns = [
- /^[a-z_]+$/, // lowercase only (likely code)
- /^[A-Z_]+$/, // CONSTANTS
- /^\d+$/, // numbers only
- /^https?:\/\//, // URLs
- /^[a-z]+\.[a-z]+/, // file paths
- /^\s*$/, // whitespace
- /^[<>\/]/, // HTML tags
- /className/, // React className
- /^\{/, // JSX expressions
- /^import/, // imports
- /^export/, // exports
- /^const /, // const declarations
- /^function/, // function declarations
- /Promise/, // Promise type
- /^[a-z]+:/, // object keys
-];
-
-function shouldIgnore(str) {
- if (str.length < 3 || str.length > 200) return true;
- return ignorePatterns.some(pattern => pattern.test(str));
-}
-
-function extractStrings(content, filePath) {
- const strings = [];
- const seen = new Set();
-
- // Pattern for JSX string literals that look like UI text
- const jsxTextPattern = />\s*([A-Z][A-Za-z0-9\s\-\.,!?:'"()]+)\s*</g;
- let match;
-
- while ((match = jsxTextPattern.exec(content)) !== null) {
- const text = match[1].trim();
- if (!shouldIgnore(text) && !seen.has(text)) {
- seen.add(text);
- strings.push({ text, type: 'jsx-text', file: filePath });
- }
- }
-
- // Pattern for string attributes
- const attrPatterns = [
- { pattern: /placeholder=["']([^"']{3,})["']/g, type: 'placeholder' },
- { pattern: /title=["']([^"']{3,})["']/g, type: 'title' },
- { pattern: /aria-label=["']([^"']{3,})["']/g, type: 'aria-label' },
- ];
-
- attrPatterns.forEach(({ pattern, type }) => {
- while ((match = pattern.exec(content)) !== null) {
- const text = match[1].trim();
- if (!shouldIgnore(text) && !seen.has(text)) {
- seen.add(text);
- strings.push({ text, type, file: filePath });
- }
- }
- });
-
- // Pattern for error/alert messages
- const errorPatterns = [
- /setError\(["']([^"']{5,})["']\)/g,
- /alert\(["']([^"']{5,})["']\)/g,
- /confirm\(["']([^"']{5,})["']\)/g,
- ];
-
- errorPatterns.forEach(pattern => {
- while ((match = pattern.exec(content)) !== null) {
- const text = match[1].trim();
- if (!shouldIgnore(text) && !seen.has(text)) {
- seen.add(text);
- strings.push({ text, type: 'message', file: filePath });
- }
- }
- });
-
- return strings;
-}
-
-function getNamespaceFromFile(filePath) {
- const fileName = path.basename(filePath, '.tsx');
-
- if (filePath.includes('/auth/')) return 'auth';
- if (filePath.includes('/settings/')) return 'settings';
- if (filePath.includes('/dashboard/')) return 'dashboard';
-
- // Tab files
- const tabMap = {
- 'DashboardTab': 'dashboard',
- 'SettingsTab': 'settings',
- 'ChatTab': 'chat',
- 'NewsTab': 'news',
- 'MarketsTab': 'markets',
- 'WatchlistTab': 'watchlist',
- 'TradingTab': 'trading',
- 'PortfolioTab': 'portfolio',
- 'ForumTab': 'forum',
- 'ProfileTab': 'profile',
- 'ScreenerTab': 'screener',
- 'BacktestingTabNew': 'backtesting',
- 'GeopoliticsTab': 'geopolitics',
- 'MaritimeTab': 'maritime',
- 'EconomicsTab': 'economics',
- 'DBnomicsTab': 'dbnomics',
- 'ExcelTab': 'excel',
- 'CodeEditorTab': 'codeEditor',
- 'NodeEditorTab': 'nodeEditor',
- 'ReportBuilderTab': 'reportBuilder',
- 'NotesTab': 'notes',
- 'SupportTicketTab': 'support',
- 'MarketplaceTab': 'marketplace',
- 'AgentConfigTab': 'agentConfig',
- 'AlphaArenaTab': 'alphaArena',
- 'DerivativesTab': 'derivatives',
- 'LoginAuditDashboard': 'loginAudit',
- };
-
- return tabMap[fileName] || 'common';
-}
-
-function generateKey(text, namespace) {
- // Convert text to camelCase key
- const key = text
- .toLowerCase()
- .replace(/[^a-z0-9\s]/g, '')
- .trim()
- .split(/\s+/)
- .slice(0, 4)
- .map((word, i) => i === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1))
- .join('');
-
- return key || 'text';
-}
-
-async function main() {
- console.log('🔍 Scanning for hardcoded strings...\n');
-
- const files = glob.sync(`${SRC_DIR}/**/*.tsx`, { ignore: '**/node_modules/**' });
- const allStrings = [];
- const byNamespace = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
-
- // Skip files that already have useTranslation with good coverage
- const hasTranslation = content.includes('useTranslation');
- const tCalls = (content.match(/\bt\(/g) || []).length;
-
- const strings = extractStrings(content, file);
-
- if (strings.length > 0) {
- const namespace = getNamespaceFromFile(file);
-
- if (!byNamespace.has(namespace)) {
- byNamespace.set(namespace, []);
- }
-
- strings.forEach(s => {
- s.namespace = namespace;
- s.key = generateKey(s.text, namespace);
- byNamespace.get(namespace).push(s);
- allStrings.push(s);
- });
- }
- }
-
- console.log(`Found ${allStrings.length} potential hardcoded strings\n`);
-
- // Group by namespace and show summary
- console.log('BY NAMESPACE:');
- console.log('-'.repeat(60));
-
- byNamespace.forEach((strings, namespace) => {
- console.log(`\n[${namespace}] - ${strings.length} strings`);
- strings.slice(0, 5).forEach(s => {
- console.log(` "${s.text.substring(0, 50)}${s.text.length > 50 ? '...' : ''}" (${s.type})`);
- });
- if (strings.length > 5) {
- console.log(` ... and ${strings.length - 5} more`);
- }
- });
-
- // Generate translation keys file
- const output = {};
- byNamespace.forEach((strings, namespace) => {
- output[namespace] = {};
- const seen = new Set();
-
- strings.forEach(s => {
- let key = s.key;
- let counter = 1;
- while (seen.has(key)) {
- key = `${s.key}${counter++}`;
- }
- seen.add(key);
- output[namespace][key] = s.text;
- });
- });
-
- fs.writeFileSync('hardcoded-strings.json', JSON.stringify(output, null, 2));
- console.log('\n\n✅ Saved to hardcoded-strings.json');
- console.log('Review this file and merge needed keys into translation files.');
-}
-
-main().catch(console.error);
diff --git a/fincept-terminal-desktop/scripts/merge-translations.js b/fincept-terminal-desktop/scripts/merge-translations.js
deleted file mode 100644
index 706d6af2f..000000000
--- a/fincept-terminal-desktop/scripts/merge-translations.js
+++ /dev/null
@@ -1,158 +0,0 @@
-#!/usr/bin/env node
-// Merge extracted hardcoded strings into existing translation files
-// This creates a comprehensive translation file with all strings
-
-import fs from 'fs';
-import path from 'path';
-
-const LOCALES_DIR = 'public/locales/en';
-const HARDCODED_FILE = 'hardcoded-strings.json';
-
-// Read existing translations
-function readExistingTranslations(namespace) {
- const filePath = path.join(LOCALES_DIR, `${namespace}.json`);
- if (fs.existsSync(filePath)) {
- const content = fs.readFileSync(filePath, 'utf-8').replace(/^\uFEFF/, '');
- try {
- return JSON.parse(content);
- } catch (e) {
- console.log(` ⚠️ Could not parse ${namespace}.json, starting fresh`);
- return {};
- }
- }
- return {};
-}
-
-// Flatten nested object to dot notation
-function flattenObject(obj, prefix = '') {
- const result = {};
- for (const [key, value] of Object.entries(obj)) {
- const newKey = prefix ? `${prefix}.${key}` : key;
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
- Object.assign(result, flattenObject(value, newKey));
- } else {
- result[newKey] = value;
- }
- }
- return result;
-}
-
-// Unflatten dot notation to nested object
-function unflattenObject(obj) {
- const result = {};
- for (const [key, value] of Object.entries(obj)) {
- const keys = key.split('.');
- let current = result;
- for (let i = 0; i < keys.length - 1; i++) {
- if (!(keys[i] in current)) {
- current[keys[i]] = {};
- }
- current = current[keys[i]];
- }
- current[keys[keys.length - 1]] = value;
- }
- return result;
-}
-
-// Clean key name
-function cleanKey(key) {
- return key
- .replace(/[^a-zA-Z0-9]/g, '')
- .replace(/^(\d)/, '_$1'); // Don't start with number
-}
-
-// Filter out non-UI strings
-function isUIString(text) {
- if (!text || typeof text !== 'string') return false;
- if (text.length < 2 || text.length > 500) return false;
-
- // Skip patterns that are clearly not UI text
- const skipPatterns = [
- /^\d+(\.\d+)?$/, // Numbers only
- /^[a-z_]+$/, // lowercase_snake_case (likely code)
- /^https?:\/\//, // URLs
- /^[a-z]+\.[a-z]+/, // file.ext
- /^\{.*\}$/, // JSON-like
- /^[<>\/]/, // HTML
- /^import\s/, // imports
- /^export\s/, // exports
- /Promise/, // Promise type
- /^\s*$/, // whitespace only
- /^[A-Z][a-z]+[A-Z]/, // camelCase
- ];
-
- return !skipPatterns.some(p => p.test(text));
-}
-
-async function main() {
- console.log('📝 Merging hardcoded strings into translation files...\n');
-
- if (!fs.existsSync(HARDCODED_FILE)) {
- console.log('❌ hardcoded-strings.json not found. Run extract-hardcoded.js first.');
- process.exit(1);
- }
-
- const hardcoded = JSON.parse(fs.readFileSync(HARDCODED_FILE, 'utf-8'));
- let totalAdded = 0;
- let totalSkipped = 0;
-
- for (const [namespace, strings] of Object.entries(hardcoded)) {
- console.log(`\n[${namespace}]`);
-
- // Read existing translations
- const existing = readExistingTranslations(namespace);
- const existingFlat = flattenObject(existing);
- const existingValues = new Set(Object.values(existingFlat));
-
- let added = 0;
- let skipped = 0;
-
- // Create new section for extracted strings
- if (!existing.extracted) {
- existing.extracted = {};
- }
-
- for (const [key, value] of Object.entries(strings)) {
- // Skip if value already exists
- if (existingValues.has(value)) {
- skipped++;
- continue;
- }
-
- // Skip non-UI strings
- if (!isUIString(value)) {
- skipped++;
- continue;
- }
-
- // Add to extracted section
- const cleanedKey = cleanKey(key);
- if (!existing.extracted[cleanedKey]) {
- existing.extracted[cleanedKey] = value;
- added++;
- }
- }
-
- // Save updated translations
- const outputPath = path.join(LOCALES_DIR, `${namespace}.json`);
- fs.writeFileSync(outputPath, JSON.stringify(existing, null, 2) + '\n', 'utf-8');
-
- console.log(` ✅ Added: ${added}, Skipped: ${skipped}`);
- totalAdded += added;
- totalSkipped += skipped;
- }
-
- console.log('\n' + '='.repeat(60));
- console.log('📋 SUMMARY');
- console.log('='.repeat(60));
- console.log(`Total strings added: ${totalAdded}`);
- console.log(`Total strings skipped: ${totalSkipped}`);
- console.log('\n✅ Translation files updated!');
- console.log('\n⚠️ NEXT STEPS:');
- console.log('1. Review the "extracted" sections in each translation file');
- console.log('2. Reorganize keys as needed');
- console.log('3. Update component files to use t() for these strings');
- console.log('4. Run: bun run i18n:sync to propagate to all languages');
-}
-
-main().catch(console.error);
diff --git a/fincept-terminal-desktop/scripts/sync-version.js b/fincept-terminal-desktop/scripts/sync-version.js
deleted file mode 100644
index 290fcb380..000000000
--- a/fincept-terminal-desktop/scripts/sync-version.js
+++ /dev/null
@@ -1,164 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Version Sync Script
- *
- * This script ensures version consistency across all files in the project:
- * - package.json (source of truth)
- * - src/constants/version.ts
- * - src-tauri/tauri.conf.json
- * - src-tauri/Cargo.toml
- *
- * Usage:
- * bun run sync-version
- */
-
-import fs from 'fs';
-import path from 'path';
-import { fileURLToPath } from 'url';
-
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = path.dirname(__filename);
-const rootDir = path.resolve(__dirname, '..');
-
-// Colors for console output
-const colors = {
- reset: '\x1b[0m',
- bright: '\x1b[1m',
- green: '\x1b[32m',
- yellow: '\x1b[33m',
- blue: '\x1b[34m',
- red: '\x1b[31m',
-};
-
-function log(message, color = colors.reset) {
- console.log(`${color}${message}${colors.reset}`);
-}
-
-function logSuccess(message) {
- log(`✓ ${message}`, colors.green);
-}
-
-function logWarning(message) {
- log(`⚠ ${message}`, colors.yellow);
-}
-
-function logError(message) {
- log(`✗ ${message}`, colors.red);
-}
-
-function logInfo(message) {
- log(`ℹ ${message}`, colors.blue);
-}
-
-// Read package.json to get the version
-function getPackageVersion() {
- const packageJsonPath = path.join(rootDir, 'package.json');
- try {
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
- return packageJson.version;
- } catch (error) {
- logError(`Failed to read package.json: ${error.message}`);
- process.exit(1);
- }
-}
-
-// Update src/constants/version.ts
-function updateVersionConstant(version) {
- const versionFilePath = path.join(rootDir, 'src', 'constants', 'version.ts');
-
- try {
- let content = fs.readFileSync(versionFilePath, 'utf8');
-
- // Replace the APP_VERSION constant
- const updatedContent = content.replace(
- /export const APP_VERSION = ['"][\d.]+['"]/,
- `export const APP_VERSION = '${version}'`
- );
-
- if (content === updatedContent) {
- logWarning('version.ts already has the correct version');
- } else {
- fs.writeFileSync(versionFilePath, updatedContent, 'utf8');
- logSuccess(`Updated src/constants/version.ts to v${version}`);
- }
- } catch (error) {
- logError(`Failed to update version.ts: ${error.message}`);
- }
-}
-
-// Update src-tauri/tauri.conf.json
-function updateTauriConfig(version) {
- const tauriConfigPath = path.join(rootDir, 'src-tauri', 'tauri.conf.json');
-
- try {
- const config = JSON.parse(fs.readFileSync(tauriConfigPath, 'utf8'));
-
- if (config.version === version) {
- logWarning('tauri.conf.json already has the correct version');
- } else {
- config.version = version;
- fs.writeFileSync(tauriConfigPath, JSON.stringify(config, null, 2) + '\n', 'utf8');
- logSuccess(`Updated src-tauri/tauri.conf.json to v${version}`);
- }
- } catch (error) {
- logError(`Failed to update tauri.conf.json: ${error.message}`);
- }
-}
-
-// Update src-tauri/Cargo.toml
-function updateCargoToml(version) {
- const cargoTomlPath = path.join(rootDir, 'src-tauri', 'Cargo.toml');
-
- try {
- let content = fs.readFileSync(cargoTomlPath, 'utf8');
-
- // Replace the version in [package] section (first occurrence)
- const lines = content.split('\n');
- let updated = false;
-
- for (let i = 0; i < lines.length; i++) {
- if (lines[i].startsWith('version = ') && !updated) {
- const currentVersion = lines[i].match(/version = "(.+)"/)?.[1];
- if (currentVersion !== version) {
- lines[i] = `version = "${version}"`;
- updated = true;
- }
- break;
- }
- }
-
- if (!updated) {
- logWarning('Cargo.toml already has the correct version');
- } else {
- fs.writeFileSync(cargoTomlPath, lines.join('\n'), 'utf8');
- logSuccess(`Updated src-tauri/Cargo.toml to v${version}`);
- }
- } catch (error) {
- logError(`Failed to update Cargo.toml: ${error.message}`);
- }
-}
-
-// Main function
-function main() {
- log('\n' + '='.repeat(60), colors.bright);
- log(' VERSION SYNC SCRIPT', colors.bright);
- log('='.repeat(60) + '\n', colors.bright);
-
- const version = getPackageVersion();
- logInfo(`Source version from package.json: v${version}\n`);
-
- updateVersionConstant(version);
- updateTauriConfig(version);
- updateCargoToml(version);
-
- log('\n' + '='.repeat(60), colors.bright);
- logSuccess('Version sync completed!');
- log('='.repeat(60) + '\n', colors.bright);
-
- logInfo('Version has been synced across all files.');
- logInfo(`Current version: ${colors.bright}v${version}${colors.reset}\n`);
-}
-
-// Run the script
-main();
diff --git a/fincept-terminal-desktop/scripts/translate-auto.js b/fincept-terminal-desktop/scripts/translate-auto.js
deleted file mode 100644
index d604ee85b..000000000
--- a/fincept-terminal-desktop/scripts/translate-auto.js
+++ /dev/null
@@ -1,196 +0,0 @@
-#!/usr/bin/env node
-// Auto-translate placeholder texts using AI or Google Translate API
-// Finds all [LANG] placeholder texts and translates them
-
-import fs from 'fs';
-import path from 'path';
-
-const LOCALES_DIR = 'public/locales';
-const LANGUAGES = ['es', 'fr', 'de', 'zh', 'ja', 'hi', 'ar', 'pt', 'ru', 'bn', 'ko', 'tr', 'it', 'id', 'vi', 'th', 'pl', 'uk', 'ro'];
-
-// Language name mapping for better AI prompting
-const LANG_NAMES = {
- 'es': 'Spanish', 'fr': 'French', 'de': 'German', 'zh': 'Chinese',
- 'ja': 'Japanese', 'hi': 'Hindi', 'ar': 'Arabic', 'pt': 'Portuguese',
- 'ru': 'Russian', 'bn': 'Bengali', 'ko': 'Korean', 'tr': 'Turkish',
- 'it': 'Italian', 'id': 'Indonesian', 'vi': 'Vietnamese', 'th': 'Thai',
- 'pl': 'Polish', 'uk': 'Ukrainian', 'ro': 'Romanian'
-};
-
-// Get nested value from object
-function getNestedValue(obj, path) {
- return path.split('.').reduce((current, key) => current?.[key], obj);
-}
-
-// Set nested value in object
-function setNestedValue(obj, path, value) {
- const keys = path.split('.');
- const lastKey = keys.pop();
- const target = keys.reduce((current, key) => {
- if (!(key in current)) {
- current[key] = {};
- }
- return current[key];
- }, obj);
- target[lastKey] = value;
-}
-
-// Get all keys from nested object with their values
-function getAllKeysWithValues(obj, prefix = '') {
- let entries = [];
- for (const [key, value] of Object.entries(obj)) {
- const fullKey = prefix ? `${prefix}.${key}` : key;
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
- entries = entries.concat(getAllKeysWithValues(value, fullKey));
- } else {
- entries.push({ key: fullKey, value });
- }
- }
- return entries;
-}
-
-// Find placeholder entries that need translation
-function findPlaceholders(lang) {
- const placeholders = new Map(); // namespace -> [{ key, value }]
- const langDir = path.join(LOCALES_DIR, lang);
-
- if (!fs.existsSync(langDir)) {
- return placeholders;
- }
-
- const files = fs.readdirSync(langDir).filter(f => f.endsWith('.json'));
-
- files.forEach(file => {
- const namespace = file.replace('.json', '');
- const filePath = path.join(langDir, file);
- const content = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
-
- const entries = getAllKeysWithValues(content);
- const needsTranslation = entries.filter(entry =>
- typeof entry.value === 'string' &&
- entry.value.startsWith(`[${lang.toUpperCase()}]`)
- );
-
- if (needsTranslation.length > 0) {
- placeholders.set(namespace, needsTranslation);
- }
- });
-
- return placeholders;
-}
-
-// Generate translation instructions
-function generateInstructions() {
- console.log('\n' + '='.repeat(70));
- console.log('🤖 AUTO-TRANSLATION HELPER');
- console.log('='.repeat(70));
- console.log('\nThis script helps you translate placeholder texts efficiently.\n');
-
- let totalPlaceholders = 0;
- const report = [];
-
- LANGUAGES.forEach(lang => {
- const placeholders = findPlaceholders(lang);
- let count = 0;
-
- placeholders.forEach(entries => {
- count += entries.length;
- });
-
- if (count > 0) {
- totalPlaceholders += count;
- report.push({ lang, count, placeholders });
- }
- });
-
- if (totalPlaceholders === 0) {
- console.log('✅ No placeholder texts found! All translations are complete.\n');
- return;
- }
-
- console.log(`Found ${totalPlaceholders} placeholder texts across ${report.length} languages.\n`);
-
- // Show breakdown
- console.log('BREAKDOWN BY LANGUAGE:');
- console.log('-'.repeat(70));
- report.forEach(({ lang, count }) => {
- console.log(`${LANG_NAMES[lang].padEnd(15)} (${lang}): ${count.toString().padStart(4)} placeholders`);
- });
-
- console.log('\n' + '='.repeat(70));
- console.log('TRANSLATION OPTIONS:');
- console.log('='.repeat(70));
-
- console.log('\n📝 OPTION 1: Manual Translation');
- console.log('-'.repeat(70));
- console.log('Navigate to: public/locales/{lang}/{namespace}.json');
- console.log('Find entries starting with [LANG] and translate them.\n');
-
- console.log('📝 OPTION 2: AI-Assisted Translation (Recommended)');
- console.log('-'.repeat(70));
- console.log('Use ChatGPT, Claude, or similar AI with this prompt:\n');
-
- // Generate sample for first language
- if (report.length > 0) {
- const { lang, placeholders } = report[0];
- const namespace = [...placeholders.keys()][0];
- const entries = placeholders.get(namespace).slice(0, 5);
-
- console.log(`"Translate these UI strings to ${LANG_NAMES[lang]}:\n`);
- entries.forEach(({ key, value }) => {
- const cleanValue = value.replace(`[${lang.toUpperCase()}] `, '');
- console.log(`- "${cleanValue}" (context: ${key})`);
- });
- console.log('"\n');
- }
-
- console.log('📝 OPTION 3: Export for Translation Service');
- console.log('-'.repeat(70));
- console.log('Export placeholder texts to CSV for professional translation:\n');
-
- // Generate CSV export
- const csvPath = 'translations-to-translate.csv';
- const csvLines = ['Language,Namespace,Key,Original Text'];
-
- report.forEach(({ lang, placeholders }) => {
- placeholders.forEach((entries, namespace) => {
- entries.forEach(({ key, value }) => {
- const cleanValue = value.replace(`[${lang.toUpperCase()}] `, '').replace(/"/g, '""');
- csvLines.push(`${lang},${namespace},${key},"${cleanValue}"`);
- });
- });
- });
-
- fs.writeFileSync(csvPath, csvLines.join('\n'), 'utf-8');
- console.log(`✅ Exported to: ${csvPath}`);
- console.log(' Send this file to translators and import results back.\n');
-
- console.log('=' .repeat(70));
- console.log('NEXT STEPS:');
- console.log('='.repeat(70));
- console.log('1. Translate the placeholder texts using one of the options above');
- console.log('2. Update the JSON files in public/locales/{lang}/');
- console.log('3. Run "bun run i18n:audit" to verify all translations');
- console.log('4. Commit the updated translation files\n');
-
- // Generate example of what translated file should look like
- console.log('EXAMPLE - Before and After:');
- console.log('-'.repeat(70));
- if (report.length > 0 && report[0].placeholders.size > 0) {
- const { lang, placeholders } = report[0];
- const namespace = [...placeholders.keys()][0];
- const entry = placeholders.get(namespace)[0];
-
- console.log(`\nFile: public/locales/${lang}/${namespace}.json`);
- console.log('\nBefore:');
- console.log(` "${entry.key}": "${entry.value}"`);
- console.log('\nAfter (example):');
- const cleanValue = entry.value.replace(`[${lang.toUpperCase()}] `, '');
- console.log(` "${entry.key}": "${cleanValue} in ${LANG_NAMES[lang]}"`);
- }
-
- console.log('\n✨ Ready to translate!\n');
-}
-
-// Run
-generateInstructions();
diff --git a/fincept-terminal-desktop/src-tauri/installer-hooks.nsh b/fincept-terminal-desktop/src-tauri/installer-hooks.nsh
deleted file mode 100644
index d2e7baadb..000000000
--- a/fincept-terminal-desktop/src-tauri/installer-hooks.nsh
+++ /dev/null
@@ -1,45 +0,0 @@
-; Fincept Terminal - NSIS Installer Hooks
-; Custom cleanup during uninstallation
-
-!macro NSIS_HOOK_PREINSTALL
- ; Hook executed before installation starts
- ; Add any pre-installation logic here if needed
-!macroend
-
-!macro NSIS_HOOK_POSTINSTALL
- ; Hook executed after installation completes
- ; Add any post-installation logic here if needed
-!macroend
-
-!macro NSIS_HOOK_PREUNINSTALL
- ; Hook executed before uninstallation starts
- ; This is where we clean up application data
-
- ; Remove AppData directory (user-specific data)
- RMDir /r "$APPDATA\com.fincept.terminal"
-
- ; Remove LocalAppData directory (cache, logs, databases)
- RMDir /r "$LOCALAPPDATA\com.fincept.terminal"
-
- ; Remove any configuration files
- Delete "$APPDATA\fincept-terminal.config"
-
- ; Clean up any temp files
- RMDir /r "$TEMP\fincept-terminal"
-
-!macroend
-
-!macro NSIS_HOOK_POSTUNINSTALL
- ; Hook executed after uninstallation completes
- ; Final cleanup after files are removed
-
- ; Remove any leftover registry keys (if any were created)
- DeleteRegKey HKCU "Software\Fincept Corporation\FinceptTerminal"
-
- ; Remove from Add/Remove Programs if any artifacts remain
- DeleteRegKey HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\FinceptTerminal"
-
- ; Show cleanup confirmation message
- MessageBox MB_OK "Fincept Terminal has been completely removed from your system.$\n$\nAll application data, settings, and cache files have been deleted."
-
-!macroend
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/=2.3.23 b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/=2.3.23
deleted file mode 100644
index 8f79623b2..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/=2.3.23
+++ /dev/null
@@ -1,34 +0,0 @@
-Defaulting to user installation because normal site-packages is not writeable
-Requirement already satisfied: agno in c:\users\tilak\appdata\roaming\python\python313\site-packages (2.3.12)
-Requirement already satisfied: docstring-parser in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (0.17.0)
-Requirement already satisfied: gitpython in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (3.1.44)
-Requirement already satisfied: h11>=0.16.0 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (0.16.0)
-Requirement already satisfied: httpx[http2] in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (0.28.1)
-Requirement already satisfied: packaging in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (25.0)
-Requirement already satisfied: pydantic-settings in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (2.10.1)
-Requirement already satisfied: pydantic in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (2.12.3)
-Requirement already satisfied: python-dotenv in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (1.2.1)
-Requirement already satisfied: python-multipart in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (0.0.20)
-Requirement already satisfied: pyyaml in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (6.0.2)
-Requirement already satisfied: rich in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (14.0.0)
-Requirement already satisfied: typer in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (0.19.2)
-Requirement already satisfied: typing-extensions in c:\users\tilak\appdata\roaming\python\python313\site-packages (from agno) (4.15.0)
-Requirement already satisfied: gitdb<5,>=4.0.1 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from gitpython->agno) (4.0.12)
-Requirement already satisfied: anyio in c:\users\tilak\appdata\roaming\python\python313\site-packages (from httpx[http2]->agno) (4.9.0)
-Requirement already satisfied: certifi in c:\users\tilak\appdata\roaming\python\python313\site-packages (from httpx[http2]->agno) (2025.11.12)
-Requirement already satisfied: httpcore==1.* in c:\users\tilak\appdata\roaming\python\python313\site-packages (from httpx[http2]->agno) (1.0.9)
-Requirement already satisfied: idna in c:\users\tilak\appdata\roaming\python\python313\site-packages (from httpx[http2]->agno) (3.11)
-Requirement already satisfied: h2<5,>=3 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from httpx[http2]->agno) (4.3.0)
-Requirement already satisfied: annotated-types>=0.6.0 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from pydantic->agno) (0.7.0)
-Requirement already satisfied: pydantic-core==2.41.4 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from pydantic->agno) (2.41.4)
-Requirement already satisfied: typing-inspection>=0.4.2 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from pydantic->agno) (0.4.2)
-Requirement already satisfied: markdown-it-py>=2.2.0 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from rich->agno) (3.0.0)
-Requirement already satisfied: pygments<3.0.0,>=2.13.0 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from rich->agno) (2.19.1)
-Requirement already satisfied: click>=8.0.0 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from typer->agno) (8.1.8)
-Requirement already satisfied: shellingham>=1.3.0 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from typer->agno) (1.5.4)
-Requirement already satisfied: colorama in c:\users\tilak\appdata\roaming\python\python313\site-packages (from click>=8.0.0->typer->agno) (0.4.6)
-Requirement already satisfied: smmap<6,>=3.0.1 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from gitdb<5,>=4.0.1->gitpython->agno) (5.0.2)
-Requirement already satisfied: hyperframe<7,>=6.1 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from h2<5,>=3->httpx[http2]->agno) (6.1.0)
-Requirement already satisfied: hpack<5,>=4.1 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from h2<5,>=3->httpx[http2]->agno) (4.1.0)
-Requirement already satisfied: mdurl~=0.1 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from markdown-it-py>=2.2.0->rich->agno) (0.1.2)
-Requirement already satisfied: sniffio>=1.1 in c:\users\tilak\appdata\roaming\python\python313\site-packages (from anyio->httpx[http2]->agno) (1.3.1)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py
index 9b8915240..42533cbaa 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py
@@ -64,18 +64,47 @@ class CoreAgent:
session_id: Optional[str] = None,
stream: bool = False
) -> Any:
- """Execute agent with given configuration."""
+ """
+ Execute agent with given configuration.
+
+ Args:
+ query: User query/prompt
+ config: Agent configuration dict containing:
+ - model: {provider, model_id, temperature, max_tokens}
+ - instructions: System prompt
+ - tools: List of tool names
+ - memory: Memory configuration (bool or dict)
+ - knowledge: Knowledge base configuration
+ - reasoning: Reasoning configuration (bool or dict)
+ - markdown: Output format
+ session_id: Session ID for memory persistence
+ stream: Enable streaming response
+
+ Returns:
+ Agent response
+ """
+ # Inject session_id into config for storage setup
+ if session_id:
+ config = {**config, "session_id": session_id}
+
+ # Recreate agent if config changed
if self._should_recreate_agent(config):
self._agent = self._create_agent(config)
self._current_config = config
- run_kwargs = {"input": query}
+ # Build run kwargs
+ run_kwargs = {"message": query} # Agno uses 'message' not 'input'
+
if session_id:
run_kwargs["session_id"] = session_id
+
if stream:
- run_kwargs["stream"] = stream
+ run_kwargs["stream"] = True
+ return self._agent.run(**run_kwargs)
- return self._agent.run(**run_kwargs)
+ # Non-streaming run
+ response = self._agent.run(**run_kwargs)
+ return response
def run_team(
self,
@@ -91,7 +120,12 @@ class CoreAgent:
agent = self._create_agent(agent_config)
agents.append(agent)
- team_module = TeamModule.from_config(team_config, agents)
+ # Create coordinator model from team_config if specified
+ coordinator_model = None
+ if team_config.get("model"):
+ coordinator_model = self._create_model(team_config["model"])
+
+ team_module = TeamModule.from_config(team_config, agents, model=coordinator_model)
return team_module.run(query, session_id=session_id)
def run_workflow(
@@ -388,11 +422,36 @@ class CoreAgent:
return True
return False
+ def _create_model(self, model_config: Dict[str, Any]) -> Any:
+ """Create a model instance from config (used for team coordinator)."""
+ from finagent_core.registries import ModelsRegistry
+ return ModelsRegistry.create_model(
+ provider=model_config.get("provider", "openai"),
+ model_id=model_config.get("model_id"),
+ api_keys=self.api_keys,
+ temperature=model_config.get("temperature"),
+ max_tokens=model_config.get("max_tokens"),
+ )
+
def _create_agent(self, config: Dict[str, Any]) -> Any:
- """Create Agno agent from config."""
+ """
+ Create Agno agent from config with full feature integration.
+
+ Supports all Agno Agent parameters:
+ - model: LLM model instance
+ - instructions: System prompt
+ - tools: List of Toolkit instances
+ - memory: Memory backend for persistence
+ - knowledge: Knowledge base for RAG
+ - reasoning: Extended thinking capabilities
+ - structured_outputs: Pydantic model outputs
+ """
from agno.agent import Agent
from finagent_core.registries import ModelsRegistry, ToolsRegistry
+ # =================================================================
+ # 1. Create Model
+ # =================================================================
model_config = config.get("model", {})
model = ModelsRegistry.create_model(
provider=model_config.get("provider", "openai"),
@@ -404,34 +463,172 @@ class CoreAgent:
agent_kwargs = {"model": model}
+ # =================================================================
+ # 2. Basic Identity
+ # =================================================================
if config.get("name"):
agent_kwargs["name"] = config["name"]
+ if config.get("role"):
+ agent_kwargs["role"] = config["role"]
+
+ if config.get("description"):
+ agent_kwargs["description"] = config["description"]
+
+ # =================================================================
+ # 3. Instructions
+ # =================================================================
instructions = config.get("instructions", "You are a helpful AI assistant.")
- if config.get("reasoning"):
- instructions = self._enhance_with_reasoning(instructions, config["reasoning"])
agent_kwargs["instructions"] = instructions
+ # =================================================================
+ # 4. Tools - Load and validate
+ # =================================================================
tool_names = config.get("tools", [])
if tool_names:
- tools = ToolsRegistry.get_tools(tool_names)
+ tools = ToolsRegistry.get_tools(tool_names, api_keys=self.api_keys)
if tools:
agent_kwargs["tools"] = tools
-
- if config.get("knowledge"):
- agent_kwargs.update(self._setup_knowledge(config["knowledge"]))
-
- if config.get("reasoning"):
+ else:
+ logger.warning(f"No tools loaded from: {tool_names}")
+
+ # =================================================================
+ # 5. Memory Integration
+ # =================================================================
+ memory_config = config.get("memory", {})
+ enable_memory = memory_config if isinstance(memory_config, bool) else memory_config.get("enabled", False)
+
+ if enable_memory:
+ agent_kwargs["enable_agentic_memory"] = True
+ agent_kwargs["add_memories_to_context"] = True
+
+ # Create memory backend if configured
+ memory_backend = self._create_memory_backend(memory_config)
+ if memory_backend:
+ agent_kwargs["memory"] = memory_backend
+
+ # =================================================================
+ # 6. Knowledge Base (RAG)
+ # =================================================================
+ knowledge_config = config.get("knowledge", {})
+ enable_knowledge = knowledge_config if isinstance(knowledge_config, bool) else bool(knowledge_config)
+
+ if enable_knowledge and isinstance(knowledge_config, dict):
+ knowledge_setup = self._setup_knowledge(knowledge_config)
+ agent_kwargs.update(knowledge_setup)
+ agent_kwargs["search_knowledge"] = True
+ agent_kwargs["add_knowledge_to_context"] = True
+
+ # =================================================================
+ # 7. Reasoning (Extended Thinking)
+ # =================================================================
+ reasoning_config = config.get("reasoning", {})
+ enable_reasoning = reasoning_config if isinstance(reasoning_config, bool) else reasoning_config.get("enabled", False)
+
+ if enable_reasoning:
agent_kwargs["reasoning"] = True
- if config.get("output_format") == "markdown":
+ # Optional: separate reasoning model
+ if isinstance(reasoning_config, dict):
+ if reasoning_config.get("min_steps"):
+ agent_kwargs["reasoning_min_steps"] = reasoning_config["min_steps"]
+ if reasoning_config.get("max_steps"):
+ agent_kwargs["reasoning_max_steps"] = reasoning_config["max_steps"]
+
+ # Create reasoning model if specified
+ if reasoning_config.get("model"):
+ reasoning_model = ModelsRegistry.create_model(
+ provider=reasoning_config["model"].get("provider", model_config.get("provider", "openai")),
+ model_id=reasoning_config["model"].get("model_id"),
+ api_keys=self.api_keys,
+ temperature=0.3, # Lower temperature for reasoning
+ )
+ agent_kwargs["reasoning_model"] = reasoning_model
+
+ # =================================================================
+ # 8. Structured Outputs
+ # =================================================================
+ if config.get("response_model"):
+ agent_kwargs["response_model"] = config["response_model"]
+ elif config.get("structured_outputs"):
+ agent_kwargs["structured_outputs"] = config["structured_outputs"]
+
+ # =================================================================
+ # 9. Output Settings
+ # =================================================================
+ if config.get("markdown", True):
agent_kwargs["markdown"] = True
if config.get("debug"):
agent_kwargs["debug_mode"] = True
+ if config.get("show_tool_calls"):
+ agent_kwargs["show_tool_calls"] = True
+
+ # =================================================================
+ # 10. Session/Storage for persistence
+ # =================================================================
+ if config.get("session_id") or config.get("storage"):
+ storage = self._create_storage(config)
+ if storage:
+ agent_kwargs["storage"] = storage
+
+ logger.debug(f"Creating agent with params: {list(agent_kwargs.keys())}")
return Agent(**agent_kwargs)
+ def _create_memory_backend(self, memory_config: Any) -> Optional[Any]:
+ """Create Agno memory backend."""
+ if isinstance(memory_config, bool):
+ return None
+
+ try:
+ from agno.memory import AgentMemory
+ from agno.memory.db.sqlite import SqliteMemoryDb
+
+ db_path = memory_config.get("db_path", "agent_memory.db")
+ table_name = memory_config.get("table_name", "agent_memory")
+
+ db = SqliteMemoryDb(
+ table_name=table_name,
+ db_file=db_path,
+ )
+
+ return AgentMemory(
+ db=db,
+ create_user_memories=memory_config.get("create_user_memories", True),
+ create_session_summary=memory_config.get("create_session_summary", True),
+ )
+ except ImportError as e:
+ logger.warning(f"Memory backend not available: {e}")
+ return None
+ except Exception as e:
+ logger.error(f"Failed to create memory backend: {e}")
+ return None
+
+ def _create_storage(self, config: Dict[str, Any]) -> Optional[Any]:
+ """Create storage backend for session persistence."""
+ try:
+ storage_config = config.get("storage", {})
+ storage_type = storage_config.get("type", "sqlite")
+
+ if storage_type == "sqlite":
+ from agno.storage.sqlite import SqliteStorage
+ return SqliteStorage(
+ table_name=storage_config.get("table_name", "agent_sessions"),
+ db_file=storage_config.get("db_path", "agent_storage.db"),
+ )
+ elif storage_type == "postgres":
+ from agno.storage.postgres import PostgresStorage
+ return PostgresStorage(
+ table_name=storage_config.get("table_name", "agent_sessions"),
+ db_url=storage_config.get("db_url"),
+ )
+ except ImportError as e:
+ logger.warning(f"Storage backend not available: {e}")
+ except Exception as e:
+ logger.error(f"Failed to create storage: {e}")
+ return None
+
def _setup_knowledge(self, knowledge_config: Dict[str, Any]) -> Dict[str, Any]:
"""Setup knowledge module."""
from finagent_core.modules import KnowledgeModule
@@ -529,197 +726,7 @@ class CoreAgentBuilder:
return self._config.copy()
-# =============================================================================
-# Entry Point - Single JSON Payload
-# =============================================================================
-def main(args=None):
- """
- Entry point - accepts single JSON payload from Rust/Tauri.
-
- Payload format:
- {
- "action": "run|run_team|run_workflow|...",
- "api_keys": {...},
- "user_id": "optional",
- "config": {...},
- "params": {...} // action-specific parameters
- }
- """
- import sys
- from pathlib import Path
-
- # Add parent directory to path for imports
- parent_dir = str(Path(__file__).parent.parent)
- if parent_dir not in sys.path:
- sys.path.insert(0, parent_dir)
-
- if args is None:
- args = sys.argv[1:]
-
- try:
- if len(args) == 0:
- return json.dumps({"success": False, "error": "No payload provided"})
-
- # Parse single JSON payload
- payload = json.loads(args[0])
- action = payload.get("action")
- api_keys = payload.get("api_keys", {})
- user_id = payload.get("user_id")
- config = payload.get("config", {})
- params = payload.get("params", {})
-
- if not action:
- return json.dumps({"success": False, "error": "Missing 'action' in payload"})
-
- # Create agent
- agent = CoreAgent(api_keys=api_keys, user_id=user_id)
-
- # Setup optional modules from config
- if config.get("guardrails"):
- agent.setup_guardrails(config["guardrails"])
- if config.get("tracing"):
- agent.setup_tracing(config["tracing"])
- if config.get("agentic_memory"):
- agent.setup_agentic_memory(config["agentic_memory"])
-
- # Dispatch action
- result = _dispatch_action(agent, action, config, params)
- return json.dumps(result)
-
- except json.JSONDecodeError as e:
- return json.dumps({"success": False, "error": f"Invalid JSON: {str(e)}"})
- except Exception as e:
- return json.dumps({"success": False, "error": str(e)})
-
-
-def _dispatch_action(agent: CoreAgent, action: str, config: Dict, params: Dict) -> Dict[str, Any]:
- """Dispatch action to appropriate agent method."""
-
- # Run single agent
- if action == "run":
- query = params.get("query")
- if not query:
- return {"success": False, "error": "Missing 'query' in params"}
-
- # Check guardrails if enabled
- if agent._guardrails:
- guard_result = agent.check_input(query)
- if not guard_result["passed"]:
- return {"success": False, "error": "Input rejected by guardrails", "violations": guard_result["violations"]}
- query = guard_result["text"]
-
- response = agent.run(query, config, params.get("session_id"))
- return {"success": True, "response": agent.get_response_content(response)}
-
- # Run with structured output
- if action == "run_structured":
- query = params.get("query")
- output_model = params.get("output_model")
- if not query or not output_model:
- return {"success": False, "error": "Missing 'query' or 'output_model' in params"}
- return agent.run_with_output_model(query, config, output_model, params.get("session_id"))
-
- # Run team
- if action == "run_team":
- query = params.get("query")
- team_config = params.get("team_config", config)
- if not query:
- return {"success": False, "error": "Missing 'query' in params"}
- response = agent.run_team(query, team_config, params.get("session_id"))
- return {"success": True, "response": agent.get_response_content(response)}
-
- # Run workflow
- if action == "run_workflow":
- workflow_config = params.get("workflow_config", config)
- input_data = params.get("input_data", {})
- result = agent.run_workflow(workflow_config, input_data)
- return {"success": True, "result": result if isinstance(result, dict) else str(result)}
-
- # Stock analysis
- if action == "stock_analysis":
- symbol = params.get("symbol")
- if not symbol:
- return {"success": False, "error": "Missing 'symbol' in params"}
- result = agent.run_stock_analysis(symbol, config)
- return {"success": True, "symbol": symbol, "result": result if isinstance(result, dict) else str(result)}
-
- # Portfolio rebalancing
- if action == "portfolio_rebal":
- portfolio_data = params.get("portfolio_data", params)
- result = agent.run_portfolio_rebalancing(portfolio_data, config)
- return {"success": True, "result": result if isinstance(result, dict) else str(result)}
-
- # Risk assessment
- if action == "risk_assessment":
- portfolio_data = params.get("portfolio_data", params)
- result = agent.run_risk_assessment(portfolio_data, config)
- return {"success": True, "result": result if isinstance(result, dict) else str(result)}
-
- # Search knowledge
- if action == "search":
- query = params.get("query")
- if not query:
- return {"success": False, "error": "Missing 'query' in params"}
- results = agent.search_knowledge(query, params.get("limit", 5))
- return {"success": True, "results": results, "count": len(results)}
-
- # Store memory
- if action == "store_memory":
- content = params.get("content")
- if not content:
- return {"success": False, "error": "Missing 'content' in params"}
- memory_id = agent.store_memory(content, params.get("type", "fact"), params.get("metadata"))
- return {"success": True, "memory_id": memory_id}
-
- # Recall memories
- if action == "recall_memories":
- memories = agent.recall_memories(params.get("query"), params.get("type"), params.get("limit", 5))
- return {"success": True, "memories": memories, "count": len(memories)}
-
- # Check guardrails
- if action == "check_guardrails":
- agent.setup_guardrails(config.get("guardrails"))
- if params.get("check_type") == "output":
- result = agent.check_output(params.get("output", {}))
- return {"success": True, "check_type": "output", **result}
- text = params.get("text")
- if not text:
- return {"success": False, "error": "Missing 'text' in params"}
- result = agent.check_input(text, params.get("context"))
- return {"success": True, "check_type": "input", **result}
-
- # Evaluate
- if action == "evaluate":
- agent.setup_evaluation(config.get("evaluation"))
- if params.get("type") == "prediction":
- result = agent.evaluate_prediction(params.get("prediction", {}), params.get("actual", {}))
- else:
- result = agent.evaluate_response(params.get("query", ""), params.get("response", ""), params.get("context"))
- return {"success": True, **result}
-
- # List tools
- if action == "list_tools":
- tools = agent.list_available_tools()
- return {"success": True, "tools": tools, "categories": list(tools.keys()), "total_count": sum(len(v) for v in tools.values())}
-
- # List models
- if action == "list_models":
- providers = agent.list_available_models()
- return {"success": True, "providers": providers, "count": len(providers)}
-
- # List output models
- if action == "list_outputs":
- models = agent.list_output_models()
- return {"success": True, "models": models, "count": len(models)}
-
- # System info
- if action == "system_info":
- return agent.get_system_info()
-
- return {"success": False, "error": f"Unknown action: {action}"}
-
-
-if __name__ == "__main__":
- result = main()
- print(result)
+# NOTE: All dispatch logic lives in finagent_core/main.py which is the
+# single entry point called by Rust/Tauri. Do not add a separate main()
+# here — it creates confusion and duplicated logic.
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py
index e5de47a9a..2a0855806 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py
@@ -35,6 +35,54 @@ if parent_dir not in sys.path:
DISCOVERY_TIMEOUT = 4.0
+def stream_print(chunk_type: str, content: str):
+ """Print a streaming chunk with immediate flush for real-time output"""
+ print(f"{chunk_type.upper()}: {content}", flush=True)
+
+
+def _setup_agent_modules(agent, config: Dict[str, Any], params: Dict[str, Any]):
+ """
+ Setup ALL optional CoreAgent modules from config/params.
+ This is the single place where every feature gets wired.
+ Called before any agent execution.
+ """
+ # Guardrails
+ guardrails_cfg = config.get("guardrails") or params.get("guardrails")
+ if guardrails_cfg:
+ cfg = guardrails_cfg if isinstance(guardrails_cfg, dict) else None
+ agent.setup_guardrails(cfg)
+
+ # Tracing
+ tracing_cfg = config.get("tracing") or params.get("tracing")
+ if tracing_cfg:
+ cfg = tracing_cfg if isinstance(tracing_cfg, dict) else None
+ agent.setup_tracing(cfg)
+
+ # Agentic Memory
+ agentic_memory_cfg = config.get("agentic_memory") or params.get("agentic_memory")
+ if agentic_memory_cfg:
+ cfg = agentic_memory_cfg if isinstance(agentic_memory_cfg, dict) else {"user_id": params.get("user_id", "default")}
+ agent.setup_agentic_memory(cfg)
+
+ # Compression
+ compression_cfg = config.get("compression") or params.get("compression")
+ if compression_cfg:
+ cfg = compression_cfg if isinstance(compression_cfg, dict) else None
+ agent.setup_compression(cfg)
+
+ # Hooks
+ hooks_cfg = config.get("hooks") or params.get("hooks")
+ if hooks_cfg:
+ cfg = hooks_cfg if isinstance(hooks_cfg, dict) else None
+ agent.setup_hooks(cfg)
+
+ # Evaluation
+ evaluation_cfg = config.get("evaluation") or params.get("evaluation")
+ if evaluation_cfg:
+ cfg = evaluation_cfg if isinstance(evaluation_cfg, dict) else None
+ agent.setup_evaluation(cfg)
+
+
def main(args=None):
"""
Main entry point - accepts single JSON payload from Rust/Tauri.
@@ -53,10 +101,19 @@ def main(args=None):
- Execution planner: create_plan, execute_plan, get_plan_status
- Paper trading: execute_trade, get_portfolio_value, get_positions_summary
- System: system_info, list_tools, list_models
+
+ Streaming mode:
+ - Pass --stream flag to enable streaming output
+ - Output format: "CHUNK_TYPE: content" with immediate flush
+ - Chunk types: THINKING, TOKEN, TOOL, TOOL_RESULT, ERROR, DONE
"""
if args is None:
args = sys.argv[1:]
+ # Check for streaming mode
+ streaming = "--stream" in args
+ args = [a for a in args if a != "--stream"]
+
try:
if len(args) == 0:
return json.dumps({"success": False, "error": "No payload provided"})
@@ -67,15 +124,30 @@ def main(args=None):
params = payload.get("params", {})
config = payload.get("config", {})
+ # Enable streaming in params if flag is set
+ if streaming:
+ params["stream"] = True
+
if not action:
return json.dumps({"success": False, "error": "Missing 'action' in payload"})
- result = dispatch_action(action, api_keys, params, config)
- return json.dumps(result)
+ if streaming:
+ # In streaming mode, dispatch_action_streaming handles output
+ result = dispatch_action_streaming(action, api_keys, params, config)
+ # Final JSON result
+ print(json.dumps(result), flush=True)
+ return ""
+ else:
+ result = dispatch_action(action, api_keys, params, config)
+ return json.dumps(result)
except json.JSONDecodeError as e:
+ if streaming:
+ stream_print("error", f"Invalid JSON: {str(e)}")
return json.dumps({"success": False, "error": f"Invalid JSON: {str(e)}"})
except Exception as e:
+ if streaming:
+ stream_print("error", str(e))
return json.dumps({"success": False, "error": str(e)})
@@ -99,26 +171,85 @@ def dispatch_action(
if action == "run":
from finagent_core.core_agent import CoreAgent
- agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+
query = params.get("query")
if not query:
return {"success": False, "error": "Missing 'query' in params"}
- response = agent.run(query, config, params.get("session_id"))
- return {"success": True, "response": agent.get_response_content(response)}
+
+ # Create agent with API keys and user context
+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+
+ # Setup ALL optional modules from config
+ _setup_agent_modules(agent, config, params)
+
+ # Check guardrails on input if enabled
+ if agent._guardrails:
+ guard_result = agent.check_input(query)
+ if not guard_result["passed"]:
+ return {"success": False, "error": "Input rejected by guardrails", "violations": guard_result["violations"]}
+ query = guard_result["text"]
+
+ # Merge params into config for full agent configuration
+ # Config can contain: model, instructions, tools, memory, knowledge, reasoning,
+ # guardrails, tracing, agentic_memory, compression, hooks, evaluation, storage
+ full_config = {**config}
+
+ # Allow params to override config
+ for key in ["model", "instructions", "tools", "knowledge", "storage"]:
+ if params.get(key):
+ full_config[key] = params[key]
+ for key in ["memory", "reasoning"]:
+ if params.get(key) is not None:
+ full_config[key] = params[key]
+
+ # Execute with session support
+ session_id = params.get("session_id")
+ stream = params.get("stream", False)
+
+ try:
+ # Start trace if tracing enabled
+ if agent._tracing:
+ agent.start_trace("agent_run", {"query": query[:100], "session_id": session_id})
+
+ response = agent.run(query, full_config, session_id, stream)
+ result = {"success": True, "response": agent.get_response_content(response)}
+
+ # Check guardrails on output if enabled
+ if agent._guardrails:
+ output_check = agent.check_output(result)
+ if not output_check.get("passed", True):
+ result["guardrail_warnings"] = output_check.get("warnings", [])
+
+ # End trace
+ if agent._tracing:
+ agent.end_trace()
+
+ return result
+ except Exception as e:
+ if agent._tracing:
+ agent.end_trace()
+ return {"success": False, "error": str(e)}
if action == "run_team":
from finagent_core.core_agent import CoreAgent
- agent = CoreAgent(api_keys=api_keys)
+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+ _setup_agent_modules(agent, config, params)
query = params.get("query")
team_config = params.get("team_config", config)
if not query:
return {"success": False, "error": "Missing 'query' in params"}
+ if agent._guardrails:
+ guard_result = agent.check_input(query)
+ if not guard_result["passed"]:
+ return {"success": False, "error": "Input rejected by guardrails", "violations": guard_result["violations"]}
+ query = guard_result["text"]
response = agent.run_team(query, team_config, params.get("session_id"))
return {"success": True, "response": agent.get_response_content(response)}
if action == "run_workflow":
from finagent_core.core_agent import CoreAgent
- agent = CoreAgent(api_keys=api_keys)
+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+ _setup_agent_modules(agent, config, params)
workflow_config = params.get("workflow_config", config)
input_data = params.get("input_data", {})
result = agent.run_workflow(workflow_config, input_data)
@@ -126,7 +257,8 @@ def dispatch_action(
if action == "run_structured":
from finagent_core.core_agent import CoreAgent
- agent = CoreAgent(api_keys=api_keys)
+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+ _setup_agent_modules(agent, config, params)
query = params.get("query")
output_model = params.get("output_model")
if not query or not output_model:
@@ -366,6 +498,102 @@ def dispatch_action(
]
}
+ # =========================================================================
+ # Financial Workflows (via CoreAgent)
+ # =========================================================================
+
+ if action == "stock_analysis":
+ from finagent_core.core_agent import CoreAgent
+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+ _setup_agent_modules(agent, config, params)
+ symbol = params.get("symbol")
+ if not symbol:
+ return {"success": False, "error": "Missing 'symbol' in params"}
+ result = agent.run_stock_analysis(symbol, config)
+ return {"success": True, "symbol": symbol, "result": result if isinstance(result, dict) else str(result)}
+
+ if action == "portfolio_rebal":
+ from finagent_core.core_agent import CoreAgent
+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+ _setup_agent_modules(agent, config, params)
+ portfolio_data = params.get("portfolio_data", params)
+ result = agent.run_portfolio_rebalancing(portfolio_data, config)
+ return {"success": True, "result": result if isinstance(result, dict) else str(result)}
+
+ if action == "risk_assessment":
+ from finagent_core.core_agent import CoreAgent
+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+ _setup_agent_modules(agent, config, params)
+ portfolio_data = params.get("portfolio_data", params)
+ result = agent.run_risk_assessment(portfolio_data, config)
+ return {"success": True, "result": result if isinstance(result, dict) else str(result)}
+
+ # =========================================================================
+ # Agent Memory (via CoreAgent module)
+ # =========================================================================
+
+ if action == "store_memory":
+ from finagent_core.core_agent import CoreAgent
+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+ agent.setup_agentic_memory(params.get("agentic_memory") or config.get("agentic_memory") or {"user_id": params.get("user_id", "default")})
+ content = params.get("content")
+ if not content:
+ return {"success": False, "error": "Missing 'content' in params"}
+ memory_id = agent.store_memory(content, params.get("type", "fact"), params.get("metadata"))
+ return {"success": True, "memory_id": memory_id}
+
+ if action == "recall_memories":
+ from finagent_core.core_agent import CoreAgent
+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+ agent.setup_agentic_memory(params.get("agentic_memory") or config.get("agentic_memory") or {"user_id": params.get("user_id", "default")})
+ memories = agent.recall_memories(params.get("query"), params.get("type"), params.get("limit", 5))
+ return {"success": True, "memories": memories, "count": len(memories)}
+
+ # =========================================================================
+ # Guardrails Check
+ # =========================================================================
+
+ if action == "check_guardrails":
+ from finagent_core.core_agent import CoreAgent
+ agent = CoreAgent(api_keys=api_keys)
+ agent.setup_guardrails(config.get("guardrails"))
+ if params.get("check_type") == "output":
+ result = agent.check_output(params.get("output", {}))
+ return {"success": True, "check_type": "output", **result}
+ text = params.get("text")
+ if not text:
+ return {"success": False, "error": "Missing 'text' in params"}
+ result = agent.check_input(text, params.get("context"))
+ return {"success": True, "check_type": "input", **result}
+
+ # =========================================================================
+ # Evaluation
+ # =========================================================================
+
+ if action == "evaluate":
+ from finagent_core.core_agent import CoreAgent
+ agent = CoreAgent(api_keys=api_keys)
+ agent.setup_evaluation(config.get("evaluation"))
+ if params.get("type") == "prediction":
+ result = agent.evaluate_prediction(params.get("prediction", {}), params.get("actual", {}))
+ else:
+ result = agent.evaluate_response(params.get("query", ""), params.get("response", ""), params.get("context"))
+ return {"success": True, **result}
+
+ # =========================================================================
+ # Knowledge Search
+ # =========================================================================
+
+ if action == "search_knowledge":
+ from finagent_core.core_agent import CoreAgent
+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+ _setup_agent_modules(agent, config, params)
+ query = params.get("query")
+ if not query:
+ return {"success": False, "error": "Missing 'query' in params"}
+ results = agent.search_knowledge(query, params.get("limit", 5))
+ return {"success": True, "results": results, "count": len(results)}
+
# =========================================================================
# System Information
# =========================================================================
@@ -405,6 +633,151 @@ def dispatch_action(
return {"success": False, "error": f"Unknown action: {action}"}
+def dispatch_action_streaming(
+ action: str,
+ api_keys: Dict[str, str],
+ params: Dict[str, Any],
+ config: Dict[str, Any]
+) -> Dict[str, Any]:
+ """
+ Dispatch action with streaming output.
+ Prints chunks in real-time for Rust to capture and emit via Tauri events.
+ """
+
+ # =========================================================================
+ # Streaming Agent Run
+ # =========================================================================
+
+ if action == "run":
+ from finagent_core.core_agent import CoreAgent
+ from finagent_core.core_agent_stream import StreamingCoreAgent
+
+ query = params.get("query")
+ if not query:
+ stream_print("error", "Missing 'query' in params")
+ return {"success": False, "error": "Missing 'query' in params"}
+
+ stream_print("thinking", "Initializing agent...")
+
+ # Create core agent for module setup
+ core_agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+
+ # Setup ALL optional modules
+ _setup_agent_modules(core_agent, config, params)
+
+ # Check guardrails on input
+ if core_agent._guardrails:
+ guard_result = core_agent.check_input(query)
+ if not guard_result["passed"]:
+ stream_print("error", "Input rejected by guardrails")
+ return {"success": False, "error": "Input rejected by guardrails", "violations": guard_result["violations"]}
+ query = guard_result["text"]
+
+ # Build config
+ full_config = {**config}
+ for key in ["model", "instructions", "tools", "knowledge", "storage"]:
+ if params.get(key):
+ full_config[key] = params[key]
+ for key in ["memory", "reasoning"]:
+ if params.get(key) is not None:
+ full_config[key] = params[key]
+
+ stream_print("thinking", f"Processing query: {query[:50]}...")
+
+ try:
+ # Start trace if enabled
+ if core_agent._tracing:
+ core_agent.start_trace("agent_run_streaming", {"query": query[:100]})
+
+ session_id = params.get("session_id")
+
+ # Use StreamingCoreAgent for real streaming
+ try:
+ streaming_agent = StreamingCoreAgent(
+ api_keys=api_keys,
+ user_id=params.get("user_id"),
+ stream_callback=lambda ct, c, m=None: stream_print(ct, c),
+ )
+ response = streaming_agent.run_streaming(query, full_config, session_id)
+ except Exception:
+ # Fallback to regular run with simulated streaming
+ response = core_agent.run(query, full_config, session_id, stream=False)
+ content = core_agent.get_response_content(response)
+ if content:
+ words = content.split()
+ chunk_size = 5
+ for i in range(0, len(words), chunk_size):
+ chunk = ' '.join(words[i:i+chunk_size])
+ stream_print("token", chunk)
+
+ if core_agent._tracing:
+ core_agent.end_trace()
+
+ stream_print("done", "completed")
+ resp_content = ""
+ if response:
+ resp_content = core_agent.get_response_content(response) if hasattr(response, 'content') else str(response)
+ return {"success": True, "response": resp_content}
+
+ except Exception as e:
+ if core_agent._tracing:
+ core_agent.end_trace()
+ stream_print("error", str(e))
+ return {"success": False, "error": str(e)}
+
+ if action == "run_team":
+ from finagent_core.core_agent import CoreAgent
+
+ query = params.get("query")
+ team_config = params.get("team_config", config)
+ if not query:
+ stream_print("error", "Missing 'query' in params")
+ return {"success": False, "error": "Missing 'query' in params"}
+
+ stream_print("thinking", "Initializing team...")
+
+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))
+ _setup_agent_modules(agent, config, params)
+
+ if agent._guardrails:
+ guard_result = agent.check_input(query)
+ if not guard_result["passed"]:
+ stream_print("error", "Input rejected by guardrails")
+ return {"success": False, "error": "Input rejected by guardrails", "violations": guard_result["violations"]}
+ query = guard_result["text"]
+
+ try:
+ members = team_config.get("members", [])
+ stream_print("thinking", f"Team has {len(members)} members")
+
+ for i, member in enumerate(members):
+ name = member.get("name", f"Agent {i+1}")
+ stream_print("thinking", f"Agent '{name}' processing...")
+
+ response = agent.run_team(query, team_config, params.get("session_id"))
+ content = agent.get_response_content(response)
+
+ if content:
+ words = content.split()
+ chunk_size = 5
+ for i in range(0, len(words), chunk_size):
+ chunk = ' '.join(words[i:i+chunk_size])
+ stream_print("token", chunk)
+
+ stream_print("done", "completed")
+ return {"success": True, "response": content}
+
+ except Exception as e:
+ stream_print("error", str(e))
+ return {"success": False, "error": str(e)}
+
+ # For non-streaming actions, fall back to regular dispatch
+ stream_print("thinking", f"Executing action: {action}")
+ result = dispatch_action(action, api_keys, params, config)
+ stream_print("done", "completed")
+ return result
+
+
if __name__ == "__main__":
result = main()
print(result)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/team_module.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/team_module.py
index 21fcb66cd..3eb18dde9 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/team_module.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/team_module.py
@@ -37,6 +37,9 @@ class TeamModule:
description: Optional[str] = None,
mode: str = "coordinate",
leader_agent: Optional[Any] = None,
+ model: Optional[Any] = None,
+ show_members_responses: bool = False,
+ leader_index: Optional[int] = None,
**kwargs
):
"""
@@ -47,12 +50,18 @@ class TeamModule:
description: Team description
mode: Coordination mode ('coordinate', 'route', 'collaborate')
leader_agent: Optional leader/coordinator agent
+ model: Coordinator model for team decisions
+ show_members_responses: Show individual member responses in output
+ leader_index: Index of the leader agent in the members list
**kwargs: Additional configuration
"""
self.name = name
self.description = description
self.mode = mode
self.leader_agent = leader_agent
+ self.model = model
+ self.show_members_responses = show_members_responses
+ self.leader_index = leader_index
self.config = kwargs
self._agents: List[Any] = []
@@ -118,6 +127,11 @@ class TeamModule:
# Agno Team uses 'members' not 'agents'
members = [info["agent"] for info in self._agents]
+ # If leader_index is set, pick that agent as leader
+ leader = self.leader_agent
+ if leader is None and self.leader_index is not None and 0 <= self.leader_index < len(members):
+ leader = members[self.leader_index]
+
team_kwargs = {
"members": members, # Required parameter
}
@@ -125,18 +139,38 @@ class TeamModule:
if self.name:
team_kwargs["name"] = self.name
+ # Add coordinator model (required for team to make decisions)
+ if self.model:
+ team_kwargs["model"] = self.model
+
+ # Show individual member responses
+ if self.show_members_responses:
+ team_kwargs["show_members_responses"] = True
+
# Add mode-specific configuration
- if self.mode == "route":
+ if self.mode == "coordinate":
+ # Default: leader delegates to chosen members
+ pass
+ elif self.mode == "route":
team_kwargs["respond_directly"] = False
elif self.mode == "collaborate":
team_kwargs["delegate_to_all_members"] = True
+ team_kwargs["share_member_interactions"] = True
+
+ # If a leader agent is specified, use its instructions/role for the team
+ # In Agno, the Team itself acts as the leader — members are workers
+ if leader:
+ if hasattr(leader, 'instructions') and leader.instructions:
+ team_kwargs["instructions"] = leader.instructions
+ if hasattr(leader, 'description') and leader.description:
+ team_kwargs["description"] = leader.description
self._team = Team(**team_kwargs)
# Register event handlers
self._register_event_handlers()
- logger.debug(f"Built team '{self.name}' with {len(members)} agents")
+ logger.debug(f"Built team '{self.name}' with {len(members)} agents, mode={self.mode}")
return self._team
except ImportError as e:
@@ -277,7 +311,8 @@ class TeamModule:
def from_config(
cls,
config: Dict[str, Any],
- agents: List[Any]
+ agents: List[Any],
+ model: Optional[Any] = None
) -> "TeamModule":
"""
Create TeamModule from configuration.
@@ -285,6 +320,7 @@ class TeamModule:
Args:
config: Team configuration
agents: List of Agno Agent instances
+ model: Optional coordinator model
Returns:
TeamModule instance
@@ -293,6 +329,9 @@ class TeamModule:
name=config.get("name", "Agent Team"),
description=config.get("description"),
mode=config.get("mode", "coordinate"),
+ model=model,
+ show_members_responses=config.get("show_members_responses", False),
+ leader_index=config.get("leader_index"),
)
for i, agent in enumerate(agents):
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/tools_registry.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/tools_registry.py
index 1cfeab31a..8db5c6905 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/tools_registry.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/tools_registry.py
@@ -220,14 +220,51 @@ class ToolsRegistry:
for tool_name, tool_path in tools.items():
cls._tool_map[tool_name] = tool_path
+ # Tools that require specific API keys
+ TOOL_API_KEY_MAP = {
+ "tavily": "TAVILY_API_KEY",
+ "exa": "EXA_API_KEY",
+ "serpapi": "SERPAPI_API_KEY",
+ "serper": "SERPER_API_KEY",
+ "bravesearch": "BRAVE_API_KEY",
+ "firecrawl": "FIRECRAWL_API_KEY",
+ "openweather": "OPENWEATHER_API_KEY",
+ "financial_datasets": "FINANCIAL_DATASETS_API_KEY",
+ "openbb": "OPENBB_API_KEY",
+ "github": "GITHUB_TOKEN",
+ "gitlab": "GITLAB_TOKEN",
+ "slack": "SLACK_BOT_TOKEN",
+ "discord": "DISCORD_BOT_TOKEN",
+ "telegram": "TELEGRAM_BOT_TOKEN",
+ "twilio": "TWILIO_API_KEY",
+ "resend": "RESEND_API_KEY",
+ "jira": "JIRA_API_TOKEN",
+ "linear": "LINEAR_API_KEY",
+ "notion": "NOTION_API_KEY",
+ "confluence": "CONFLUENCE_API_KEY",
+ "shopify": "SHOPIFY_API_KEY",
+ "zendesk": "ZENDESK_API_KEY",
+ "x": "X_API_KEY",
+ "apify": "APIFY_API_TOKEN",
+ "brightdata": "BRIGHTDATA_API_KEY",
+ "mem0": "MEM0_API_KEY",
+ "zep": "ZEP_API_KEY",
+ "replicate": "REPLICATE_API_TOKEN",
+ "fal": "FAL_API_KEY",
+ "eleven_labs": "ELEVEN_LABS_API_KEY",
+ "spotify": "SPOTIFY_API_KEY",
+ "google_maps": "GOOGLE_MAPS_API_KEY",
+ }
+
@classmethod
- def get_tool(cls, tool_name: str, **kwargs) -> Optional[Any]:
+ def get_tool(cls, tool_name: str, api_keys: Optional[Dict[str, str]] = None, **kwargs) -> Optional[Any]:
"""
- Get a tool instance by name.
+ Get a tool instance by name with proper API key injection.
Args:
tool_name: Name of the tool (e.g., 'yfinance', 'duckduckgo')
- **kwargs: Arguments to pass to tool constructor
+ api_keys: Dict of API keys to inject
+ **kwargs: Additional arguments to pass to tool constructor
Returns:
Tool instance or None if not available
@@ -238,9 +275,16 @@ class ToolsRegistry:
logger.warning(f"Tool '{tool_name}' not found in registry")
return None
- # Check cache first
- cache_key = f"{tool_name}_{hash(str(kwargs))}"
- if cache_key in cls._loaded_tools:
+ # Build tool kwargs with API keys
+ tool_kwargs = dict(kwargs)
+ if api_keys and tool_name in cls.TOOL_API_KEY_MAP:
+ api_key_name = cls.TOOL_API_KEY_MAP[tool_name]
+ if api_key_name in api_keys:
+ tool_kwargs["api_key"] = api_keys[api_key_name]
+
+ # Check cache (without API keys in cache key for security)
+ cache_key = tool_name
+ if cache_key in cls._loaded_tools and not tool_kwargs:
return cls._loaded_tools[cache_key]
try:
@@ -252,37 +296,56 @@ class ToolsRegistry:
module = importlib.import_module(module_path)
tool_class = getattr(module, class_name)
- # Instantiate tool
- tool_instance = tool_class(**kwargs) if kwargs else tool_class()
- cls._loaded_tools[cache_key] = tool_instance
+ # Instantiate tool with kwargs
+ tool_instance = tool_class(**tool_kwargs) if tool_kwargs else tool_class()
+
+ # Only cache tools without API keys
+ if not tool_kwargs:
+ cls._loaded_tools[cache_key] = tool_instance
logger.debug(f"Loaded tool: {tool_name}")
return tool_instance
except ImportError as e:
- logger.warning(f"Tool '{tool_name}' import failed: {e}")
+ logger.debug(f"Tool '{tool_name}' import failed (may not be installed): {e}")
return None
+ except TypeError as e:
+ # Try without kwargs if constructor doesn't accept them
+ try:
+ tool_instance = tool_class()
+ cls._loaded_tools[cache_key] = tool_instance
+ logger.debug(f"Loaded tool (no args): {tool_name}")
+ return tool_instance
+ except Exception:
+ logger.warning(f"Tool '{tool_name}' initialization failed: {e}")
+ return None
except Exception as e:
logger.error(f"Tool '{tool_name}' initialization failed: {e}")
return None
@classmethod
- def get_tools(cls, tool_names: List[str], **kwargs) -> List[Any]:
+ def get_tools(cls, tool_names: List[str], api_keys: Optional[Dict[str, str]] = None, **kwargs) -> List[Any]:
"""
- Get multiple tool instances.
+ Get multiple tool instances with API key injection.
Args:
tool_names: List of tool names
- **kwargs: Arguments to pass to tool constructors
+ api_keys: Dict of API keys for tools that need them
+ **kwargs: Additional arguments to pass to tool constructors
Returns:
List of tool instances (excludes None values)
"""
tools = []
for name in tool_names:
- tool = cls.get_tool(name, **kwargs)
+ tool = cls.get_tool(name, api_keys=api_keys, **kwargs)
if tool is not None:
tools.append(tool)
+
+ if len(tools) < len(tool_names):
+ loaded = [t.__class__.__name__ for t in tools]
+ logger.info(f"Loaded {len(tools)}/{len(tool_names)} tools: {loaded}")
+
return tools
@classmethod
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/main.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/main.py
index 49cb0d351..7dbee4a72 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/main.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/main.py
@@ -214,8 +214,8 @@ class RenaissanceTechnologiesSystem:
stat_arb_analysis = run_stat_arb_analysis(
ticker=ticker,
prices=inputs["prices"],
- intrinsic_estimates=None, # Would need analyst estimates
- peer_prices=None, # Would need peer selection
+ intrinsic_estimates=None, # TODO: Integrate analyst estimates API
+ peer_prices=None, # TODO: Integrate peer/sector data API
metrics=inputs["metrics"]
)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/ic_deliberation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/ic_deliberation.py
index 7e3bc1cd3..deba5cae7 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/ic_deliberation.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/ic_deliberation.py
@@ -135,6 +135,15 @@ class ICDeliberator:
"""
Perform full IC deliberation on a proposed trade.
"""
+ import logging
+ logger = logging.getLogger(__name__)
+
+ # Log LLM configuration being used
+ logger.info(f"=== IC DELIBERATION STARTING ===")
+ logger.info(f"Model Provider: {self.config.models.provider.value}")
+ logger.info(f"Model ID: {self.config.models.model_id}")
+ logger.info(f"Temperature: {self.config.models.temperature}")
+
ticker = signal.get("ticker", "UNKNOWN")
direction = signal.get("direction", "long")
signal_type = signal.get("signal_type", "unknown")
@@ -354,125 +363,182 @@ Overall Score: {evaluation.get('overall_score', 0):.0f}/100
cons: List[str],
precedents: List[Dict[str, Any]],
) -> List[ICMemberOpinion]:
- """Gather opinions from each IC member"""
+ """Gather opinions from each IC member using REAL Agno agents"""
+ import logging
+ from ..agents import (
+ create_investment_committee_chair,
+ create_research_lead,
+ create_risk_quant,
+ create_execution_trader,
+ create_portfolio_manager,
+ )
+
+ logger = logging.getLogger(__name__)
opinions = []
+ # Create actual agents for each IC member role
+ agent_creators = {
+ "Chief Investment Officer": create_investment_committee_chair,
+ "Research Lead": create_research_lead,
+ "Chief Risk Officer": create_risk_quant,
+ "Head of Trading": create_execution_trader,
+ "Portfolio Manager": create_portfolio_manager,
+ }
+
for member in self.ic_members:
- opinion = self._get_member_opinion(
- member, signal, evaluation, risk, sizing, pros, cons
+ role = member["role"]
+ perspective = member["perspective"]
+
+ # Get the agent creator
+ creator = agent_creators.get(role)
+ if not creator:
+ continue
+
+ # Create agent
+ logger.info(f"Creating agent for {role} using {self.config.models.provider.value}/{self.config.models.model_id}")
+ agent = creator(self.config)
+
+ # Build deliberation prompt
+ prompt = self._build_deliberation_prompt(
+ role, perspective, signal, evaluation, risk, sizing, pros, cons, precedents
)
+
+ # Get agent's opinion via LLM
+ opinion = await self._get_agent_opinion(agent, role, prompt, member["weight"])
opinions.append(opinion)
return opinions
- def _get_member_opinion(
+ def _build_deliberation_prompt(
self,
- member: Dict[str, Any],
+ role: str,
+ perspective: str,
signal: Dict[str, Any],
evaluation: Dict[str, Any],
risk: Dict[str, Any],
sizing: Dict[str, Any],
pros: List[str],
cons: List[str],
+ precedents: List[Dict[str, Any]],
+ ) -> str:
+ """Build deliberation prompt for agent"""
+ ticker = signal.get("ticker", "N/A")
+ direction = signal.get("direction", "N/A")
+ signal_type = signal.get("signal_type", "N/A")
+
+ precedent_text = "\n".join([
+ f" - {p.get('subject', 'N/A')}: {p.get('decision', 'N/A')} → {p.get('outcome', 'N/A')}"
+ for p in precedents[:3]
+ ]) if precedents else " - No similar precedents found"
+
+ return f"""# Investment Committee Deliberation
+
+You are participating in an IC meeting to decide on a proposed trade.
+
+**Your Role**: {role}
+**Your Focus**: {perspective}
+
+## Proposed Trade
+
+- **Ticker**: {ticker}
+- **Direction**: {direction.upper()}
+- **Signal Type**: {signal_type}
+- **P-value**: {signal.get('p_value', 1.0):.4f}
+- **Confidence**: {signal.get('confidence', 0):.1%}
+- **Expected Return**: {signal.get('expected_return_bps', 0):.0f} bps
+
+## Analysis Summary
+
+**Overall Score**: {evaluation.get('overall_score', 0)}/100
+**Statistical Quality**: {evaluation.get('statistical_quality', 'unknown')}
+
+**Risk Assessment**:
+- Risk Level: {risk.get('risk_level', 'unknown')}
+- VaR Utilization: {risk.get('var_utilization_pct', 0):.0f}%
+- Risk Flags: {', '.join(risk.get('risk_flags', [])) or 'None'}
+- Sector Concentration: {risk.get('sector_concentrations', {})}
+
+**Proposed Size**: {sizing.get('final_size_pct', 0):.2f}% of portfolio
+
+## Pros
+{chr(10).join([f'+ {p}' for p in pros]) or '+ None identified'}
+
+## Cons
+{chr(10).join([f'- {c}' for c in cons]) or '- None identified'}
+
+## Historical Precedents
+{precedent_text}
+
+## Your Task
+
+As the **{role}**, provide your vote and detailed rationale.
+
+**Respond EXACTLY in this format**:
+
+VOTE: [APPROVE/REJECT/CONDITIONAL/ABSTAIN]
+CONFIDENCE: [0-100]%
+RATIONALE:
+[Your detailed reasoning from your perspective as {role}]
+
+CONDITIONS (if CONDITIONAL):
+- [List specific conditions, or write "None" if APPROVE/REJECT]
+"""
+
+ async def _get_agent_opinion(
+ self,
+ agent,
+ role: str,
+ prompt: str,
+ weight: float,
) -> ICMemberOpinion:
- """Get opinion from a specific IC member based on their perspective"""
- role = member["role"]
- perspective = member["perspective"]
-
- # CIO focuses on overall fit
- if role == "Chief Investment Officer":
- overall_score = evaluation.get("overall_score", 50)
- if overall_score >= 70:
- vote = ICVote.APPROVE
- rationale = f"Strong overall signal (score={overall_score}), fits strategy"
- confidence = 0.8
- elif overall_score >= 50:
- vote = ICVote.CONDITIONAL
- rationale = f"Moderate signal (score={overall_score}), proceed with caution"
- confidence = 0.6
- conditions = ["Reduce size by 30%"]
- else:
- vote = ICVote.REJECT
- rationale = f"Weak signal (score={overall_score}), doesn't meet threshold"
- confidence = 0.7
- conditions = []
-
- # Research Lead focuses on statistical quality
- elif role == "Research Lead":
- p_value = signal.get("p_value", 1.0)
- if p_value < 0.01:
- vote = ICVote.APPROVE
- rationale = f"Excellent statistical significance (p={p_value:.4f})"
- confidence = 0.85
- elif p_value < 0.02:
- vote = ICVote.CONDITIONAL
- rationale = f"Borderline p-value ({p_value:.4f}), reduce size"
- confidence = 0.55
- else:
- vote = ICVote.REJECT
- rationale = f"Insufficient statistical significance (p={p_value:.4f})"
- confidence = 0.75
-
- # CRO focuses on risk
- elif role == "Chief Risk Officer":
- risk_level = risk.get("risk_level", "medium")
- risk_flags = risk.get("risk_flags", [])
- if risk_level == "low" and not risk_flags:
- vote = ICVote.APPROVE
- rationale = "Risk within acceptable limits"
- confidence = 0.8
- elif risk_level in ["high", "critical"]:
- vote = ICVote.REJECT
- rationale = f"Risk level {risk_level} is unacceptable: {', '.join(risk_flags[:2])}"
- confidence = 0.85
- else:
- vote = ICVote.CONDITIONAL
- rationale = f"Moderate risk, require monitoring: {', '.join(risk_flags[:1])}"
- confidence = 0.65
-
- # Head of Trading focuses on execution
- elif role == "Head of Trading":
- adv = signal.get("average_daily_volume", 1000000)
- size = sizing.get("final_notional", 0)
- if adv > 5000000 or size < adv * 0.01:
- vote = ICVote.APPROVE
- rationale = "Execution should be straightforward"
- confidence = 0.75
- else:
- vote = ICVote.CONDITIONAL
- rationale = "Need to use careful execution to minimize impact"
- confidence = 0.6
-
- # Portfolio Manager focuses on construction
- elif role == "Portfolio Manager":
- # Check correlation
- sector_concentration = risk.get("sector_concentrations", {})
- max_concentration = max(sector_concentration.values()) if sector_concentration else 0
- if max_concentration > 20:
- vote = ICVote.CONDITIONAL
- rationale = f"Sector concentration at {max_concentration:.0f}%, reduce size"
- confidence = 0.6
- else:
- vote = ICVote.APPROVE
- rationale = "Fits portfolio construction, good diversification"
- confidence = 0.7
+ """Get opinion from agent via LLM"""
+ import re
+
+ try:
+ # Run agent with deliberation prompt
+ response = agent.run(prompt)
+ response_text = response.content if hasattr(response, 'content') else str(response)
+
+ # Parse response
+ vote_match = re.search(r'VOTE:\s*(APPROVE|REJECT|CONDITIONAL|ABSTAIN)', response_text, re.IGNORECASE)
+ conf_match = re.search(r'CONFIDENCE:\s*(\d+)%?', response_text)
+ rationale_match = re.search(r'RATIONALE:\s*(.+?)(?=CONDITIONS:|$)', response_text, re.DOTALL | re.IGNORECASE)
+ conditions_match = re.search(r'CONDITIONS.*?:\s*(.+?)$', response_text, re.DOTALL | re.IGNORECASE)
+
+ # Extract values
+ vote_str = vote_match.group(1).upper() if vote_match else "ABSTAIN"
+ confidence = float(conf_match.group(1)) / 100 if conf_match else 0.5
+ rationale = rationale_match.group(1).strip() if rationale_match else "No rationale provided"
+ conditions_text = conditions_match.group(1).strip() if conditions_match else ""
+
+ # Parse vote
+ vote = ICVote.APPROVE if vote_str == "APPROVE" else \
+ ICVote.REJECT if vote_str == "REJECT" else \
+ ICVote.CONDITIONAL if vote_str == "CONDITIONAL" else \
+ ICVote.ABSTAIN
+
+ # Parse conditions
+ conditions = []
+ if vote == ICVote.CONDITIONAL and conditions_text and "none" not in conditions_text.lower():
+ conditions = [c.strip().lstrip('-•').strip() for c in conditions_text.split('\n') if c.strip()]
+
+ return ICMemberOpinion(
+ member_role=role,
+ vote=vote,
+ rationale=rationale[:500], # Truncate if too long
+ conditions=conditions,
+ confidence=confidence,
+ )
- else:
- vote = ICVote.ABSTAIN
- rationale = "No specific view"
- confidence = 0.5
-
- conditions = []
- if vote == ICVote.CONDITIONAL:
- conditions = ["Monitor closely", "Review at EOD"]
-
- return ICMemberOpinion(
- member_role=role,
- vote=vote,
- rationale=rationale,
- conditions=conditions,
- confidence=confidence,
- )
+ except Exception as e:
+ # Fallback if agent fails
+ return ICMemberOpinion(
+ member_role=role,
+ vote=ICVote.ABSTAIN,
+ rationale=f"Error getting opinion: {str(e)}",
+ conditions=[],
+ confidence=0.5,
+ )
def _tally_votes(
self,
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/rentech_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/rentech_cli.py
index 805674775..40273d99d 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/rentech_cli.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/rentech_cli.py
@@ -481,6 +481,10 @@ def run_ic_deliberation(json_str: str) -> str:
historical_decisions=historical_decisions,
))
+ # Get model config for response
+ from .config import get_config
+ cfg = get_config()
+
return success_response({
"deliberation_id": result.deliberation_id,
"subject": result.subject,
@@ -502,6 +506,11 @@ def run_ic_deliberation(json_str: str) -> str:
"pros": result.pros,
"cons": result.cons,
"reasoning_summary": result.reasoning_chain_summary,
+ "llm_config": {
+ "provider": cfg.models.provider.value,
+ "model_id": cfg.models.model_id,
+ "temperature": cfg.models.temperature,
+ },
}, f"IC Decision: {result.decision}")
except Exception as e:
@@ -568,17 +577,37 @@ def analyze_signal(json_str: str) -> str:
# Include IC deliberation if requested
if include_deliberation:
+ # Calculate p-value from statistical significance
+ p_value = 1 - (decision.signal_score / 10.0) # Convert 0-10 scale to p-value
+ p_value = max(0.001, min(0.5, p_value)) # Clamp between 0.001 and 0.5
+
delib_result = run_ic_deliberation(json.dumps({
"signal": {
"ticker": ticker,
"direction": decision.signal.value,
- "signal_type": "combined",
- "p_value": 0.01, # Placeholder
+ "signal_type": data.get("signal_type", "combined"),
+ "p_value": p_value, # Use calculated p-value
"confidence": decision.confidence / 100,
"expected_return_bps": decision.statistical_edge * 10000,
+ "average_daily_volume": 10_000_000, # TODO: Fetch from yfinance/market data API
+ },
+ "signal_evaluation": {
+ "statistical_quality": "good" if p_value < 0.02 else "moderate" if p_value < 0.05 else "weak",
+ "overall_score": decision.signal_score * 10, # Convert to 0-100 scale
+ },
+ "risk_assessment": {
+ "risk_level": "high" if decision.risk_score < 4 else "medium" if decision.risk_score < 7 else "low",
+ "var_utilization_pct": 50.0, # TODO: Calculate from portfolio VaR
+ "risk_flags": decision.risks,
+ "sector_concentrations": {}, # TODO: Calculate from portfolio holdings
},
"sizing_recommendation": {
"final_size_pct": decision.position_sizing.recommended_size_pct,
+ "final_notional": trade_value,
+ },
+ "market_context": {
+ "vix": 20.0, # TODO: Fetch real-time VIX from market data
+ "regime": "bullish" if decision.signal.value == "long" else "bearish" if decision.signal.value == "short" else "neutral",
},
}))
result["ic_deliberation"] = json.loads(delib_result).get("data", {})
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/analysis.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/analysis.py
index 9363d7553..6331a2264 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/analysis.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/analysis.py
@@ -103,6 +103,11 @@ def run_signal_analysis(
if roe:
factor_exposures["quality"] = max(-1, min(1, (roe - 0.1) / 0.2))
+ # Calculate p-value from statistical significance
+ # Convert stat_sig (0-1) to p-value (lower is better)
+ # stat_sig 0.9 -> p-value 0.01, stat_sig 0.5 -> p-value 0.5
+ p_value = max(0.001, 1 - stat_sig)
+
return {
"ticker": ticker,
"mean_reversion": {
@@ -132,6 +137,7 @@ def run_signal_analysis(
},
"aggregate_signal": max(-1, min(1, aggregate_signal)),
"statistical_significance": max(0, min(1, stat_sig)),
+ "p_value": p_value, # Add calculated p-value
"reasoning": _generate_signal_reasoning(
mean_reversion, momentum, regime, aggregate_signal, stat_sig
)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/__init__.py
new file mode 100644
index 000000000..652861391
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/__init__.py
@@ -0,0 +1 @@
+# Algo Trading Module
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.py
new file mode 100644
index 000000000..92e527620
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/algo_live_runner.py
@@ -0,0 +1,356 @@
+"""
+Algo Live Runner
+
+Long-running Python process spawned by Rust for strategy deployment.
+Reads candle_cache, evaluates conditions, generates trade signals.
+
+Usage:
+ python algo_live_runner.py --deploy-id <id> --strategy-id <id> --symbol <sym>
+ --provider <prov> --mode paper|live --timeframe <tf> --quantity <qty> --db <path>
+"""
+
+import json
+import sys
+import argparse
+import sqlite3
+import time
+import os
+import signal
+import uuid
+from datetime import datetime
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from condition_evaluator import load_candles_from_db, evaluate_condition_group
+
+# Graceful shutdown
+running = True
+
+def signal_handler(sig, frame):
+ global running
+ running = False
+
+signal.signal(signal.SIGTERM, signal_handler)
+signal.signal(signal.SIGINT, signal_handler)
+
+
+TIMEFRAME_SECONDS = {
+ '1m': 60, '3m': 180, '5m': 300, '10m': 600, '15m': 900,
+ '30m': 1800, '1h': 3600, '4h': 14400, '1d': 86400,
+}
+
+
+def load_strategy(db_path: str, strategy_id: str) -> dict:
+ """Load strategy conditions from algo_strategies table."""
+ conn = sqlite3.connect(db_path)
+ row = conn.execute(
+ "SELECT entry_conditions, exit_conditions, entry_logic, exit_logic, "
+ "stop_loss, take_profit, trailing_stop, trailing_stop_type "
+ "FROM algo_strategies WHERE id = ?",
+ (strategy_id,)
+ ).fetchone()
+ conn.close()
+
+ if not row:
+ return None
+
+ return {
+ 'entry_conditions': json.loads(row[0]),
+ 'exit_conditions': json.loads(row[1]),
+ 'entry_logic': row[2],
+ 'exit_logic': row[3],
+ 'stop_loss': row[4],
+ 'take_profit': row[5],
+ 'trailing_stop': row[6],
+ 'trailing_stop_type': row[7],
+ }
+
+
+def update_deployment_status(db_path: str, deploy_id: str, status: str, error: str = None):
+ """Update deployment status in DB."""
+ conn = sqlite3.connect(db_path)
+ if error:
+ conn.execute(
+ "UPDATE algo_deployments SET status = ?, error_message = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
+ (status, error, deploy_id)
+ )
+ else:
+ conn.execute(
+ "UPDATE algo_deployments SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
+ (status, deploy_id)
+ )
+ conn.commit()
+ conn.close()
+
+
+def update_metrics(db_path: str, deploy_id: str, metrics: dict):
+ """Update algo_metrics table."""
+ conn = sqlite3.connect(db_path)
+ conn.execute(
+ """INSERT INTO algo_metrics (deployment_id, total_pnl, unrealized_pnl, total_trades,
+ win_rate, max_drawdown, current_position_qty, current_position_side,
+ current_position_entry, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
+ ON CONFLICT(deployment_id) DO UPDATE SET
+ total_pnl = excluded.total_pnl,
+ unrealized_pnl = excluded.unrealized_pnl,
+ total_trades = excluded.total_trades,
+ win_rate = excluded.win_rate,
+ max_drawdown = excluded.max_drawdown,
+ current_position_qty = excluded.current_position_qty,
+ current_position_side = excluded.current_position_side,
+ current_position_entry = excluded.current_position_entry,
+ updated_at = CURRENT_TIMESTAMP""",
+ (deploy_id, metrics.get('total_pnl', 0), metrics.get('unrealized_pnl', 0),
+ metrics.get('total_trades', 0), metrics.get('win_rate', 0),
+ metrics.get('max_drawdown', 0), metrics.get('current_position_qty', 0),
+ metrics.get('current_position_side', ''), metrics.get('current_position_entry', 0))
+ )
+ conn.commit()
+ conn.close()
+
+
+def record_trade(db_path: str, deploy_id: str, symbol: str, side: str,
+ quantity: float, price: float, pnl: float, reason: str):
+ """Record a trade in algo_trades table."""
+ trade_id = f"trade-{uuid.uuid4()}"
+ conn = sqlite3.connect(db_path)
+ conn.execute(
+ "INSERT INTO algo_trades (id, deployment_id, symbol, side, quantity, price, pnl, signal_reason) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ (trade_id, deploy_id, symbol, side, quantity, price, pnl, reason)
+ )
+ conn.commit()
+ conn.close()
+ return trade_id
+
+
+def create_order_signal(db_path: str, deploy_id: str, symbol: str, side: str,
+ quantity: float, order_type: str = 'MARKET', price: float = None):
+ """Write an order signal for Rust to execute (live mode)."""
+ signal_id = f"signal-{uuid.uuid4()}"
+ conn = sqlite3.connect(db_path)
+ conn.execute(
+ "INSERT INTO algo_order_signals (id, deployment_id, symbol, side, quantity, order_type, price, status) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')",
+ (signal_id, deploy_id, symbol, side, quantity, order_type, price)
+ )
+ conn.commit()
+ conn.close()
+ return signal_id
+
+
+def get_current_price(db_path: str, symbol: str) -> float:
+ """Get latest price from strategy_price_cache."""
+ conn = sqlite3.connect(db_path)
+ row = conn.execute(
+ "SELECT price FROM strategy_price_cache WHERE symbol = ?",
+ (symbol,)
+ ).fetchone()
+ conn.close()
+ return row[0] if row else 0.0
+
+
+def check_risk_management(current_price: float, position: dict, strategy: dict) -> str:
+ """Check stop-loss, take-profit, trailing stop. Returns 'exit' reason or None."""
+ if not position or position['qty'] == 0:
+ return None
+
+ entry_price = position['entry']
+ side = position['side']
+
+ if side == 'BUY':
+ pnl_pct = (current_price - entry_price) / entry_price * 100
+ else:
+ pnl_pct = (entry_price - current_price) / entry_price * 100
+
+ # Stop loss
+ sl = strategy.get('stop_loss')
+ if sl and pnl_pct <= -abs(sl):
+ return f'stop_loss_hit ({pnl_pct:.2f}%)'
+
+ # Take profit
+ tp = strategy.get('take_profit')
+ if tp and pnl_pct >= abs(tp):
+ return f'take_profit_hit ({pnl_pct:.2f}%)'
+
+ # Trailing stop
+ ts = strategy.get('trailing_stop')
+ if ts and position.get('max_pnl_pct', 0) > 0:
+ if position['max_pnl_pct'] - pnl_pct >= abs(ts):
+ return f'trailing_stop_hit ({pnl_pct:.2f}%)'
+
+ return None
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Algo Live Runner')
+ parser.add_argument('--deploy-id', required=True)
+ parser.add_argument('--strategy-id', required=True)
+ parser.add_argument('--symbol', required=True)
+ parser.add_argument('--provider', default='')
+ parser.add_argument('--mode', default='paper', choices=['paper', 'live'])
+ parser.add_argument('--timeframe', default='5m')
+ parser.add_argument('--quantity', type=float, default=1.0)
+ 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")
+
+ # Load strategy
+ strategy = load_strategy(args.db, args.strategy_id)
+ if not strategy:
+ update_deployment_status(args.db, args.deploy_id, 'error', 'Strategy not found')
+ sys.exit(1)
+
+ update_deployment_status(args.db, args.deploy_id, 'running')
+
+ # Inject logic operators into condition lists
+ entry_conds = strategy['entry_conditions']
+ exit_conds = strategy['exit_conditions']
+
+ # State
+ position = {'qty': 0, 'side': '', 'entry': 0, 'max_pnl_pct': 0}
+ total_pnl = 0.0
+ total_trades = 0
+ winning_trades = 0
+ max_drawdown = 0.0
+ peak_pnl = 0.0
+ last_candle_time = 0
+
+ interval = TIMEFRAME_SECONDS.get(args.timeframe, 300)
+ check_interval = max(interval // 2, 5) # check at half the timeframe interval, min 5s
+
+ while running:
+ try:
+ # Load candles
+ df = load_candles_from_db(args.db, args.symbol, args.timeframe, limit=200)
+ if df.empty or len(df) < 10:
+ time.sleep(check_interval)
+ continue
+
+ # Check if we have new data
+ newest_time = int(df['open_time'].iloc[-1]) if 'open_time' in df.columns else 0
+ if newest_time == last_candle_time:
+ time.sleep(check_interval)
+ continue
+ last_candle_time = newest_time
+
+ current_price = get_current_price(args.db, args.symbol)
+ if current_price <= 0:
+ current_price = float(df['close'].iloc[-1])
+
+ # Check risk management first
+ if position['qty'] != 0:
+ # Update max P&L for trailing stop
+ if position['side'] == 'BUY':
+ pnl_pct = (current_price - position['entry']) / position['entry'] * 100
+ else:
+ pnl_pct = (position['entry'] - current_price) / position['entry'] * 100
+ position['max_pnl_pct'] = max(position.get('max_pnl_pct', 0), pnl_pct)
+
+ risk_exit = check_risk_management(current_price, position, strategy)
+ if risk_exit:
+ # Close position
+ pnl = (current_price - position['entry']) * position['qty'] if position['side'] == 'BUY' \
+ else (position['entry'] - current_price) * position['qty']
+
+ if args.mode == 'paper':
+ record_trade(args.db, args.deploy_id, args.symbol, 'SELL' if position['side'] == 'BUY' else 'BUY',
+ abs(position['qty']), current_price, pnl, risk_exit)
+ else:
+ create_order_signal(args.db, args.deploy_id, args.symbol,
+ 'SELL' if position['side'] == 'BUY' else 'BUY',
+ abs(position['qty']))
+
+ total_pnl += pnl
+ total_trades += 1
+ if pnl > 0:
+ winning_trades += 1
+ position = {'qty': 0, 'side': '', 'entry': 0, 'max_pnl_pct': 0}
+
+ # Evaluate conditions
+ if position['qty'] == 0:
+ # No position: check entry conditions
+ entry_result = evaluate_condition_group(entry_conds, df)
+ if entry_result['result']:
+ # Enter position
+ position = {
+ 'qty': args.quantity,
+ 'side': 'BUY',
+ 'entry': current_price,
+ 'max_pnl_pct': 0,
+ }
+
+ if args.mode == 'paper':
+ record_trade(args.db, args.deploy_id, args.symbol, 'BUY',
+ args.quantity, current_price, 0,
+ f'entry_signal: {json.dumps([d.get("indicator", "") for d in entry_result.get("details", [])])}')
+ else:
+ create_order_signal(args.db, args.deploy_id, args.symbol, 'BUY', args.quantity)
+
+ else:
+ # In position: check exit conditions
+ exit_result = evaluate_condition_group(exit_conds, df)
+ if exit_result['result']:
+ # Exit position
+ pnl = (current_price - position['entry']) * position['qty'] if position['side'] == 'BUY' \
+ else (position['entry'] - current_price) * position['qty']
+
+ if args.mode == 'paper':
+ record_trade(args.db, args.deploy_id, args.symbol,
+ 'SELL' if position['side'] == 'BUY' else 'BUY',
+ abs(position['qty']), current_price, pnl,
+ f'exit_signal: {json.dumps([d.get("indicator", "") for d in exit_result.get("details", [])])}')
+ else:
+ create_order_signal(args.db, args.deploy_id, args.symbol,
+ 'SELL' if position['side'] == 'BUY' else 'BUY',
+ abs(position['qty']))
+
+ total_pnl += pnl
+ total_trades += 1
+ if pnl > 0:
+ winning_trades += 1
+ position = {'qty': 0, 'side': '', 'entry': 0, 'max_pnl_pct': 0}
+
+ # Update metrics
+ unrealized = 0
+ if position['qty'] != 0:
+ if position['side'] == 'BUY':
+ unrealized = (current_price - position['entry']) * position['qty']
+ else:
+ unrealized = (position['entry'] - current_price) * position['qty']
+
+ # Track drawdown
+ current_equity = total_pnl + unrealized
+ if current_equity > peak_pnl:
+ peak_pnl = current_equity
+ dd = peak_pnl - current_equity
+ if dd > max_drawdown:
+ max_drawdown = dd
+
+ win_rate = (winning_trades / total_trades * 100) if total_trades > 0 else 0
+
+ update_metrics(args.db, args.deploy_id, {
+ 'total_pnl': total_pnl,
+ 'unrealized_pnl': unrealized,
+ 'total_trades': total_trades,
+ 'win_rate': win_rate,
+ 'max_drawdown': max_drawdown,
+ 'current_position_qty': position['qty'],
+ 'current_position_side': position['side'],
+ 'current_position_entry': position['entry'],
+ })
+
+ time.sleep(check_interval)
+
+ except Exception as e:
+ sys.stderr.write(f"[algo_runner] Error: {e}\n")
+ time.sleep(check_interval)
+
+ # Shutdown: update status
+ update_deployment_status(args.db, args.deploy_id, 'stopped')
+ sys.stderr.write(f"[algo_runner] Deployment {args.deploy_id} stopped\n")
+
+
+if __name__ == '__main__':
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/backtest_engine.py b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/backtest_engine.py
new file mode 100644
index 000000000..f4cb9aa0b
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/backtest_engine.py
@@ -0,0 +1,304 @@
+"""
+Backtest Engine — Walk-forward strategy backtester
+
+Fetches historical data via yfinance, walks through candles bar-by-bar,
+evaluates entry/exit conditions at each bar, and computes performance metrics.
+
+Usage:
+ python backtest_engine.py \
+ --symbol RELIANCE.NS \
+ --entry-conditions '[{"indicator":"RSI","params":{"period":14},"field":"value","operator":"crosses_below","value":30}]' \
+ --exit-conditions '[{"indicator":"RSI","params":{"period":14},"field":"value","operator":"crosses_above","value":70}]' \
+ --timeframe 1d \
+ --period 1y \
+ --stop-loss 3 \
+ --take-profit 5 \
+ --initial-capital 100000
+
+Output:
+ JSON with trades, equity curve, and performance metrics
+"""
+
+import json
+import sys
+import argparse
+import math
+import os
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from condition_evaluator import evaluate_condition_group
+
+# Minimum candles needed before we start evaluating (for indicator warmup)
+WARMUP_BARS = 50
+
+
+def fetch_historical_data(symbol: str, period: str, interval: str):
+ """Fetch OHLCV data via yfinance."""
+ try:
+ import yfinance as yf
+ ticker = yf.Ticker(symbol)
+ df = ticker.history(period=period, interval=interval)
+ if df.empty:
+ return None
+ # Normalize column names
+ df.columns = [c.lower() for c in df.columns]
+ # Ensure we have needed columns
+ for col in ['open', 'high', 'low', 'close', 'volume']:
+ if col not in df.columns:
+ return None
+ df = df[['open', 'high', 'low', 'close', 'volume']].reset_index(drop=True)
+ return df
+ except Exception as e:
+ print(json.dumps({'success': False, 'error': f'Failed to fetch data: {e}'}), flush=True)
+ sys.exit(1)
+
+
+def run_backtest(
+ df,
+ entry_conditions: list,
+ exit_conditions: list,
+ stop_loss_pct: float = 0,
+ take_profit_pct: float = 0,
+ initial_capital: float = 100000,
+):
+ """
+ Walk forward through candle data and generate trades.
+
+ Returns dict with trades, equity curve, and metrics.
+ """
+ trades = []
+ equity_curve = []
+ in_position = False
+ entry_price = 0.0
+ entry_bar = 0
+ capital = initial_capital
+ peak_capital = initial_capital
+ max_drawdown = 0.0
+
+ for i in range(WARMUP_BARS, len(df)):
+ # Use candles up to and including bar i
+ window = df.iloc[:i + 1].copy()
+ current_price = window['close'].iloc[-1]
+ current_bar = i
+
+ if not in_position:
+ # Check entry conditions
+ result = evaluate_condition_group(entry_conditions, window)
+ if result['result']:
+ in_position = True
+ entry_price = current_price
+ entry_bar = current_bar
+ else:
+ # Check risk management first
+ pnl_pct = ((current_price - entry_price) / entry_price) * 100
+
+ # Stop loss
+ if stop_loss_pct > 0 and pnl_pct <= -stop_loss_pct:
+ exit_price = current_price
+ pnl = exit_price - entry_price
+ capital += pnl
+ trades.append({
+ 'entry_bar': entry_bar,
+ 'exit_bar': current_bar,
+ 'entry_price': round(entry_price, 2),
+ 'exit_price': round(exit_price, 2),
+ 'pnl': round(pnl, 2),
+ 'pnl_pct': round(pnl_pct, 2),
+ 'reason': 'stop_loss',
+ 'bars_held': current_bar - entry_bar,
+ })
+ in_position = False
+ continue
+
+ # Take profit
+ if take_profit_pct > 0 and pnl_pct >= take_profit_pct:
+ exit_price = current_price
+ pnl = exit_price - entry_price
+ capital += pnl
+ trades.append({
+ 'entry_bar': entry_bar,
+ 'exit_bar': current_bar,
+ 'entry_price': round(entry_price, 2),
+ 'exit_price': round(exit_price, 2),
+ 'pnl': round(pnl, 2),
+ 'pnl_pct': round(pnl_pct, 2),
+ 'reason': 'take_profit',
+ 'bars_held': current_bar - entry_bar,
+ })
+ in_position = False
+ continue
+
+ # Check exit conditions
+ result = evaluate_condition_group(exit_conditions, window)
+ if result['result']:
+ exit_price = current_price
+ pnl = exit_price - entry_price
+ capital += pnl
+ trades.append({
+ 'entry_bar': entry_bar,
+ 'exit_bar': current_bar,
+ 'entry_price': round(entry_price, 2),
+ 'exit_price': round(exit_price, 2),
+ 'pnl': round(pnl, 2),
+ 'pnl_pct': round(pnl_pct, 2),
+ 'reason': 'exit_signal',
+ 'bars_held': current_bar - entry_bar,
+ })
+ in_position = False
+
+ # Track equity curve
+ unrealized = (current_price - entry_price) if in_position else 0
+ current_equity = capital + unrealized
+ equity_curve.append(round(current_equity, 2))
+
+ if current_equity > peak_capital:
+ peak_capital = current_equity
+ dd = ((peak_capital - current_equity) / peak_capital) * 100 if peak_capital > 0 else 0
+ if dd > max_drawdown:
+ max_drawdown = dd
+
+ # Close any open position at last bar
+ if in_position and len(df) > 0:
+ exit_price = df['close'].iloc[-1]
+ pnl = exit_price - entry_price
+ pnl_pct = ((exit_price - entry_price) / entry_price) * 100
+ capital += pnl
+ trades.append({
+ 'entry_bar': entry_bar,
+ 'exit_bar': len(df) - 1,
+ 'entry_price': round(entry_price, 2),
+ 'exit_price': round(exit_price, 2),
+ 'pnl': round(pnl, 2),
+ 'pnl_pct': round(pnl_pct, 2),
+ 'reason': 'end_of_data',
+ 'bars_held': len(df) - 1 - entry_bar,
+ })
+
+ # Compute metrics
+ total_trades = len(trades)
+ if total_trades == 0:
+ return {
+ 'trades': [],
+ 'equity_curve': equity_curve,
+ 'metrics': {
+ 'total_trades': 0,
+ 'win_rate': 0,
+ 'total_return': 0,
+ 'total_return_pct': 0,
+ 'max_drawdown': round(max_drawdown, 2),
+ 'avg_pnl': 0,
+ 'avg_bars_held': 0,
+ 'profit_factor': 0,
+ 'sharpe': 0,
+ },
+ }
+
+ wins = [t for t in trades if t['pnl'] > 0]
+ losses = [t for t in trades if t['pnl'] <= 0]
+ win_rate = (len(wins) / total_trades) * 100
+
+ total_return = capital - initial_capital
+ total_return_pct = (total_return / initial_capital) * 100
+
+ avg_pnl = sum(t['pnl'] for t in trades) / total_trades
+ avg_bars_held = sum(t['bars_held'] for t in trades) / total_trades
+
+ gross_profit = sum(t['pnl'] for t in wins) if wins else 0
+ gross_loss = abs(sum(t['pnl'] for t in losses)) if losses else 0
+ profit_factor = (gross_profit / gross_loss) if gross_loss > 0 else float('inf') if gross_profit > 0 else 0
+
+ # Simple Sharpe approximation (annualized using daily returns)
+ if len(equity_curve) > 1:
+ returns = []
+ for i in range(1, len(equity_curve)):
+ if equity_curve[i - 1] != 0:
+ returns.append((equity_curve[i] - equity_curve[i - 1]) / equity_curve[i - 1])
+ if returns:
+ mean_ret = sum(returns) / len(returns)
+ std_ret = (sum((r - mean_ret) ** 2 for r in returns) / len(returns)) ** 0.5
+ sharpe = (mean_ret / std_ret) * (252 ** 0.5) if std_ret > 0 else 0
+ else:
+ sharpe = 0
+ else:
+ sharpe = 0
+
+ # Cap profit_factor for JSON serialization
+ if math.isinf(profit_factor):
+ profit_factor = 999.99
+
+ return {
+ 'trades': trades,
+ 'equity_curve': equity_curve[-100:], # Last 100 points for chart
+ 'metrics': {
+ 'total_trades': total_trades,
+ 'winning_trades': len(wins),
+ 'losing_trades': len(losses),
+ 'win_rate': round(win_rate, 1),
+ 'total_return': round(total_return, 2),
+ 'total_return_pct': round(total_return_pct, 2),
+ 'max_drawdown': round(max_drawdown, 2),
+ 'avg_pnl': round(avg_pnl, 2),
+ 'avg_bars_held': round(avg_bars_held, 1),
+ 'profit_factor': round(profit_factor, 2),
+ 'sharpe': round(sharpe, 2),
+ },
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Backtest Engine')
+ parser.add_argument('--symbol', required=True, help='yfinance-compatible ticker (e.g. RELIANCE.NS)')
+ parser.add_argument('--entry-conditions', required=True, help='JSON entry conditions')
+ parser.add_argument('--exit-conditions', required=True, help='JSON exit conditions')
+ parser.add_argument('--timeframe', default='1d', help='Candle interval (1d, 1h, 5m, etc.)')
+ parser.add_argument('--period', default='1y', help='History period (1mo, 3mo, 6mo, 1y, 2y, 5y)')
+ parser.add_argument('--stop-loss', type=float, default=0, help='Stop loss percentage')
+ parser.add_argument('--take-profit', type=float, default=0, help='Take profit percentage')
+ parser.add_argument('--initial-capital', type=float, default=100000, help='Starting capital')
+ args = parser.parse_args()
+
+ try:
+ entry_conditions = json.loads(args.entry_conditions)
+ exit_conditions = json.loads(args.exit_conditions)
+ except json.JSONDecodeError as e:
+ print(json.dumps({'success': False, 'error': f'Invalid conditions JSON: {e}'}))
+ sys.exit(1)
+
+ # Fetch historical data
+ df = fetch_historical_data(args.symbol, args.period, args.timeframe)
+ if df is None or df.empty:
+ print(json.dumps({
+ 'success': False,
+ 'error': f'No historical data available for {args.symbol}'
+ }))
+ sys.exit(0)
+
+ if len(df) < WARMUP_BARS + 10:
+ print(json.dumps({
+ 'success': False,
+ 'error': f'Insufficient data ({len(df)} bars, need at least {WARMUP_BARS + 10})'
+ }))
+ sys.exit(0)
+
+ # Run backtest
+ result = run_backtest(
+ df=df,
+ entry_conditions=entry_conditions,
+ exit_conditions=exit_conditions,
+ stop_loss_pct=args.stop_loss,
+ take_profit_pct=args.take_profit,
+ initial_capital=args.initial_capital,
+ )
+
+ print(json.dumps({
+ 'success': True,
+ 'symbol': args.symbol,
+ 'timeframe': args.timeframe,
+ 'period': args.period,
+ 'total_bars': len(df),
+ **result,
+ }))
+
+
+if __name__ == '__main__':
+ 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.py
new file mode 100644
index 000000000..d542ddd57
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.py
@@ -0,0 +1,228 @@
+"""
+Condition Evaluator Engine
+
+Short-lived subprocess called from Rust. Evaluates condition groups against candle data.
+
+Usage:
+ python condition_evaluator.py --mode once --conditions <json> --symbol <sym> --timeframe <tf> --db <path>
+
+Input conditions JSON format:
+ [
+ {"indicator":"RSI","params":{"period":14},"field":"value","operator":"crosses_below","value":30},
+ "AND",
+ {"indicator":"MACD","params":{"fast":12,"slow":26,"signal":9},"field":"histogram","operator":">","value":0}
+ ]
+
+Output:
+ {"success": true, "result": true/false, "details": [...]}
+"""
+
+import json
+import sys
+import argparse
+import sqlite3
+import pandas as pd
+import math
+import os
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from indicators import get_latest_value, get_last_n_values
+
+
+def load_candles_from_db(db_path: str, symbol: str, timeframe: str, limit: int = 200) -> pd.DataFrame:
+ """Load candles from candle_cache table."""
+ conn = sqlite3.connect(db_path)
+ query = """
+ SELECT open_time, o, h, l, c, volume
+ FROM candle_cache
+ WHERE symbol = ? AND timeframe = ? AND is_closed = 1
+ ORDER BY open_time ASC
+ LIMIT ?
+ """
+ df = pd.read_sql_query(query, conn, params=(symbol, timeframe, limit))
+ conn.close()
+
+ if df.empty:
+ return pd.DataFrame(columns=['open', 'high', 'low', 'close', 'volume'])
+
+ df.rename(columns={'o': 'open', 'h': 'high', 'l': 'low', 'c': 'close'}, inplace=True)
+ return df
+
+
+def evaluate_single_condition(condition: dict, df: pd.DataFrame) -> dict:
+ """
+ Evaluate a single condition against candle data.
+
+ Returns: {"met": bool, "indicator": str, "field": str, "computed_value": float, "operator": str, "target": float}
+ """
+ indicator = condition.get('indicator', '')
+ params = condition.get('params', {})
+ field = condition.get('field', 'value')
+ operator = condition.get('operator', '>')
+ target_value = condition.get('value', 0)
+ target_value2 = condition.get('value2', None)
+
+ try:
+ if operator in ('crosses_above', 'crosses_below'):
+ # Need last 2 values for crossing detection
+ values = get_last_n_values(indicator, df, params, field, n=2)
+ if len(values) < 2 or any(math.isnan(v) for v in values):
+ return {
+ 'met': False,
+ 'indicator': indicator,
+ 'field': field,
+ 'computed_value': values[-1] if values else None,
+ 'operator': operator,
+ 'target': target_value,
+ 'error': 'Insufficient data for crossing detection'
+ }
+
+ prev_val, curr_val = values
+ if operator == 'crosses_above':
+ met = prev_val <= target_value and curr_val > target_value
+ else:
+ met = prev_val >= target_value and curr_val < target_value
+
+ return {
+ 'met': met,
+ 'indicator': indicator,
+ 'field': field,
+ 'computed_value': curr_val,
+ 'prev_value': prev_val,
+ 'operator': operator,
+ 'target': target_value,
+ }
+ else:
+ current_value = get_latest_value(indicator, df, params, field)
+
+ if math.isnan(current_value):
+ return {
+ 'met': False,
+ 'indicator': indicator,
+ 'field': field,
+ 'computed_value': None,
+ 'operator': operator,
+ 'target': target_value,
+ 'error': 'Indicator returned NaN'
+ }
+
+ if operator == '>':
+ met = current_value > target_value
+ elif operator == '<':
+ met = current_value < target_value
+ elif operator == '>=':
+ met = current_value >= target_value
+ elif operator == '<=':
+ met = current_value <= target_value
+ elif operator == '==':
+ met = abs(current_value - target_value) < 0.0001
+ elif operator == 'between':
+ if target_value2 is not None:
+ met = target_value <= current_value <= target_value2
+ else:
+ met = False
+ else:
+ met = False
+
+ return {
+ 'met': met,
+ 'indicator': indicator,
+ 'field': field,
+ 'computed_value': current_value,
+ 'operator': operator,
+ 'target': target_value,
+ }
+
+ except Exception as e:
+ return {
+ 'met': False,
+ 'indicator': indicator,
+ 'field': field,
+ 'computed_value': None,
+ 'operator': operator,
+ 'target': target_value,
+ 'error': str(e)
+ }
+
+
+def evaluate_condition_group(conditions: list, df: pd.DataFrame) -> dict:
+ """
+ Evaluate a flat list of conditions with AND/OR logic.
+
+ conditions format: [condition_dict, "AND"/"OR", condition_dict, ...]
+ If no logic operators, default is AND.
+ """
+ if not conditions:
+ return {'result': False, 'details': [], 'logic': 'AND'}
+
+ # Parse into conditions and logic
+ condition_items = []
+ logic = 'AND' # default
+
+ for item in conditions:
+ if isinstance(item, str) and item.upper() in ('AND', 'OR'):
+ logic = item.upper()
+ elif isinstance(item, dict):
+ condition_items.append(item)
+
+ if not condition_items:
+ return {'result': False, 'details': [], 'logic': logic}
+
+ details = []
+ for cond in condition_items:
+ result = evaluate_single_condition(cond, df)
+ details.append(result)
+
+ met_results = [d['met'] for d in details]
+
+ if logic == 'AND':
+ overall = all(met_results)
+ else:
+ overall = any(met_results)
+
+ return {
+ 'result': overall,
+ 'details': details,
+ 'logic': logic,
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Condition Evaluator')
+ parser.add_argument('--mode', default='once', choices=['once'])
+ parser.add_argument('--conditions', required=True, help='JSON conditions array')
+ parser.add_argument('--symbol', required=True)
+ parser.add_argument('--timeframe', default='5m')
+ parser.add_argument('--db', required=True, help='SQLite database path')
+ parser.add_argument('--limit', type=int, default=200)
+ args = parser.parse_args()
+
+ try:
+ conditions = json.loads(args.conditions)
+ except json.JSONDecodeError as e:
+ print(json.dumps({'success': False, 'error': f'Invalid conditions JSON: {e}'}))
+ sys.exit(1)
+
+ # Load candle data
+ df = load_candles_from_db(args.db, args.symbol, args.timeframe, args.limit)
+ if df.empty or len(df) < 5:
+ print(json.dumps({
+ 'success': False,
+ 'error': f'Insufficient candle data for {args.symbol} ({len(df)} candles)'
+ }))
+ sys.exit(0)
+
+ # Evaluate conditions
+ result = evaluate_condition_group(conditions, df)
+
+ print(json.dumps({
+ 'success': True,
+ 'symbol': args.symbol,
+ 'timeframe': args.timeframe,
+ 'candle_count': len(df),
+ **result,
+ }))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/indicators.py b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/indicators.py
new file mode 100644
index 000000000..97a109174
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/indicators.py
@@ -0,0 +1,210 @@
+"""
+Unified Indicator Wrapper for Algo Trading
+
+Single entry point: compute_indicator(name, df, params) -> dict of field_name: series
+Reuses existing technicals library (ta-based indicators).
+"""
+
+import pandas as pd
+import numpy as np
+import sys
+import os
+
+# Add parent to path so we can import technicals
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from technicals.momentum_indicators import (
+ calculate_rsi, calculate_stochastic, calculate_williams_r, calculate_roc
+)
+from technicals.trend_indicators import (
+ calculate_sma, calculate_ema, calculate_macd, calculate_cci, calculate_adx
+)
+from technicals.volatility_indicators import (
+ calculate_atr, calculate_bollinger_bands, calculate_keltner_channel, calculate_donchian_channel
+)
+from technicals.volume_indicators import calculate_obv
+
+
+def compute_indicator(name: str, df: pd.DataFrame, params: dict) -> dict:
+ """
+ Compute a technical indicator and return its fields as a dict of Series.
+
+ Args:
+ name: Indicator name (case-insensitive), e.g. 'RSI', 'MACD', 'SMA'
+ df: DataFrame with columns: open, high, low, close, volume
+ params: Indicator parameters, e.g. {'period': 14}
+
+ Returns:
+ Dict mapping field names to pd.Series, e.g. {'value': Series([...])}
+ """
+ name = name.upper()
+
+ if name == 'RSI':
+ period = params.get('period', 14)
+ series = calculate_rsi(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'SMA':
+ period = params.get('period', 20)
+ series = calculate_sma(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'EMA':
+ period = params.get('period', 12)
+ series = calculate_ema(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'MACD':
+ fast = params.get('fast', 12)
+ slow = params.get('slow', 26)
+ signal = params.get('signal', 9)
+ result = calculate_macd(df, window_fast=fast, window_slow=slow, window_sign=signal, fillna=True)
+ return {
+ 'line': result['macd'],
+ 'signal_line': result['macd_signal'],
+ 'histogram': result['macd_diff'],
+ }
+
+ elif name == 'BOLLINGER' or name == 'BB':
+ period = params.get('period', 20)
+ std_dev = params.get('std_dev', 2)
+ result = calculate_bollinger_bands(df, window=period, window_dev=std_dev, fillna=True)
+ # Calculate %B
+ upper = result['bb_upper']
+ lower = result['bb_lower']
+ close = df['close']
+ pct_b = (close - lower) / (upper - lower)
+ return {
+ 'upper': upper,
+ 'middle': result['bb_middle'],
+ 'lower': lower,
+ 'pct_b': pct_b,
+ }
+
+ elif name == 'ATR':
+ period = params.get('period', 14)
+ series = calculate_atr(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'ADX':
+ period = params.get('period', 14)
+ result = calculate_adx(df, window=period, fillna=True)
+ return {
+ 'value': result['adx'],
+ 'plus_di': result['adx_pos'],
+ 'minus_di': result['adx_neg'],
+ }
+
+ elif name == 'CCI':
+ period = params.get('period', 20)
+ series = calculate_cci(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'OBV':
+ series = calculate_obv(df, fillna=True)
+ return {'value': series}
+
+ elif name == 'WILLIAMS_R' or name == 'WILLR':
+ period = params.get('period', 14)
+ series = calculate_williams_r(df, lbp=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'STOCHASTIC' or name == 'STOCH':
+ period = params.get('period', 14)
+ smooth = params.get('smooth', 3)
+ result = calculate_stochastic(df, window=period, smooth_window=smooth, fillna=True)
+ return {
+ 'k': result['stoch_k'],
+ 'd': result['stoch_d'],
+ }
+
+ elif name == 'ROC' or name == 'MOMENTUM':
+ period = params.get('period', 12)
+ series = calculate_roc(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'KELTNER':
+ period = params.get('period', 20)
+ result = calculate_keltner_channel(df, window=period, fillna=True)
+ return {
+ 'upper': result['kc_upper'],
+ 'middle': result['kc_middle'],
+ 'lower': result['kc_lower'],
+ }
+
+ elif name == 'DONCHIAN':
+ period = params.get('period', 20)
+ result = calculate_donchian_channel(df, window=period, fillna=True)
+ return {
+ 'upper': result['dc_upper'],
+ 'middle': result['dc_middle'],
+ 'lower': result['dc_lower'],
+ }
+
+ elif name == 'SUPERTREND':
+ period = params.get('period', 10)
+ multiplier = params.get('multiplier', 3.0)
+ atr = calculate_atr(df, window=period, fillna=True)
+ hl2 = (df['high'] + df['low']) / 2
+ upper_band = hl2 + multiplier * atr
+ lower_band = hl2 - multiplier * atr
+ supertrend = pd.Series(index=df.index, dtype=float)
+ direction = pd.Series(1, index=df.index, dtype=int)
+ supertrend.iloc[0] = lower_band.iloc[0]
+ for i in range(1, len(df)):
+ if df['close'].iloc[i] > upper_band.iloc[i - 1]:
+ direction.iloc[i] = 1
+ elif df['close'].iloc[i] < lower_band.iloc[i - 1]:
+ direction.iloc[i] = -1
+ else:
+ direction.iloc[i] = direction.iloc[i - 1]
+ if direction.iloc[i] == 1:
+ supertrend.iloc[i] = max(lower_band.iloc[i], supertrend.iloc[i - 1]) if direction.iloc[i - 1] == 1 else lower_band.iloc[i]
+ else:
+ supertrend.iloc[i] = min(upper_band.iloc[i], supertrend.iloc[i - 1]) if direction.iloc[i - 1] == -1 else upper_band.iloc[i]
+ return {
+ 'value': supertrend,
+ 'direction': direction,
+ }
+
+ elif name == 'VWAP':
+ typical_price = (df['high'] + df['low'] + df['close']) / 3
+ cumulative_tp_vol = (typical_price * df['volume']).cumsum()
+ cumulative_vol = df['volume'].cumsum()
+ vwap = cumulative_tp_vol / cumulative_vol
+ return {'value': vwap}
+
+ elif name == 'PRICE':
+ return {'value': df['close']}
+
+ elif name == 'VOLUME':
+ return {'value': df['volume']}
+
+ elif name == 'CHANGE_PCT':
+ pct = df['close'].pct_change() * 100
+ return {'value': pct.fillna(0)}
+
+ else:
+ raise ValueError(f"Unknown indicator: {name}")
+
+
+def get_latest_value(name: str, df: pd.DataFrame, params: dict, field: str = 'value') -> float:
+ """Get the most recent value of an indicator field."""
+ result = compute_indicator(name, df, params)
+ if field not in result:
+ raise ValueError(f"Indicator {name} has no field '{field}'. Available: {list(result.keys())}")
+ series = result[field]
+ val = series.iloc[-1]
+ if pd.isna(val):
+ return float('nan')
+ return float(val)
+
+
+def get_last_n_values(name: str, df: pd.DataFrame, params: dict, field: str = 'value', n: int = 2) -> list:
+ """Get the last N values of an indicator field (for crossing detection)."""
+ result = compute_indicator(name, df, params)
+ if field not in result:
+ raise ValueError(f"Indicator {name} has no field '{field}'. Available: {list(result.keys())}")
+ series = result[field]
+ values = series.iloc[-n:].tolist()
+ return [float(v) if not pd.isna(v) else float('nan') for v in values]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/scanner_engine.py b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/scanner_engine.py
new file mode 100644
index 000000000..3c3056986
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/scanner_engine.py
@@ -0,0 +1,78 @@
+"""
+Scanner Engine
+
+One-shot scanner: evaluates conditions across multiple symbols.
+Returns list of symbols that match the given conditions.
+
+Usage:
+ python scanner_engine.py --conditions <json> --symbols <json_array> --timeframe <tf> --db <path>
+"""
+
+import json
+import sys
+import argparse
+import sqlite3
+import os
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from condition_evaluator import load_candles_from_db, evaluate_condition_group
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Algo Scanner Engine')
+ parser.add_argument('--conditions', required=True, help='JSON conditions array')
+ parser.add_argument('--symbols', required=True, help='JSON array of symbols')
+ parser.add_argument('--timeframe', default='5m')
+ parser.add_argument('--db', required=True, help='SQLite database path')
+ parser.add_argument('--limit', type=int, default=200)
+ args = parser.parse_args()
+
+ try:
+ conditions = json.loads(args.conditions)
+ symbols = json.loads(args.symbols)
+ except json.JSONDecodeError as e:
+ print(json.dumps({'success': False, 'error': f'Invalid JSON: {e}'}))
+ sys.exit(1)
+
+ if not isinstance(symbols, list) or not symbols:
+ print(json.dumps({'success': False, 'error': 'symbols must be a non-empty array'}))
+ sys.exit(1)
+
+ matches = []
+ errors = []
+ scanned = 0
+
+ for symbol in symbols:
+ scanned += 1
+ try:
+ df = load_candles_from_db(args.db, symbol, args.timeframe, args.limit)
+ if df.empty or len(df) < 10:
+ errors.append({'symbol': symbol, 'error': f'Insufficient data ({len(df)} candles)'})
+ continue
+
+ result = evaluate_condition_group(conditions, df)
+
+ if result['result']:
+ # Get current price from last candle
+ current_price = float(df['close'].iloc[-1])
+ matches.append({
+ 'symbol': symbol,
+ 'price': current_price,
+ 'details': result['details'],
+ })
+
+ except Exception as e:
+ errors.append({'symbol': symbol, 'error': str(e)})
+
+ print(json.dumps({
+ 'success': True,
+ 'matches': matches,
+ 'match_count': len(matches),
+ 'scanned': scanned,
+ 'errors': errors,
+ 'timeframe': args.timeframe,
+ }))
+
+
+if __name__ == '__main__':
+ main()
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.py
index 81dcb756a..b20b24745 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
@@ -145,12 +145,14 @@ class BaseTradingAgent(BaseAgent):
instructions: Optional[List[str]] = None,
enable_features: bool = True,
enable_metrics: bool = True,
+ initial_capital: float = 10000.0,
):
super().__init__(name)
self.provider = provider
self.model_id = model_id
self.api_key = api_key
self.temperature = temperature
+ self.initial_capital = initial_capital
self.instructions = instructions or self._default_instructions()
self._agent = None
self._decisions: List[ModelDecision] = []
@@ -325,8 +327,9 @@ class LLMTradingAgent(BaseTradingAgent):
mode: str = "baseline",
trading_style: Optional[str] = None, # Style ID (e.g., "aggressive", "conservative")
style_config: Optional[Dict[str, Any]] = None, # Full style configuration
+ initial_capital: float = 10000.0,
):
- super().__init__(name, provider, model_id, api_key, temperature, instructions)
+ super().__init__(name, provider, model_id, api_key, temperature, instructions, initial_capital=initial_capital)
self.mode = mode
self._llm = None
@@ -362,20 +365,32 @@ class LLMTradingAgent(BaseTradingAgent):
async def initialize(self) -> bool:
"""Initialize the LLM agent."""
+ self._mock_reason = None # Track why we're in mock mode
try:
self._llm = await self._create_llm()
if self._llm is None:
- logger.warning(f"LLM agent '{self.name}' initialized in mock mode (agno library not available)")
+ self._mock_reason = "agno library not available"
+ logger.warning(f"LLM agent '{self.name}' initialized in MOCK mode ({self._mock_reason})")
await super().initialize()
return True
except Exception as e:
logger.error(f"Failed to initialize LLM agent '{self.name}': {e}")
- # Still return True but use mock mode - don't block competition
self._llm = None
+ self._mock_reason = str(e)
await super().initialize()
- logger.warning(f"Agent '{self.name}' will use mock decisions due to initialization error")
+ 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
+
+ @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)
+
async def _create_llm(self):
"""Create the LLM instance based on provider."""
try:
@@ -641,8 +656,8 @@ class LLMTradingAgent(BaseTradingAgent):
"""Build the trading prompt with optional features and metrics."""
has_positions = len(portfolio.positions) > 0
num_trades = portfolio.trades_count
- pnl = portfolio.portfolio_value - 10000 # Assuming 10k initial
- pnl_pct = (pnl / 10000) * 100
+ pnl = portfolio.portfolio_value - self.initial_capital
+ pnl_pct = (pnl / self.initial_capital) * 100 if self.initial_capital > 0 else 0
if not has_positions and num_trades == 0:
action_guidance = """
@@ -963,6 +978,7 @@ Respond ONLY with the JSON object, nothing else.
actions = [TradeAction.BUY, TradeAction.SELL, TradeAction.HOLD]
action = random.choice(actions)
+ mock_reason = getattr(self, '_mock_reason', 'unknown')
return ModelDecision(
competition_id="",
@@ -971,7 +987,7 @@ Respond ONLY with the JSON object, nothing else.
action=action,
symbol=market_data.symbol,
quantity=0.01 if action != TradeAction.HOLD else 0,
- confidence=random.uniform(0.5, 0.9),
- reasoning=f"Mock decision: {action.value}",
+ 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/competition.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.py
index b9167d938..68c79eb65 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
@@ -138,15 +138,24 @@ class AlphaArenaCompetition:
elif hasattr(model, 'metadata') and model.metadata:
trading_style = model.metadata.get('trading_style')
+ # Build instructions from custom system prompt (from Settings tab)
+ custom_instructions = None
+ if self.config.custom_prompt:
+ custom_instructions = [self.config.custom_prompt]
+
# Create agent with optional trading style
+ # Temperature and system prompt come from Settings > LLM Config global settings
+ agent_capital = model.initial_capital or self.config.initial_capital
agent = LLMTradingAgent(
name=model.name,
provider=provider,
model_id=model_id,
api_key=api_key,
- temperature=0.7,
+ temperature=self.config.temperature,
+ instructions=custom_instructions,
mode=self.config.mode.value if hasattr(self.config.mode, 'value') else self.config.mode,
trading_style=trading_style,
+ initial_capital=agent_capital,
)
# Initialize with timeout
@@ -156,7 +165,11 @@ class AlphaArenaCompetition:
timeout=30.0
)
if init_success:
- logger.info(f"Agent {model.name} initialized successfully")
+ 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")
else:
logger.warning(f"Agent {model.name} initialization returned False, using mock mode")
except asyncio.TimeoutError:
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.py
index adf17f4e4..e9535d893 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
@@ -215,6 +215,26 @@ async def create_competition_handler(params: Dict, api_keys: Dict) -> Dict[str,
if not models_data:
return {"success": False, "error": "No models provided in configuration"}
+ if len(models_data) < 2:
+ return {"success": False, "error": "At least 2 models are required for a competition"}
+
+ # Validate API keys before creating agents
+ missing_keys = []
+ for model_data in models_data:
+ provider = (model_data.get("provider") or "").lower()
+ has_key = bool(model_data.get("api_key"))
+ has_provider_key = bool(api_keys.get(provider) or api_keys.get(model_data.get("provider", "")))
+ no_key_required = provider in ("ollama", "fincept")
+
+ if not has_key and not has_provider_key and not no_key_required:
+ missing_keys.append(f"{model_data.get('name', 'Unknown')} ({provider})")
+
+ if missing_keys:
+ return {
+ "success": False,
+ "error": f"Missing API keys for: {', '.join(missing_keys)}. Configure API keys in Settings > LLM Config.",
+ }
+
models = []
for model_data in models_data:
@@ -234,6 +254,14 @@ async def create_competition_handler(params: Dict, api_keys: Dict) -> Dict[str,
style_info = f" [style: {model.trading_style}]" if model.trading_style else ""
logger.info(f"Configured model: {model.name} ({model.provider}/{model.model_id}){style_info}")
+ # Extract global LLM settings from Settings tab (if provided)
+ llm_settings = params.get("llm_settings", {})
+ llm_temperature = llm_settings.get("temperature", 0.7) if llm_settings else 0.7
+ llm_max_tokens = llm_settings.get("max_tokens", 2000) if llm_settings else 2000
+ llm_system_prompt = llm_settings.get("system_prompt", "") if llm_settings else ""
+
+ logger.info(f"LLM global settings: temperature={llm_temperature}, max_tokens={llm_max_tokens}, system_prompt={'(set)' if llm_system_prompt else '(default)'}")
+
# Create config
config = CompetitionConfig(
competition_id=competition_id,
@@ -245,6 +273,9 @@ async def create_competition_handler(params: Dict, api_keys: Dict) -> Dict[str,
cycle_interval_seconds=params.get("cycle_interval_seconds", 150),
exchange_id=params.get("exchange_id", "kraken"),
max_cycles=params.get("max_cycles"),
+ custom_prompt=llm_system_prompt if llm_system_prompt else None,
+ temperature=llm_temperature,
+ max_tokens=llm_max_tokens,
)
logger.info(f"Competition config created: {competition_id}")
@@ -274,13 +305,26 @@ 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
- return {
+ # 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}")
+
+ result = {
"success": True,
"competition_id": competition_id,
"config": config.model_dump(),
"status": "created",
"models_count": len(models),
}
+ 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}")
+
+ return result
else:
return {
"success": False,
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/models.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/models.py
index a2de575ff..7fce55c0f 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/models.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/models.py
@@ -230,6 +230,8 @@ class CompetitionConfig(BaseModel):
exchange_id: str = Field("kraken", description="Exchange for market data")
max_cycles: Optional[int] = Field(None, description="Max cycles (None = unlimited)")
custom_prompt: Optional[str] = Field(None, description="Custom system prompt")
+ temperature: float = Field(0.7, ge=0.0, le=2.0, description="LLM temperature from Settings")
+ max_tokens: int = Field(2000, ge=100, description="LLM max tokens from Settings")
class Config:
use_enum_values = True
diff --git a/fincept-terminal-desktop/src-tauri/scan_dependencies.py b/fincept-terminal-desktop/src-tauri/scan_dependencies.py
deleted file mode 100644
index 6e5a74484..000000000
--- a/fincept-terminal-desktop/src-tauri/scan_dependencies.py
+++ /dev/null
@@ -1,109 +0,0 @@
-#!/usr/bin/env python3
-"""Scan Python scripts and update requirements.txt with missing packages."""
-import ast
-import os
-import re
-from pathlib import Path
-
-SCRIPTS_DIR = Path("resources/scripts")
-REQUIREMENTS_FILE = Path("resources/requirements.txt")
-STDLIB_MODULES = set([
- 'abc', 'aifc', 'argparse', 'array', 'ast', 'asynchat', 'asyncio', 'asyncore',
- 'base64', 'bdb', 'binascii', 'binhex', 'bisect', 'builtins', 'bz2',
- 'calendar', 'cgi', 'cgitb', 'chunk', 'cmath', 'cmd', 'code', 'codecs',
- 'codeop', 'collections', 'colorsys', 'compileall', 'concurrent', 'configparser',
- 'contextlib', 'copy', 'copyreg', 'cProfile', 'csv', 'ctypes', 'curses',
- 'dataclasses', 'datetime', 'dbm', 'decimal', 'difflib', 'dis', 'distutils',
- 'doctest', 'email', 'encodings', 'enum', 'errno', 'faulthandler', 'fcntl',
- 'filecmp', 'fileinput', 'fnmatch', 'formatter', 'fractions', 'ftplib',
- 'functools', 'gc', 'getopt', 'getpass', 'gettext', 'glob', 'gzip',
- 'hashlib', 'heapq', 'hmac', 'html', 'http', 'imaplib', 'imghdr', 'imp',
- 'importlib', 'inspect', 'io', 'ipaddress', 'itertools', 'json', 'keyword',
- 'lib2to3', 'linecache', 'locale', 'logging', 'lzma', 'mailbox', 'mailcap',
- 'marshal', 'math', 'mimetypes', 'mmap', 'modulefinder', 'multiprocessing',
- 'netrc', 'numbers', 'operator', 'optparse', 'os', 'ossaudiodev', 'parser',
- 'pathlib', 'pdb', 'pickle', 'pickletools', 'pipes', 'pkgutil', 'platform',
- 'plistlib', 'poplib', 'posix', 'posixpath', 'pprint', 'profile', 'pstats',
- 'pty', 'pwd', 'py_compile', 'pyclbr', 'pydoc', 'queue', 'quopri', 'random',
- 're', 'readline', 'reprlib', 'resource', 'rlcompleter', 'runpy', 'sched',
- 'secrets', 'select', 'selectors', 'shelve', 'shlex', 'shutil', 'signal',
- 'site', 'smtpd', 'smtplib', 'sndhdr', 'socket', 'socketserver', 'sqlite3',
- 'ssl', 'stat', 'statistics', 'string', 'stringprep', 'struct', 'subprocess',
- 'sunau', 'symbol', 'symtable', 'sys', 'sysconfig', 'syslog', 'tabnanny',
- 'tarfile', 'telnetlib', 'tempfile', 'termios', 'test', 'textwrap', 'threading',
- 'time', 'timeit', 'token', 'tokenize', 'trace', 'traceback', 'tracemalloc',
- 'tty', 'turtle', 'turtledemo', 'types', 'typing', 'unicodedata', 'unittest',
- 'urllib', 'uu', 'uuid', 'venv', 'warnings', 'wave', 'weakref', 'webbrowser',
- 'winreg', 'winsound', 'wsgiref', 'xdrlib', 'xml', 'xmlrpc', 'zipapp',
- 'zipfile', 'zipimport', 'zlib'
-])
-
-def extract_imports(file_path):
- """Extract all import statements from a Python file."""
- imports = set()
- try:
- with open(file_path, 'r', encoding='utf-8') as f:
- tree = ast.parse(f.read(), filename=str(file_path))
-
- for node in ast.walk(tree):
- if isinstance(node, ast.Import):
- for alias in node.names:
- imports.add(alias.name.split('.')[0])
- elif isinstance(node, ast.ImportFrom):
- if node.module:
- imports.add(node.module.split('.')[0])
- except Exception as e:
- print(f"Warning: Could not parse {file_path}: {e}")
-
- return imports
-
-def scan_all_scripts():
- """Scan all Python scripts in resources/scripts directory."""
- all_imports = set()
-
- for py_file in SCRIPTS_DIR.rglob("*.py"):
- imports = extract_imports(py_file)
- all_imports.update(imports)
-
- # Filter out standard library modules
- third_party = {imp for imp in all_imports if imp not in STDLIB_MODULES}
-
- return sorted(third_party)
-
-def read_requirements():
- """Read existing requirements.txt."""
- if not REQUIREMENTS_FILE.exists():
- return set()
-
- packages = set()
- with open(REQUIREMENTS_FILE, 'r') as f:
- for line in f:
- line = line.strip()
- if line and not line.startswith('#'):
- # Extract package name (before ==, >=, etc.)
- pkg = re.split(r'[=<>!]', line)[0].strip()
- packages.add(pkg.lower())
-
- return packages
-
-def update_requirements(new_packages):
- """Update requirements.txt with new packages."""
- existing = read_requirements()
- to_add = [pkg for pkg in new_packages if pkg.lower() not in existing]
-
- if to_add:
- print(f"Adding {len(to_add)} new packages to requirements.txt:")
- for pkg in to_add:
- print(f" - {pkg}")
-
- with open(REQUIREMENTS_FILE, 'a') as f:
- for pkg in to_add:
- f.write(f"{pkg}\n")
- else:
- print("All packages already in requirements.txt")
-
-if __name__ == "__main__":
- print("Scanning Python scripts for dependencies...")
- packages = scan_all_scripts()
- print(f"Found {len(packages)} third-party packages")
- update_requirements(packages)
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs b/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs
index 52d67a989..e9de031c4 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs
@@ -162,22 +162,7 @@ pub async fn execute_agent_streaming(
}).to_string())
}
-/// Cancel an active stream
-#[tauri::command]
-pub async fn cancel_agent_stream(stream_id: String) -> Result<String, String> {
- let streams = ACTIVE_STREAMS.read().await;
-
- if let Some(cancel_flag) = streams.get(&stream_id) {
- cancel_flag.store(true, Ordering::Relaxed);
- Ok(serde_json::json!({
- "success": true,
- "stream_id": stream_id,
- "status": "cancelled"
- }).to_string())
- } else {
- Err(format!("Stream {} not found or already completed", stream_id))
- }
-}
+// cancel_agent_stream is defined in agents.rs
/// Execute multiple agent tasks in parallel
///
@@ -305,8 +290,8 @@ pub async fn get_active_agent_streams() -> Result<String, String> {
}).to_string())
}
-/// Internal: Execute with streaming callback (simulated for now)
-/// In production, this would use a named pipe or socket to get streaming output
+/// Internal: Execute with real streaming via stdout line-by-line reading
+/// Python script must print lines with flush=True for real-time output
async fn execute_with_stream_callback<F>(
app: &AppHandle,
script_name: &str,
@@ -316,27 +301,83 @@ async fn execute_with_stream_callback<F>(
where
F: FnMut(&str, &str, Option<serde_json::Value>) -> bool + Send + 'static,
{
- // For now, execute normally and emit result as single chunk
- // Future: Use named pipes or Unix sockets for true streaming
+ use std::io::{BufRead, BufReader};
+ use std::process::{Command, Stdio};
+
+ let script_path = crate::python::get_script_path(app, script_name)?;
+ let python_path = crate::python::get_python_path(app, None)?;
+
+ let mut cmd = Command::new(&python_path);
+ cmd.arg(&script_path)
+ .args(&args)
+ .arg("--stream")
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ #[cfg(target_os = "windows")]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
+ }
- // Emit thinking indicator
- callback("thinking", "Processing your request...", None);
+ let mut child = cmd.spawn()
+ .map_err(|e| format!("Failed to spawn Python: {}", e))?;
- let result = crate::python::execute(app, script_name, args).await?;
+ let stdout = child.stdout.take()
+ .ok_or_else(|| "Failed to capture stdout".to_string())?;
- // Parse and emit tokens (simulated chunking for now)
- if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&result) {
- if let Some(response) = parsed.get("response").and_then(|r| r.as_str()) {
- // Emit in chunks for smoother UI
- for chunk in response.chars().collect::<Vec<_>>().chunks(50) {
- let chunk_str: String = chunk.iter().collect();
- if !callback("token", &chunk_str, None) {
+ let reader = BufReader::new(stdout);
+ let mut full_output = String::new();
+
+ // Read stdout line by line and invoke callback
+ for line in reader.lines() {
+ match line {
+ Ok(line_content) => {
+ let trimmed = line_content.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+
+ // Determine chunk type based on content prefix
+ let (chunk_type, content) = if trimmed.starts_with("THINKING:") {
+ ("thinking", trimmed.strip_prefix("THINKING:").unwrap_or(trimmed).trim())
+ } else if trimmed.starts_with("TOOL:") {
+ ("tool_call", trimmed.strip_prefix("TOOL:").unwrap_or(trimmed).trim())
+ } else if trimmed.starts_with("TOOL_RESULT:") {
+ ("tool_result", trimmed.strip_prefix("TOOL_RESULT:").unwrap_or(trimmed).trim())
+ } else if trimmed.starts_with("ERROR:") {
+ ("error", trimmed.strip_prefix("ERROR:").unwrap_or(trimmed).trim())
+ } else if trimmed.starts_with("DONE:") {
+ ("done", trimmed.strip_prefix("DONE:").unwrap_or(trimmed).trim())
+ } else if trimmed.starts_with('{') || trimmed.starts_with('[') {
+ ("json", trimmed)
+ } else {
+ ("token", trimmed)
+ };
+
+ full_output.push_str(content);
+ full_output.push('\n');
+
+ // Invoke callback - returns false if cancelled
+ if !callback(chunk_type, content, None) {
+ let _ = child.kill();
return Err("Stream cancelled".to_string());
}
- tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
+ }
+ Err(e) => {
+ eprintln!("[Streaming] Error reading line: {}", e);
+ break;
}
}
}
- Ok(result)
+ // Wait for process to complete
+ let status = child.wait()
+ .map_err(|e| format!("Failed to wait for process: {}", e))?;
+
+ if status.success() {
+ Ok(full_output)
+ } else {
+ Err(format!("Script failed with exit code: {:?}", status.code()))
+ }
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
index bf77fda91..fb3dcca4a 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
@@ -3,7 +3,15 @@ use crate::python;
use serde::{Deserialize, Serialize};
use tauri::Manager;
use std::time::Duration;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::collections::HashMap;
use tokio::time::timeout;
+use tokio::sync::Mutex;
+use once_cell::sync::Lazy;
+
+// Global registry for active streams (for cancellation)
+static ACTIVE_STREAMS: Lazy<Mutex<HashMap<String, Arc<AtomicBool>>>> = Lazy::new(|| Mutex::new(HashMap::new()));
/// Default timeout for agent operations (120 seconds - LLM calls can take 30-60s+)
const AGENT_TIMEOUT_SECS: u64 = 120;
@@ -103,6 +111,59 @@ async fn execute_core_agent_with_timeout(
}
}
+/// Execute CoreAgent with streaming output via Tauri events
+/// Returns stream_id for the frontend to listen to events: `agent-stream-{stream_id}`
+#[tauri::command]
+pub async fn execute_core_agent_streaming(
+ app: tauri::AppHandle,
+ payload: serde_json::Value,
+ stream_id: String,
+) -> Result<String, String> {
+ let payload_str = serde_json::to_string(&payload)
+ .map_err(|e| format!("Failed to serialize payload: {}", e))?;
+
+ // Create cancellation flag
+ let cancel_flag = Arc::new(AtomicBool::new(false));
+
+ // Register stream for potential cancellation
+ {
+ let mut streams = ACTIVE_STREAMS.lock().await;
+ streams.insert(stream_id.clone(), cancel_flag.clone());
+ }
+
+ let args: Vec<String> = vec![payload_str];
+ let stream_id_clone = stream_id.clone();
+
+ // Execute with streaming
+ let result = python::execute_streaming(
+ app,
+ "agents/finagent_core/main.py",
+ args,
+ stream_id_clone,
+ cancel_flag,
+ ).await;
+
+ // Cleanup stream registration
+ {
+ let mut streams = ACTIVE_STREAMS.lock().await;
+ streams.remove(&stream_id);
+ }
+
+ result
+}
+
+/// Cancel an active streaming operation
+#[tauri::command]
+pub async fn cancel_agent_stream(stream_id: String) -> Result<bool, String> {
+ let streams = ACTIVE_STREAMS.lock().await;
+ if let Some(cancel_flag) = streams.get(&stream_id) {
+ cancel_flag.store(true, Ordering::Relaxed);
+ Ok(true)
+ } else {
+ Ok(false) // Stream not found or already completed
+ }
+}
+
/// Route a query to the appropriate agent using SuperAgent
/// Uses shorter timeout since routing is just keyword matching (no LLM call)
#[tauri::command]
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading.rs b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading.rs
new file mode 100644
index 000000000..6c923bab1
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading.rs
@@ -0,0 +1,1236 @@
+//! Algo Trading Commands
+//!
+//! Tauri commands for the visual algo trading system:
+//! - Strategy CRUD (save, list, get, delete)
+//! - Deployment lifecycle (deploy, stop, stop-all, list)
+//! - Trade history
+//! - Scanner execution
+//! - Candle cache reads
+//! - One-shot condition evaluation (preview)
+//! - Candle aggregation control
+
+use crate::database::pool::get_db;
+use serde_json::json;
+use std::path::PathBuf;
+use tauri::{Emitter, Manager};
+
+// ============================================================================
+// HELPERS
+// ============================================================================
+
+/// Get the algo trading scripts directory
+fn get_algo_scripts_dir(app: &tauri::AppHandle) -> Result<PathBuf, String> {
+ let resource_dir = app
+ .path()
+ .resource_dir()
+ .map_err(|e| format!("Failed to get resource dir: {}", e))?;
+
+ let scripts_dir = resource_dir
+ .join("resources")
+ .join("scripts")
+ .join("algo_trading");
+
+ if scripts_dir.exists() {
+ return Ok(scripts_dir);
+ }
+
+ // Fallback for development mode
+ let dev_dir = std::env::current_dir()
+ .map_err(|e| format!("Failed to get current dir: {}", e))?
+ .join("src-tauri")
+ .join("resources")
+ .join("scripts")
+ .join("algo_trading");
+
+ if dev_dir.exists() {
+ return Ok(dev_dir);
+ }
+
+ Err("Algo trading scripts directory not found".to_string())
+}
+
+/// Get the main database path for passing to Python subprocesses
+fn get_main_db_path_str() -> Result<String, String> {
+ let db_dir = if cfg!(target_os = "windows") {
+ let appdata = std::env::var("APPDATA")
+ .map_err(|_| "APPDATA not set".to_string())?;
+ PathBuf::from(appdata).join("fincept-terminal")
+ } else if cfg!(target_os = "macos") {
+ let home = std::env::var("HOME")
+ .map_err(|_| "HOME not set".to_string())?;
+ PathBuf::from(home)
+ .join("Library")
+ .join("Application Support")
+ .join("fincept-terminal")
+ } else {
+ let home = std::env::var("HOME")
+ .map_err(|_| "HOME not set".to_string())?;
+ let xdg = std::env::var("XDG_DATA_HOME")
+ .unwrap_or_else(|_| format!("{}/.local/share", home));
+ PathBuf::from(xdg).join("fincept-terminal")
+ };
+ Ok(db_dir.join("fincept_terminal.db").to_string_lossy().to_string())
+}
+
+// ============================================================================
+// STRATEGY CRUD
+// ============================================================================
+
+/// Save or update an algo strategy (condition-based)
+#[tauri::command]
+pub async fn save_algo_strategy(
+ id: String,
+ name: String,
+ description: Option<String>,
+ entry_conditions: String,
+ exit_conditions: String,
+ entry_logic: Option<String>,
+ exit_logic: Option<String>,
+ stop_loss: Option<f64>,
+ take_profit: Option<f64>,
+ trailing_stop: Option<f64>,
+ trailing_stop_type: Option<String>,
+ timeframe: Option<String>,
+ symbols: Option<String>,
+) -> Result<String, String> {
+ let conn = get_db().map_err(|e| e.to_string())?;
+
+ conn.execute(
+ "INSERT INTO algo_strategies (id, name, description, entry_conditions, exit_conditions,
+ entry_logic, exit_logic, stop_loss, take_profit, trailing_stop, trailing_stop_type,
+ timeframe, symbols, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, CURRENT_TIMESTAMP)
+ ON CONFLICT(id) DO UPDATE SET
+ name = excluded.name,
+ description = excluded.description,
+ entry_conditions = excluded.entry_conditions,
+ exit_conditions = excluded.exit_conditions,
+ entry_logic = excluded.entry_logic,
+ exit_logic = excluded.exit_logic,
+ stop_loss = excluded.stop_loss,
+ take_profit = excluded.take_profit,
+ trailing_stop = excluded.trailing_stop,
+ trailing_stop_type = excluded.trailing_stop_type,
+ timeframe = excluded.timeframe,
+ symbols = excluded.symbols,
+ updated_at = CURRENT_TIMESTAMP",
+ rusqlite::params![
+ id,
+ name,
+ description.unwrap_or_default(),
+ entry_conditions,
+ exit_conditions,
+ entry_logic.unwrap_or_else(|| "AND".to_string()),
+ exit_logic.unwrap_or_else(|| "AND".to_string()),
+ stop_loss,
+ take_profit,
+ trailing_stop,
+ trailing_stop_type.unwrap_or_else(|| "percent".to_string()),
+ timeframe.unwrap_or_else(|| "5m".to_string()),
+ symbols.unwrap_or_else(|| "[]".to_string()),
+ ],
+ )
+ .map_err(|e| format!("Failed to save strategy: {}", e))?;
+
+ Ok(json!({
+ "success": true,
+ "id": id
+ }).to_string())
+}
+
+/// List all algo strategies
+#[tauri::command]
+pub async fn list_algo_strategies() -> Result<String, String> {
+ let conn = get_db().map_err(|e| e.to_string())?;
+
+ let mut stmt = conn
+ .prepare(
+ "SELECT id, name, description, entry_conditions, exit_conditions,
+ entry_logic, exit_logic, stop_loss, take_profit, trailing_stop,
+ trailing_stop_type, timeframe, symbols, is_active, created_at, updated_at
+ FROM algo_strategies ORDER BY updated_at DESC",
+ )
+ .map_err(|e| format!("Failed to prepare query: {}", e))?;
+
+ let rows = stmt
+ .query_map([], |row| {
+ Ok(json!({
+ "id": row.get::<_, String>(0)?,
+ "name": row.get::<_, String>(1)?,
+ "description": row.get::<_, String>(2)?,
+ "entry_conditions": row.get::<_, String>(3)?,
+ "exit_conditions": row.get::<_, String>(4)?,
+ "entry_logic": row.get::<_, String>(5)?,
+ "exit_logic": row.get::<_, String>(6)?,
+ "stop_loss": row.get::<_, Option<f64>>(7)?,
+ "take_profit": row.get::<_, Option<f64>>(8)?,
+ "trailing_stop": row.get::<_, Option<f64>>(9)?,
+ "trailing_stop_type": row.get::<_, String>(10)?,
+ "timeframe": row.get::<_, String>(11)?,
+ "symbols": row.get::<_, String>(12)?,
+ "is_active": row.get::<_, i32>(13)?,
+ "created_at": row.get::<_, String>(14)?,
+ "updated_at": row.get::<_, String>(15)?,
+ }))
+ })
+ .map_err(|e| format!("Failed to query strategies: {}", e))?;
+
+ let strategies: Vec<serde_json::Value> = rows.filter_map(|r| r.ok()).collect();
+
+ Ok(json!({
+ "success": true,
+ "data": strategies,
+ "count": strategies.len()
+ }).to_string())
+}
+
+/// Get a single algo strategy by ID
+#[tauri::command]
+pub async fn get_algo_strategy(id: String) -> Result<String, String> {
+ let conn = get_db().map_err(|e| e.to_string())?;
+
+ let result = conn.query_row(
+ "SELECT id, name, description, entry_conditions, exit_conditions,
+ entry_logic, exit_logic, stop_loss, take_profit, trailing_stop,
+ trailing_stop_type, timeframe, symbols, is_active, created_at, updated_at
+ FROM algo_strategies WHERE id = ?1",
+ rusqlite::params![id],
+ |row| {
+ Ok(json!({
+ "id": row.get::<_, String>(0)?,
+ "name": row.get::<_, String>(1)?,
+ "description": row.get::<_, String>(2)?,
+ "entry_conditions": row.get::<_, String>(3)?,
+ "exit_conditions": row.get::<_, String>(4)?,
+ "entry_logic": row.get::<_, String>(5)?,
+ "exit_logic": row.get::<_, String>(6)?,
+ "stop_loss": row.get::<_, Option<f64>>(7)?,
+ "take_profit": row.get::<_, Option<f64>>(8)?,
+ "trailing_stop": row.get::<_, Option<f64>>(9)?,
+ "trailing_stop_type": row.get::<_, String>(10)?,
+ "timeframe": row.get::<_, String>(11)?,
+ "symbols": row.get::<_, String>(12)?,
+ "is_active": row.get::<_, i32>(13)?,
+ "created_at": row.get::<_, String>(14)?,
+ "updated_at": row.get::<_, String>(15)?,
+ }))
+ },
+ );
+
+ match result {
+ Ok(strategy) => Ok(json!({ "success": true, "data": strategy }).to_string()),
+ Err(rusqlite::Error::QueryReturnedNoRows) => {
+ Ok(json!({ "success": false, "error": "Strategy not found" }).to_string())
+ }
+ Err(e) => Ok(json!({ "success": false, "error": e.to_string() }).to_string()),
+ }
+}
+
+/// Delete an algo strategy
+#[tauri::command]
+pub async fn delete_algo_strategy(id: String) -> Result<String, String> {
+ let conn = get_db().map_err(|e| e.to_string())?;
+
+ let changes = conn
+ .execute("DELETE FROM algo_strategies WHERE id = ?1", rusqlite::params![id])
+ .map_err(|e| format!("Failed to delete strategy: {}", e))?;
+
+ Ok(json!({
+ "success": changes > 0,
+ "deleted": changes > 0
+ }).to_string())
+}
+
+// ============================================================================
+// DEPLOYMENT LIFECYCLE
+// ============================================================================
+
+/// Deploy an algo strategy (spawn Python algo_live_runner.py as background process)
+#[tauri::command]
+pub async fn deploy_algo_strategy(
+ app: tauri::AppHandle,
+ state: tauri::State<'_, crate::WebSocketState>,
+ strategy_id: String,
+ symbol: String,
+ provider: Option<String>,
+ mode: Option<String>,
+ timeframe: Option<String>,
+ quantity: Option<f64>,
+ params: Option<String>,
+) -> Result<String, String> {
+ use std::process::Command;
+
+ let deploy_mode = mode.unwrap_or_else(|| "paper".to_string());
+ let deploy_timeframe = timeframe.unwrap_or_else(|| "5m".to_string());
+ let deploy_qty = quantity.unwrap_or(1.0);
+ let deploy_provider = provider.unwrap_or_default();
+ let deploy_params = params.unwrap_or_else(|| "{}".to_string());
+
+ // Generate deployment ID
+ let deploy_id = format!("algo-{}", uuid::Uuid::new_v4());
+
+ // Insert deployment record
+ let conn = get_db().map_err(|e| e.to_string())?;
+ conn.execute(
+ "INSERT INTO algo_deployments (id, strategy_id, symbol, provider, mode, status, timeframe, quantity, params)
+ VALUES (?1, ?2, ?3, ?4, ?5, 'starting', ?6, ?7, ?8)",
+ rusqlite::params![deploy_id, strategy_id, symbol, deploy_provider, deploy_mode, deploy_timeframe, deploy_qty, deploy_params],
+ )
+ .map_err(|e| format!("Failed to create deployment: {}", e))?;
+
+ // Insert initial metrics row
+ conn.execute(
+ "INSERT OR IGNORE INTO algo_metrics (deployment_id) VALUES (?1)",
+ rusqlite::params![deploy_id],
+ )
+ .map_err(|e| format!("Failed to create metrics: {}", e))?;
+
+ // Get paths
+ let scripts_dir = get_algo_scripts_dir(&app)?;
+ let runner_path = scripts_dir.join("algo_live_runner.py");
+ let db_path = get_main_db_path_str()?;
+
+ if !runner_path.exists() {
+ // Update deployment status to error
+ let _ = conn.execute(
+ "UPDATE algo_deployments SET status = 'error', error_message = 'Runner script not found' WHERE id = ?1",
+ rusqlite::params![deploy_id],
+ );
+ return Ok(json!({
+ "success": false,
+ "error": "algo_live_runner.py not found"
+ }).to_string());
+ }
+
+ // Spawn the Python runner as a background process
+ let child = Command::new("python")
+ .arg(&runner_path)
+ .arg("--deploy-id")
+ .arg(&deploy_id)
+ .arg("--strategy-id")
+ .arg(&strategy_id)
+ .arg("--symbol")
+ .arg(&symbol)
+ .arg("--provider")
+ .arg(&deploy_provider)
+ .arg("--mode")
+ .arg(&deploy_mode)
+ .arg("--timeframe")
+ .arg(&deploy_timeframe)
+ .arg("--quantity")
+ .arg(deploy_qty.to_string())
+ .arg("--db")
+ .arg(&db_path)
+ .spawn();
+
+ match child {
+ Ok(child) => {
+ let pid = child.id();
+
+ // Update deployment with PID and running status
+ let _ = conn.execute(
+ "UPDATE algo_deployments SET status = 'running', pid = ?1, updated_at = CURRENT_TIMESTAMP WHERE id = ?2",
+ rusqlite::params![pid as i64, deploy_id],
+ );
+
+ // Auto-start candle aggregation for this symbol+timeframe
+ let services = state.services.read().await;
+ services
+ .candle_aggregator
+ .add_subscription(symbol.clone(), deploy_timeframe.clone())
+ .await;
+
+ Ok(json!({
+ "success": true,
+ "deploy_id": deploy_id,
+ "pid": pid
+ }).to_string())
+ }
+ Err(e) => {
+ let _ = conn.execute(
+ "UPDATE algo_deployments SET status = 'error', error_message = ?1 WHERE id = ?2",
+ rusqlite::params![format!("Failed to spawn: {}", e), deploy_id],
+ );
+ Ok(json!({
+ "success": false,
+ "error": format!("Failed to spawn runner: {}", e)
+ }).to_string())
+ }
+ }
+}
+
+/// Stop a running algo deployment (kill process, update DB)
+#[tauri::command]
+pub async fn stop_algo_deployment(deploy_id: String) -> Result<String, String> {
+ let conn = get_db().map_err(|e| e.to_string())?;
+
+ // Get PID from deployment record
+ let pid_result: Result<Option<i64>, _> = conn.query_row(
+ "SELECT pid FROM algo_deployments WHERE id = ?1 AND status = 'running'",
+ rusqlite::params![deploy_id],
+ |row| row.get(0),
+ );
+
+ match pid_result {
+ Ok(Some(pid)) => {
+ // Kill the process
+ #[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();
+ }
+
+ // Update status
+ conn.execute(
+ "UPDATE algo_deployments SET status = 'stopped', stopped_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE id = ?1",
+ rusqlite::params![deploy_id],
+ )
+ .map_err(|e| format!("Failed to update deployment: {}", e))?;
+
+ Ok(json!({ "success": true, "stopped": true }).to_string())
+ }
+ Ok(None) => {
+ // No PID but try to update status anyway
+ let _ = conn.execute(
+ "UPDATE algo_deployments SET status = 'stopped', stopped_at = CURRENT_TIMESTAMP WHERE id = ?1",
+ rusqlite::params![deploy_id],
+ );
+ Ok(json!({ "success": true, "stopped": true, "note": "No PID found" }).to_string())
+ }
+ Err(rusqlite::Error::QueryReturnedNoRows) => {
+ Ok(json!({ "success": false, "error": "Deployment not found or not running" }).to_string())
+ }
+ Err(e) => {
+ Ok(json!({ "success": false, "error": e.to_string() }).to_string())
+ }
+ }
+}
+
+/// Emergency stop all running algo deployments
+#[tauri::command]
+pub async fn stop_all_algo_deployments() -> Result<String, String> {
+ let conn = get_db().map_err(|e| e.to_string())?;
+
+ // Get all running PIDs
+ let mut stmt = conn
+ .prepare("SELECT id, pid FROM algo_deployments WHERE status = 'running' AND pid IS NOT NULL")
+ .map_err(|e| format!("Failed to query: {}", e))?;
+
+ let deployments: Vec<(String, i64)> = stmt
+ .query_map([], |row| {
+ Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
+ })
+ .map_err(|e| format!("Failed to read deployments: {}", e))?
+ .filter_map(|r| r.ok())
+ .collect();
+
+ let mut stopped = 0;
+ for (id, pid) in &deployments {
+ #[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();
+ }
+
+ let _ = conn.execute(
+ "UPDATE algo_deployments SET status = 'stopped', stopped_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE id = ?1",
+ rusqlite::params![id],
+ );
+ stopped += 1;
+ }
+
+ Ok(json!({
+ "success": true,
+ "stopped": stopped
+ }).to_string())
+}
+
+/// List all algo deployments with their metrics
+#[tauri::command]
+pub async fn list_algo_deployments() -> Result<String, String> {
+ let conn = get_db().map_err(|e| e.to_string())?;
+
+ let mut stmt = conn
+ .prepare(
+ "SELECT d.id, d.strategy_id, d.symbol, d.provider, d.mode, d.status,
+ d.timeframe, d.quantity, d.params, d.pid, d.error_message,
+ d.created_at, d.updated_at, d.stopped_at,
+ m.total_pnl, m.unrealized_pnl, m.total_trades, m.win_rate,
+ m.max_drawdown, m.current_position_qty, m.current_position_side,
+ m.current_position_entry, m.updated_at as metrics_updated,
+ s.name as strategy_name
+ FROM algo_deployments d
+ LEFT JOIN algo_metrics m ON d.id = m.deployment_id
+ LEFT JOIN algo_strategies s ON d.strategy_id = s.id
+ ORDER BY d.created_at DESC",
+ )
+ .map_err(|e| format!("Failed to prepare query: {}", e))?;
+
+ let rows = stmt
+ .query_map([], |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)?,
+ "params": row.get::<_, String>(8)?,
+ "pid": row.get::<_, Option<i64>>(9)?,
+ "error_message": row.get::<_, Option<String>>(10)?,
+ "created_at": row.get::<_, String>(11)?,
+ "updated_at": row.get::<_, String>(12)?,
+ "stopped_at": row.get::<_, Option<String>>(13)?,
+ "metrics": {
+ "total_pnl": row.get::<_, Option<f64>>(14)?.unwrap_or(0.0),
+ "unrealized_pnl": row.get::<_, Option<f64>>(15)?.unwrap_or(0.0),
+ "total_trades": row.get::<_, Option<i32>>(16)?.unwrap_or(0),
+ "win_rate": row.get::<_, Option<f64>>(17)?.unwrap_or(0.0),
+ "max_drawdown": row.get::<_, Option<f64>>(18)?.unwrap_or(0.0),
+ "current_position_qty": row.get::<_, Option<f64>>(19)?.unwrap_or(0.0),
+ "current_position_side": row.get::<_, Option<String>>(20)?.unwrap_or_default(),
+ "current_position_entry": row.get::<_, Option<f64>>(21)?.unwrap_or(0.0),
+ "metrics_updated": row.get::<_, Option<String>>(22)?,
+ },
+ "strategy_name": row.get::<_, Option<String>>(23)?,
+ }))
+ })
+ .map_err(|e| format!("Failed to query deployments: {}", e))?;
+
+ let deployments: Vec<serde_json::Value> = rows.filter_map(|r| r.ok()).collect();
+
+ Ok(json!({
+ "success": true,
+ "data": deployments,
+ "count": deployments.len()
+ }).to_string())
+}
+
+// ============================================================================
+// TRADE HISTORY
+// ============================================================================
+
+/// Get trade history for a deployment
+#[tauri::command]
+pub async fn get_algo_trades(
+ deployment_id: String,
+ limit: Option<i32>,
+) -> Result<String, String> {
+ let conn = get_db().map_err(|e| e.to_string())?;
+ let row_limit = limit.unwrap_or(100);
+
+ let mut stmt = conn
+ .prepare(
+ "SELECT id, deployment_id, symbol, side, quantity, price, pnl, timestamp, signal_reason
+ FROM algo_trades WHERE deployment_id = ?1
+ ORDER BY timestamp DESC LIMIT ?2",
+ )
+ .map_err(|e| format!("Failed to prepare query: {}", e))?;
+
+ let rows = stmt
+ .query_map(rusqlite::params![deployment_id, row_limit], |row| {
+ Ok(json!({
+ "id": row.get::<_, String>(0)?,
+ "deployment_id": row.get::<_, String>(1)?,
+ "symbol": row.get::<_, String>(2)?,
+ "side": row.get::<_, String>(3)?,
+ "quantity": row.get::<_, f64>(4)?,
+ "price": row.get::<_, f64>(5)?,
+ "pnl": row.get::<_, f64>(6)?,
+ "timestamp": row.get::<_, String>(7)?,
+ "signal_reason": row.get::<_, String>(8)?,
+ }))
+ })
+ .map_err(|e| format!("Failed to query trades: {}", e))?;
+
+ let trades: Vec<serde_json::Value> = rows.filter_map(|r| r.ok()).collect();
+
+ Ok(json!({
+ "success": true,
+ "data": trades,
+ "count": trades.len()
+ }).to_string())
+}
+
+// ============================================================================
+// SCANNER
+// ============================================================================
+
+/// Run algo scanner across a list of symbols.
+/// For daily+ timeframes, pre-fetches historical data from broker into candle_cache
+/// so the scanner has data to evaluate conditions against.
+#[tauri::command]
+pub async fn run_algo_scan(
+ app: tauri::AppHandle,
+ conditions: String,
+ symbols: String,
+ timeframe: Option<String>,
+ provider: Option<String>,
+) -> Result<String, String> {
+ use std::process::Command;
+
+ let scripts_dir = get_algo_scripts_dir(&app)?;
+ let scanner_path = scripts_dir.join("scanner_engine.py");
+ let db_path = get_main_db_path_str()?;
+ let tf = timeframe.unwrap_or_else(|| "5m".to_string());
+
+ if !scanner_path.exists() {
+ return Ok(json!({
+ "success": false,
+ "error": "scanner_engine.py not found"
+ }).to_string());
+ }
+
+ // Pre-fetch historical data from broker into candle_cache for each symbol
+ // This ensures the scanner has data even if WebSocket candle aggregation hasn't run
+ let symbol_list: Vec<String> = serde_json::from_str(&symbols).unwrap_or_default();
+ if !symbol_list.is_empty() {
+ let broker = provider.as_deref().unwrap_or("fyers");
+ if let Err(e) = prefetch_historical_candles(&db_path, &symbol_list, &tf, broker).await {
+ eprintln!("[run_algo_scan] Warning: prefetch failed: {}", e);
+ // Continue anyway — scanner will report insufficient data per symbol
+ }
+ }
+
+ let output = Command::new("python")
+ .arg(&scanner_path)
+ .arg("--conditions")
+ .arg(&conditions)
+ .arg("--symbols")
+ .arg(&symbols)
+ .arg("--timeframe")
+ .arg(&tf)
+ .arg("--db")
+ .arg(&db_path)
+ .output()
+ .map_err(|e| format!("Failed to run scanner: {}", e))?;
+
+ if output.status.success() {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ // Try to parse as JSON, otherwise wrap
+ if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&stdout) {
+ Ok(parsed.to_string())
+ } else {
+ Ok(json!({ "success": true, "raw": stdout.to_string() }).to_string())
+ }
+ } else {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ Ok(json!({
+ "success": false,
+ "error": format!("Scanner failed: {}", stderr)
+ }).to_string())
+ }
+}
+
+/// Pre-fetch historical candles from broker API and insert into candle_cache table.
+/// Maps timeframe strings to Fyers resolution values and fetches ~1 year of daily data
+/// or appropriate ranges for other timeframes.
+async fn prefetch_historical_candles(
+ db_path: &str,
+ symbols: &[String],
+ timeframe: &str,
+ broker: &str,
+) -> Result<(), String> {
+ use crate::commands::brokers;
+
+ // Only support Fyers for now
+ if broker != "fyers" {
+ return Ok(());
+ }
+
+ // Get Fyers credentials
+ let creds = brokers::get_indian_broker_credentials("fyers".to_string())
+ .await
+ .map_err(|e| format!("Failed to get credentials: {}", e))?;
+
+ if !creds.success || creds.data.is_none() {
+ return Err("Fyers credentials not found. Authenticate first.".to_string());
+ }
+
+ 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")?
+ .to_string();
+ let access_token = cred_data.get("accessToken")
+ .and_then(|v| v.as_str())
+ .ok_or("Fyers access token not found")?
+ .to_string();
+
+ // Map timeframe to Fyers resolution and lookback days
+ let (resolution, lookback_days) = match timeframe {
+ "1m" => ("1", 5),
+ "3m" => ("3", 10),
+ "5m" => ("5", 15),
+ "15m" => ("15", 30),
+ "30m" => ("30", 60),
+ "1h" => ("60", 90),
+ "4h" => ("240", 180),
+ "1d" | "1D" | "D" => ("1D", 365),
+ _ => ("1D", 365),
+ };
+
+ let now = chrono::Utc::now();
+ let from_date = (now - chrono::Duration::days(lookback_days)).format("%Y-%m-%d").to_string();
+ let to_date = now.format("%Y-%m-%d").to_string();
+
+ eprintln!("[prefetch] Fetching {} candles for {} symbols, range {} to {}",
+ resolution, symbols.len(), from_date, to_date);
+
+ // Open DB connection for inserting candles
+ let conn = rusqlite::Connection::open(db_path)
+ .map_err(|e| format!("Failed to open DB: {}", e))?;
+
+ // Ensure candle_cache table exists
+ conn.execute_batch(
+ "CREATE TABLE IF NOT EXISTS candle_cache (
+ symbol TEXT NOT NULL,
+ provider TEXT NOT NULL DEFAULT 'fyers',
+ timeframe TEXT NOT NULL,
+ open_time INTEGER NOT NULL,
+ o REAL NOT NULL,
+ h REAL NOT NULL,
+ l REAL NOT NULL,
+ c REAL NOT NULL,
+ volume REAL NOT NULL DEFAULT 0,
+ is_closed INTEGER NOT NULL DEFAULT 1,
+ PRIMARY KEY (symbol, provider, timeframe, open_time)
+ );"
+ ).map_err(|e| format!("Failed to create candle_cache table: {}", e))?;
+
+ for symbol in symbols {
+ // Build Fyers symbol format: "NSE:SYMBOL-EQ" if not already formatted
+ let fyers_symbol = if symbol.contains(':') {
+ symbol.clone()
+ } else {
+ format!("NSE:{}-EQ", symbol)
+ };
+
+ // Check if we already have recent data for this symbol+timeframe
+ let existing_count: i64 = conn.query_row(
+ "SELECT COUNT(*) FROM candle_cache WHERE symbol = ?1 AND timeframe = ?2 AND is_closed = 1",
+ rusqlite::params![symbol, timeframe],
+ |row| row.get(0),
+ ).unwrap_or(0);
+
+ if existing_count >= 50 {
+ eprintln!("[prefetch] {} already has {} candles, skipping", symbol, existing_count);
+ continue;
+ }
+
+ // Fetch from Fyers API
+ match brokers::fyers_get_history(
+ api_key.clone(),
+ access_token.clone(),
+ fyers_symbol.clone(),
+ resolution.to_string(),
+ from_date.clone(),
+ to_date.clone(),
+ ).await {
+ Ok(response) => {
+ if response.success {
+ if let Some(candles) = response.data.and_then(|d| d.as_array().cloned()) {
+ eprintln!("[prefetch] {} -> {} candles fetched", symbol, candles.len());
+
+ // Insert candles into candle_cache
+ // Fyers format: [timestamp, O, H, L, C, V]
+ let mut inserted = 0;
+ for candle in &candles {
+ if let Some(arr) = candle.as_array() {
+ if arr.len() >= 6 {
+ let open_time = arr[0].as_i64().unwrap_or(0);
+ let o = arr[1].as_f64().unwrap_or(0.0);
+ let h = arr[2].as_f64().unwrap_or(0.0);
+ let l = arr[3].as_f64().unwrap_or(0.0);
+ let c = arr[4].as_f64().unwrap_or(0.0);
+ let v = arr[5].as_f64().unwrap_or(0.0);
+
+ let _ = 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)",
+ rusqlite::params![symbol, "fyers", timeframe, open_time, o, h, l, c, v],
+ );
+ inserted += 1;
+ }
+ }
+ }
+ eprintln!("[prefetch] {} -> {} candles inserted into cache", symbol, inserted);
+ }
+ } else {
+ eprintln!("[prefetch] {} fetch failed: {:?}", symbol, response.error);
+ }
+ }
+ Err(e) => {
+ eprintln!("[prefetch] {} fetch error: {}", symbol, e);
+ }
+ }
+ }
+
+ Ok(())
+}
+
+// ============================================================================
+// CANDLE CACHE
+// ============================================================================
+
+/// Read aggregated candles from cache
+#[tauri::command]
+pub async fn get_candle_cache(
+ symbol: String,
+ timeframe: Option<String>,
+ limit: Option<i32>,
+) -> Result<String, String> {
+ let conn = get_db().map_err(|e| e.to_string())?;
+ let tf = timeframe.unwrap_or_else(|| "5m".to_string());
+ let row_limit = limit.unwrap_or(200);
+
+ let mut stmt = conn
+ .prepare(
+ "SELECT symbol, provider, timeframe, open_time, o, h, l, c, volume, is_closed
+ FROM candle_cache
+ WHERE symbol = ?1 AND timeframe = ?2
+ ORDER BY open_time DESC LIMIT ?3",
+ )
+ .map_err(|e| format!("Failed to prepare query: {}", e))?;
+
+ let rows = stmt
+ .query_map(rusqlite::params![symbol, tf, row_limit], |row| {
+ Ok(json!({
+ "symbol": row.get::<_, String>(0)?,
+ "provider": row.get::<_, String>(1)?,
+ "timeframe": row.get::<_, String>(2)?,
+ "open_time": row.get::<_, i64>(3)?,
+ "o": row.get::<_, f64>(4)?,
+ "h": row.get::<_, f64>(5)?,
+ "l": row.get::<_, f64>(6)?,
+ "c": row.get::<_, f64>(7)?,
+ "volume": row.get::<_, f64>(8)?,
+ "is_closed": row.get::<_, i32>(9)?,
+ }))
+ })
+ .map_err(|e| format!("Failed to query candles: {}", e))?;
+
+ let candles: Vec<serde_json::Value> = rows.filter_map(|r| r.ok()).collect();
+
+ Ok(json!({
+ "success": true,
+ "data": candles,
+ "count": candles.len()
+ }).to_string())
+}
+
+// ============================================================================
+// CONDITION EVALUATION (ONE-SHOT PREVIEW)
+// ============================================================================
+
+/// Evaluate conditions once against current data (for builder UI preview)
+#[tauri::command]
+pub async fn evaluate_conditions_once(
+ app: tauri::AppHandle,
+ conditions: String,
+ symbol: String,
+ timeframe: Option<String>,
+) -> Result<String, String> {
+ use std::process::Command;
+
+ let scripts_dir = get_algo_scripts_dir(&app)?;
+ let evaluator_path = scripts_dir.join("condition_evaluator.py");
+ let db_path = get_main_db_path_str()?;
+ let tf = timeframe.unwrap_or_else(|| "5m".to_string());
+
+ if !evaluator_path.exists() {
+ return Ok(json!({
+ "success": false,
+ "error": "condition_evaluator.py not found"
+ }).to_string());
+ }
+
+ let output = Command::new("python")
+ .arg(&evaluator_path)
+ .arg("--mode")
+ .arg("once")
+ .arg("--conditions")
+ .arg(&conditions)
+ .arg("--symbol")
+ .arg(&symbol)
+ .arg("--timeframe")
+ .arg(&tf)
+ .arg("--db")
+ .arg(&db_path)
+ .output()
+ .map_err(|e| format!("Failed to evaluate conditions: {}", e))?;
+
+ if output.status.success() {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&stdout) {
+ Ok(parsed.to_string())
+ } else {
+ Ok(json!({ "success": true, "raw": stdout.to_string() }).to_string())
+ }
+ } else {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ Ok(json!({
+ "success": false,
+ "error": format!("Evaluation failed: {}", stderr)
+ }).to_string())
+ }
+}
+
+// ============================================================================
+// CANDLE AGGREGATION CONTROL
+// ============================================================================
+
+/// Start candle aggregation for a symbol+timeframe
+/// (Registers the symbol with the CandleAggregator service)
+#[tauri::command]
+pub async fn start_candle_aggregation(
+ state: tauri::State<'_, crate::WebSocketState>,
+ symbol: String,
+ timeframe: Option<String>,
+) -> Result<String, String> {
+ let tf = timeframe.unwrap_or_else(|| "5m".to_string());
+
+ // Register with the live CandleAggregator service
+ let services = state.services.read().await;
+ services
+ .candle_aggregator
+ .add_subscription(symbol.clone(), tf.clone())
+ .await;
+
+ Ok(json!({
+ "success": true,
+ "symbol": symbol,
+ "timeframe": tf,
+ "message": "Candle aggregation started"
+ }).to_string())
+}
+
+/// Stop candle aggregation for a symbol+timeframe
+#[tauri::command]
+pub async fn stop_candle_aggregation(
+ state: tauri::State<'_, crate::WebSocketState>,
+ symbol: String,
+ timeframe: Option<String>,
+) -> Result<String, String> {
+ let tf = timeframe.unwrap_or_else(|| "5m".to_string());
+
+ // Unregister from the live CandleAggregator service
+ let services = state.services.read().await;
+ services
+ .candle_aggregator
+ .remove_subscription(symbol.clone(), tf.clone())
+ .await;
+
+ Ok(json!({
+ "success": true,
+ "symbol": symbol,
+ "timeframe": tf,
+ "message": "Candle aggregation stopped"
+ }).to_string())
+}
+
+// ============================================================================
+// BACKTEST
+// ============================================================================
+
+/// Run a walk-forward backtest using historical data (via yfinance)
+#[tauri::command]
+pub async fn run_algo_backtest(
+ app: tauri::AppHandle,
+ symbol: String,
+ entry_conditions: String,
+ exit_conditions: String,
+ timeframe: Option<String>,
+ period: Option<String>,
+ stop_loss: Option<f64>,
+ take_profit: Option<f64>,
+ initial_capital: Option<f64>,
+) -> Result<String, String> {
+ use std::process::Command;
+
+ let scripts_dir = get_algo_scripts_dir(&app)?;
+ let backtest_path = scripts_dir.join("backtest_engine.py");
+
+ if !backtest_path.exists() {
+ return Ok(json!({
+ "success": false,
+ "error": "backtest_engine.py not found"
+ }).to_string());
+ }
+
+ let tf = timeframe.unwrap_or_else(|| "1d".to_string());
+ let pd = period.unwrap_or_else(|| "1y".to_string());
+ let sl = stop_loss.unwrap_or(0.0);
+ let tp = take_profit.unwrap_or(0.0);
+ let capital = initial_capital.unwrap_or(100000.0);
+
+ let output = Command::new("python")
+ .arg(&backtest_path)
+ .arg("--symbol")
+ .arg(&symbol)
+ .arg("--entry-conditions")
+ .arg(&entry_conditions)
+ .arg("--exit-conditions")
+ .arg(&exit_conditions)
+ .arg("--timeframe")
+ .arg(&tf)
+ .arg("--period")
+ .arg(&pd)
+ .arg("--stop-loss")
+ .arg(sl.to_string())
+ .arg("--take-profit")
+ .arg(tp.to_string())
+ .arg("--initial-capital")
+ .arg(capital.to_string())
+ .output()
+ .map_err(|e| format!("Failed to run backtest: {}", e))?;
+
+ let stdout = String::from_utf8_lossy(&output.stdout).to_string();
+ let stderr = String::from_utf8_lossy(&output.stderr).to_string();
+
+ if !output.status.success() {
+ return Ok(json!({
+ "success": false,
+ "error": format!("Backtest process failed: {}", stderr.trim())
+ }).to_string());
+ }
+
+ // Return the raw JSON from Python
+ if stdout.trim().is_empty() {
+ return Ok(json!({
+ "success": false,
+ "error": "Backtest returned no output"
+ }).to_string());
+ }
+
+ Ok(stdout.trim().to_string())
+}
+
+// ============================================================================
+// ORDER SIGNAL BRIDGE
+// ============================================================================
+// Background task that polls `algo_order_signals` for pending signals written
+// by Python live runners in "live" mode. Executes orders via the existing
+// unified trading system and updates signal status.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+
+static ORDER_BRIDGE_RUNNING: AtomicBool = AtomicBool::new(false);
+
+/// Start the order signal polling bridge (idempotent — only one instance runs)
+#[tauri::command]
+pub async fn start_order_signal_bridge(
+ app: tauri::AppHandle,
+) -> Result<String, String> {
+ if ORDER_BRIDGE_RUNNING.swap(true, Ordering::SeqCst) {
+ return Ok(json!({
+ "success": true,
+ "message": "Order bridge already running"
+ }).to_string());
+ }
+
+ let app_handle = app.clone();
+
+ tokio::spawn(async move {
+ println!("[AlgoOrderBridge] Starting order signal polling...");
+
+ loop {
+ // Check if we should still be running
+ if !ORDER_BRIDGE_RUNNING.load(Ordering::SeqCst) {
+ break;
+ }
+
+ // Poll for pending signals
+ match poll_and_execute_signals(&app_handle).await {
+ Ok(count) => {
+ if count > 0 {
+ println!("[AlgoOrderBridge] Executed {} order signal(s)", count);
+ }
+ }
+ Err(e) => {
+ eprintln!("[AlgoOrderBridge] Error polling signals: {}", e);
+ }
+ }
+
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
+ }
+
+ println!("[AlgoOrderBridge] Order signal polling stopped");
+ ORDER_BRIDGE_RUNNING.store(false, Ordering::SeqCst);
+ });
+
+ Ok(json!({
+ "success": true,
+ "message": "Order bridge started"
+ }).to_string())
+}
+
+/// Stop the order signal polling bridge
+#[tauri::command]
+pub async fn stop_order_signal_bridge() -> Result<String, String> {
+ ORDER_BRIDGE_RUNNING.store(false, Ordering::SeqCst);
+ Ok(json!({
+ "success": true,
+ "message": "Order bridge stopping"
+ }).to_string())
+}
+
+/// Poll `algo_order_signals` for pending signals and execute them
+async fn poll_and_execute_signals(
+ app_handle: &tauri::AppHandle,
+) -> Result<usize, String> {
+ use crate::commands::unified_trading::{UnifiedOrder, unified_place_order};
+
+ // Read pending signals from DB
+ let signals = tokio::task::spawn_blocking(|| -> Result<Vec<(String, String, String, f64, String, Option<f64>)>, String> {
+ let conn = get_db().map_err(|e| e.to_string())?;
+ let mut stmt = conn
+ .prepare(
+ "SELECT id, symbol, side, quantity, order_type, price
+ FROM algo_order_signals
+ WHERE status = 'pending'
+ ORDER BY created_at ASC
+ LIMIT 10",
+ )
+ .map_err(|e| format!("Failed to query signals: {}", e))?;
+
+ let rows = stmt
+ .query_map([], |row| {
+ Ok((
+ row.get::<_, String>(0)?,
+ row.get::<_, String>(1)?,
+ row.get::<_, String>(2)?,
+ row.get::<_, f64>(3)?,
+ row.get::<_, String>(4)?,
+ row.get::<_, Option<f64>>(5)?,
+ ))
+ })
+ .map_err(|e| format!("Failed to read signals: {}", e))?;
+
+ let mut result = Vec::new();
+ for row in rows {
+ if let Ok(r) = row {
+ result.push(r);
+ }
+ }
+ Ok(result)
+ })
+ .await
+ .map_err(|e| format!("Spawn blocking error: {}", e))??;
+
+ if signals.is_empty() {
+ return Ok(0);
+ }
+
+ let mut executed = 0;
+
+ for (signal_id, symbol, side, quantity, order_type, price) in &signals {
+ // Emit algo_signal event to notify frontend that a condition matched
+ let _ = app_handle.emit(
+ "algo_signal",
+ json!({
+ "signal_id": signal_id,
+ "symbol": symbol,
+ "side": side,
+ "quantity": quantity,
+ "order_type": order_type,
+ }),
+ );
+
+ // Mark as processing
+ let sid = signal_id.clone();
+ let _ = tokio::task::spawn_blocking(move || {
+ if let Ok(conn) = get_db() {
+ let _ = conn.execute(
+ "UPDATE algo_order_signals SET status = 'processing' WHERE id = ?1",
+ rusqlite::params![sid],
+ );
+ }
+ })
+ .await;
+
+ // Build the UnifiedOrder
+ // Parse exchange from symbol (e.g., "NSE:RELIANCE" -> exchange="NSE", symbol="RELIANCE")
+ let (exchange, clean_symbol) = if symbol.contains(':') {
+ let parts: Vec<&str> = symbol.splitn(2, ':').collect();
+ (parts[0].to_string(), parts[1].to_string())
+ } else {
+ ("NSE".to_string(), symbol.clone())
+ };
+
+ let order = UnifiedOrder {
+ symbol: clean_symbol,
+ exchange,
+ side: side.to_lowercase(),
+ order_type: order_type.to_lowercase(),
+ quantity: *quantity,
+ price: *price,
+ stop_price: None,
+ product_type: Some("MIS".to_string()),
+ };
+
+ // Execute via unified trading system
+ let result = unified_place_order(order).await;
+
+ let success = result.is_ok() && result.as_ref().map(|r| r.success).unwrap_or(false);
+ let result_msg = match &result {
+ Ok(r) => r.message.clone().unwrap_or_default(),
+ Err(e) => e.clone(),
+ };
+
+ // Update signal status
+ let sid = signal_id.clone();
+ let status = if success { "filled" } else { "failed" };
+ let result_json = json!({
+ "success": success,
+ "message": result_msg,
+ })
+ .to_string();
+
+ let _ = tokio::task::spawn_blocking(move || {
+ if let Ok(conn) = get_db() {
+ let _ = conn.execute(
+ "UPDATE algo_order_signals SET status = ?1, result = ?2, executed_at = CURRENT_TIMESTAMP WHERE id = ?3",
+ rusqlite::params![status, result_json, sid],
+ );
+ }
+ })
+ .await;
+
+ // Emit event to frontend
+ let _ = app_handle.emit(
+ "algo_trade_executed",
+ json!({
+ "signal_id": signal_id,
+ "symbol": symbol,
+ "side": side,
+ "quantity": quantity,
+ "success": success,
+ "message": result_msg,
+ }),
+ );
+
+ if success {
+ executed += 1;
+ }
+ }
+
+ Ok(executed)
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs
index 1dab6bef4..3c135992d 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs
@@ -336,88 +336,6 @@ pub async fn get_alpha_evaluation(
execute_alpha_arena_action(&app, "get_evaluation", params, None).await
}
-/// Get stored API keys (masked for display)
-#[command]
-pub async fn get_alpha_api_keys() -> Result<Value, String> {
- eprintln!("[Alpha Arena v2] get_alpha_api_keys called");
-
- let conn = crate::database::pool::get_db()
- .map_err(|e| format!("Failed to get database connection: {}", e))?;
-
- // Create table if not exists
- conn.execute(
- "CREATE TABLE IF NOT EXISTS api_keys (
- provider TEXT PRIMARY KEY,
- api_key TEXT NOT NULL
- )",
- [],
- )
- .map_err(|e| format!("Failed to create api_keys table: {}", e))?;
-
- // Fetch all keys and mask them for display
- let mut stmt = conn
- .prepare("SELECT provider, api_key FROM api_keys")
- .map_err(|e| format!("Failed to prepare statement: {}", e))?;
-
- let mut keys: HashMap<String, String> = HashMap::new();
- let rows = stmt
- .query_map([], |row| {
- Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
- })
- .map_err(|e| format!("Failed to query api_keys: {}", e))?;
-
- for row in rows {
- if let Ok((provider, key)) = row {
- if !key.is_empty() {
- let masked = if key.len() > 8 {
- format!("{}...{}", &key[..4], &key[key.len()-4..])
- } else {
- "*".repeat(key.len())
- };
- keys.insert(provider, masked);
- }
- }
- }
-
- Ok(json!({
- "success": true,
- "keys": keys
- }))
-}
-
-/// Save API keys to database
-#[command]
-pub async fn save_alpha_api_keys(keys: HashMap<String, String>) -> Result<Value, String> {
- eprintln!("[Alpha Arena v2] save_alpha_api_keys called");
-
- let conn = crate::database::pool::get_db()
- .map_err(|e| format!("Failed to get database connection: {}", e))?;
-
- // Create table if not exists
- conn.execute(
- "CREATE TABLE IF NOT EXISTS api_keys (
- provider TEXT PRIMARY KEY,
- api_key TEXT NOT NULL
- )",
- [],
- )
- .map_err(|e| format!("Failed to create api_keys table: {}", e))?;
-
- // Insert/update each key
- for (provider, key) in &keys {
- conn.execute(
- "INSERT OR REPLACE INTO api_keys (provider, api_key) VALUES (?1, ?2)",
- rusqlite::params![provider, key],
- )
- .map_err(|e| format!("Failed to save api key for {}: {}", provider, e))?;
- }
-
- Ok(json!({
- "success": true,
- "message": format!("Saved {} API keys to database", keys.len())
- }))
-}
-
/// List all competitions from the database
#[command]
pub async fn list_alpha_competitions(app: AppHandle, limit: Option<u32>) -> Result<Value, String> {
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/angelone.rs b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/angelone.rs
new file mode 100644
index 000000000..7f9ec54c4
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/angelone.rs
@@ -0,0 +1,338 @@
+//! Angel One (SmartAPI) Master Contract Download
+//!
+//! Downloads and parses Angel One instruments from public JSON endpoint.
+//! No authentication required for master contract download.
+//! Transforms to unified symbol format following OpenAlgo pattern.
+
+use crate::database::symbol_master::{
+ complete_master_contract_download, normalize_index_symbol, update_status, DownloadStatus,
+ SymbolRecord,
+};
+use anyhow::{Context, Result};
+use serde::{Deserialize, Serialize};
+use tauri::command;
+
+const BROKER_ID: &str = "angelone";
+const INSTRUMENTS_URL: &str = "https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json";
+
+/// Angel One JSON instrument structure
+#[derive(Debug, Deserialize)]
+struct AngelInstrument {
+ token: String,
+ symbol: String,
+ name: String,
+ expiry: Option<String>,
+ strike: Option<String>,
+ lotsize: Option<String>,
+ instrumenttype: Option<String>,
+ exch_seg: String,
+ tick_size: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DownloadResponse {
+ pub success: bool,
+ pub message: String,
+ pub total_symbols: i64,
+}
+
+/// Download and process Angel One master contract
+/// No authentication required
+#[command]
+pub async fn angelone_download_symbols() -> DownloadResponse {
+ match download_angelone_symbols().await {
+ Ok(count) => DownloadResponse {
+ success: true,
+ message: format!("Successfully downloaded {} symbols", count),
+ total_symbols: count,
+ },
+ Err(e) => {
+ let _ = update_status(
+ BROKER_ID,
+ DownloadStatus::Error,
+ &format!("Download failed: {}", e),
+ None,
+ );
+ DownloadResponse {
+ success: false,
+ message: format!("Download failed: {}", e),
+ total_symbols: 0,
+ }
+ }
+ }
+}
+
+async fn download_angelone_symbols() -> Result<i64> {
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ "Starting Angel One symbol download...",
+ None,
+ )?;
+
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(120))
+ .build()?;
+
+ let response = client
+ .get(INSTRUMENTS_URL)
+ .send()
+ .await
+ .context("Failed to fetch Angel One instruments")?;
+
+ if !response.status().is_success() {
+ return Err(anyhow::anyhow!(
+ "Angel One API returned status: {}",
+ response.status()
+ ));
+ }
+
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ "Parsing instruments...",
+ None,
+ )?;
+
+ let instruments: Vec<AngelInstrument> = response
+ .json()
+ .await
+ .context("Failed to parse Angel One JSON")?;
+
+ eprintln!("[angelone] Downloaded {} raw instruments", instruments.len());
+
+ let symbols: Vec<SymbolRecord> = instruments
+ .into_iter()
+ .filter_map(|inst| convert_angel_instrument(inst))
+ .collect();
+
+ if symbols.is_empty() {
+ return Err(anyhow::anyhow!("No symbols parsed from Angel One response"));
+ }
+
+ eprintln!("[angelone] Parsed {} symbols", symbols.len());
+
+ // Use the unified complete_master_contract_download
+ let count = complete_master_contract_download(BROKER_ID, &symbols)?;
+
+ Ok(count)
+}
+
+fn convert_angel_instrument(inst: AngelInstrument) -> Option<SymbolRecord> {
+ let exchange = &inst.exch_seg;
+ let instrument_type = inst.instrumenttype.as_deref().unwrap_or("");
+
+ // Determine unified exchange (handle indices)
+ let unified_exchange = if instrument_type == "AMXIDX" {
+ match exchange.as_str() {
+ "NSE" => "NSE_INDEX",
+ "BSE" => "BSE_INDEX",
+ "MCX" => "MCX_INDEX",
+ _ => exchange.as_str(),
+ }
+ } else {
+ exchange.as_str()
+ };
+
+ // Parse strike price (Angel sends strike * 100)
+ let strike: f64 = inst
+ .strike
+ .as_ref()
+ .and_then(|s| s.parse::<f64>().ok())
+ .unwrap_or(0.0)
+ / 100.0;
+
+ // Additional strike adjustment for CDS options
+ let strike = if (instrument_type == "OPTCUR" || instrument_type == "OPTIRC")
+ && exchange == "CDS"
+ {
+ strike / 1000.0
+ } else {
+ strike
+ };
+
+ // Parse lot size
+ let lot_size: i32 = inst
+ .lotsize
+ .as_ref()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(1);
+
+ // Parse tick size (Angel sends tick_size * 100)
+ let tick_size: f64 = inst
+ .tick_size
+ .as_ref()
+ .and_then(|s| s.parse::<f64>().ok())
+ .unwrap_or(5.0)
+ / 100.0;
+
+ // Format expiry date from 19MAR2024 to 19-MAR-24
+ let expiry = inst.expiry.as_ref().map(|e| format_angel_expiry(e));
+
+ // Clean broker symbol (remove -EQ, -BE, -MF, -SG suffixes)
+ let clean_symbol = inst
+ .symbol
+ .replace("-EQ", "")
+ .replace("-BE", "")
+ .replace("-MF", "")
+ .replace("-SG", "");
+
+ // Build unified symbol
+ let unified_symbol = build_unified_symbol(
+ &inst.name,
+ &clean_symbol,
+ &expiry,
+ strike,
+ instrument_type,
+ exchange,
+ );
+
+ // Normalize instrument type to standard format (CE, PE, FUT, EQ)
+ let normalized_inst_type = normalize_instrument_type(instrument_type, &unified_symbol);
+
+ // Normalize name for indices
+ let normalized_name = normalize_index_symbol(&inst.name);
+
+ Some(SymbolRecord {
+ id: None,
+ broker_id: BROKER_ID.to_string(),
+ symbol: unified_symbol,
+ br_symbol: inst.symbol.clone(),
+ name: Some(normalized_name),
+ exchange: unified_exchange.to_string(),
+ br_exchange: Some(exchange.to_string()),
+ token: inst.token,
+ expiry,
+ strike: if strike > 0.0 { Some(strike) } else { None },
+ lot_size: Some(lot_size),
+ instrument_type: Some(normalized_inst_type),
+ tick_size: Some(tick_size),
+ segment: Some(exchange.to_string()),
+ })
+}
+
+/// Format Angel expiry from 19MAR2024 to 19-MAR-24
+fn format_angel_expiry(expiry: &str) -> String {
+ if expiry.len() >= 9 {
+ // Format: DDMMMYYYY (e.g., 19MAR2024)
+ let day = &expiry[0..2];
+ let month = &expiry[2..5];
+ let year = &expiry[7..9]; // Last 2 digits
+
+ format!("{}-{}-{}", day, month.to_uppercase(), year)
+ } else if expiry.len() == 7 {
+ // Format: DDMMMYY (e.g., 19MAR24)
+ let day = &expiry[0..2];
+ let month = &expiry[2..5];
+ let year = &expiry[5..7];
+
+ format!("{}-{}-{}", day, month.to_uppercase(), year)
+ } else {
+ expiry.to_uppercase()
+ }
+}
+
+/// Build unified symbol format
+fn build_unified_symbol(
+ name: &str,
+ symbol: &str,
+ expiry: &Option<String>,
+ strike: f64,
+ instrument_type: &str,
+ exchange: &str,
+) -> String {
+ let normalized_name = normalize_index_symbol(name);
+
+ match instrument_type {
+ // Equity
+ "" | "AMXIDX" => normalized_name,
+
+ // Futures
+ "FUTIDX" | "FUTSTK" | "FUTCOM" | "FUTCUR" | "FUTIRC" | "FUTIRT" => {
+ if let Some(exp) = expiry {
+ let exp_formatted = exp.replace("-", "");
+ format!("{}{}FUT", normalized_name, exp_formatted)
+ } else {
+ normalized_name
+ }
+ }
+
+ // Options
+ "OPTIDX" | "OPTSTK" | "OPTFUT" | "OPTCUR" | "OPTIRC" => {
+ if let Some(exp) = expiry {
+ let exp_formatted = exp.replace("-", "");
+ let strike_str = format_strike(strike);
+ // Get option type from symbol suffix
+ let opt_type = if symbol.ends_with("CE") {
+ "CE"
+ } else if symbol.ends_with("PE") {
+ "PE"
+ } else {
+ return normalized_name;
+ };
+ format!(
+ "{}{}{}{}",
+ normalized_name, exp_formatted, strike_str, opt_type
+ )
+ } else {
+ normalized_name
+ }
+ }
+
+ _ => normalized_name,
+ }
+}
+
+/// Normalize instrument type to standard format (CE, PE, FUT, EQ)
+fn normalize_instrument_type(instrument_type: &str, symbol: &str) -> String {
+ match instrument_type {
+ // Futures
+ "FUTIDX" | "FUTSTK" | "FUTCOM" | "FUTCUR" | "FUTIRC" | "FUTIRT" => "FUT".to_string(),
+
+ // Options - determine CE/PE from symbol
+ "OPTIDX" | "OPTSTK" | "OPTFUT" | "OPTCUR" | "OPTIRC" => {
+ if symbol.ends_with("CE") {
+ "CE".to_string()
+ } else if symbol.ends_with("PE") {
+ "PE".to_string()
+ } else {
+ instrument_type.to_string()
+ }
+ }
+
+ // Index
+ "AMXIDX" => "INDEX".to_string(),
+
+ // Equity or other
+ "" => "EQ".to_string(),
+
+ _ => instrument_type.to_string(),
+ }
+}
+
+/// Format strike price (remove trailing .0)
+fn format_strike(strike: f64) -> String {
+ if strike.fract() == 0.0 {
+ format!("{}", strike as i64)
+ } else {
+ format!("{}", strike)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_format_angel_expiry() {
+ assert_eq!(format_angel_expiry("19MAR2024"), "19-MAR-24");
+ assert_eq!(format_angel_expiry("26DEC2024"), "26-DEC-24");
+ assert_eq!(format_angel_expiry("19MAR24"), "19-MAR-24");
+ }
+
+ #[test]
+ fn test_format_strike() {
+ assert_eq!(format_strike(24000.0), "24000");
+ assert_eq!(format_strike(24000.5), "24000.5");
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/dhan.rs b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/dhan.rs
new file mode 100644
index 000000000..0c3623793
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/dhan.rs
@@ -0,0 +1,279 @@
+//! Dhan Master Contract Download
+//!
+//! Downloads and parses Dhan instruments from public CSV endpoint.
+//! No authentication required for instrument download.
+//! Transforms to unified symbol format following OpenAlgo pattern.
+
+use crate::database::symbol_master::{
+ complete_master_contract_download, normalize_index_symbol, update_status, DownloadStatus,
+ SymbolRecord,
+};
+use anyhow::{Context, Result};
+use serde::{Deserialize, Serialize};
+use tauri::command;
+
+const BROKER_ID: &str = "dhan";
+
+// Dhan CSV endpoints (compact format)
+const DHAN_CSV_URLS: &[(&str, &str)] = &[
+ ("NSE_EQ", "https://images.dhan.co/api-data/api-scrip-master-NSE_EQ.csv"),
+ ("NSE_FNO", "https://images.dhan.co/api-data/api-scrip-master-NSE_FNO.csv"),
+ ("NSE_CURRENCY", "https://images.dhan.co/api-data/api-scrip-master-NSE_CURRENCY.csv"),
+ ("BSE_EQ", "https://images.dhan.co/api-data/api-scrip-master-BSE_EQ.csv"),
+ ("BSE_FNO", "https://images.dhan.co/api-data/api-scrip-master-BSE_FNO.csv"),
+ ("BSE_CURRENCY", "https://images.dhan.co/api-data/api-scrip-master-BSE_CURRENCY.csv"),
+ ("MCX_COMM", "https://images.dhan.co/api-data/api-scrip-master-MCX_COMM.csv"),
+ ("IDX_NSE", "https://images.dhan.co/api-data/api-scrip-master-IDX_NSE.csv"),
+ ("IDX_BSE", "https://images.dhan.co/api-data/api-scrip-master-IDX_BSE.csv"),
+];
+
+/// Dhan CSV columns (0-based)
+/// SEM_EXM_EXCH_ID,SEM_SEGMENT,SEM_SMST_SECURITY_ID,SEM_INSTRUMENT_NAME,SEM_EXCH_INSTRUMENT_TYPE,
+/// SEM_TRADING_SYMBOL,SEM_LOT_UNITS,SEM_TICK_SIZE,SEM_EXPIRY_FLAG,SEM_EXPIRY_DATE,SEM_STRIKE_PRICE,
+/// SEM_OPTION_TYPE,SEM_CUSTOM_SYMBOL,SEM_ISIN
+const COL_EXCHANGE: usize = 0;
+const COL_SEGMENT: usize = 1;
+const COL_SECURITY_ID: usize = 2;
+const COL_INSTRUMENT_NAME: usize = 3;
+const COL_INSTRUMENT_TYPE: usize = 4;
+const COL_TRADING_SYMBOL: usize = 5;
+const COL_LOT_SIZE: usize = 6;
+const COL_TICK_SIZE: usize = 7;
+const COL_EXPIRY_DATE: usize = 9;
+const COL_STRIKE: usize = 10;
+const COL_OPTION_TYPE: usize = 11;
+const COL_CUSTOM_SYMBOL: usize = 12;
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DownloadResponse {
+ pub success: bool,
+ pub message: String,
+ pub total_symbols: i64,
+}
+
+/// Download and process Dhan master contract
+#[command]
+pub async fn dhan_download_symbols() -> DownloadResponse {
+ match download_dhan_symbols().await {
+ Ok(count) => DownloadResponse {
+ success: true,
+ message: format!("Successfully downloaded {} symbols", count),
+ total_symbols: count,
+ },
+ Err(e) => {
+ let _ = update_status(
+ BROKER_ID,
+ DownloadStatus::Error,
+ &format!("Download failed: {}", e),
+ None,
+ );
+ DownloadResponse {
+ success: false,
+ message: format!("Download failed: {}", e),
+ total_symbols: 0,
+ }
+ }
+ }
+}
+
+async fn download_dhan_symbols() -> Result<i64> {
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ "Starting Dhan symbol download...",
+ None,
+ )?;
+
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(120))
+ .build()?;
+
+ let mut all_symbols: Vec<SymbolRecord> = Vec::new();
+
+ for (segment, url) in DHAN_CSV_URLS {
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ &format!("Downloading {}...", segment),
+ None,
+ )?;
+
+ match download_and_parse_dhan(&client, url, segment).await {
+ Ok(symbols) => {
+ eprintln!("[dhan] Downloaded {} symbols from {}", symbols.len(), segment);
+ all_symbols.extend(symbols);
+ }
+ Err(e) => {
+ eprintln!("[dhan] Error downloading {}: {}", segment, e);
+ }
+ }
+ }
+
+ if all_symbols.is_empty() {
+ return Err(anyhow::anyhow!("No symbols downloaded from any segment"));
+ }
+
+ let count = complete_master_contract_download(BROKER_ID, &all_symbols)?;
+ Ok(count)
+}
+
+async fn download_and_parse_dhan(
+ client: &reqwest::Client,
+ url: &str,
+ segment: &str,
+) -> Result<Vec<SymbolRecord>> {
+ let response = client
+ .get(url)
+ .send()
+ .await
+ .context(format!("Failed to fetch {}", url))?;
+
+ let csv_text = response
+ .text()
+ .await
+ .context(format!("Failed to read response from {}", url))?;
+
+ parse_dhan_csv(&csv_text, segment)
+}
+
+fn parse_dhan_csv(csv_text: &str, segment: &str) -> Result<Vec<SymbolRecord>> {
+ let mut symbols = Vec::new();
+ let mut lines = csv_text.lines();
+
+ // Skip header
+ if let Some(header) = lines.next() {
+ eprintln!("[dhan] CSV header: {}", header);
+ }
+
+ for line in lines {
+ if line.trim().is_empty() {
+ continue;
+ }
+
+ let fields: Vec<&str> = line.split(',').collect();
+ if fields.len() < 13 {
+ continue;
+ }
+
+ if let Some(symbol) = parse_dhan_row(&fields, segment) {
+ symbols.push(symbol);
+ }
+ }
+
+ Ok(symbols)
+}
+
+fn parse_dhan_row(fields: &[&str], segment: &str) -> Option<SymbolRecord> {
+ let exchange = fields.get(COL_EXCHANGE)?.trim();
+ let segment_code = fields.get(COL_SEGMENT)?.trim();
+ let security_id = fields.get(COL_SECURITY_ID)?.trim();
+ let instrument_name = fields.get(COL_INSTRUMENT_NAME)?.trim();
+ let instrument_type = fields.get(COL_INSTRUMENT_TYPE)?.trim();
+ let trading_symbol = fields.get(COL_TRADING_SYMBOL)?.trim();
+ let lot_size: i32 = fields.get(COL_LOT_SIZE)?.trim().parse().unwrap_or(1);
+ let tick_size: f64 = fields.get(COL_TICK_SIZE)?.trim().parse().unwrap_or(0.05);
+ let expiry_raw = fields.get(COL_EXPIRY_DATE)?.trim();
+ let strike: f64 = fields.get(COL_STRIKE)?.trim().parse().unwrap_or(0.0);
+ let option_type = fields.get(COL_OPTION_TYPE)?.trim();
+ let custom_symbol = fields.get(COL_CUSTOM_SYMBOL)?.trim();
+
+ // Determine unified exchange
+ let unified_exchange = match segment {
+ "IDX_NSE" => "NSE_INDEX",
+ "IDX_BSE" => "BSE_INDEX",
+ "NSE_EQ" => "NSE",
+ "BSE_EQ" => "BSE",
+ "NSE_FNO" => "NFO",
+ "BSE_FNO" => "BFO",
+ "NSE_CURRENCY" => "CDS",
+ "BSE_CURRENCY" => "BCD",
+ "MCX_COMM" => "MCX",
+ _ => exchange,
+ };
+
+ // Format expiry
+ let expiry = format_dhan_expiry(expiry_raw);
+
+ // Determine instrument type
+ let inst_type = match option_type {
+ "CE" => "CE",
+ "PE" => "PE",
+ "" if instrument_type.contains("FUT") => "FUT",
+ "" if instrument_type.contains("IDX") => "INDEX",
+ "" => "EQ",
+ _ => option_type,
+ };
+
+ // Build unified symbol
+ let name = normalize_index_symbol(instrument_name);
+ let unified_symbol = build_unified_symbol(&name, &expiry, strike, inst_type);
+
+ Some(SymbolRecord {
+ id: None,
+ broker_id: BROKER_ID.to_string(),
+ symbol: unified_symbol,
+ br_symbol: trading_symbol.to_string(),
+ name: Some(name),
+ exchange: unified_exchange.to_string(),
+ br_exchange: Some(exchange.to_string()),
+ token: security_id.to_string(),
+ expiry,
+ strike: if strike > 0.0 { Some(strike) } else { None },
+ lot_size: Some(lot_size),
+ instrument_type: Some(inst_type.to_string()),
+ tick_size: Some(tick_size),
+ segment: Some(segment.to_string()),
+ })
+}
+
+fn format_dhan_expiry(expiry: &str) -> Option<String> {
+ if expiry.is_empty() || expiry == "0" {
+ return None;
+ }
+
+ // Dhan format: YYYY-MM-DD
+ let parts: Vec<&str> = expiry.split('-').collect();
+ if parts.len() == 3 {
+ let year = parts[0];
+ let month: u32 = parts[1].parse().unwrap_or(1);
+ let day = parts[2];
+
+ let month_str = match month {
+ 1 => "JAN", 2 => "FEB", 3 => "MAR", 4 => "APR",
+ 5 => "MAY", 6 => "JUN", 7 => "JUL", 8 => "AUG",
+ 9 => "SEP", 10 => "OCT", 11 => "NOV", 12 => "DEC",
+ _ => "JAN",
+ };
+
+ let year_short = if year.len() >= 2 { &year[year.len() - 2..] } else { year };
+ return Some(format!("{}-{}-{}", day, month_str, year_short));
+ }
+
+ Some(expiry.to_uppercase())
+}
+
+fn build_unified_symbol(name: &str, expiry: &Option<String>, strike: f64, inst_type: &str) -> String {
+ match inst_type {
+ "EQ" | "INDEX" => name.to_string(),
+ "FUT" => {
+ if let Some(exp) = expiry {
+ format!("{}{}FUT", name, exp.replace("-", ""))
+ } else {
+ name.to_string()
+ }
+ }
+ "CE" | "PE" => {
+ if let Some(exp) = expiry {
+ let strike_str = if strike.fract() == 0.0 {
+ format!("{}", strike as i64)
+ } else {
+ format!("{}", strike)
+ };
+ format!("{}{}{}{}", name, exp.replace("-", ""), strike_str, inst_type)
+ } else {
+ name.to_string()
+ }
+ }
+ _ => name.to_string(),
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/fyers.rs b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/fyers.rs
new file mode 100644
index 000000000..10fe59b26
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/fyers.rs
@@ -0,0 +1,381 @@
+//! Fyers Master Contract Download
+//!
+//! Downloads and parses Fyers symbol master from public CSVs.
+//! Transforms to unified symbol format following OpenAlgo pattern.
+
+use crate::database::symbol_master::{
+ complete_master_contract_download, normalize_index_symbol, update_status, DownloadStatus,
+ SymbolRecord,
+};
+use anyhow::{Context, Result};
+use serde::{Deserialize, Serialize};
+use tauri::command;
+
+const BROKER_ID: &str = "fyers";
+
+/// Fyers CSV URLs
+const FYERS_CSV_URLS: &[(&str, &str)] = &[
+ ("NSE_CM", "https://public.fyers.in/sym_details/NSE_CM.csv"),
+ ("BSE_CM", "https://public.fyers.in/sym_details/BSE_CM.csv"),
+ ("NSE_FO", "https://public.fyers.in/sym_details/NSE_FO.csv"),
+ ("BSE_FO", "https://public.fyers.in/sym_details/BSE_FO.csv"),
+ ("NSE_CD", "https://public.fyers.in/sym_details/NSE_CD.csv"),
+ ("MCX_COM", "https://public.fyers.in/sym_details/MCX_COM.csv"),
+];
+
+/// Fyers CSV column indices (0-based)
+/// Headers: Fytoken, Symbol Details, Exchange Instrument type, Minimum lot size,
+/// Tick size, ISIN, Trading Session, Last update date, Expiry date, Symbol ticker,
+/// Exchange, Segment, Scrip code, Underlying symbol, Underlying scrip code,
+/// Strike price, Option type, Underlying FyToken, Reserved1, Reserved2, Reserved3
+const COL_FYTOKEN: usize = 0;
+const COL_SYMBOL_DETAILS: usize = 1;
+const COL_EXCHANGE_INST_TYPE: usize = 2;
+const COL_LOT_SIZE: usize = 3;
+const COL_TICK_SIZE: usize = 4;
+const COL_EXPIRY: usize = 8;
+const COL_SYMBOL_TICKER: usize = 9;
+const COL_UNDERLYING: usize = 13;
+const COL_STRIKE: usize = 15;
+const COL_OPTION_TYPE: usize = 16;
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DownloadResponse {
+ pub success: bool,
+ pub message: String,
+ pub total_symbols: i64,
+}
+
+/// Download and process Fyers master contract
+#[command]
+pub async fn fyers_download_symbols() -> DownloadResponse {
+ match download_fyers_symbols().await {
+ Ok(count) => DownloadResponse {
+ success: true,
+ message: format!("Successfully downloaded {} symbols", count),
+ total_symbols: count,
+ },
+ Err(e) => {
+ let _ = update_status(
+ BROKER_ID,
+ DownloadStatus::Error,
+ &format!("Download failed: {}", e),
+ None,
+ );
+ DownloadResponse {
+ success: false,
+ message: format!("Download failed: {}", e),
+ total_symbols: 0,
+ }
+ }
+ }
+}
+
+async fn download_fyers_symbols() -> Result<i64> {
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ "Starting Fyers symbol download...",
+ None,
+ )?;
+
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(60))
+ .build()?;
+
+ let mut all_symbols: Vec<SymbolRecord> = Vec::new();
+
+ for (segment, url) in FYERS_CSV_URLS {
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ &format!("Downloading {}...", segment),
+ None,
+ )?;
+
+ match download_and_parse_csv(&client, url, segment).await {
+ Ok(symbols) => {
+ eprintln!(
+ "[fyers] Downloaded {} symbols from {}",
+ symbols.len(),
+ segment
+ );
+ all_symbols.extend(symbols);
+ }
+ Err(e) => {
+ eprintln!("[fyers] Error downloading {}: {}", segment, e);
+ // Continue with other segments
+ }
+ }
+ }
+
+ if all_symbols.is_empty() {
+ return Err(anyhow::anyhow!("No symbols downloaded from any segment"));
+ }
+
+ // Use the unified complete_master_contract_download
+ let count = complete_master_contract_download(BROKER_ID, &all_symbols)?;
+
+ Ok(count)
+}
+
+async fn download_and_parse_csv(
+ client: &reqwest::Client,
+ url: &str,
+ segment: &str,
+) -> Result<Vec<SymbolRecord>> {
+ let response = client
+ .get(url)
+ .send()
+ .await
+ .context(format!("Failed to fetch {}", url))?;
+
+ let csv_text = response
+ .text()
+ .await
+ .context(format!("Failed to read response from {}", url))?;
+
+ parse_fyers_csv(&csv_text, segment)
+}
+
+fn parse_fyers_csv(csv_text: &str, segment: &str) -> Result<Vec<SymbolRecord>> {
+ let mut symbols = Vec::new();
+
+ for line in csv_text.lines() {
+ if line.trim().is_empty() {
+ continue;
+ }
+
+ let fields: Vec<&str> = line.split(',').collect();
+ if fields.len() < 17 {
+ continue;
+ }
+
+ if let Some(symbol) = parse_fyers_row(&fields, segment) {
+ symbols.push(symbol);
+ }
+ }
+
+ Ok(symbols)
+}
+
+fn parse_fyers_row(fields: &[&str], segment: &str) -> Option<SymbolRecord> {
+ let fytoken = fields.get(COL_FYTOKEN)?.trim();
+ let symbol_details = fields.get(COL_SYMBOL_DETAILS)?.trim();
+ let exchange_inst_type: i32 = fields.get(COL_EXCHANGE_INST_TYPE)?.trim().parse().ok()?;
+ let lot_size: i32 = fields.get(COL_LOT_SIZE)?.trim().parse().unwrap_or(1);
+ let tick_size: f64 = fields.get(COL_TICK_SIZE)?.trim().parse().unwrap_or(0.05);
+ let expiry_raw = fields.get(COL_EXPIRY)?.trim();
+ let symbol_ticker = fields.get(COL_SYMBOL_TICKER)?.trim();
+ let underlying = fields.get(COL_UNDERLYING)?.trim();
+ let strike: f64 = fields.get(COL_STRIKE)?.trim().parse().unwrap_or(0.0);
+ let option_type = fields.get(COL_OPTION_TYPE)?.trim();
+
+ // Determine exchange and instrument type based on segment and exchange_inst_type
+ let (exchange, instrument_type) = match segment {
+ "NSE_CM" => {
+ match exchange_inst_type {
+ 0 | 9 => ("NSE", "EQ"),
+ 2 if symbol_ticker.ends_with("-GB") => ("NSE", "GB"),
+ 10 => ("NSE_INDEX", "INDEX"),
+ _ => return None, // Skip unsupported types
+ }
+ }
+ "BSE_CM" => {
+ match exchange_inst_type {
+ 0 | 4 | 50 => ("BSE", "EQ"),
+ 10 => ("BSE_INDEX", "INDEX"),
+ _ => return None,
+ }
+ }
+ "NSE_FO" => ("NFO", get_instrument_type(option_type)),
+ "BSE_FO" => ("BFO", get_instrument_type(option_type)),
+ "NSE_CD" => ("CDS", get_instrument_type(option_type)),
+ "MCX_COM" => ("MCX", get_instrument_type(option_type)),
+ _ => return None,
+ };
+
+ // Build unified symbol
+ let unified_symbol = build_unified_symbol(
+ underlying,
+ symbol_details,
+ expiry_raw,
+ strike,
+ option_type,
+ instrument_type,
+ );
+
+ // Format expiry date
+ let expiry = format_expiry_timestamp(expiry_raw);
+
+ // Get the underlying name (normalized for indices)
+ let name = if instrument_type == "INDEX" || instrument_type == "EQ" {
+ normalize_index_symbol(underlying)
+ } else {
+ get_underlying_from_symbol_details(symbol_details)
+ };
+
+ Some(SymbolRecord {
+ id: None,
+ broker_id: BROKER_ID.to_string(),
+ symbol: unified_symbol,
+ br_symbol: symbol_ticker.to_string(),
+ name: Some(name),
+ exchange: exchange.to_string(),
+ br_exchange: Some(segment.to_string()),
+ token: fytoken.to_string(),
+ expiry,
+ strike: if strike > 0.0 { Some(strike) } else { None },
+ lot_size: Some(lot_size),
+ instrument_type: Some(instrument_type.to_string()),
+ tick_size: Some(tick_size),
+ segment: Some(segment.to_string()),
+ })
+}
+
+fn get_instrument_type(option_type: &str) -> &'static str {
+ match option_type.to_uppercase().as_str() {
+ "CE" => "CE",
+ "PE" => "PE",
+ "XX" | "" => "FUT",
+ _ => "FUT",
+ }
+}
+
+/// Build unified symbol format following OpenAlgo pattern
+/// - Equity: RELIANCE
+/// - Futures: NIFTY26DEC24FUT
+/// - Options: NIFTY26DEC2424000CE
+fn build_unified_symbol(
+ underlying: &str,
+ symbol_details: &str,
+ expiry_raw: &str,
+ strike: f64,
+ option_type: &str,
+ instrument_type: &str,
+) -> String {
+ let normalized_underlying = normalize_index_symbol(underlying);
+
+ match instrument_type {
+ "EQ" | "INDEX" | "GB" => normalized_underlying,
+ "FUT" | "CE" | "PE" => {
+ // Parse "NIFTY 26 Dec 24 FUT" format
+ if let Some(symbol) = reformat_symbol_detail(symbol_details) {
+ if instrument_type == "CE" || instrument_type == "PE" {
+ format!("{}{}", symbol, instrument_type)
+ } else {
+ symbol
+ }
+ } else {
+ // Fallback: build from parts
+ let expiry_formatted = format_expiry_for_symbol(expiry_raw);
+ if strike > 0.0 && (instrument_type == "CE" || instrument_type == "PE") {
+ let strike_str = format_strike(strike);
+ format!(
+ "{}{}{}{}",
+ normalized_underlying, expiry_formatted, strike_str, instrument_type
+ )
+ } else {
+ format!("{}{}FUT", normalized_underlying, expiry_formatted)
+ }
+ }
+ }
+ _ => normalized_underlying,
+ }
+}
+
+/// Reformat "NIFTY 26 Dec 24 FUT" to "NIFTY26DEC24FUT"
+fn reformat_symbol_detail(s: &str) -> Option<String> {
+ let parts: Vec<&str> = s.split_whitespace().collect();
+ if parts.len() >= 5 {
+ // Format: Name DD Mon YY FUT/CE/PE
+ Some(format!(
+ "{}{}{}{}{}",
+ parts[0],
+ parts[3].to_uppercase(), // Year (YY)
+ parts[2].to_uppercase(), // Month
+ parts[1], // Day
+ parts[4].to_uppercase() // FUT/CE/PE
+ ))
+ } else if parts.len() == 4 {
+ // Some formats might be shorter
+ Some(format!(
+ "{}{}{}{}",
+ parts[0],
+ parts[2].to_uppercase(),
+ parts[1],
+ parts[3].to_uppercase()
+ ))
+ } else {
+ None
+ }
+}
+
+/// Get underlying name from symbol details (first word)
+fn get_underlying_from_symbol_details(s: &str) -> String {
+ s.split_whitespace()
+ .next()
+ .map(|s| normalize_index_symbol(s))
+ .unwrap_or_else(|| s.to_string())
+}
+
+/// Format Unix timestamp to DD-MMM-YY
+fn format_expiry_timestamp(expiry_raw: &str) -> Option<String> {
+ if expiry_raw.is_empty() || expiry_raw == "0" {
+ return None;
+ }
+
+ // Try to parse as Unix timestamp
+ if let Ok(timestamp) = expiry_raw.parse::<i64>() {
+ if timestamp > 0 {
+ use chrono::{TimeZone, Utc};
+ if let Some(dt) = Utc.timestamp_opt(timestamp, 0).single() {
+ return Some(dt.format("%d-%b-%y").to_string().to_uppercase());
+ }
+ }
+ }
+
+ // Return as-is if not a timestamp
+ Some(expiry_raw.to_uppercase())
+}
+
+/// Format expiry for symbol construction (DDMMMYY without dashes)
+fn format_expiry_for_symbol(expiry_raw: &str) -> String {
+ if let Some(formatted) = format_expiry_timestamp(expiry_raw) {
+ formatted.replace("-", "")
+ } else {
+ String::new()
+ }
+}
+
+/// Format strike price (remove trailing .0)
+fn format_strike(strike: f64) -> String {
+ if strike.fract() == 0.0 {
+ format!("{}", strike as i64)
+ } else {
+ format!("{}", strike)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_reformat_symbol_detail() {
+ assert_eq!(
+ reformat_symbol_detail("NIFTY 26 Dec 24 FUT"),
+ Some("NIFTY24DEC26FUT".to_string())
+ );
+ assert_eq!(
+ reformat_symbol_detail("BANKNIFTY 25 Dec 24 CE"),
+ Some("BANKNIFTY24DEC25CE".to_string())
+ );
+ }
+
+ #[test]
+ fn test_format_strike() {
+ assert_eq!(format_strike(24000.0), "24000");
+ assert_eq!(format_strike(24000.5), "24000.5");
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/mod.rs
new file mode 100644
index 000000000..b0d4f56ea
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/mod.rs
@@ -0,0 +1,19 @@
+//! Broker Master Contract Downloads
+//!
+//! This module contains master contract download implementations for all supported brokers.
+//! Each broker downloads from their public CSV/JSON endpoints and transforms to the unified symbol format.
+
+pub mod fyers;
+pub mod zerodha;
+pub mod angelone;
+pub mod upstox;
+pub mod dhan;
+pub mod shoonya;
+
+// Re-export commonly used types
+pub use fyers::fyers_download_symbols;
+pub use zerodha::zerodha_download_symbols;
+pub use angelone::angelone_download_symbols;
+pub use upstox::upstox_download_symbols;
+pub use dhan::dhan_download_symbols;
+pub use shoonya::shoonya_download_symbols;
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/shoonya.rs b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/shoonya.rs
new file mode 100644
index 000000000..db1f057c2
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/shoonya.rs
@@ -0,0 +1,267 @@
+//! Shoonya (Finvasia) Master Contract Download
+//!
+//! Downloads and parses Shoonya instruments from public endpoints.
+//! Transforms to unified symbol format following OpenAlgo pattern.
+
+use crate::database::symbol_master::{
+ complete_master_contract_download, normalize_index_symbol, update_status, DownloadStatus,
+ SymbolRecord,
+};
+use anyhow::{Context, Result};
+use serde::{Deserialize, Serialize};
+use tauri::command;
+
+const BROKER_ID: &str = "shoonya";
+
+// Shoonya uses the same format as Flattrade (both use NorenOMS)
+// Symbol master endpoints
+const SHOONYA_URLS: &[(&str, &str)] = &[
+ ("NSE", "https://shoonya.finvasia.com/NSE_symbols.txt.zip"),
+ ("NFO", "https://shoonya.finvasia.com/NFO_symbols.txt.zip"),
+ ("BSE", "https://shoonya.finvasia.com/BSE_symbols.txt.zip"),
+ ("BFO", "https://shoonya.finvasia.com/BFO_symbols.txt.zip"),
+ ("CDS", "https://shoonya.finvasia.com/CDS_symbols.txt.zip"),
+ ("MCX", "https://shoonya.finvasia.com/MCX_symbols.txt.zip"),
+];
+
+/// Shoonya symbol file columns (pipe-separated)
+/// Exchange,Token,LotSize,Symbol,TradingSymbol,Expiry,Instrument,OptionType,StrikePrice,TickSize
+const COL_EXCHANGE: usize = 0;
+const COL_TOKEN: usize = 1;
+const COL_LOT_SIZE: usize = 2;
+const COL_SYMBOL: usize = 3;
+const COL_TRADING_SYMBOL: usize = 4;
+const COL_EXPIRY: usize = 5;
+const COL_INSTRUMENT: usize = 6;
+const COL_OPTION_TYPE: usize = 7;
+const COL_STRIKE: usize = 8;
+const COL_TICK_SIZE: usize = 9;
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DownloadResponse {
+ pub success: bool,
+ pub message: String,
+ pub total_symbols: i64,
+}
+
+/// Download and process Shoonya master contract
+#[command]
+pub async fn shoonya_download_symbols() -> DownloadResponse {
+ match download_shoonya_symbols().await {
+ Ok(count) => DownloadResponse {
+ success: true,
+ message: format!("Successfully downloaded {} symbols", count),
+ total_symbols: count,
+ },
+ Err(e) => {
+ let _ = update_status(
+ BROKER_ID,
+ DownloadStatus::Error,
+ &format!("Download failed: {}", e),
+ None,
+ );
+ DownloadResponse {
+ success: false,
+ message: format!("Download failed: {}", e),
+ total_symbols: 0,
+ }
+ }
+ }
+}
+
+async fn download_shoonya_symbols() -> Result<i64> {
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ "Starting Shoonya symbol download...",
+ None,
+ )?;
+
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(120))
+ .build()?;
+
+ let mut all_symbols: Vec<SymbolRecord> = Vec::new();
+
+ for (segment, url) in SHOONYA_URLS {
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ &format!("Downloading {}...", segment),
+ None,
+ )?;
+
+ match download_and_parse_shoonya(&client, url, segment).await {
+ Ok(symbols) => {
+ eprintln!("[shoonya] Downloaded {} symbols from {}", symbols.len(), segment);
+ all_symbols.extend(symbols);
+ }
+ Err(e) => {
+ eprintln!("[shoonya] Error downloading {}: {}", segment, e);
+ }
+ }
+ }
+
+ if all_symbols.is_empty() {
+ return Err(anyhow::anyhow!("No symbols downloaded from any segment"));
+ }
+
+ let count = complete_master_contract_download(BROKER_ID, &all_symbols)?;
+ Ok(count)
+}
+
+async fn download_and_parse_shoonya(
+ client: &reqwest::Client,
+ url: &str,
+ segment: &str,
+) -> Result<Vec<SymbolRecord>> {
+ let response = client
+ .get(url)
+ .send()
+ .await
+ .context(format!("Failed to fetch {}", url))?;
+
+ let bytes = response
+ .bytes()
+ .await
+ .context(format!("Failed to read response from {}", url))?;
+
+ // Decompress ZIP
+ let cursor = std::io::Cursor::new(&bytes);
+ let mut archive = zip::ZipArchive::new(cursor).context("Failed to read ZIP archive")?;
+
+ let mut text_content = String::new();
+ for i in 0..archive.len() {
+ let mut file = archive.by_index(i)?;
+ if file.name().ends_with(".txt") {
+ std::io::Read::read_to_string(&mut file, &mut text_content)?;
+ break;
+ }
+ }
+
+ parse_shoonya_text(&text_content, segment)
+}
+
+fn parse_shoonya_text(text: &str, segment: &str) -> Result<Vec<SymbolRecord>> {
+ let mut symbols = Vec::new();
+
+ for line in text.lines() {
+ if line.trim().is_empty() {
+ continue;
+ }
+
+ let fields: Vec<&str> = line.split(',').collect();
+ if fields.len() < 10 {
+ continue;
+ }
+
+ if let Some(symbol) = parse_shoonya_row(&fields, segment) {
+ symbols.push(symbol);
+ }
+ }
+
+ Ok(symbols)
+}
+
+fn parse_shoonya_row(fields: &[&str], segment: &str) -> Option<SymbolRecord> {
+ let exchange = fields.get(COL_EXCHANGE)?.trim();
+ let token = fields.get(COL_TOKEN)?.trim();
+ let lot_size: i32 = fields.get(COL_LOT_SIZE)?.trim().parse().unwrap_or(1);
+ let symbol_name = fields.get(COL_SYMBOL)?.trim();
+ let trading_symbol = fields.get(COL_TRADING_SYMBOL)?.trim();
+ let expiry_raw = fields.get(COL_EXPIRY)?.trim();
+ let instrument = fields.get(COL_INSTRUMENT)?.trim();
+ let option_type = fields.get(COL_OPTION_TYPE)?.trim();
+ let strike: f64 = fields.get(COL_STRIKE)?.trim().parse().unwrap_or(0.0);
+ let tick_size: f64 = fields.get(COL_TICK_SIZE)?.trim().parse().unwrap_or(0.05);
+
+ // Determine unified exchange
+ let unified_exchange = match segment {
+ "NSE" if instrument == "INDEX" => "NSE_INDEX",
+ "BSE" if instrument == "INDEX" => "BSE_INDEX",
+ "NFO" => "NFO",
+ "BFO" => "BFO",
+ "CDS" => "CDS",
+ "MCX" => "MCX",
+ _ => segment,
+ };
+
+ // Format expiry
+ let expiry = format_shoonya_expiry(expiry_raw);
+
+ // Determine instrument type
+ let inst_type = match option_type {
+ "CE" => "CE",
+ "PE" => "PE",
+ "" if instrument.contains("FUT") => "FUT",
+ "" if instrument == "INDEX" => "INDEX",
+ "" => "EQ",
+ _ => option_type,
+ };
+
+ // Build unified symbol
+ let name = normalize_index_symbol(symbol_name);
+ let unified_symbol = build_unified_symbol(&name, &expiry, strike, inst_type);
+
+ Some(SymbolRecord {
+ id: None,
+ broker_id: BROKER_ID.to_string(),
+ symbol: unified_symbol,
+ br_symbol: trading_symbol.to_string(),
+ name: Some(name),
+ exchange: unified_exchange.to_string(),
+ br_exchange: Some(exchange.to_string()),
+ token: token.to_string(),
+ expiry,
+ strike: if strike > 0.0 { Some(strike) } else { None },
+ lot_size: Some(lot_size),
+ instrument_type: Some(inst_type.to_string()),
+ tick_size: Some(tick_size),
+ segment: Some(segment.to_string()),
+ })
+}
+
+fn format_shoonya_expiry(expiry: &str) -> Option<String> {
+ if expiry.is_empty() || expiry == "0" {
+ return None;
+ }
+
+ // Shoonya format: DD-MMM-YYYY (e.g., 26-DEC-2024)
+ let parts: Vec<&str> = expiry.split('-').collect();
+ if parts.len() == 3 {
+ let day = parts[0];
+ let month = parts[1];
+ let year = parts[2];
+
+ let year_short = if year.len() >= 2 { &year[year.len() - 2..] } else { year };
+ return Some(format!("{}-{}-{}", day, month.to_uppercase(), year_short));
+ }
+
+ Some(expiry.to_uppercase())
+}
+
+fn build_unified_symbol(name: &str, expiry: &Option<String>, strike: f64, inst_type: &str) -> String {
+ match inst_type {
+ "EQ" | "INDEX" => name.to_string(),
+ "FUT" => {
+ if let Some(exp) = expiry {
+ format!("{}{}FUT", name, exp.replace("-", ""))
+ } else {
+ name.to_string()
+ }
+ }
+ "CE" | "PE" => {
+ if let Some(exp) = expiry {
+ let strike_str = if strike.fract() == 0.0 {
+ format!("{}", strike as i64)
+ } else {
+ format!("{}", strike)
+ };
+ format!("{}{}{}{}", name, exp.replace("-", ""), strike_str, inst_type)
+ } else {
+ name.to_string()
+ }
+ }
+ _ => name.to_string(),
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/upstox.rs b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/upstox.rs
new file mode 100644
index 000000000..af6ace848
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/upstox.rs
@@ -0,0 +1,275 @@
+//! Upstox Master Contract Download
+//!
+//! Downloads and parses Upstox instruments.
+//! Transforms to unified symbol format following OpenAlgo pattern.
+
+use crate::database::symbol_master::{
+ complete_master_contract_download, normalize_index_symbol, update_status, DownloadStatus,
+ SymbolRecord,
+};
+use anyhow::{Context, Result};
+use serde::{Deserialize, Serialize};
+use tauri::command;
+
+const BROKER_ID: &str = "upstox";
+
+// Upstox instrument files (gzipped JSON)
+const UPSTOX_URLS: &[(&str, &str)] = &[
+ ("NSE_EQ", "https://assets.upstox.com/market-quote/instruments/exchange/NSE.json.gz"),
+ ("BSE_EQ", "https://assets.upstox.com/market-quote/instruments/exchange/BSE.json.gz"),
+ ("NFO", "https://assets.upstox.com/market-quote/instruments/exchange/NFO.json.gz"),
+ ("BFO", "https://assets.upstox.com/market-quote/instruments/exchange/BFO.json.gz"),
+ ("CDS", "https://assets.upstox.com/market-quote/instruments/exchange/CDS.json.gz"),
+ ("MCX", "https://assets.upstox.com/market-quote/instruments/exchange/MCX.json.gz"),
+];
+
+/// Upstox JSON instrument structure
+#[derive(Debug, Deserialize)]
+struct UpstoxInstrument {
+ instrument_key: String,
+ trading_symbol: String,
+ name: Option<String>,
+ expiry: Option<String>,
+ strike_price: Option<f64>,
+ lot_size: Option<i32>,
+ instrument_type: Option<String>,
+ exchange: String,
+ tick_size: Option<f64>,
+ #[serde(default)]
+ underlying_symbol: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DownloadResponse {
+ pub success: bool,
+ pub message: String,
+ pub total_symbols: i64,
+}
+
+/// Download and process Upstox master contract
+/// No authentication required for instrument files
+#[command]
+pub async fn upstox_download_symbols() -> DownloadResponse {
+ match download_upstox_symbols().await {
+ Ok(count) => DownloadResponse {
+ success: true,
+ message: format!("Successfully downloaded {} symbols", count),
+ total_symbols: count,
+ },
+ Err(e) => {
+ let _ = update_status(
+ BROKER_ID,
+ DownloadStatus::Error,
+ &format!("Download failed: {}", e),
+ None,
+ );
+ DownloadResponse {
+ success: false,
+ message: format!("Download failed: {}", e),
+ total_symbols: 0,
+ }
+ }
+ }
+}
+
+async fn download_upstox_symbols() -> Result<i64> {
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ "Starting Upstox symbol download...",
+ None,
+ )?;
+
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(120))
+ .build()?;
+
+ let mut all_symbols: Vec<SymbolRecord> = Vec::new();
+
+ for (segment, url) in UPSTOX_URLS {
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ &format!("Downloading {}...", segment),
+ None,
+ )?;
+
+ match download_and_parse_upstox(&client, url, segment).await {
+ Ok(symbols) => {
+ eprintln!("[upstox] Downloaded {} symbols from {}", symbols.len(), segment);
+ all_symbols.extend(symbols);
+ }
+ Err(e) => {
+ eprintln!("[upstox] Error downloading {}: {}", segment, e);
+ // Continue with other segments
+ }
+ }
+ }
+
+ if all_symbols.is_empty() {
+ return Err(anyhow::anyhow!("No symbols downloaded from any segment"));
+ }
+
+ let count = complete_master_contract_download(BROKER_ID, &all_symbols)?;
+ Ok(count)
+}
+
+async fn download_and_parse_upstox(
+ client: &reqwest::Client,
+ url: &str,
+ segment: &str,
+) -> Result<Vec<SymbolRecord>> {
+ let response = client
+ .get(url)
+ .send()
+ .await
+ .context(format!("Failed to fetch {}", url))?;
+
+ let bytes = response
+ .bytes()
+ .await
+ .context(format!("Failed to read response from {}", url))?;
+
+ // Decompress gzip
+ let mut decoder = flate2::read::GzDecoder::new(&bytes[..]);
+ let mut json_text = String::new();
+ std::io::Read::read_to_string(&mut decoder, &mut json_text)
+ .context("Failed to decompress gzip")?;
+
+ // Parse JSON
+ let instruments: Vec<UpstoxInstrument> =
+ serde_json::from_str(&json_text).context("Failed to parse Upstox JSON")?;
+
+ let symbols: Vec<SymbolRecord> = instruments
+ .into_iter()
+ .filter_map(|inst| convert_upstox_instrument(inst, segment))
+ .collect();
+
+ Ok(symbols)
+}
+
+fn convert_upstox_instrument(inst: UpstoxInstrument, segment: &str) -> Option<SymbolRecord> {
+ let instrument_type = inst.instrument_type.as_deref().unwrap_or("");
+
+ // Determine exchange
+ let exchange = match segment {
+ "NSE_EQ" => {
+ if instrument_type == "INDEX" {
+ "NSE_INDEX"
+ } else {
+ "NSE"
+ }
+ }
+ "BSE_EQ" => {
+ if instrument_type == "INDEX" {
+ "BSE_INDEX"
+ } else {
+ "BSE"
+ }
+ }
+ _ => &inst.exchange,
+ };
+
+ // Format expiry
+ let expiry = inst.expiry.as_ref().map(|e| format_upstox_expiry(e));
+
+ // Get underlying name
+ let name = inst
+ .underlying_symbol
+ .as_ref()
+ .or(inst.name.as_ref())
+ .map(|s| normalize_index_symbol(s))
+ .unwrap_or_else(|| inst.trading_symbol.clone());
+
+ // Build unified symbol
+ let unified_symbol = build_unified_symbol(
+ &name,
+ &expiry,
+ inst.strike_price.unwrap_or(0.0),
+ instrument_type,
+ );
+
+ // Normalize instrument type
+ let normalized_inst_type = normalize_instrument_type(instrument_type, &inst.trading_symbol);
+
+ Some(SymbolRecord {
+ id: None,
+ broker_id: BROKER_ID.to_string(),
+ symbol: unified_symbol,
+ br_symbol: inst.trading_symbol,
+ name: Some(name),
+ exchange: exchange.to_string(),
+ br_exchange: Some(inst.exchange),
+ token: inst.instrument_key,
+ expiry,
+ strike: inst.strike_price.filter(|&s| s > 0.0),
+ lot_size: inst.lot_size,
+ instrument_type: Some(normalized_inst_type),
+ tick_size: inst.tick_size,
+ segment: Some(segment.to_string()),
+ })
+}
+
+fn format_upstox_expiry(expiry: &str) -> String {
+ // Upstox format: YYYY-MM-DD
+ let parts: Vec<&str> = expiry.split('-').collect();
+ if parts.len() == 3 {
+ let year = parts[0];
+ let month: u32 = parts[1].parse().unwrap_or(1);
+ let day = parts[2];
+
+ let month_str = match month {
+ 1 => "JAN", 2 => "FEB", 3 => "MAR", 4 => "APR",
+ 5 => "MAY", 6 => "JUN", 7 => "JUL", 8 => "AUG",
+ 9 => "SEP", 10 => "OCT", 11 => "NOV", 12 => "DEC",
+ _ => "JAN",
+ };
+
+ let year_short = if year.len() >= 2 { &year[year.len() - 2..] } else { year };
+ format!("{}-{}-{}", day, month_str, year_short)
+ } else {
+ expiry.to_uppercase()
+ }
+}
+
+fn build_unified_symbol(name: &str, expiry: &Option<String>, strike: f64, instrument_type: &str) -> String {
+ match instrument_type {
+ "EQ" | "INDEX" => name.to_string(),
+ "FUT" | "FUTIDX" | "FUTSTK" => {
+ if let Some(exp) = expiry {
+ format!("{}{}FUT", name, exp.replace("-", ""))
+ } else {
+ name.to_string()
+ }
+ }
+ "CE" | "PE" | "OPTIDX" | "OPTSTK" => {
+ if let Some(exp) = expiry {
+ let strike_str = if strike.fract() == 0.0 {
+ format!("{}", strike as i64)
+ } else {
+ format!("{}", strike)
+ };
+ let opt_type = if instrument_type.contains("CE") || instrument_type == "CE" { "CE" } else { "PE" };
+ format!("{}{}{}{}", name, exp.replace("-", ""), strike_str, opt_type)
+ } else {
+ name.to_string()
+ }
+ }
+ _ => name.to_string(),
+ }
+}
+
+fn normalize_instrument_type(instrument_type: &str, symbol: &str) -> String {
+ match instrument_type {
+ "FUTIDX" | "FUTSTK" | "FUT" => "FUT".to_string(),
+ "OPTIDX" | "OPTSTK" => {
+ if symbol.ends_with("CE") { "CE".to_string() }
+ else if symbol.ends_with("PE") { "PE".to_string() }
+ else { instrument_type.to_string() }
+ }
+ "CE" | "PE" => instrument_type.to_string(),
+ "INDEX" => "INDEX".to_string(),
+ "EQ" | "" => "EQ".to_string(),
+ _ => instrument_type.to_string(),
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/zerodha.rs b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/zerodha.rs
new file mode 100644
index 000000000..836971459
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/zerodha.rs
@@ -0,0 +1,308 @@
+//! Zerodha (Kite) Master Contract Download
+//!
+//! Downloads and parses Zerodha instruments from the Kite API.
+//! Transforms to unified symbol format following OpenAlgo pattern.
+//! Note: Requires authentication token (API key + access token).
+
+use crate::database::symbol_master::{
+ complete_master_contract_download, normalize_index_symbol, update_status, DownloadStatus,
+ SymbolRecord,
+};
+use anyhow::{Context, Result};
+use serde::{Deserialize, Serialize};
+use tauri::command;
+
+const BROKER_ID: &str = "zerodha";
+const INSTRUMENTS_URL: &str = "https://api.kite.trade/instruments";
+
+/// Zerodha instrument CSV columns
+/// instrument_token,exchange_token,tradingsymbol,name,last_price,expiry,strike,tick_size,lot_size,instrument_type,segment,exchange
+const COL_INSTRUMENT_TOKEN: usize = 0;
+const COL_EXCHANGE_TOKEN: usize = 1;
+const COL_TRADINGSYMBOL: usize = 2;
+const COL_NAME: usize = 3;
+const COL_EXPIRY: usize = 5;
+const COL_STRIKE: usize = 6;
+const COL_TICK_SIZE: usize = 7;
+const COL_LOT_SIZE: usize = 8;
+const COL_INSTRUMENT_TYPE: usize = 9;
+const COL_SEGMENT: usize = 10;
+const COL_EXCHANGE: usize = 11;
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DownloadResponse {
+ pub success: bool,
+ pub message: String,
+ pub total_symbols: i64,
+}
+
+/// Download and process Zerodha master contract
+/// Requires API key and access token for authentication
+#[command]
+pub async fn zerodha_download_symbols(
+ api_key: String,
+ access_token: String,
+) -> DownloadResponse {
+ match download_zerodha_symbols(&api_key, &access_token).await {
+ Ok(count) => DownloadResponse {
+ success: true,
+ message: format!("Successfully downloaded {} symbols", count),
+ total_symbols: count,
+ },
+ Err(e) => {
+ let _ = update_status(
+ BROKER_ID,
+ DownloadStatus::Error,
+ &format!("Download failed: {}", e),
+ None,
+ );
+ DownloadResponse {
+ success: false,
+ message: format!("Download failed: {}", e),
+ total_symbols: 0,
+ }
+ }
+ }
+}
+
+async fn download_zerodha_symbols(api_key: &str, access_token: &str) -> Result<i64> {
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ "Starting Zerodha instrument download...",
+ None,
+ )?;
+
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(120))
+ .build()?;
+
+ // Build authorization header: "token api_key:access_token"
+ let auth_header = format!("token {}:{}", api_key, access_token);
+
+ let response = client
+ .get(INSTRUMENTS_URL)
+ .header("X-Kite-Version", "3")
+ .header("Authorization", &auth_header)
+ .send()
+ .await
+ .context("Failed to fetch Zerodha instruments")?;
+
+ if !response.status().is_success() {
+ return Err(anyhow::anyhow!(
+ "Zerodha API returned status: {}",
+ response.status()
+ ));
+ }
+
+ let csv_text = response
+ .text()
+ .await
+ .context("Failed to read Zerodha response")?;
+
+ update_status(
+ BROKER_ID,
+ DownloadStatus::Downloading,
+ "Parsing instruments...",
+ None,
+ )?;
+
+ let symbols = parse_zerodha_csv(&csv_text)?;
+
+ if symbols.is_empty() {
+ return Err(anyhow::anyhow!("No symbols parsed from Zerodha response"));
+ }
+
+ eprintln!("[zerodha] Parsed {} symbols", symbols.len());
+
+ // Use the unified complete_master_contract_download
+ let count = complete_master_contract_download(BROKER_ID, &symbols)?;
+
+ Ok(count)
+}
+
+fn parse_zerodha_csv(csv_text: &str) -> Result<Vec<SymbolRecord>> {
+ let mut symbols = Vec::new();
+ let mut lines = csv_text.lines();
+
+ // Skip header line
+ if let Some(header) = lines.next() {
+ eprintln!("[zerodha] CSV header: {}", header);
+ }
+
+ for line in lines {
+ if line.trim().is_empty() {
+ continue;
+ }
+
+ let fields: Vec<&str> = line.split(',').collect();
+ if fields.len() < 12 {
+ continue;
+ }
+
+ if let Some(symbol) = parse_zerodha_row(&fields) {
+ symbols.push(symbol);
+ }
+ }
+
+ Ok(symbols)
+}
+
+fn parse_zerodha_row(fields: &[&str]) -> Option<SymbolRecord> {
+ let instrument_token = fields.get(COL_INSTRUMENT_TOKEN)?.trim();
+ let exchange_token = fields.get(COL_EXCHANGE_TOKEN)?.trim();
+ let trading_symbol = fields.get(COL_TRADINGSYMBOL)?.trim();
+ let name = fields.get(COL_NAME)?.trim();
+ let expiry_raw = fields.get(COL_EXPIRY)?.trim();
+ let strike: f64 = fields.get(COL_STRIKE)?.trim().parse().unwrap_or(0.0);
+ let tick_size: f64 = fields.get(COL_TICK_SIZE)?.trim().parse().unwrap_or(0.05);
+ let lot_size: i32 = fields.get(COL_LOT_SIZE)?.trim().parse().unwrap_or(1);
+ let instrument_type = fields.get(COL_INSTRUMENT_TYPE)?.trim();
+ let segment = fields.get(COL_SEGMENT)?.trim();
+ let exchange = fields.get(COL_EXCHANGE)?.trim();
+
+ // Combine instrument_token and exchange_token for unique ID
+ let token = format!("{}::::{}", instrument_token, exchange_token);
+
+ // Determine exchange (handle indices)
+ let unified_exchange = if segment == "INDICES" {
+ match exchange {
+ "NSE" => "NSE_INDEX",
+ "BSE" => "BSE_INDEX",
+ "MCX" => "MCX_INDEX",
+ "CDS" => "CDS_INDEX",
+ _ => exchange,
+ }
+ } else {
+ exchange
+ };
+
+ // Format expiry date to DD-MMM-YY
+ let expiry = format_expiry(expiry_raw);
+
+ // Build unified symbol
+ let unified_symbol = build_unified_symbol(name, &expiry, strike, instrument_type);
+
+ // Normalize name for indices
+ let normalized_name = normalize_index_symbol(name);
+
+ Some(SymbolRecord {
+ id: None,
+ broker_id: BROKER_ID.to_string(),
+ symbol: unified_symbol,
+ br_symbol: trading_symbol.to_string(),
+ name: Some(normalized_name),
+ exchange: unified_exchange.to_string(),
+ br_exchange: Some(exchange.to_string()),
+ token,
+ expiry,
+ strike: if strike > 0.0 { Some(strike) } else { None },
+ lot_size: Some(lot_size),
+ instrument_type: Some(instrument_type.to_string()),
+ tick_size: Some(tick_size),
+ segment: Some(segment.to_string()),
+ })
+}
+
+/// Build unified symbol format following OpenAlgo pattern
+fn build_unified_symbol(name: &str, expiry: &Option<String>, strike: f64, instrument_type: &str) -> String {
+ let normalized_name = normalize_index_symbol(name);
+
+ match instrument_type {
+ "EQ" | "INDEX" => normalized_name,
+ "FUT" => {
+ if let Some(exp) = expiry {
+ let exp_formatted = exp.replace("-", "");
+ format!("{}{}FUT", normalized_name, exp_formatted)
+ } else {
+ normalized_name
+ }
+ }
+ "CE" | "PE" => {
+ if let Some(exp) = expiry {
+ let exp_formatted = exp.replace("-", "");
+ let strike_str = format_strike(strike);
+ format!("{}{}{}{}", normalized_name, exp_formatted, strike_str, instrument_type)
+ } else {
+ normalized_name
+ }
+ }
+ _ => normalized_name,
+ }
+}
+
+/// Format expiry date from YYYY-MM-DD to DD-MMM-YY
+fn format_expiry(expiry_raw: &str) -> Option<String> {
+ if expiry_raw.is_empty() {
+ return None;
+ }
+
+ // Expected format: YYYY-MM-DD
+ let parts: Vec<&str> = expiry_raw.split('-').collect();
+ if parts.len() == 3 {
+ let year = parts[0];
+ let month: u32 = parts[1].parse().unwrap_or(1);
+ let day = parts[2];
+
+ let month_str = match month {
+ 1 => "JAN",
+ 2 => "FEB",
+ 3 => "MAR",
+ 4 => "APR",
+ 5 => "MAY",
+ 6 => "JUN",
+ 7 => "JUL",
+ 8 => "AUG",
+ 9 => "SEP",
+ 10 => "OCT",
+ 11 => "NOV",
+ 12 => "DEC",
+ _ => "JAN",
+ };
+
+ // Get last 2 digits of year
+ let year_short = if year.len() >= 2 {
+ &year[year.len() - 2..]
+ } else {
+ year
+ };
+
+ return Some(format!("{}-{}-{}", day, month_str, year_short));
+ }
+
+ // Return as-is if can't parse
+ Some(expiry_raw.to_uppercase())
+}
+
+/// Format strike price (remove trailing .0)
+fn format_strike(strike: f64) -> String {
+ if strike.fract() == 0.0 {
+ format!("{}", strike as i64)
+ } else {
+ format!("{}", strike)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_format_expiry() {
+ assert_eq!(format_expiry("2024-12-26"), Some("26-DEC-24".to_string()));
+ assert_eq!(format_expiry("2025-01-30"), Some("30-JAN-25".to_string()));
+ assert_eq!(format_expiry(""), None);
+ }
+
+ #[test]
+ fn test_build_unified_symbol() {
+ assert_eq!(
+ build_unified_symbol("NIFTY", &Some("26-DEC-24".to_string()), 0.0, "FUT"),
+ "NIFTY26DEC24FUT"
+ );
+ assert_eq!(
+ build_unified_symbol("NIFTY", &Some("26-DEC-24".to_string()), 24000.0, "CE"),
+ "NIFTY26DEC2424000CE"
+ );
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/angelone.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/angelone.rs
index db64239f3..96eadbdfc 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/angelone.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/angelone.rs
@@ -7,7 +7,7 @@ use reqwest::Client;
use serde_json::{json, Value};
use super::common::ApiResponse;
use totp_rs::{Algorithm, TOTP, Secret};
-use crate::database::master_contract;
+use crate::database::symbol_master;
use std::time::Duration;
use std::sync::OnceLock;
@@ -418,7 +418,7 @@ pub async fn angelone_search_symbols(
) -> ApiResponse<Value> {
let timestamp = chrono::Utc::now().timestamp_millis();
- match master_contract::search_symbols(
+ match symbol_master::search_symbols(
"angelone",
&query,
exchange.as_deref(),
@@ -467,7 +467,7 @@ pub async fn angelone_get_instrument(
) -> ApiResponse<Value> {
let timestamp = chrono::Utc::now().timestamp_millis();
- match master_contract::get_symbol("angelone", &symbol, &exchange) {
+ match symbol_master::get_symbol("angelone", &symbol, &exchange) {
Ok(Some(result)) => {
ApiResponse {
success: true,
@@ -490,7 +490,7 @@ pub async fn angelone_get_instrument(
}
Ok(None) => {
// Try fuzzy search as fallback
- match master_contract::search_symbols("angelone", &symbol, Some(&exchange), None, 1) {
+ match symbol_master::search_symbols("angelone", &symbol, Some(&exchange), None, 1) {
Ok(results) if !results.is_empty() => {
let r = &results[0];
ApiResponse {
@@ -536,23 +536,25 @@ pub async fn angelone_download_master_contract(
) -> ApiResponse<Value> {
let timestamp = chrono::Utc::now().timestamp_millis();
- // Delegate to the existing master contract download
- match crate::commands::master_contract::download_angelone_master_contract().await {
- Ok(result) => ApiResponse {
- success: result.success,
+ // Delegate to the new symbol master download
+ let result = crate::commands::broker_downloads::angelone::angelone_download_symbols().await;
+ if result.success {
+ ApiResponse {
+ success: true,
data: Some(json!({
- "symbol_count": result.symbol_count,
+ "symbol_count": result.total_symbols,
"message": result.message,
})),
error: None,
timestamp,
- },
- Err(e) => ApiResponse {
+ }
+ } else {
+ ApiResponse {
success: false,
data: None,
- error: Some(e),
+ error: Some(result.message),
timestamp,
- },
+ }
}
}
@@ -561,27 +563,23 @@ pub async fn angelone_download_master_contract(
pub async fn angelone_master_contract_info() -> ApiResponse<Value> {
let timestamp = chrono::Utc::now().timestamp_millis();
- match master_contract::get_master_contract("angelone") {
- Ok(Some(info)) => {
+ match symbol_master::get_status("angelone") {
+ Ok(info) => {
let now = chrono::Utc::now().timestamp();
let cache_age = now - info.last_updated;
ApiResponse {
success: true,
data: Some(json!({
"timestamp": info.last_updated,
- "symbol_count": info.symbol_count,
+ "symbol_count": info.total_symbols,
"cache_age_seconds": cache_age,
+ "status": info.status,
+ "is_ready": info.is_ready,
})),
error: None,
timestamp,
}
}
- Ok(None) => ApiResponse {
- success: false,
- data: None,
- error: Some("No master contract data found".to_string()),
- timestamp,
- },
Err(e) => ApiResponse {
success: false,
data: None,
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/dhan.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/dhan.rs
index 45a0c4563..c9af043f6 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/dhan.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/dhan.rs
@@ -779,113 +779,33 @@ fn init_dhan_symbols_table() -> Result<(), String> {
/// Download and store master contract
#[tauri::command]
pub async fn dhan_download_master_contract() -> Result<ApiResponse<Value>, String> {
- let client = reqwest::Client::new();
+ let timestamp = chrono::Utc::now().timestamp();
- // Download CSV
- let response = client
- .get(DHAN_MASTER_CONTRACT_URL)
- .timeout(std::time::Duration::from_secs(120))
- .send()
- .await
- .map_err(|e| e.to_string())?;
-
- let csv_text = response.text().await.map_err(|e| e.to_string())?;
-
- // Initialize table
- init_dhan_symbols_table()?;
-
- let db = get_db().map_err(|e| e.to_string())?;
+ // Use the new unified broker downloads system
+ let result = crate::commands::broker_downloads::dhan::dhan_download_symbols().await;
- // Clear existing data
- db.execute("DELETE FROM dhan_symbols", []).map_err(|e| e.to_string())?;
-
- // Parse CSV and insert
- let mut rdr = csv::ReaderBuilder::new()
- .has_headers(true)
- .flexible(true)
- .from_reader(csv_text.as_bytes());
-
- let mut count = 0;
- for result in rdr.records() {
- if let Ok(record) = result {
- // Parse CSV columns based on Dhan format
- // Columns: SEM_EXM_EXCH_ID, SEM_SEGMENT, SEM_SMST_SECURITY_ID, SEM_INSTRUMENT_NAME,
- // SEM_EXPIRY_CODE, SEM_TRADING_SYMBOL, SEM_LOT_UNITS, SEM_CUSTOM_SYMBOL,
- // SEM_EXPIRY_DATE, SEM_STRIKE_PRICE, SEM_TICK_SIZE, SEM_OPTION_TYPE, ...
- let exch_id = record.get(0).unwrap_or("");
- let security_id = record.get(2).unwrap_or("");
- let instrument_name = record.get(3).unwrap_or("");
- let trading_symbol = record.get(5).unwrap_or("");
- let lot_size: i32 = record.get(6).unwrap_or("1").parse().unwrap_or(1);
- let expiry = record.get(8).unwrap_or("");
- let strike: f64 = record.get(9).unwrap_or("0").parse().unwrap_or(0.0);
- let tick_size: f64 = record.get(10).unwrap_or("0.05").parse().unwrap_or(0.05);
- let option_type = record.get(11).unwrap_or("");
- let symbol_name = record.get(15).unwrap_or(trading_symbol);
-
- // Map exchange
- let (exchange, br_exchange, inst_type) = match (exch_id, instrument_name) {
- ("NSE", "EQUITY") => ("NSE", "NSE_EQ", "EQ"),
- ("BSE", "EQUITY") => ("BSE", "BSE_EQ", "EQ"),
- ("NSE", "INDEX") => ("NSE_INDEX", "IDX_I", "INDEX"),
- ("BSE", "INDEX") => ("BSE_INDEX", "IDX_I", "INDEX"),
- ("NSE", s) if s.contains("FUT") || s.contains("OPT") => {
- let it = if option_type.is_empty() { "FUT" } else { option_type };
- ("NFO", "NSE_FNO", it)
- }
- ("BSE", s) if s.contains("FUT") || s.contains("OPT") => {
- let it = if option_type.is_empty() { "FUT" } else { option_type };
- ("BFO", "BSE_FNO", it)
- }
- ("MCX", _) => {
- let it = if option_type.is_empty() { "FUT" } else { option_type };
- ("MCX", "MCX_COMM", it)
- }
- ("NSE", s) if s.contains("CUR") => {
- let it = if option_type.is_empty() { "FUT" } else { option_type };
- ("CDS", "NSE_CURRENCY", it)
- }
- ("BSE", s) if s.contains("CUR") => {
- let it = if option_type.is_empty() { "FUT" } else { option_type };
- ("BCD", "BSE_CURRENCY", it)
- }
- _ => continue,
- };
-
- let _ = db.execute(
- "INSERT INTO dhan_symbols (symbol, name, exchange, br_exchange, security_id, instrument_type, lot_size, tick_size, expiry, strike)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
- rusqlite::params![trading_symbol, symbol_name, exchange, br_exchange, security_id, inst_type, lot_size, tick_size, expiry, strike],
- );
-
- count += 1;
- }
+ if result.success {
+ Ok(ApiResponse {
+ success: true,
+ data: Some(json!({
+ "total_symbols": result.total_symbols,
+ "message": result.message
+ })),
+ error: None,
+ timestamp,
+ })
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(result.message),
+ timestamp,
+ })
}
-
- // Update metadata
- db.execute(
- "INSERT OR REPLACE INTO dhan_metadata (key, value) VALUES ('last_updated', ?1)",
- rusqlite::params![get_timestamp().to_string()],
- )
- .map_err(|e| e.to_string())?;
-
- db.execute(
- "INSERT OR REPLACE INTO dhan_metadata (key, value) VALUES ('symbol_count', ?1)",
- rusqlite::params![count.to_string()],
- )
- .map_err(|e| e.to_string())?;
-
- Ok(ApiResponse {
- success: true,
- data: Some(json!({
- "count": count,
- "message": format!("Downloaded {} symbols", count)
- })),
- error: None,
- timestamp: get_timestamp(),
- })
}
+// Legacy download code removed - now using broker_downloads::dhan module
+
/// Search symbols in master contract
#[tauri::command]
pub async fn dhan_search_symbol(
@@ -893,70 +813,43 @@ pub async fn dhan_search_symbol(
exchange: Option<String>,
limit: Option<i32>,
) -> Result<ApiResponse<Vec<Value>>, String> {
- init_dhan_symbols_table()?;
- let db = get_db().map_err(|e| e.to_string())?;
+ use crate::database::symbol_master;
+
+ let search_limit = limit.unwrap_or(20);
+
+ match symbol_master::search_symbols("dhan", &keyword, exchange.as_deref(), None, search_limit) {
+ Ok(results) => {
+ let symbols: Vec<Value> = results.iter().map(|r| {
+ json!({
+ "symbol": r.symbol,
+ "name": r.name,
+ "exchange": r.exchange,
+ "br_symbol": r.br_symbol,
+ "token": r.token,
+ "lot_size": r.lot_size,
+ "tick_size": r.tick_size,
+ "instrument_type": r.instrument_type,
+ "strike": r.strike,
+ "expiry": r.expiry,
+ })
+ }).collect();
- let limit = limit.unwrap_or(20);
- let search_pattern = format!("%{}%", keyword);
-
- let query = if let Some(ref exch) = exchange {
- format!(
- "SELECT symbol, name, exchange, br_exchange, security_id, lot_size, tick_size, instrument_type, strike
- FROM dhan_symbols
- WHERE (symbol LIKE '{}' OR name LIKE '{}') AND exchange = '{}'
- LIMIT {}",
- search_pattern, search_pattern, exch, limit
- )
- } else {
- format!(
- "SELECT symbol, name, exchange, br_exchange, security_id, lot_size, tick_size, instrument_type, strike
- FROM dhan_symbols
- WHERE symbol LIKE '{}' OR name LIKE '{}'
- LIMIT {}",
- search_pattern, search_pattern, limit
- )
- };
-
- let mut stmt = db.prepare(&query).map_err(|e| e.to_string())?;
- let rows = stmt
- .query_map([], |row| {
- Ok((
- row.get::<_, String>(0)?,
- row.get::<_, String>(1)?,
- row.get::<_, String>(2)?,
- row.get::<_, String>(3)?,
- row.get::<_, String>(4)?,
- row.get::<_, i32>(5)?,
- row.get::<_, f64>(6)?,
- row.get::<_, String>(7)?,
- row.get::<_, f64>(8)?,
- ))
- })
- .map_err(|e| e.to_string())?;
-
- let symbols: Vec<Value> = rows
- .filter_map(|r| r.ok())
- .map(|(symbol, name, exchange, br_exchange, security_id, lot_size, tick_size, instrument_type, strike)| {
- json!({
- "symbol": symbol,
- "name": name,
- "exchange": exchange,
- "br_exchange": br_exchange,
- "security_id": security_id,
- "lot_size": lot_size,
- "tick_size": tick_size,
- "instrument_type": instrument_type,
- "strike": strike
+ Ok(ApiResponse {
+ success: true,
+ data: Some(symbols),
+ error: None,
+ timestamp: get_timestamp(),
})
- })
- .collect();
-
- Ok(ApiResponse {
- success: true,
- data: Some(symbols),
- error: None,
- timestamp: get_timestamp(),
- })
+ }
+ Err(e) => {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(vec![]),
+ error: Some(format!("Search failed: {}", e)),
+ timestamp: get_timestamp(),
+ })
+ }
+ }
}
/// Get security ID for a symbol
@@ -965,67 +858,55 @@ pub async fn dhan_get_security_id(
symbol: String,
exchange: String,
) -> Result<ApiResponse<String>, String> {
- init_dhan_symbols_table()?;
- let db = get_db().map_err(|e| e.to_string())?;
+ use crate::database::symbol_master;
- let result: Result<String, _> = db.query_row(
- "SELECT security_id FROM dhan_symbols WHERE symbol = ?1 AND exchange = ?2 LIMIT 1",
- rusqlite::params![symbol, exchange],
- |row| row.get(0),
- );
-
- match result {
- Ok(security_id) => Ok(ApiResponse {
+ match symbol_master::get_token_by_symbol("dhan", &symbol, &exchange) {
+ Ok(Some(token)) => Ok(ApiResponse {
success: true,
- data: Some(security_id),
+ data: Some(token),
error: None,
timestamp: get_timestamp(),
}),
- Err(_) => Ok(ApiResponse {
+ Ok(None) => Ok(ApiResponse {
success: false,
data: None,
error: Some(format!("Symbol {} not found on {}", symbol, exchange)),
timestamp: get_timestamp(),
}),
+ Err(e) => Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(format!("Lookup failed: {}", e)),
+ timestamp: get_timestamp(),
+ }),
}
}
/// Get master contract metadata
#[tauri::command]
pub async fn dhan_get_master_contract_metadata() -> Result<ApiResponse<Value>, String> {
- init_dhan_symbols_table()?;
- let db = get_db().map_err(|e| e.to_string())?;
-
- let last_updated: Result<String, _> = db.query_row(
- "SELECT value FROM dhan_metadata WHERE key = 'last_updated'",
- [],
- |row| row.get(0),
- );
+ use crate::database::symbol_master;
- let count: Result<String, _> = db.query_row(
- "SELECT value FROM dhan_metadata WHERE key = 'symbol_count'",
- [],
- |row| row.get(0),
- );
-
- match last_updated {
- Ok(timestamp_str) => {
- let last_updated: i64 = timestamp_str.parse().unwrap_or(0);
- let symbol_count: i64 = count.unwrap_or_default().parse().unwrap_or(0);
+ match symbol_master::get_status("dhan") {
+ Ok(info) => {
+ let now = chrono::Utc::now().timestamp();
Ok(ApiResponse {
success: true,
data: Some(json!({
- "last_updated": last_updated,
- "symbol_count": symbol_count
+ "last_updated": info.last_updated,
+ "symbol_count": info.total_symbols,
+ "age_seconds": now - info.last_updated,
+ "status": info.status,
+ "is_ready": info.is_ready,
})),
error: None,
timestamp: get_timestamp(),
})
}
- Err(_) => Ok(ApiResponse {
+ Err(e) => Ok(ApiResponse {
success: false,
data: None,
- error: Some("Master contract not downloaded".to_string()),
+ error: Some(format!("Failed to get metadata: {}", e)),
timestamp: get_timestamp(),
}),
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs
index 21f762688..ee100e41f 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs
@@ -20,6 +20,7 @@ use tauri::Emitter;
use crate::websocket::types::MarketMessage;
use crate::websocket::types::ProviderConfig;
use crate::websocket::adapters::WebSocketAdapter;
+use crate::WebSocketState;
use super::common::{ApiResponse, TokenExchangeResponse, OrderPlaceResponse};
// Fyers API Configuration
@@ -866,55 +867,29 @@ pub async fn fyers_calculate_margin(
// Fyers Master Contract Commands
// ============================================================================
-use crate::database::fyers_symbols::{self, FyersSymbol};
+use crate::database::symbol_master;
+// Legacy: use crate::database::fyers_symbols::{self, FyersSymbol};
/// Download and cache Fyers master contract (symbol master)
/// This provides symbol-to-token mapping required for WebSocket subscriptions
#[tauri::command]
pub async fn fyers_download_master_contract(
- api_key: String,
- access_token: String,
+ _api_key: String,
+ _access_token: String,
) -> Result<ApiResponse<Value>, String> {
- eprintln!("[fyers_download_master_contract] Downloading master contract");
+ eprintln!("[fyers_download_master_contract] Downloading master contract via unified system");
let timestamp = chrono::Utc::now().timestamp();
- let headers = create_fyers_headers(&api_key, &access_token);
- let client = reqwest::Client::new();
-
- // Fyers provides symbol master as CSV download
- // Note: Fyers symbol master endpoint is /data/symbol-master (NOT /data-rest/v3/symbol-master)
- let url = format!("{}/data/symbol-master", FYERS_API_BASE);
-
- let response = client
- .get(&url)
- .headers(headers)
- .send()
- .await
- .map_err(|e| format!("Request failed: {}", e))?;
-
- let status = response.status();
-
- if status.is_success() {
- // Get response body as text (CSV format)
- let csv_data = response.text().await.map_err(|e| format!("Failed to read response: {}", e))?;
-
- eprintln!("[fyers_download_master_contract] Downloaded CSV with {} lines", csv_data.lines().count());
-
- // Parse CSV and populate database
- let symbols = parse_fyers_csv(&csv_data).map_err(|e| format!("Failed to parse CSV: {}", e))?;
- eprintln!("[fyers_download_master_contract] Parsed {} symbols", symbols.len());
-
- // Save to database in bulk
- fyers_symbols::save_symbols_bulk(&symbols).map_err(|e| format!("Failed to save symbols: {}", e))?;
-
- eprintln!("[fyers_download_master_contract] Saved {} symbols to database", symbols.len());
+ // Use the new unified broker downloads system
+ let result = crate::commands::broker_downloads::fyers::fyers_download_symbols().await;
+ if result.success {
Ok(ApiResponse {
success: true,
data: Some(json!({
- "symbol_count": symbols.len(),
- "message": "Master contract downloaded and cached successfully"
+ "symbol_count": result.total_symbols,
+ "message": result.message
})),
error: None,
timestamp,
@@ -923,75 +898,13 @@ pub async fn fyers_download_master_contract(
Ok(ApiResponse {
success: false,
data: None,
- error: Some("Failed to download master contract".to_string()),
+ error: Some(result.message),
timestamp,
})
}
}
-/// Parse Fyers CSV format into symbol structures
-fn parse_fyers_csv(csv_data: &str) -> Result<Vec<FyersSymbol>, String> {
- let mut symbols = Vec::new();
- let mut lines = csv_data.lines();
-
- // Skip header line
- lines.next();
-
- for line in lines {
- if line.trim().is_empty() {
- continue;
- }
-
- let fields: Vec<&str> = line.split(',').collect();
-
- // Fyers CSV format (typical):
- // Token,Symbol,Name,Exchange,Segment,InstrumentType,ISIN,TickSize,LotSize
- // Example: 11536,RELIANCE-EQ,Reliance Industries Ltd,NSE,CM,EQ,INE002A01018,0.05,1
-
- if fields.len() >= 6 {
- // Parse token safely
- let token = fields[0].trim().parse::<i32>().unwrap_or(0);
-
- if token == 0 {
- continue; // Skip invalid tokens
- }
-
- let symbol = fields.get(1).unwrap_or(&"").trim().to_string();
- let name = fields.get(2).unwrap_or(&"").trim().to_string();
- let exchange = fields.get(3).unwrap_or(&"NSE").trim().to_string();
- let segment = fields.get(4).unwrap_or(&"").trim().to_string();
- let instrument_type = fields.get(5).unwrap_or(&"").trim().to_string();
- let isin = fields.get(6).and_then(|s| {
- let trimmed = s.trim();
- if trimmed.is_empty() {
- None
- } else {
- Some(trimmed.to_string())
- }
- });
- let tick_size = fields.get(7)
- .and_then(|s| s.trim().parse::<f64>().ok())
- .unwrap_or(0.05);
- let lot_size = fields.get(8)
- .and_then(|s| s.trim().parse::<i32>().ok())
- .unwrap_or(1);
-
- symbols.push(FyersSymbol {
- token,
- symbol,
- name,
- exchange,
- segment,
- instrument_type,
- isin,
- tick_size,
- lot_size,
- });
- }
- }
-
- Ok(symbols)
-}
+// Legacy parse_fyers_csv removed - now using broker_downloads::fyers module
/// Search for symbols in master contract
#[tauri::command]
@@ -1005,13 +918,25 @@ pub async fn fyers_search_symbol(
let timestamp = chrono::Utc::now().timestamp();
let search_limit = limit.unwrap_or(20);
- match fyers_symbols::search_symbols(&keyword, exchange.as_deref(), search_limit) {
+ match symbol_master::search_symbols("fyers", &keyword, exchange.as_deref(), None, search_limit) {
Ok(results) => {
eprintln!("[fyers_search_symbol] Found {} results", results.len());
+ let json_results: Vec<Value> = results.iter().map(|r| json!({
+ "symbol": r.symbol,
+ "br_symbol": r.br_symbol,
+ "name": r.name,
+ "exchange": r.exchange,
+ "token": r.token,
+ "instrument_type": r.instrument_type,
+ "lot_size": r.lot_size,
+ "tick_size": r.tick_size,
+ "expiry": r.expiry,
+ "strike": r.strike,
+ })).collect();
Ok(ApiResponse {
success: true,
data: Some(json!({
- "results": results,
+ "results": json_results,
"count": results.len()
})),
error: None,
@@ -1040,8 +965,9 @@ pub async fn fyers_get_token_for_symbol(
let timestamp = chrono::Utc::now().timestamp();
- match fyers_symbols::get_token_by_symbol(&symbol, &exchange) {
- Ok(Some(token)) => {
+ match symbol_master::get_token_by_symbol("fyers", &symbol, &exchange) {
+ Ok(Some(token_str)) => {
+ let token: i32 = token_str.parse().unwrap_or(0);
eprintln!("[fyers_get_token_for_symbol] Found token: {}", token);
Ok(ApiResponse {
success: true,
@@ -1080,11 +1006,22 @@ pub async fn fyers_get_symbol_by_token(
let timestamp = chrono::Utc::now().timestamp();
- match fyers_symbols::get_symbol_by_token(token) {
- Ok(Some(symbol_info)) => {
+ match symbol_master::get_symbol_by_token("fyers", &token.to_string()) {
+ Ok(Some(r)) => {
Ok(ApiResponse {
success: true,
- data: Some(json!(symbol_info)),
+ data: Some(json!({
+ "symbol": r.symbol,
+ "br_symbol": r.br_symbol,
+ "name": r.name,
+ "exchange": r.exchange,
+ "token": r.token,
+ "instrument_type": r.instrument_type,
+ "lot_size": r.lot_size,
+ "tick_size": r.tick_size,
+ "expiry": r.expiry,
+ "strike": r.strike,
+ })),
error: None,
timestamp,
})
@@ -1113,27 +1050,21 @@ pub async fn fyers_get_symbol_by_token(
pub async fn fyers_get_master_contract_metadata() -> Result<ApiResponse<Value>, String> {
let timestamp = chrono::Utc::now().timestamp();
- match fyers_symbols::get_metadata() {
- Ok(Some((last_updated, count))) => {
+ match symbol_master::get_status("fyers") {
+ Ok(info) => {
Ok(ApiResponse {
success: true,
data: Some(json!({
- "last_updated": last_updated,
- "symbol_count": count,
- "age_seconds": timestamp - last_updated
+ "last_updated": info.last_updated,
+ "symbol_count": info.total_symbols,
+ "age_seconds": timestamp - info.last_updated,
+ "status": info.status,
+ "is_ready": info.is_ready,
})),
error: None,
timestamp,
})
}
- Ok(None) => {
- Ok(ApiResponse {
- success: false,
- data: None,
- error: Some("Master contract not downloaded yet".to_string()),
- timestamp,
- })
- }
Err(e) => {
Ok(ApiResponse {
success: false,
@@ -1157,6 +1088,7 @@ static FYERS_WS: Lazy<Arc<RwLock<Option<crate::websocket::adapters::FyersAdapter
#[tauri::command]
pub async fn fyers_ws_connect(
app: tauri::AppHandle,
+ state: tauri::State<'_, WebSocketState>,
_api_key: String,
access_token: String,
) -> Result<ApiResponse<bool>, String> {
@@ -1180,9 +1112,13 @@ pub async fn fyers_ws_connect(
let mut adapter = crate::websocket::adapters::FyersAdapter::new(config);
- // Set up message callback to emit Tauri events
+ // Clone the router so backend services (monitoring, candle aggregation, etc.) receive ticks
+ let router = state.router.clone();
+
+ // Set up message callback to emit Tauri events AND route through MessageRouter
let app_handle = app.clone();
adapter.set_message_callback(Box::new(move |msg: MarketMessage| {
+ // 1. Emit broker-specific events to frontend
match &msg {
MarketMessage::Ticker(data) => {
let _ = app_handle.emit("fyers_ticker", data);
@@ -1200,6 +1136,13 @@ pub async fn fyers_ws_connect(
let _ = app_handle.emit("fyers_candle", data);
}
}
+
+ // 2. Route through MessageRouter for backend services (monitoring, algo trading, etc.)
+ let router = router.clone();
+ let msg = msg.clone();
+ tokio::spawn(async move {
+ router.read().await.route(msg).await;
+ });
}));
// Connect to WebSocket
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/shoonya.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/shoonya.rs
index d4e3c7e25..6c12f3080 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/shoonya.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/shoonya.rs
@@ -943,59 +943,31 @@ const SHOONYA_MASTER_URLS: &[(&str, &str)] = &[
/// Download and cache Shoonya master contract
#[tauri::command]
pub async fn shoonya_download_master_contract() -> Result<ApiResponse<Value>, String> {
- eprintln!("[shoonya_download_master_contract] Downloading master contract");
+ eprintln!("[shoonya_download_master_contract] Downloading master contract via unified system");
let timestamp = chrono::Utc::now().timestamp();
- let client = reqwest::Client::new();
- let mut total_symbols = 0;
- let mut segment_counts: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
-
- for (exchange, url) in SHOONYA_MASTER_URLS {
- eprintln!("[shoonya_download_master_contract] Downloading {}", exchange);
-
- match client.get(*url).send().await {
- Ok(response) => {
- if response.status().is_success() {
- let bytes = response.bytes().await.map_err(|e| format!("Failed to read response: {}", e))?;
-
- // Unzip and parse CSV
- match parse_shoonya_zip(&bytes, exchange) {
- Ok(symbols) => {
- let count = symbols.len() as i32;
- eprintln!("[shoonya_download_master_contract] Parsed {} symbols for {}", count, exchange);
-
- // Save to database
- if let Err(e) = shoonya_symbols::save_symbols_bulk(&symbols) {
- eprintln!("[shoonya_download_master_contract] Failed to save {} symbols: {}", exchange, e);
- } else {
- segment_counts.insert(exchange.to_string(), count);
- total_symbols += count;
- }
- }
- Err(e) => {
- eprintln!("[shoonya_download_master_contract] Failed to parse {}: {}", exchange, e);
- }
- }
- } else {
- eprintln!("[shoonya_download_master_contract] Failed to download {}: {}", exchange, response.status());
- }
- }
- Err(e) => {
- eprintln!("[shoonya_download_master_contract] Request failed for {}: {}", exchange, e);
- }
- }
- }
- Ok(ApiResponse {
- success: total_symbols > 0,
- data: Some(json!({
- "total_symbols": total_symbols,
- "segments": segment_counts,
- "message": format!("Downloaded {} symbols", total_symbols)
- })),
- error: if total_symbols == 0 { Some("Failed to download any symbols".to_string()) } else { None },
- timestamp,
- })
+ // Use the new unified broker downloads system
+ let result = crate::commands::broker_downloads::shoonya::shoonya_download_symbols().await;
+
+ if result.success {
+ Ok(ApiResponse {
+ success: true,
+ data: Some(json!({
+ "total_symbols": result.total_symbols,
+ "message": result.message
+ })),
+ error: None,
+ timestamp,
+ })
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(result.message),
+ timestamp,
+ })
+ }
}
/// Parse Shoonya ZIP file containing symbol CSV
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/upstox.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/upstox.rs
index 42d122f8b..ba9a6ff26 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/upstox.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/upstox.rs
@@ -937,26 +937,26 @@ fn get_upstox_metadata() -> Result<Option<(i64, i64)>, String> {
pub async fn upstox_download_master_contract() -> Result<ApiResponse<Value>, String> {
let timestamp = chrono::Utc::now().timestamp();
- match download_and_store_upstox_symbols().await {
- Ok((total, segments)) => {
- Ok(ApiResponse {
- success: true,
- data: Some(json!({
- "total_symbols": total,
- "segments": segments
- })),
- error: None,
- timestamp,
- })
- }
- Err(e) => {
- Ok(ApiResponse {
- success: false,
- data: None,
- error: Some(e),
- timestamp,
- })
- }
+ // Use the new unified broker downloads system
+ let result = crate::commands::broker_downloads::upstox::upstox_download_symbols().await;
+
+ if result.success {
+ Ok(ApiResponse {
+ success: true,
+ data: Some(json!({
+ "total_symbols": result.total_symbols,
+ "message": result.message
+ })),
+ error: None,
+ timestamp,
+ })
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(result.message),
+ timestamp,
+ })
}
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/zerodha.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/zerodha.rs
index 3f4a84db9..f8e47a90c 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/zerodha.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/zerodha.rs
@@ -942,46 +942,29 @@ pub async fn search_indian_symbols(
) -> Result<Vec<Value>, String> {
eprintln!("[search_indian_symbols] Searching for '{}' in {} broker", query, broker_id);
- use crate::commands::master_contract::get_master_contract_cache;
-
- // Get cached master contract
- let cache_data = get_master_contract_cache(broker_id.clone()).await?;
-
- // Parse the cached data
- let instruments: Vec<Value> = serde_json::from_str(&cache_data)
- .map_err(|e| format!("Failed to parse master contract: {}", e))?;
-
- // Filter instruments
- let query_lower = query.to_lowercase();
- let results: Vec<Value> = instruments
- .into_iter()
- .filter(|inst| {
- let symbol = inst.get("symbol")
- .or(inst.get("tradingsymbol"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_lowercase();
-
- let name = inst.get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_lowercase();
-
- let inst_exchange = inst.get("exchange")
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- let matches_query = symbol.contains(&query_lower) || name.contains(&query_lower);
- let matches_exchange = exchange.as_ref()
- .map(|e| inst_exchange.eq_ignore_ascii_case(e))
- .unwrap_or(true);
-
- matches_query && matches_exchange
- })
- .take(50) // Limit results
- .collect();
-
- Ok(results)
+ use crate::database::symbol_master;
+
+ // Search using symbol master DB
+ match symbol_master::search_symbols(&broker_id, &query, exchange.as_deref(), None, 50) {
+ Ok(results) => {
+ let values: Vec<Value> = results.iter().map(|r| {
+ json!({
+ "symbol": r.symbol,
+ "tradingsymbol": r.br_symbol,
+ "name": r.name,
+ "exchange": r.exchange,
+ "token": r.token,
+ "instrumenttype": r.instrument_type,
+ "lotsize": r.lot_size,
+ "ticksize": r.tick_size,
+ "expiry": r.expiry,
+ "strike": r.strike,
+ })
+ }).collect();
+ Ok(values)
+ }
+ Err(e) => Err(format!("Search failed: {}", e)),
+ }
}
/// Get symbol token from master contract
@@ -993,37 +976,25 @@ pub async fn get_indian_symbol_token(
) -> Result<Option<Value>, String> {
eprintln!("[get_indian_symbol_token] Getting token for {}:{}", exchange, symbol);
- use crate::commands::master_contract::get_master_contract_cache;
-
- // Get cached master contract
- let cache_data = get_master_contract_cache(broker_id.clone()).await?;
-
- // Parse the cached data
- let instruments: Vec<Value> = serde_json::from_str(&cache_data)
- .map_err(|e| format!("Failed to parse master contract: {}", e))?;
-
- // Find matching instrument
- let symbol_upper = symbol.to_uppercase();
- let exchange_upper = exchange.to_uppercase();
-
- let result = instruments
- .into_iter()
- .find(|inst| {
- let inst_symbol = inst.get("symbol")
- .or(inst.get("tradingsymbol"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_uppercase();
-
- let inst_exchange = inst.get("exchange")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_uppercase();
-
- inst_symbol == symbol_upper && inst_exchange == exchange_upper
- });
-
- Ok(result)
+ use crate::database::symbol_master;
+
+ // Search using symbol master DB
+ match symbol_master::get_symbol(&broker_id, &symbol, &exchange) {
+ Ok(Some(r)) => Ok(Some(json!({
+ "symbol": r.symbol,
+ "tradingsymbol": r.br_symbol,
+ "name": r.name,
+ "exchange": r.exchange,
+ "token": r.token,
+ "instrumenttype": r.instrument_type,
+ "lotsize": r.lot_size,
+ "ticksize": r.tick_size,
+ "expiry": r.expiry,
+ "strike": r.strike,
+ }))),
+ Ok(None) => Ok(None),
+ Err(e) => Err(format!("Lookup failed: {}", e)),
+ }
}
/// Get master contract last updated timestamp
@@ -1033,9 +1004,9 @@ pub async fn get_master_contract_timestamp(
) -> Result<Option<i64>, String> {
eprintln!("[get_master_contract_timestamp] Getting timestamp for: {}", broker_id);
- use crate::commands::master_contract::get_master_contract_cache_info;
+ use crate::database::symbol_master;
- match get_master_contract_cache_info(broker_id).await {
+ match symbol_master::get_status(&broker_id) {
Ok(info) => Ok(Some(info.last_updated)),
Err(_) => Ok(None),
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/master_contract.rs b/fincept-terminal-desktop/src-tauri/src/commands/master_contract.rs
deleted file mode 100644
index 3b93d7608..000000000
--- a/fincept-terminal-desktop/src-tauri/src/commands/master_contract.rs
+++ /dev/null
@@ -1,549 +0,0 @@
-#![allow(dead_code)]
-// Master Contract Commands
-// Tauri commands for broker symbol data management and search
-
-use crate::database::master_contract::{self, SearchResult, Symbol};
-use serde::{Deserialize, Serialize};
-
-// ============================================================================
-// Data Structures
-// ============================================================================
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct MasterContractInfo {
- pub broker_id: String,
- pub symbol_count: i64,
- pub last_updated: i64,
- pub created_at: i64,
- pub cache_age_seconds: i64,
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct DownloadResult {
- pub success: bool,
- pub broker_id: String,
- pub symbol_count: i64,
- pub message: String,
-}
-
-/// Angel One symbol from their JSON API
-#[derive(Debug, Deserialize)]
-struct AngelOneSymbol {
- token: String,
- symbol: String,
- name: String,
- expiry: Option<String>,
- strike: Option<String>,
- lotsize: Option<String>,
- instrumenttype: Option<String>,
- exch_seg: String,
- tick_size: Option<String>,
-}
-
-/// Fyers symbol from their CSV
-#[derive(Debug, Deserialize)]
-struct FyersSymbol {
- #[serde(rename = "Fytoken")]
- fytoken: String,
- #[serde(rename = "Symbol Details")]
- symbol_details: Option<String>,
- #[serde(rename = "Exchange Instrument type")]
- exchange_instrument_type: Option<i32>,
- #[serde(rename = "Minimum lot size")]
- minimum_lot_size: Option<i32>,
- #[serde(rename = "Tick size")]
- tick_size: Option<f64>,
- #[serde(rename = "ISIN")]
- isin: Option<String>,
- #[serde(rename = "Trading Session")]
- trading_session: Option<String>,
- #[serde(rename = "Last update date")]
- last_update_date: Option<String>,
- #[serde(rename = "Expiry date")]
- expiry_date: Option<String>,
- #[serde(rename = "Symbol ticker")]
- symbol_ticker: String,
- #[serde(rename = "Exchange")]
- exchange: Option<i32>,
- #[serde(rename = "Segment")]
- segment: Option<i32>,
- #[serde(rename = "Scrip code")]
- scrip_code: Option<i32>,
- #[serde(rename = "Underlying symbol")]
- underlying_symbol: Option<String>,
- #[serde(rename = "Underlying scrip code")]
- underlying_scrip_code: Option<i64>,
- #[serde(rename = "Strike price")]
- strike_price: Option<f64>,
- #[serde(rename = "Option type")]
- option_type: Option<String>,
-}
-
-// ============================================================================
-// Download Commands
-// ============================================================================
-
-/// Download master contract for Angel One
-#[tauri::command]
-pub async fn download_angelone_master_contract() -> Result<DownloadResult, String> {
- eprintln!("[MasterContract] Downloading Angel One master contract...");
-
- let url = "https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json";
-
- let response = reqwest::get(url)
- .await
- .map_err(|e| format!("Failed to download: {}", e))?;
-
- if !response.status().is_success() {
- return Err(format!("HTTP error: {}", response.status()));
- }
-
- let json_data: Vec<AngelOneSymbol> = response
- .json()
- .await
- .map_err(|e| format!("Failed to parse JSON: {}", e))?;
-
- eprintln!("[MasterContract] Downloaded {} symbols from Angel One", json_data.len());
-
- // Transform to our schema
- let symbols: Vec<Symbol> = json_data
- .into_iter()
- .map(|s| {
- // Normalize exchange
- let exchange = normalize_angelone_exchange(&s.exch_seg, s.instrumenttype.as_deref());
-
- // Normalize symbol (remove suffixes like -EQ, -BE, etc.)
- let symbol = s.symbol
- .replace("-EQ", "")
- .replace("-BE", "")
- .replace("-MF", "")
- .replace("-SG", "");
-
- // Parse strike price
- let strike = s.strike
- .as_ref()
- .and_then(|st| st.parse::<f64>().ok())
- .map(|st| st / 100.0);
-
- // Parse lot size
- let lot_size = s.lotsize
- .as_ref()
- .and_then(|ls| ls.parse::<i32>().ok());
-
- // Parse tick size
- let tick_size = s.tick_size
- .as_ref()
- .and_then(|ts| ts.parse::<f64>().ok())
- .map(|ts| ts / 100.0);
-
- // Normalize instrument type
- let instrument_type = normalize_instrument_type(s.instrumenttype.as_deref());
-
- // Format expiry
- let expiry = s.expiry.as_ref().map(|e| format_angelone_expiry(e));
-
- Symbol {
- id: None,
- broker_id: "angelone".to_string(),
- symbol,
- br_symbol: s.symbol.clone(),
- name: Some(s.name),
- exchange,
- br_exchange: Some(s.exch_seg.clone()),
- token: s.token,
- expiry,
- strike,
- lot_size,
- instrument_type,
- tick_size,
- segment: Some(s.exch_seg),
- }
- })
- .collect();
-
- let symbol_count = symbols.len() as i64;
-
- // Delete old symbols and insert new ones
- master_contract::delete_symbols_for_broker("angelone")
- .map_err(|e| format!("Failed to delete old symbols: {}", e))?;
-
- master_contract::bulk_insert_symbols(&symbols)
- .map_err(|e| format!("Failed to insert symbols: {}", e))?;
-
- // Update cache metadata
- master_contract::save_master_contract("angelone", "{}", symbol_count)
- .map_err(|e| format!("Failed to save cache metadata: {}", e))?;
-
- eprintln!("[MasterContract] ✓ Angel One master contract saved ({} symbols)", symbol_count);
-
- Ok(DownloadResult {
- success: true,
- broker_id: "angelone".to_string(),
- symbol_count,
- message: format!("Successfully downloaded {} symbols", symbol_count),
- })
-}
-
-/// Download master contract for Fyers
-#[tauri::command]
-pub async fn download_fyers_master_contract() -> Result<DownloadResult, String> {
- eprintln!("[MasterContract] Downloading Fyers master contract...");
-
- let segments = vec![
- ("NSE_CM", "https://public.fyers.in/sym_details/NSE_CM.csv"),
- ("NSE_FO", "https://public.fyers.in/sym_details/NSE_FO.csv"),
- ("NSE_CD", "https://public.fyers.in/sym_details/NSE_CD.csv"),
- ("BSE_CM", "https://public.fyers.in/sym_details/BSE_CM.csv"),
- ("BSE_FO", "https://public.fyers.in/sym_details/BSE_FO.csv"),
- ("MCX_COM", "https://public.fyers.in/sym_details/MCX_COM.csv"),
- ];
-
- let mut all_symbols: Vec<Symbol> = Vec::new();
-
- for (segment_name, url) in segments {
- eprintln!("[MasterContract] Downloading Fyers {} segment...", segment_name);
-
- let response = match reqwest::get(url).await {
- Ok(r) => r,
- Err(e) => {
- eprintln!("[MasterContract] Warning: Failed to download {}: {}", segment_name, e);
- continue;
- }
- };
-
- if !response.status().is_success() {
- eprintln!("[MasterContract] Warning: HTTP error for {}: {}", segment_name, response.status());
- continue;
- }
-
- let csv_text = response
- .text()
- .await
- .map_err(|e| format!("Failed to read CSV: {}", e))?;
-
- // Parse CSV with flexible reader
- let mut reader = csv::ReaderBuilder::new()
- .has_headers(false)
- .flexible(true)
- .from_reader(csv_text.as_bytes());
-
- for result in reader.records() {
- let record: csv::StringRecord = match result {
- Ok(r) => r,
- Err(_) => continue,
- };
-
- // Fyers CSV format: Fytoken, Symbol Details, Exchange Instrument type, Lot size, Tick size, ISIN, Trading Session, Last update, Expiry, Symbol ticker, Exchange, Segment, Scrip code, Underlying, Underlying code, Strike, Option type, Underlying FyToken, Reserved...
- if record.len() < 10 {
- continue;
- }
-
- let fytoken = record.get(0).unwrap_or("").to_string();
- let symbol_ticker = record.get(9).unwrap_or("").to_string();
-
- if fytoken.is_empty() || symbol_ticker.is_empty() {
- continue;
- }
-
- let exchange = map_fyers_exchange(record.get(10).and_then(|s| s.parse::<i32>().ok()));
- let lot_size = record.get(3).and_then(|s| s.parse::<i32>().ok());
- let tick_size = record.get(4).and_then(|s| s.parse::<f64>().ok());
- let expiry = record.get(8).map(|s| s.to_string()).filter(|s| !s.is_empty());
- let underlying = record.get(13).map(|s| s.to_string()).filter(|s| !s.is_empty());
- let strike = record.get(15).and_then(|s| s.parse::<f64>().ok());
- let option_type = record.get(16).map(|s| s.to_string()).filter(|s| !s.is_empty());
-
- // Determine instrument type
- let instrument_type = determine_fyers_instrument_type(&symbol_ticker, option_type.as_deref());
-
- // Extract base symbol
- let symbol = extract_fyers_symbol(&symbol_ticker);
-
- all_symbols.push(Symbol {
- id: None,
- broker_id: "fyers".to_string(),
- symbol,
- br_symbol: symbol_ticker.clone(),
- name: underlying,
- exchange,
- br_exchange: Some(segment_name.to_string()),
- token: fytoken,
- expiry,
- strike,
- lot_size,
- instrument_type,
- tick_size,
- segment: Some(segment_name.to_string()),
- });
- }
- }
-
- let symbol_count = all_symbols.len() as i64;
-
- if symbol_count == 0 {
- return Err("No symbols downloaded from Fyers".to_string());
- }
-
- // Delete old symbols and insert new ones
- master_contract::delete_symbols_for_broker("fyers")
- .map_err(|e| format!("Failed to delete old symbols: {}", e))?;
-
- master_contract::bulk_insert_symbols(&all_symbols)
- .map_err(|e| format!("Failed to insert symbols: {}", e))?;
-
- // Update cache metadata
- master_contract::save_master_contract("fyers", "{}", symbol_count)
- .map_err(|e| format!("Failed to save cache metadata: {}", e))?;
-
- eprintln!("[MasterContract] ✓ Fyers master contract saved ({} symbols)", symbol_count);
-
- Ok(DownloadResult {
- success: true,
- broker_id: "fyers".to_string(),
- symbol_count,
- message: format!("Successfully downloaded {} symbols", symbol_count),
- })
-}
-
-/// Download master contract for any broker
-#[tauri::command]
-pub async fn download_master_contract(broker_id: String) -> Result<DownloadResult, String> {
- match broker_id.as_str() {
- "angelone" => download_angelone_master_contract().await,
- "fyers" => download_fyers_master_contract().await,
- "zerodha" => Err("Zerodha master contract requires authentication. Use zerodha_download_instruments command.".to_string()),
- _ => Err(format!("Unknown broker: {}", broker_id)),
- }
-}
-
-// ============================================================================
-// Search Commands
-// ============================================================================
-
-/// Search symbols
-#[tauri::command]
-pub async fn search_symbols(
- broker_id: String,
- query: String,
- exchange: Option<String>,
- instrument_type: Option<String>,
- limit: Option<i32>,
-) -> Result<Vec<SearchResult>, String> {
- let limit = limit.unwrap_or(50);
-
- master_contract::search_symbols(
- &broker_id,
- &query,
- exchange.as_deref(),
- instrument_type.as_deref(),
- limit,
- )
- .map_err(|e| format!("Search failed: {}", e))
-}
-
-/// Get symbol by exact match
-#[tauri::command]
-pub async fn get_symbol(
- broker_id: String,
- symbol: String,
- exchange: String,
-) -> Result<Option<SearchResult>, String> {
- master_contract::get_symbol(&broker_id, &symbol, &exchange)
- .map_err(|e| format!("Failed to get symbol: {}", e))
-}
-
-/// Get symbol by token
-#[tauri::command]
-pub async fn get_symbol_by_token(
- broker_id: String,
- token: String,
-) -> Result<Option<SearchResult>, String> {
- master_contract::get_symbol_by_token(&broker_id, &token)
- .map_err(|e| format!("Failed to get symbol: {}", e))
-}
-
-/// Get symbol count for a broker
-#[tauri::command]
-pub async fn get_symbol_count(broker_id: String) -> Result<i64, String> {
- master_contract::get_symbol_count(&broker_id)
- .map_err(|e| format!("Failed to get symbol count: {}", e))
-}
-
-/// Get available exchanges for a broker
-#[tauri::command]
-pub async fn get_exchanges(broker_id: String) -> Result<Vec<String>, String> {
- master_contract::get_exchanges(&broker_id)
- .map_err(|e| format!("Failed to get exchanges: {}", e))
-}
-
-/// Get available expiries
-#[tauri::command]
-pub async fn get_expiries(
- broker_id: String,
- exchange: Option<String>,
- underlying: Option<String>,
-) -> Result<Vec<String>, String> {
- master_contract::get_expiries(&broker_id, exchange.as_deref(), underlying.as_deref())
- .map_err(|e| format!("Failed to get expiries: {}", e))
-}
-
-// ============================================================================
-// Cache Management Commands
-// ============================================================================
-
-/// Save master contract cache (legacy)
-#[tauri::command]
-pub async fn save_master_contract_cache(
- broker_id: String,
- symbols_data: String,
- symbol_count: i64,
-) -> Result<String, String> {
- master_contract::save_master_contract(&broker_id, &symbols_data, symbol_count)
- .map_err(|e| format!("Failed to save master contract: {}", e))?;
-
- Ok(format!(
- "Master contract saved for {} ({} symbols)",
- broker_id, symbol_count
- ))
-}
-
-/// Get master contract cache (legacy)
-#[tauri::command]
-pub async fn get_master_contract_cache(broker_id: String) -> Result<String, String> {
- let cache = master_contract::get_master_contract(&broker_id)
- .map_err(|e| format!("Failed to get master contract: {}", e))?;
-
- match cache {
- Some(data) => Ok(data.symbols_data),
- None => Err(format!("No master contract found for {}", broker_id)),
- }
-}
-
-/// Delete master contract cache
-#[tauri::command]
-pub async fn delete_master_contract_cache(broker_id: String) -> Result<String, String> {
- // Delete both cache and symbols
- master_contract::delete_symbols_for_broker(&broker_id)
- .map_err(|e| format!("Failed to delete symbols: {}", e))?;
-
- master_contract::delete_master_contract(&broker_id)
- .map_err(|e| format!("Failed to delete master contract: {}", e))?;
-
- Ok(format!("Master contract deleted for {}", broker_id))
-}
-
-/// Check if cache is valid
-#[tauri::command]
-pub async fn is_master_contract_cache_valid(
- broker_id: String,
- ttl_seconds: i64,
-) -> Result<bool, String> {
- master_contract::is_cache_valid(&broker_id, ttl_seconds)
- .map_err(|e| format!("Failed to check cache validity: {}", e))
-}
-
-/// Get master contract cache info
-#[tauri::command]
-pub async fn get_master_contract_cache_info(
- broker_id: String,
-) -> Result<MasterContractInfo, String> {
- let cache = master_contract::get_master_contract(&broker_id)
- .map_err(|e| format!("Failed to get master contract: {}", e))?;
-
- match cache {
- Some(data) => {
- let cache_age = master_contract::get_cache_age(&broker_id)
- .map_err(|e| format!("Failed to get cache age: {}", e))?
- .unwrap_or(0);
-
- Ok(MasterContractInfo {
- broker_id: data.broker_id,
- symbol_count: data.symbol_count,
- last_updated: data.last_updated,
- created_at: data.created_at,
- cache_age_seconds: cache_age,
- })
- }
- None => Err(format!("No master contract found for {}", broker_id)),
- }
-}
-
-// ============================================================================
-// Helper Functions
-// ============================================================================
-
-fn normalize_angelone_exchange(exch_seg: &str, instrument_type: Option<&str>) -> String {
- match (exch_seg, instrument_type) {
- ("NSE", Some("AMXIDX")) => "NSE_INDEX".to_string(),
- ("BSE", Some("AMXIDX")) => "BSE_INDEX".to_string(),
- ("MCX", Some("AMXIDX")) => "MCX_INDEX".to_string(),
- _ => exch_seg.to_string(),
- }
-}
-
-fn normalize_instrument_type(inst_type: Option<&str>) -> Option<String> {
- match inst_type {
- Some("OPTIDX") | Some("OPTSTK") => {
- // Will be determined by symbol suffix (CE/PE)
- None
- }
- Some("FUTIDX") | Some("FUTSTK") | Some("FUTCOM") | Some("FUTCUR") | Some("FUTIRC") => {
- Some("FUT".to_string())
- }
- Some("OPTFUT") | Some("OPTCUR") | Some("OPTIRC") => None,
- Some(t) => Some(t.to_string()),
- None => None,
- }
-}
-
-fn format_angelone_expiry(expiry: &str) -> String {
- // Convert from '19MAR2024' to '19-MAR-24'
- if expiry.len() >= 9 {
- let day = &expiry[0..2];
- let month = &expiry[2..5];
- let year = &expiry[7..9];
- format!("{}-{}-{}", day, month.to_uppercase(), year)
- } else {
- expiry.to_uppercase()
- }
-}
-
-fn map_fyers_exchange(exchange_code: Option<i32>) -> String {
- match exchange_code {
- Some(10) => "NSE".to_string(),
- Some(11) => "MCX".to_string(),
- Some(12) => "BSE".to_string(),
- _ => "NSE".to_string(),
- }
-}
-
-fn determine_fyers_instrument_type(symbol: &str, option_type: Option<&str>) -> Option<String> {
- if let Some(opt) = option_type {
- if opt == "CE" || opt == "PE" {
- return Some(opt.to_string());
- }
- }
-
- if symbol.ends_with("FUT") {
- Some("FUT".to_string())
- } else if symbol.ends_with("CE") {
- Some("CE".to_string())
- } else if symbol.ends_with("PE") {
- Some("PE".to_string())
- } else if symbol.contains("-EQ") || !symbol.contains('-') {
- Some("EQ".to_string())
- } else {
- None
- }
-}
-
-fn extract_fyers_symbol(symbol_ticker: &str) -> String {
- // Fyers symbols are like "NSE:RELIANCE-EQ" or "NSE:NIFTY24JAN25000CE"
- if let Some(pos) = symbol_ticker.find(':') {
- let after_colon = &symbol_ticker[pos + 1..];
- // Remove -EQ suffix for equity
- after_colon.replace("-EQ", "").replace("-BE", "")
- } else {
- symbol_ticker.replace("-EQ", "").replace("-BE", "")
- }
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
index 8b2fb6fac..171556d56 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
@@ -145,8 +145,14 @@ pub mod brokers;
// Broker Credentials - Secure encrypted storage for broker API credentials
pub mod broker_credentials;
-// Master Contract Cache - Broker symbol data caching
-pub mod master_contract;
+// Master Contract Cache - REMOVED (use symbol_master instead)
+// pub mod master_contract;
+
+// Unified Symbol Master - Cross-broker symbol database
+pub mod symbol_master;
+
+// Broker Master Contract Downloads - Unified symbol download for all brokers
+pub mod broker_downloads;
// Generic Storage - SQLite key-value storage
pub mod storage;
@@ -168,3 +174,6 @@ pub mod ma_analytics;
// Strategy Engine - 400+ algorithmic trading strategies
pub mod strategies;
+
+// Algo Trading - Visual condition-based strategy builder, deployment, scanner
+pub mod algo_trading;
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/symbol_master.rs b/fincept-terminal-desktop/src-tauri/src/commands/symbol_master.rs
new file mode 100644
index 000000000..7cb832c98
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/symbol_master.rs
@@ -0,0 +1,407 @@
+//! Unified Symbol Master Commands
+//!
+//! Tauri commands for managing the unified symbol database across all brokers.
+//! Provides search, status tracking, and download functionality.
+
+use crate::database::symbol_master::{
+ self, DownloadStatus, MasterContractStatus, SymbolSearchResult, CACHE_TTL_SECONDS,
+};
+use serde::{Deserialize, Serialize};
+use tauri::command;
+
+// ============================================================================
+// RESPONSE TYPES
+// ============================================================================
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct SymbolSearchResponse {
+ pub success: bool,
+ pub symbols: Vec<SymbolSearchResult>,
+ pub total: usize,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct StatusResponse {
+ pub success: bool,
+ pub status: Option<MasterContractStatus>,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct BrokerStatusesResponse {
+ pub success: bool,
+ pub statuses: Vec<MasterContractStatus>,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct CacheValidityResponse {
+ pub success: bool,
+ pub is_valid: bool,
+ pub age_seconds: Option<i64>,
+ pub ttl_seconds: i64,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ExchangesResponse {
+ pub success: bool,
+ pub exchanges: Vec<String>,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ExpiriesResponse {
+ pub success: bool,
+ pub expiries: Vec<String>,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct UnderlyingsResponse {
+ pub success: bool,
+ pub underlyings: Vec<String>,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct SymbolCountResponse {
+ pub success: bool,
+ pub count: i64,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct TokenLookupResponse {
+ pub success: bool,
+ pub token: Option<String>,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct SymbolLookupResponse {
+ pub success: bool,
+ pub symbol: Option<SymbolSearchResult>,
+ pub error: Option<String>,
+}
+
+// ============================================================================
+// SEARCH COMMANDS
+// ============================================================================
+
+/// Search symbols for a broker
+#[command]
+pub fn symbol_master_search(
+ broker_id: String,
+ query: String,
+ exchange: Option<String>,
+ instrument_type: Option<String>,
+ limit: Option<i32>,
+) -> SymbolSearchResponse {
+ let limit = limit.unwrap_or(50);
+
+ match symbol_master::search_symbols(
+ &broker_id,
+ &query,
+ exchange.as_deref(),
+ instrument_type.as_deref(),
+ limit,
+ ) {
+ Ok(symbols) => {
+ let total = symbols.len();
+ SymbolSearchResponse {
+ success: true,
+ symbols,
+ total,
+ error: None,
+ }
+ }
+ Err(e) => SymbolSearchResponse {
+ success: false,
+ symbols: vec![],
+ total: 0,
+ error: Some(format!("Search failed: {}", e)),
+ },
+ }
+}
+
+/// Get symbol by exact match
+#[command]
+pub fn symbol_master_get_symbol(
+ broker_id: String,
+ symbol: String,
+ exchange: String,
+) -> SymbolLookupResponse {
+ match symbol_master::get_symbol(&broker_id, &symbol, &exchange) {
+ Ok(symbol) => SymbolLookupResponse {
+ success: true,
+ symbol,
+ error: None,
+ },
+ Err(e) => SymbolLookupResponse {
+ success: false,
+ symbol: None,
+ error: Some(format!("Lookup failed: {}", e)),
+ },
+ }
+}
+
+/// Get symbol by token
+#[command]
+pub fn symbol_master_get_by_token(broker_id: String, token: String) -> SymbolLookupResponse {
+ match symbol_master::get_symbol_by_token(&broker_id, &token) {
+ Ok(symbol) => SymbolLookupResponse {
+ success: true,
+ symbol,
+ error: None,
+ },
+ Err(e) => SymbolLookupResponse {
+ success: false,
+ symbol: None,
+ error: Some(format!("Lookup failed: {}", e)),
+ },
+ }
+}
+
+/// Get token for a symbol (for WebSocket subscriptions)
+#[command]
+pub fn symbol_master_get_token(
+ broker_id: String,
+ symbol: String,
+ exchange: String,
+) -> TokenLookupResponse {
+ match symbol_master::get_token_by_symbol(&broker_id, &symbol, &exchange) {
+ Ok(token) => TokenLookupResponse {
+ success: true,
+ token,
+ error: None,
+ },
+ Err(e) => TokenLookupResponse {
+ success: false,
+ token: None,
+ error: Some(format!("Lookup failed: {}", e)),
+ },
+ }
+}
+
+// ============================================================================
+// STATUS COMMANDS
+// ============================================================================
+
+/// Get master contract status for a broker
+#[command]
+pub fn symbol_master_get_status(broker_id: String) -> StatusResponse {
+ match symbol_master::get_status(&broker_id) {
+ Ok(status) => StatusResponse {
+ success: true,
+ status: Some(status),
+ error: None,
+ },
+ Err(e) => StatusResponse {
+ success: false,
+ status: None,
+ error: Some(format!("Failed to get status: {}", e)),
+ },
+ }
+}
+
+/// Check if master contracts are ready (cached and valid)
+#[command]
+pub fn symbol_master_is_ready(broker_id: String) -> CacheValidityResponse {
+ let is_valid = symbol_master::is_cache_valid(&broker_id, CACHE_TTL_SECONDS).unwrap_or(false);
+ let age_seconds = symbol_master::get_cache_age(&broker_id).unwrap_or(None);
+
+ CacheValidityResponse {
+ success: true,
+ is_valid,
+ age_seconds,
+ ttl_seconds: CACHE_TTL_SECONDS,
+ error: None,
+ }
+}
+
+/// Initialize broker status (call on login)
+#[command]
+pub fn symbol_master_init_broker(broker_id: String) -> StatusResponse {
+ // First check if we have a valid cache
+ let is_valid = symbol_master::is_cache_valid(&broker_id, CACHE_TTL_SECONDS).unwrap_or(false);
+
+ if is_valid {
+ // Cache is still valid, don't reinitialize
+ match symbol_master::get_status(&broker_id) {
+ Ok(status) => {
+ return StatusResponse {
+ success: true,
+ status: Some(status),
+ error: None,
+ }
+ }
+ Err(_) => {}
+ }
+ }
+
+ // Initialize or reinitialize
+ match symbol_master::init_broker_status(&broker_id) {
+ Ok(_) => match symbol_master::get_status(&broker_id) {
+ Ok(status) => StatusResponse {
+ success: true,
+ status: Some(status),
+ error: None,
+ },
+ Err(e) => StatusResponse {
+ success: false,
+ status: None,
+ error: Some(format!("Failed to get status after init: {}", e)),
+ },
+ },
+ Err(e) => StatusResponse {
+ success: false,
+ status: None,
+ error: Some(format!("Failed to initialize broker: {}", e)),
+ },
+ }
+}
+
+/// Update master contract status (used by download commands)
+#[command]
+pub fn symbol_master_update_status(
+ broker_id: String,
+ status: String,
+ message: String,
+ total_symbols: Option<i64>,
+) -> StatusResponse {
+ let status_enum = DownloadStatus::from(status.as_str());
+
+ match symbol_master::update_status(&broker_id, status_enum, &message, total_symbols) {
+ Ok(_) => match symbol_master::get_status(&broker_id) {
+ Ok(status) => StatusResponse {
+ success: true,
+ status: Some(status),
+ error: None,
+ },
+ Err(e) => StatusResponse {
+ success: false,
+ status: None,
+ error: Some(format!("Failed to get updated status: {}", e)),
+ },
+ },
+ Err(e) => StatusResponse {
+ success: false,
+ status: None,
+ error: Some(format!("Failed to update status: {}", e)),
+ },
+ }
+}
+
+// ============================================================================
+// METADATA COMMANDS
+// ============================================================================
+
+/// Get symbol count for a broker
+#[command]
+pub fn symbol_master_get_count(broker_id: String) -> SymbolCountResponse {
+ match symbol_master::get_symbol_count(&broker_id) {
+ Ok(count) => SymbolCountResponse {
+ success: true,
+ count,
+ error: None,
+ },
+ Err(e) => SymbolCountResponse {
+ success: false,
+ count: 0,
+ error: Some(format!("Failed to get count: {}", e)),
+ },
+ }
+}
+
+/// Get distinct exchanges for a broker
+#[command]
+pub fn symbol_master_get_exchanges(broker_id: String) -> ExchangesResponse {
+ match symbol_master::get_exchanges(&broker_id) {
+ Ok(exchanges) => ExchangesResponse {
+ success: true,
+ exchanges,
+ error: None,
+ },
+ Err(e) => ExchangesResponse {
+ success: false,
+ exchanges: vec![],
+ error: Some(format!("Failed to get exchanges: {}", e)),
+ },
+ }
+}
+
+/// Get distinct expiries for FNO symbols
+#[command]
+pub fn symbol_master_get_expiries(
+ broker_id: String,
+ exchange: Option<String>,
+ underlying: Option<String>,
+) -> ExpiriesResponse {
+ match symbol_master::get_expiries(&broker_id, exchange.as_deref(), underlying.as_deref()) {
+ Ok(expiries) => ExpiriesResponse {
+ success: true,
+ expiries,
+ error: None,
+ },
+ Err(e) => ExpiriesResponse {
+ success: false,
+ expiries: vec![],
+ error: Some(format!("Failed to get expiries: {}", e)),
+ },
+ }
+}
+
+/// Get distinct underlyings (for option chain)
+#[command]
+pub fn symbol_master_get_underlyings(
+ broker_id: String,
+ exchange: Option<String>,
+) -> UnderlyingsResponse {
+ match symbol_master::get_underlyings(&broker_id, exchange.as_deref()) {
+ Ok(underlyings) => UnderlyingsResponse {
+ success: true,
+ underlyings,
+ error: None,
+ },
+ Err(e) => UnderlyingsResponse {
+ success: false,
+ underlyings: vec![],
+ error: Some(format!("Failed to get underlyings: {}", e)),
+ },
+ }
+}
+
+// ============================================================================
+// UTILITY COMMANDS
+// ============================================================================
+
+/// Normalize index symbol to unified format
+#[command]
+pub fn symbol_master_normalize_index(symbol: String) -> String {
+ symbol_master::normalize_index_symbol(&symbol)
+}
+
+/// Format expiry date to DD-MMM-YY format
+#[command]
+pub fn symbol_master_format_expiry(expiry: String) -> String {
+ symbol_master::format_expiry(&expiry)
+}
+
+/// Build unified futures symbol
+#[command]
+pub fn symbol_master_build_futures_symbol(underlying: String, expiry: String) -> String {
+ symbol_master::build_futures_symbol(&underlying, &expiry)
+}
+
+/// Build unified options symbol
+#[command]
+pub fn symbol_master_build_options_symbol(
+ underlying: String,
+ expiry: String,
+ strike: f64,
+ option_type: String,
+) -> String {
+ symbol_master::build_options_symbol(&underlying, &expiry, strike, &option_type)
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs b/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs
index c3a57e65b..cb8eb4a93 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs
@@ -240,6 +240,9 @@ async fn place_live_order(
"zerodha" => {
place_zerodha_order(order).await
}
+ "fyers" => {
+ place_fyers_order(order).await
+ }
_ => Err(format!("Live trading not implemented for {}", session.broker))
}
}
@@ -319,6 +322,82 @@ async fn place_zerodha_order(order: &UnifiedOrder) -> Result<UnifiedOrderRespons
})
}
+/// Place order via Fyers API
+async fn place_fyers_order(order: &UnifiedOrder) -> Result<UnifiedOrderResponse, String> {
+ use crate::commands::brokers;
+
+ // Get stored credentials
+ let creds = brokers::get_indian_broker_credentials("fyers".to_string())
+ .await
+ .map_err(|e| e.to_string())?;
+
+ if !creds.success || creds.data.is_none() {
+ return Err("Fyers credentials not found. Please authenticate first.".to_string());
+ }
+
+ 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")?
+ .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.")?
+ .to_string();
+
+ // Map order type: UnifiedOrder uses "market"/"limit"/"stop"/"stop_limit"
+ // Fyers uses: 1=Limit, 2=Market, 3=Stop Loss Limit, 4=Stop Loss Market
+ let fyers_order_type: i32 = match order.order_type.as_str() {
+ "market" => 2,
+ "limit" => 1,
+ "stop" => 4, // Stop Loss Market
+ "stop_limit" => 3, // Stop Loss Limit
+ _ => 2, // Default to market
+ };
+
+ // Map side: UnifiedOrder uses "buy"/"sell", Fyers uses 1=Buy, -1=Sell
+ let fyers_side: i32 = match order.side.to_lowercase().as_str() {
+ "buy" => 1,
+ "sell" => -1,
+ _ => 1,
+ };
+
+ // Map product type: default to INTRADAY for algo trading
+ let product_type = order.product_type.as_deref().unwrap_or("INTRADAY").to_string();
+
+ // Build Fyers symbol format: "NSE:SBIN-EQ" or use as-is if already formatted
+ let fyers_symbol = if order.symbol.contains(':') {
+ order.symbol.clone()
+ } else {
+ format!("{}:{}-EQ", order.exchange, order.symbol)
+ };
+
+ // Place order via Fyers API
+ let response = brokers::fyers_place_order(
+ api_key,
+ access_token,
+ fyers_symbol,
+ order.quantity as i32,
+ fyers_order_type,
+ fyers_side,
+ product_type,
+ order.price, // limit_price
+ order.stop_price, // stop_price
+ None, // disclosed_qty
+ Some("DAY".to_string()), // validity
+ None, // offline_order
+ None, // stop_loss
+ None, // take_profit
+ ).await.map_err(|e| e.to_string())?;
+
+ Ok(UnifiedOrderResponse {
+ success: response.success,
+ order_id: response.order_id,
+ message: response.error,
+ mode: TradingMode::Live,
+ })
+}
+
// ============================================================================
// Price Updates & Order Fills
// ============================================================================
@@ -497,6 +576,74 @@ async fn get_live_positions(session: &TradingSession) -> Result<Vec<UnifiedPosit
Ok(positions)
}
+ "fyers" => {
+ use crate::commands::brokers;
+
+ let creds = brokers::get_indian_broker_credentials("fyers".to_string())
+ .await
+ .map_err(|e| e.to_string())?;
+
+ if !creds.success || creds.data.is_none() {
+ return Err("Fyers credentials not found".to_string());
+ }
+
+ let cred_data = creds.data.unwrap();
+ let api_key = cred_data.get("apiKey")
+ .and_then(|v| v.as_str())
+ .ok_or("API key not found")?
+ .to_string();
+ let access_token = cred_data.get("accessToken")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let response = brokers::fyers_get_positions(
+ api_key,
+ access_token,
+ ).await.map_err(|e| e.to_string())?;
+
+ if !response.success {
+ return Err(response.error.unwrap_or("Failed to get Fyers positions".to_string()));
+ }
+
+ // Map Fyers positions to unified format
+ // Fyers netPositions array has: symbol, qty, avgPrice, ltp, pl, unrealizedProfit, etc.
+ let positions: Vec<UnifiedPosition> = response.data.map(|data| {
+ if let Some(positions_arr) = data.as_array() {
+ positions_arr.iter().filter_map(|p| {
+ let qty = p.get("netQty").or_else(|| p.get("qty"))
+ .and_then(|v| v.as_f64()).unwrap_or(0.0);
+ if qty == 0.0 { return None; }
+ let side = if qty > 0.0 { "long" } else { "short" };
+
+ // Fyers symbol format: "NSE:SBIN-EQ" -> extract parts
+ let full_symbol = p.get("symbol").and_then(|v| v.as_str()).unwrap_or("");
+ let parts: Vec<&str> = full_symbol.splitn(2, ':').collect();
+ let exchange = parts.first().unwrap_or(&"NSE").to_string();
+ let symbol = parts.get(1).unwrap_or(&full_symbol).to_string();
+
+ Some(UnifiedPosition {
+ symbol,
+ exchange,
+ side: side.to_string(),
+ quantity: qty.abs(),
+ entry_price: p.get("avgPrice").or_else(|| p.get("buyAvg"))
+ .and_then(|v| v.as_f64()).unwrap_or(0.0),
+ current_price: p.get("ltp").and_then(|v| v.as_f64()).unwrap_or(0.0),
+ unrealized_pnl: p.get("unrealizedProfit").or_else(|| p.get("pl"))
+ .and_then(|v| v.as_f64()).unwrap_or(0.0),
+ realized_pnl: p.get("realizedProfit")
+ .and_then(|v| v.as_f64()).unwrap_or(0.0),
+ mode: TradingMode::Live,
+ })
+ }).collect()
+ } else {
+ Vec::new()
+ }
+ }).unwrap_or_default();
+
+ Ok(positions)
+ }
_ => Err(format!("Not implemented for {}", session.broker))
}
}
diff --git a/fincept-terminal-desktop/src-tauri/src/database/master_contract.rs b/fincept-terminal-desktop/src-tauri/src/database/master_contract.rs
deleted file mode 100644
index a82ac9759..000000000
--- a/fincept-terminal-desktop/src-tauri/src/database/master_contract.rs
+++ /dev/null
@@ -1,431 +0,0 @@
-// Master Contract Database Operations
-// Stores broker symbol data for fast lookup and offline access
-
-use crate::database::pool::get_db;
-use anyhow::{Context, Result};
-use rusqlite::{params, OptionalExtension};
-use serde::{Deserialize, Serialize};
-use std::time::{SystemTime, UNIX_EPOCH};
-
-// ============================================================================
-// Data Structures
-// ============================================================================
-
-/// Symbol record for database storage
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Symbol {
- pub id: Option<i64>,
- pub broker_id: String,
- pub symbol: String,
- pub br_symbol: String,
- pub name: Option<String>,
- pub exchange: String,
- pub br_exchange: Option<String>,
- pub token: String,
- pub expiry: Option<String>,
- pub strike: Option<f64>,
- pub lot_size: Option<i32>,
- pub instrument_type: Option<String>,
- pub tick_size: Option<f64>,
- pub segment: Option<String>,
-}
-
-/// Master contract cache metadata
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct MasterContractCache {
- pub broker_id: String,
- pub symbols_data: String,
- pub symbol_count: i64,
- pub last_updated: i64,
- pub created_at: i64,
-}
-
-/// Search result with relevance score
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct SearchResult {
- pub symbol: String,
- pub br_symbol: String,
- pub name: Option<String>,
- pub exchange: String,
- pub token: String,
- pub expiry: Option<String>,
- pub strike: Option<f64>,
- pub lot_size: Option<i32>,
- pub instrument_type: Option<String>,
- pub tick_size: Option<f64>,
-}
-
-// ============================================================================
-// Symbol Operations (New searchable table)
-// ============================================================================
-
-/// Delete all symbols for a broker
-pub fn delete_symbols_for_broker(broker_id: &str) -> Result<i64> {
- let db = get_db()?;
- let deleted = db.execute(
- "DELETE FROM symbols WHERE broker_id = ?",
- params![broker_id],
- ).context("Failed to delete symbols")?;
-
- Ok(deleted as i64)
-}
-
-/// Bulk insert symbols using a transaction for performance
-pub fn bulk_insert_symbols(symbols: &[Symbol]) -> Result<i64> {
- if symbols.is_empty() {
- return Ok(0);
- }
-
- let mut db = get_db()?;
- let now = SystemTime::now()
- .duration_since(UNIX_EPOCH)?
- .as_secs() as i64;
-
- let tx = db.transaction()?;
-
- {
- let mut stmt = tx.prepare_cached(
- "INSERT INTO symbols (broker_id, symbol, br_symbol, name, exchange, br_exchange, token, expiry, strike, lot_size, instrument_type, tick_size, segment, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
- )?;
-
- for symbol in symbols {
- stmt.execute(params![
- symbol.broker_id,
- symbol.symbol,
- symbol.br_symbol,
- symbol.name,
- symbol.exchange,
- symbol.br_exchange,
- symbol.token,
- symbol.expiry,
- symbol.strike,
- symbol.lot_size,
- symbol.instrument_type,
- symbol.tick_size,
- symbol.segment,
- now,
- ])?;
- }
- }
-
- tx.commit()?;
-
- Ok(symbols.len() as i64)
-}
-
-/// Search symbols by query string
-pub fn search_symbols(
- broker_id: &str,
- query: &str,
- exchange: Option<&str>,
- instrument_type: Option<&str>,
- limit: i32,
-) -> Result<Vec<SearchResult>> {
- let db = get_db()?;
-
- let search_pattern = format!("%{}%", query.to_uppercase());
-
- // Build dynamic query based on filters
- let mut sql = String::from(
- "SELECT symbol, br_symbol, name, exchange, token, expiry, strike, lot_size, instrument_type, tick_size
- FROM symbols
- WHERE broker_id = ? AND (
- UPPER(symbol) LIKE ? OR
- UPPER(name) LIKE ? OR
- UPPER(br_symbol) LIKE ? OR
- token LIKE ?
- )"
- );
-
- let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![
- Box::new(broker_id.to_string()),
- Box::new(search_pattern.clone()),
- Box::new(search_pattern.clone()),
- Box::new(search_pattern.clone()),
- Box::new(search_pattern.clone()),
- ];
-
- if let Some(exch) = exchange {
- sql.push_str(" AND exchange = ?");
- params_vec.push(Box::new(exch.to_string()));
- }
-
- if let Some(inst_type) = instrument_type {
- sql.push_str(" AND instrument_type = ?");
- params_vec.push(Box::new(inst_type.to_string()));
- }
-
- // Order by relevance: exact matches first, then starts with, then contains
- sql.push_str(&format!(
- " ORDER BY
- CASE
- WHEN UPPER(symbol) = UPPER(?) THEN 0
- WHEN UPPER(symbol) LIKE UPPER(?) || '%' THEN 1
- WHEN UPPER(name) = UPPER(?) THEN 2
- WHEN UPPER(name) LIKE UPPER(?) || '%' THEN 3
- ELSE 4
- END,
- symbol
- LIMIT ?"
- ));
-
- params_vec.push(Box::new(query.to_uppercase()));
- params_vec.push(Box::new(query.to_uppercase()));
- params_vec.push(Box::new(query.to_uppercase()));
- params_vec.push(Box::new(query.to_uppercase()));
- params_vec.push(Box::new(limit));
-
- let mut stmt = db.prepare(&sql)?;
-
- let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();
-
- let results = stmt.query_map(params_refs.as_slice(), |row| {
- Ok(SearchResult {
- symbol: row.get(0)?,
- br_symbol: row.get(1)?,
- name: row.get(2)?,
- exchange: row.get(3)?,
- token: row.get(4)?,
- expiry: row.get(5)?,
- strike: row.get(6)?,
- lot_size: row.get(7)?,
- instrument_type: row.get(8)?,
- tick_size: row.get(9)?,
- })
- })?;
-
- let mut symbols = Vec::new();
- for result in results {
- symbols.push(result?);
- }
-
- Ok(symbols)
-}
-
-/// Get symbol by exact match
-pub fn get_symbol(broker_id: &str, symbol: &str, exchange: &str) -> Result<Option<SearchResult>> {
- let db = get_db()?;
-
- let result = db.query_row(
- "SELECT symbol, br_symbol, name, exchange, token, expiry, strike, lot_size, instrument_type, tick_size
- FROM symbols
- WHERE broker_id = ? AND UPPER(symbol) = UPPER(?) AND exchange = ?",
- params![broker_id, symbol, exchange],
- |row| {
- Ok(SearchResult {
- symbol: row.get(0)?,
- br_symbol: row.get(1)?,
- name: row.get(2)?,
- exchange: row.get(3)?,
- token: row.get(4)?,
- expiry: row.get(5)?,
- strike: row.get(6)?,
- lot_size: row.get(7)?,
- instrument_type: row.get(8)?,
- tick_size: row.get(9)?,
- })
- },
- ).optional()?;
-
- Ok(result)
-}
-
-/// Get symbol by token
-pub fn get_symbol_by_token(broker_id: &str, token: &str) -> Result<Option<SearchResult>> {
- let db = get_db()?;
-
- let result = db.query_row(
- "SELECT symbol, br_symbol, name, exchange, token, expiry, strike, lot_size, instrument_type, tick_size
- FROM symbols
- WHERE broker_id = ? AND token = ?",
- params![broker_id, token],
- |row| {
- Ok(SearchResult {
- symbol: row.get(0)?,
- br_symbol: row.get(1)?,
- name: row.get(2)?,
- exchange: row.get(3)?,
- token: row.get(4)?,
- expiry: row.get(5)?,
- strike: row.get(6)?,
- lot_size: row.get(7)?,
- instrument_type: row.get(8)?,
- tick_size: row.get(9)?,
- })
- },
- ).optional()?;
-
- Ok(result)
-}
-
-/// Get symbol count for a broker
-pub fn get_symbol_count(broker_id: &str) -> Result<i64> {
- let db = get_db()?;
-
- let count: i64 = db.query_row(
- "SELECT COUNT(*) FROM symbols WHERE broker_id = ?",
- params![broker_id],
- |row| row.get(0),
- )?;
-
- Ok(count)
-}
-
-/// Get distinct exchanges for a broker
-pub fn get_exchanges(broker_id: &str) -> Result<Vec<String>> {
- let db = get_db()?;
-
- let mut stmt = db.prepare(
- "SELECT DISTINCT exchange FROM symbols WHERE broker_id = ? ORDER BY exchange"
- )?;
-
- let results = stmt.query_map(params![broker_id], |row| row.get(0))?;
-
- let mut exchanges = Vec::new();
- for result in results {
- exchanges.push(result?);
- }
-
- Ok(exchanges)
-}
-
-/// Get distinct expiries for a broker/exchange/underlying
-pub fn get_expiries(
- broker_id: &str,
- exchange: Option<&str>,
- underlying: Option<&str>,
-) -> Result<Vec<String>> {
- let db = get_db()?;
-
- let mut sql = String::from(
- "SELECT DISTINCT expiry FROM symbols WHERE broker_id = ? AND expiry IS NOT NULL AND expiry != ''"
- );
-
- let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(broker_id.to_string())];
-
- if let Some(exch) = exchange {
- sql.push_str(" AND exchange = ?");
- params_vec.push(Box::new(exch.to_string()));
- }
-
- if let Some(name) = underlying {
- sql.push_str(" AND name = ?");
- params_vec.push(Box::new(name.to_string()));
- }
-
- sql.push_str(" ORDER BY expiry");
-
- let mut stmt = db.prepare(&sql)?;
- let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();
-
- let results = stmt.query_map(params_refs.as_slice(), |row| row.get(0))?;
-
- let mut expiries = Vec::new();
- for result in results {
- expiries.push(result?);
- }
-
- Ok(expiries)
-}
-
-// ============================================================================
-// Cache Metadata Operations (Existing)
-// ============================================================================
-
-/// Save master contract cache metadata
-pub fn save_master_contract(
- broker_id: &str,
- symbols_data: &str,
- symbol_count: i64,
-) -> Result<()> {
- let db = get_db()?;
- let now = SystemTime::now()
- .duration_since(UNIX_EPOCH)?
- .as_secs() as i64;
-
- db.execute(
- "INSERT OR REPLACE INTO master_contract_cache
- (broker_id, symbols_data, symbol_count, last_updated, created_at)
- VALUES (?, ?, ?, ?, COALESCE((SELECT created_at FROM master_contract_cache WHERE broker_id = ?), ?))",
- params![broker_id, symbols_data, symbol_count, now, broker_id, now],
- )
- .context("Failed to save master contract")?;
-
- Ok(())
-}
-
-/// Get master contract cache metadata
-pub fn get_master_contract(broker_id: &str) -> Result<Option<MasterContractCache>> {
- let db = get_db()?;
-
- let mut stmt = db
- .prepare("SELECT broker_id, symbols_data, symbol_count, last_updated, created_at FROM master_contract_cache WHERE broker_id = ?")?;
-
- let result = stmt
- .query_row(params![broker_id], |row: &rusqlite::Row| {
- Ok(MasterContractCache {
- broker_id: row.get(0)?,
- symbols_data: row.get(1)?,
- symbol_count: row.get(2)?,
- last_updated: row.get(3)?,
- created_at: row.get(4)?,
- })
- })
- .optional()
- .context("Failed to get master contract")?;
-
- Ok(result)
-}
-
-/// Delete master contract cache
-pub fn delete_master_contract(broker_id: &str) -> Result<()> {
- let db = get_db()?;
-
- db.execute(
- "DELETE FROM master_contract_cache WHERE broker_id = ?",
- params![broker_id],
- )
- .context("Failed to delete master contract")?;
-
- Ok(())
-}
-
-/// Check if cache is valid (not expired)
-pub fn is_cache_valid(broker_id: &str, ttl_seconds: i64) -> Result<bool> {
- let db = get_db()?;
- let now = SystemTime::now()
- .duration_since(UNIX_EPOCH)?
- .as_secs() as i64;
-
- let mut stmt = db.prepare(
- "SELECT last_updated FROM master_contract_cache WHERE broker_id = ?",
- )?;
-
- let last_updated: Option<i64> = stmt
- .query_row(params![broker_id], |row: &rusqlite::Row| row.get(0))
- .optional()?;
-
- match last_updated {
- Some(timestamp) => Ok((now - timestamp) < ttl_seconds),
- None => Ok(false),
- }
-}
-
-/// Get cache age in seconds
-pub fn get_cache_age(broker_id: &str) -> Result<Option<i64>> {
- let db = get_db()?;
- let now = SystemTime::now()
- .duration_since(UNIX_EPOCH)?
- .as_secs() as i64;
-
- let mut stmt = db.prepare(
- "SELECT last_updated FROM master_contract_cache WHERE broker_id = ?",
- )?;
-
- let last_updated: Option<i64> = stmt
- .query_row(params![broker_id], |row: &rusqlite::Row| row.get(0))
- .optional()?;
-
- Ok(last_updated.map(|ts| now - ts))
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/database/mod.rs b/fincept-terminal-desktop/src-tauri/src/database/mod.rs
index 813ddcee4..16e291dfe 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/mod.rs
@@ -1,5 +1,5 @@
// Database Module - High-performance SQLite with connection pooling
-// Structure: 8 files for optimal organization and performance
+// Structure: Modular organization for optimal performance
pub mod pool;
pub mod schema;
@@ -9,8 +9,11 @@ pub mod queries;
pub mod cache;
pub mod notes_excel;
pub mod broker_credentials;
-pub mod master_contract;
+// pub mod master_contract; // REMOVED - use symbol_master instead
pub mod storage;
+pub mod symbol_master; // Unified symbol database (preferred)
+
+// Legacy broker-specific symbol tables (deprecated - use symbol_master instead)
pub mod fyers_symbols;
pub mod shoonya_symbols;
@@ -34,12 +37,19 @@ pub async fn initialize() -> Result<()> {
} else {
}
- // Initialize Fyers symbols table
+ // Initialize unified symbol master status table
+ if let Err(_e) = symbol_master::init_master_contract_status_table() {
+ eprintln!("[database] Failed to initialize master_contract_status table");
+ } else {
+ eprintln!("[database] Master contract status table initialized");
+ }
+
+ // Legacy: Initialize Fyers symbols table (deprecated)
if let Err(_e) = fyers_symbols::init_fyers_symbols_table() {
} else {
}
- // Initialize Shoonya symbols table
+ // Legacy: Initialize Shoonya symbols table (deprecated)
if let Err(_e) = shoonya_symbols::init_shoonya_symbols_table() {
} else {
}
diff --git a/fincept-terminal-desktop/src-tauri/src/database/schema.rs b/fincept-terminal-desktop/src-tauri/src/database/schema.rs
index 1693a40cb..631383aae 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/schema.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/schema.rs
@@ -620,7 +620,7 @@ pub fn create_schema(conn: &Connection) -> Result<()> {
CREATE INDEX IF NOT EXISTS idx_broker_credentials_broker_id ON broker_credentials(broker_id);
- -- Master Contract Cache table (Broker symbol data metadata)
+ -- Master Contract Cache table (DEPRECATED - use master_contract_status instead)
CREATE TABLE IF NOT EXISTS master_contract_cache (
broker_id TEXT PRIMARY KEY,
symbols_data TEXT NOT NULL,
@@ -629,6 +629,16 @@ pub fn create_schema(conn: &Connection) -> Result<()> {
created_at INTEGER NOT NULL
);
+ -- Master Contract Status table (New unified status tracking)
+ CREATE TABLE IF NOT EXISTS master_contract_status (
+ broker_id TEXT PRIMARY KEY,
+ status TEXT NOT NULL DEFAULT 'pending',
+ message TEXT,
+ last_updated INTEGER NOT NULL,
+ total_symbols INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL
+ );
+
-- Symbols table (Searchable instrument database)
CREATE TABLE IF NOT EXISTS symbols (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -881,7 +891,122 @@ pub fn create_schema(conn: &Connection) -> Result<()> {
change_percent REAL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (symbol)
- )
+ );
+
+ -- ============================================================================
+ -- ALGO TRADING SYSTEM TABLES
+ -- ============================================================================
+
+ -- User-created visual algo strategies (condition-based)
+ CREATE TABLE IF NOT EXISTS algo_strategies (
+ id TEXT PRIMARY KEY NOT NULL,
+ name TEXT NOT NULL,
+ description TEXT DEFAULT '',
+ entry_conditions TEXT NOT NULL DEFAULT '[]',
+ exit_conditions TEXT NOT NULL DEFAULT '[]',
+ entry_logic TEXT NOT NULL DEFAULT 'AND',
+ exit_logic TEXT NOT NULL DEFAULT 'AND',
+ stop_loss REAL,
+ take_profit REAL,
+ trailing_stop REAL,
+ trailing_stop_type TEXT DEFAULT 'percent',
+ timeframe TEXT NOT NULL DEFAULT '5m',
+ symbols TEXT NOT NULL DEFAULT '[]',
+ is_active INTEGER NOT NULL DEFAULT 1,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ );
+
+ -- Aggregated OHLCV candles built from ticks
+ CREATE TABLE IF NOT EXISTS candle_cache (
+ symbol TEXT NOT NULL,
+ provider TEXT NOT NULL DEFAULT '',
+ timeframe TEXT NOT NULL DEFAULT '5m',
+ open_time INTEGER NOT NULL,
+ o REAL NOT NULL,
+ h REAL NOT NULL,
+ l REAL NOT NULL,
+ c REAL NOT NULL,
+ volume REAL NOT NULL DEFAULT 0,
+ is_closed INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (symbol, provider, timeframe, open_time)
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_candle_cache_lookup
+ ON candle_cache(symbol, timeframe, open_time DESC);
+
+ -- Algo deployments (live/paper strategy runs)
+ CREATE TABLE IF NOT EXISTS algo_deployments (
+ id TEXT PRIMARY KEY NOT NULL,
+ strategy_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ provider TEXT NOT NULL DEFAULT '',
+ mode TEXT NOT NULL DEFAULT 'paper',
+ status TEXT NOT NULL DEFAULT 'pending',
+ timeframe TEXT NOT NULL DEFAULT '5m',
+ quantity REAL NOT NULL DEFAULT 1,
+ params TEXT DEFAULT '{}',
+ pid INTEGER,
+ error_message TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ stopped_at TEXT,
+ FOREIGN KEY (strategy_id) REFERENCES algo_strategies(id) ON DELETE CASCADE
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_algo_deployments_status ON algo_deployments(status);
+ CREATE INDEX IF NOT EXISTS idx_algo_deployments_strategy ON algo_deployments(strategy_id);
+
+ -- Trade log per deployment
+ CREATE TABLE IF NOT EXISTS algo_trades (
+ id TEXT PRIMARY KEY NOT NULL,
+ deployment_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ side TEXT NOT NULL,
+ quantity REAL NOT NULL,
+ price REAL NOT NULL,
+ pnl REAL DEFAULT 0,
+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP,
+ signal_reason TEXT DEFAULT '',
+ FOREIGN KEY (deployment_id) REFERENCES algo_deployments(id) ON DELETE CASCADE
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_algo_trades_deployment ON algo_trades(deployment_id);
+ CREATE INDEX IF NOT EXISTS idx_algo_trades_timestamp ON algo_trades(timestamp DESC);
+
+ -- Live metrics per deployment
+ CREATE TABLE IF NOT EXISTS algo_metrics (
+ deployment_id TEXT PRIMARY KEY NOT NULL,
+ total_pnl REAL NOT NULL DEFAULT 0,
+ unrealized_pnl REAL NOT NULL DEFAULT 0,
+ total_trades INTEGER NOT NULL DEFAULT 0,
+ win_rate REAL NOT NULL DEFAULT 0,
+ max_drawdown REAL NOT NULL DEFAULT 0,
+ current_position_qty REAL NOT NULL DEFAULT 0,
+ current_position_side TEXT DEFAULT '',
+ current_position_entry REAL DEFAULT 0,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (deployment_id) REFERENCES algo_deployments(id) ON DELETE CASCADE
+ );
+
+ -- Order signal queue (Python -> Rust for live execution)
+ CREATE TABLE IF NOT EXISTS algo_order_signals (
+ id TEXT PRIMARY KEY NOT NULL,
+ deployment_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ side TEXT NOT NULL,
+ quantity REAL NOT NULL,
+ order_type TEXT NOT NULL DEFAULT 'MARKET',
+ price REAL,
+ status TEXT NOT NULL DEFAULT 'pending',
+ result TEXT DEFAULT '',
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ executed_at TEXT,
+ FOREIGN KEY (deployment_id) REFERENCES algo_deployments(id) ON DELETE CASCADE
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_algo_order_signals_status ON algo_order_signals(status);
+ CREATE INDEX IF NOT EXISTS idx_algo_order_signals_deployment ON algo_order_signals(deployment_id)
",
)?;
diff --git a/fincept-terminal-desktop/src-tauri/src/database/symbol_master.rs b/fincept-terminal-desktop/src-tauri/src/database/symbol_master.rs
new file mode 100644
index 000000000..7b905656f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/database/symbol_master.rs
@@ -0,0 +1,756 @@
+//! Unified Symbol Master Database
+//!
+//! This module provides a unified symbol database that works across all brokers.
+//! It follows the OpenAlgo pattern with standardized symbol formats and unified storage.
+//!
+//! Key Features:
+//! - Single `symbols` table for all brokers (with broker_id column)
+//! - Standardized symbol format (e.g., NIFTY26DEC24FUT)
+//! - Status tracking for master contract downloads
+//! - TTL-based cache validation
+//! - Unified search across exchanges
+
+use crate::database::pool::get_db;
+use anyhow::{Context, Result};
+use rusqlite::{params, OptionalExtension};
+use serde::{Deserialize, Serialize};
+use std::time::{SystemTime, UNIX_EPOCH};
+
+// ============================================================================
+// CONSTANTS
+// ============================================================================
+
+/// Cache TTL in seconds (24 hours)
+pub const CACHE_TTL_SECONDS: i64 = 86400;
+
+/// Index symbol mappings (broker format -> unified format)
+pub const INDEX_SYMBOL_MAPPINGS: &[(&str, &str)] = &[
+ ("NIFTY 50", "NIFTY"),
+ ("Nifty 50", "NIFTY"),
+ ("NIFTY50", "NIFTY"),
+ ("NIFTY NEXT 50", "NIFTYNXT50"),
+ ("Nifty Next 50", "NIFTYNXT50"),
+ ("NIFTY FIN SERVICE", "FINNIFTY"),
+ ("Nifty Fin Service", "FINNIFTY"),
+ ("FINNIFTY", "FINNIFTY"),
+ ("NIFTY BANK", "BANKNIFTY"),
+ ("Nifty Bank", "BANKNIFTY"),
+ ("BANKNIFTY", "BANKNIFTY"),
+ ("NIFTY MID SELECT", "MIDCPNIFTY"),
+ ("NIFTY MIDCAP SELECT", "MIDCPNIFTY"),
+ ("MIDCPNIFTY", "MIDCPNIFTY"),
+ ("INDIA VIX", "INDIAVIX"),
+ ("India VIX", "INDIAVIX"),
+ ("SENSEX", "SENSEX"),
+ ("SENSEX50", "SENSEX50"),
+ ("SNSX50", "SENSEX50"),
+ ("BANKEX", "BANKEX"),
+];
+
+// ============================================================================
+// DATA STRUCTURES
+// ============================================================================
+
+/// Unified symbol record matching OpenAlgo's SymToken structure
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SymbolRecord {
+ pub id: Option<i64>,
+ /// Broker identifier (e.g., "fyers", "zerodha", "angel")
+ pub broker_id: String,
+ /// Unified symbol format (e.g., "RELIANCE", "NIFTY26DEC24FUT", "NIFTY26DEC2424000CE")
+ pub symbol: String,
+ /// Broker-specific symbol (e.g., "NSE:RELIANCE-EQ", "RELIANCE-EQ")
+ pub br_symbol: String,
+ /// Company/underlying name (e.g., "Reliance Industries Ltd", "NIFTY")
+ pub name: Option<String>,
+ /// Unified exchange (NSE, BSE, NFO, BFO, CDS, MCX, NSE_INDEX, BSE_INDEX)
+ pub exchange: String,
+ /// Broker-specific exchange code
+ pub br_exchange: Option<String>,
+ /// Broker token/instrument ID
+ pub token: String,
+ /// Expiry date in DD-MMM-YY format (e.g., "26-DEC-24")
+ pub expiry: Option<String>,
+ /// Strike price for options
+ pub strike: Option<f64>,
+ /// Lot size
+ pub lot_size: Option<i32>,
+ /// Instrument type (EQ, FUT, CE, PE, INDEX)
+ pub instrument_type: Option<String>,
+ /// Tick size
+ pub tick_size: Option<f64>,
+ /// Segment (CM, FO, CD, etc.)
+ pub segment: Option<String>,
+}
+
+/// Master contract download status
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub enum DownloadStatus {
+ Pending,
+ Downloading,
+ Success,
+ Error,
+}
+
+impl ToString for DownloadStatus {
+ fn to_string(&self) -> String {
+ match self {
+ DownloadStatus::Pending => "pending".to_string(),
+ DownloadStatus::Downloading => "downloading".to_string(),
+ DownloadStatus::Success => "success".to_string(),
+ DownloadStatus::Error => "error".to_string(),
+ }
+ }
+}
+
+impl From<&str> for DownloadStatus {
+ fn from(s: &str) -> Self {
+ match s.to_lowercase().as_str() {
+ "pending" => DownloadStatus::Pending,
+ "downloading" => DownloadStatus::Downloading,
+ "success" => DownloadStatus::Success,
+ "error" => DownloadStatus::Error,
+ _ => DownloadStatus::Pending,
+ }
+ }
+}
+
+/// Master contract status record
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MasterContractStatus {
+ pub broker_id: String,
+ pub status: String,
+ pub message: Option<String>,
+ pub last_updated: i64,
+ pub total_symbols: i64,
+ pub is_ready: bool,
+}
+
+/// Symbol search result
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SymbolSearchResult {
+ pub symbol: String,
+ pub br_symbol: String,
+ pub name: Option<String>,
+ pub exchange: String,
+ pub token: String,
+ pub expiry: Option<String>,
+ pub strike: Option<f64>,
+ pub lot_size: Option<i32>,
+ pub instrument_type: Option<String>,
+ pub tick_size: Option<f64>,
+ pub relevance_score: f64,
+}
+
+// ============================================================================
+// DATABASE INITIALIZATION
+// ============================================================================
+
+/// Initialize the master contract status table
+pub fn init_master_contract_status_table() -> Result<()> {
+ let db = get_db()?;
+
+ db.execute(
+ "CREATE TABLE IF NOT EXISTS master_contract_status (
+ broker_id TEXT PRIMARY KEY,
+ status TEXT NOT NULL DEFAULT 'pending',
+ message TEXT,
+ last_updated INTEGER NOT NULL,
+ total_symbols INTEGER NOT NULL DEFAULT 0,
+ is_ready INTEGER NOT NULL DEFAULT 0
+ )",
+ [],
+ )
+ .context("Failed to create master_contract_status table")?;
+
+ Ok(())
+}
+
+// ============================================================================
+// STATUS TRACKING
+// ============================================================================
+
+/// Initialize broker status when they login
+pub fn init_broker_status(broker_id: &str) -> Result<()> {
+ let db = get_db()?;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)?
+ .as_secs() as i64;
+
+ db.execute(
+ "INSERT OR REPLACE INTO master_contract_status
+ (broker_id, status, message, last_updated, total_symbols, is_ready)
+ VALUES (?, 'pending', 'Master contract download pending', ?, 0, 0)",
+ params![broker_id, now],
+ )
+ .context("Failed to initialize broker status")?;
+
+ Ok(())
+}
+
+/// Update download status for a broker
+pub fn update_status(
+ broker_id: &str,
+ status: DownloadStatus,
+ message: &str,
+ total_symbols: Option<i64>,
+) -> Result<()> {
+ let db = get_db()?;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)?
+ .as_secs() as i64;
+
+ let is_ready = status == DownloadStatus::Success;
+
+ db.execute(
+ "INSERT OR REPLACE INTO master_contract_status
+ (broker_id, status, message, last_updated, total_symbols, is_ready)
+ VALUES (?, ?, ?, ?, COALESCE(?, (SELECT total_symbols FROM master_contract_status WHERE broker_id = ?), 0), ?)",
+ params![
+ broker_id,
+ status.to_string(),
+ message,
+ now,
+ total_symbols,
+ broker_id,
+ is_ready as i32
+ ],
+ )
+ .context("Failed to update status")?;
+
+ Ok(())
+}
+
+/// Get current status for a broker
+pub fn get_status(broker_id: &str) -> Result<MasterContractStatus> {
+ let db = get_db()?;
+
+ let result = db
+ .query_row(
+ "SELECT broker_id, status, message, last_updated, total_symbols, is_ready
+ FROM master_contract_status WHERE broker_id = ?",
+ params![broker_id],
+ |row| {
+ Ok(MasterContractStatus {
+ broker_id: row.get(0)?,
+ status: row.get(1)?,
+ message: row.get(2)?,
+ last_updated: row.get(3)?,
+ total_symbols: row.get(4)?,
+ is_ready: row.get::<_, i32>(5)? == 1,
+ })
+ },
+ )
+ .optional()
+ .context("Failed to get status")?;
+
+ Ok(result.unwrap_or(MasterContractStatus {
+ broker_id: broker_id.to_string(),
+ status: "unknown".to_string(),
+ message: Some("No status available".to_string()),
+ last_updated: 0,
+ total_symbols: 0,
+ is_ready: false,
+ }))
+}
+
+/// Check if master contracts are ready for a broker
+pub fn is_ready(broker_id: &str) -> Result<bool> {
+ let db = get_db()?;
+
+ let is_ready: Option<i32> = db
+ .query_row(
+ "SELECT is_ready FROM master_contract_status WHERE broker_id = ?",
+ params![broker_id],
+ |row| row.get(0),
+ )
+ .optional()?;
+
+ Ok(is_ready.unwrap_or(0) == 1)
+}
+
+// ============================================================================
+// SYMBOL OPERATIONS
+// ============================================================================
+
+/// Delete all symbols for a broker
+pub fn delete_symbols_for_broker(broker_id: &str) -> Result<i64> {
+ let db = get_db()?;
+ let deleted = db
+ .execute("DELETE FROM symbols WHERE broker_id = ?", params![broker_id])
+ .context("Failed to delete symbols")?;
+
+ Ok(deleted as i64)
+}
+
+/// Bulk insert symbols using a transaction for performance
+pub fn bulk_insert_symbols(symbols: &[SymbolRecord]) -> Result<i64> {
+ if symbols.is_empty() {
+ return Ok(0);
+ }
+
+ let mut db = get_db()?;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)?
+ .as_secs() as i64;
+
+ let tx = db.transaction()?;
+
+ {
+ let mut stmt = tx.prepare_cached(
+ "INSERT INTO symbols (broker_id, symbol, br_symbol, name, exchange, br_exchange, token, expiry, strike, lot_size, instrument_type, tick_size, segment, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
+ )?;
+
+ for symbol in symbols {
+ stmt.execute(params![
+ symbol.broker_id,
+ symbol.symbol,
+ symbol.br_symbol,
+ symbol.name,
+ symbol.exchange,
+ symbol.br_exchange,
+ symbol.token,
+ symbol.expiry,
+ symbol.strike,
+ symbol.lot_size,
+ symbol.instrument_type,
+ symbol.tick_size,
+ symbol.segment,
+ now,
+ ])?;
+ }
+ }
+
+ tx.commit()?;
+
+ Ok(symbols.len() as i64)
+}
+
+/// Search symbols by query string with relevance scoring
+pub fn search_symbols(
+ broker_id: &str,
+ query: &str,
+ exchange: Option<&str>,
+ instrument_type: Option<&str>,
+ limit: i32,
+) -> Result<Vec<SymbolSearchResult>> {
+ let db = get_db()?;
+
+ let search_pattern = format!("%{}%", query.to_uppercase());
+ let query_upper = query.to_uppercase();
+
+ // Build dynamic query based on filters
+ let mut sql = String::from(
+ "SELECT symbol, br_symbol, name, exchange, token, expiry, strike, lot_size, instrument_type, tick_size,
+ CASE
+ WHEN UPPER(symbol) = ? THEN 100.0
+ WHEN UPPER(symbol) LIKE ? || '%' THEN 90.0
+ WHEN UPPER(name) = ? THEN 85.0
+ WHEN UPPER(name) LIKE ? || '%' THEN 80.0
+ WHEN UPPER(symbol) LIKE ? THEN 70.0
+ WHEN UPPER(name) LIKE ? THEN 60.0
+ ELSE 50.0
+ END as relevance_score
+ FROM symbols
+ WHERE broker_id = ? AND (
+ UPPER(symbol) LIKE ? OR
+ UPPER(name) LIKE ? OR
+ UPPER(br_symbol) LIKE ? OR
+ token LIKE ?
+ )",
+ );
+
+ let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![
+ Box::new(query_upper.clone()),
+ Box::new(query_upper.clone()),
+ Box::new(query_upper.clone()),
+ Box::new(query_upper.clone()),
+ Box::new(search_pattern.clone()),
+ Box::new(search_pattern.clone()),
+ Box::new(broker_id.to_string()),
+ Box::new(search_pattern.clone()),
+ Box::new(search_pattern.clone()),
+ Box::new(search_pattern.clone()),
+ Box::new(search_pattern.clone()),
+ ];
+
+ if let Some(exch) = exchange {
+ sql.push_str(" AND exchange = ?");
+ params_vec.push(Box::new(exch.to_string()));
+ }
+
+ if let Some(inst_type) = instrument_type {
+ sql.push_str(" AND instrument_type = ?");
+ params_vec.push(Box::new(inst_type.to_string()));
+ }
+
+ sql.push_str(" ORDER BY relevance_score DESC, symbol ASC LIMIT ?");
+ params_vec.push(Box::new(limit));
+
+ let mut stmt = db.prepare(&sql)?;
+ let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();
+
+ let results = stmt.query_map(params_refs.as_slice(), |row| {
+ Ok(SymbolSearchResult {
+ symbol: row.get(0)?,
+ br_symbol: row.get(1)?,
+ name: row.get(2)?,
+ exchange: row.get(3)?,
+ token: row.get(4)?,
+ expiry: row.get(5)?,
+ strike: row.get(6)?,
+ lot_size: row.get(7)?,
+ instrument_type: row.get(8)?,
+ tick_size: row.get(9)?,
+ relevance_score: row.get(10)?,
+ })
+ })?;
+
+ let mut symbols = Vec::new();
+ for result in results {
+ symbols.push(result?);
+ }
+
+ Ok(symbols)
+}
+
+/// Get symbol by exact match
+pub fn get_symbol(broker_id: &str, symbol: &str, exchange: &str) -> Result<Option<SymbolSearchResult>> {
+ let db = get_db()?;
+
+ let result = db
+ .query_row(
+ "SELECT symbol, br_symbol, name, exchange, token, expiry, strike, lot_size, instrument_type, tick_size
+ FROM symbols
+ WHERE broker_id = ? AND UPPER(symbol) = UPPER(?) AND exchange = ?",
+ params![broker_id, symbol, exchange],
+ |row| {
+ Ok(SymbolSearchResult {
+ symbol: row.get(0)?,
+ br_symbol: row.get(1)?,
+ name: row.get(2)?,
+ exchange: row.get(3)?,
+ token: row.get(4)?,
+ expiry: row.get(5)?,
+ strike: row.get(6)?,
+ lot_size: row.get(7)?,
+ instrument_type: row.get(8)?,
+ tick_size: row.get(9)?,
+ relevance_score: 100.0,
+ })
+ },
+ )
+ .optional()?;
+
+ Ok(result)
+}
+
+/// Get symbol by token
+pub fn get_symbol_by_token(broker_id: &str, token: &str) -> Result<Option<SymbolSearchResult>> {
+ let db = get_db()?;
+
+ let result = db
+ .query_row(
+ "SELECT symbol, br_symbol, name, exchange, token, expiry, strike, lot_size, instrument_type, tick_size
+ FROM symbols
+ WHERE broker_id = ? AND token = ?",
+ params![broker_id, token],
+ |row| {
+ Ok(SymbolSearchResult {
+ symbol: row.get(0)?,
+ br_symbol: row.get(1)?,
+ name: row.get(2)?,
+ exchange: row.get(3)?,
+ token: row.get(4)?,
+ expiry: row.get(5)?,
+ strike: row.get(6)?,
+ lot_size: row.get(7)?,
+ instrument_type: row.get(8)?,
+ tick_size: row.get(9)?,
+ relevance_score: 100.0,
+ })
+ },
+ )
+ .optional()?;
+
+ Ok(result)
+}
+
+/// Get token by symbol (for WebSocket subscriptions)
+pub fn get_token_by_symbol(broker_id: &str, symbol: &str, exchange: &str) -> Result<Option<String>> {
+ let db = get_db()?;
+
+ let token: Option<String> = db
+ .query_row(
+ "SELECT token FROM symbols WHERE broker_id = ? AND UPPER(symbol) = UPPER(?) AND exchange = ? LIMIT 1",
+ params![broker_id, symbol, exchange],
+ |row| row.get(0),
+ )
+ .optional()?;
+
+ Ok(token)
+}
+
+/// Get symbol count for a broker
+pub fn get_symbol_count(broker_id: &str) -> Result<i64> {
+ let db = get_db()?;
+
+ let count: i64 = db.query_row(
+ "SELECT COUNT(*) FROM symbols WHERE broker_id = ?",
+ params![broker_id],
+ |row| row.get(0),
+ )?;
+
+ Ok(count)
+}
+
+/// Get distinct exchanges for a broker
+pub fn get_exchanges(broker_id: &str) -> Result<Vec<String>> {
+ let db = get_db()?;
+
+ let mut stmt =
+ db.prepare("SELECT DISTINCT exchange FROM symbols WHERE broker_id = ? ORDER BY exchange")?;
+
+ let results = stmt.query_map(params![broker_id], |row| row.get(0))?;
+
+ let mut exchanges = Vec::new();
+ for result in results {
+ exchanges.push(result?);
+ }
+
+ Ok(exchanges)
+}
+
+/// Get distinct expiries for FNO symbols
+pub fn get_expiries(
+ broker_id: &str,
+ exchange: Option<&str>,
+ underlying: Option<&str>,
+) -> Result<Vec<String>> {
+ let db = get_db()?;
+
+ let mut sql = String::from(
+ "SELECT DISTINCT expiry FROM symbols WHERE broker_id = ? AND expiry IS NOT NULL AND expiry != ''",
+ );
+
+ let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(broker_id.to_string())];
+
+ if let Some(exch) = exchange {
+ sql.push_str(" AND exchange = ?");
+ params_vec.push(Box::new(exch.to_string()));
+ }
+
+ if let Some(name) = underlying {
+ sql.push_str(" AND UPPER(name) = UPPER(?)");
+ params_vec.push(Box::new(name.to_string()));
+ }
+
+ sql.push_str(" ORDER BY expiry");
+
+ let mut stmt = db.prepare(&sql)?;
+ let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();
+
+ let results = stmt.query_map(params_refs.as_slice(), |row| row.get(0))?;
+
+ let mut expiries = Vec::new();
+ for result in results {
+ expiries.push(result?);
+ }
+
+ Ok(expiries)
+}
+
+/// Get distinct underlyings (for option chain)
+pub fn get_underlyings(broker_id: &str, exchange: Option<&str>) -> Result<Vec<String>> {
+ let db = get_db()?;
+
+ let mut sql = String::from(
+ "SELECT DISTINCT name FROM symbols WHERE broker_id = ? AND name IS NOT NULL AND name != ''",
+ );
+
+ let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(broker_id.to_string())];
+
+ if let Some(exch) = exchange {
+ sql.push_str(" AND exchange = ?");
+ params_vec.push(Box::new(exch.to_string()));
+ }
+
+ sql.push_str(" ORDER BY name");
+
+ let mut stmt = db.prepare(&sql)?;
+ let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();
+
+ let results = stmt.query_map(params_refs.as_slice(), |row| row.get(0))?;
+
+ let mut underlyings = Vec::new();
+ for result in results {
+ underlyings.push(result?);
+ }
+
+ Ok(underlyings)
+}
+
+// ============================================================================
+// CACHE VALIDATION
+// ============================================================================
+
+/// Check if cache is valid (not expired based on TTL)
+pub fn is_cache_valid(broker_id: &str, ttl_seconds: i64) -> Result<bool> {
+ let db = get_db()?;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)?
+ .as_secs() as i64;
+
+ let last_updated: Option<i64> = db
+ .query_row(
+ "SELECT last_updated FROM master_contract_status WHERE broker_id = ? AND is_ready = 1",
+ params![broker_id],
+ |row| row.get(0),
+ )
+ .optional()?;
+
+ match last_updated {
+ Some(timestamp) => Ok((now - timestamp) < ttl_seconds),
+ None => Ok(false),
+ }
+}
+
+/// Get cache age in seconds
+pub fn get_cache_age(broker_id: &str) -> Result<Option<i64>> {
+ let db = get_db()?;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)?
+ .as_secs() as i64;
+
+ let last_updated: Option<i64> = db
+ .query_row(
+ "SELECT last_updated FROM master_contract_status WHERE broker_id = ?",
+ params![broker_id],
+ |row| row.get(0),
+ )
+ .optional()?;
+
+ Ok(last_updated.map(|ts| now - ts))
+}
+
+// ============================================================================
+// SYMBOL FORMAT UTILITIES
+// ============================================================================
+
+/// Normalize index symbol to unified format
+pub fn normalize_index_symbol(symbol: &str) -> String {
+ let symbol_upper = symbol.to_uppercase();
+
+ for (from, to) in INDEX_SYMBOL_MAPPINGS {
+ if symbol_upper == from.to_uppercase() {
+ return to.to_string();
+ }
+ }
+
+ symbol.to_string()
+}
+
+/// Format expiry date to DD-MMM-YY format
+pub fn format_expiry(expiry: &str) -> String {
+ // Already in correct format
+ if expiry.len() == 9 && expiry.chars().nth(2) == Some('-') && expiry.chars().nth(6) == Some('-') {
+ return expiry.to_uppercase();
+ }
+
+ // Try to parse various formats
+ // Format: DDMMMYY (e.g., 26DEC24)
+ if expiry.len() == 7 {
+ let day = &expiry[0..2];
+ let month = &expiry[2..5];
+ let year = &expiry[5..7];
+ return format!("{}-{}-{}", day, month.to_uppercase(), year);
+ }
+
+ // Format: DDMMMYYYY (e.g., 26DEC2024)
+ if expiry.len() == 9 && expiry.chars().all(|c| c.is_alphanumeric()) {
+ let day = &expiry[0..2];
+ let month = &expiry[2..5];
+ let year = &expiry[7..9];
+ return format!("{}-{}-{}", day, month.to_uppercase(), year);
+ }
+
+ // Return as-is if can't parse
+ expiry.to_uppercase()
+}
+
+/// Build unified futures symbol
+/// Format: UNDERLYING + EXPIRY + FUT (e.g., NIFTY26DEC24FUT)
+pub fn build_futures_symbol(underlying: &str, expiry: &str) -> String {
+ let normalized = normalize_index_symbol(underlying);
+ let formatted_expiry = format_expiry(expiry).replace("-", "");
+ format!("{}{}FUT", normalized, formatted_expiry)
+}
+
+/// Build unified options symbol
+/// Format: UNDERLYING + EXPIRY + STRIKE + TYPE (e.g., NIFTY26DEC2424000CE)
+pub fn build_options_symbol(underlying: &str, expiry: &str, strike: f64, option_type: &str) -> String {
+ let normalized = normalize_index_symbol(underlying);
+ let formatted_expiry = format_expiry(expiry).replace("-", "");
+ let strike_str = if strike.fract() == 0.0 {
+ format!("{}", strike as i64)
+ } else {
+ format!("{}", strike)
+ };
+ format!("{}{}{}{}", normalized, formatted_expiry, strike_str, option_type.to_uppercase())
+}
+
+/// Format strike price (remove trailing .0)
+pub fn format_strike(strike: f64) -> String {
+ if strike.fract() == 0.0 {
+ format!("{}", strike as i64)
+ } else {
+ format!("{}", strike)
+ }
+}
+
+// ============================================================================
+// MASTER CONTRACT DOWNLOAD HELPER
+// ============================================================================
+
+/// Complete master contract download workflow
+/// 1. Set status to downloading
+/// 2. Delete old symbols
+/// 3. Insert new symbols
+/// 4. Update status to success/error
+pub fn complete_master_contract_download(
+ broker_id: &str,
+ symbols: &[SymbolRecord],
+) -> Result<i64> {
+ // Update status to downloading
+ update_status(broker_id, DownloadStatus::Downloading, "Downloading master contract...", None)?;
+
+ // Delete old symbols
+ let deleted = delete_symbols_for_broker(broker_id)?;
+ eprintln!("[symbol_master] Deleted {} old symbols for {}", deleted, broker_id);
+
+ // Insert new symbols
+ let inserted = match bulk_insert_symbols(symbols) {
+ Ok(count) => {
+ update_status(
+ broker_id,
+ DownloadStatus::Success,
+ &format!("Successfully loaded {} symbols", count),
+ Some(count),
+ )?;
+ count
+ }
+ Err(e) => {
+ update_status(
+ broker_id,
+ DownloadStatus::Error,
+ &format!("Failed to insert symbols: {}", e),
+ None,
+ )?;
+ return Err(e);
+ }
+ };
+
+ eprintln!("[symbol_master] Inserted {} symbols for {}", inserted, broker_id);
+ Ok(inserted)
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index 7e0e81432..d68573546 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -48,6 +48,7 @@ struct WebSocketServices {
arbitrage: websocket::services::ArbitrageService,
portfolio: websocket::services::PortfolioService,
monitoring: websocket::services::MonitoringService,
+ candle_aggregator: websocket::services::CandleAggregatorService,
}
#[derive(Debug, Serialize)]
@@ -648,6 +649,7 @@ pub fn run() {
arbitrage: websocket::services::ArbitrageService::new(),
portfolio: websocket::services::PortfolioService::new(),
monitoring: websocket::services::MonitoringService::default(),
+ candle_aggregator: websocket::services::CandleAggregatorService::new(),
}));
let ws_state = WebSocketState {
@@ -707,6 +709,12 @@ pub fn run() {
// Load existing conditions from database
let _ = services_guard.monitoring.load_conditions().await;
+ // Initialize candle aggregator service
+ services_guard.candle_aggregator = websocket::services::CandleAggregatorService::new();
+ services_guard.candle_aggregator.set_app_handle(app_handle.clone());
+ let candle_ticker_rx = router_clone.read().await.subscribe_ticker();
+ services_guard.candle_aggregator.start_aggregation(candle_ticker_rx);
+
drop(services_guard); // Release the lock before listening
// Listen for Fyers ticker events from frontend
@@ -1406,7 +1414,7 @@ pub fn run() {
commands::agents::get_trade_decisions,
// Agent Streaming & Performance Commands
commands::agent_streaming::execute_agent_streaming,
- commands::agent_streaming::cancel_agent_stream,
+ commands::agents::cancel_agent_stream,
commands::agent_streaming::execute_agents_parallel,
commands::agent_streaming::execute_agent_priority,
commands::agent_streaming::get_active_agent_streams,
@@ -1653,8 +1661,6 @@ pub fn run() {
commands::alpha_arena::get_alpha_snapshots,
commands::alpha_arena::list_alpha_agents,
commands::alpha_arena::get_alpha_evaluation,
- commands::alpha_arena::get_alpha_api_keys,
- commands::alpha_arena::save_alpha_api_keys,
commands::alpha_arena::list_alpha_competitions,
commands::alpha_arena::get_alpha_competition,
commands::alpha_arena::delete_alpha_competition,
@@ -1909,21 +1915,31 @@ pub fn run() {
commands::broker_credentials::get_broker_credentials,
commands::broker_credentials::delete_broker_credentials,
commands::broker_credentials::list_broker_credentials,
- // Master Contract Commands
- commands::master_contract::save_master_contract_cache,
- commands::master_contract::get_master_contract_cache,
- commands::master_contract::delete_master_contract_cache,
- commands::master_contract::is_master_contract_cache_valid,
- commands::master_contract::get_master_contract_cache_info,
- commands::master_contract::download_master_contract,
- commands::master_contract::download_angelone_master_contract,
- commands::master_contract::download_fyers_master_contract,
- commands::master_contract::search_symbols,
- commands::master_contract::get_symbol,
- commands::master_contract::get_symbol_by_token,
- commands::master_contract::get_symbol_count,
- commands::master_contract::get_exchanges,
- commands::master_contract::get_expiries,
+ // Master Contract Commands (Legacy - removed, use symbol_master instead)
+ // Unified Symbol Master Commands
+ commands::symbol_master::symbol_master_search,
+ commands::symbol_master::symbol_master_get_symbol,
+ commands::symbol_master::symbol_master_get_by_token,
+ commands::symbol_master::symbol_master_get_token,
+ commands::symbol_master::symbol_master_get_status,
+ commands::symbol_master::symbol_master_is_ready,
+ commands::symbol_master::symbol_master_init_broker,
+ commands::symbol_master::symbol_master_update_status,
+ commands::symbol_master::symbol_master_get_count,
+ commands::symbol_master::symbol_master_get_exchanges,
+ commands::symbol_master::symbol_master_get_expiries,
+ commands::symbol_master::symbol_master_get_underlyings,
+ commands::symbol_master::symbol_master_normalize_index,
+ commands::symbol_master::symbol_master_format_expiry,
+ commands::symbol_master::symbol_master_build_futures_symbol,
+ commands::symbol_master::symbol_master_build_options_symbol,
+ // Broker Master Contract Downloads (unified)
+ commands::broker_downloads::fyers::fyers_download_symbols,
+ commands::broker_downloads::zerodha::zerodha_download_symbols,
+ commands::broker_downloads::angelone::angelone_download_symbols,
+ commands::broker_downloads::upstox::upstox_download_symbols,
+ commands::broker_downloads::dhan::dhan_download_symbols,
+ commands::broker_downloads::shoonya::shoonya_download_symbols,
// Indian Broker Commands (Zerodha, Angel, Dhan, etc.)
commands::brokers::zerodha_exchange_token,
commands::brokers::zerodha_validate_token,
@@ -2462,7 +2478,25 @@ pub fn run() {
commands::strategies::stop_strategy,
commands::strategies::stop_all_strategies,
commands::strategies::list_deployed_strategies,
- commands::strategies::update_strategy
+ commands::strategies::update_strategy,
+ // Algo Trading
+ commands::algo_trading::save_algo_strategy,
+ commands::algo_trading::list_algo_strategies,
+ commands::algo_trading::get_algo_strategy,
+ commands::algo_trading::delete_algo_strategy,
+ commands::algo_trading::deploy_algo_strategy,
+ commands::algo_trading::stop_algo_deployment,
+ commands::algo_trading::stop_all_algo_deployments,
+ commands::algo_trading::list_algo_deployments,
+ commands::algo_trading::get_algo_trades,
+ commands::algo_trading::run_algo_scan,
+ commands::algo_trading::get_candle_cache,
+ commands::algo_trading::evaluate_conditions_once,
+ commands::algo_trading::start_candle_aggregation,
+ commands::algo_trading::stop_candle_aggregation,
+ commands::algo_trading::run_algo_backtest,
+ commands::algo_trading::start_order_signal_bridge,
+ commands::algo_trading::stop_order_signal_bridge
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
diff --git a/fincept-terminal-desktop/src-tauri/src/python.rs b/fincept-terminal-desktop/src-tauri/src/python.rs
index 95f01eb39..8e932aa8d 100644
--- a/fincept-terminal-desktop/src-tauri/src/python.rs
+++ b/fincept-terminal-desktop/src-tauri/src/python.rs
@@ -1,13 +1,15 @@
#![allow(dead_code)]
// Unified Python Runtime Module
// Provides Python script execution via subprocess
-// Public API: execute(), execute_sync(), execute_with_stdin(), initialize(), get_bun_path()
+// Public API: execute(), execute_sync(), execute_with_stdin(), execute_streaming(), initialize(), get_bun_path()
-use std::io::Write;
+use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
-use std::process::{Command, Stdio};
+use std::process::{Command, Stdio, Child};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
-use tauri::Manager;
+use tauri::{Manager, Emitter};
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
@@ -336,3 +338,164 @@ pub fn get_python_path(app: &tauri::AppHandle, library_hint: Option<&str>) -> Re
pub fn get_script_path(app: &tauri::AppHandle, script: &str) -> Result<PathBuf, String> {
resolve_script_path(app, script)
}
+
+// ============================================================================
+// STREAMING EXECUTION
+// ============================================================================
+
+/// Streaming chunk types emitted to frontend
+#[derive(Clone, serde::Serialize)]
+pub struct StreamChunk {
+ pub stream_id: String,
+ pub chunk_type: String, // "token", "thinking", "tool_call", "done", "error"
+ pub content: String,
+ pub sequence: u32,
+}
+
+/// Execute Python script with real-time streaming via Tauri events
+/// Each line from Python stdout is immediately emitted to frontend
+pub async fn execute_streaming(
+ app: tauri::AppHandle,
+ script: &str,
+ args: Vec<String>,
+ stream_id: String,
+ cancel_flag: Arc<AtomicBool>,
+) -> Result<String, String> {
+ let script_path = resolve_script_path(&app, script)?;
+ let python = resolve_python_path(&app, script)?;
+
+ let mut cmd = Command::new(&python);
+ cmd.arg(&script_path)
+ .args(&args)
+ .arg("--stream") // Tell Python to output in streaming mode
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ let mut child = cmd.spawn()
+ .map_err(|e| format!("Failed to spawn Python process: {}", e))?;
+
+ let stdout = child.stdout.take()
+ .ok_or_else(|| "Failed to capture stdout".to_string())?;
+
+ let reader = BufReader::new(stdout);
+ let mut sequence: u32 = 0;
+ let mut full_output = String::new();
+ let event_name = format!("agent-stream-{}", stream_id);
+
+ // Read stdout line by line and emit events in real-time
+ for line in reader.lines() {
+ // Check if cancelled
+ if cancel_flag.load(Ordering::Relaxed) {
+ let _ = child.kill();
+ let chunk = StreamChunk {
+ stream_id: stream_id.clone(),
+ chunk_type: "cancelled".to_string(),
+ content: "Stream cancelled by user".to_string(),
+ sequence,
+ };
+ let _ = app.emit(&event_name, &chunk);
+ return Err("Stream cancelled".to_string());
+ }
+
+ match line {
+ Ok(line_content) => {
+ let trimmed = line_content.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+
+ // Determine chunk type based on content prefix
+ let (chunk_type, content) = if trimmed.starts_with("THINKING:") {
+ ("thinking".to_string(), trimmed.strip_prefix("THINKING:").unwrap_or(trimmed).trim().to_string())
+ } else if trimmed.starts_with("TOOL:") {
+ ("tool_call".to_string(), trimmed.strip_prefix("TOOL:").unwrap_or(trimmed).trim().to_string())
+ } else if trimmed.starts_with("ERROR:") {
+ ("error".to_string(), trimmed.strip_prefix("ERROR:").unwrap_or(trimmed).trim().to_string())
+ } else if trimmed.starts_with("DONE:") {
+ ("done".to_string(), trimmed.strip_prefix("DONE:").unwrap_or(trimmed).trim().to_string())
+ } else if trimmed.starts_with('{') || trimmed.starts_with('[') {
+ // JSON output - likely final result
+ ("json".to_string(), trimmed.to_string())
+ } else {
+ // Regular token/content
+ ("token".to_string(), trimmed.to_string())
+ };
+
+ full_output.push_str(&content);
+ full_output.push('\n');
+
+ let chunk = StreamChunk {
+ stream_id: stream_id.clone(),
+ chunk_type,
+ content,
+ sequence,
+ };
+
+ // Emit to frontend immediately
+ if let Err(e) = app.emit(&event_name, &chunk) {
+ eprintln!("[Streaming] Failed to emit event: {}", e);
+ }
+
+ sequence += 1;
+ }
+ Err(e) => {
+ eprintln!("[Streaming] Error reading line: {}", e);
+ break;
+ }
+ }
+ }
+
+ // Wait for process to complete
+ let status = child.wait()
+ .map_err(|e| format!("Failed to wait for process: {}", e))?;
+
+ // Emit done event
+ let done_chunk = StreamChunk {
+ stream_id: stream_id.clone(),
+ chunk_type: "done".to_string(),
+ content: if status.success() { "completed".to_string() } else { "failed".to_string() },
+ sequence,
+ };
+ let _ = app.emit(&event_name, &done_chunk);
+
+ // Capture any stderr
+ if let Some(stderr) = child.stderr.take() {
+ let stderr_reader = BufReader::new(stderr);
+ for line in stderr_reader.lines().flatten() {
+ eprintln!("[Python stderr] {}", line);
+ }
+ }
+
+ if status.success() {
+ // Try to extract final JSON if present
+ extract_json(&full_output).or_else(|_| Ok(full_output))
+ } else {
+ Err(format!("Script failed with exit code: {:?}", status.code()))
+ }
+}
+
+/// Spawn streaming execution and return the child process handle for cancellation
+pub fn spawn_streaming(
+ app: &tauri::AppHandle,
+ script: &str,
+ args: Vec<String>,
+) -> Result<Child, String> {
+ let script_path = resolve_script_path(app, script)?;
+ let python = resolve_python_path(app, script)?;
+
+ let mut cmd = Command::new(&python);
+ cmd.arg(&script_path)
+ .args(&args)
+ .arg("--stream")
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ cmd.spawn()
+ .map_err(|e| format!("Failed to spawn: {}", e))
+}
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.rs
new file mode 100644
index 000000000..c617cc310
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/services/candle_aggregator.rs
@@ -0,0 +1,332 @@
+#![allow(dead_code)]
+// Candle Aggregator Service — builds OHLCV candles from tick stream
+//
+// Subscribes to the ticker broadcast channel and aggregates ticks into
+// candles of various timeframes. When a candle closes (new tick falls
+// into the next window), the closed candle is written to the
+// `candle_cache` table and an `algo_candle_closed` Tauri event is emitted.
+
+use crate::database::pool::get_pool;
+use crate::websocket::types::TickerData;
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::sync::Arc;
+use tokio::sync::RwLock;
+use tauri::Emitter;
+
+// ============================================================================
+// TYPES
+// ============================================================================
+
+/// In-memory state for a single open candle
+#[derive(Debug, Clone)]
+struct CandleState {
+ symbol: String,
+ provider: String,
+ timeframe: String,
+ open_time: u64, // epoch seconds, start of candle window
+ o: f64,
+ h: f64,
+ l: f64,
+ c: f64,
+ volume: f64,
+ tick_count: u64,
+}
+
+/// A subscription request: track this symbol+timeframe pair
+#[derive(Debug, Clone, Hash, Eq, PartialEq)]
+pub struct AggregationKey {
+ pub symbol: String,
+ pub timeframe: String,
+}
+
+/// Closed candle emitted as Tauri event
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ClosedCandle {
+ pub symbol: String,
+ pub provider: String,
+ pub timeframe: String,
+ pub open_time: u64,
+ pub o: f64,
+ pub h: f64,
+ pub l: f64,
+ pub c: f64,
+ pub volume: f64,
+}
+
+// ============================================================================
+// CANDLE AGGREGATOR SERVICE
+// ============================================================================
+
+pub struct CandleAggregatorService {
+ /// Active aggregation subscriptions: (symbol, timeframe) -> CandleState
+ candles: Arc<RwLock<HashMap<AggregationKey, CandleState>>>,
+ /// Set of active subscriptions (which symbol+timeframe pairs to aggregate)
+ subscriptions: Arc<RwLock<HashMap<AggregationKey, ()>>>,
+ app_handle: Option<tauri::AppHandle>,
+}
+
+impl Default for CandleAggregatorService {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl CandleAggregatorService {
+ pub fn new() -> Self {
+ Self {
+ candles: Arc::new(RwLock::new(HashMap::new())),
+ subscriptions: Arc::new(RwLock::new(HashMap::new())),
+ app_handle: None,
+ }
+ }
+
+ pub fn set_app_handle(&mut self, app_handle: tauri::AppHandle) {
+ self.app_handle = Some(app_handle);
+ }
+
+ /// Register a symbol+timeframe pair for aggregation
+ pub async fn add_subscription(&self, symbol: String, timeframe: String) {
+ let key = AggregationKey {
+ symbol: symbol.clone(),
+ timeframe: timeframe.clone(),
+ };
+ self.subscriptions.write().await.insert(key, ());
+ println!(
+ "[CandleAggregator] Subscribed: {} @ {}",
+ symbol, timeframe
+ );
+ }
+
+ /// Unregister a symbol+timeframe pair
+ pub async fn remove_subscription(&self, symbol: String, timeframe: String) {
+ let key = AggregationKey {
+ symbol: symbol.clone(),
+ timeframe: timeframe.clone(),
+ };
+ self.subscriptions.write().await.remove(&key);
+ self.candles.write().await.remove(&key);
+ println!(
+ "[CandleAggregator] Unsubscribed: {} @ {}",
+ symbol, timeframe
+ );
+ }
+
+ /// Start listening for ticker data from the broadcast channel
+ pub fn start_aggregation(
+ &self,
+ mut ticker_rx: tokio::sync::broadcast::Receiver<TickerData>,
+ ) {
+ let candles = self.candles.clone();
+ let subscriptions = self.subscriptions.clone();
+ let app_handle = self.app_handle.clone();
+
+ println!("[CandleAggregator] Starting tick aggregation loop...");
+
+ tokio::spawn(async move {
+ loop {
+ match ticker_rx.recv().await {
+ Ok(ticker) => {
+ Self::process_tick(
+ &candles,
+ &subscriptions,
+ &app_handle,
+ &ticker,
+ )
+ .await;
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
+ println!(
+ "[CandleAggregator] Channel lagged, skipped {} messages",
+ n
+ );
+ continue;
+ }
+ Err(_) => {
+ println!("[CandleAggregator] Channel closed — stopping aggregation");
+ break;
+ }
+ }
+ }
+ println!("[CandleAggregator] Aggregation loop exited");
+ });
+ }
+
+ /// Process a single tick: update in-memory candle or close+create new
+ async fn process_tick(
+ candles: &Arc<RwLock<HashMap<AggregationKey, CandleState>>>,
+ subscriptions: &Arc<RwLock<HashMap<AggregationKey, ()>>>,
+ app_handle: &Option<tauri::AppHandle>,
+ ticker: &TickerData,
+ ) {
+ let subs = subscriptions.read().await;
+ if subs.is_empty() {
+ return;
+ }
+
+ // Find all subscriptions matching this symbol
+ let matching_keys: Vec<AggregationKey> = subs
+ .keys()
+ .filter(|k| k.symbol == ticker.symbol)
+ .cloned()
+ .collect();
+ drop(subs);
+
+ if matching_keys.is_empty() {
+ return;
+ }
+
+ let price = ticker.price;
+ let volume = ticker.volume.unwrap_or(0.0);
+ let tick_ts = ticker.timestamp; // epoch seconds
+
+ for key in matching_keys {
+ let tf_seconds = timeframe_to_seconds(&key.timeframe);
+ if tf_seconds == 0 {
+ continue;
+ }
+
+ let candle_open_time = (tick_ts / tf_seconds) * tf_seconds;
+
+ let mut candle_map = candles.write().await;
+
+ if let Some(existing) = candle_map.get_mut(&key) {
+ if candle_open_time == existing.open_time {
+ // Same candle window — update OHLCV
+ if price > existing.h {
+ existing.h = price;
+ }
+ if price < existing.l {
+ existing.l = price;
+ }
+ existing.c = price;
+ existing.volume += volume;
+ existing.tick_count += 1;
+ } else {
+ // New candle window — close the old one
+ let closed = ClosedCandle {
+ symbol: existing.symbol.clone(),
+ provider: existing.provider.clone(),
+ timeframe: existing.timeframe.clone(),
+ open_time: existing.open_time,
+ o: existing.o,
+ h: existing.h,
+ l: existing.l,
+ c: existing.c,
+ volume: existing.volume,
+ };
+
+ // Write to DB
+ Self::write_candle_to_db(&closed);
+
+ // Emit event to frontend
+ if let Some(ref handle) = app_handle {
+ let _ = handle.emit("algo_candle_closed", &closed);
+ }
+
+ // Start new candle
+ *existing = CandleState {
+ symbol: ticker.symbol.clone(),
+ provider: ticker.provider.clone(),
+ timeframe: key.timeframe.clone(),
+ open_time: candle_open_time,
+ o: price,
+ h: price,
+ l: price,
+ c: price,
+ volume,
+ tick_count: 1,
+ };
+ }
+ } else {
+ // First tick for this key — start new candle
+ candle_map.insert(
+ key.clone(),
+ CandleState {
+ symbol: ticker.symbol.clone(),
+ provider: ticker.provider.clone(),
+ timeframe: key.timeframe.clone(),
+ open_time: candle_open_time,
+ o: price,
+ h: price,
+ l: price,
+ c: price,
+ volume,
+ tick_count: 1,
+ },
+ );
+ }
+ }
+ }
+
+ /// Write a closed candle to the candle_cache table
+ fn write_candle_to_db(candle: &ClosedCandle) {
+ let candle = candle.clone();
+ // Spawn blocking task to avoid blocking the async runtime
+ tokio::task::spawn_blocking(move || {
+ let pool = match get_pool() {
+ Ok(p) => p,
+ Err(e) => {
+ eprintln!("[CandleAggregator] DB pool error: {}", e);
+ return;
+ }
+ };
+ let conn = match pool.get() {
+ Ok(c) => c,
+ Err(e) => {
+ eprintln!("[CandleAggregator] DB conn error: {}", e);
+ return;
+ }
+ };
+
+ if let Err(e) = 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)",
+ rusqlite::params![
+ candle.symbol,
+ candle.provider,
+ candle.timeframe,
+ candle.open_time,
+ candle.o,
+ candle.h,
+ candle.l,
+ candle.c,
+ candle.volume,
+ ],
+ ) {
+ eprintln!("[CandleAggregator] DB write error: {}", e);
+ }
+ });
+ }
+}
+
+// ============================================================================
+// HELPERS
+// ============================================================================
+
+/// Convert timeframe string to seconds
+fn timeframe_to_seconds(tf: &str) -> u64 {
+ match tf {
+ "1m" => 60,
+ "3m" => 180,
+ "5m" => 300,
+ "15m" => 900,
+ "30m" => 1800,
+ "1h" => 3600,
+ "4h" => 14400,
+ "1d" => 86400,
+ _ => {
+ // Try parsing numeric suffix
+ if let Some(num_str) = tf.strip_suffix('m') {
+ num_str.parse::<u64>().unwrap_or(0) * 60
+ } else if let Some(num_str) = tf.strip_suffix('h') {
+ num_str.parse::<u64>().unwrap_or(0) * 3600
+ } else if let Some(num_str) = tf.strip_suffix('d') {
+ num_str.parse::<u64>().unwrap_or(0) * 86400
+ } else {
+ 0
+ }
+ }
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/services/mod.rs b/fincept-terminal-desktop/src-tauri/src/websocket/services/mod.rs
index fa6cc7111..f8fa18aff 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/services/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/services/mod.rs
@@ -4,8 +4,10 @@ pub mod paper_trading;
pub mod arbitrage;
pub mod portfolio;
pub mod monitoring;
+pub mod candle_aggregator;
pub use paper_trading::PaperTradingService;
pub use arbitrage::ArbitrageService;
pub use portfolio::PortfolioService;
pub use monitoring::MonitoringService;
+pub use candle_aggregator::CandleAggregatorService;
diff --git a/fincept-terminal-desktop/src/brokers/stocks/registry.ts b/fincept-terminal-desktop/src/brokers/stocks/registry.ts
index 836b4916e..9c5b5eb02 100644
--- a/fincept-terminal-desktop/src/brokers/stocks/registry.ts
+++ b/fincept-terminal-desktop/src/brokers/stocks/registry.ts
@@ -713,6 +713,62 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {
defaultSymbols: NIFTY_50_SYMBOLS,
},
+ flattrade: {
+ id: 'flattrade',
+ name: 'flattrade',
+ displayName: 'Flattrade',
+ logo: 'https://fincept.in/brokers/flattrade.png',
+ website: 'https://flattrade.in',
+
+ region: 'india',
+ country: 'IN',
+ currency: 'INR',
+ exchanges: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'],
+ marketHours: {
+ open: '09:15',
+ close: '15:30',
+ timezone: 'Asia/Kolkata',
+ preMarketOpen: '09:00',
+ preMarketClose: '09:08',
+ },
+
+ features: {
+ webSocket: true,
+ amo: true,
+ gtt: false,
+ bracketOrder: true,
+ coverOrder: true,
+ marginCalculator: true,
+ optionsChain: true,
+ paperTrading: false,
+ },
+
+ tradingFeatures: {
+ marketOrders: true,
+ limitOrders: true,
+ stopOrders: true,
+ stopLimitOrders: true,
+ trailingStopOrders: false,
+ },
+
+ productTypes: ['CASH', 'INTRADAY', 'MARGIN'],
+
+ authType: 'oauth', // OAuth redirect + SHA256 hash
+
+ rateLimit: {
+ ordersPerSecond: 10,
+ quotesPerSecond: 5,
+ },
+
+ fees: {
+ equity: { brokerage: 0, stt: 0.001 }, // Zero brokerage
+ intraday: { brokerage: 0 }, // Zero brokerage
+ fno: { brokerage: 0 }, // Zero brokerage
+ },
+
+ defaultSymbols: NIFTY_50_SYMBOLS,
+ },
+
// ============================================================================
// US BROKERS
// ============================================================================
diff --git a/fincept-terminal-desktop/src/components/common/MarkdownRenderer.tsx b/fincept-terminal-desktop/src/components/common/MarkdownRenderer.tsx
index 879306e1d..3cdd2a44a 100644
--- a/fincept-terminal-desktop/src/components/common/MarkdownRenderer.tsx
+++ b/fincept-terminal-desktop/src/components/common/MarkdownRenderer.tsx
@@ -1,6 +1,8 @@
import React, { useMemo } from 'react';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
+import katex from 'katex';
+import 'katex/dist/katex.min.css';
interface MarkdownRendererProps {
content: string;
@@ -13,6 +15,33 @@ marked.setOptions({
breaks: true,
});
+// Render LaTeX formulas using KaTeX
+const renderLatex = (text: string): string => {
+ // Block formulas: \[ ... \] or $$ ... $$
+ text = text.replace(/\\\[([\s\S]*?)\\\]|\$\$([\s\S]*?)\$\$/g, (match, b1, b2) => {
+ const formula = b1 || b2;
+ try {
+ return `<div class="katex-block">${katex.renderToString(formula.trim(), { displayMode: true, throwOnError: false })}</div>`;
+ } catch (e) {
+ console.warn('[KaTeX] Block formula error:', e);
+ return match;
+ }
+ });
+
+ // Inline formulas: \( ... \) or $ ... $ (but not $$ which is block)
+ text = text.replace(/\\\((.*?)\\\)|\$([^\$\n]+?)\$/g, (match, i1, i2) => {
+ const formula = i1 || i2;
+ try {
+ return katex.renderToString(formula.trim(), { displayMode: false, throwOnError: false });
+ } catch (e) {
+ console.warn('[KaTeX] Inline formula error:', e);
+ return match;
+ }
+ });
+
+ return text;
+};
+
const MARKDOWN_CSS = `
.fincept-md h1 {
color: #FF8800;
@@ -190,6 +219,29 @@ const MARKDOWN_CSS = `
.fincept-md input[type="checkbox"] {
margin-right: 4px;
}
+/* KaTeX Formula Styles */
+.fincept-md .katex-block {
+ display: block;
+ text-align: center;
+ margin: 12px 0;
+ padding: 12px;
+ background-color: #0F0F0F;
+ border: 1px solid #2A2A2A;
+ border-left: 2px solid #FF8800;
+ border-radius: 2px;
+ overflow-x: auto;
+}
+.fincept-md .katex {
+ color: #00E5FF;
+ font-size: 1.1em;
+}
+.fincept-md .katex-display {
+ margin: 0;
+ padding: 0;
+}
+.fincept-md .katex-display > .katex {
+ color: #00E5FF;
+}
/* Price/Data Cards */
.price-card {
display: inline-flex;
@@ -273,14 +325,17 @@ const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({ content, style = {}
const html = useMemo(() => {
if (!content || typeof content !== 'string') return '';
try {
- // First, parse data cards from raw content
- const withCards = parseDataCards(content);
+ // First, render LaTeX formulas
+ const withLatex = renderLatex(content);
+
+ // Then, parse data cards from raw content
+ const withCards = parseDataCards(withLatex);
// Then parse markdown
const raw = marked.parse(withCards) as string;
return DOMPurify.sanitize(raw, {
- ADD_ATTR: ['target', 'class'],
+ ADD_ATTR: ['target', 'class', 'style', 'xmlns', 'viewBox', 'd', 'fill', 'stroke', 'width', 'height', 'aria-hidden', 'focusable'],
ALLOWED_TAGS: [
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'p', 'br', 'hr',
@@ -289,6 +344,11 @@ const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({ content, style = {}
'blockquote', 'a', 'img',
'table', 'thead', 'tbody', 'tr', 'th', 'td',
'input', 'span', 'div', 'sub', 'sup',
+ // KaTeX elements
+ 'math', 'semantics', 'mrow', 'mi', 'mo', 'mn', 'ms', 'mtext',
+ 'mfrac', 'msqrt', 'mroot', 'msub', 'msup', 'msubsup', 'munder',
+ 'mover', 'munderover', 'mtable', 'mtr', 'mtd', 'annotation',
+ 'svg', 'path', 'line', 'rect', 'circle', 'g', 'use', 'defs',
],
});
} catch (error) {
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 28abab36d..cb82cd174 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -68,6 +68,7 @@ const NotesTab = React.lazy(() => import('@/components/tabs/notes').then(m => ({
const AlternativeInvestmentsTab = React.lazy(() => import('@/components/tabs/alternative-investments').then(m => ({ default: m.AlternativeInvestmentsTab })));
const MarketSimTab = React.lazy(() => import('@/components/tabs/market-sim').then(m => ({ default: m.MarketSimTab })));
const StrategiesTab = React.lazy(() => import('@/components/tabs/strategies'));
+const AlgoTradingTab = React.lazy(() => import('@/components/tabs/algo-trading'));
// Loading fallback component for lazy-loaded tabs
const TabLoadingFallback = () => (
@@ -580,6 +581,7 @@ function FinxeptTerminalContent() {
// Tools
{ label: 'Tools', header: true },
{ label: 'Strategy Engine', action: () => setActiveTab('strategies') },
+ { label: 'Algo Trading', action: () => setActiveTab('algo-trading') },
{ label: 'Agent Config', action: () => setActiveTab('agents') },
{ label: 'MCP Servers', action: () => setActiveTab('mcp') },
{ label: 'Data Sources', action: () => setActiveTab('datasources') },
@@ -884,6 +886,13 @@ function FinxeptTerminalContent() {
>
{t('navigation.backtesting')}
</TabsTrigger>
+ <TabsTrigger
+ value="algo-trading"
+ style={activeTab === 'algo-trading' ? tabStyles.active : tabStyles.default}
+ title="Algo Trading"
+ >
+ Algo Trading
+ </TabsTrigger>
<TabsTrigger
value="nodes"
style={activeTab === 'nodes' ? tabStyles.active : tabStyles.default}
@@ -995,6 +1004,11 @@ function FinxeptTerminalContent() {
<StrategiesTab />
</React.Suspense>
</TabsContent>
+ <TabsContent value="algo-trading" className="h-full m-0 p-0">
+ <React.Suspense fallback={<TabLoadingFallback />}>
+ <AlgoTradingTab />
+ </React.Suspense>
+ </TabsContent>
<TabsContent value="backtesting" className="h-full m-0 p-0">
<React.Suspense fallback={<TabLoadingFallback />}>
<BacktestingTab />
diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx b/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx
index 8f629d145..4926847d7 100644
--- a/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx
@@ -21,6 +21,7 @@ import {
ChevronRight, ChevronDown, Search, Copy, Check, Cpu,
Sparkles, Route, ListTree, Save, Edit3, ToggleLeft, ToggleRight,
Loader2, Target, FileJson, Sliders, Database, Eye, Workflow,
+ Shield, BookOpen, Activity, Layers, Minimize2, Anchor, ClipboardCheck,
} from 'lucide-react';
import {
getLLMConfigs,
@@ -264,6 +265,34 @@ const AgentConfigTab: React.FC = () => {
instructions: string;
enable_memory: boolean;
enable_reasoning: boolean;
+ enable_knowledge: boolean;
+ enable_guardrails: boolean;
+ enable_agentic_memory: boolean;
+ enable_storage: boolean;
+ enable_tracing: boolean;
+ enable_compression: boolean;
+ enable_hooks: boolean;
+ enable_evaluation: boolean;
+ // Detailed Knowledge config
+ knowledge_type: 'url' | 'pdf' | 'text' | 'combined';
+ knowledge_urls: string;
+ knowledge_vector_db: string;
+ knowledge_embedder: string;
+ // Detailed Guardrails config
+ guardrails_pii: boolean;
+ guardrails_injection: boolean;
+ guardrails_compliance: boolean;
+ // Detailed Storage config
+ storage_type: 'sqlite' | 'postgres';
+ storage_db_path: string;
+ storage_table: string;
+ // Agentic Memory config
+ agentic_memory_user_id: string;
+ // Memory detailed config
+ memory_db_path: string;
+ memory_table: string;
+ memory_create_user_memories: boolean;
+ memory_create_session_summary: boolean;
}>({
provider: 'openai',
model_id: 'gpt-4-turbo',
@@ -273,6 +302,29 @@ const AgentConfigTab: React.FC = () => {
instructions: '',
enable_memory: false,
enable_reasoning: false,
+ enable_knowledge: false,
+ enable_guardrails: false,
+ enable_agentic_memory: false,
+ enable_storage: false,
+ enable_tracing: false,
+ enable_compression: false,
+ enable_hooks: false,
+ enable_evaluation: false,
+ knowledge_type: 'url',
+ knowledge_urls: '',
+ knowledge_vector_db: 'lancedb',
+ knowledge_embedder: 'openai',
+ guardrails_pii: true,
+ guardrails_injection: true,
+ guardrails_compliance: false,
+ storage_type: 'sqlite',
+ storage_db_path: '',
+ storage_table: 'agent_sessions',
+ agentic_memory_user_id: '',
+ memory_db_path: '',
+ memory_table: 'agent_memory',
+ memory_create_user_memories: true,
+ memory_create_session_summary: true,
});
// System state (cached via service)
@@ -311,6 +363,8 @@ const AgentConfigTab: React.FC = () => {
setTeamModeInternal(m);
updateTabSession({ teamMode: m });
}, [updateTabSession]);
+ const [showMembersResponses, setShowMembersResponses] = useState(false);
+ const [teamLeaderIndex, setTeamLeaderIndex] = useState<number>(-1); // -1 = no leader
// Chat state
const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
@@ -323,6 +377,11 @@ const AgentConfigTab: React.FC = () => {
const [selectedTools, setSelectedTools] = useState<string[]>([]);
const [copiedTool, setCopiedTool] = useState<string | null>(null);
+ // Streaming state
+ const [streamingContent, setStreamingContent] = useState<string>('');
+ const [isStreaming, setIsStreaming] = useState(false);
+ const [activeStreamHandle, setActiveStreamHandle] = useState<any>(null);
+
// Workflow/Planner state - synced with tab session
const [workflowSymbol, setWorkflowSymbolInternal] = useState(tabSession.workflowSymbol);
const setWorkflowSymbol = useCallback((s: string) => {
@@ -545,6 +604,11 @@ const AgentConfigTab: React.FC = () => {
const updateEditedConfigFromAgent = (agent: AgentCard) => {
const config = agent.config || {};
const model = config.model || {};
+ const knowledgeCfg = typeof config.knowledge === 'object' ? config.knowledge : {};
+ const guardrailsCfg = typeof config.guardrails === 'object' ? config.guardrails : {};
+ const storageCfg = typeof config.storage === 'object' ? config.storage : {};
+ const memoryCfg = typeof config.memory === 'object' ? config.memory : {};
+ const agenticMemCfg = typeof config.agentic_memory === 'object' ? config.agentic_memory : {};
setEditedConfig({
provider: model.provider || 'openai',
model_id: model.model_id || 'gpt-4-turbo',
@@ -552,8 +616,32 @@ const AgentConfigTab: React.FC = () => {
max_tokens: model.max_tokens ?? 4096,
tools: config.tools || [],
instructions: config.instructions || '',
- enable_memory: config.memory?.enabled || false,
- enable_reasoning: config.reasoning || false,
+ enable_memory: !!(config.memory?.enabled ?? config.memory),
+ enable_reasoning: !!(config.reasoning?.enabled ?? config.reasoning),
+ enable_knowledge: !!(config.knowledge?.enabled ?? config.knowledge),
+ enable_guardrails: !!(config.guardrails?.enabled ?? config.guardrails),
+ enable_agentic_memory: !!(config.agentic_memory?.enabled ?? config.agentic_memory),
+ enable_storage: !!(config.storage?.enabled ?? config.storage),
+ enable_tracing: !!config.tracing,
+ enable_compression: !!config.compression,
+ enable_hooks: !!config.hooks,
+ enable_evaluation: !!config.evaluation,
+ // Detailed configs from loaded agent
+ knowledge_type: knowledgeCfg?.type || 'url',
+ knowledge_urls: (knowledgeCfg?.urls || []).join('\n'),
+ knowledge_vector_db: knowledgeCfg?.vector_db || 'lancedb',
+ knowledge_embedder: knowledgeCfg?.embedder || 'openai',
+ guardrails_pii: guardrailsCfg?.pii_detection ?? true,
+ guardrails_injection: guardrailsCfg?.injection_check ?? true,
+ guardrails_compliance: guardrailsCfg?.financial_compliance ?? false,
+ storage_type: storageCfg?.type || 'sqlite',
+ storage_db_path: storageCfg?.db_path || '',
+ storage_table: storageCfg?.table_name || 'agent_sessions',
+ agentic_memory_user_id: agenticMemCfg?.user_id || '',
+ memory_db_path: memoryCfg?.db_path || '',
+ memory_table: memoryCfg?.table_name || 'agent_memory',
+ memory_create_user_memories: memoryCfg?.create_user_memories ?? true,
+ memory_create_session_summary: memoryCfg?.create_session_summary ?? true,
});
setJsonText(JSON.stringify(agent, null, 2));
};
@@ -584,6 +672,64 @@ const AgentConfigTab: React.FC = () => {
}
};
+ // =============================================================================
+ // Helper: Build detailed config options from editedConfig state
+ // =============================================================================
+
+ const buildDetailedConfigOptions = () => {
+ const opts: Parameters<typeof agentService.buildAgentConfig>[3] = {
+ tools: selectedTools.length > 0 ? selectedTools : editedConfig.tools,
+ temperature: editedConfig.temperature,
+ maxTokens: editedConfig.max_tokens,
+ memory: editedConfig.enable_memory
+ ? {
+ enabled: true,
+ db_path: editedConfig.memory_db_path || undefined,
+ table_name: editedConfig.memory_table || undefined,
+ create_user_memories: editedConfig.memory_create_user_memories,
+ create_session_summary: editedConfig.memory_create_session_summary,
+ }
+ : false,
+ reasoning: editedConfig.enable_reasoning,
+ knowledge: editedConfig.enable_knowledge
+ ? {
+ enabled: true,
+ type: editedConfig.knowledge_type,
+ urls: editedConfig.knowledge_urls ? editedConfig.knowledge_urls.split('\n').filter(u => u.trim()) : undefined,
+ vector_db: editedConfig.knowledge_vector_db || undefined,
+ embedder: editedConfig.knowledge_embedder || undefined,
+ }
+ : undefined,
+ guardrails: editedConfig.enable_guardrails
+ ? {
+ enabled: true,
+ pii_detection: editedConfig.guardrails_pii,
+ injection_check: editedConfig.guardrails_injection,
+ financial_compliance: editedConfig.guardrails_compliance,
+ }
+ : false,
+ agentic_memory: editedConfig.enable_agentic_memory
+ ? {
+ enabled: true,
+ user_id: editedConfig.agentic_memory_user_id || undefined,
+ }
+ : false,
+ storage: editedConfig.enable_storage
+ ? {
+ enabled: true,
+ type: editedConfig.storage_type,
+ db_path: editedConfig.storage_db_path || undefined,
+ table_name: editedConfig.storage_table || undefined,
+ }
+ : undefined,
+ tracing: editedConfig.enable_tracing,
+ compression: editedConfig.enable_compression,
+ hooks: editedConfig.enable_hooks,
+ evaluation: editedConfig.enable_evaluation,
+ };
+ return opts;
+ };
+
// =============================================================================
// Agent Execution
// =============================================================================
@@ -620,13 +766,7 @@ const AgentConfigTab: React.FC = () => {
editedConfig.provider,
editedConfig.model_id,
editedConfig.instructions,
- {
- tools: selectedTools.length > 0 ? selectedTools : editedConfig.tools,
- temperature: editedConfig.temperature,
- maxTokens: editedConfig.max_tokens,
- memory: editedConfig.enable_memory,
- reasoning: editedConfig.enable_reasoning,
- }
+ buildDetailedConfigOptions()
);
const result = await agentService.executeRoutedQuery(testQuery, apiKeys, undefined, userConfig);
setTestResult(result);
@@ -647,13 +787,7 @@ const AgentConfigTab: React.FC = () => {
editedConfig.provider,
editedConfig.model_id,
editedConfig.instructions,
- {
- tools: selectedTools.length > 0 ? selectedTools : editedConfig.tools,
- temperature: editedConfig.temperature,
- maxTokens: editedConfig.max_tokens,
- memory: editedConfig.enable_memory,
- reasoning: editedConfig.enable_reasoning,
- }
+ buildDetailedConfigOptions()
);
let result;
@@ -690,8 +824,16 @@ const AgentConfigTab: React.FC = () => {
if (teamMembers.length === 0 || !testQuery.trim()) return;
setExecuting(true);
+ setIsStreaming(true);
+ setStreamingContent('');
setError(null);
+ // Add user message immediately
+ setChatMessages(prev => [
+ ...prev,
+ { role: 'user', content: testQuery, timestamp: new Date() },
+ ]);
+
try {
const apiKeys = await getApiKeys();
@@ -705,35 +847,84 @@ const AgentConfigTab: React.FC = () => {
modelId: agent.config?.model?.model_id || 'gpt-4-turbo',
tools: agent.config?.tools || [],
instructions: agent.config?.instructions || '',
- }))
+ })),
+ {
+ show_members_responses: showMembersResponses,
+ leader_index: teamLeaderIndex >= 0 ? teamLeaderIndex : undefined,
+ }
);
- const result = await agentService.runTeam(testQuery, teamConfig, apiKeys);
- setTestResult(result);
+ let accumulatedContent = '';
+
+ // Use streaming API
+ const streamHandle = await agentService.runTeamStreaming(
+ testQuery,
+ teamConfig,
+ apiKeys,
+ (chunk) => {
+ // Handle each streaming chunk
+ if (chunk.chunk_type === 'token') {
+ accumulatedContent += chunk.content + ' ';
+ setStreamingContent(accumulatedContent);
+ } else if (chunk.chunk_type === 'thinking') {
+ setStreamingContent(prev => prev + `\n_${chunk.content}_\n`);
+ } else if (chunk.chunk_type === 'tool_call') {
+ setStreamingContent(prev => prev + `\n**Tool:** ${chunk.content}\n`);
+ } else if (chunk.chunk_type === 'done') {
+ // Streaming complete
+ setIsStreaming(false);
+ } else if (chunk.chunk_type === 'error') {
+ setError(chunk.content);
+ setIsStreaming(false);
+ }
+ }
+ );
- setChatMessages(prev => [
- ...prev,
- { role: 'user', content: testQuery, timestamp: new Date() },
- {
- role: 'assistant',
- content: extractAgentResponseText(result.response || result.error || JSON.stringify(result, null, 2)),
- timestamp: new Date(),
- agentName: `Team (${teamMembers.length} agents)`,
- },
- ]);
+ setActiveStreamHandle(streamHandle);
+
+ // Wait for stream to complete (the callback handles updates)
+ // The stream handle will clean up when done
+
+ // Add final assistant message after streaming completes
+ setTimeout(() => {
+ if (accumulatedContent.trim()) {
+ setChatMessages(prev => [
+ ...prev,
+ {
+ role: 'assistant',
+ content: accumulatedContent.trim(),
+ timestamp: new Date(),
+ agentName: `Team (${teamMembers.length} agents)`,
+ },
+ ]);
+ setTestResult({ success: true, response: accumulatedContent.trim() });
+ setSuccess('Team executed successfully');
+ setTimeout(() => setSuccess(null), 3000);
+ }
+ setExecuting(false);
+ setIsStreaming(false);
+ setStreamingContent('');
+ }, 500);
- if (result.success) {
- setSuccess('Team executed successfully');
- setTimeout(() => setSuccess(null), 3000);
- }
} catch (err: any) {
setError(err.toString());
- } finally {
setExecuting(false);
+ setIsStreaming(false);
+ }
+ };
+
+ // Cancel streaming
+ const cancelStream = async () => {
+ if (activeStreamHandle) {
+ await activeStreamHandle.cancel();
+ setActiveStreamHandle(null);
+ setIsStreaming(false);
+ setExecuting(false);
+ setStreamingContent('');
}
};
- const runWorkflow = async (workflowType: string) => {
+ const runWorkflow = async (workflowType: string, extraParams?: Record<string, any>) => {
setExecuting(true);
setError(null);
@@ -751,6 +942,57 @@ const AgentConfigTab: React.FC = () => {
case 'risk_assessment':
result = await agentService.runRiskAssessment({ holdings: [] }, apiKeys);
break;
+ case 'portfolio_plan':
+ result = await agentService.createPortfolioPlan(
+ extraParams?.portfolio_id || 'default'
+ );
+ break;
+ case 'paper_trade': {
+ const symbol = extraParams?.symbol || workflowSymbol || 'AAPL';
+ result = await agentService.paperExecuteTrade(
+ extraParams?.portfolio_id || 'paper-default',
+ symbol,
+ extraParams?.action || 'buy',
+ extraParams?.quantity || 10,
+ extraParams?.price || 150
+ );
+ break;
+ }
+ case 'paper_portfolio':
+ result = await agentService.paperGetPortfolio(
+ extraParams?.portfolio_id || 'paper-default'
+ );
+ break;
+ case 'paper_positions':
+ result = await agentService.paperGetPositions(
+ extraParams?.portfolio_id || 'paper-default'
+ );
+ break;
+ case 'save_session':
+ result = await agentService.saveSession({
+ agent_id: selectedAgent?.id || 'default',
+ messages: chatMessages.map(m => ({ role: m.role, content: m.content })),
+ });
+ break;
+ case 'save_memory':
+ result = await agentService.saveMemoryRepo(
+ extraParams?.content || testQuery,
+ { type: extraParams?.category || 'general' }
+ );
+ break;
+ case 'search_memories':
+ result = await agentService.searchMemoriesRepo(
+ extraParams?.query || testQuery,
+ undefined,
+ extraParams?.limit || 10
+ );
+ break;
+ case 'multi_query':
+ result = await agentService.executeMultiQuery(
+ extraParams?.query || testQuery,
+ apiKeys
+ );
+ break;
default:
throw new Error(`Unknown workflow: ${workflowType}`);
}
@@ -1083,49 +1325,253 @@ const AgentConfigTab: React.FC = () => {
</div>
</div>
- {/* Toggle Options */}
- <div style={{ display: 'flex', gap: '8px' }}>
- <button
- onClick={() => editMode && setEditedConfig(prev => ({ ...prev, enable_memory: !prev.enable_memory }))}
- style={{
- padding: '8px 12px',
- backgroundColor: editedConfig.enable_memory ? `${FINCEPT.ORANGE}20` : FINCEPT.DARK_BG,
- border: `1px solid ${editedConfig.enable_memory ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
- color: editedConfig.enable_memory ? FINCEPT.ORANGE : FINCEPT.GRAY,
- fontSize: '9px',
- fontWeight: 700,
- cursor: editMode ? 'pointer' : 'default',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- borderRadius: '2px',
- }}
- >
- {editedConfig.enable_memory ? <ToggleRight size={14} /> : <ToggleLeft size={14} />}
- MEMORY
- </button>
-
- <button
- onClick={() => editMode && setEditedConfig(prev => ({ ...prev, enable_reasoning: !prev.enable_reasoning }))}
- style={{
- padding: '8px 12px',
- backgroundColor: editedConfig.enable_reasoning ? `${FINCEPT.PURPLE}20` : FINCEPT.DARK_BG,
- border: `1px solid ${editedConfig.enable_reasoning ? FINCEPT.PURPLE : FINCEPT.BORDER}`,
- color: editedConfig.enable_reasoning ? FINCEPT.PURPLE : FINCEPT.GRAY,
- fontSize: '9px',
- fontWeight: 700,
- cursor: editMode ? 'pointer' : 'default',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- borderRadius: '2px',
- }}
- >
- {editedConfig.enable_reasoning ? <ToggleRight size={14} /> : <ToggleLeft size={14} />}
- REASONING
- </button>
+ {/* Toggle Options — All CoreAgent Features */}
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
+ {([
+ { key: 'enable_memory' as const, label: 'MEMORY', icon: Database, color: FINCEPT.ORANGE },
+ { key: 'enable_reasoning' as const, label: 'REASONING', icon: Brain, color: FINCEPT.PURPLE || '#a855f7' },
+ { key: 'enable_knowledge' as const, label: 'KNOWLEDGE', icon: BookOpen, color: '#3b82f6' },
+ { key: 'enable_guardrails' as const, label: 'GUARDRAILS', icon: Shield, color: '#ef4444' },
+ { key: 'enable_agentic_memory' as const, label: 'AGENT MEMORY', icon: Layers, color: '#f59e0b' },
+ { key: 'enable_storage' as const, label: 'STORAGE', icon: Save, color: '#10b981' },
+ { key: 'enable_tracing' as const, label: 'TRACING', icon: Activity, color: '#6366f1' },
+ { key: 'enable_compression' as const, label: 'COMPRESS', icon: Minimize2, color: '#8b5cf6' },
+ { key: 'enable_hooks' as const, label: 'HOOKS', icon: Anchor, color: '#ec4899' },
+ { key: 'enable_evaluation' as const, label: 'EVAL', icon: ClipboardCheck, color: '#14b8a6' },
+ ] as const).map(({ key, label, icon: Icon, color }) => (
+ <button
+ key={key}
+ onClick={() => editMode && setEditedConfig(prev => ({ ...prev, [key]: !prev[key] }))}
+ style={{
+ padding: '6px 10px',
+ backgroundColor: editedConfig[key] ? `${color}20` : FINCEPT.DARK_BG,
+ border: `1px solid ${editedConfig[key] ? color : FINCEPT.BORDER}`,
+ color: editedConfig[key] ? color : FINCEPT.GRAY,
+ fontSize: '8px',
+ fontWeight: 700,
+ cursor: editMode ? 'pointer' : 'default',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ borderRadius: '2px',
+ letterSpacing: '0.3px',
+ }}
+ >
+ <Icon size={11} />
+ {label}
+ </button>
+ ))}
</div>
+ {/* ─── Expandable Config Panels ─── */}
+ {editMode && (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+
+ {/* Knowledge Config Panel */}
+ {editedConfig.enable_knowledge && (
+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid #3b82f640`, borderRadius: '2px' }}>
+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: '#3b82f6', marginBottom: '8px', letterSpacing: '0.5px' }}>
+ <BookOpen size={10} style={{ marginRight: '4px', verticalAlign: 'middle' }} />
+ KNOWLEDGE BASE CONFIG
+ </label>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
+ <div>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>TYPE</label>
+ <select
+ value={editedConfig.knowledge_type}
+ onChange={e => setEditedConfig(prev => ({ ...prev, knowledge_type: e.target.value as any }))}
+ style={{ width: '100%', padding: '5px 8px', backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}
+ >
+ <option value="url">URL</option>
+ <option value="pdf">PDF</option>
+ <option value="text">Text</option>
+ <option value="combined">Combined</option>
+ </select>
+ </div>
+ <div>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>VECTOR DB</label>
+ <select
+ value={editedConfig.knowledge_vector_db}
+ onChange={e => setEditedConfig(prev => ({ ...prev, knowledge_vector_db: e.target.value }))}
+ style={{ width: '100%', padding: '5px 8px', backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}
+ >
+ <option value="lancedb">LanceDB</option>
+ <option value="pgvector">PgVector</option>
+ <option value="qdrant">Qdrant</option>
+ </select>
+ </div>
+ </div>
+ <div style={{ marginTop: '8px' }}>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>
+ {editedConfig.knowledge_type === 'url' ? 'URLS (one per line)' : editedConfig.knowledge_type === 'pdf' ? 'PDF PATHS (one per line)' : 'KNOWLEDGE TEXT / PATHS'}
+ </label>
+ <textarea
+ value={editedConfig.knowledge_urls}
+ onChange={e => setEditedConfig(prev => ({ ...prev, knowledge_urls: e.target.value }))}
+ rows={3}
+ placeholder={editedConfig.knowledge_type === 'url' ? 'https://example.com/docs\nhttps://example.com/api' : 'Enter paths or text...'}
+ style={{ width: '100%', padding: '8px', backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace', resize: 'none' }}
+ />
+ </div>
+ <div style={{ marginTop: '8px' }}>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>EMBEDDER</label>
+ <select
+ value={editedConfig.knowledge_embedder}
+ onChange={e => setEditedConfig(prev => ({ ...prev, knowledge_embedder: e.target.value }))}
+ style={{ width: '100%', padding: '5px 8px', backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}
+ >
+ <option value="openai">OpenAI</option>
+ <option value="ollama">Ollama</option>
+ <option value="huggingface">HuggingFace</option>
+ </select>
+ </div>
+ </div>
+ )}
+
+ {/* Guardrails Config Panel */}
+ {editedConfig.enable_guardrails && (
+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid #ef444440`, borderRadius: '2px' }}>
+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: '#ef4444', marginBottom: '8px', letterSpacing: '0.5px' }}>
+ <Shield size={10} style={{ marginRight: '4px', verticalAlign: 'middle' }} />
+ GUARDRAILS CONFIG
+ </label>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
+ {([
+ { key: 'guardrails_pii' as const, label: 'PII Detection', desc: 'Detect and redact personal information' },
+ { key: 'guardrails_injection' as const, label: 'Injection Check', desc: 'Block prompt injection attempts' },
+ { key: 'guardrails_compliance' as const, label: 'Financial Compliance', desc: 'Enforce financial regulation rules' },
+ ] as const).map(({ key, label, desc }) => (
+ <div
+ key={key}
+ onClick={() => setEditedConfig(prev => ({ ...prev, [key]: !prev[key] }))}
+ style={{
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
+ padding: '6px 8px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px', cursor: 'pointer',
+ }}
+ >
+ <div>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: editedConfig[key] ? '#ef4444' : FINCEPT.GRAY }}>{label}</div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED }}>{desc}</div>
+ </div>
+ <div style={{ width: '28px', height: '14px', borderRadius: '7px', backgroundColor: editedConfig[key] ? '#ef4444' : FINCEPT.BORDER, position: 'relative', transition: 'background 0.2s' }}>
+ <div style={{ width: '10px', height: '10px', borderRadius: '50%', backgroundColor: FINCEPT.WHITE, position: 'absolute', top: '2px', left: editedConfig[key] ? '16px' : '2px', transition: 'left 0.2s' }} />
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Storage Config Panel */}
+ {editedConfig.enable_storage && (
+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid #10b98140`, borderRadius: '2px' }}>
+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: '#10b981', marginBottom: '8px', letterSpacing: '0.5px' }}>
+ <Save size={10} style={{ marginRight: '4px', verticalAlign: 'middle' }} />
+ STORAGE CONFIG
+ </label>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
+ <div>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>TYPE</label>
+ <select
+ value={editedConfig.storage_type}
+ onChange={e => setEditedConfig(prev => ({ ...prev, storage_type: e.target.value as any }))}
+ style={{ width: '100%', padding: '5px 8px', backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}
+ >
+ <option value="sqlite">SQLite</option>
+ <option value="postgres">PostgreSQL</option>
+ </select>
+ </div>
+ <div>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>TABLE NAME</label>
+ <input
+ value={editedConfig.storage_table}
+ onChange={e => setEditedConfig(prev => ({ ...prev, storage_table: e.target.value }))}
+ placeholder="agent_sessions"
+ style={{ width: '100%', padding: '5px 8px', backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}
+ />
+ </div>
+ </div>
+ <div style={{ marginTop: '8px' }}>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>DB PATH (leave empty for default)</label>
+ <input
+ value={editedConfig.storage_db_path}
+ onChange={e => setEditedConfig(prev => ({ ...prev, storage_db_path: e.target.value }))}
+ placeholder="tmp/agent_storage.db"
+ style={{ width: '100%', padding: '5px 8px', backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}
+ />
+ </div>
+ </div>
+ )}
+
+ {/* Memory Config Panel */}
+ {editedConfig.enable_memory && (
+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.ORANGE}40`, borderRadius: '2px' }}>
+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.ORANGE, marginBottom: '8px', letterSpacing: '0.5px' }}>
+ <Database size={10} style={{ marginRight: '4px', verticalAlign: 'middle' }} />
+ MEMORY CONFIG
+ </label>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
+ <div>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>DB PATH</label>
+ <input
+ value={editedConfig.memory_db_path}
+ onChange={e => setEditedConfig(prev => ({ ...prev, memory_db_path: e.target.value }))}
+ placeholder="tmp/agent_memory.db"
+ style={{ width: '100%', padding: '5px 8px', backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}
+ />
+ </div>
+ <div>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>TABLE</label>
+ <input
+ value={editedConfig.memory_table}
+ onChange={e => setEditedConfig(prev => ({ ...prev, memory_table: e.target.value }))}
+ placeholder="agent_memory"
+ style={{ width: '100%', padding: '5px 8px', backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}
+ />
+ </div>
+ </div>
+ <div style={{ display: 'flex', gap: '12px', marginTop: '8px' }}>
+ {([
+ { key: 'memory_create_user_memories' as const, label: 'User Memories' },
+ { key: 'memory_create_session_summary' as const, label: 'Session Summary' },
+ ] as const).map(({ key, label }) => (
+ <div
+ key={key}
+ onClick={() => setEditedConfig(prev => ({ ...prev, [key]: !prev[key] }))}
+ style={{ display: 'flex', alignItems: 'center', gap: '6px', cursor: 'pointer' }}
+ >
+ <div style={{ width: '24px', height: '12px', borderRadius: '6px', backgroundColor: editedConfig[key] ? FINCEPT.ORANGE : FINCEPT.BORDER, position: 'relative', transition: 'background 0.2s' }}>
+ <div style={{ width: '8px', height: '8px', borderRadius: '50%', backgroundColor: FINCEPT.WHITE, position: 'absolute', top: '2px', left: editedConfig[key] ? '14px' : '2px', transition: 'left 0.2s' }} />
+ </div>
+ <span style={{ fontSize: '8px', fontWeight: 700, color: editedConfig[key] ? FINCEPT.ORANGE : FINCEPT.GRAY }}>{label}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Agentic Memory Config Panel */}
+ {editedConfig.enable_agentic_memory && (
+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid #f59e0b40`, borderRadius: '2px' }}>
+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: '#f59e0b', marginBottom: '8px', letterSpacing: '0.5px' }}>
+ <Layers size={10} style={{ marginRight: '4px', verticalAlign: 'middle' }} />
+ AGENTIC MEMORY CONFIG
+ </label>
+ <div>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>USER ID (for persistent cross-session memory)</label>
+ <input
+ value={editedConfig.agentic_memory_user_id}
+ onChange={e => setEditedConfig(prev => ({ ...prev, agentic_memory_user_id: e.target.value }))}
+ placeholder="user-001"
+ style={{ width: '100%', padding: '5px 8px', backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
{/* Instructions */}
{editMode && (
<div>
@@ -1843,29 +2289,78 @@ const AgentConfigTab: React.FC = () => {
padding: '12px',
backgroundColor: FINCEPT.HEADER_BG,
borderBottom: `1px solid ${FINCEPT.BORDER}`,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
}}>
- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
- TEAM ({teamMembers.length})
- </span>
- <select
- value={teamMode}
- onChange={e => setTeamMode(e.target.value as any)}
- style={{
- padding: '4px 8px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '2px',
- fontSize: '9px',
- }}
- >
- <option value="coordinate">SEQUENTIAL</option>
- <option value="route">ROUTE</option>
- <option value="collaborate">PARALLEL</option>
- </select>
+ {/* Row 1: Team count + mode selector */}
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
+ TEAM ({teamMembers.length})
+ </span>
+ <select
+ value={teamMode}
+ onChange={e => setTeamMode(e.target.value as any)}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ }}
+ >
+ <option value="coordinate">DELEGATE</option>
+ <option value="route">ROUTE</option>
+ <option value="collaborate">COLLABORATE</option>
+ </select>
+ </div>
+ {/* Row 2: Leader selector + show responses toggle */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ {/* Leader selector */}
+ <select
+ value={teamLeaderIndex}
+ onChange={e => setTeamLeaderIndex(parseInt(e.target.value))}
+ style={{
+ flex: 1,
+ padding: '4px 6px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: teamLeaderIndex >= 0 ? FINCEPT.ORANGE : FINCEPT.GRAY,
+ border: `1px solid ${teamLeaderIndex >= 0 ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '8px',
+ }}
+ >
+ <option value={-1}>NO LEADER</option>
+ {teamMembers.map((m, i) => (
+ <option key={i} value={i}>{m.name.toUpperCase()}</option>
+ ))}
+ </select>
+ {/* Show members responses toggle */}
+ <button
+ onClick={() => setShowMembersResponses(prev => !prev)}
+ title="Show individual member responses"
+ style={{
+ padding: '4px 8px',
+ backgroundColor: showMembersResponses ? `${FINCEPT.ORANGE}20` : FINCEPT.DARK_BG,
+ border: `1px solid ${showMembersResponses ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ color: showMembersResponses ? FINCEPT.ORANGE : FINCEPT.GRAY,
+ fontSize: '8px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ borderRadius: '2px',
+ }}
+ >
+ <Eye size={10} />
+ SHOW ALL
+ </button>
+ </div>
+ {/* Mode description */}
+ <div style={{ marginTop: '6px', fontSize: '8px', color: FINCEPT.GRAY, fontStyle: 'italic' }}>
+ {teamMode === 'coordinate' && 'Leader delegates tasks to chosen members'}
+ {teamMode === 'route' && 'Routes query to the most appropriate member'}
+ {teamMode === 'collaborate' && 'All members receive the task and discuss consensus'}
+ </div>
</div>
{/* Team Members List */}
@@ -2078,7 +2573,42 @@ const AgentConfigTab: React.FC = () => {
</span>
</div>
<div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
- {testResult ? (
+ {isStreaming && streamingContent ? (
+ // Show streaming content in real-time
+ <div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ padding: '8px',
+ backgroundColor: FINCEPT.ORANGE + '15',
+ borderRadius: '4px',
+ borderLeft: `3px solid ${FINCEPT.ORANGE}`,
+ }}>
+ <Loader2 size={14} className="animate-spin" style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ fontSize: '10px', color: FINCEPT.ORANGE, fontWeight: 600 }}>
+ Streaming response...
+ </span>
+ <button
+ onClick={cancelStream}
+ style={{
+ marginLeft: 'auto',
+ padding: '4px 8px',
+ fontSize: '9px',
+ backgroundColor: FINCEPT.RED + '20',
+ color: FINCEPT.RED,
+ border: `1px solid ${FINCEPT.RED}40`,
+ borderRadius: '3px',
+ cursor: 'pointer',
+ }}
+ >
+ Cancel
+ </button>
+ </div>
+ <MarkdownRenderer content={streamingContent} />
+ </div>
+ ) : testResult ? (
<MarkdownRenderer
content={extractAgentResponseText(
typeof testResult === 'string' ? testResult : (testResult.response || JSON.stringify(testResult, null, 2))
@@ -2276,6 +2806,113 @@ const AgentConfigTab: React.FC = () => {
ASSESS RISK
</button>
</div>
+
+ {/* Portfolio Plan */}
+ <div style={{ padding: '16px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
+ <Target size={16} style={{ color: FINCEPT.GREEN }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>PORTFOLIO PLAN</span>
+ </div>
+ <p style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '12px', lineHeight: 1.4 }}>
+ Generate an AI-powered investment plan based on goals and risk profile.
+ </p>
+ <button
+ onClick={() => runWorkflow('portfolio_plan', { goals: 'Balanced growth', budget: 100000, risk_tolerance: 'moderate' })}
+ disabled={executing}
+ style={{ width: '100%', padding: '8px', backgroundColor: FINCEPT.GREEN, color: FINCEPT.DARK_BG, border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: executing ? 'not-allowed' : 'pointer', opacity: executing ? 0.7 : 1 }}
+ >
+ CREATE PLAN
+ </button>
+ </div>
+
+ {/* Paper Trading */}
+ <div style={{ padding: '16px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
+ <FileJson size={16} style={{ color: FINCEPT.CYAN }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>PAPER TRADING</span>
+ </div>
+ <div style={{ display: 'flex', gap: '6px', marginBottom: '8px' }}>
+ <button
+ onClick={() => runWorkflow('paper_trade', { symbol: workflowSymbol, action: 'buy', quantity: 10, price: 150 })}
+ disabled={executing}
+ style={{ flex: 1, padding: '6px', backgroundColor: `${FINCEPT.GREEN}30`, color: FINCEPT.GREEN, border: `1px solid ${FINCEPT.GREEN}60`, borderRadius: '2px', fontSize: '8px', fontWeight: 700, cursor: executing ? 'not-allowed' : 'pointer' }}
+ >
+ BUY {workflowSymbol || 'AAPL'}
+ </button>
+ <button
+ onClick={() => runWorkflow('paper_trade', { symbol: workflowSymbol, action: 'sell', quantity: 10, price: 150 })}
+ disabled={executing}
+ style={{ flex: 1, padding: '6px', backgroundColor: `${FINCEPT.RED}30`, color: FINCEPT.RED, border: `1px solid ${FINCEPT.RED}60`, borderRadius: '2px', fontSize: '8px', fontWeight: 700, cursor: executing ? 'not-allowed' : 'pointer' }}
+ >
+ SELL {workflowSymbol || 'AAPL'}
+ </button>
+ </div>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={() => runWorkflow('paper_portfolio')}
+ disabled={executing}
+ style={{ flex: 1, padding: '6px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.CYAN, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '8px', fontWeight: 700, cursor: executing ? 'not-allowed' : 'pointer' }}
+ >
+ PORTFOLIO
+ </button>
+ <button
+ onClick={() => runWorkflow('paper_positions')}
+ disabled={executing}
+ style={{ flex: 1, padding: '6px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.CYAN, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '8px', fontWeight: 700, cursor: executing ? 'not-allowed' : 'pointer' }}
+ >
+ POSITIONS
+ </button>
+ </div>
+ </div>
+
+ {/* Session & Memory */}
+ <div style={{ padding: '16px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
+ <Database size={16} style={{ color: FINCEPT.YELLOW }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>SESSION & MEMORY</span>
+ </div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
+ <button
+ onClick={() => runWorkflow('save_session', { session_id: `session-${Date.now()}` })}
+ disabled={executing}
+ style={{ width: '100%', padding: '6px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.YELLOW, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '8px', fontWeight: 700, cursor: executing ? 'not-allowed' : 'pointer' }}
+ >
+ SAVE CURRENT SESSION
+ </button>
+ <button
+ onClick={() => runWorkflow('save_memory', { content: testQuery || 'Important note', category: 'general' })}
+ disabled={executing}
+ style={{ width: '100%', padding: '6px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.YELLOW, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '8px', fontWeight: 700, cursor: executing ? 'not-allowed' : 'pointer' }}
+ >
+ SAVE TO MEMORY
+ </button>
+ <button
+ onClick={() => runWorkflow('search_memories', { query: testQuery || 'recent analysis' })}
+ disabled={executing}
+ style={{ width: '100%', padding: '6px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.YELLOW, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '8px', fontWeight: 700, cursor: executing ? 'not-allowed' : 'pointer' }}
+ >
+ SEARCH MEMORIES
+ </button>
+ </div>
+ </div>
+
+ {/* Multi-Query */}
+ <div style={{ padding: '16px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
+ <Route size={16} style={{ color: FINCEPT.BLUE }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>MULTI-QUERY</span>
+ </div>
+ <p style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '12px', lineHeight: 1.4 }}>
+ Route your query to multiple agents simultaneously for parallel analysis.
+ </p>
+ <button
+ onClick={() => runWorkflow('multi_query', { query: testQuery })}
+ disabled={executing || !testQuery.trim()}
+ style={{ width: '100%', padding: '8px', backgroundColor: FINCEPT.BLUE, color: FINCEPT.WHITE, border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: (executing || !testQuery.trim()) ? 'not-allowed' : 'pointer', opacity: (executing || !testQuery.trim()) ? 0.7 : 1 }}
+ >
+ EXECUTE MULTI-QUERY
+ </button>
+ </div>
</div>
</div>
@@ -2880,13 +3517,7 @@ const AgentConfigTab: React.FC = () => {
editedConfig.provider,
editedConfig.model_id,
editedConfig.instructions,
- {
- tools: selectedTools.length > 0 ? selectedTools : editedConfig.tools,
- temperature: editedConfig.temperature,
- maxTokens: editedConfig.max_tokens,
- memory: editedConfig.enable_memory,
- reasoning: editedConfig.enable_reasoning,
- }
+ buildDetailedConfigOptions()
);
if (useAutoRouting) {
diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/RenaissanceTechnologiesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/agent-config/RenaissanceTechnologiesPanel.tsx
index ec6bb3ac3..c00bcd48d 100644
--- a/fincept-terminal-desktop/src/components/tabs/agent-config/RenaissanceTechnologiesPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/RenaissanceTechnologiesPanel.tsx
@@ -74,6 +74,11 @@ interface ICDeliberationResult {
vote_summary: Record<string, number>;
approved_size_pct?: number;
conditions?: string[];
+ llm_config?: {
+ provider: string;
+ model_id: string;
+ temperature: number;
+ };
}
interface ICVote {
@@ -152,19 +157,13 @@ export default function RenaissanceTechnologiesPanel() {
setAnalysisResult(null);
try {
- const signalData = {
+ // Send only user inputs - backend will calculate signal metrics from real data
+ const cliInput = {
ticker,
signal_type: signalType,
- direction: 'long',
- strength: 0.75,
- confidence: 0.65,
- p_value: 0.008,
- information_coefficient: 0.05,
- };
-
- const cliInput = {
- signal: signalData,
- config: riskLimits,
+ trade_value: 1_000_000, // Default $1M trade
+ period: '1y',
+ include_deliberation: true, // Include IC deliberation
};
const result = await invoke<string>('execute_renaissance_cli', {
@@ -259,8 +258,20 @@ export default function RenaissanceTechnologiesPanel() {
</div>
</div>
- {/* Right: Time & Status */}
+ {/* Right: Time, LLM Status & System Status */}
<div style={{ display: 'flex', alignItems: 'center', gap: SPACING.MEDIUM }}>
+ {/* LLM Config Display */}
+ {analysisResult?.ic_decision?.llm_config && (
+ <>
+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>
+ <Cpu size={12} color={FINCEPT.CYAN} />
+ <span style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.CYAN }}>
+ {analysisResult.ic_decision.llm_config.provider.toUpperCase()}/{analysisResult.ic_decision.llm_config.model_id}
+ </span>
+ </div>
+ <div style={COMMON_STYLES.verticalDivider} />
+ </>
+ )}
<div style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>
<Clock size={12} color={FINCEPT.GRAY} />
<span style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.GRAY }}>
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsx
index a1adfa2dc..6c60b14c7 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsx
@@ -35,6 +35,7 @@ import {
Server
} from 'lucide-react';
import { TabFooter } from '@/components/common/TabFooter';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
// Sub-components
import { FactorDiscoveryPanel } from './FactorDiscoveryPanel';
@@ -54,25 +55,6 @@ import { MetaLearningPanel } from './MetaLearningPanel';
import { RollingRetrainingPanel } from './RollingRetrainingPanel';
import { AdvancedModelsPanel } from './AdvancedModelsPanel';
-// Fincept Terminal Color Palette
-const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- BLUE: '#0088FF',
- PURPLE: '#9D4EDD',
- MAGENTA: '#E91E8C',
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F',
- MUTED: '#4A4A4A'
-};
type ViewMode = 'factor_discovery' | 'model_library' | 'backtesting' | 'live_signals' | 'ffn_analytics' | 'functime' | 'fortitudo' | 'statsmodels' | 'cfa_quant' | 'deep_agent' | 'rl_trading' | 'online_learning' | 'hft' | 'meta_learning' | 'rolling_retraining' | 'advanced_models';
@@ -186,36 +168,51 @@ function aiQuantLabReducer(state: AIQuantLabState, action: AIQuantLabAction): AI
}
export default function AIQuantLabTab() {
+ // Theme hook
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+
// State management with useReducer (atomic updates)
const [state, dispatch] = useReducer(aiQuantLabReducer, initialState);
const [currentTime, setCurrentTime] = useState(new Date());
const [deepAgentOutput, setDeepAgentOutput] = useState<DeepAgentOutput | null>(null);
+ // Theme-derived colors for module categories
+ const moduleColors = {
+ purple: colors.accent || '#9D4EDD',
+ blue: colors.info || '#0088FF',
+ orange: colors.primary,
+ green: colors.success,
+ cyan: colors.accent || '#00E5FF',
+ yellow: colors.warning,
+ magenta: '#E91E8C',
+ red: colors.alert,
+ };
+
// Modules organized by category
const modules: ModuleItem[] = [
// Core
- { id: 'factor_discovery', label: 'Factor Discovery', shortLabel: 'FACTOR', icon: Sparkles, category: 'Core', color: FINCEPT.PURPLE },
- { id: 'model_library', label: 'Model Library', shortLabel: 'MODELS', icon: Brain, category: 'Core', color: FINCEPT.BLUE },
- { id: 'backtesting', label: 'Backtesting', shortLabel: 'BACKTEST', icon: BarChart3, category: 'Core', color: FINCEPT.ORANGE },
- { id: 'live_signals', label: 'Live Signals', shortLabel: 'SIGNALS', icon: Activity, category: 'Core', color: FINCEPT.GREEN },
+ { id: 'factor_discovery', label: 'Factor Discovery', shortLabel: 'FACTOR', icon: Sparkles, category: 'Core', color: moduleColors.purple },
+ { id: 'model_library', label: 'Model Library', shortLabel: 'MODELS', icon: Brain, category: 'Core', color: moduleColors.blue },
+ { id: 'backtesting', label: 'Backtesting', shortLabel: 'BACKTEST', icon: BarChart3, category: 'Core', color: moduleColors.orange },
+ { id: 'live_signals', label: 'Live Signals', shortLabel: 'SIGNALS', icon: Activity, category: 'Core', color: moduleColors.green },
// AI/ML
- { id: 'deep_agent', label: 'Deep Agent', shortLabel: 'AGENT', icon: Brain, category: 'AI/ML', color: FINCEPT.CYAN },
- { id: 'rl_trading', label: 'RL Trading', shortLabel: 'RL', icon: Target, category: 'AI/ML', color: FINCEPT.PURPLE },
- { id: 'online_learning', label: 'Online Learning', shortLabel: 'ONLINE', icon: Zap, category: 'AI/ML', color: FINCEPT.YELLOW },
- { id: 'meta_learning', label: 'Meta Learning', shortLabel: 'META', icon: Layers, category: 'AI/ML', color: FINCEPT.MAGENTA },
+ { id: 'deep_agent', label: 'Deep Agent', shortLabel: 'AGENT', icon: Brain, category: 'AI/ML', color: moduleColors.cyan },
+ { id: 'rl_trading', label: 'RL Trading', shortLabel: 'RL', icon: Target, category: 'AI/ML', color: moduleColors.purple },
+ { id: 'online_learning', label: 'Online Learning', shortLabel: 'ONLINE', icon: Zap, category: 'AI/ML', color: moduleColors.yellow },
+ { id: 'meta_learning', label: 'Meta Learning', shortLabel: 'META', icon: Layers, category: 'AI/ML', color: moduleColors.magenta },
// Advanced
- { id: 'hft', label: 'High Frequency Trading', shortLabel: 'HFT', icon: Activity, category: 'Advanced', color: FINCEPT.RED },
- { id: 'rolling_retraining', label: 'Rolling Retraining', shortLabel: 'RETRAIN', icon: RefreshCw, category: 'Advanced', color: FINCEPT.CYAN },
- { id: 'advanced_models', label: 'Advanced Models', shortLabel: 'ADV', icon: Brain, category: 'Advanced', color: FINCEPT.PURPLE },
+ { id: 'hft', label: 'High Frequency Trading', shortLabel: 'HFT', icon: Activity, category: 'Advanced', color: moduleColors.red },
+ { id: 'rolling_retraining', label: 'Rolling Retraining', shortLabel: 'RETRAIN', icon: RefreshCw, category: 'Advanced', color: moduleColors.cyan },
+ { id: 'advanced_models', label: 'Advanced Models', shortLabel: 'ADV', icon: Brain, category: 'Advanced', color: moduleColors.purple },
// Analytics
- { id: 'ffn_analytics', label: 'FFN Analytics', shortLabel: 'FFN', icon: TrendingUp, category: 'Analytics', color: FINCEPT.GREEN },
- { id: 'functime', label: 'Functime', shortLabel: 'FUNC', icon: Zap, category: 'Analytics', color: FINCEPT.YELLOW },
- { id: 'fortitudo', label: 'Fortitudo', shortLabel: 'FORT', icon: Database, category: 'Analytics', color: FINCEPT.BLUE },
- { id: 'statsmodels', label: 'Statsmodels', shortLabel: 'STATS', icon: Sigma, category: 'Analytics', color: FINCEPT.CYAN },
- { id: 'cfa_quant', label: 'CFA Quant', shortLabel: 'CFA', icon: Calculator, category: 'Analytics', color: FINCEPT.ORANGE }
+ { id: 'ffn_analytics', label: 'FFN Analytics', shortLabel: 'FFN', icon: TrendingUp, category: 'Analytics', color: moduleColors.green },
+ { id: 'functime', label: 'Functime', shortLabel: 'FUNC', icon: Zap, category: 'Analytics', color: moduleColors.yellow },
+ { id: 'fortitudo', label: 'Fortitudo', shortLabel: 'FORT', icon: Database, category: 'Analytics', color: moduleColors.blue },
+ { id: 'statsmodels', label: 'Statsmodels', shortLabel: 'STATS', icon: Sigma, category: 'Analytics', color: moduleColors.cyan },
+ { id: 'cfa_quant', label: 'CFA Quant', shortLabel: 'CFA', icon: Calculator, category: 'Analytics', color: moduleColors.orange }
];
const activeModule = modules.find(m => m.id === state.activeView) || modules[0];
@@ -236,22 +233,22 @@ export default function AIQuantLabTab() {
}, [state.showModuleDropdown]);
return (
- <div className="flex flex-col h-full" style={{ backgroundColor: FINCEPT.DARK_BG, fontFamily: 'system-ui, -apple-system, sans-serif' }}>
+ <div className="flex flex-col h-full" style={{ backgroundColor: colors.background, fontFamily }}>
{/* ===== TOP NAVIGATION BAR ===== */}
<div
className="flex items-center justify-between px-3 py-2.5 border-b"
- style={{ backgroundColor: FINCEPT.HEADER_BG, borderColor: FINCEPT.BORDER, height: '48px' }}
+ style={{ backgroundColor: colors.panel, borderColor: 'var(--ft-border-color, #2A2A2A)', height: '48px' }}
>
{/* Left: Branding + Module Selector */}
<div className="flex items-center gap-3">
- <div className="flex items-center gap-2 px-3 py-1.5" style={{ backgroundColor: FINCEPT.ORANGE }}>
- <Brain size={16} color={FINCEPT.DARK_BG} />
- <span className="font-bold text-xs tracking-wider" style={{ color: FINCEPT.DARK_BG }}>
+ <div className="flex items-center gap-2 px-3 py-1.5" style={{ backgroundColor: colors.primary }}>
+ <Brain size={16} color={colors.background} />
+ <span className="font-bold text-xs tracking-wider" style={{ color: colors.background }}>
AI QUANT LAB
</span>
</div>
- <div className="h-5 w-px" style={{ backgroundColor: FINCEPT.BORDER }} />
+ <div className="h-5 w-px" style={{ backgroundColor: 'var(--ft-border-color, #2A2A2A)' }} />
{/* Module Selector Dropdown */}
<div className="relative">
@@ -262,12 +259,12 @@ export default function AIQuantLabTab() {
}}
className="flex items-center gap-2 px-3 py-1.5 text-xs font-semibold tracking-wide transition-colors"
style={{
- backgroundColor: FINCEPT.PANEL_BG,
+ backgroundColor: colors.panel,
color: activeModule.color,
- border: `1px solid ${FINCEPT.BORDER}`
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
- onMouseEnter={(e) => e.currentTarget.style.backgroundColor = FINCEPT.HOVER}
- onMouseLeave={(e) => e.currentTarget.style.backgroundColor = FINCEPT.PANEL_BG}
+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#1F1F1F'}
+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = colors.panel}
>
<activeModule.icon size={14} />
<span>{activeModule.shortLabel}</span>
@@ -279,17 +276,17 @@ export default function AIQuantLabTab() {
<div
className="absolute top-full left-0 mt-1 z-50"
style={{
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
minWidth: '220px',
maxHeight: '400px',
overflowY: 'auto',
- boxShadow: `0 4px 12px ${FINCEPT.DARK_BG}80`
+ boxShadow: `0 4px 12px ${colors.background}80`
}}
>
{['Core', 'AI/ML', 'Advanced', 'Analytics'].map((category) => (
<div key={category}>
- <div className="px-2 py-1.5 text-[10px] font-bold tracking-wider" style={{ color: FINCEPT.MUTED, backgroundColor: FINCEPT.DARK_BG }}>
+ <div className="px-2 py-1.5 text-[10px] font-bold tracking-wider" style={{ color: colors.textMuted, backgroundColor: colors.background }}>
{category}
</div>
{modules.filter(m => m.category === category).map((mod) => {
@@ -300,12 +297,12 @@ export default function AIQuantLabTab() {
onClick={() => dispatch({ type: 'SET_ACTIVE_VIEW', payload: mod.id })}
className="w-full flex items-center gap-2 px-3 py-2 text-xs transition-colors"
style={{
- backgroundColor: state.activeView === mod.id ? FINCEPT.HOVER : 'transparent',
- color: state.activeView === mod.id ? mod.color : FINCEPT.GRAY,
+ backgroundColor: state.activeView === mod.id ? '#1F1F1F' : 'transparent',
+ color: state.activeView === mod.id ? mod.color : colors.textMuted,
borderLeft: state.activeView === mod.id ? `2px solid ${mod.color}` : '2px solid transparent'
}}
onMouseEnter={(e) => {
- if (state.activeView !== mod.id) e.currentTarget.style.backgroundColor = `${FINCEPT.HOVER}80`;
+ if (state.activeView !== mod.id) e.currentTarget.style.backgroundColor = `${'#1F1F1F'}80`;
}}
onMouseLeave={(e) => {
if (state.activeView !== mod.id) e.currentTarget.style.backgroundColor = 'transparent';
@@ -322,7 +319,7 @@ export default function AIQuantLabTab() {
)}
</div>
- <div className="text-[11px]" style={{ color: FINCEPT.GRAY }}>
+ <div className="text-[11px]" style={{ color: colors.textMuted }}>
Microsoft Qlib + RD-Agent
</div>
</div>
@@ -330,23 +327,23 @@ export default function AIQuantLabTab() {
{/* Right: Status Indicators + Actions */}
<div className="flex items-center gap-3">
{/* Clock */}
- <div className="text-xs font-mono px-2" style={{ color: FINCEPT.GRAY }}>
+ <div className="text-xs font-mono px-2" style={{ color: colors.textMuted }}>
{currentTime.toLocaleTimeString('en-US', { hour12: false })}
</div>
- <div className="h-5 w-px" style={{ backgroundColor: FINCEPT.BORDER }} />
+ <div className="h-5 w-px" style={{ backgroundColor: 'var(--ft-border-color, #2A2A2A)' }} />
{/* System Status Badge */}
{state.systemStatus.status === 'loading' && (
- <div className="flex items-center gap-1.5 px-2.5 py-1 text-xs font-mono" style={{ border: `1px solid ${FINCEPT.YELLOW}` }}>
- <RefreshCw size={12} color={FINCEPT.YELLOW} className="animate-spin" />
- <span style={{ color: FINCEPT.YELLOW }}>LOADING...</span>
+ <div className="flex items-center gap-1.5 px-2.5 py-1 text-xs font-mono" style={{ border: `1px solid ${colors.warning}` }}>
+ <RefreshCw size={12} color={colors.warning} className="animate-spin" />
+ <span style={{ color: colors.warning }}>LOADING...</span>
</div>
)}
{state.systemStatus.status === 'error' && (
- <div className="flex items-center gap-1.5 px-2.5 py-1 text-xs font-mono" style={{ border: `1px solid ${FINCEPT.RED}` }}>
- <AlertCircle size={12} color={FINCEPT.RED} />
- <span style={{ color: FINCEPT.RED }}>ERROR</span>
+ <div className="flex items-center gap-1.5 px-2.5 py-1 text-xs font-mono" style={{ border: `1px solid ${colors.alert}` }}>
+ <AlertCircle size={12} color={colors.alert} />
+ <span style={{ color: colors.alert }}>ERROR</span>
</div>
)}
{state.systemStatus.status === 'ready' && (
@@ -354,16 +351,16 @@ export default function AIQuantLabTab() {
<div
className="flex items-center gap-1.5 px-2.5 py-1 text-xs font-mono"
style={{
- backgroundColor: state.systemStatus.qlib.available ? `${FINCEPT.GREEN}20` : FINCEPT.DARK_BG,
- border: `1px solid ${state.systemStatus.qlib.available ? FINCEPT.GREEN : FINCEPT.RED}`
+ backgroundColor: state.systemStatus.qlib.available ? `${colors.success}20` : colors.background,
+ border: `1px solid ${state.systemStatus.qlib.available ? colors.success : colors.alert}`
}}
>
{state.systemStatus.qlib.available ? (
- <CheckCircle2 size={12} color={FINCEPT.GREEN} />
+ <CheckCircle2 size={12} color={colors.success} />
) : (
- <AlertCircle size={12} color={FINCEPT.RED} />
+ <AlertCircle size={12} color={colors.alert} />
)}
- <span style={{ color: state.systemStatus.qlib.available ? FINCEPT.GREEN : FINCEPT.RED }}>
+ <span style={{ color: state.systemStatus.qlib.available ? colors.success : colors.alert }}>
QLIB
</span>
</div>
@@ -371,16 +368,16 @@ export default function AIQuantLabTab() {
<div
className="flex items-center gap-1.5 px-2.5 py-1 text-xs font-mono"
style={{
- backgroundColor: state.systemStatus.rdagent.available ? `${FINCEPT.CYAN}20` : FINCEPT.DARK_BG,
- border: `1px solid ${state.systemStatus.rdagent.available ? FINCEPT.CYAN : FINCEPT.RED}`
+ backgroundColor: state.systemStatus.rdagent.available ? `${colors.accent}20` : colors.background,
+ border: `1px solid ${state.systemStatus.rdagent.available ? colors.accent : colors.alert}`
}}
>
{state.systemStatus.rdagent.available ? (
- <CheckCircle2 size={12} color={FINCEPT.CYAN} />
+ <CheckCircle2 size={12} color={colors.accent} />
) : (
- <AlertCircle size={12} color={FINCEPT.RED} />
+ <AlertCircle size={12} color={colors.alert} />
)}
- <span style={{ color: state.systemStatus.rdagent.available ? FINCEPT.CYAN : FINCEPT.RED }}>
+ <span style={{ color: state.systemStatus.rdagent.available ? colors.accent : colors.alert }}>
RD-AGENT
</span>
</div>
@@ -391,12 +388,12 @@ export default function AIQuantLabTab() {
<button
onClick={() => dispatch({ type: 'TOGGLE_SETTINGS' })}
className="p-1.5 transition-colors"
- style={{ backgroundColor: state.showSettings ? FINCEPT.HOVER : 'transparent' }}
+ style={{ backgroundColor: state.showSettings ? '#1F1F1F' : 'transparent' }}
title="Settings"
- onMouseEnter={(e) => e.currentTarget.style.backgroundColor = FINCEPT.HOVER}
- onMouseLeave={(e) => e.currentTarget.style.backgroundColor = state.showSettings ? FINCEPT.HOVER : 'transparent'}
+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#1F1F1F'}
+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = state.showSettings ? '#1F1F1F' : 'transparent'}
>
- <Settings size={14} color={FINCEPT.GRAY} />
+ <Settings size={14} color={colors.textMuted} />
</button>
</div>
</div>
@@ -408,14 +405,14 @@ export default function AIQuantLabTab() {
<div
className="flex flex-col border-r"
style={{
- backgroundColor: FINCEPT.PANEL_BG,
- borderColor: FINCEPT.BORDER,
+ backgroundColor: colors.panel,
+ borderColor: 'var(--ft-border-color, #2A2A2A)',
width: '200px'
}}
>
{/* Panel Header */}
- <div className="flex items-center justify-between px-3 py-2 border-b" style={{ borderColor: FINCEPT.BORDER }}>
- <span className="text-[11px] font-bold tracking-wider" style={{ color: FINCEPT.MUTED }}>
+ <div className="flex items-center justify-between px-3 py-2 border-b" style={{ borderColor: 'var(--ft-border-color, #2A2A2A)' }}>
+ <span className="text-[11px] font-bold tracking-wider" style={{ color: colors.textMuted }}>
MODULES
</span>
<button
@@ -423,7 +420,7 @@ export default function AIQuantLabTab() {
className="p-0.5"
title="Minimize panel"
>
- <ChevronUp size={12} color={FINCEPT.GRAY} />
+ <ChevronUp size={12} color={colors.textMuted} />
</button>
</div>
@@ -431,7 +428,7 @@ export default function AIQuantLabTab() {
<div className="flex-1 overflow-y-auto p-2">
{['Core', 'AI/ML', 'Advanced', 'Analytics'].map((category) => (
<div key={category} className="mb-3">
- <div className="px-2 py-1 text-[10px] font-bold tracking-wider" style={{ color: FINCEPT.MUTED }}>
+ <div className="px-2 py-1 text-[10px] font-bold tracking-wider" style={{ color: colors.textMuted }}>
{category}
</div>
<div className="space-y-1">
@@ -445,11 +442,11 @@ export default function AIQuantLabTab() {
className="w-full flex items-center gap-2 px-2 py-1.5 text-xs transition-all"
style={{
backgroundColor: isActive ? `${mod.color}20` : 'transparent',
- color: isActive ? mod.color : FINCEPT.GRAY,
+ color: isActive ? mod.color : colors.textMuted,
borderLeft: isActive ? `2px solid ${mod.color}` : '2px solid transparent'
}}
onMouseEnter={(e) => {
- if (!isActive) e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ if (!isActive) e.currentTarget.style.backgroundColor = '#1F1F1F';
}}
onMouseLeave={(e) => {
if (!isActive) e.currentTarget.style.backgroundColor = 'transparent';
@@ -472,8 +469,8 @@ export default function AIQuantLabTab() {
<div
className="flex flex-col items-center border-r"
style={{
- backgroundColor: FINCEPT.PANEL_BG,
- borderColor: FINCEPT.BORDER,
+ backgroundColor: colors.panel,
+ borderColor: 'var(--ft-border-color, #2A2A2A)',
width: '32px'
}}
>
@@ -482,7 +479,7 @@ export default function AIQuantLabTab() {
className="p-1 mt-1"
title="Expand panel"
>
- <ChevronDown size={12} color={FINCEPT.GRAY} />
+ <ChevronDown size={12} color={colors.textMuted} />
</button>
</div>
)}
@@ -492,15 +489,15 @@ export default function AIQuantLabTab() {
{/* Content Header */}
<div
className="flex items-center justify-between px-3 py-2 border-b"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ style={{ backgroundColor: colors.panel, borderColor: 'var(--ft-border-color, #2A2A2A)' }}
>
<div className="flex items-center gap-2">
<activeModule.icon size={14} color={activeModule.color} />
- <span className="text-xs font-bold tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ <span className="text-xs font-bold tracking-wide" style={{ color: colors.text }}>
{activeModule.label}
</span>
</div>
- <div className="text-[10px]" style={{ color: FINCEPT.MUTED }}>
+ <div className="text-[10px]" style={{ color: colors.textMuted }}>
{activeModule.category}
</div>
</div>
@@ -531,15 +528,15 @@ export default function AIQuantLabTab() {
<div
className="flex flex-col border-l"
style={{
- backgroundColor: FINCEPT.PANEL_BG,
- borderColor: FINCEPT.BORDER,
+ backgroundColor: colors.panel,
+ borderColor: 'var(--ft-border-color, #2A2A2A)',
width: state.activeView === 'deep_agent' ? '340px' : '220px',
transition: 'width 0.2s ease'
}}
>
{/* Panel Header */}
- <div className="flex items-center justify-between px-3 py-2 border-b" style={{ borderColor: FINCEPT.BORDER }}>
- <span className="text-[11px] font-bold tracking-wider" style={{ color: FINCEPT.MUTED }}>
+ <div className="flex items-center justify-between px-3 py-2 border-b" style={{ borderColor: 'var(--ft-border-color, #2A2A2A)' }}>
+ <span className="text-[11px] font-bold tracking-wider" style={{ color: colors.textMuted }}>
{state.activeView === 'deep_agent' ? 'AGENT OUTPUT' : 'SYSTEM STATUS'}
</span>
<button
@@ -547,7 +544,7 @@ export default function AIQuantLabTab() {
className="p-0.5"
title="Minimize panel"
>
- <ChevronUp size={12} color={FINCEPT.GRAY} />
+ <ChevronUp size={12} color={colors.textMuted} />
</button>
</div>
@@ -558,35 +555,35 @@ export default function AIQuantLabTab() {
<>
{/* Execution status */}
{deepAgentOutput?.isExecuting && (
- <div className="p-2.5" style={{ backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.YELLOW}` }}>
+ <div className="p-2.5" style={{ backgroundColor: colors.background, border: `1px solid ${colors.warning}` }}>
<div className="flex items-center gap-2">
- <RefreshCw size={14} color={FINCEPT.YELLOW} className="animate-spin" />
- <span className="text-xs font-mono" style={{ color: FINCEPT.YELLOW }}>Executing...</span>
+ <RefreshCw size={14} color={colors.warning} className="animate-spin" />
+ <span className="text-xs font-mono" style={{ color: colors.warning }}>Executing...</span>
</div>
</div>
)}
{/* Error */}
{deepAgentOutput?.error && (
- <div className="p-2.5" style={{ backgroundColor: `${FINCEPT.RED}15`, border: `1px solid ${FINCEPT.RED}` }}>
+ <div className="p-2.5" style={{ backgroundColor: `${colors.alert}15`, border: `1px solid ${colors.alert}` }}>
<div className="flex items-center gap-2 mb-2">
- <AlertCircle size={14} color={FINCEPT.RED} />
- <span className="text-[11px] font-bold" style={{ color: FINCEPT.RED }}>ERROR</span>
+ <AlertCircle size={14} color={colors.alert} />
+ <span className="text-[11px] font-bold" style={{ color: colors.alert }}>ERROR</span>
</div>
- <div className="text-[10px] font-mono" style={{ color: FINCEPT.GRAY, lineHeight: '1.4' }}>{deepAgentOutput.error}</div>
+ <div className="text-[10px] font-mono" style={{ color: colors.textMuted, lineHeight: '1.4' }}>{deepAgentOutput.error}</div>
</div>
)}
{/* Execution Log */}
{deepAgentOutput && deepAgentOutput.executionLog.length > 0 && (
- <div className="p-2.5" style={{ backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.CYAN}` }}>
+ <div className="p-2.5" style={{ backgroundColor: colors.background, border: `1px solid ${colors.accent}` }}>
<div className="flex items-center gap-2 mb-2">
- <Cpu size={14} color={FINCEPT.CYAN} />
- <span className="text-[11px] font-bold" style={{ color: FINCEPT.WHITE }}>Execution Log</span>
+ <Cpu size={14} color={colors.accent} />
+ <span className="text-[11px] font-bold" style={{ color: colors.text }}>Execution Log</span>
</div>
<div className="space-y-0.5" style={{ maxHeight: '120px', overflowY: 'auto' }}>
{deepAgentOutput.executionLog.map((log, idx) => (
- <div key={idx} className="text-[10px] font-mono" style={{ color: FINCEPT.CYAN, lineHeight: '1.4' }}>
+ <div key={idx} className="text-[10px] font-mono" style={{ color: colors.accent, lineHeight: '1.4' }}>
{log}
</div>
))}
@@ -599,16 +596,16 @@ export default function AIQuantLabTab() {
<div
className="p-2.5"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.GREEN}`,
- borderLeft: `3px solid ${FINCEPT.GREEN}`
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.success}`,
+ borderLeft: `3px solid ${colors.success}`
}}
>
<div className="flex items-center gap-2 mb-2">
- <Sparkles size={14} color={FINCEPT.GREEN} />
- <span className="text-[11px] font-bold" style={{ color: FINCEPT.WHITE }}>Result</span>
+ <Sparkles size={14} color={colors.success} />
+ <span className="text-[11px] font-bold" style={{ color: colors.text }}>Result</span>
</div>
- <div className="text-[11px] font-mono" style={{ color: FINCEPT.WHITE, lineHeight: '1.6' }}>
+ <div className="text-[11px] font-mono" style={{ color: colors.text, lineHeight: '1.6' }}>
{formatResultText(deepAgentOutput.result)}
</div>
</div>
@@ -616,12 +613,12 @@ export default function AIQuantLabTab() {
{/* Empty state */}
{!deepAgentOutput?.isExecuting && !deepAgentOutput?.result && !deepAgentOutput?.error && (
- <div className="p-2.5" style={{ backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.BORDER}` }}>
+ <div className="p-2.5" style={{ backgroundColor: colors.background, border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}` }}>
<div className="flex items-center gap-2 mb-2">
- <Brain size={14} color={FINCEPT.CYAN} />
- <span className="text-[11px] font-bold" style={{ color: FINCEPT.WHITE }}>DeepAgent</span>
+ <Brain size={14} color={colors.accent} />
+ <span className="text-[11px] font-bold" style={{ color: colors.text }}>DeepAgent</span>
</div>
- <div className="text-[10px]" style={{ color: FINCEPT.GRAY, lineHeight: '1.5' }}>
+ <div className="text-[10px]" style={{ color: colors.textMuted, lineHeight: '1.5' }}>
Select an agent type, enter a task, and click Execute to see results here.
</div>
</div>
@@ -634,22 +631,22 @@ export default function AIQuantLabTab() {
<>
{/* Loading State */}
{state.systemStatus.status === 'loading' && (
- <div className="p-2.5" style={{ backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.YELLOW}` }}>
+ <div className="p-2.5" style={{ backgroundColor: colors.background, border: `1px solid ${colors.warning}` }}>
<div className="flex items-center gap-2">
- <RefreshCw size={14} color={FINCEPT.YELLOW} className="animate-spin" />
- <span className="text-xs" style={{ color: FINCEPT.YELLOW }}>Loading...</span>
+ <RefreshCw size={14} color={colors.warning} className="animate-spin" />
+ <span className="text-xs" style={{ color: colors.warning }}>Loading...</span>
</div>
</div>
)}
{/* Error State */}
{state.systemStatus.status === 'error' && (
- <div className="p-2.5" style={{ backgroundColor: `${FINCEPT.RED}15`, border: `1px solid ${FINCEPT.RED}` }}>
+ <div className="p-2.5" style={{ backgroundColor: `${colors.alert}15`, border: `1px solid ${colors.alert}` }}>
<div className="flex items-center gap-2 mb-2">
- <AlertCircle size={14} color={FINCEPT.RED} />
- <span className="text-[11px] font-bold" style={{ color: FINCEPT.RED }}>ERROR</span>
+ <AlertCircle size={14} color={colors.alert} />
+ <span className="text-[11px] font-bold" style={{ color: colors.alert }}>ERROR</span>
</div>
- <div className="text-[10px]" style={{ color: FINCEPT.GRAY }}>{state.systemStatus.message}</div>
+ <div className="text-[10px]" style={{ color: colors.textMuted }}>{state.systemStatus.message}</div>
</div>
)}
@@ -660,32 +657,32 @@ export default function AIQuantLabTab() {
<div
className="p-2.5"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${state.systemStatus.qlib.available ? FINCEPT.GREEN : FINCEPT.RED}`
+ backgroundColor: colors.background,
+ border: `1px solid ${state.systemStatus.qlib.available ? colors.success : colors.alert}`
}}
>
<div className="flex items-center gap-2 mb-2">
- <Cpu size={14} color={state.systemStatus.qlib.available ? FINCEPT.GREEN : FINCEPT.RED} />
- <span className="text-[11px] font-bold" style={{ color: FINCEPT.WHITE }}>
+ <Cpu size={14} color={state.systemStatus.qlib.available ? colors.success : colors.alert} />
+ <span className="text-[11px] font-bold" style={{ color: colors.text }}>
Microsoft Qlib
</span>
</div>
<div className="space-y-1">
<div className="flex justify-between text-[10px]">
- <span style={{ color: FINCEPT.GRAY }}>Status:</span>
- <span style={{ color: state.systemStatus.qlib.available ? FINCEPT.GREEN : FINCEPT.RED }}>
+ <span style={{ color: colors.textMuted }}>Status:</span>
+ <span style={{ color: state.systemStatus.qlib.available ? colors.success : colors.alert }}>
{state.systemStatus.qlib.available ? 'INSTALLED' : 'NOT INSTALLED'}
</span>
</div>
{state.systemStatus.qlib.version && (
<div className="flex justify-between text-[10px]">
- <span style={{ color: FINCEPT.GRAY }}>Version:</span>
- <span style={{ color: FINCEPT.WHITE }}>{state.systemStatus.qlib.version}</span>
+ <span style={{ color: colors.textMuted }}>Version:</span>
+ <span style={{ color: colors.text }}>{state.systemStatus.qlib.version}</span>
</div>
)}
<div className="flex justify-between text-[10px]">
- <span style={{ color: FINCEPT.GRAY }}>Models:</span>
- <span style={{ color: FINCEPT.WHITE }}>15+</span>
+ <span style={{ color: colors.textMuted }}>Models:</span>
+ <span style={{ color: colors.text }}>15+</span>
</div>
</div>
</div>
@@ -694,32 +691,32 @@ export default function AIQuantLabTab() {
<div
className="p-2.5"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${state.systemStatus.rdagent.available ? FINCEPT.CYAN : FINCEPT.RED}`
+ backgroundColor: colors.background,
+ border: `1px solid ${state.systemStatus.rdagent.available ? colors.accent : colors.alert}`
}}
>
<div className="flex items-center gap-2 mb-2">
- <Server size={14} color={state.systemStatus.rdagent.available ? FINCEPT.CYAN : FINCEPT.RED} />
- <span className="text-[11px] font-bold" style={{ color: FINCEPT.WHITE }}>
+ <Server size={14} color={state.systemStatus.rdagent.available ? colors.accent : colors.alert} />
+ <span className="text-[11px] font-bold" style={{ color: colors.text }}>
RD-Agent
</span>
</div>
<div className="space-y-1">
<div className="flex justify-between text-[10px]">
- <span style={{ color: FINCEPT.GRAY }}>Status:</span>
- <span style={{ color: state.systemStatus.rdagent.available ? FINCEPT.CYAN : FINCEPT.RED }}>
+ <span style={{ color: colors.textMuted }}>Status:</span>
+ <span style={{ color: state.systemStatus.rdagent.available ? colors.accent : colors.alert }}>
{state.systemStatus.rdagent.available ? 'INSTALLED' : 'NOT INSTALLED'}
</span>
</div>
<div className="flex justify-between text-[10px]">
- <span style={{ color: FINCEPT.GRAY }}>Factor Loop:</span>
- <span style={{ color: state.systemStatus.rdagent.factor_loop_available ? FINCEPT.GREEN : FINCEPT.RED }}>
+ <span style={{ color: colors.textMuted }}>Factor Loop:</span>
+ <span style={{ color: state.systemStatus.rdagent.factor_loop_available ? colors.success : colors.alert }}>
{state.systemStatus.rdagent.factor_loop_available ? 'YES' : 'NO'}
</span>
</div>
<div className="flex justify-between text-[10px]">
- <span style={{ color: FINCEPT.GRAY }}>Model Loop:</span>
- <span style={{ color: state.systemStatus.rdagent.model_loop_available ? FINCEPT.GREEN : FINCEPT.RED }}>
+ <span style={{ color: colors.textMuted }}>Model Loop:</span>
+ <span style={{ color: state.systemStatus.rdagent.model_loop_available ? colors.success : colors.alert }}>
{state.systemStatus.rdagent.model_loop_available ? 'YES' : 'NO'}
</span>
</div>
@@ -732,31 +729,31 @@ export default function AIQuantLabTab() {
<div
className="p-2.5"
style={{
- backgroundColor: FINCEPT.DARK_BG,
+ backgroundColor: colors.background,
border: `1px solid ${activeModule.color}`
}}
>
<div className="flex items-center gap-2 mb-2">
<activeModule.icon size={14} color={activeModule.color} />
- <span className="text-[11px] font-bold" style={{ color: FINCEPT.WHITE }}>
+ <span className="text-[11px] font-bold" style={{ color: colors.text }}>
Active Module
</span>
</div>
<div className="space-y-1">
<div className="flex justify-between text-[10px]">
- <span style={{ color: FINCEPT.GRAY }}>Name:</span>
+ <span style={{ color: colors.textMuted }}>Name:</span>
<span style={{ color: activeModule.color }}>{activeModule.shortLabel}</span>
</div>
<div className="flex justify-between text-[10px]">
- <span style={{ color: FINCEPT.GRAY }}>Category:</span>
- <span style={{ color: FINCEPT.WHITE }}>{activeModule.category}</span>
+ <span style={{ color: colors.textMuted }}>Category:</span>
+ <span style={{ color: colors.text }}>{activeModule.category}</span>
</div>
</div>
</div>
{/* Quick Actions */}
- <div className="pt-2 border-t" style={{ borderColor: FINCEPT.BORDER }}>
- <div className="text-[10px] font-bold tracking-wider mb-2" style={{ color: FINCEPT.MUTED }}>
+ <div className="pt-2 border-t" style={{ borderColor: 'var(--ft-border-color, #2A2A2A)' }}>
+ <div className="text-[10px] font-bold tracking-wider mb-2" style={{ color: colors.textMuted }}>
QUICK ACTIONS
</div>
<div className="space-y-1.5">
@@ -764,12 +761,12 @@ export default function AIQuantLabTab() {
onClick={() => dispatch({ type: 'TOGGLE_SETTINGS' })}
className="w-full flex items-center gap-2 px-2.5 py-1.5 text-[10px] transition-colors"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text
}}
- onMouseEnter={(e) => e.currentTarget.style.backgroundColor = FINCEPT.HOVER}
- onMouseLeave={(e) => e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG}
+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#1F1F1F'}
+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = colors.background}
>
<Settings size={12} />
<span>Configuration</span>
@@ -787,8 +784,8 @@ export default function AIQuantLabTab() {
<div
className="flex flex-col items-center border-l"
style={{
- backgroundColor: FINCEPT.PANEL_BG,
- borderColor: FINCEPT.BORDER,
+ backgroundColor: colors.panel,
+ borderColor: 'var(--ft-border-color, #2A2A2A)',
width: '32px'
}}
>
@@ -797,7 +794,7 @@ export default function AIQuantLabTab() {
className="p-1 mt-1"
title="Expand panel"
>
- <ChevronDown size={12} color={FINCEPT.GRAY} />
+ <ChevronDown size={12} color={colors.textMuted} />
</button>
</div>
)}
@@ -807,38 +804,38 @@ export default function AIQuantLabTab() {
<div
className="flex items-center justify-between px-4 py-1.5 border-t text-[10px] font-mono"
style={{
- backgroundColor: FINCEPT.HEADER_BG,
- borderColor: FINCEPT.BORDER,
+ backgroundColor: colors.panel,
+ borderColor: 'var(--ft-border-color, #2A2A2A)',
height: '28px'
}}
>
<div className="flex items-center gap-4">
- <span style={{ color: FINCEPT.MUTED }}>Fincept AI Quant Lab v3.2.0</span>
- <span style={{ color: FINCEPT.GRAY }}>•</span>
- <span style={{ color: FINCEPT.GRAY }}>
+ <span style={{ color: colors.textMuted }}>Fincept AI Quant Lab v3.2.0</span>
+ <span style={{ color: colors.textMuted }}>•</span>
+ <span style={{ color: colors.textMuted }}>
Qlib: {state.systemStatus.status === 'ready' && state.systemStatus.qlib.available ? (
- <span style={{ color: FINCEPT.GREEN }}>INSTALLED</span>
+ <span style={{ color: colors.success }}>INSTALLED</span>
) : (
- <span style={{ color: state.systemStatus.status === 'loading' ? FINCEPT.YELLOW : FINCEPT.RED }}>
+ <span style={{ color: state.systemStatus.status === 'loading' ? colors.warning : colors.alert }}>
{state.systemStatus.status === 'loading' ? 'LOADING...' : 'NOT INSTALLED'}
</span>
)}
</span>
- <span style={{ color: FINCEPT.GRAY }}>•</span>
- <span style={{ color: FINCEPT.GRAY }}>
+ <span style={{ color: colors.textMuted }}>•</span>
+ <span style={{ color: colors.textMuted }}>
RD-Agent: {state.systemStatus.status === 'ready' && state.systemStatus.rdagent.available ? (
- <span style={{ color: FINCEPT.CYAN }}>INSTALLED</span>
+ <span style={{ color: colors.accent }}>INSTALLED</span>
) : (
- <span style={{ color: state.systemStatus.status === 'loading' ? FINCEPT.YELLOW : FINCEPT.RED }}>
+ <span style={{ color: state.systemStatus.status === 'loading' ? colors.warning : colors.alert }}>
{state.systemStatus.status === 'loading' ? 'LOADING...' : 'NOT INSTALLED'}
</span>
)}
</span>
</div>
<div className="flex items-center gap-3">
- <span style={{ color: FINCEPT.GRAY }}>Module: <span style={{ color: activeModule.color }}>{activeModule.shortLabel}</span></span>
- <span style={{ color: FINCEPT.GRAY }}>•</span>
- <span style={{ color: FINCEPT.GRAY }}>{currentTime.toLocaleDateString()}</span>
+ <span style={{ color: colors.textMuted }}>Module: <span style={{ color: activeModule.color }}>{activeModule.shortLabel}</span></span>
+ <span style={{ color: colors.textMuted }}>•</span>
+ <span style={{ color: colors.textMuted }}>{currentTime.toLocaleDateString()}</span>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AdvancedModelsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AdvancedModelsPanel.tsx
index 034b08d06..0926d9099 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AdvancedModelsPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AdvancedModelsPanel.tsx
@@ -6,19 +6,7 @@
import React, { useState } from 'react';
import { Layers, Zap, Info, Play, FileText } from 'lucide-react';
-
-const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- BORDER: '#2A2A2A',
- PURPLE: '#9D4EDD',
- MUTED: '#4A4A4A',
- HOVER: '#1F1F1F'
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface ModelInfo {
id: string;
@@ -29,6 +17,7 @@ interface ModelInfo {
}
export function AdvancedModelsPanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const models: ModelInfo[] = [
{
id: 'lstm_ts',
@@ -81,20 +70,20 @@ export function AdvancedModelsPanel() {
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: FINCEPT.DARK_BG
+ backgroundColor: colors.background
}}>
{/* Terminal-style Header */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
gap: '12px'
}}>
- <Layers size={16} color={FINCEPT.PURPLE} />
+ <Layers size={16} color={colors.purple} />
<span style={{
- color: FINCEPT.PURPLE,
+ color: colors.purple,
fontSize: '12px',
fontWeight: 700,
letterSpacing: '0.5px',
@@ -107,9 +96,9 @@ export function AdvancedModelsPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.PURPLE + '20',
- border: `1px solid ${FINCEPT.PURPLE}`,
- color: FINCEPT.PURPLE
+ backgroundColor: colors.purple + '20',
+ border: `1px solid ${colors.purple}`,
+ color: colors.purple
}}>
{models.length} MODELS AVAILABLE
</div>
@@ -119,19 +108,19 @@ export function AdvancedModelsPanel() {
{/* Left Panel - Model Selection */}
<div style={{
width: '320px',
- borderRight: `1px solid ${FINCEPT.BORDER}`,
+ borderRight: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
display: 'flex',
flexDirection: 'column'
}}>
<div style={{
padding: '10px 12px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.PURPLE,
+ color: colors.purple,
fontFamily: 'monospace',
letterSpacing: '0.5px',
- backgroundColor: FINCEPT.PANEL_BG
+ backgroundColor: colors.panel
}}>
SELECT MODEL ARCHITECTURE
</div>
@@ -146,29 +135,29 @@ export function AdvancedModelsPanel() {
onClick={() => setSelectedModel(model)}
style={{
padding: '12px',
- backgroundColor: isSelected ? FINCEPT.HOVER : 'transparent',
- border: `1px solid ${isSelected ? FINCEPT.PURPLE : FINCEPT.BORDER}`,
- borderTop: idx === 0 ? `1px solid ${isSelected ? FINCEPT.PURPLE : FINCEPT.BORDER}` : '0',
+ backgroundColor: isSelected ? '#1F1F1F' : 'transparent',
+ border: `1px solid ${isSelected ? colors.purple : 'var(--ft-border-color, #2A2A2A)'}`,
+ borderTop: idx === 0 ? `1px solid ${isSelected ? colors.purple : 'var(--ft-border-color, #2A2A2A)'}` : '0',
cursor: 'pointer',
transition: 'all 0.15s',
marginTop: idx === 0 ? '0' : '-1px'
}}
onMouseEnter={(e) => {
if (!isSelected) {
- e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG;
- e.currentTarget.style.borderColor = FINCEPT.PURPLE;
+ e.currentTarget.style.backgroundColor = colors.background;
+ e.currentTarget.style.borderColor = colors.purple;
}
}}
onMouseLeave={(e) => {
if (!isSelected) {
e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
<span style={{
- color: FINCEPT.WHITE,
+ color: colors.text,
fontSize: '12px',
fontWeight: 700,
fontFamily: 'monospace'
@@ -179,15 +168,15 @@ export function AdvancedModelsPanel() {
fontSize: '8px',
fontFamily: 'monospace',
padding: '2px 6px',
- backgroundColor: FINCEPT.PURPLE + '30',
- border: `1px solid ${FINCEPT.PURPLE}`,
- color: FINCEPT.PURPLE
+ backgroundColor: colors.purple + '30',
+ border: `1px solid ${colors.purple}`,
+ color: colors.purple
}}>
{model.category.toUpperCase()}
</div>
</div>
<div style={{
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.6,
fontSize: '10px',
lineHeight: '1.5',
@@ -205,13 +194,13 @@ export function AdvancedModelsPanel() {
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
<div style={{
padding: '10px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.PURPLE,
+ color: colors.purple,
fontFamily: 'monospace',
letterSpacing: '0.5px',
- backgroundColor: FINCEPT.PANEL_BG
+ backgroundColor: colors.panel
}}>
MODEL DETAILS: {selectedModel.name}
</div>
@@ -220,14 +209,14 @@ export function AdvancedModelsPanel() {
{/* Model Description */}
<div style={{
padding: '14px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `3px solid ${FINCEPT.PURPLE}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${colors.purple}`,
marginBottom: '16px'
}}>
<div style={{
fontSize: '9px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
fontFamily: 'monospace',
marginBottom: '6px',
@@ -236,7 +225,7 @@ export function AdvancedModelsPanel() {
DESCRIPTION
</div>
<div style={{
- color: FINCEPT.WHITE,
+ color: colors.text,
fontSize: '11px',
lineHeight: '1.6',
fontFamily: 'monospace',
@@ -251,12 +240,12 @@ export function AdvancedModelsPanel() {
{/* Key Features */}
<div style={{
padding: '14px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}>
<div style={{
fontSize: '10px',
- color: FINCEPT.PURPLE,
+ color: colors.purple,
fontFamily: 'monospace',
marginBottom: '12px',
fontWeight: 700,
@@ -270,12 +259,12 @@ export function AdvancedModelsPanel() {
<div style={{
width: '4px',
height: '4px',
- backgroundColor: FINCEPT.PURPLE,
+ backgroundColor: colors.purple,
marginTop: '6px',
flexShrink: 0
}} />
<span style={{
- color: FINCEPT.WHITE,
+ color: colors.text,
fontSize: '10px',
lineHeight: '1.5',
fontFamily: 'monospace',
@@ -291,12 +280,12 @@ export function AdvancedModelsPanel() {
{/* Architecture Info */}
<div style={{
padding: '14px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}>
<div style={{
fontSize: '10px',
- color: FINCEPT.PURPLE,
+ color: colors.purple,
fontFamily: 'monospace',
marginBottom: '12px',
fontWeight: 700,
@@ -309,11 +298,11 @@ export function AdvancedModelsPanel() {
{ label: 'INPUT TYPE', value: 'Time-series' },
{ label: 'OUTPUT', value: 'Predictions' },
{ label: 'FRAMEWORK', value: 'PyTorch' },
- { label: 'STATUS', value: 'AVAILABLE', color: FINCEPT.GREEN }
+ { label: 'STATUS', value: 'AVAILABLE', color: colors.success }
].map((item, idx) => (
<div key={idx} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span style={{
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
fontSize: '9px',
fontFamily: 'monospace',
@@ -322,7 +311,7 @@ export function AdvancedModelsPanel() {
{item.label}
</span>
<span style={{
- color: item.color || FINCEPT.WHITE,
+ color: item.color || colors.text,
fontSize: '10px',
fontFamily: 'monospace',
fontWeight: 600,
@@ -342,7 +331,7 @@ export function AdvancedModelsPanel() {
style={{
flex: 1,
padding: '12px 16px',
- backgroundColor: FINCEPT.PURPLE,
+ backgroundColor: colors.purple,
border: 'none',
color: '#000000',
fontSize: '11px',
@@ -371,8 +360,8 @@ export function AdvancedModelsPanel() {
flex: 1,
padding: '12px 16px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.PURPLE}`,
- color: FINCEPT.PURPLE,
+ border: `1px solid ${colors.purple}`,
+ color: colors.purple,
fontSize: '11px',
fontWeight: 700,
fontFamily: 'monospace',
@@ -385,7 +374,7 @@ export function AdvancedModelsPanel() {
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.PURPLE + '20';
+ e.currentTarget.style.backgroundColor = colors.purple + '20';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/BacktestingPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/BacktestingPanel.tsx
index a8da5b191..5656b0749 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/BacktestingPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/BacktestingPanel.tsx
@@ -23,25 +23,7 @@ import {
Info
} from 'lucide-react';
import { qlibService } from '@/services/aiQuantLab/qlibService';
-
-// Fincept Professional Color Palette
-const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- BLUE: '#0088FF',
- PURPLE: '#9D4EDD',
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F',
- MUTED: '#4A4A4A'
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface BacktestMetrics {
annual_return?: number;
@@ -57,6 +39,8 @@ interface BacktestMetrics {
}
export function BacktestingPanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+
// Strategy Configuration
const [strategyType, setStrategyType] = useState('topk_dropout');
const [instruments, setInstruments] = useState('AAPL,MSFT,GOOGL,AMZN,NVDA,TSLA,META,NFLX');
@@ -130,36 +114,36 @@ export function BacktestingPanel() {
};
return (
- <div className="flex h-full" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <div className="flex h-full" style={{ backgroundColor: colors.background }}>
{/* Left Panel - Configuration */}
<div
className="w-96 border-r overflow-auto flex-shrink-0"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ style={{ backgroundColor: colors.panel, borderColor: 'var(--ft-border-color, #2A2A2A)' }}
>
<div className="p-4 space-y-4">
{/* Header */}
- <div className="pb-3 border-b" style={{ borderColor: FINCEPT.BORDER }}>
+ <div className="pb-3 border-b" style={{ borderColor: 'var(--ft-border-color, #2A2A2A)' }}>
<div className="flex items-center gap-2 mb-1">
- <BarChart3 size={18} color={FINCEPT.ORANGE} />
- <h2 className="text-sm font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ <BarChart3 size={18} color={colors.primary} />
+ <h2 className="text-sm font-bold uppercase tracking-wide" style={{ color: colors.text }}>
STRATEGY BACKTESTING
</h2>
</div>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ <p className="text-xs font-mono" style={{ color: colors.textMuted }}>
Test trading strategies with historical data
</p>
</div>
{/* Strategy Configuration */}
<div>
- <h3 className="text-xs font-bold uppercase tracking-wide mb-3 flex items-center gap-1" style={{ color: FINCEPT.GRAY }}>
+ <h3 className="text-xs font-bold uppercase tracking-wide mb-3 flex items-center gap-1" style={{ color: colors.textMuted }}>
<Layers size={12} />
STRATEGY CONFIGURATION
</h3>
<div className="space-y-3">
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
Strategy Type
</label>
<select
@@ -167,9 +151,9 @@ export function BacktestingPanel() {
onChange={(e) => setStrategyType(e.target.value)}
className="w-full px-3 py-2 rounded text-xs font-mono outline-none uppercase"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
>
<option value="topk_dropout">Top-K Dropout</option>
@@ -179,7 +163,7 @@ export function BacktestingPanel() {
</div>
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
Universe (Comma-separated)
</label>
<textarea
@@ -188,16 +172,16 @@ export function BacktestingPanel() {
rows={3}
className="w-full px-3 py-2 rounded text-xs font-mono outline-none resize-none"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
<Calendar size={12} className="inline mr-1" />
Start Date
</label>
@@ -207,14 +191,14 @@ export function BacktestingPanel() {
onChange={(e) => setStartDate(e.target.value)}
className="w-full px-3 py-2 rounded text-xs font-mono outline-none"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
/>
</div>
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
<Calendar size={12} className="inline mr-1" />
End Date
</label>
@@ -224,16 +208,16 @@ export function BacktestingPanel() {
onChange={(e) => setEndDate(e.target.value)}
className="w-full px-3 py-2 rounded text-xs font-mono outline-none"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
/>
</div>
</div>
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
Top K Positions
</label>
<input
@@ -243,9 +227,9 @@ export function BacktestingPanel() {
onChange={(e) => { const v = e.target.value; if (v === '' || /^\d+$/.test(v)) { setTopK(Number(v) || 0) } }}
className="w-full px-3 py-2 rounded text-xs font-mono outline-none"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
/>
</div>
@@ -253,15 +237,15 @@ export function BacktestingPanel() {
</div>
{/* Portfolio Configuration */}
- <div className="pt-3 border-t" style={{ borderColor: FINCEPT.BORDER }}>
- <h3 className="text-xs font-bold uppercase tracking-wide mb-3 flex items-center gap-1" style={{ color: FINCEPT.GRAY }}>
+ <div className="pt-3 border-t" style={{ borderColor: 'var(--ft-border-color, #2A2A2A)' }}>
+ <h3 className="text-xs font-bold uppercase tracking-wide mb-3 flex items-center gap-1" style={{ color: colors.textMuted }}>
<Settings size={12} />
PORTFOLIO SETTINGS
</h3>
<div className="space-y-3">
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
Initial Capital (USD)
</label>
<input
@@ -271,15 +255,15 @@ export function BacktestingPanel() {
onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setInitialCapital(Number(v) || 0) } }}
className="w-full px-3 py-2 rounded text-xs font-mono outline-none"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
/>
</div>
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
Benchmark
</label>
<input
@@ -289,16 +273,16 @@ export function BacktestingPanel() {
placeholder="SPY"
className="w-full px-3 py-2 rounded text-xs font-mono outline-none"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
Commission (%)
</label>
<input
@@ -308,14 +292,14 @@ export function BacktestingPanel() {
onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setCommission((Number(v) || 0) / 100) } }}
className="w-full px-3 py-2 rounded text-xs font-mono outline-none"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
/>
</div>
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
Slippage (%)
</label>
<input
@@ -325,9 +309,9 @@ export function BacktestingPanel() {
onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setSlippage((Number(v) || 0) / 100) } }}
className="w-full px-3 py-2 rounded text-xs font-mono outline-none"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
/>
</div>
@@ -341,7 +325,7 @@ export function BacktestingPanel() {
onClick={handleRunBacktest}
disabled={isRunning || !instruments || !startDate || !endDate}
className="w-full py-3 rounded font-bold uppercase text-sm tracking-wide hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ style={{ backgroundColor: colors.primary, color: colors.background }}
>
{isRunning ? (
<>
@@ -360,20 +344,20 @@ export function BacktestingPanel() {
</div>
{/* Right Panel - Results */}
- <div className="flex-1 overflow-auto p-6" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <div className="flex-1 overflow-auto p-6" style={{ backgroundColor: colors.background }}>
{error ? (
<div className="flex items-center justify-center h-full">
<div
className="max-w-md p-6 rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.RED }}
+ style={{ backgroundColor: colors.panel, borderColor: colors.alert }}
>
<div className="flex items-center gap-3 mb-3">
- <AlertCircle size={24} color={FINCEPT.RED} />
- <h3 className="text-sm font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ <AlertCircle size={24} color={colors.alert} />
+ <h3 className="text-sm font-bold uppercase tracking-wide" style={{ color: colors.text }}>
BACKTEST ERROR
</h3>
</div>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ <p className="text-xs font-mono" style={{ color: colors.textMuted }}>
{error}
</p>
</div>
@@ -383,16 +367,16 @@ export function BacktestingPanel() {
{/* Header */}
<div className="flex items-center justify-between">
<div>
- <h2 className="text-xl font-bold uppercase tracking-wide mb-1" style={{ color: FINCEPT.WHITE }}>
+ <h2 className="text-xl font-bold uppercase tracking-wide mb-1" style={{ color: colors.text }}>
BACKTEST RESULTS
</h2>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ <p className="text-xs font-mono" style={{ color: colors.textMuted }}>
{startDate} to {endDate} • {instruments.split(',').length} instruments
</p>
</div>
<button
className="px-4 py-2 rounded font-bold uppercase text-xs tracking-wide hover:bg-opacity-80 transition-colors flex items-center gap-2"
- style={{ backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE }}
+ style={{ backgroundColor: colors.panel, color: colors.text }}
>
<Download size={14} />
EXPORT
@@ -401,7 +385,7 @@ export function BacktestingPanel() {
{/* Performance Metrics */}
<div>
- <h3 className="text-xs font-bold uppercase tracking-wide mb-3" style={{ color: FINCEPT.GRAY }}>
+ <h3 className="text-xs font-bold uppercase tracking-wide mb-3" style={{ color: colors.textMuted }}>
PERFORMANCE METRICS
</h3>
<div className="grid grid-cols-3 gap-4">
@@ -409,38 +393,38 @@ export function BacktestingPanel() {
label="Annual Return"
value={backtestResults.annual_return ? `${(backtestResults.annual_return * 100).toFixed(2)}%` : 'N/A'}
icon={<TrendingUp size={18} />}
- color={backtestResults.annual_return && backtestResults.annual_return > 0 ? FINCEPT.GREEN : FINCEPT.RED}
+ color={backtestResults.annual_return && backtestResults.annual_return > 0 ? colors.success : colors.alert}
positive={backtestResults.annual_return ? backtestResults.annual_return > 0 : undefined}
/>
<MetricCard
label="Sharpe Ratio"
value={backtestResults.sharpe_ratio?.toFixed(2) || 'N/A'}
icon={<Activity size={18} />}
- color={FINCEPT.ORANGE}
+ color={colors.primary}
/>
<MetricCard
label="Max Drawdown"
value={backtestResults.max_drawdown ? `${(backtestResults.max_drawdown * 100).toFixed(2)}%` : 'N/A'}
icon={<TrendingDown size={18} />}
- color={FINCEPT.RED}
+ color={colors.alert}
/>
<MetricCard
label="Volatility"
value={backtestResults.volatility ? `${(backtestResults.volatility * 100).toFixed(2)}%` : 'N/A'}
icon={<Activity size={18} />}
- color={FINCEPT.CYAN}
+ color={colors.accent}
/>
<MetricCard
label="Win Rate"
value={backtestResults.win_rate ? `${(backtestResults.win_rate * 100).toFixed(1)}%` : 'N/A'}
icon={<Target size={18} />}
- color={FINCEPT.GREEN}
+ color={colors.success}
/>
<MetricCard
label="Total Trades"
value={backtestResults.total_trades?.toString() || 'N/A'}
icon={<BarChart3 size={18} />}
- color={FINCEPT.WHITE}
+ color={colors.text}
/>
</div>
</div>
@@ -448,7 +432,7 @@ export function BacktestingPanel() {
{/* Trade Statistics */}
{(backtestResults.avg_win !== undefined || backtestResults.avg_loss !== undefined) && (
<div>
- <h3 className="text-xs font-bold uppercase tracking-wide mb-3" style={{ color: FINCEPT.GRAY }}>
+ <h3 className="text-xs font-bold uppercase tracking-wide mb-3" style={{ color: colors.textMuted }}>
TRADE STATISTICS
</h3>
<div className="grid grid-cols-3 gap-4">
@@ -456,19 +440,19 @@ export function BacktestingPanel() {
label="Profitable Trades"
value={backtestResults.profitable_trades?.toString() || 'N/A'}
icon={<CheckCircle2 size={18} />}
- color={FINCEPT.GREEN}
+ color={colors.success}
/>
<MetricCard
label="Average Win"
value={backtestResults.avg_win ? `${(backtestResults.avg_win * 100).toFixed(2)}%` : 'N/A'}
icon={<TrendingUp size={18} />}
- color={FINCEPT.GREEN}
+ color={colors.success}
/>
<MetricCard
label="Average Loss"
value={backtestResults.avg_loss ? `${(backtestResults.avg_loss * 100).toFixed(2)}%` : 'N/A'}
icon={<TrendingDown size={18} />}
- color={FINCEPT.RED}
+ color={colors.alert}
/>
</div>
</div>
@@ -476,16 +460,16 @@ export function BacktestingPanel() {
{/* Full Results JSON */}
<div>
- <h3 className="text-xs font-bold uppercase tracking-wide mb-3" style={{ color: FINCEPT.GRAY }}>
+ <h3 className="text-xs font-bold uppercase tracking-wide mb-3" style={{ color: colors.textMuted }}>
<Info size={12} className="inline mr-1" />
DETAILED RESULTS
</h3>
<pre
className="p-4 rounded text-xs font-mono overflow-x-auto border"
style={{
- backgroundColor: FINCEPT.PANEL_BG,
- color: FINCEPT.WHITE,
- borderColor: FINCEPT.BORDER
+ backgroundColor: colors.panel,
+ color: colors.text,
+ borderColor: 'var(--ft-border-color, #2A2A2A)'
}}
>
{JSON.stringify(backtestResults, null, 2)}
@@ -495,11 +479,11 @@ export function BacktestingPanel() {
) : (
<div className="flex items-center justify-center h-full">
<div className="text-center max-w-md">
- <BarChart3 size={64} color={FINCEPT.GRAY} className="mx-auto mb-4" />
- <h3 className="text-base font-bold uppercase tracking-wide mb-2" style={{ color: FINCEPT.WHITE }}>
+ <BarChart3 size={64} color={colors.textMuted} className="mx-auto mb-4" />
+ <h3 className="text-base font-bold uppercase tracking-wide mb-2" style={{ color: colors.text }}>
NO BACKTEST RESULTS
</h3>
- <p className="text-sm font-mono" style={{ color: FINCEPT.GRAY }}>
+ <p className="text-sm font-mono" style={{ color: colors.textMuted }}>
Configure your strategy parameters and run a backtest<br/>
to see performance metrics and trade analysis
</p>
@@ -524,13 +508,15 @@ function MetricCard({
color: string;
positive?: boolean;
}) {
+ const { colors } = useTerminalTheme();
+
return (
<div
className="p-4 rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ style={{ backgroundColor: colors.panel, borderColor: 'var(--ft-border-color, #2A2A2A)' }}
>
<div className="flex items-center justify-between mb-2">
- <span className="text-xs uppercase font-mono" style={{ color: FINCEPT.GRAY }}>
+ <span className="text-xs uppercase font-mono" style={{ color: colors.textMuted }}>
{label}
</span>
<div style={{ color }}>{icon}</div>
@@ -538,7 +524,7 @@ function MetricCard({
<div className="text-2xl font-bold font-mono flex items-center gap-2" style={{ color }}>
{value}
{positive !== undefined && (
- positive ? <TrendingUp size={16} color={FINCEPT.GREEN} /> : <TrendingDown size={16} color={FINCEPT.RED} />
+ positive ? <TrendingUp size={16} color={colors.success} /> : <TrendingDown size={16} color={colors.alert} />
)}
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/DeepAgentPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/DeepAgentPanel.tsx
index e093d2e31..dc404fe61 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/DeepAgentPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/DeepAgentPanel.tsx
@@ -23,21 +23,7 @@ import {
import { deepAgentService, ExecuteTaskRequest, Todo, PlanTodo, AgentConfig } from '@/services/aiQuantLab/deepAgentService';
import { useAuth } from '@/contexts/AuthContext';
import { getActiveLLMConfig } from '@/services/core/sqliteService';
-
-const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- GREEN: '#00D66F',
- RED: '#FF3B3B',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- PURPLE: '#9D4EDD',
- BORDER: '#2A2A2A',
- PANEL_BG: '#0F0F0F',
- DARK_BG: '#000000',
- HOVER: '#1F1F1F',
- MUTED: '#4A4A4A'
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface AgentType {
id: string;
@@ -48,48 +34,8 @@ interface AgentType {
subagents: string[];
}
-const AGENT_TYPES: AgentType[] = [
- {
- id: 'research',
- name: 'Research Agent',
- description: 'Autonomous research, data analysis, and report generation',
- icon: FileText,
- color: FINCEPT.CYAN,
- subagents: ['data_analyst', 'reporter']
- },
- {
- id: 'trading_strategy',
- name: 'Strategy Builder',
- description: 'Design, backtest, and validate trading strategies',
- icon: Zap,
- color: FINCEPT.YELLOW,
- subagents: ['data_analyst', 'trading', 'backtester', 'risk_analyzer', 'reporter']
- },
- {
- id: 'portfolio_management',
- name: 'Portfolio Manager',
- description: 'Optimize portfolios with risk management',
- icon: GitBranch,
- color: FINCEPT.GREEN,
- subagents: ['data_analyst', 'portfolio_optimizer', 'risk_analyzer', 'reporter']
- },
- {
- id: 'risk_assessment',
- name: 'Risk Analyzer',
- description: 'Comprehensive risk assessment and stress testing',
- icon: AlertCircle,
- color: FINCEPT.RED,
- subagents: ['data_analyst', 'risk_analyzer', 'reporter']
- },
- {
- id: 'general',
- name: 'General Agent',
- description: 'Full-featured agent with all specialists',
- icon: Brain,
- color: FINCEPT.PURPLE,
- subagents: ['research', 'data_analyst', 'trading', 'risk_analyzer', 'portfolio_optimizer', 'backtester', 'reporter']
- }
-];
+// Agent types are defined inside the component to use theme colors
+// See getAgentTypes() function inside DeepAgentPanel
const EXAMPLE_TASKS = {
research: [
@@ -128,7 +74,7 @@ export function formatResultText(text: string): React.ReactNode[] {
// Horizontal rule
if (/^-{3,}$/.test(trimmed) || /^\*{3,}$/.test(trimmed)) {
- nodes.push(<hr key={i} style={{ border: 'none', borderTop: '1px solid #2A2A2A', margin: '12px 0' }} />);
+ nodes.push(<hr key={i} style={{ border: 'none', borderTop: '1px solid var(--ft-border-color, #2A2A2A)', margin: '12px 0' }} />);
return;
}
@@ -138,7 +84,7 @@ export function formatResultText(text: string): React.ReactNode[] {
const level = headingMatch[1].length;
const sizes = { 1: '16px', 2: '14px', 3: '13px' } as Record<number, string>;
nodes.push(
- <div key={i} style={{ fontSize: sizes[level] || '13px', fontWeight: 700, color: '#FF8800', margin: '14px 0 6px 0' }}>
+ <div key={i} style={{ fontSize: sizes[level] || '13px', fontWeight: 700, color: 'var(--ft-color-primary, #FF8800)', margin: '14px 0 6px 0' }}>
{renderInlineFormatting(headingMatch[2])}
</div>
);
@@ -149,7 +95,7 @@ export function formatResultText(text: string): React.ReactNode[] {
if (/^[-*]\s+/.test(trimmed)) {
nodes.push(
<div key={i} style={{ paddingLeft: '16px', position: 'relative', marginBottom: '2px' }}>
- <span style={{ position: 'absolute', left: '4px', color: '#FF8800' }}>•</span>
+ <span style={{ position: 'absolute', left: '4px', color: 'var(--ft-color-primary, #FF8800)' }}>•</span>
{renderInlineFormatting(trimmed.replace(/^[-*]\s+/, ''))}
</div>
);
@@ -180,7 +126,7 @@ function renderInlineFormatting(text: string): React.ReactNode {
if (boldMatch.index > 0) {
parts.push(remaining.slice(0, boldMatch.index));
}
- parts.push(<span key={key++} style={{ fontWeight: 700, color: '#FFFFFF' }}>{boldMatch[1]}</span>);
+ parts.push(<span key={key++} style={{ fontWeight: 700, color: 'var(--ft-color-text, #FFFFFF)' }}>{boldMatch[1]}</span>);
remaining = remaining.slice(boldMatch.index + boldMatch[0].length);
continue;
}
@@ -204,8 +150,53 @@ interface DeepAgentPanelProps {
}
export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const { session } = useAuth();
const [selectedAgent, setSelectedAgent] = useState<string>('research');
+
+ // Agent types using theme colors
+ const AGENT_TYPES: AgentType[] = [
+ {
+ id: 'research',
+ name: 'Research Agent',
+ description: 'Autonomous research, data analysis, and report generation',
+ icon: FileText,
+ color: colors.accent,
+ subagents: ['data_analyst', 'reporter']
+ },
+ {
+ id: 'trading_strategy',
+ name: 'Strategy Builder',
+ description: 'Design, backtest, and validate trading strategies',
+ icon: Zap,
+ color: colors.warning,
+ subagents: ['data_analyst', 'trading', 'backtester', 'risk_analyzer', 'reporter']
+ },
+ {
+ id: 'portfolio_management',
+ name: 'Portfolio Manager',
+ description: 'Optimize portfolios with risk management',
+ icon: GitBranch,
+ color: colors.success,
+ subagents: ['data_analyst', 'portfolio_optimizer', 'risk_analyzer', 'reporter']
+ },
+ {
+ id: 'risk_assessment',
+ name: 'Risk Analyzer',
+ description: 'Comprehensive risk assessment and stress testing',
+ icon: AlertCircle,
+ color: colors.alert,
+ subagents: ['data_analyst', 'risk_analyzer', 'reporter']
+ },
+ {
+ id: 'general',
+ name: 'General Agent',
+ description: 'Full-featured agent with all specialists',
+ icon: Brain,
+ color: colors.purple,
+ subagents: ['research', 'data_analyst', 'trading', 'risk_analyzer', 'portfolio_optimizer', 'backtester', 'reporter']
+ }
+ ];
const [task, setTask] = useState<string>('');
const [isExecuting, setIsExecuting] = useState(false);
const [result, setResult] = useState<string>('');
@@ -386,9 +377,9 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
const hasSubtasks = todo.subtasks && todo.subtasks.length > 0;
const statusColors = {
- pending: FINCEPT.MUTED,
- in_progress: FINCEPT.YELLOW,
- completed: FINCEPT.GREEN
+ pending: colors.textMuted,
+ in_progress: colors.warning,
+ completed: colors.success
};
const statusIcon = {
@@ -402,7 +393,7 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
<div
style={{
padding: '8px 12px',
- backgroundColor: FINCEPT.DARK_BG,
+ backgroundColor: colors.background,
border: `1px solid ${statusColors[todo.status]}`,
borderLeft: `3px solid ${statusColors[todo.status]}`,
marginBottom: '5px',
@@ -417,11 +408,11 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
>
{hasSubtasks && (
isExpanded ?
- <ChevronDown size={10} style={{ color: FINCEPT.ORANGE }} /> :
- <ChevronRight size={10} style={{ color: FINCEPT.ORANGE }} />
+ <ChevronDown size={10} style={{ color: colors.primary }} /> :
+ <ChevronRight size={10} style={{ color: colors.primary }} />
)}
<span style={{ color: statusColors[todo.status] }}>{statusIcon}</span>
- <span style={{ flex: 1, color: FINCEPT.WHITE }}>
+ <span style={{ flex: 1, color: colors.text }}>
{todo.task}
</span>
</div>
@@ -443,20 +434,20 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: FINCEPT.DARK_BG
+ backgroundColor: colors.background
}}>
{/* Terminal-style Header */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
gap: '12px'
}}>
- <Network size={16} color={FINCEPT.ORANGE} />
+ <Network size={16} color={colors.primary} />
<span style={{
- color: FINCEPT.ORANGE,
+ color: colors.primary,
fontSize: '12px',
fontWeight: 700,
letterSpacing: '0.5px',
@@ -469,9 +460,9 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.GREEN + '20',
- border: `1px solid ${FINCEPT.GREEN}`,
- color: FINCEPT.GREEN
+ backgroundColor: colors.success + '20',
+ border: `1px solid ${colors.success}`,
+ color: colors.success
}}>
READY
</div>
@@ -481,17 +472,17 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
{/* Left Sidebar - Agent Selection */}
<div style={{
width: '240px',
- borderRight: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
flexDirection: 'column'
}}>
<div style={{
padding: '10px 12px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.MUTED,
+ color: colors.textMuted,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -507,31 +498,31 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
onClick={() => setSelectedAgent(agent.id)}
style={{
padding: '10px',
- backgroundColor: isSelected ? FINCEPT.HOVER : 'transparent',
- border: `1px solid ${isSelected ? agent.color : FINCEPT.BORDER}`,
+ backgroundColor: isSelected ? '#1F1F1F' : 'transparent',
+ border: `1px solid ${isSelected ? agent.color : 'var(--ft-border-color, #2A2A2A)'}`,
cursor: 'pointer',
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
if (!isSelected) {
- e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG;
+ e.currentTarget.style.backgroundColor = colors.background;
e.currentTarget.style.borderColor = agent.color;
}
}}
onMouseLeave={(e) => {
if (!isSelected) {
e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>
<Icon size={14} style={{ color: agent.color }} />
- <span style={{ color: FINCEPT.WHITE, fontSize: '11px', fontWeight: 600, fontFamily: 'monospace' }}>
+ <span style={{ color: colors.text, fontSize: '11px', fontWeight: 600, fontFamily: 'monospace' }}>
{agent.name}
</span>
</div>
- <p style={{ color: FINCEPT.MUTED, fontSize: '9px', margin: '0 0 6px 0', lineHeight: '1.3' }}>
+ <p style={{ color: colors.textMuted, fontSize: '9px', margin: '0 0 6px 0', lineHeight: '1.3' }}>
{agent.description}
</p>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px' }}>
@@ -540,7 +531,7 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
key={sub}
style={{
padding: '1px 4px',
- backgroundColor: FINCEPT.DARK_BG,
+ backgroundColor: colors.background,
fontSize: '8px',
color: agent.color,
fontFamily: 'monospace'
@@ -550,7 +541,7 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
</span>
))}
{agent.subagents.length > 2 && (
- <span style={{ fontSize: '8px', color: FINCEPT.MUTED, fontFamily: 'monospace' }}>
+ <span style={{ fontSize: '8px', color: colors.textMuted, fontFamily: 'monospace' }}>
+{agent.subagents.length - 2}
</span>
)}
@@ -566,18 +557,18 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
{/* Task Input Section */}
<div style={{
padding: '16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
display: 'flex',
flexDirection: 'column',
gap: '12px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
{AgentIcon && <AgentIcon size={14} style={{ color: selectedAgentInfo?.color }} />}
- <span style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE, fontFamily: 'monospace' }}>
+ <span style={{ fontSize: '11px', fontWeight: 600, color: colors.text, fontFamily: 'monospace' }}>
{selectedAgentInfo?.name.toUpperCase()}
</span>
- <span style={{ fontSize: '10px', color: FINCEPT.MUTED }}>•</span>
- <span style={{ fontSize: '10px', color: FINCEPT.MUTED }}>
+ <span style={{ fontSize: '10px', color: colors.textMuted }}>•</span>
+ <span style={{ fontSize: '10px', color: colors.textMuted }}>
{selectedAgentInfo?.subagents.length} SUBAGENTS
</span>
</div>
@@ -590,9 +581,9 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
width: '100%',
height: '100px',
padding: '10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '11px',
fontFamily: 'monospace',
resize: 'vertical'
@@ -604,9 +595,9 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
disabled={isExecuting || !task.trim()}
style={{
padding: '8px 16px',
- backgroundColor: selectedAgentInfo?.color || FINCEPT.ORANGE,
+ backgroundColor: selectedAgentInfo?.color || colors.primary,
border: 'none',
- color: FINCEPT.DARK_BG,
+ color: colors.background,
fontSize: '11px',
fontWeight: 700,
cursor: isExecuting ? 'not-allowed' : 'pointer',
@@ -636,10 +627,10 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
{/* Examples Section */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel
}}>
- <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.MUTED, marginBottom: '8px', fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '10px', fontWeight: 700, color: colors.textMuted, marginBottom: '8px', fontFamily: 'monospace' }}>
EXAMPLE TASKS
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
@@ -649,9 +640,9 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
onClick={() => loadExample(example)}
style={{
padding: '6px 8px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: selectedAgentInfo?.color || FINCEPT.CYAN,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: selectedAgentInfo?.color || colors.accent,
fontSize: '10px',
textAlign: 'left',
cursor: 'pointer',
@@ -659,12 +650,12 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- e.currentTarget.style.borderColor = selectedAgentInfo?.color || FINCEPT.CYAN;
+ e.currentTarget.style.backgroundColor = '#1F1F1F';
+ e.currentTarget.style.borderColor = selectedAgentInfo?.color || colors.accent;
}}
onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG;
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.backgroundColor = colors.background;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}}
>
› {example}
@@ -681,7 +672,7 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
<div style={{
fontSize: '11px',
fontWeight: 700,
- color: FINCEPT.CYAN,
+ color: colors.accent,
marginBottom: '8px',
fontFamily: 'monospace',
letterSpacing: '0.5px',
@@ -689,19 +680,19 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
alignItems: 'center',
gap: '6px'
}}>
- <Cpu size={13} color={FINCEPT.CYAN} />
+ <Cpu size={13} color={colors.accent} />
EXECUTION LOG
</div>
<div style={{
padding: '12px 14px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `3px solid ${FINCEPT.CYAN}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${colors.accent}`,
maxHeight: '180px',
overflowY: 'auto',
fontSize: '13px',
fontFamily: 'monospace',
- color: FINCEPT.CYAN,
+ color: colors.accent,
lineHeight: '1.7'
}}>
{executionLog.map((log, idx) => (
@@ -716,10 +707,10 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
{error && (
<div style={{
padding: '12px 14px',
- backgroundColor: FINCEPT.RED + '15',
- border: `1px solid ${FINCEPT.RED}`,
- borderLeft: `3px solid ${FINCEPT.RED}`,
- color: FINCEPT.RED,
+ backgroundColor: colors.alert + '15',
+ border: `1px solid ${colors.alert}`,
+ borderLeft: `3px solid ${colors.alert}`,
+ color: colors.alert,
fontSize: '13px',
display: 'flex',
alignItems: 'center',
@@ -738,7 +729,7 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
<div style={{
fontSize: '11px',
fontWeight: 700,
- color: FINCEPT.YELLOW,
+ color: colors.warning,
marginBottom: '8px',
fontFamily: 'monospace',
letterSpacing: '0.5px',
@@ -746,7 +737,7 @@ export function DeepAgentPanel({ onOutputChange }: DeepAgentPanelProps) {
alignItems: 'center',
gap: '6px'
}}>
- <GitBranch size={13} color={FINCEPT.YELLOW} />
+ <GitBranch size={13} color={colors.warning} />
TASK BREAKDOWN
</div>
{todos.map(todo => renderTodo(todo))}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FactorDiscoveryPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FactorDiscoveryPanel.tsx
index 65fea4b43..572ccfec0 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FactorDiscoveryPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FactorDiscoveryPanel.tsx
@@ -26,22 +26,10 @@ import {
} from 'lucide-react';
import { rdAgentService, type DiscoveredFactor } from '@/services/aiQuantLab/rdAgentService';
import { showError, showWarning, showSuccess } from '@/utils/notifications';
-
-// Fincept Terminal Color Palette - PURPLE THEME
-const FINCEPT = {
- PURPLE: '#9D4EDD', // Primary theme color for Factor Discovery
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- GREEN: '#00D66F',
- ORANGE: '#FF8800',
- DARK_BG: '#0F0F0F',
- PANEL_BG: '#0F0F0F',
- CYAN: '#00E5FF',
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F'
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
export function FactorDiscoveryPanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [taskDescription, setTaskDescription] = useState('');
const [apiKey, setApiKey] = useState('');
const [targetMarket, setTargetMarket] = useState('US');
@@ -186,19 +174,19 @@ export function FactorDiscoveryPanel() {
};
return (
- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', backgroundColor: FINCEPT.DARK_BG }}>
+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', backgroundColor: colors.background }}>
{/* Terminal-style Header */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
gap: '12px'
}}>
- <Sparkles size={16} color={FINCEPT.PURPLE} />
+ <Sparkles size={16} color={colors.purple} />
<span style={{
- color: FINCEPT.PURPLE,
+ color: colors.purple,
fontSize: '12px',
fontWeight: 700,
letterSpacing: '0.5px',
@@ -212,9 +200,9 @@ export function FactorDiscoveryPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.PURPLE + '20',
- border: `1px solid ${FINCEPT.PURPLE}`,
- color: FINCEPT.PURPLE,
+ backgroundColor: colors.purple + '20',
+ border: `1px solid ${colors.purple}`,
+ color: colors.purple,
display: 'flex',
alignItems: 'center',
gap: '6px'
@@ -223,7 +211,7 @@ export function FactorDiscoveryPanel() {
width: '6px',
height: '6px',
borderRadius: '50%',
- backgroundColor: FINCEPT.PURPLE,
+ backgroundColor: colors.purple,
animation: 'pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite'
}} />
MINING IN PROGRESS
@@ -234,9 +222,9 @@ export function FactorDiscoveryPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.GREEN + '20',
- border: `1px solid ${FINCEPT.GREEN}`,
- color: FINCEPT.GREEN
+ backgroundColor: colors.success + '20',
+ border: `1px solid ${colors.success}`,
+ color: colors.success
}}>
{discoveredFactors.length} FACTORS DISCOVERED
</div>
@@ -247,18 +235,18 @@ export function FactorDiscoveryPanel() {
{/* Left Panel - Configuration */}
<div style={{
width: '360px',
- borderRight: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
flexDirection: 'column',
overflowY: 'auto'
}}>
<div style={{
padding: '10px 12px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.PURPLE,
+ color: colors.purple,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -273,7 +261,7 @@ export function FactorDiscoveryPanel() {
display: 'block',
fontSize: '9px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '8px',
letterSpacing: '0.5px'
@@ -288,9 +276,9 @@ export function FactorDiscoveryPanel() {
style={{
width: '100%',
padding: '10px 12px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontFamily: 'monospace',
outline: 'none',
@@ -301,7 +289,7 @@ export function FactorDiscoveryPanel() {
<div style={{
fontSize: '9px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
letterSpacing: '0.5px'
}}>
@@ -315,7 +303,7 @@ export function FactorDiscoveryPanel() {
textAlign: 'left',
fontSize: '9px',
fontFamily: 'monospace',
- color: FINCEPT.PURPLE,
+ color: colors.purple,
background: 'none',
border: 'none',
cursor: 'pointer',
@@ -341,7 +329,7 @@ export function FactorDiscoveryPanel() {
display: 'block',
fontSize: '9px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '8px',
letterSpacing: '0.5px'
@@ -356,9 +344,9 @@ export function FactorDiscoveryPanel() {
style={{
width: '100%',
padding: '10px 12px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontFamily: 'monospace',
fontWeight: 700,
@@ -368,7 +356,7 @@ export function FactorDiscoveryPanel() {
<div style={{
fontSize: '9px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginTop: '6px'
}}>
@@ -383,7 +371,7 @@ export function FactorDiscoveryPanel() {
display: 'block',
fontSize: '9px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '8px',
letterSpacing: '0.5px'
@@ -396,9 +384,9 @@ export function FactorDiscoveryPanel() {
style={{
width: '100%',
padding: '10px 12px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontFamily: 'monospace',
fontWeight: 700,
@@ -416,7 +404,7 @@ export function FactorDiscoveryPanel() {
display: 'block',
fontSize: '9px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '8px',
letterSpacing: '0.5px'
@@ -436,9 +424,9 @@ export function FactorDiscoveryPanel() {
style={{
width: '100%',
padding: '10px 12px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontFamily: 'monospace',
fontWeight: 700,
@@ -456,9 +444,9 @@ export function FactorDiscoveryPanel() {
style={{
flex: 1,
padding: '12px 16px',
- backgroundColor: (!taskDescription || !apiKey) ? FINCEPT.DARK_BG : FINCEPT.PURPLE,
+ backgroundColor: (!taskDescription || !apiKey) ? colors.background : colors.purple,
border: 'none',
- color: (!taskDescription || !apiKey) ? FINCEPT.WHITE : '#000000',
+ color: (!taskDescription || !apiKey) ? colors.text : '#000000',
opacity: (!taskDescription || !apiKey) ? 0.5 : 1,
fontSize: '11px',
fontWeight: 700,
@@ -499,9 +487,9 @@ export function FactorDiscoveryPanel() {
onClick={handleStop}
style={{
padding: '12px 16px',
- backgroundColor: FINCEPT.RED,
+ backgroundColor: colors.alert,
border: 'none',
- color: FINCEPT.WHITE,
+ color: colors.text,
fontSize: '11px',
fontWeight: 700,
fontFamily: 'monospace',
@@ -524,9 +512,9 @@ export function FactorDiscoveryPanel() {
{taskStatus && (
<div style={{
padding: '14px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `3px solid ${FINCEPT.PURPLE}`
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${colors.purple}`
}}>
<div style={{
display: 'flex',
@@ -538,7 +526,7 @@ export function FactorDiscoveryPanel() {
fontSize: '10px',
fontWeight: 700,
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
letterSpacing: '0.5px'
}}>
TASK STATUS
@@ -548,8 +536,8 @@ export function FactorDiscoveryPanel() {
fontWeight: 700,
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: taskStatus.status === 'completed' ? FINCEPT.GREEN :
- taskStatus.status === 'running' ? FINCEPT.PURPLE : FINCEPT.RED,
+ backgroundColor: taskStatus.status === 'completed' ? colors.success :
+ taskStatus.status === 'running' ? colors.purple : colors.alert,
color: '#000000',
letterSpacing: '0.5px'
}}>
@@ -560,20 +548,20 @@ export function FactorDiscoveryPanel() {
{taskStatus.progress !== undefined && (
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
- <span style={{ color: FINCEPT.WHITE, opacity: 0.5 }}>PROGRESS</span>
- <span style={{ color: FINCEPT.WHITE, fontWeight: 700 }}>{taskStatus.progress}%</span>
+ <span style={{ color: colors.text, opacity: 0.5 }}>PROGRESS</span>
+ <span style={{ color: colors.text, fontWeight: 700 }}>{taskStatus.progress}%</span>
</div>
<div style={{
width: '100%',
height: '3px',
- backgroundColor: FINCEPT.PANEL_BG,
+ backgroundColor: colors.panel,
overflow: 'hidden',
- border: `1px solid ${FINCEPT.BORDER}`
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}>
<div style={{
height: '100%',
width: `${taskStatus.progress}%`,
- backgroundColor: FINCEPT.PURPLE,
+ backgroundColor: colors.purple,
transition: 'width 0.3s ease'
}} />
</div>
@@ -581,26 +569,26 @@ export function FactorDiscoveryPanel() {
)}
{taskStatus.factors_generated !== undefined && (
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: FINCEPT.WHITE, opacity: 0.5 }}>FACTORS GENERATED</span>
- <span style={{ color: FINCEPT.GREEN, fontWeight: 700 }}>{taskStatus.factors_generated}</span>
+ <span style={{ color: colors.text, opacity: 0.5 }}>FACTORS GENERATED</span>
+ <span style={{ color: colors.success, fontWeight: 700 }}>{taskStatus.factors_generated}</span>
</div>
)}
{taskStatus.factors_tested !== undefined && (
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: FINCEPT.WHITE, opacity: 0.5 }}>FACTORS TESTED</span>
- <span style={{ color: FINCEPT.WHITE, fontWeight: 700 }}>{taskStatus.factors_tested}</span>
+ <span style={{ color: colors.text, opacity: 0.5 }}>FACTORS TESTED</span>
+ <span style={{ color: colors.text, fontWeight: 700 }}>{taskStatus.factors_tested}</span>
</div>
)}
{taskStatus.best_ic !== undefined && taskStatus.best_ic !== null && (
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: FINCEPT.WHITE, opacity: 0.5 }}>BEST IC</span>
- <span style={{ color: FINCEPT.GREEN, fontWeight: 700 }}>{taskStatus.best_ic.toFixed(4)}</span>
+ <span style={{ color: colors.text, opacity: 0.5 }}>BEST IC</span>
+ <span style={{ color: colors.success, fontWeight: 700 }}>{taskStatus.best_ic.toFixed(4)}</span>
</div>
)}
{taskStatus.elapsed_time && (
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: FINCEPT.WHITE, opacity: 0.5 }}>ELAPSED TIME</span>
- <span style={{ color: FINCEPT.WHITE, fontWeight: 700 }}>{taskStatus.elapsed_time}</span>
+ <span style={{ color: colors.text, opacity: 0.5 }}>ELAPSED TIME</span>
+ <span style={{ color: colors.text, fontWeight: 700 }}>{taskStatus.elapsed_time}</span>
</div>
)}
</div>
@@ -616,14 +604,14 @@ export function FactorDiscoveryPanel() {
{/* Factor List */}
<div style={{
width: '340px',
- borderRight: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
flexDirection: 'column'
}}>
<div style={{
padding: '10px 12px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between'
@@ -632,7 +620,7 @@ export function FactorDiscoveryPanel() {
fontSize: '10px',
fontWeight: 700,
fontFamily: 'monospace',
- color: FINCEPT.PURPLE,
+ color: colors.purple,
letterSpacing: '0.5px'
}}>
DISCOVERED FACTORS
@@ -642,9 +630,9 @@ export function FactorDiscoveryPanel() {
fontWeight: 700,
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.PURPLE + '20',
- border: `1px solid ${FINCEPT.PURPLE}`,
- color: FINCEPT.PURPLE
+ backgroundColor: colors.purple + '20',
+ border: `1px solid ${colors.purple}`,
+ color: colors.purple
}}>
{discoveredFactors.length}
</div>
@@ -658,9 +646,9 @@ export function FactorDiscoveryPanel() {
onClick={() => setSelectedFactor(factor)}
style={{
padding: '12px',
- backgroundColor: isSelected ? FINCEPT.HOVER : 'transparent',
- border: `1px solid ${isSelected ? FINCEPT.PURPLE : FINCEPT.BORDER}`,
- borderTop: idx === 0 ? `1px solid ${isSelected ? FINCEPT.PURPLE : FINCEPT.BORDER}` : '0',
+ backgroundColor: isSelected ? '#1F1F1F' : 'transparent',
+ border: `1px solid ${isSelected ? colors.purple : 'var(--ft-border-color, #2A2A2A)'}`,
+ borderTop: idx === 0 ? `1px solid ${isSelected ? colors.purple : 'var(--ft-border-color, #2A2A2A)'}` : '0',
cursor: 'pointer',
transition: 'all 0.15s',
marginTop: idx === 0 ? '0' : '-1px',
@@ -668,14 +656,14 @@ export function FactorDiscoveryPanel() {
}}
onMouseEnter={(e) => {
if (!isSelected) {
- e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG;
- e.currentTarget.style.borderColor = FINCEPT.PURPLE;
+ e.currentTarget.style.backgroundColor = colors.background;
+ e.currentTarget.style.borderColor = colors.purple;
}
}}
onMouseLeave={(e) => {
if (!isSelected) {
e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}
}}
>
@@ -684,7 +672,7 @@ export function FactorDiscoveryPanel() {
fontSize: '11px',
fontWeight: 700,
fontFamily: 'monospace',
- color: FINCEPT.WHITE
+ color: colors.text
}}>
{factor.name}
</span>
@@ -693,9 +681,9 @@ export function FactorDiscoveryPanel() {
fontWeight: 700,
fontFamily: 'monospace',
padding: '2px 6px',
- backgroundColor: FINCEPT.GREEN + '20',
- border: `1px solid ${FINCEPT.GREEN}`,
- color: FINCEPT.GREEN
+ backgroundColor: colors.success + '20',
+ border: `1px solid ${colors.success}`,
+ color: colors.success
}}>
IC: {factor.ic.toFixed(4)}
</div>
@@ -703,7 +691,7 @@ export function FactorDiscoveryPanel() {
<div style={{
fontSize: '9px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.6,
marginBottom: '8px',
lineHeight: '1.4'
@@ -711,11 +699,11 @@ export function FactorDiscoveryPanel() {
{factor.description}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px', fontSize: '9px', fontFamily: 'monospace' }}>
- <span style={{ color: FINCEPT.WHITE, opacity: 0.5 }}>
- SHARPE: <span style={{ color: FINCEPT.WHITE, opacity: 1, fontWeight: 700 }}>{factor.sharpe.toFixed(2)}</span>
+ <span style={{ color: colors.text, opacity: 0.5 }}>
+ SHARPE: <span style={{ color: colors.text, opacity: 1, fontWeight: 700 }}>{factor.sharpe.toFixed(2)}</span>
</span>
- <span style={{ color: FINCEPT.WHITE, opacity: 0.5 }}>
- RET: <span style={{ color: FINCEPT.GREEN, opacity: 1, fontWeight: 700 }}>{factor.performance_metrics.annual_return.toFixed(1)}%</span>
+ <span style={{ color: colors.text, opacity: 0.5 }}>
+ RET: <span style={{ color: colors.success, opacity: 1, fontWeight: 700 }}>{factor.performance_metrics.annual_return.toFixed(1)}%</span>
</span>
</div>
</button>
@@ -726,7 +714,7 @@ export function FactorDiscoveryPanel() {
{/* Factor Details */}
{selectedFactor && (
- <div style={{ flex: 1, overflowY: 'auto', padding: '16px', backgroundColor: FINCEPT.DARK_BG }}>
+ <div style={{ flex: 1, overflowY: 'auto', padding: '16px', backgroundColor: colors.background }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', maxWidth: '1200px' }}>
{/* Header */}
<div>
@@ -740,7 +728,7 @@ export function FactorDiscoveryPanel() {
fontSize: '18px',
fontWeight: 700,
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
letterSpacing: '0.5px'
}}>
{selectedFactor.name}
@@ -750,9 +738,9 @@ export function FactorDiscoveryPanel() {
fontWeight: 700,
fontFamily: 'monospace',
padding: '4px 10px',
- backgroundColor: FINCEPT.PURPLE + '20',
- border: `1px solid ${FINCEPT.PURPLE}`,
- color: FINCEPT.PURPLE
+ backgroundColor: colors.purple + '20',
+ border: `1px solid ${colors.purple}`,
+ color: colors.purple
}}>
FACTOR ID: {selectedFactor.factor_id}
</div>
@@ -760,7 +748,7 @@ export function FactorDiscoveryPanel() {
<div style={{
fontSize: '11px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.6,
lineHeight: '1.5'
}}>
@@ -774,7 +762,7 @@ export function FactorDiscoveryPanel() {
fontSize: '10px',
fontWeight: 700,
fontFamily: 'monospace',
- color: FINCEPT.PURPLE,
+ color: colors.purple,
letterSpacing: '0.5px',
marginBottom: '12px'
}}>
@@ -790,31 +778,31 @@ export function FactorDiscoveryPanel() {
value={selectedFactor.ic.toFixed(4)}
subtext={`± ${selectedFactor.ic_std.toFixed(4)}`}
icon={<TrendingUp size={16} />}
- color={FINCEPT.GREEN}
+ color={colors.success}
/>
<MetricCard
label="Sharpe Ratio"
value={selectedFactor.sharpe.toFixed(2)}
icon={<BarChart2 size={16} />}
- color={FINCEPT.ORANGE}
+ color={colors.primary}
/>
<MetricCard
label="Annual Return"
value={`${selectedFactor.performance_metrics.annual_return.toFixed(1)}%`}
icon={<DollarSign size={16} />}
- color={FINCEPT.GREEN}
+ color={colors.success}
/>
<MetricCard
label="Max Drawdown"
value={`${selectedFactor.performance_metrics.max_drawdown.toFixed(1)}%`}
icon={<AlertCircle size={16} />}
- color={FINCEPT.RED}
+ color={colors.alert}
/>
<MetricCard
label="Win Rate"
value={`${selectedFactor.performance_metrics.win_rate.toFixed(1)}%`}
icon={<Target size={16} />}
- color={FINCEPT.CYAN}
+ color={colors.accent}
/>
</div>
</div>
@@ -828,12 +816,12 @@ export function FactorDiscoveryPanel() {
marginBottom: '12px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Code size={16} color={FINCEPT.PURPLE} />
+ <Code size={16} color={colors.purple} />
<span style={{
fontSize: '10px',
fontWeight: 700,
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
letterSpacing: '0.5px'
}}>
FACTOR IMPLEMENTATION
@@ -847,8 +835,8 @@ export function FactorDiscoveryPanel() {
gap: '6px',
padding: '8px 12px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.PURPLE}`,
- color: FINCEPT.PURPLE,
+ border: `1px solid ${colors.purple}`,
+ color: colors.purple,
fontSize: '10px',
fontWeight: 700,
fontFamily: 'monospace',
@@ -857,7 +845,7 @@ export function FactorDiscoveryPanel() {
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.PURPLE + '20';
+ e.currentTarget.style.backgroundColor = colors.purple + '20';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
@@ -869,9 +857,9 @@ export function FactorDiscoveryPanel() {
</div>
<pre style={{
padding: '14px',
- backgroundColor: FINCEPT.PANEL_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.panel,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontFamily: 'monospace',
overflowX: 'auto',
@@ -882,12 +870,12 @@ export function FactorDiscoveryPanel() {
</div>
{/* Action Buttons */}
- <div style={{ display: 'flex', gap: '12px', paddingTop: '16px', borderTop: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{ display: 'flex', gap: '12px', paddingTop: '16px', borderTop: `1px solid ${'var(--ft-border-color, #2A2A2A)'}` }}>
<button
style={{
flex: 1,
padding: '12px 16px',
- backgroundColor: FINCEPT.PURPLE,
+ backgroundColor: colors.purple,
border: 'none',
color: '#000000',
fontSize: '11px',
@@ -915,8 +903,8 @@ export function FactorDiscoveryPanel() {
style={{
padding: '12px 24px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.PURPLE}`,
- color: FINCEPT.PURPLE,
+ border: `1px solid ${colors.purple}`,
+ color: colors.purple,
fontSize: '11px',
fontWeight: 700,
fontFamily: 'monospace',
@@ -929,7 +917,7 @@ export function FactorDiscoveryPanel() {
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.PURPLE + '20';
+ e.currentTarget.style.backgroundColor = colors.purple + '20';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
@@ -952,11 +940,11 @@ export function FactorDiscoveryPanel() {
flexDirection: 'column',
gap: '12px'
}}>
- <Sparkles size={32} color={FINCEPT.BORDER} />
+ <Sparkles size={32} color={'var(--ft-border-color, #2A2A2A)'} />
<div style={{
fontSize: '11px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
textAlign: 'center',
letterSpacing: '0.5px'
@@ -1006,8 +994,8 @@ function MetricCard({
return (
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: 'var(--ft-color-panel, #0a0a0a)',
+ border: '1px solid var(--ft-border-color, #2A2A2A)',
borderLeft: `3px solid ${color}`
}}>
<div style={{
@@ -1017,9 +1005,9 @@ function MetricCard({
marginBottom: '8px'
}}>
<span style={{
- fontSize: '9px',
- fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ fontSize: 'var(--ft-font-size-tiny, 9px)',
+ fontFamily: 'var(--ft-font-family, monospace)',
+ color: 'var(--ft-color-text, #FFFFFF)',
opacity: 0.5,
letterSpacing: '0.5px'
}}>
@@ -1030,16 +1018,16 @@ function MetricCard({
<div style={{
fontSize: '18px',
fontWeight: 700,
- fontFamily: 'monospace',
+ fontFamily: 'var(--ft-font-family, monospace)',
color
}}>
{value}
</div>
{subtext && (
<div style={{
- fontSize: '9px',
- fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ fontSize: 'var(--ft-font-size-tiny, 9px)',
+ fontFamily: 'var(--ft-font-family, monospace)',
+ color: 'var(--ft-color-text, #FFFFFF)',
opacity: 0.5,
marginTop: '4px'
}}>
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/HFTPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/HFTPanel.tsx
index 18e010bfa..d9b567448 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/HFTPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/HFTPanel.tsx
@@ -5,6 +5,7 @@
*/
import React, { useState, useEffect, useRef } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import {
Gauge,
Activity,
@@ -23,19 +24,6 @@ import {
Loader2
} from 'lucide-react';
-const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- RED: '#FF3B3B', // Primary theme color for HFT
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- BORDER: '#2A2A2A',
- CYAN: '#00E5FF',
- MUTED: '#4A4A4A',
- HOVER: '#1F1F1F'
-};
interface OrderBookLevel {
price: number;
@@ -50,6 +38,7 @@ interface MarketMakingQuotes {
}
export function HFTPanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [symbol, setSymbol] = useState('AAPL');
const [orderBookCreated, setOrderBookCreated] = useState(false);
const [isLive, setIsLive] = useState(false);
@@ -149,20 +138,20 @@ export function HFTPanel() {
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: FINCEPT.DARK_BG
+ backgroundColor: colors.background
}}>
{/* Terminal-style Header */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
gap: '12px'
}}>
- <Activity size={16} color={FINCEPT.RED} />
+ <Activity size={16} color={colors.alert} />
<span style={{
- color: FINCEPT.RED,
+ color: colors.alert,
fontSize: '12px',
fontWeight: 700,
letterSpacing: '0.5px',
@@ -178,9 +167,9 @@ export function HFTPanel() {
fontSize: '11px',
fontFamily: 'monospace',
padding: '3px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.ORANGE}`,
- color: FINCEPT.ORANGE,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.primary,
fontWeight: 700
}}>
{symbol}
@@ -192,9 +181,9 @@ export function HFTPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.CYAN}`,
- color: FINCEPT.CYAN
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.accent}`,
+ color: colors.accent
}}>
{latencyStats.mean}μs
</div>
@@ -205,14 +194,14 @@ export function HFTPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.GREEN + '20',
- border: `1px solid ${FINCEPT.GREEN}`,
- color: FINCEPT.GREEN,
+ backgroundColor: colors.success + '20',
+ border: `1px solid ${colors.success}`,
+ color: colors.success,
display: 'flex',
alignItems: 'center',
gap: '4px'
}}>
- <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: FINCEPT.GREEN, animation: 'pulse 2s infinite' }} />
+ <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: colors.success, animation: 'pulse 2s infinite' }} />
LIVE
</div>
)}
@@ -221,9 +210,9 @@ export function HFTPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: orderBookCreated ? (isLive ? FINCEPT.GREEN + '20' : FINCEPT.DARK_BG) : FINCEPT.DARK_BG,
- border: `1px solid ${orderBookCreated ? (isLive ? FINCEPT.GREEN : FINCEPT.BORDER) : FINCEPT.BORDER}`,
- color: orderBookCreated ? (isLive ? FINCEPT.GREEN : FINCEPT.MUTED) : FINCEPT.MUTED
+ backgroundColor: orderBookCreated ? (isLive ? colors.success + '20' : colors.background) : colors.background,
+ border: `1px solid ${orderBookCreated ? (isLive ? colors.success : 'var(--ft-border-color, #2A2A2A)') : 'var(--ft-border-color, #2A2A2A)'}`,
+ color: orderBookCreated ? (isLive ? colors.success : colors.textMuted) : colors.textMuted
}}>
{isLive ? 'STREAMING' : orderBookCreated ? 'READY' : 'IDLE'}
</div>
@@ -245,9 +234,9 @@ export function HFTPanel() {
maxWidth: '500px',
width: '100%',
padding: '24px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `3px solid ${FINCEPT.RED}`
+ backgroundColor: colors.panel,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${colors.alert}`
}}>
<div style={{
display: 'flex',
@@ -255,11 +244,11 @@ export function HFTPanel() {
gap: '10px',
marginBottom: '20px'
}}>
- <Gauge size={18} color={FINCEPT.RED} />
+ <Gauge size={18} color={colors.alert} />
<span style={{
fontSize: '12px',
fontWeight: 700,
- color: FINCEPT.RED,
+ color: colors.alert,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -272,7 +261,7 @@ export function HFTPanel() {
display: 'block',
fontSize: '9px',
marginBottom: '6px',
- color: FINCEPT.WHITE,
+ color: colors.text,
fontFamily: 'monospace',
letterSpacing: '0.5px',
opacity: 0.7
@@ -287,9 +276,9 @@ export function HFTPanel() {
style={{
width: '100%',
padding: '12px 14px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.RED,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.alert,
fontSize: '16px',
fontFamily: 'monospace',
fontWeight: 700,
@@ -297,10 +286,10 @@ export function HFTPanel() {
transition: 'border-color 0.15s'
}}
onFocus={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.RED;
+ e.currentTarget.style.borderColor = colors.alert;
}}
onBlur={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}}
/>
</div>
@@ -310,7 +299,7 @@ export function HFTPanel() {
style={{
width: '100%',
padding: '14px 20px',
- backgroundColor: FINCEPT.RED,
+ backgroundColor: colors.alert,
border: 'none',
color: '#000000',
fontSize: '11px',
@@ -338,15 +327,15 @@ export function HFTPanel() {
<div style={{
marginTop: '16px',
padding: '12px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.7,
lineHeight: '1.6'
}}>
- <strong style={{ color: FINCEPT.RED }}>Note:</strong> This creates a simulated HFT order book with real-time price updates, microstructure analytics, and market making capabilities.
+ <strong style={{ color: colors.alert }}>Note:</strong> This creates a simulated HFT order book with real-time price updates, microstructure analytics, and market making capabilities.
</div>
</div>
</div>
@@ -355,74 +344,74 @@ export function HFTPanel() {
{/* Metrics Bar */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel
}}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px' }}>
<div style={{
padding: '10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `3px solid ${FINCEPT.RED}`
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${colors.alert}`
}}>
- <div style={{ fontSize: '9px', color: FINCEPT.WHITE, opacity: 0.5, marginBottom: '3px', fontFamily: 'monospace', letterSpacing: '0.5px' }}>
+ <div style={{ fontSize: '9px', color: colors.text, opacity: 0.5, marginBottom: '3px', fontFamily: 'monospace', letterSpacing: '0.5px' }}>
MID PRICE
</div>
- <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.RED, fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '16px', fontWeight: 700, color: colors.alert, fontFamily: 'monospace' }}>
${midPrice.toFixed(2)}
</div>
</div>
<div style={{
padding: '10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `3px solid ${FINCEPT.RED}`
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${colors.alert}`
}}>
- <div style={{ fontSize: '9px', color: FINCEPT.WHITE, opacity: 0.5, marginBottom: '3px', fontFamily: 'monospace', letterSpacing: '0.5px' }}>
+ <div style={{ fontSize: '9px', color: colors.text, opacity: 0.5, marginBottom: '3px', fontFamily: 'monospace', letterSpacing: '0.5px' }}>
SPREAD
</div>
- <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.RED, fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '16px', fontWeight: 700, color: colors.alert, fontFamily: 'monospace' }}>
${spread.toFixed(3)}
</div>
</div>
<div style={{
padding: '10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}>
- <div style={{ fontSize: '9px', color: FINCEPT.WHITE, opacity: 0.5, marginBottom: '3px', fontFamily: 'monospace', letterSpacing: '0.5px' }}>
+ <div style={{ fontSize: '9px', color: colors.text, opacity: 0.5, marginBottom: '3px', fontFamily: 'monospace', letterSpacing: '0.5px' }}>
MEAN LATENCY
</div>
- <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.CYAN, fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '16px', fontWeight: 700, color: colors.accent, fontFamily: 'monospace' }}>
{latencyStats.mean}μs
</div>
</div>
<div style={{
padding: '10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}>
- <div style={{ fontSize: '9px', color: FINCEPT.WHITE, opacity: 0.5, marginBottom: '3px', fontFamily: 'monospace', letterSpacing: '0.5px' }}>
+ <div style={{ fontSize: '9px', color: colors.text, opacity: 0.5, marginBottom: '3px', fontFamily: 'monospace', letterSpacing: '0.5px' }}>
P99 LATENCY
</div>
- <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.WHITE, opacity: 0.7, fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '16px', fontWeight: 700, color: colors.text, opacity: 0.7, fontFamily: 'monospace' }}>
{latencyStats.p99}μs
</div>
</div>
<div style={{
padding: '10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${microstructure.toxicity_score > 0.5 ? FINCEPT.RED : FINCEPT.GREEN}`,
- borderLeft: `3px solid ${microstructure.toxicity_score > 0.5 ? FINCEPT.RED : FINCEPT.GREEN}`
+ backgroundColor: colors.background,
+ border: `1px solid ${microstructure.toxicity_score > 0.5 ? colors.alert : colors.success}`,
+ borderLeft: `3px solid ${microstructure.toxicity_score > 0.5 ? colors.alert : colors.success}`
}}>
- <div style={{ fontSize: '9px', color: FINCEPT.WHITE, opacity: 0.5, marginBottom: '3px', fontFamily: 'monospace', letterSpacing: '0.5px' }}>
+ <div style={{ fontSize: '9px', color: colors.text, opacity: 0.5, marginBottom: '3px', fontFamily: 'monospace', letterSpacing: '0.5px' }}>
TOXICITY
</div>
- <div style={{ fontSize: '14px', fontWeight: 700, color: microstructure.toxicity_score > 0.5 ? FINCEPT.RED : FINCEPT.GREEN, fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '14px', fontWeight: 700, color: microstructure.toxicity_score > 0.5 ? colors.alert : colors.success, fontFamily: 'monospace' }}>
{microstructure.toxicity_score > 0.5 ? 'HIGH' : 'LOW'}
</div>
</div>
@@ -432,18 +421,18 @@ export function HFTPanel() {
{/* Control Bar */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
gap: '12px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Network size={14} color={FINCEPT.RED} />
+ <Network size={14} color={colors.alert} />
<span style={{
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.RED,
+ color: colors.alert,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -456,7 +445,7 @@ export function HFTPanel() {
onClick={handleStartLive}
style={{
padding: '8px 16px',
- backgroundColor: FINCEPT.GREEN,
+ backgroundColor: colors.success,
border: 'none',
color: '#000000',
fontSize: '10px',
@@ -484,7 +473,7 @@ export function HFTPanel() {
onClick={handleStopLive}
style={{
padding: '8px 16px',
- backgroundColor: FINCEPT.RED,
+ backgroundColor: colors.alert,
border: 'none',
color: '#000000',
fontSize: '10px',
@@ -513,8 +502,8 @@ export function HFTPanel() {
style={{
padding: '8px 16px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.RED}`,
- color: FINCEPT.RED,
+ border: `1px solid ${colors.alert}`,
+ color: colors.alert,
fontSize: '10px',
fontWeight: 700,
cursor: 'pointer',
@@ -526,7 +515,7 @@ export function HFTPanel() {
transition: 'background-color 0.15s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.RED + '20';
+ e.currentTarget.style.backgroundColor = colors.alert + '20';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
@@ -540,16 +529,16 @@ export function HFTPanel() {
{/* Order Book Display */}
<div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
{/* Order Book */}
- <div style={{ flex: 1, padding: '16px', backgroundColor: FINCEPT.DARK_BG, borderRight: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{ flex: 1, padding: '16px', backgroundColor: colors.background, borderRight: `1px solid ${'var(--ft-border-color, #2A2A2A)'}` }}>
{/* Header Row */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px', marginBottom: '12px', padding: '0 8px' }}>
- <div style={{ textAlign: 'right', fontSize: '10px', fontWeight: 700, color: FINCEPT.MUTED, fontFamily: 'monospace' }}>
+ <div style={{ textAlign: 'right', fontSize: '10px', fontWeight: 700, color: colors.textMuted, fontFamily: 'monospace' }}>
BID SIZE
</div>
- <div style={{ textAlign: 'center', fontSize: '10px', fontWeight: 700, color: FINCEPT.MUTED, fontFamily: 'monospace' }}>
+ <div style={{ textAlign: 'center', fontSize: '10px', fontWeight: 700, color: colors.textMuted, fontFamily: 'monospace' }}>
PRICE
</div>
- <div style={{ textAlign: 'left', fontSize: '10px', fontWeight: 700, color: FINCEPT.MUTED, fontFamily: 'monospace' }}>
+ <div style={{ textAlign: 'left', fontSize: '10px', fontWeight: 700, color: colors.textMuted, fontFamily: 'monospace' }}>
ASK SIZE
</div>
</div>
@@ -564,29 +553,29 @@ export function HFTPanel() {
<div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px', alignItems: 'center' }}>
{/* Bid Side */}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '6px' }}>
- <span style={{ fontSize: '11px', fontFamily: 'monospace', color: FINCEPT.GREEN, minWidth: '50px', textAlign: 'right' }}>
+ <span style={{ fontSize: '11px', fontFamily: 'monospace', color: colors.success, minWidth: '50px', textAlign: 'right' }}>
{bid?.size || ''}
</span>
<div style={{
height: '20px',
width: `${bid ? (bid.size / maxBidSize) * 100 : 0}%`,
maxWidth: '150px',
- backgroundColor: FINCEPT.GREEN + '30',
- borderRight: `2px solid ${FINCEPT.GREEN}`
+ backgroundColor: colors.success + '30',
+ borderRight: `2px solid ${colors.success}`
}} />
</div>
{/* Price */}
<div style={{ textAlign: 'center' }}>
- <div style={{ fontSize: '12px', fontFamily: 'monospace', fontWeight: 600, color: FINCEPT.WHITE }}>
+ <div style={{ fontSize: '12px', fontFamily: 'monospace', fontWeight: 600, color: colors.text }}>
{bid ? bid.price.toFixed(2) : ''}
</div>
{i === 0 && (
- <div style={{ fontSize: '9px', fontFamily: 'monospace', color: FINCEPT.ORANGE, marginTop: '2px' }}>
+ <div style={{ fontSize: '9px', fontFamily: 'monospace', color: colors.primary, marginTop: '2px' }}>
↕ ${spread.toFixed(3)}
</div>
)}
- <div style={{ fontSize: '12px', fontFamily: 'monospace', fontWeight: 600, color: FINCEPT.WHITE, marginTop: i === 0 ? '2px' : '0' }}>
+ <div style={{ fontSize: '12px', fontFamily: 'monospace', fontWeight: 600, color: colors.text, marginTop: i === 0 ? '2px' : '0' }}>
{ask ? ask.price.toFixed(2) : ''}
</div>
</div>
@@ -597,10 +586,10 @@ export function HFTPanel() {
height: '20px',
width: `${ask ? (ask.size / maxAskSize) * 100 : 0}%`,
maxWidth: '150px',
- backgroundColor: FINCEPT.RED + '30',
- borderLeft: `2px solid ${FINCEPT.RED}`
+ backgroundColor: colors.alert + '30',
+ borderLeft: `2px solid ${colors.alert}`
}} />
- <span style={{ fontSize: '11px', fontFamily: 'monospace', color: FINCEPT.RED, minWidth: '50px' }}>
+ <span style={{ fontSize: '11px', fontFamily: 'monospace', color: colors.alert, minWidth: '50px' }}>
{ask?.size || ''}
</span>
</div>
@@ -611,13 +600,13 @@ export function HFTPanel() {
</div>
{/* Right Panel - Microstructure & Market Making */}
- <div style={{ width: '300px', display: 'flex', flexDirection: 'column', gap: '0', borderLeft: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{ width: '300px', display: 'flex', flexDirection: 'column', gap: '0', borderLeft: `1px solid ${'var(--ft-border-color, #2A2A2A)'}` }}>
{/* Microstructure Section */}
- <div style={{ padding: '16px', borderBottom: `1px solid ${FINCEPT.BORDER}`, backgroundColor: FINCEPT.PANEL_BG }}>
+ <div style={{ padding: '16px', borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`, backgroundColor: colors.panel }}>
<div style={{
fontSize: '11px',
fontWeight: 700,
- color: FINCEPT.CYAN,
+ color: colors.accent,
marginBottom: '12px',
fontFamily: 'monospace',
letterSpacing: '0.5px',
@@ -625,7 +614,7 @@ export function HFTPanel() {
alignItems: 'center',
gap: '6px'
}}>
- <Cpu size={13} color={FINCEPT.CYAN} />
+ <Cpu size={13} color={colors.accent} />
MICROSTRUCTURE
</div>
@@ -634,7 +623,7 @@ export function HFTPanel() {
<div>
<div style={{
fontSize: '9px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '6px',
fontFamily: 'monospace',
@@ -646,8 +635,8 @@ export function HFTPanel() {
<div style={{
flex: 1,
height: '8px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
position: 'relative',
overflow: 'hidden'
}}>
@@ -655,7 +644,7 @@ export function HFTPanel() {
position: 'absolute',
height: '100%',
width: `${Math.abs(microstructure.depth_imbalance) * 100}%`,
- backgroundColor: microstructure.depth_imbalance > 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ backgroundColor: microstructure.depth_imbalance > 0 ? colors.success : colors.alert,
left: microstructure.depth_imbalance < 0 ? 'auto' : '0',
right: microstructure.depth_imbalance < 0 ? '0' : 'auto'
}} />
@@ -663,7 +652,7 @@ export function HFTPanel() {
<span style={{
fontSize: '11px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
fontWeight: 600,
minWidth: '45px'
}}>
@@ -676,13 +665,13 @@ export function HFTPanel() {
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div style={{
padding: '8px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.GREEN}`,
- borderLeft: `2px solid ${FINCEPT.GREEN}`
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.success}`,
+ borderLeft: `2px solid ${colors.success}`
}}>
<div style={{
fontSize: '9px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '3px',
fontFamily: 'monospace',
@@ -693,7 +682,7 @@ export function HFTPanel() {
<div style={{
fontSize: '11px',
fontFamily: 'monospace',
- color: FINCEPT.GREEN,
+ color: colors.success,
fontWeight: 700
}}>
${microstructure.vwap_bid.toFixed(2)}
@@ -701,13 +690,13 @@ export function HFTPanel() {
</div>
<div style={{
padding: '8px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.RED}`,
- borderLeft: `2px solid ${FINCEPT.RED}`
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.alert}`,
+ borderLeft: `2px solid ${colors.alert}`
}}>
<div style={{
fontSize: '9px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '3px',
fontFamily: 'monospace',
@@ -718,7 +707,7 @@ export function HFTPanel() {
<div style={{
fontSize: '11px',
fontFamily: 'monospace',
- color: FINCEPT.RED,
+ color: colors.alert,
fontWeight: 700
}}>
${microstructure.vwap_ask.toFixed(2)}
@@ -729,11 +718,11 @@ export function HFTPanel() {
</div>
{/* Market Making Section */}
- <div style={{ padding: '16px', backgroundColor: FINCEPT.DARK_BG, flex: 1 }}>
+ <div style={{ padding: '16px', backgroundColor: colors.background, flex: 1 }}>
<div style={{
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.RED,
+ color: colors.alert,
marginBottom: '12px',
fontFamily: 'monospace',
letterSpacing: '0.5px',
@@ -741,7 +730,7 @@ export function HFTPanel() {
alignItems: 'center',
gap: '6px'
}}>
- <DollarSign size={13} color={FINCEPT.RED} />
+ <DollarSign size={13} color={colors.alert} />
MARKET MAKING
</div>
@@ -750,13 +739,13 @@ export function HFTPanel() {
{/* Bid Quote */}
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.GREEN + '15',
- border: `1px solid ${FINCEPT.GREEN}`,
- borderLeft: `3px solid ${FINCEPT.GREEN}`
+ backgroundColor: colors.success + '15',
+ border: `1px solid ${colors.success}`,
+ borderLeft: `3px solid ${colors.success}`
}}>
<div style={{
fontSize: '9px',
- color: FINCEPT.GREEN,
+ color: colors.success,
marginBottom: '6px',
fontFamily: 'monospace',
fontWeight: 700,
@@ -768,7 +757,7 @@ export function HFTPanel() {
<span style={{
fontSize: '16px',
fontFamily: 'monospace',
- color: FINCEPT.GREEN,
+ color: colors.success,
fontWeight: 700
}}>
${marketMakingQuotes.bid.price.toFixed(2)}
@@ -776,7 +765,7 @@ export function HFTPanel() {
<span style={{
fontSize: '10px',
fontFamily: 'monospace',
- color: FINCEPT.GREEN,
+ color: colors.success,
opacity: 0.8
}}>
{marketMakingQuotes.bid.size}
@@ -787,13 +776,13 @@ export function HFTPanel() {
{/* Ask Quote */}
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.RED + '15',
- border: `1px solid ${FINCEPT.RED}`,
- borderLeft: `3px solid ${FINCEPT.RED}`
+ backgroundColor: colors.alert + '15',
+ border: `1px solid ${colors.alert}`,
+ borderLeft: `3px solid ${colors.alert}`
}}>
<div style={{
fontSize: '9px',
- color: FINCEPT.RED,
+ color: colors.alert,
marginBottom: '6px',
fontFamily: 'monospace',
fontWeight: 700,
@@ -805,7 +794,7 @@ export function HFTPanel() {
<span style={{
fontSize: '16px',
fontFamily: 'monospace',
- color: FINCEPT.RED,
+ color: colors.alert,
fontWeight: 700
}}>
${marketMakingQuotes.ask.price.toFixed(2)}
@@ -813,7 +802,7 @@ export function HFTPanel() {
<span style={{
fontSize: '10px',
fontFamily: 'monospace',
- color: FINCEPT.RED,
+ color: colors.alert,
opacity: 0.8
}}>
{marketMakingQuotes.ask.size}
@@ -825,12 +814,12 @@ export function HFTPanel() {
<div style={{
textAlign: 'center',
padding: '8px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}>
<span style={{
fontSize: '9px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.6,
fontFamily: 'monospace',
letterSpacing: '0.5px'
@@ -843,13 +832,13 @@ export function HFTPanel() {
<div style={{
textAlign: 'center',
padding: '30px 20px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}>
- <DollarSign size={32} color={FINCEPT.MUTED} style={{ margin: '0 auto 12px' }} />
+ <DollarSign size={32} color={colors.textMuted} style={{ margin: '0 auto 12px' }} />
<div style={{
fontSize: '10px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.6,
fontFamily: 'monospace',
lineHeight: '1.6'
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/LiveSignalsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/LiveSignalsPanel.tsx
index 0617d2144..3ab90ac77 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/LiveSignalsPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/LiveSignalsPanel.tsx
@@ -24,19 +24,7 @@ import {
Filter
} from 'lucide-react';
import { qlibService } from '@/services/aiQuantLab/qlibService';
-
-// Fincept Terminal Color Palette - GREEN THEME
-const FINCEPT = {
- GREEN: '#00D66F', // Primary theme color for Live Signals
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- ORANGE: '#FF8800',
- DARK_BG: '#0F0F0F',
- PANEL_BG: '#0F0F0F',
- CYAN: '#00E5FF',
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F'
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface Signal {
id: string;
@@ -50,6 +38,7 @@ interface Signal {
}
export function LiveSignalsPanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [isStreaming, setIsStreaming] = useState(false);
const [signals, setSignals] = useState<Signal[]>([]);
const [selectedModel, setSelectedModel] = useState('lightgbm');
@@ -138,19 +127,19 @@ export function LiveSignalsPanel() {
});
return (
- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', backgroundColor: FINCEPT.DARK_BG }}>
+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', backgroundColor: colors.background }}>
{/* Terminal-style Header */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
gap: '12px'
}}>
- <Activity size={16} color={FINCEPT.GREEN} />
+ <Activity size={16} color={colors.success} />
<span style={{
- color: FINCEPT.GREEN,
+ color: colors.success,
fontSize: '12px',
fontWeight: 700,
letterSpacing: '0.5px',
@@ -163,9 +152,9 @@ export function LiveSignalsPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: isStreaming ? FINCEPT.GREEN + '20' : FINCEPT.BORDER,
- border: `1px solid ${isStreaming ? FINCEPT.GREEN : FINCEPT.BORDER}`,
- color: isStreaming ? FINCEPT.GREEN : FINCEPT.WHITE,
+ backgroundColor: isStreaming ? colors.success + '20' : 'var(--ft-border-color, #2A2A2A)',
+ border: `1px solid ${isStreaming ? colors.success : 'var(--ft-border-color, #2A2A2A)'}`,
+ color: isStreaming ? colors.success : colors.text,
opacity: isStreaming ? 1 : 0.5
}}>
{isStreaming ? '● STREAMING' : '○ OFFLINE'}
@@ -175,9 +164,9 @@ export function LiveSignalsPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.GREEN + '20',
- border: `1px solid ${FINCEPT.GREEN}`,
- color: FINCEPT.GREEN
+ backgroundColor: colors.success + '20',
+ border: `1px solid ${colors.success}`,
+ color: colors.success
}}>
{filteredSignals.length} SIGNALS
</div>
@@ -188,17 +177,17 @@ export function LiveSignalsPanel() {
{/* Left Panel - Configuration */}
<div style={{
width: '320px',
- borderRight: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
flexDirection: 'column'
}}>
<div style={{
padding: '10px 12px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.GREEN,
+ color: colors.success,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -215,7 +204,7 @@ export function LiveSignalsPanel() {
gap: '6px',
fontSize: '9px',
fontWeight: 700,
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '8px',
fontFamily: 'monospace',
@@ -231,9 +220,9 @@ export function LiveSignalsPanel() {
style={{
width: '100%',
padding: '10px 12px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '10px',
fontFamily: 'monospace',
fontWeight: 700,
@@ -258,7 +247,7 @@ export function LiveSignalsPanel() {
gap: '6px',
fontSize: '9px',
fontWeight: 700,
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '8px',
fontFamily: 'monospace',
@@ -275,9 +264,9 @@ export function LiveSignalsPanel() {
style={{
width: '100%',
padding: '10px 12px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '10px',
fontFamily: 'monospace',
outline: 'none',
@@ -296,7 +285,7 @@ export function LiveSignalsPanel() {
gap: '6px',
fontSize: '9px',
fontWeight: 700,
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '8px',
fontFamily: 'monospace',
@@ -317,9 +306,9 @@ export function LiveSignalsPanel() {
style={{
width: '100%',
padding: '10px 12px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '10px',
fontFamily: 'monospace',
fontWeight: 700,
@@ -338,7 +327,7 @@ export function LiveSignalsPanel() {
gap: '6px',
fontSize: '9px',
fontWeight: 700,
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '8px',
fontFamily: 'monospace',
@@ -355,11 +344,11 @@ export function LiveSignalsPanel() {
style={{
flex: 1,
padding: '8px 12px',
- backgroundColor: signalFilter === filter ? FINCEPT.GREEN : FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: idx === 0 ? `1px solid ${FINCEPT.BORDER}` : '0',
+ backgroundColor: signalFilter === filter ? colors.success : colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: idx === 0 ? `1px solid ${'var(--ft-border-color, #2A2A2A)'}` : '0',
marginLeft: idx === 0 ? '0' : '-1px',
- color: signalFilter === filter ? '#000000' : FINCEPT.WHITE,
+ color: signalFilter === filter ? '#000000' : colors.text,
opacity: signalFilter === filter ? 1 : 0.7,
fontSize: '10px',
fontWeight: 700,
@@ -370,14 +359,14 @@ export function LiveSignalsPanel() {
}}
onMouseEnter={(e) => {
if (signalFilter !== filter) {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- e.currentTarget.style.borderColor = FINCEPT.GREEN;
+ e.currentTarget.style.backgroundColor = '#1F1F1F';
+ e.currentTarget.style.borderColor = colors.success;
}
}}
onMouseLeave={(e) => {
if (signalFilter !== filter) {
- e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG;
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.backgroundColor = colors.background;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}
}}
>
@@ -389,7 +378,7 @@ export function LiveSignalsPanel() {
</div>
{/* Action Buttons */}
- <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}`, padding: '12px', display: 'flex', gap: '8px' }}>
+ <div style={{ borderTop: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`, padding: '12px', display: 'flex', gap: '8px' }}>
{!isStreaming ? (
<button
onClick={handleStartStreaming}
@@ -397,9 +386,9 @@ export function LiveSignalsPanel() {
style={{
flex: 1,
padding: '12px 16px',
- backgroundColor: (!instruments || !selectedModel) ? FINCEPT.DARK_BG : FINCEPT.GREEN,
+ backgroundColor: (!instruments || !selectedModel) ? colors.background : colors.success,
border: 'none',
- color: (!instruments || !selectedModel) ? FINCEPT.WHITE : '#000000',
+ color: (!instruments || !selectedModel) ? colors.text : '#000000',
opacity: (!instruments || !selectedModel) ? 0.5 : 1,
fontSize: '11px',
fontWeight: 700,
@@ -432,9 +421,9 @@ export function LiveSignalsPanel() {
style={{
flex: 1,
padding: '12px 16px',
- backgroundColor: FINCEPT.RED,
+ backgroundColor: colors.alert,
border: 'none',
- color: FINCEPT.WHITE,
+ color: colors.text,
fontSize: '11px',
fontWeight: 700,
fontFamily: 'monospace',
@@ -461,16 +450,16 @@ export function LiveSignalsPanel() {
</div>
{/* Right Panel - Signals Feed */}
- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', backgroundColor: FINCEPT.DARK_BG }}>
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', backgroundColor: colors.background }}>
<div style={{
padding: '10px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.GREEN,
+ color: colors.success,
fontFamily: 'monospace',
letterSpacing: '0.5px',
- backgroundColor: FINCEPT.PANEL_BG,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between'
@@ -479,7 +468,7 @@ export function LiveSignalsPanel() {
{filteredSignals.length > 0 && (
<span style={{
fontSize: '9px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5
}}>
LAST UPDATE: {new Date().toLocaleTimeString()}
@@ -505,11 +494,11 @@ export function LiveSignalsPanel() {
}}>
{isStreaming ? (
<>
- <RefreshCw size={32} color={FINCEPT.GREEN} style={{ animation: 'spin 2s linear infinite' }} />
+ <RefreshCw size={32} color={colors.success} style={{ animation: 'spin 2s linear infinite' }} />
<div style={{
fontSize: '11px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.7,
textAlign: 'center',
letterSpacing: '0.5px'
@@ -519,7 +508,7 @@ export function LiveSignalsPanel() {
<div style={{
fontSize: '10px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
textAlign: 'center',
letterSpacing: '0.5px'
@@ -531,11 +520,11 @@ export function LiveSignalsPanel() {
</>
) : (
<>
- <Activity size={32} color={FINCEPT.BORDER} />
+ <Activity size={32} color={'var(--ft-border-color, #2A2A2A)'} />
<div style={{
fontSize: '11px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
textAlign: 'center',
letterSpacing: '0.5px'
@@ -566,24 +555,24 @@ style.textContent = `
document.head.appendChild(style);
function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
- const signalColor = signal.signal === 'BUY' ? FINCEPT.GREEN : signal.signal === 'SELL' ? FINCEPT.RED : FINCEPT.WHITE;
+ const signalColor = signal.signal === 'BUY' ? 'var(--ft-color-success, #00D66F)' : signal.signal === 'SELL' ? 'var(--ft-color-alert, #FF3B3B)' : 'var(--ft-color-text, #FFFFFF)';
return (
<div
style={{
padding: '14px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderTop: isFirst ? `1px solid ${FINCEPT.BORDER}` : '0',
+ backgroundColor: 'var(--ft-color-panel, #0F0F0F)',
+ border: '1px solid var(--ft-border-color, #2A2A2A)',
+ borderTop: isFirst ? '1px solid var(--ft-border-color, #2A2A2A)' : '0',
borderLeft: `3px solid ${signalColor}`,
marginTop: isFirst ? '0' : '-1px',
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ e.currentTarget.style.backgroundColor = '#1F1F1F';
}}
onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.PANEL_BG;
+ e.currentTarget.style.backgroundColor = 'var(--ft-color-panel, #0F0F0F)';
}}
>
{/* Header Row */}
@@ -597,8 +586,8 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
<span style={{
fontSize: '14px',
fontWeight: 700,
- fontFamily: 'monospace',
- color: FINCEPT.WHITE
+ fontFamily: 'var(--ft-font-family, monospace)',
+ color: 'var(--ft-color-text, #FFFFFF)'
}}>
{signal.instrument}
</span>
@@ -608,7 +597,7 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
color: '#000000',
fontSize: '9px',
fontWeight: 700,
- fontFamily: 'monospace',
+ fontFamily: 'var(--ft-font-family, monospace)',
letterSpacing: '0.5px'
}}>
{signal.signal}
@@ -619,8 +608,8 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
alignItems: 'center',
gap: '6px',
fontSize: '9px',
- fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ fontFamily: 'var(--ft-font-family, monospace)',
+ color: 'var(--ft-color-text, #FFFFFF)',
opacity: 0.5
}}>
<Clock size={12} />
@@ -638,8 +627,8 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
<div>
<div style={{
fontSize: '9px',
- fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ fontFamily: 'var(--ft-font-family, monospace)',
+ color: 'var(--ft-color-text, #FFFFFF)',
opacity: 0.5,
marginBottom: '4px',
letterSpacing: '0.5px'
@@ -649,7 +638,7 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
<div style={{
fontSize: '11px',
fontWeight: 700,
- fontFamily: 'monospace',
+ fontFamily: 'var(--ft-font-family, monospace)',
color: signalColor
}}>
{signal.score.toFixed(4)}
@@ -659,8 +648,8 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
<div>
<div style={{
fontSize: '9px',
- fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ fontFamily: 'var(--ft-font-family, monospace)',
+ color: 'var(--ft-color-text, #FFFFFF)',
opacity: 0.5,
marginBottom: '4px',
letterSpacing: '0.5px'
@@ -670,8 +659,8 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
<div style={{
fontSize: '11px',
fontWeight: 700,
- fontFamily: 'monospace',
- color: FINCEPT.WHITE
+ fontFamily: 'var(--ft-font-family, monospace)',
+ color: 'var(--ft-color-text, #FFFFFF)'
}}>
${signal.price.toFixed(2)}
</div>
@@ -680,8 +669,8 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
<div>
<div style={{
fontSize: '9px',
- fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ fontFamily: 'var(--ft-font-family, monospace)',
+ color: 'var(--ft-color-text, #FFFFFF)',
opacity: 0.5,
marginBottom: '4px',
letterSpacing: '0.5px'
@@ -691,8 +680,8 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
<div style={{
fontSize: '11px',
fontWeight: 700,
- fontFamily: 'monospace',
- color: FINCEPT.CYAN
+ fontFamily: 'var(--ft-font-family, monospace)',
+ color: 'var(--ft-color-accent, #00E5FF)'
}}>
{(signal.confidence * 100).toFixed(1)}%
</div>
@@ -701,8 +690,8 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
<div>
<div style={{
fontSize: '9px',
- fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ fontFamily: 'var(--ft-font-family, monospace)',
+ color: 'var(--ft-color-text, #FFFFFF)',
opacity: 0.5,
marginBottom: '4px',
letterSpacing: '0.5px'
@@ -712,8 +701,8 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
<div style={{
fontSize: '11px',
fontWeight: 700,
- fontFamily: 'monospace',
- color: FINCEPT.GREEN,
+ fontFamily: 'var(--ft-font-family, monospace)',
+ color: 'var(--ft-color-success, #00D66F)',
textTransform: 'uppercase'
}}>
{signal.model}
@@ -725,9 +714,9 @@ function SignalCard({ signal, isFirst }: { signal: Signal; isFirst: boolean }) {
<div style={{
width: '100%',
height: '3px',
- backgroundColor: FINCEPT.DARK_BG,
+ backgroundColor: 'var(--ft-color-background, #000000)',
overflow: 'hidden',
- border: `1px solid ${FINCEPT.BORDER}`
+ border: '1px solid var(--ft-border-color, #2A2A2A)'
}}>
<div
style={{
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/MetaLearningPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/MetaLearningPanel.tsx
index 5aa7a8036..b681f8cd9 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/MetaLearningPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/MetaLearningPanel.tsx
@@ -4,16 +4,7 @@
*/
import React, { useState } from 'react';
import { Brain, Award, BarChart3, Layers, Play, Zap, TrendingUp, CheckCircle2 } from 'lucide-react';
-
-const FINCEPT = {
- MAGENTA: '#E91E8C', // Primary theme color for Meta Learning
- WHITE: '#FFFFFF',
- GREEN: '#00D66F',
- DARK_BG: '#0F0F0F',
- PANEL_BG: '#0F0F0F',
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F'
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface ModelConfig {
id: string;
@@ -24,6 +15,7 @@ interface ModelConfig {
}
export function MetaLearningPanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const models: ModelConfig[] = [
{ id: 'lightgbm', name: 'LightGBM', type: 'gradient_boosting', description: 'Gradient boosting framework', icon: Zap },
{ id: 'xgboost', name: 'XGBoost', type: 'gradient_boosting', description: 'Extreme gradient boosting', icon: TrendingUp },
@@ -55,19 +47,19 @@ export function MetaLearningPanel() {
};
return (
- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', backgroundColor: FINCEPT.DARK_BG }}>
+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', backgroundColor: colors.background }}>
{/* Terminal-style Header */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
gap: '12px'
}}>
- <Brain size={16} color={FINCEPT.MAGENTA} />
+ <Brain size={16} color={colors.primary} />
<span style={{
- color: FINCEPT.MAGENTA,
+ color: colors.primary,
fontSize: '12px',
fontWeight: 700,
letterSpacing: '0.5px',
@@ -81,9 +73,9 @@ export function MetaLearningPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.MAGENTA + '20',
- border: `1px solid ${FINCEPT.MAGENTA}`,
- color: FINCEPT.MAGENTA
+ backgroundColor: colors.primary + '20',
+ border: `1px solid ${colors.primary}`,
+ color: colors.primary
}}>
{selectedModels.length} MODELS SELECTED
</div>
@@ -93,9 +85,9 @@ export function MetaLearningPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.GREEN + '20',
- border: `1px solid ${FINCEPT.GREEN}`,
- color: FINCEPT.GREEN
+ backgroundColor: colors.success + '20',
+ border: `1px solid ${colors.success}`,
+ color: colors.success
}}>
BEST MODEL FOUND
</div>
@@ -107,17 +99,17 @@ export function MetaLearningPanel() {
{/* Left Panel - Model Selection */}
<div style={{
width: '400px',
- borderRight: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
flexDirection: 'column'
}}>
<div style={{
padding: '10px 12px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.MAGENTA,
+ color: colors.primary,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -136,9 +128,9 @@ export function MetaLearningPanel() {
onClick={() => toggleModel(model.id)}
style={{
padding: '12px',
- backgroundColor: isSelected ? FINCEPT.HOVER : 'transparent',
- border: `1px solid ${isSelected ? FINCEPT.MAGENTA : FINCEPT.BORDER}`,
- borderTop: idx === 0 ? `1px solid ${isSelected ? FINCEPT.MAGENTA : FINCEPT.BORDER}` : '0',
+ backgroundColor: isSelected ? '#1F1F1F' : 'transparent',
+ border: `1px solid ${isSelected ? colors.primary : 'var(--ft-border-color, #2A2A2A)'}`,
+ borderTop: idx === 0 ? `1px solid ${isSelected ? colors.primary : 'var(--ft-border-color, #2A2A2A)'}` : '0',
cursor: 'pointer',
transition: 'all 0.15s',
marginTop: idx === 0 ? '0' : '-1px',
@@ -148,14 +140,14 @@ export function MetaLearningPanel() {
}}
onMouseEnter={(e) => {
if (!isSelected) {
- e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG;
- e.currentTarget.style.borderColor = FINCEPT.MAGENTA;
+ e.currentTarget.style.backgroundColor = colors.background;
+ e.currentTarget.style.borderColor = colors.primary;
}
}}
onMouseLeave={(e) => {
if (!isSelected) {
e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}
}}
>
@@ -163,8 +155,8 @@ export function MetaLearningPanel() {
<div style={{
width: '16px',
height: '16px',
- border: `1px solid ${isSelected ? FINCEPT.MAGENTA : FINCEPT.BORDER}`,
- backgroundColor: isSelected ? FINCEPT.MAGENTA : 'transparent',
+ border: `1px solid ${isSelected ? colors.primary : 'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: isSelected ? colors.primary : 'transparent',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
@@ -173,14 +165,14 @@ export function MetaLearningPanel() {
{isSelected && <CheckCircle2 size={12} color="#000000" />}
</div>
- <Icon size={16} color={FINCEPT.MAGENTA} />
+ <Icon size={16} color={colors.primary} />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{
fontSize: '11px',
fontWeight: 700,
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
marginBottom: '2px'
}}>
{model.name}
@@ -188,7 +180,7 @@ export function MetaLearningPanel() {
<div style={{
fontSize: '10px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.6
}}>
{model.description}
@@ -199,9 +191,9 @@ export function MetaLearningPanel() {
fontSize: '9px',
fontFamily: 'monospace',
padding: '2px 6px',
- backgroundColor: FINCEPT.MAGENTA + '20',
- border: `1px solid ${FINCEPT.MAGENTA}`,
- color: FINCEPT.MAGENTA
+ backgroundColor: colors.primary + '20',
+ border: `1px solid ${colors.primary}`,
+ color: colors.primary
}}>
{model.type.replace('_', ' ').toUpperCase()}
</div>
@@ -211,16 +203,16 @@ export function MetaLearningPanel() {
</div>
{/* Action Button */}
- <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}`, padding: '12px' }}>
+ <div style={{ borderTop: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`, padding: '12px' }}>
<button
onClick={runModelSelection}
disabled={selectedModels.length === 0 || isRunning}
style={{
width: '100%',
padding: '12px 16px',
- backgroundColor: selectedModels.length > 0 ? FINCEPT.MAGENTA : FINCEPT.DARK_BG,
+ backgroundColor: selectedModels.length > 0 ? colors.primary : colors.background,
border: 'none',
- color: selectedModels.length > 0 ? '#000000' : FINCEPT.WHITE,
+ color: selectedModels.length > 0 ? '#000000' : colors.text,
opacity: selectedModels.length > 0 ? 1 : 0.5,
fontSize: '11px',
fontWeight: 700,
@@ -251,16 +243,16 @@ export function MetaLearningPanel() {
</div>
{/* Right Panel - Results */}
- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', backgroundColor: FINCEPT.DARK_BG }}>
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', backgroundColor: colors.background }}>
<div style={{
padding: '10px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.MAGENTA,
+ color: colors.primary,
fontFamily: 'monospace',
letterSpacing: '0.5px',
- backgroundColor: FINCEPT.PANEL_BG
+ backgroundColor: colors.panel
}}>
AUTOML RESULTS
</div>
@@ -269,23 +261,23 @@ export function MetaLearningPanel() {
{bestModel ? (
<div style={{
padding: '16px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.GREEN}`,
- borderLeft: `3px solid ${FINCEPT.GREEN}`
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.success}`,
+ borderLeft: `3px solid ${colors.success}`
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '12px' }}>
<div style={{
padding: '8px',
- backgroundColor: FINCEPT.GREEN + '20',
- border: `1px solid ${FINCEPT.GREEN}`
+ backgroundColor: colors.success + '20',
+ border: `1px solid ${colors.success}`
}}>
- <Award size={20} color={FINCEPT.GREEN} />
+ <Award size={20} color={colors.success} />
</div>
<div>
<div style={{
fontSize: '10px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.6,
marginBottom: '2px',
letterSpacing: '0.5px'
@@ -296,7 +288,7 @@ export function MetaLearningPanel() {
fontSize: '16px',
fontWeight: 700,
fontFamily: 'monospace',
- color: FINCEPT.GREEN
+ color: colors.success
}}>
{models.find(m => m.id === bestModel)?.name}
</div>
@@ -312,13 +304,13 @@ export function MetaLearningPanel() {
}}>
<div style={{
padding: '10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `3px solid ${FINCEPT.MAGENTA}`
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${colors.primary}`
}}>
<div style={{
fontSize: '9px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '4px',
fontFamily: 'monospace',
@@ -329,7 +321,7 @@ export function MetaLearningPanel() {
<div style={{
fontSize: '16px',
fontWeight: 700,
- color: FINCEPT.MAGENTA,
+ color: colors.primary,
fontFamily: 'monospace'
}}>
85.42%
@@ -338,13 +330,13 @@ export function MetaLearningPanel() {
<div style={{
padding: '10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `3px solid ${FINCEPT.MAGENTA}`
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${colors.primary}`
}}>
<div style={{
fontSize: '9px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '4px',
fontFamily: 'monospace',
@@ -355,7 +347,7 @@ export function MetaLearningPanel() {
<div style={{
fontSize: '16px',
fontWeight: 700,
- color: FINCEPT.MAGENTA,
+ color: colors.primary,
fontFamily: 'monospace'
}}>
0.8312
@@ -364,13 +356,13 @@ export function MetaLearningPanel() {
<div style={{
padding: '10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `3px solid ${FINCEPT.MAGENTA}`
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${colors.primary}`
}}>
<div style={{
fontSize: '9px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginBottom: '4px',
fontFamily: 'monospace',
@@ -381,7 +373,7 @@ export function MetaLearningPanel() {
<div style={{
fontSize: '16px',
fontWeight: 700,
- color: FINCEPT.MAGENTA,
+ color: colors.primary,
fontFamily: 'monospace'
}}>
0.9124
@@ -394,7 +386,7 @@ export function MetaLearningPanel() {
<div style={{
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.MAGENTA,
+ color: colors.primary,
fontFamily: 'monospace',
letterSpacing: '0.5px',
marginBottom: '10px'
@@ -413,9 +405,9 @@ export function MetaLearningPanel() {
key={modelId}
style={{
padding: '8px 10px',
- backgroundColor: isBest ? FINCEPT.GREEN + '15' : FINCEPT.DARK_BG,
- border: `1px solid ${isBest ? FINCEPT.GREEN : FINCEPT.BORDER}`,
- borderTop: idx === 0 ? `1px solid ${isBest ? FINCEPT.GREEN : FINCEPT.BORDER}` : '0',
+ backgroundColor: isBest ? colors.success + '15' : colors.background,
+ border: `1px solid ${isBest ? colors.success : 'var(--ft-border-color, #2A2A2A)'}`,
+ borderTop: idx === 0 ? `1px solid ${isBest ? colors.success : 'var(--ft-border-color, #2A2A2A)'}` : '0',
marginTop: idx === 0 ? '0' : '-1px',
display: 'flex',
alignItems: 'center',
@@ -426,7 +418,7 @@ export function MetaLearningPanel() {
fontSize: '11px',
fontWeight: 700,
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
width: '24px'
}}>
@@ -437,7 +429,7 @@ export function MetaLearningPanel() {
fontSize: '10px',
fontWeight: 700,
fontFamily: 'monospace',
- color: isBest ? FINCEPT.GREEN : FINCEPT.WHITE
+ color: isBest ? colors.success : colors.text
}}>
{model.name}
</span>
@@ -446,7 +438,7 @@ export function MetaLearningPanel() {
fontSize: '10px',
fontFamily: 'monospace',
fontWeight: 700,
- color: isBest ? FINCEPT.GREEN : FINCEPT.MAGENTA
+ color: isBest ? colors.success : colors.primary
}}>
{score}
</div>
@@ -465,11 +457,11 @@ export function MetaLearningPanel() {
flexDirection: 'column',
gap: '12px'
}}>
- <Brain size={32} color={FINCEPT.BORDER} />
+ <Brain size={32} color={'var(--ft-border-color, #2A2A2A)'} />
<div style={{
fontSize: '11px',
fontFamily: 'monospace',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
textAlign: 'center',
letterSpacing: '0.5px'
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ModelLibraryPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ModelLibraryPanel.tsx
index 208e3f61e..b4e575d17 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ModelLibraryPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ModelLibraryPanel.tsx
@@ -26,27 +26,10 @@ import {
} from 'lucide-react';
import { qlibService, type QlibModel } from '@/services/aiQuantLab/qlibService';
import { showError } from '@/utils/notifications';
-
-// Fincept Professional Color Palette
-const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- BLUE: '#0088FF',
- PURPLE: '#9D4EDD',
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F',
- MUTED: '#4A4A4A'
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
export function ModelLibraryPanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [models, setModels] = useState<QlibModel[]>([]);
const [selectedModel, setSelectedModel] = useState<QlibModel | null>(null);
const [loading, setLoading] = useState(true);
@@ -120,23 +103,23 @@ export function ModelLibraryPanel() {
});
return (
- <div className="flex h-full" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <div className="flex h-full" style={{ backgroundColor: colors.background }}>
{/* Left Panel - Model List */}
<div
className="w-96 border-r overflow-auto flex-shrink-0"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ style={{ backgroundColor: colors.panel, borderColor: 'var(--ft-border-color, #2A2A2A)' }}
>
<div className="p-4">
{/* Header */}
- <div className="flex items-center justify-between mb-4 pb-3 border-b" style={{ borderColor: FINCEPT.BORDER }}>
+ <div className="flex items-center justify-between mb-4 pb-3 border-b" style={{ borderColor: 'var(--ft-border-color, #2A2A2A)' }}>
<div>
<div className="flex items-center gap-2 mb-1">
- <Brain size={18} color={FINCEPT.ORANGE} />
- <h2 className="text-sm font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ <Brain size={18} color={colors.primary} />
+ <h2 className="text-sm font-bold uppercase tracking-wide" style={{ color: colors.text }}>
MODEL LIBRARY
</h2>
</div>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ <p className="text-xs font-mono" style={{ color: colors.textMuted }}>
{filteredModels.length} Pre-trained Models Available
</p>
</div>
@@ -147,13 +130,13 @@ export function ModelLibraryPanel() {
style={{ backgroundColor: 'transparent' }}
title="Refresh models"
>
- <RefreshCw size={14} color={FINCEPT.GRAY} className={loading ? 'animate-spin' : ''} />
+ <RefreshCw size={14} color={colors.textMuted} className={loading ? 'animate-spin' : ''} />
</button>
</div>
{/* Filter */}
<div className="mb-4">
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
<Filter size={12} className="inline mr-1" />
Model Type
</label>
@@ -162,9 +145,9 @@ export function ModelLibraryPanel() {
onChange={(e) => setFilterType(e.target.value as any)}
className="w-full px-3 py-2 rounded text-xs font-mono outline-none uppercase"
style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
>
<option value="all">All Models</option>
@@ -179,15 +162,15 @@ export function ModelLibraryPanel() {
<div className="space-y-2">
{loading ? (
<div className="text-center py-8">
- <RefreshCw size={32} color={FINCEPT.ORANGE} className="animate-spin mx-auto mb-2" />
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ <RefreshCw size={32} color={colors.primary} className="animate-spin mx-auto mb-2" />
+ <p className="text-xs font-mono" style={{ color: colors.textMuted }}>
LOADING MODELS...
</p>
</div>
) : filteredModels.length === 0 ? (
<div className="text-center py-8">
- <AlertCircle size={32} color={FINCEPT.GRAY} className="mx-auto mb-2" />
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ <AlertCircle size={32} color={colors.textMuted} className="mx-auto mb-2" />
+ <p className="text-xs font-mono" style={{ color: colors.textMuted }}>
No models found
</p>
</div>
@@ -198,22 +181,22 @@ export function ModelLibraryPanel() {
onClick={() => setSelectedModel(model)}
className="w-full p-3 rounded text-left transition-all hover:bg-opacity-80"
style={{
- backgroundColor: selectedModel?.id === model.id ? FINCEPT.DARK_BG : FINCEPT.HEADER_BG,
- border: selectedModel?.id === model.id ? `1px solid ${FINCEPT.ORANGE}` : `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: selectedModel?.id === model.id ? colors.background : colors.panel,
+ border: selectedModel?.id === model.id ? `1px solid ${colors.primary}` : `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
>
<div className="flex items-start justify-between mb-2">
- <span className="font-bold text-xs uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ <span className="font-bold text-xs uppercase tracking-wide" style={{ color: colors.text }}>
{model.name}
</span>
<span
className="text-xs px-1.5 py-0.5 rounded uppercase font-bold"
style={{
- backgroundColor: model.type === 'tree_based' ? FINCEPT.GREEN
- : model.type === 'linear' ? FINCEPT.YELLOW
- : model.type === 'ensemble' ? FINCEPT.PURPLE
- : FINCEPT.CYAN,
- color: FINCEPT.DARK_BG
+ backgroundColor: model.type === 'tree_based' ? colors.success
+ : model.type === 'linear' ? colors.warning
+ : model.type === 'ensemble' ? colors.purple
+ : colors.accent,
+ color: colors.background
}}
>
{model.type === 'tree_based' ? 'TREE'
@@ -222,7 +205,7 @@ export function ModelLibraryPanel() {
: 'NEURAL'}
</span>
</div>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ <p className="text-xs font-mono" style={{ color: colors.textMuted }}>
{model.description}
</p>
</button>
@@ -234,17 +217,17 @@ export function ModelLibraryPanel() {
{/* Right Panel - Model Details */}
{selectedModel ? (
- <div className="flex-1 overflow-auto p-6" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <div className="flex-1 overflow-auto p-6" style={{ backgroundColor: colors.background }}>
<div className="space-y-6 max-w-5xl">
{/* Header */}
<div>
- <h2 className="text-xl font-bold mb-2 uppercase tracking-wide flex items-center gap-3" style={{ color: FINCEPT.WHITE }}>
+ <h2 className="text-xl font-bold mb-2 uppercase tracking-wide flex items-center gap-3" style={{ color: colors.text }}>
{selectedModel.name}
- <span className="text-sm px-3 py-1 rounded font-bold" style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}>
+ <span className="text-sm px-3 py-1 rounded font-bold" style={{ backgroundColor: colors.primary, color: colors.background }}>
MODEL ID: {selectedModel.id}
</span>
</h2>
- <p className="font-mono text-sm" style={{ color: FINCEPT.GRAY }}>
+ <p className="font-mono text-sm" style={{ color: colors.textMuted }}>
{selectedModel.description}
</p>
</div>
@@ -253,20 +236,20 @@ export function ModelLibraryPanel() {
<div className="flex items-center gap-3">
<div
className="flex items-center gap-2 px-4 py-2 rounded"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderLeft: `3px solid ${
- selectedModel.type === 'tree_based' ? FINCEPT.GREEN
- : selectedModel.type === 'linear' ? FINCEPT.YELLOW
- : selectedModel.type === 'ensemble' ? FINCEPT.PURPLE
- : FINCEPT.CYAN
+ style={{ backgroundColor: colors.panel, borderLeft: `3px solid ${
+ selectedModel.type === 'tree_based' ? colors.success
+ : selectedModel.type === 'linear' ? colors.warning
+ : selectedModel.type === 'ensemble' ? colors.purple
+ : colors.accent
}` }}
>
<Cpu size={16} color={
- selectedModel.type === 'tree_based' ? FINCEPT.GREEN
- : selectedModel.type === 'linear' ? FINCEPT.YELLOW
- : selectedModel.type === 'ensemble' ? FINCEPT.PURPLE
- : FINCEPT.CYAN
+ selectedModel.type === 'tree_based' ? colors.success
+ : selectedModel.type === 'linear' ? colors.warning
+ : selectedModel.type === 'ensemble' ? colors.purple
+ : colors.accent
} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: colors.text }}>
{selectedModel.type === 'tree_based' ? 'GRADIENT BOOSTING'
: selectedModel.type === 'linear' ? 'LINEAR REGRESSION'
: selectedModel.type === 'ensemble' ? 'ENSEMBLE MODEL'
@@ -277,7 +260,7 @@ export function ModelLibraryPanel() {
{/* Key Features */}
<div>
- <h3 className="text-xs font-bold uppercase tracking-wide mb-3" style={{ color: FINCEPT.GRAY }}>
+ <h3 className="text-xs font-bold uppercase tracking-wide mb-3" style={{ color: colors.textMuted }}>
<Star size={12} className="inline mr-1" />
KEY FEATURES
</h3>
@@ -286,10 +269,10 @@ export function ModelLibraryPanel() {
<div
key={idx}
className="flex items-center gap-2 p-3 rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ style={{ backgroundColor: colors.panel, borderColor: 'var(--ft-border-color, #2A2A2A)' }}
>
- <CheckCircle2 size={14} color={FINCEPT.GREEN} />
- <span className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
+ <CheckCircle2 size={14} color={colors.success} />
+ <span className="text-xs font-mono" style={{ color: colors.text }}>
{feature}
</span>
</div>
@@ -299,7 +282,7 @@ export function ModelLibraryPanel() {
{/* Use Cases */}
<div>
- <h3 className="text-xs font-bold uppercase tracking-wide mb-3" style={{ color: FINCEPT.GRAY }}>
+ <h3 className="text-xs font-bold uppercase tracking-wide mb-3" style={{ color: colors.textMuted }}>
<Target size={12} className="inline mr-1" />
USE CASES
</h3>
@@ -308,10 +291,10 @@ export function ModelLibraryPanel() {
<div
key={idx}
className="flex items-center gap-2 p-3 rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ style={{ backgroundColor: colors.panel, borderColor: 'var(--ft-border-color, #2A2A2A)' }}
>
- <TrendingUp size={14} color={FINCEPT.ORANGE} />
- <span className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
+ <TrendingUp size={14} color={colors.primary} />
+ <span className="text-xs font-mono" style={{ color: colors.text }}>
{useCase}
</span>
</div>
@@ -320,8 +303,8 @@ export function ModelLibraryPanel() {
</div>
{/* Prediction Configuration */}
- <div className="pt-4 border-t" style={{ borderColor: FINCEPT.BORDER }}>
- <h3 className="text-xs font-bold uppercase tracking-wide mb-4" style={{ color: FINCEPT.GRAY }}>
+ <div className="pt-4 border-t" style={{ borderColor: 'var(--ft-border-color, #2A2A2A)' }}>
+ <h3 className="text-xs font-bold uppercase tracking-wide mb-4" style={{ color: colors.textMuted }}>
<Settings size={12} className="inline mr-1" />
PREDICTION CONFIGURATION
</h3>
@@ -329,7 +312,7 @@ export function ModelLibraryPanel() {
<div className="space-y-4">
{/* Instruments */}
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
Instruments (Comma-separated)
</label>
<input
@@ -339,9 +322,9 @@ export function ModelLibraryPanel() {
placeholder="AAPL,MSFT,GOOGL"
className="w-full px-3 py-2 rounded text-xs font-mono outline-none"
style={{
- backgroundColor: FINCEPT.PANEL_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
/>
</div>
@@ -349,7 +332,7 @@ export function ModelLibraryPanel() {
{/* Date Range */}
<div className="grid grid-cols-2 gap-3">
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
<Calendar size={12} className="inline mr-1" />
Start Date
</label>
@@ -359,14 +342,14 @@ export function ModelLibraryPanel() {
onChange={(e) => setStartDate(e.target.value)}
className="w-full px-3 py-2 rounded text-xs font-mono outline-none"
style={{
- backgroundColor: FINCEPT.PANEL_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
/>
</div>
<div>
- <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: FINCEPT.GRAY }}>
+ <label className="block text-xs font-bold mb-2 uppercase tracking-wide" style={{ color: colors.textMuted }}>
<Calendar size={12} className="inline mr-1" />
End Date
</label>
@@ -376,9 +359,9 @@ export function ModelLibraryPanel() {
onChange={(e) => setEndDate(e.target.value)}
className="w-full px-3 py-2 rounded text-xs font-mono outline-none"
style={{
- backgroundColor: FINCEPT.PANEL_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}
/>
</div>
@@ -390,17 +373,17 @@ export function ModelLibraryPanel() {
{predictionResult && (
<div
className="p-4 rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.GREEN }}
+ style={{ backgroundColor: colors.panel, borderColor: colors.success }}
>
<div className="flex items-center gap-2 mb-3">
- <CheckCircle2 size={16} color={FINCEPT.GREEN} />
- <h3 className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ <CheckCircle2 size={16} color={colors.success} />
+ <h3 className="text-xs font-bold uppercase tracking-wide" style={{ color: colors.text }}>
PREDICTION RESULTS
</h3>
</div>
<pre
className="text-xs font-mono overflow-x-auto"
- style={{ color: FINCEPT.WHITE }}
+ style={{ color: colors.text }}
>
{JSON.stringify(predictionResult, null, 2)}
</pre>
@@ -408,12 +391,12 @@ export function ModelLibraryPanel() {
)}
{/* Action Buttons */}
- <div className="flex gap-3 pt-4 border-t" style={{ borderColor: FINCEPT.BORDER }}>
+ <div className="flex gap-3 pt-4 border-t" style={{ borderColor: 'var(--ft-border-color, #2A2A2A)' }}>
<button
onClick={handleRunPredictions}
disabled={isPredicting || !instruments || !startDate || !endDate}
className="flex-1 py-3 rounded font-bold uppercase text-sm tracking-wide hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ style={{ backgroundColor: colors.primary, color: colors.background }}
>
{isPredicting ? (
<>
@@ -429,7 +412,7 @@ export function ModelLibraryPanel() {
</button>
<button
className="px-6 py-3 rounded font-bold uppercase text-sm tracking-wide hover:bg-opacity-80 transition-colors flex items-center justify-center gap-2"
- style={{ backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.WHITE }}
+ style={{ backgroundColor: colors.panel, color: colors.text }}
>
<Info size={16} />
DETAILS
@@ -438,13 +421,13 @@ export function ModelLibraryPanel() {
</div>
</div>
) : (
- <div className="flex-1 flex items-center justify-center" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <div className="flex-1 flex items-center justify-center" style={{ backgroundColor: colors.background }}>
<div className="text-center max-w-md">
- <Brain size={64} color={FINCEPT.GRAY} className="mx-auto mb-4" />
- <h3 className="text-base font-bold uppercase tracking-wide mb-2" style={{ color: FINCEPT.WHITE }}>
+ <Brain size={64} color={colors.textMuted} className="mx-auto mb-4" />
+ <h3 className="text-base font-bold uppercase tracking-wide mb-2" style={{ color: colors.text }}>
NO MODEL SELECTED
</h3>
- <p className="text-sm font-mono" style={{ color: FINCEPT.GRAY }}>
+ <p className="text-sm font-mono" style={{ color: colors.textMuted }}>
Select a model from the library to view details and run predictions
</p>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/OnlineLearningPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/OnlineLearningPanel.tsx
index 1e3530dea..9c7e577c5 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/OnlineLearningPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/OnlineLearningPanel.tsx
@@ -5,6 +5,7 @@
*/
import React, { useState, useEffect, useRef } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import {
Zap,
Activity,
@@ -24,24 +25,6 @@ import {
AlertCircle
} from 'lucide-react';
-const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- BLUE: '#0088FF',
- PURPLE: '#9D4EDD',
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F',
- MUTED: '#4A4A4A'
-};
-
interface ModelMetrics {
model_id: string;
current_mae: number;
@@ -58,6 +41,7 @@ interface UpdateHistory {
}
export function OnlineLearningPanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [modelType, setModelType] = useState('linear');
const [modelId, setModelId] = useState<string | null>(null);
const [isLive, setIsLive] = useState(false);
@@ -135,20 +119,20 @@ export function OnlineLearningPanel() {
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: FINCEPT.DARK_BG
+ backgroundColor: colors.background
}}>
{/* Terminal-style Header */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
gap: '12px'
}}>
- <Zap size={16} color={FINCEPT.YELLOW} />
+ <Zap size={16} color={colors.warning} />
<span style={{
- color: FINCEPT.YELLOW,
+ color: colors.warning,
fontSize: '12px',
fontWeight: 700,
letterSpacing: '0.5px',
@@ -165,9 +149,9 @@ export function OnlineLearningPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.CYAN}`,
- color: FINCEPT.CYAN
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.accent}`,
+ color: colors.accent
}}>
MODEL: {modelId.substring(0, 12)}...
</div>
@@ -176,14 +160,14 @@ export function OnlineLearningPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.GREEN + '20',
- border: `1px solid ${FINCEPT.GREEN}`,
- color: FINCEPT.GREEN,
+ backgroundColor: colors.success + '20',
+ border: `1px solid ${colors.success}`,
+ color: colors.success,
display: 'flex',
alignItems: 'center',
gap: '4px'
}}>
- <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: FINCEPT.GREEN, animation: 'pulse 2s infinite' }} />
+ <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: colors.success, animation: 'pulse 2s infinite' }} />
LIVE
</div>
)}
@@ -194,9 +178,9 @@ export function OnlineLearningPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: modelId ? (isLive ? FINCEPT.GREEN + '20' : FINCEPT.DARK_BG) : FINCEPT.DARK_BG,
- border: `1px solid ${modelId ? (isLive ? FINCEPT.GREEN : FINCEPT.BORDER) : FINCEPT.BORDER}`,
- color: modelId ? (isLive ? FINCEPT.GREEN : FINCEPT.MUTED) : FINCEPT.MUTED
+ backgroundColor: modelId ? (isLive ? colors.success + '20' : colors.background) : colors.background,
+ border: `1px solid ${modelId ? (isLive ? colors.success : 'var(--ft-border-color, #2A2A2A)') : 'var(--ft-border-color, #2A2A2A)'}`,
+ color: modelId ? (isLive ? colors.success : colors.textMuted) : colors.textMuted
}}>
{isLive ? 'ACTIVE' : modelId ? 'READY' : 'IDLE'}
</div>
@@ -206,17 +190,17 @@ export function OnlineLearningPanel() {
{/* Left Sidebar - Model Type Selection */}
<div style={{
width: '220px',
- borderRight: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
flexDirection: 'column'
}}>
<div style={{
padding: '10px 12px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.MUTED,
+ color: colors.textMuted,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -231,32 +215,32 @@ export function OnlineLearningPanel() {
onClick={() => !modelId && setModelType(type.id)}
style={{
padding: '10px',
- backgroundColor: isSelected ? FINCEPT.HOVER : 'transparent',
- border: `1px solid ${isSelected ? FINCEPT.YELLOW : FINCEPT.BORDER}`,
+ backgroundColor: isSelected ? '#1F1F1F' : 'transparent',
+ border: `1px solid ${isSelected ? colors.warning : 'var(--ft-border-color, #2A2A2A)'}`,
cursor: modelId ? 'not-allowed' : 'pointer',
opacity: modelId ? 0.5 : 1,
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
if (!isSelected && !modelId) {
- e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG;
- e.currentTarget.style.borderColor = FINCEPT.YELLOW;
+ e.currentTarget.style.backgroundColor = colors.background;
+ e.currentTarget.style.borderColor = colors.warning;
}
}}
onMouseLeave={(e) => {
if (!isSelected && !modelId) {
e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>
- <Activity size={14} style={{ color: FINCEPT.YELLOW }} />
- <span style={{ color: FINCEPT.WHITE, fontSize: '11px', fontWeight: 600, fontFamily: 'monospace' }}>
+ <Activity size={14} style={{ color: colors.warning }} />
+ <span style={{ color: colors.text, fontSize: '11px', fontWeight: 600, fontFamily: 'monospace' }}>
{type.name}
</span>
</div>
- <p style={{ color: FINCEPT.MUTED, fontSize: '9px', margin: 0, lineHeight: '1.3' }}>
+ <p style={{ color: colors.textMuted, fontSize: '9px', margin: 0, lineHeight: '1.3' }}>
{type.desc}
</p>
</div>
@@ -267,13 +251,13 @@ export function OnlineLearningPanel() {
{/* Drift Strategy Section */}
<div style={{
padding: '12px',
- borderTop: `1px solid ${FINCEPT.BORDER}`,
+ borderTop: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
marginTop: 'auto'
}}>
<div style={{
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.MUTED,
+ color: colors.textMuted,
marginBottom: '8px',
fontFamily: 'monospace',
letterSpacing: '0.5px'
@@ -287,9 +271,9 @@ export function OnlineLearningPanel() {
style={{
width: '100%',
padding: '6px 8px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '10px',
fontFamily: 'monospace',
opacity: isLive ? 0.5 : 1
@@ -307,18 +291,18 @@ export function OnlineLearningPanel() {
{/* Configuration & Control Section */}
<div style={{
padding: '16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
display: 'flex',
flexDirection: 'column',
gap: '12px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Zap size={14} style={{ color: FINCEPT.YELLOW }} />
- <span style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE, fontFamily: 'monospace' }}>
+ <Zap size={14} style={{ color: colors.warning }} />
+ <span style={{ fontSize: '11px', fontWeight: 600, color: colors.text, fontFamily: 'monospace' }}>
MODEL CONTROL
</span>
- <span style={{ fontSize: '10px', color: FINCEPT.MUTED }}>•</span>
- <span style={{ fontSize: '10px', color: FINCEPT.MUTED }}>
+ <span style={{ fontSize: '10px', color: colors.textMuted }}>•</span>
+ <span style={{ fontSize: '10px', color: colors.textMuted }}>
{modelId ? 'MODEL INITIALIZED' : 'NO MODEL'}
</span>
</div>
@@ -326,7 +310,7 @@ export function OnlineLearningPanel() {
{/* Control Grid */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', alignItems: 'end' }}>
<div>
- <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>
+ <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: colors.textMuted, fontFamily: 'monospace' }}>
UPDATE FREQUENCY
</label>
<select
@@ -336,9 +320,9 @@ export function OnlineLearningPanel() {
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '11px',
fontFamily: 'monospace',
opacity: isLive ? 0.5 : 1
@@ -351,14 +335,14 @@ export function OnlineLearningPanel() {
</div>
<div>
- <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>
+ <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: colors.textMuted, fontFamily: 'monospace' }}>
SELECTED MODEL
</label>
<div style={{
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.YELLOW}`,
- color: FINCEPT.YELLOW,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.warning}`,
+ color: colors.warning,
fontSize: '11px',
fontFamily: 'monospace',
fontWeight: 600
@@ -376,9 +360,9 @@ export function OnlineLearningPanel() {
style={{
flex: 1,
padding: '10px 16px',
- backgroundColor: FINCEPT.ORANGE,
+ backgroundColor: colors.primary,
border: 'none',
- color: FINCEPT.DARK_BG,
+ color: colors.background,
fontSize: '11px',
fontWeight: 700,
cursor: 'pointer',
@@ -400,9 +384,9 @@ export function OnlineLearningPanel() {
style={{
flex: 1,
padding: '10px 16px',
- backgroundColor: FINCEPT.GREEN,
+ backgroundColor: colors.success,
border: 'none',
- color: FINCEPT.DARK_BG,
+ color: colors.background,
fontSize: '11px',
fontWeight: 700,
cursor: 'pointer',
@@ -424,9 +408,9 @@ export function OnlineLearningPanel() {
style={{
flex: 1,
padding: '10px 16px',
- backgroundColor: FINCEPT.RED,
+ backgroundColor: colors.alert,
border: 'none',
- color: FINCEPT.WHITE,
+ color: colors.text,
fontSize: '11px',
fontWeight: 700,
cursor: 'pointer',
@@ -450,13 +434,13 @@ export function OnlineLearningPanel() {
{metrics && (
<div style={{
padding: '16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel
}}>
<div style={{
fontSize: '11px',
fontWeight: 700,
- color: FINCEPT.CYAN,
+ color: colors.accent,
marginBottom: '12px',
fontFamily: 'monospace',
letterSpacing: '0.5px',
@@ -464,62 +448,62 @@ export function OnlineLearningPanel() {
alignItems: 'center',
gap: '6px'
}}>
- <Cpu size={13} color={FINCEPT.CYAN} />
+ <Cpu size={13} color={colors.accent} />
REAL-TIME METRICS
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px' }}>
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.CYAN}`,
- borderLeft: `3px solid ${FINCEPT.CYAN}`
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.accent}`,
+ borderLeft: `3px solid ${colors.accent}`
}}>
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '9px', color: colors.textMuted, marginBottom: '4px', fontFamily: 'monospace' }}>
CURRENT MAE
</div>
- <div style={{ fontSize: '18px', fontWeight: 700, color: FINCEPT.CYAN, fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '18px', fontWeight: 700, color: colors.accent, fontFamily: 'monospace' }}>
{metrics.current_mae.toFixed(4)}
</div>
</div>
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.GREEN}`,
- borderLeft: `3px solid ${FINCEPT.GREEN}`
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.success}`,
+ borderLeft: `3px solid ${colors.success}`
}}>
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '9px', color: colors.textMuted, marginBottom: '4px', fontFamily: 'monospace' }}>
SAMPLES TRAINED
</div>
- <div style={{ fontSize: '18px', fontWeight: 700, color: FINCEPT.GREEN, fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '18px', fontWeight: 700, color: colors.success, fontFamily: 'monospace' }}>
{metrics.samples_trained.toLocaleString()}
</div>
</div>
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${metrics.drift_detected ? FINCEPT.RED : FINCEPT.GREEN}`,
- borderLeft: `3px solid ${metrics.drift_detected ? FINCEPT.RED : FINCEPT.GREEN}`
+ backgroundColor: colors.background,
+ border: `1px solid ${metrics.drift_detected ? colors.alert : colors.success}`,
+ borderLeft: `3px solid ${metrics.drift_detected ? colors.alert : colors.success}`
}}>
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontFamily: 'monospace', display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <div style={{ fontSize: '9px', color: colors.textMuted, marginBottom: '4px', fontFamily: 'monospace', display: 'flex', alignItems: 'center', gap: '4px' }}>
DRIFT STATUS
- {metrics.drift_detected && <Bell size={10} color={FINCEPT.RED} />}
+ {metrics.drift_detected && <Bell size={10} color={colors.alert} />}
</div>
- <div style={{ fontSize: '14px', fontWeight: 700, color: metrics.drift_detected ? FINCEPT.RED : FINCEPT.GREEN, fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '14px', fontWeight: 700, color: metrics.drift_detected ? colors.alert : colors.success, fontFamily: 'monospace' }}>
{metrics.drift_detected ? 'DETECTED' : 'STABLE'}
</div>
</div>
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}>
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '9px', color: colors.textMuted, marginBottom: '4px', fontFamily: 'monospace' }}>
LAST UPDATE
</div>
- <div style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE, fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '11px', fontWeight: 600, color: colors.text, fontFamily: 'monospace' }}>
{new Date(metrics.last_updated).toLocaleTimeString()}
</div>
</div>
@@ -532,10 +516,10 @@ export function OnlineLearningPanel() {
{error && (
<div style={{
padding: '12px 14px',
- backgroundColor: FINCEPT.RED + '15',
- border: `1px solid ${FINCEPT.RED}`,
- borderLeft: `3px solid ${FINCEPT.RED}`,
- color: FINCEPT.RED,
+ backgroundColor: colors.alert + '15',
+ border: `1px solid ${colors.alert}`,
+ borderLeft: `3px solid ${colors.alert}`,
+ color: colors.alert,
fontSize: '13px',
display: 'flex',
alignItems: 'center',
@@ -554,7 +538,7 @@ export function OnlineLearningPanel() {
<div style={{
fontSize: '11px',
fontWeight: 700,
- color: FINCEPT.CYAN,
+ color: colors.accent,
marginBottom: '8px',
fontFamily: 'monospace',
letterSpacing: '0.5px',
@@ -562,7 +546,7 @@ export function OnlineLearningPanel() {
alignItems: 'center',
gap: '6px'
}}>
- <Clock size={13} color={FINCEPT.CYAN} />
+ <Clock size={13} color={colors.accent} />
UPDATE HISTORY
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
@@ -571,13 +555,13 @@ export function OnlineLearningPanel() {
key={idx}
style={{
padding: '10px 12px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${update.drift ? FINCEPT.RED : FINCEPT.BORDER}`,
- borderLeft: `3px solid ${update.drift ? FINCEPT.RED : FINCEPT.CYAN}`
+ backgroundColor: colors.panel,
+ border: `1px solid ${update.drift ? colors.alert : 'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${update.drift ? colors.alert : colors.accent}`
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
- <span style={{ fontSize: '10px', fontFamily: 'monospace', color: FINCEPT.GRAY }}>
+ <span style={{ fontSize: '10px', fontFamily: 'monospace', color: colors.textMuted }}>
{new Date(update.timestamp).toLocaleTimeString()}
</span>
{update.drift && (
@@ -586,9 +570,9 @@ export function OnlineLearningPanel() {
alignItems: 'center',
gap: '4px',
padding: '2px 6px',
- backgroundColor: FINCEPT.RED + '20',
+ backgroundColor: colors.alert + '20',
fontSize: '9px',
- color: FINCEPT.RED,
+ color: colors.alert,
fontFamily: 'monospace',
fontWeight: 700
}}>
@@ -599,14 +583,14 @@ export function OnlineLearningPanel() {
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', fontSize: '10px' }}>
<div>
- <span style={{ color: FINCEPT.GRAY, fontFamily: 'monospace' }}>MAE: </span>
- <span style={{ color: FINCEPT.WHITE, fontFamily: 'monospace', fontWeight: 600 }}>
+ <span style={{ color: colors.textMuted, fontFamily: 'monospace' }}>MAE: </span>
+ <span style={{ color: colors.text, fontFamily: 'monospace', fontWeight: 600 }}>
{update.mae.toFixed(4)}
</span>
</div>
<div>
- <span style={{ color: FINCEPT.GRAY, fontFamily: 'monospace' }}>Samples: </span>
- <span style={{ color: FINCEPT.WHITE, fontFamily: 'monospace', fontWeight: 600 }}>
+ <span style={{ color: colors.textMuted, fontFamily: 'monospace' }}>Samples: </span>
+ <span style={{ color: colors.text, fontFamily: 'monospace', fontWeight: 600 }}>
{update.samples}
</span>
</div>
@@ -623,11 +607,11 @@ export function OnlineLearningPanel() {
padding: '40px 20px',
textAlign: 'center'
}}>
- <Activity size={48} color={FINCEPT.MUTED} style={{ margin: '0 auto 16px' }} />
- <div style={{ fontSize: '11px', color: FINCEPT.WHITE, marginBottom: '8px', fontFamily: 'monospace' }}>
+ <Activity size={48} color={colors.textMuted} style={{ margin: '0 auto 16px' }} />
+ <div style={{ fontSize: '11px', color: colors.text, marginBottom: '8px', fontFamily: 'monospace' }}>
Ready for Online Learning
</div>
- <div style={{ fontSize: '10px', color: FINCEPT.GRAY, lineHeight: '1.5' }}>
+ <div style={{ fontSize: '10px', color: colors.textMuted, lineHeight: '1.5' }}>
Create a model and start live updates to see real-time metrics and drift detection.
<br />Results and update history will appear here.
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/RLTradingPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/RLTradingPanel.tsx
index 1c58ef49f..98ed39742 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/RLTradingPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/RLTradingPanel.tsx
@@ -5,6 +5,7 @@
*/
import React, { useState, useEffect, useRef } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import {
Brain,
Play,
@@ -30,24 +31,6 @@ import {
Clock
} from 'lucide-react';
-// Fincept Professional Color Palette
-const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- BLUE: '#0088FF',
- PURPLE: '#9D4EDD',
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F',
- MUTED: '#4A4A4A'
-};
interface TrainingMetrics {
mean_reward: number;
@@ -68,6 +51,8 @@ interface EnvironmentConfig {
}
export function RLTradingPanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+
// Environment Configuration
const [tickers, setTickers] = useState('AAPL,MSFT,GOOGL,NVDA,TSLA');
const [startDate, setStartDate] = useState('2023-01-01');
@@ -233,20 +218,20 @@ export function RLTradingPanel() {
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: FINCEPT.DARK_BG
+ backgroundColor: colors.background
}}>
{/* Terminal-style Header */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
gap: '12px'
}}>
- <Target size={16} color={FINCEPT.PURPLE} />
+ <Target size={16} color={colors.purple} />
<span style={{
- color: FINCEPT.PURPLE,
+ color: colors.purple,
fontSize: '12px',
fontWeight: 700,
letterSpacing: '0.5px',
@@ -259,9 +244,9 @@ export function RLTradingPanel() {
onClick={handleReset}
style={{
padding: '4px 12px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '10px',
fontFamily: 'monospace',
cursor: 'pointer',
@@ -271,12 +256,12 @@ export function RLTradingPanel() {
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- e.currentTarget.style.borderColor = FINCEPT.PURPLE;
+ e.currentTarget.style.backgroundColor = '#1F1F1F';
+ e.currentTarget.style.borderColor = colors.purple;
}}
onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG;
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.backgroundColor = colors.background;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}}
>
<RefreshCw size={12} />
@@ -286,9 +271,9 @@ export function RLTradingPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: envCreated && modelTrained ? FINCEPT.GREEN + '20' : FINCEPT.DARK_BG,
- border: `1px solid ${envCreated && modelTrained ? FINCEPT.GREEN : FINCEPT.BORDER}`,
- color: envCreated && modelTrained ? FINCEPT.GREEN : FINCEPT.MUTED
+ backgroundColor: envCreated && modelTrained ? colors.success + '20' : colors.background,
+ border: `1px solid ${envCreated && modelTrained ? colors.success : 'var(--ft-border-color, #2A2A2A)'}`,
+ color: envCreated && modelTrained ? colors.success : colors.textMuted
}}>
{envCreated && modelTrained ? 'READY' : 'IDLE'}
</div>
@@ -298,17 +283,17 @@ export function RLTradingPanel() {
{/* Left Sidebar - Algorithm Selection */}
<div style={{
width: '200px',
- borderRight: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
flexDirection: 'column'
}}>
<div style={{
padding: '10px 12px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.MUTED,
+ color: colors.textMuted,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -323,32 +308,32 @@ export function RLTradingPanel() {
onClick={() => !envCreated && setAlgorithm(algo.id)}
style={{
padding: '10px',
- backgroundColor: isSelected ? FINCEPT.HOVER : 'transparent',
- border: `1px solid ${isSelected ? FINCEPT.PURPLE : FINCEPT.BORDER}`,
+ backgroundColor: isSelected ? '#1F1F1F' : 'transparent',
+ border: `1px solid ${isSelected ? colors.purple : 'var(--ft-border-color, #2A2A2A)'}`,
cursor: envCreated ? 'not-allowed' : 'pointer',
opacity: envCreated ? 0.5 : 1,
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
if (!isSelected && !envCreated) {
- e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG;
- e.currentTarget.style.borderColor = FINCEPT.PURPLE;
+ e.currentTarget.style.backgroundColor = colors.background;
+ e.currentTarget.style.borderColor = colors.purple;
}
}}
onMouseLeave={(e) => {
if (!isSelected && !envCreated) {
e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>
- <Zap size={14} style={{ color: FINCEPT.PURPLE }} />
- <span style={{ color: FINCEPT.WHITE, fontSize: '11px', fontWeight: 600, fontFamily: 'monospace' }}>
+ <Zap size={14} style={{ color: colors.purple }} />
+ <span style={{ color: colors.text, fontSize: '11px', fontWeight: 600, fontFamily: 'monospace' }}>
{algo.name}
</span>
</div>
- <p style={{ color: FINCEPT.MUTED, fontSize: '9px', margin: 0, lineHeight: '1.3' }}>
+ <p style={{ color: colors.textMuted, fontSize: '9px', margin: 0, lineHeight: '1.3' }}>
{algo.desc}
</p>
</div>
@@ -362,18 +347,18 @@ export function RLTradingPanel() {
{/* Configuration Section */}
<div style={{
padding: '16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
display: 'flex',
flexDirection: 'column',
gap: '12px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Target size={14} style={{ color: FINCEPT.PURPLE }} />
- <span style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE, fontFamily: 'monospace' }}>
+ <Target size={14} style={{ color: colors.purple }} />
+ <span style={{ fontSize: '11px', fontWeight: 600, color: colors.text, fontFamily: 'monospace' }}>
ENVIRONMENT CONFIGURATION
</span>
- <span style={{ fontSize: '10px', color: FINCEPT.MUTED }}>•</span>
- <span style={{ fontSize: '10px', color: FINCEPT.MUTED }}>
+ <span style={{ fontSize: '10px', color: colors.textMuted }}>•</span>
+ <span style={{ fontSize: '10px', color: colors.textMuted }}>
{envCreated ? 'LOCKED' : 'READY TO CONFIGURE'}
</span>
</div>
@@ -381,7 +366,7 @@ export function RLTradingPanel() {
{/* Configuration Grid */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
<div>
- <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>
+ <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: colors.textMuted, fontFamily: 'monospace' }}>
TICKERS
</label>
<input
@@ -393,9 +378,9 @@ export function RLTradingPanel() {
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '11px',
fontFamily: 'monospace',
opacity: envCreated ? 0.5 : 1
@@ -404,14 +389,14 @@ export function RLTradingPanel() {
</div>
<div>
- <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>
+ <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: colors.textMuted, fontFamily: 'monospace' }}>
ALGORITHM
</label>
<div style={{
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.PURPLE}`,
- color: FINCEPT.PURPLE,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.purple}`,
+ color: colors.purple,
fontSize: '11px',
fontFamily: 'monospace',
fontWeight: 600
@@ -421,7 +406,7 @@ export function RLTradingPanel() {
</div>
<div>
- <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>
+ <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: colors.textMuted, fontFamily: 'monospace' }}>
START DATE
</label>
<input
@@ -432,9 +417,9 @@ export function RLTradingPanel() {
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '11px',
fontFamily: 'monospace',
opacity: envCreated ? 0.5 : 1
@@ -443,7 +428,7 @@ export function RLTradingPanel() {
</div>
<div>
- <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>
+ <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: colors.textMuted, fontFamily: 'monospace' }}>
END DATE
</label>
<input
@@ -454,9 +439,9 @@ export function RLTradingPanel() {
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '11px',
fontFamily: 'monospace',
opacity: envCreated ? 0.5 : 1
@@ -465,7 +450,7 @@ export function RLTradingPanel() {
</div>
<div>
- <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>
+ <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: colors.textMuted, fontFamily: 'monospace' }}>
INITIAL CASH ($)
</label>
<input
@@ -477,9 +462,9 @@ export function RLTradingPanel() {
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '11px',
fontFamily: 'monospace',
opacity: envCreated ? 0.5 : 1
@@ -488,7 +473,7 @@ export function RLTradingPanel() {
</div>
<div>
- <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>
+ <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: colors.textMuted, fontFamily: 'monospace' }}>
COMMISSION (%)
</label>
<input
@@ -500,9 +485,9 @@ export function RLTradingPanel() {
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '11px',
fontFamily: 'monospace',
opacity: envCreated ? 0.5 : 1
@@ -511,7 +496,7 @@ export function RLTradingPanel() {
</div>
<div>
- <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>
+ <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: colors.textMuted, fontFamily: 'monospace' }}>
ACTION SPACE
</label>
<div style={{ display: 'flex', gap: '8px' }}>
@@ -523,9 +508,9 @@ export function RLTradingPanel() {
style={{
flex: 1,
padding: '8px 10px',
- backgroundColor: actionSpaceType === type ? FINCEPT.PURPLE : FINCEPT.DARK_BG,
- border: `1px solid ${actionSpaceType === type ? FINCEPT.PURPLE : FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: actionSpaceType === type ? colors.purple : colors.background,
+ border: `1px solid ${actionSpaceType === type ? colors.purple : 'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '10px',
fontFamily: 'monospace',
cursor: envCreated ? 'not-allowed' : 'pointer',
@@ -541,7 +526,7 @@ export function RLTradingPanel() {
</div>
<div>
- <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>
+ <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: colors.textMuted, fontFamily: 'monospace' }}>
TIMESTEPS
</label>
<input
@@ -553,9 +538,9 @@ export function RLTradingPanel() {
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '11px',
fontFamily: 'monospace',
opacity: (isTraining || modelTrained) ? 0.5 : 1
@@ -564,7 +549,7 @@ export function RLTradingPanel() {
</div>
<div>
- <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>
+ <label style={{ display: 'block', fontSize: '10px', marginBottom: '6px', color: colors.textMuted, fontFamily: 'monospace' }}>
LEARNING RATE
</label>
<input
@@ -576,9 +561,9 @@ export function RLTradingPanel() {
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '11px',
fontFamily: 'monospace',
opacity: (isTraining || modelTrained) ? 0.5 : 1
@@ -595,9 +580,9 @@ export function RLTradingPanel() {
style={{
flex: 1,
padding: '10px 16px',
- backgroundColor: envCreated ? FINCEPT.GREEN : FINCEPT.ORANGE,
+ backgroundColor: envCreated ? colors.success : colors.primary,
border: 'none',
- color: FINCEPT.DARK_BG,
+ color: colors.background,
fontSize: '11px',
fontWeight: 700,
cursor: envCreated ? 'not-allowed' : 'pointer',
@@ -621,9 +606,9 @@ export function RLTradingPanel() {
style={{
flex: 1,
padding: '10px 16px',
- backgroundColor: modelTrained ? FINCEPT.GREEN : FINCEPT.PURPLE,
+ backgroundColor: modelTrained ? colors.success : colors.purple,
border: 'none',
- color: FINCEPT.DARK_BG,
+ color: colors.background,
fontSize: '11px',
fontWeight: 700,
cursor: (!envCreated || isTraining || modelTrained) ? 'not-allowed' : 'pointer',
@@ -661,9 +646,9 @@ export function RLTradingPanel() {
style={{
flex: 1,
padding: '10px 16px',
- backgroundColor: FINCEPT.CYAN,
+ backgroundColor: colors.accent,
border: 'none',
- color: FINCEPT.DARK_BG,
+ color: colors.background,
fontSize: '11px',
fontWeight: 700,
cursor: (!modelTrained || isEvaluating) ? 'not-allowed' : 'pointer',
@@ -695,15 +680,15 @@ export function RLTradingPanel() {
{isTraining && (
<div style={{ marginTop: '12px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
- <span style={{ fontSize: '10px', color: FINCEPT.GRAY, fontFamily: 'monospace' }}>TRAINING PROGRESS</span>
- <span style={{ fontSize: '10px', color: FINCEPT.PURPLE, fontFamily: 'monospace' }}>{progress}%</span>
+ <span style={{ fontSize: '10px', color: colors.textMuted, fontFamily: 'monospace' }}>TRAINING PROGRESS</span>
+ <span style={{ fontSize: '10px', color: colors.purple, fontFamily: 'monospace' }}>{progress}%</span>
</div>
- <div style={{ width: '100%', height: '6px', backgroundColor: FINCEPT.DARK_BG, overflow: 'hidden' }}>
+ <div style={{ width: '100%', height: '6px', backgroundColor: colors.background, overflow: 'hidden' }}>
<div
style={{
width: `${progress}%`,
height: '100%',
- backgroundColor: FINCEPT.PURPLE,
+ backgroundColor: colors.purple,
transition: 'width 0.3s ease'
}}
/>
@@ -718,10 +703,10 @@ export function RLTradingPanel() {
{error && (
<div style={{
padding: '12px 14px',
- backgroundColor: FINCEPT.RED + '15',
- border: `1px solid ${FINCEPT.RED}`,
- borderLeft: `3px solid ${FINCEPT.RED}`,
- color: FINCEPT.RED,
+ backgroundColor: colors.alert + '15',
+ border: `1px solid ${colors.alert}`,
+ borderLeft: `3px solid ${colors.alert}`,
+ color: colors.alert,
fontSize: '13px',
display: 'flex',
alignItems: 'center',
@@ -741,7 +726,7 @@ export function RLTradingPanel() {
<div style={{
fontSize: '11px',
fontWeight: 700,
- color: FINCEPT.CYAN,
+ color: colors.accent,
marginBottom: '8px',
fontFamily: 'monospace',
letterSpacing: '0.5px',
@@ -749,23 +734,23 @@ export function RLTradingPanel() {
alignItems: 'center',
gap: '6px'
}}>
- <Cpu size={13} color={FINCEPT.CYAN} />
+ <Cpu size={13} color={colors.accent} />
EXECUTION LOG
</div>
<div style={{
padding: '12px 14px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `3px solid ${FINCEPT.CYAN}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${colors.accent}`,
maxHeight: '180px',
overflowY: 'auto',
fontSize: '11px',
fontFamily: 'monospace',
- color: FINCEPT.CYAN,
+ color: colors.accent,
lineHeight: '1.7'
}}>
{logs.map((log, idx) => (
- <div key={idx} style={{ marginBottom: '3px', color: log.includes('ERROR') ? FINCEPT.RED : log.includes('✓') ? FINCEPT.GREEN : FINCEPT.CYAN }}>
+ <div key={idx} style={{ marginBottom: '3px', color: log.includes('ERROR') ? colors.alert : log.includes('✓') ? colors.success : colors.accent }}>
{log}
</div>
))}
@@ -779,7 +764,7 @@ export function RLTradingPanel() {
<div style={{
fontSize: '11px',
fontWeight: 700,
- color: FINCEPT.GREEN,
+ color: colors.success,
marginBottom: '8px',
fontFamily: 'monospace',
letterSpacing: '0.5px',
@@ -787,7 +772,7 @@ export function RLTradingPanel() {
alignItems: 'center',
gap: '6px'
}}>
- <CheckCircle2 size={13} color={FINCEPT.GREEN} />
+ <CheckCircle2 size={13} color={colors.success} />
EVALUATION RESULTS
</div>
@@ -795,17 +780,17 @@ export function RLTradingPanel() {
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '12px' }}>
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${trainingMetrics.portfolio_return > 0 ? FINCEPT.GREEN : FINCEPT.RED}`,
- borderLeft: `3px solid ${trainingMetrics.portfolio_return > 0 ? FINCEPT.GREEN : FINCEPT.RED}`
+ backgroundColor: colors.panel,
+ border: `1px solid ${trainingMetrics.portfolio_return > 0 ? colors.success : colors.alert}`,
+ borderLeft: `3px solid ${trainingMetrics.portfolio_return > 0 ? colors.success : colors.alert}`
}}>
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '9px', color: colors.textMuted, marginBottom: '4px', fontFamily: 'monospace' }}>
PORTFOLIO RETURN
</div>
<div style={{
fontSize: '20px',
fontWeight: 700,
- color: trainingMetrics.portfolio_return > 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ color: trainingMetrics.portfolio_return > 0 ? colors.success : colors.alert,
fontFamily: 'monospace'
}}>
{trainingMetrics.portfolio_return > 0 ? '+' : ''}{trainingMetrics.portfolio_return.toFixed(2)}%
@@ -814,14 +799,14 @@ export function RLTradingPanel() {
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.CYAN}`,
- borderLeft: `3px solid ${FINCEPT.CYAN}`
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.accent}`,
+ borderLeft: `3px solid ${colors.accent}`
}}>
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '9px', color: colors.textMuted, marginBottom: '4px', fontFamily: 'monospace' }}>
PORTFOLIO VALUE
</div>
- <div style={{ fontSize: '20px', fontWeight: 700, color: FINCEPT.CYAN, fontFamily: 'monospace' }}>
+ <div style={{ fontSize: '20px', fontWeight: 700, color: colors.accent, fontFamily: 'monospace' }}>
${(trainingMetrics.mean_portfolio_value / 1000).toFixed(0)}K
</div>
</div>
@@ -830,31 +815,31 @@ export function RLTradingPanel() {
{/* Detailed Metrics */}
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px' }}>
- <span style={{ color: FINCEPT.GRAY, fontFamily: 'monospace' }}>Mean Reward:</span>
- <span style={{ color: FINCEPT.WHITE, fontFamily: 'monospace', fontWeight: 600 }}>
+ <span style={{ color: colors.textMuted, fontFamily: 'monospace' }}>Mean Reward:</span>
+ <span style={{ color: colors.text, fontFamily: 'monospace', fontWeight: 600 }}>
{trainingMetrics.mean_reward.toFixed(4)}
</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px' }}>
- <span style={{ color: FINCEPT.GRAY, fontFamily: 'monospace' }}>Std Reward:</span>
- <span style={{ color: FINCEPT.WHITE, fontFamily: 'monospace', fontWeight: 600 }}>
+ <span style={{ color: colors.textMuted, fontFamily: 'monospace' }}>Std Reward:</span>
+ <span style={{ color: colors.text, fontFamily: 'monospace', fontWeight: 600 }}>
{trainingMetrics.std_reward.toFixed(4)}
</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px' }}>
- <span style={{ color: FINCEPT.GRAY, fontFamily: 'monospace' }}>Episode Length:</span>
- <span style={{ color: FINCEPT.WHITE, fontFamily: 'monospace', fontWeight: 600 }}>
+ <span style={{ color: colors.textMuted, fontFamily: 'monospace' }}>Episode Length:</span>
+ <span style={{ color: colors.text, fontFamily: 'monospace', fontWeight: 600 }}>
{trainingMetrics.mean_length}
</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px' }}>
- <span style={{ color: FINCEPT.GRAY, fontFamily: 'monospace' }}>Episodes:</span>
- <span style={{ color: FINCEPT.WHITE, fontFamily: 'monospace', fontWeight: 600 }}>
+ <span style={{ color: colors.textMuted, fontFamily: 'monospace' }}>Episodes:</span>
+ <span style={{ color: colors.text, fontFamily: 'monospace', fontWeight: 600 }}>
{trainingMetrics.episode_count}
</span>
</div>
@@ -869,11 +854,11 @@ export function RLTradingPanel() {
padding: '40px 20px',
textAlign: 'center'
}}>
- <Brain size={48} color={FINCEPT.MUTED} style={{ margin: '0 auto 16px' }} />
- <div style={{ fontSize: '11px', color: FINCEPT.WHITE, marginBottom: '8px', fontFamily: 'monospace' }}>
+ <Brain size={48} color={colors.textMuted} style={{ margin: '0 auto 16px' }} />
+ <div style={{ fontSize: '11px', color: colors.text, marginBottom: '8px', fontFamily: 'monospace' }}>
Ready to Train RL Agent
</div>
- <div style={{ fontSize: '10px', color: FINCEPT.GRAY, lineHeight: '1.5' }}>
+ <div style={{ fontSize: '10px', color: colors.textMuted, lineHeight: '1.5' }}>
Configure your environment, select an algorithm, and start training.
<br />Results and logs will appear here.
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/RollingRetrainingPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/RollingRetrainingPanel.tsx
index c62500f93..aaf97f673 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/RollingRetrainingPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/RollingRetrainingPanel.tsx
@@ -4,14 +4,10 @@
*/
import React, { useState } from 'react';
import { RefreshCw, Calendar, Clock, CheckCircle2, Play, Pause, Trash2, Settings, Zap } from 'lucide-react';
-
-const FINCEPT = {
- ORANGE: '#FF8800', WHITE: '#FFFFFF', GREEN: '#00D66F', GRAY: '#787878',
- DARK_BG: '#000000', PANEL_BG: '#0F0F0F', BORDER: '#2A2A2A', CYAN: '#00E5FF',
- MUTED: '#4A4A4A', HOVER: '#1F1F1F', PURPLE: '#9D4EDD', RED: '#FF3B3B'
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
export function RollingRetrainingPanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [frequency, setFrequency] = useState('daily');
const [modelName, setModelName] = useState('');
const [windowSize, setWindowSize] = useState('252');
@@ -26,20 +22,20 @@ export function RollingRetrainingPanel() {
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: FINCEPT.DARK_BG
+ backgroundColor: colors.background
}}>
{/* Terminal-style Header */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
gap: '12px'
}}>
- <RefreshCw size={16} color={FINCEPT.CYAN} />
+ <RefreshCw size={16} color={colors.accent} />
<span style={{
- color: FINCEPT.CYAN,
+ color: colors.accent,
fontSize: '12px',
fontWeight: 700,
letterSpacing: '0.5px',
@@ -52,9 +48,9 @@ export function RollingRetrainingPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: FINCEPT.GREEN + '20',
- border: `1px solid ${FINCEPT.GREEN}`,
- color: FINCEPT.GREEN
+ backgroundColor: colors.success + '20',
+ border: `1px solid ${colors.success}`,
+ color: colors.success
}}>
{schedules.filter(s => s.status === 'active').length} ACTIVE
</div>
@@ -64,19 +60,19 @@ export function RollingRetrainingPanel() {
{/* Left Panel - Create Schedule */}
<div style={{
width: '320px',
- borderRight: `1px solid ${FINCEPT.BORDER}`,
+ borderRight: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
display: 'flex',
flexDirection: 'column'
}}>
<div style={{
padding: '10px 12px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.ORANGE,
+ color: colors.primary,
fontFamily: 'monospace',
letterSpacing: '0.5px',
- backgroundColor: FINCEPT.PANEL_BG
+ backgroundColor: colors.panel
}}>
CREATE NEW SCHEDULE
</div>
@@ -88,7 +84,7 @@ export function RollingRetrainingPanel() {
display: 'block',
fontSize: '10px',
marginBottom: '6px',
- color: FINCEPT.WHITE,
+ color: colors.text,
fontFamily: 'monospace',
letterSpacing: '0.5px',
opacity: 0.7
@@ -103,9 +99,9 @@ export function RollingRetrainingPanel() {
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '11px',
fontFamily: 'monospace',
outline: 'none'
@@ -119,7 +115,7 @@ export function RollingRetrainingPanel() {
display: 'block',
fontSize: '10px',
marginBottom: '6px',
- color: FINCEPT.WHITE,
+ color: colors.text,
fontFamily: 'monospace',
letterSpacing: '0.5px',
opacity: 0.7
@@ -138,9 +134,9 @@ export function RollingRetrainingPanel() {
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: colors.text,
fontSize: '11px',
fontFamily: 'monospace',
outline: 'none'
@@ -154,7 +150,7 @@ export function RollingRetrainingPanel() {
display: 'block',
fontSize: '10px',
marginBottom: '6px',
- color: FINCEPT.WHITE,
+ color: colors.text,
fontFamily: 'monospace',
letterSpacing: '0.5px',
opacity: 0.7
@@ -168,9 +164,9 @@ export function RollingRetrainingPanel() {
onClick={() => setFrequency(freq)}
style={{
padding: '10px',
- backgroundColor: frequency === freq ? FINCEPT.CYAN + '30' : FINCEPT.PANEL_BG,
- border: `1px solid ${frequency === freq ? FINCEPT.CYAN : FINCEPT.BORDER}`,
- color: frequency === freq ? FINCEPT.CYAN : FINCEPT.WHITE,
+ backgroundColor: frequency === freq ? colors.accent + '30' : colors.panel,
+ border: `1px solid ${frequency === freq ? colors.accent : 'var(--ft-border-color, #2A2A2A)'}`,
+ color: frequency === freq ? colors.accent : colors.text,
fontSize: '11px',
fontWeight: 600,
fontFamily: 'monospace',
@@ -185,14 +181,14 @@ export function RollingRetrainingPanel() {
}}
onMouseEnter={(e) => {
if (frequency !== freq) {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- e.currentTarget.style.borderColor = FINCEPT.CYAN;
+ e.currentTarget.style.backgroundColor = '#1F1F1F';
+ e.currentTarget.style.borderColor = colors.accent;
}
}}
onMouseLeave={(e) => {
if (frequency !== freq) {
- e.currentTarget.style.backgroundColor = FINCEPT.PANEL_BG;
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.backgroundColor = colors.panel;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}
}}
>
@@ -208,7 +204,7 @@ export function RollingRetrainingPanel() {
style={{
width: '100%',
padding: '12px 16px',
- backgroundColor: FINCEPT.CYAN,
+ backgroundColor: colors.accent,
border: 'none',
color: '#000000',
fontSize: '11px',
@@ -234,13 +230,13 @@ export function RollingRetrainingPanel() {
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
<div style={{
padding: '10px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.GREEN,
+ color: colors.success,
fontFamily: 'monospace',
letterSpacing: '0.5px',
- backgroundColor: FINCEPT.PANEL_BG
+ backgroundColor: colors.panel
}}>
ACTIVE SCHEDULES ({schedules.length})
</div>
@@ -252,9 +248,9 @@ export function RollingRetrainingPanel() {
key={sched.id}
style={{
padding: '14px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${sched.status === 'active' ? FINCEPT.GREEN : FINCEPT.BORDER}`,
- borderLeft: `3px solid ${sched.status === 'active' ? FINCEPT.GREEN : FINCEPT.PURPLE}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${sched.status === 'active' ? colors.success : 'var(--ft-border-color, #2A2A2A)'}`,
+ borderLeft: `3px solid ${sched.status === 'active' ? colors.success : colors.purple}`,
display: 'flex',
flexDirection: 'column',
gap: '10px'
@@ -263,9 +259,9 @@ export function RollingRetrainingPanel() {
{/* Header */}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Zap size={14} color={sched.status === 'active' ? FINCEPT.GREEN : FINCEPT.PURPLE} />
+ <Zap size={14} color={sched.status === 'active' ? colors.success : colors.purple} />
<span style={{
- color: FINCEPT.WHITE,
+ color: colors.text,
fontSize: '12px',
fontWeight: 700,
fontFamily: 'monospace'
@@ -277,9 +273,9 @@ export function RollingRetrainingPanel() {
fontSize: '9px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: sched.status === 'active' ? FINCEPT.GREEN + '20' : FINCEPT.PURPLE + '20',
- border: `1px solid ${sched.status === 'active' ? FINCEPT.GREEN : FINCEPT.PURPLE}`,
- color: sched.status === 'active' ? FINCEPT.GREEN : FINCEPT.PURPLE,
+ backgroundColor: sched.status === 'active' ? colors.success + '20' : colors.purple + '20',
+ border: `1px solid ${sched.status === 'active' ? colors.success : colors.purple}`,
+ color: sched.status === 'active' ? colors.success : colors.purple,
textTransform: 'uppercase'
}}>
{sched.status}
@@ -289,34 +285,34 @@ export function RollingRetrainingPanel() {
{/* Details Grid */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
<div>
- <div style={{ fontSize: '9px', color: FINCEPT.WHITE, opacity: 0.5, fontFamily: 'monospace', marginBottom: '3px' }}>
+ <div style={{ fontSize: '9px', color: colors.text, opacity: 0.5, fontFamily: 'monospace', marginBottom: '3px' }}>
FREQUENCY
</div>
- <div style={{ fontSize: '11px', color: FINCEPT.CYAN, fontFamily: 'monospace', fontWeight: 600 }}>
+ <div style={{ fontSize: '11px', color: colors.accent, fontFamily: 'monospace', fontWeight: 600 }}>
{sched.frequency.toUpperCase()}
</div>
</div>
<div>
- <div style={{ fontSize: '9px', color: FINCEPT.WHITE, opacity: 0.5, fontFamily: 'monospace', marginBottom: '3px' }}>
+ <div style={{ fontSize: '9px', color: colors.text, opacity: 0.5, fontFamily: 'monospace', marginBottom: '3px' }}>
WINDOW
</div>
- <div style={{ fontSize: '11px', color: FINCEPT.CYAN, fontFamily: 'monospace', fontWeight: 600 }}>
+ <div style={{ fontSize: '11px', color: colors.accent, fontFamily: 'monospace', fontWeight: 600 }}>
{sched.windowSize} days
</div>
</div>
<div>
- <div style={{ fontSize: '9px', color: FINCEPT.WHITE, opacity: 0.5, fontFamily: 'monospace', marginBottom: '3px' }}>
+ <div style={{ fontSize: '9px', color: colors.text, opacity: 0.5, fontFamily: 'monospace', marginBottom: '3px' }}>
LAST RUN
</div>
- <div style={{ fontSize: '10px', color: FINCEPT.WHITE, fontFamily: 'monospace', opacity: 0.7 }}>
+ <div style={{ fontSize: '10px', color: colors.text, fontFamily: 'monospace', opacity: 0.7 }}>
{sched.lastRun}
</div>
</div>
<div>
- <div style={{ fontSize: '9px', color: FINCEPT.WHITE, opacity: 0.5, fontFamily: 'monospace', marginBottom: '3px' }}>
+ <div style={{ fontSize: '9px', color: colors.text, opacity: 0.5, fontFamily: 'monospace', marginBottom: '3px' }}>
NEXT RUN
</div>
- <div style={{ fontSize: '10px', color: FINCEPT.ORANGE, fontFamily: 'monospace', fontWeight: 600 }}>
+ <div style={{ fontSize: '10px', color: colors.primary, fontFamily: 'monospace', fontWeight: 600 }}>
{sched.nextRun}
</div>
</div>
@@ -329,8 +325,8 @@ export function RollingRetrainingPanel() {
flex: 1,
padding: '6px 10px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.ORANGE}`,
- color: FINCEPT.ORANGE,
+ border: `1px solid ${colors.primary}`,
+ color: colors.primary,
fontSize: '9px',
fontWeight: 700,
fontFamily: 'monospace',
@@ -343,7 +339,7 @@ export function RollingRetrainingPanel() {
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.ORANGE + '20';
+ e.currentTarget.style.backgroundColor = colors.primary + '20';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
@@ -357,8 +353,8 @@ export function RollingRetrainingPanel() {
flex: 1,
padding: '6px 10px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.CYAN}`,
- color: FINCEPT.CYAN,
+ border: `1px solid ${colors.accent}`,
+ color: colors.accent,
fontSize: '9px',
fontWeight: 700,
fontFamily: 'monospace',
@@ -371,7 +367,7 @@ export function RollingRetrainingPanel() {
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.CYAN + '20';
+ e.currentTarget.style.backgroundColor = colors.accent + '20';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
@@ -384,8 +380,8 @@ export function RollingRetrainingPanel() {
style={{
padding: '6px 10px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.RED}`,
- color: FINCEPT.RED,
+ border: `1px solid ${colors.alert}`,
+ color: colors.alert,
fontSize: '9px',
fontWeight: 700,
fontFamily: 'monospace',
@@ -398,7 +394,7 @@ export function RollingRetrainingPanel() {
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.RED + '20';
+ e.currentTarget.style.backgroundColor = colors.alert + '20';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
@@ -421,11 +417,11 @@ export function RollingRetrainingPanel() {
height: '300px',
textAlign: 'center'
}}>
- <Calendar size={48} color={FINCEPT.MUTED} style={{ opacity: 0.3, marginBottom: '16px' }} />
- <div style={{ color: FINCEPT.WHITE, fontSize: '12px', fontWeight: 700, letterSpacing: '0.5px', marginBottom: '8px', fontFamily: 'monospace' }}>
+ <Calendar size={48} color={colors.textMuted} style={{ opacity: 0.3, marginBottom: '16px' }} />
+ <div style={{ color: colors.text, fontSize: '12px', fontWeight: 700, letterSpacing: '0.5px', marginBottom: '8px', fontFamily: 'monospace' }}>
NO SCHEDULES CONFIGURED
</div>
- <div style={{ color: FINCEPT.MUTED, fontSize: '11px', maxWidth: '400px', lineHeight: '1.6' }}>
+ <div style={{ color: colors.textMuted, fontSize: '11px', maxWidth: '400px', lineHeight: '1.6' }}>
Create a new retraining schedule to automate model updates
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/StatsmodelsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/StatsmodelsPanel.tsx
index 6eaeecd8f..dbc198cd0 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/StatsmodelsPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/StatsmodelsPanel.tsx
@@ -23,25 +23,10 @@ import {
} from 'lucide-react';
import { statsmodelsService, type StatsmodelsResult } from '@/services/aiQuantLab/statsmodelsService';
import { yfinanceService } from '@/services/markets/yfinanceService';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
-const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- BLUE: '#0088FF',
- PURPLE: '#9D4EDD',
- TEAL: '#00C9A7', // Unique theme color for Statsmodels
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F',
- MUTED: '#4A4A4A'
-};
+// Unique theme color for Statsmodels
+const TEAL = '#00C9A7';
type AnalysisCategory = 'time_series' | 'stationarity' | 'regression' | 'glm' | 'tests' | 'power' | 'multivariate' | 'nonparametric';
type DataSourceType = 'manual' | 'symbol';
@@ -147,6 +132,7 @@ const getParamFields = (analysisId: string): ParamField[] => {
};
export function StatsmodelsPanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [analysisResult, setAnalysisResult] = useState<StatsmodelsResult<Record<string, unknown>> | null>(null);
@@ -329,35 +315,35 @@ export function StatsmodelsPanel() {
return (
<div
className="border rounded p-4 mt-4"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ style={{ backgroundColor: colors.panel, borderColor: 'var(--ft-border-color, #2A2A2A)' }}
>
<div className="flex items-center gap-2 mb-3">
{analysisResult.success ? (
- <CheckCircle2 size={16} color={FINCEPT.GREEN} />
+ <CheckCircle2 size={16} color={colors.success} />
) : (
- <AlertCircle size={16} color={FINCEPT.RED} />
+ <AlertCircle size={16} color={colors.alert} />
)}
<span
className="text-xs font-semibold"
- style={{ color: analysisResult.success ? FINCEPT.GREEN : FINCEPT.RED }}
+ style={{ color: analysisResult.success ? colors.success : colors.alert }}
>
{analysisResult.success ? 'ANALYSIS COMPLETE' : 'ANALYSIS FAILED'}
</span>
{analysisResult.analysis_type && (
- <span className="text-xs" style={{ color: FINCEPT.GRAY }}>
+ <span className="text-xs" style={{ color: colors.textMuted }}>
- {analysisResult.analysis_type.toUpperCase()}
</span>
)}
</div>
{analysisResult.error && (
- <div className="text-xs p-2 rounded mb-3" style={{ backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.RED }}>
+ <div className="text-xs p-2 rounded mb-3" style={{ backgroundColor: colors.background, color: colors.alert }}>
{analysisResult.error}
{analysisResult.message && (
- <div className="mt-1" style={{ color: FINCEPT.GRAY }}>{analysisResult.message}</div>
+ <div className="mt-1" style={{ color: colors.textMuted }}>{analysisResult.message}</div>
)}
{analysisResult.suggestions && Array.isArray(analysisResult.suggestions) && (
- <div className="mt-2" style={{ color: FINCEPT.ORANGE }}>
+ <div className="mt-2" style={{ color: colors.primary }}>
<div className="font-semibold mb-1">Suggestions:</div>
<ul className="list-disc list-inside">
{analysisResult.suggestions.map((s: string, i: number) => (
@@ -377,9 +363,9 @@ export function StatsmodelsPanel() {
const isExpanded = expandedArrays.has(key);
return (
- <div key={key} className="py-2 border-b" style={{ borderColor: FINCEPT.BORDER }}>
+ <div key={key} className="py-2 border-b" style={{ borderColor: 'var(--ft-border-color, #2A2A2A)' }}>
<div className="flex justify-between items-start gap-4">
- <span className="text-xs font-mono" style={{ color: FINCEPT.ORANGE }}>{key}</span>
+ <span className="text-xs font-mono" style={{ color: colors.primary }}>{key}</span>
<div className="flex items-center gap-1">
{isLargeArray && (
<>
@@ -389,9 +375,9 @@ export function StatsmodelsPanel() {
title={isExpanded ? "Collapse" : "View All"}
>
{isExpanded ? (
- <ChevronUp size={12} color={FINCEPT.GRAY} />
+ <ChevronUp size={12} color={colors.textMuted} />
) : (
- <Eye size={12} color={FINCEPT.GRAY} />
+ <Eye size={12} color={colors.textMuted} />
)}
</button>
<button
@@ -399,14 +385,14 @@ export function StatsmodelsPanel() {
className="p-1 rounded hover:bg-opacity-20 hover:bg-white"
title="Copy to Clipboard"
>
- <Copy size={12} color={FINCEPT.GRAY} />
+ <Copy size={12} color={colors.textMuted} />
</button>
<button
onClick={() => exportData(key, value)}
className="p-1 rounded hover:bg-opacity-20 hover:bg-white"
title="Export as CSV"
>
- <Download size={12} color={FINCEPT.GRAY} />
+ <Download size={12} color={colors.textMuted} />
</button>
</>
)}
@@ -415,7 +401,7 @@ export function StatsmodelsPanel() {
<div
className="text-xs font-mono mt-1"
style={{
- color: FINCEPT.WHITE,
+ color: colors.text,
maxHeight: isExpanded ? '300px' : 'none',
overflowY: isExpanded ? 'auto' : 'visible',
wordBreak: 'break-all'
@@ -434,7 +420,7 @@ export function StatsmodelsPanel() {
<button
onClick={exportAllResults}
className="flex items-center gap-1 px-3 py-1.5 text-xs font-semibold rounded"
- style={{ backgroundColor: FINCEPT.HEADER_BG, color: FINCEPT.ORANGE, border: `1px solid ${FINCEPT.BORDER}` }}
+ style={{ backgroundColor: colors.panel, color: colors.primary, border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}` }}
>
<Download size={12} />
Export All Results
@@ -443,7 +429,7 @@ export function StatsmodelsPanel() {
)}
{analysisResult.timestamp && (
- <div className="mt-3 text-xs" style={{ color: FINCEPT.MUTED }}>
+ <div className="mt-3 text-xs" style={{ color: colors.textMuted }}>
Timestamp: {analysisResult.timestamp}
</div>
)}
@@ -456,20 +442,20 @@ export function StatsmodelsPanel() {
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: FINCEPT.DARK_BG
+ backgroundColor: colors.background
}}>
{/* Terminal-style Header */}
<div style={{
padding: '12px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
alignItems: 'center',
gap: '12px'
}}>
- <Activity size={16} color={FINCEPT.TEAL} />
+ <Activity size={16} color={TEAL} />
<span style={{
- color: FINCEPT.TEAL,
+ color: TEAL,
fontSize: '12px',
fontWeight: 700,
letterSpacing: '0.5px',
@@ -482,9 +468,9 @@ export function StatsmodelsPanel() {
fontSize: '10px',
fontFamily: 'monospace',
padding: '3px 8px',
- backgroundColor: analysisResult ? FINCEPT.GREEN + '20' : FINCEPT.TEAL + '20',
- border: `1px solid ${analysisResult ? FINCEPT.GREEN : FINCEPT.TEAL}`,
- color: analysisResult ? FINCEPT.GREEN : FINCEPT.TEAL
+ backgroundColor: analysisResult ? colors.success + '20' : TEAL + '20',
+ border: `1px solid ${analysisResult ? colors.success : TEAL}`,
+ color: analysisResult ? colors.success : TEAL
}}>
{analysisResult ? 'RESULTS READY' : 'READY'}
</div>
@@ -494,8 +480,8 @@ export function StatsmodelsPanel() {
{/* Left Sidebar - Configuration */}
<div style={{
width: '320px',
- borderRight: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ backgroundColor: colors.panel,
display: 'flex',
flexDirection: 'column'
}}>
@@ -503,10 +489,10 @@ export function StatsmodelsPanel() {
{/* Data Source Section */}
<div style={{
padding: '10px 12px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.TEAL,
+ color: TEAL,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -520,9 +506,9 @@ export function StatsmodelsPanel() {
style={{
flex: 1,
padding: '8px 14px',
- backgroundColor: dataSourceType === 'symbol' ? FINCEPT.TEAL : FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: dataSourceType === 'symbol' ? '#000000' : FINCEPT.WHITE,
+ backgroundColor: dataSourceType === 'symbol' ? TEAL : colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ color: dataSourceType === 'symbol' ? '#000000' : colors.text,
opacity: dataSourceType === 'symbol' ? 1 : 0.7,
fontSize: '10px',
fontWeight: 700,
@@ -539,11 +525,11 @@ export function StatsmodelsPanel() {
style={{
flex: 1,
padding: '8px 14px',
- backgroundColor: dataSourceType === 'manual' ? FINCEPT.TEAL : FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: dataSourceType === 'manual' ? TEAL : colors.background,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
borderLeft: '0',
marginLeft: '-1px',
- color: dataSourceType === 'manual' ? '#000000' : FINCEPT.WHITE,
+ color: dataSourceType === 'manual' ? '#000000' : colors.text,
opacity: dataSourceType === 'manual' ? 1 : 0.7,
fontSize: '10px',
fontWeight: 700,
@@ -570,9 +556,9 @@ export function StatsmodelsPanel() {
padding: '8px 10px',
fontSize: '11px',
fontFamily: 'monospace',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
outline: 'none'
}}
/>
@@ -581,7 +567,7 @@ export function StatsmodelsPanel() {
disabled={priceDataLoading}
style={{
padding: '8px 12px',
- backgroundColor: FINCEPT.TEAL,
+ backgroundColor: TEAL,
border: 'none',
color: '#000000',
cursor: priceDataLoading ? 'not-allowed' : 'pointer',
@@ -599,7 +585,7 @@ export function StatsmodelsPanel() {
display: 'block',
fontSize: '9px',
marginBottom: '6px',
- color: FINCEPT.WHITE,
+ color: colors.text,
fontFamily: 'monospace',
letterSpacing: '0.5px',
opacity: 0.7
@@ -614,9 +600,9 @@ export function StatsmodelsPanel() {
padding: '8px 10px',
fontSize: '11px',
fontFamily: 'monospace',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
outline: 'none'
}}
>
@@ -632,10 +618,10 @@ export function StatsmodelsPanel() {
<div style={{
fontSize: '10px',
fontFamily: 'monospace',
- color: FINCEPT.GREEN,
+ color: colors.success,
padding: '6px 10px',
- backgroundColor: FINCEPT.GREEN + '20',
- border: `1px solid ${FINCEPT.GREEN}`
+ backgroundColor: colors.success + '20',
+ border: `1px solid ${colors.success}`
}}>
Loaded {priceData.length} data points
</div>
@@ -652,9 +638,9 @@ export function StatsmodelsPanel() {
padding: '8px 10px',
fontSize: '11px',
fontFamily: 'monospace',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
outline: 'none',
resize: 'vertical'
}}
@@ -665,11 +651,11 @@ export function StatsmodelsPanel() {
{/* Category Section */}
<div style={{
padding: '10px 12px',
- borderTop: `1px solid ${FINCEPT.BORDER}`,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderTop: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.TEAL,
+ color: TEAL,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -692,9 +678,9 @@ export function StatsmodelsPanel() {
padding: '8px 10px',
fontSize: '11px',
fontFamily: 'monospace',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
outline: 'none'
}}
>
@@ -707,11 +693,11 @@ export function StatsmodelsPanel() {
{/* Analysis Type Section */}
<div style={{
padding: '10px 12px',
- borderTop: `1px solid ${FINCEPT.BORDER}`,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderTop: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.TEAL,
+ color: TEAL,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -729,9 +715,9 @@ export function StatsmodelsPanel() {
padding: '8px 10px',
fontSize: '11px',
fontFamily: 'monospace',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
outline: 'none',
marginBottom: '10px'
}}
@@ -744,7 +730,7 @@ export function StatsmodelsPanel() {
</select>
<div style={{
fontSize: '10px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.6,
lineHeight: '1.5',
fontFamily: 'monospace'
@@ -756,10 +742,10 @@ export function StatsmodelsPanel() {
marginTop: '10px',
padding: '10px',
fontSize: '10px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.TEAL}`,
- borderLeft: `3px solid ${FINCEPT.TEAL}`,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${TEAL}`,
+ borderLeft: `3px solid ${TEAL}`,
+ color: colors.text,
lineHeight: '1.5',
fontFamily: 'monospace'
}}>
@@ -773,11 +759,11 @@ export function StatsmodelsPanel() {
<>
<div style={{
padding: '10px 12px',
- borderTop: `1px solid ${FINCEPT.BORDER}`,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderTop: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.TEAL,
+ color: TEAL,
fontFamily: 'monospace',
letterSpacing: '0.5px'
}}>
@@ -790,7 +776,7 @@ export function StatsmodelsPanel() {
display: 'block',
fontSize: '9px',
marginBottom: '6px',
- color: FINCEPT.WHITE,
+ color: colors.text,
fontFamily: 'monospace',
letterSpacing: '0.5px',
opacity: 0.7
@@ -806,9 +792,9 @@ export function StatsmodelsPanel() {
padding: '8px 10px',
fontSize: '11px',
fontFamily: 'monospace',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
outline: 'none'
}}
>
@@ -827,9 +813,9 @@ export function StatsmodelsPanel() {
padding: '8px 10px',
fontSize: '11px',
fontFamily: 'monospace',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
outline: 'none'
}}
/>
@@ -842,14 +828,14 @@ export function StatsmodelsPanel() {
</div>
{/* Run Button */}
- <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}`, padding: '12px' }}>
+ <div style={{ borderTop: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`, padding: '12px' }}>
<button
onClick={runAnalysis}
disabled={isLoading}
style={{
width: '100%',
padding: '12px 16px',
- backgroundColor: FINCEPT.TEAL,
+ backgroundColor: TEAL,
border: 'none',
color: '#000000',
fontSize: '11px',
@@ -884,13 +870,13 @@ export function StatsmodelsPanel() {
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
<div style={{
padding: '10px 16px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`,
fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.TEAL,
+ color: TEAL,
fontFamily: 'monospace',
letterSpacing: '0.5px',
- backgroundColor: FINCEPT.PANEL_BG
+ backgroundColor: colors.panel
}}>
STATISTICAL MODELING & ECONOMETRIC ANALYSIS
</div>
@@ -914,38 +900,38 @@ export function StatsmodelsPanel() {
}}
style={{
padding: '12px',
- backgroundColor: isSelected ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- border: `1px solid ${isSelected ? FINCEPT.TEAL : FINCEPT.BORDER}`,
+ backgroundColor: isSelected ? '#1F1F1F' : colors.panel,
+ border: `1px solid ${isSelected ? TEAL : 'var(--ft-border-color, #2A2A2A)'}`,
cursor: 'pointer',
textAlign: 'left',
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
if (!isSelected) {
- e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG;
- e.currentTarget.style.borderColor = FINCEPT.TEAL;
+ e.currentTarget.style.backgroundColor = colors.background;
+ e.currentTarget.style.borderColor = TEAL;
}
}}
onMouseLeave={(e) => {
if (!isSelected) {
- e.currentTarget.style.backgroundColor = FINCEPT.PANEL_BG;
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.backgroundColor = colors.panel;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}
}}
>
- <Icon size={16} color={FINCEPT.TEAL} />
+ <Icon size={16} color={TEAL} />
<div style={{
fontSize: '11px',
fontWeight: 600,
marginTop: '8px',
- color: FINCEPT.WHITE,
+ color: colors.text,
fontFamily: 'monospace'
}}>
{label}
</div>
<div style={{
fontSize: '9px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
marginTop: '4px',
fontFamily: 'monospace'
@@ -963,7 +949,7 @@ export function StatsmodelsPanel() {
fontSize: '10px',
fontWeight: 700,
marginBottom: '12px',
- color: FINCEPT.TEAL,
+ color: TEAL,
letterSpacing: '0.5px',
fontFamily: 'monospace'
}}>
@@ -983,29 +969,29 @@ export function StatsmodelsPanel() {
}}
style={{
padding: '10px',
- backgroundColor: isSelected ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- border: `1px solid ${isSelected ? FINCEPT.TEAL : FINCEPT.BORDER}`,
+ backgroundColor: isSelected ? '#1F1F1F' : colors.panel,
+ border: `1px solid ${isSelected ? TEAL : 'var(--ft-border-color, #2A2A2A)'}`,
cursor: 'pointer',
textAlign: 'left',
transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
if (!isSelected) {
- e.currentTarget.style.backgroundColor = FINCEPT.DARK_BG;
- e.currentTarget.style.borderColor = FINCEPT.TEAL;
+ e.currentTarget.style.backgroundColor = colors.background;
+ e.currentTarget.style.borderColor = TEAL;
}
}}
onMouseLeave={(e) => {
if (!isSelected) {
- e.currentTarget.style.backgroundColor = FINCEPT.PANEL_BG;
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.backgroundColor = colors.panel;
+ e.currentTarget.style.borderColor = 'var(--ft-border-color, #2A2A2A)';
}
}}
>
<div style={{
fontSize: '11px',
fontWeight: 600,
- color: isSelected ? FINCEPT.TEAL : FINCEPT.WHITE,
+ color: isSelected ? TEAL : colors.text,
fontFamily: 'monospace',
marginBottom: '4px'
}}>
@@ -1013,7 +999,7 @@ export function StatsmodelsPanel() {
</div>
<div style={{
fontSize: '10px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.6,
lineHeight: '1.4',
fontFamily: 'monospace'
@@ -1030,10 +1016,10 @@ export function StatsmodelsPanel() {
{error && (
<div style={{
padding: '12px 14px',
- backgroundColor: FINCEPT.RED + '15',
- border: `1px solid ${FINCEPT.RED}`,
- borderLeft: `3px solid ${FINCEPT.RED}`,
- color: FINCEPT.RED,
+ backgroundColor: colors.alert + '15',
+ border: `1px solid ${colors.alert}`,
+ borderLeft: `3px solid ${colors.alert}`,
+ color: colors.alert,
fontSize: '11px',
display: 'flex',
alignItems: 'center',
@@ -1055,13 +1041,13 @@ export function StatsmodelsPanel() {
<div style={{
padding: '40px 20px',
textAlign: 'center',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ border: `1px solid ${'var(--ft-border-color, #2A2A2A)'}`
}}>
- <Database size={48} color={FINCEPT.MUTED} style={{ margin: '0 auto 16px' }} />
+ <Database size={48} color={colors.textMuted} style={{ margin: '0 auto 16px' }} />
<div style={{
fontSize: '11px',
- color: FINCEPT.WHITE,
+ color: colors.text,
marginBottom: '8px',
fontFamily: 'monospace'
}}>
@@ -1069,7 +1055,7 @@ export function StatsmodelsPanel() {
</div>
<div style={{
fontSize: '10px',
- color: FINCEPT.WHITE,
+ color: colors.text,
opacity: 0.5,
fontFamily: 'monospace'
}}>
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/StatusBar.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/StatusBar.tsx
index 17c66d908..0cca63c32 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/StatusBar.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/StatusBar.tsx
@@ -6,25 +6,7 @@
import React from 'react';
import { CheckCircle, XCircle } from 'lucide-react';
import { APP_VERSION } from '@/constants/version';
-
-// Fincept Professional Color Palette
-const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- BLUE: '#0088FF',
- PURPLE: '#9D4EDD',
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F',
- MUTED: '#4A4A4A'
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface StatusBarProps {
qlibStatus: { available: boolean };
@@ -32,34 +14,36 @@ interface StatusBarProps {
}
export function StatusBar({ qlibStatus, rdAgentStatus }: StatusBarProps) {
+ const { colors } = useTerminalTheme();
+
return (
<div
className="flex items-center justify-between px-6 py-2 border-t text-xs uppercase"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ style={{ backgroundColor: colors.panel, borderColor: 'var(--ft-border-color, #2A2A2A)' }}
>
<div className="flex items-center gap-6">
<div className="flex items-center gap-2">
{qlibStatus.available ? (
- <CheckCircle size={14} color={FINCEPT.GREEN} />
+ <CheckCircle size={14} color={colors.success} />
) : (
- <XCircle size={14} color={FINCEPT.RED} />
+ <XCircle size={14} color={colors.alert} />
)}
- <span style={{ color: FINCEPT.GRAY }}>
+ <span style={{ color: colors.textMuted }}>
Qlib: {qlibStatus.available ? 'Installed' : 'Not Installed'}
</span>
</div>
<div className="flex items-center gap-2">
{rdAgentStatus.available ? (
- <CheckCircle size={14} color={FINCEPT.GREEN} />
+ <CheckCircle size={14} color={colors.success} />
) : (
- <XCircle size={14} color={FINCEPT.RED} />
+ <XCircle size={14} color={colors.alert} />
)}
- <span style={{ color: FINCEPT.GRAY }}>
+ <span style={{ color: colors.textMuted }}>
RD-Agent: {rdAgentStatus.available ? 'Installed' : 'Not Installed'}
</span>
</div>
</div>
- <div style={{ color: FINCEPT.GRAY }}>
+ <div style={{ color: colors.textMuted }}>
AI Quant Lab v{APP_VERSION} | Microsoft Qlib + RD-Agent Integration
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/constants.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/constants.ts
index 2007b395e..291f1da9a 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/constants.ts
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/constants.ts
@@ -16,41 +16,42 @@ import {
import type { AnalysisConfig } from './types';
// Fincept-style color palette - AMBER THEME for CFA Quant
+// Components should prefer useTerminalTheme() hook for runtime values
export const BB = {
// Core Fincept colors
- black: '#000000',
- darkBg: '#0F0F0F',
- panelBg: '#0F0F0F',
+ black: 'var(--ft-color-background, #000000)',
+ darkBg: 'var(--ft-color-background, #0F0F0F)',
+ panelBg: 'var(--ft-color-panel, #0F0F0F)',
cardBg: '#1F1F1F',
- borderDark: '#2A2A2A',
+ borderDark: 'var(--ft-border-color, #2A2A2A)',
borderLight: '#3a3a3a',
hover: '#1F1F1F',
// Accent colors - AMBER THEME
- amber: '#FF8800', // Primary theme color (matching FINCEPT.ORANGE)
- amberLight: '#FFA500',
+ amber: 'var(--ft-color-primary, #FF8800)', // Primary theme color (matching FINCEPT.ORANGE)
+ amberLight: 'var(--ft-color-primary, #FFA500)',
amberDim: '#CC7000',
// Status colors
- green: '#00D66F',
+ green: 'var(--ft-color-success, #00D66F)',
greenDim: '#00A040',
- red: '#FF3B3B',
+ red: 'var(--ft-color-alert, #FF3B3B)',
redDim: '#CC3000',
// Text colors
- textPrimary: '#FFFFFF',
+ textPrimary: 'var(--ft-color-text, #FFFFFF)',
textSecondary: '#B0B0B0',
- textMuted: '#787878',
- textAmber: '#FF8800',
+ textMuted: 'var(--ft-color-text-muted, #787878)',
+ textAmber: 'var(--ft-color-primary, #FF8800)',
// Chart colors
- chartLine: '#00D4FF',
+ chartLine: 'var(--ft-color-accent, #00D4FF)',
chartArea: 'rgba(0, 212, 255, 0.1)',
chartGrid: '#1f1f1f',
// Fincept blue
- blue: '#0088FF',
- blueLight: '#0088FF',
+ blue: 'var(--ft-color-info, #0088FF)',
+ blueLight: 'var(--ft-color-info, #0088FF)',
};
export const analysisConfigs: AnalysisConfig[] = [
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/constants.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/constants.ts
index 35aab8283..7b1d1f04c 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/constants.ts
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/constants.ts
@@ -108,33 +108,34 @@ export const CATEGORY_CONFIG: Record<string, CategoryConfig> = {
'analytics': { icon: React.createElement(BarChart2, { size: 14 }), color: '#06b6d4' },
};
-// Fincept color palette
+// Fincept color palette - use CSS variables for theme integration
+// Components should prefer useTerminalTheme() hook or CSS variables
export const FINCEPT_COLORS = {
- primary: '#FF8800',
- orange: '#FFA500',
- white: '#FFFFFF',
- gray: '#787878',
- darkBg: '#0a0a0a',
- panelBg: '#1a1a1a',
- border: '#2d2d2d',
- green: '#10b981',
- red: '#ef4444',
- blue: '#3b82f6',
- purple: '#8b5cf6',
- cyan: '#06b6d4',
- yellow: '#f59e0b',
+ primary: 'var(--ft-color-primary, #FF8800)',
+ orange: 'var(--ft-color-primary, #FFA500)',
+ white: 'var(--ft-color-text, #FFFFFF)',
+ gray: 'var(--ft-color-text-muted, #787878)',
+ darkBg: 'var(--ft-color-background, #0a0a0a)',
+ panelBg: 'var(--ft-color-panel, #1a1a1a)',
+ border: 'var(--ft-border-color, #2d2d2d)',
+ green: 'var(--ft-color-success, #10b981)',
+ red: 'var(--ft-color-alert, #ef4444)',
+ blue: 'var(--ft-color-info, #3b82f6)',
+ purple: 'var(--ft-color-purple, #8b5cf6)',
+ cyan: 'var(--ft-color-accent, #06b6d4)',
+ yellow: 'var(--ft-color-warning, #f59e0b)',
};
// Default edge options for ReactFlow
export const DEFAULT_EDGE_OPTIONS = {
animated: true,
- style: { stroke: '#ea580c', strokeWidth: 2 },
+ style: { stroke: 'var(--ft-color-primary, #ea580c)', strokeWidth: 2 },
};
// ReactFlow background settings
export const FLOW_BACKGROUND_CONFIG = {
- color: '#2d2d2d',
+ color: 'var(--ft-border-color, #2d2d2d)',
gap: 20,
size: 1,
- style: { backgroundColor: '#0a0a0a' },
+ style: { backgroundColor: 'var(--ft-color-background, #0a0a0a)' },
};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/constants.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/constants.ts
index 75198d045..b4f6377c9 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/constants.ts
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/constants.ts
@@ -5,22 +5,23 @@
*/
// Fincept Terminal Color Palette - GREEN THEME for FFN Analytics
+// Components should prefer useTerminalTheme() hook for runtime values
export const FINCEPT = {
- GREEN: '#00D66F', // Primary theme color for FFN Analytics
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- ORANGE: '#FF8800',
- DARK_BG: '#0F0F0F',
- PANEL_BG: '#0F0F0F',
- CYAN: '#00E5FF',
- BLUE: '#0088FF',
- BORDER: '#2A2A2A',
+ GREEN: 'var(--ft-color-success, #00D66F)', // Primary theme color for FFN Analytics
+ WHITE: 'var(--ft-color-text, #FFFFFF)',
+ RED: 'var(--ft-color-alert, #FF3B3B)',
+ ORANGE: 'var(--ft-color-primary, #FF8800)',
+ DARK_BG: 'var(--ft-color-background, #0F0F0F)',
+ PANEL_BG: 'var(--ft-color-panel, #0F0F0F)',
+ CYAN: 'var(--ft-color-accent, #00E5FF)',
+ BLUE: 'var(--ft-color-info, #0088FF)',
+ BORDER: 'var(--ft-border-color, #2A2A2A)',
HOVER: '#1F1F1F',
- GRAY: '#888888',
- MUTED: '#666666',
- PURPLE: '#BB86FC',
- YELLOW: '#FFD700',
- HEADER_BG: '#1A1A1A'
+ GRAY: 'var(--ft-color-text-muted, #888888)',
+ MUTED: 'var(--ft-color-text-muted, #666666)',
+ PURPLE: 'var(--ft-color-purple, #BB86FC)',
+ YELLOW: 'var(--ft-color-warning, #FFD700)',
+ HEADER_BG: 'var(--ft-color-panel, #1A1A1A)'
};
// Sample price data for demonstration (kept for backward compatibility)
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/constants.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/constants.ts
index ec09e55f8..d9b7516fc 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/constants.ts
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/constants.ts
@@ -4,22 +4,23 @@
*/
// Fincept Professional Color Palette
+// Components should prefer useTerminalTheme() hook for runtime values
export const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- BLUE: '#0088FF',
- PURPLE: '#9D4EDD',
- BORDER: '#2A2A2A',
+ ORANGE: 'var(--ft-color-primary, #FF8800)',
+ WHITE: 'var(--ft-color-text, #FFFFFF)',
+ RED: 'var(--ft-color-alert, #FF3B3B)',
+ GREEN: 'var(--ft-color-success, #00D66F)',
+ GRAY: 'var(--ft-color-text-muted, #787878)',
+ DARK_BG: 'var(--ft-color-background, #000000)',
+ PANEL_BG: 'var(--ft-color-panel, #0F0F0F)',
+ HEADER_BG: 'var(--ft-color-panel, #1A1A1A)',
+ CYAN: 'var(--ft-color-accent, #00E5FF)',
+ YELLOW: 'var(--ft-color-warning, #FFD700)',
+ BLUE: 'var(--ft-color-info, #0088FF)',
+ PURPLE: 'var(--ft-color-purple, #9D4EDD)',
+ BORDER: 'var(--ft-border-color, #2A2A2A)',
HOVER: '#1F1F1F',
- MUTED: '#4A4A4A'
+ MUTED: 'var(--ft-color-text-muted, #4A4A4A)'
};
// Pie chart colors for allocations
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/constants.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/constants.ts
index 552bfe940..187c207b6 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/constants.ts
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/constants.ts
@@ -4,22 +4,23 @@
*/
// Fincept Professional Color Palette
+// Components should prefer useTerminalTheme() hook for runtime values
export const FINCEPT = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- BLUE: '#0088FF',
- PURPLE: '#9D4EDD',
- BORDER: '#2A2A2A',
+ ORANGE: 'var(--ft-color-primary, #FF8800)',
+ WHITE: 'var(--ft-color-text, #FFFFFF)',
+ RED: 'var(--ft-color-alert, #FF3B3B)',
+ GREEN: 'var(--ft-color-success, #00D66F)',
+ GRAY: 'var(--ft-color-text-muted, #787878)',
+ DARK_BG: 'var(--ft-color-background, #000000)',
+ PANEL_BG: 'var(--ft-color-panel, #0F0F0F)',
+ HEADER_BG: 'var(--ft-color-panel, #1A1A1A)',
+ CYAN: 'var(--ft-color-accent, #00E5FF)',
+ YELLOW: 'var(--ft-color-warning, #FFD700)',
+ BLUE: 'var(--ft-color-info, #0088FF)',
+ PURPLE: 'var(--ft-color-purple, #9D4EDD)',
+ BORDER: 'var(--ft-border-color, #2A2A2A)',
HOVER: '#1F1F1F',
- MUTED: '#4A4A4A'
+ MUTED: 'var(--ft-color-text-muted, #4A4A4A)'
};
// Sample panel data for demonstration (kept for backward compatibility)
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/AlgoTradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/AlgoTradingTab.tsx
new file mode 100644
index 000000000..863ca5121
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/AlgoTradingTab.tsx
@@ -0,0 +1,157 @@
+import React, { useState } from 'react';
+import { Bot, Wrench, Search, BarChart3, Layout, Activity } from 'lucide-react';
+import type { AlgoSubView } from './types';
+import StrategyEditor from './components/StrategyEditor';
+import StrategyManager from './components/StrategyManager';
+import ScannerPanel from './components/ScannerPanel';
+import MonitorDashboard from './components/MonitorDashboard';
+
+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 SUB_VIEWS: { key: AlgoSubView; label: string; icon: React.ElementType }[] = [
+ { key: 'builder', label: 'BUILDER', icon: Wrench },
+ { key: 'strategies', label: 'STRATEGIES', icon: Layout },
+ { key: 'scanner', label: 'SCANNER', icon: Search },
+ { key: 'dashboard', label: 'DASHBOARD', icon: BarChart3 },
+];
+
+const AlgoTradingTab: React.FC = () => {
+ const [activeView, setActiveView] = useState<AlgoSubView>('builder');
+ const [editStrategyId, setEditStrategyId] = useState<string | null>(null);
+
+ const handleEditStrategy = (id: string) => {
+ setEditStrategyId(id);
+ setActiveView('builder');
+ };
+
+ const handleNewStrategy = () => {
+ setEditStrategyId(null);
+ setActiveView('builder');
+ };
+
+ 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 */}
+ <div style={{
+ backgroundColor: F.HEADER_BG,
+ borderBottom: `2px solid ${F.ORANGE}`,
+ padding: '8px 16px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ boxShadow: `0 2px 8px ${F.ORANGE}20`,
+ }}>
+ <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' }} />
+ </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>
+ ))}
+ </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}
+ />
+ )}
+ {activeView === 'scanner' && <ScannerPanel />}
+ {activeView === 'dashboard' && <MonitorDashboard />}
+ </div>
+
+ {/* Status Bar */}
+ <div style={{
+ backgroundColor: F.HEADER_BG,
+ borderTop: `1px solid ${F.BORDER}`,
+ padding: '4px 16px',
+ fontSize: '9px',
+ color: F.GRAY,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ }}>
+ <span>ALGO ENGINE v1.0</span>
+ <span style={{ color: F.MUTED }}>
+ VIEW: {activeView.toUpperCase()}
+ </span>
+ </div>
+ </div>
+ );
+};
+
+export default AlgoTradingTab;
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.tsx
new file mode 100644
index 000000000..62e2d1cec
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionBuilder.tsx
@@ -0,0 +1,153 @@
+import React from 'react';
+import { Plus } from 'lucide-react';
+import type { ConditionItem } from '../types';
+import ConditionRow from './ConditionRow';
+
+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',
+};
+
+interface ConditionBuilderProps {
+ label: string;
+ conditions: ConditionItem[];
+ logic: 'AND' | 'OR';
+ onConditionsChange: (conditions: ConditionItem[]) => void;
+ onLogicChange: (logic: 'AND' | 'OR') => void;
+}
+
+const DEFAULT_CONDITION: ConditionItem = {
+ indicator: 'RSI',
+ params: { period: 14 },
+ field: 'value',
+ operator: 'crosses_below',
+ value: 30,
+};
+
+const ConditionBuilder: React.FC<ConditionBuilderProps> = ({
+ label,
+ conditions,
+ logic,
+ onConditionsChange,
+ onLogicChange,
+}) => {
+ const handleAdd = () => {
+ onConditionsChange([...conditions, { ...DEFAULT_CONDITION }]);
+ };
+
+ const handleChange = (index: number, updated: ConditionItem) => {
+ const next = [...conditions];
+ next[index] = updated;
+ onConditionsChange(next);
+ };
+
+ const handleRemove = (index: number) => {
+ onConditionsChange(conditions.filter((_, i) => i !== index));
+ };
+
+ 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',
+ }}>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>
+ {label.toUpperCase()}
+ </span>
+ <div style={{ display: 'flex', gap: '2px' }}>
+ {(['AND', 'OR'] as const).map(l => (
+ <button
+ key={l}
+ onClick={() => onLogicChange(l)}
+ style={{
+ padding: '3px 8px',
+ backgroundColor: logic === l ? F.ORANGE : 'transparent',
+ color: logic === l ? F.DARK_BG : F.GRAY,
+ border: logic === l ? 'none' : `1px solid ${F.BORDER}`,
+ fontSize: '8px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ cursor: 'pointer',
+ borderRadius: '2px',
+ transition: 'all 0.2s',
+ }}
+ >
+ {l}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Condition rows */}
+ <div style={{ padding: '4px 0' }}>
+ {conditions.map((cond, i) => (
+ <div key={i}>
+ {i > 0 && (
+ <div style={{
+ fontSize: '8px',
+ fontWeight: 700,
+ color: F.ORANGE,
+ paddingLeft: '12px',
+ paddingTop: '2px',
+ paddingBottom: '2px',
+ letterSpacing: '0.5px',
+ }}>
+ {logic}
+ </div>
+ )}
+ <ConditionRow
+ condition={cond}
+ index={i}
+ onChange={handleChange}
+ onRemove={handleRemove}
+ />
+ </div>
+ ))}
+ </div>
+
+ {/* Add button */}
+ <div style={{ padding: '4px 8px 8px' }}>
+ <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>
+ </div>
+ </div>
+ );
+};
+
+export default ConditionBuilder;
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.tsx
new file mode 100644
index 000000000..223ead124
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionRow.tsx
@@ -0,0 +1,177 @@
+import React from 'react';
+import { X } from 'lucide-react';
+import type { ConditionItem } from '../types';
+import { INDICATOR_DEFINITIONS, OPERATORS, getIndicatorDef } from '../constants/indicators';
+
+const F = {
+ ORANGE: '#FF8800', WHITE: '#FFFFFF', GRAY: '#787878', DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F', BORDER: '#2A2A2A', HOVER: '#1F1F1F', MUTED: '#4A4A4A',
+ CYAN: '#00E5FF', RED: '#FF3B3B',
+};
+
+interface ConditionRowProps {
+ condition: ConditionItem;
+ index: number;
+ onChange: (index: number, updated: ConditionItem) => void;
+ onRemove: (index: number) => void;
+}
+
+const selectStyle: React.CSSProperties = {
+ backgroundColor: F.DARK_BG,
+ color: F.WHITE,
+ border: `1px solid ${F.BORDER}`,
+ borderRadius: '2px',
+ padding: '6px 8px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ outline: 'none',
+};
+
+const inputStyle: React.CSSProperties = {
+ ...selectStyle,
+ width: '60px',
+};
+
+const ConditionRow: React.FC<ConditionRowProps> = ({ condition, index, onChange, onRemove }) => {
+ const indicatorDef = getIndicatorDef(condition.indicator);
+ const fields = indicatorDef?.fields || ['value'];
+
+ const handleIndicatorChange = (name: string) => {
+ const def = getIndicatorDef(name);
+ 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,
+ });
+ };
+
+ const handleParamChange = (key: string, val: string) => {
+ const num = parseFloat(val);
+ if (!isNaN(num)) {
+ onChange(index, { ...condition, params: { ...condition.params, [key]: num } });
+ }
+ };
+
+ const categories = ['momentum', 'trend', 'volatility', 'volume', 'price'] as const;
+
+ return (
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ padding: '6px 8px',
+ flexWrap: 'wrap',
+ borderRadius: '2px',
+ transition: 'all 0.2s',
+ }}>
+ {/* Indicator selector */}
+ <select
+ value={condition.indicator}
+ onChange={e => handleIndicatorChange(e.target.value)}
+ style={{ ...selectStyle, width: '120px' }}
+ >
+ {categories.map(cat => (
+ <optgroup key={cat} label={cat.charAt(0).toUpperCase() + cat.slice(1)}>
+ {INDICATOR_DEFINITIONS.filter(d => d.category === cat).map(d => (
+ <option key={d.name} value={d.name}>{d.label}</option>
+ ))}
+ </optgroup>
+ ))}
+ </select>
+
+ {/* Params */}
+ {indicatorDef?.params.map(p => (
+ <div key={p.key} style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>
+ {p.label.toUpperCase()}:
+ </span>
+ <input
+ type="number"
+ value={condition.params[p.key] ?? p.default}
+ onChange={e => handleParamChange(p.key, e.target.value)}
+ min={p.min}
+ max={p.max}
+ style={inputStyle}
+ />
+ </div>
+ ))}
+
+ {/* Field selector */}
+ {fields.length > 1 && (
+ <select
+ value={condition.field}
+ onChange={e => onChange(index, { ...condition, field: e.target.value })}
+ style={{ ...selectStyle, width: '90px' }}
+ >
+ {fields.map(f => (
+ <option key={f} value={f}>{f}</option>
+ ))}
+ </select>
+ )}
+
+ {/* Operator */}
+ <select
+ value={condition.operator}
+ onChange={e => onChange(index, { ...condition, operator: e.target.value })}
+ style={{ ...selectStyle, width: '110px' }}
+ >
+ {OPERATORS.map(op => (
+ <option key={op.value} value={op.value}>{op.label}</option>
+ ))}
+ </select>
+
+ {/* 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 }}
+ />
+
+ {/* Value2 for between */}
+ {condition.operator === 'between' && (
+ <>
+ <span style={{ fontSize: '9px', color: F.GRAY }}>AND</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: '72px', color: F.CYAN }}
+ />
+ </>
+ )}
+
+ {/* Remove */}
+ <button
+ onClick={() => onRemove(index)}
+ style={{
+ padding: '4px',
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: F.MUTED,
+ cursor: 'pointer',
+ borderRadius: '2px',
+ transition: 'all 0.2s',
+ }}
+ onMouseEnter={e => { (e.currentTarget as HTMLElement).style.color = F.RED; }}
+ onMouseLeave={e => { (e.currentTarget as HTMLElement).style.color = F.MUTED; }}
+ >
+ <X size={12} />
+ </button>
+ </div>
+ );
+};
+
+export default ConditionRow;
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.tsx
new file mode 100644
index 000000000..096c141dd
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeployPanel.tsx
@@ -0,0 +1,141 @@
+import React, { useState } from 'react';
+import { Rocket, X, Link, AlertTriangle } from 'lucide-react';
+import { TIMEFRAMES } from '../constants/indicators';
+import { deployAlgoStrategy, startOrderSignalBridge } from '../services/algoTradingService';
+import { useBrokerContext } from '@/contexts/BrokerContext';
+
+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',
+};
+
+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',
+};
+
+const labelStyle: React.CSSProperties = {
+ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px',
+ marginBottom: '4px', display: 'block',
+};
+
+interface DeployPanelProps {
+ strategyId: string;
+ strategyName: string;
+ onClose: () => void;
+}
+
+const DeployPanel: React.FC<DeployPanelProps> = ({ strategyId, strategyName, onClose }) => {
+ const { activeBroker, activeBrokerMetadata, realAdapter, tradingMode } = useBrokerContext();
+ const [symbol, setSymbol] = useState('');
+ const [mode, setMode] = useState<'paper' | 'live'>('paper');
+ 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 brokerConnected = !!realAdapter;
+ const brokerName = activeBrokerMetadata?.displayName || activeBroker;
+
+ const handleDeploy = async () => {
+ if (!symbol.trim()) return;
+ if (mode === 'live' && !brokerConnected) {
+ setResult({ success: false, message: `No broker connected. Connect ${brokerName} first.` });
+ return;
+ }
+ setDeploying(true); setResult(null);
+ const res = await deployAlgoStrategy({
+ strategyId, symbol: symbol.trim().toUpperCase(), provider: activeBroker,
+ mode, timeframe, quantity: parseFloat(quantity) || 1,
+ });
+ setDeploying(false);
+ if (res.success) {
+ setResult({ success: true, message: `Deployed! ID: ${res.data?.deploy_id}` });
+ if (mode === 'live') startOrderSignalBridge().catch(() => {});
+ } else {
+ setResult({ success: false, message: res.error || 'Deploy failed' });
+ }
+ };
+
+ return (
+ <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 */}
+ <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,
+ }}>
+ <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} />
+ </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
+ </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()}
+ </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>
+ </div>
+ );
+};
+
+export default DeployPanel;
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.tsx
new file mode 100644
index 000000000..fc3431899
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeploymentCard.tsx
@@ -0,0 +1,151 @@
+import React, { useState } from 'react';
+import { Square, ChevronDown, ChevronUp, TrendingUp, TrendingDown } from 'lucide-react';
+import type { AlgoDeployment } from '../types';
+import { stopAlgoDeployment } 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',
+};
+
+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` };
+ }
+};
+
+interface DeploymentCardProps {
+ deployment: AlgoDeployment;
+ onStopped: () => void;
+}
+
+const DeploymentCard: React.FC<DeploymentCardProps> = ({ deployment, onStopped }) => {
+ const [showTrades, setShowTrades] = useState(false);
+ const [stopping, setStopping] = useState(false);
+
+ const handleStop = async () => {
+ setStopping(true);
+ await stopAlgoDeployment(deployment.id);
+ setStopping(false);
+ onStopped();
+ };
+
+ const m = deployment.metrics;
+ const totalPnl = m.total_pnl + m.unrealized_pnl;
+ const isPositive = totalPnl >= 0;
+
+ 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`,
+ overflow: 'hidden',
+ }}>
+ {/* Main row */}
+ <div style={{
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 12px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flex: 1, minWidth: 0 }}>
+ <div style={statusStyle(deployment.status)}>
+ {deployment.status.toUpperCase()}
+ </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}
+ </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)}
+ </span>
+ )}
+ </div>
+ </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>
+ </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>
+ <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>
+ <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>
+ </div>
+
+ {/* Actions */}
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {deployment.status === 'running' && (
+ <button
+ onClick={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',
+ }}
+ >
+ <Square size={10} />
+ {stopping ? '...' : 'STOP'}
+ </button>
+ )}
+ <button
+ onClick={() => setShowTrades(!showTrades)}
+ style={{
+ padding: '4px 6px', backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,
+ color: F.GRAY, borderRadius: '2px', cursor: 'pointer', transition: 'all 0.2s',
+ }}
+ >
+ {showTrades ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
+ </button>
+ </div>
+ </div>
+
+ {/* Trade history */}
+ {showTrades && (
+ <div style={{ borderTop: `1px solid ${F.BORDER}` }}>
+ <TradeHistoryTable deploymentId={deployment.id} />
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default DeploymentCard;
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.tsx
new file mode 100644
index 000000000..7eaf87431
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/MonitorDashboard.tsx
@@ -0,0 +1,201 @@
+import React, { useState, useEffect, useCallback } from 'react';
+import { RefreshCw, StopCircle } from 'lucide-react';
+import { listen } from '@tauri-apps/api/event';
+import type { AlgoDeployment } from '../types';
+import { listAlgoDeployments, stopAllAlgoDeployments } from '../services/algoTradingService';
+import DeploymentCard from './DeploymentCard';
+
+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',
+};
+
+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 loadDeployments = useCallback(async () => {
+ const result = await listAlgoDeployments();
+ if (result.success && result.data) {
+ setDeployments(result.data);
+ }
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ loadDeployments();
+ const interval = setInterval(loadDeployments, 5000);
+ return () => clearInterval(interval);
+ }, [loadDeployments]);
+
+ // Listen for Tauri events from the backend
+ useEffect(() => {
+ const addEvent = (type: string, message: string) => {
+ setRecentEvents(prev => [{ type, message, ts: Date.now() }, ...prev].slice(0, 20));
+ };
+
+ const unlisteners: (() => void)[] = [];
+
+ listen<{ symbol: string; timeframe: string }>('algo_candle_closed', (event) => {
+ addEvent('candle', `${event.payload.symbol} [${event.payload.timeframe}] candle closed`);
+ }).then(fn => unlisteners.push(fn));
+
+ listen<{ signal_id: string; symbol: string; side: string; quantity: number; order_type: string }>(
+ 'algo_signal',
+ (event) => {
+ const p = event.payload;
+ addEvent('signal', `Signal: ${p.side.toUpperCase()} ${p.quantity} ${p.symbol} (${p.order_type})`);
+ }
+ ).then(fn => unlisteners.push(fn));
+
+ listen<{ signal_id: string; symbol: string; side: string; success: boolean; message: string }>(
+ 'algo_trade_executed',
+ (event) => {
+ const p = event.payload;
+ addEvent(
+ p.success ? 'trade' : 'error',
+ `${p.side.toUpperCase()} ${p.symbol}: ${p.success ? 'filled' : 'failed'} — ${p.message}`
+ );
+ loadDeployments();
+ }
+ ).then(fn => unlisteners.push(fn));
+
+ return () => {
+ unlisteners.forEach(fn => fn());
+ };
+ }, [loadDeployments]);
+
+ const handleStopAll = async () => {
+ await stopAllAlgoDeployments();
+ loadDeployments();
+ };
+
+ 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 eventColor = (type: string): string => {
+ if (type === 'trade') return F.GREEN;
+ if (type === 'error') return F.RED;
+ if (type === 'signal') return F.YELLOW;
+ return F.GRAY;
+ };
+
+ 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>
+ </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>
+ )}
+ </div>
+ </div>
+
+ {loading ? (
+ <div style={{ textAlign: 'center', padding: '32px', fontSize: '10px', color: F.MUTED }}>
+ Loading deployments...
+ </div>
+ ) : deployments.length === 0 ? (
+ <div style={{
+ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
+ height: '200px', color: F.MUTED, fontSize: '10px', textAlign: 'center',
+ }}>
+ <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
+ </div>
+ )}
+ {stopped.map(d => (
+ <DeploymentCard key={d.id} deployment={d} onStopped={loadDeployments} />
+ ))}
+ </div>
+ )}
+
+ {/* Recent Events */}
+ {recentEvents.length > 0 && (
+ <div style={{
+ backgroundColor: F.PANEL_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px',
+ }}>
+ <div style={{
+ padding: '6px 12px', backgroundColor: F.HEADER_BG,
+ borderBottom: `1px solid ${F.BORDER}`,
+ }}>
+ <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',
+ }}>
+ <span style={{ color: F.MUTED }}>{new Date(evt.ts).toLocaleTimeString()}</span>
+ <span style={{ color: eventColor(evt.type) }}>{evt.message}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default MonitorDashboard;
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx
new file mode 100644
index 000000000..827491418
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx
@@ -0,0 +1,148 @@
+import React, { useState } from 'react';
+import { Search, Loader } from 'lucide-react';
+import type { ConditionItem, ScanResult } from '../types';
+import { TIMEFRAMES } from '../constants/indicators';
+import { runAlgoScan } from '../services/algoTradingService';
+import { useStockBrokerContextOptional } from '@/contexts/StockBrokerContext';
+import { useBrokerContext } from '@/contexts/BrokerContext';
+import ConditionBuilder from './ConditionBuilder';
+
+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',
+};
+
+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',
+};
+
+const labelStyle: React.CSSProperties = {
+ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px',
+ marginBottom: '4px', display: 'block',
+};
+
+const ScannerPanel: React.FC = () => {
+ const stockBroker = useStockBrokerContextOptional();
+ const { activeBroker } = useBrokerContext();
+ // Prefer stock broker (fyers, zerodha) over crypto broker
+ const provider = stockBroker?.activeBroker || activeBroker || 'fyers';
+
+ const [conditions, setConditions] = useState<ConditionItem[]>([
+ { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '<', value: 30 },
+ ]);
+ const [logic, setLogic] = useState<'AND' | 'OR'>('AND');
+ const [symbolsInput, setSymbolsInput] = useState('');
+ const [timeframe, setTimeframe] = useState('1d');
+ const [scanning, setScanning] = useState(false);
+ const [results, setResults] = useState<ScanResult[] | null>(null);
+ const [scanned, setScanned] = useState(0);
+ const [error, setError] = useState('');
+
+ const buildConditionsJson = (): string => {
+ if (conditions.length === 0) return '[]';
+ const mixed: (ConditionItem | string)[] = [];
+ conditions.forEach((c, i) => { if (i > 0) mixed.push(logic); mixed.push(c); });
+ return JSON.stringify(mixed);
+ };
+
+ const handleScan = async () => {
+ const symbols = symbolsInput.split(/[,\n]/).map(s => s.trim().toUpperCase()).filter(Boolean);
+ if (symbols.length === 0) { setError('Enter at least one symbol'); return; }
+ if (conditions.length === 0) { setError('Add at least one condition'); return; }
+ setScanning(true); setError(''); setResults(null);
+ const result = await runAlgoScan(buildConditionsJson(), JSON.stringify(symbols), timeframe, provider);
+ setScanning(false);
+ if (result.success && result.data) { setResults(result.data.matches); setScanned(result.data.scanned); }
+ else setError(result.error || 'Scan failed');
+ };
+
+ return (
+ <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>SCANNER</span>
+
+ <ConditionBuilder label="Scan Conditions" conditions={conditions} logic={logic}
+ onConditionsChange={setConditions} onLogicChange={setLogic} />
+
+ {/* Symbol Universe + Timeframe */}
+ <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '12px' }}>
+ <div>
+ <label style={labelStyle}>SYMBOLS (COMMA OR NEWLINE SEPARATED)</label>
+ <textarea
+ value={symbolsInput}
+ onChange={e => setSymbolsInput(e.target.value)}
+ placeholder="RELIANCE, TCS, INFY, HDFCBANK, ICICIBANK"
+ rows={3}
+ style={{ ...inputStyle, resize: 'none' } as React.CSSProperties}
+ />
+ </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>
+ <button onClick={handleScan} disabled={scanning} style={{
+ width: '100%', marginTop: '8px', padding: '8px 16px',
+ backgroundColor: F.ORANGE, color: F.DARK_BG, border: 'none', borderRadius: '2px',
+ fontSize: '9px', fontWeight: 700, cursor: 'pointer', opacity: scanning ? 0.5 : 1,
+ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px',
+ }}>
+ {scanning ? <Loader size={10} className="animate-spin" /> : <Search size={10} />}
+ {scanning ? 'SCANNING...' : 'RUN SCAN'}
+ </button>
+ </div>
+ </div>
+
+ {error && (
+ <div style={{ padding: '6px 10px', backgroundColor: `${F.RED}20`, color: F.RED, fontSize: '9px', fontWeight: 700, borderRadius: '2px' }}>{error}</div>
+ )}
+
+ {/* Results */}
+ {results !== null && (
+ <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' }}>
+ RESULTS: <span style={{ color: F.CYAN }}>{results.length}</span> MATCH{results.length !== 1 ? 'ES' : ''} / {scanned} SCANNED
+ </span>
+ </div>
+ {results.length === 0 ? (
+ <div style={{ padding: '24px', textAlign: 'center', fontSize: '10px', color: F.MUTED }}>
+ No symbols match the conditions
+ </div>
+ ) : (
+ <div style={{ overflow: 'auto' }}>
+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}>
+ <thead>
+ <tr style={{ borderBottom: `1px solid ${F.BORDER}` }}>
+ <th style={{ padding: '6px 12px', textAlign: 'left', fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>SYMBOL</th>
+ <th style={{ padding: '6px 12px', textAlign: 'right', fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>PRICE</th>
+ <th style={{ padding: '6px 12px', textAlign: 'left', fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>INDICATORS</th>
+ </tr>
+ </thead>
+ <tbody>
+ {results.map((r, i) => (
+ <tr key={i} style={{ borderBottom: `1px solid ${F.BORDER}15` }}>
+ <td style={{ padding: '6px 12px', fontWeight: 700, color: F.WHITE }}>{r.symbol}</td>
+ <td style={{ padding: '6px 12px', textAlign: 'right', color: F.CYAN }}>{r.price.toFixed(2)}</td>
+ <td style={{ padding: '6px 12px' }}>
+ {r.details.map((d, j) => (
+ <span key={j} style={{ marginRight: '8px', color: d.met ? F.GREEN : F.RED, fontSize: '9px' }}>
+ {d.indicator}({d.field})={d.computed_value?.toFixed(2)}
+ </span>
+ ))}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default ScannerPanel;
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.tsx
new file mode 100644
index 000000000..e033e6969
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyEditor.tsx
@@ -0,0 +1,310 @@
+import React, { useState, useEffect } from 'react';
+import { Save, Play, Loader, ArrowLeft } from 'lucide-react';
+import type { ConditionItem } from '../types';
+import { TIMEFRAMES } from '../constants/indicators';
+import { saveAlgoStrategy, getAlgoStrategy, runAlgoBacktest } from '../services/algoTradingService';
+import ConditionBuilder from './ConditionBuilder';
+
+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', PURPLE: '#9D4EDD',
+};
+
+interface StrategyEditorProps {
+ editStrategyId: string | null;
+ onSaved: () => void;
+ onCancel: () => void;
+}
+
+interface BacktestMetrics {
+ total_trades: number; winning_trades: number; losing_trades: number;
+ win_rate: number; total_return: number; total_return_pct: number;
+ max_drawdown: number; avg_pnl: number; avg_bars_held: number;
+ profit_factor: number; sharpe: number;
+}
+
+interface BacktestResult {
+ trades: Array<{ entry_price: number; exit_price: number; pnl: number; pnl_pct: number; reason: string; bars_held: number }>;
+ metrics: BacktestMetrics;
+}
+
+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',
+};
+
+const labelStyle: React.CSSProperties = {
+ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px',
+ marginBottom: '4px', display: 'block',
+};
+
+const StrategyEditor: React.FC<StrategyEditorProps> = ({ editStrategyId, onSaved, onCancel }) => {
+ const [name, setName] = useState('');
+ const [description, setDescription] = useState('');
+ const [timeframe, setTimeframe] = useState('5m');
+ const [entryConditions, setEntryConditions] = useState<ConditionItem[]>([
+ { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: 'crosses_below', value: 30 },
+ ]);
+ const [exitConditions, setExitConditions] = useState<ConditionItem[]>([
+ { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: 'crosses_above', value: 70 },
+ ]);
+ const [entryLogic, setEntryLogic] = useState<'AND' | 'OR'>('AND');
+ const [exitLogic, setExitLogic] = useState<'AND' | 'OR'>('AND');
+ const [stopLoss, setStopLoss] = useState<string>('');
+ const [takeProfit, setTakeProfit] = useState<string>('');
+ const [trailingStop, setTrailingStop] = useState<string>('');
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState('');
+ const [btSymbol, setBtSymbol] = useState('');
+ const [btPeriod, setBtPeriod] = useState('1y');
+ const [backtesting, setBacktesting] = useState(false);
+ const [btResult, setBtResult] = useState<BacktestResult | null>(null);
+ const [btError, setBtError] = useState('');
+
+ useEffect(() => {
+ if (editStrategyId) loadStrategy(editStrategyId);
+ }, [editStrategyId]);
+
+ const loadStrategy = async (id: string) => {
+ const result = await getAlgoStrategy(id);
+ if (result.success && result.data) {
+ const s = result.data;
+ setName(s.name); setDescription(s.description); setTimeframe(s.timeframe);
+ setEntryLogic(s.entry_logic); setExitLogic(s.exit_logic);
+ setStopLoss(s.stop_loss != null ? String(s.stop_loss) : '');
+ setTakeProfit(s.take_profit != null ? String(s.take_profit) : '');
+ setTrailingStop(s.trailing_stop != null ? String(s.trailing_stop) : '');
+ try {
+ setEntryConditions(JSON.parse(s.entry_conditions).filter((c: unknown) => typeof c === 'object'));
+ setExitConditions(JSON.parse(s.exit_conditions).filter((c: unknown) => typeof c === 'object'));
+ } catch { /* keep defaults */ }
+ }
+ };
+
+ const buildConditionsJson = (conditions: ConditionItem[], logic: string): string => {
+ if (conditions.length === 0) return '[]';
+ const mixed: (ConditionItem | string)[] = [];
+ conditions.forEach((c, i) => { if (i > 0) mixed.push(logic); mixed.push(c); });
+ return JSON.stringify(mixed);
+ };
+
+ const handleSave = async () => {
+ if (!name.trim()) { setError('Strategy name is required'); return; }
+ if (entryConditions.length === 0) { setError('At least one entry condition is required'); return; }
+ setSaving(true); setError('');
+ const id = editStrategyId || `algo-${Date.now()}`;
+ const result = await saveAlgoStrategy({
+ id, name: name.trim(), description: description.trim(),
+ entry_conditions: buildConditionsJson(entryConditions, entryLogic),
+ exit_conditions: buildConditionsJson(exitConditions, exitLogic),
+ entry_logic: entryLogic, exit_logic: exitLogic,
+ stop_loss: stopLoss ? parseFloat(stopLoss) : null,
+ take_profit: takeProfit ? parseFloat(takeProfit) : null,
+ trailing_stop: trailingStop ? parseFloat(trailingStop) : null,
+ timeframe,
+ });
+ setSaving(false);
+ if (result.success) onSaved();
+ else setError(result.error || 'Failed to save');
+ };
+
+ const handleBacktest = async () => {
+ if (!btSymbol.trim()) { setBtError('Enter a symbol (e.g. RELIANCE.NS, AAPL)'); return; }
+ if (entryConditions.length === 0) { setBtError('Add at least one entry condition'); return; }
+ setBacktesting(true); setBtError(''); setBtResult(null);
+ const res = await runAlgoBacktest({
+ symbol: btSymbol.trim(),
+ entryConditions: buildConditionsJson(entryConditions, entryLogic),
+ exitConditions: buildConditionsJson(exitConditions, exitLogic),
+ timeframe: ['1m','3m','5m'].includes(timeframe) ? '1d' : timeframe,
+ period: btPeriod,
+ stopLoss: stopLoss ? parseFloat(stopLoss) : undefined,
+ takeProfit: takeProfit ? parseFloat(takeProfit) : undefined,
+ });
+ setBacktesting(false);
+ if (res.success && res.data) setBtResult(res.data);
+ else setBtError(res.error || 'Backtest failed');
+ };
+
+ 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' }}>
+ <button
+ onClick={onCancel}
+ style={{ padding: '6px', backgroundColor: 'transparent', border: 'none', color: F.GRAY, cursor: 'pointer', borderRadius: '2px' }}
+ >
+ <ArrowLeft size={14} />
+ </button>
+ <span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE }}>
+ {editStrategyId ? 'EDIT STRATEGY' : 'CREATE STRATEGY'}
+ </span>
+ </div>
+ <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',
+ }}>
+ <Save size={10} />
+ {saving ? 'SAVING...' : 'SAVE STRATEGY'}
+ </button>
+ </div>
+ </div>
+
+ {error && (
+ <div style={{ padding: '6px 10px', backgroundColor: `${F.RED}20`, color: F.RED, fontSize: '9px', fontWeight: 700, borderRadius: '2px' }}>
+ {error}
+ </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} />
+ <ConditionBuilder label="Exit Conditions (SELL when)" conditions={exitConditions} logic={exitLogic}
+ onConditionsChange={setExitConditions} onLogicChange={setExitLogic} />
+
+ {/* 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>
+ </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" style={inputStyle} />
+ </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" style={inputStyle} />
+ </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" style={inputStyle} />
+ </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', gap: '12px' }}>
+ <div>
+ <label style={labelStyle}>SYMBOL (YFINANCE)</label>
+ <input value={btSymbol} onChange={e => setBtSymbol(e.target.value)} placeholder="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',
+ }}>
+ {backtesting ? <Loader size={10} className="animate-spin" /> : <Play size={10} />}
+ {backtesting ? 'RUNNING...' : 'RUN BACKTEST'}
+ </button>
+ </div>
+ </div>
+
+ {btError && (
+ <div style={{ margin: '0 12px 12px', padding: '6px 10px', backgroundColor: `${F.RED}20`, color: F.RED, fontSize: '9px', borderRadius: '2px' }}>
+ {btError}
+ </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>
+ </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>
+ ))}
+ </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>
+ );
+};
+
+export default StrategyEditor;
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyManager.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyManager.tsx
new file mode 100644
index 000000000..2649cb00b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyManager.tsx
@@ -0,0 +1,159 @@
+import React, { useState, useEffect } from 'react';
+import { Plus, Edit, Trash2, Rocket, RefreshCw } from 'lucide-react';
+import type { AlgoStrategy } from '../types';
+import { listAlgoStrategies, deleteAlgoStrategy } from '../services/algoTradingService';
+import DeployPanel from './DeployPanel';
+
+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',
+};
+
+interface StrategyManagerProps {
+ onEdit: (id: string) => void;
+ onNew: () => void;
+}
+
+const StrategyManager: React.FC<StrategyManagerProps> = ({ onEdit, onNew }) => {
+ const [strategies, setStrategies] = useState<AlgoStrategy[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [deployStrategyId, setDeployStrategyId] = useState<string | null>(null);
+ const [hoveredId, setHoveredId] = useState<string | null>(null);
+
+ const loadStrategies = async () => {
+ setLoading(true);
+ const result = await listAlgoStrategies();
+ if (result.success && result.data) setStrategies(result.data);
+ setLoading(false);
+ };
+
+ useEffect(() => { loadStrategies(); }, []);
+
+ const handleDelete = async (id: string) => {
+ const result = await deleteAlgoStrategy(id);
+ if (result.success) setStrategies(prev => prev.filter(s => s.id !== id));
+ };
+
+ const parseConditionCount = (json: string): number => {
+ try { return JSON.parse(json).filter((c: unknown) => typeof c === 'object').length; }
+ catch { return 0; }
+ };
+
+ return (
+ <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ {/* Section Header */}
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
+ <span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>SAVED STRATEGIES</span>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button onClick={loadStrategies} 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>
+ <button onClick={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',
+ }}>
+ <Plus size={10} />
+ NEW STRATEGY
+ </button>
+ </div>
+ </div>
+
+ {/* Deploy Panel */}
+ {deployStrategyId && (
+ <DeployPanel
+ strategyId={deployStrategyId}
+ strategyName={strategies.find(s => s.id === deployStrategyId)?.name || ''}
+ onClose={() => setDeployStrategyId(null)}
+ />
+ )}
+
+ {/* List */}
+ {loading ? (
+ <div style={{ textAlign: 'center', padding: '32px', fontSize: '10px', color: F.MUTED }}>Loading strategies...</div>
+ ) : strategies.length === 0 ? (
+ <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>No strategies yet</span>
+ <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',
+ }}>CREATE YOUR FIRST STRATEGY</button>
+ </div>
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ {strategies.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={{ fontSize: '10px', fontWeight: 700, color: F.WHITE, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ {strategy.name}
+ </div>
+ {strategy.description && (
+ <div style={{ fontSize: '9px', color: F.MUTED, marginTop: '2px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ {strategy.description}
+ </div>
+ )}
+ <div style={{ display: 'flex', gap: '12px', marginTop: '4px', fontSize: '9px', color: F.GRAY }}>
+ <span>TF: <span style={{ color: F.CYAN }}>{strategy.timeframe}</span></span>
+ <span>ENTRY: <span style={{ color: F.CYAN }}>{parseConditionCount(strategy.entry_conditions)}</span></span>
+ <span>EXIT: <span style={{ color: F.CYAN }}>{parseConditionCount(strategy.exit_conditions)}</span></span>
+ {strategy.stop_loss != null && <span>SL: <span style={{ color: F.RED }}>{strategy.stop_loss}%</span></span>}
+ {strategy.take_profit != null && <span>TP: <span style={{ color: F.GREEN }}>{strategy.take_profit}%</span></span>}
+ </div>
+ </div>
+ <div style={{ display: 'flex', gap: '4px', marginLeft: '12px' }}>
+ <button onClick={() => setDeployStrategyId(strategy.id)} 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={() => onEdit(strategy.id)} 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.id)} 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>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default StrategyManager;
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/TradeHistoryTable.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/TradeHistoryTable.tsx
new file mode 100644
index 000000000..b096d1170
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/TradeHistoryTable.tsx
@@ -0,0 +1,107 @@
+import React, { useState, useEffect } from 'react';
+import type { AlgoTrade } from '../types';
+import { getAlgoTrades } 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', MUTED: '#4A4A4A', CYAN: '#00E5FF',
+};
+
+const thStyle: React.CSSProperties = {
+ padding: '6px 12px', fontSize: '8px', fontWeight: 700, color: F.GRAY,
+ letterSpacing: '0.5px',
+};
+
+const tdStyle: React.CSSProperties = {
+ padding: '5px 12px', fontSize: '9px',
+ fontFamily: '"IBM Plex Mono", monospace',
+};
+
+interface TradeHistoryTableProps {
+ deploymentId: string;
+}
+
+const TradeHistoryTable: React.FC<TradeHistoryTableProps> = ({ deploymentId }) => {
+ const [trades, setTrades] = useState<AlgoTrade[]>([]);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ const load = async () => {
+ const result = await getAlgoTrades(deploymentId, 50);
+ if (result.success && result.data) {
+ setTrades(result.data);
+ }
+ setLoading(false);
+ };
+ load();
+ }, [deploymentId]);
+
+ if (loading) {
+ return (
+ <div style={{ padding: '12px', fontSize: '9px', color: F.MUTED }}>
+ Loading trades...
+ </div>
+ );
+ }
+
+ if (trades.length === 0) {
+ return (
+ <div style={{ padding: '12px', fontSize: '9px', color: F.MUTED }}>
+ No trades yet
+ </div>
+ );
+ }
+
+ return (
+ <div style={{ overflow: 'auto' }}>
+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}>
+ <thead>
+ <tr style={{ borderBottom: `1px solid ${F.BORDER}` }}>
+ <th style={{ ...thStyle, textAlign: 'left' }}>TIME</th>
+ <th style={{ ...thStyle, textAlign: 'left' }}>SIDE</th>
+ <th style={{ ...thStyle, textAlign: 'right' }}>QTY</th>
+ <th style={{ ...thStyle, textAlign: 'right' }}>PRICE</th>
+ <th style={{ ...thStyle, textAlign: 'right' }}>P&L</th>
+ <th style={{ ...thStyle, textAlign: 'left' }}>REASON</th>
+ </tr>
+ </thead>
+ <tbody>
+ {trades.map(trade => (
+ <tr key={trade.id} style={{ borderBottom: `1px solid ${F.BORDER}15` }}>
+ <td style={{ ...tdStyle, textAlign: 'left', color: F.MUTED }}>
+ {new Date(trade.timestamp).toLocaleString()}
+ </td>
+ <td style={{
+ ...tdStyle, textAlign: 'left', fontWeight: 700,
+ color: trade.side === 'BUY' ? F.GREEN : F.RED,
+ }}>
+ {trade.side}
+ </td>
+ <td style={{ ...tdStyle, textAlign: 'right', color: F.WHITE }}>
+ {trade.quantity}
+ </td>
+ <td style={{ ...tdStyle, textAlign: 'right', color: F.CYAN }}>
+ {trade.price.toFixed(2)}
+ </td>
+ <td style={{
+ ...tdStyle, textAlign: 'right', fontWeight: 700,
+ color: trade.pnl >= 0 ? F.GREEN : F.RED,
+ }}>
+ {trade.pnl >= 0 ? '+' : ''}{trade.pnl.toFixed(2)}
+ </td>
+ <td style={{
+ ...tdStyle, textAlign: 'left', color: F.MUTED,
+ maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
+ }}>
+ {trade.signal_reason}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+};
+
+export default TradeHistoryTable;
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.ts
new file mode 100644
index 000000000..6500de051
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/indicators.ts
@@ -0,0 +1,205 @@
+import { IndicatorDefinition } from '../types';
+
+export const OPERATORS = [
+ { value: '>', label: '>' },
+ { value: '<', label: '<' },
+ { value: '>=', label: '>=' },
+ { value: '<=', label: '<=' },
+ { value: '==', label: '==' },
+ { value: 'crosses_above', label: 'Crosses Above' },
+ { value: 'crosses_below', label: 'Crosses Below' },
+ { value: 'between', label: 'Between' },
+];
+
+export const TIMEFRAMES = [
+ { value: '1m', label: '1 Min' },
+ { value: '3m', label: '3 Min' },
+ { value: '5m', label: '5 Min' },
+ { value: '10m', label: '10 Min' },
+ { value: '15m', label: '15 Min' },
+ { value: '30m', label: '30 Min' },
+ { value: '1h', label: '1 Hour' },
+ { value: '4h', label: '4 Hour' },
+ { value: '1d', label: '1 Day' },
+];
+
+export const INDICATOR_DEFINITIONS: IndicatorDefinition[] = [
+ // Momentum
+ {
+ name: 'RSI',
+ label: 'RSI',
+ category: 'momentum',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 14, min: 2, max: 100 }],
+ },
+ {
+ name: 'STOCHASTIC',
+ label: 'Stochastic',
+ category: 'momentum',
+ fields: ['k', 'd'],
+ defaultField: 'k',
+ params: [
+ { key: 'period', label: 'Period', default: 14, min: 2, max: 100 },
+ { key: 'smooth', label: 'Smooth', default: 3, min: 1, max: 20 },
+ ],
+ },
+ {
+ name: 'WILLIAMS_R',
+ label: "Williams %R",
+ category: 'momentum',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 14, min: 2, max: 100 }],
+ },
+ {
+ name: 'ROC',
+ label: 'ROC / Momentum',
+ category: 'momentum',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 12, min: 1, max: 100 }],
+ },
+
+ // Trend
+ {
+ name: 'MACD',
+ label: 'MACD',
+ category: 'trend',
+ fields: ['line', 'signal_line', 'histogram'],
+ defaultField: 'histogram',
+ params: [
+ { key: 'fast', label: 'Fast', default: 12, min: 2, max: 50 },
+ { key: 'slow', label: 'Slow', default: 26, min: 5, max: 100 },
+ { key: 'signal', label: 'Signal', default: 9, min: 2, max: 50 },
+ ],
+ },
+ {
+ name: 'SMA',
+ label: 'SMA',
+ category: 'trend',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 500 }],
+ },
+ {
+ name: 'EMA',
+ label: 'EMA',
+ category: 'trend',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 12, min: 2, max: 500 }],
+ },
+ {
+ name: 'ADX',
+ label: 'ADX',
+ category: 'trend',
+ fields: ['value', 'plus_di', 'minus_di'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 14, min: 2, max: 100 }],
+ },
+ {
+ name: 'CCI',
+ label: 'CCI',
+ category: 'trend',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 100 }],
+ },
+ {
+ name: 'SUPERTREND',
+ label: 'Supertrend',
+ category: 'trend',
+ fields: ['value', 'direction'],
+ defaultField: 'direction',
+ params: [
+ { key: 'period', label: 'Period', default: 10, min: 2, max: 100 },
+ { key: 'multiplier', label: 'Multiplier', default: 3, min: 1, max: 10 },
+ ],
+ },
+
+ // Volatility
+ {
+ name: 'BOLLINGER',
+ label: 'Bollinger Bands',
+ category: 'volatility',
+ fields: ['upper', 'middle', 'lower', 'pct_b'],
+ defaultField: 'pct_b',
+ params: [
+ { key: 'period', label: 'Period', default: 20, min: 2, max: 100 },
+ { key: 'std_dev', label: 'Std Dev', default: 2, min: 1, max: 5 },
+ ],
+ },
+ {
+ name: 'ATR',
+ label: 'ATR',
+ category: 'volatility',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 14, min: 2, max: 100 }],
+ },
+ {
+ name: 'KELTNER',
+ label: 'Keltner Channel',
+ category: 'volatility',
+ fields: ['upper', 'middle', 'lower'],
+ defaultField: 'middle',
+ params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 100 }],
+ },
+ {
+ name: 'DONCHIAN',
+ label: 'Donchian Channel',
+ category: 'volatility',
+ fields: ['upper', 'middle', 'lower'],
+ defaultField: 'middle',
+ params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 100 }],
+ },
+
+ // Volume
+ {
+ name: 'OBV',
+ label: 'OBV',
+ category: 'volume',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'VWAP',
+ label: 'VWAP',
+ category: 'volume',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+
+ // Price
+ {
+ name: 'PRICE',
+ label: 'Price',
+ category: 'price',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'VOLUME',
+ label: 'Volume',
+ category: 'price',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'CHANGE_PCT',
+ label: 'Change %',
+ category: 'price',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+];
+
+export function getIndicatorDef(name: string): IndicatorDefinition | undefined {
+ return INDICATOR_DEFINITIONS.find(d => d.name === name);
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useAlgoDeployments.ts b/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useAlgoDeployments.ts
new file mode 100644
index 000000000..04d62db48
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useAlgoDeployments.ts
@@ -0,0 +1,48 @@
+import { useState, useCallback, useEffect, useRef } from 'react';
+import type { AlgoDeployment } from '../types';
+import { listAlgoDeployments, stopAlgoDeployment, stopAllAlgoDeployments } from '../services/algoTradingService';
+
+const POLL_INTERVAL = 5000;
+
+export function useAlgoDeployments() {
+ const [deployments, setDeployments] = useState<AlgoDeployment[]>([]);
+ const [loading, setLoading] = useState(true);
+ const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
+
+ const refresh = useCallback(async () => {
+ const result = await listAlgoDeployments();
+ if (result.success && result.data) {
+ setDeployments(result.data);
+ }
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ intervalRef.current = setInterval(refresh, POLL_INTERVAL);
+ return () => {
+ if (intervalRef.current) clearInterval(intervalRef.current);
+ };
+ }, [refresh]);
+
+ const stop = useCallback(async (deployId: string) => {
+ const result = await stopAlgoDeployment(deployId);
+ if (result.success) {
+ await refresh();
+ }
+ return result;
+ }, [refresh]);
+
+ const stopAll = useCallback(async () => {
+ const result = await stopAllAlgoDeployments();
+ if (result.success) {
+ await refresh();
+ }
+ return result;
+ }, [refresh]);
+
+ const running = deployments.filter(d => d.status === 'running');
+ const stopped = deployments.filter(d => d.status !== 'running');
+
+ return { deployments, running, stopped, loading, refresh, stop, stopAll };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useAlgoStrategies.ts b/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useAlgoStrategies.ts
new file mode 100644
index 000000000..8d4ec96ad
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useAlgoStrategies.ts
@@ -0,0 +1,44 @@
+import { useState, useCallback, useEffect } from 'react';
+import type { AlgoStrategy } from '../types';
+import { listAlgoStrategies, getAlgoStrategy, saveAlgoStrategy, deleteAlgoStrategy } from '../services/algoTradingService';
+
+export function useAlgoStrategies() {
+ const [strategies, setStrategies] = useState<AlgoStrategy[]>([]);
+ const [loading, setLoading] = useState(true);
+
+ const refresh = useCallback(async () => {
+ setLoading(true);
+ const result = await listAlgoStrategies();
+ if (result.success && result.data) {
+ setStrategies(result.data);
+ }
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ }, [refresh]);
+
+ const get = useCallback(async (id: string) => {
+ const result = await getAlgoStrategy(id);
+ return result.success ? result.data ?? null : null;
+ }, []);
+
+ const save = useCallback(async (strategy: Parameters<typeof saveAlgoStrategy>[0]) => {
+ const result = await saveAlgoStrategy(strategy);
+ if (result.success) {
+ await refresh();
+ }
+ return result;
+ }, [refresh]);
+
+ const remove = useCallback(async (id: string) => {
+ const result = await deleteAlgoStrategy(id);
+ if (result.success) {
+ setStrategies(prev => prev.filter(s => s.id !== id));
+ }
+ return result;
+ }, []);
+
+ return { strategies, loading, refresh, get, save, remove };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useCandleData.ts b/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useCandleData.ts
new file mode 100644
index 000000000..cdc7f6b6c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useCandleData.ts
@@ -0,0 +1,31 @@
+import { useState, useCallback } from 'react';
+import { getCandleCache } from '../services/algoTradingService';
+
+export function useCandleData() {
+ const [candles, setCandles] = useState<unknown[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const fetch = useCallback(async (symbol: string, timeframe?: string, limit?: number) => {
+ setLoading(true);
+ setError(null);
+
+ const result = await getCandleCache(symbol, timeframe, limit);
+ setLoading(false);
+
+ if (result.success && result.data) {
+ setCandles(result.data);
+ } else {
+ setError(result.error || 'Failed to fetch candles');
+ }
+
+ return result;
+ }, []);
+
+ const clear = useCallback(() => {
+ setCandles([]);
+ setError(null);
+ }, []);
+
+ return { candles, loading, error, fetch, clear };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useScanner.ts b/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useScanner.ts
new file mode 100644
index 000000000..2fd7eb60c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useScanner.ts
@@ -0,0 +1,37 @@
+import { useState, useCallback } from 'react';
+import type { ScanResult } from '../types';
+import { runAlgoScan } from '../services/algoTradingService';
+
+export function useScanner() {
+ const [results, setResults] = useState<ScanResult[]>([]);
+ const [scanned, setScanned] = useState(0);
+ const [scanning, setScanning] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const scan = useCallback(async (conditions: string, symbols: string, timeframe?: string) => {
+ setScanning(true);
+ setError(null);
+ setResults([]);
+ setScanned(0);
+
+ const result = await runAlgoScan(conditions, symbols, timeframe);
+ setScanning(false);
+
+ if (result.success && result.data) {
+ setResults(result.data.matches);
+ setScanned(result.data.scanned);
+ } else {
+ setError(result.error || 'Scan failed');
+ }
+
+ return result;
+ }, []);
+
+ const clear = useCallback(() => {
+ setResults([]);
+ setScanned(0);
+ setError(null);
+ }, []);
+
+ return { results, scanned, scanning, error, scan, clear };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/index.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/index.tsx
new file mode 100644
index 000000000..41ce00191
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/index.tsx
@@ -0,0 +1 @@
+export { default } from './AlgoTradingTab';
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.ts
new file mode 100644
index 000000000..25bdbe181
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/services/algoTradingService.ts
@@ -0,0 +1,203 @@
+import { invoke } from '@tauri-apps/api/core';
+import type { AlgoStrategy, AlgoDeployment, AlgoTrade, ScanResult } from '../types';
+
+interface ApiResult<T = unknown> {
+ success: boolean;
+ data?: T;
+ error?: string;
+ count?: number;
+}
+
+function parseResult<T>(raw: string): ApiResult<T> {
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return { success: false, error: 'Failed to parse response' };
+ }
+}
+
+// Strategy CRUD
+export async function saveAlgoStrategy(strategy: {
+ id: string;
+ name: string;
+ description?: string;
+ entry_conditions: string;
+ exit_conditions: string;
+ entry_logic?: string;
+ exit_logic?: string;
+ stop_loss?: number | null;
+ take_profit?: number | null;
+ trailing_stop?: number | null;
+ trailing_stop_type?: string;
+ timeframe?: string;
+ symbols?: string;
+}): Promise<ApiResult> {
+ const raw = await invoke<string>('save_algo_strategy', {
+ id: strategy.id,
+ name: strategy.name,
+ description: strategy.description,
+ entryConditions: strategy.entry_conditions,
+ exitConditions: strategy.exit_conditions,
+ entryLogic: strategy.entry_logic,
+ exitLogic: strategy.exit_logic,
+ stopLoss: strategy.stop_loss,
+ takeProfit: strategy.take_profit,
+ trailingStop: strategy.trailing_stop,
+ trailingStopType: strategy.trailing_stop_type,
+ timeframe: strategy.timeframe,
+ symbols: strategy.symbols,
+ });
+ return parseResult(raw);
+}
+
+export async function listAlgoStrategies(): Promise<ApiResult<AlgoStrategy[]>> {
+ const raw = await invoke<string>('list_algo_strategies');
+ return parseResult(raw);
+}
+
+export async function getAlgoStrategy(id: string): Promise<ApiResult<AlgoStrategy>> {
+ const raw = await invoke<string>('get_algo_strategy', { id });
+ return parseResult(raw);
+}
+
+export async function deleteAlgoStrategy(id: string): Promise<ApiResult> {
+ const raw = await invoke<string>('delete_algo_strategy', { id });
+ return parseResult(raw);
+}
+
+// Deployment lifecycle
+export async function deployAlgoStrategy(params: {
+ strategyId: string;
+ symbol: string;
+ provider?: string;
+ mode?: string;
+ timeframe?: string;
+ quantity?: number;
+ params?: string;
+}): Promise<ApiResult<{ deploy_id: string; pid: number }>> {
+ const raw = await invoke<string>('deploy_algo_strategy', params);
+ return parseResult(raw);
+}
+
+export async function stopAlgoDeployment(deployId: string): Promise<ApiResult> {
+ const raw = await invoke<string>('stop_algo_deployment', { deployId });
+ return parseResult(raw);
+}
+
+export async function stopAllAlgoDeployments(): Promise<ApiResult<{ stopped: number }>> {
+ const raw = await invoke<string>('stop_all_algo_deployments');
+ return parseResult(raw);
+}
+
+export async function listAlgoDeployments(): Promise<ApiResult<AlgoDeployment[]>> {
+ const raw = await invoke<string>('list_algo_deployments');
+ return parseResult(raw);
+}
+
+// Trades
+export async function getAlgoTrades(
+ deploymentId: string,
+ limit?: number
+): Promise<ApiResult<AlgoTrade[]>> {
+ const raw = await invoke<string>('get_algo_trades', { deploymentId, limit });
+ return parseResult(raw);
+}
+
+// Scanner
+export async function runAlgoScan(
+ conditions: string,
+ symbols: string,
+ timeframe?: string,
+ provider?: string
+): Promise<ApiResult<{ matches: ScanResult[]; scanned: number }>> {
+ const raw = await invoke<string>('run_algo_scan', { conditions, symbols, timeframe, provider });
+ return parseResult(raw);
+}
+
+// Candle cache
+export async function getCandleCache(
+ symbol: string,
+ timeframe?: string,
+ limit?: number
+): Promise<ApiResult<unknown[]>> {
+ const raw = await invoke<string>('get_candle_cache', { symbol, timeframe, limit });
+ return parseResult(raw);
+}
+
+// Condition evaluation (one-shot preview)
+export async function evaluateConditionsOnce(
+ conditions: string,
+ symbol: string,
+ timeframe?: string
+): Promise<ApiResult<{ result: boolean; details: unknown[] }>> {
+ const raw = await invoke<string>('evaluate_conditions_once', { conditions, symbol, timeframe });
+ return parseResult(raw);
+}
+
+// Backtest
+export async function runAlgoBacktest(params: {
+ symbol: string;
+ entryConditions: string;
+ exitConditions: string;
+ timeframe?: string;
+ period?: string;
+ stopLoss?: number;
+ takeProfit?: number;
+ initialCapital?: number;
+}): Promise<ApiResult<{
+ trades: Array<{
+ entry_bar: number;
+ exit_bar: number;
+ entry_price: number;
+ exit_price: number;
+ pnl: number;
+ pnl_pct: number;
+ reason: string;
+ bars_held: number;
+ }>;
+ equity_curve: number[];
+ metrics: {
+ total_trades: number;
+ winning_trades: number;
+ losing_trades: number;
+ win_rate: number;
+ total_return: number;
+ total_return_pct: number;
+ max_drawdown: number;
+ avg_pnl: number;
+ avg_bars_held: number;
+ profit_factor: number;
+ sharpe: number;
+ };
+}>> {
+ const raw = await invoke<string>('run_algo_backtest', params);
+ return parseResult(raw);
+}
+
+// Candle aggregation control
+export async function startCandleAggregation(
+ symbol: string,
+ timeframe?: string
+): Promise<ApiResult> {
+ const raw = await invoke<string>('start_candle_aggregation', { symbol, timeframe });
+ return parseResult(raw);
+}
+
+export async function stopCandleAggregation(
+ symbol: string,
+ timeframe?: string
+): Promise<ApiResult> {
+ const raw = await invoke<string>('stop_candle_aggregation', { symbol, timeframe });
+ return parseResult(raw);
+}
+
+// Order signal bridge
+export async function startOrderSignalBridge(): Promise<ApiResult> {
+ const raw = await invoke<string>('start_order_signal_bridge');
+ return parseResult(raw);
+}
+
+export async function stopOrderSignalBridge(): Promise<ApiResult> {
+ const raw = await invoke<string>('stop_order_signal_bridge');
+ return parseResult(raw);
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/types/index.ts b/fincept-terminal-desktop/src/components/tabs/algo-trading/types/index.ts
new file mode 100644
index 000000000..055c9d5d0
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/types/index.ts
@@ -0,0 +1,110 @@
+export interface ConditionItem {
+ indicator: string;
+ params: Record<string, number>;
+ field: string;
+ operator: string;
+ value: number;
+ value2?: number;
+}
+
+export interface ConditionGroup {
+ conditions: ConditionItem[];
+ logic: 'AND' | 'OR';
+}
+
+export interface AlgoStrategy {
+ id: string;
+ name: string;
+ description: string;
+ entry_conditions: string; // JSON string of (ConditionItem | string)[]
+ exit_conditions: string; // JSON string of (ConditionItem | string)[]
+ entry_logic: 'AND' | 'OR';
+ exit_logic: 'AND' | 'OR';
+ stop_loss: number | null;
+ take_profit: number | null;
+ trailing_stop: number | null;
+ trailing_stop_type: string;
+ timeframe: string;
+ symbols: string; // JSON string of string[]
+ is_active: number;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface AlgoDeployment {
+ id: string;
+ strategy_id: string;
+ strategy_name: string | null;
+ symbol: string;
+ provider: string;
+ mode: 'paper' | 'live';
+ status: 'pending' | 'starting' | 'running' | 'stopped' | 'error';
+ timeframe: string;
+ quantity: number;
+ params: string;
+ pid: number | null;
+ error_message: string | null;
+ created_at: string;
+ updated_at: string;
+ stopped_at: string | null;
+ metrics: AlgoMetrics;
+}
+
+export interface AlgoMetrics {
+ total_pnl: number;
+ unrealized_pnl: number;
+ total_trades: number;
+ win_rate: number;
+ max_drawdown: number;
+ current_position_qty: number;
+ current_position_side: string;
+ current_position_entry: number;
+ metrics_updated: string | null;
+}
+
+export interface AlgoTrade {
+ id: string;
+ deployment_id: string;
+ symbol: string;
+ side: 'BUY' | 'SELL';
+ quantity: number;
+ price: number;
+ pnl: number;
+ timestamp: string;
+ signal_reason: string;
+}
+
+export interface ScanResult {
+ symbol: string;
+ price: number;
+ details: ConditionDetail[];
+}
+
+export interface ConditionDetail {
+ met: boolean;
+ indicator: string;
+ field: string;
+ computed_value: number | null;
+ operator: string;
+ target: number;
+ error?: string;
+}
+
+export interface IndicatorDefinition {
+ name: string;
+ label: string;
+ category: 'trend' | 'momentum' | 'volatility' | 'volume' | 'price';
+ fields: string[];
+ defaultField: string;
+ params: IndicatorParam[];
+}
+
+export interface IndicatorParam {
+ key: string;
+ label: string;
+ default: number;
+ min?: number;
+ max?: number;
+}
+
+export type AlgoSubView = 'builder' | 'strategies' | 'scanner' | 'dashboard';
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx
index 2af082781..638e2ec6e 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx
@@ -12,7 +12,7 @@ import React, { useState, useEffect, useCallback, useRef } from 'react';
import { listen, UnlistenFn } from '@tauri-apps/api/event';
import { showConfirm } from '@/utils/notifications';
import {
- Bot, Trophy, Play, Pause, RotateCcw, Plus, Settings, Key,
+ Bot, Trophy, Play, Pause, RotateCcw, Plus, Settings,
TrendingUp, TrendingDown, Activity, Zap, AlertCircle, CheckCircle,
ChevronRight, Loader2, BarChart3, Clock, Target, Brain,
RefreshCw, Eye, Users, Sparkles, Check, Circle, History, Trash2, PlayCircle,
@@ -20,7 +20,7 @@ import {
} from 'lucide-react';
import { TabFooter } from '@/components/common/TabFooter';
import { withErrorBoundary } from '@/components/common/ErrorBoundary';
-import { sqliteService, type LLMModelConfig, type LLMConfig } from '@/services/core/sqliteService';
+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';
@@ -156,6 +156,7 @@ const AlphaArenaTab: React.FC = () => {
// 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);
@@ -217,6 +218,16 @@ const AlphaArenaTab: React.FC = () => {
// 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[] = [];
@@ -292,6 +303,17 @@ const AlphaArenaTab: React.FC = () => {
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)
// =============================================================================
@@ -506,6 +528,12 @@ const AlphaArenaTab: React.FC = () => {
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;
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ApiKeysModal.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ApiKeysModal.tsx
index 51b117328..7cb495aab 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ApiKeysModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ApiKeysModal.tsx
@@ -1,14 +1,13 @@
/**
* API Keys Modal Component
*
- * Modal for configuring LLM provider API keys.
+ * @deprecated This component is no longer used. API keys are now managed
+ * exclusively through Settings > LLM Config. Kept for reference only.
*/
import React, { useState, useEffect, useReducer, useRef } from 'react';
import { X, Key, Eye, EyeOff, Save, Loader2, AlertCircle } from 'lucide-react';
import { withErrorBoundary } from '@/components/common/ErrorBoundary';
-import { withTimeout } from '@/services/core/apiUtils';
-import alphaArenaService from '../services/alphaArenaService';
interface ApiKeysModalProps {
isOpen: boolean;
@@ -122,23 +121,8 @@ const ApiKeysModal: React.FC<ApiKeysModalProps> = ({ isOpen, onClose }) => {
const loadApiKeys = async () => {
dispatchLoad({ type: 'LOAD_START' });
-
- try {
- const result = await alphaArenaService.getApiKeys();
- if (!mountedRef.current) return;
- if (result.success && result.keys) {
- setApiKeys((prev) =>
- prev.map((key) => ({
- ...key,
- value: result.keys?.[key.provider] || '',
- }))
- );
- }
- dispatchLoad({ type: 'LOAD_SUCCESS' });
- } catch (err) {
- if (!mountedRef.current) return;
- dispatchLoad({ type: 'LOAD_ERROR', error: err instanceof Error ? err.message : 'Failed to load API keys' });
- }
+ // API keys are now managed in Settings > LLM Config
+ dispatchLoad({ type: 'LOAD_SUCCESS' });
};
const handleKeyChange = (provider: string, value: string) => {
@@ -158,31 +142,8 @@ const ApiKeysModal: React.FC<ApiKeysModalProps> = ({ isOpen, onClose }) => {
};
const handleSave = async () => {
- if (saveState.status === 'saving') return;
- dispatchSave({ type: 'SAVE_START' });
-
- try {
- const keysToSave: Record<string, string> = {};
- apiKeys.forEach((key) => {
- if (key.value.trim()) {
- keysToSave[key.provider] = key.value.trim();
- }
- });
-
- const result = await alphaArenaService.saveApiKeys(keysToSave);
- if (!mountedRef.current) return;
- if (result.success) {
- dispatchSave({ type: 'SAVE_SUCCESS' });
- setTimeout(() => {
- if (mountedRef.current) dispatchSave({ type: 'SAVE_RESET' });
- }, 3000);
- } else {
- dispatchSave({ type: 'SAVE_ERROR', error: result.error || 'Failed to save API keys' });
- }
- } catch (err) {
- if (!mountedRef.current) return;
- dispatchSave({ type: 'SAVE_ERROR', error: err instanceof Error ? err.message : 'Unknown error' });
- }
+ // API keys are now managed in Settings > LLM Config
+ dispatchSave({ type: 'SAVE_ERROR', error: 'Please configure API keys in Settings > LLM Config instead.' });
};
const isLoading = loadState.status === 'loading';
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/index.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/index.ts
index 7905a7f5d..7d2451190 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/index.ts
@@ -7,8 +7,6 @@ export { default as Leaderboard } from './Leaderboard';
export { default as DecisionsPanel } from './DecisionsPanel';
export { default as PerformanceChart } from './PerformanceChart';
export { default as CompetitionControls } from './CompetitionControls';
-export { default as ApiKeysModal } from './ApiKeysModal';
-
// Enhanced Alpha Arena Components
export { default as HITLApprovalPanel } from './HITLApprovalPanel';
export { default as SentimentPanel } from './SentimentPanel';
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaService.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaService.ts
index f6adc7b6e..c415e1a66 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaService.ts
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaService.ts
@@ -33,49 +33,6 @@ function extractError(err: unknown): string {
return 'Unknown error';
}
-// =============================================================================
-// API Key Management
-// =============================================================================
-
-interface ApiKeysResponse {
- success: boolean;
- keys?: Record<string, string>;
- error?: string;
-}
-
-/**
- * Get API keys (masked for display)
- */
-export async function getApiKeys(): Promise<ApiKeysResponse> {
- try {
- const result = await deduplicatedFetch('alpha:getApiKeys', () =>
- withTimeout(invoke<ApiKeysResponse>('get_alpha_api_keys'), 15000, 'Get API keys timeout')
- );
- return result;
- } catch (error) {
- console.error('Error getting API keys:', error);
- return { success: false, error: extractError(error) };
- }
-}
-
-/**
- * Save API keys
- */
-export async function saveApiKeys(
- keys: Record<string, string>
-): Promise<{ success: boolean; error?: string }> {
- try {
- const result = await withTimeout(
- invoke<{ success: boolean; message?: string }>('save_alpha_api_keys', { keys }),
- 30000, 'Save API keys timeout'
- );
- return { success: result.success };
- } catch (error) {
- console.error('Error saving API keys:', error);
- return { success: false, error: extractError(error) };
- }
-}
-
// =============================================================================
// Competition Management
// =============================================================================
@@ -825,10 +782,6 @@ export async function createStyledCompetition(params: {
// =============================================================================
export const alphaArenaService = {
- // API Keys
- getApiKeys,
- saveApiKeys,
-
// Competition Management
createCompetition,
startCompetition,
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/types/index.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/types/index.ts
index 48dafbcf3..4da8cacc0 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/types/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/types/index.ts
@@ -228,6 +228,12 @@ export interface CreateCompetitionRequest {
cycle_interval_seconds?: number;
exchange_id?: string;
max_cycles?: number;
+ // Global LLM settings from Settings tab
+ llm_settings?: {
+ temperature: number;
+ max_tokens: number;
+ system_prompt: string;
+ };
}
export interface CreateCompetitionResponse {
diff --git a/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTab.tsx b/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTab.tsx
index a069df233..0cd046869 100644
--- a/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTab.tsx
@@ -27,7 +27,7 @@ import {
} from './backtestingProviderConfigs';
// ============================================================================
-// FINCEPT DESIGN SYSTEM
+// FINCEPT DESIGN SYSTEM - ENHANCED
// ============================================================================
const FINCEPT = {
@@ -35,6 +35,12 @@ const FINCEPT = {
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',
+ // Enhanced gradients and effects
+ GRADIENT_ORANGE: 'linear-gradient(135deg, #FF8800 0%, #FF6B00 100%)',
+ GRADIENT_DARK: 'linear-gradient(180deg, #1A1A1A 0%, #0F0F0F 100%)',
+ GLASS_BG: 'rgba(15, 15, 15, 0.85)',
+ GLOW_ORANGE: '0 0 20px rgba(255, 136, 0, 0.3)',
+ GLOW_CYAN: '0 0 15px rgba(0, 229, 255, 0.2)',
};
// Provider accent colors for visual separation
@@ -508,89 +514,157 @@ const BacktestingTab: React.FC = () => {
const renderTopNav = () => (
<div style={{
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `2px solid ${providerColor}`,
- padding: '8px 16px',
+ background: FINCEPT.GRADIENT_DARK,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ padding: '0',
display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- boxShadow: `0 2px 8px ${providerColor}20`,
+ flexDirection: 'column',
}}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <Activity size={16} color={providerColor} />
- <span style={{
- fontSize: '12px',
- fontWeight: 700,
- color: FINCEPT.WHITE,
- fontFamily: '"IBM Plex Mono", monospace',
- letterSpacing: '0.5px',
- }}>
- BACKTESTING
- </span>
- <div style={{ display: 'flex', gap: '2px', marginLeft: '4px' }}>
- {PROVIDER_OPTIONS.map(p => (
- <button
- key={p.slug}
- onClick={() => setSelectedProvider(p.slug)}
- style={{
- padding: '4px 10px',
- backgroundColor: selectedProvider === p.slug ? PROVIDER_COLORS[p.slug] : 'transparent',
- color: selectedProvider === p.slug ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${selectedProvider === p.slug ? PROVIDER_COLORS[p.slug] : FINCEPT.BORDER}`,
- borderRadius: '2px',
- fontSize: '9px',
- fontWeight: 700,
- cursor: 'pointer',
- fontFamily: '"IBM Plex Mono", monospace',
- letterSpacing: '0.5px',
- transition: 'all 0.2s',
- }}
- onMouseEnter={e => {
- if (selectedProvider !== p.slug) {
- e.currentTarget.style.borderColor = PROVIDER_COLORS[p.slug];
- e.currentTarget.style.color = PROVIDER_COLORS[p.slug];
- }
- }}
- onMouseLeave={e => {
- if (selectedProvider !== p.slug) {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
- e.currentTarget.style.color = FINCEPT.GRAY;
- }
- }}
- >
- {p.displayName}
- </button>
- ))}
+ {/* Top accent bar */}
+ <div style={{
+ height: '3px',
+ background: `linear-gradient(90deg, ${providerColor} 0%, ${providerColor}40 50%, transparent 100%)`,
+ boxShadow: FINCEPT.GLOW_ORANGE,
+ }} />
+
+ {/* Main nav content */}
+ <div style={{
+ padding: '10px 20px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
+ {/* Logo/Title with glow effect */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ padding: '6px 14px',
+ background: `${providerColor}10`,
+ borderRadius: '4px',
+ border: `1px solid ${providerColor}30`,
+ }}>
+ <Activity size={18} color={providerColor} style={{ filter: `drop-shadow(0 0 4px ${providerColor})` }} />
+ <span style={{
+ fontSize: '13px',
+ fontWeight: 800,
+ color: FINCEPT.WHITE,
+ fontFamily: '"IBM Plex Mono", monospace',
+ letterSpacing: '1px',
+ textShadow: `0 0 10px ${providerColor}40`,
+ }}>
+ BACKTESTING
+ </span>
+ </div>
+
+ {/* Provider selector - pill style */}
+ <div style={{
+ display: 'flex',
+ gap: '3px',
+ padding: '3px',
+ backgroundColor: FINCEPT.DARK_BG,
+ borderRadius: '6px',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ {PROVIDER_OPTIONS.map(p => (
+ <button
+ key={p.slug}
+ onClick={() => setSelectedProvider(p.slug)}
+ style={{
+ padding: '5px 12px',
+ backgroundColor: selectedProvider === p.slug ? PROVIDER_COLORS[p.slug] : 'transparent',
+ color: selectedProvider === p.slug ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ border: 'none',
+ borderRadius: '4px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ fontFamily: '"IBM Plex Mono", monospace',
+ letterSpacing: '0.5px',
+ transition: 'all 0.25s ease',
+ boxShadow: selectedProvider === p.slug ? `0 2px 8px ${PROVIDER_COLORS[p.slug]}40` : 'none',
+ }}
+ onMouseEnter={e => {
+ if (selectedProvider !== p.slug) {
+ e.currentTarget.style.backgroundColor = `${PROVIDER_COLORS[p.slug]}20`;
+ e.currentTarget.style.color = PROVIDER_COLORS[p.slug];
+ }
+ }}
+ onMouseLeave={e => {
+ if (selectedProvider !== p.slug) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = FINCEPT.GRAY;
+ }
+ }}
+ >
+ {p.displayName}
+ </button>
+ ))}
+ </div>
</div>
- </div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <button
- onClick={() => setShowAdvanced(!showAdvanced)}
- style={{
- padding: '4px 8px',
- backgroundColor: showAdvanced ? `${FINCEPT.ORANGE}20` : 'transparent',
- border: `1px solid ${showAdvanced ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
- color: showAdvanced ? FINCEPT.ORANGE : FINCEPT.GRAY,
- borderRadius: '2px',
- fontSize: '8px',
- fontWeight: 700,
- cursor: 'pointer',
- fontFamily: '"IBM Plex Mono", monospace',
- }}
- >
- {showAdvanced ? 'HIDE' : 'SHOW'} ADVANCED
- </button>
- <div style={{
- padding: '2px 6px',
- backgroundColor: `${FINCEPT.GREEN}20`,
- color: FINCEPT.GREEN,
- fontSize: '8px',
- fontWeight: 700,
- borderRadius: '2px',
- }}>
- ACTIVE
+
+ {/* Right side controls */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
+ <button
+ onClick={() => setShowAdvanced(!showAdvanced)}
+ style={{
+ padding: '6px 12px',
+ background: showAdvanced ? `linear-gradient(135deg, ${FINCEPT.ORANGE}30 0%, ${FINCEPT.ORANGE}10 100%)` : 'transparent',
+ border: `1px solid ${showAdvanced ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ color: showAdvanced ? FINCEPT.ORANGE : FINCEPT.GRAY,
+ borderRadius: '4px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ fontFamily: '"IBM Plex Mono", monospace',
+ transition: 'all 0.2s',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}
+ >
+ <Settings size={10} />
+ {showAdvanced ? 'HIDE' : 'SHOW'} ADVANCED
+ </button>
+
+ {/* Status indicator with pulse animation */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ padding: '5px 10px',
+ backgroundColor: `${FINCEPT.GREEN}15`,
+ borderRadius: '4px',
+ border: `1px solid ${FINCEPT.GREEN}30`,
+ }}>
+ <div style={{
+ width: '6px',
+ height: '6px',
+ borderRadius: '50%',
+ backgroundColor: FINCEPT.GREEN,
+ boxShadow: `0 0 8px ${FINCEPT.GREEN}`,
+ animation: 'pulse 2s infinite',
+ }} />
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GREEN,
+ letterSpacing: '0.5px',
+ }}>
+ READY
+ </span>
+ </div>
</div>
</div>
+
+ {/* CSS for pulse animation */}
+ <style>{`
+ @keyframes pulse {
+ 0%, 100% { opacity: 1; transform: scale(1); }
+ 50% { opacity: 0.6; transform: scale(1.1); }
+ }
+ `}</style>
</div>
);
@@ -600,138 +674,225 @@ const BacktestingTab: React.FC = () => {
const renderLeftPanel = () => (
<div style={{
- width: '280px',
- backgroundColor: FINCEPT.DARK_BG,
+ width: '260px',
+ background: `linear-gradient(180deg, ${FINCEPT.PANEL_BG} 0%, ${FINCEPT.DARK_BG} 100%)`,
borderRight: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
}}>
- {/* Commands Header */}
+ {/* Commands Header - Enhanced */}
<div style={{
- padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
+ padding: '14px 16px',
+ background: FINCEPT.HEADER_BG,
borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
}}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <div style={{
+ width: '4px',
+ height: '14px',
+ background: providerColor,
+ borderRadius: '2px',
+ boxShadow: `0 0 8px ${providerColor}60`,
+ }} />
+ <span style={{
+ fontSize: '10px',
+ fontWeight: 800,
+ color: FINCEPT.WHITE,
+ letterSpacing: '1px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}>
+ COMMANDS
+ </span>
+ </div>
<span style={{
fontSize: '9px',
- fontWeight: 700,
- color: FINCEPT.GRAY,
- letterSpacing: '0.5px',
- fontFamily: '"IBM Plex Mono", monospace',
+ fontWeight: 600,
+ color: providerColor,
+ backgroundColor: `${providerColor}15`,
+ padding: '2px 8px',
+ borderRadius: '10px',
}}>
- COMMANDS ({providerCommands.length})
+ {providerCommands.length}
</span>
</div>
- {/* Command List (provider-specific) */}
- <div style={{ flex: 1, overflowY: 'auto' }}>
- {providerCommands.map(cmd => {
- const Icon = cmd.icon;
- const isActive = activeCommand === cmd.id;
-
- return (
- <div
- key={cmd.id}
- onClick={() => setActiveCommand(cmd.id)}
- style={{
- padding: '10px 12px',
- backgroundColor: isActive ? `${cmd.color}15` : 'transparent',
- borderLeft: isActive ? `2px solid ${cmd.color}` : '2px solid transparent',
- cursor: 'pointer',
- transition: 'all 0.2s',
- display: 'flex',
- alignItems: 'center',
- gap: '10px',
- }}
- onMouseEnter={e => {
- if (!isActive) e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- }}
- onMouseLeave={e => {
- if (!isActive) e.currentTarget.style.backgroundColor = 'transparent';
- }}
- >
- <Icon size={14} color={isActive ? cmd.color : FINCEPT.GRAY} />
- <div style={{ flex: 1 }}>
+ {/* Command List - Card Style */}
+ <div style={{ flex: 1, overflowY: 'auto', padding: '8px' }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ {providerCommands.map(cmd => {
+ const Icon = cmd.icon;
+ const isActive = activeCommand === cmd.id;
+
+ return (
+ <div
+ key={cmd.id}
+ onClick={() => setActiveCommand(cmd.id)}
+ style={{
+ padding: '10px 12px',
+ backgroundColor: isActive ? `${cmd.color}12` : FINCEPT.PANEL_BG,
+ border: `1px solid ${isActive ? cmd.color : FINCEPT.BORDER}`,
+ borderRadius: '6px',
+ cursor: 'pointer',
+ transition: 'all 0.25s ease',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ boxShadow: isActive ? `0 2px 12px ${cmd.color}20, inset 0 1px 0 ${cmd.color}20` : 'none',
+ position: 'relative',
+ overflow: 'hidden',
+ }}
+ onMouseEnter={e => {
+ if (!isActive) {
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ e.currentTarget.style.borderColor = `${cmd.color}50`;
+ e.currentTarget.style.transform = 'translateX(2px)';
+ }
+ }}
+ onMouseLeave={e => {
+ if (!isActive) {
+ e.currentTarget.style.backgroundColor = FINCEPT.PANEL_BG;
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.transform = 'translateX(0)';
+ }
+ }}
+ >
+ {/* Active indicator glow */}
+ {isActive && (
+ <div style={{
+ position: 'absolute',
+ left: 0,
+ top: 0,
+ bottom: 0,
+ width: '3px',
+ background: cmd.color,
+ boxShadow: `0 0 10px ${cmd.color}`,
+ }} />
+ )}
<div style={{
- fontSize: '10px',
- fontWeight: 700,
- color: isActive ? FINCEPT.WHITE : FINCEPT.GRAY,
- fontFamily: '"IBM Plex Mono", monospace',
+ width: '28px',
+ height: '28px',
+ borderRadius: '6px',
+ backgroundColor: `${cmd.color}15`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
}}>
- {cmd.label}
+ <Icon size={14} color={isActive ? cmd.color : FINCEPT.GRAY} />
</div>
- <div style={{ fontSize: '8px', color: FINCEPT.MUTED }}>
- {cmd.description}
+ <div style={{ flex: 1 }}>
+ <div style={{
+ fontSize: '10px',
+ fontWeight: 700,
+ color: isActive ? FINCEPT.WHITE : FINCEPT.GRAY,
+ fontFamily: '"IBM Plex Mono", monospace',
+ marginBottom: '2px',
+ }}>
+ {cmd.label}
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED, lineHeight: 1.3 }}>
+ {cmd.description}
+ </div>
</div>
+ <ChevronRight size={12} color={isActive ? cmd.color : FINCEPT.MUTED} style={{
+ opacity: isActive ? 1 : 0.5,
+ transition: 'all 0.2s',
+ }} />
</div>
- </div>
- );
- })}
+ );
+ })}
+ </div>
</div>
- {/* Strategy Categories (provider-specific) */}
+ {/* Strategy Categories - Enhanced */}
{['backtest', 'optimize', 'walk_forward'].includes(activeCommand) && (
<>
<div style={{
- padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
+ padding: '14px 16px',
+ background: FINCEPT.HEADER_BG,
borderTop: `1px solid ${FINCEPT.BORDER}`,
borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
}}>
+ <div style={{
+ width: '4px',
+ height: '14px',
+ background: FINCEPT.PURPLE,
+ borderRadius: '2px',
+ }} />
<span style={{
- fontSize: '9px',
- fontWeight: 700,
- color: FINCEPT.GRAY,
- letterSpacing: '0.5px',
+ fontSize: '10px',
+ fontWeight: 800,
+ color: FINCEPT.WHITE,
+ letterSpacing: '1px',
fontFamily: '"IBM Plex Mono", monospace',
}}>
- STRATEGY CATEGORIES
+ STRATEGIES
</span>
</div>
- <div style={{ overflowY: 'auto', maxHeight: '300px' }}>
- {Object.entries(providerCategoryInfo).map(([key, info]) => {
- const Icon = info.icon;
- const isActive = selectedCategory === key;
- const count = providerStrategies[key]?.length || 0;
-
- return (
- <div
- key={key}
- onClick={() => setSelectedCategory(key)}
- style={{
- padding: '8px 12px',
- backgroundColor: isActive ? `${info.color}15` : 'transparent',
- borderLeft: isActive ? `2px solid ${info.color}` : '2px solid transparent',
- cursor: 'pointer',
- transition: 'all 0.2s',
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- }}
- onMouseEnter={e => {
- if (!isActive) e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- }}
- onMouseLeave={e => {
- if (!isActive) e.currentTarget.style.backgroundColor = 'transparent';
- }}
- >
- <Icon size={12} color={isActive ? info.color : FINCEPT.GRAY} />
- <span style={{
- fontSize: '9px',
- fontWeight: 700,
- color: isActive ? FINCEPT.WHITE : FINCEPT.GRAY,
- fontFamily: '"IBM Plex Mono", monospace',
- flex: 1,
- }}>
- {info.label.toUpperCase()}
- </span>
- <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>
- {count}
- </span>
- </div>
- );
- })}
+ <div style={{ overflowY: 'auto', maxHeight: '280px', padding: '8px' }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}>
+ {Object.entries(providerCategoryInfo).map(([key, info]) => {
+ const Icon = info.icon;
+ const isActive = selectedCategory === key;
+ const count = providerStrategies[key]?.length || 0;
+
+ return (
+ <div
+ key={key}
+ onClick={() => setSelectedCategory(key)}
+ style={{
+ padding: '8px 12px',
+ backgroundColor: isActive ? `${info.color}10` : 'transparent',
+ border: `1px solid ${isActive ? `${info.color}40` : 'transparent'}`,
+ borderRadius: '5px',
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ }}
+ onMouseEnter={e => {
+ if (!isActive) {
+ e.currentTarget.style.backgroundColor = `${info.color}08`;
+ }
+ }}
+ onMouseLeave={e => {
+ if (!isActive) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
+ >
+ <Icon size={13} color={isActive ? info.color : FINCEPT.GRAY} />
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: isActive ? FINCEPT.WHITE : FINCEPT.GRAY,
+ fontFamily: '"IBM Plex Mono", monospace',
+ flex: 1,
+ letterSpacing: '0.3px',
+ }}>
+ {info.label.toUpperCase()}
+ </span>
+ <span style={{
+ fontSize: '8px',
+ fontWeight: 600,
+ color: isActive ? info.color : FINCEPT.MUTED,
+ backgroundColor: isActive ? `${info.color}20` : 'transparent',
+ padding: '1px 6px',
+ borderRadius: '8px',
+ }}>
+ {count}
+ </span>
+ </div>
+ );
+ })}
+ </div>
</div>
</>
)}
@@ -750,59 +911,99 @@ const BacktestingTab: React.FC = () => {
flexDirection: 'column',
overflow: 'hidden',
}}>
- {/* Header */}
+ {/* Header - Enhanced with gradient */}
<div style={{
- padding: '12px 16px',
- backgroundColor: FINCEPT.HEADER_BG,
+ padding: '14px 20px',
+ background: `linear-gradient(90deg, ${FINCEPT.HEADER_BG} 0%, ${FINCEPT.PANEL_BG} 100%)`,
borderBottom: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}>
- <span style={{
- fontSize: '9px',
- fontWeight: 700,
- color: FINCEPT.GRAY,
- letterSpacing: '0.5px',
- fontFamily: '"IBM Plex Mono", monospace',
- }}>
- {activeCommand.toUpperCase()} CONFIGURATION
- </span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <div style={{
+ padding: '6px 12px',
+ background: `${providerColor}10`,
+ borderRadius: '6px',
+ border: `1px solid ${providerColor}30`,
+ }}>
+ <span style={{
+ fontSize: '11px',
+ fontWeight: 800,
+ color: FINCEPT.WHITE,
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}>
+ {activeCommand.toUpperCase().replace('_', ' ')}
+ </span>
+ </div>
+ <span style={{
+ fontSize: '9px',
+ color: FINCEPT.MUTED,
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}>
+ CONFIGURATION
+ </span>
+ </div>
+
+ {/* Run Button - Premium Style */}
<button
onClick={handleRunCommand}
disabled={isRunning}
style={{
- padding: '6px 12px',
- backgroundColor: isRunning ? FINCEPT.MUTED : FINCEPT.ORANGE,
+ padding: '8px 20px',
+ background: isRunning
+ ? FINCEPT.MUTED
+ : `linear-gradient(135deg, ${FINCEPT.ORANGE} 0%, #FF6B00 100%)`,
color: FINCEPT.DARK_BG,
border: 'none',
- borderRadius: '2px',
- fontSize: '9px',
- fontWeight: 700,
+ borderRadius: '6px',
+ fontSize: '10px',
+ fontWeight: 800,
cursor: isRunning ? 'wait' : 'pointer',
display: 'flex',
alignItems: 'center',
- gap: '6px',
- opacity: isRunning ? 0.7 : 1,
+ gap: '8px',
+ boxShadow: isRunning ? 'none' : `0 4px 15px ${FINCEPT.ORANGE}40`,
+ transition: 'all 0.3s ease',
fontFamily: '"IBM Plex Mono", monospace',
+ letterSpacing: '0.5px',
+ transform: isRunning ? 'none' : 'translateY(0)',
+ }}
+ onMouseEnter={e => {
+ if (!isRunning) {
+ e.currentTarget.style.transform = 'translateY(-1px)';
+ e.currentTarget.style.boxShadow = `0 6px 20px ${FINCEPT.ORANGE}50`;
+ }
+ }}
+ onMouseLeave={e => {
+ if (!isRunning) {
+ e.currentTarget.style.transform = 'translateY(0)';
+ e.currentTarget.style.boxShadow = `0 4px 15px ${FINCEPT.ORANGE}40`;
+ }
}}
>
{isRunning ? (
<>
- <Loader size={10} className="animate-spin" />
- RUNNING...
+ <Loader size={12} className="animate-spin" />
+ EXECUTING...
</>
) : (
<>
- <Play size={10} />
- RUN {activeCommand.toUpperCase()}
+ <Play size={12} style={{ filter: 'drop-shadow(0 1px 2px rgba(0,0,0,0.3))' }} />
+ RUN {activeCommand.toUpperCase().replace('_', ' ')}
</>
)}
</button>
</div>
- {/* Content */}
- <div style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>
+ {/* Content with subtle gradient background */}
+ <div style={{
+ flex: 1,
+ overflowY: 'auto',
+ padding: '20px',
+ background: `radial-gradient(ellipse at top, ${FINCEPT.PANEL_BG}40 0%, transparent 70%)`,
+ }}>
{activeCommand === 'backtest' && renderBacktestConfig()}
{activeCommand === 'optimize' && renderOptimizeConfig()}
{activeCommand === 'walk_forward' && renderWalkForwardConfig()}
@@ -1578,36 +1779,71 @@ const BacktestingTab: React.FC = () => {
<div style={{
backgroundColor: FINCEPT.PANEL_BG,
border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '2px',
+ borderRadius: '8px',
+ overflow: 'hidden',
+ transition: 'all 0.3s ease',
+ boxShadow: isExpanded ? `0 2px 10px rgba(0,0,0,0.2)` : 'none',
}}>
<div
onClick={() => toggleSection(id)}
style={{
- padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
+ padding: '14px 16px',
+ background: isExpanded
+ ? `linear-gradient(90deg, ${FINCEPT.HEADER_BG} 0%, ${FINCEPT.PANEL_BG} 100%)`
+ : FINCEPT.HEADER_BG,
borderBottom: isExpanded ? `1px solid ${FINCEPT.BORDER}` : 'none',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
+ transition: 'all 0.2s ease',
}}
>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Icon size={12} color={FINCEPT.ORANGE} />
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
+ <div style={{
+ width: '26px',
+ height: '26px',
+ borderRadius: '6px',
+ backgroundColor: `${FINCEPT.ORANGE}15`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ border: `1px solid ${FINCEPT.ORANGE}30`,
+ }}>
+ <Icon size={13} color={FINCEPT.ORANGE} />
+ </div>
<span style={{
- fontSize: '9px',
+ fontSize: '10px',
fontWeight: 700,
- color: FINCEPT.GRAY,
+ color: isExpanded ? FINCEPT.WHITE : FINCEPT.GRAY,
letterSpacing: '0.5px',
fontFamily: '"IBM Plex Mono", monospace',
+ transition: 'color 0.2s',
}}>
{title}
</span>
</div>
- {isExpanded ? <Minimize2 size={10} color={FINCEPT.GRAY} /> : <Maximize2 size={10} color={FINCEPT.GRAY} />}
+ <div style={{
+ width: '20px',
+ height: '20px',
+ borderRadius: '4px',
+ backgroundColor: isExpanded ? `${FINCEPT.ORANGE}15` : 'transparent',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ transition: 'all 0.2s',
+ }}>
+ {isExpanded
+ ? <Minimize2 size={11} color={FINCEPT.ORANGE} />
+ : <Maximize2 size={11} color={FINCEPT.GRAY} />
+ }
+ </div>
</div>
{isExpanded && (
- <div style={{ padding: '12px' }}>
+ <div style={{
+ padding: '16px',
+ background: `linear-gradient(180deg, transparent 0%, ${FINCEPT.DARK_BG}30 100%)`,
+ }}>
{content}
</div>
)}
@@ -1628,14 +1864,15 @@ const BacktestingTab: React.FC = () => {
<div>
<label style={{
display: 'block',
- fontSize: '9px',
+ fontSize: '8px',
fontWeight: 700,
color: FINCEPT.GRAY,
- marginBottom: '4px',
- letterSpacing: '0.5px',
+ marginBottom: '6px',
+ letterSpacing: '0.8px',
fontFamily: '"IBM Plex Mono", monospace',
+ textTransform: 'uppercase',
}}>
- {label.toUpperCase()}
+ {label}
</label>
<input
type={type}
@@ -1647,17 +1884,25 @@ const BacktestingTab: React.FC = () => {
step={step}
style={{
width: '100%',
- padding: '8px 10px',
+ padding: '10px 12px',
backgroundColor: FINCEPT.DARK_BG,
color: type === 'number' ? FINCEPT.CYAN : FINCEPT.WHITE,
border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '2px',
- fontSize: '10px',
+ borderRadius: '6px',
+ fontSize: '11px',
fontFamily: '"IBM Plex Mono", monospace',
outline: 'none',
+ transition: 'all 0.2s ease',
+ boxShadow: 'inset 0 1px 3px rgba(0,0,0,0.2)',
+ }}
+ onFocus={e => {
+ e.target.style.borderColor = FINCEPT.ORANGE;
+ e.target.style.boxShadow = `inset 0 1px 3px rgba(0,0,0,0.2), 0 0 0 2px ${FINCEPT.ORANGE}20`;
+ }}
+ onBlur={e => {
+ e.target.style.borderColor = FINCEPT.BORDER;
+ e.target.style.boxShadow = 'inset 0 1px 3px rgba(0,0,0,0.2)';
}}
- onFocus={e => (e.target.style.borderColor = FINCEPT.ORANGE)}
- onBlur={e => (e.target.style.borderColor = FINCEPT.BORDER)}
/>
</div>
);
@@ -1709,47 +1954,68 @@ const BacktestingTab: React.FC = () => {
const renderRightPanel = () => (
<div style={{
- width: '350px',
- backgroundColor: FINCEPT.DARK_BG,
+ width: '360px',
+ background: `linear-gradient(180deg, ${FINCEPT.PANEL_BG} 0%, ${FINCEPT.DARK_BG} 100%)`,
borderLeft: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
}}>
- {/* Header */}
+ {/* Header - Enhanced */}
<div style={{
- padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
+ padding: '14px 16px',
+ background: FINCEPT.HEADER_BG,
borderBottom: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}>
- <span style={{
- fontSize: '9px',
- fontWeight: 700,
- color: FINCEPT.GRAY,
- letterSpacing: '0.5px',
- fontFamily: '"IBM Plex Mono", monospace',
- }}>
- RESULTS
- </span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
+ <div style={{
+ width: '28px',
+ height: '28px',
+ borderRadius: '6px',
+ background: `linear-gradient(135deg, ${FINCEPT.CYAN}20 0%, ${FINCEPT.BLUE}20 100%)`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ border: `1px solid ${FINCEPT.CYAN}30`,
+ }}>
+ <BarChart3 size={14} color={FINCEPT.CYAN} />
+ </div>
+ <span style={{
+ fontSize: '11px',
+ fontWeight: 800,
+ color: FINCEPT.WHITE,
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}>
+ RESULTS
+ </span>
+ </div>
{result && (
- <div style={{ display: 'flex', gap: '4px' }}>
+ <div style={{
+ display: 'flex',
+ gap: '2px',
+ padding: '3px',
+ backgroundColor: FINCEPT.DARK_BG,
+ borderRadius: '6px',
+ }}>
{(['summary', 'metrics', 'trades', 'raw'] as const).map(view => (
<button
key={view}
onClick={() => setResultView(view)}
style={{
- padding: '4px 6px',
+ padding: '5px 8px',
backgroundColor: resultView === view ? FINCEPT.ORANGE : 'transparent',
color: resultView === view ? FINCEPT.DARK_BG : FINCEPT.GRAY,
border: 'none',
- borderRadius: '2px',
- fontSize: '7px',
+ borderRadius: '4px',
+ fontSize: '8px',
fontWeight: 700,
cursor: 'pointer',
fontFamily: '"IBM Plex Mono", monospace',
+ transition: 'all 0.2s',
}}
>
{view.toUpperCase()}
@@ -1879,66 +2145,109 @@ const BacktestingTab: React.FC = () => {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
- {/* Status Badge */}
+ {/* Status Badge - Enhanced */}
<div style={{
- padding: '4px 8px',
- backgroundColor: `${FINCEPT.GREEN}20`,
- color: FINCEPT.GREEN,
- fontSize: '8px',
- fontWeight: 700,
- borderRadius: '2px',
- display: 'inline-block',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '6px 12px',
+ background: `linear-gradient(90deg, ${FINCEPT.GREEN}20 0%, transparent 100%)`,
+ borderRadius: '6px',
+ border: `1px solid ${FINCEPT.GREEN}30`,
alignSelf: 'flex-start',
}}>
- ✓ COMPLETED
+ <CheckCircle size={12} color={FINCEPT.GREEN} />
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GREEN,
+ letterSpacing: '0.5px',
+ }}>
+ BACKTEST COMPLETED
+ </span>
</div>
- {/* Main Performance Card */}
+ {/* Main Performance Card - Premium Style */}
<div style={{
- padding: '12px',
- backgroundColor: `${isProfit ? FINCEPT.GREEN : FINCEPT.RED}10`,
- border: `2px solid ${isProfit ? FINCEPT.GREEN : FINCEPT.RED}`,
- borderRadius: '4px',
+ padding: '16px',
+ background: `linear-gradient(135deg, ${isProfit ? FINCEPT.GREEN : FINCEPT.RED}15 0%, ${isProfit ? FINCEPT.GREEN : FINCEPT.RED}05 100%)`,
+ border: `1px solid ${isProfit ? FINCEPT.GREEN : FINCEPT.RED}40`,
+ borderRadius: '10px',
+ position: 'relative',
+ overflow: 'hidden',
}}>
+ {/* Decorative glow */}
+ <div style={{
+ position: 'absolute',
+ top: '-50%',
+ right: '-20%',
+ width: '150px',
+ height: '150px',
+ background: `radial-gradient(circle, ${isProfit ? FINCEPT.GREEN : FINCEPT.RED}20 0%, transparent 70%)`,
+ pointerEvents: 'none',
+ }} />
+
<div style={{
fontSize: '9px',
color: FINCEPT.GRAY,
- marginBottom: '4px',
- fontWeight: 600,
+ marginBottom: '6px',
+ fontWeight: 700,
+ letterSpacing: '1px',
}}>
TOTAL RETURN
</div>
<div style={{
- fontSize: '20px',
+ fontSize: '28px',
color: isProfit ? FINCEPT.GREEN : FINCEPT.RED,
- fontWeight: 700,
+ fontWeight: 800,
fontFamily: '"IBM Plex Mono", monospace',
+ textShadow: `0 0 30px ${isProfit ? FINCEPT.GREEN : FINCEPT.RED}40`,
+ letterSpacing: '-1px',
}}>
{totalReturn >= 0 ? '+' : ''}{totalReturn.toFixed(2)}%
</div>
<div style={{
- fontSize: '8px',
+ fontSize: '10px',
color: FINCEPT.MUTED,
- marginTop: '4px',
+ marginTop: '8px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
}}>
- {stats?.initialCapital ? `$${stats.initialCapital.toLocaleString()}` : ''} → {stats?.finalCapital ? `$${stats.finalCapital.toLocaleString()}` : ''}
+ <span style={{ color: FINCEPT.GRAY }}>
+ ${(stats?.initialCapital ?? 0).toLocaleString()}
+ </span>
+ <TrendingUp size={12} color={isProfit ? FINCEPT.GREEN : FINCEPT.RED} />
+ <span style={{ color: isProfit ? FINCEPT.GREEN : FINCEPT.RED, fontWeight: 600 }}>
+ ${(stats?.finalCapital ?? 0).toLocaleString()}
+ </span>
</div>
</div>
- {/* Key Metrics Grid */}
+ {/* Key Metrics Grid - Enhanced Cards */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
{/* Sharpe Ratio */}
<div style={{
- padding: '8px',
+ padding: '12px',
backgroundColor: FINCEPT.PANEL_BG,
border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '3px',
+ borderRadius: '8px',
+ position: 'relative',
+ overflow: 'hidden',
}}>
- <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '2px' }}>SHARPE</div>
<div style={{
- fontSize: '14px',
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ height: '2px',
+ background: (perf.sharpeRatio ?? 0) > 1 ? FINCEPT.GREEN : FINCEPT.CYAN,
+ }} />
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600 }}>SHARPE RATIO</div>
+ <div style={{
+ fontSize: '18px',
color: (perf.sharpeRatio ?? 0) > 1 ? FINCEPT.GREEN : FINCEPT.CYAN,
- fontWeight: 700,
+ fontWeight: 800,
fontFamily: '"IBM Plex Mono", monospace',
}}>
{(perf.sharpeRatio ?? 0).toFixed(2)}
@@ -1947,16 +2256,26 @@ const BacktestingTab: React.FC = () => {
{/* Max Drawdown */}
<div style={{
- padding: '8px',
+ padding: '12px',
backgroundColor: FINCEPT.PANEL_BG,
border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '3px',
+ borderRadius: '8px',
+ position: 'relative',
+ overflow: 'hidden',
}}>
- <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '2px' }}>MAX DD</div>
<div style={{
- fontSize: '14px',
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ height: '2px',
+ background: FINCEPT.RED,
+ }} />
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600 }}>MAX DRAWDOWN</div>
+ <div style={{
+ fontSize: '18px',
color: FINCEPT.RED,
- fontWeight: 700,
+ fontWeight: 800,
fontFamily: '"IBM Plex Mono", monospace',
}}>
{((perf.maxDrawdown ?? 0) * 100).toFixed(2)}%
@@ -1965,16 +2284,26 @@ const BacktestingTab: React.FC = () => {
{/* Win Rate */}
<div style={{
- padding: '8px',
+ padding: '12px',
backgroundColor: FINCEPT.PANEL_BG,
border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '3px',
+ borderRadius: '8px',
+ position: 'relative',
+ overflow: 'hidden',
}}>
- <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '2px' }}>WIN RATE</div>
<div style={{
- fontSize: '14px',
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ height: '2px',
+ background: (perf.winRate ?? 0) > 0.5 ? FINCEPT.GREEN : FINCEPT.YELLOW,
+ }} />
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600 }}>WIN RATE</div>
+ <div style={{
+ fontSize: '18px',
color: (perf.winRate ?? 0) > 0.5 ? FINCEPT.GREEN : FINCEPT.YELLOW,
- fontWeight: 700,
+ fontWeight: 800,
fontFamily: '"IBM Plex Mono", monospace',
}}>
{((perf.winRate ?? 0) * 100).toFixed(1)}%
@@ -1983,16 +2312,26 @@ const BacktestingTab: React.FC = () => {
{/* Total Trades */}
<div style={{
- padding: '8px',
+ padding: '12px',
backgroundColor: FINCEPT.PANEL_BG,
border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '3px',
+ borderRadius: '8px',
+ position: 'relative',
+ overflow: 'hidden',
}}>
- <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '2px' }}>TRADES</div>
<div style={{
- fontSize: '14px',
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ height: '2px',
+ background: FINCEPT.CYAN,
+ }} />
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600 }}>TOTAL TRADES</div>
+ <div style={{
+ fontSize: '18px',
color: FINCEPT.CYAN,
- fontWeight: 700,
+ fontWeight: 800,
fontFamily: '"IBM Plex Mono", monospace',
}}>
{perf.totalTrades ?? 0}
@@ -2000,31 +2339,61 @@ const BacktestingTab: React.FC = () => {
</div>
</div>
- {/* Trade Breakdown */}
+ {/* Trade Breakdown - Enhanced */}
{(perf.totalTrades ?? 0) > 0 && (
<div style={{
- padding: '8px',
+ padding: '12px',
backgroundColor: FINCEPT.PANEL_BG,
border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '3px',
- fontSize: '8px',
+ borderRadius: '8px',
}}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: FINCEPT.GRAY }}>Winning Trades</span>
- <span style={{ color: FINCEPT.GREEN, fontWeight: 600 }}>{perf.winningTrades ?? 0}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: FINCEPT.GRAY }}>Losing Trades</span>
- <span style={{ color: FINCEPT.RED, fontWeight: 600 }}>{perf.losingTrades ?? 0}</span>
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '10px', fontWeight: 700, letterSpacing: '0.5px' }}>
+ TRADE BREAKDOWN
</div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: FINCEPT.GRAY }}>Profit Factor</span>
- <span style={{
- color: (perf.profitFactor ?? 0) > 1 ? FINCEPT.GREEN : FINCEPT.RED,
- fontWeight: 600,
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Winning</span>
+ <span style={{
+ fontSize: '11px',
+ color: FINCEPT.GREEN,
+ fontWeight: 700,
+ backgroundColor: `${FINCEPT.GREEN}15`,
+ padding: '2px 8px',
+ borderRadius: '4px',
+ }}>
+ {perf.winningTrades ?? 0}
+ </span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Losing</span>
+ <span style={{
+ fontSize: '11px',
+ color: FINCEPT.RED,
+ fontWeight: 700,
+ backgroundColor: `${FINCEPT.RED}15`,
+ padding: '2px 8px',
+ borderRadius: '4px',
+ }}>
+ {perf.losingTrades ?? 0}
+ </span>
+ </div>
+ <div style={{
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ paddingTop: '8px',
+ marginTop: '4px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
}}>
- {(perf.profitFactor ?? 0).toFixed(2)}
- </span>
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Profit Factor</span>
+ <span style={{
+ fontSize: '12px',
+ color: (perf.profitFactor ?? 0) > 1 ? FINCEPT.GREEN : FINCEPT.RED,
+ fontWeight: 800,
+ }}>
+ {(perf.profitFactor ?? 0).toFixed(2)}
+ </span>
+ </div>
</div>
</div>
)}
@@ -2032,14 +2401,18 @@ const BacktestingTab: React.FC = () => {
{/* Warning for zero trades */}
{(perf.totalTrades ?? 0) === 0 && (
<div style={{
- padding: '8px',
- backgroundColor: `${FINCEPT.YELLOW}10`,
- border: `1px solid ${FINCEPT.YELLOW}`,
- borderRadius: '3px',
- fontSize: '8px',
- color: FINCEPT.YELLOW,
+ padding: '12px',
+ background: `linear-gradient(90deg, ${FINCEPT.YELLOW}15 0%, transparent 100%)`,
+ border: `1px solid ${FINCEPT.YELLOW}40`,
+ borderRadius: '8px',
+ display: 'flex',
+ alignItems: 'flex-start',
+ gap: '10px',
}}>
- ⚠ No trades executed. Strategy generated no signals or all entries were skipped.
+ <AlertCircle size={14} color={FINCEPT.YELLOW} style={{ marginTop: '1px' }} />
+ <div style={{ fontSize: '9px', color: FINCEPT.YELLOW, lineHeight: 1.4 }}>
+ No trades executed. Strategy generated no signals or all entries were skipped.
+ </div>
</div>
)}
</div>
@@ -2828,7 +3201,7 @@ const BacktestingTab: React.FC = () => {
<div style={{
backgroundColor: FINCEPT.HEADER_BG,
borderTop: `1px solid ${FINCEPT.BORDER}`,
- padding: '4px 16px',
+ padding: '8px 20px',
fontSize: '9px',
color: FINCEPT.GRAY,
display: 'flex',
@@ -2836,23 +3209,72 @@ const BacktestingTab: React.FC = () => {
justifyContent: 'space-between',
fontFamily: '"IBM Plex Mono", monospace',
}}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
- <span>PROVIDER: {providerConfig.displayName}</span>
- <span>•</span>
- <span>COMMAND: {activeCommand.toUpperCase()}</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
+ {/* Provider badge */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ padding: '3px 10px',
+ backgroundColor: `${providerColor}10`,
+ borderRadius: '4px',
+ border: `1px solid ${providerColor}30`,
+ }}>
+ <div style={{
+ width: '6px',
+ height: '6px',
+ borderRadius: '2px',
+ backgroundColor: providerColor,
+ }} />
+ <span style={{ color: providerColor, fontWeight: 600 }}>
+ {providerConfig.displayName}
+ </span>
+ </div>
+
+ <span style={{ color: FINCEPT.MUTED }}>│</span>
+
+ {/* Command */}
+ <span>
+ <span style={{ color: FINCEPT.MUTED }}>CMD:</span>{' '}
+ <span style={{ color: FINCEPT.WHITE }}>{activeCommand.toUpperCase().replace('_', ' ')}</span>
+ </span>
+
{currentStrategy && (
<>
- <span>•</span>
- <span>STRATEGY: {currentStrategy.name.toUpperCase()}</span>
+ <span style={{ color: FINCEPT.MUTED }}>│</span>
+ <span>
+ <span style={{ color: FINCEPT.MUTED }}>STRATEGY:</span>{' '}
+ <span style={{ color: FINCEPT.CYAN }}>{currentStrategy.name.toUpperCase()}</span>
+ </span>
</>
)}
</div>
- <div>
- {isRunning ? (
- <span style={{ color: FINCEPT.ORANGE }}>● RUNNING</span>
- ) : (
- <span style={{ color: FINCEPT.GREEN }}>● READY</span>
- )}
+
+ {/* Status indicator */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '4px 12px',
+ backgroundColor: isRunning ? `${FINCEPT.ORANGE}15` : `${FINCEPT.GREEN}15`,
+ borderRadius: '4px',
+ border: `1px solid ${isRunning ? FINCEPT.ORANGE : FINCEPT.GREEN}30`,
+ }}>
+ <div style={{
+ width: '6px',
+ height: '6px',
+ borderRadius: '50%',
+ backgroundColor: isRunning ? FINCEPT.ORANGE : FINCEPT.GREEN,
+ boxShadow: `0 0 6px ${isRunning ? FINCEPT.ORANGE : FINCEPT.GREEN}`,
+ animation: isRunning ? 'pulse 1s infinite' : 'none',
+ }} />
+ <span style={{
+ color: isRunning ? FINCEPT.ORANGE : FINCEPT.GREEN,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ }}>
+ {isRunning ? 'RUNNING' : 'READY'}
+ </span>
</div>
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx b/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx
index c91228938..2007ef108 100644
--- a/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx
@@ -19,30 +19,19 @@ import { sanitizeInput } from '@/services/core/validators';
import { ErrorBoundary } from '@/components/common/ErrorBoundary';
import { showConfirm, showError } from '@/utils/notifications';
-// Fincept Terminal Design System Colors
-const FINCEPT = {
- 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',
-};
+// NOTE: All colors should use theme context
+// No hardcoded colors - use colors.* from useTerminalTheme()
interface ChatTabProps {
onNavigateToSettings?: () => void;
onNavigateToTab?: (tabName: string) => void;
}
+interface QuickPrompt {
+ cmd: string;
+ prompt: string;
+}
+
// Constants
const SESSION_CREATION_DELAY_MS = 100;
const MAX_MESSAGES_IN_MEMORY = 200;
@@ -50,6 +39,8 @@ const MCP_RETRY_INTERVAL_MS = 10000;
const MCP_MAX_RETRIES = 5;
const CLOCK_UPDATE_INTERVAL_MS = 1000;
const MCP_SUPPORTED_PROVIDERS = ['openai', 'anthropic', 'gemini', 'google', 'groq', 'deepseek', 'openrouter', 'fincept'];
+const STREAMING_SUPPORTED_PROVIDERS = ['openai', 'anthropic', 'gemini', 'google', 'groq', 'deepseek', 'openrouter', 'ollama', 'fincept'];
+const NO_API_KEY_PROVIDERS = ['ollama', 'fincept']; // Providers that don't require API key
const API_TIMEOUT_MS = 30000;
const DB_TIMEOUT_MS = 10000;
@@ -93,6 +84,19 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
});
const [showLLMSelector, setShowLLMSelector] = useState(false);
+ // Quick Prompts state
+ const DEFAULT_QUICK_PROMPTS: QuickPrompt[] = [
+ { cmd: 'MARKET TRENDS', prompt: 'Analyze current market trends and key insights' },
+ { cmd: 'PORTFOLIO', prompt: 'Portfolio diversification recommendations' },
+ { cmd: 'RISK', prompt: 'Investment risk assessment strategies' },
+ { cmd: 'TECHNICAL', prompt: 'Key technical analysis indicators' }
+ ];
+ const [quickPrompts, setQuickPrompts] = useState<QuickPrompt[]>(DEFAULT_QUICK_PROMPTS);
+ const [isEditingPrompts, setIsEditingPrompts] = useState(false);
+ const [editingPromptIndex, setEditingPromptIndex] = useState<number | null>(null);
+ const [editPromptCmd, setEditPromptCmd] = useState('');
+ const [editPromptText, setEditPromptText] = useState('');
+
const handleContextsChange = (contexts: RecordedContext[]) => {
setLinkedContexts(contexts);
};
@@ -115,6 +119,34 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
return MCP_SUPPORTED_PROVIDERS.includes(activeLLMConfig.provider.toLowerCase());
};
+ // Check if current provider supports streaming
+ const providerSupportsStreaming = () => {
+ if (!activeLLMConfig) return false;
+ return STREAMING_SUPPORTED_PROVIDERS.includes(activeLLMConfig.provider.toLowerCase());
+ };
+
+ // Check if current provider requires API key and if it's configured
+ const getApiKeyStatus = (): { required: boolean; configured: boolean } => {
+ if (!activeLLMConfig) return { required: false, configured: false };
+ const provider = activeLLMConfig.provider.toLowerCase();
+ const required = !NO_API_KEY_PROVIDERS.includes(provider);
+ const configured = !required || (activeLLMConfig.api_key && activeLLMConfig.api_key.trim().length > 0);
+ return { required, configured: !!configured };
+ };
+
+ // Check if a custom system prompt is configured
+ const hasCustomSystemPrompt = () => {
+ return llmGlobalSettings.system_prompt && llmGlobalSettings.system_prompt.trim().length > 0;
+ };
+
+ // Check if base URL should be shown (for Ollama or custom endpoints)
+ const shouldShowBaseUrl = () => {
+ if (!activeLLMConfig) return false;
+ const provider = activeLLMConfig.provider.toLowerCase();
+ // Show for Ollama, or if a custom base_url is set
+ return provider === 'ollama' || (activeLLMConfig.base_url && activeLLMConfig.base_url.trim().length > 0);
+ };
+
// Cleanup on unmount
useEffect(() => {
mountedRef.current = true;
@@ -304,6 +336,82 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
}
}, []);
+ // Listen for LLM configuration changes from Settings tab
+ useEffect(() => {
+ const handleLLMConfigChange = () => {
+ console.log('[ChatTab] LLM configuration changed, reloading...');
+ loadLLMConfiguration();
+ };
+
+ window.addEventListener('llm-config-changed', handleLLMConfigChange);
+ return () => {
+ window.removeEventListener('llm-config-changed', handleLLMConfigChange);
+ };
+ }, [loadLLMConfiguration]);
+
+ // Load quick prompts from database
+ const loadQuickPrompts = useCallback(async () => {
+ try {
+ const savedPrompts = await sqliteService.getSetting('chat_quick_prompts');
+ if (savedPrompts) {
+ const parsed = JSON.parse(savedPrompts);
+ if (Array.isArray(parsed) && parsed.length > 0) {
+ setQuickPrompts(parsed);
+ }
+ }
+ } catch (error) {
+ console.error('[ChatTab] Failed to load quick prompts:', error);
+ // Keep default prompts on error
+ }
+ }, []);
+
+ // Save quick prompts to database
+ const saveQuickPrompts = useCallback(async (prompts: QuickPrompt[]) => {
+ try {
+ await sqliteService.saveSetting('chat_quick_prompts', JSON.stringify(prompts), 'chat');
+ setQuickPrompts(prompts);
+ } catch (error) {
+ console.error('[ChatTab] Failed to save quick prompts:', error);
+ }
+ }, []);
+
+ // Quick prompt editing handlers
+ const startEditingPrompt = (index: number) => {
+ setEditingPromptIndex(index);
+ setEditPromptCmd(quickPrompts[index].cmd);
+ setEditPromptText(quickPrompts[index].prompt);
+ setIsEditingPrompts(true);
+ };
+
+ const saveEditedPrompt = async () => {
+ if (editingPromptIndex === null || !editPromptCmd.trim() || !editPromptText.trim()) return;
+
+ const newPrompts = [...quickPrompts];
+ newPrompts[editingPromptIndex] = {
+ cmd: editPromptCmd.trim().toUpperCase(),
+ prompt: editPromptText.trim()
+ };
+ await saveQuickPrompts(newPrompts);
+ setEditingPromptIndex(null);
+ setIsEditingPrompts(false);
+ };
+
+ const cancelEditingPrompt = () => {
+ setEditingPromptIndex(null);
+ setIsEditingPrompts(false);
+ setEditPromptCmd('');
+ setEditPromptText('');
+ };
+
+ const resetQuickPrompts = async () => {
+ await saveQuickPrompts(DEFAULT_QUICK_PROMPTS);
+ };
+
+ // Load quick prompts on mount
+ useEffect(() => {
+ loadQuickPrompts();
+ }, [loadQuickPrompts]);
+
const switchLLMProvider = useCallback(async (provider: string) => {
try {
setSystemStatus('STATUS: SWITCHING LLM PROVIDER...');
@@ -864,17 +972,17 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
alignItems: 'center',
justifyContent: 'center',
height: '100%',
- backgroundColor: FINCEPT.DARK_BG
+ backgroundColor: colors.background
}}>
<div style={{
textAlign: 'center',
padding: '24px',
maxWidth: '400px'
}}>
- <Bot size={48} color={FINCEPT.ORANGE} style={{ marginBottom: '16px', opacity: 0.8 }} />
+ <Bot size={48} color={colors.primary} style={{ marginBottom: '16px', opacity: 0.8 }} />
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '16px',
+ color: colors.primary,
+ fontSize: fontSize.heading,
fontWeight: 700,
marginBottom: '8px',
letterSpacing: '0.5px'
@@ -882,8 +990,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{t('title').toUpperCase()}
</div>
<div style={{
- color: FINCEPT.WHITE,
- fontSize: '11px',
+ color: colors.text,
+ fontSize: fontSize.body,
marginBottom: '16px',
lineHeight: '1.5'
}}>
@@ -891,9 +999,9 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
</div>
<div style={{
padding: '6px 12px',
- backgroundColor: `${FINCEPT.YELLOW}20`,
- color: FINCEPT.YELLOW,
- fontSize: '9px',
+ backgroundColor: `${colors.warning}20`,
+ color: colors.warning,
+ fontSize: fontSize.small,
fontWeight: 700,
borderRadius: '2px',
marginBottom: '16px',
@@ -907,10 +1015,10 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
onClick={createNewSession}
style={{
padding: '8px 16px',
- backgroundColor: FINCEPT.ORANGE,
- color: FINCEPT.DARK_BG,
+ backgroundColor: colors.primary,
+ color: colors.background,
border: 'none',
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 700,
borderRadius: '2px',
cursor: 'pointer',
@@ -936,8 +1044,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
<div style={{
maxWidth: '85%',
minWidth: '120px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${message.role === 'user' ? FINCEPT.YELLOW : FINCEPT.ORANGE}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${message.role === 'user' ? colors.warning : colors.primary}`,
borderRadius: '2px',
padding: '10px'
}}>
@@ -947,25 +1055,25 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
gap: '6px',
marginBottom: '8px',
paddingBottom: '6px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ borderBottom: `1px solid ${'rgba(255,255,255,0.1)'}`
}}>
{message.role === 'user' ? (
- <User size={12} color={FINCEPT.YELLOW} />
+ <User size={12} color={colors.warning} />
) : (
- <Bot size={12} color={FINCEPT.ORANGE} />
+ <Bot size={12} color={colors.primary} />
)}
<span style={{
- color: message.role === 'user' ? FINCEPT.YELLOW : FINCEPT.ORANGE,
- fontSize: '9px',
+ color: message.role === 'user' ? colors.warning : colors.primary,
+ fontSize: fontSize.small,
fontWeight: 700,
letterSpacing: '0.5px'
}}>
{message.role === 'user' ? 'YOU' : 'AI'}
</span>
- <Clock size={10} color={FINCEPT.GRAY} />
+ <Clock size={10} color={colors.textMuted} />
<span style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.small,
letterSpacing: '0.5px',
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}>
@@ -973,8 +1081,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
</span>
{message.provider && (
<span style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.small,
letterSpacing: '0.5px'
}}>
| {message.provider.toUpperCase()}
@@ -986,8 +1094,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
<div style={{
marginBottom: '12px',
padding: '8px 12px',
- background: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
+ background: colors.panel,
+ border: `1px solid ${'rgba(255,255,255,0.1)'}`,
borderRadius: '4px',
display: 'flex',
flexWrap: 'wrap',
@@ -995,8 +1103,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
alignItems: 'center'
}}>
<span style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.small,
letterSpacing: '0.5px',
textTransform: 'uppercase'
}}>
@@ -1007,14 +1115,14 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
key={idx}
style={{
padding: '4px 8px',
- background: tool.status === 'success' ? FINCEPT.GREEN + '20' :
- tool.status === 'error' ? FINCEPT.RED + '20' : FINCEPT.ORANGE + '20',
- border: `1px solid ${tool.status === 'success' ? FINCEPT.GREEN :
- tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE}`,
+ background: tool.status === 'success' ? colors.success + '20' :
+ tool.status === 'error' ? colors.alert + '20' : colors.primary + '20',
+ border: `1px solid ${tool.status === 'success' ? colors.success :
+ tool.status === 'error' ? colors.alert : colors.primary}`,
borderRadius: '3px',
- fontSize: '9px',
- color: tool.status === 'success' ? FINCEPT.GREEN :
- tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE,
+ fontSize: fontSize.small,
+ color: tool.status === 'success' ? colors.success :
+ tool.status === 'error' ? colors.alert : colors.primary,
letterSpacing: '0.5px',
fontFamily: '"IBM Plex Mono", "Consolas", monospace',
display: 'flex',
@@ -1022,7 +1130,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
gap: '4px'
}}
>
- <span style={{ fontSize: '8px' }}>
+ <span style={{ fontSize: fontSize.tiny }}>
{tool.status === 'success' ? '✓' : tool.status === 'error' ? '✗' : '⋯'}
</span>
{tool.name.replace('edgar_', '').replace(/_/g, ' ')}
@@ -1045,8 +1153,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
</>
) : (
<div style={{
- color: FINCEPT.WHITE,
- fontSize: '11px',
+ color: colors.text,
+ fontSize: fontSize.body,
lineHeight: '1.6',
whiteSpace: 'pre-wrap',
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
@@ -1063,8 +1171,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
return (
<div key={message.id} style={{
marginBottom: '12px',
- color: FINCEPT.RED,
- fontSize: '10px',
+ color: colors.alert,
+ fontSize: fontSize.small,
letterSpacing: '0.5px'
}}>
ERROR RENDERING MESSAGE
@@ -1080,8 +1188,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
<div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'flex-start' }}>
<div style={{
maxWidth: '85%',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `2px solid ${FINCEPT.ORANGE}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.primary}`,
borderRadius: '2px',
padding: '10px'
}}>
@@ -1091,16 +1199,16 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
gap: '6px',
marginBottom: '8px',
paddingBottom: '6px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ borderBottom: `1px solid ${'rgba(255,255,255,0.1)'}`
}}>
<Bot
size={12}
- color={FINCEPT.ORANGE}
+ color={colors.primary}
style={{ animation: 'spin 2s linear infinite' }}
/>
<span style={{
- color: FINCEPT.ORANGE,
- fontSize: '9px',
+ color: colors.primary,
+ fontSize: fontSize.small,
fontWeight: 700,
letterSpacing: '0.5px',
animation: 'fadeInOut 1.5s ease-in-out infinite'
@@ -1108,8 +1216,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{t('messages.typing').toUpperCase()}
</span>
<span style={{
- color: FINCEPT.ORANGE,
- fontSize: '9px',
+ color: colors.primary,
+ fontSize: fontSize.small,
animation: 'dots 1.5s steps(4, end) infinite'
}}>
<span>.</span>
@@ -1123,8 +1231,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
<div style={{
marginBottom: streamingContent ? '12px' : '0',
padding: '8px 12px',
- background: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
+ background: colors.background,
+ border: `1px solid ${'rgba(255,255,255,0.1)'}`,
borderRadius: '4px',
display: 'flex',
flexWrap: 'wrap',
@@ -1132,8 +1240,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
alignItems: 'center'
}}>
<span style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.small,
letterSpacing: '0.5px',
textTransform: 'uppercase'
}}>
@@ -1144,14 +1252,14 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
key={idx}
style={{
padding: '4px 8px',
- background: tool.status === 'success' ? FINCEPT.GREEN + '20' :
- tool.status === 'error' ? FINCEPT.RED + '20' : FINCEPT.ORANGE + '20',
- border: `1px solid ${tool.status === 'success' ? FINCEPT.GREEN :
- tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE}`,
+ background: tool.status === 'success' ? colors.success + '20' :
+ tool.status === 'error' ? colors.alert + '20' : colors.primary + '20',
+ border: `1px solid ${tool.status === 'success' ? colors.success :
+ tool.status === 'error' ? colors.alert : colors.primary}`,
borderRadius: '3px',
- fontSize: '9px',
- color: tool.status === 'success' ? FINCEPT.GREEN :
- tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE,
+ fontSize: fontSize.small,
+ color: tool.status === 'success' ? colors.success :
+ tool.status === 'error' ? colors.alert : colors.primary,
letterSpacing: '0.5px',
fontFamily: '"IBM Plex Mono", "Consolas", monospace',
display: 'flex',
@@ -1160,7 +1268,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
animation: tool.status === 'calling' ? 'pulse 1.5s infinite' : 'none'
}}
>
- <span style={{ fontSize: '8px' }}>
+ <span style={{ fontSize: fontSize.tiny }}>
{tool.status === 'success' ? '✓' : tool.status === 'error' ? '✗' : '⋯'}
</span>
{tool.name.replace('edgar_', '').replace('stock_', '').replace(/_/g, ' ')}
@@ -1171,15 +1279,15 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{streamingContent && (
<div style={{
- color: FINCEPT.WHITE,
- fontSize: '11px',
+ color: colors.text,
+ fontSize: fontSize.body,
lineHeight: '1.6',
whiteSpace: 'pre-wrap',
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}>
{streamingContent}
<span style={{
- color: FINCEPT.ORANGE,
+ color: colors.primary,
animation: 'blink 1s infinite'
}}>▊</span>
</div>
@@ -1192,8 +1300,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
return (
<div style={{
height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.background,
+ color: colors.text,
fontFamily: '"IBM Plex Mono", "Consolas", monospace',
display: 'flex',
flexDirection: 'column'
@@ -1205,24 +1313,24 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
height: 6px;
}
*::-webkit-scrollbar-track {
- background: ${FINCEPT.DARK_BG};
+ background: ${colors.background};
}
*::-webkit-scrollbar-thumb {
- background: ${FINCEPT.BORDER};
+ background: ${'rgba(255,255,255,0.1)'};
border-radius: 3px;
}
*::-webkit-scrollbar-thumb:hover {
- background: ${FINCEPT.MUTED};
+ background: ${colors.textMuted};
}
/* For Firefox */
* {
scrollbar-width: thin;
- scrollbar-color: ${FINCEPT.BORDER} ${FINCEPT.DARK_BG};
+ scrollbar-color: ${'rgba(255,255,255,0.1)'} ${colors.background};
}
/* Input focus states */
input:focus, textarea:focus {
outline: none;
- border-color: ${FINCEPT.ORANGE} !important;
+ border-color: ${colors.primary} !important;
}
/* Blink animation for cursor */
@keyframes blink {
@@ -1249,36 +1357,36 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
`}</style>
{/* Top Navigation Bar */}
<div style={{
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `2px solid ${FINCEPT.ORANGE}`,
+ backgroundColor: colors.panel,
+ borderBottom: `2px solid ${colors.primary}`,
padding: '8px 16px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
flexShrink: 0,
- boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`
+ boxShadow: `0 2px 8px ${colors.primary}20`
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<span style={{
- color: FINCEPT.ORANGE,
+ color: colors.primary,
fontWeight: 700,
- fontSize: '11px',
+ fontSize: fontSize.body,
letterSpacing: '0.5px'
}}>
{t('title').toUpperCase()}
</span>
- <span style={{ color: FINCEPT.GRAY }}>|</span>
+ <span style={{ color: colors.textMuted }}>|</span>
{/* LLM Provider Selector */}
<div ref={llmSelectorRef} style={{ position: 'relative' }}>
<button
onClick={() => setShowLLMSelector(!showLLMSelector)}
style={{
- backgroundColor: `${FINCEPT.YELLOW}20`,
- border: `1px solid ${FINCEPT.YELLOW}40`,
- color: FINCEPT.YELLOW,
+ backgroundColor: `${colors.warning}20`,
+ border: `1px solid ${colors.warning}40`,
+ color: colors.warning,
padding: '4px 10px',
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 700,
borderRadius: '2px',
cursor: 'pointer',
@@ -1289,18 +1397,18 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
transition: 'all 0.2s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = `${FINCEPT.YELLOW}30`;
- e.currentTarget.style.borderColor = FINCEPT.YELLOW;
+ e.currentTarget.style.backgroundColor = `${colors.warning}30`;
+ e.currentTarget.style.borderColor = colors.warning;
}}
onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = `${FINCEPT.YELLOW}20`;
- e.currentTarget.style.borderColor = `${FINCEPT.YELLOW}40`;
+ e.currentTarget.style.backgroundColor = `${colors.warning}20`;
+ e.currentTarget.style.borderColor = `${colors.warning}40`;
}}
title="Switch LLM Provider"
>
<Bot size={10} />
{activeLLMConfig?.provider.toUpperCase() || 'NO PROVIDER'}
- <span style={{ fontSize: '7px' }}>▼</span>
+ <span style={{ fontSize: fontSize.tiny }}>▼</span>
</button>
{/* Dropdown Menu */}
@@ -1310,23 +1418,23 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
top: '100%',
left: 0,
marginTop: '4px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.ORANGE}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px',
padding: '4px',
minWidth: '220px',
maxHeight: '400px',
overflowY: 'auto',
zIndex: 1000,
- boxShadow: `0 4px 12px ${FINCEPT.DARK_BG}80`
+ boxShadow: `0 4px 12px ${colors.background}80`
}}>
<div style={{
padding: '6px 8px',
- fontSize: '8px',
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid ${'rgba(255,255,255,0.1)'}`,
marginBottom: '4px'
}}>
SELECT LLM PROVIDER
@@ -1338,11 +1446,11 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
onClick={() => switchLLMProvider(config.provider)}
style={{
width: '100%',
- backgroundColor: activeLLMConfig?.provider === config.provider ? `${FINCEPT.ORANGE}20` : 'transparent',
- border: activeLLMConfig?.provider === config.provider ? `1px solid ${FINCEPT.ORANGE}` : `1px solid ${FINCEPT.BORDER}`,
- color: activeLLMConfig?.provider === config.provider ? FINCEPT.ORANGE : FINCEPT.WHITE,
+ backgroundColor: activeLLMConfig?.provider === config.provider ? `${colors.primary}20` : 'transparent',
+ border: activeLLMConfig?.provider === config.provider ? `1px solid ${colors.primary}` : `1px solid ${'rgba(255,255,255,0.1)'}`,
+ color: activeLLMConfig?.provider === config.provider ? colors.primary : colors.text,
padding: '8px',
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 600,
borderRadius: '2px',
cursor: 'pointer',
@@ -1355,14 +1463,14 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
}}
onMouseEnter={(e) => {
if (activeLLMConfig?.provider !== config.provider) {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- e.currentTarget.style.borderColor = FINCEPT.MUTED;
+ e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.05)';
+ e.currentTarget.style.borderColor = colors.textMuted;
}
}}
onMouseLeave={(e) => {
if (activeLLMConfig?.provider !== config.provider) {
e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.borderColor = 'rgba(255,255,255,0.1)';
}
}}
>
@@ -1371,14 +1479,14 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{config.provider.toUpperCase()}
</span>
{activeLLMConfig?.provider === config.provider && (
- <span style={{ color: FINCEPT.GREEN, fontSize: '8px' }}>● ACTIVE</span>
+ <span style={{ color: colors.success, fontSize: fontSize.tiny }}>● ACTIVE</span>
)}
</div>
- <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>
+ <div style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
Model: {config.model || 'N/A'}
</div>
{config.base_url && (
- <div style={{ fontSize: '7px', color: FINCEPT.MUTED }}>
+ <div style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
{config.base_url}
</div>
)}
@@ -1388,8 +1496,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
<div style={{
padding: '12px',
textAlign: 'center',
- fontSize: '9px',
- color: FINCEPT.MUTED
+ fontSize: fontSize.small,
+ color: colors.textMuted
}}>
No LLM providers configured. Go to Settings to add one.
</div>
@@ -1398,10 +1506,10 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
)}
</div>
- <span style={{ color: FINCEPT.GRAY }}>|</span>
+ <span style={{ color: colors.textMuted }}>|</span>
<span style={{
- color: FINCEPT.WHITE,
- fontSize: '9px',
+ color: colors.text,
+ fontSize: fontSize.small,
letterSpacing: '0.5px'
}}>
{currentTime.toLocaleTimeString('en-US', { hour12: false })}
@@ -1412,10 +1520,10 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
onClick={() => onNavigateToSettings?.()}
style={{
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
+ border: `1px solid ${'rgba(255,255,255,0.1)'}`,
+ color: colors.textMuted,
padding: '6px 10px',
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 700,
borderRadius: '2px',
cursor: 'pointer',
@@ -1426,12 +1534,12 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
transition: 'all 0.2s'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.ORANGE;
- e.currentTarget.style.color = FINCEPT.WHITE;
+ e.currentTarget.style.borderColor = colors.primary;
+ e.currentTarget.style.color = colors.text;
}}
onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
- e.currentTarget.style.color = FINCEPT.GRAY;
+ e.currentTarget.style.borderColor = 'rgba(255,255,255,0.1)';
+ e.currentTarget.style.color = colors.textMuted;
}}
title="Go to Settings tab to configure LLM providers"
>
@@ -1441,11 +1549,11 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
<button
onClick={createNewSession}
style={{
- backgroundColor: FINCEPT.ORANGE,
+ backgroundColor: colors.primary,
border: 'none',
- color: FINCEPT.DARK_BG,
+ color: colors.background,
padding: '8px 16px',
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 700,
borderRadius: '2px',
cursor: 'pointer',
@@ -1468,8 +1576,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Left Panel - Sessions */}
<div style={{
width: '280px',
- backgroundColor: FINCEPT.PANEL_BG,
- borderRight: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.panel,
+ borderRight: `1px solid ${'rgba(255,255,255,0.1)'}`,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden'
@@ -1477,14 +1585,14 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Section Header */}
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${'rgba(255,255,255,0.1)'}`
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
<span style={{
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 700,
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px'
}}>
{t('history.sessions').toUpperCase()} ({statistics.totalSessions})
@@ -1494,10 +1602,10 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
onClick={deleteAllSessions}
style={{
padding: '2px 6px',
- backgroundColor: `${FINCEPT.RED}20`,
- color: FINCEPT.RED,
+ backgroundColor: `${colors.alert}20`,
+ color: colors.alert,
border: 'none',
- fontSize: '8px',
+ fontSize: fontSize.tiny,
fontWeight: 700,
borderRadius: '2px',
cursor: 'pointer',
@@ -1513,7 +1621,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Search */}
<div style={{ position: 'relative', marginBottom: '8px' }}>
- <Search size={12} color={FINCEPT.GRAY} style={{ position: 'absolute', left: '8px', top: '9px' }} />
+ <Search size={12} color={colors.textMuted} style={{ position: 'absolute', left: '8px', top: '9px' }} />
<input
id="session-search"
type="text"
@@ -1523,11 +1631,11 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
style={{
width: '100%',
padding: '8px 10px 8px 32px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'rgba(255,255,255,0.1)'}`,
borderRadius: '2px',
- fontSize: '10px',
+ fontSize: fontSize.small,
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}
/>
@@ -1535,8 +1643,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Stats */}
<div style={{
- fontSize: '9px',
- color: FINCEPT.CYAN,
+ fontSize: fontSize.small,
+ color: colors.secondary,
letterSpacing: '0.5px',
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}>
@@ -1558,8 +1666,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
key={session.session_uuid}
style={{
padding: '10px 12px',
- backgroundColor: currentSessionUuid === session.session_uuid ? `${FINCEPT.ORANGE}15` : 'transparent',
- borderLeft: currentSessionUuid === session.session_uuid ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
+ backgroundColor: currentSessionUuid === session.session_uuid ? `${colors.primary}15` : 'transparent',
+ borderLeft: currentSessionUuid === session.session_uuid ? `2px solid ${colors.primary}` : '2px solid transparent',
cursor: renamingSessionId === session.session_uuid ? 'default' : 'pointer',
transition: 'all 0.2s',
marginBottom: '4px'
@@ -1567,7 +1675,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
onClick={() => renamingSessionId !== session.session_uuid && selectSession(session.session_uuid)}
onMouseEnter={(e) => {
if (currentSessionUuid !== session.session_uuid && renamingSessionId !== session.session_uuid) {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.05)';
}
}}
onMouseLeave={(e) => {
@@ -1591,10 +1699,10 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
style={{
flex: 1,
padding: '4px 6px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.ORANGE}`,
- color: FINCEPT.WHITE,
- fontSize: '10px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: fontSize.small,
borderRadius: '2px',
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}
@@ -1606,7 +1714,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
}}
style={{
backgroundColor: 'transparent',
- color: FINCEPT.GREEN,
+ color: colors.success,
border: 'none',
cursor: 'pointer',
padding: '0',
@@ -1623,7 +1731,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
}}
style={{
backgroundColor: 'transparent',
- color: FINCEPT.RED,
+ color: colors.alert,
border: 'none',
cursor: 'pointer',
padding: '0',
@@ -1636,8 +1744,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
</div>
) : (
<div style={{
- color: FINCEPT.WHITE,
- fontSize: '10px',
+ color: colors.text,
+ fontSize: fontSize.small,
marginBottom: '6px',
overflow: 'hidden',
textOverflow: 'ellipsis',
@@ -1651,8 +1759,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Actions Row */}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.small,
letterSpacing: '0.5px',
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}>
@@ -1666,9 +1774,9 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
}}
style={{
backgroundColor: 'transparent',
- color: FINCEPT.YELLOW,
+ color: colors.warning,
border: 'none',
- fontSize: '9px',
+ fontSize: fontSize.small,
cursor: 'pointer',
padding: '0',
display: 'flex',
@@ -1685,9 +1793,9 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
}}
style={{
backgroundColor: 'transparent',
- color: FINCEPT.RED,
+ color: colors.alert,
border: 'none',
- fontSize: '9px',
+ fontSize: fontSize.small,
cursor: 'pointer',
padding: '0',
display: 'flex',
@@ -1707,7 +1815,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Center Panel - Chat */}
<div style={{
flex: 1,
- backgroundColor: FINCEPT.PANEL_BG,
+ backgroundColor: colors.panel,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden'
@@ -1715,16 +1823,16 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Chat Header */}
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${'rgba(255,255,255,0.1)'}`,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}>
<span style={{
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 700,
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px'
}}>
{currentSessionUuid ? (sessions.find(s => s.session_uuid === currentSessionUuid)?.title || 'CHAT').toUpperCase() : 'NO ACTIVE SESSION'}
@@ -1734,10 +1842,10 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
onClick={clearCurrentChat}
style={{
padding: '2px 6px',
- backgroundColor: `${FINCEPT.RED}20`,
- color: FINCEPT.RED,
+ backgroundColor: `${colors.alert}20`,
+ color: colors.alert,
border: 'none',
- fontSize: '8px',
+ fontSize: fontSize.tiny,
fontWeight: 700,
borderRadius: '2px',
cursor: 'pointer',
@@ -1755,7 +1863,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
flex: 1,
padding: '16px',
overflow: 'auto',
- backgroundColor: FINCEPT.DARK_BG
+ backgroundColor: colors.background
}}>
{messages.length === 0 && !streamingContent ? renderWelcomeScreen() : (
<div>
@@ -1766,11 +1874,11 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
display: 'flex',
alignItems: 'center',
gap: '6px',
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.small,
letterSpacing: '0.5px'
}}>
- <Bot size={12} color={FINCEPT.GRAY} />
+ <Bot size={12} color={colors.textMuted} />
<span>{t('messages.thinking').toUpperCase()}</span>
</div>
)}
@@ -1782,8 +1890,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Input Area */}
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderTop: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ borderTop: `1px solid ${'rgba(255,255,255,0.1)'}`
}}>
<div style={{ display: 'flex', gap: '8px' }}>
<textarea
@@ -1799,11 +1907,11 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
style={{
flex: 1,
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${'rgba(255,255,255,0.1)'}`,
borderRadius: '2px',
- fontSize: '10px',
+ fontSize: fontSize.small,
resize: 'none',
height: '60px',
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
@@ -1814,11 +1922,11 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
disabled={!messageInput.trim() || isTyping}
style={{
padding: '8px 16px',
- backgroundColor: messageInput.trim() && !isTyping ? FINCEPT.ORANGE : FINCEPT.MUTED,
- color: FINCEPT.DARK_BG,
+ backgroundColor: messageInput.trim() && !isTyping ? colors.primary : colors.textMuted,
+ color: colors.background,
border: 'none',
borderRadius: '2px',
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 700,
cursor: messageInput.trim() && !isTyping ? 'pointer' : 'not-allowed',
display: 'flex',
@@ -1834,8 +1942,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
</button>
</div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.small,
marginTop: '6px',
letterSpacing: '0.5px',
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
@@ -1848,25 +1956,25 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Right Panel - Quick Actions & Context Selector */}
<div style={{
width: '300px',
- backgroundColor: FINCEPT.PANEL_BG,
- borderLeft: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.panel,
+ borderLeft: `1px solid ${'rgba(255,255,255,0.1)'}`,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden'
}}>
{/* Context Selector Section */}
<div style={{
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ borderBottom: `1px solid ${'rgba(255,255,255,0.1)'}`
}}>
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${'rgba(255,255,255,0.1)'}`
}}>
<span style={{
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 700,
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px'
}}>
{t('panel.dataContexts').toUpperCase()}
@@ -1882,58 +1990,200 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Quick Prompts Section */}
<div style={{
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ borderBottom: `1px solid ${'rgba(255,255,255,0.1)'}`
}}>
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${'rgba(255,255,255,0.1)'}`,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
}}>
<span style={{
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 700,
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px'
}}>
{t('panel.quickPrompts').toUpperCase()}
</span>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {isEditingPrompts ? (
+ <>
+ <button
+ onClick={cancelEditingPrompt}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${colors.alert}`,
+ color: colors.alert,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ letterSpacing: '0.5px'
+ }}
+ >
+ <X size={10} />
+ </button>
+ <button
+ onClick={saveEditedPrompt}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${colors.success}`,
+ color: colors.success,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ letterSpacing: '0.5px'
+ }}
+ >
+ <Check size={10} />
+ </button>
+ </>
+ ) : (
+ <button
+ onClick={resetQuickPrompts}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ letterSpacing: '0.5px'
+ }}
+ title="Reset to default prompts"
+ >
+ RESET
+ </button>
+ )}
+ </div>
</div>
<div style={{ padding: '12px' }}>
- {[
- { cmd: 'MARKET TRENDS', prompt: 'Analyze current market trends and key insights' },
- { cmd: 'PORTFOLIO', prompt: 'Portfolio diversification recommendations' },
- { cmd: 'RISK', prompt: 'Investment risk assessment strategies' },
- { cmd: 'TECHNICAL', prompt: 'Key technical analysis indicators' }
- ].map(item => (
- <button
- key={item.cmd}
- onClick={() => setMessageInput(item.prompt)}
+ {/* Editing form */}
+ {isEditingPrompts && editingPromptIndex !== null && (
+ <div style={{
+ marginBottom: '8px',
+ padding: '8px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ borderRadius: '2px'
+ }}>
+ <input
+ type="text"
+ value={editPromptCmd}
+ onChange={(e) => setEditPromptCmd(e.target.value.toUpperCase())}
+ placeholder="LABEL"
+ style={{
+ width: '100%',
+ padding: '4px 6px',
+ backgroundColor: colors.panel,
+ border: `1px solid ${'rgba(255,255,255,0.1)'}`,
+ color: colors.text,
+ fontSize: fontSize.small,
+ borderRadius: '2px',
+ marginBottom: '4px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}
+ />
+ <textarea
+ value={editPromptText}
+ onChange={(e) => setEditPromptText(e.target.value)}
+ placeholder="Prompt text..."
+ style={{
+ width: '100%',
+ padding: '4px 6px',
+ backgroundColor: colors.panel,
+ border: `1px solid ${'rgba(255,255,255,0.1)'}`,
+ color: colors.text,
+ fontSize: fontSize.small,
+ borderRadius: '2px',
+ resize: 'vertical',
+ minHeight: '40px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}
+ />
+ </div>
+ )}
+ {/* Quick prompt buttons */}
+ {quickPrompts.map((item, index) => (
+ <div
+ key={`${item.cmd}-${index}`}
style={{
- width: '100%',
- padding: '6px 10px',
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
- fontSize: '9px',
- fontWeight: 700,
- borderRadius: '2px',
- textAlign: 'left',
- cursor: 'pointer',
- marginBottom: '6px',
- letterSpacing: '0.5px',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.ORANGE;
- e.currentTarget.style.color = FINCEPT.WHITE;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
- e.currentTarget.style.color = FINCEPT.GRAY;
+ display: 'flex',
+ gap: '4px',
+ marginBottom: '6px'
}}
>
- {item.cmd}
- </button>
+ <button
+ onClick={() => !isEditingPrompts && setMessageInput(item.prompt)}
+ disabled={isEditingPrompts}
+ style={{
+ flex: 1,
+ padding: '6px 10px',
+ backgroundColor: editingPromptIndex === index ? `${colors.primary}20` : 'transparent',
+ border: `1px solid ${editingPromptIndex === index ? colors.primary : 'rgba(255,255,255,0.1)'}`,
+ color: editingPromptIndex === index ? colors.primary : colors.textMuted,
+ fontSize: fontSize.small,
+ fontWeight: 700,
+ borderRadius: '2px',
+ textAlign: 'left',
+ cursor: isEditingPrompts ? 'default' : 'pointer',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s',
+ opacity: isEditingPrompts && editingPromptIndex !== index ? 0.5 : 1
+ }}
+ onMouseEnter={(e) => {
+ if (!isEditingPrompts) {
+ e.currentTarget.style.borderColor = colors.primary;
+ e.currentTarget.style.color = colors.text;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (!isEditingPrompts && editingPromptIndex !== index) {
+ e.currentTarget.style.borderColor = 'rgba(255,255,255,0.1)';
+ e.currentTarget.style.color = colors.textMuted;
+ }
+ }}
+ title={item.prompt}
+ >
+ {item.cmd}
+ </button>
+ {!isEditingPrompts && (
+ <button
+ onClick={() => startEditingPrompt(index)}
+ style={{
+ padding: '4px 6px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${'rgba(255,255,255,0.1)'}`,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = colors.warning;
+ e.currentTarget.style.color = colors.warning;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = 'rgba(255,255,255,0.1)';
+ e.currentTarget.style.color = colors.textMuted;
+ }}
+ title="Edit this prompt"
+ >
+ <Edit2 size={10} />
+ </button>
+ )}
+ </div>
))}
</div>
</div>
@@ -1942,13 +2192,13 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
<div style={{ flex: 1, overflow: 'auto' }}>
<div style={{
padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${'rgba(255,255,255,0.1)'}`
}}>
<span style={{
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 700,
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px'
}}>
{t('panel.systemInfo').toUpperCase()}
@@ -1958,8 +2208,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{activeLLMConfig ? (
<>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '9px',
+ color: colors.secondary,
+ fontSize: fontSize.small,
marginBottom: '4px',
letterSpacing: '0.5px',
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
@@ -1967,42 +2217,104 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
PROVIDER: {activeLLMConfig.provider.toUpperCase()}
</div>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '9px',
+ color: colors.secondary,
+ fontSize: fontSize.small,
marginBottom: '4px',
letterSpacing: '0.5px',
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}>
MODEL: {activeLLMConfig.model}
</div>
+ {/* Base URL - shown for Ollama or custom endpoints */}
+ {shouldShowBaseUrl() && activeLLMConfig.base_url && (
+ <div style={{
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ marginBottom: '4px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ wordBreak: 'break-all'
+ }}>
+ ENDPOINT: {activeLLMConfig.base_url}
+ </div>
+ )}
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '9px',
+ color: colors.secondary,
+ fontSize: fontSize.small,
marginBottom: '4px',
letterSpacing: '0.5px',
fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}>
- TEMP: {llmGlobalSettings.temperature}
+ TEMP: {llmGlobalSettings.temperature} | MAX TOKENS: {llmGlobalSettings.max_tokens}
</div>
- <div style={{
- padding: '2px 6px',
- backgroundColor: `${FINCEPT.GREEN}20`,
- color: FINCEPT.GREEN,
- fontSize: '8px',
- fontWeight: 700,
- borderRadius: '2px',
- display: 'inline-block',
- letterSpacing: '0.5px'
- }}>
- STREAMING: ENABLED
+ {/* Status badges row */}
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginBottom: '8px' }}>
+ {/* Streaming status */}
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: providerSupportsStreaming() ? `${colors.success}20` : `${colors.textMuted}20`,
+ color: providerSupportsStreaming() ? colors.success : colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ borderRadius: '2px',
+ letterSpacing: '0.5px'
+ }}>
+ STREAMING: {providerSupportsStreaming() ? 'ENABLED' : 'DISABLED'}
+ </div>
+ {/* API Key status */}
+ {(() => {
+ const apiKeyStatus = getApiKeyStatus();
+ if (!apiKeyStatus.required) {
+ return (
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: `${colors.secondary}20`,
+ color: colors.secondary,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ borderRadius: '2px',
+ letterSpacing: '0.5px'
+ }}>
+ API KEY: NOT REQUIRED
+ </div>
+ );
+ }
+ return (
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: apiKeyStatus.configured ? `${colors.success}20` : `${colors.alert}20`,
+ color: apiKeyStatus.configured ? colors.success : colors.alert,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ borderRadius: '2px',
+ letterSpacing: '0.5px'
+ }}>
+ API KEY: {apiKeyStatus.configured ? 'CONFIGURED' : 'MISSING'}
+ </div>
+ );
+ })()}
+ {/* Custom system prompt indicator */}
+ {hasCustomSystemPrompt() && (
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: `${colors.primary}20`,
+ color: colors.primary,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ borderRadius: '2px',
+ letterSpacing: '0.5px'
+ }}>
+ CUSTOM PROMPT: YES
+ </div>
+ )}
</div>
</>
) : (
<div style={{
padding: '2px 6px',
- backgroundColor: `${FINCEPT.RED}20`,
- color: FINCEPT.RED,
- fontSize: '8px',
+ backgroundColor: `${colors.alert}20`,
+ color: colors.alert,
+ fontSize: fontSize.tiny,
fontWeight: 700,
borderRadius: '2px',
letterSpacing: '0.5px'
@@ -2013,13 +2325,13 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
<div style={{
marginTop: '12px',
paddingTop: '12px',
- borderTop: `1px solid ${FINCEPT.BORDER}`
+ borderTop: `1px solid ${'rgba(255,255,255,0.1)'}`
}}>
<div style={{
padding: '2px 6px',
- backgroundColor: mcpToolsCount > 0 ? `${FINCEPT.CYAN}20` : `${FINCEPT.MUTED}20`,
- color: mcpToolsCount > 0 ? FINCEPT.CYAN : FINCEPT.MUTED,
- fontSize: '8px',
+ backgroundColor: mcpToolsCount > 0 ? `${colors.secondary}20` : `${colors.textMuted}20`,
+ color: mcpToolsCount > 0 ? colors.secondary : colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
borderRadius: '2px',
marginBottom: '8px',
@@ -2033,10 +2345,10 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
style={{
width: '100%',
padding: '8px 16px',
- backgroundColor: FINCEPT.ORANGE,
- color: FINCEPT.DARK_BG,
+ backgroundColor: colors.primary,
+ color: colors.background,
border: 'none',
- fontSize: '9px',
+ fontSize: fontSize.small,
fontWeight: 700,
borderRadius: '2px',
cursor: 'pointer',
@@ -2051,11 +2363,11 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{mcpToolsCount > 0 && !providerSupportsMCP() && activeLLMConfig && (
<div style={{
padding: '6px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.RED}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.alert}`,
borderRadius: '2px',
- color: FINCEPT.RED,
- fontSize: '8px',
+ color: colors.alert,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px'
}}>
@@ -2071,11 +2383,11 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Status Bar (Bottom) */}
<div style={{
- backgroundColor: FINCEPT.HEADER_BG,
- borderTop: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.panel,
+ borderTop: `1px solid ${'rgba(255,255,255,0.1)'}`,
padding: '4px 16px',
- fontSize: '9px',
- color: FINCEPT.GRAY,
+ fontSize: fontSize.small,
+ color: colors.textMuted,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
diff --git a/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx.backup b/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx.backup
new file mode 100644
index 000000000..9655e43eb
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx.backup
@@ -0,0 +1,2412 @@
+import React, { useState, useEffect, useRef, useCallback } from 'react';
+import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';
+import { flushSync } from 'react-dom';
+import { Settings, Trash2, Bot, User, Clock, Send, Plus, Search, Edit2, Check, X } from 'lucide-react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { useAuth } from '@/contexts/AuthContext';
+import { useBrokerContext } from '@/contexts/BrokerContext';
+import { useTranslation } from 'react-i18next';
+import { llmApiService, ChatMessage as APIMessage } from '@/services/chat/llmApi';
+import { sqliteService, ChatSession, ChatMessage, RecordedContext, LLMConfig, LLMGlobalSettings, ChatStatistics } from '@/services/core/sqliteService';
+import { contextRecorderService } from '@/services/data-sources/contextRecorderService';
+import { brokerMCPBridge } from '@/services/mcp/internal/BrokerMCPBridge';
+import { notesMCPBridge } from '@/services/mcp/internal/NotesMCPBridge';
+import MarkdownRenderer from '@/components/common/MarkdownRenderer';
+import ContextSelector from '@/components/common/ContextSelector';
+import FinancialSparklines from './FinancialSparklines';
+import { withTimeout } from '@/services/core/apiUtils';
+import { sanitizeInput } from '@/services/core/validators';
+import { ErrorBoundary } from '@/components/common/ErrorBoundary';
+import { showConfirm, showError } from '@/utils/notifications';
+
+// NOTE: All colors should use theme context
+// No hardcoded colors - use colors.* from useTerminalTheme()
+
+interface ChatTabProps {
+ onNavigateToSettings?: () => void;
+ onNavigateToTab?: (tabName: string) => void;
+}
+
+interface QuickPrompt {
+ cmd: string;
+ prompt: string;
+}
+
+// Constants
+const SESSION_CREATION_DELAY_MS = 100;
+const MAX_MESSAGES_IN_MEMORY = 200;
+const MCP_RETRY_INTERVAL_MS = 10000;
+const MCP_MAX_RETRIES = 5;
+const CLOCK_UPDATE_INTERVAL_MS = 1000;
+const MCP_SUPPORTED_PROVIDERS = ['openai', 'anthropic', 'gemini', 'google', 'groq', 'deepseek', 'openrouter', 'fincept'];
+const STREAMING_SUPPORTED_PROVIDERS = ['openai', 'anthropic', 'gemini', 'google', 'groq', 'deepseek', 'openrouter', 'ollama', 'fincept'];
+const NO_API_KEY_PROVIDERS = ['ollama', 'fincept']; // Providers that don't require API key
+const API_TIMEOUT_MS = 30000;
+const DB_TIMEOUT_MS = 10000;
+
+const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab }) => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
+ const auth = useAuth();
+ const { t } = useTranslation('chat');
+ const { activeAdapter, tradingMode, activeBroker } = useBrokerContext();
+ const [currentTime, setCurrentTime] = useState(new Date());
+ const [currentSessionUuid, setCurrentSessionUuid] = useState<string | null>(null);
+ const [messages, setMessages] = useState<ChatMessage[]>([]);
+ const [messageInput, setMessageInput] = useState('');
+ const [isTyping, setIsTyping] = useState(false);
+ const [sessions, setSessions] = useState<ChatSession[]>([]);
+ const [systemStatus, setSystemStatus] = useState('STATUS: INITIALIZING...');
+ const [streamingContent, setStreamingContent] = useState('');
+ const [statistics, setStatistics] = useState({ totalSessions: 0, totalMessages: 0, totalTokens: 0 });
+
+ // Workspace tab state - persist active session across workspace switches
+ const getWorkspaceState = useCallback(() => ({
+ currentSessionUuid: currentSessionUuid || null,
+ }), [currentSessionUuid]);
+
+ const setWorkspaceState = useCallback((state: Record<string, unknown>) => {
+ if (typeof state.currentSessionUuid === 'string') setCurrentSessionUuid(state.currentSessionUuid);
+ }, []);
+
+ useWorkspaceTabState('chat', getWorkspaceState, setWorkspaceState);
+ const [mcpToolsCount, setMcpToolsCount] = useState(0);
+ const [linkedContexts, setLinkedContexts] = useState<RecordedContext[]>([]);
+ const [activeToolCalls, setActiveToolCalls] = useState<Array<{ name: string; args: any; status: 'calling' | 'success' | 'error' }>>([]);
+ const [pendingChartData, setPendingChartData] = useState<any>(null);
+
+ // LLM Configuration state
+ const [activeLLMConfig, setActiveLLMConfig] = useState<LLMConfig | null>(null);
+ const [allLLMConfigs, setAllLLMConfigs] = useState<LLMConfig[]>([]);
+ const [llmGlobalSettings, setLLMGlobalSettings] = useState<LLMGlobalSettings>({
+ temperature: 0.7,
+ max_tokens: 4096,
+ system_prompt: ''
+ });
+ const [showLLMSelector, setShowLLMSelector] = useState(false);
+
+ // Quick Prompts state
+ const DEFAULT_QUICK_PROMPTS: QuickPrompt[] = [
+ { cmd: 'MARKET TRENDS', prompt: 'Analyze current market trends and key insights' },
+ { cmd: 'PORTFOLIO', prompt: 'Portfolio diversification recommendations' },
+ { cmd: 'RISK', prompt: 'Investment risk assessment strategies' },
+ { cmd: 'TECHNICAL', prompt: 'Key technical analysis indicators' }
+ ];
+ const [quickPrompts, setQuickPrompts] = useState<QuickPrompt[]>(DEFAULT_QUICK_PROMPTS);
+ const [isEditingPrompts, setIsEditingPrompts] = useState(false);
+ const [editingPromptIndex, setEditingPromptIndex] = useState<number | null>(null);
+ const [editPromptCmd, setEditPromptCmd] = useState('');
+ const [editPromptText, setEditPromptText] = useState('');
+
+ const handleContextsChange = (contexts: RecordedContext[]) => {
+ setLinkedContexts(contexts);
+ };
+
+ // Rename and search functionality
+ const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
+ const [renameValue, setRenameValue] = useState('');
+ const [searchQuery, setSearchQuery] = useState('');
+
+ const messagesEndRef = useRef<HTMLDivElement>(null);
+ const sessionsListRef = useRef<HTMLDivElement>(null);
+ const streamedContentRef = useRef<string>(''); // Track accumulated streaming content
+ const retryTimeoutsRef = useRef<Set<NodeJS.Timeout>>(new Set()); // Track pending retry timeouts
+ const llmSelectorRef = useRef<HTMLDivElement>(null);
+ const mountedRef = useRef(true); // Track component mount state for cleanup
+
+ // Check if current provider supports MCP tools
+ const providerSupportsMCP = () => {
+ if (!activeLLMConfig) return false;
+ return MCP_SUPPORTED_PROVIDERS.includes(activeLLMConfig.provider.toLowerCase());
+ };
+
+ // Check if current provider supports streaming
+ const providerSupportsStreaming = () => {
+ if (!activeLLMConfig) return false;
+ return STREAMING_SUPPORTED_PROVIDERS.includes(activeLLMConfig.provider.toLowerCase());
+ };
+
+ // Check if current provider requires API key and if it's configured
+ const getApiKeyStatus = (): { required: boolean; configured: boolean } => {
+ if (!activeLLMConfig) return { required: false, configured: false };
+ const provider = activeLLMConfig.provider.toLowerCase();
+ const required = !NO_API_KEY_PROVIDERS.includes(provider);
+ const configured = !required || (activeLLMConfig.api_key && activeLLMConfig.api_key.trim().length > 0);
+ return { required, configured: !!configured };
+ };
+
+ // Check if a custom system prompt is configured
+ const hasCustomSystemPrompt = () => {
+ return llmGlobalSettings.system_prompt && llmGlobalSettings.system_prompt.trim().length > 0;
+ };
+
+ // Check if base URL should be shown (for Ollama or custom endpoints)
+ const shouldShowBaseUrl = () => {
+ if (!activeLLMConfig) return false;
+ const provider = activeLLMConfig.provider.toLowerCase();
+ // Show for Ollama, or if a custom base_url is set
+ return provider === 'ollama' || (activeLLMConfig.base_url && activeLLMConfig.base_url.trim().length > 0);
+ };
+
+ // Cleanup on unmount
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
+
+ // Connect broker to MCP bridge
+ useEffect(() => {
+ if (activeAdapter) {
+ brokerMCPBridge.connect({
+ activeAdapter,
+ tradingMode,
+ activeBroker,
+ });
+ console.log(`[Chat MCP] Connected to ${activeBroker} in ${tradingMode} mode`);
+ }
+
+ return () => {
+ brokerMCPBridge.disconnect();
+ };
+ }, [activeAdapter, tradingMode, activeBroker]);
+
+ // Connect notes to MCP bridge
+ useEffect(() => {
+ notesMCPBridge.connect();
+ return () => {
+ notesMCPBridge.disconnect();
+ };
+ }, []);
+
+ // Initialize database on mount
+ useEffect(() => {
+ const initDatabase = async () => {
+ try {
+ setSystemStatus('STATUS: INITIALIZING DATABASE...');
+
+ // Initialize database
+ await sqliteService.initialize();
+
+ // Verify database health
+ const healthCheck = await sqliteService.healthCheck();
+ if (!healthCheck.healthy) {
+ throw new Error(healthCheck.message);
+ }
+
+ // Ensure default LLM configs exist
+ await sqliteService.ensureDefaultLLMConfigs();
+
+ // Load initial data
+ await loadSessions();
+ await loadStatistics();
+ await loadLLMConfiguration();
+ await loadMCPToolsCount();
+
+ setSystemStatus('STATUS: READY');
+ } catch (error) {
+ console.error('Database initialization error:', error);
+ const errorMsg = error instanceof Error ? error.message : 'Unknown error';
+ setSystemStatus(`ERROR: ${errorMsg}`);
+ }
+ };
+
+ initDatabase();
+
+ // Note: Don't close database on unmount as it's shared across tabs
+ // The database connection is managed as a singleton
+ }, []);
+
+ // Update clock
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setCurrentTime(new Date());
+ }, CLOCK_UPDATE_INTERVAL_MS);
+ return () => clearInterval(timer);
+ }, []);
+
+ // Periodically check for MCP tools updates
+ useEffect(() => {
+ const mcpCheckInterval = setInterval(() => {
+ loadMCPToolsCount();
+ }, MCP_RETRY_INTERVAL_MS);
+
+ return () => {
+ clearInterval(mcpCheckInterval);
+ // Clear all pending retry timeouts on unmount
+ retryTimeoutsRef.current.forEach(clearTimeout);
+ retryTimeoutsRef.current.clear();
+ };
+ }, []);
+
+ // Auto-scroll to bottom
+ useEffect(() => {
+ scrollToBottom();
+ }, [messages, streamingContent]);
+
+ // Click outside to close LLM selector
+ useEffect(() => {
+ const handleClickOutside = (event: MouseEvent) => {
+ if (llmSelectorRef.current && !llmSelectorRef.current.contains(event.target as Node)) {
+ setShowLLMSelector(false);
+ }
+ };
+
+ if (showLLMSelector) {
+ document.addEventListener('mousedown', handleClickOutside);
+ }
+
+ return () => {
+ document.removeEventListener('mousedown', handleClickOutside);
+ };
+ }, [showLLMSelector]);
+
+ const scrollToBottom = () => {
+ messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
+ };
+
+ const loadSessions = useCallback(async () => {
+ try {
+ const loadedSessions = await withTimeout(
+ sqliteService.getChatSessions(),
+ DB_TIMEOUT_MS,
+ 'Load sessions timeout'
+ );
+ if (!mountedRef.current) return;
+ setSessions(loadedSessions);
+ } catch (error) {
+ if (!mountedRef.current) return;
+ console.error('Failed to load sessions:', error);
+ }
+ }, []);
+
+ const loadStatistics = useCallback(async () => {
+ try {
+ // Optimized: Use SQL aggregation instead of loading all messages
+ const stats = await withTimeout(
+ sqliteService.getChatStatistics(),
+ DB_TIMEOUT_MS,
+ 'Load statistics timeout'
+ );
+ if (!mountedRef.current) return;
+ setStatistics(stats);
+ } catch (error) {
+ if (!mountedRef.current) return;
+ console.error('[ChatTab] Failed to load statistics:', error);
+ // Fallback to basic count
+ try {
+ const sessions = await sqliteService.getChatSessions(1000);
+ if (!mountedRef.current) return;
+ setStatistics({
+ totalSessions: sessions.length,
+ totalMessages: 0,
+ totalTokens: 0
+ });
+ } catch (fallbackError) {
+ console.error('[ChatTab] Fallback statistics also failed:', fallbackError);
+ }
+ }
+ }, []);
+
+ const loadLLMConfiguration = useCallback(async () => {
+ try {
+ const [activeConfig, globalSettings, allConfigs] = await withTimeout(
+ Promise.all([
+ sqliteService.getActiveLLMConfig(),
+ sqliteService.getLLMGlobalSettings(),
+ sqliteService.getLLMConfigs()
+ ]),
+ DB_TIMEOUT_MS,
+ 'Load LLM configuration timeout'
+ );
+
+ if (!mountedRef.current) return;
+
+ setActiveLLMConfig(activeConfig);
+ setAllLLMConfigs(allConfigs);
+ setLLMGlobalSettings(globalSettings);
+
+ if (!activeConfig) {
+ setSystemStatus('WARNING: No active LLM provider configured');
+ }
+ } catch (error) {
+ if (!mountedRef.current) return;
+ console.error('[ChatTab] Failed to load LLM configuration:', error);
+ setSystemStatus('ERROR: Failed to load LLM configuration');
+ }
+ }, []);
+
+ // Listen for LLM configuration changes from Settings tab
+ useEffect(() => {
+ const handleLLMConfigChange = () => {
+ console.log('[ChatTab] LLM configuration changed, reloading...');
+ loadLLMConfiguration();
+ };
+
+ window.addEventListener('llm-config-changed', handleLLMConfigChange);
+ return () => {
+ window.removeEventListener('llm-config-changed', handleLLMConfigChange);
+ };
+ }, [loadLLMConfiguration]);
+
+ // Load quick prompts from database
+ const loadQuickPrompts = useCallback(async () => {
+ try {
+ const savedPrompts = await sqliteService.getSetting('chat_quick_prompts');
+ if (savedPrompts) {
+ const parsed = JSON.parse(savedPrompts);
+ if (Array.isArray(parsed) && parsed.length > 0) {
+ setQuickPrompts(parsed);
+ }
+ }
+ } catch (error) {
+ console.error('[ChatTab] Failed to load quick prompts:', error);
+ // Keep default prompts on error
+ }
+ }, []);
+
+ // Save quick prompts to database
+ const saveQuickPrompts = useCallback(async (prompts: QuickPrompt[]) => {
+ try {
+ await sqliteService.saveSetting('chat_quick_prompts', JSON.stringify(prompts), 'chat');
+ setQuickPrompts(prompts);
+ } catch (error) {
+ console.error('[ChatTab] Failed to save quick prompts:', error);
+ }
+ }, []);
+
+ // Quick prompt editing handlers
+ const startEditingPrompt = (index: number) => {
+ setEditingPromptIndex(index);
+ setEditPromptCmd(quickPrompts[index].cmd);
+ setEditPromptText(quickPrompts[index].prompt);
+ setIsEditingPrompts(true);
+ };
+
+ const saveEditedPrompt = async () => {
+ if (editingPromptIndex === null || !editPromptCmd.trim() || !editPromptText.trim()) return;
+
+ const newPrompts = [...quickPrompts];
+ newPrompts[editingPromptIndex] = {
+ cmd: editPromptCmd.trim().toUpperCase(),
+ prompt: editPromptText.trim()
+ };
+ await saveQuickPrompts(newPrompts);
+ setEditingPromptIndex(null);
+ setIsEditingPrompts(false);
+ };
+
+ const cancelEditingPrompt = () => {
+ setEditingPromptIndex(null);
+ setIsEditingPrompts(false);
+ setEditPromptCmd('');
+ setEditPromptText('');
+ };
+
+ const resetQuickPrompts = async () => {
+ await saveQuickPrompts(DEFAULT_QUICK_PROMPTS);
+ };
+
+ // Load quick prompts on mount
+ useEffect(() => {
+ loadQuickPrompts();
+ }, [loadQuickPrompts]);
+
+ const switchLLMProvider = useCallback(async (provider: string) => {
+ try {
+ setSystemStatus('STATUS: SWITCHING LLM PROVIDER...');
+ await withTimeout(
+ sqliteService.setActiveLLMProvider(provider),
+ DB_TIMEOUT_MS,
+ 'Switch provider timeout'
+ );
+ if (!mountedRef.current) return;
+ await loadLLMConfiguration();
+ if (!mountedRef.current) return;
+ setShowLLMSelector(false);
+ setSystemStatus('STATUS: READY');
+ console.log(`[ChatTab] Switched to LLM provider: ${provider}`);
+ } catch (error) {
+ if (!mountedRef.current) return;
+ console.error('[ChatTab] Failed to switch LLM provider:', error);
+ setSystemStatus('ERROR: Failed to switch provider');
+ }
+ }, [loadLLMConfiguration]);
+
+ const loadMCPToolsCount = async (retryCount = 0, maxRetries = MCP_MAX_RETRIES) => {
+ try {
+ const { mcpToolService } = await import('@/services/mcp/mcpToolService');
+ const tools = await mcpToolService.getAllTools();
+ setMcpToolsCount(tools.length);
+
+ if (tools.length === 0 && retryCount < maxRetries) {
+ const delay = Math.min(1000 * Math.pow(2, retryCount), MCP_RETRY_INTERVAL_MS);
+ const timeoutId = setTimeout(() => {
+ retryTimeoutsRef.current.delete(timeoutId);
+ loadMCPToolsCount(retryCount + 1, maxRetries);
+ }, delay);
+ retryTimeoutsRef.current.add(timeoutId);
+ }
+ } catch (error) {
+ setMcpToolsCount(0);
+ }
+ };
+
+ const loadSessionMessages = async (sessionUuid: string) => {
+ try {
+ setSystemStatus('STATUS: LOADING MESSAGES...');
+ const loadedMessages = await sqliteService.getChatMessages(sessionUuid);
+ setMessages(loadedMessages.slice(-MAX_MESSAGES_IN_MEMORY));
+ setSystemStatus('STATUS: READY');
+ } catch (error) {
+ console.error('[ChatTab] Failed to load messages:', error);
+ setSystemStatus('ERROR: Failed to load messages');
+ }
+ };
+
+ const generateSmartTitle = (message: string): string => {
+ // Clean the message but keep important characters
+ const trimmed = message.trim();
+
+ if (!trimmed) {
+ const now = new Date();
+ return `Chat ${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
+ }
+
+ // Extract keywords from common patterns
+ const lowerMsg = trimmed.toLowerCase();
+
+ // Check for common financial terms
+ const financialKeywords = [
+ 'market', 'stock', 'portfolio', 'risk', 'analysis',
+ 'trend', 'trading', 'investment', 'price', 'strategy',
+ 'forecast', 'data', 'chart', 'indicator', 'technical'
+ ];
+
+ const foundKeyword = financialKeywords.find(kw => lowerMsg.includes(kw));
+ if (foundKeyword) {
+ return foundKeyword.charAt(0).toUpperCase() + foundKeyword.slice(1) + ' Chat';
+ }
+
+ // Check for question words
+ if (lowerMsg.startsWith('what')) return 'What Query';
+ if (lowerMsg.startsWith('how')) return 'How To';
+ if (lowerMsg.startsWith('why')) return 'Why Question';
+ if (lowerMsg.startsWith('when')) return 'When Query';
+ if (lowerMsg.startsWith('where')) return 'Where Query';
+ if (lowerMsg.startsWith('analyze')) return 'Analysis';
+ if (lowerMsg.startsWith('explain')) return 'Explanation';
+ if (lowerMsg.startsWith('compare')) return 'Comparison';
+ if (lowerMsg.startsWith('calculate')) return 'Calculation';
+ if (lowerMsg.startsWith('show') || lowerMsg.startsWith('get')) return 'Data Request';
+
+ // Extract first 2-3 meaningful words (max 20 chars)
+ const words = trimmed.split(/\s+/).filter(w => w.length > 2);
+ if (words.length === 0) {
+ const now = new Date();
+ return `Chat ${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
+ }
+
+ let title = words.slice(0, 2).join(' ');
+ if (title.length > 20) {
+ title = title.substring(0, 20);
+ }
+
+ return title;
+ };
+
+ const createNewSession = useCallback(async (): Promise<string | null> => {
+ try {
+ const title = messageInput.trim() ?
+ generateSmartTitle(messageInput) :
+ `Chat ${new Date().toLocaleString()}`;
+
+ const newSession = await withTimeout(
+ sqliteService.createChatSession(title),
+ DB_TIMEOUT_MS,
+ 'Create session timeout'
+ );
+ if (!mountedRef.current) return null;
+ setSessions(prev => [newSession, ...prev]);
+ setCurrentSessionUuid(newSession.session_uuid);
+ setMessages([]);
+ await loadStatistics();
+ if (!mountedRef.current) return null;
+ setSystemStatus('STATUS: NEW SESSION CREATED');
+ return newSession.session_uuid;
+ } catch (error) {
+ if (!mountedRef.current) return null;
+ console.error('Failed to create session:', error);
+ setSystemStatus('ERROR: Failed to create session');
+ return null;
+ }
+ }, [messageInput, loadStatistics]);
+
+ const selectSession = useCallback(async (sessionUuid: string) => {
+ setCurrentSessionUuid(sessionUuid);
+ await loadSessionMessages(sessionUuid);
+ }, []);
+
+ const deleteSession = useCallback(async (sessionUuid: string) => {
+ try {
+ await withTimeout(
+ sqliteService.deleteChatSession(sessionUuid),
+ DB_TIMEOUT_MS,
+ 'Delete session timeout'
+ );
+ if (!mountedRef.current) return;
+ setSessions(prev => prev.filter(s => s.session_uuid !== sessionUuid));
+ if (currentSessionUuid === sessionUuid) {
+ setCurrentSessionUuid(null);
+ setMessages([]);
+ }
+ await loadStatistics();
+ if (!mountedRef.current) return;
+ setSystemStatus('STATUS: SESSION DELETED');
+ } catch (error) {
+ if (!mountedRef.current) return;
+ console.error('Failed to delete session:', error);
+ setSystemStatus('ERROR: Failed to delete session');
+ }
+ }, [currentSessionUuid, loadStatistics]);
+
+ const startRenaming = useCallback((sessionUuid: string, currentTitle: string) => {
+ setRenamingSessionId(sessionUuid);
+ setRenameValue(currentTitle);
+ }, []);
+
+ const saveRename = useCallback(async (sessionUuid: string) => {
+ const sanitizedName = sanitizeInput(renameValue);
+ if (!sanitizedName.trim()) {
+ setRenamingSessionId(null);
+ return;
+ }
+
+ try {
+ await withTimeout(
+ sqliteService.updateChatSessionTitle(sessionUuid, sanitizedName.trim()),
+ DB_TIMEOUT_MS,
+ 'Rename session timeout'
+ );
+ if (!mountedRef.current) return;
+ setSessions(prev => prev.map(s =>
+ s.session_uuid === sessionUuid ? { ...s, title: sanitizedName.trim() } : s
+ ));
+ setRenamingSessionId(null);
+ setSystemStatus('STATUS: SESSION RENAMED');
+ } catch (error) {
+ if (!mountedRef.current) return;
+ console.error('Failed to rename session:', error);
+ setSystemStatus('ERROR: Failed to rename session');
+ }
+ }, [renameValue]);
+
+ const cancelRename = useCallback(() => {
+ setRenamingSessionId(null);
+ setRenameValue('');
+ }, []);
+
+ const clearCurrentChat = useCallback(async () => {
+ if (!currentSessionUuid) return;
+
+ try {
+ await withTimeout(
+ sqliteService.clearChatSessionMessages(currentSessionUuid),
+ DB_TIMEOUT_MS,
+ 'Clear chat timeout'
+ );
+ if (!mountedRef.current) return;
+ setMessages([]);
+ await loadSessions();
+ await loadStatistics();
+ if (!mountedRef.current) return;
+ setSystemStatus('STATUS: CHAT CLEARED');
+ } catch (error) {
+ if (!mountedRef.current) return;
+ console.error('Failed to clear chat:', error);
+ setSystemStatus('ERROR: Failed to clear chat');
+ }
+ }, [currentSessionUuid, loadSessions, loadStatistics]);
+
+ const deleteAllSessions = useCallback(async () => {
+ const confirmed = await showConfirm('This action cannot be undone.', {
+ title: 'Delete ALL sessions and messages?',
+ type: 'danger'
+ });
+ if (!confirmed) {
+ return;
+ }
+
+ try {
+ for (const session of sessions) {
+ await sqliteService.deleteChatSession(session.session_uuid);
+ if (!mountedRef.current) return;
+ }
+ setSessions([]);
+ setMessages([]);
+ setCurrentSessionUuid(null);
+ await loadStatistics();
+ if (!mountedRef.current) return;
+ setSystemStatus('STATUS: ALL SESSIONS DELETED');
+ } catch (error) {
+ if (!mountedRef.current) return;
+ console.error('Failed to delete all sessions:', error);
+ setSystemStatus('ERROR: Failed to delete all sessions');
+ }
+ }, [sessions, loadStatistics]);
+
+ // Helper functions for handleSendMessage
+ const validateLLMConfiguration = (): { valid: boolean; error?: string } => {
+ if (!activeLLMConfig) {
+ return {
+ valid: false,
+ error: 'No LLM provider is configured.\n\nPlease go to Settings → LLM Configuration to set up a provider.'
+ };
+ }
+
+ // Providers that don't require API key
+ const noApiKeyProviders = ['ollama', 'fincept'];
+ const requiresApiKey = !noApiKeyProviders.includes(activeLLMConfig.provider.toLowerCase());
+
+ if (requiresApiKey && !activeLLMConfig.api_key) {
+ const providerName = activeLLMConfig.provider.charAt(0).toUpperCase() + activeLLMConfig.provider.slice(1);
+ return {
+ valid: false,
+ error: `${providerName} requires an API key.\n\nPlease go to Settings → LLM Configuration to add your ${providerName} API key.`
+ };
+ }
+
+ return { valid: true };
+ };
+
+ const ensureSessionExists = async (): Promise<string | null> => {
+ if (currentSessionUuid) {
+ return currentSessionUuid;
+ }
+
+ // createNewSession now returns the UUID directly, no need to wait for state update
+ const newSessionUuid = await createNewSession();
+ return newSessionUuid;
+ };
+
+ const buildConversationHistory = (): APIMessage[] => {
+ return messages.map(msg => ({
+ role: msg.role as 'system' | 'user' | 'assistant',
+ content: msg.content
+ }));
+ };
+
+ const addContextToConversation = async (conversationHistory: APIMessage[]): Promise<void> => {
+ if (linkedContexts.length === 0) {
+ console.log('[ChatTab] No active contexts linked');
+ return;
+ }
+
+ console.log('[ChatTab] Active contexts linked:', linkedContexts.length);
+ const contextIds = linkedContexts.map(ctx => ctx.id);
+ const contextData = await contextRecorderService.formatMultipleContexts(contextIds, 'markdown');
+
+ const systemMessage: APIMessage = {
+ role: 'system' as const,
+ content: `The following recorded data contexts are provided for your reference:\n\n${contextData}\n\n---\n\nPlease use this information to help answer the user's questions.`
+ };
+
+ conversationHistory.unshift(systemMessage);
+ console.log('[ChatTab] System message with context added to conversation');
+ };
+
+ const getMCPTools = async (): Promise<any[]> => {
+ try {
+ const { mcpToolService } = await import('@/services/mcp/mcpToolService');
+ return await mcpToolService.getAllTools();
+ } catch (error) {
+ return [];
+ }
+ };
+
+ const handleStreamingCallback = (chunk: string, done: boolean) => {
+ if (!done) {
+ streamedContentRef.current += chunk;
+ flushSync(() => {
+ setStreamingContent(prev => prev + chunk);
+ });
+ } else {
+ flushSync(() => {
+ setIsTyping(false);
+ setStreamingContent('');
+ setSystemStatus('STATUS: READY');
+ });
+ }
+ };
+
+ const handleToolCallback = (toolName: string, args: any, result?: any) => {
+ if (!result) {
+ // Tool call started
+ console.log(`[Tool Call] ${toolName}`, args);
+ setSystemStatus(`STATUS: Calling ${toolName}...`);
+ setActiveToolCalls(prev => [...prev, { name: toolName, args, status: 'calling' }]);
+ } else {
+ // Tool call completed
+ console.log(`[Tool Result] ${toolName}`, result);
+ setSystemStatus('STATUS: Processing response...');
+ setActiveToolCalls(prev =>
+ prev.map(call =>
+ call.name === toolName && call.status === 'calling'
+ ? { ...call, status: result.error ? 'error' : 'success' }
+ : call
+ )
+ );
+
+ // Store chart data for financial tools
+ if (result.chart_data) {
+ console.log('[ChatTab] Chart data received:', result.chart_data);
+ setPendingChartData({
+ data: result.chart_data,
+ ticker: result.ticker,
+ company: result.company
+ });
+ }
+
+ // Check if a report was created and schedule navigation after completion
+ if (toolName === 'create_report_template' && result?.id) {
+ (window as any).__navigateToReportBuilder = true;
+ }
+ }
+ };
+
+ const saveAssistantMessage = async (sessionUuid: string, content: string, usage?: any): Promise<void> => {
+ if (!activeLLMConfig) return;
+
+ // Save message with chart data if available
+ const chartData = pendingChartData;
+
+ const aiMessage = await sqliteService.addChatMessage({
+ session_uuid: sessionUuid,
+ role: 'assistant',
+ content,
+ provider: activeLLMConfig.provider,
+ model: activeLLMConfig.model,
+ tokens_used: usage?.totalTokens,
+ tool_calls: activeToolCalls.length > 0 ? activeToolCalls.map(call => ({
+ name: call.name,
+ args: call.args,
+ timestamp: new Date().toISOString(),
+ status: call.status
+ })) : undefined,
+ metadata: chartData ? { chart_data: chartData.data, ticker: chartData.ticker, company: chartData.company } : undefined
+ });
+
+ setMessages(prev => [...prev, aiMessage]);
+ setActiveToolCalls([]);
+ setPendingChartData(null);
+ };
+
+ const saveErrorMessage = async (sessionUuid: string, error: string): Promise<void> => {
+ const errorMessage = await sqliteService.addChatMessage({
+ session_uuid: sessionUuid,
+ role: 'assistant',
+ content: `[ERROR] ${error}\n\nPlease check your LLM configuration and try again.`
+ });
+
+ setMessages(prev => [...prev, errorMessage]);
+ };
+
+ const handleSendMessage = useCallback(async () => {
+ // Sanitize user input
+ const sanitizedInput = sanitizeInput(messageInput);
+ if (!sanitizedInput.trim()) return;
+
+ // Validate LLM configuration
+ const validation = validateLLMConfiguration();
+ if (!validation.valid) {
+ setSystemStatus('ERROR: Invalid LLM configuration');
+ showError('Invalid LLM configuration', [
+ { label: 'ERROR', value: validation.error || 'Unknown error' }
+ ]);
+ onNavigateToSettings?.();
+ return;
+ }
+
+ // Ensure session exists
+ const sessionUuid = await ensureSessionExists();
+ if (!sessionUuid) {
+ setSystemStatus('ERROR: Failed to create session');
+ return;
+ }
+
+ const userContent = sanitizedInput.trim();
+ setMessageInput('');
+ setIsTyping(true);
+ setStreamingContent('');
+ setSystemStatus(`STATUS: CALLING ${activeLLMConfig!.provider.toUpperCase()} API...`);
+
+ try {
+ // Save user message
+ const userMessage = await sqliteService.addChatMessage({
+ session_uuid: sessionUuid,
+ role: 'user',
+ content: userContent
+ });
+ setMessages(prev => [...prev, userMessage]);
+
+ // Build conversation history
+ const conversationHistory = buildConversationHistory();
+
+ // Add linked contexts if any
+ await addContextToConversation(conversationHistory);
+
+ // Get MCP tools
+ const mcpTools = await getMCPTools();
+ console.log(`[Chat] MCP Tools available: ${mcpTools.length}`, mcpTools.map(t => t.name));
+
+ // Reset streaming reference
+ streamedContentRef.current = '';
+
+ // Call LLM API
+ const response = mcpTools.length > 0
+ ? await llmApiService.chatWithTools(
+ userContent,
+ conversationHistory,
+ mcpTools,
+ handleStreamingCallback,
+ handleToolCallback
+ )
+ : await llmApiService.chat(
+ userContent,
+ conversationHistory,
+ handleStreamingCallback
+ );
+
+ // Handle response
+ if (response.error) {
+ await saveErrorMessage(sessionUuid, response.error);
+ setSystemStatus(`ERROR: ${response.error}`);
+ } else {
+ const contentToSave = response.content || streamedContentRef.current || '(No response generated)';
+ await saveAssistantMessage(sessionUuid, contentToSave, response.usage);
+ streamedContentRef.current = '';
+ }
+
+ // Update UI state
+ setIsTyping(false);
+ setStreamingContent('');
+
+ // Reload data
+ await Promise.all([
+ loadSessions(),
+ loadStatistics(),
+ auth.refreshUserData()
+ ]);
+
+ // Check if we should navigate to report builder (after everything is done)
+ if ((window as any).__navigateToReportBuilder && onNavigateToTab) {
+ (window as any).__navigateToReportBuilder = false;
+ // Small delay to ensure message is saved and UI is stable
+ setTimeout(() => {
+ onNavigateToTab('report-builder');
+ }, 500);
+ }
+
+ } catch (error) {
+ if (!mountedRef.current) return;
+ console.error('[ChatTab] Send message error:', error);
+ await saveErrorMessage(
+ sessionUuid,
+ `Unexpected error: ${error instanceof Error ? error.message : 'Unknown error'}`
+ );
+ setIsTyping(false);
+ setStreamingContent('');
+ setSystemStatus('ERROR: Request failed');
+ }
+ }, [messageInput, activeLLMConfig, onNavigateToSettings, onNavigateToTab, loadSessions, loadStatistics, auth]);
+
+ // Filter sessions by search query (searches in both title and message content)
+ const filteredSessions = searchQuery
+ ? sessions.filter(session =>
+ session.title.toLowerCase().includes(searchQuery.toLowerCase())
+ )
+ : sessions;
+
+ const formatTime = (date: Date | string | undefined) => {
+ if (!date) return '00:00:00';
+ try {
+ const d = typeof date === 'string' ? new Date(date) : date;
+ if (isNaN(d.getTime())) return '00:00:00';
+ return d.toLocaleTimeString('en-US', {
+ hour12: false,
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit'
+ });
+ } catch (error) {
+ console.error('Error formatting time:', error, date);
+ return '00:00:00';
+ }
+ };
+
+ const formatSessionTime = (dateString: string | undefined) => {
+ if (!dateString) return '00:00';
+ try {
+ const date = new Date(dateString);
+ if (isNaN(date.getTime())) return '00:00';
+
+ const now = new Date();
+ const diffHours = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60));
+
+ if (diffHours < 24) {
+ return date.toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' });
+ } else if (diffHours < 168) { // Less than a week
+ return date.toLocaleDateString('en-US', { weekday: 'short', hour: '2-digit', minute: '2-digit' });
+ } else {
+ return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
+ }
+ } catch (error) {
+ console.error('Error formatting session time:', error, dateString);
+ return '00:00';
+ }
+ };
+
+ const renderWelcomeScreen = () => (
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ backgroundColor: colors.background
+ }}>
+ <div style={{
+ textAlign: 'center',
+ padding: '24px',
+ maxWidth: '400px'
+ }}>
+ <Bot size={48} color={colors.primary} style={{ marginBottom: '16px', opacity: 0.8 }} />
+ <div style={{
+ color: colors.primary,
+ fontSize: fontSize.heading,
+ fontWeight: 700,
+ marginBottom: '8px',
+ letterSpacing: '0.5px'
+ }}>
+ {t('title').toUpperCase()}
+ </div>
+ <div style={{
+ color: colors.text,
+ fontSize: fontSize.body,
+ marginBottom: '16px',
+ lineHeight: '1.5'
+ }}>
+ {t('subtitle')}
+ </div>
+ <div style={{
+ padding: '6px 12px',
+ backgroundColor: `${colors.warning}20`,
+ color: colors.warning,
+ fontSize: fontSize.small,
+ fontWeight: 700,
+ borderRadius: '2px',
+ marginBottom: '16px',
+ display: 'inline-block',
+ letterSpacing: '0.5px'
+ }}>
+ PROVIDER: {activeLLMConfig?.provider.toUpperCase() || 'NONE'} | MODEL: {activeLLMConfig?.model || 'N/A'}
+ </div>
+ <br />
+ <button
+ onClick={createNewSession}
+ style={{
+ padding: '8px 16px',
+ backgroundColor: colors.primary,
+ color: colors.background,
+ border: 'none',
+ fontSize: fontSize.small,
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ >
+ {t('header.newChat').toUpperCase()}
+ </button>
+ </div>
+ </div>
+ );
+
+ const renderMessage = (message: ChatMessage) => {
+ try {
+ return (
+ <div key={message.id} style={{ marginBottom: '12px' }}>
+ <div style={{
+ display: 'flex',
+ justifyContent: message.role === 'user' ? 'flex-end' : 'flex-start',
+ marginBottom: '4px'
+ }}>
+ <div style={{
+ maxWidth: '85%',
+ minWidth: '120px',
+ backgroundColor: colors.panel,
+ border: `1px solid ${message.role === 'user' ? colors.warning : colors.primary}`,
+ borderRadius: '2px',
+ padding: '10px'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '8px',
+ paddingBottom: '6px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ {message.role === 'user' ? (
+ <User size={12} color={FINCEPT.YELLOW} />
+ ) : (
+ <Bot size={12} color={FINCEPT.ORANGE} />
+ )}
+ <span style={{
+ color: message.role === 'user' ? FINCEPT.YELLOW : FINCEPT.ORANGE,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>
+ {message.role === 'user' ? 'YOU' : 'AI'}
+ </span>
+ <Clock size={10} color={FINCEPT.GRAY} />
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {formatTime(message.timestamp)}
+ </span>
+ {message.provider && (
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px'
+ }}>
+ | {message.provider.toUpperCase()}
+ </span>
+ )}
+ </div>
+ {/* Tool calls indicator - like Perplexity sources */}
+ {message.tool_calls && message.tool_calls.length > 0 && (
+ <div style={{
+ marginBottom: '12px',
+ padding: '8px 12px',
+ background: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: '6px',
+ alignItems: 'center'
+ }}>
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>
+ Tools Used:
+ </span>
+ {message.tool_calls.map((tool, idx) => (
+ <div
+ key={idx}
+ style={{
+ padding: '4px 8px',
+ background: tool.status === 'success' ? FINCEPT.GREEN + '20' :
+ tool.status === 'error' ? FINCEPT.RED + '20' : FINCEPT.ORANGE + '20',
+ border: `1px solid ${tool.status === 'success' ? FINCEPT.GREEN :
+ tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE}`,
+ borderRadius: '3px',
+ fontSize: '9px',
+ color: tool.status === 'success' ? FINCEPT.GREEN :
+ tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE,
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <span style={{ fontSize: '8px' }}>
+ {tool.status === 'success' ? '✓' : tool.status === 'error' ? '✗' : '⋯'}
+ </span>
+ {tool.name.replace('edgar_', '').replace(/_/g, ' ')}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {message.role === 'assistant' && message.content ? (
+ <>
+ <MarkdownRenderer content={message.content} />
+ {message.metadata?.chart_data && (
+ <FinancialSparklines
+ data={message.metadata.chart_data}
+ ticker={message.metadata.ticker}
+ company={message.metadata.company}
+ responseText={message.content}
+ />
+ )}
+ </>
+ ) : (
+ <div style={{
+ color: FINCEPT.WHITE,
+ fontSize: '11px',
+ lineHeight: '1.6',
+ whiteSpace: 'pre-wrap',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {message.content || '(Empty message)'}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ } catch (error) {
+ console.error('Error rendering message:', error, message);
+ return (
+ <div key={message.id} style={{
+ marginBottom: '12px',
+ color: FINCEPT.RED,
+ fontSize: '10px',
+ letterSpacing: '0.5px'
+ }}>
+ ERROR RENDERING MESSAGE
+ </div>
+ );
+ }
+ };
+
+ const renderStreamingMessage = () => {
+ if (!streamingContent && activeToolCalls.length === 0) return null;
+
+ return (
+ <div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'flex-start' }}>
+ <div style={{
+ maxWidth: '85%',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `2px solid ${FINCEPT.ORANGE}`,
+ borderRadius: '2px',
+ padding: '10px'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '8px',
+ paddingBottom: '6px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <Bot
+ size={12}
+ color={FINCEPT.ORANGE}
+ style={{ animation: 'spin 2s linear infinite' }}
+ />
+ <span style={{
+ color: FINCEPT.ORANGE,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ animation: 'fadeInOut 1.5s ease-in-out infinite'
+ }}>
+ {t('messages.typing').toUpperCase()}
+ </span>
+ <span style={{
+ color: FINCEPT.ORANGE,
+ fontSize: '9px',
+ animation: 'dots 1.5s steps(4, end) infinite'
+ }}>
+ <span>.</span>
+ <span>.</span>
+ <span>.</span>
+ </span>
+ </div>
+
+ {/* Live tool calls - Perplexity-style */}
+ {activeToolCalls.length > 0 && (
+ <div style={{
+ marginBottom: streamingContent ? '12px' : '0',
+ padding: '8px 12px',
+ background: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: '6px',
+ alignItems: 'center'
+ }}>
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>
+ Calling:
+ </span>
+ {activeToolCalls.map((tool, idx) => (
+ <div
+ key={idx}
+ style={{
+ padding: '4px 8px',
+ background: tool.status === 'success' ? FINCEPT.GREEN + '20' :
+ tool.status === 'error' ? FINCEPT.RED + '20' : FINCEPT.ORANGE + '20',
+ border: `1px solid ${tool.status === 'success' ? FINCEPT.GREEN :
+ tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE}`,
+ borderRadius: '3px',
+ fontSize: '9px',
+ color: tool.status === 'success' ? FINCEPT.GREEN :
+ tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE,
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ animation: tool.status === 'calling' ? 'pulse 1.5s infinite' : 'none'
+ }}
+ >
+ <span style={{ fontSize: '8px' }}>
+ {tool.status === 'success' ? '✓' : tool.status === 'error' ? '✗' : '⋯'}
+ </span>
+ {tool.name.replace('edgar_', '').replace('stock_', '').replace(/_/g, ' ')}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {streamingContent && (
+ <div style={{
+ color: FINCEPT.WHITE,
+ fontSize: '11px',
+ lineHeight: '1.6',
+ whiteSpace: 'pre-wrap',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {streamingContent}
+ <span style={{
+ color: FINCEPT.ORANGE,
+ animation: 'blink 1s infinite'
+ }}>▊</span>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ <style>{`
+ /* Scrollbar styling per design system */
+ *::-webkit-scrollbar {
+ width: 6px;
+ height: 6px;
+ }
+ *::-webkit-scrollbar-track {
+ background: ${FINCEPT.DARK_BG};
+ }
+ *::-webkit-scrollbar-thumb {
+ background: ${FINCEPT.BORDER};
+ border-radius: 3px;
+ }
+ *::-webkit-scrollbar-thumb:hover {
+ background: ${FINCEPT.MUTED};
+ }
+ /* For Firefox */
+ * {
+ scrollbar-width: thin;
+ scrollbar-color: ${FINCEPT.BORDER} ${FINCEPT.DARK_BG};
+ }
+ /* Input focus states */
+ input:focus, textarea:focus {
+ outline: none;
+ border-color: ${FINCEPT.ORANGE} !important;
+ }
+ /* Blink animation for cursor */
+ @keyframes blink {
+ 0%, 50% { opacity: 1; }
+ 51%, 100% { opacity: 0; }
+ }
+ @keyframes pulse {
+ 0%, 100% { opacity: 0.6; transform: scale(1); }
+ 50% { opacity: 1; transform: scale(1.02); }
+ }
+ @keyframes spin {
+ from { transform: rotate(0deg); }
+ to { transform: rotate(360deg); }
+ }
+ @keyframes fadeInOut {
+ 0%, 100% { opacity: 0.5; }
+ 50% { opacity: 1; }
+ }
+ @keyframes dots {
+ 0%, 20% { content: '.'; }
+ 40% { content: '..'; }
+ 60%, 100% { content: '...'; }
+ }
+ `}</style>
+ {/* Top Navigation Bar */}
+ <div style={{
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,
+ padding: '8px 16px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexShrink: 0,
+ boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <span style={{
+ color: FINCEPT.ORANGE,
+ fontWeight: 700,
+ fontSize: '11px',
+ letterSpacing: '0.5px'
+ }}>
+ {t('title').toUpperCase()}
+ </span>
+ <span style={{ color: FINCEPT.GRAY }}>|</span>
+
+ {/* LLM Provider Selector */}
+ <div ref={llmSelectorRef} style={{ position: 'relative' }}>
+ <button
+ onClick={() => setShowLLMSelector(!showLLMSelector)}
+ style={{
+ backgroundColor: `${FINCEPT.YELLOW}20`,
+ border: `1px solid ${FINCEPT.YELLOW}40`,
+ color: FINCEPT.YELLOW,
+ padding: '4px 10px',
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = `${FINCEPT.YELLOW}30`;
+ e.currentTarget.style.borderColor = FINCEPT.YELLOW;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = `${FINCEPT.YELLOW}20`;
+ e.currentTarget.style.borderColor = `${FINCEPT.YELLOW}40`;
+ }}
+ title="Switch LLM Provider"
+ >
+ <Bot size={10} />
+ {activeLLMConfig?.provider.toUpperCase() || 'NO PROVIDER'}
+ <span style={{ fontSize: '7px' }}>▼</span>
+ </button>
+
+ {/* Dropdown Menu */}
+ {showLLMSelector && (
+ <div style={{
+ position: 'absolute',
+ top: '100%',
+ left: 0,
+ marginTop: '4px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.ORANGE}`,
+ borderRadius: '2px',
+ padding: '4px',
+ minWidth: '220px',
+ maxHeight: '400px',
+ overflowY: 'auto',
+ zIndex: 1000,
+ boxShadow: `0 4px 12px ${FINCEPT.DARK_BG}80`
+ }}>
+ <div style={{
+ padding: '6px 8px',
+ fontSize: '8px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ marginBottom: '4px'
+ }}>
+ SELECT LLM PROVIDER
+ </div>
+ {allLLMConfigs.length > 0 ? (
+ allLLMConfigs.map((config) => (
+ <button
+ key={config.provider}
+ onClick={() => switchLLMProvider(config.provider)}
+ style={{
+ width: '100%',
+ backgroundColor: activeLLMConfig?.provider === config.provider ? `${FINCEPT.ORANGE}20` : 'transparent',
+ border: activeLLMConfig?.provider === config.provider ? `1px solid ${FINCEPT.ORANGE}` : `1px solid ${FINCEPT.BORDER}`,
+ color: activeLLMConfig?.provider === config.provider ? FINCEPT.ORANGE : FINCEPT.WHITE,
+ padding: '8px',
+ fontSize: '9px',
+ fontWeight: 600,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ textAlign: 'left',
+ marginBottom: '2px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '4px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (activeLLMConfig?.provider !== config.provider) {
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ e.currentTarget.style.borderColor = FINCEPT.MUTED;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (activeLLMConfig?.provider !== config.provider) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ }
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <span style={{ fontWeight: 700, letterSpacing: '0.3px' }}>
+ {config.provider.toUpperCase()}
+ </span>
+ {activeLLMConfig?.provider === config.provider && (
+ <span style={{ color: FINCEPT.GREEN, fontSize: '8px' }}>● ACTIVE</span>
+ )}
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>
+ Model: {config.model || 'N/A'}
+ </div>
+ {config.base_url && (
+ <div style={{ fontSize: '7px', color: FINCEPT.MUTED }}>
+ {config.base_url}
+ </div>
+ )}
+ </button>
+ ))
+ ) : (
+ <div style={{
+ padding: '12px',
+ textAlign: 'center',
+ fontSize: '9px',
+ color: FINCEPT.MUTED
+ }}>
+ No LLM providers configured. Go to Settings to add one.
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ <span style={{ color: FINCEPT.GRAY }}>|</span>
+ <span style={{
+ color: FINCEPT.WHITE,
+ fontSize: '9px',
+ letterSpacing: '0.5px'
+ }}>
+ {currentTime.toLocaleTimeString('en-US', { hour12: false })}
+ </span>
+ </div>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ <button
+ onClick={() => onNavigateToSettings?.()}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ padding: '6px 10px',
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.color = FINCEPT.WHITE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.color = FINCEPT.GRAY;
+ }}
+ title="Go to Settings tab to configure LLM providers"
+ >
+ <Settings size={12} />
+ {t('header.settings').toUpperCase()}
+ </button>
+ <button
+ onClick={createNewSession}
+ style={{
+ backgroundColor: FINCEPT.ORANGE,
+ border: 'none',
+ color: FINCEPT.DARK_BG,
+ padding: '8px 16px',
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ >
+ <Plus size={12} />
+ {t('header.newChat').toUpperCase()}
+ </button>
+ </div>
+ </div>
+
+ {/* Main Content */}
+ <ErrorBoundary name="ChatMainContent" variant="minimal">
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* Left Panel - Sessions */}
+ <div style={{
+ width: '280px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {/* Section Header */}
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
+ }}>
+ {t('history.sessions').toUpperCase()} ({statistics.totalSessions})
+ </span>
+ {sessions.length > 0 && (
+ <button
+ onClick={deleteAllSessions}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.RED}20`,
+ color: FINCEPT.RED,
+ border: 'none',
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ title={t('history.deleteAll')}
+ >
+ {t('history.clearAll').toUpperCase()}
+ </button>
+ )}
+ </div>
+
+ {/* Search */}
+ <div style={{ position: 'relative', marginBottom: '8px' }}>
+ <Search size={12} color={FINCEPT.GRAY} style={{ position: 'absolute', left: '8px', top: '9px' }} />
+ <input
+ id="session-search"
+ type="text"
+ placeholder={t('input.placeholder')}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ style={{
+ width: '100%',
+ padding: '8px 10px 8px 32px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}
+ />
+ </div>
+
+ {/* Stats */}
+ <div style={{
+ fontSize: '9px',
+ color: FINCEPT.CYAN,
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ MESSAGES: {statistics.totalMessages} | TOKENS: {statistics.totalTokens.toLocaleString()}
+ </div>
+ </div>
+
+ {/* Session List with scrollbar */}
+ <div
+ ref={sessionsListRef}
+ style={{
+ flex: 1,
+ overflow: 'auto',
+ padding: '8px'
+ }}
+ >
+ {filteredSessions.map(session => (
+ <div
+ key={session.session_uuid}
+ style={{
+ padding: '10px 12px',
+ backgroundColor: currentSessionUuid === session.session_uuid ? `${FINCEPT.ORANGE}15` : 'transparent',
+ borderLeft: currentSessionUuid === session.session_uuid ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
+ cursor: renamingSessionId === session.session_uuid ? 'default' : 'pointer',
+ transition: 'all 0.2s',
+ marginBottom: '4px'
+ }}
+ onClick={() => renamingSessionId !== session.session_uuid && selectSession(session.session_uuid)}
+ onMouseEnter={(e) => {
+ if (currentSessionUuid !== session.session_uuid && renamingSessionId !== session.session_uuid) {
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (currentSessionUuid !== session.session_uuid) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
+ >
+ {/* Title or Rename Input */}
+ {renamingSessionId === session.session_uuid ? (
+ <div style={{ marginBottom: '6px', display: 'flex', gap: '4px', alignItems: 'center' }}>
+ <input
+ type="text"
+ value={renameValue}
+ onChange={(e) => setRenameValue(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') saveRename(session.session_uuid);
+ if (e.key === 'Escape') cancelRename();
+ }}
+ autoFocus
+ style={{
+ flex: 1,
+ padding: '4px 6px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.ORANGE}`,
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ borderRadius: '2px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}
+ />
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ saveRename(session.session_uuid);
+ }}
+ style={{
+ backgroundColor: 'transparent',
+ color: FINCEPT.GREEN,
+ border: 'none',
+ cursor: 'pointer',
+ padding: '0',
+ display: 'flex',
+ transition: 'all 0.2s'
+ }}
+ >
+ <Check size={12} />
+ </button>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ cancelRename();
+ }}
+ style={{
+ backgroundColor: 'transparent',
+ color: FINCEPT.RED,
+ border: 'none',
+ cursor: 'pointer',
+ padding: '0',
+ display: 'flex',
+ transition: 'all 0.2s'
+ }}
+ >
+ <X size={12} />
+ </button>
+ </div>
+ ) : (
+ <div style={{
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ marginBottom: '6px',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ fontWeight: 700
+ }}>
+ {session.title}
+ </div>
+ )}
+
+ {/* Actions Row */}
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {session.message_count} MSGS • {formatSessionTime(session.updated_at)}
+ </span>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ startRenaming(session.session_uuid, session.title);
+ }}
+ style={{
+ backgroundColor: 'transparent',
+ color: FINCEPT.YELLOW,
+ border: 'none',
+ fontSize: '9px',
+ cursor: 'pointer',
+ padding: '0',
+ display: 'flex',
+ transition: 'all 0.2s'
+ }}
+ title="Rename session"
+ >
+ <Edit2 size={10} />
+ </button>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ deleteSession(session.session_uuid);
+ }}
+ style={{
+ backgroundColor: 'transparent',
+ color: FINCEPT.RED,
+ border: 'none',
+ fontSize: '9px',
+ cursor: 'pointer',
+ padding: '0',
+ display: 'flex',
+ transition: 'all 0.2s'
+ }}
+ title="Delete session"
+ >
+ <Trash2 size={10} />
+ </button>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Center Panel - Chat */}
+ <div style={{
+ flex: 1,
+ backgroundColor: FINCEPT.PANEL_BG,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {/* Chat Header */}
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
+ }}>
+ {currentSessionUuid ? (sessions.find(s => s.session_uuid === currentSessionUuid)?.title || 'CHAT').toUpperCase() : 'NO ACTIVE SESSION'}
+ </span>
+ {currentSessionUuid && (
+ <button
+ onClick={clearCurrentChat}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.RED}20`,
+ color: FINCEPT.RED,
+ border: 'none',
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ >
+ CLEAR
+ </button>
+ )}
+ </div>
+
+ {/* Messages Area with scrollbar */}
+ <div style={{
+ flex: 1,
+ padding: '16px',
+ overflow: 'auto',
+ backgroundColor: FINCEPT.DARK_BG
+ }}>
+ {messages.length === 0 && !streamingContent ? renderWelcomeScreen() : (
+ <div>
+ {messages.map(renderMessage)}
+ {streamingContent && renderStreamingMessage()}
+ {isTyping && !streamingContent && (
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px'
+ }}>
+ <Bot size={12} color={FINCEPT.GRAY} />
+ <span>{t('messages.thinking').toUpperCase()}</span>
+ </div>
+ )}
+ <div ref={messagesEndRef} />
+ </div>
+ )}
+ </div>
+
+ {/* Input Area */}
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderTop: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ <textarea
+ value={messageInput}
+ onChange={(e) => setMessageInput(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ handleSendMessage();
+ }
+ }}
+ placeholder={t('input.placeholder')}
+ style={{
+ flex: 1,
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ resize: 'none',
+ height: '60px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}
+ />
+ <button
+ onClick={handleSendMessage}
+ disabled={!messageInput.trim() || isTyping}
+ style={{
+ padding: '8px 16px',
+ backgroundColor: messageInput.trim() && !isTyping ? FINCEPT.ORANGE : FINCEPT.MUTED,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: messageInput.trim() && !isTyping ? 'pointer' : 'not-allowed',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s',
+ opacity: messageInput.trim() && !isTyping ? 1 : 0.5
+ }}
+ >
+ <Send size={12} />
+ {t('input.send').toUpperCase()}
+ </button>
+ </div>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ marginTop: '6px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {messageInput.length > 0 ? `${messageInput.length} CHARS` : systemStatus}
+ </div>
+ </div>
+ </div>
+
+ {/* Right Panel - Quick Actions & Context Selector */}
+ <div style={{
+ width: '300px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderLeft: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {/* Context Selector Section */}
+ <div style={{
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
+ }}>
+ {t('panel.dataContexts').toUpperCase()}
+ </span>
+ </div>
+ <div style={{ padding: '12px' }}>
+ <ContextSelector
+ chatSessionUuid={currentSessionUuid}
+ onContextsChange={handleContextsChange}
+ />
+ </div>
+ </div>
+
+ {/* Quick Prompts Section */}
+ <div style={{
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
+ }}>
+ {t('panel.quickPrompts').toUpperCase()}
+ </span>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {isEditingPrompts ? (
+ <>
+ <button
+ onClick={cancelEditingPrompt}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.RED}`,
+ color: FINCEPT.RED,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ letterSpacing: '0.5px'
+ }}
+ >
+ <X size={10} />
+ </button>
+ <button
+ onClick={saveEditedPrompt}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.GREEN}`,
+ color: FINCEPT.GREEN,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ letterSpacing: '0.5px'
+ }}
+ >
+ <Check size={10} />
+ </button>
+ </>
+ ) : (
+ <button
+ onClick={resetQuickPrompts}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.MUTED}`,
+ color: FINCEPT.MUTED,
+ fontSize: '7px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ letterSpacing: '0.5px'
+ }}
+ title="Reset to default prompts"
+ >
+ RESET
+ </button>
+ )}
+ </div>
+ </div>
+ <div style={{ padding: '12px' }}>
+ {/* Editing form */}
+ {isEditingPrompts && editingPromptIndex !== null && (
+ <div style={{
+ marginBottom: '8px',
+ padding: '8px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.ORANGE}`,
+ borderRadius: '2px'
+ }}>
+ <input
+ type="text"
+ value={editPromptCmd}
+ onChange={(e) => setEditPromptCmd(e.target.value.toUpperCase())}
+ placeholder="LABEL"
+ style={{
+ width: '100%',
+ padding: '4px 6px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '9px',
+ borderRadius: '2px',
+ marginBottom: '4px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}
+ />
+ <textarea
+ value={editPromptText}
+ onChange={(e) => setEditPromptText(e.target.value)}
+ placeholder="Prompt text..."
+ style={{
+ width: '100%',
+ padding: '4px 6px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '9px',
+ borderRadius: '2px',
+ resize: 'vertical',
+ minHeight: '40px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}
+ />
+ </div>
+ )}
+ {/* Quick prompt buttons */}
+ {quickPrompts.map((item, index) => (
+ <div
+ key={`${item.cmd}-${index}`}
+ style={{
+ display: 'flex',
+ gap: '4px',
+ marginBottom: '6px'
+ }}
+ >
+ <button
+ onClick={() => !isEditingPrompts && setMessageInput(item.prompt)}
+ disabled={isEditingPrompts}
+ style={{
+ flex: 1,
+ padding: '6px 10px',
+ backgroundColor: editingPromptIndex === index ? `${FINCEPT.ORANGE}20` : 'transparent',
+ border: `1px solid ${editingPromptIndex === index ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ color: editingPromptIndex === index ? FINCEPT.ORANGE : FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ textAlign: 'left',
+ cursor: isEditingPrompts ? 'default' : 'pointer',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s',
+ opacity: isEditingPrompts && editingPromptIndex !== index ? 0.5 : 1
+ }}
+ onMouseEnter={(e) => {
+ if (!isEditingPrompts) {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.color = FINCEPT.WHITE;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (!isEditingPrompts && editingPromptIndex !== index) {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.color = FINCEPT.GRAY;
+ }
+ }}
+ title={item.prompt}
+ >
+ {item.cmd}
+ </button>
+ {!isEditingPrompts && (
+ <button
+ onClick={() => startEditingPrompt(index)}
+ style={{
+ padding: '4px 6px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.MUTED,
+ fontSize: '8px',
+ borderRadius: '2px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.YELLOW;
+ e.currentTarget.style.color = FINCEPT.YELLOW;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.color = FINCEPT.MUTED;
+ }}
+ title="Edit this prompt"
+ >
+ <Edit2 size={10} />
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* System Info Section */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
+ }}>
+ {t('panel.systemInfo').toUpperCase()}
+ </span>
+ </div>
+ <div style={{ padding: '12px' }}>
+ {activeLLMConfig ? (
+ <>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '9px',
+ marginBottom: '4px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ PROVIDER: {activeLLMConfig.provider.toUpperCase()}
+ </div>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '9px',
+ marginBottom: '4px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ MODEL: {activeLLMConfig.model}
+ </div>
+ {/* Base URL - shown for Ollama or custom endpoints */}
+ {shouldShowBaseUrl() && activeLLMConfig.base_url && (
+ <div style={{
+ color: FINCEPT.MUTED,
+ fontSize: '8px',
+ marginBottom: '4px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ wordBreak: 'break-all'
+ }}>
+ ENDPOINT: {activeLLMConfig.base_url}
+ </div>
+ )}
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '9px',
+ marginBottom: '4px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ TEMP: {llmGlobalSettings.temperature} | MAX TOKENS: {llmGlobalSettings.max_tokens}
+ </div>
+ {/* Status badges row */}
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginBottom: '8px' }}>
+ {/* Streaming status */}
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: providerSupportsStreaming() ? `${FINCEPT.GREEN}20` : `${FINCEPT.MUTED}20`,
+ color: providerSupportsStreaming() ? FINCEPT.GREEN : FINCEPT.MUTED,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ letterSpacing: '0.5px'
+ }}>
+ STREAMING: {providerSupportsStreaming() ? 'ENABLED' : 'DISABLED'}
+ </div>
+ {/* API Key status */}
+ {(() => {
+ const apiKeyStatus = getApiKeyStatus();
+ if (!apiKeyStatus.required) {
+ return (
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.CYAN}20`,
+ color: FINCEPT.CYAN,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ letterSpacing: '0.5px'
+ }}>
+ API KEY: NOT REQUIRED
+ </div>
+ );
+ }
+ return (
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: apiKeyStatus.configured ? `${FINCEPT.GREEN}20` : `${FINCEPT.RED}20`,
+ color: apiKeyStatus.configured ? FINCEPT.GREEN : FINCEPT.RED,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ letterSpacing: '0.5px'
+ }}>
+ API KEY: {apiKeyStatus.configured ? 'CONFIGURED' : 'MISSING'}
+ </div>
+ );
+ })()}
+ {/* Custom system prompt indicator */}
+ {hasCustomSystemPrompt() && (
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.PURPLE}20`,
+ color: FINCEPT.PURPLE,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ letterSpacing: '0.5px'
+ }}>
+ CUSTOM PROMPT: YES
+ </div>
+ )}
+ </div>
+ </>
+ ) : (
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.RED}20`,
+ color: FINCEPT.RED,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ letterSpacing: '0.5px'
+ }}>
+ NO LLM PROVIDER CONFIGURED
+ </div>
+ )}
+ <div style={{
+ marginTop: '12px',
+ paddingTop: '12px',
+ borderTop: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: mcpToolsCount > 0 ? `${FINCEPT.CYAN}20` : `${FINCEPT.MUTED}20`,
+ color: mcpToolsCount > 0 ? FINCEPT.CYAN : FINCEPT.MUTED,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ marginBottom: '8px',
+ letterSpacing: '0.5px',
+ display: 'inline-block'
+ }}>
+ MCP TOOLS: {mcpToolsCount > 0 ? `${mcpToolsCount} AVAILABLE [OK]` : 'NONE'}
+ </div>
+ <button
+ onClick={() => onNavigateToTab?.('mcp')}
+ style={{
+ width: '100%',
+ padding: '8px 16px',
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ marginBottom: '8px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ title="Configure MCP servers and tools"
+ >
+ 🔧 MCP INTEGRATION
+ </button>
+ {mcpToolsCount > 0 && !providerSupportsMCP() && activeLLMConfig && (
+ <div style={{
+ padding: '6px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.RED}`,
+ borderRadius: '2px',
+ color: FINCEPT.RED,
+ fontSize: '8px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>
+ [WARN] {activeLLMConfig.provider.toUpperCase()} DOESN'T SUPPORT MCP TOOLS
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </ErrorBoundary>
+
+ {/* Status Bar (Bottom) */}
+ <div style={{
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ padding: '4px 16px',
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ <div style={{ display: 'flex', gap: '12px' }}>
+ <span>TAB: AI CHAT</span>
+ <span>|</span>
+ <span>PROVIDER: {activeLLMConfig?.provider.toUpperCase() || 'NONE'}</span>
+ <span>|</span>
+ <span>SESSION: {currentSessionUuid ? 'ACTIVE' : 'NONE'}</span>
+ </div>
+ <div>
+ MESSAGES: {messages.length} | STATUS: {streamingContent ? 'STREAMING...' : 'READY'}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default ChatTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/chat/FinancialSparklines.tsx b/fincept-terminal-desktop/src/components/tabs/chat/FinancialSparklines.tsx
index 8bd1d6ac2..3d4c7af31 100644
--- a/fincept-terminal-desktop/src/components/tabs/chat/FinancialSparklines.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/chat/FinancialSparklines.tsx
@@ -1,4 +1,5 @@
import React, { useMemo } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface DataPoint {
period: string;
@@ -87,6 +88,7 @@ const MetricRow: React.FC<{
growth?: number;
color: string;
}> = ({ label, values, growth, color }) => {
+ const { colors, fontSize } = useTerminalTheme();
const sortedValues = [...values].sort((a, b) => a.period.localeCompare(b.period));
const numericValues = sortedValues.map(v => v.value);
const latest = sortedValues[sortedValues.length - 1];
@@ -103,25 +105,25 @@ const MetricRow: React.FC<{
borderLeft: `3px solid ${color}`,
}}>
<div style={{ minWidth: '80px' }}>
- <div style={{ fontSize: '10px', color: '#888', textTransform: 'uppercase', letterSpacing: '0.5px' }}>
+ <div style={{ fontSize: fontSize.small, color: colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
{label}
</div>
- <div style={{ fontSize: '13px', color: '#fff', fontWeight: 600 }}>
+ <div style={{ fontSize: fontSize.subheading, color: colors.text, fontWeight: 600 }}>
{formatValue(latest.value)}
</div>
</div>
<Sparkline values={numericValues} color={color} />
- <div style={{ fontSize: '10px', color: '#666', minWidth: '70px' }}>
+ <div style={{ fontSize: fontSize.small, color: colors.textMuted, minWidth: '70px' }}>
{formatValue(oldest.value)} → {formatValue(latest.value)}
</div>
{growth !== undefined && (
<div style={{
- fontSize: '11px',
+ fontSize: fontSize.body,
fontWeight: 600,
- color: growth >= 0 ? '#00D66F' : '#FF3B3B',
+ color: growth >= 0 ? colors.success : colors.alert,
minWidth: '50px',
textAlign: 'right'
}}>
@@ -138,48 +140,50 @@ const FinancialSparklines: React.FC<FinancialSparklinesProps> = ({
company,
responseText = ''
}) => {
+ const { colors, fontSize } = useTerminalTheme();
+
// Determine which metrics to show based on response text
const metricsToShow = useMemo(() => {
const text = responseText.toLowerCase();
const metrics: Array<{ key: keyof ChartData; label: string; color: string }> = [];
- // Check each metric type
+ // Check each metric type - use theme colors
if (data.revenue?.length) {
const hasKeyword = METRIC_KEYWORDS.revenue.some(kw => text.includes(kw));
if (hasKeyword || !responseText) {
- metrics.push({ key: 'revenue', label: 'Revenue', color: '#3b82f6' });
+ metrics.push({ key: 'revenue', label: 'Revenue', color: colors.secondary });
}
}
if (data.net_income?.length) {
const hasKeyword = METRIC_KEYWORDS.net_income.some(kw => text.includes(kw));
if (hasKeyword || !responseText) {
- metrics.push({ key: 'net_income', label: 'Net Income', color: '#10b981' });
+ metrics.push({ key: 'net_income', label: 'Net Income', color: colors.success });
}
}
if (data.total_assets?.length) {
const hasKeyword = METRIC_KEYWORDS.total_assets.some(kw => text.includes(kw));
if (hasKeyword) {
- metrics.push({ key: 'total_assets', label: 'Assets', color: '#f59e0b' });
+ metrics.push({ key: 'total_assets', label: 'Assets', color: colors.warning });
}
}
if (data.total_equity?.length) {
const hasKeyword = METRIC_KEYWORDS.total_equity.some(kw => text.includes(kw));
if (hasKeyword) {
- metrics.push({ key: 'total_equity', label: 'Equity', color: '#8b5cf6' });
+ metrics.push({ key: 'total_equity', label: 'Equity', color: colors.primary });
}
}
// If no keywords matched but we have data, show revenue and net_income by default
if (metrics.length === 0) {
- if (data.revenue?.length) metrics.push({ key: 'revenue', label: 'Revenue', color: '#3b82f6' });
- if (data.net_income?.length) metrics.push({ key: 'net_income', label: 'Net Income', color: '#10b981' });
+ if (data.revenue?.length) metrics.push({ key: 'revenue', label: 'Revenue', color: colors.secondary });
+ if (data.net_income?.length) metrics.push({ key: 'net_income', label: 'Net Income', color: colors.success });
}
return metrics;
- }, [data, responseText]);
+ }, [data, responseText, colors]);
if (metricsToShow.length === 0) return null;
@@ -193,8 +197,8 @@ const FinancialSparklines: React.FC<FinancialSparklinesProps> = ({
}}>
{(ticker || company) && (
<div style={{
- fontSize: '10px',
- color: '#666',
+ fontSize: fontSize.small,
+ color: colors.textMuted,
marginBottom: '8px',
textTransform: 'uppercase',
letterSpacing: '0.5px'
diff --git a/fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsx
index 5616343dc..7e9a1998c 100644
--- a/fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsx
@@ -1,4 +1,5 @@
import React, { useState, useRef, useEffect, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';
import {
Play, Save, FileText, Plus, X, Terminal as TerminalIcon,
@@ -11,27 +12,9 @@ import { invoke } from '@tauri-apps/api/core';
import { open, save } from '@tauri-apps/plugin-dialog';
import { FinScriptOutputPanel, FinScriptExecutionResult } from './FinScriptOutputPanel';
import { showConfirm } from '@/utils/notifications';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
-// ─── Design System Constants ────────────────────────────────────────────────
-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';
+// Theme colors provided by useTerminalTheme() hook
// ─── Interfaces ─────────────────────────────────────────────────────────────
interface EditorFile {
@@ -53,13 +36,7 @@ interface SearchState {
currentMatch: number;
}
-// ─── Language Config ────────────────────────────────────────────────────────
-const LANG_CONFIG: Record<string, { icon: React.ReactNode; color: string; ext: string }> = {
- 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' },
-};
+// ─── Language Config (moved inside component to access theme colors) ────────────────
const DEFAULT_FINSCRIPT = `// FinScript - EMA/RSI Crossover Strategy
// Data is generated synthetically for instant execution
@@ -1208,6 +1185,17 @@ label_new(250, take_profit, "TP", "green")
// ─── Component ──────────────────────────────────────────────────────────────
export default function CodeEditorTab() {
+ const { t } = useTranslation('codeEditor');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+
+ // Language Config
+ const 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' },
+ };
+
// ─── State ──────────────────────────────────────────────────────────────
const [files, setFiles] = useState<EditorFile[]>([
{
@@ -1357,8 +1345,8 @@ export default function CodeEditorTab() {
const fileToClose = files.find(f => f.id === id);
if (fileToClose?.unsaved) {
const confirmed = await showConfirm(
- 'You have unsaved changes.',
- { title: 'Close file without saving?', type: 'warning' }
+ t('dialogs.unsavedChanges'),
+ { title: t('dialogs.closeUnsaved'), type: 'warning' }
);
if (!confirmed) return;
}
@@ -1506,52 +1494,54 @@ export default function CodeEditorTab() {
// ─── Render ─────────────────────────────────────────────────────────────
const effectiveOutputHeight = isOutputMaximized ? 500 : (showOutput ? outputHeight : 0);
+ 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}; }`,
+ ].join('\n');
+
return (
<div style={{
width: '100%', height: '100%',
- backgroundColor: F.DARK_BG,
- color: F.WHITE,
- fontFamily: FONT,
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontFamily: fontFamily,
display: 'flex', flexDirection: 'column',
overflow: 'hidden',
}}>
{/* ─── CSS ──────────────────────────────────────────────────────── */}
- <style>{`
- .ce-scroll::-webkit-scrollbar { width: 6px; height: 6px; }
- .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}; }
- `}</style>
+ <style dangerouslySetInnerHTML={{ __html: editorCSS }} />
{/* ─── Top Navigation Bar ───────────────────────────────────────── */}
<div style={{
- backgroundColor: F.HEADER_BG,
- borderBottom: `2px solid ${F.ORANGE}`,
+ backgroundColor: colors.panel,
+ borderBottom: `2px solid ${colors.primary}`,
padding: '6px 16px',
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
- boxShadow: `0 2px 8px ${F.ORANGE}20`,
+ boxShadow: `0 2px 8px ${colors.primary}20`,
minHeight: '38px',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <Zap size={14} style={{ color: F.ORANGE }} />
- <span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>FINSCRIPT IDE</span>
- <span style={{ color: F.MUTED }}>|</span>
- <span style={{ fontSize: '9px', color: F.GRAY, letterSpacing: '0.5px' }}>v1.0</span>
+ <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>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
{/* Toggle Explorer */}
<button
onClick={() => setShowExplorer(v => !v)}
- title="Toggle Explorer (Ctrl+B)"
+ title={t('toolbar.toggleExplorer')}
style={{
- padding: '4px 8px', backgroundColor: showExplorer ? `${F.ORANGE}20` : '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',
+ 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',
}}
>
<FolderOpen size={11} />
@@ -1560,12 +1550,12 @@ export default function CodeEditorTab() {
{/* Open File */}
<button
onClick={openFileFromDisk}
- title="Open File"
+ title={t('toolbar.openFile')}
style={{
padding: '4px 8px', backgroundColor: 'transparent',
- border: `1px solid ${F.BORDER}`, borderRadius: '2px',
- color: F.GRAY, fontSize: '9px', fontWeight: 700,
- cursor: 'pointer', fontFamily: FONT, transition: 'all 0.2s',
+ border: `1px solid ${colors.panel}`, borderRadius: '2px',
+ color: colors.textMuted, fontSize: '9px', fontWeight: 700,
+ cursor: 'pointer', fontFamily: fontFamily, transition: 'all 0.2s',
}}
>
<Upload size={11} />
@@ -1575,12 +1565,12 @@ export default function CodeEditorTab() {
<button
onClick={saveFile}
disabled={!activeFile.unsaved}
- title="Save (Ctrl+S)"
+ title={t('toolbar.saveShortcut')}
style={{
padding: '4px 8px', backgroundColor: 'transparent',
- border: `1px solid ${activeFile.unsaved ? F.YELLOW : F.BORDER}`, borderRadius: '2px',
- color: activeFile.unsaved ? F.YELLOW : F.MUTED, fontSize: '9px', fontWeight: 700,
- cursor: activeFile.unsaved ? 'pointer' : 'default', fontFamily: FONT,
+ 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,
opacity: activeFile.unsaved ? 1 : 0.5, transition: 'all 0.2s',
}}
>
@@ -1590,35 +1580,35 @@ export default function CodeEditorTab() {
{/* Search */}
<button
onClick={() => setSearch(s => ({ ...s, isOpen: !s.isOpen }))}
- title="Find (Ctrl+F)"
+ title={t('toolbar.findShortcut')}
style={{
- 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',
+ 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',
}}
>
<Search size={11} />
</button>
- <div style={{ width: '1px', height: '18px', backgroundColor: F.BORDER, margin: '0 4px' }} />
+ <div style={{ width: '1px', height: '18px', backgroundColor: colors.panel, margin: '0 4px' }} />
{/* Run Button */}
<button
onClick={runCode}
disabled={isRunning || activeFile.language !== 'finscript'}
- title="Run (Ctrl+Enter)"
+ title={t('toolbar.runShortcut')}
style={{
padding: '5px 14px', display: 'flex', alignItems: 'center', gap: '6px',
- backgroundColor: isRunning ? F.MUTED : F.ORANGE,
- color: F.DARK_BG, border: 'none', borderRadius: '2px',
+ backgroundColor: isRunning ? colors.textMuted : colors.primary,
+ color: colors.background, border: 'none', borderRadius: '2px',
fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px',
- cursor: isRunning ? 'not-allowed' : 'pointer', fontFamily: FONT,
+ cursor: isRunning ? 'not-allowed' : 'pointer', fontFamily: fontFamily,
transition: 'all 0.2s',
}}
>
- <Play size={11} fill={F.DARK_BG} />
- {isRunning ? 'RUNNING...' : 'RUN'}
+ <Play size={11} fill={colors.background} />
+ {isRunning ? t('toolbar.running') : t('toolbar.run')}
</button>
</div>
</div>
@@ -1629,26 +1619,26 @@ export default function CodeEditorTab() {
{/* ─── Explorer Panel ─────────────────────────────────────────── */}
{showExplorer && (
<div style={{
- width: '220px', backgroundColor: F.PANEL_BG,
- borderRight: `1px solid ${F.BORDER}`,
+ width: '220px', backgroundColor: colors.panel,
+ borderRight: `1px solid ${colors.panel}`,
display: 'flex', flexDirection: 'column',
}}>
{/* Explorer Header */}
<div style={{
padding: '10px 12px',
- backgroundColor: F.HEADER_BG,
- borderBottom: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.panel}`,
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
}}>
- <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>
- EXPLORER
+ <span style={{ fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px' }}>
+ {t('explorer.title')}
</span>
<button
onClick={createNewFile}
- title="New File (Ctrl+N)"
+ title={t('toolbar.newFile')}
style={{
padding: '2px 4px', backgroundColor: 'transparent',
- border: 'none', color: F.GRAY, cursor: 'pointer',
+ border: 'none', color: colors.textMuted, cursor: 'pointer',
transition: 'all 0.2s',
}}
>
@@ -1661,10 +1651,10 @@ export default function CodeEditorTab() {
{/* Section Label */}
<div style={{
padding: '6px 12px', display: 'flex', alignItems: 'center', gap: '4px',
- fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px',
+ fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px',
}}>
<ChevronDown size={10} />
- OPEN FILES ({files.length})
+ {t('explorer.openFiles')} ({files.length})
</div>
{files.map(file => {
@@ -1678,25 +1668,25 @@ export default function CodeEditorTab() {
style={{
padding: '6px 12px 6px 24px',
display: 'flex', alignItems: 'center', gap: '8px',
- backgroundColor: isActive ? `${F.ORANGE}15` : 'transparent',
- borderLeft: isActive ? `2px solid ${F.ORANGE}` : '2px solid transparent',
+ backgroundColor: isActive ? `${colors.primary}15` : 'transparent',
+ borderLeft: isActive ? `2px solid ${colors.primary}` : '2px solid transparent',
cursor: 'pointer', transition: 'all 0.2s',
}}
>
<span style={{ color: lang.color }}>{lang.icon}</span>
<span style={{
- fontSize: '10px', color: isActive ? F.WHITE : F.GRAY,
+ fontSize: '10px', color: isActive ? colors.text : colors.textMuted,
flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>
{file.name}
</span>
{file.unsaved && (
- <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: F.YELLOW }} />
+ <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: colors.warning }} />
)}
{files.length > 1 && (
<X size={10}
onClick={(e) => { e.stopPropagation(); closeFile(file.id); }}
- style={{ color: F.MUTED, cursor: 'pointer', opacity: 0.6 }}
+ style={{ color: colors.textMuted, cursor: 'pointer', opacity: 0.6 }}
/>
)}
</div>
@@ -1705,13 +1695,13 @@ export default function CodeEditorTab() {
{/* Examples Section */}
<div style={{
- borderTop: `1px solid ${F.BORDER}`, marginTop: '8px',
+ borderTop: `1px solid ${colors.panel}`, marginTop: '8px',
}}>
<div
onClick={() => setExamplesExpanded(!examplesExpanded)}
style={{
padding: '10px 12px 6px', display: 'flex', alignItems: 'center', gap: '4px',
- fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px',
+ fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px',
cursor: 'pointer',
}}
>
@@ -1719,8 +1709,8 @@ export default function CodeEditorTab() {
transform: examplesExpanded ? 'rotate(0deg)' : 'rotate(-90deg)',
transition: 'transform 0.2s',
}} />
- <BookOpen size={10} style={{ color: F.ORANGE }} />
- EXAMPLES
+ <BookOpen size={10} style={{ color: colors.primary }} />
+ {t('explorer.examples')}
</div>
{examplesExpanded && (
<div>
@@ -1728,7 +1718,7 @@ export default function CodeEditorTab() {
<div key={category}>
<div style={{
padding: '4px 12px 2px 20px',
- fontSize: '9px', color: F.MUTED, fontWeight: 600,
+ fontSize: '9px', color: colors.textMuted, fontWeight: 600,
letterSpacing: '0.3px',
}}>
{category}
@@ -1745,9 +1735,9 @@ export default function CodeEditorTab() {
cursor: 'pointer', transition: 'all 0.2s',
}}
>
- <Zap size={9} style={{ color: F.ORANGE, flexShrink: 0 }} />
+ <Zap size={9} style={{ color: colors.primary, flexShrink: 0 }} />
<span style={{
- fontSize: '10px', color: F.GRAY,
+ fontSize: '10px', color: colors.textMuted,
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>
{example.name.replace('.fincept', '')}
@@ -1765,11 +1755,11 @@ export default function CodeEditorTab() {
<>
<div style={{
padding: '10px 12px 6px', display: 'flex', alignItems: 'center', gap: '4px',
- fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px',
- borderTop: `1px solid ${F.BORDER}`, marginTop: '8px',
+ fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px',
+ borderTop: `1px solid ${colors.panel}`, marginTop: '8px',
}}>
<ChevronDown size={10} />
- RUN HISTORY
+ {t('explorer.runHistory')}
</div>
{executionHistory.slice().reverse().map((h, idx) => (
<div key={idx} style={{
@@ -1778,11 +1768,11 @@ export default function CodeEditorTab() {
fontSize: '9px',
}}>
{h.status === 'success'
- ? <CheckCircle size={9} style={{ color: F.GREEN }} />
- : <AlertTriangle size={9} style={{ color: F.RED }} />
+ ? <CheckCircle size={9} style={{ color: colors.success }} />
+ : <AlertTriangle size={9} style={{ color: colors.alert }} />
}
- <span style={{ color: F.MUTED }}>{h.time}</span>
- <span style={{ color: F.GRAY }}>{h.ms}ms</span>
+ <span style={{ color: colors.textMuted }}>{h.time}</span>
+ <span style={{ color: colors.textMuted }}>{h.ms}ms</span>
</div>
))}
</>
@@ -1792,12 +1782,12 @@ export default function CodeEditorTab() {
{/* Explorer Footer */}
<div style={{
padding: '8px 12px',
- borderTop: `1px solid ${F.BORDER}`,
- fontSize: '9px', color: F.MUTED,
+ borderTop: `1px solid ${colors.panel}`,
+ fontSize: '9px', color: colors.textMuted,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- <Zap size={9} style={{ color: F.ORANGE }} />
- <span>FinScript Engine</span>
+ <Zap size={9} style={{ color: colors.primary }} />
+ <span>{t('explorer.finscriptEngine')}</span>
</div>
</div>
</div>
@@ -1808,8 +1798,8 @@ export default function CodeEditorTab() {
{/* ─── Tab Bar ──────────────────────────────────────────────── */}
<div style={{
- backgroundColor: F.HEADER_BG,
- borderBottom: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.panel}`,
display: 'flex', alignItems: 'center',
overflow: 'hidden',
}}>
@@ -1825,9 +1815,9 @@ export default function CodeEditorTab() {
style={{
padding: '7px 14px',
display: 'flex', alignItems: 'center', gap: '6px',
- backgroundColor: isActive ? F.PANEL_BG : 'transparent',
- borderRight: `1px solid ${F.BORDER}`,
- borderBottom: isActive ? `2px solid ${F.ORANGE}` : '2px solid transparent',
+ backgroundColor: isActive ? colors.panel : 'transparent',
+ borderRight: `1px solid ${colors.panel}`,
+ borderBottom: isActive ? `2px solid ${colors.primary}` : '2px solid transparent',
cursor: 'pointer', transition: 'all 0.2s',
maxWidth: '180px',
}}
@@ -1835,7 +1825,7 @@ export default function CodeEditorTab() {
<span style={{ color: lang.color }}>{lang.icon}</span>
<span style={{
fontSize: '10px',
- color: isActive ? F.WHITE : F.GRAY,
+ color: isActive ? colors.text : colors.textMuted,
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>
{file.name}{file.unsaved ? ' *' : ''}
@@ -1843,7 +1833,7 @@ export default function CodeEditorTab() {
{files.length > 1 && (
<X size={10}
onClick={(e) => { e.stopPropagation(); closeFile(file.id); }}
- style={{ color: F.MUTED, cursor: 'pointer' }}
+ style={{ color: colors.textMuted, cursor: 'pointer' }}
/>
)}
</div>
@@ -1855,12 +1845,12 @@ export default function CodeEditorTab() {
{/* ─── Search Bar ───────────────────────────────────────────── */}
{search.isOpen && (
<div style={{
- backgroundColor: F.HEADER_BG,
- borderBottom: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.panel}`,
padding: '6px 12px',
display: 'flex', alignItems: 'center', gap: '8px',
}}>
- <Search size={12} style={{ color: F.GRAY }} />
+ <Search size={12} style={{ color: colors.textMuted }} />
<input
autoFocus
type="text"
@@ -1869,14 +1859,14 @@ export default function CodeEditorTab() {
placeholder="Find..."
style={{
width: '200px', padding: '4px 8px',
- backgroundColor: F.DARK_BG, color: F.WHITE,
- border: `1px solid ${F.BORDER}`, borderRadius: '2px',
- fontSize: '10px', fontFamily: FONT,
+ backgroundColor: colors.background, color: colors.text,
+ border: `1px solid ${colors.panel}`, borderRadius: '2px',
+ fontSize: '10px', fontFamily: fontFamily,
outline: 'none',
}}
/>
{search.query && (
- <span style={{ fontSize: '9px', color: F.GRAY }}>
+ <span style={{ fontSize: '9px', color: colors.textMuted }}>
{getMatchCount()} matches
</span>
)}
@@ -1884,14 +1874,14 @@ export default function CodeEditorTab() {
onClick={() => setSearch(s => ({ ...s, showReplace: !s.showReplace }))}
style={{
padding: '2px 6px', backgroundColor: 'transparent',
- border: `1px solid ${F.BORDER}`, borderRadius: '2px',
- color: F.GRAY, fontSize: '9px', cursor: 'pointer', fontFamily: FONT,
+ border: `1px solid ${colors.panel}`, borderRadius: '2px',
+ color: colors.textMuted, fontSize: '9px', cursor: 'pointer', fontFamily: fontFamily,
}}
>
<Replace size={10} />
</button>
<X size={12}
- style={{ color: F.GRAY, cursor: 'pointer' }}
+ style={{ color: colors.textMuted, cursor: 'pointer' }}
onClick={() => setSearch(s => ({ ...s, isOpen: false }))}
/>
</div>
@@ -1901,8 +1891,8 @@ 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: F.DARK_BG,
- borderRight: `1px solid ${F.BORDER}`,
+ width: '48px', backgroundColor: colors.background,
+ borderRight: `1px solid ${colors.panel}`,
overflowY: 'hidden', padding: '12px 0',
userSelect: 'none',
}}>
@@ -1910,8 +1900,8 @@ export default function CodeEditorTab() {
<div key={i} style={{
padding: '0 8px', textAlign: 'right',
fontSize: '11px', lineHeight: '20px',
- color: (i + 1) === activeFile.cursorLine ? F.WHITE : F.MUTED,
- fontFamily: FONT,
+ color: (i + 1) === activeFile.cursorLine ? colors.text : colors.textMuted,
+ fontFamily: fontFamily,
}}>
{i + 1}
</div>
@@ -1930,12 +1920,12 @@ export default function CodeEditorTab() {
spellCheck={false}
style={{
flex: 1,
- backgroundColor: F.PANEL_BG,
- color: F.WHITE,
+ backgroundColor: colors.panel,
+ color: colors.text,
border: 'none', outline: 'none', resize: 'none',
padding: '12px 16px',
fontSize: '12px', lineHeight: '20px',
- fontFamily: FONT,
+ fontFamily: fontFamily,
whiteSpace: 'pre', overflowWrap: 'normal',
overflowX: 'auto',
tabSize: 4,
@@ -1944,15 +1934,15 @@ export default function CodeEditorTab() {
{/* Minimap Gutter */}
<div style={{
- width: '4px', backgroundColor: F.DARK_BG,
- borderLeft: `1px solid ${F.BORDER}`,
+ width: '4px', backgroundColor: colors.background,
+ borderLeft: `1px solid ${colors.panel}`,
position: 'relative',
}}>
{/* Simple scrollbar indicator */}
<div style={{
position: 'absolute', top: '0',
width: '100%', height: `${Math.min(100, (20 / lines.length) * 100)}%`,
- backgroundColor: `${F.ORANGE}40`, borderRadius: '2px',
+ backgroundColor: `${colors.primary}40`, borderRadius: '2px',
}} />
</div>
</div>
@@ -1963,7 +1953,7 @@ export default function CodeEditorTab() {
className="ce-resize-handle"
onMouseDown={handleResizeStart}
style={{
- height: '3px', backgroundColor: F.BORDER,
+ height: '3px', backgroundColor: colors.panel,
cursor: 'ns-resize', transition: 'background-color 0.2s',
}}
/>
@@ -1974,27 +1964,27 @@ export default function CodeEditorTab() {
<div style={{
height: `${effectiveOutputHeight}px`,
display: 'flex', flexDirection: 'column',
- borderTop: `1px solid ${F.BORDER}`,
+ borderTop: `1px solid ${colors.panel}`,
}}>
{/* Output Header */}
<div style={{
- backgroundColor: F.HEADER_BG,
+ backgroundColor: colors.panel,
padding: '6px 12px',
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
- borderBottom: `1px solid ${F.BORDER}`,
+ borderBottom: `1px solid ${colors.panel}`,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <TerminalIcon size={11} style={{ color: F.GREEN }} />
- <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>
- OUTPUT
+ <TerminalIcon size={11} style={{ color: colors.success }} />
+ <span style={{ fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px' }}>
+ {t('output.title')}
</span>
{finscriptResult && (
<span style={{
padding: '1px 5px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,
- backgroundColor: finscriptResult.success ? `${F.GREEN}20` : `${F.RED}20`,
- color: finscriptResult.success ? F.GREEN : F.RED,
+ backgroundColor: finscriptResult.success ? `${colors.success}20` : `${colors.alert}20`,
+ color: finscriptResult.success ? colors.success : colors.alert,
}}>
- {finscriptResult.success ? 'SUCCESS' : 'ERROR'}
+ {finscriptResult.success ? t('output.success') : t('output.error')}
</span>
)}
</div>
@@ -2003,7 +1993,7 @@ export default function CodeEditorTab() {
onClick={() => setIsOutputMaximized(v => !v)}
style={{
padding: '2px 4px', backgroundColor: 'transparent',
- border: 'none', color: F.GRAY, cursor: 'pointer',
+ border: 'none', color: colors.textMuted, cursor: 'pointer',
}}
>
{isOutputMaximized ? <Minimize2 size={10} /> : <Maximize2 size={10} />}
@@ -2012,7 +2002,7 @@ export default function CodeEditorTab() {
onClick={() => setShowOutput(false)}
style={{
padding: '2px 4px', backgroundColor: 'transparent',
- border: 'none', color: F.GRAY, cursor: 'pointer',
+ border: 'none', color: colors.textMuted, cursor: 'pointer',
}}
>
<X size={10} />
@@ -2027,17 +2017,18 @@ export default function CodeEditorTab() {
isRunning={isRunning}
onClear={() => setFinscriptResult(null)}
colors={{
- 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,
+ 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,
}}
+ fontFamily={fontFamily}
/>
</div>
</div>
@@ -2047,11 +2038,11 @@ export default function CodeEditorTab() {
{/* ─── Status Bar ───────────────────────────────────────────────── */}
<div style={{
- backgroundColor: F.HEADER_BG,
- borderTop: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.panel,
+ borderTop: `1px solid ${colors.panel}`,
padding: '3px 16px',
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
- fontSize: '9px', color: F.GRAY, fontFamily: FONT,
+ fontSize: '9px', color: colors.textMuted, fontFamily: fontFamily,
minHeight: '22px',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
@@ -2063,20 +2054,20 @@ export default function CodeEditorTab() {
<span style={{ letterSpacing: '0.5px' }}>{activeFile.language.toUpperCase()}</span>
</div>
- <span style={{ color: F.MUTED }}>|</span>
+ <span style={{ color: colors.textMuted }}>|</span>
{/* Cursor Position */}
<span>Ln {activeFile.cursorLine}, Col {activeFile.cursorCol}</span>
- <span style={{ color: F.MUTED }}>|</span>
+ <span style={{ color: colors.textMuted }}>|</span>
{/* Line Count */}
- <span>{lines.length} lines</span>
+ <span>{lines.length} {t('statusBar.lines')}</span>
{activeFile.unsaved && (
<>
- <span style={{ color: F.MUTED }}>|</span>
- <span style={{ color: F.YELLOW }}>MODIFIED</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.warning }}>{t('statusBar.modified')}</span>
</>
)}
</div>
@@ -2088,22 +2079,22 @@ export default function CodeEditorTab() {
onClick={() => setShowOutput(true)}
style={{
padding: '1px 6px', backgroundColor: 'transparent',
- border: `1px solid ${F.BORDER}`, borderRadius: '2px',
- color: F.GRAY, fontSize: '8px', cursor: 'pointer', fontFamily: FONT,
+ border: `1px solid ${colors.panel}`, borderRadius: '2px',
+ color: colors.textMuted, fontSize: '8px', cursor: 'pointer', fontFamily: fontFamily,
}}
>
- SHOW OUTPUT
+ {t('statusBar.showOutput')}
</button>
)}
{/* Encoding */}
- <span>UTF-8</span>
- <span style={{ color: F.MUTED }}>|</span>
- <span>4 Spaces</span>
- <span style={{ color: F.MUTED }}>|</span>
+ <span>{t('statusBar.encoding')}</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span>{t('statusBar.spaces')}</span>
+ <span style={{ color: colors.textMuted }}>|</span>
{/* Shortcuts */}
- <span style={{ color: F.MUTED }}>Ctrl+Enter: Run</span>
+ <span style={{ color: colors.textMuted }}>{t('statusBar.runShortcut')}</span>
</div>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptChart.tsx b/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptChart.tsx
index eb05edeb4..14ef61500 100644
--- a/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptChart.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptChart.tsx
@@ -1,4 +1,5 @@
import React, { useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
import { createChart, IChartApi, ColorType, CandlestickSeries, LineSeries, HistogramSeries } from 'lightweight-charts';
interface PlotPoint {
@@ -21,9 +22,21 @@ interface PlotData {
interface FinScriptChartProps {
plot: PlotData;
height?: number;
+ colors?: {
+ background?: string;
+ text?: string;
+ panel?: string;
+ };
+ fontFamily?: string;
}
-export const FinScriptChart: React.FC<FinScriptChartProps> = ({ plot, height = 250 }) => {
+export const FinScriptChart: React.FC<FinScriptChartProps> = ({
+ plot,
+ height = 250,
+ colors = { background: '#0a0a0a', text: '#a0a0a0', panel: '#2a2a2a' },
+ fontFamily = 'Consolas, monospace'
+}) => {
+ const { t } = useTranslation('codeEditor');
const containerRef = useRef<HTMLDivElement>(null);
const chartRef = useRef<IChartApi | null>(null);
@@ -40,8 +53,8 @@ export const FinScriptChart: React.FC<FinScriptChartProps> = ({ plot, height = 2
width: containerRef.current.clientWidth,
height,
layout: {
- background: { type: ColorType.Solid, color: '#0a0a0a' },
- textColor: '#a0a0a0',
+ background: { type: ColorType.Solid, color: colors.background || '#0a0a0a' },
+ textColor: colors.text || '#a0a0a0',
fontSize: 11,
},
grid: {
@@ -52,10 +65,10 @@ export const FinScriptChart: React.FC<FinScriptChartProps> = ({ plot, height = 2
mode: 0,
},
rightPriceScale: {
- borderColor: '#2a2a2a',
+ borderColor: colors.panel || '#2a2a2a',
},
timeScale: {
- borderColor: '#2a2a2a',
+ borderColor: colors.panel || '#2a2a2a',
timeVisible: true,
},
});
@@ -147,19 +160,19 @@ export const FinScriptChart: React.FC<FinScriptChartProps> = ({ plot, height = 2
return (
<div style={{ marginBottom: '12px' }}>
<div style={{
- color: '#a0a0a0',
+ color: colors.text,
fontSize: '11px',
fontWeight: 'bold',
marginBottom: '4px',
- fontFamily: 'Consolas, monospace',
+ fontFamily,
}}>
- {plot.label} ({plot.plot_type === 'candlestick' ? 'OHLC' : plot.plot_type === 'histogram' ? 'Histogram' : 'Line'} - {plot.data.length} points)
+ {plot.label} ({plot.plot_type === 'candlestick' ? t('chart.ohlc') : plot.plot_type === 'histogram' ? t('chart.histogram') : t('chart.line')} - {plot.data.length} {t('chart.points')})
</div>
<div
ref={containerRef}
style={{
width: '100%',
- border: '1px solid #2a2a2a',
+ border: `1px solid ${colors.panel}`,
borderRadius: '2px',
}}
/>
diff --git a/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptOutputPanel.tsx b/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptOutputPanel.tsx
index bc58a3126..2d8171728 100644
--- a/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptOutputPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptOutputPanel.tsx
@@ -1,26 +1,9 @@
import React from 'react';
+import { useTranslation } from 'react-i18next';
import { Terminal as TerminalIcon, TrendingUp, TrendingDown, BarChart2, AlertCircle, Clock, CheckCircle } from 'lucide-react';
import { FinScriptChart } from './FinScriptChart';
-// ─── Design System Constants ────────────────────────────────────────────────
-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',
-};
-
-const FONT = '"IBM Plex Mono", "Consolas", monospace';
+// Theme colors passed via props from parent
interface PlotPoint {
timestamp: number;
@@ -67,19 +50,24 @@ interface FinScriptOutputPanelProps {
background: string;
panel: string;
};
+ fontFamily?: string;
}
export const FinScriptOutputPanel: React.FC<FinScriptOutputPanelProps> = ({
result,
isRunning,
onClear,
+ colors,
+ fontFamily = '"IBM Plex Mono", monospace',
}) => {
+ const { t } = useTranslation('codeEditor');
+
if (isRunning) {
return (
<div style={{
width: '100%', height: '100%',
display: 'flex', flexDirection: 'column',
- backgroundColor: F.DARK_BG,
+ backgroundColor: colors.background,
}}>
<div style={{
flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
@@ -87,12 +75,12 @@ export const FinScriptOutputPanel: React.FC<FinScriptOutputPanelProps> = ({
}}>
<div className="animate-spin" style={{
width: '24px', height: '24px',
- border: `2px solid ${F.BORDER}`,
- borderTop: `2px solid ${F.ORANGE}`,
+ border: `2px solid ${colors.panel}`,
+ borderTop: `2px solid ${colors.primary}`,
borderRadius: '50%',
}} />
- <span style={{ color: F.GRAY, fontSize: '10px', fontFamily: FONT, letterSpacing: '0.5px' }}>
- EXECUTING FINSCRIPT...
+ <span style={{ color: colors.textMuted, fontSize: '10px', fontFamily: fontFamily, letterSpacing: '0.5px' }}>
+ {t('output.executing')}
</span>
</div>
</div>
@@ -104,16 +92,16 @@ export const FinScriptOutputPanel: React.FC<FinScriptOutputPanelProps> = ({
<div style={{
width: '100%', height: '100%',
display: 'flex', flexDirection: 'column',
- backgroundColor: F.DARK_BG,
+ backgroundColor: colors.background,
}}>
<div style={{
flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
- flexDirection: 'column', color: F.MUTED,
+ flexDirection: 'column', color: colors.textMuted,
}}>
<TerminalIcon size={20} style={{ marginBottom: '8px', opacity: 0.5 }} />
- <div style={{ fontSize: '10px', fontFamily: FONT }}>No output yet</div>
- <div style={{ fontSize: '9px', marginTop: '4px', fontFamily: FONT, color: F.MUTED }}>
- Press Ctrl+Enter to run
+ <div style={{ fontSize: '10px', fontFamily: fontFamily }}>{t('output.noOutput')}</div>
+ <div style={{ fontSize: '9px', marginTop: '4px', fontFamily: fontFamily, color: colors.textMuted }}>
+ {t('output.pressToRun')}
</div>
</div>
</div>
@@ -124,7 +112,7 @@ export const FinScriptOutputPanel: React.FC<FinScriptOutputPanelProps> = ({
<div style={{
width: '100%', height: '100%',
display: 'flex', flexDirection: 'column',
- backgroundColor: F.DARK_BG,
+ backgroundColor: colors.background,
}}>
{/* Scrollable Content */}
<div className="ce-scroll" style={{
@@ -134,41 +122,41 @@ export const FinScriptOutputPanel: React.FC<FinScriptOutputPanelProps> = ({
<div style={{
display: 'flex', alignItems: 'center', gap: '8px',
marginBottom: '12px', padding: '6px 8px',
- backgroundColor: F.PANEL_BG,
- border: `1px solid ${F.BORDER}`, borderRadius: '2px',
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.panel}`, borderRadius: '2px',
}}>
{result.success
- ? <CheckCircle size={10} style={{ color: F.GREEN }} />
- : <AlertCircle size={10} style={{ color: F.RED }} />
+ ? <CheckCircle size={10} style={{ color: colors.secondary }} />
+ : <AlertCircle size={10} style={{ color: colors.alert }} />
}
<span style={{
- fontSize: '9px', fontWeight: 700, fontFamily: FONT,
- color: result.success ? F.GREEN : F.RED,
+ fontSize: '9px', fontWeight: 700, fontFamily: fontFamily,
+ color: result.success ? colors.secondary : colors.alert,
letterSpacing: '0.5px',
}}>
- {result.success ? 'COMPLETED' : 'FAILED'}
+ {result.success ? t('output.completed') : t('output.failed')}
</span>
- <span style={{ color: F.MUTED, fontSize: '9px' }}>|</span>
- <span style={{ color: F.GRAY, fontSize: '9px', fontFamily: FONT, display: 'flex', alignItems: 'center', gap: '3px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '9px' }}>|</span>
+ <span style={{ color: colors.textMuted, fontSize: '9px', fontFamily: fontFamily, display: 'flex', alignItems: 'center', gap: '3px' }}>
<Clock size={9} /> {result.execution_time_ms}ms
</span>
{result.signals.length > 0 && (
<>
- <span style={{ color: F.MUTED, fontSize: '9px' }}>|</span>
- <span style={{ color: F.CYAN, fontSize: '9px', fontFamily: FONT }}>
- {result.signals.length} signals
+ <span style={{ color: colors.textMuted, fontSize: '9px' }}>|</span>
+ <span style={{ color: colors.accent, fontSize: '9px', fontFamily: fontFamily }}>
+ {result.signals.length} {t('output.signals')}
</span>
</>
)}
<div style={{ flex: 1 }} />
<button onClick={onClear} style={{
padding: '2px 6px', backgroundColor: 'transparent',
- border: `1px solid ${F.BORDER}`, borderRadius: '2px',
- color: F.GRAY, fontSize: '8px', fontWeight: 700,
- cursor: 'pointer', fontFamily: FONT,
+ border: `1px solid ${colors.panel}`, borderRadius: '2px',
+ color: colors.textMuted, fontSize: '8px', fontWeight: 700,
+ cursor: 'pointer', fontFamily: fontFamily,
letterSpacing: '0.5px',
}}>
- CLEAR
+ {t('output.clear')}
</button>
</div>
@@ -176,21 +164,21 @@ export const FinScriptOutputPanel: React.FC<FinScriptOutputPanelProps> = ({
{result.errors.length > 0 && (
<div style={{
marginBottom: '12px', padding: '8px',
- border: `1px solid ${F.RED}`, borderRadius: '2px',
- backgroundColor: `${F.RED}08`,
+ border: `1px solid ${colors.alert}`, borderRadius: '2px',
+ backgroundColor: `${colors.alert}08`,
}}>
<div style={{
display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px',
}}>
- <AlertCircle size={10} style={{ color: F.RED }} />
- <span style={{ color: F.RED, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', fontFamily: FONT }}>
- ERRORS ({result.errors.length})
+ <AlertCircle size={10} style={{ color: colors.alert }} />
+ <span style={{ color: colors.alert, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', fontFamily: fontFamily }}>
+ {t('output.errors')} ({result.errors.length})
</span>
</div>
{result.errors.map((error, idx) => (
<div key={idx} style={{
- color: F.RED, fontSize: '10px', marginBottom: '3px',
- paddingLeft: '16px', fontFamily: FONT, lineHeight: '1.4',
+ color: colors.alert, fontSize: '10px', marginBottom: '3px',
+ paddingLeft: '16px', fontFamily: fontFamily, lineHeight: '1.4',
}}>
{error}
</div>
@@ -204,37 +192,37 @@ export const FinScriptOutputPanel: React.FC<FinScriptOutputPanelProps> = ({
<div style={{
display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px',
}}>
- <BarChart2 size={10} style={{ color: F.CYAN }} />
- <span style={{ color: F.CYAN, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', fontFamily: FONT }}>
- SIGNALS ({result.signals.length})
+ <BarChart2 size={10} style={{ color: colors.accent }} />
+ <span style={{ color: colors.accent, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', fontFamily: fontFamily }}>
+ {t('output.signalsSection')} ({result.signals.length})
</span>
</div>
{result.signals.map((signal, idx) => (
<div key={idx} style={{
display: 'flex', alignItems: 'center', gap: '8px',
padding: '5px 8px', marginBottom: '3px',
- backgroundColor: signal.signal_type === 'Buy' ? `${F.GREEN}08` : `${F.RED}08`,
- border: `1px solid ${signal.signal_type === 'Buy' ? F.GREEN : F.RED}`,
+ backgroundColor: signal.signal_type === 'Buy' ? `${colors.secondary}08` : `${colors.alert}08`,
+ border: `1px solid ${signal.signal_type === 'Buy' ? colors.secondary : colors.alert}`,
borderRadius: '2px',
}}>
{signal.signal_type === 'Buy' ? (
- <TrendingUp size={11} style={{ color: F.GREEN }} />
+ <TrendingUp size={11} style={{ color: colors.secondary }} />
) : (
- <TrendingDown size={11} style={{ color: F.RED }} />
+ <TrendingDown size={11} style={{ color: colors.alert }} />
)}
<div style={{ flex: 1 }}>
<span style={{
- color: signal.signal_type === 'Buy' ? F.GREEN : F.RED,
- fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', fontFamily: FONT,
+ color: signal.signal_type === 'Buy' ? colors.secondary : colors.alert,
+ fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', fontFamily: fontFamily,
}}>
{signal.signal_type.toUpperCase()}
</span>
- <span style={{ color: F.WHITE, fontSize: '10px', marginLeft: '8px', fontFamily: FONT }}>
+ <span style={{ color: colors.text, fontSize: '10px', marginLeft: '8px', fontFamily: fontFamily }}>
{signal.message}
</span>
</div>
{signal.price && (
- <span style={{ color: F.YELLOW, fontSize: '10px', fontFamily: FONT, fontWeight: 700 }}>
+ <span style={{ color: colors.warning, fontSize: '10px', fontFamily: fontFamily, fontWeight: 700 }}>
${signal.price.toFixed(2)}
</span>
)}
@@ -249,18 +237,18 @@ export const FinScriptOutputPanel: React.FC<FinScriptOutputPanelProps> = ({
<div style={{
display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px',
}}>
- <TerminalIcon size={10} style={{ color: F.GREEN }} />
- <span style={{ color: F.GREEN, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', fontFamily: FONT }}>
- OUTPUT
+ <TerminalIcon size={10} style={{ color: colors.secondary }} />
+ <span style={{ color: colors.secondary, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', fontFamily: fontFamily }}>
+ {t('output.outputSection')}
</span>
</div>
<pre style={{
- color: F.WHITE, fontSize: '10px', margin: 0,
+ color: colors.text, fontSize: '10px', margin: 0,
whiteSpace: 'pre-wrap', wordBreak: 'break-word',
- fontFamily: FONT,
- backgroundColor: F.PANEL_BG,
+ fontFamily: fontFamily,
+ backgroundColor: colors.panel,
padding: '8px',
- border: `1px solid ${F.BORDER}`,
+ border: `1px solid ${colors.panel}`,
borderRadius: '2px',
lineHeight: '1.5',
}}>
@@ -275,13 +263,19 @@ export const FinScriptOutputPanel: React.FC<FinScriptOutputPanelProps> = ({
<div style={{
display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '8px',
}}>
- <BarChart2 size={10} style={{ color: F.ORANGE }} />
- <span style={{ color: F.ORANGE, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', fontFamily: FONT }}>
- CHARTS ({result.plots.length})
+ <BarChart2 size={10} style={{ color: colors.primary }} />
+ <span style={{ color: colors.primary, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', fontFamily: fontFamily }}>
+ {t('output.charts')} ({result.plots.length})
</span>
</div>
{result.plots.map((plot, idx) => (
- <FinScriptChart key={`${plot.label}-${idx}`} plot={plot} height={200} />
+ <FinScriptChart
+ key={`${plot.label}-${idx}`}
+ plot={plot}
+ height={200}
+ colors={{ background: colors.background, text: colors.text, panel: colors.panel }}
+ fontFamily={fontFamily}
+ />
))}
</div>
)}
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
index 990e49ee4..dc5f2682c 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
@@ -34,8 +34,6 @@ import type {
TradeData,
WatchlistPrice,
CenterViewType,
- RightPanelViewType,
- LeftSidebarViewType,
BottomPanelTabType,
} from './types';
@@ -265,21 +263,17 @@ export function CryptoTradingTab() {
const [showSymbolDropdown, setShowSymbolDropdown] = useState(false);
const [showBrokerDropdown, setShowBrokerDropdown] = useState(false);
const [selectedView, setSelectedView] = useState<CenterViewType>('chart');
- const [rightPanelView, setRightPanelView] = useState<RightPanelViewType>('orderbook');
- const [leftSidebarView, setLeftSidebarView] = useState<LeftSidebarViewType>('watchlist');
const [activeBottomTab, setActiveBottomTab] = useState<BottomPanelTabType>('positions');
const [isBottomPanelMinimized, setIsBottomPanelMinimized] = useState(false);
// Workspace tab state
const getWorkspaceState = useCallback(() => ({
- selectedSymbol, selectedView, rightPanelView, leftSidebarView, activeBottomTab, isBottomPanelMinimized,
- }), [selectedSymbol, selectedView, rightPanelView, leftSidebarView, activeBottomTab, isBottomPanelMinimized]);
+ selectedSymbol, selectedView, activeBottomTab, isBottomPanelMinimized,
+ }), [selectedSymbol, selectedView, activeBottomTab, isBottomPanelMinimized]);
const setWorkspaceState = useCallback((state: Record<string, unknown>) => {
if (typeof state.selectedSymbol === "string") setSelectedSymbol(state.selectedSymbol);
if (typeof state.selectedView === "string") setSelectedView(state.selectedView as any);
- if (typeof state.rightPanelView === "string") setRightPanelView(state.rightPanelView as any);
- if (typeof state.leftSidebarView === "string") setLeftSidebarView(state.leftSidebarView as any);
if (typeof state.activeBottomTab === "string") setActiveBottomTab(state.activeBottomTab as any);
if (typeof state.isBottomPanelMinimized === "boolean") setIsBottomPanelMinimized(state.isBottomPanelMinimized);
}, []);
@@ -901,11 +895,7 @@ export function CryptoTradingTab() {
watchlist={watchlist}
watchlistPrices={state.watchlistPrices}
selectedSymbol={selectedSymbol}
- leftSidebarView={leftSidebarView}
- positions={state.positions}
- equity={state.equity}
onSymbolSelect={handleSymbolSelect}
- onViewChange={setLeftSidebarView}
/>
</ErrorBoundary>
@@ -965,6 +955,7 @@ export function CryptoTradingTab() {
paperAdapter={paperAdapter}
realAdapter={realAdapter}
onTradingModeChange={setTradingMode}
+ onOrderPlaced={loadPaperTradingData}
/>
</ErrorBoundary>
@@ -974,8 +965,6 @@ export function CryptoTradingTab() {
currentPrice={currentPrice}
selectedSymbol={selectedSymbol}
activeBroker={activeBroker}
- rightPanelView={rightPanelView}
- onViewChange={setRightPanelView}
/>
</ErrorBoundary>
</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.tsx
index 66bbfd4b3..36f2d5d29 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
@@ -2,28 +2,25 @@
// Direct Kraken WebSocket connection with incremental updates
import React, { useCallback, useRef, useEffect, memo, useState } from 'react';
import { FINCEPT } from '../constants';
-import type { RightPanelViewType } from '../types';
import { VolumeProfile } from '../../trading/charts';
-import { ModelChatPanel } from '../../trading/ai-agents/ModelChatPanel';
import { ErrorBoundary } from '@/components/common/ErrorBoundary';
const NUM_LEVELS = 12;
+type OrderBookViewType = 'orderbook' | 'volume';
+
interface CryptoOrderBookProps {
currentPrice: number;
selectedSymbol: string;
activeBroker: string | null;
- rightPanelView: RightPanelViewType;
- onViewChange: (view: RightPanelViewType) => void;
}
export const CryptoOrderBook = memo(function CryptoOrderBook({
currentPrice,
selectedSymbol,
activeBroker,
- rightPanelView,
- onViewChange,
}: CryptoOrderBookProps) {
+ const [activeView, setActiveView] = useState<OrderBookViewType>('orderbook');
const [status, setStatus] = useState<'connecting' | 'connected' | 'disconnected'>('disconnected');
const wsRef = useRef<WebSocket | null>(null);
@@ -262,10 +259,6 @@ export const CryptoOrderBook = memo(function CryptoOrderBook({
}
}, [currentPrice]);
- const handleViewChange = useCallback((view: RightPanelViewType) => {
- onViewChange(view);
- }, [onViewChange]);
-
return (
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', backgroundColor: FINCEPT.PANEL_BG }}>
<style>{`
@@ -360,17 +353,17 @@ export const CryptoOrderBook = memo(function CryptoOrderBook({
backgroundColor: FINCEPT.HEADER_BG,
}}>
<div style={{ display: 'flex' }}>
- {(['orderbook', 'volume', 'modelchat'] as RightPanelViewType[]).map((view) => (
+ {(['orderbook', 'volume'] as OrderBookViewType[]).map((view) => (
<button
key={view}
- className={`tab-btn ${rightPanelView === view ? 'active' : ''}`}
- onClick={() => handleViewChange(view)}
+ className={`tab-btn ${activeView === view ? 'active' : ''}`}
+ onClick={() => setActiveView(view)}
>
- {view === 'orderbook' ? 'ORDER BOOK' : view === 'volume' ? 'VOLUME' : 'AI CHAT'}
+ {view === 'orderbook' ? 'ORDER BOOK' : 'VOLUME'}
</button>
))}
</div>
- {rightPanelView === 'orderbook' && (
+ {activeView === 'orderbook' && (
<div style={{ padding: '0 12px', fontSize: '9px', color: FINCEPT.GRAY }}>
<span ref={levelCountRef}>0</span> levels
</div>
@@ -378,7 +371,7 @@ export const CryptoOrderBook = memo(function CryptoOrderBook({
</div>
{/* Order Book Content */}
- {rightPanelView === 'orderbook' && (
+ {activeView === 'orderbook' && (
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
{/* Connection Status */}
<div style={{
@@ -497,22 +490,13 @@ export const CryptoOrderBook = memo(function CryptoOrderBook({
)}
{/* Volume Profile View */}
- {rightPanelView === 'volume' && (
+ {activeView === 'volume' && (
<div style={{ flex: 1, overflow: 'hidden', padding: '8px' }}>
<ErrorBoundary name="VolumeProfile" variant="minimal">
<VolumeProfile symbol={selectedSymbol} height={500} />
</ErrorBoundary>
</div>
)}
-
- {/* AI Chat View */}
- {rightPanelView === 'modelchat' && (
- <div style={{ flex: 1, overflow: 'hidden' }}>
- <ErrorBoundary name="ModelChatPanel" variant="minimal">
- <ModelChatPanel refreshInterval={5000} />
- </ErrorBoundary>
- </div>
- )}
</div>
);
});
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderEntry.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderEntry.tsx
index 85a0fb32a..b7d61d6bc 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderEntry.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderEntry.tsx
@@ -2,8 +2,6 @@
import React, { useState, useCallback, useMemo, useRef, useEffect } from 'react';
import { RefreshCw, TrendingUp, TrendingDown, AlertTriangle, Check, Loader2, ChevronDown, ChevronUp } from 'lucide-react';
import { FINCEPT } from '../constants';
-import { useBrokerContext } from '@/contexts/BrokerContext';
-import { ErrorBoundary } from '@/components/common/ErrorBoundary';
interface CryptoOrderEntryProps {
selectedSymbol: string;
@@ -17,6 +15,7 @@ interface CryptoOrderEntryProps {
realAdapter: any;
onTradingModeChange: (mode: 'paper' | 'live') => void;
onRetryConnection?: () => void;
+ onOrderPlaced?: () => void;
}
type OrderType = 'market' | 'limit' | 'stop-limit';
@@ -34,6 +33,7 @@ export function CryptoOrderEntry({
realAdapter,
onTradingModeChange,
onRetryConnection,
+ onOrderPlaced,
}: CryptoOrderEntryProps) {
// Order state
const [side, setSide] = useState<OrderSide>('buy');
@@ -45,6 +45,7 @@ export function CryptoOrderEntry({
const [showAdvanced, setShowAdvanced] = useState(false);
const [stopLoss, setStopLoss] = useState('');
const [takeProfit, setTakeProfit] = useState('');
+ const [orderMessage, setOrderMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
// Refs for input focus
const quantityInputRef = useRef<HTMLInputElement>(null);
@@ -107,7 +108,9 @@ export function CryptoOrderEntry({
if (quantityNum <= 0) errors.push('Enter quantity');
if ((orderType === 'limit' || orderType === 'stop-limit') && priceNum <= 0) errors.push('Enter price');
if (orderType === 'stop-limit' && (!stopPrice || parseFloat(stopPrice) <= 0)) errors.push('Enter stop price');
- if (side === 'buy' && total > balance && total > 0) errors.push('Insufficient balance');
+ // Include estimated fee (0.1%) in balance check
+ const totalWithFees = total + (total * 0.001);
+ if (side === 'buy' && totalWithFees > balance && total > 0) errors.push(`Insufficient balance ($${balance.toFixed(2)} available, $${totalWithFees.toFixed(2)} needed)`);
return { valid: errors.length === 0, errors };
}, [quantityNum, priceNum, orderType, stopPrice, side, total, balance]);
@@ -134,6 +137,7 @@ export function CryptoOrderEntry({
if (!validation.valid || !adapter || isPlacing) return;
setIsPlacing(true);
+ setOrderMessage(null);
try {
const parsedStopLoss = parseFloat(stopLoss) || undefined;
const parsedTakeProfit = parseFloat(takeProfit) || undefined;
@@ -166,12 +170,22 @@ export function CryptoOrderEntry({
setPriceInitialized(true);
}
- } catch (err) {
+ setOrderMessage({ type: 'success', text: `${side.toUpperCase()} ${quantityNum} ${selectedSymbol} ${orderType} order placed` });
+
+ // Trigger data refresh in parent
+ onOrderPlaced?.();
+
+ // Auto-clear message after 4 seconds
+ setTimeout(() => setOrderMessage(null), 4000);
+
+ } catch (err: any) {
console.error('[OrderEntry] Order failed:', err);
+ setOrderMessage({ type: 'error', text: err?.message || 'Order failed' });
+ setTimeout(() => setOrderMessage(null), 6000);
} finally {
setIsPlacing(false);
}
- }, [validation.valid, adapter, isPlacing, selectedSymbol, orderType, side, quantityNum, priceNum, currentPrice, stopLoss, takeProfit, stopPrice]);
+ }, [validation.valid, adapter, isPlacing, selectedSymbol, orderType, side, quantityNum, priceNum, currentPrice, stopLoss, takeProfit, stopPrice, onOrderPlaced]);
// Handle retry connection
const handleRetryConnection = useCallback(() => {
@@ -582,6 +596,24 @@ export function CryptoOrderEntry({
</div>
)}
+ {/* Order Result Message */}
+ {orderMessage && (
+ <div style={{
+ padding: '8px 12px',
+ marginBottom: '12px',
+ background: orderMessage.type === 'success' ? `${FINCEPT.GREEN}15` : `${FINCEPT.RED}15`,
+ borderLeft: `3px solid ${orderMessage.type === 'success' ? FINCEPT.GREEN : FINCEPT.RED}`,
+ color: orderMessage.type === 'success' ? FINCEPT.GREEN : FINCEPT.RED,
+ fontSize: '10px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}>
+ {orderMessage.type === 'success' ? <Check size={12} /> : <AlertTriangle size={12} />}
+ {orderMessage.text}
+ </div>
+ )}
+
{/* Submit Button */}
<button
onClick={handleSubmit}
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTickerBar.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTickerBar.tsx
index f1723e17a..5be68bc3a 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTickerBar.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTickerBar.tsx
@@ -1,7 +1,7 @@
// CryptoTickerBar.tsx - Ticker/Price Bar for Crypto Trading
// Uses ref-based DOM updates for high-frequency price changes to prevent flickering
-import React, { useRef, useEffect, memo } from 'react';
-import { TrendingUp as ArrowUp, TrendingDown as ArrowDown, ChevronDown } from 'lucide-react';
+import React, { useRef, useEffect } from 'react';
+import { ChevronDown } from 'lucide-react';
import { FINCEPT } from '../constants';
import type { TickerData } from '../types';
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoWatchlist.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoWatchlist.tsx
index 3d0587341..651535b93 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoWatchlist.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoWatchlist.tsx
@@ -1,32 +1,21 @@
// CryptoWatchlist.tsx - Professional Terminal-Style Left Sidebar Watchlist
import React from 'react';
-import { Star, Bot, Trophy, TrendingUp, TrendingDown } from 'lucide-react';
+import { Star, TrendingUp, TrendingDown } from 'lucide-react';
import { FINCEPT } from '../constants';
-import type { WatchlistPrice, LeftSidebarViewType, Position } from '../types';
-import { AIAgentsPanel } from '../../trading/ai-agents/AIAgentsPanel';
-import { LeaderboardPanel } from '../../trading/ai-agents/LeaderboardPanel';
-import { ErrorBoundary } from '@/components/common/ErrorBoundary';
+import type { WatchlistPrice } from '../types';
interface CryptoWatchlistProps {
watchlist: string[];
watchlistPrices: Record<string, WatchlistPrice>;
selectedSymbol: string;
- leftSidebarView: LeftSidebarViewType;
- positions: Position[];
- equity: number;
onSymbolSelect: (symbol: string) => void;
- onViewChange: (view: LeftSidebarViewType) => void;
}
export function CryptoWatchlist({
watchlist,
watchlistPrices,
selectedSymbol,
- leftSidebarView,
- positions,
- equity,
onSymbolSelect,
- onViewChange,
}: CryptoWatchlistProps) {
const formatPrice = (price: number) => {
if (price >= 1000) return price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
@@ -44,227 +33,160 @@ export function CryptoWatchlist({
overflow: 'hidden',
fontFamily: '"IBM Plex Mono", monospace',
}}>
- {/* Tab Header - Terminal style */}
+ {/* Header */}
<div style={{
- display: 'flex',
+ padding: '10px 12px',
backgroundColor: FINCEPT.HEADER_BG,
borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
}}>
- {[
- { id: 'watchlist' as LeftSidebarViewType, label: 'WATCH', icon: <Star size={10} /> },
- { id: 'ai-agents' as LeftSidebarViewType, label: 'AGENTS', icon: <Bot size={10} /> },
- { id: 'leaderboard' as LeftSidebarViewType, label: 'RANK', icon: <Trophy size={10} /> },
- ].map((tab) => {
- const isActive = leftSidebarView === tab.id;
+ <Star size={12} color={FINCEPT.ORANGE} />
+ <span style={{
+ fontSize: '11px',
+ fontWeight: 700,
+ color: FINCEPT.WHITE,
+ letterSpacing: '0.5px',
+ }}>
+ WATCHLIST
+ </span>
+ </div>
+
+ {/* Column Headers */}
+ <div style={{
+ padding: '8px 10px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.HEADER_BG,
+ }}>
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, fontWeight: 600, letterSpacing: '0.5px' }}>
+ SYMBOL
+ </span>
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, fontWeight: 600, letterSpacing: '0.5px' }}>
+ PRICE / 24H
+ </span>
+ </div>
+
+ {/* Watchlist Items */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {watchlist.map((symbol) => {
+ const data = watchlistPrices[symbol];
+ const isSelected = selectedSymbol === symbol;
+ const isPositive = data && data.change >= 0;
+
return (
- <button
- key={tab.id}
- onClick={() => onViewChange(tab.id)}
+ <div
+ key={symbol}
+ onClick={() => onSymbolSelect(symbol)}
style={{
- flex: 1,
- padding: '8px 6px',
- backgroundColor: isActive ? FINCEPT.ORANGE : 'transparent',
- border: 'none',
- borderBottom: isActive ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
- color: isActive ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ padding: '8px 10px',
cursor: 'pointer',
- fontSize: '9px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- gap: '4px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}20`,
+ borderLeft: isSelected ? `3px solid ${FINCEPT.ORANGE}` : '3px solid transparent',
+ backgroundColor: isSelected ? `${FINCEPT.ORANGE}10` : 'transparent',
transition: 'all 0.15s',
}}
onMouseEnter={(e) => {
- if (!isActive) {
+ if (!isSelected) {
e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- e.currentTarget.style.color = FINCEPT.WHITE;
}
}}
onMouseLeave={(e) => {
- if (!isActive) {
+ if (!isSelected) {
e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = FINCEPT.GRAY;
}
}}
>
- {tab.icon}
- {tab.label}
- </button>
- );
- })}
- </div>
-
- {/* Content */}
- <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
- {leftSidebarView === 'watchlist' && (
- <>
- {/* Watchlist Header */}
- <div style={{
- padding: '8px 10px',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.HEADER_BG,
- }}>
- <span style={{ fontSize: '9px', color: FINCEPT.GRAY, fontWeight: 600, letterSpacing: '0.5px' }}>
- SYMBOL
- </span>
- <span style={{ fontSize: '9px', color: FINCEPT.GRAY, fontWeight: 600, letterSpacing: '0.5px' }}>
- PRICE / 24H
- </span>
- </div>
-
- {/* Watchlist Items */}
- <div style={{ flex: 1, overflow: 'auto' }}>
- {watchlist.map((symbol) => {
- const data = watchlistPrices[symbol];
- const isSelected = selectedSymbol === symbol;
- const isPositive = data && data.change >= 0;
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ }}>
+ {/* Symbol */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <div style={{
+ width: '24px',
+ height: '24px',
+ backgroundColor: `${isSelected ? FINCEPT.ORANGE : FINCEPT.GRAY}20`,
+ border: `1px solid ${isSelected ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: '8px',
+ fontWeight: 700,
+ color: isSelected ? FINCEPT.ORANGE : FINCEPT.WHITE,
+ }}>
+ {symbol.replace('/USD', '').slice(0, 3)}
+ </div>
+ <div>
+ <div style={{
+ fontSize: '11px',
+ fontWeight: 600,
+ color: isSelected ? FINCEPT.ORANGE : FINCEPT.WHITE,
+ }}>
+ {symbol.replace('/USD', '')}
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>
+ USD
+ </div>
+ </div>
+ </div>
- return (
- <div
- key={symbol}
- onClick={() => onSymbolSelect(symbol)}
- style={{
- padding: '8px 10px',
- cursor: 'pointer',
- borderBottom: `1px solid ${FINCEPT.BORDER}20`,
- borderLeft: isSelected ? `3px solid ${FINCEPT.ORANGE}` : '3px solid transparent',
- backgroundColor: isSelected ? `${FINCEPT.ORANGE}10` : 'transparent',
- transition: 'all 0.15s',
- }}
- onMouseEnter={(e) => {
- if (!isSelected) {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- }
- }}
- onMouseLeave={(e) => {
- if (!isSelected) {
- e.currentTarget.style.backgroundColor = 'transparent';
- }
- }}
- >
+ {/* Price & Change */}
+ {data ? (
+ <div style={{ textAlign: 'right' }}>
+ <div style={{
+ fontSize: '11px',
+ fontWeight: 600,
+ color: FINCEPT.WHITE,
+ }}>
+ ${formatPrice(data.price)}
+ </div>
<div style={{
display: 'flex',
- justifyContent: 'space-between',
alignItems: 'center',
+ justifyContent: 'flex-end',
+ gap: '3px',
+ fontSize: '9px',
+ fontWeight: 600,
+ color: isPositive ? FINCEPT.GREEN : FINCEPT.RED,
}}>
- {/* Symbol */}
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <div style={{
- width: '24px',
- height: '24px',
- backgroundColor: `${isSelected ? FINCEPT.ORANGE : FINCEPT.GRAY}20`,
- border: `1px solid ${isSelected ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- fontSize: '8px',
- fontWeight: 700,
- color: isSelected ? FINCEPT.ORANGE : FINCEPT.WHITE,
- }}>
- {symbol.replace('/USD', '').slice(0, 3)}
- </div>
- <div>
- <div style={{
- fontSize: '11px',
- fontWeight: 600,
- color: isSelected ? FINCEPT.ORANGE : FINCEPT.WHITE,
- }}>
- {symbol.replace('/USD', '')}
- </div>
- <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>
- USD
- </div>
- </div>
- </div>
-
- {/* Price & Change */}
- {data ? (
- <div style={{ textAlign: 'right' }}>
- <div style={{
- fontSize: '11px',
- fontWeight: 600,
- color: FINCEPT.WHITE,
- }}>
- ${formatPrice(data.price)}
- </div>
- <div style={{
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'flex-end',
- gap: '3px',
- fontSize: '9px',
- fontWeight: 600,
- color: isPositive ? FINCEPT.GREEN : FINCEPT.RED,
- }}>
- {isPositive ? <TrendingUp size={9} /> : <TrendingDown size={9} />}
- {isPositive ? '+' : ''}{data.change.toFixed(2)}%
- </div>
- </div>
- ) : (
- <div style={{
- fontSize: '9px',
- color: FINCEPT.GRAY,
- }}>
- Loading...
- </div>
- )}
+ {isPositive ? <TrendingUp size={9} /> : <TrendingDown size={9} />}
+ {isPositive ? '+' : ''}{data.change.toFixed(2)}%
</div>
</div>
- );
- })}
- </div>
-
- {/* Footer Stats */}
- <div style={{
- padding: '8px 10px',
- borderTop: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.HEADER_BG,
- fontSize: '9px',
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: FINCEPT.GRAY }}>ASSETS</span>
- <span style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>{watchlist.length}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: FINCEPT.GRAY }}>UPDATED</span>
- <span style={{ color: FINCEPT.CYAN }}>{new Date().toLocaleTimeString()}</span>
+ ) : (
+ <div style={{
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ }}>
+ Loading...
+ </div>
+ )}
</div>
</div>
- </>
- )}
-
- {leftSidebarView === 'ai-agents' && (
- <div style={{ flex: 1, overflow: 'auto' }}>
- <ErrorBoundary name="AIAgentsPanel" variant="minimal">
- <AIAgentsPanel
- selectedSymbol={selectedSymbol}
- portfolioData={{
- positions: positions.map(p => ({
- symbol: p.symbol,
- quantity: p.quantity,
- entry_price: p.entryPrice,
- current_price: p.currentPrice,
- value: p.positionValue
- })),
- total_value: equity
- }}
- />
- </ErrorBoundary>
- </div>
- )}
+ );
+ })}
+ </div>
- {leftSidebarView === 'leaderboard' && (
- <div style={{ flex: 1, overflow: 'hidden' }}>
- <ErrorBoundary name="LeaderboardPanel" variant="minimal">
- <LeaderboardPanel refreshInterval={10000} />
- </ErrorBoundary>
- </div>
- )}
+ {/* Footer Stats */}
+ <div style={{
+ padding: '8px 10px',
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.HEADER_BG,
+ fontSize: '9px',
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
+ <span style={{ color: FINCEPT.GRAY }}>ASSETS</span>
+ <span style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>{watchlist.length}</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.GRAY }}>UPDATED</span>
+ <span style={{ color: FINCEPT.CYAN }}>{new Date().toLocaleTimeString()}</span>
+ </div>
</div>
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/index.ts b/fincept-terminal-desktop/src/components/tabs/crypto-trading/index.ts
index 60fc7cef4..59a810fe1 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/index.ts
@@ -12,8 +12,6 @@ export type {
TradeData,
WatchlistPrice,
CenterViewType,
- RightPanelViewType,
- LeftSidebarViewType,
BottomPanelTabType,
} from './types';
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/types.ts b/fincept-terminal-desktop/src/components/tabs/crypto-trading/types.ts
index 13818c116..70846c2f0 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/types.ts
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/types.ts
@@ -64,6 +64,6 @@ export interface WatchlistPrice {
// UI State Types
export type CenterViewType = 'chart' | 'depth' | 'trades' | 'algo';
-export type RightPanelViewType = 'orderbook' | 'volume' | 'modelchat';
-export type LeftSidebarViewType = 'watchlist' | 'ai-agents' | 'leaderboard';
export type BottomPanelTabType = 'positions' | 'orders' | 'history' | 'trades' | 'stats' | 'features' | 'cross-exchange' | 'grid-trading' | 'monitoring';
+export type RightPanelViewType = 'orderbook' | 'order' | 'chat';
+export type LeftSidebarViewType = 'watchlist' | 'positions' | 'orders';
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokersManagementPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokersManagementPanel.tsx
index b50d93fb2..8c1f0c5b8 100644
--- a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokersManagementPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokersManagementPanel.tsx
@@ -1036,122 +1036,294 @@ export function BrokersManagementPanel() {
</h3>
</div>
- {/* API Key / UCC / Vendor Code */}
- <div style={{ marginBottom: '12px' }}>
- <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
- {selectedBroker.id === 'kotak' ? 'UCC (USER CLIENT CODE)' : selectedBroker.id === 'shoonya' ? 'VENDOR CODE' : 'API KEY / APP ID'} <span style={{ color: COLORS.RED }}>*</span>
- </label>
- <input
- type="text"
- value={config.apiKey}
- onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}
- placeholder={
- selectedBroker.id === 'kotak' ? 'Enter your UCC (e.g., KS12345)' :
- selectedBroker.id === 'shoonya' ? 'Enter your Vendor Code' :
- `Enter your ${selectedBroker.displayName} API Key`
- }
- style={{
- width: '100%',
- padding: '10px 12px',
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- fontSize: '12px',
- fontFamily: 'monospace',
- outline: 'none',
- boxSizing: 'border-box',
- }}
- />
- {selectedBroker.id === 'kotak' && (
- <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Your UCC (User Client Code) - Primary identifier
- </p>
- )}
- {selectedBroker.id === 'shoonya' && (
- <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Vendor Code from Shoonya API settings
- </p>
- )}
- </div>
-
- {/* Mobile Number (Kotak only) */}
- {selectedBroker.id === 'kotak' && (
- <div style={{ marginBottom: '12px' }}>
- <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
- MOBILE NUMBER <span style={{ color: COLORS.RED }}>*</span>
- </label>
- <input
- type="text"
- value={mobileNumber}
- onChange={(e) => setMobileNumber(e.target.value)}
- placeholder="10-digit mobile number"
- style={{
- width: '100%',
- padding: '10px 12px',
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- fontSize: '12px',
- fontFamily: 'monospace',
- outline: 'none',
- boxSizing: 'border-box',
- }}
- />
- <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Will be prefixed with +91 automatically
- </p>
- </div>
+ {/* ============================================================ */}
+ {/* BROKER-SPECIFIC AUTHENTICATION FORMS */}
+ {/* Based on OpenAlgo authentication patterns */}
+ {/* ============================================================ */}
+
+ {/* ------------------------------------------------------------ */}
+ {/* OAUTH BROKERS: Zerodha, Fyers, Upstox, Dhan, IIFL, IBKR, Saxo */}
+ {/* Fields: API Key + API Secret */}
+ {/* ------------------------------------------------------------ */}
+ {['zerodha', 'fyers', 'upstox', 'dhan', 'iifl', 'ibkr', 'saxobank', 'flattrade'].includes(selectedBroker.id) && (
+ <>
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ {selectedBroker.id === 'fyers' ? 'APP ID' :
+ selectedBroker.id === 'dhan' ? 'CLIENT ID' :
+ selectedBroker.id === 'flattrade' ? 'API KEY (userid:::api_key format)' :
+ 'API KEY'} <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <input
+ type="text"
+ value={config.apiKey}
+ onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}
+ placeholder={
+ selectedBroker.id === 'fyers' ? 'Enter your Fyers App ID (e.g., XYZ123-100)' :
+ selectedBroker.id === 'dhan' ? 'Enter your Dhan Client ID' :
+ selectedBroker.id === 'flattrade' ? 'Enter API Key (userid:::api_key)' :
+ `Enter your ${selectedBroker.displayName} API Key`
+ }
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ </div>
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ {selectedBroker.id === 'fyers' ? 'SECRET KEY' : 'API SECRET'} <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <div style={{ position: 'relative' }}>
+ <input
+ type={showSecret ? 'text' : 'password'}
+ value={config.apiSecret || ''}
+ onChange={(e) => setConfig({ ...config, apiSecret: e.target.value })}
+ placeholder="Enter your API Secret"
+ style={{
+ width: '100%',
+ padding: '10px 40px 10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <button
+ type="button"
+ onClick={() => setShowSecret(!showSecret)}
+ style={{
+ position: 'absolute',
+ right: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ background: 'none',
+ border: 'none',
+ color: COLORS.GRAY,
+ cursor: 'pointer',
+ }}
+ >
+ {showSecret ? <EyeOff size={16} /> : <Eye size={16} />}
+ </button>
+ </div>
+ {selectedBroker.id === 'fyers' && (
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ Hash is generated as SHA256(api_key:api_secret) for token exchange
+ </p>
+ )}
+ {selectedBroker.id === 'flattrade' && (
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ Security hash: SHA256(api_key + request_code + api_secret)
+ </p>
+ )}
+ </div>
+ </>
)}
- {/* MPIN (Kotak only) */}
+ {/* ------------------------------------------------------------ */}
+ {/* KOTAK NEO: UCC + Mobile + MPIN + TOTP (2-step auth) */}
+ {/* Step 1: TOTP login → view_token */}
+ {/* Step 2: MPIN validation → trading_token */}
+ {/* ------------------------------------------------------------ */}
{selectedBroker.id === 'kotak' && (
- <div style={{ marginBottom: '12px' }}>
- <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
- MPIN (6-DIGIT TRADING PIN) <span style={{ color: COLORS.RED }}>*</span>
- </label>
- <input
- type={showSecret ? 'text' : 'password'}
- value={config.userId || ''}
- onChange={(e) => setConfig({ ...config, userId: e.target.value.replace(/\D/g, '').slice(0, 6) })}
- placeholder="Enter your 6-digit MPIN"
- maxLength={6}
- style={{
- width: '100%',
- padding: '10px 12px',
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- fontSize: '16px',
- fontFamily: 'monospace',
- textAlign: 'center',
- letterSpacing: '4px',
- outline: 'none',
- boxSizing: 'border-box',
- }}
- />
- <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Your 6-digit trading MPIN
- </p>
- </div>
- )}
+ <>
+ {/* UCC */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ UCC (USER CLIENT CODE) <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <input
+ type="text"
+ value={config.apiKey}
+ onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}
+ placeholder="e.g., KS12345"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ Your UCC (User Client Code) - Primary identifier
+ </p>
+ </div>
- {/* API Secret (for OAuth) or Access Token (for Kotak) or API Secret Key (for Shoonya) */}
- {(selectedBroker.authType === 'oauth' || selectedBroker.id === 'kotak' || selectedBroker.id === 'shoonya') && (
- <div style={{ marginBottom: '12px' }}>
- <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
- {selectedBroker.id === 'kotak' ? 'ACCESS TOKEN (NEO-FIN-KEY)' :
- selectedBroker.id === 'shoonya' ? 'API SECRET KEY' :
- 'API SECRET'} <span style={{ color: COLORS.RED }}>*</span>
- </label>
- <div style={{ position: 'relative' }}>
+ {/* Access Token / NEO-FIN-KEY */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ ACCESS TOKEN (NEO-FIN-KEY) <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <div style={{ position: 'relative' }}>
+ <input
+ type={showSecret ? 'text' : 'password'}
+ value={config.apiSecret || ''}
+ onChange={(e) => setConfig({ ...config, apiSecret: e.target.value })}
+ placeholder="Enter your Access Token"
+ style={{
+ width: '100%',
+ padding: '10px 40px 10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <button
+ type="button"
+ onClick={() => setShowSecret(!showSecret)}
+ style={{
+ position: 'absolute',
+ right: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ background: 'none',
+ border: 'none',
+ color: COLORS.GRAY,
+ cursor: 'pointer',
+ }}
+ >
+ {showSecret ? <EyeOff size={16} /> : <Eye size={16} />}
+ </button>
+ </div>
+ </div>
+
+ {/* Mobile Number */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ MOBILE NUMBER <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: COLORS.GRAY, fontSize: '12px', fontFamily: 'monospace' }}>+91</span>
+ <input
+ type="text"
+ value={mobileNumber}
+ onChange={(e) => setMobileNumber(e.target.value.replace(/\D/g, '').slice(0, 10))}
+ placeholder="9999955555"
+ maxLength={10}
+ style={{
+ flex: 1,
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ </div>
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ 10-digit mobile number (auto-prefixed with +91)
+ </p>
+ </div>
+
+ {/* MPIN */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ MPIN (6-DIGIT) <span style={{ color: COLORS.RED }}>*</span>
+ </label>
<input
type={showSecret ? 'text' : 'password'}
- value={config.apiSecret || ''}
- onChange={(e) => setConfig({ ...config, apiSecret: e.target.value })}
- placeholder="Enter your API Secret"
+ value={(config as any).mpin || ''}
+ onChange={(e) => setConfig({ ...config, mpin: e.target.value.replace(/\D/g, '').slice(0, 6) } as any)}
+ placeholder="******"
+ maxLength={6}
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '16px',
+ fontFamily: 'monospace',
+ textAlign: 'center',
+ letterSpacing: '4px',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ Your 6-digit trading MPIN
+ </p>
+ </div>
+
+ {/* TOTP Code */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ TOTP CODE <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <input
+ type="text"
+ value={(config as any).totpCode || ''}
+ onChange={(e) => setConfig({ ...config, totpCode: e.target.value.replace(/\D/g, '').slice(0, 6) } as any)}
+ placeholder="123456"
+ maxLength={6}
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '16px',
+ fontFamily: 'monospace',
+ textAlign: 'center',
+ letterSpacing: '4px',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ 6-digit code from Google/Microsoft Authenticator
+ </p>
+ </div>
+
+ {/* Kotak Auth Info */}
+ <div style={{ padding: '10px', backgroundColor: `${COLORS.YELLOW}10`, border: `1px solid ${COLORS.YELLOW}40`, marginBottom: '12px' }}>
+ <p style={{ color: COLORS.YELLOW, fontSize: '9px', margin: 0 }}>
+ <strong>TOTP Registration Required:</strong> You must register TOTP in the NEO app before using this feature.
+ </p>
+ </div>
+ </>
+ )}
+
+ {/* ------------------------------------------------------------ */}
+ {/* GROWW: API Key + API Secret (Server-side TOTP) */}
+ {/* TOTP is generated server-side from API Secret */}
+ {/* ------------------------------------------------------------ */}
+ {selectedBroker.id === 'groww' && (
+ <>
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ API KEY <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <input
+ type="text"
+ value={config.apiKey}
+ onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}
+ placeholder="Enter your Groww API Key"
style={{
width: '100%',
- padding: '10px 40px 10px 12px',
+ padding: '10px 12px',
backgroundColor: COLORS.PANEL_BG,
border: `1px solid ${COLORS.BORDER}`,
color: COLORS.WHITE,
@@ -1161,29 +1333,222 @@ export function BrokersManagementPanel() {
boxSizing: 'border-box',
}}
/>
- <button
- type="button"
- onClick={() => setShowSecret(!showSecret)}
+ </div>
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ API SECRET (TOTP SECRET) <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <div style={{ position: 'relative' }}>
+ <input
+ type={showSecret ? 'text' : 'password'}
+ value={config.apiSecret || ''}
+ onChange={(e) => setConfig({ ...config, apiSecret: e.target.value })}
+ placeholder="Enter your API Secret"
+ style={{
+ width: '100%',
+ padding: '10px 40px 10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <button
+ type="button"
+ onClick={() => setShowSecret(!showSecret)}
+ style={{
+ position: 'absolute',
+ right: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ background: 'none',
+ border: 'none',
+ color: COLORS.GRAY,
+ cursor: 'pointer',
+ }}
+ >
+ {showSecret ? <EyeOff size={16} /> : <Eye size={16} />}
+ </button>
+ </div>
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ TOTP is generated automatically from this secret - no manual entry required
+ </p>
+ </div>
+ </>
+ )}
+
+ {/* ------------------------------------------------------------ */}
+ {/* US BROKERS: Alpaca, Tradier */}
+ {/* Simple API Key authentication */}
+ {/* ------------------------------------------------------------ */}
+ {['alpaca', 'tradier'].includes(selectedBroker.id) && (
+ <>
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ {selectedBroker.id === 'tradier' ? 'ACCESS TOKEN' : 'API KEY ID'} <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <input
+ type={selectedBroker.id === 'tradier' ? 'password' : 'text'}
+ value={config.apiKey}
+ onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}
+ placeholder={selectedBroker.id === 'tradier' ? 'Enter your Tradier Access Token' : 'Enter your Alpaca API Key ID'}
style={{
- position: 'absolute',
- right: '10px',
- top: '50%',
- transform: 'translateY(-50%)',
- background: 'none',
- border: 'none',
- color: COLORS.GRAY,
- cursor: 'pointer',
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
}}
- >
- {showSecret ? <EyeOff size={16} /> : <Eye size={16} />}
- </button>
+ />
</div>
+ {selectedBroker.id === 'alpaca' && (
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ SECRET KEY <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <div style={{ position: 'relative' }}>
+ <input
+ type={showSecret ? 'text' : 'password'}
+ value={config.apiSecret || ''}
+ onChange={(e) => setConfig({ ...config, apiSecret: e.target.value })}
+ placeholder="Enter your Alpaca Secret Key"
+ style={{
+ width: '100%',
+ padding: '10px 40px 10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <button
+ type="button"
+ onClick={() => setShowSecret(!showSecret)}
+ style={{
+ position: 'absolute',
+ right: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ background: 'none',
+ border: 'none',
+ color: COLORS.GRAY,
+ cursor: 'pointer',
+ }}
+ >
+ {showSecret ? <EyeOff size={16} /> : <Eye size={16} />}
+ </button>
+ </div>
+ </div>
+ )}
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ {selectedBroker.id === 'tradier' ? 'Tradier uses a single bearer token for authentication' : 'Use paper trading keys for testing'}
+ </p>
+ </>
+ )}
+
+ {/* ------------------------------------------------------------ */}
+ {/* YFINANCE: No authentication required */}
+ {/* ------------------------------------------------------------ */}
+ {selectedBroker.id === 'yfinance' && (
+ <div style={{ padding: '16px', backgroundColor: `${COLORS.GREEN}10`, border: `1px solid ${COLORS.GREEN}40`, marginBottom: '12px' }}>
+ <p style={{ color: COLORS.GREEN, fontSize: '11px', margin: 0, fontWeight: 600 }}>
+ No API keys required
+ </p>
+ <p style={{ color: COLORS.GRAY, fontSize: '10px', margin: '8px 0 0 0' }}>
+ YFinance provides free market data for paper trading. Click "Save Configuration" to activate paper trading mode.
+ </p>
</div>
)}
- {/* Shoonya-specific fields: User ID, Password, TOTP */}
+ {/* ------------------------------------------------------------ */}
+ {/* SHOONYA (FINVASIA): SHA256 Hash-based Authentication */}
+ {/* Fields: Vendor Code, API Secret, User ID, Password, TOTP */}
+ {/* Hash: SHA256(password), AppKey: SHA256(userid|api_secret) */}
+ {/* ------------------------------------------------------------ */}
{selectedBroker.id === 'shoonya' && (
<>
+ {/* Vendor Code */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ VENDOR CODE <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <input
+ type="text"
+ value={config.apiKey || ''}
+ onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}
+ placeholder="Enter your Vendor Code"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ Vendor Code from Shoonya API settings
+ </p>
+ </div>
+
+ {/* API Secret Key */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ API SECRET KEY <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <div style={{ position: 'relative' }}>
+ <input
+ type={showSecret ? 'text' : 'password'}
+ value={config.apiSecret || ''}
+ onChange={(e) => setConfig({ ...config, apiSecret: e.target.value })}
+ placeholder="Enter your API Secret Key"
+ style={{
+ width: '100%',
+ padding: '10px 40px 10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <button
+ type="button"
+ onClick={() => setShowSecret(!showSecret)}
+ style={{
+ position: 'absolute',
+ right: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ background: 'none',
+ border: 'none',
+ color: COLORS.GRAY,
+ cursor: 'pointer',
+ }}
+ >
+ {showSecret ? <EyeOff size={16} /> : <Eye size={16} />}
+ </button>
+ </div>
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ Used to generate AppKey hash: SHA256(userid|api_secret)
+ </p>
+ </div>
+
{/* User ID */}
<div style={{ marginBottom: '12px' }}>
<label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
@@ -1265,7 +1630,7 @@ export function BrokersManagementPanel() {
type="text"
value={(config as any).totpCode || ''}
onChange={(e) => setConfig({ ...config, totpCode: e.target.value.replace(/\D/g, '').slice(0, 6) } as any)}
- placeholder="Enter 6-digit TOTP"
+ placeholder="123456"
maxLength={6}
style={{
width: '100%',
@@ -1282,15 +1647,46 @@ export function BrokersManagementPanel() {
}}
/>
<p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- TOTP code from your authenticator app
+ 6-digit TOTP from your authenticator app
</p>
</div>
</>
)}
- {/* AngelOne-specific fields: Client ID, PIN, TOTP */}
+ {/* ------------------------------------------------------------ */}
+ {/* ANGEL ONE: TOTP-based Authentication */}
+ {/* Fields: API Key, Client ID, PIN, TOTP Secret */}
+ {/* Headers: X-PrivateKey (api_key), Content-Type */}
+ {/* ------------------------------------------------------------ */}
{selectedBroker.id === 'angelone' && (
<>
+ {/* API Key */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ API KEY <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <input
+ type="text"
+ value={config.apiKey || ''}
+ onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}
+ placeholder="Enter your SmartAPI Key"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ Your Angel One SmartAPI Key from publisher dashboard
+ </p>
+ </div>
+
{/* Client ID (Trading Account) */}
<div style={{ marginBottom: '12px' }}>
<label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
@@ -1300,7 +1696,7 @@ export function BrokersManagementPanel() {
type="text"
value={config.userId || ''}
onChange={(e) => setConfig({ ...config, userId: e.target.value.toUpperCase() })}
- placeholder="e.g. T55289 (your Angel One login ID)"
+ placeholder="e.g. T55289"
style={{
width: '100%',
padding: '10px 12px',
@@ -1314,7 +1710,7 @@ export function BrokersManagementPanel() {
}}
/>
<p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Your Angel One trading account login ID (NOT the API secret UUID)
+ Your Angel One trading account login ID (letters and numbers only)
</p>
</div>
@@ -1328,7 +1724,7 @@ export function BrokersManagementPanel() {
type={showSecret ? 'text' : 'password'}
value={(config as any).pin || ''}
onChange={(e) => setConfig({ ...config, pin: e.target.value } as any)}
- placeholder="Enter your PIN"
+ placeholder="Enter your trading PIN"
minLength={4}
style={{
width: '100%',
@@ -1360,7 +1756,7 @@ export function BrokersManagementPanel() {
</button>
</div>
<p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Your Angel One trading account PIN
+ Your Angel One account PIN (minimum 4 digits)
</p>
</div>
@@ -1374,7 +1770,7 @@ export function BrokersManagementPanel() {
type={showSecret ? 'text' : 'password'}
value={(config as any).totpSecret || ''}
onChange={(e) => setConfig({ ...config, totpSecret: e.target.value.trim() } as any)}
- placeholder="Enter your TOTP secret string"
+ placeholder="Enter your TOTP secret key"
style={{
width: '100%',
padding: '10px 40px 10px 12px',
@@ -1405,13 +1801,25 @@ export function BrokersManagementPanel() {
</button>
</div>
<p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Base32 secret key from Angel One TOTP setup. Enables automated login.
+ Base32 secret key from Angel One TOTP setup (enables automated login)
+ </p>
+ </div>
+
+ {/* Angel One Auth Info */}
+ <div style={{ padding: '10px', backgroundColor: `${COLORS.CYAN}10`, border: `1px solid ${COLORS.CYAN}40`, marginBottom: '12px' }}>
+ <p style={{ color: COLORS.CYAN, fontSize: '9px', margin: 0 }}>
+ <strong>Note:</strong> 6-digit TOTP is generated automatically from the TOTP secret. Authentication happens immediately on save.
</p>
</div>
</>
)}
- {/* AliceBlue-specific fields: User ID, Encryption Key */}
+ {/* ------------------------------------------------------------ */}
+ {/* ALICE BLUE: Encryption Key-based Authentication */}
+ {/* Fields: User ID, API Key, API Secret */}
+ {/* Step 1: Get encKey from API using User ID */}
+ {/* Step 2: Generate checksum: SHA256(userid + api_secret + encKey) */}
+ {/* ------------------------------------------------------------ */}
{selectedBroker.id === 'aliceblue' && (
<>
{/* User ID */}
@@ -1422,7 +1830,7 @@ export function BrokersManagementPanel() {
<input
type="text"
value={config.userId || ''}
- onChange={(e) => setConfig({ ...config, userId: e.target.value })}
+ onChange={(e) => setConfig({ ...config, userId: e.target.value.toUpperCase() })}
placeholder="Enter your AliceBlue User ID"
style={{
width: '100%',
@@ -1441,17 +1849,44 @@ export function BrokersManagementPanel() {
</p>
</div>
- {/* Encryption Key */}
+ {/* API Key */}
<div style={{ marginBottom: '12px' }}>
<label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
- ENCRYPTION KEY <span style={{ color: COLORS.RED }}>*</span>
+ API KEY <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <input
+ type="text"
+ value={config.apiKey || ''}
+ onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}
+ placeholder="Enter your API Key"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ Your AliceBlue API Key
+ </p>
+ </div>
+
+ {/* API Secret */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ API SECRET <span style={{ color: COLORS.RED }}>*</span>
</label>
<div style={{ position: 'relative' }}>
<input
type={showSecret ? 'text' : 'password'}
- value={(config as any).encryptionKey || ''}
- onChange={(e) => setConfig({ ...config, encryptionKey: e.target.value } as any)}
- placeholder="Enter your Encryption Key"
+ value={config.apiSecret || ''}
+ onChange={(e) => setConfig({ ...config, apiSecret: e.target.value })}
+ placeholder="Enter your API Secret"
style={{
width: '100%',
padding: '10px 40px 10px 12px',
@@ -1482,25 +1917,104 @@ export function BrokersManagementPanel() {
</button>
</div>
<p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Your AliceBlue Encryption Key (encKey)
+ Your AliceBlue API Secret
+ </p>
+ </div>
+
+ {/* AliceBlue Auth Info */}
+ <div style={{ padding: '10px', backgroundColor: `${COLORS.CYAN}10`, border: `1px solid ${COLORS.CYAN}40`, marginBottom: '12px' }}>
+ <p style={{ color: COLORS.CYAN, fontSize: '9px', margin: 0 }}>
+ <strong>Auth Flow:</strong> Encryption key is fetched automatically. Checksum generated as SHA256(userid + api_secret + encKey)
</p>
</div>
</>
)}
- {/* 5Paisa-specific fields: Email, PIN, TOTP */}
+ {/* ------------------------------------------------------------ */}
+ {/* 5PAISA: TOTP-based Authentication */}
+ {/* Fields: App Name/User Key, App Secret, Client Code/Mobile, PIN, TOTP */}
+ {/* ------------------------------------------------------------ */}
{selectedBroker.id === 'fivepaisa' && (
<>
- {/* Email ID */}
+ {/* App Name / User Key */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ APP NAME / USER KEY <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <input
+ type="text"
+ value={config.apiKey || ''}
+ onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}
+ placeholder="Enter your App Name or User Key"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ Your 5Paisa App Name or User Key
+ </p>
+ </div>
+
+ {/* App Secret / Encryption Key */}
<div style={{ marginBottom: '12px' }}>
<label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
- EMAIL ID <span style={{ color: COLORS.RED }}>*</span>
+ APP SECRET / ENCRYPTION KEY <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <div style={{ position: 'relative' }}>
+ <input
+ type={showSecret ? 'text' : 'password'}
+ value={config.apiSecret || ''}
+ onChange={(e) => setConfig({ ...config, apiSecret: e.target.value })}
+ placeholder="Enter your App Secret"
+ style={{
+ width: '100%',
+ padding: '10px 40px 10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <button
+ type="button"
+ onClick={() => setShowSecret(!showSecret)}
+ style={{
+ position: 'absolute',
+ right: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ background: 'none',
+ border: 'none',
+ color: COLORS.GRAY,
+ cursor: 'pointer',
+ }}
+ >
+ {showSecret ? <EyeOff size={16} /> : <Eye size={16} />}
+ </button>
+ </div>
+ </div>
+
+ {/* Client Code / Mobile Number */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ CLIENT CODE / MOBILE NO <span style={{ color: COLORS.RED }}>*</span>
</label>
<input
- type="email"
- value={(config as any).email || ''}
- onChange={(e) => setConfig({ ...config, email: e.target.value } as any)}
- placeholder="Enter your 5Paisa Email ID"
+ type="text"
+ value={config.userId || ''}
+ onChange={(e) => setConfig({ ...config, userId: e.target.value })}
+ placeholder="Enter Client Code or Mobile Number"
style={{
width: '100%',
padding: '10px 12px',
@@ -1514,7 +2028,7 @@ export function BrokersManagementPanel() {
}}
/>
<p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Your 5Paisa registered Email ID
+ Your 5Paisa Client Code or registered Mobile Number
</p>
</div>
@@ -1572,7 +2086,7 @@ export function BrokersManagementPanel() {
type="text"
value={(config as any).totpCode || ''}
onChange={(e) => setConfig({ ...config, totpCode: e.target.value.replace(/\D/g, '').slice(0, 6) } as any)}
- placeholder="Enter 6-digit TOTP"
+ placeholder="123456"
maxLength={6}
style={{
width: '100%',
@@ -1595,19 +2109,50 @@ export function BrokersManagementPanel() {
</>
)}
- {/* Motilal Oswal-specific fields: User ID, Password, 2FA (DOB), TOTP */}
+ {/* ------------------------------------------------------------ */}
+ {/* MOTILAL OSWAL: Multi-factor Authentication (DOB + optional TOTP) */}
+ {/* Fields: API Key, User ID, Password, DOB (2FA), TOTP (optional) */}
+ {/* Password hash: SHA256(password + api_key) */}
+ {/* ------------------------------------------------------------ */}
{selectedBroker.id === 'motilal' && (
<>
+ {/* API Key */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
+ API KEY <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <input
+ type="text"
+ value={config.apiKey || ''}
+ onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}
+ placeholder="Enter your Motilal Oswal API Key"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
+ Your Motilal Oswal API Key
+ </p>
+ </div>
+
{/* User ID */}
<div style={{ marginBottom: '12px' }}>
<label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>
- USER ID <span style={{ color: COLORS.RED }}>*</span>
+ USER ID (CLIENT ID) <span style={{ color: COLORS.RED }}>*</span>
</label>
<input
type="text"
value={config.userId || ''}
onChange={(e) => setConfig({ ...config, userId: e.target.value })}
- placeholder="Enter your Motilal Oswal User ID"
+ placeholder="Enter your User ID"
style={{
width: '100%',
padding: '10px 12px',
@@ -1666,7 +2211,7 @@ export function BrokersManagementPanel() {
</button>
</div>
<p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Your Motilal Oswal trading password
+ Password hash is generated as SHA256(password + api_key)
</p>
</div>
@@ -1693,7 +2238,7 @@ export function BrokersManagementPanel() {
}}
/>
<p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Format: DD/MM/YYYY (required for 2FA)
+ Format: DD/MM/YYYY (required as 2FA factor)
</p>
</div>
@@ -1706,7 +2251,7 @@ export function BrokersManagementPanel() {
type="text"
value={(config as any).totpCode || ''}
onChange={(e) => setConfig({ ...config, totpCode: e.target.value.replace(/\D/g, '').slice(0, 6) } as any)}
- placeholder="Enter 6-digit TOTP (if enabled)"
+ placeholder="Leave blank if using OTP via SMS/Email"
maxLength={6}
style={{
width: '100%',
@@ -1723,7 +2268,7 @@ export function BrokersManagementPanel() {
}}
/>
<p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px', margin: '4px 0 0 0' }}>
- Optional TOTP if enabled on your account
+ Optional: 6-digit TOTP from authenticator app (leave blank for SMS/Email OTP)
</p>
</div>
</>
diff --git a/fincept-terminal-desktop/src/components/tabs/geopolitics/GeopoliticsTab.tsx b/fincept-terminal-desktop/src/components/tabs/geopolitics/GeopoliticsTab.tsx
index d82eec438..de3683a5d 100644
--- a/fincept-terminal-desktop/src/components/tabs/geopolitics/GeopoliticsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/geopolitics/GeopoliticsTab.tsx
@@ -7,6 +7,7 @@ import { BitmapLayer } from '@deck.gl/layers';
import { useAuth } from '@/contexts/AuthContext';
import { NewsEventsService, NewsEvent, UniqueCity, UniqueCountry, UniqueCategory } from '@/services/news/newsEventsService';
import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { useTranslation } from 'react-i18next';
import { TabFooter } from '@/components/common/TabFooter';
import { useCache, cacheKey } from '@/hooks/useCache';
import { withTimeout } from '@/services/core/apiUtils';
@@ -25,20 +26,6 @@ const INITIAL_VIEW_STATE = {
bearing: 0
};
-const THEME = {
- ORANGE: '#FF6600',
- BLACK: '#000000',
- DARK_BG: '#0F0F0F',
- BORDER: '#333333',
- WHITE: '#FFFFFF',
- GREEN: '#00FF00',
- RED: '#FF0000',
- YELLOW: '#FFD700',
- CYAN: '#00E5FF',
- GRAY: '#888888',
- PURPLE: '#9333EA'
-};
-
const API_TIMEOUT_MS = 30000;
const REFRESH_INTERVAL_MS = 300000; // 5 minutes
@@ -213,7 +200,8 @@ function getCategoryColor(category?: string): [number, number, number, number] {
// ============================================================================
const GeopoliticsTabInner: React.FC = () => {
- const { colors, fontFamily } = useTerminalTheme();
+ const { colors, fontFamily, fontSize } = useTerminalTheme();
+ const { t } = useTranslation('geopolitics');
const { session } = useAuth();
const apiKey = session?.api_key || null;
@@ -535,11 +523,11 @@ const GeopoliticsTabInner: React.FC = () => {
top: 0,
left: 0,
right: 0,
- background: THEME.BLACK,
- borderBottom: `2px solid ${THEME.ORANGE}`,
+ background: colors.background,
+ borderBottom: `2px solid ${colors.primary}`,
zIndex: 1000,
- fontFamily: 'Consolas, monospace',
- fontSize: '12px'
+ fontFamily,
+ fontSize: fontSize.body
}}>
{/* Title Bar */}
<div style={{
@@ -547,24 +535,24 @@ const GeopoliticsTabInner: React.FC = () => {
display: 'flex',
alignItems: 'center',
gap: '8px',
- borderBottom: `1px solid ${THEME.BORDER}`,
+ borderBottom: `1px solid ${colors.panel}`,
flexWrap: 'wrap'
}}>
- <div style={{ color: THEME.ORANGE, fontWeight: 'bold', fontSize: '13px' }}>
- GEO&gt;
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: fontSize.subheading }}>
+ {t('header.prefix')}
</div>
- <div style={{ color: THEME.WHITE, fontWeight: 'bold', fontSize: '12px' }}>
- GEOPOLITICAL CONFLICT MONITOR
+ <div style={{ color: colors.text, fontWeight: 'bold', fontSize: fontSize.body }}>
+ {t('header.title')}
</div>
- <div style={{ color: events.length > 0 ? THEME.GREEN : THEME.RED, fontWeight: 'bold', fontSize: '11px' }}>
- {events.length} EVENTS
+ <div style={{ color: events.length > 0 ? colors.success : colors.alert, fontWeight: 'bold', fontSize: fontSize.small }}>
+ {events.length} {t('header.events')}
</div>
- <div style={{ color: THEME.CYAN, fontSize: '10px' }}>
+ <div style={{ color: colors.secondary, fontSize: fontSize.tiny }}>
{currentTime.toISOString().substring(0, 19)} UTC
</div>
{eventsStale && (
- <div style={{ color: THEME.YELLOW, fontSize: '10px' }}>
- STALE
+ <div style={{ color: colors.warning, fontSize: fontSize.tiny }}>
+ {t('status.stale')}
</div>
)}
</div>
@@ -580,7 +568,7 @@ const GeopoliticsTabInner: React.FC = () => {
<div style={{ position: 'relative', minWidth: '100px', flex: '0 1 auto' }}>
<input
type="text"
- placeholder="Country..."
+ placeholder={t('filters.country')}
value={countryFilter}
onChange={(e) => dispatch({ type: 'SET_COUNTRY_FILTER', payload: e.target.value })}
onKeyDown={(e) => {
@@ -596,11 +584,11 @@ const GeopoliticsTabInner: React.FC = () => {
onFocus={() => countrySuggestions.length > 0 && dispatch({ type: 'SET_SHOW_COUNTRY_SUGGESTIONS', payload: true })}
style={{
padding: '5px 8px',
- background: '#1a1a1a',
- border: '1px solid #333',
- color: '#fff',
- fontFamily: 'Consolas, monospace',
- fontSize: '11px',
+ background: colors.panel,
+ border: `1px solid ${colors.panel}`,
+ color: colors.text,
+ fontFamily,
+ fontSize: fontSize.small,
width: '100%',
outline: 'none',
borderRadius: '2px'
@@ -651,7 +639,7 @@ const GeopoliticsTabInner: React.FC = () => {
<div style={{ position: 'relative', minWidth: '100px', flex: '0 1 auto' }}>
<input
type="text"
- placeholder={selectedCities.length > 0 ? `${selectedCities.length} cities` : "Cities..."}
+ placeholder={selectedCities.length > 0 ? `${selectedCities.length} cities` : t('filters.cities')}
value={citySearchInput}
onChange={(e) => dispatch({ type: 'SET_CITY_SEARCH_INPUT', payload: e.target.value })}
onKeyDown={(e) => {
@@ -665,11 +653,11 @@ const GeopoliticsTabInner: React.FC = () => {
style={{
padding: '5px 8px',
paddingRight: selectedCities.length > 0 ? '24px' : '8px',
- background: '#1a1a1a',
- border: `1px solid ${selectedCities.length > 0 ? THEME.PURPLE : '#333'}`,
- color: '#fff',
- fontFamily: 'Consolas, monospace',
- fontSize: '11px',
+ background: colors.panel,
+ border: `1px solid ${selectedCities.length > 0 ? colors.primary : colors.panel}`,
+ color: colors.text,
+ fontFamily,
+ fontSize: fontSize.small,
width: '100%',
outline: 'none',
borderRadius: '2px'
@@ -684,13 +672,13 @@ const GeopoliticsTabInner: React.FC = () => {
top: '50%',
transform: 'translateY(-50%)',
cursor: 'pointer',
- color: THEME.RED,
+ color: colors.alert,
fontWeight: 'bold',
- fontSize: '12px',
+ fontSize: fontSize.body,
lineHeight: '1',
padding: '2px'
}}
- title="Clear all cities"
+ title={t('filters.clearAllCities')}
>
×
</div>
@@ -701,8 +689,8 @@ const GeopoliticsTabInner: React.FC = () => {
top: '100%',
left: 0,
width: '240px',
- background: '#1a1a1a',
- border: '1px solid #333',
+ background: colors.panel,
+ border: `1px solid ${colors.panel}`,
borderTop: 'none',
maxHeight: '200px',
overflowY: 'auto',
@@ -718,29 +706,29 @@ const GeopoliticsTabInner: React.FC = () => {
style={{
padding: '6px 8px',
cursor: 'pointer',
- fontSize: '10px',
- borderBottom: idx < citySuggestions.length - 1 ? '1px solid #333' : 'none',
- color: isSelected ? THEME.PURPLE : '#ccc',
- background: isSelected ? 'rgba(147, 51, 234, 0.2)' : '#1a1a1a',
+ fontSize: fontSize.tiny,
+ borderBottom: idx < citySuggestions.length - 1 ? `1px solid ${colors.panel}` : 'none',
+ color: isSelected ? colors.primary : colors.textMuted,
+ background: isSelected ? 'rgba(147, 51, 234, 0.2)' : colors.panel,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}
onMouseEnter={(e) => {
if (!isSelected) {
- e.currentTarget.style.background = '#2a2a2a';
- e.currentTarget.style.color = '#fff';
+ e.currentTarget.style.background = colors.background;
+ e.currentTarget.style.color = colors.text;
}
}}
onMouseLeave={(e) => {
if (!isSelected) {
- e.currentTarget.style.background = '#1a1a1a';
- e.currentTarget.style.color = '#ccc';
+ e.currentTarget.style.background = colors.panel;
+ e.currentTarget.style.color = colors.textMuted;
}
}}
>
<span>{suggestion.city}, {suggestion.country}</span>
- {isSelected && <span style={{ color: THEME.PURPLE }}>✓</span>}
+ {isSelected && <span style={{ color: colors.primary }}>✓</span>}
</div>
);
})}
@@ -751,7 +739,7 @@ const GeopoliticsTabInner: React.FC = () => {
<div style={{ position: 'relative', minWidth: '110px', flex: '0 1 auto' }}>
<input
type="text"
- placeholder="Category..."
+ placeholder={t('filters.category')}
value={categoryFilter}
onChange={(e) => dispatch({ type: 'SET_CATEGORY_FILTER', payload: e.target.value })}
onKeyDown={(e) => {
@@ -767,11 +755,11 @@ const GeopoliticsTabInner: React.FC = () => {
onFocus={() => categorySuggestions.length > 0 && dispatch({ type: 'SET_SHOW_CATEGORY_SUGGESTIONS', payload: true })}
style={{
padding: '5px 8px',
- background: '#1a1a1a',
- border: '1px solid #333',
- color: '#fff',
- fontFamily: 'Consolas, monospace',
- fontSize: '11px',
+ background: colors.panel,
+ border: `1px solid ${colors.panel}`,
+ color: colors.text,
+ fontFamily,
+ fontSize: fontSize.small,
width: '100%',
outline: 'none',
borderRadius: '2px'
@@ -783,8 +771,8 @@ const GeopoliticsTabInner: React.FC = () => {
top: '100%',
left: 0,
width: '200px',
- background: '#1a1a1a',
- border: '1px solid #333',
+ background: colors.panel,
+ border: `1px solid ${colors.panel}`,
borderTop: 'none',
maxHeight: '200px',
overflowY: 'auto',
@@ -798,18 +786,18 @@ const GeopoliticsTabInner: React.FC = () => {
style={{
padding: '6px 8px',
cursor: 'pointer',
- fontSize: '10px',
- borderBottom: idx < categorySuggestions.length - 1 ? '1px solid #333' : 'none',
- color: '#ccc',
- background: '#1a1a1a'
+ fontSize: fontSize.tiny,
+ borderBottom: idx < categorySuggestions.length - 1 ? `1px solid ${colors.panel}` : 'none',
+ color: colors.textMuted,
+ background: colors.panel
}}
onMouseEnter={(e) => {
- e.currentTarget.style.background = '#2a2a2a';
- e.currentTarget.style.color = '#fff';
+ e.currentTarget.style.background = colors.background;
+ e.currentTarget.style.color = colors.text;
}}
onMouseLeave={(e) => {
- e.currentTarget.style.background = '#1a1a1a';
- e.currentTarget.style.color = '#ccc';
+ e.currentTarget.style.background = colors.panel;
+ e.currentTarget.style.color = colors.textMuted;
}}
>
{suggestion.event_category} ({suggestion.event_count} events)
@@ -824,11 +812,11 @@ const GeopoliticsTabInner: React.FC = () => {
disabled={eventsLoading}
style={{
padding: '5px 14px',
- background: THEME.ORANGE,
+ background: colors.primary,
border: 'none',
- color: '#000',
- fontFamily: 'Consolas, monospace',
- fontSize: '10px',
+ color: colors.background,
+ fontFamily,
+ fontSize: fontSize.tiny,
fontWeight: 'bold',
cursor: eventsLoading ? 'not-allowed' : 'pointer',
opacity: eventsLoading ? 0.5 : 1,
@@ -836,7 +824,7 @@ const GeopoliticsTabInner: React.FC = () => {
minWidth: '60px'
}}
>
- {eventsLoading ? 'LOADING...' : 'APPLY'}
+ {eventsLoading ? t('status.loading') : t('filters.apply')}
</button>
{(countryFilter || cityFilter || selectedCities.length > 0 || categoryFilter) && (
@@ -844,18 +832,18 @@ const GeopoliticsTabInner: React.FC = () => {
onClick={() => dispatch({ type: 'CLEAR_FILTERS' })}
style={{
padding: '5px 12px',
- background: '#000',
- border: '1px solid #666',
- color: '#fff',
- fontFamily: 'Consolas, monospace',
- fontSize: '10px',
+ background: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.text,
+ fontFamily,
+ fontSize: fontSize.tiny,
fontWeight: 'bold',
cursor: 'pointer',
borderRadius: '2px',
minWidth: '55px'
}}
>
- CLEAR
+ {t('filters.clear')}
</button>
)}
@@ -869,15 +857,15 @@ const GeopoliticsTabInner: React.FC = () => {
flex: '1 1 100%',
marginTop: '4px'
}}>
- <span style={{ fontSize: '9px', color: THEME.GRAY }}>Selected:</span>
+ <span style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>{t('filters.selectedLabel')}</span>
{selectedCities.map((city, idx) => (
<div
key={idx}
style={{
padding: '3px 8px',
- background: THEME.PURPLE,
- color: THEME.WHITE,
- fontSize: '9px',
+ background: colors.primary,
+ color: colors.text,
+ fontSize: fontSize.tiny,
borderRadius: '3px',
display: 'flex',
alignItems: 'center',
@@ -887,7 +875,7 @@ const GeopoliticsTabInner: React.FC = () => {
{city}
<span
onClick={() => dispatch({ type: 'REMOVE_CITY', payload: city })}
- style={{ cursor: 'pointer', fontWeight: 'bold', color: THEME.WHITE, fontSize: '11px' }}
+ style={{ cursor: 'pointer', fontWeight: 'bold', color: colors.text, fontSize: fontSize.small }}
>
×
</span>
@@ -907,31 +895,31 @@ const GeopoliticsTabInner: React.FC = () => {
right: '20px',
padding: '12px 20px',
background: 'rgba(255, 0, 0, 0.2)',
- border: '1px solid #ff0000',
+ border: `1px solid ${colors.alert}`,
borderRadius: '4px',
- color: '#ff6b6b',
- fontFamily: 'Consolas, monospace',
- fontSize: '13px',
+ color: colors.alert,
+ fontFamily,
+ fontSize: fontSize.subheading,
zIndex: 10,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}>
- <span>ERROR: {eventsErrorMessage}</span>
+ <span>{t('status.error')} {eventsErrorMessage}</span>
<button
onClick={handleApply}
style={{
background: 'transparent',
- border: '1px solid #ff6b6b',
- color: '#ff6b6b',
+ border: `1px solid ${colors.alert}`,
+ color: colors.alert,
padding: '4px 12px',
cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- fontSize: '11px',
+ fontFamily,
+ fontSize: fontSize.small,
borderRadius: '2px',
}}
>
- RETRY
+ {t('messages.retry')}
</button>
</div>
)}
@@ -945,27 +933,27 @@ const GeopoliticsTabInner: React.FC = () => {
width: isPanelCollapsed ? '40px' : 'min(280px, calc(100vw - 20px))',
maxWidth: isPanelCollapsed ? '40px' : '90vw',
background: 'rgba(0, 0, 0, 0.95)',
- border: `1px solid ${THEME.BORDER}`,
+ border: `1px solid ${colors.panel}`,
borderRadius: '4px',
zIndex: 999,
overflowY: isPanelCollapsed ? 'hidden' : 'auto',
overflowX: 'hidden',
- fontFamily: 'Consolas, monospace',
- fontSize: '10px',
+ fontFamily,
+ fontSize: fontSize.tiny,
backdropFilter: 'blur(10px)',
transition: 'width 0.3s ease'
}}>
{/* Collapse Button */}
<div style={{
padding: '8px',
- borderBottom: `1px solid ${THEME.BORDER}`,
+ borderBottom: `1px solid ${colors.panel}`,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}>
{!isPanelCollapsed && (
- <div style={{ color: THEME.ORANGE, fontWeight: 'bold', fontSize: '11px' }}>
- INFO PANEL
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: fontSize.small }}>
+ {t('panel.title')}
</div>
)}
<button
@@ -973,15 +961,15 @@ const GeopoliticsTabInner: React.FC = () => {
style={{
background: 'transparent',
border: 'none',
- color: THEME.ORANGE,
+ color: colors.primary,
cursor: 'pointer',
- fontSize: '14px',
+ fontSize: fontSize.subheading,
padding: '4px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}
- title={isPanelCollapsed ? 'Expand panel' : 'Collapse panel'}
+ title={isPanelCollapsed ? t('panel.expand') : t('panel.collapse')}
>
{isPanelCollapsed ? '◀' : '▶'}
</button>
@@ -990,29 +978,29 @@ const GeopoliticsTabInner: React.FC = () => {
{!isPanelCollapsed && (
<>
{/* Events Loaded */}
- <div style={{ padding: '10px', borderBottom: `1px solid ${THEME.BORDER}` }}>
- <div style={{ color: THEME.ORANGE, fontWeight: 'bold', marginBottom: '8px', fontSize: '11px' }}>
- EVENTS LOADED
+ <div style={{ padding: '10px', borderBottom: `1px solid ${colors.panel}` }}>
+ <div style={{ color: colors.primary, fontWeight: 'bold', marginBottom: '8px', fontSize: fontSize.small }}>
+ {t('panel.eventsLoaded')}
</div>
- <div style={{ color: THEME.YELLOW, fontSize: '14px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.warning, fontSize: fontSize.subheading, fontWeight: 'bold', marginBottom: '4px' }}>
{events.length} events
</div>
- <div style={{ color: THEME.GRAY, fontSize: '9px' }}>
- on map visualization
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
+ {t('panel.onMapVisualization')}
</div>
</div>
{/* Statistics */}
- <div style={{ padding: '10px', borderBottom: `1px solid ${THEME.BORDER}` }}>
- <div style={{ color: THEME.ORANGE, fontWeight: 'bold', marginBottom: '8px', fontSize: '11px' }}>
- TOP CATEGORIES
+ <div style={{ padding: '10px', borderBottom: `1px solid ${colors.panel}` }}>
+ <div style={{ color: colors.primary, fontWeight: 'bold', marginBottom: '8px', fontSize: fontSize.small }}>
+ {t('panel.topCategories')}
</div>
{categoryStats.map(([cat, count], idx) => (
<div key={idx} style={{
display: 'flex',
justifyContent: 'space-between',
marginBottom: '4px',
- color: THEME.WHITE,
+ color: colors.text,
gap: '8px'
}}>
<span style={{
@@ -1021,21 +1009,21 @@ const GeopoliticsTabInner: React.FC = () => {
whiteSpace: 'nowrap',
flex: 1
}}>{cat}</span>
- <span style={{ color: THEME.YELLOW, flexShrink: 0 }}>{count}</span>
+ <span style={{ color: colors.warning, flexShrink: 0 }}>{count}</span>
</div>
))}
</div>
- <div style={{ padding: '10px', borderBottom: `1px solid ${THEME.BORDER}` }}>
- <div style={{ color: THEME.ORANGE, fontWeight: 'bold', marginBottom: '8px', fontSize: '11px' }}>
- TOP COUNTRIES
+ <div style={{ padding: '10px', borderBottom: `1px solid ${colors.panel}` }}>
+ <div style={{ color: colors.primary, fontWeight: 'bold', marginBottom: '8px', fontSize: fontSize.small }}>
+ {t('panel.topCountries')}
</div>
{countryStats.map(([country, count], idx) => (
<div key={idx} style={{
display: 'flex',
justifyContent: 'space-between',
marginBottom: '4px',
- color: THEME.WHITE,
+ color: colors.text,
gap: '8px'
}}>
<span style={{
@@ -1044,7 +1032,7 @@ const GeopoliticsTabInner: React.FC = () => {
whiteSpace: 'nowrap',
flex: 1
}}>{country}</span>
- <span style={{ color: THEME.YELLOW, flexShrink: 0 }}>{count}</span>
+ <span style={{ color: colors.warning, flexShrink: 0 }}>{count}</span>
</div>
))}
</div>
@@ -1052,55 +1040,55 @@ const GeopoliticsTabInner: React.FC = () => {
{/* Selected Event Details */}
{selectedEvent && (
<div style={{ padding: '10px' }}>
- <div style={{ color: THEME.ORANGE, fontWeight: 'bold', marginBottom: '8px', fontSize: '11px' }}>
- EVENT DETAILS
+ <div style={{ color: colors.primary, fontWeight: 'bold', marginBottom: '8px', fontSize: fontSize.small }}>
+ {t('panel.eventDetails')}
</div>
- <div style={{ color: THEME.WHITE, lineHeight: '1.6', wordBreak: 'break-word' }}>
+ <div style={{ color: colors.text, lineHeight: '1.6', wordBreak: 'break-word' }}>
{selectedEvent.event_category && (
- <div style={{ marginBottom: '6px', fontWeight: 'bold', color: THEME.YELLOW, fontSize: '10px' }}>
+ <div style={{ marginBottom: '6px', fontWeight: 'bold', color: colors.warning, fontSize: fontSize.tiny }}>
{selectedEvent.event_category.toUpperCase().replace(/_/g, ' ')}
</div>
)}
{selectedEvent.country && (
- <div style={{ marginBottom: '4px', fontSize: '9px' }}>
- <span style={{ color: THEME.GRAY }}>Country:</span> {selectedEvent.country}
+ <div style={{ marginBottom: '4px', fontSize: fontSize.tiny }}>
+ <span style={{ color: colors.textMuted }}>{t('eventDetails.country')}</span> {selectedEvent.country}
</div>
)}
{selectedEvent.city && (
- <div style={{ marginBottom: '4px', fontSize: '9px' }}>
- <span style={{ color: THEME.GRAY }}>City:</span> {selectedEvent.city}
+ <div style={{ marginBottom: '4px', fontSize: fontSize.tiny }}>
+ <span style={{ color: colors.textMuted }}>{t('eventDetails.city')}</span> {selectedEvent.city}
</div>
)}
{selectedEvent.matched_keywords && (
- <div style={{ marginBottom: '4px', fontSize: '9px' }}>
- <span style={{ color: THEME.GRAY }}>Keywords:</span> {selectedEvent.matched_keywords}
+ <div style={{ marginBottom: '4px', fontSize: fontSize.tiny }}>
+ <span style={{ color: colors.textMuted }}>{t('eventDetails.keywords')}</span> {selectedEvent.matched_keywords}
</div>
)}
{selectedEvent.latitude !== undefined && selectedEvent.longitude !== undefined && (
- <div style={{ marginBottom: '4px', fontSize: '8px' }}>
- <span style={{ color: THEME.GRAY }}>Coords:</span> {selectedEvent.latitude.toFixed(4)}, {selectedEvent.longitude.toFixed(4)}
+ <div style={{ marginBottom: '4px', fontSize: fontSize.tiny }}>
+ <span style={{ color: colors.textMuted }}>{t('eventDetails.coords')}</span> {selectedEvent.latitude.toFixed(4)}, {selectedEvent.longitude.toFixed(4)}
</div>
)}
{selectedEvent.extracted_date && (
- <div style={{ marginBottom: '4px', fontSize: '8px' }}>
- <span style={{ color: THEME.GRAY }}>Date:</span> {new Date(selectedEvent.extracted_date).toLocaleString()}
+ <div style={{ marginBottom: '4px', fontSize: fontSize.tiny }}>
+ <span style={{ color: colors.textMuted }}>{t('eventDetails.date')}</span> {new Date(selectedEvent.extracted_date).toLocaleString()}
</div>
)}
{selectedEvent.url && (
- <div style={{ marginBottom: '4px', fontSize: '8px' }}>
- <span style={{ color: THEME.GRAY }}>Source:</span>{' '}
+ <div style={{ marginBottom: '4px', fontSize: fontSize.tiny }}>
+ <span style={{ color: colors.textMuted }}>{t('eventDetails.source')}</span>{' '}
<a
href={selectedEvent.url}
target="_blank"
rel="noopener noreferrer"
style={{
- color: THEME.CYAN,
+ color: colors.secondary,
textDecoration: 'underline',
cursor: 'pointer',
wordBreak: 'break-all'
}}
>
- View Article
+ {t('eventDetails.viewArticle')}
</a>
</div>
)}
@@ -1109,67 +1097,67 @@ const GeopoliticsTabInner: React.FC = () => {
style={{
marginTop: '8px',
padding: '6px 10px',
- background: THEME.BORDER,
+ background: colors.panel,
border: 'none',
- color: THEME.WHITE,
- fontFamily: 'Consolas, monospace',
- fontSize: '9px',
+ color: colors.text,
+ fontFamily,
+ fontSize: fontSize.tiny,
cursor: 'pointer',
width: '100%',
borderRadius: '2px'
}}
>
- CLOSE
+ {t('panel.close')}
</button>
</div>
</div>
)}
{/* Legend */}
- <div style={{ padding: '10px', borderTop: `1px solid ${THEME.BORDER}` }}>
- <div style={{ color: THEME.ORANGE, fontWeight: 'bold', marginBottom: '8px', fontSize: '11px' }}>
- EVENT CATEGORIES
+ <div style={{ padding: '10px', borderTop: `1px solid ${colors.panel}` }}>
+ <div style={{ color: colors.primary, fontWeight: 'bold', marginBottom: '8px', fontSize: fontSize.small }}>
+ {t('legend.title')}
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#FF0000', flexShrink: 0 }}></div>
- <span style={{ color: THEME.GRAY, fontSize: '8px' }}>Armed Conflict</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>{t('legend.armedConflict')}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#FF4500', flexShrink: 0 }}></div>
- <span style={{ color: THEME.GRAY, fontSize: '8px' }}>Terrorism</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>{t('legend.terrorism')}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#FFD700', flexShrink: 0 }}></div>
- <span style={{ color: THEME.GRAY, fontSize: '8px' }}>Protests</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>{t('legend.protests')}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#FF6464', flexShrink: 0 }}></div>
- <span style={{ color: THEME.GRAY, fontSize: '8px' }}>Civilian Violence</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>{t('legend.civilianViolence')}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#FFA500', flexShrink: 0 }}></div>
- <span style={{ color: THEME.GRAY, fontSize: '8px' }}>Riots</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>{t('legend.riots')}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#9333EA', flexShrink: 0 }}></div>
- <span style={{ color: THEME.GRAY, fontSize: '8px' }}>Political Violence</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>{t('legend.politicalViolence')}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#00E5FF', flexShrink: 0 }}></div>
- <span style={{ color: THEME.GRAY, fontSize: '8px' }}>Crisis</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>{t('legend.crisis')}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#FF1493', flexShrink: 0 }}></div>
- <span style={{ color: THEME.GRAY, fontSize: '8px' }}>Explosions</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>{t('legend.explosions')}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#6495ED', flexShrink: 0 }}></div>
- <span style={{ color: THEME.GRAY, fontSize: '8px' }}>Strategic</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>{t('legend.strategic')}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#888888', flexShrink: 0 }}></div>
- <span style={{ color: THEME.GRAY, fontSize: '8px' }}>Unclassified</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>{t('legend.unclassified')}</span>
</div>
</div>
</div>
@@ -1194,13 +1182,13 @@ const GeopoliticsTabInner: React.FC = () => {
Keywords: ${object.event.matched_keywords || 'N/A'}<br/>
${object.event.extracted_date ? new Date(object.event.extracted_date).toLocaleDateString() : ''}</div>`,
style: {
- backgroundColor: '#000',
- color: '#fff',
+ backgroundColor: colors.background,
+ color: colors.text,
padding: '8px',
borderRadius: '4px',
- border: '1px solid #ff6600',
- fontFamily: 'Consolas, monospace',
- fontSize: '10px'
+ border: `1px solid ${colors.primary}`,
+ fontFamily,
+ fontSize: fontSize.tiny
}
}}
/>
@@ -1209,16 +1197,16 @@ const GeopoliticsTabInner: React.FC = () => {
{/* Footer */}
<div style={{ flexShrink: 0 }}>
<TabFooter
- tabName="GEOPOLITICAL CONFLICT MONITOR"
+ tabName={t('footer.tabName')}
leftInfo={[
- { label: 'EVENTS', value: `${events.length}`, color: events.length > 0 ? '#10b981' : '#ef4444' },
- { label: 'ENGINE', value: 'DECK.GL v9.2', color: '#06b6d4' },
- { label: 'SOURCE', value: 'NEWS-EVENTS API', color: '#fbbf24' },
- ...(selectedEvent ? [{ label: 'SELECTED', value: selectedEvent.country || 'N/A', color: '#ffd700' }] : [])
+ { label: t('footer.labelEvents'), value: `${events.length}`, color: events.length > 0 ? colors.success : colors.alert },
+ { label: t('footer.labelEngine'), value: t('footer.engineValue'), color: colors.secondary },
+ { label: t('footer.labelSource'), value: t('footer.sourceValue'), color: colors.warning },
+ ...(selectedEvent ? [{ label: t('footer.labelSelected'), value: selectedEvent.country || 'N/A', color: colors.warning }] : [])
]}
- statusInfo={`REAL-TIME GLOBAL INTELLIGENCE | AUTO-REFRESH: 5MIN | ${currentTime.toLocaleTimeString()}`}
- backgroundColor="#000000"
- borderColor="#ff6600"
+ statusInfo={t('footer.statusInfo', { time: currentTime.toLocaleTimeString() })}
+ backgroundColor={colors.background}
+ borderColor={colors.primary}
/>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx b/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx
index 896a3078f..9669e76d2 100644
--- a/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx
@@ -191,7 +191,7 @@ const MarketPanel: React.FC<MarketPanelProps> = ({
backgroundColor: 'rgba(239, 68, 68, 0.1)',
color: colors.alert,
padding: '4px 8px',
- fontSize: '10px',
+ fontSize: fontSize.small,
display: 'flex',
justifyContent: 'space-between',
}}
@@ -331,9 +331,9 @@ const MarketPanel: React.FC<MarketPanelProps> = ({
<div
style={{
backgroundColor: 'rgba(245, 158, 11, 0.1)',
- color: '#f59e0b',
+ color: colors.warning,
padding: '2px 8px',
- fontSize: '9px',
+ fontSize: fontSize.tiny,
textAlign: 'center',
}}
>
@@ -487,7 +487,7 @@ const MarketsTab: React.FC = () => {
onClick={() => window.location.reload()}
style={{
backgroundColor: colors.primary,
- color: '#000',
+ color: colors.background,
border: 'none',
padding: '8px 24px',
cursor: 'pointer',
@@ -502,8 +502,8 @@ const MarketsTab: React.FC = () => {
style={{
width: '50px',
height: '50px',
- border: '3px solid #404040',
- borderTop: '3px solid #ea580c',
+ border: `3px solid ${colors.textMuted}`,
+ borderTop: `3px solid ${colors.primary}`,
borderRadius: '50%',
animation: 'spin 1s linear infinite',
}}
@@ -546,14 +546,14 @@ const MarketsTab: React.FC = () => {
padding: '8px 12px',
backgroundColor: colors.panel,
borderBottom: `1px solid ${colors.textMuted}`,
- fontSize: '13px',
+ fontSize: fontSize.subheading,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<span style={{ color: colors.primary, fontWeight: 'bold' }}>FINCEPT</span>
<span>{t('marketTerminalLive')}</span>
<span style={{ color: colors.textMuted }}>|</span>
- <span style={{ fontSize: '11px' }}>
+ <span style={{ fontSize: fontSize.body }}>
{currentTime.toISOString().replace('T', ' ').substring(0, 19)}
</span>
</div>
@@ -564,7 +564,7 @@ const MarketsTab: React.FC = () => {
color: colors.background,
border: 'none',
padding: '4px 8px',
- fontSize: '11px',
+ fontSize: fontSize.body,
fontWeight: 'bold',
cursor: 'pointer',
display: 'flex',
@@ -593,10 +593,10 @@ const MarketsTab: React.FC = () => {
onClick={handleRefreshAll}
style={{
backgroundColor: colors.primary,
- color: '#000',
+ color: colors.background,
border: 'none',
padding: '4px 12px',
- fontSize: '11px',
+ fontSize: fontSize.body,
fontWeight: 'bold',
cursor: 'pointer',
display: 'flex',
@@ -610,10 +610,10 @@ const MarketsTab: React.FC = () => {
onClick={() => dispatch({ type: 'SET_AUTO_UPDATE', payload: !state.autoUpdate })}
style={{
backgroundColor: state.autoUpdate ? colors.secondary : colors.textMuted,
- color: '#000',
+ color: colors.background,
border: 'none',
padding: '4px 12px',
- fontSize: '11px',
+ fontSize: fontSize.body,
fontWeight: 'bold',
cursor: 'pointer',
}}
@@ -628,7 +628,7 @@ const MarketsTab: React.FC = () => {
border: `1px solid ${colors.textMuted}`,
color: colors.text,
padding: '4px 8px',
- fontSize: '11px',
+ fontSize: fontSize.body,
}}
>
<option value={600000}>10 min</option>
@@ -647,7 +647,7 @@ const MarketsTab: React.FC = () => {
{/* Content */}
<div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
{/* Global Markets */}
- <div style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ <div style={{ color: colors.primary, fontSize: fontSize.subheading, fontWeight: 'bold', marginBottom: '8px' }}>
{t('globalMarkets')}
</div>
<div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '16px' }} />
@@ -667,7 +667,7 @@ const MarketsTab: React.FC = () => {
</div>
{/* Regional Markets */}
- <div style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ <div style={{ color: colors.primary, fontSize: fontSize.subheading, fontWeight: 'bold', marginBottom: '8px' }}>
{t('regionalMarketsLive')}
</div>
<div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '16px' }} />
diff --git a/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx.backup b/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx.backup
new file mode 100644
index 000000000..896a3078f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx.backup
@@ -0,0 +1,716 @@
+// MarketsTab - Production-ready Markets Terminal
+// Uses shared utilities: apiUtils, validators, ErrorBoundary
+
+import React, { useState, useEffect, useCallback, useReducer } from 'react';
+import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';
+import { Edit2, Info, RefreshCw, AlertCircle } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { marketDataService, QuoteData } from '@/services/markets/marketDataService';
+import { tickerStorage, UserMarketPreferences } from '@/services/core/tickerStorageService';
+import { sqliteService } from '@/services/core/sqliteService';
+import { contextRecorderService } from '@/services/data-sources/contextRecorderService';
+import { withTimeout, rateLimiters } from '@/services/core/apiUtils';
+import { validateSymbolList } from '@/services/core/validators';
+import { useCache } from '@/hooks/useCache';
+import { ErrorBoundary } from '@/components/common/ErrorBoundary';
+import TickerEditModal from '@/components/tabs/ticker-edit-modal';
+import RecordingControlPanel from '@/components/common/RecordingControlPanel';
+import { TabFooter } from '@/components/common/TabFooter';
+import { createMarketsTabTour } from '@/components/tabs/tours/marketsTabTour';
+
+// ============================================================================
+// Constants
+// ============================================================================
+
+const API_TIMEOUT_MS = 30000;
+const STALE_DATA_WARNING_MS = 30 * 60 * 1000;
+
+// ============================================================================
+// State Reducer (lightweight, component-local)
+// ============================================================================
+
+type ModalState = {
+ isOpen: boolean;
+ category: string;
+ type: 'global' | 'regional';
+ tickers: string[];
+};
+
+type State = {
+ preferences: UserMarketPreferences | null;
+ autoUpdate: boolean;
+ updateInterval: number;
+ isRecording: boolean;
+ editModal: ModalState;
+};
+
+type Action =
+ | { type: 'SET_PREFERENCES'; payload: UserMarketPreferences }
+ | { type: 'SET_AUTO_UPDATE'; payload: boolean }
+ | { type: 'SET_UPDATE_INTERVAL'; payload: number }
+ | { type: 'SET_RECORDING'; payload: boolean }
+ | { type: 'OPEN_MODAL'; payload: Omit<ModalState, 'isOpen'> }
+ | { type: 'CLOSE_MODAL' };
+
+const initialState: State = {
+ preferences: null,
+ autoUpdate: true,
+ updateInterval: 600000,
+ isRecording: false,
+ editModal: { isOpen: false, category: '', type: 'global', tickers: [] },
+};
+
+function reducer(state: State, action: Action): State {
+ switch (action.type) {
+ case 'SET_PREFERENCES':
+ return { ...state, preferences: action.payload };
+ case 'SET_AUTO_UPDATE':
+ return { ...state, autoUpdate: action.payload };
+ case 'SET_UPDATE_INTERVAL':
+ return { ...state, updateInterval: action.payload };
+ case 'SET_RECORDING':
+ return { ...state, isRecording: action.payload };
+ case 'OPEN_MODAL':
+ return { ...state, editModal: { isOpen: true, ...action.payload } };
+ case 'CLOSE_MODAL':
+ return { ...state, editModal: { ...state.editModal, isOpen: false } };
+ default:
+ return state;
+ }
+}
+
+// ============================================================================
+// Market Panel Component
+// ============================================================================
+
+interface MarketPanelProps {
+ title: string;
+ tickers: string[];
+ tickerNames?: Record<string, string>;
+ enabled: boolean;
+ refetchInterval: number;
+ onEdit: () => void;
+ onDataUpdate: (data: QuoteData[]) => void;
+ showName?: boolean;
+}
+
+const MarketPanel: React.FC<MarketPanelProps> = ({
+ title,
+ tickers,
+ tickerNames,
+ enabled,
+ refetchInterval,
+ onEdit,
+ onDataUpdate,
+ showName = false,
+}) => {
+ const { t } = useTranslation('markets');
+ const { colors, fontSize } = useTerminalTheme();
+
+ const { data, isLoading, isFetching, error, isStale, refresh } = useCache<QuoteData[]>({
+ key: `markets:${title}:${tickers.length}:${tickers[0] || 'empty'}`,
+ category: 'market-quotes',
+ fetcher: async () => {
+ if (!rateLimiters.standard.canProceed()) {
+ throw new Error('Rate limit exceeded. Please wait.');
+ }
+ rateLimiters.standard.record();
+
+ const validation = validateSymbolList(tickers);
+ if (!validation.valid) {
+ throw new Error(`Invalid symbols: ${validation.error}`);
+ }
+
+ return withTimeout(
+ marketDataService.getQuotes(validation.sanitized),
+ API_TIMEOUT_MS,
+ 'Request timed out'
+ );
+ },
+ ttl: '10m',
+ enabled: enabled && tickers.length > 0,
+ refetchInterval,
+ staleWhileRevalidate: true,
+ onSuccess: onDataUpdate,
+ });
+
+ const quotes = data || [];
+ const formatChange = (v: number) => (v >= 0 ? `+${v.toFixed(2)}` : v.toFixed(2));
+ const formatPercent = (v: number) => (v >= 0 ? `+${v.toFixed(2)}%` : `${v.toFixed(2)}%`);
+
+ const columns = showName
+ ? { template: '1fr 2fr 1fr 1fr 1fr', count: 5 }
+ : { template: '2fr 1fr 1fr 1fr 1fr 1fr', count: 6 };
+
+ return (
+ <div
+ style={{
+ backgroundColor: colors.panel,
+ border: `1px solid ${error ? colors.alert : colors.textMuted}`,
+ flex: '1 1 calc(33.333% - 16px)',
+ minWidth: '300px',
+ maxWidth: '600px',
+ height: showName ? '300px' : '280px',
+ margin: '8px',
+ display: 'flex',
+ flexDirection: 'column',
+ }}
+ >
+ {/* Header */}
+ <div
+ style={{
+ backgroundColor: colors.background,
+ color: colors.primary,
+ padding: '8px',
+ fontSize: fontSize.subheading,
+ fontWeight: 'bold',
+ textAlign: 'center',
+ borderBottom: `1px solid ${colors.textMuted}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ }}
+ >
+ {title.toUpperCase()}
+ {showName && ' - LIVE DATA'}
+ {isFetching && <RefreshCw size={12} className="animate-spin" />}
+ <Edit2
+ size={14}
+ style={{ cursor: 'pointer', color: colors.text }}
+ onClick={onEdit}
+ aria-label={`Edit ${title}`}
+ />
+ </div>
+
+ {/* Error Banner */}
+ {error && (
+ <div
+ style={{
+ backgroundColor: 'rgba(239, 68, 68, 0.1)',
+ color: colors.alert,
+ padding: '4px 8px',
+ fontSize: '10px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ }}
+ >
+ <span>{error.message}</span>
+ <button
+ onClick={refresh}
+ style={{
+ background: 'none',
+ border: 'none',
+ color: colors.alert,
+ cursor: 'pointer',
+ textDecoration: 'underline',
+ }}
+ >
+ Retry
+ </button>
+ </div>
+ )}
+
+ {/* Table Header */}
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: columns.template,
+ gap: '4px',
+ padding: '4px 8px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontSize: fontSize.body,
+ fontWeight: 'bold',
+ borderBottom: `1px solid ${colors.textMuted}`,
+ }}
+ >
+ <div>{t('symbol')}</div>
+ {showName && <div>{t('name')}</div>}
+ <div style={{ textAlign: 'right' }}>{t('price')}</div>
+ <div style={{ textAlign: 'right' }}>{t('change')}</div>
+ <div style={{ textAlign: 'right' }}>{t('percentChange')}</div>
+ {!showName && (
+ <>
+ <div style={{ textAlign: 'right' }}>{t('high')}</div>
+ <div style={{ textAlign: 'right' }}>{t('low')}</div>
+ </>
+ )}
+ </div>
+
+ {/* Data Rows */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {isLoading && quotes.length === 0 ? (
+ Array.from({ length: Math.min(tickers.length, 12) }).map((_, idx) => (
+ <div
+ key={idx}
+ style={{
+ display: 'grid',
+ gridTemplateColumns: columns.template,
+ gap: '4px',
+ padding: '2px 8px',
+ minHeight: '18px',
+ alignItems: 'center',
+ borderBottom: '1px solid rgba(120,120,120,0.3)',
+ }}
+ >
+ {Array.from({ length: columns.count }).map((_, i) => (
+ <div
+ key={i}
+ style={{
+ backgroundColor: 'rgba(120,120,120,0.3)',
+ height: '12px',
+ borderRadius: '2px',
+ animation: 'pulse 1.5s infinite',
+ }}
+ />
+ ))}
+ </div>
+ ))
+ ) : quotes.length === 0 ? (
+ <div style={{ color: colors.textMuted, textAlign: 'center', padding: '16px' }}>
+ {error ? 'Error loading data' : t('noData')}
+ </div>
+ ) : (
+ quotes.map((quote, idx) => (
+ <div
+ key={quote.symbol}
+ style={{
+ display: 'grid',
+ gridTemplateColumns: columns.template,
+ gap: '4px',
+ padding: '2px 8px',
+ fontSize: fontSize.small,
+ backgroundColor: idx % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
+ borderBottom: '1px solid rgba(120,120,120,0.3)',
+ minHeight: '18px',
+ alignItems: 'center',
+ }}
+ >
+ <div style={{ color: colors.text }}>{quote.symbol}</div>
+ {showName && (
+ <div style={{ color: colors.text, overflow: 'hidden', textOverflow: 'ellipsis' }}>
+ {tickerNames?.[quote.symbol] || quote.symbol}
+ </div>
+ )}
+ <div style={{ color: colors.text, textAlign: 'right' }}>{quote.price.toFixed(2)}</div>
+ <div
+ style={{
+ color: quote.change >= 0 ? colors.secondary : colors.alert,
+ textAlign: 'right',
+ }}
+ >
+ {formatChange(quote.change)}
+ </div>
+ <div
+ style={{
+ color: quote.change_percent >= 0 ? colors.secondary : colors.alert,
+ textAlign: 'right',
+ }}
+ >
+ {formatPercent(quote.change_percent)}
+ </div>
+ {!showName && (
+ <>
+ <div style={{ color: colors.text, textAlign: 'right' }}>
+ {quote.high?.toFixed(2) || '-'}
+ </div>
+ <div style={{ color: colors.text, textAlign: 'right' }}>
+ {quote.low?.toFixed(2) || '-'}
+ </div>
+ </>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+
+ {/* Stale Warning */}
+ {isStale && (
+ <div
+ style={{
+ backgroundColor: 'rgba(245, 158, 11, 0.1)',
+ color: '#f59e0b',
+ padding: '2px 8px',
+ fontSize: '9px',
+ textAlign: 'center',
+ }}
+ >
+ Showing cached data (may be outdated)
+ </div>
+ )}
+ </div>
+ );
+};
+
+// ============================================================================
+// Main Component
+// ============================================================================
+
+const MarketsTab: React.FC = () => {
+ const { t } = useTranslation('markets');
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
+
+ const [state, dispatch] = useReducer(reducer, initialState);
+ const [currentTime, setCurrentTime] = useState(new Date());
+ const [dbInitialized, setDbInitialized] = useState(false);
+ const [refreshKey, setRefreshKey] = useState(0);
+ const [collectedData, setCollectedData] = useState<Record<string, QuoteData[]>>({});
+ const [initError, setInitError] = useState<string | null>(null);
+
+ // Workspace tab state
+ const getWorkspaceState = useCallback(() => ({
+ autoUpdate: state.autoUpdate,
+ updateInterval: state.updateInterval,
+ }), [state.autoUpdate, state.updateInterval]);
+
+ const setWorkspaceState = useCallback((restored: Record<string, unknown>) => {
+ if (typeof restored.autoUpdate === 'boolean') dispatch({ type: 'SET_AUTO_UPDATE', payload: restored.autoUpdate });
+ if (typeof restored.updateInterval === 'number') dispatch({ type: 'SET_UPDATE_INTERVAL', payload: restored.updateInterval });
+ }, []);
+
+ useWorkspaceTabState('markets', getWorkspaceState, setWorkspaceState);
+
+ const effectiveRefetchInterval = state.autoUpdate ? state.updateInterval : 0;
+
+ // Initialize
+ useEffect(() => {
+ let mounted = true;
+
+ const init = async () => {
+ try {
+ await sqliteService.initialize();
+ if (!mounted) return;
+ setDbInitialized(true);
+
+ const prefs = await withTimeout(tickerStorage.loadPreferences(), 10000);
+ if (!mounted) return;
+ dispatch({ type: 'SET_PREFERENCES', payload: prefs });
+ } catch (err) {
+ if (!mounted) return;
+ setInitError(err instanceof Error ? err.message : 'Failed to initialize');
+ setDbInitialized(true);
+ }
+ };
+
+ init();
+ return () => { mounted = false; };
+ }, []);
+
+ // Clock
+ useEffect(() => {
+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);
+ return () => clearInterval(timer);
+ }, []);
+
+ // Handlers
+ const handleDataUpdate = useCallback((category: string) => (data: QuoteData[]) => {
+ setCollectedData((prev) => ({ ...prev, [category]: data }));
+ }, []);
+
+ const handleRefreshAll = useCallback(() => setRefreshKey((k) => k + 1), []);
+
+ const handleOpenEdit = useCallback(async (category: string, type: 'global' | 'regional') => {
+ let tickers: string[] = [];
+ try {
+ if (type === 'global') {
+ tickers = await tickerStorage.getCategoryTickers(category);
+ } else {
+ const regional = await tickerStorage.getRegionalTickers(category);
+ tickers = regional.map((t) => t.symbol);
+ }
+ } catch (err) {
+ console.error('Failed to load tickers:', err);
+ }
+ dispatch({ type: 'OPEN_MODAL', payload: { category, type, tickers } });
+ }, []);
+
+ const handleSaveTickers = useCallback(async (tickers: string[]) => {
+ const { editModal } = state;
+ const validation = validateSymbolList(tickers);
+ if (!validation.valid) return;
+
+ try {
+ if (editModal.type === 'global') {
+ await tickerStorage.updateCategoryTickers(editModal.category, validation.sanitized);
+ } else {
+ await tickerStorage.updateRegionalTickers(
+ editModal.category,
+ validation.sanitized.map((s) => ({ symbol: s, name: s }))
+ );
+ }
+ const prefs = await tickerStorage.loadPreferences();
+ dispatch({ type: 'SET_PREFERENCES', payload: prefs });
+ dispatch({ type: 'CLOSE_MODAL' });
+ setRefreshKey((k) => k + 1);
+ } catch (err) {
+ console.error('Failed to save tickers:', err);
+ }
+ }, [state.editModal]);
+
+ const recordData = useCallback(async () => {
+ if (Object.keys(collectedData).length === 0) return;
+ try {
+ await contextRecorderService.recordApiResponse(
+ 'Markets',
+ 'market-data',
+ { data: collectedData, timestamp: new Date().toISOString() },
+ `Market Data - ${new Date().toLocaleString()}`,
+ ['markets', 'snapshot']
+ );
+ } catch (err) {
+ console.error('Failed to record:', err);
+ }
+ }, [collectedData]);
+
+ // Loading
+ if (!dbInitialized || !state.preferences) {
+ return (
+ <div
+ style={{
+ height: '100%',
+ backgroundColor: colors.background,
+ color: colors.text,
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '20px',
+ }}
+ >
+ {initError ? (
+ <>
+ <AlertCircle size={48} color={colors.alert} />
+ <div style={{ color: colors.alert }}>{initError}</div>
+ <button
+ onClick={() => window.location.reload()}
+ style={{
+ backgroundColor: colors.primary,
+ color: '#000',
+ border: 'none',
+ padding: '8px 24px',
+ cursor: 'pointer',
+ }}
+ >
+ Reload
+ </button>
+ </>
+ ) : (
+ <>
+ <div
+ style={{
+ width: '50px',
+ height: '50px',
+ border: '3px solid #404040',
+ borderTop: '3px solid #ea580c',
+ borderRadius: '50%',
+ animation: 'spin 1s linear infinite',
+ }}
+ />
+ <div>{t('loading.title', 'Initializing...')}</div>
+ </>
+ )}
+ <style>{`@keyframes spin { to { transform: rotate(360deg); } } @keyframes pulse { 50% { opacity: 0.5; } }`}</style>
+ </div>
+ );
+ }
+
+ const { preferences } = state;
+
+ return (
+ <div
+ style={{
+ height: '100%',
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontFamily,
+ fontWeight,
+ fontStyle,
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column',
+ }}
+ >
+ <style>{`
+ @keyframes spin { to { transform: rotate(360deg); } }
+ @keyframes pulse { 50% { opacity: 0.5; } }
+ .animate-spin { animation: spin 1s linear infinite; }
+ `}</style>
+
+ {/* Header */}
+ <div
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ padding: '8px 12px',
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
+ fontSize: '13px',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>FINCEPT</span>
+ <span>{t('marketTerminalLive')}</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ fontSize: '11px' }}>
+ {currentTime.toISOString().replace('T', ' ').substring(0, 19)}
+ </span>
+ </div>
+ <button
+ onClick={() => createMarketsTabTour().drive()}
+ style={{
+ backgroundColor: colors.info,
+ color: colors.background,
+ border: 'none',
+ padding: '4px 8px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}
+ >
+ <Info size={14} /> HELP
+ </button>
+ </div>
+
+ {/* Controls */}
+ <div
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ flexWrap: 'wrap',
+ padding: '8px 12px',
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
+ gap: '8px',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
+ <button
+ onClick={handleRefreshAll}
+ style={{
+ backgroundColor: colors.primary,
+ color: '#000',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}
+ >
+ <RefreshCw size={12} /> {t('refresh')}
+ </button>
+ <button
+ onClick={() => dispatch({ type: 'SET_AUTO_UPDATE', payload: !state.autoUpdate })}
+ style={{
+ backgroundColor: state.autoUpdate ? colors.secondary : colors.textMuted,
+ color: '#000',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ }}
+ >
+ {t('auto')} {state.autoUpdate ? t('on') : t('off')}
+ </button>
+ <select
+ value={state.updateInterval}
+ onChange={(e) => dispatch({ type: 'SET_UPDATE_INTERVAL', payload: Number(e.target.value) })}
+ style={{
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.text,
+ padding: '4px 8px',
+ fontSize: '11px',
+ }}
+ >
+ <option value={600000}>10 min</option>
+ <option value={900000}>15 min</option>
+ <option value={1800000}>30 min</option>
+ <option value={3600000}>1 hour</option>
+ </select>
+ </div>
+ <RecordingControlPanel
+ tabName="Markets"
+ onRecordingChange={(r) => dispatch({ type: 'SET_RECORDING', payload: r })}
+ onRecordingStart={recordData}
+ />
+ </div>
+
+ {/* Content */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
+ {/* Global Markets */}
+ <div style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ {t('globalMarkets')}
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '16px' }} />
+ <div style={{ display: 'flex', flexWrap: 'wrap', marginBottom: '24px' }}>
+ {preferences.globalMarkets.map((m) => (
+ <ErrorBoundary key={`${m.category}-${refreshKey}`} name={m.category} variant="minimal">
+ <MarketPanel
+ title={m.category}
+ tickers={m.tickers}
+ enabled={dbInitialized}
+ refetchInterval={effectiveRefetchInterval}
+ onEdit={() => handleOpenEdit(m.category, 'global')}
+ onDataUpdate={handleDataUpdate(m.category)}
+ />
+ </ErrorBoundary>
+ ))}
+ </div>
+
+ {/* Regional Markets */}
+ <div style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ {t('regionalMarketsLive')}
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '16px' }} />
+ <div style={{ display: 'flex', flexWrap: 'wrap' }}>
+ {preferences.regionalMarkets.map((m) => {
+ const names = Object.fromEntries(m.tickers.map((t) => [t.symbol, t.name]));
+ return (
+ <ErrorBoundary key={`${m.region}-${refreshKey}`} name={m.region} variant="minimal">
+ <MarketPanel
+ title={m.region}
+ tickers={m.tickers.map((t) => t.symbol)}
+ tickerNames={names}
+ enabled={dbInitialized}
+ refetchInterval={effectiveRefetchInterval}
+ onEdit={() => handleOpenEdit(m.region, 'regional')}
+ onDataUpdate={handleDataUpdate(m.region)}
+ showName
+ />
+ </ErrorBoundary>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* Footer */}
+ <TabFooter
+ tabName="LIVE MARKETS"
+ leftInfo={[{ label: 'Yahoo Finance API', color: colors.textMuted }]}
+ statusInfo={`${preferences.regionalMarkets.length} regional markets | Cache: ENABLED`}
+ backgroundColor={colors.panel}
+ borderColor={colors.textMuted}
+ />
+
+ {/* Edit Modal */}
+ <TickerEditModal
+ isOpen={state.editModal.isOpen}
+ onClose={() => dispatch({ type: 'CLOSE_MODAL' })}
+ title={state.editModal.category}
+ tickers={state.editModal.tickers}
+ onSave={handleSaveTickers}
+ />
+ </div>
+ );
+};
+
+export default MarketsTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
index b04c2bd97..b4727c38c 100644
--- a/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
@@ -6,6 +6,7 @@ import { contextRecorderService } from '@/services/data-sources/contextRecorderS
import RecordingControlPanel from '@/components/common/RecordingControlPanel';
import { TimezoneSelector } from '@/components/common/TimezoneSelector';
import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { analyzeNewsArticle, type NewsAnalysisData, getSentimentColor, getUrgencyColor, getRiskColor } from '@/services/news/newsAnalysisService';
import { createNewsTabTour } from '@/components/tabs/tours/newsTabTour';
import RSSFeedSettingsModal from './RSSFeedSettingsModal';
@@ -14,19 +15,7 @@ declare global {
interface Window { __TAURI__?: any; }
}
-// ── 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',
-};
-const FONT = '"IBM Plex Mono", "Consolas", monospace';
-
-// ── Helpers ──
-const priColor = (p: string) => ({ FLASH: F.RED, URGENT: F.ORANGE, BREAKING: F.YELLOW, ROUTINE: F.GRAY }[p] || F.MUTED);
-const sentColor = (s: string) => ({ BULLISH: F.GREEN, BEARISH: F.RED, NEUTRAL: F.YELLOW }[s] || F.MUTED);
-const impColor = (i: string) => ({ HIGH: F.RED, MEDIUM: F.YELLOW, LOW: F.GREEN }[i] || F.MUTED);
+// Theme colors provided by useTerminalTheme() hook
const SentIcon: React.FC<{ s: string; size?: number }> = ({ s, size = 10 }) =>
s === 'BULLISH' ? <TrendingUp size={size} /> : s === 'BEARISH' ? <TrendingDown size={size} /> : <Minus size={size} />;
@@ -39,7 +28,12 @@ const NewsGridCard: React.FC<{
analyzing: boolean;
currentAnalyzingId: string | null;
openExternal: (url: string) => void;
-}> = ({ article, onAnalyze, analyzing, currentAnalyzingId, openExternal }) => {
+ colors: any;
+ priColor: (p: string) => string;
+ sentColor: (s: string) => string;
+ impColor: (i: string) => string;
+ fontFamily: string;
+}> = ({ article, onAnalyze, analyzing, currentAnalyzingId, openExternal, colors, priColor, sentColor, impColor, fontFamily }) => {
const [hovered, setHovered] = useState(false);
const [expanded, setExpanded] = useState(false);
const isHighPri = article.priority === 'FLASH' || article.priority === 'URGENT';
@@ -51,8 +45,8 @@ const NewsGridCard: React.FC<{
onMouseLeave={() => setHovered(false)}
style={{
padding: '10px 12px',
- backgroundColor: hovered ? F.HOVER : F.PANEL_BG,
- border: `1px solid ${isHighPri ? `${priColor(article.priority)}40` : F.BORDER}`,
+ backgroundColor: hovered ? '#1F1F1F' : colors.panel,
+ border: `1px solid ${isHighPri ? `${priColor(article.priority)}40` : colors.panel}`,
borderLeft: `3px solid ${priColor(article.priority)}`,
borderRadius: '2px',
transition: 'background 0.15s',
@@ -63,11 +57,11 @@ const NewsGridCard: React.FC<{
>
{/* Top: Source + Time */}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
- <span style={{ fontSize: '9px', fontWeight: 700, color: F.CYAN, letterSpacing: '0.3px' }}>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: 'var(--ft-color-accent, #00E5FF)', letterSpacing: '0.3px' }}>
{article.source}
</span>
{article.time && article.time.trim() !== '' && (
- <span style={{ fontSize: '9px', color: F.MUTED }}>{article.time}</span>
+ <span style={{ fontSize: '9px', color: colors.textMuted }}>{article.time}</span>
)}
</div>
@@ -75,7 +69,7 @@ const NewsGridCard: React.FC<{
<div
onClick={() => setExpanded(!expanded)}
style={{
- color: F.WHITE,
+ color: colors.text,
fontSize: '11px',
fontWeight: 600,
lineHeight: '1.4',
@@ -92,12 +86,12 @@ const NewsGridCard: React.FC<{
{/* Summary (when expanded) */}
{expanded && (
<div style={{
- color: F.GRAY,
+ color: colors.textMuted,
fontSize: '10px',
lineHeight: '1.5',
marginBottom: '8px',
paddingLeft: '8px',
- borderLeft: `2px solid ${F.BORDER}`,
+ borderLeft: `2px solid ${colors.panel}`,
}}>{article.summary}</div>
)}
@@ -106,8 +100,8 @@ const NewsGridCard: React.FC<{
<div style={{ display: 'flex', gap: '4px', marginBottom: '8px', flexWrap: 'wrap' }}>
{article.tickers.map((ticker, i) => (
<span key={i} style={{
- padding: '1px 6px', backgroundColor: `${F.GREEN}15`, color: F.GREEN,
- fontSize: '8px', fontWeight: 700, borderRadius: '2px', border: `1px solid ${F.GREEN}30`,
+ padding: '1px 6px', backgroundColor: `${colors.success}15`, color: colors.success,
+ fontSize: '8px', fontWeight: 700, borderRadius: '2px', border: `1px solid ${colors.success}30`,
}}>{ticker}</span>
))}
</div>
@@ -125,7 +119,7 @@ const NewsGridCard: React.FC<{
<button
onClick={(e) => { e.stopPropagation(); openExternal(article.link!); }}
style={{
- flex: 1, padding: '5px 8px', backgroundColor: F.BLUE, color: F.WHITE,
+ flex: 1, padding: '5px 8px', backgroundColor: 'var(--ft-color-blue, #0088FF)', color: colors.text,
border: 'none', fontSize: '8px', fontWeight: 700, cursor: 'pointer',
borderRadius: '2px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px',
}}
@@ -133,8 +127,8 @@ const NewsGridCard: React.FC<{
<button
onClick={(e) => { e.stopPropagation(); navigator.clipboard.writeText(article.link!); }}
style={{
- padding: '5px 8px', background: 'none', border: `1px solid ${F.BORDER}`,
- color: F.GRAY, fontSize: '8px', fontWeight: 700, cursor: 'pointer',
+ padding: '5px 8px', background: 'none', border: `1px solid ${colors.panel}`,
+ color: colors.textMuted, fontSize: '8px', fontWeight: 700, cursor: 'pointer',
borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '3px',
}}
><Copy size={9} /></button>
@@ -143,8 +137,8 @@ const NewsGridCard: React.FC<{
disabled={isAnalyzing}
style={{
flex: 1, padding: '5px 8px',
- backgroundColor: isAnalyzing ? F.MUTED : F.PURPLE,
- color: F.WHITE, border: 'none', fontSize: '8px', fontWeight: 700,
+ backgroundColor: isAnalyzing ? colors.textMuted : 'var(--ft-color-purple, #9D4EDD)',
+ color: colors.text, border: 'none', fontSize: '8px', fontWeight: 700,
cursor: isAnalyzing ? 'not-allowed' : 'pointer',
borderRadius: '2px', opacity: isAnalyzing ? 0.5 : 1,
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px',
@@ -172,7 +166,7 @@ const NewsGridCard: React.FC<{
</span>
<span style={{
padding: '1px 6px', fontSize: '8px', fontWeight: 700, borderRadius: '2px',
- color: F.GRAY, backgroundColor: `${F.MUTED}20`,
+ color: colors.textMuted, backgroundColor: `${colors.textMuted}20`,
}}>{article.category}</span>
<span style={{
marginLeft: 'auto', fontSize: '8px', fontWeight: 700,
@@ -188,6 +182,28 @@ const NewsGridCard: React.FC<{
// ══════════════════════════════════════════════════════════════
const NewsTab: React.FC = () => {
const { t } = useTranslation('news');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+
+ // Helper functions for priority/sentiment colors
+ const priColor = (p: string) => ({
+ FLASH: colors.alert,
+ URGENT: colors.primary,
+ BREAKING: colors.warning,
+ ROUTINE: colors.textMuted
+ }[p] || colors.textMuted);
+
+ const sentColor = (s: string) => ({
+ BULLISH: colors.success,
+ BEARISH: colors.alert,
+ NEUTRAL: colors.warning
+ }[s] || colors.textMuted);
+
+ const impColor = (i: string) => ({
+ HIGH: colors.alert,
+ MEDIUM: colors.warning,
+ LOW: colors.success
+ }[i] || colors.textMuted);
+
const [currentTime, setCurrentTime] = useState(new Date());
const [activeFilter, setActiveFilter] = useState('ALL');
const [newsUpdateCount, setNewsUpdateCount] = useState(0);
@@ -382,12 +398,24 @@ const NewsTab: React.FC = () => {
// ══════════════════════════════════════════════════════════════
// RENDER
// ══════════════════════════════════════════════════════════════
+ const scrollbarCSS = [
+ '@keyframes ntBlink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0.3; } }',
+ '.nt-grid::-webkit-scrollbar { width: 6px; height: 6px; }',
+ `.nt-grid::-webkit-scrollbar-track { background: ${colors.background}; }`,
+ `.nt-grid::-webkit-scrollbar-thumb { background: ${colors.panel}; border-radius: 3px; }`,
+ `.nt-grid::-webkit-scrollbar-thumb:hover { background: ${colors.textMuted}; }`,
+ '*::-webkit-scrollbar { width: 6px; height: 6px; }',
+ `*::-webkit-scrollbar-track { background: ${colors.background}; }`,
+ `*::-webkit-scrollbar-thumb { background: ${colors.panel}; border-radius: 3px; }`,
+ `*::-webkit-scrollbar-thumb:hover { background: ${colors.textMuted}; }`,
+ ].join('\n');
+
return (
<div style={{
height: '100%',
- backgroundColor: F.DARK_BG,
- color: F.WHITE,
- fontFamily: FONT,
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontFamily: fontFamily,
overflow: 'hidden',
display: 'flex',
flexDirection: 'column',
@@ -396,56 +424,56 @@ const NewsTab: React.FC = () => {
{/* ── TOP BAR: Title + Filters + Actions (single merged bar) ── */}
<div style={{
- backgroundColor: F.HEADER_BG,
- borderBottom: `2px solid ${F.ORANGE}`,
+ backgroundColor: colors.panel,
+ borderBottom: `2px solid ${colors.primary}`,
padding: '0 16px',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
- boxShadow: `0 2px 8px ${F.ORANGE}20`,
+ boxShadow: `0 2px 8px ${colors.primary}20`,
flexShrink: 0,
height: '38px',
position: 'relative',
}}>
{/* Left: branding + live indicator */}
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Newspaper size={13} style={{ color: F.ORANGE }} />
- <span style={{ color: F.ORANGE, fontWeight: 700, fontSize: '11px', letterSpacing: '0.5px' }}>
+ <Newspaper size={13} style={{ color: colors.primary }} />
+ <span style={{ color: colors.primary, fontWeight: 700, fontSize: '11px', letterSpacing: '0.5px' }}>
{t('title')}
</span>
- <span style={{ color: F.BORDER }}>|</span>
- <span style={{ color: F.RED, fontWeight: 700, fontSize: '9px', animation: 'ntBlink 1s infinite' }}>LIVE</span>
- <span style={{ color: F.BORDER }}>|</span>
- <span style={{ color: F.YELLOW, fontSize: '9px', fontWeight: 700 }}>
+ <span style={{ color: colors.panel }}>|</span>
+ <span style={{ color: colors.alert, fontWeight: 700, fontSize: '9px', animation: 'ntBlink 1s infinite' }}>LIVE</span>
+ <span style={{ color: colors.panel }}>|</span>
+ <span style={{ color: colors.warning, fontSize: '9px', fontWeight: 700 }}>
<AlertTriangle size={9} style={{ display: 'inline', verticalAlign: 'middle', marginRight: '3px' }} />
{alertCount}
</span>
- <span style={{ color: F.BORDER }}>|</span>
- <span style={{ color: F.GREEN, fontSize: '9px', fontWeight: 700 }}>{feedCount} SRC</span>
- <span style={{ color: F.BORDER }}>|</span>
+ <span style={{ color: colors.panel }}>|</span>
+ <span style={{ color: colors.success, fontSize: '9px', fontWeight: 700 }}>{feedCount} SRC</span>
+ <span style={{ color: colors.panel }}>|</span>
<TimezoneSelector compact />
</div>
{/* Right: actions */}
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<button onClick={() => createNewsTabTour().drive()} style={{
- padding: '4px 8px', background: 'none', border: `1px solid ${F.BORDER}`,
- color: F.GRAY, fontSize: '9px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px',
+ padding: '4px 8px', background: 'none', border: `1px solid ${colors.panel}`,
+ color: colors.textMuted, fontSize: '9px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px',
}}><Info size={10} /></button>
<button id="news-refresh" onClick={() => handleRefresh(true)} disabled={loading} style={{
- padding: '4px 10px', backgroundColor: loading ? F.MUTED : F.ORANGE,
- color: loading ? F.GRAY : F.DARK_BG, border: 'none', fontSize: '9px', fontWeight: 700,
+ padding: '4px 10px', backgroundColor: loading ? colors.textMuted : colors.primary,
+ color: loading ? colors.textMuted : colors.background, border: 'none', fontSize: '9px', fontWeight: 700,
cursor: loading ? 'not-allowed' : 'pointer', borderRadius: '2px',
display: 'flex', alignItems: 'center', gap: '4px',
}}><RefreshCw size={10} />{loading ? 'LOADING' : 'REFRESH'}</button>
<button id="news-interval-settings" onClick={() => setShowIntervalSettings(!showIntervalSettings)} style={{
- padding: '4px 8px', background: 'none', border: `1px solid ${F.BORDER}`,
- color: F.GRAY, fontSize: '9px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px',
+ padding: '4px 8px', background: 'none', border: `1px solid ${colors.panel}`,
+ color: colors.textMuted, fontSize: '9px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px',
display: 'flex', alignItems: 'center', gap: '3px',
}}><Clock size={10} />{refreshInterval}M</button>
<button onClick={() => setShowFeedSettings(true)} style={{
- padding: '4px 8px', background: 'none', border: `1px solid ${F.BORDER}`,
- color: F.GRAY, fontSize: '9px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px',
+ padding: '4px 8px', background: 'none', border: `1px solid ${colors.panel}`,
+ color: colors.textMuted, fontSize: '9px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px',
}}><Settings size={10} /></button>
<RecordingControlPanel tabName="News" onRecordingChange={setIsRecording} onRecordingStart={recordCurrentData} />
</div>
@@ -454,19 +482,19 @@ const NewsTab: React.FC = () => {
{showIntervalSettings && (
<div style={{
position: 'absolute', top: '100%', right: 16,
- backgroundColor: F.PANEL_BG, border: `1px solid ${F.ORANGE}`,
+ backgroundColor: colors.panel, border: `1px solid ${colors.primary}`,
borderRadius: '2px', padding: '6px', zIndex: 1000, marginTop: '2px',
}}>
- <div style={{ fontSize: '9px', color: F.GRAY, fontWeight: 700, marginBottom: '4px', letterSpacing: '0.5px' }}>
+ <div style={{ fontSize: '9px', color: colors.textMuted, fontWeight: 700, marginBottom: '4px', letterSpacing: '0.5px' }}>
AUTO-REFRESH
</div>
{[1, 2, 5, 10, 15, 30].map(min => (
<button key={min}
onClick={() => { setRefreshInterval(min); setShowIntervalSettings(false); }}
style={{
- width: '100%', backgroundColor: refreshInterval === min ? F.ORANGE : 'transparent',
- color: refreshInterval === min ? F.DARK_BG : F.WHITE,
- border: `1px solid ${refreshInterval === min ? F.ORANGE : F.BORDER}`,
+ width: '100%', backgroundColor: refreshInterval === min ? colors.primary : 'transparent',
+ color: refreshInterval === min ? colors.background : colors.text,
+ border: `1px solid ${refreshInterval === min ? colors.primary : colors.panel}`,
padding: '3px 8px', fontSize: '9px', fontWeight: 700, cursor: 'pointer',
marginBottom: '2px', textAlign: 'left', borderRadius: '2px',
}}
@@ -478,7 +506,7 @@ const NewsTab: React.FC = () => {
{/* ── FILTER BAR ── */}
<div id="news-filters" style={{
- backgroundColor: F.PANEL_BG, borderBottom: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.panel, borderBottom: `1px solid ${colors.panel}`,
padding: '3px 10px', flexShrink: 0, display: 'flex', alignItems: 'center', gap: '2px',
}}>
{filters.map(item => (
@@ -486,12 +514,12 @@ const NewsTab: React.FC = () => {
onClick={() => setActiveFilter(item.f)}
style={{
padding: '3px 10px',
- backgroundColor: activeFilter === item.f ? F.ORANGE : 'transparent',
- color: activeFilter === item.f ? F.DARK_BG : F.GRAY,
+ backgroundColor: activeFilter === item.f ? colors.primary : 'transparent',
+ color: activeFilter === item.f ? colors.background : colors.textMuted,
border: 'none', fontSize: '9px', fontWeight: 700,
letterSpacing: '0.3px', cursor: 'pointer', borderRadius: '2px',
}}>
- <span style={{ color: activeFilter === item.f ? F.DARK_BG : F.MUTED, marginRight: '3px', fontSize: '8px' }}>{item.key}</span>
+ <span style={{ color: activeFilter === item.f ? colors.background : colors.textMuted, marginRight: '3px', fontSize: '8px' }}>{item.key}</span>
{item.label}
</button>
))}
@@ -501,14 +529,14 @@ const NewsTab: React.FC = () => {
display: 'flex',
alignItems: 'center',
gap: '4px',
- backgroundColor: F.DARK_BG,
- border: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.panel}`,
borderRadius: '2px',
padding: '2px 8px',
flex: '0 1 220px',
minWidth: '120px',
}}>
- <Search size={10} style={{ color: F.MUTED, flexShrink: 0 }} />
+ <Search size={10} style={{ color: colors.textMuted, flexShrink: 0 }} />
<input
type="text"
value={searchQuery}
@@ -519,9 +547,9 @@ const NewsTab: React.FC = () => {
backgroundColor: 'transparent',
border: 'none',
outline: 'none',
- color: F.WHITE,
+ color: colors.text,
fontSize: '9px',
- fontFamily: FONT,
+ fontFamily: fontFamily,
padding: '2px 0',
}}
/>
@@ -529,7 +557,7 @@ const NewsTab: React.FC = () => {
<button
onClick={() => setSearchQuery('')}
style={{
- background: 'none', border: 'none', color: F.MUTED,
+ background: 'none', border: 'none', color: colors.textMuted,
cursor: 'pointer', padding: '0', display: 'flex', alignItems: 'center',
}}
>
@@ -538,9 +566,9 @@ const NewsTab: React.FC = () => {
)}
</div>
<div style={{ marginLeft: 'auto', display: 'flex', gap: '12px', fontSize: '9px' }}>
- <span style={{ color: F.GRAY }}>TOTAL: <span style={{ color: F.CYAN, fontWeight: 700 }}>{newsArticles.length}</span></span>
- <span style={{ color: F.GRAY }}>SHOWING: <span style={{ color: F.CYAN, fontWeight: 700 }}>{filteredNews.length}</span></span>
- <span style={{ color: loading ? F.YELLOW : F.GREEN, fontWeight: 700 }}>
+ <span style={{ color: colors.textMuted }}>TOTAL: <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontWeight: 700 }}>{newsArticles.length}</span></span>
+ <span style={{ color: colors.textMuted }}>SHOWING: <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontWeight: 700 }}>{filteredNews.length}</span></span>
+ <span style={{ color: loading ? colors.warning : colors.success, fontWeight: 700 }}>
{loading ? 'UPDATING' : (isUsingMockData() ? 'DEMO' : 'LIVE')}
</span>
</div>
@@ -551,8 +579,8 @@ const NewsTab: React.FC = () => {
{/* ── LEFT SIDEBAR: Sentiment + Stats (fixed, no scroll needed) ── */}
<div style={{
- width: '200px', flexShrink: 0, backgroundColor: F.PANEL_BG,
- borderRight: `1px solid ${F.BORDER}`,
+ width: '200px', flexShrink: 0, backgroundColor: colors.panel,
+ borderRight: `1px solid ${colors.panel}`,
display: 'flex', flexDirection: 'column',
padding: '12px',
gap: '12px',
@@ -560,37 +588,37 @@ const NewsTab: React.FC = () => {
}}>
{/* Sentiment */}
<div>
- <div style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px', marginBottom: '8px' }}>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px', marginBottom: '8px' }}>
MARKET SENTIMENT
</div>
- <div style={{ backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px', padding: '10px' }}>
+ <div style={{ backgroundColor: colors.background, border: `1px solid ${colors.panel}`, borderRadius: '2px', padding: '10px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '5px', fontSize: '10px' }}>
- <span style={{ color: F.GREEN }}>BULL</span>
- <span style={{ color: F.GREEN, fontWeight: 700 }}>{bullish} ({Math.round((bullish / total) * 100)}%)</span>
+ <span style={{ color: colors.success }}>BULL</span>
+ <span style={{ color: colors.success, fontWeight: 700 }}>{bullish} ({Math.round((bullish / total) * 100)}%)</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '5px', fontSize: '10px' }}>
- <span style={{ color: F.RED }}>BEAR</span>
- <span style={{ color: F.RED, fontWeight: 700 }}>{bearish} ({Math.round((bearish / total) * 100)}%)</span>
+ <span style={{ color: colors.alert }}>BEAR</span>
+ <span style={{ color: colors.alert, fontWeight: 700 }}>{bearish} ({Math.round((bearish / total) * 100)}%)</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px', fontSize: '10px' }}>
- <span style={{ color: F.YELLOW }}>NEUT</span>
- <span style={{ color: F.YELLOW, fontWeight: 700 }}>{neutral} ({Math.round((neutral / total) * 100)}%)</span>
+ <span style={{ color: colors.warning }}>NEUT</span>
+ <span style={{ color: colors.warning, fontWeight: 700 }}>{neutral} ({Math.round((neutral / total) * 100)}%)</span>
</div>
{/* Bar */}
- <div style={{ height: '4px', backgroundColor: F.BORDER, borderRadius: '2px', display: 'flex', overflow: 'hidden', marginBottom: '8px' }}>
- <div style={{ width: `${Math.round((bullish / total) * 100)}%`, backgroundColor: F.GREEN }} />
- <div style={{ width: `${Math.round((neutral / total) * 100)}%`, backgroundColor: F.YELLOW }} />
- <div style={{ width: `${Math.round((bearish / total) * 100)}%`, backgroundColor: F.RED }} />
+ <div style={{ height: '4px', backgroundColor: colors.panel, borderRadius: '2px', display: 'flex', overflow: 'hidden', marginBottom: '8px' }}>
+ <div style={{ width: `${Math.round((bullish / total) * 100)}%`, backgroundColor: colors.success }} />
+ <div style={{ width: `${Math.round((neutral / total) * 100)}%`, backgroundColor: colors.warning }} />
+ <div style={{ width: `${Math.round((bearish / total) * 100)}%`, backgroundColor: colors.alert }} />
</div>
{/* Net Score */}
<div style={{
- textAlign: 'center', padding: '6px', backgroundColor: `${parseFloat(score) > 0 ? F.GREEN : parseFloat(score) < 0 ? F.RED : F.YELLOW}10`,
- borderRadius: '2px', border: `1px solid ${parseFloat(score) > 0 ? F.GREEN : parseFloat(score) < 0 ? F.RED : F.YELLOW}30`,
+ textAlign: 'center', padding: '6px', backgroundColor: `${parseFloat(score) > 0 ? colors.success : parseFloat(score) < 0 ? colors.alert : colors.warning}10`,
+ borderRadius: '2px', border: `1px solid ${parseFloat(score) > 0 ? colors.success : parseFloat(score) < 0 ? colors.alert : colors.warning}30`,
}}>
- <div style={{ fontSize: '9px', color: F.GRAY, marginBottom: '2px' }}>NET SCORE</div>
+ <div style={{ fontSize: '9px', color: colors.textMuted, marginBottom: '2px' }}>NET SCORE</div>
<div style={{
fontSize: '16px', fontWeight: 700,
- color: parseFloat(score) > 0 ? F.GREEN : parseFloat(score) < 0 ? F.RED : F.YELLOW,
+ color: parseFloat(score) > 0 ? colors.success : parseFloat(score) < 0 ? colors.alert : colors.warning,
}}>{score}</div>
</div>
</div>
@@ -598,18 +626,18 @@ const NewsTab: React.FC = () => {
{/* Feed Stats */}
<div>
- <div style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px', marginBottom: '8px' }}>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px', marginBottom: '8px' }}>
FEED STATISTICS
</div>
- <div style={{ backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px', padding: '10px' }}>
+ <div style={{ backgroundColor: colors.background, border: `1px solid ${colors.panel}`, borderRadius: '2px', padding: '10px' }}>
{[
- { label: 'ARTICLES', value: newsArticles.length, color: F.CYAN },
- { label: 'FEEDS', value: feedCount, color: F.CYAN },
- { label: 'ALERTS', value: alertCount, color: F.ORANGE },
- { label: 'UPDATES', value: newsUpdateCount, color: F.CYAN },
+ { label: 'ARTICLES', value: newsArticles.length, color: 'var(--ft-color-accent, #00E5FF)' },
+ { label: 'FEEDS', value: feedCount, color: 'var(--ft-color-accent, #00E5FF)' },
+ { label: 'ALERTS', value: alertCount, color: colors.primary },
+ { label: 'UPDATES', value: newsUpdateCount, color: 'var(--ft-color-accent, #00E5FF)' },
].map((s, i) => (
<div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', marginBottom: i < 3 ? '4px' : 0 }}>
- <span style={{ color: F.GRAY }}>{s.label}</span>
+ <span style={{ color: colors.textMuted }}>{s.label}</span>
<span style={{ color: s.color, fontWeight: 700 }}>{s.value}</span>
</div>
))}
@@ -618,39 +646,39 @@ const NewsTab: React.FC = () => {
{/* Top Categories */}
<div>
- <div style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px', marginBottom: '8px' }}>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px', marginBottom: '8px' }}>
CATEGORIES
</div>
- <div style={{ backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px', padding: '10px' }}>
+ <div style={{ backgroundColor: colors.background, border: `1px solid ${colors.panel}`, borderRadius: '2px', padding: '10px' }}>
{topCategories.length > 0 ? topCategories.map(([cat, count], i) => (
<div key={cat} style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', marginBottom: i < topCategories.length - 1 ? '4px' : 0 }}>
- <span style={{ color: F.GRAY }}>{cat}</span>
- <span style={{ color: F.PURPLE, fontWeight: 700 }}>{count}</span>
+ <span style={{ color: colors.textMuted }}>{cat}</span>
+ <span style={{ color: 'var(--ft-color-purple, #9D4EDD)', fontWeight: 700 }}>{count}</span>
</div>
)) : (
- <div style={{ fontSize: '10px', color: F.MUTED }}>No data</div>
+ <div style={{ fontSize: '10px', color: colors.textMuted }}>No data</div>
)}
</div>
</div>
{/* Active Sources (compact) */}
<div style={{ flex: 1, minHeight: 0 }}>
- <div style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px', marginBottom: '8px' }}>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: colors.textMuted, letterSpacing: '0.5px', marginBottom: '8px' }}>
ACTIVE SOURCES
</div>
<div style={{
- backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px',
+ backgroundColor: colors.background, border: `1px solid ${colors.panel}`, borderRadius: '2px',
padding: '8px 10px', display: 'flex', flexWrap: 'wrap', gap: '4px',
}}>
{activeSources.slice(0, 8).map((src, i) => (
<span key={i} style={{
padding: '1px 6px', fontSize: '8px', fontWeight: 700,
- color: F.CYAN, backgroundColor: `${F.CYAN}10`,
- borderRadius: '2px', border: `1px solid ${F.CYAN}20`,
+ color: 'var(--ft-color-accent, #00E5FF)', backgroundColor: 'rgba(0, 229, 255, 0.1)',
+ borderRadius: '2px', border: '1px solid rgba(0, 229, 255, 0.2)',
}}>{src}</span>
))}
{activeSources.length > 8 && (
- <span style={{ fontSize: '8px', color: F.MUTED }}>+{activeSources.length - 8}</span>
+ <span style={{ fontSize: '8px', color: colors.textMuted }}>+{activeSources.length - 8}</span>
)}
</div>
</div>
@@ -659,12 +687,12 @@ const NewsTab: React.FC = () => {
{/* ── CENTER: News Grid ── */}
<div id="news-primary-feed" style={{
flex: 1, overflow: 'auto', padding: '12px',
- backgroundColor: F.DARK_BG,
+ backgroundColor: colors.background,
}}>
{loading && newsArticles.length === 0 ? (
<div style={{
display: 'flex', flexDirection: 'column', alignItems: 'center',
- justifyContent: 'center', height: '100%', color: F.MUTED,
+ justifyContent: 'center', height: '100%', color: colors.textMuted,
}}>
<RefreshCw size={20} className="animate-spin" style={{ marginBottom: '10px', opacity: 0.5 }} />
<span style={{ fontSize: '11px' }}>Loading news from {feedCount} RSS feeds...</span>
@@ -672,7 +700,7 @@ const NewsTab: React.FC = () => {
) : filteredNews.length === 0 ? (
<div style={{
display: 'flex', flexDirection: 'column', alignItems: 'center',
- justifyContent: 'center', height: '100%', color: F.MUTED,
+ justifyContent: 'center', height: '100%', color: colors.textMuted,
}}>
<Newspaper size={20} style={{ marginBottom: '10px', opacity: 0.5 }} />
<span style={{ fontSize: '11px' }}>No articles found for filter: {activeFilter}</span>
@@ -692,6 +720,11 @@ const NewsTab: React.FC = () => {
analyzing={analyzingArticle}
currentAnalyzingId={currentAnalyzingId}
openExternal={openExternal}
+ colors={colors}
+ priColor={priColor}
+ sentColor={sentColor}
+ impColor={impColor}
+ fontFamily={fontFamily}
/>
))}
</div>
@@ -703,8 +736,8 @@ const NewsTab: React.FC = () => {
<div style={{
width: '400px',
flexShrink: 0,
- backgroundColor: F.PANEL_BG,
- borderLeft: `2px solid ${F.ORANGE}`,
+ backgroundColor: colors.panel,
+ borderLeft: `2px solid ${colors.primary}`,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
@@ -714,16 +747,16 @@ const NewsTab: React.FC = () => {
{/* Panel Header */}
<div style={{
padding: '10px 14px',
- backgroundColor: F.HEADER_BG,
- borderBottom: `2px solid ${F.ORANGE}`,
+ backgroundColor: colors.panel,
+ borderBottom: `2px solid ${colors.primary}`,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
flexShrink: 0,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Zap size={13} style={{ color: F.PURPLE }} />
- <span style={{ fontSize: '10px', fontWeight: 700, color: F.PURPLE, letterSpacing: '0.5px' }}>
+ <Zap size={13} style={{ color: 'var(--ft-color-purple, #9D4EDD)' }} />
+ <span style={{ fontSize: '10px', fontWeight: 700, color: 'var(--ft-color-purple, #9D4EDD)', letterSpacing: '0.5px' }}>
AI ANALYSIS
</span>
</div>
@@ -731,8 +764,8 @@ const NewsTab: React.FC = () => {
onClick={() => setAnalysisPanelOpen(false)}
style={{
background: 'none',
- border: `1px solid ${F.BORDER}`,
- color: F.GRAY,
+ border: `1px solid ${colors.panel}`,
+ color: colors.textMuted,
cursor: 'pointer',
borderRadius: '2px',
padding: '3px 8px',
@@ -758,7 +791,7 @@ const NewsTab: React.FC = () => {
<div style={{ marginBottom: '14px' }}>
<div style={{
fontSize: '9px',
- color: F.GRAY,
+ color: colors.textMuted,
fontWeight: 700,
marginBottom: '6px',
letterSpacing: '0.5px',
@@ -767,14 +800,14 @@ const NewsTab: React.FC = () => {
</div>
<div style={{
padding: '10px 12px',
- backgroundColor: F.DARK_BG,
- border: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.panel}`,
borderLeft: `3px solid ${priColor(currentAnalyzedArticle.priority)}`,
borderRadius: '2px',
}}>
<div style={{
fontSize: '11px',
- color: F.WHITE,
+ color: colors.text,
fontWeight: 600,
lineHeight: '1.4',
marginBottom: '8px',
@@ -784,13 +817,13 @@ const NewsTab: React.FC = () => {
<div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', marginBottom: '6px' }}>
<span style={{
fontSize: '8px',
- color: F.CYAN,
+ color: 'var(--ft-color-accent, #00E5FF)',
fontWeight: 700,
}}>
{currentAnalyzedArticle.source}
</span>
{currentAnalyzedArticle.time && (
- <span style={{ fontSize: '8px', color: F.MUTED }}>
+ <span style={{ fontSize: '8px', color: colors.textMuted }}>
{currentAnalyzedArticle.time}
</span>
)}
@@ -822,8 +855,8 @@ const NewsTab: React.FC = () => {
fontSize: '8px',
fontWeight: 700,
borderRadius: '2px',
- color: F.GRAY,
- backgroundColor: `${F.MUTED}20`,
+ color: colors.textMuted,
+ backgroundColor: `${colors.textMuted}20`,
}}>
{currentAnalyzedArticle.category}
</span>
@@ -845,13 +878,13 @@ const NewsTab: React.FC = () => {
<div style={{
width: '40px',
height: '40px',
- border: `3px solid ${F.BORDER}`,
- borderTop: `3px solid ${F.PURPLE}`,
+ border: `3px solid ${colors.panel}`,
+ borderTop: '3px solid var(--ft-color-purple, #9D4EDD)',
borderRadius: '50%',
animation: 'spin 1s linear infinite',
}} />
<div style={{
- color: F.PURPLE,
+ color: 'var(--ft-color-purple, #9D4EDD)',
fontSize: '10px',
fontWeight: 700,
letterSpacing: '0.5px',
@@ -859,7 +892,7 @@ const NewsTab: React.FC = () => {
ANALYZING WITH AI...
</div>
<div style={{
- color: F.GRAY,
+ color: colors.textMuted,
fontSize: '9px',
textAlign: 'center',
lineHeight: '1.5',
@@ -875,8 +908,8 @@ const NewsTab: React.FC = () => {
{/* Credits Info */}
<div style={{
padding: '8px 12px',
- backgroundColor: `${F.PURPLE}15`,
- border: `1px solid ${F.PURPLE}`,
+ backgroundColor: 'rgba(157, 78, 221, 0.1)',
+ border: '1px solid var(--ft-color-purple, #9D4EDD)',
borderRadius: '2px',
marginBottom: '14px',
display: 'flex',
@@ -884,10 +917,10 @@ const NewsTab: React.FC = () => {
alignItems: 'center',
fontSize: '9px',
}}>
- <span style={{ color: F.PURPLE, fontWeight: 700, letterSpacing: '0.5px' }}>
+ <span style={{ color: 'var(--ft-color-purple, #9D4EDD)', fontWeight: 700, letterSpacing: '0.5px' }}>
ANALYSIS COMPLETE
</span>
- <span style={{ color: F.GRAY }}>
+ <span style={{ color: colors.textMuted }}>
{analysisData.credits_used} CR | {analysisData.credits_remaining.toLocaleString()} REM
</span>
</div>
@@ -897,7 +930,7 @@ const NewsTab: React.FC = () => {
<div style={{ marginBottom: '14px' }}>
<div style={{
fontSize: '9px',
- color: F.GRAY,
+ color: colors.textMuted,
fontWeight: 700,
marginBottom: '6px',
letterSpacing: '0.5px',
@@ -906,11 +939,11 @@ const NewsTab: React.FC = () => {
</div>
<div style={{
fontSize: '10px',
- color: F.WHITE,
+ color: colors.text,
lineHeight: '1.6',
padding: '10px 12px',
- backgroundColor: F.DARK_BG,
- border: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.panel}`,
borderRadius: '2px',
}}>
{analysisData.analysis.summary}
@@ -923,7 +956,7 @@ const NewsTab: React.FC = () => {
<div style={{ marginBottom: '14px' }}>
<div style={{
fontSize: '9px',
- color: F.GRAY,
+ color: colors.textMuted,
fontWeight: 700,
marginBottom: '6px',
letterSpacing: '0.5px',
@@ -932,8 +965,8 @@ const NewsTab: React.FC = () => {
</div>
<div style={{
padding: '10px 12px',
- backgroundColor: F.DARK_BG,
- border: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.panel}`,
borderRadius: '2px',
}}>
{analysisData.analysis.key_points.filter(pt => typeof pt === 'string').map((pt, i) => (
@@ -941,9 +974,9 @@ const NewsTab: React.FC = () => {
key={i}
style={{
fontSize: '9px',
- color: F.WHITE,
+ color: colors.text,
paddingLeft: '10px',
- borderLeft: `2px solid ${F.ORANGE}`,
+ borderLeft: `2px solid ${colors.primary}`,
marginBottom: i < analysisData.analysis.key_points.length - 1 ? '8px' : 0,
lineHeight: '1.5',
}}
@@ -964,13 +997,13 @@ const NewsTab: React.FC = () => {
}}>
<div style={{
padding: '10px',
- backgroundColor: F.DARK_BG,
- border: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.panel}`,
borderRadius: '2px',
}}>
<div style={{
fontSize: '9px',
- color: F.GRAY,
+ color: colors.textMuted,
fontWeight: 700,
marginBottom: '6px',
}}>
@@ -982,7 +1015,7 @@ const NewsTab: React.FC = () => {
fontSize: '9px',
marginBottom: '3px',
}}>
- <span style={{ color: F.GRAY }}>Score</span>
+ <span style={{ color: colors.textMuted }}>Score</span>
<span style={{
color: getSentimentColor(analysisData.analysis.sentiment.score),
fontWeight: 700,
@@ -996,8 +1029,8 @@ const NewsTab: React.FC = () => {
fontSize: '9px',
marginBottom: '3px',
}}>
- <span style={{ color: F.GRAY }}>Intensity</span>
- <span style={{ color: F.CYAN, fontWeight: 700 }}>
+ <span style={{ color: colors.textMuted }}>Intensity</span>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontWeight: 700 }}>
{analysisData.analysis.sentiment.intensity.toFixed(2)}
</span>
</div>
@@ -1006,21 +1039,21 @@ const NewsTab: React.FC = () => {
justifyContent: 'space-between',
fontSize: '9px',
}}>
- <span style={{ color: F.GRAY }}>Confidence</span>
- <span style={{ color: F.GREEN, fontWeight: 700 }}>
+ <span style={{ color: colors.textMuted }}>Confidence</span>
+ <span style={{ color: colors.success, fontWeight: 700 }}>
{(analysisData.analysis.sentiment.confidence * 100).toFixed(0)}%
</span>
</div>
</div>
<div style={{
padding: '10px',
- backgroundColor: F.DARK_BG,
- border: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.panel}`,
borderRadius: '2px',
}}>
<div style={{
fontSize: '9px',
- color: F.GRAY,
+ color: colors.textMuted,
fontWeight: 700,
marginBottom: '6px',
}}>
@@ -1032,7 +1065,7 @@ const NewsTab: React.FC = () => {
fontSize: '9px',
marginBottom: '3px',
}}>
- <span style={{ color: F.GRAY }}>Urgency</span>
+ <span style={{ color: colors.textMuted }}>Urgency</span>
<span style={{
color: getUrgencyColor(analysisData.analysis.market_impact.urgency),
fontWeight: 700,
@@ -1045,8 +1078,8 @@ const NewsTab: React.FC = () => {
justifyContent: 'space-between',
fontSize: '9px',
}}>
- <span style={{ color: F.GRAY }}>Prediction</span>
- <span style={{ color: F.CYAN, fontWeight: 700 }}>
+ <span style={{ color: colors.textMuted }}>Prediction</span>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontWeight: 700 }}>
{analysisData.analysis.market_impact.prediction.replace('_', ' ').toUpperCase()}
</span>
</div>
@@ -1058,7 +1091,7 @@ const NewsTab: React.FC = () => {
<div style={{ marginBottom: '14px' }}>
<div style={{
fontSize: '9px',
- color: F.GRAY,
+ color: colors.textMuted,
fontWeight: 700,
marginBottom: '6px',
letterSpacing: '0.5px',
@@ -1077,8 +1110,8 @@ const NewsTab: React.FC = () => {
key={type}
style={{
padding: '8px',
- backgroundColor: F.DARK_BG,
- border: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.panel}`,
borderRadius: '2px',
}}
>
@@ -1092,7 +1125,7 @@ const NewsTab: React.FC = () => {
</div>
{riskSignal.details && typeof riskSignal.details === 'string' && (
<div style={{
- color: F.MUTED,
+ color: colors.textMuted,
fontSize: '8px',
lineHeight: '1.3',
}}>
@@ -1111,7 +1144,7 @@ const NewsTab: React.FC = () => {
<div style={{ marginBottom: '14px' }}>
<div style={{
fontSize: '9px',
- color: F.GRAY,
+ color: colors.textMuted,
fontWeight: 700,
marginBottom: '6px',
}}>
@@ -1123,12 +1156,12 @@ const NewsTab: React.FC = () => {
key={idx}
style={{
padding: '2px 8px',
- backgroundColor: `${F.PURPLE}20`,
- color: F.WHITE,
+ backgroundColor: 'rgba(157, 78, 221, 0.15)',
+ color: colors.text,
fontSize: '8px',
fontWeight: 700,
borderRadius: '2px',
- border: `1px solid ${F.PURPLE}`,
+ border: '1px solid var(--ft-color-purple, #9D4EDD)',
}}
>
{topic}
@@ -1143,7 +1176,7 @@ const NewsTab: React.FC = () => {
<div style={{ marginBottom: '14px' }}>
<div style={{
fontSize: '9px',
- color: F.GRAY,
+ color: colors.textMuted,
fontWeight: 700,
marginBottom: '6px',
}}>
@@ -1155,11 +1188,11 @@ const NewsTab: React.FC = () => {
key={idx}
style={{
padding: '2px 8px',
- backgroundColor: `${F.MUTED}20`,
- color: F.GRAY,
+ backgroundColor: `${colors.textMuted}20`,
+ color: colors.textMuted,
fontSize: '8px',
borderRadius: '2px',
- border: `1px solid ${F.MUTED}`,
+ border: `1px solid ${colors.textMuted}`,
}}
>
{kw}
@@ -1174,7 +1207,7 @@ const NewsTab: React.FC = () => {
<div>
<div style={{
fontSize: '9px',
- color: F.GRAY,
+ color: colors.textMuted,
fontWeight: 700,
marginBottom: '6px',
}}>
@@ -1185,21 +1218,21 @@ const NewsTab: React.FC = () => {
key={idx}
style={{
padding: '6px 10px',
- backgroundColor: F.DARK_BG,
- border: `1px solid ${F.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.panel}`,
borderRadius: '2px',
marginBottom: '4px',
}}
>
<span style={{
- color: F.WHITE,
+ color: colors.text,
fontWeight: 700,
fontSize: '9px',
}}>
{typeof org.name === 'string' ? org.name : ''}
</span>
<span style={{
- color: F.GRAY,
+ color: colors.textMuted,
fontSize: '9px',
marginLeft: '6px',
}}>
@@ -1221,7 +1254,7 @@ const NewsTab: React.FC = () => {
justifyContent: 'center',
padding: '40px 20px',
gap: '12px',
- color: F.MUTED,
+ color: colors.textMuted,
}}>
<Zap size={32} style={{ opacity: 0.3 }} />
<div style={{
@@ -1247,40 +1280,30 @@ const NewsTab: React.FC = () => {
{/* ── STATUS BAR ── */}
<div style={{
- backgroundColor: F.HEADER_BG, borderTop: `1px solid ${F.BORDER}`,
- padding: '3px 16px', fontSize: '9px', color: F.GRAY, flexShrink: 0,
+ backgroundColor: colors.panel, borderTop: `1px solid ${colors.panel}`,
+ padding: '3px 16px', fontSize: '9px', color: colors.textMuted, flexShrink: 0,
display: 'flex', justifyContent: 'space-between', alignItems: 'center',
}}>
<div style={{ display: 'flex', gap: '12px' }}>
<span>FINCEPT NEWS v1.0</span>
- <span style={{ color: F.BORDER }}>|</span>
- <span>FEEDS: <span style={{ color: F.CYAN }}>{feedCount}</span></span>
- <span style={{ color: F.BORDER }}>|</span>
- <span>ARTICLES: <span style={{ color: F.CYAN }}>{newsArticles.length}</span></span>
- <span style={{ color: F.BORDER }}>|</span>
- <span>FILTER: <span style={{ color: F.ORANGE }}>{activeFilter}</span></span>
+ <span style={{ color: colors.panel }}>|</span>
+ <span>FEEDS: <span style={{ color: 'var(--ft-color-accent, #00E5FF)' }}>{feedCount}</span></span>
+ <span style={{ color: colors.panel }}>|</span>
+ <span>ARTICLES: <span style={{ color: 'var(--ft-color-accent, #00E5FF)' }}>{newsArticles.length}</span></span>
+ <span style={{ color: colors.panel }}>|</span>
+ <span>FILTER: <span style={{ color: colors.primary }}>{activeFilter}</span></span>
</div>
<div style={{ display: 'flex', gap: '12px' }}>
- <span>SENTIMENT: <span style={{ color: parseFloat(score) > 0 ? F.GREEN : parseFloat(score) < 0 ? F.RED : F.YELLOW }}>{score}</span></span>
- <span style={{ color: F.BORDER }}>|</span>
+ <span>SENTIMENT: <span style={{ color: parseFloat(score) > 0 ? colors.success : parseFloat(score) < 0 ? colors.alert : colors.warning }}>{score}</span></span>
+ <span style={{ color: colors.panel }}>|</span>
<span>{currentTime.toTimeString().substring(0, 8)}</span>
- <span style={{ color: F.BORDER }}>|</span>
- <span style={{ color: loading ? F.YELLOW : F.GREEN, fontWeight: 700 }}>{loading ? 'UPDATING' : 'LIVE'}</span>
+ <span style={{ color: colors.panel }}>|</span>
+ <span style={{ color: loading ? colors.warning : colors.success, fontWeight: 700 }}>{loading ? 'UPDATING' : 'LIVE'}</span>
</div>
</div>
{/* ── CSS ── */}
- <style>{`
- @keyframes ntBlink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0.3; } }
- .nt-grid::-webkit-scrollbar { width: 6px; height: 6px; }
- .nt-grid::-webkit-scrollbar-track { background: ${F.DARK_BG}; }
- .nt-grid::-webkit-scrollbar-thumb { background: ${F.BORDER}; border-radius: 3px; }
- .nt-grid::-webkit-scrollbar-thumb:hover { background: ${F.MUTED}; }
- *::-webkit-scrollbar { width: 6px; height: 6px; }
- *::-webkit-scrollbar-track { background: ${F.DARK_BG}; }
- *::-webkit-scrollbar-thumb { background: ${F.BORDER}; border-radius: 3px; }
- *::-webkit-scrollbar-thumb:hover { background: ${F.MUTED}; }
- `}</style>
+ <style dangerouslySetInnerHTML={{ __html: scrollbarCSS }} />
<RSSFeedSettingsModal isOpen={showFeedSettings} onClose={() => setShowFeedSettings(false)} onFeedsUpdated={() => handleRefresh(true)} />
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/news/RSSFeedSettingsModal.tsx b/fincept-terminal-desktop/src/components/tabs/news/RSSFeedSettingsModal.tsx
index 76361d5c6..423855665 100644
--- a/fincept-terminal-desktop/src/components/tabs/news/RSSFeedSettingsModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/news/RSSFeedSettingsModal.tsx
@@ -1,5 +1,7 @@
// RSS Feed Settings Modal - Allows users to manage their RSS news sources
import React, { useState, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { Plus, Trash2, Edit2, Check, X, ExternalLink, RefreshCw, AlertCircle } from 'lucide-react';
import { showConfirm } from '@/utils/notifications';
import {
@@ -23,27 +25,6 @@ import {
type RSSFeed,
} from '@/services/news/rssFeedService';
-// FINCEPT Design System Colors
-const FINCEPT = {
- 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_FAMILY = '"IBM Plex Mono", "Consolas", monospace';
-
interface RSSFeedSettingsModalProps {
isOpen: boolean;
onClose: () => void;
@@ -55,6 +36,9 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
onClose,
onFeedsUpdated,
}) => {
+ const { t } = useTranslation('news');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+
const [activeTab, setActiveTab] = useState<'user' | 'default'>('user');
const [userFeeds, setUserFeeds] = useState<UserRSSFeed[]>([]);
const [defaultFeeds, setDefaultFeeds] = useState<RSSFeed[]>([]);
@@ -95,7 +79,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
setDefaultFeeds(defaults);
setDeletedDefaultCount(deletedIds.length);
} catch (err) {
- setError('Failed to load RSS feeds');
+ setError(t('messages.failedToLoad'));
console.error('[RSSFeedSettings] Failed to load feeds:', err);
} finally {
setLoading(false);
@@ -104,7 +88,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
const handleTestUrl = async () => {
if (!isValidRSSUrl(formData.url)) {
- setFormError('Please enter a valid URL');
+ setFormError(t('rssSettings.errors.invalidUrl'));
return;
}
setTesting(true);
@@ -113,13 +97,13 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
const result = await testRSSFeedUrl(formData.url);
setTestResult(result);
if (!result) {
- setFormError('URL does not appear to be a valid RSS feed');
+ setFormError(t('rssSettings.errors.invalidRss'));
} else {
setFormError(null);
}
} catch (err) {
setTestResult(false);
- setFormError('Failed to test URL');
+ setFormError(t('rssSettings.errors.testFailed'));
} finally {
setTesting(false);
}
@@ -127,15 +111,15 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
const handleAddFeed = async () => {
if (!formData.name.trim()) {
- setFormError('Name is required');
+ setFormError(t('rssSettings.errors.nameRequired'));
return;
}
if (!isValidRSSUrl(formData.url)) {
- setFormError('Please enter a valid URL');
+ setFormError(t('rssSettings.errors.invalidUrl'));
return;
}
if (!formData.source_name.trim()) {
- setFormError('Source name is required');
+ setFormError(t('rssSettings.errors.sourceRequired'));
return;
}
@@ -162,15 +146,15 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
const handleUpdateFeed = async () => {
if (!editingFeed) return;
if (!formData.name.trim()) {
- setFormError('Name is required');
+ setFormError(t('rssSettings.errors.nameRequired'));
return;
}
if (!isValidRSSUrl(formData.url)) {
- setFormError('Please enter a valid URL');
+ setFormError(t('rssSettings.errors.invalidUrl'));
return;
}
if (!formData.source_name.trim()) {
- setFormError('Source name is required');
+ setFormError(t('rssSettings.errors.sourceRequired'));
return;
}
@@ -197,8 +181,8 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
const handleDeleteFeed = async (id: string) => {
const confirmed = await showConfirm(
- 'This action cannot be undone.',
- { title: 'Delete this RSS feed?', type: 'danger' }
+ t('rssSettings.confirmDelete.message'),
+ { title: t('rssSettings.confirmDelete.title'), type: 'danger' }
);
if (!confirmed) return;
try {
@@ -298,14 +282,14 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
alignItems: 'center',
justifyContent: 'center',
zIndex: 10000,
- fontFamily: FONT_FAMILY,
+ fontFamily,
}}
onClick={onClose}
>
<div
style={{
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.ORANGE}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px',
width: '800px',
maxWidth: '95vw',
@@ -318,8 +302,8 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{/* Header */}
<div
style={{
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `2px solid ${FINCEPT.ORANGE}`,
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: `2px solid ${colors.primary}`,
padding: '10px 16px',
display: 'flex',
justifyContent: 'space-between',
@@ -327,19 +311,19 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: FINCEPT.ORANGE, fontWeight: 700, fontSize: '11px', letterSpacing: '0.5px' }}>
- RSS FEED SETTINGS
+ <span style={{ color: colors.primary, fontWeight: 700, fontSize: fontSize.tiny, letterSpacing: '0.5px' }}>
+ {t('rssSettings.title')}
</span>
- <span style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>
- MANAGE YOUR NEWS SOURCES
+ <span style={{ color: colors.textMuted, fontSize: '9px' }}>
+ {t('rssSettings.subtitle')}
</span>
</div>
<button
onClick={onClose}
style={{
padding: '4px 10px',
- backgroundColor: FINCEPT.RED,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.alert,
+ color: colors.text,
border: 'none',
fontSize: '9px',
fontWeight: 700,
@@ -350,7 +334,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
gap: '4px',
}}
>
- <X size={12} /> CLOSE
+ <X size={12} /> {t('rssSettings.close')}
</button>
</div>
@@ -358,16 +342,16 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
<div
style={{
display: 'flex',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid var(--ft-color-border, #2A2A2A)`,
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
}}
>
<button
onClick={() => setActiveTab('user')}
style={{
padding: '8px 16px',
- backgroundColor: activeTab === 'user' ? FINCEPT.ORANGE : 'transparent',
- color: activeTab === 'user' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ backgroundColor: activeTab === 'user' ? colors.primary : 'transparent',
+ color: activeTab === 'user' ? colors.background : colors.textMuted,
border: 'none',
cursor: 'pointer',
fontSize: '9px',
@@ -375,14 +359,14 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
letterSpacing: '0.5px',
}}
>
- MY FEEDS ({userFeeds.length})
+ {t('rssSettings.myFeeds')} ({userFeeds.length})
</button>
<button
onClick={() => setActiveTab('default')}
style={{
padding: '8px 16px',
- backgroundColor: activeTab === 'default' ? FINCEPT.ORANGE : 'transparent',
- color: activeTab === 'default' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ backgroundColor: activeTab === 'default' ? colors.primary : 'transparent',
+ color: activeTab === 'default' ? colors.background : colors.textMuted,
border: 'none',
cursor: 'pointer',
fontSize: '9px',
@@ -390,7 +374,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
letterSpacing: '0.5px',
}}
>
- DEFAULT FEEDS ({defaultFeeds.length})
+ {t('rssSettings.defaultFeeds')} ({defaultFeeds.length})
</button>
</div>
@@ -403,13 +387,13 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
alignItems: 'center',
justifyContent: 'center',
height: '100%',
- color: FINCEPT.MUTED,
+ color: colors.textMuted,
fontSize: '10px',
textAlign: 'center',
padding: '40px',
}}>
<RefreshCw size={20} style={{ marginBottom: '8px', opacity: 0.5 }} className="animate-spin" />
- <span>Loading feeds...</span>
+ <span>{t('messages.loadingFeedsModal')}</span>
</div>
) : error ? (
<div style={{
@@ -418,7 +402,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
alignItems: 'center',
justifyContent: 'center',
height: '100%',
- color: FINCEPT.RED,
+ color: colors.alert,
fontSize: '10px',
textAlign: 'center',
padding: '40px',
@@ -434,26 +418,26 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
style={{
textAlign: 'center',
padding: '40px 20px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.YELLOW}`,
+ backgroundColor: colors.background,
+ border: `1px solid var(--ft-color-warning, #FFD700)`,
borderRadius: '2px',
marginBottom: '16px',
}}
>
- <AlertCircle size={24} style={{ color: FINCEPT.YELLOW, marginBottom: '12px' }} />
- <div style={{ color: FINCEPT.WHITE, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
- NO RSS FEEDS AVAILABLE
+ <AlertCircle size={24} style={{ color: 'var(--ft-color-warning, #FFD700)', marginBottom: '12px' }} />
+ <div style={{ color: colors.text, fontSize: fontSize.tiny, fontWeight: 700, marginBottom: '8px' }}>
+ {t('rssSettings.noFeedsAvailable')}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px', marginBottom: '16px' }}>
- All feeds have been deleted. Add a new feed or restore defaults.
+ <div style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '16px' }}>
+ {t('messages.allFeedsDeleted')}
</div>
<div style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>
<button
onClick={() => setShowAddForm(true)}
style={{
padding: '8px 16px',
- backgroundColor: FINCEPT.ORANGE,
- color: FINCEPT.DARK_BG,
+ backgroundColor: colors.primary,
+ color: colors.background,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
@@ -464,15 +448,15 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
gap: '4px',
}}
>
- <Plus size={12} /> ADD NEW FEED
+ <Plus size={12} /> {t('rssSettings.addNewFeed')}
</button>
<button
onClick={handleRestoreAllDefaults}
style={{
padding: '8px 16px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
+ border: `1px solid var(--ft-color-border, #2A2A2A)`,
+ color: colors.textMuted,
borderRadius: '2px',
cursor: 'pointer',
fontSize: '9px',
@@ -482,7 +466,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
gap: '4px',
}}
>
- <RefreshCw size={12} /> RESTORE DEFAULTS
+ <RefreshCw size={12} /> {t('rssSettings.restoreDefaults')}
</button>
</div>
</div>
@@ -496,9 +480,9 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
width: '100%',
padding: '10px',
backgroundColor: 'transparent',
- border: `1px dashed ${FINCEPT.BORDER}`,
+ border: `1px dashed var(--ft-color-border, #2A2A2A)`,
borderRadius: '2px',
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
@@ -511,7 +495,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
letterSpacing: '0.5px',
}}
>
- <Plus size={12} /> ADD NEW RSS FEED
+ <Plus size={12} /> {t('rssSettings.addNewRssFeed')}
</button>
)}
@@ -520,22 +504,22 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
<div
style={{
padding: '12px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.ORANGE}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px',
marginBottom: '12px',
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
- <span style={{ color: FINCEPT.ORANGE, fontWeight: 700, fontSize: '9px', letterSpacing: '0.5px' }}>
- {editingFeed ? 'EDIT RSS FEED' : 'ADD NEW RSS FEED'}
+ <span style={{ color: colors.primary, fontWeight: 700, fontSize: '9px', letterSpacing: '0.5px' }}>
+ {editingFeed ? t('rssSettings.editRssFeed') : t('rssSettings.addNewRssFeed')}
</span>
<button
onClick={resetForm}
style={{
background: 'none',
border: 'none',
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
cursor: 'pointer',
}}
>
@@ -547,8 +531,8 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
<div
style={{
padding: '6px 10px',
- backgroundColor: `${FINCEPT.RED}20`,
- color: FINCEPT.RED,
+ backgroundColor: `${colors.alert}20`,
+ color: colors.alert,
fontSize: '9px',
fontWeight: 700,
borderRadius: '2px',
@@ -565,46 +549,46 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
{/* Name */}
<div>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
- DISPLAY NAME *
+ <label style={{ color: colors.textMuted, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
+ {t('rssSettings.displayName')} {t('rssSettings.required')}
</label>
<input
type="text"
value={formData.name}
onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))}
- placeholder="e.g., Bloomberg Markets"
+ placeholder={t('rssSettings.placeholders.displayName')}
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid var(--ft-color-border, #2A2A2A)`,
borderRadius: '2px',
fontSize: '10px',
- fontFamily: FONT_FAMILY,
+ fontFamily,
}}
/>
</div>
{/* Source Name */}
<div>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
- SOURCE NAME (SHORT) *
+ <label style={{ color: colors.textMuted, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
+ {t('rssSettings.sourceName')} {t('rssSettings.required')}
</label>
<input
type="text"
value={formData.source_name}
onChange={e => setFormData(prev => ({ ...prev, source_name: e.target.value }))}
- placeholder="e.g., BLOOMBERG"
+ placeholder={t('rssSettings.placeholders.sourceName')}
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid var(--ft-color-border, #2A2A2A)`,
borderRadius: '2px',
fontSize: '10px',
- fontFamily: FONT_FAMILY,
+ fontFamily,
textTransform: 'uppercase',
}}
/>
@@ -612,8 +596,8 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{/* URL */}
<div style={{ gridColumn: '1 / -1' }}>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
- RSS FEED URL *
+ <label style={{ color: colors.textMuted, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
+ {t('rssSettings.feedUrl')} {t('rssSettings.required')}
</label>
<div style={{ display: 'flex', gap: '8px' }}>
<input
@@ -623,16 +607,16 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
setFormData(prev => ({ ...prev, url: e.target.value }));
setTestResult(null);
}}
- placeholder="https://example.com/rss/feed"
+ placeholder={t('rssSettings.placeholders.feedUrl')}
style={{
flex: 1,
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${testResult === true ? FINCEPT.GREEN : testResult === false ? FINCEPT.RED : FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${testResult === true ? colors.success : testResult === false ? colors.alert : 'var(--ft-color-border, #2A2A2A)'}`,
borderRadius: '2px',
fontSize: '10px',
- fontFamily: FONT_FAMILY,
+ fontFamily,
}}
/>
<button
@@ -640,8 +624,8 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
disabled={testing || !formData.url}
style={{
padding: '8px 16px',
- backgroundColor: testing ? FINCEPT.MUTED : FINCEPT.BLUE,
- color: FINCEPT.WHITE,
+ backgroundColor: testing ? colors.textMuted : 'var(--ft-color-blue, #0088FF)',
+ color: colors.text,
border: 'none',
borderRadius: '2px',
cursor: testing || !formData.url ? 'not-allowed' : 'pointer',
@@ -653,15 +637,15 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}}
>
{testing ? <RefreshCw size={12} className="animate-spin" /> : testResult === true ? <Check size={12} /> : <ExternalLink size={12} />}
- {testing ? 'TESTING...' : testResult === true ? 'VALID' : 'TEST URL'}
+ {testing ? t('rssSettings.testing') : testResult === true ? t('rssSettings.valid') : t('rssSettings.testUrl')}
</button>
</div>
</div>
{/* Category */}
<div>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
- CATEGORY
+ <label style={{ color: colors.textMuted, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
+ {t('rssSettings.category')}
</label>
<select
value={formData.category}
@@ -669,12 +653,12 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid var(--ft-color-border, #2A2A2A)`,
borderRadius: '2px',
fontSize: '10px',
- fontFamily: FONT_FAMILY,
+ fontFamily,
}}
>
{RSS_CATEGORIES.map(cat => (
@@ -687,8 +671,8 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{/* Region */}
<div>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
- REGION
+ <label style={{ color: colors.textMuted, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
+ {t('rssSettings.region')}
</label>
<select
value={formData.region}
@@ -696,12 +680,12 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
style={{
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid var(--ft-color-border, #2A2A2A)`,
borderRadius: '2px',
fontSize: '10px',
- fontFamily: FONT_FAMILY,
+ fontFamily,
}}
>
{RSS_REGIONS.map(reg => (
@@ -720,23 +704,23 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
style={{
padding: '6px 12px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
+ border: `1px solid var(--ft-color-border, #2A2A2A)`,
+ color: colors.textMuted,
borderRadius: '2px',
cursor: 'pointer',
fontSize: '9px',
fontWeight: 700,
}}
>
- CANCEL
+ {t('rssSettings.cancel')}
</button>
<button
onClick={editingFeed ? handleUpdateFeed : handleAddFeed}
disabled={submitting}
style={{
padding: '6px 12px',
- backgroundColor: submitting ? FINCEPT.MUTED : FINCEPT.ORANGE,
- color: submitting ? FINCEPT.GRAY : FINCEPT.DARK_BG,
+ backgroundColor: submitting ? colors.textMuted : colors.primary,
+ color: submitting ? colors.textMuted : colors.background,
border: 'none',
borderRadius: '2px',
cursor: submitting ? 'not-allowed' : 'pointer',
@@ -744,7 +728,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
fontWeight: 700,
}}
>
- {submitting ? 'SAVING...' : editingFeed ? 'UPDATE FEED' : 'ADD FEED'}
+ {submitting ? t('rssSettings.saving') : editingFeed ? t('rssSettings.updateFeed') : t('rssSettings.addFeed')}
</button>
</div>
</div>
@@ -759,13 +743,13 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
alignItems: 'center',
justifyContent: 'center',
height: '100%',
- color: FINCEPT.MUTED,
+ color: colors.textMuted,
fontSize: '10px',
textAlign: 'center',
padding: '40px',
}}
>
- <span>No custom feeds yet. Add your first RSS feed above.</span>
+ <span>{t('messages.noCustomFeeds')}</span>
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
@@ -774,8 +758,8 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
key={feed.id}
style={{
padding: '10px 12px',
- backgroundColor: feed.enabled ? FINCEPT.DARK_BG : `${FINCEPT.MUTED}10`,
- border: `1px solid ${feed.enabled ? FINCEPT.BORDER : FINCEPT.MUTED}`,
+ backgroundColor: feed.enabled ? colors.background : `${colors.textMuted}10`,
+ border: `1px solid ${feed.enabled ? 'var(--ft-color-border, #2A2A2A)' : colors.textMuted}`,
borderRadius: '2px',
opacity: feed.enabled ? 1 : 0.7,
transition: 'all 0.2s',
@@ -784,22 +768,22 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
<div style={{ flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' }}>
- <span style={{ color: FINCEPT.WHITE, fontWeight: 700, fontSize: '10px' }}>
+ <span style={{ color: colors.text, fontWeight: 700, fontSize: '10px' }}>
{feed.name}
</span>
- <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.CYAN}20`, color: FINCEPT.CYAN, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
+ <span style={{ padding: '2px 6px', backgroundColor: 'rgba(0, 229, 255, 0.15)', color: 'var(--ft-color-accent, #00E5FF)', fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{feed.source_name}
</span>
- <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.PURPLE}20`, color: FINCEPT.PURPLE, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
+ <span style={{ padding: '2px 6px', backgroundColor: 'rgba(157, 78, 221, 0.15)', color: 'var(--ft-color-purple, #9D4EDD)', fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{getCategoryLabel(feed.category)}
</span>
- <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.YELLOW}20`, color: FINCEPT.YELLOW, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
+ <span style={{ padding: '2px 6px', backgroundColor: 'rgba(255, 215, 0, 0.15)', color: 'var(--ft-color-warning, #FFD700)', fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{getRegionLabel(feed.region)}
</span>
</div>
<div
style={{
- color: FINCEPT.MUTED,
+ color: colors.textMuted,
fontSize: '9px',
overflow: 'hidden',
textOverflow: 'ellipsis',
@@ -815,8 +799,8 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
onClick={() => handleToggleFeed(feed.id, !feed.enabled)}
style={{
padding: '4px 8px',
- backgroundColor: feed.enabled ? FINCEPT.GREEN : FINCEPT.MUTED,
- color: feed.enabled ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ backgroundColor: feed.enabled ? colors.success : colors.textMuted,
+ color: feed.enabled ? colors.background : colors.textMuted,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
@@ -824,15 +808,15 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
fontWeight: 700,
}}
>
- {feed.enabled ? 'ON' : 'OFF'}
+ {feed.enabled ? t('rssSettings.on') : t('rssSettings.off')}
</button>
<button
onClick={() => handleEditFeed(feed)}
style={{
padding: '4px 8px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
+ border: `1px solid var(--ft-color-border, #2A2A2A)`,
+ color: colors.textMuted,
borderRadius: '2px',
cursor: 'pointer',
}}
@@ -843,8 +827,8 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
onClick={() => handleDeleteFeed(feed.id)}
style={{
padding: '4px 8px',
- backgroundColor: FINCEPT.RED,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.alert,
+ color: colors.text,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
@@ -865,11 +849,11 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
<div
style={{
padding: '8px 12px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid var(--ft-color-border, #2A2A2A)`,
borderRadius: '2px',
marginBottom: '12px',
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
fontSize: '9px',
display: 'flex',
justifyContent: 'space-between',
@@ -877,15 +861,15 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}}
>
<span>
- Default RSS feeds included with Fincept Terminal. Toggle or remove as needed.
+ {t('messages.defaultFeedsInfo')}
</span>
{deletedDefaultCount > 0 && (
<button
onClick={handleRestoreAllDefaults}
style={{
padding: '4px 10px',
- backgroundColor: FINCEPT.ORANGE,
- color: FINCEPT.DARK_BG,
+ backgroundColor: colors.primary,
+ color: colors.background,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
@@ -897,7 +881,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
whiteSpace: 'nowrap',
}}
>
- <RefreshCw size={10} /> RESTORE ALL ({deletedDefaultCount})
+ <RefreshCw size={10} /> {t('rssSettings.restoreAll')} ({deletedDefaultCount})
</button>
)}
</div>
@@ -908,25 +892,25 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
style={{
textAlign: 'center',
padding: '40px 20px',
- backgroundColor: FINCEPT.DARK_BG,
- border: `1px solid ${FINCEPT.YELLOW}`,
+ backgroundColor: colors.background,
+ border: `1px solid var(--ft-color-warning, #FFD700)`,
borderRadius: '2px',
marginBottom: '12px',
}}
>
- <AlertCircle size={24} style={{ color: FINCEPT.YELLOW, marginBottom: '12px' }} />
- <div style={{ color: FINCEPT.WHITE, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
- ALL DEFAULT FEEDS DELETED
+ <AlertCircle size={24} style={{ color: 'var(--ft-color-warning, #FFD700)', marginBottom: '12px' }} />
+ <div style={{ color: colors.text, fontSize: fontSize.tiny, fontWeight: 700, marginBottom: '8px' }}>
+ {t('rssSettings.allDefaultsDeleted')}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px', marginBottom: '16px' }}>
- You have deleted all {deletedDefaultCount} default feeds. Click below to restore them.
+ <div style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '16px' }}>
+ {t('messages.allDefaultFeedsDeleted', { count: deletedDefaultCount })}
</div>
<button
onClick={handleRestoreAllDefaults}
style={{
padding: '8px 16px',
- backgroundColor: FINCEPT.ORANGE,
- color: FINCEPT.DARK_BG,
+ backgroundColor: colors.primary,
+ color: colors.background,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
@@ -938,7 +922,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
margin: '0 auto',
}}
>
- <RefreshCw size={12} /> RESTORE ALL DEFAULT FEEDS
+ <RefreshCw size={12} /> {t('rssSettings.restoreAllDefaultFeeds')}
</button>
</div>
)}
@@ -949,8 +933,8 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
key={feed.id || feed.url}
style={{
padding: '10px 12px',
- backgroundColor: feed.enabled ? FINCEPT.DARK_BG : `${FINCEPT.MUTED}10`,
- border: `1px solid ${feed.enabled ? FINCEPT.BORDER : FINCEPT.MUTED}`,
+ backgroundColor: feed.enabled ? colors.background : `${colors.textMuted}10`,
+ border: `1px solid ${feed.enabled ? 'var(--ft-color-border, #2A2A2A)' : colors.textMuted}`,
borderRadius: '2px',
opacity: feed.enabled ? 1 : 0.7,
transition: 'all 0.2s',
@@ -959,25 +943,25 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
<div style={{ flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' }}>
- <span style={{ color: FINCEPT.WHITE, fontWeight: 700, fontSize: '10px' }}>
+ <span style={{ color: colors.text, fontWeight: 700, fontSize: '10px' }}>
{feed.name}
</span>
- <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.GREEN}20`, color: FINCEPT.GREEN, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
- DEFAULT
+ <span style={{ padding: '2px 6px', backgroundColor: `${colors.success}20`, color: colors.success, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
+ {t('rssSettings.default')}
</span>
- <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.CYAN}20`, color: FINCEPT.CYAN, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
+ <span style={{ padding: '2px 6px', backgroundColor: 'rgba(0, 229, 255, 0.15)', color: 'var(--ft-color-accent, #00E5FF)', fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{feed.source}
</span>
- <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.PURPLE}20`, color: FINCEPT.PURPLE, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
+ <span style={{ padding: '2px 6px', backgroundColor: 'rgba(157, 78, 221, 0.15)', color: 'var(--ft-color-purple, #9D4EDD)', fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{getCategoryLabel(feed.category)}
</span>
- <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.YELLOW}20`, color: FINCEPT.YELLOW, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
+ <span style={{ padding: '2px 6px', backgroundColor: 'rgba(255, 215, 0, 0.15)', color: 'var(--ft-color-warning, #FFD700)', fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{getRegionLabel(feed.region)}
</span>
</div>
<div
style={{
- color: FINCEPT.MUTED,
+ color: colors.textMuted,
fontSize: '9px',
overflow: 'hidden',
textOverflow: 'ellipsis',
@@ -993,8 +977,8 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
onClick={() => feed.id && handleToggleDefaultFeed(feed.id, !feed.enabled)}
style={{
padding: '4px 8px',
- backgroundColor: feed.enabled ? FINCEPT.GREEN : FINCEPT.MUTED,
- color: feed.enabled ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ backgroundColor: feed.enabled ? colors.success : colors.textMuted,
+ color: feed.enabled ? colors.background : colors.textMuted,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
@@ -1002,14 +986,14 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
fontWeight: 700,
}}
>
- {feed.enabled ? 'ON' : 'OFF'}
+ {feed.enabled ? t('rssSettings.on') : t('rssSettings.off')}
</button>
<button
onClick={() => feed.id && handleDeleteDefaultFeed(feed.id)}
style={{
padding: '4px 8px',
- backgroundColor: FINCEPT.RED,
- color: FINCEPT.WHITE,
+ backgroundColor: colors.alert,
+ color: colors.text,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
@@ -1029,30 +1013,30 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{/* Footer / Status Bar */}
<div
style={{
- borderTop: `1px solid ${FINCEPT.BORDER}`,
+ borderTop: `1px solid var(--ft-color-border, #2A2A2A)`,
padding: '6px 16px',
- backgroundColor: FINCEPT.HEADER_BG,
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
fontSize: '9px',
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
}}
>
<span>
- TOTAL: <span style={{ color: FINCEPT.CYAN }}>{defaultFeeds.length + userFeeds.filter(f => f.enabled).length}</span> ACTIVE
- <span style={{ color: FINCEPT.BORDER }}> | </span>
- <span style={{ color: FINCEPT.CYAN }}>{defaultFeeds.length}</span> DEFAULT
- <span style={{ color: FINCEPT.BORDER }}> | </span>
- <span style={{ color: FINCEPT.CYAN }}>{userFeeds.filter(f => f.enabled).length}</span> CUSTOM
+ {t('rssSettings.total')}: <span style={{ color: 'var(--ft-color-accent, #00E5FF)' }}>{defaultFeeds.length + userFeeds.filter(f => f.enabled).length}</span> {t('rssSettings.active')}
+ <span style={{ color: 'var(--ft-color-border, #2A2A2A)' }}> | </span>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)' }}>{defaultFeeds.length}</span> {t('rssSettings.default')}
+ <span style={{ color: 'var(--ft-color-border, #2A2A2A)' }}> | </span>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)' }}>{userFeeds.filter(f => f.enabled).length}</span> {t('rssSettings.custom')}
</span>
<button
onClick={loadFeeds}
style={{
padding: '4px 10px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
+ border: `1px solid var(--ft-color-border, #2A2A2A)`,
+ color: colors.textMuted,
borderRadius: '2px',
cursor: 'pointer',
fontSize: '9px',
@@ -1062,7 +1046,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
gap: '4px',
}}
>
- <RefreshCw size={10} /> REFRESH
+ <RefreshCw size={10} /> {t('header.refresh')}
</button>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodeConfigPanel.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodeConfigPanel.tsx
index 829eef61e..5d322116b 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodeConfigPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodeConfigPanel.tsx
@@ -4,7 +4,7 @@
* Right sidebar panel for configuring selected node properties
*/
-import React from 'react';
+import React, { useState, useEffect } from 'react';
import { Node } from 'reactflow';
import {
Settings2,
@@ -13,9 +13,18 @@ import {
Plus,
Edit3,
AlertCircle,
+ Database,
+ TrendingUp,
+ Brain,
+ Wrench,
+ Play,
+ BarChart3,
+ Zap,
+ Info,
} from 'lucide-react';
import { NodeParameterInput } from '../nodes/NodeParameterInput';
import type { INodeProperties, NodeParameterValue } from '@/services/nodeSystem';
+import { useDataSources } from '@/contexts/DataSourceContext';
interface NodeConfigPanelProps {
selectedNode: Node;
@@ -26,6 +35,21 @@ interface NodeConfigPanelProps {
onDuplicate: () => void;
}
+// Design system colors
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ CYAN: '#00E5FF',
+ BLUE: '#0088FF',
+};
+
const NodeConfigPanel: React.FC<NodeConfigPanelProps> = ({
selectedNode,
onLabelChange,
@@ -38,6 +62,48 @@ const NodeConfigPanel: React.FC<NodeConfigPanelProps> = ({
const nodeProperties: INodeProperties[] = registryData?.properties || [];
const nodeColor = selectedNode.data.color || '#FF8800';
+ // Data source context for data-source nodes
+ const { connections } = useDataSources();
+
+ // Local state for custom node configs
+ const [localConnection, setLocalConnection] = useState(selectedNode.data.selectedConnectionId || '');
+ const [localQuery, setLocalQuery] = useState(selectedNode.data.query || '');
+
+ // Technical indicator state
+ const [tiDataSource, setTiDataSource] = useState(selectedNode.data.dataSource || 'yfinance');
+ const [tiSymbol, setTiSymbol] = useState(selectedNode.data.symbol || 'AAPL');
+ const [tiPeriod, setTiPeriod] = useState(selectedNode.data.period || '1y');
+ const [tiCategories, setTiCategories] = useState<string[]>(selectedNode.data.categories || ['momentum', 'volume', 'volatility', 'trend', 'others']);
+
+ // Agent mediator state
+ const [amProvider, setAmProvider] = useState(selectedNode.data.selectedProvider || '');
+ const [amPrompt, setAmPrompt] = useState(selectedNode.data.customPrompt || '');
+
+ // Sync local state when node changes
+ useEffect(() => {
+ setLocalConnection(selectedNode.data.selectedConnectionId || '');
+ setLocalQuery(selectedNode.data.query || '');
+ setTiDataSource(selectedNode.data.dataSource || 'yfinance');
+ setTiSymbol(selectedNode.data.symbol || 'AAPL');
+ setTiPeriod(selectedNode.data.period || '1y');
+ setTiCategories(selectedNode.data.categories || ['momentum', 'volume', 'volatility', 'trend', 'others']);
+ setAmProvider(selectedNode.data.selectedProvider || '');
+ setAmPrompt(selectedNode.data.customPrompt || '');
+ }, [selectedNode.id]);
+
+ // Check if this is a custom node type that needs special handling
+ const isDataSourceNode = selectedNode.type === 'data-source';
+ const isTechnicalIndicatorNode = selectedNode.type === 'technical-indicator';
+ const isAgentMediatorNode = selectedNode.type === 'agent-mediator';
+ const isPythonAgentNode = selectedNode.type === 'python-agent';
+ const isMCPToolNode = selectedNode.type === 'mcp-tool';
+ const isBacktestNode = selectedNode.type === 'backtest';
+ const isOptimizationNode = selectedNode.type === 'optimization';
+ const isResultsDisplayNode = selectedNode.type === 'results-display';
+
+ const hasCustomConfig = isDataSourceNode || isTechnicalIndicatorNode || isAgentMediatorNode ||
+ isPythonAgentNode || isMCPToolNode || isBacktestNode || isOptimizationNode;
+
return (
<div
style={{
@@ -206,6 +272,753 @@ const NodeConfigPanel: React.FC<NodeConfigPanelProps> = ({
</div>
</div>
+ {/* ==================== DATA SOURCE NODE CONFIG ==================== */}
+ {isDataSourceNode && (
+ <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <Database size={14} color={FINCEPT.ORANGE} />
+ <span style={{
+ color: FINCEPT.ORANGE,
+ fontSize: '11px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ DATA SOURCE CONFIG
+ </span>
+ </div>
+
+ {/* Connection Selector */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ }}>
+ CONNECTION
+ </label>
+ <select
+ value={localConnection}
+ onChange={(e) => {
+ setLocalConnection(e.target.value);
+ selectedNode.data.onConnectionChange?.(e.target.value);
+ }}
+ style={{
+ width: '100%',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}
+ >
+ <option value="">-- Select Connection --</option>
+ {connections.filter(c => c.status === 'connected' || c.status === 'disconnected').map((conn) => (
+ <option key={conn.id} value={conn.id}>
+ {conn.name} ({conn.type})
+ </option>
+ ))}
+ </select>
+ {connections.length === 0 && (
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '4px' }}>
+ No connections. Add them in Data Sources tab.
+ </div>
+ )}
+ </div>
+
+ {/* Query Editor */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ }}>
+ QUERY
+ </label>
+ <textarea
+ value={localQuery}
+ onChange={(e) => {
+ setLocalQuery(e.target.value);
+ selectedNode.data.onQueryChange?.(e.target.value);
+ }}
+ placeholder="SELECT * FROM table..."
+ style={{
+ width: '100%',
+ height: '100px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ resize: 'vertical',
+ boxSizing: 'border-box',
+ }}
+ />
+ </div>
+
+ {/* Execute Button */}
+ <button
+ onClick={() => selectedNode.data.onExecute?.()}
+ disabled={!localConnection || !localQuery}
+ style={{
+ width: '100%',
+ backgroundColor: (!localConnection || !localQuery) ? FINCEPT.BORDER : FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ padding: '8px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: (!localConnection || !localQuery) ? 'not-allowed' : 'pointer',
+ opacity: (!localConnection || !localQuery) ? 0.5 : 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ }}
+ >
+ <Play size={10} />
+ EXECUTE QUERY
+ </button>
+ </div>
+ )}
+
+ {/* ==================== TECHNICAL INDICATOR NODE CONFIG ==================== */}
+ {isTechnicalIndicatorNode && (
+ <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <TrendingUp size={14} color={FINCEPT.CYAN} />
+ <span style={{
+ color: FINCEPT.CYAN,
+ fontSize: '11px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ TECHNICAL INDICATOR CONFIG
+ </span>
+ </div>
+
+ {/* Data Source */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ }}>
+ DATA SOURCE
+ </label>
+ <select
+ value={tiDataSource}
+ onChange={(e) => {
+ setTiDataSource(e.target.value);
+ selectedNode.data.onParameterChange?.({ dataSource: e.target.value });
+ }}
+ style={{
+ width: '100%',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}
+ >
+ <option value="yfinance">Yahoo Finance</option>
+ <option value="csv">CSV File</option>
+ <option value="json">JSON Data</option>
+ </select>
+ </div>
+
+ {/* Symbol */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ }}>
+ SYMBOL
+ </label>
+ <input
+ type="text"
+ value={tiSymbol}
+ onChange={(e) => {
+ setTiSymbol(e.target.value);
+ selectedNode.data.onParameterChange?.({ symbol: e.target.value });
+ }}
+ placeholder="AAPL, MSFT, BTC-USD..."
+ style={{
+ width: '100%',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ boxSizing: 'border-box',
+ }}
+ />
+ </div>
+
+ {/* Period */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ }}>
+ PERIOD
+ </label>
+ <select
+ value={tiPeriod}
+ onChange={(e) => {
+ setTiPeriod(e.target.value);
+ selectedNode.data.onParameterChange?.({ period: e.target.value });
+ }}
+ style={{
+ width: '100%',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}
+ >
+ <option value="1d">1 Day</option>
+ <option value="5d">5 Days</option>
+ <option value="1mo">1 Month</option>
+ <option value="3mo">3 Months</option>
+ <option value="6mo">6 Months</option>
+ <option value="1y">1 Year</option>
+ <option value="2y">2 Years</option>
+ <option value="5y">5 Years</option>
+ </select>
+ </div>
+
+ {/* Indicator Categories */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ }}>
+ INDICATOR CATEGORIES
+ </label>
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
+ {['momentum', 'volume', 'volatility', 'trend', 'others'].map((cat) => (
+ <button
+ key={cat}
+ onClick={() => {
+ const newCats = tiCategories.includes(cat)
+ ? tiCategories.filter(c => c !== cat)
+ : [...tiCategories, cat];
+ setTiCategories(newCats);
+ selectedNode.data.onParameterChange?.({ categories: newCats });
+ }}
+ style={{
+ padding: '4px 8px',
+ fontSize: '9px',
+ fontWeight: 600,
+ backgroundColor: tiCategories.includes(cat) ? FINCEPT.CYAN + '30' : FINCEPT.DARK_BG,
+ border: `1px solid ${tiCategories.includes(cat) ? FINCEPT.CYAN : FINCEPT.BORDER}`,
+ color: tiCategories.includes(cat) ? FINCEPT.CYAN : FINCEPT.GRAY,
+ cursor: 'pointer',
+ textTransform: 'uppercase',
+ }}
+ >
+ {cat}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Execute Button */}
+ <button
+ onClick={() => selectedNode.data.onExecute?.()}
+ style={{
+ width: '100%',
+ backgroundColor: FINCEPT.CYAN,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ padding: '8px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ }}
+ >
+ <Play size={10} />
+ CALCULATE INDICATORS
+ </button>
+ </div>
+ )}
+
+ {/* ==================== AGENT MEDIATOR NODE CONFIG ==================== */}
+ {isAgentMediatorNode && (
+ <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <Brain size={14} color="#a855f7" />
+ <span style={{
+ color: '#a855f7',
+ fontSize: '11px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ AI MEDIATOR CONFIG
+ </span>
+ </div>
+
+ {/* LLM Provider */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ }}>
+ LLM PROVIDER
+ </label>
+ <select
+ value={amProvider}
+ onChange={(e) => {
+ setAmProvider(e.target.value);
+ selectedNode.data.onConfigChange?.({ selectedProvider: e.target.value, customPrompt: amPrompt });
+ }}
+ style={{
+ width: '100%',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}
+ >
+ <option value="">-- Select Provider --</option>
+ <option value="ollama">Ollama (Local)</option>
+ <option value="openai">OpenAI</option>
+ <option value="anthropic">Anthropic</option>
+ <option value="groq">Groq</option>
+ </select>
+ </div>
+
+ {/* Custom Prompt */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ }}>
+ CUSTOM PROMPT
+ </label>
+ <textarea
+ value={amPrompt}
+ onChange={(e) => {
+ setAmPrompt(e.target.value);
+ selectedNode.data.onConfigChange?.({ selectedProvider: amProvider, customPrompt: e.target.value });
+ }}
+ placeholder="Enter instructions for the AI agent..."
+ style={{
+ width: '100%',
+ height: '100px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ resize: 'vertical',
+ boxSizing: 'border-box',
+ }}
+ />
+ </div>
+
+ {/* Execute Button */}
+ <button
+ onClick={() => selectedNode.data.onExecute?.()}
+ disabled={!amProvider}
+ style={{
+ width: '100%',
+ backgroundColor: !amProvider ? FINCEPT.BORDER : '#a855f7',
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ padding: '8px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: !amProvider ? 'not-allowed' : 'pointer',
+ opacity: !amProvider ? 0.5 : 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ }}
+ >
+ <Play size={10} />
+ RUN AI MEDIATOR
+ </button>
+ </div>
+ )}
+
+ {/* ==================== PYTHON AGENT NODE CONFIG ==================== */}
+ {isPythonAgentNode && (
+ <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <span style={{ fontSize: '14px' }}>🐍</span>
+ <span style={{
+ color: '#fbbf24',
+ fontSize: '11px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ PYTHON AGENT CONFIG
+ </span>
+ </div>
+
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px', marginBottom: '12px' }}>
+ <strong style={{ color: FINCEPT.WHITE }}>Agent:</strong> {selectedNode.data.agentType || 'Unknown'}
+ </div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px', marginBottom: '12px' }}>
+ <strong style={{ color: FINCEPT.WHITE }}>Category:</strong> {selectedNode.data.agentCategory || 'Unknown'}
+ </div>
+
+ {/* LLM Selection */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ }}>
+ LLM PROVIDER
+ </label>
+ <select
+ value={selectedNode.data.selectedLLM || 'active'}
+ onChange={(e) => selectedNode.data.onLLMChange?.(e.target.value)}
+ style={{
+ width: '100%',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}
+ >
+ <option value="active">Active LLM</option>
+ <option value="ollama">Ollama</option>
+ <option value="openai">OpenAI</option>
+ <option value="anthropic">Anthropic</option>
+ </select>
+ </div>
+
+ {/* Execute Button */}
+ <button
+ onClick={() => selectedNode.data.onExecute?.(selectedNode.id)}
+ disabled={selectedNode.data.status === 'running'}
+ style={{
+ width: '100%',
+ backgroundColor: selectedNode.data.status === 'running' ? FINCEPT.BORDER : '#fbbf24',
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ padding: '8px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: selectedNode.data.status === 'running' ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ }}
+ >
+ <Play size={10} />
+ {selectedNode.data.status === 'running' ? 'RUNNING...' : 'RUN AGENT'}
+ </button>
+ </div>
+ )}
+
+ {/* ==================== MCP TOOL NODE CONFIG ==================== */}
+ {isMCPToolNode && (
+ <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <Wrench size={14} color={FINCEPT.ORANGE} />
+ <span style={{
+ color: FINCEPT.ORANGE,
+ fontSize: '11px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ MCP TOOL CONFIG
+ </span>
+ </div>
+
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px', marginBottom: '8px' }}>
+ <strong style={{ color: FINCEPT.WHITE }}>Server:</strong> {selectedNode.data.serverId || 'Unknown'}
+ </div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px', marginBottom: '12px' }}>
+ <strong style={{ color: FINCEPT.WHITE }}>Tool:</strong> {selectedNode.data.toolName || 'Unknown'}
+ </div>
+
+ {/* Dynamic parameters would go here based on tool schema */}
+ <div style={{
+ padding: '8px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ marginBottom: '12px',
+ }}>
+ Configure tool parameters in the node directly
+ </div>
+
+ {/* Execute Button */}
+ <button
+ onClick={() => selectedNode.data.onExecute?.()}
+ style={{
+ width: '100%',
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ padding: '8px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ }}
+ >
+ <Play size={10} />
+ EXECUTE TOOL
+ </button>
+ </div>
+ )}
+
+ {/* ==================== BACKTEST NODE CONFIG ==================== */}
+ {isBacktestNode && (
+ <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <BarChart3 size={14} color={FINCEPT.GREEN} />
+ <span style={{
+ color: FINCEPT.GREEN,
+ fontSize: '11px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ BACKTEST CONFIG
+ </span>
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ fontSize: '10px',
+ textAlign: 'center',
+ }}>
+ Backtest configuration coming soon.<br/>
+ Connect data source and strategy nodes.
+ </div>
+ </div>
+ )}
+
+ {/* ==================== OPTIMIZATION NODE CONFIG ==================== */}
+ {isOptimizationNode && (
+ <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <Zap size={14} color="#f97316" />
+ <span style={{
+ color: '#f97316',
+ fontSize: '11px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ OPTIMIZATION CONFIG
+ </span>
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ fontSize: '10px',
+ textAlign: 'center',
+ }}>
+ Optimization configuration coming soon.<br/>
+ Connect backtest node for parameter optimization.
+ </div>
+ </div>
+ )}
+
+ {/* ==================== CUSTOM/REGISTRY NODE (no registryData) ==================== */}
+ {selectedNode.type === 'custom' && !registryData && (
+ <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <Settings2 size={14} color={FINCEPT.ORANGE} />
+ <span style={{
+ color: FINCEPT.ORANGE,
+ fontSize: '11px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ NODE CONFIG
+ </span>
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ fontSize: '10px',
+ textAlign: 'center',
+ }}>
+ {selectedNode.data.nodeTypeName ? (
+ <>
+ <div style={{ marginBottom: '8px', color: FINCEPT.WHITE }}>
+ <strong>Type:</strong> {selectedNode.data.nodeTypeName}
+ </div>
+ <div style={{ fontSize: '9px' }}>
+ This node's configuration will be available when executed in a workflow.
+ </div>
+ </>
+ ) : (
+ <div>Configure this node's connections and parameters.</div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* ==================== RESULTS DISPLAY NODE ==================== */}
+ {isResultsDisplayNode && (
+ <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <span style={{ fontSize: '14px' }}>📊</span>
+ <span style={{
+ color: FINCEPT.GREEN,
+ fontSize: '11px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ RESULTS DISPLAY
+ </span>
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ fontSize: '10px',
+ }}>
+ This node displays output from connected nodes.<br/>
+ Connect input from any data-producing node.
+ </div>
+ </div>
+ )}
+
{/* Registry Node Parameters */}
{nodeProperties.length > 0 && (
<div
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx
index 8066d8f4b..0c796e105 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx
@@ -5,6 +5,8 @@
import React, { useState, useEffect, useCallback } from 'react';
import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import {
Briefcase, TrendingUp, TrendingDown, DollarSign, BarChart3,
RefreshCw, Plus, Download, Trash2, PieChart, Activity,
@@ -31,12 +33,13 @@ import ConfirmDeleteModal from './modals/ConfirmDeleteModal';
import { usePortfolioOperations } from './hooks/usePortfolioOperations';
import { formatCurrency, formatPercent } from './portfolio/utils';
import { TabFooter } from '@/components/common/TabFooter';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS, COMMON_STYLES, LAYOUT } from './finceptStyles';
import { showError } from '@/utils/notifications';
type SubTab = 'positions' | 'history' | 'analytics' | 'sectors' | 'performance' | 'risk' | 'reports' | 'alerts' | 'active-mgmt' | 'optimization' | 'indices' | 'quantstats';
const PortfolioTab: React.FC = () => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
const [activeSubTab, setActiveSubTab] = useState<SubTab>('positions');
@@ -171,48 +174,59 @@ const PortfolioTab: React.FC = () => {
// Sub-tab configurations
const subTabs = [
- { id: 'positions' as SubTab, label: 'POSITIONS', icon: Briefcase },
- { id: 'history' as SubTab, label: 'HISTORY', icon: Clock },
- { id: 'indices' as SubTab, label: 'INDICES', icon: Layers },
- { id: 'analytics' as SubTab, label: 'ANALYTICS', icon: BarChart3 },
- { id: 'sectors' as SubTab, label: 'SECTORS', icon: PieChart },
- { id: 'performance' as SubTab, label: 'PERFORMANCE', icon: TrendingUp },
- { id: 'risk' as SubTab, label: 'RISK', icon: AlertCircle },
- { id: 'optimization' as SubTab, label: 'OPTIMIZATION', icon: Target },
- { id: 'active-mgmt' as SubTab, label: 'ACTIVE MGMT', icon: Activity },
- { id: 'quantstats' as SubTab, label: 'QUANTSTATS', icon: Activity },
- { id: 'reports' as SubTab, label: 'REPORTS', icon: BarChart3 },
- { id: 'alerts' as SubTab, label: 'ALERTS', icon: AlertCircle }
+ { id: 'positions' as SubTab, label: t('views.positions'), icon: Briefcase },
+ { id: 'history' as SubTab, label: t('views.history'), icon: Clock },
+ { id: 'indices' as SubTab, label: t('views.indices', 'INDICES'), icon: Layers },
+ { id: 'analytics' as SubTab, label: t('views.analytics'), icon: BarChart3 },
+ { id: 'sectors' as SubTab, label: t('views.sectors'), icon: PieChart },
+ { id: 'performance' as SubTab, label: t('views.performance'), icon: TrendingUp },
+ { id: 'risk' as SubTab, label: t('views.risk', 'RISK'), icon: AlertCircle },
+ { id: 'optimization' as SubTab, label: t('views.optimization', 'OPTIMIZATION'), icon: Target },
+ { id: 'active-mgmt' as SubTab, label: t('views.activeMgmt'), icon: Activity },
+ { id: 'quantstats' as SubTab, label: t('views.quantstats', 'QUANTSTATS'), icon: Activity },
+ { id: 'reports' as SubTab, label: t('views.reports'), icon: BarChart3 },
+ { id: 'alerts' as SubTab, label: t('views.alerts'), icon: AlertCircle }
];
return (
<div style={{
- ...COMMON_STYLES.container,
+ height: '100%',
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontFamily,
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column',
}}>
{/* Top Navigation Bar */}
<div style={{
- ...COMMON_STYLES.header,
- height: 'auto',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: `2px solid ${colors.primary}`,
padding: '6px 16px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ flexShrink: 0,
+ boxShadow: `0 2px 8px ${colors.primary}20`,
gap: '8px',
flexWrap: 'nowrap',
}}>
{/* Title */}
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexShrink: 0 }}>
- <Briefcase size={14} color={FINCEPT.ORANGE} style={{ filter: EFFECTS.ICON_GLOW_ORANGE }} />
+ <Briefcase size={14} color={colors.primary} style={{ filter: `drop-shadow(0 0 4px ${colors.primary})` }} />
<span style={{
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.BOLD,
- color: FINCEPT.ORANGE,
- letterSpacing: TYPOGRAPHY.WIDE,
- textShadow: EFFECTS.ORANGE_GLOW,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ color: colors.primary,
+ letterSpacing: '0.5px',
+ textShadow: `0 0 10px ${colors.primary}40`,
textTransform: 'uppercase' as const,
}}>
- PORTFOLIO
+ {t('views.positions', 'PORTFOLIO')}
</span>
</div>
- <div style={{ ...COMMON_STYLES.verticalDivider, height: '16px' }} />
+ <div style={{ width: '1px', backgroundColor: 'var(--ft-color-border, #2A2A2A)', alignSelf: 'stretch', height: '16px' }} />
{/* Sub-tab Navigation */}
<div id="portfolio-subtabs" style={{ display: 'flex', gap: '2px', flex: 1, overflowX: 'auto', overflowY: 'hidden' }}>
@@ -225,27 +239,35 @@ const PortfolioTab: React.FC = () => {
onClick={() => setActiveSubTab(tab.id)}
disabled={!selectedPortfolio}
style={{
- ...COMMON_STYLES.tabButton(isActive),
+ padding: '6px 12px',
+ backgroundColor: isActive ? colors.primary : 'transparent',
+ color: isActive ? colors.background : colors.textMuted,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ cursor: selectedPortfolio ? 'pointer' : 'not-allowed',
+ transition: 'all 0.15s ease',
+ textTransform: 'uppercase' as const,
display: 'flex',
alignItems: 'center',
gap: '3px',
- padding: '4px 8px',
- fontFamily: TYPOGRAPHY.MONO,
- cursor: selectedPortfolio ? 'pointer' : 'not-allowed',
+ fontFamily,
opacity: selectedPortfolio ? 1 : 0.5,
whiteSpace: 'nowrap',
flexShrink: 0,
}}
onMouseEnter={(e) => {
if (!isActive && selectedPortfolio) {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- e.currentTarget.style.color = FINCEPT.WHITE;
+ e.currentTarget.style.backgroundColor = 'var(--ft-color-hover, #1F1F1F)';
+ e.currentTarget.style.color = colors.text;
}
}}
onMouseLeave={(e) => {
if (!isActive) {
e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = selectedPortfolio ? FINCEPT.GRAY : FINCEPT.MUTED;
+ e.currentTarget.style.color = selectedPortfolio ? colors.textMuted : '#4A4A4A';
}
}}
>
@@ -256,7 +278,7 @@ const PortfolioTab: React.FC = () => {
})}
</div>
- <div style={{ ...COMMON_STYLES.verticalDivider, height: '16px' }} />
+ <div style={{ width: '1px', backgroundColor: 'var(--ft-color-border, #2A2A2A)', alignSelf: 'stretch', height: '16px' }} />
{/* Actions */}
<div style={{ display: 'flex', alignItems: 'center', gap: '4px', flexShrink: 0 }}>
@@ -268,22 +290,22 @@ const PortfolioTab: React.FC = () => {
style={{
padding: '3px 8px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.GREEN}`,
+ border: `1px solid ${colors.success}`,
borderRadius: '2px',
- color: FINCEPT.GREEN,
- fontSize: TYPOGRAPHY.TINY,
- fontWeight: TYPOGRAPHY.BOLD,
- fontFamily: TYPOGRAPHY.MONO,
- letterSpacing: TYPOGRAPHY.WIDE,
+ color: colors.success,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ fontFamily,
+ letterSpacing: '0.5px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '3px',
- transition: EFFECTS.TRANSITION_FAST,
+ transition: 'all 0.15s ease',
}}
>
<ArrowUpRight size={9} />
- BUY
+ {t('actions.buy', 'BUY')}
</button>
<button
@@ -292,22 +314,22 @@ const PortfolioTab: React.FC = () => {
style={{
padding: '3px 8px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.RED}`,
+ border: `1px solid ${colors.alert}`,
borderRadius: '2px',
- color: FINCEPT.RED,
- fontSize: TYPOGRAPHY.TINY,
- fontWeight: TYPOGRAPHY.BOLD,
- fontFamily: TYPOGRAPHY.MONO,
- letterSpacing: TYPOGRAPHY.WIDE,
+ color: colors.alert,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ fontFamily,
+ letterSpacing: '0.5px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '3px',
- transition: EFFECTS.TRANSITION_FAST,
+ transition: 'all 0.15s ease',
}}
>
<ArrowDownRight size={9} />
- SELL
+ {t('actions.sell', 'SELL')}
</button>
<button
@@ -317,14 +339,14 @@ const PortfolioTab: React.FC = () => {
style={{
padding: '3px 6px',
backgroundColor: 'transparent',
- border: BORDERS.STANDARD,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
- color: refreshing ? FINCEPT.MUTED : FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.TINY,
+ color: refreshing ? '#4A4A4A' : 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
cursor: refreshing ? 'wait' : 'pointer',
display: 'flex',
alignItems: 'center',
- transition: EFFECTS.TRANSITION_FAST,
+ transition: 'all 0.15s ease',
}}
>
<RefreshCw size={9} className={refreshing ? 'animate-spin' : ''} />
@@ -336,15 +358,15 @@ const PortfolioTab: React.FC = () => {
style={{
padding: '3px 6px',
backgroundColor: 'transparent',
- border: BORDERS.STANDARD,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
- color: FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.TINY,
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '3px',
- transition: EFFECTS.TRANSITION_FAST,
+ transition: 'all 0.15s ease',
}}
>
<Download size={9} />
@@ -360,22 +382,22 @@ const PortfolioTab: React.FC = () => {
style={{
padding: '3px 6px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BLUE}`,
+ border: `1px solid var(--ft-color-info, #0088FF)`,
borderRadius: '2px',
- color: FINCEPT.BLUE,
- fontSize: TYPOGRAPHY.TINY,
- fontWeight: TYPOGRAPHY.BOLD,
- fontFamily: TYPOGRAPHY.MONO,
+ color: 'var(--ft-color-info, #0088FF)',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ fontFamily,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '2px',
- transition: EFFECTS.TRANSITION_FAST,
+ transition: 'all 0.15s ease',
}}
- title="Start portfolio tour"
+ title={t('views.help')}
>
<Info size={9} />
- HELP
+ {t('views.help')}
</button>
</div>
</div>
@@ -386,44 +408,44 @@ const PortfolioTab: React.FC = () => {
<div style={{
width: '280px',
flexShrink: 0,
- backgroundColor: FINCEPT.PANEL_BG,
- borderRight: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.panel,
+ borderRight: `1px solid var(--ft-color-border, #2A2A2A)`,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
}}>
{/* Left Panel Header */}
<div style={{
- padding: SPACING.DEFAULT,
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: `1px solid var(--ft-color-border, #2A2A2A)`,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}>
- <span style={{ ...COMMON_STYLES.dataLabel }}>PORTFOLIOS</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('sidebar.portfolios')}</span>
<button
id="portfolio-create"
onClick={() => setShowCreatePortfolio(true)}
style={{
padding: '2px 8px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.ORANGE}`,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px',
- color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.TINY,
- fontWeight: TYPOGRAPHY.BOLD,
- fontFamily: TYPOGRAPHY.MONO,
- letterSpacing: TYPOGRAPHY.WIDE,
+ color: colors.primary,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ fontFamily,
+ letterSpacing: '0.5px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '3px',
- transition: EFFECTS.TRANSITION_FAST,
+ transition: 'all 0.15s ease',
}}
>
<Plus size={9} />
- NEW
+ {t('actions.new', 'NEW')}
</button>
</div>
@@ -431,14 +453,20 @@ const PortfolioTab: React.FC = () => {
<div style={{ flex: 1, overflow: 'auto' }}>
{portfolios.length === 0 ? (
<div style={{
- ...COMMON_STYLES.emptyState,
- padding: SPACING.XLARGE,
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: '24px',
height: 'auto',
+ color: '#4A4A4A',
+ fontSize: fontSize.small,
+ textAlign: 'center',
}}>
<Briefcase size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />
- <span>No portfolios yet</span>
- <span style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY, marginTop: '4px' }}>
- Click NEW to create one
+ <span>{t('sidebar.noPortfolios')}</span>
+ <span style={{ fontSize: fontSize.tiny, color: colors.textMuted, marginTop: '4px' }}>
+ {t('sidebar.clickCreate')}
</span>
</div>
) : (
@@ -450,14 +478,14 @@ const PortfolioTab: React.FC = () => {
onClick={() => setSelectedPortfolio(portfolio)}
style={{
padding: '10px 12px',
- backgroundColor: isSelected ? `${FINCEPT.ORANGE}15` : 'transparent',
- borderLeft: isSelected ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
+ backgroundColor: isSelected ? `${colors.primary}15` : 'transparent',
+ borderLeft: isSelected ? `2px solid ${colors.primary}` : '2px solid transparent',
cursor: 'pointer',
- transition: EFFECTS.TRANSITION_STANDARD,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ transition: 'all 0.2s ease',
+ borderBottom: `1px solid var(--ft-color-border, #2A2A2A)`,
}}
onMouseEnter={(e) => {
- if (!isSelected) e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ if (!isSelected) e.currentTarget.style.backgroundColor = 'var(--ft-color-hover, #1F1F1F)';
}}
onMouseLeave={(e) => {
if (!isSelected) e.currentTarget.style.backgroundColor = 'transparent';
@@ -465,10 +493,10 @@ const PortfolioTab: React.FC = () => {
>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '4px' }}>
<span style={{
- color: isSelected ? FINCEPT.ORANGE : FINCEPT.WHITE,
- fontSize: TYPOGRAPHY.SMALL,
- fontWeight: TYPOGRAPHY.BOLD,
- fontFamily: TYPOGRAPHY.MONO,
+ color: isSelected ? colors.primary : colors.text,
+ fontSize: fontSize.small,
+ fontWeight: 700,
+ fontFamily,
}}>
{portfolio.name}
</span>
@@ -480,24 +508,24 @@ const PortfolioTab: React.FC = () => {
style={{
background: 'none',
border: 'none',
- color: FINCEPT.MUTED,
+ color: '#4A4A4A',
cursor: 'pointer',
padding: '2px',
display: 'flex',
- transition: EFFECTS.TRANSITION_FAST,
+ transition: 'all 0.15s ease',
}}
- onMouseEnter={(e) => { e.currentTarget.style.color = FINCEPT.RED; }}
- onMouseLeave={(e) => { e.currentTarget.style.color = FINCEPT.MUTED; }}
+ onMouseEnter={(e) => { e.currentTarget.style.color = colors.alert; }}
+ onMouseLeave={(e) => { e.currentTarget.style.color = '#4A4A4A'; }}
>
<Trash2 size={10} />
</button>
</div>
<div style={{ display: 'flex', gap: '8px' }}>
- <span style={{ ...COMMON_STYLES.dataLabel, fontSize: '8px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '8px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>
{portfolio.currency}
</span>
{portfolio.owner && (
- <span style={{ ...COMMON_STYLES.dataLabel, fontSize: '8px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '8px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>
{portfolio.owner}
</span>
)}
@@ -513,40 +541,54 @@ const PortfolioTab: React.FC = () => {
<div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
{!selectedPortfolio ? (
<div style={{
- ...COMMON_STYLES.emptyState,
- gap: SPACING.LARGE,
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ color: '#4A4A4A',
+ fontSize: fontSize.small,
+ textAlign: 'center',
+ gap: '16px',
}}>
- <Briefcase size={48} color={FINCEPT.MUTED} style={{ opacity: 0.2 }} />
+ <Briefcase size={48} color="#4A4A4A" style={{ opacity: 0.2 }} />
<div style={{
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.SUBHEADING,
- fontWeight: TYPOGRAPHY.BOLD,
+ color: colors.textMuted,
+ fontSize: fontSize.subheading,
+ fontWeight: 700,
letterSpacing: '1px',
- fontFamily: TYPOGRAPHY.MONO,
+ fontFamily,
textTransform: 'uppercase' as const,
}}>
- NO PORTFOLIO SELECTED
+ {t('extracted.noPortfolioSelected')}
</div>
<div style={{
- color: FINCEPT.MUTED,
- fontSize: TYPOGRAPHY.SMALL,
- fontFamily: TYPOGRAPHY.MONO,
+ color: '#4A4A4A',
+ fontSize: fontSize.small,
+ fontFamily,
}}>
- {portfolios.length === 0 ? 'Create a new portfolio to get started' : 'Select a portfolio from the left panel'}
+ {portfolios.length === 0 ? t('content.selectOrCreate') : t('content.selectOrCreate')}
</div>
</div>
) : !portfolioSummary ? (
<div style={{
- ...COMMON_STYLES.emptyState,
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ color: '#4A4A4A',
+ fontSize: fontSize.small,
+ textAlign: 'center',
}}>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.SEMIBOLD,
+ color: colors.textMuted,
+ fontSize: fontSize.body,
+ fontWeight: 600,
letterSpacing: '1px',
- fontFamily: TYPOGRAPHY.MONO,
+ fontFamily,
}}>
- LOADING PORTFOLIO DATA...
+ {t('extracted.loadingPortfolioData')}
</div>
</div>
) : (
@@ -575,7 +617,7 @@ const PortfolioTab: React.FC = () => {
</div>
)}
{activeSubTab === 'indices' && (
- <div id="indices-view" style={{ height: '100%', padding: SPACING.DEFAULT }}>
+ <div id="indices-view" style={{ height: '100%', padding: '12px' }}>
<CustomIndexView
key={indexRefreshKey}
portfolioId={selectedPortfolio?.id}
@@ -591,46 +633,56 @@ const PortfolioTab: React.FC = () => {
<div style={{
width: '300px',
flexShrink: 0,
- backgroundColor: FINCEPT.PANEL_BG,
- borderLeft: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: colors.panel,
+ borderLeft: `1px solid var(--ft-color-border, #2A2A2A)`,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
}}>
{/* Right Panel Header */}
<div style={{
- padding: SPACING.DEFAULT,
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: `1px solid var(--ft-color-border, #2A2A2A)`,
}}>
- <span style={{ ...COMMON_STYLES.dataLabel }}>PORTFOLIO SUMMARY</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('summary.portfolioSummary', 'PORTFOLIO SUMMARY')}</span>
</div>
{/* Summary Content */}
- <div style={{ flex: 1, overflow: 'auto', padding: SPACING.DEFAULT }}>
+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
{!portfolioSummary ? (
<div style={{
- ...COMMON_STYLES.emptyState,
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
height: 'auto',
- padding: SPACING.XLARGE,
+ padding: '24px',
+ color: '#4A4A4A',
+ fontSize: fontSize.small,
+ textAlign: 'center',
}}>
<DollarSign size={24} style={{ marginBottom: '8px', opacity: 0.3 }} />
- <span>Select a portfolio</span>
+ <span>{t('content.selectPortfolio', 'Select a portfolio')}</span>
</div>
) : (
- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.MEDIUM }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
{/* Total Value Card */}
<div style={{
- ...COMMON_STYLES.metricCard,
- borderColor: FINCEPT.ORANGE,
- padding: SPACING.DEFAULT,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.primary}`,
+ borderRadius: '2px',
+ padding: '12px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '4px',
}}>
- <div style={{ ...COMMON_STYLES.dataLabel }}>TOTAL VALUE</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('summary.totalValue')}</div>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD,
- fontFamily: TYPOGRAPHY.MONO,
+ color: colors.primary,
+ fontSize: fontSize.heading,
+ fontWeight: 700,
+ fontFamily,
}}>
{formatCurrency(portfolioSummary.total_market_value, currency)}
</div>
@@ -638,88 +690,92 @@ const PortfolioTab: React.FC = () => {
{/* Total P&L */}
<div style={{
- ...COMMON_STYLES.metricCard,
- borderColor: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- padding: SPACING.DEFAULT,
+ backgroundColor: colors.panel,
+ border: `1px solid ${portfolioSummary.total_unrealized_pnl >= 0 ? colors.success : colors.alert}`,
+ borderRadius: '2px',
+ padding: '12px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '4px',
}}>
- <div style={{ ...COMMON_STYLES.dataLabel }}>UNREALIZED P&L</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('summary.unrealizedPnl', 'UNREALIZED P&L')}</div>
<div style={{
display: 'flex',
alignItems: 'center',
gap: '4px',
}}>
{portfolioSummary.total_unrealized_pnl >= 0
- ? <ArrowUpRight size={14} color={FINCEPT.GREEN} />
- : <ArrowDownRight size={14} color={FINCEPT.RED} />
+ ? <ArrowUpRight size={14} color={colors.success} />
+ : <ArrowDownRight size={14} color={colors.alert} />
}
<span style={{
- color: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.SUBHEADING,
- fontWeight: TYPOGRAPHY.BOLD,
- fontFamily: TYPOGRAPHY.MONO,
+ color: portfolioSummary.total_unrealized_pnl >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.subheading,
+ fontWeight: 700,
+ fontFamily,
}}>
{portfolioSummary.total_unrealized_pnl >= 0 ? '+' : ''}{formatCurrency(portfolioSummary.total_unrealized_pnl, currency)}
</span>
</div>
<div style={{
- color: portfolioSummary.total_unrealized_pnl_percent >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.SMALL,
- fontFamily: TYPOGRAPHY.MONO,
+ color: portfolioSummary.total_unrealized_pnl_percent >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.small,
+ fontFamily,
}}>
{formatPercent(portfolioSummary.total_unrealized_pnl_percent)}
</div>
</div>
{/* Cost Basis */}
- <div style={{ ...COMMON_STYLES.metricCard, padding: SPACING.DEFAULT }}>
- <div style={{ ...COMMON_STYLES.dataLabel }}>COST BASIS</div>
+ <div style={{ backgroundColor: colors.panel, border: '1px solid var(--ft-color-border, #2A2A2A)', borderRadius: '2px', padding: '12px', display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('summary.costBasis', 'COST BASIS')}</div>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.SUBHEADING,
- fontWeight: TYPOGRAPHY.BOLD,
- fontFamily: TYPOGRAPHY.MONO,
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.subheading,
+ fontWeight: 700,
+ fontFamily,
}}>
{formatCurrency(portfolioSummary.total_cost_basis, currency)}
</div>
</div>
{/* Day Change */}
- <div style={{ ...COMMON_STYLES.metricCard, padding: SPACING.DEFAULT }}>
- <div style={{ ...COMMON_STYLES.dataLabel }}>DAY CHANGE</div>
+ <div style={{ backgroundColor: colors.panel, border: '1px solid var(--ft-color-border, #2A2A2A)', borderRadius: '2px', padding: '12px', display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('summary.dayChange', 'DAY CHANGE')}</div>
<div style={{
- color: portfolioSummary.total_day_change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.BOLD,
- fontFamily: TYPOGRAPHY.MONO,
+ color: portfolioSummary.total_day_change >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ fontFamily,
}}>
{portfolioSummary.total_day_change >= 0 ? '+' : ''}{formatCurrency(portfolioSummary.total_day_change, currency)}
- <span style={{ marginLeft: '6px', fontSize: TYPOGRAPHY.SMALL }}>
+ <span style={{ marginLeft: '6px', fontSize: fontSize.small }}>
({formatPercent(portfolioSummary.total_day_change_percent)})
</span>
</div>
</div>
{/* Divider */}
- <div style={COMMON_STYLES.divider} />
+ <div style={{ height: '1px', backgroundColor: 'var(--ft-color-border, #2A2A2A)', margin: '8px 0' }} />
{/* Quick Stats */}
- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.MEDIUM }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <span style={{ ...COMMON_STYLES.dataLabel }}>POSITIONS</span>
- <span style={{ ...COMMON_STYLES.dataValue }}>{portfolioSummary.total_positions}</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('summary.positions')}</span>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.small, fontFamily }}>{portfolioSummary.total_positions}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <span style={{ ...COMMON_STYLES.dataLabel }}>CURRENCY</span>
- <span style={{ ...COMMON_STYLES.dataValue }}>{currency}</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('sidebar.currency')}</span>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.small, fontFamily }}>{currency}</span>
</div>
</div>
{/* Divider */}
- <div style={COMMON_STYLES.divider} />
+ <div style={{ height: '1px', backgroundColor: 'var(--ft-color-border, #2A2A2A)', margin: '8px 0' }} />
{/* Top Holdings */}
<div>
- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.MEDIUM }}>TOP HOLDINGS</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase', marginBottom: '8px' }}>{t('summary.topHoldings', 'TOP HOLDINGS')}</div>
{portfolioSummary.holdings
.slice()
.sort((a, b) => b.weight - a.weight)
@@ -730,29 +786,29 @@ const PortfolioTab: React.FC = () => {
justifyContent: 'space-between',
alignItems: 'center',
padding: '4px 0',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderBottom: `1px solid var(--ft-color-border, #2A2A2A)`,
}}>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.SMALL, fontWeight: TYPOGRAPHY.BOLD, fontFamily: TYPOGRAPHY.MONO }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.small, fontWeight: 700, fontFamily }}>
{holding.symbol}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontFamily }}>
{holding.weight.toFixed(1)}%
</div>
</div>
<div style={{ textAlign: 'right' }}>
<div style={{
- color: holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.SMALL,
- fontWeight: TYPOGRAPHY.BOLD,
- fontFamily: TYPOGRAPHY.MONO,
+ color: holding.unrealized_pnl >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.small,
+ fontWeight: 700,
+ fontFamily,
}}>
{holding.unrealized_pnl >= 0 ? '+' : ''}{formatCurrency(holding.unrealized_pnl, currency)}
</div>
<div style={{
- color: holding.unrealized_pnl_percent >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.TINY,
- fontFamily: TYPOGRAPHY.MONO,
+ color: holding.unrealized_pnl_percent >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.tiny,
+ fontFamily,
}}>
{formatPercent(holding.unrealized_pnl_percent)}
</div>
@@ -769,34 +825,34 @@ const PortfolioTab: React.FC = () => {
{/* Status Bar (Bottom) */}
<TabFooter
- tabName="PORTFOLIO MANAGER"
- backgroundColor={FINCEPT.HEADER_BG}
- borderColor={FINCEPT.ORANGE}
+ tabName={t('title', 'PORTFOLIO MANAGER')}
+ backgroundColor="var(--ft-color-header, #1A1A1A)"
+ borderColor={colors.primary}
leftInfo={
portfolioSummary
? [
{
- label: 'Positions',
+ label: t('summary.positions'),
value: portfolioSummary.total_positions.toString(),
- color: FINCEPT.WHITE
+ color: colors.text
},
{
- label: 'Total Value',
+ label: t('summary.totalValue'),
value: formatCurrency(portfolioSummary.total_market_value, currency),
- color: FINCEPT.WHITE
+ color: colors.text
},
{
- label: 'Total P&L',
+ label: t('summary.totalPnl'),
value: `${portfolioSummary.total_unrealized_pnl >= 0 ? '+' : ''}${formatCurrency(portfolioSummary.total_unrealized_pnl, currency)}`,
- color: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED
+ color: portfolioSummary.total_unrealized_pnl >= 0 ? colors.success : colors.alert
}
]
: []
}
statusInfo={
- <span style={{ color: FINCEPT.GRAY, fontFamily: TYPOGRAPHY.MONO }}>
+ <span style={{ color: colors.textMuted, fontFamily }}>
{selectedPortfolio ? `${selectedPortfolio.name} | ` : ''}
- Last Updated: {currentTime.toLocaleTimeString('en-US', { hour12: false })}
+ {t('status.lastUpdated')}: {currentTime.toLocaleTimeString('en-US', { hour12: false })}
</span>
}
/>
@@ -805,7 +861,20 @@ const PortfolioTab: React.FC = () => {
<style>{`
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap');
- ${COMMON_STYLES.scrollbarCSS}
+ *::-webkit-scrollbar {
+ width: 6px;
+ height: 6px;
+ }
+ *::-webkit-scrollbar-track {
+ background: var(--ft-color-background, #000000);
+ }
+ *::-webkit-scrollbar-thumb {
+ background: var(--ft-color-border, #2A2A2A);
+ border-radius: 3px;
+ }
+ *::-webkit-scrollbar-thumb:hover {
+ background: #4A4A4A;
+ }
@keyframes pulse {
0%, 100% { opacity: 1; }
@@ -813,7 +882,7 @@ const PortfolioTab: React.FC = () => {
}
@keyframes priceFlash {
- 0% { background-color: ${FINCEPT.YELLOW}40; }
+ 0% { background-color: var(--ft-color-warning, #FFD700)40; }
100% { background-color: transparent; }
}
`}</style>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/AddAssetModal.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/AddAssetModal.tsx
index 111905749..1184974b5 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/AddAssetModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/AddAssetModal.tsx
@@ -1,7 +1,8 @@
import React, { useState, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { invoke } from '@tauri-apps/api/core';
import { marketDataService } from '../../../../services/markets/marketDataService';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, createFocusHandlers } from '../finceptStyles';
interface AddAssetModalProps {
show: boolean;
@@ -26,6 +27,8 @@ const AddAssetModal: React.FC<AddAssetModalProps> = ({
onClose,
onAdd
}) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [fetchingPrice, setFetchingPrice] = useState(false);
const [priceError, setPriceError] = useState<string | null>(null);
const [resolvedExchange, setResolvedExchange] = useState<string>('');
@@ -93,85 +96,133 @@ const AddAssetModal: React.FC<AddAssetModalProps> = ({
if (!show) return null;
return (
- <div style={COMMON_STYLES.modalOverlay}>
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 9999,
+ }}>
<div style={{
- ...COMMON_STYLES.modalPanel,
- border: BORDERS.GREEN,
- borderWidth: '2px',
- fontFamily: TYPOGRAPHY.MONO
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.success}`,
+ padding: '24px',
+ minWidth: '400px',
+ maxWidth: '600px',
+ boxShadow: `0 4px 16px ${colors.background}80`,
+ fontFamily,
}}>
<div style={{
- color: FINCEPT.GREEN,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.LARGE,
- letterSpacing: TYPOGRAPHY.WIDE
+ color: colors.success,
+ fontSize: fontSize.heading,
+ fontWeight: 700,
+ marginBottom: '16px',
+ letterSpacing: '0.5px',
}}>
- ADD ASSET TO PORTFOLIO
+ {t('modals.addAssetTitle')}
</div>
- <div style={{ marginBottom: SPACING.DEFAULT }}>
+ <div style={{ marginBottom: '12px' }}>
<label style={{
- ...COMMON_STYLES.dataLabel,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
display: 'block',
- marginBottom: SPACING.SMALL
+ marginBottom: '4px',
}}>
- SYMBOL *
+ {t('modals.symbol')} *
</label>
<input
type="text"
value={formState.symbol}
onChange={(e) => onSymbolChange(e.target.value.toUpperCase())}
style={{
- ...COMMON_STYLES.inputField,
- textTransform: 'uppercase'
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
+ borderRadius: '2px',
+ fontSize: fontSize.small,
+ fontFamily,
+ outline: 'none',
+ textTransform: 'uppercase',
}}
- {...createFocusHandlers()}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.success; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = 'var(--ft-color-border, #2A2A2A)'; }}
placeholder="AAPL"
/>
</div>
- <div style={{ marginBottom: SPACING.DEFAULT }}>
+ <div style={{ marginBottom: '12px' }}>
<label style={{
- ...COMMON_STYLES.dataLabel,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
display: 'block',
- marginBottom: SPACING.SMALL
+ marginBottom: '4px',
}}>
- QUANTITY *
+ {t('modals.quantity')} *
</label>
<input
type="text"
inputMode="decimal"
value={formState.quantity}
onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) onQuantityChange(v); }}
- style={COMMON_STYLES.inputField}
- {...createFocusHandlers()}
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
+ borderRadius: '2px',
+ fontSize: fontSize.small,
+ fontFamily,
+ outline: 'none',
+ }}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.success; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = 'var(--ft-color-border, #2A2A2A)'; }}
placeholder="100"
/>
</div>
- <div style={{ marginBottom: SPACING.LARGE }}>
+ <div style={{ marginBottom: '16px' }}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
- marginBottom: SPACING.SMALL
+ marginBottom: '4px'
}}>
- <label style={COMMON_STYLES.dataLabel}>
- BUY PRICE *
+ <label style={{
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ }}>
+ {t('modals.price')} *
</label>
{fetchingPrice && (
- <span style={{ color: FINCEPT.YELLOW, fontSize: TYPOGRAPHY.TINY }}>
+ <span style={{ color: 'var(--ft-color-warning, #FFD700)', fontSize: fontSize.tiny }}>
● Fetching...
</span>
)}
{!fetchingPrice && priceError && (
- <span style={{ color: FINCEPT.RED, fontSize: TYPOGRAPHY.TINY }}>
+ <span style={{ color: colors.alert, fontSize: fontSize.tiny }}>
{priceError}
</span>
)}
{!fetchingPrice && !priceError && formState.price && formState.symbol && (
- <span style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.TINY }}>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.tiny }}>
{resolvedExchange ? `✓ ${resolvedExchange}` : '✓ Auto-fetched'}
</span>
)}
@@ -182,33 +233,61 @@ const AddAssetModal: React.FC<AddAssetModalProps> = ({
value={formState.price}
onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) onPriceChange(v); }}
style={{
- ...COMMON_STYLES.inputField,
- borderColor: fetchingPrice ? FINCEPT.YELLOW : FINCEPT.BORDER
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${fetchingPrice ? 'var(--ft-color-warning, #FFD700)' : 'var(--ft-color-border, #2A2A2A)'}`,
+ borderRadius: '2px',
+ fontSize: fontSize.small,
+ fontFamily,
+ outline: 'none',
}}
- {...createFocusHandlers()}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.success; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = fetchingPrice ? 'var(--ft-color-warning, #FFD700)' : 'var(--ft-color-border, #2A2A2A)'; }}
placeholder="150.00"
/>
</div>
- <div style={{ display: 'flex', gap: SPACING.MEDIUM, justifyContent: 'flex-end' }}>
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
<button
onClick={onClose}
- style={COMMON_STYLES.buttonSecondary}
+ style={{
+ padding: '6px 10px',
+ backgroundColor: 'transparent',
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.textMuted,
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ e.currentTarget.style.backgroundColor = 'var(--ft-color-hover, #1F1F1F)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
}}
>
- CANCEL
+ {t('modals.cancel')}
</button>
<button
onClick={onAdd}
style={{
- ...COMMON_STYLES.buttonPrimary,
- backgroundColor: FINCEPT.GREEN,
- borderColor: FINCEPT.GREEN
+ padding: '8px 16px',
+ backgroundColor: colors.success,
+ color: colors.background,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = '0.85';
@@ -217,7 +296,7 @@ const AddAssetModal: React.FC<AddAssetModalProps> = ({
e.currentTarget.style.opacity = '1';
}}
>
- ADD
+ {t('modals.add')}
</button>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/ConfirmDeleteModal.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/ConfirmDeleteModal.tsx
index 932410d91..85665df25 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/ConfirmDeleteModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/ConfirmDeleteModal.tsx
@@ -1,6 +1,7 @@
import React from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { AlertTriangle } from 'lucide-react';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../finceptStyles';
interface ConfirmDeleteModalProps {
show: boolean;
@@ -15,73 +16,109 @@ const ConfirmDeleteModal: React.FC<ConfirmDeleteModalProps> = ({
onClose,
onConfirm
}) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+
if (!show) return null;
return (
- <div style={COMMON_STYLES.modalOverlay}>
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 9999,
+ }}>
<div style={{
- ...COMMON_STYLES.modalPanel,
- fontFamily: TYPOGRAPHY.MONO,
- maxWidth: '450px'
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.alert}`,
+ padding: '24px',
+ minWidth: '400px',
+ maxWidth: '450px',
+ boxShadow: `0 4px 16px ${colors.background}80`,
+ fontFamily,
}}>
<div style={{
display: 'flex',
alignItems: 'center',
- gap: SPACING.MEDIUM,
- marginBottom: SPACING.LARGE
+ gap: '12px',
+ marginBottom: '16px'
}}>
- <AlertTriangle size={24} color={FINCEPT.RED} />
+ <AlertTriangle size={24} color={colors.alert} />
<div style={{
- color: FINCEPT.RED,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD,
- letterSpacing: TYPOGRAPHY.WIDE
+ color: colors.alert,
+ fontSize: fontSize.heading,
+ fontWeight: 700,
+ letterSpacing: '0.5px'
}}>
DELETE PORTFOLIO
</div>
</div>
<div style={{
- color: FINCEPT.WHITE,
- fontSize: TYPOGRAPHY.DEFAULT,
- marginBottom: SPACING.LARGE,
+ color: colors.text,
+ fontSize: fontSize.small,
+ marginBottom: '16px',
lineHeight: 1.5
}}>
- Are you sure you want to delete <span style={{ color: FINCEPT.ORANGE, fontWeight: TYPOGRAPHY.BOLD }}>"{portfolioName}"</span>?
+ {t('extracted.areYouSureYou').split('"')[0]}<span style={{ color: colors.primary, fontWeight: 700 }}>"{portfolioName}"</span>?
</div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.BODY,
- marginBottom: SPACING.LARGE,
- padding: SPACING.MEDIUM,
- backgroundColor: FINCEPT.DARK_BG,
- border: BORDERS.RED
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ marginBottom: '16px',
+ padding: '12px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.alert}`
}}>
This action cannot be undone. All positions, transactions, and history will be permanently deleted.
</div>
- <div style={{ display: 'flex', gap: SPACING.MEDIUM, justifyContent: 'flex-end' }}>
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
<button
onClick={onClose}
style={{
- ...COMMON_STYLES.buttonSecondary,
+ padding: '6px 10px',
+ backgroundColor: 'transparent',
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.textMuted,
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ e.currentTarget.style.backgroundColor = 'var(--ft-color-hover, #1F1F1F)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
}}
>
- CANCEL
+ {t('modals.cancel')}
</button>
<button
onClick={onConfirm}
style={{
- ...COMMON_STYLES.buttonPrimary,
- backgroundColor: FINCEPT.RED,
- border: BORDERS.RED
+ padding: '8px 16px',
+ backgroundColor: colors.alert,
+ color: colors.text,
+ border: `1px solid ${colors.alert}`,
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = '0.85';
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/CreatePortfolioModal.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/CreatePortfolioModal.tsx
index 9f6e7b2c9..6e1d8ded6 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/CreatePortfolioModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/CreatePortfolioModal.tsx
@@ -1,5 +1,6 @@
import React from 'react';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, createFocusHandlers } from '../finceptStyles';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface CreatePortfolioModalProps {
show: boolean;
@@ -24,74 +25,134 @@ const CreatePortfolioModal: React.FC<CreatePortfolioModalProps> = ({
onClose,
onCreate
}) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+
if (!show) return null;
return (
- <div style={COMMON_STYLES.modalOverlay}>
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 9999,
+ }}>
<div style={{
- ...COMMON_STYLES.modalPanel,
- fontFamily: TYPOGRAPHY.MONO
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.primary}`,
+ padding: '24px',
+ minWidth: '400px',
+ maxWidth: '600px',
+ boxShadow: `0 4px 16px ${colors.background}80`,
+ fontFamily,
}}>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.LARGE,
- letterSpacing: TYPOGRAPHY.WIDE
+ color: colors.primary,
+ fontSize: fontSize.heading,
+ fontWeight: 700,
+ marginBottom: '16px',
+ letterSpacing: '0.5px',
}}>
- CREATE NEW PORTFOLIO
+ {t('modals.createNew')}
</div>
- <div style={{ marginBottom: SPACING.DEFAULT }}>
+ <div style={{ marginBottom: '12px' }}>
<label style={{
- ...COMMON_STYLES.dataLabel,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
display: 'block',
- marginBottom: SPACING.SMALL
+ marginBottom: '4px',
}}>
- PORTFOLIO NAME *
+ {t('modals.portfolioName')} *
</label>
<input
type="text"
value={formState.name}
onChange={(e) => onNameChange(e.target.value)}
- style={COMMON_STYLES.inputField}
- {...createFocusHandlers()}
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
+ borderRadius: '2px',
+ fontSize: fontSize.small,
+ fontFamily,
+ outline: 'none',
+ }}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = 'var(--ft-color-border, #2A2A2A)'; }}
placeholder="My Portfolio"
/>
</div>
- <div style={{ marginBottom: SPACING.DEFAULT }}>
+ <div style={{ marginBottom: '12px' }}>
<label style={{
- ...COMMON_STYLES.dataLabel,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
display: 'block',
- marginBottom: SPACING.SMALL
+ marginBottom: '4px',
}}>
- OWNER *
+ {t('modals.owner')} *
</label>
<input
type="text"
value={formState.owner}
onChange={(e) => onOwnerChange(e.target.value)}
- style={COMMON_STYLES.inputField}
- {...createFocusHandlers()}
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
+ borderRadius: '2px',
+ fontSize: fontSize.small,
+ fontFamily,
+ outline: 'none',
+ }}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = 'var(--ft-color-border, #2A2A2A)'; }}
placeholder="John Doe"
/>
</div>
- <div style={{ marginBottom: SPACING.LARGE }}>
+ <div style={{ marginBottom: '16px' }}>
<label style={{
- ...COMMON_STYLES.dataLabel,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
display: 'block',
- marginBottom: SPACING.SMALL
+ marginBottom: '4px',
}}>
- CURRENCY
+ {t('modals.currency')}
</label>
<select
value={formState.currency}
onChange={(e) => onCurrencyChange(e.target.value)}
style={{
- ...COMMON_STYLES.inputField,
- cursor: 'pointer'
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
+ borderRadius: '2px',
+ fontSize: fontSize.small,
+ fontFamily,
+ cursor: 'pointer',
}}
>
<option value="USD">USD - US Dollar</option>
@@ -101,24 +162,46 @@ const CreatePortfolioModal: React.FC<CreatePortfolioModalProps> = ({
</select>
</div>
- <div style={{ display: 'flex', gap: SPACING.MEDIUM, justifyContent: 'flex-end' }}>
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
<button
onClick={onClose}
style={{
- ...COMMON_STYLES.buttonSecondary,
+ padding: '6px 10px',
+ backgroundColor: 'transparent',
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.textMuted,
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ e.currentTarget.style.backgroundColor = 'var(--ft-color-hover, #1F1F1F)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
}}
>
- CANCEL
+ {t('modals.cancel')}
</button>
<button
onClick={onCreate}
- style={COMMON_STYLES.buttonPrimary}
+ style={{
+ padding: '8px 16px',
+ backgroundColor: colors.primary,
+ color: colors.background,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = '0.85';
}}
@@ -126,7 +209,7 @@ const CreatePortfolioModal: React.FC<CreatePortfolioModalProps> = ({
e.currentTarget.style.opacity = '1';
}}
>
- CREATE
+ {t('modals.create')}
</button>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/SellAssetModal.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/SellAssetModal.tsx
index 851929701..0ae4a3ed5 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/SellAssetModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/SellAssetModal.tsx
@@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { marketDataService } from '../../../../services/markets/marketDataService';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, createFocusHandlers } from '../finceptStyles';
interface SellAssetModalProps {
show: boolean;
@@ -25,6 +26,8 @@ const SellAssetModal: React.FC<SellAssetModalProps> = ({
onClose,
onSell
}) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [fetchingPrice, setFetchingPrice] = useState(false);
const [priceError, setPriceError] = useState<string | null>(null);
@@ -65,85 +68,133 @@ const SellAssetModal: React.FC<SellAssetModalProps> = ({
if (!show) return null;
return (
- <div style={COMMON_STYLES.modalOverlay}>
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 9999,
+ }}>
<div style={{
- ...COMMON_STYLES.modalPanel,
- border: BORDERS.RED,
- borderWidth: '2px',
- fontFamily: TYPOGRAPHY.MONO
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.alert}`,
+ padding: '24px',
+ minWidth: '400px',
+ maxWidth: '600px',
+ boxShadow: `0 4px 16px ${colors.background}80`,
+ fontFamily,
}}>
<div style={{
- color: FINCEPT.RED,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.LARGE,
- letterSpacing: TYPOGRAPHY.WIDE
+ color: colors.alert,
+ fontSize: fontSize.heading,
+ fontWeight: 700,
+ marginBottom: '16px',
+ letterSpacing: '0.5px',
}}>
- SELL ASSET FROM PORTFOLIO
+ {t('modals.sellAssetTitle')}
</div>
- <div style={{ marginBottom: SPACING.DEFAULT }}>
+ <div style={{ marginBottom: '12px' }}>
<label style={{
- ...COMMON_STYLES.dataLabel,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
display: 'block',
- marginBottom: SPACING.SMALL
+ marginBottom: '4px',
}}>
- SYMBOL *
+ {t('modals.symbol')} *
</label>
<input
type="text"
value={formState.symbol}
onChange={(e) => onSymbolChange(e.target.value.toUpperCase())}
style={{
- ...COMMON_STYLES.inputField,
- textTransform: 'uppercase'
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
+ borderRadius: '2px',
+ fontSize: fontSize.small,
+ fontFamily,
+ outline: 'none',
+ textTransform: 'uppercase',
}}
- {...createFocusHandlers()}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.alert; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = 'var(--ft-color-border, #2A2A2A)'; }}
placeholder="AAPL"
/>
</div>
- <div style={{ marginBottom: SPACING.DEFAULT }}>
+ <div style={{ marginBottom: '12px' }}>
<label style={{
- ...COMMON_STYLES.dataLabel,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
display: 'block',
- marginBottom: SPACING.SMALL
+ marginBottom: '4px',
}}>
- QUANTITY *
+ {t('modals.quantity')} *
</label>
<input
type="text"
inputMode="decimal"
value={formState.quantity}
onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) onQuantityChange(v); }}
- style={COMMON_STYLES.inputField}
- {...createFocusHandlers()}
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
+ borderRadius: '2px',
+ fontSize: fontSize.small,
+ fontFamily,
+ outline: 'none',
+ }}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.alert; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = 'var(--ft-color-border, #2A2A2A)'; }}
placeholder="50"
/>
</div>
- <div style={{ marginBottom: SPACING.LARGE }}>
+ <div style={{ marginBottom: '16px' }}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
- marginBottom: SPACING.SMALL
+ marginBottom: '4px'
}}>
- <label style={COMMON_STYLES.dataLabel}>
- SELL PRICE *
+ <label style={{
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ }}>
+ {t('modals.price')} *
</label>
{fetchingPrice && (
- <span style={{ color: FINCEPT.YELLOW, fontSize: TYPOGRAPHY.TINY }}>
+ <span style={{ color: 'var(--ft-color-warning, #FFD700)', fontSize: fontSize.tiny }}>
● Fetching...
</span>
)}
{!fetchingPrice && priceError && (
- <span style={{ color: FINCEPT.RED, fontSize: TYPOGRAPHY.TINY }}>
+ <span style={{ color: colors.alert, fontSize: fontSize.tiny }}>
{priceError}
</span>
)}
{!fetchingPrice && !priceError && formState.price && formState.symbol && (
- <span style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.TINY }}>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.tiny }}>
✓ Auto-fetched
</span>
)}
@@ -154,34 +205,61 @@ const SellAssetModal: React.FC<SellAssetModalProps> = ({
value={formState.price}
onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) onPriceChange(v); }}
style={{
- ...COMMON_STYLES.inputField,
- borderColor: fetchingPrice ? FINCEPT.YELLOW : FINCEPT.BORDER
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${fetchingPrice ? 'var(--ft-color-warning, #FFD700)' : 'var(--ft-color-border, #2A2A2A)'}`,
+ borderRadius: '2px',
+ fontSize: fontSize.small,
+ fontFamily,
+ outline: 'none',
}}
- {...createFocusHandlers()}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.alert; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = fetchingPrice ? 'var(--ft-color-warning, #FFD700)' : 'var(--ft-color-border, #2A2A2A)'; }}
placeholder="180.00"
/>
</div>
- <div style={{ display: 'flex', gap: SPACING.MEDIUM, justifyContent: 'flex-end' }}>
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
<button
onClick={onClose}
- style={COMMON_STYLES.buttonSecondary}
+ style={{
+ padding: '6px 10px',
+ backgroundColor: 'transparent',
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.textMuted,
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ e.currentTarget.style.backgroundColor = 'var(--ft-color-hover, #1F1F1F)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
}}
>
- CANCEL
+ {t('modals.cancel')}
</button>
<button
onClick={onSell}
style={{
- ...COMMON_STYLES.buttonPrimary,
- backgroundColor: FINCEPT.RED,
- borderColor: FINCEPT.RED,
- color: FINCEPT.WHITE
+ padding: '8px 16px',
+ backgroundColor: colors.alert,
+ color: colors.text,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = '0.85';
@@ -190,7 +268,7 @@ const SellAssetModal: React.FC<SellAssetModalProps> = ({
e.currentTarget.style.opacity = '1';
}}
>
- SELL
+ {t('modals.sell')}
</button>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AlertsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AlertsView.tsx
index 11a7f920c..6197ec216 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AlertsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AlertsView.tsx
@@ -1,65 +1,75 @@
import React, { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { PortfolioSummary } from '../../../../services/portfolio/portfolioService';
import { formatCurrency } from './utils';
import { Bell } from 'lucide-react';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, EFFECTS } from '../finceptStyles';
interface AlertsViewProps {
portfolioSummary: PortfolioSummary;
}
const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const currency = portfolioSummary.portfolio.currency;
const [hoveredCard, setHoveredCard] = useState<string | null>(null);
return (
<div style={{
height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.DEFAULT,
+ backgroundColor: colors.background,
+ padding: '12px',
overflow: 'auto',
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
<div style={{
- ...COMMON_STYLES.sectionHeader,
- marginBottom: SPACING.LARGE
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '16px',
}}>
- PRICE ALERTS & NOTIFICATIONS
+ {t('alerts.priceAlerts')}
</div>
{/* Feature Not Implemented Notice */}
<div style={{
- padding: SPACING.XLARGE,
+ padding: '24px',
textAlign: 'center',
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.ORANGE,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px',
- marginBottom: SPACING.LARGE
+ marginBottom: '16px'
}}>
- <Bell size={64} color={FINCEPT.ORANGE} style={{ margin: `0 auto ${SPACING.MEDIUM}` }} />
+ <Bell size={64} color={colors.primary} style={{ margin: `0 auto 12px` }} />
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '13px',
+ color: colors.primary,
+ fontSize: fontSize.small,
fontWeight: 700,
- marginBottom: SPACING.SMALL,
- fontFamily: TYPOGRAPHY.MONO
+ marginBottom: '8px',
+ fontFamily
}}>
- PRICE ALERTS FEATURE
+ {t('alerts.featureTitle')}
</div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '11px',
- marginBottom: SPACING.MEDIUM,
- fontFamily: TYPOGRAPHY.MONO
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ marginBottom: '12px',
+ fontFamily
}}>
- This feature is not yet implemented.
+ {t('alerts.notImplemented')}
</div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '11px',
- fontFamily: TYPOGRAPHY.MONO
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontFamily
}}>
- Price alerts will allow you to set notifications for:
+ {t('alerts.willAllowYou')}
</div>
</div>
@@ -67,94 +77,94 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(2, 1fr)',
- gap: SPACING.DEFAULT,
- marginBottom: SPACING.LARGE
+ gap: '12px',
+ marginBottom: '16px'
}}>
<div style={{
- padding: SPACING.MEDIUM,
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ padding: '12px',
+ backgroundColor: colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px'
}}>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '9px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
- marginBottom: SPACING.SMALL,
- fontFamily: TYPOGRAPHY.MONO
+ marginBottom: '8px',
+ fontFamily
}}>
- PLANNED FEATURES
+ {t('alerts.plannedFeatures')}
</div>
<ul style={{
margin: 0,
- paddingLeft: SPACING.DEFAULT,
- fontSize: '10px',
- color: FINCEPT.WHITE,
- fontFamily: TYPOGRAPHY.MONO
+ paddingLeft: '12px',
+ fontSize: fontSize.tiny,
+ color: colors.text,
+ fontFamily
}}>
- <li style={{ marginBottom: SPACING.TINY }}>Price target alerts</li>
- <li style={{ marginBottom: SPACING.TINY }}>Stop loss notifications</li>
- <li style={{ marginBottom: SPACING.TINY }}>Take profit alerts</li>
- <li style={{ marginBottom: SPACING.TINY }}>Custom price conditions</li>
- <li style={{ marginBottom: SPACING.TINY }}>Volume spike alerts</li>
+ <li style={{ marginBottom: '4px' }}>{t('alerts.priceTargetAlerts')}</li>
+ <li style={{ marginBottom: '4px' }}>{t('alerts.stopLossNotifications')}</li>
+ <li style={{ marginBottom: '4px' }}>{t('alerts.takeProfitAlerts')}</li>
+ <li style={{ marginBottom: '4px' }}>{t('alerts.customPriceConditions')}</li>
+ <li style={{ marginBottom: '4px' }}>{t('alerts.volumeSpikeAlerts')}</li>
</ul>
</div>
<div style={{
- padding: SPACING.MEDIUM,
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ padding: '12px',
+ backgroundColor: colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px'
}}>
<div style={{
- color: FINCEPT.GREEN,
- fontSize: '9px',
+ color: colors.success,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
- marginBottom: SPACING.SMALL,
- fontFamily: TYPOGRAPHY.MONO
+ marginBottom: '8px',
+ fontFamily
}}>
- NOTIFICATION CHANNELS
+ {t('alerts.notificationChannels')}
</div>
<ul style={{
margin: 0,
- paddingLeft: SPACING.DEFAULT,
- fontSize: '10px',
- color: FINCEPT.WHITE,
- fontFamily: TYPOGRAPHY.MONO
+ paddingLeft: '12px',
+ fontSize: fontSize.tiny,
+ color: colors.text,
+ fontFamily
}}>
- <li style={{ marginBottom: SPACING.TINY }}>Desktop notifications</li>
- <li style={{ marginBottom: SPACING.TINY }}>Email alerts</li>
- <li style={{ marginBottom: SPACING.TINY }}>SMS notifications (Premium)</li>
- <li style={{ marginBottom: SPACING.TINY }}>Push notifications</li>
- <li style={{ marginBottom: SPACING.TINY }}>Daily/weekly summaries</li>
+ <li style={{ marginBottom: '4px' }}>{t('alerts.desktopNotifications')}</li>
+ <li style={{ marginBottom: '4px' }}>{t('alerts.emailAlerts')}</li>
+ <li style={{ marginBottom: '4px' }}>{t('alerts.smsNotifications')}</li>
+ <li style={{ marginBottom: '4px' }}>{t('alerts.pushNotifications')}</li>
+ <li style={{ marginBottom: '4px' }}>{t('alerts.dailyWeeklySummaries')}</li>
</ul>
</div>
</div>
{/* Position-Based Alert Suggestions Preview */}
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '9px',
+ color: colors.primary,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
- marginBottom: SPACING.MEDIUM,
- paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.ORANGE,
- fontFamily: TYPOGRAPHY.MONO
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${colors.primary}`,
+ fontFamily
}}>
- SUGGESTED ALERTS FOR YOUR POSITIONS (PREVIEW)
+ {t('alerts.suggestedAlerts')}
</div>
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(2, 1fr)',
- gap: SPACING.DEFAULT,
- marginBottom: SPACING.LARGE
+ gap: '12px',
+ marginBottom: '16px'
}}>
{portfolioSummary.holdings.slice(0, 4).map(holding => {
const stopLoss = holding.avg_buy_price * 0.9;
@@ -167,55 +177,55 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
onMouseEnter={() => setHoveredCard(holding.id)}
onMouseLeave={() => setHoveredCard(null)}
style={{
- padding: SPACING.MEDIUM,
- backgroundColor: isHovered ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- border: isHovered ? BORDERS.CYAN : BORDERS.STANDARD,
+ padding: '12px',
+ backgroundColor: isHovered ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
+ border: isHovered ? `1px solid var(--ft-color-accent, #00E5FF)` : '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
opacity: 0.6,
- transition: EFFECTS.TRANSITION_STANDARD,
+ transition: 'all 0.2s ease',
cursor: 'default'
}}
>
<div style={{
display: 'flex',
justifyContent: 'space-between',
- marginBottom: SPACING.SMALL
+ marginBottom: '8px'
}}>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '10px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
{holding.symbol}
</div>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '10px',
- fontFamily: TYPOGRAPHY.MONO
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
+ fontFamily
}}>
{formatCurrency(holding.current_price, currency)}
</div>
</div>
- <div style={{ fontSize: '10px', marginBottom: SPACING.SMALL }}>
+ <div style={{ fontSize: fontSize.tiny, marginBottom: '8px' }}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
- marginBottom: SPACING.TINY
+ marginBottom: '4px'
}}>
<span style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
- fontFamily: TYPOGRAPHY.MONO
- }}>Stop Loss (10%):</span>
+ fontFamily
+ }}>{t('alerts.stopLoss')}</span>
<span style={{
- color: FINCEPT.RED,
- fontSize: '10px',
- fontFamily: TYPOGRAPHY.MONO
+ color: colors.alert,
+ fontSize: fontSize.tiny,
+ fontFamily
}}>{formatCurrency(stopLoss, currency)}</span>
</div>
<div style={{
@@ -223,17 +233,17 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
justifyContent: 'space-between'
}}>
<span style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
- fontFamily: TYPOGRAPHY.MONO
- }}>Take Profit (20%):</span>
+ fontFamily
+ }}>{t('alerts.takeProfit')}</span>
<span style={{
- color: FINCEPT.GREEN,
- fontSize: '10px',
- fontFamily: TYPOGRAPHY.MONO
+ color: colors.success,
+ fontSize: fontSize.tiny,
+ fontFamily
}}>{formatCurrency(takeProfit, currency)}</span>
</div>
</div>
@@ -242,21 +252,21 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
disabled
style={{
width: '100%',
- padding: SPACING.TINY,
- backgroundColor: FINCEPT.GRAY,
- color: FINCEPT.DARK_BG,
+ padding: '4px',
+ backgroundColor: colors.textMuted,
+ color: colors.background,
border: 'none',
borderRadius: '2px',
- fontSize: '9px',
+ fontSize: fontSize.tiny,
fontWeight: 700,
cursor: 'not-allowed',
- fontFamily: TYPOGRAPHY.MONO,
+ fontFamily,
opacity: 0.5,
letterSpacing: '0.5px',
textTransform: 'uppercase'
}}
>
- COMING SOON
+ {t('alerts.comingSoon')}
</button>
</div>
);
@@ -265,29 +275,29 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
{/* Implementation Note */}
<div style={{
- padding: SPACING.DEFAULT,
+ padding: '12px',
backgroundColor: 'rgba(255,136,0,0.05)',
- border: BORDERS.ORANGE,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px'
}}>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '9px',
+ color: colors.primary,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
- marginBottom: SPACING.SMALL,
- fontFamily: TYPOGRAPHY.MONO
+ marginBottom: '8px',
+ fontFamily
}}>
- IMPLEMENTATION STATUS
+ {t('alerts.implementationStatus')}
</div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '10px',
- fontFamily: TYPOGRAPHY.MONO
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontFamily
}}>
The price alerts system requires backend implementation including:
- <ul style={{ marginTop: SPACING.SMALL, paddingLeft: SPACING.DEFAULT }}>
+ <ul style={{ marginTop: '8px', paddingLeft: '12px' }}>
<li>Database schema for price alert conditions</li>
<li>Real-time price monitoring service</li>
<li>Notification delivery system</li>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AnalyticsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AnalyticsView.tsx
index bb6810012..716b29521 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AnalyticsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AnalyticsView.tsx
@@ -1,14 +1,17 @@
import React, { useState, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { PortfolioSummary, portfolioService } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatPercent, formatLargeNumber } from './utils';
-import { TrendingUp, Activity, PieChart, Target } from 'lucide-react';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, GRID_TEMPLATES, EFFECTS } from '../finceptStyles';
+import { Activity, Target } from 'lucide-react';
interface AnalyticsViewProps {
portfolioSummary: PortfolioSummary;
}
const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const currency = portfolioSummary.portfolio.currency;
// Advanced analytics state
@@ -83,29 +86,36 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
return (
<div style={{
height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.DEFAULT,
+ backgroundColor: colors.background,
+ padding: '12px',
overflow: 'auto',
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
{/* Section Header */}
<div style={{
- ...COMMON_STYLES.sectionHeader,
- marginBottom: SPACING.LARGE
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '16px',
}}>
- PORTFOLIO ANALYTICS DASHBOARD
+ {t('analytics.dashboard', 'PORTFOLIO ANALYTICS DASHBOARD')}
</div>
{/* Error Message */}
{analyticsError && (
<div style={{
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.RED,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.alert}`,
borderRadius: '2px',
- padding: SPACING.DEFAULT,
- marginBottom: SPACING.LARGE,
- color: FINCEPT.RED,
- fontSize: '10px'
+ padding: '12px',
+ marginBottom: '16px',
+ color: colors.alert,
+ fontSize: fontSize.small
}}>
[WARN] {analyticsError}
</div>
@@ -114,30 +124,30 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Advanced Analytics Section */}
{advancedMetrics && (
<div style={{
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.CYAN,
+ backgroundColor: colors.panel,
+ border: '1px solid var(--ft-color-accent, #00E5FF)',
borderRadius: '2px',
- padding: SPACING.LARGE,
- marginBottom: SPACING.LARGE,
+ padding: '16px',
+ marginBottom: '16px',
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
- marginBottom: SPACING.DEFAULT
+ marginBottom: '12px'
}}>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '11px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.body,
fontWeight: 700,
display: 'flex',
alignItems: 'center',
- gap: SPACING.SMALL,
+ gap: '4px',
letterSpacing: '0.5px',
textTransform: 'uppercase' as const
}}>
- <Activity size={14} color={FINCEPT.CYAN} />
- ADVANCED PORTFOLIO METRICS (Python-Powered)
+ <Activity size={14} color="var(--ft-color-accent, #00E5FF)" />
+ {t('analytics.advancedMetrics', 'ADVANCED PORTFOLIO METRICS (Python-Powered)')}
</div>
<button
onClick={loadOptimization}
@@ -145,48 +155,55 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
onMouseEnter={() => setHoveredOptimize(true)}
onMouseLeave={() => setHoveredOptimize(false)}
style={{
- ...COMMON_STYLES.buttonPrimary,
- background: loadingOptimization ? FINCEPT.MUTED : (hoveredOptimize ? '#FF9922' : FINCEPT.ORANGE),
+ padding: '8px 16px',
+ backgroundColor: loadingOptimization ? '#4A4A4A' : (hoveredOptimize ? '#FF9922' : colors.primary),
+ color: colors.background,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
cursor: loadingOptimization ? 'not-allowed' : 'pointer',
display: 'flex',
alignItems: 'center',
- gap: SPACING.SMALL,
+ gap: '4px',
opacity: loadingOptimization ? 0.6 : 1,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
}}
>
<Target size={10} />
- {loadingOptimization ? 'OPTIMIZING...' : 'OPTIMIZE WEIGHTS'}
+ {loadingOptimization ? t('analytics.optimizing', 'OPTIMIZING...') : t('analytics.optimizeWeights', 'OPTIMIZE WEIGHTS')}
</button>
</div>
- <div style={{ ...GRID_TEMPLATES.autoFit('120px'), marginTop: SPACING.DEFAULT }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: '12px', marginTop: '12px' }}>
<div style={{ textAlign: 'center' }}>
- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>SHARPE RATIO</div>
- <div style={{ color: FINCEPT.GREEN, fontSize: '15px', fontWeight: 700 }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase', marginBottom: '4px' }}>{t('analytics.sharpeRatio', 'SHARPE RATIO')}</div>
+ <div style={{ color: colors.success, fontSize: '15px', fontWeight: 700 }}>
{advancedMetrics.sharpe_ratio?.toFixed(2) || 'N/A'}
</div>
</div>
<div style={{ textAlign: 'center' }}>
- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>VOLATILITY</div>
- <div style={{ color: FINCEPT.YELLOW, fontSize: '15px', fontWeight: 700 }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase', marginBottom: '4px' }}>{t('analytics.volatility', 'VOLATILITY')}</div>
+ <div style={{ color: 'var(--ft-color-warning, #FFD700)', fontSize: '15px', fontWeight: 700 }}>
{(advancedMetrics.portfolio_volatility * 100)?.toFixed(2)}%
</div>
</div>
<div style={{ textAlign: 'center' }}>
- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>VaR (95%)</div>
- <div style={{ color: FINCEPT.RED, fontSize: '15px', fontWeight: 700 }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase', marginBottom: '4px' }}>{t('analytics.var95', 'VaR (95%)')}</div>
+ <div style={{ color: colors.alert, fontSize: '15px', fontWeight: 700 }}>
{(advancedMetrics.value_at_risk_95 * 100)?.toFixed(2)}%
</div>
</div>
<div style={{ textAlign: 'center' }}>
- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>MAX DRAWDOWN</div>
- <div style={{ color: FINCEPT.RED, fontSize: '15px', fontWeight: 700 }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase', marginBottom: '4px' }}>{t('analytics.maxDrawdown', 'MAX DRAWDOWN')}</div>
+ <div style={{ color: colors.alert, fontSize: '15px', fontWeight: 700 }}>
{(advancedMetrics.max_drawdown * 100)?.toFixed(2)}%
</div>
</div>
<div style={{ textAlign: 'center' }}>
- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>ANNUAL RETURN</div>
- <div style={{ color: FINCEPT.GREEN, fontSize: '15px', fontWeight: 700 }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase', marginBottom: '4px' }}>{t('analytics.annualReturn', 'ANNUAL RETURN')}</div>
+ <div style={{ color: colors.success, fontSize: '15px', fontWeight: 700 }}>
{(advancedMetrics.portfolio_return * 100)?.toFixed(2)}%
</div>
</div>
@@ -195,21 +212,21 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Optimized Portfolio Section */}
{optimizedPortfolio && (
<div style={{
- marginTop: SPACING.DEFAULT,
- paddingTop: SPACING.DEFAULT,
- borderTop: BORDERS.STANDARD
+ marginTop: '12px',
+ paddingTop: '12px',
+ borderTop: '1px solid var(--ft-color-border, #2A2A2A)'
}}>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '10px',
+ color: colors.primary,
+ fontSize: fontSize.small,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const,
- marginBottom: SPACING.MEDIUM
+ marginBottom: '8px'
}}>
- OPTIMIZED ALLOCATION (Max Sharpe Ratio)
+ {t('analytics.optimizedAllocation', 'OPTIMIZED ALLOCATION (Max Sharpe Ratio)')}
</div>
- <div style={{ ...GRID_TEMPLATES.autoFit('120px') }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: '12px' }}>
{portfolioSummary.holdings.map((holding, idx) => {
const currentWeight = holding.weight;
const optimalWeight = (optimizedPortfolio.optimal_weights[idx] * 100);
@@ -217,28 +234,28 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
return (
<div key={holding.id} style={{
- padding: SPACING.SMALL,
- backgroundColor: FINCEPT.DARK_BG,
- border: BORDERS.STANDARD,
+ padding: '4px',
+ backgroundColor: colors.background,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
}}>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '10px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.small,
fontWeight: 700,
- marginBottom: SPACING.TINY
+ marginBottom: '2px'
}}>
{holding.symbol}
</div>
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
+ <div style={{ fontSize: fontSize.tiny, color: colors.textMuted, letterSpacing: '0.5px' }}>
Current: {currentWeight.toFixed(1)}%
</div>
- <div style={{ fontSize: '9px', color: FINCEPT.YELLOW }}>
+ <div style={{ fontSize: fontSize.tiny, color: 'var(--ft-color-warning, #FFD700)' }}>
Optimal: {optimalWeight.toFixed(1)}%
</div>
<div style={{
- fontSize: '9px',
- color: diff > 0 ? FINCEPT.GREEN : diff < 0 ? FINCEPT.RED : FINCEPT.GRAY
+ fontSize: fontSize.tiny,
+ color: diff > 0 ? colors.success : diff < 0 ? colors.alert : colors.textMuted
}}>
{diff > 0 ? '\u2191' : diff < 0 ? '\u2193' : '='} {Math.abs(diff).toFixed(1)}%
</div>
@@ -247,17 +264,17 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
})}
</div>
<div style={{
- marginTop: SPACING.MEDIUM,
- fontSize: '10px',
- color: FINCEPT.GRAY
+ marginTop: '8px',
+ fontSize: fontSize.small,
+ color: colors.textMuted
}}>
- Optimized Sharpe: <span style={{ color: FINCEPT.GREEN, fontWeight: 700 }}>
+ Optimized Sharpe: <span style={{ color: colors.success, fontWeight: 700 }}>
{optimizedPortfolio.sharpe_ratio?.toFixed(2)}
</span> |
- Expected Return: <span style={{ color: FINCEPT.GREEN, fontWeight: 700 }}>
+ Expected Return: <span style={{ color: colors.success, fontWeight: 700 }}>
{(optimizedPortfolio.expected_return * 100)?.toFixed(2)}%
</span> |
- Volatility: <span style={{ color: FINCEPT.YELLOW, fontWeight: 700 }}>
+ Volatility: <span style={{ color: 'var(--ft-color-warning, #FFD700)', fontWeight: 700 }}>
{(optimizedPortfolio.volatility * 100)?.toFixed(2)}%
</span>
</div>
@@ -269,14 +286,14 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Loading State */}
{loadingMetrics && !advancedMetrics && (
<div style={{
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.CYAN,
+ backgroundColor: colors.panel,
+ border: '1px solid var(--ft-color-accent, #00E5FF)',
borderRadius: '2px',
- padding: SPACING.LARGE,
- marginBottom: SPACING.LARGE,
+ padding: '16px',
+ marginBottom: '16px',
textAlign: 'center',
- color: FINCEPT.CYAN,
- fontSize: '10px'
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.small
}}>
Loading advanced analytics...
</div>
@@ -284,27 +301,34 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Key Metrics Grid */}
<div style={{
- ...GRID_TEMPLATES.fourColumn,
- marginBottom: SPACING.LARGE
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: '12px',
+ marginBottom: '16px'
}}>
{/* Total Value Card */}
<div style={{
- ...COMMON_STYLES.metricCard,
- border: BORDERS.ORANGE
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.primary}`,
+ borderRadius: '2px',
+ padding: '12px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '4px',
}}>
- <div style={{ ...COMMON_STYLES.dataLabel }}>TOTAL VALUE</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('analytics.totalValue', 'TOTAL VALUE')}</div>
<div style={{
- color: FINCEPT.CYAN,
+ color: 'var(--ft-color-accent, #00E5FF)',
fontSize: '16px',
fontWeight: 700
}}>
{formatLargeNumber(totalValue, currency)}
</div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
letterSpacing: '0.5px',
- marginTop: SPACING.TINY
+ marginTop: '2px'
}}>
{formatCurrency(totalValue, currency)}
</div>
@@ -312,21 +336,32 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Total P&L Card */}
<div style={{
- ...COMMON_STYLES.metricCard,
- border: totalPnL >= 0 ? BORDERS.GREEN : BORDERS.RED
+ backgroundColor: colors.panel,
+ border: `1px solid ${totalPnL >= 0 ? colors.success : colors.alert}`,
+ borderRadius: '2px',
+ padding: '12px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '4px',
}}>
- <div style={{ ...COMMON_STYLES.dataLabel }}>TOTAL P&L</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('analytics.totalPnl', 'TOTAL P&L')}</div>
<div style={{
- color: totalPnL >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ color: totalPnL >= 0 ? colors.success : colors.alert,
fontSize: '16px',
fontWeight: 700
}}>
{totalPnL >= 0 ? '+' : ''}{formatLargeNumber(totalPnL, currency)}
</div>
<div style={{
- ...(totalPnL >= 0 ? COMMON_STYLES.badgeSuccess : COMMON_STYLES.badgeError),
- marginTop: SPACING.TINY,
- display: 'inline-block'
+ padding: '2px 6px',
+ backgroundColor: totalPnL >= 0 ? `${colors.success}20` : `${colors.alert}20`,
+ color: totalPnL >= 0 ? colors.success : colors.alert,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ marginTop: '2px',
+ display: 'inline-block',
+ width: 'fit-content'
}}>
{formatPercent(totalPnLPercent)}
</div>
@@ -334,21 +369,32 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Day Change Card */}
<div style={{
- ...COMMON_STYLES.metricCard,
- border: dayChange >= 0 ? BORDERS.GREEN : BORDERS.RED
+ backgroundColor: colors.panel,
+ border: `1px solid ${dayChange >= 0 ? colors.success : colors.alert}`,
+ borderRadius: '2px',
+ padding: '12px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '4px',
}}>
- <div style={{ ...COMMON_STYLES.dataLabel }}>DAY CHANGE</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('analytics.dayChange', 'DAY CHANGE')}</div>
<div style={{
- color: dayChange >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ color: dayChange >= 0 ? colors.success : colors.alert,
fontSize: '16px',
fontWeight: 700
}}>
{dayChange >= 0 ? '+' : ''}{formatLargeNumber(dayChange, currency)}
</div>
<div style={{
- ...(dayChange >= 0 ? COMMON_STYLES.badgeSuccess : COMMON_STYLES.badgeError),
- marginTop: SPACING.TINY,
- display: 'inline-block'
+ padding: '2px 6px',
+ backgroundColor: dayChange >= 0 ? `${colors.success}20` : `${colors.alert}20`,
+ color: dayChange >= 0 ? colors.success : colors.alert,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ marginTop: '2px',
+ display: 'inline-block',
+ width: 'fit-content'
}}>
{formatPercent(dayChangePercent)}
</div>
@@ -356,21 +402,32 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Positions Card */}
<div style={{
- ...COMMON_STYLES.metricCard,
- border: BORDERS.CYAN
+ backgroundColor: colors.panel,
+ border: '1px solid var(--ft-color-accent, #00E5FF)',
+ borderRadius: '2px',
+ padding: '12px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '4px',
}}>
- <div style={{ ...COMMON_STYLES.dataLabel }}>POSITIONS</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' }}>{t('analytics.positions', 'POSITIONS')}</div>
<div style={{
- color: FINCEPT.CYAN,
+ color: 'var(--ft-color-accent, #00E5FF)',
fontSize: '16px',
fontWeight: 700
}}>
{positionsCount}
</div>
<div style={{
- ...COMMON_STYLES.badgeInfo,
- marginTop: SPACING.TINY,
- display: 'inline-block'
+ padding: '2px 6px',
+ backgroundColor: 'var(--ft-color-accent, #00E5FF)20',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ marginTop: '2px',
+ display: 'inline-block',
+ width: 'fit-content'
}}>
Active Holdings
</div>
@@ -378,19 +435,24 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
</div>
{/* Performance Section */}
- <div style={{ ...GRID_TEMPLATES.threeColumn, marginBottom: SPACING.LARGE }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', marginBottom: '16px' }}>
{/* Top Gainers */}
<div>
<div style={{
- ...COMMON_STYLES.sectionHeader,
- color: FINCEPT.GREEN,
- borderBottom: BORDERS.GREEN,
- marginBottom: SPACING.MEDIUM,
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: `1px solid ${colors.success}`,
+ color: colors.success,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '8px',
}}>
- TOP GAINERS
+ {t('analytics.topGainers', 'TOP GAINERS')}
</div>
{topGainers.length === 0 ? (
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px', padding: SPACING.MEDIUM }}>No data</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.small, padding: '8px' }}>{t('analytics.noData', 'No data')}</div>
) : (
topGainers.map(holding => (
<div
@@ -398,31 +460,31 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
onMouseEnter={() => setHoveredGainer(holding.id)}
onMouseLeave={() => setHoveredGainer(null)}
style={{
- padding: SPACING.MEDIUM,
- marginBottom: SPACING.SMALL,
- backgroundColor: hoveredGainer === holding.id ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- borderLeft: `3px solid ${FINCEPT.GREEN}`,
+ padding: '8px',
+ marginBottom: '4px',
+ backgroundColor: hoveredGainer === holding.id ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
+ borderLeft: `3px solid ${colors.success}`,
borderRadius: '2px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
- transition: EFFECTS.TRANSITION_STANDARD,
+ transition: 'all 0.2s ease',
cursor: 'default'
}}
>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.small, fontWeight: 700 }}>
{holding.symbol}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', letterSpacing: '0.5px' }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, letterSpacing: '0.5px' }}>
{formatCurrency(holding.market_value, currency)}
</div>
</div>
<div style={{ textAlign: 'right' }}>
- <div style={{ ...COMMON_STYLES.badgeSuccess }}>
+ <div style={{ padding: '2px 6px', backgroundColor: `${colors.success}20`, color: colors.success, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
+{formatPercent(holding.unrealized_pnl_percent)}
</div>
- <div style={{ color: FINCEPT.GREEN, fontSize: '9px', marginTop: SPACING.TINY }}>
+ <div style={{ color: colors.success, fontSize: fontSize.tiny, marginTop: '2px' }}>
+{formatCurrency(holding.unrealized_pnl, currency)}
</div>
</div>
@@ -434,15 +496,20 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Top Losers */}
<div>
<div style={{
- ...COMMON_STYLES.sectionHeader,
- color: FINCEPT.RED,
- borderBottom: BORDERS.RED,
- marginBottom: SPACING.MEDIUM,
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: `1px solid ${colors.alert}`,
+ color: colors.alert,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '8px',
}}>
- TOP LOSERS
+ {t('analytics.topLosers', 'TOP LOSERS')}
</div>
{topLosers.length === 0 ? (
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px', padding: SPACING.MEDIUM }}>No data</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.small, padding: '8px' }}>{t('analytics.noData', 'No data')}</div>
) : (
topLosers.map(holding => (
<div
@@ -450,31 +517,31 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
onMouseEnter={() => setHoveredLoser(holding.id)}
onMouseLeave={() => setHoveredLoser(null)}
style={{
- padding: SPACING.MEDIUM,
- marginBottom: SPACING.SMALL,
- backgroundColor: hoveredLoser === holding.id ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- borderLeft: `3px solid ${FINCEPT.RED}`,
+ padding: '8px',
+ marginBottom: '4px',
+ backgroundColor: hoveredLoser === holding.id ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
+ borderLeft: `3px solid ${colors.alert}`,
borderRadius: '2px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
- transition: EFFECTS.TRANSITION_STANDARD,
+ transition: 'all 0.2s ease',
cursor: 'default'
}}
>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.small, fontWeight: 700 }}>
{holding.symbol}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', letterSpacing: '0.5px' }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, letterSpacing: '0.5px' }}>
{formatCurrency(holding.market_value, currency)}
</div>
</div>
<div style={{ textAlign: 'right' }}>
- <div style={{ ...COMMON_STYLES.badgeError }}>
+ <div style={{ padding: '2px 6px', backgroundColor: `${colors.alert}20`, color: colors.alert, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{formatPercent(holding.unrealized_pnl_percent)}
</div>
- <div style={{ color: FINCEPT.RED, fontSize: '9px', marginTop: SPACING.TINY }}>
+ <div style={{ color: colors.alert, fontSize: fontSize.tiny, marginTop: '2px' }}>
{formatCurrency(holding.unrealized_pnl, currency)}
</div>
</div>
@@ -486,15 +553,20 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Largest Positions */}
<div>
<div style={{
- ...COMMON_STYLES.sectionHeader,
- color: FINCEPT.CYAN,
- borderBottom: BORDERS.CYAN,
- marginBottom: SPACING.MEDIUM,
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-accent, #00E5FF)',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '8px',
}}>
- LARGEST POSITIONS
+ {t('analytics.largestPositions', 'LARGEST POSITIONS')}
</div>
{largestPositions.length === 0 ? (
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px', padding: SPACING.MEDIUM }}>No data</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.small, padding: '8px' }}>{t('analytics.noData', 'No data')}</div>
) : (
largestPositions.map(holding => (
<div
@@ -502,33 +574,38 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
onMouseEnter={() => setHoveredPosition(holding.id)}
onMouseLeave={() => setHoveredPosition(null)}
style={{
- padding: SPACING.MEDIUM,
- marginBottom: SPACING.SMALL,
- backgroundColor: hoveredPosition === holding.id ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- borderLeft: `3px solid ${FINCEPT.CYAN}`,
+ padding: '8px',
+ marginBottom: '4px',
+ backgroundColor: hoveredPosition === holding.id ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
+ borderLeft: '3px solid var(--ft-color-accent, #00E5FF)',
borderRadius: '2px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
- transition: EFFECTS.TRANSITION_STANDARD,
+ transition: 'all 0.2s ease',
cursor: 'default'
}}
>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.small, fontWeight: 700 }}>
{holding.symbol}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', letterSpacing: '0.5px' }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, letterSpacing: '0.5px' }}>
Weight: {holding.weight.toFixed(1)}%
</div>
</div>
<div style={{ textAlign: 'right' }}>
- <div style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.small, fontWeight: 700 }}>
{formatLargeNumber(holding.market_value, currency)}
</div>
<div style={{
- ...(holding.unrealized_pnl >= 0 ? COMMON_STYLES.badgeSuccess : COMMON_STYLES.badgeError),
- marginTop: SPACING.TINY,
+ padding: '2px 6px',
+ backgroundColor: holding.unrealized_pnl >= 0 ? `${colors.success}20` : `${colors.alert}20`,
+ color: holding.unrealized_pnl >= 0 ? colors.success : colors.alert,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ marginTop: '2px',
display: 'inline-block'
}}>
{formatPercent(holding.unrealized_pnl_percent)}
@@ -543,18 +620,23 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Allocation Summary */}
<div>
<div style={{
- ...COMMON_STYLES.sectionHeader,
- color: FINCEPT.ORANGE,
- borderBottom: BORDERS.ORANGE,
- marginBottom: SPACING.DEFAULT,
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: `1px solid ${colors.primary}`,
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '12px',
}}>
- ALLOCATION BREAKDOWN
+ {t('analytics.allocationBreakdown', 'ALLOCATION BREAKDOWN')}
</div>
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))',
- gap: SPACING.MEDIUM
+ gap: '8px'
}}>
{portfolioSummary.holdings.map(holding => (
<div
@@ -562,11 +644,11 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
onMouseEnter={() => setHoveredAllocation(holding.id)}
onMouseLeave={() => setHoveredAllocation(null)}
style={{
- padding: SPACING.MEDIUM,
- backgroundColor: hoveredAllocation === holding.id ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ padding: '8px',
+ backgroundColor: hoveredAllocation === holding.id ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD,
+ transition: 'all 0.2s ease',
cursor: 'default'
}}
>
@@ -574,41 +656,46 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
- marginBottom: SPACING.SMALL
+ marginBottom: '4px'
}}>
- <span style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.small, fontWeight: 700 }}>
{holding.symbol}
</span>
- <span style={{ color: FINCEPT.YELLOW, fontSize: '10px', fontWeight: 700 }}>
+ <span style={{ color: 'var(--ft-color-warning, #FFD700)', fontSize: fontSize.small, fontWeight: 700 }}>
{holding.weight.toFixed(1)}%
</span>
</div>
<div style={{
width: '100%',
height: '4px',
- backgroundColor: FINCEPT.BORDER,
+ backgroundColor: 'var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
overflow: 'hidden'
}}>
<div style={{
width: `${holding.weight}%`,
height: '100%',
- backgroundColor: FINCEPT.YELLOW,
+ backgroundColor: 'var(--ft-color-warning, #FFD700)',
transition: 'width 0.3s',
borderRadius: '2px'
}} />
</div>
<div style={{
- marginTop: SPACING.SMALL,
+ marginTop: '4px',
display: 'flex',
justifyContent: 'space-between',
- fontSize: '9px',
- color: FINCEPT.GRAY,
+ fontSize: fontSize.tiny,
+ color: colors.textMuted,
letterSpacing: '0.5px'
}}>
<span>{formatLargeNumber(holding.market_value, currency)}</span>
<span style={{
- ...(holding.unrealized_pnl >= 0 ? COMMON_STYLES.badgeSuccess : COMMON_STYLES.badgeError),
+ padding: '2px 6px',
+ backgroundColor: holding.unrealized_pnl >= 0 ? `${colors.success}20` : `${colors.alert}20`,
+ color: holding.unrealized_pnl >= 0 ? colors.success : colors.alert,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
}}>
{formatPercent(holding.unrealized_pnl_percent)}
</span>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/HistoryView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/HistoryView.tsx
index 42f36ae73..af3304172 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/HistoryView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/HistoryView.tsx
@@ -1,7 +1,8 @@
import React from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { Transaction } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatNumber, formatDateTime } from './utils';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS, COMMON_STYLES } from '../finceptStyles';
interface HistoryViewProps {
transactions: Transaction[];
@@ -9,31 +10,47 @@ interface HistoryViewProps {
}
const HistoryView: React.FC<HistoryViewProps> = ({ transactions, currency }) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+
return (
<div style={{
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: FINCEPT.DARK_BG,
+ backgroundColor: colors.background,
overflow: 'hidden',
- fontFamily: TYPOGRAPHY.MONO,
+ fontFamily,
}}>
{/* Section Header */}
<div style={{
- ...COMMON_STYLES.sectionHeader,
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
marginBottom: '0px',
}}>
- TRANSACTION HISTORY
+ {t('history.transactionHistory', 'TRANSACTION HISTORY')}
</div>
{transactions.length === 0 ? (
<div style={{
- ...COMMON_STYLES.emptyState,
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
padding: '24px',
height: 'auto',
flex: 1,
+ color: '#4A4A4A',
+ fontSize: fontSize.small,
+ textAlign: 'center',
}}>
- No transactions yet
+ {t('history.noTransactions', 'No transactions yet')}
</div>
) : (
<div style={{ flex: 1, overflow: 'auto' }}>
@@ -43,22 +60,22 @@ const HistoryView: React.FC<HistoryViewProps> = ({ transactions, currency }) =>
gridTemplateColumns: '1.5fr 1fr 0.8fr 1fr 1fr 1fr 2fr',
gap: '8px',
padding: '8px 12px',
- backgroundColor: FINCEPT.HEADER_BG,
- fontSize: '9px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
- borderBottom: `1px solid ${FINCEPT.ORANGE}`,
+ borderBottom: `1px solid ${colors.primary}`,
position: 'sticky',
top: 0,
zIndex: 1,
}}>
- <div style={{ color: FINCEPT.ORANGE }}>DATE</div>
- <div style={{ color: FINCEPT.ORANGE }}>SYMBOL</div>
- <div style={{ color: FINCEPT.ORANGE }}>TYPE</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>QTY</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>PRICE</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>TOTAL</div>
- <div style={{ color: FINCEPT.ORANGE }}>NOTES</div>
+ <div style={{ color: colors.primary }}>{t('history.date', 'DATE')}</div>
+ <div style={{ color: colors.primary }}>{t('history.symbol', 'SYMBOL')}</div>
+ <div style={{ color: colors.primary }}>{t('history.type', 'TYPE')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('history.qty', 'QTY')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('history.price', 'PRICE')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('history.total', 'TOTAL')}</div>
+ <div style={{ color: colors.primary }}>{t('history.notes', 'NOTES')}</div>
</div>
{/* Transaction Rows */}
@@ -71,26 +88,26 @@ const HistoryView: React.FC<HistoryViewProps> = ({ transactions, currency }) =>
gap: '8px',
padding: '8px 12px',
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent',
- borderLeft: `3px solid ${txn.transaction_type === 'BUY' ? FINCEPT.GREEN : FINCEPT.RED}`,
- fontSize: '10px',
+ borderLeft: `3px solid ${txn.transaction_type === 'BUY' ? colors.success : colors.alert}`,
+ fontSize: fontSize.small,
marginBottom: '1px',
- fontFamily: TYPOGRAPHY.MONO,
+ fontFamily,
minHeight: '32px',
alignItems: 'center',
- transition: EFFECTS.TRANSITION_STANDARD,
+ transition: 'all 0.2s ease',
}}
- onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = FINCEPT.HOVER; }}
+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = 'var(--ft-color-hover, #1F1F1F)'; }}
onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent'; }}
>
- <div style={{ color: FINCEPT.GRAY }}>
+ <div style={{ color: colors.textMuted }}>
{formatDateTime(txn.transaction_date)}
</div>
- <div style={{ color: FINCEPT.CYAN, fontWeight: 600 }}>{txn.symbol}</div>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', fontWeight: 600 }}>{txn.symbol}</div>
<div>
<span style={{
padding: '2px 6px',
- backgroundColor: txn.transaction_type === 'BUY' ? `${FINCEPT.GREEN}20` : `${FINCEPT.RED}20`,
- color: txn.transaction_type === 'BUY' ? FINCEPT.GREEN : FINCEPT.RED,
+ backgroundColor: txn.transaction_type === 'BUY' ? `${colors.success}20` : `${colors.alert}20`,
+ color: txn.transaction_type === 'BUY' ? colors.success : colors.alert,
fontSize: '8px',
fontWeight: 700,
borderRadius: '2px',
@@ -98,12 +115,12 @@ const HistoryView: React.FC<HistoryViewProps> = ({ transactions, currency }) =>
{txn.transaction_type}
</span>
</div>
- <div style={{ color: FINCEPT.CYAN, textAlign: 'right' }}>{formatNumber(txn.quantity, 4)}</div>
- <div style={{ color: FINCEPT.CYAN, textAlign: 'right' }}>{formatCurrency(txn.price, currency)}</div>
- <div style={{ color: FINCEPT.YELLOW, textAlign: 'right', fontWeight: 600 }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', textAlign: 'right' }}>{formatNumber(txn.quantity, 4)}</div>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', textAlign: 'right' }}>{formatCurrency(txn.price, currency)}</div>
+ <div style={{ color: 'var(--ft-color-warning, #FFD700)', textAlign: 'right', fontWeight: 600 }}>
{formatCurrency(txn.total_value, currency)}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>{txn.notes || '-'}</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>{txn.notes || '-'}</div>
</div>
))}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PerformanceView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PerformanceView.tsx
index 1b34b5459..48c59cd42 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PerformanceView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PerformanceView.tsx
@@ -1,7 +1,8 @@
import React, { useState, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { PortfolioSummary, portfolioService, PortfolioSnapshot } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatPercent } from './utils';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS, COMMON_STYLES } from '../finceptStyles';
interface PerformanceViewProps {
portfolioSummary: PortfolioSummary;
@@ -14,9 +15,9 @@ interface PerformanceDataPoint {
changePercent: number;
}
-const FONT_FAMILY = TYPOGRAPHY.MONO;
-
const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const currency = portfolioSummary.portfolio.currency;
const [performanceData, setPerformanceData] = useState<PerformanceDataPoint[]>([]);
const [loading, setLoading] = useState(true);
@@ -86,15 +87,15 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
return (
<div style={{
height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.XLARGE,
+ backgroundColor: colors.background,
+ padding: '24px',
textAlign: 'center',
- fontFamily: FONT_FAMILY
+ fontFamily
}}>
- <div style={{ color: FINCEPT.ORANGE, fontSize: '11px', fontWeight: 700, marginBottom: SPACING.SMALL }}>
- Loading performance data...
+ <div style={{ color: colors.primary, fontSize: fontSize.tiny, fontWeight: 700, marginBottom: '8px' }}>
+ {t('performance.loading')}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
Fetching portfolio snapshots from database
</div>
</div>
@@ -105,15 +106,15 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
return (
<div style={{
height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.XLARGE,
+ backgroundColor: colors.background,
+ padding: '24px',
textAlign: 'center',
- fontFamily: FONT_FAMILY
+ fontFamily
}}>
- <div style={{ color: FINCEPT.GRAY, fontSize: '11px', fontWeight: 700, marginBottom: SPACING.SMALL }}>
- No performance data available
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, marginBottom: '8px' }}>
+ {t('performance.noData')}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
Portfolio snapshots will be created automatically as you use the application
</div>
</div>
@@ -167,40 +168,48 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
return (
<div style={{
height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.DEFAULT,
+ backgroundColor: colors.background,
+ padding: '12px',
overflow: 'auto',
- fontFamily: FONT_FAMILY
+ fontFamily
}}>
<div style={{
- ...COMMON_STYLES.sectionHeader,
- marginBottom: SPACING.LARGE
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '16px',
}}>
- PERFORMANCE CHART ({performanceData.length} DAY{performanceData.length > 1 ? 'S' : ''})
+ {t('performance.performanceChart')} ({performanceData.length} DAY{performanceData.length > 1 ? 'S' : ''})
</div>
{/* Performance Metrics Bar */}
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(5, 1fr)',
- gap: SPACING.DEFAULT,
- marginBottom: SPACING.LARGE
+ gap: '12px',
+ marginBottom: '16px'
}}>
<div style={{
- ...COMMON_STYLES.metricCard,
+ padding: '12px',
+ backgroundColor: colors.panel,
borderRadius: '2px',
- border: periodReturn >= 0 ? BORDERS.GREEN : BORDERS.RED
+ border: `1px solid ${periodReturn >= 0 ? colors.success : colors.alert}`
}}>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const
- }}>PERIOD RETURN</div>
+ }}>{t('performance.totalReturn')}</div>
<div style={{
- color: periodReturn >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: '10px',
+ color: periodReturn >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.small,
fontWeight: 700
}}>
{formatPercent(periodReturn)}
@@ -208,20 +217,21 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
</div>
<div style={{
- ...COMMON_STYLES.metricCard,
+ padding: '12px',
+ backgroundColor: colors.panel,
borderRadius: '2px',
- border: periodGain >= 0 ? BORDERS.GREEN : BORDERS.RED
+ border: `1px solid ${periodGain >= 0 ? colors.success : colors.alert}`
}}>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const
- }}>PERIOD GAIN</div>
+ }}>{t('performance.dayChange')}</div>
<div style={{
- color: periodGain >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: '10px',
+ color: periodGain >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.small,
fontWeight: 700
}}>
{formatCurrency(periodGain, currency)}
@@ -229,20 +239,21 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
</div>
<div style={{
- ...COMMON_STYLES.metricCard,
+ padding: '12px',
+ backgroundColor: colors.panel,
borderRadius: '2px',
- border: `1px solid ${FINCEPT.YELLOW}`
+ border: `1px solid var(--ft-color-warning, #FFD700)`
}}>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const
}}>CURRENT VALUE</div>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '10px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.small,
fontWeight: 700
}}>
{formatCurrency(latestValue, currency)}
@@ -250,20 +261,21 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
</div>
<div style={{
- ...COMMON_STYLES.metricCard,
+ padding: '12px',
+ backgroundColor: colors.panel,
borderRadius: '2px',
- border: BORDERS.CYAN
+ border: `1px solid var(--ft-color-accent, #00E5FF)`
}}>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const
}}>START VALUE</div>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '10px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.small,
fontWeight: 700
}}>
{formatCurrency(earliestValue, currency)}
@@ -271,20 +283,21 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
</div>
<div style={{
- ...COMMON_STYLES.metricCard,
+ padding: '12px',
+ backgroundColor: colors.panel,
borderRadius: '2px',
- border: BORDERS.ORANGE
+ border: `1px solid ${colors.primary}`
}}>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const
}}>VOLATILITY</div>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '10px',
+ color: colors.primary,
+ fontSize: fontSize.small,
fontWeight: 700
}}>
{((valueRange / earliestValue) * 100).toFixed(2)}%
@@ -294,11 +307,11 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
{/* Chart */}
<div style={{
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ backgroundColor: colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
- padding: SPACING.DEFAULT,
- marginBottom: SPACING.LARGE
+ padding: '12px',
+ marginBottom: '16px'
}}>
<svg width={chartWidth} height={chartHeight}>
{/* Grid lines */}
@@ -312,7 +325,7 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
y1={y}
x2={chartWidth - padding.right}
y2={y}
- stroke={FINCEPT.BORDER}
+ stroke="var(--ft-color-border, #2A2A2A)"
strokeWidth="0.5"
strokeDasharray="4,4"
opacity="0.3"
@@ -321,9 +334,9 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
x={padding.left - 10}
y={y + 4}
textAnchor="end"
- fill={FINCEPT.GRAY}
+ fill={colors.textMuted}
fontSize="9"
- fontFamily={FONT_FAMILY}
+ fontFamily={fontFamily}
>
{formatCurrency(value, currency)}
</text>
@@ -341,9 +354,9 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
x={x}
y={chartHeight - padding.bottom + 20}
textAnchor="middle"
- fill={FINCEPT.GRAY}
+ fill={colors.textMuted}
fontSize="8"
- fontFamily={FONT_FAMILY}
+ fontFamily={fontFamily}
>
{d.date.substring(5)}
</text>
@@ -353,7 +366,7 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
{/* Area fill */}
<path
d={areaPath}
- fill={periodReturn >= 0 ? FINCEPT.GREEN : FINCEPT.RED}
+ fill={periodReturn >= 0 ? colors.success : colors.alert}
opacity="0.1"
/>
@@ -361,7 +374,7 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
<path
d={linePath}
fill="none"
- stroke={periodReturn >= 0 ? FINCEPT.GREEN : FINCEPT.RED}
+ stroke={periodReturn >= 0 ? colors.success : colors.alert}
strokeWidth="2"
/>
@@ -372,8 +385,8 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
cx={xScale(i)}
cy={yScale(d.value)}
r="3"
- fill={d.changePercent >= 0 ? FINCEPT.GREEN : FINCEPT.RED}
- stroke={FINCEPT.DARK_BG}
+ fill={d.changePercent >= 0 ? colors.success : colors.alert}
+ stroke={colors.background}
strokeWidth="1"
/>
))}
@@ -384,7 +397,7 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
y1={yScale(portfolioSummary.total_cost_basis)}
x2={chartWidth - padding.right}
y2={yScale(portfolioSummary.total_cost_basis)}
- stroke={FINCEPT.YELLOW}
+ stroke="var(--ft-color-warning, #FFD700)"
strokeWidth="2"
strokeDasharray="8,4"
/>
@@ -392,10 +405,10 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
x={chartWidth - padding.right - 10}
y={yScale(portfolioSummary.total_cost_basis) - 8}
textAnchor="end"
- fill={FINCEPT.YELLOW}
+ fill="var(--ft-color-warning, #FFD700)"
fontSize="10"
fontWeight="bold"
- fontFamily={FONT_FAMILY}
+ fontFamily={fontFamily}
>
COST BASIS
</text>
@@ -405,26 +418,26 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
x={chartWidth / 2}
y={15}
textAnchor="middle"
- fill={FINCEPT.ORANGE}
+ fill={colors.primary}
fontSize="12"
fontWeight="bold"
- fontFamily={FONT_FAMILY}
+ fontFamily={fontFamily}
>
- PORTFOLIO VALUE OVER TIME
+ {t('performance.portfolioValue')}
</text>
</svg>
</div>
{/* Performance Table */}
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '9px',
+ color: colors.primary,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const,
- marginBottom: SPACING.SMALL,
- paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.ORANGE
+ marginBottom: '8px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${colors.primary}`
}}>
DAILY PERFORMANCE DATA
</div>
@@ -434,21 +447,21 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
<div style={{
display: 'grid',
gridTemplateColumns: '1fr 1.2fr 1fr 1fr',
- gap: SPACING.SMALL,
- padding: SPACING.SMALL,
- backgroundColor: FINCEPT.HEADER_BG,
- fontSize: '9px',
+ gap: '8px',
+ padding: '8px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
position: 'sticky',
top: 0,
zIndex: 1,
- borderBottom: BORDERS.ORANGE
+ borderBottom: `1px solid ${colors.primary}`
}}>
- <div style={{ color: FINCEPT.ORANGE }}>DATE</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>VALUE</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>CHANGE</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>CHANGE %</div>
+ <div style={{ color: colors.primary }}>DATE</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>VALUE</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>CHANGE</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>CHANGE %</div>
</div>
{/* Table Rows */}
@@ -460,33 +473,33 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
style={{
display: 'grid',
gridTemplateColumns: '1fr 1.2fr 1fr 1fr',
- gap: SPACING.SMALL,
- padding: SPACING.SMALL,
+ gap: '8px',
+ padding: '8px',
backgroundColor: hoveredRow === index
- ? FINCEPT.HOVER
+ ? 'var(--ft-color-hover, #1F1F1F)'
: index % 2 === 0
? 'rgba(255,255,255,0.03)'
: 'transparent',
- borderLeft: `3px solid ${d.changePercent >= 0 ? FINCEPT.GREEN : FINCEPT.RED}`,
- fontSize: '10px',
+ borderLeft: `3px solid ${d.changePercent >= 0 ? colors.success : colors.alert}`,
+ fontSize: fontSize.tiny,
marginBottom: '2px',
- transition: EFFECTS.TRANSITION_STANDARD,
+ transition: 'all 0.2s ease',
cursor: 'default'
}}
>
- <div style={{ color: FINCEPT.GRAY }}>{d.date}</div>
- <div style={{ color: FINCEPT.CYAN, textAlign: 'right', fontWeight: 700 }}>
+ <div style={{ color: colors.textMuted }}>{d.date}</div>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', textAlign: 'right', fontWeight: 700 }}>
{formatCurrency(d.value, currency)}
</div>
<div style={{
- color: d.change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ color: d.change >= 0 ? colors.success : colors.alert,
textAlign: 'right',
fontWeight: 700
}}>
{formatCurrency(d.change, currency)}
</div>
<div style={{
- color: d.changePercent >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ color: d.changePercent >= 0 ? colors.success : colors.alert,
textAlign: 'right',
fontWeight: 700
}}>
@@ -499,15 +512,15 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
{/* Info Note */}
{performanceData.length < 7 && (
<div style={{
- marginTop: SPACING.DEFAULT,
- padding: SPACING.MEDIUM,
+ marginTop: '12px',
+ padding: '12px',
backgroundColor: 'rgba(255,136,0,0.05)',
- border: BORDERS.ORANGE,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px',
- fontSize: '10px',
- color: FINCEPT.GRAY
+ fontSize: fontSize.tiny,
+ color: colors.textMuted
}}>
- <strong style={{ color: FINCEPT.ORANGE }}>TIP:</strong> Portfolio snapshots are created automatically.
+ <strong style={{ color: colors.primary }}>TIP:</strong> Portfolio snapshots are created automatically.
More historical data will be available as you continue to use the application.
Current data points: {performanceData.length}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsx
index 9fb230d96..c9a765b3e 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsx
@@ -1,13 +1,17 @@
import React from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { PortfolioSummary } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatNumber, formatPercent } from './utils';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS, COMMON_STYLES } from '../finceptStyles';
+import { COMMON_STYLES } from '../finceptStyles';
interface PositionsViewProps {
portfolioSummary: PortfolioSummary;
}
const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const currency = portfolioSummary.portfolio.currency;
return (
@@ -15,16 +19,23 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: FINCEPT.DARK_BG,
+ backgroundColor: colors.background,
overflow: 'hidden',
- fontFamily: TYPOGRAPHY.MONO,
+ fontFamily,
}}>
{/* Section Header */}
<div style={{
- ...COMMON_STYLES.sectionHeader,
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
marginBottom: '0px',
}}>
- CURRENT POSITIONS
+ {t('positions.currentPositions', 'CURRENT POSITIONS')}
</div>
{/* Table Container */}
@@ -35,34 +46,40 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr 1fr 1fr 1.2fr 1fr',
gap: '8px',
padding: '8px 12px',
- backgroundColor: FINCEPT.HEADER_BG,
- fontSize: '9px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
- borderBottom: `1px solid ${FINCEPT.ORANGE}`,
+ borderBottom: `1px solid ${colors.primary}`,
position: 'sticky',
top: 0,
zIndex: 1,
}}>
- <div style={{ color: FINCEPT.ORANGE }}>SYMBOL</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>QTY</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>AVG PRICE</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>CURRENT</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>MKT VALUE</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>COST BASIS</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>P&L</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>DAY CHANGE</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>WEIGHT</div>
+ <div style={{ color: colors.primary }}>{t('positions.symbol', 'SYMBOL')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('positions.qty', 'QTY')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('positions.avgPrice', 'AVG PRICE')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('positions.current', 'CURRENT')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('positions.mktValue', 'MKT VALUE')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('positions.costBasis', 'COST BASIS')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('positions.pnl', 'P&L')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('positions.dayChange', 'DAY CHANGE')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('positions.weight', 'WEIGHT')}</div>
</div>
{/* Position Rows */}
{portfolioSummary.holdings.length === 0 ? (
<div style={{
- ...COMMON_STYLES.emptyState,
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
padding: '24px',
height: 'auto',
+ color: '#4A4A4A',
+ fontSize: fontSize.small,
+ textAlign: 'center',
}}>
- No positions yet. Click BUY to add your first position.
+ {t('positions.noPositions', 'No positions yet. Click BUY to add your first position.')}
</div>
) : (
portfolioSummary.holdings.map((holding, index) => (
@@ -74,53 +91,53 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
gap: '8px',
padding: '8px 12px',
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent',
- borderLeft: `3px solid ${holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED}`,
- fontSize: '10px',
+ borderLeft: `3px solid ${holding.unrealized_pnl >= 0 ? colors.success : colors.alert}`,
+ fontSize: fontSize.small,
marginBottom: '1px',
- fontFamily: TYPOGRAPHY.MONO,
+ fontFamily,
minHeight: '32px',
alignItems: 'center',
- transition: EFFECTS.TRANSITION_STANDARD,
+ transition: 'all 0.2s ease',
}}
- onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = FINCEPT.HOVER; }}
+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = 'var(--ft-color-hover, #1F1F1F)'; }}
onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent'; }}
>
- <div style={{ color: FINCEPT.CYAN, fontWeight: 700 }}>{holding.symbol}</div>
- <div style={{ color: FINCEPT.CYAN, textAlign: 'right' }}>{formatNumber(holding.quantity, 4)}</div>
- <div style={{ color: FINCEPT.GRAY, textAlign: 'right' }}>{formatCurrency(holding.avg_buy_price, currency)}</div>
- <div style={{ color: FINCEPT.CYAN, textAlign: 'right' }}>{formatCurrency(holding.current_price, currency)}</div>
- <div style={{ color: FINCEPT.WHITE, textAlign: 'right', fontWeight: 600 }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', fontWeight: 700 }}>{holding.symbol}</div>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', textAlign: 'right' }}>{formatNumber(holding.quantity, 4)}</div>
+ <div style={{ color: colors.textMuted, textAlign: 'right' }}>{formatCurrency(holding.avg_buy_price, currency)}</div>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', textAlign: 'right' }}>{formatCurrency(holding.current_price, currency)}</div>
+ <div style={{ color: colors.text, textAlign: 'right', fontWeight: 600 }}>
{formatCurrency(holding.market_value, currency)}
</div>
- <div style={{ color: FINCEPT.GRAY, textAlign: 'right' }}>{formatCurrency(holding.cost_basis, currency)}</div>
+ <div style={{ color: colors.textMuted, textAlign: 'right' }}>{formatCurrency(holding.cost_basis, currency)}</div>
<div style={{ textAlign: 'right' }}>
<div style={{
- color: holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ color: holding.unrealized_pnl >= 0 ? colors.success : colors.alert,
fontWeight: 600,
}}>
{holding.unrealized_pnl >= 0 ? '+' : ''}{formatCurrency(holding.unrealized_pnl, currency)}
</div>
<div style={{
- color: holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: '9px',
+ color: holding.unrealized_pnl >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.tiny,
}}>
{formatPercent(holding.unrealized_pnl_percent)}
</div>
</div>
<div style={{ textAlign: 'right' }}>
<div style={{
- color: holding.day_change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ color: holding.day_change >= 0 ? colors.success : colors.alert,
}}>
{holding.day_change >= 0 ? '+' : ''}{formatCurrency(holding.day_change, currency)}
</div>
<div style={{
- color: holding.day_change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: '9px',
+ color: holding.day_change >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.tiny,
}}>
{formatPercent(holding.day_change_percent)}
</div>
</div>
- <div style={{ color: FINCEPT.YELLOW, textAlign: 'right', fontWeight: 600 }}>
+ <div style={{ color: 'var(--ft-color-warning, #FFD700)', textAlign: 'right', fontWeight: 600 }}>
{formatNumber(holding.weight)}%
</div>
</div>
@@ -134,52 +151,52 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr 1fr 1fr 1.2fr 1fr',
gap: '8px',
padding: '8px 12px',
- backgroundColor: FINCEPT.PANEL_BG,
- borderTop: `2px solid ${FINCEPT.ORANGE}`,
- fontSize: '10px',
+ backgroundColor: colors.panel,
+ borderTop: `2px solid ${colors.primary}`,
+ fontSize: fontSize.small,
fontWeight: 700,
marginTop: '8px',
- fontFamily: TYPOGRAPHY.MONO,
+ fontFamily,
minHeight: '36px',
alignItems: 'center',
}}>
- <div style={{ color: FINCEPT.ORANGE }}>TOTAL</div>
+ <div style={{ color: colors.primary }}>{t('positions.total', 'TOTAL')}</div>
<div></div>
<div></div>
<div></div>
- <div style={{ color: FINCEPT.WHITE, textAlign: 'right' }}>
+ <div style={{ color: colors.text, textAlign: 'right' }}>
{formatCurrency(portfolioSummary.total_market_value, currency)}
</div>
- <div style={{ color: FINCEPT.GRAY, textAlign: 'right' }}>
+ <div style={{ color: colors.textMuted, textAlign: 'right' }}>
{formatCurrency(portfolioSummary.total_cost_basis, currency)}
</div>
<div style={{ textAlign: 'right' }}>
<div style={{
- color: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ color: portfolioSummary.total_unrealized_pnl >= 0 ? colors.success : colors.alert,
}}>
{portfolioSummary.total_unrealized_pnl >= 0 ? '+' : ''}{formatCurrency(portfolioSummary.total_unrealized_pnl, currency)}
</div>
<div style={{
- color: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: '9px',
+ color: portfolioSummary.total_unrealized_pnl >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.tiny,
}}>
{formatPercent(portfolioSummary.total_unrealized_pnl_percent)}
</div>
</div>
<div style={{ textAlign: 'right' }}>
<div style={{
- color: portfolioSummary.total_day_change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ color: portfolioSummary.total_day_change >= 0 ? colors.success : colors.alert,
}}>
{portfolioSummary.total_day_change >= 0 ? '+' : ''}{formatCurrency(portfolioSummary.total_day_change, currency)}
</div>
<div style={{
- color: portfolioSummary.total_day_change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: '9px',
+ color: portfolioSummary.total_day_change >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.tiny,
}}>
{formatPercent(portfolioSummary.total_day_change_percent)}
</div>
</div>
- <div style={{ color: FINCEPT.YELLOW, textAlign: 'right' }}>100.0%</div>
+ <div style={{ color: 'var(--ft-color-warning, #FFD700)', textAlign: 'right' }}>100.0%</div>
</div>
)}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ReportsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ReportsView.tsx
index 9c2ee20f7..87d85ceb0 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ReportsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ReportsView.tsx
@@ -1,7 +1,8 @@
import React from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { PortfolioSummary, Transaction } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatPercent, calculateTaxLiability } from './utils';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, EFFECTS } from '../finceptStyles';
interface ReportsViewProps {
portfolioSummary: PortfolioSummary;
@@ -9,6 +10,8 @@ interface ReportsViewProps {
}
const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transactions }) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const currency = portfolioSummary.portfolio.currency;
// Calculate tax liability
@@ -24,133 +27,144 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
return (
<div style={{
height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.DEFAULT,
+ backgroundColor: colors.background,
+ padding: '12px',
overflow: 'auto',
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
<div style={{
- ...COMMON_STYLES.sectionHeader,
- marginBottom: SPACING.LARGE
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '16px',
}}>
- TAX REPORTS & STATEMENTS
+ {t('reports.taxReports')}
</div>
{/* Summary Cards */}
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(4, 1fr)',
- gap: SPACING.DEFAULT,
- marginBottom: SPACING.XLARGE
+ gap: '12px',
+ marginBottom: '24px'
}}>
<div style={{
- ...COMMON_STYLES.metricCard,
- border: BORDERS.ORANGE,
+ padding: '12px',
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}>
<div style={{
- fontSize: '9px',
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const
- }}>TOTAL TAX LIABILITY</div>
+ }}>{t('reports.totalTaxLiability')}</div>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '15px',
+ color: colors.primary,
+ fontSize: fontSize.body,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
{formatCurrency(taxCalculation.totalTax, currency)}
</div>
</div>
<div style={{
- ...COMMON_STYLES.metricCard,
- border: BORDERS.GREEN,
+ padding: '12px',
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.success}`,
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}>
<div style={{
- fontSize: '9px',
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const
- }}>LONG-TERM GAINS</div>
+ }}>{t('reports.longTermGains')}</div>
<div style={{
- color: FINCEPT.GREEN,
- fontSize: '15px',
+ color: colors.success,
+ fontSize: fontSize.body,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
{formatCurrency(taxCalculation.longTermGains, currency)}
</div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
- marginTop: SPACING.TINY
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ marginTop: '4px'
}}>
Tax: {formatCurrency(taxCalculation.longTermTax, currency)}
</div>
</div>
<div style={{
- ...COMMON_STYLES.metricCard,
- border: `1px solid ${FINCEPT.YELLOW}`,
+ padding: '12px',
+ backgroundColor: colors.panel,
+ border: `1px solid var(--ft-color-warning, #FFD700)`,
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}>
<div style={{
- fontSize: '9px',
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const
- }}>SHORT-TERM GAINS</div>
+ }}>{t('reports.shortTermGains')}</div>
<div style={{
- color: FINCEPT.YELLOW,
- fontSize: '15px',
+ color: 'var(--ft-color-warning, #FFD700)',
+ fontSize: fontSize.body,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
{formatCurrency(taxCalculation.shortTermGains, currency)}
</div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
- marginTop: SPACING.TINY
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ marginTop: '4px'
}}>
Tax: {formatCurrency(taxCalculation.shortTermTax, currency)}
</div>
</div>
<div style={{
- ...COMMON_STYLES.metricCard,
- border: BORDERS.CYAN,
+ padding: '12px',
+ backgroundColor: colors.panel,
+ border: `1px solid var(--ft-color-accent, #00E5FF)`,
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}>
<div style={{
- fontSize: '9px',
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const
- }}>UNREALIZED GAINS</div>
+ }}>{t('reports.unrealizedGains')}</div>
<div style={{
- color: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: '15px',
+ color: portfolioSummary.total_unrealized_pnl >= 0 ? colors.success : colors.alert,
+ fontSize: fontSize.body,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
{formatCurrency(portfolioSummary.total_unrealized_pnl, currency)}
</div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
- marginTop: SPACING.TINY
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ marginTop: '4px'
}}>
Not taxable until sold
</div>
@@ -159,54 +173,61 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
{/* Tax Breakdown */}
<div style={{
- ...COMMON_STYLES.sectionHeader,
- marginBottom: SPACING.MEDIUM
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '12px',
}}>
- TAX BREAKDOWN (FIFO METHOD)
+ {t('reports.taxBreakdown')}
</div>
<div style={{
- padding: SPACING.DEFAULT,
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ padding: '12px',
+ backgroundColor: colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
- marginBottom: SPACING.XLARGE
+ marginBottom: '24px'
}}>
<div style={{
display: 'grid',
gridTemplateColumns: '2fr 1fr 1fr 1fr',
- gap: SPACING.MEDIUM,
- marginBottom: SPACING.MEDIUM,
- padding: SPACING.MEDIUM,
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: BORDERS.ORANGE,
+ gap: '12px',
+ marginBottom: '12px',
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: `1px solid ${colors.primary}`,
borderRadius: '2px'
}}>
- <div style={{ color: FINCEPT.ORANGE, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>CATEGORY</div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const, textAlign: 'right' }}>GAINS</div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const, textAlign: 'right' }}>TAX RATE</div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const, textAlign: 'right' }}>TAX DUE</div>
+ <div style={{ color: colors.primary, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>{t('reports.category')}</div>
+ <div style={{ color: colors.primary, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const, textAlign: 'right' }}>{t('reports.gains')}</div>
+ <div style={{ color: colors.primary, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const, textAlign: 'right' }}>{t('reports.taxRate')}</div>
+ <div style={{ color: colors.primary, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const, textAlign: 'right' }}>{t('reports.taxDue')}</div>
</div>
<div style={{
display: 'grid',
gridTemplateColumns: '2fr 1fr 1fr 1fr',
- gap: SPACING.MEDIUM,
- padding: SPACING.MEDIUM,
+ gap: '12px',
+ padding: '12px',
backgroundColor: 'rgba(255,215,0,0.05)',
- borderLeft: `3px solid ${FINCEPT.YELLOW}`,
+ borderLeft: `3px solid var(--ft-color-warning, #FFD700)`,
borderRadius: '2px',
- marginBottom: SPACING.SMALL,
- transition: EFFECTS.TRANSITION_STANDARD
+ marginBottom: '8px',
+ transition: 'all 0.2s ease'
}}>
- <div style={{ color: FINCEPT.YELLOW, fontSize: '10px', fontWeight: 700 }}>
+ <div style={{ color: 'var(--ft-color-warning, #FFD700)', fontSize: fontSize.tiny, fontWeight: 700 }}>
Short-Term Capital Gains (&lt; 1 year)
</div>
- <div style={{ color: FINCEPT.CYAN, fontSize: '10px', textAlign: 'right' }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.tiny, textAlign: 'right' }}>
{formatCurrency(taxCalculation.shortTermGains, currency)}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px', textAlign: 'right' }}>15%</div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: '10px', textAlign: 'right', fontWeight: 700 }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, textAlign: 'right' }}>15%</div>
+ <div style={{ color: colors.primary, fontSize: fontSize.tiny, textAlign: 'right', fontWeight: 700 }}>
{formatCurrency(taxCalculation.shortTermTax, currency)}
</div>
</div>
@@ -214,22 +235,22 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
display: 'grid',
gridTemplateColumns: '2fr 1fr 1fr 1fr',
- gap: SPACING.MEDIUM,
- padding: SPACING.MEDIUM,
+ gap: '12px',
+ padding: '12px',
backgroundColor: 'rgba(0,214,111,0.05)',
- borderLeft: `3px solid ${FINCEPT.GREEN}`,
+ borderLeft: `3px solid ${colors.success}`,
borderRadius: '2px',
- marginBottom: SPACING.SMALL,
- transition: EFFECTS.TRANSITION_STANDARD
+ marginBottom: '8px',
+ transition: 'all 0.2s ease'
}}>
- <div style={{ color: FINCEPT.GREEN, fontSize: '10px', fontWeight: 700 }}>
+ <div style={{ color: colors.success, fontSize: fontSize.tiny, fontWeight: 700 }}>
Long-Term Capital Gains (&gt; 1 year)
</div>
- <div style={{ color: FINCEPT.CYAN, fontSize: '10px', textAlign: 'right' }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.tiny, textAlign: 'right' }}>
{formatCurrency(taxCalculation.longTermGains, currency)}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px', textAlign: 'right' }}>20%</div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: '10px', textAlign: 'right', fontWeight: 700 }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, textAlign: 'right' }}>20%</div>
+ <div style={{ color: colors.primary, fontSize: fontSize.tiny, textAlign: 'right', fontWeight: 700 }}>
{formatCurrency(taxCalculation.longTermTax, currency)}
</div>
</div>
@@ -237,49 +258,56 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
display: 'grid',
gridTemplateColumns: '2fr 1fr 1fr 1fr',
- gap: SPACING.MEDIUM,
- padding: SPACING.MEDIUM,
+ gap: '12px',
+ padding: '12px',
backgroundColor: 'rgba(255,136,0,0.1)',
- borderTop: `2px solid ${FINCEPT.ORANGE}`,
+ borderTop: `2px solid ${colors.primary}`,
borderRadius: '2px',
- marginTop: SPACING.SMALL
+ marginTop: '8px'
}}>
- <div style={{ color: FINCEPT.ORANGE, fontSize: '11px', fontWeight: 700 }}>TOTAL TAX DUE</div>
+ <div style={{ color: colors.primary, fontSize: fontSize.tiny, fontWeight: 700 }}>{t('reports.totalTaxDue')}</div>
<div></div>
<div></div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: '13px', textAlign: 'right', fontWeight: 700 }}>
+ <div style={{ color: colors.primary, fontSize: fontSize.small, textAlign: 'right', fontWeight: 700 }}>
{formatCurrency(taxCalculation.totalTax, currency)}
</div>
</div>
</div>
{/* Additional Information */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.DEFAULT }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
{/* Transaction Summary */}
<div>
<div style={{
- ...COMMON_STYLES.sectionHeader,
- marginBottom: SPACING.MEDIUM
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '12px',
}}>
- TRANSACTION SUMMARY
+ {t('reports.transactionSummary')}
</div>
<div style={{
- padding: SPACING.DEFAULT,
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ padding: '12px',
+ backgroundColor: colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px'
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
- marginBottom: SPACING.SMALL,
- paddingBottom: SPACING.SMALL,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- transition: EFFECTS.TRANSITION_STANDARD
+ marginBottom: '8px',
+ paddingBottom: '8px',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ transition: 'all 0.2s ease'
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Total Transactions:</span>
- <span style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>{t('reports.totalTransactions')}</span>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.tiny, fontWeight: 700 }}>
{transactions.length}
</span>
</div>
@@ -287,13 +315,13 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
display: 'flex',
justifyContent: 'space-between',
- marginBottom: SPACING.SMALL,
- paddingBottom: SPACING.SMALL,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- transition: EFFECTS.TRANSITION_STANDARD
+ marginBottom: '8px',
+ paddingBottom: '8px',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ transition: 'all 0.2s ease'
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Buy Transactions:</span>
- <span style={{ color: FINCEPT.GREEN, fontSize: '10px', fontWeight: 700 }}>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>{t('reports.buyTransactions')}</span>
+ <span style={{ color: colors.success, fontSize: fontSize.tiny, fontWeight: 700 }}>
{transactions.filter(t => t.transaction_type === 'BUY').length}
</span>
</div>
@@ -301,13 +329,13 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
display: 'flex',
justifyContent: 'space-between',
- marginBottom: SPACING.SMALL,
- paddingBottom: SPACING.SMALL,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- transition: EFFECTS.TRANSITION_STANDARD
+ marginBottom: '8px',
+ paddingBottom: '8px',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ transition: 'all 0.2s ease'
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Sell Transactions:</span>
- <span style={{ color: FINCEPT.RED, fontSize: '10px', fontWeight: 700 }}>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>{t('reports.sellTransactions')}</span>
+ <span style={{ color: colors.alert, fontSize: fontSize.tiny, fontWeight: 700 }}>
{transactions.filter(t => t.transaction_type === 'SELL').length}
</span>
</div>
@@ -315,10 +343,10 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
display: 'flex',
justifyContent: 'space-between',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Current Positions:</span>
- <span style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>{t('reports.currentPositions')}</span>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.tiny, fontWeight: 700 }}>
{portfolioSummary.holdings.length}
</span>
</div>
@@ -328,28 +356,35 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
{/* Dividend Information */}
<div>
<div style={{
- ...COMMON_STYLES.sectionHeader,
- marginBottom: SPACING.MEDIUM
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '12px',
}}>
- DIVIDEND INCOME
+ {t('reports.dividendIncome')}
</div>
<div style={{
- padding: SPACING.DEFAULT,
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ padding: '12px',
+ backgroundColor: colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px'
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
- marginBottom: SPACING.SMALL,
- paddingBottom: SPACING.SMALL,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- transition: EFFECTS.TRANSITION_STANDARD
+ marginBottom: '8px',
+ paddingBottom: '8px',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ transition: 'all 0.2s ease'
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Total Dividends (YTD):</span>
- <span style={{ color: FINCEPT.GREEN, fontSize: '10px', fontWeight: 700 }}>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>{t('reports.totalDividends')}</span>
+ <span style={{ color: colors.success, fontSize: fontSize.tiny, fontWeight: 700 }}>
{formatCurrency(totalDividends, currency)}
</span>
</div>
@@ -357,10 +392,10 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
display: 'flex',
justifyContent: 'space-between',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Portfolio Yield:</span>
- <span style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.tiny, fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>{t('reports.portfolioYield')}</span>
+ <span style={{ color: 'var(--ft-color-accent, #00E5FF)', fontSize: fontSize.tiny, fontWeight: 700 }}>
{dividendYield.toFixed(2)}%
</span>
</div>
@@ -370,28 +405,36 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
{/* Export Options */}
<div style={{
- marginTop: SPACING.XLARGE,
- padding: SPACING.DEFAULT,
+ marginTop: '24px',
+ padding: '12px',
backgroundColor: 'rgba(255,136,0,0.05)',
- border: BORDERS.ORANGE,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px'
}}>
<div style={{
- fontSize: '9px',
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT.ORANGE,
+ color: colors.primary,
letterSpacing: '0.5px',
textTransform: 'uppercase' as const,
- marginBottom: SPACING.MEDIUM
+ marginBottom: '12px'
}}>
- EXPORT OPTIONS
+ {t('reports.exportOptions')}
</div>
- <div style={{ display: 'flex', gap: SPACING.MEDIUM }}>
+ <div style={{ display: 'flex', gap: '12px' }}>
<button style={{
- ...COMMON_STYLES.buttonPrimary,
- backgroundColor: FINCEPT.ORANGE,
- color: FINCEPT.DARK_BG
+ padding: '8px 16px',
+ backgroundColor: colors.primary,
+ color: colors.background,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = '0.85';
@@ -399,13 +442,21 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
onMouseLeave={(e) => {
e.currentTarget.style.opacity = '1';
}}>
- EXPORT TAX REPORT (PDF)
+ {t('reports.exportTaxReport')}
</button>
<button style={{
- ...COMMON_STYLES.buttonPrimary,
- backgroundColor: FINCEPT.GREEN,
- color: FINCEPT.DARK_BG
+ padding: '8px 16px',
+ backgroundColor: colors.success,
+ color: colors.background,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = '0.85';
@@ -413,13 +464,21 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
onMouseLeave={(e) => {
e.currentTarget.style.opacity = '1';
}}>
- EXPORT TRANSACTIONS (CSV)
+ {t('reports.exportTransactions')}
</button>
<button style={{
- ...COMMON_STYLES.buttonPrimary,
- backgroundColor: FINCEPT.CYAN,
- color: FINCEPT.DARK_BG
+ padding: '8px 16px',
+ backgroundColor: 'var(--ft-color-accent, #00E5FF)',
+ color: colors.background,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s ease',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = '0.85';
@@ -427,14 +486,14 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
onMouseLeave={(e) => {
e.currentTarget.style.opacity = '1';
}}>
- EXPORT HOLDINGS (XLSX)
+ {t('reports.exportHoldings')}
</button>
</div>
<div style={{
- marginTop: SPACING.MEDIUM,
- fontSize: '9px',
- color: FINCEPT.GRAY
+ marginTop: '12px',
+ fontSize: fontSize.tiny,
+ color: colors.textMuted
}}>
Reports are generated for the current tax year. Consult with a tax professional for accurate filing.
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/RiskMetricsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/RiskMetricsView.tsx
index 0e5aae065..6f8cbbd17 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/RiskMetricsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/RiskMetricsView.tsx
@@ -1,4 +1,6 @@
import React, { useState, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { PortfolioSummary, portfolioService } from '../../../../services/portfolio/portfolioService';
import {
formatPercent,
@@ -8,13 +10,14 @@ import {
calculateMaxDrawdown,
calculateVaR
} from './utils';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, EFFECTS } from '../finceptStyles';
interface RiskMetricsViewProps {
portfolioSummary: PortfolioSummary;
}
const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [loading, setLoading] = useState(true);
const [portfolioReturns, setPortfolioReturns] = useState<number[]>([]);
const [portfolioValues, setPortfolioValues] = useState<number[]>([]);
@@ -75,27 +78,27 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
// Risk level determination
const getRiskLevel = (sharpe: number) => {
- if (sharpe > 2) return { level: 'LOW', color: FINCEPT.GREEN };
- if (sharpe > 1) return { level: 'MODERATE', color: FINCEPT.YELLOW };
- if (sharpe > 0) return { level: 'HIGH', color: FINCEPT.ORANGE };
- return { level: 'VERY HIGH', color: FINCEPT.RED };
+ if (sharpe > 2) return { level: t('risk.low'), color: colors.success };
+ if (sharpe > 1) return { level: t('risk.moderate'), color: 'var(--ft-color-warning, #FFD700)' };
+ if (sharpe > 0) return { level: t('risk.high'), color: colors.primary };
+ return { level: t('risk.veryHigh'), color: colors.alert };
};
const riskLevel = getRiskLevel(sharpeRatio);
const getBetaRating = (beta: number) => {
- if (beta < 0.8) return { rating: 'DEFENSIVE', color: FINCEPT.BLUE };
- if (beta < 1.2) return { rating: 'NEUTRAL', color: FINCEPT.CYAN };
- return { rating: 'AGGRESSIVE', color: FINCEPT.ORANGE };
+ if (beta < 0.8) return { rating: t('risk.defensive'), color: 'var(--ft-color-blue, #3B82F6)' };
+ if (beta < 1.2) return { rating: t('risk.neutral'), color: 'var(--ft-color-accent, #00E5FF)' };
+ return { rating: t('risk.aggressive'), color: colors.primary };
};
const betaRating = getBetaRating(beta);
const getVolatilityRating = (vol: number) => {
- if (vol < 10) return { rating: 'LOW', color: FINCEPT.GREEN };
- if (vol < 20) return { rating: 'MODERATE', color: FINCEPT.YELLOW };
- if (vol < 30) return { rating: 'HIGH', color: FINCEPT.ORANGE };
- return { rating: 'VERY HIGH', color: FINCEPT.RED };
+ if (vol < 10) return { rating: t('risk.low'), color: colors.success };
+ if (vol < 20) return { rating: t('risk.moderate'), color: 'var(--ft-color-warning, #FFD700)' };
+ if (vol < 30) return { rating: t('risk.high'), color: colors.primary };
+ return { rating: t('risk.veryHigh'), color: colors.alert };
};
const volatilityRating = getVolatilityRating(volatility);
@@ -104,15 +107,15 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
return (
<div style={{
height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
+ backgroundColor: colors.background,
padding: '24px',
textAlign: 'center',
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
- <div style={{ color: FINCEPT.ORANGE, fontSize: '11px', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: fontSize.tiny, marginBottom: '4px' }}>
Loading risk metrics...
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
Calculating portfolio risk from historical data
</div>
</div>
@@ -122,20 +125,24 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
return (
<div style={{
height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
+ backgroundColor: colors.background,
padding: '12px',
overflow: 'auto',
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
<div style={{
- ...COMMON_STYLES.sectionHeader,
padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: BORDERS.STANDARD,
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
marginBottom: '16px',
borderRadius: '2px'
}}>
- RISK METRICS & ANALYTICS {hasInsufficientData && '(LIMITED DATA)'}
+ {t('risk.riskMetrics')} {hasInsufficientData && t('risk.limitedData')}
</div>
{hasInsufficientData && (
@@ -143,13 +150,13 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
padding: '8px',
marginBottom: '12px',
backgroundColor: 'rgba(255,136,0,0.1)',
- border: `1px solid ${FINCEPT.ORANGE}`,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px',
- fontSize: '10px',
- color: FINCEPT.ORANGE
+ fontSize: fontSize.tiny,
+ color: colors.primary
}}>
- [WARN] <strong>INSUFFICIENT HISTORICAL DATA:</strong> Risk metrics require at least 5 days of portfolio snapshots for accurate calculations.
- Current data points: {portfolioReturns.length}. Metrics shown are preliminary.
+ {t('risk.insufficientData')} {t('risk.insufficientDataDesc')}
+ {t('risk.currentDataPoints')} {portfolioReturns.length}. {t('risk.metricsShownPreliminary')}
</div>
)}
@@ -164,32 +171,32 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div
style={{
padding: '12px',
- backgroundColor: hoveredCard === 'risk' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ backgroundColor: hoveredCard === 'risk' ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
border: `2px solid ${riskLevel.color}`,
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}
onMouseEnter={() => setHoveredCard('risk')}
onMouseLeave={() => setHoveredCard(null)}
>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
marginBottom: '4px'
- }}>OVERALL RISK</div>
+ }}>{t('risk.overallRisk')}</div>
<div style={{
color: riskLevel.color,
- fontSize: '16px',
+ fontSize: fontSize.heading,
fontWeight: 700,
marginBottom: '2px'
}}>
{riskLevel.level}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>
- Based on Sharpe Ratio: {sharpeRatio.toFixed(2)}
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
+ {t('risk.sharpeRatio')}: {sharpeRatio.toFixed(2)}
</div>
</div>
@@ -197,32 +204,32 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div
style={{
padding: '12px',
- backgroundColor: hoveredCard === 'beta-overview' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ backgroundColor: hoveredCard === 'beta-overview' ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
border: `2px solid ${betaRating.color}`,
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}
onMouseEnter={() => setHoveredCard('beta-overview')}
onMouseLeave={() => setHoveredCard(null)}
>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
marginBottom: '4px'
- }}>MARKET SENSITIVITY</div>
+ }}>{t('risk.marketSensitivity')}</div>
<div style={{
color: betaRating.color,
- fontSize: '16px',
+ fontSize: fontSize.heading,
fontWeight: 700,
marginBottom: '2px'
}}>
{betaRating.rating}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>
- Beta: {beta.toFixed(2)}
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
+ {t('risk.beta')}: {beta.toFixed(2)}
</div>
</div>
@@ -230,31 +237,31 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div
style={{
padding: '12px',
- backgroundColor: hoveredCard === 'vol-overview' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ backgroundColor: hoveredCard === 'vol-overview' ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
border: `2px solid ${volatilityRating.color}`,
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}
onMouseEnter={() => setHoveredCard('vol-overview')}
onMouseLeave={() => setHoveredCard(null)}
>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: '9px',
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
marginBottom: '4px'
- }}>VOLATILITY</div>
+ }}>{t('risk.volatility')}</div>
<div style={{
color: volatilityRating.color,
- fontSize: '16px',
+ fontSize: fontSize.heading,
fontWeight: 700,
marginBottom: '2px'
}}>
{volatilityRating.rating}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
Annualized: {volatility.toFixed(2)}%
</div>
</div>
@@ -265,16 +272,16 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
{/* Left Column - Return Metrics */}
<div>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '11px',
+ color: colors.primary,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
marginBottom: '8px',
paddingBottom: '4px',
- borderBottom: `1px solid ${FINCEPT.ORANGE}`
+ borderBottom: `1px solid ${colors.primary}`
}}>
- RISK-ADJUSTED RETURNS
+ {t('risk.riskAdjustedReturns')}
</div>
{/* Sharpe Ratio */}
@@ -282,10 +289,10 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
style={{
padding: '8px',
marginBottom: '8px',
- backgroundColor: hoveredCard === 'sharpe' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ backgroundColor: hoveredCard === 'sharpe' ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}
onMouseEnter={() => setHoveredCard('sharpe')}
onMouseLeave={() => setHoveredCard(null)}
@@ -293,25 +300,25 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '10px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase'
- }}>SHARPE RATIO</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
+ }}>{t('risk.sharpeRatio')}</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, marginTop: '2px' }}>
Risk-adjusted return measure
</div>
</div>
<div style={{
- color: sharpeRatio > 1 ? FINCEPT.GREEN : sharpeRatio > 0 ? FINCEPT.YELLOW : FINCEPT.RED,
- fontSize: '16px',
+ color: sharpeRatio > 1 ? colors.success : sharpeRatio > 0 ? 'var(--ft-color-warning, #FFD700)' : colors.alert,
+ fontSize: fontSize.heading,
fontWeight: 700
}}>
{sharpeRatio.toFixed(3)}
</div>
</div>
- <div style={{ marginTop: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>
+ <div style={{ marginTop: '4px', fontSize: fontSize.tiny, color: colors.textMuted }}>
{'> 2: Excellent | 1-2: Good | 0-1: Fair | < 0: Poor'}
</div>
</div>
@@ -321,10 +328,10 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
style={{
padding: '8px',
marginBottom: '8px',
- backgroundColor: hoveredCard === 'beta' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ backgroundColor: hoveredCard === 'beta' ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}
onMouseEnter={() => setHoveredCard('beta')}
onMouseLeave={() => setHoveredCard(null)}
@@ -332,21 +339,21 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '10px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase'
- }}>BETA ({'\u03B2'})</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
+ }}>{t('risk.beta')} ({'\u03B2'})</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, marginTop: '2px' }}>
Market correlation coefficient
</div>
</div>
- <div style={{ color: betaRating.color, fontSize: '16px', fontWeight: 700 }}>
+ <div style={{ color: betaRating.color, fontSize: fontSize.heading, fontWeight: 700 }}>
{beta.toFixed(3)}
</div>
</div>
- <div style={{ marginTop: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>
+ <div style={{ marginTop: '4px', fontSize: fontSize.tiny, color: colors.textMuted }}>
{'< 1: Less volatile | 1: Market neutral | > 1: More volatile'}
</div>
</div>
@@ -355,10 +362,10 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div
style={{
padding: '8px',
- backgroundColor: hoveredCard === 'volatility' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ backgroundColor: hoveredCard === 'volatility' ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}
onMouseEnter={() => setHoveredCard('volatility')}
onMouseLeave={() => setHoveredCard(null)}
@@ -366,21 +373,21 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '10px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase'
- }}>VOLATILITY</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
+ }}>{t('risk.volatility')}</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, marginTop: '2px' }}>
Annualized standard deviation
</div>
</div>
- <div style={{ color: volatilityRating.color, fontSize: '16px', fontWeight: 700 }}>
+ <div style={{ color: volatilityRating.color, fontSize: fontSize.heading, fontWeight: 700 }}>
{volatility.toFixed(2)}%
</div>
</div>
- <div style={{ marginTop: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>
+ <div style={{ marginTop: '4px', fontSize: fontSize.tiny, color: colors.textMuted }}>
Lower volatility indicates more stable returns
</div>
</div>
@@ -389,16 +396,16 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
{/* Right Column - Risk Metrics */}
<div>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '11px',
+ color: colors.primary,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
marginBottom: '8px',
paddingBottom: '4px',
- borderBottom: `1px solid ${FINCEPT.ORANGE}`
+ borderBottom: `1px solid ${colors.primary}`
}}>
- DOWNSIDE RISK METRICS
+ {t('risk.downsideRiskMetrics')}
</div>
{/* Maximum Drawdown */}
@@ -406,10 +413,10 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
style={{
padding: '8px',
marginBottom: '8px',
- backgroundColor: hoveredCard === 'drawdown' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ backgroundColor: hoveredCard === 'drawdown' ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}
onMouseEnter={() => setHoveredCard('drawdown')}
onMouseLeave={() => setHoveredCard(null)}
@@ -417,25 +424,25 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '10px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase'
- }}>MAX DRAWDOWN</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
+ }}>{t('risk.maxDrawdown')}</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, marginTop: '2px' }}>
Largest peak-to-trough decline
</div>
</div>
<div style={{
- color: maxDrawdown > 20 ? FINCEPT.RED : maxDrawdown > 10 ? FINCEPT.ORANGE : FINCEPT.GREEN,
- fontSize: '16px',
+ color: maxDrawdown > 20 ? colors.alert : maxDrawdown > 10 ? colors.primary : colors.success,
+ fontSize: fontSize.heading,
fontWeight: 700
}}>
-{maxDrawdown.toFixed(2)}%
</div>
</div>
- <div style={{ marginTop: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>
+ <div style={{ marginTop: '4px', fontSize: fontSize.tiny, color: colors.textMuted }}>
Maximum loss from peak value
</div>
</div>
@@ -445,10 +452,10 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
style={{
padding: '8px',
marginBottom: '8px',
- backgroundColor: hoveredCard === 'var' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
+ backgroundColor: hoveredCard === 'var' ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}
onMouseEnter={() => setHoveredCard('var')}
onMouseLeave={() => setHoveredCard(null)}
@@ -456,25 +463,25 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '10px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase'
- }}>VALUE AT RISK (95%)</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
+ }}>{t('risk.valueAtRisk')}</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, marginTop: '2px' }}>
Expected loss at 95% confidence
</div>
</div>
<div style={{
- color: var95 < -0.03 ? FINCEPT.RED : var95 < -0.02 ? FINCEPT.ORANGE : FINCEPT.YELLOW,
- fontSize: '16px',
+ color: var95 < -0.03 ? colors.alert : var95 < -0.02 ? colors.primary : 'var(--ft-color-warning, #FFD700)',
+ fontSize: fontSize.heading,
fontWeight: 700
}}>
{(var95 * 100).toFixed(2)}%
</div>
</div>
- <div style={{ marginTop: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>
+ <div style={{ marginTop: '4px', fontSize: fontSize.tiny, color: colors.textMuted }}>
5% chance of losing more than this in a day
</div>
</div>
@@ -486,7 +493,7 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
backgroundColor: hoveredCard === 'composite' ? 'rgba(255,59,59,0.08)' : 'rgba(255,59,59,0.05)',
border: `2px solid ${riskLevel.color}`,
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD
+ transition: 'all 0.2s ease'
}}
onMouseEnter={() => setHoveredCard('composite')}
onMouseLeave={() => setHoveredCard(null)}
@@ -495,16 +502,16 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div>
<div style={{
color: riskLevel.color,
- fontSize: '10px',
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase'
- }}>COMPOSITE RISK SCORE</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
+ }}>{t('risk.compositeRiskScore')}</div>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.tiny, marginTop: '2px' }}>
Weighted risk assessment
</div>
</div>
- <div style={{ color: riskLevel.color, fontSize: '16px', fontWeight: 700 }}>
+ <div style={{ color: riskLevel.color, fontSize: fontSize.heading, fontWeight: 700 }}>
{((1 / (sharpeRatio + 1)) * 100).toFixed(0)}/100
</div>
</div>
@@ -512,7 +519,7 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div style={{
width: '100%',
height: '8px',
- backgroundColor: FINCEPT.HOVER,
+ backgroundColor: 'var(--ft-color-hover, #1F1F1F)',
borderRadius: '2px',
overflow: 'hidden'
}}>
@@ -532,25 +539,25 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div style={{
padding: '12px',
backgroundColor: 'rgba(255,136,0,0.05)',
- border: `1px solid ${FINCEPT.ORANGE}`,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px'
}}>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '11px',
+ color: colors.primary,
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
textTransform: 'uppercase',
marginBottom: '8px'
}}>
- RISK MANAGEMENT RECOMMENDATIONS
+ {t('risk.riskManagementRecommendations')}
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
{sharpeRatio < 1 && (
<div style={{
- fontSize: '10px',
- color: FINCEPT.WHITE,
+ fontSize: fontSize.tiny,
+ color: colors.text,
padding: '4px',
backgroundColor: 'rgba(255,59,59,0.1)',
borderRadius: '2px'
@@ -560,8 +567,8 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
)}
{beta > 1.5 && (
<div style={{
- fontSize: '10px',
- color: FINCEPT.WHITE,
+ fontSize: fontSize.tiny,
+ color: colors.text,
padding: '4px',
backgroundColor: 'rgba(255,136,0,0.1)',
borderRadius: '2px'
@@ -571,8 +578,8 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
)}
{volatility > 25 && (
<div style={{
- fontSize: '10px',
- color: FINCEPT.WHITE,
+ fontSize: fontSize.tiny,
+ color: colors.text,
padding: '4px',
backgroundColor: 'rgba(255,59,59,0.1)',
borderRadius: '2px'
@@ -582,8 +589,8 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
)}
{maxDrawdown > 20 && (
<div style={{
- fontSize: '10px',
- color: FINCEPT.WHITE,
+ fontSize: fontSize.tiny,
+ color: colors.text,
padding: '4px',
backgroundColor: 'rgba(255,59,59,0.1)',
borderRadius: '2px'
@@ -593,8 +600,8 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
)}
{sharpeRatio > 2 && (
<div style={{
- fontSize: '10px',
- color: FINCEPT.WHITE,
+ fontSize: fontSize.tiny,
+ color: colors.text,
padding: '4px',
backgroundColor: 'rgba(0,214,111,0.1)',
borderRadius: '2px'
@@ -604,8 +611,8 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
)}
{beta >= 0.8 && beta <= 1.2 && (
<div style={{
- fontSize: '10px',
- color: FINCEPT.WHITE,
+ fontSize: fontSize.tiny,
+ color: colors.text,
padding: '4px',
backgroundColor: 'rgba(0,229,255,0.1)',
borderRadius: '2px'
@@ -620,13 +627,13 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div style={{
marginTop: '12px',
padding: '8px',
- backgroundColor: FINCEPT.HOVER,
- border: BORDERS.STANDARD,
+ backgroundColor: 'var(--ft-color-hover, #1F1F1F)',
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px',
- fontSize: '9px',
- color: FINCEPT.GRAY
+ fontSize: fontSize.tiny,
+ color: colors.textMuted
}}>
- <strong style={{ color: FINCEPT.ORANGE }}>DISCLAIMER:</strong> Risk metrics are calculated from portfolio snapshot history.
+ <strong style={{ color: colors.primary }}>{t('risk.disclaimer')}</strong> Risk metrics are calculated from portfolio snapshot history.
{hasInsufficientData && ' More data points are needed for statistically significant results.'}
{' '}Beta calculations use portfolio returns as market proxy until real market benchmarks are integrated.
Past performance does not guarantee future results. Consult a financial advisor before making investment decisions.
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsx
index 2c9b8c976..fa06f0057 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsx
@@ -1,8 +1,9 @@
import React, { useMemo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { PortfolioSummary, PortfolioHolding } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatPercent } from './utils';
import { sectorService } from '../../../../services/data-sources/sectorService';
-import { FINCEPT, BORDERS, COMMON_STYLES, TYPOGRAPHY, EFFECTS } from '../finceptStyles';
interface SectorsViewProps {
portfolioSummary: PortfolioSummary;
@@ -18,6 +19,8 @@ interface SectorAllocation {
const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
+ const { t } = useTranslation('portfolio');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const currency = portfolioSummary.portfolio.currency;
const [sectorsLoaded, setSectorsLoaded] = useState(false);
const [, forceUpdate] = useState(0);
@@ -25,15 +28,15 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
const [hoveredHoldingRow, setHoveredHoldingRow] = useState<string | null>(null);
const [hoveredLegendRow, setHoveredLegendRow] = useState<string | null>(null);
- // Fincept color palette for sectors
+ // Theme-based color palette for sectors
const sectorColors = [
- FINCEPT.CYAN,
- FINCEPT.GREEN,
- FINCEPT.ORANGE,
- FINCEPT.PURPLE,
- FINCEPT.BLUE,
- FINCEPT.YELLOW,
- FINCEPT.RED
+ 'var(--ft-color-accent, #00E5FF)',
+ colors.success,
+ colors.primary,
+ 'var(--ft-color-purple, #A855F7)',
+ 'var(--ft-color-blue, #3B82F6)',
+ 'var(--ft-color-warning, #FFD700)',
+ colors.alert
];
// Prefetch sector data for all holdings
@@ -73,7 +76,7 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
color: sectorColors[index % sectorColors.length]
}))
.sort((a, b) => b.weight - a.weight);
- }, [portfolioSummary.holdings, portfolioSummary.total_market_value, sectorsLoaded]);
+ }, [portfolioSummary.holdings, portfolioSummary.total_market_value, sectorsLoaded, sectorColors]);
// Calculate pie chart angles
let currentAngle = 0;
@@ -112,35 +115,42 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
return (
<div style={{
height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
+ backgroundColor: colors.background,
padding: '12px',
overflow: 'auto',
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
{/* Section Header */}
<div style={{
- ...COMMON_STYLES.sectionHeader,
- marginBottom: '16px'
+ padding: '12px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ borderBottom: '1px solid var(--ft-color-border, #2A2A2A)',
+ color: colors.primary,
+ fontSize: fontSize.body,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
+ marginBottom: '16px',
}}>
- SECTOR ALLOCATION
+ {t('sectors.sectorAllocation')}
</div>
{!sectorsLoaded && portfolioSummary.holdings.length > 0 && (
<div style={{
padding: '8px',
marginBottom: '8px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.CYAN,
+ backgroundColor: colors.panel,
+ border: `1px solid var(--ft-color-accent, #00E5FF)`,
borderRadius: '2px',
- color: FINCEPT.CYAN,
- fontSize: '11px',
- fontFamily: TYPOGRAPHY.MONO,
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
+ fontFamily,
display: 'flex',
alignItems: 'center',
gap: '4px'
}}>
<span style={{ animation: 'pulse 1.5s infinite' }}>●</span>
- Loading sector data from API...
+ {t('sectors.loadingSectorData')}
</div>
)}
@@ -148,11 +158,11 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
<div style={{
padding: '24px',
textAlign: 'center',
- color: FINCEPT.GRAY,
- fontSize: '11px',
- fontFamily: TYPOGRAPHY.MONO
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontFamily
}}>
- No sector data available. Add holdings with sector information.
+ {t('sectors.noSectorData')}
</div>
) : (
<div style={{ display: 'grid', gridTemplateColumns: '400px 1fr', gap: '24px' }}>
@@ -169,7 +179,7 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
<path
d={createArc(sector.startAngle, sector.endAngle)}
fill={sector.color}
- stroke={FINCEPT.DARK_BG}
+ stroke={colors.background}
strokeWidth="2"
opacity="0.9"
/>
@@ -179,10 +189,10 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
x={centerX + (radius * 0.7) * Math.cos((((sector.startAngle + sector.endAngle) / 2) - 90) * Math.PI / 180)}
y={centerY + (radius * 0.7) * Math.sin((((sector.startAngle + sector.endAngle) / 2) - 90) * Math.PI / 180)}
textAnchor="middle"
- fill={FINCEPT.WHITE}
- fontSize="11px"
+ fill={colors.text}
+ fontSize={fontSize.tiny}
fontWeight={700}
- fontFamily={TYPOGRAPHY.MONO}
+ fontFamily={fontFamily}
>
{sector.weight.toFixed(1)}%
</text>
@@ -194,29 +204,29 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
cx={centerX}
cy={centerY}
r={radius * 0.4}
- fill={FINCEPT.PANEL_BG}
- stroke={FINCEPT.ORANGE}
+ fill={colors.panel}
+ stroke={colors.primary}
strokeWidth="2"
/>
<text
x={centerX}
y={centerY - 10}
textAnchor="middle"
- fill={FINCEPT.ORANGE}
- fontSize="13px"
+ fill={colors.primary}
+ fontSize={fontSize.small}
fontWeight={700}
- fontFamily={TYPOGRAPHY.MONO}
+ fontFamily={fontFamily}
>
- SECTORS
+ {t('views.sectors')}
</text>
<text
x={centerX}
y={centerY + 10}
textAnchor="middle"
- fill={FINCEPT.WHITE}
- fontSize="15px"
+ fill={colors.text}
+ fontSize={fontSize.body}
fontWeight={700}
- fontFamily={TYPOGRAPHY.MONO}
+ fontFamily={fontFamily}
>
{sectorAllocations.length}
</text>
@@ -234,10 +244,10 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
alignItems: 'center',
marginBottom: '4px',
padding: '4px',
- backgroundColor: hoveredLegendRow === sector.sector ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ backgroundColor: hoveredLegendRow === sector.sector ? 'var(--ft-color-hover, #1F1F1F)' : colors.panel,
borderLeft: `4px solid ${sector.color}`,
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD,
+ transition: 'all 0.2s ease',
cursor: 'default'
}}
>
@@ -246,25 +256,25 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
height: '12px',
backgroundColor: sector.color,
marginRight: '8px',
- border: BORDERS.STANDARD,
+ border: '1px solid var(--ft-color-border, #2A2A2A)',
borderRadius: '2px'
}} />
<div style={{ flex: 1 }}>
<span style={{
- color: FINCEPT.WHITE,
- fontSize: '11px',
+ color: colors.text,
+ fontSize: fontSize.tiny,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
{sector.sector}
</span>
</div>
<div style={{ textAlign: 'right' }}>
<span style={{
- color: FINCEPT.CYAN,
- fontSize: '10px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
{sector.weight.toFixed(1)}%
</span>
@@ -277,17 +287,17 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
{/* Sector Details Table */}
<div>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '11px',
+ color: colors.primary,
+ fontSize: fontSize.tiny,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO,
+ fontFamily,
letterSpacing: '0.5px',
textTransform: 'uppercase',
marginBottom: '8px',
paddingBottom: '4px',
- borderBottom: BORDERS.ORANGE
+ borderBottom: `1px solid ${colors.primary}`
}}>
- SECTOR BREAKDOWN
+ {t('sectors.sectorBreakdown')}
</div>
{/* Table Header */}
@@ -296,20 +306,20 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
gridTemplateColumns: '1.5fr 1fr 1fr 1fr',
gap: '8px',
padding: '8px 12px',
- backgroundColor: FINCEPT.HEADER_BG,
- fontSize: '9px',
+ backgroundColor: 'var(--ft-color-header, #1A1A1A)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO,
+ fontFamily,
letterSpacing: '0.5px',
textTransform: 'uppercase',
- borderBottom: BORDERS.ORANGE,
+ borderBottom: `1px solid ${colors.primary}`,
marginBottom: '4px',
borderRadius: '2px'
}}>
- <div style={{ color: FINCEPT.ORANGE }}>SECTOR</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>VALUE</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>WEIGHT</div>
- <div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>HOLDINGS</div>
+ <div style={{ color: colors.primary }}>{t('sectors.sector')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('sectors.value')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('sectors.weight')}</div>
+ <div style={{ color: colors.primary, textAlign: 'right' }}>{t('sectors.holdings')}</div>
</div>
{/* Sector Rows */}
@@ -327,29 +337,29 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
gap: '8px',
padding: '8px',
backgroundColor: hoveredSectorRow === sectorKey
- ? FINCEPT.HOVER
+ ? 'var(--ft-color-hover, #1F1F1F)'
: index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent',
borderLeft: `3px solid ${sector.color}`,
borderRadius: '2px',
- fontSize: '11px',
- fontFamily: TYPOGRAPHY.MONO,
+ fontSize: fontSize.tiny,
+ fontFamily,
marginBottom: '4px',
minHeight: '32px',
alignItems: 'center',
- transition: EFFECTS.TRANSITION_STANDARD,
+ transition: 'all 0.2s ease',
cursor: 'default'
}}
>
<div style={{ color: sector.color, fontWeight: 700 }}>
{sector.sector}
</div>
- <div style={{ color: FINCEPT.CYAN, textAlign: 'right', fontWeight: 700, fontSize: '10px' }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', textAlign: 'right', fontWeight: 700, fontSize: fontSize.tiny }}>
{formatCurrency(sector.value, currency)}
</div>
- <div style={{ color: FINCEPT.CYAN, textAlign: 'right', fontWeight: 700, fontSize: '10px' }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', textAlign: 'right', fontWeight: 700, fontSize: fontSize.tiny }}>
{sector.weight.toFixed(2)}%
</div>
- <div style={{ color: FINCEPT.CYAN, textAlign: 'right', fontSize: '10px' }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)', textAlign: 'right', fontSize: fontSize.tiny }}>
{sector.holdings.length}
</div>
</div>
@@ -368,28 +378,28 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
gap: '8px',
padding: '4px 8px 4px 16px',
backgroundColor: hoveredHoldingRow === holdingKey
- ? FINCEPT.HOVER
+ ? 'var(--ft-color-hover, #1F1F1F)'
: 'rgba(255,255,255,0.01)',
- fontSize: '10px',
- fontFamily: TYPOGRAPHY.MONO,
+ fontSize: fontSize.tiny,
+ fontFamily,
borderLeft: `1px solid ${sector.color}`,
marginLeft: '8px',
minHeight: '28px',
alignItems: 'center',
borderRadius: '2px',
- transition: EFFECTS.TRANSITION_STANDARD,
+ transition: 'all 0.2s ease',
cursor: 'default'
}}
>
- <div style={{ color: FINCEPT.CYAN }}>{'\u2514\u2500'} {holding.symbol}</div>
- <div style={{ color: FINCEPT.WHITE, textAlign: 'right' }}>
+ <div style={{ color: 'var(--ft-color-accent, #00E5FF)' }}>{'\u2514\u2500'} {holding.symbol}</div>
+ <div style={{ color: colors.text, textAlign: 'right' }}>
{formatCurrency(holding.market_value, currency)}
</div>
- <div style={{ color: FINCEPT.GRAY, textAlign: 'right' }}>
+ <div style={{ color: colors.textMuted, textAlign: 'right' }}>
{holding.weight.toFixed(2)}%
</div>
<div style={{
- color: holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ color: holding.unrealized_pnl >= 0 ? colors.success : colors.alert,
textAlign: 'right',
fontWeight: 600
}}>
@@ -406,84 +416,100 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
<div style={{
marginTop: '16px',
padding: '12px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.ORANGE,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.primary}`,
borderRadius: '2px'
}}>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: '9px',
+ color: colors.primary,
+ fontSize: fontSize.tiny,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO,
+ fontFamily,
letterSpacing: '0.5px',
textTransform: 'uppercase',
marginBottom: '8px'
}}>
- DIVERSIFICATION METRICS
+ {t('sectors.diversificationMetrics')}
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
<div>
<div style={{
- ...COMMON_STYLES.dataLabel,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
marginBottom: '2px'
}}>
- Total Sectors
+ {t('sectors.totalSectors')}
</div>
<div style={{
- color: FINCEPT.CYAN,
- fontSize: '15px',
+ color: 'var(--ft-color-accent, #00E5FF)',
+ fontSize: fontSize.body,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
{sectorAllocations.length}
</div>
</div>
<div>
<div style={{
- ...COMMON_STYLES.dataLabel,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
marginBottom: '2px'
}}>
- Largest Sector
+ {t('sectors.largestSector')}
</div>
<div style={{
- color: FINCEPT.YELLOW,
- fontSize: '15px',
+ color: 'var(--ft-color-warning, #FFD700)',
+ fontSize: fontSize.body,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
{sectorAllocations[0]?.sector || 'N/A'} ({sectorAllocations[0]?.weight.toFixed(1)}%)
</div>
</div>
<div>
<div style={{
- ...COMMON_STYLES.dataLabel,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
marginBottom: '2px'
}}>
- Concentration Risk
+ {t('sectors.concentrationRisk')}
</div>
<div style={{
- color: sectorAllocations[0]?.weight > 40 ? FINCEPT.RED : sectorAllocations[0]?.weight > 25 ? FINCEPT.YELLOW : FINCEPT.GREEN,
- fontSize: '15px',
+ color: sectorAllocations[0]?.weight > 40 ? colors.alert : sectorAllocations[0]?.weight > 25 ? 'var(--ft-color-warning, #FFD700)' : colors.success,
+ fontSize: fontSize.body,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
- {sectorAllocations[0]?.weight > 40 ? 'HIGH' : sectorAllocations[0]?.weight > 25 ? 'MEDIUM' : 'LOW'}
+ {sectorAllocations[0]?.weight > 40 ? t('sectors.high') : sectorAllocations[0]?.weight > 25 ? t('sectors.medium') : t('sectors.low')}
</div>
</div>
<div>
<div style={{
- ...COMMON_STYLES.dataLabel,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
marginBottom: '2px'
}}>
- Diversification
+ {t('sectors.diversification')}
</div>
<div style={{
- color: sectorAllocations.length >= 5 ? FINCEPT.GREEN : sectorAllocations.length >= 3 ? FINCEPT.YELLOW : FINCEPT.RED,
- fontSize: '15px',
+ color: sectorAllocations.length >= 5 ? colors.success : sectorAllocations.length >= 3 ? 'var(--ft-color-warning, #FFD700)' : colors.alert,
+ fontSize: fontSize.body,
fontWeight: 700,
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily
}}>
- {sectorAllocations.length >= 5 ? 'GOOD' : sectorAllocations.length >= 3 ? 'MODERATE' : 'POOR'}
+ {sectorAllocations.length >= 5 ? t('sectors.good') : sectorAllocations.length >= 3 ? t('sectors.moderate') : t('sectors.poor')}
</div>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/AIChatPanel.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/AIChatPanel.tsx
index 127ec26d8..1d785184a 100644
--- a/fincept-terminal-desktop/src/components/tabs/report-builder/AIChatPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/AIChatPanel.tsx
@@ -5,8 +5,8 @@ import {
User,
Sparkles,
} from 'lucide-react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { AIChatPanelProps } from './types';
-import { FINCEPT_COLORS } from './constants';
import MarkdownRenderer from '../../common/MarkdownRenderer';
export const AIChatPanel: React.FC<AIChatPanelProps> = ({
@@ -21,6 +21,7 @@ export const AIChatPanel: React.FC<AIChatPanelProps> = ({
onProviderChange,
availableModels,
}) => {
+ const { colors, fontSize } = useTerminalTheme();
const messagesEndRef = useRef<HTMLDivElement>(null);
// Auto-scroll to bottom when messages change
@@ -36,29 +37,29 @@ export const AIChatPanel: React.FC<AIChatPanelProps> = ({
};
return (
- <div className="flex flex-col h-full min-h-0" style={{ backgroundColor: FINCEPT_COLORS.PANEL_BG }}>
+ <div className="flex flex-col h-full min-h-0" style={{ backgroundColor: colors.panel }}>
{/* AI Assistant Header */}
<div className="p-4 border-b border-[#333333] flex-shrink-0">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
- <Bot size={18} style={{ color: FINCEPT_COLORS.ORANGE }} />
- <h3 className="text-sm font-bold" style={{ color: FINCEPT_COLORS.ORANGE }}>
+ <Bot size={18} style={{ color: colors.primary }} />
+ <h3 className="text-sm font-bold" style={{ color: colors.primary }}>
AI WRITING ASSISTANT
</h3>
</div>
- <Sparkles size={16} style={{ color: FINCEPT_COLORS.ORANGE }} />
+ <Sparkles size={16} style={{ color: colors.primary }} />
</div>
{/* Model Selector */}
<div className="mb-3">
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-[9px] block mb-1" style={{ color: colors.textMuted }}>
AI Model
</label>
<select
value={currentProvider}
onChange={(e) => onProviderChange(e.target.value)}
className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
{availableModels.map(model => (
<option key={model.id} value={model.provider}>
@@ -76,28 +77,28 @@ export const AIChatPanel: React.FC<AIChatPanelProps> = ({
<button
onClick={() => onQuickAction('improve')}
className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
✨ Improve
</button>
<button
onClick={() => onQuickAction('expand')}
className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
📝 Expand
</button>
<button
onClick={() => onQuickAction('summarize')}
className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
📋 Summary
</button>
<button
onClick={() => onQuickAction('grammar')}
className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
[OK] Grammar
</button>
@@ -108,11 +109,11 @@ export const AIChatPanel: React.FC<AIChatPanelProps> = ({
<div className="flex-1 overflow-y-auto p-4 space-y-3 min-h-0">
{messages.length === 0 && (
<div className="text-center py-8">
- <Bot size={32} className="mx-auto mb-3" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }} />
- <p className="text-xs" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <Bot size={32} className="mx-auto mb-3" style={{ color: colors.textMuted }} />
+ <p className="text-xs" style={{ color: colors.textMuted }}>
Ask me to help you write better reports!
</p>
- <p className="text-[9px] mt-2" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <p className="text-[9px] mt-2" style={{ color: colors.textMuted }}>
Try: "Help me write an introduction"
</p>
</div>
@@ -121,7 +122,7 @@ export const AIChatPanel: React.FC<AIChatPanelProps> = ({
{messages.map((msg, idx) => (
<div key={idx} className={`flex gap-2 ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
{msg.role === 'assistant' && (
- <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: FINCEPT_COLORS.ORANGE }}>
+ <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: colors.primary }}>
<Bot size={14} style={{ color: '#000' }} />
</div>
)}
@@ -132,7 +133,7 @@ export const AIChatPanel: React.FC<AIChatPanelProps> = ({
: 'bg-[#1a1a1a] border border-[#333333]'
}`}
>
- <div className="text-xs break-words" style={{ color: msg.role === 'user' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}>
+ <div className="text-xs break-words" style={{ color: msg.role === 'user' ? '#000' : colors.text }}>
{msg.role === 'assistant' ? (
<MarkdownRenderer content={msg.content} />
) : (
@@ -142,7 +143,7 @@ export const AIChatPanel: React.FC<AIChatPanelProps> = ({
</div>
{msg.role === 'user' && (
<div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center bg-[#333333]">
- <User size={14} style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }} />
+ <User size={14} style={{ color: colors.text }} />
</div>
)}
</div>
@@ -151,11 +152,11 @@ export const AIChatPanel: React.FC<AIChatPanelProps> = ({
{/* Streaming content */}
{isTyping && streamingContent && (
<div className="flex gap-2 justify-start">
- <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: FINCEPT_COLORS.ORANGE }}>
+ <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: colors.primary }}>
<Bot size={14} style={{ color: '#000' }} />
</div>
<div className="max-w-[85%] rounded-lg p-3 bg-[#1a1a1a] border border-[#333333]">
- <div className="text-xs break-words" style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}>
+ <div className="text-xs break-words" style={{ color: colors.text }}>
<MarkdownRenderer content={streamingContent} />
</div>
</div>
@@ -165,11 +166,11 @@ export const AIChatPanel: React.FC<AIChatPanelProps> = ({
{/* Typing indicator */}
{isTyping && !streamingContent && (
<div className="flex gap-2 justify-start">
- <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: FINCEPT_COLORS.ORANGE }}>
+ <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: colors.primary }}>
<Bot size={14} style={{ color: '#000' }} />
</div>
<div className="max-w-[85%] rounded-lg p-3 bg-[#1a1a1a] border border-[#333333]">
- <div className="text-xs flex gap-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <div className="text-xs flex gap-1" style={{ color: colors.textMuted }}>
<span className="animate-bounce">●</span>
<span className="animate-bounce delay-100">●</span>
<span className="animate-bounce delay-200">●</span>
@@ -191,7 +192,7 @@ export const AIChatPanel: React.FC<AIChatPanelProps> = ({
onKeyPress={handleKeyPress}
placeholder="Ask AI to help with your report..."
className="flex-1 px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
disabled={isTyping}
/>
<button
@@ -199,7 +200,7 @@ export const AIChatPanel: React.FC<AIChatPanelProps> = ({
disabled={isTyping || !input.trim()}
className="px-3 py-2 rounded transition-all disabled:opacity-50 disabled:cursor-not-allowed"
style={{
- backgroundColor: FINCEPT_COLORS.ORANGE,
+ backgroundColor: colors.primary,
color: '#000'
}}
>
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/AdvancedStylingPanel.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/AdvancedStylingPanel.tsx
index 374006696..473beb004 100644
--- a/fincept-terminal-desktop/src/components/tabs/report-builder/AdvancedStylingPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/AdvancedStylingPanel.tsx
@@ -36,19 +36,9 @@ import {
} from '@/services/core/brandKitService';
import { open } from '@tauri-apps/plugin-dialog';
import { toast } from '@/components/ui/terminal-toast';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
-// Fincept color palette
-const FINCEPT_COLORS = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- BLACK: '#000000',
- DARK_BG: '#0a0a0a',
- PANEL_BG: '#1a1a1a',
- BORDER: '#333333',
- HOVER: '#2a2a2a',
- TEXT_PRIMARY: '#FFFFFF',
- TEXT_SECONDARY: '#999999',
-};
+// Theme colors provided by useTerminalTheme() hook
interface AdvancedStylingPanelProps {
onBrandKitChange?: (brandKit: BrandKit) => void;
@@ -68,6 +58,7 @@ export const AdvancedStylingPanel: React.FC<AdvancedStylingPanelProps> = ({
onComponentTemplateSelect,
onStylesChange,
}) => {
+ const { colors, fontSize } = useTerminalTheme();
const [activeTab, setActiveTab] = useState<TabType>('brandKit');
const [brandKits, setBrandKits] = useState<BrandKit[]>([]);
const [activeBrandKit, setActiveBrandKit] = useState<BrandKit | null>(null);
@@ -217,9 +208,9 @@ export const AdvancedStylingPanel: React.FC<AdvancedStylingPanelProps> = ({
);
return (
- <div className="h-full flex flex-col" style={{ backgroundColor: FINCEPT_COLORS.PANEL_BG }}>
+ <div className="h-full flex flex-col" style={{ backgroundColor: colors.panel }}>
{/* Tab Navigation */}
- <div className="flex flex-wrap gap-1 p-2 border-b" style={{ borderColor: FINCEPT_COLORS.BORDER }}>
+ <div className="flex flex-wrap gap-1 p-2 border-b" style={{ borderColor: colors.panel }}>
{renderTabButton('brandKit', <Palette size={14} />, 'Brand Kit')}
{renderTabButton('templates', <LayoutTemplate size={14} />, 'Templates')}
{renderTabButton('headerFooter', <Layers size={14} />, 'Header/Footer')}
@@ -352,6 +343,7 @@ const BrandKitTab: React.FC<BrandKitTabProps> = ({
handleCreateNewBrandKit,
handleDeleteBrandKit,
}) => {
+ const { colors } = useTerminalTheme();
const availableFonts = brandKitService.getAvailableFonts();
const presetKits = brandKitService.getPresetBrandKits();
@@ -360,7 +352,7 @@ const BrandKitTab: React.FC<BrandKitTabProps> = ({
{/* Brand Kit Selector */}
<div className="space-y-2">
<div className="flex items-center justify-between">
- <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.ORANGE }}>
+ <label className="text-xs font-semibold" style={{ color: colors.primary }}>
SELECT BRAND KIT
</label>
<button
@@ -368,7 +360,7 @@ const BrandKitTab: React.FC<BrandKitTabProps> = ({
className="p-1 rounded hover:bg-[#2a2a2a] transition-colors"
title="Create New"
>
- <Plus size={14} style={{ color: FINCEPT_COLORS.ORANGE }} />
+ <Plus size={14} style={{ color: colors.primary }} />
</button>
</div>
<select
@@ -387,7 +379,7 @@ const BrandKitTab: React.FC<BrandKitTabProps> = ({
{/* Preset Brand Kits */}
<div className="space-y-2">
- <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold" style={{ color: colors.textMuted }}>
QUICK PRESETS
</label>
<div className="grid grid-cols-2 gap-2">
@@ -424,7 +416,7 @@ const BrandKitTab: React.FC<BrandKitTabProps> = ({
<>
{/* Brand Kit Name */}
<div className="space-y-1">
- <label className="text-xs" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs" style={{ color: colors.textMuted }}>
Brand Kit Name
</label>
<input
@@ -442,7 +434,7 @@ const BrandKitTab: React.FC<BrandKitTabProps> = ({
className="w-full flex items-center justify-between p-3 hover:bg-[#2a2a2a] transition-colors"
>
<div className="flex items-center gap-2">
- <Palette size={14} style={{ color: FINCEPT_COLORS.ORANGE }} />
+ <Palette size={14} style={{ color: colors.primary }} />
<span className="text-xs font-semibold text-white">Colors</span>
</div>
{expandedSections.colors ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
@@ -500,7 +492,7 @@ const BrandKitTab: React.FC<BrandKitTabProps> = ({
className="w-full flex items-center justify-between p-3 hover:bg-[#2a2a2a] transition-colors"
>
<div className="flex items-center gap-2">
- <Type size={14} style={{ color: FINCEPT_COLORS.ORANGE }} />
+ <Type size={14} style={{ color: colors.primary }} />
<span className="text-xs font-semibold text-white">Fonts</span>
</div>
{expandedSections.fonts ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
@@ -552,7 +544,7 @@ const BrandKitTab: React.FC<BrandKitTabProps> = ({
className="w-full flex items-center justify-between p-3 hover:bg-[#2a2a2a] transition-colors"
>
<div className="flex items-center gap-2">
- <ImageIcon size={14} style={{ color: FINCEPT_COLORS.ORANGE }} />
+ <ImageIcon size={14} style={{ color: colors.primary }} />
<span className="text-xs font-semibold text-white">Logos</span>
</div>
{expandedSections.logos ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
@@ -584,7 +576,7 @@ const BrandKitTab: React.FC<BrandKitTabProps> = ({
<button
onClick={handleSaveBrandKit}
className="w-full py-2 text-xs font-semibold rounded transition-colors flex items-center justify-center gap-2"
- style={{ backgroundColor: FINCEPT_COLORS.ORANGE, color: FINCEPT_COLORS.BLACK }}
+ style={{ backgroundColor: colors.primary, color: '#000' }}
>
<Save size={14} />
Save Brand Kit
@@ -607,6 +599,7 @@ const ComponentTemplatesTab: React.FC<ComponentTemplatesTabProps> = ({
onSelect,
onRefresh,
}) => {
+ const { colors } = useTerminalTheme();
const [selectedCategory, setSelectedCategory] = useState<string>('all');
const categories = ['all', 'text', 'layout', 'data', 'media', 'custom'];
@@ -637,7 +630,7 @@ const ComponentTemplatesTab: React.FC<ComponentTemplatesTabProps> = ({
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
- <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.ORANGE }}>
+ <label className="text-xs font-semibold" style={{ color: colors.primary }}>
COMPONENT TEMPLATES
</label>
<button
@@ -691,7 +684,7 @@ const ComponentTemplatesTab: React.FC<ComponentTemplatesTabProps> = ({
className="p-1 rounded hover:bg-[#2a2a2a]"
title="Use Template"
>
- <Plus size={12} style={{ color: FINCEPT_COLORS.ORANGE }} />
+ <Plus size={12} style={{ color: colors.primary }} />
</button>
<button
onClick={(e) => {
@@ -736,6 +729,7 @@ interface HeaderFooterTabProps {
}
const HeaderFooterTab: React.FC<HeaderFooterTabProps> = ({ brandKit, onUpdate }) => {
+ const { colors } = useTerminalTheme();
const [editingSection, setEditingSection] = useState<'header' | 'footer'>('header');
if (!brandKit) {
@@ -760,7 +754,7 @@ const HeaderFooterTab: React.FC<HeaderFooterTabProps> = ({ brandKit, onUpdate })
return (
<div className="space-y-4">
- <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.ORANGE }}>
+ <label className="text-xs font-semibold" style={{ color: colors.primary }}>
HEADER & FOOTER
</label>
@@ -1081,6 +1075,7 @@ interface TypographyTabProps {
}
const TypographyTab: React.FC<TypographyTabProps> = ({ brandKit, onUpdate }) => {
+ const { colors } = useTerminalTheme();
if (!brandKit) {
return (
<div className="text-center py-8 text-gray-500 text-xs">
@@ -1097,7 +1092,7 @@ const TypographyTab: React.FC<TypographyTabProps> = ({ brandKit, onUpdate }) =>
return (
<div className="space-y-4">
- <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.ORANGE }}>
+ <label className="text-xs font-semibold" style={{ color: colors.primary }}>
PARAGRAPH & LINE SPACING
</label>
@@ -1115,7 +1110,7 @@ const TypographyTab: React.FC<TypographyTabProps> = ({ brandKit, onUpdate }) =>
value={styles.lineHeight}
onChange={(e) => updateStyles({ lineHeight: Number(e.target.value) })}
className="w-full"
- style={{ accentColor: FINCEPT_COLORS.ORANGE }}
+ style={{ accentColor: colors.primary }}
/>
<div className="flex justify-between text-[10px] text-gray-500">
<span>Tight (1.0)</span>
@@ -1138,7 +1133,7 @@ const TypographyTab: React.FC<TypographyTabProps> = ({ brandKit, onUpdate }) =>
value={styles.paragraphSpacing}
onChange={(e) => updateStyles({ paragraphSpacing: Number(e.target.value) })}
className="w-full"
- style={{ accentColor: FINCEPT_COLORS.ORANGE }}
+ style={{ accentColor: colors.primary }}
/>
</div>
@@ -1156,7 +1151,7 @@ const TypographyTab: React.FC<TypographyTabProps> = ({ brandKit, onUpdate }) =>
value={styles.textIndent}
onChange={(e) => updateStyles({ textIndent: Number(e.target.value) })}
className="w-full"
- style={{ accentColor: FINCEPT_COLORS.ORANGE }}
+ style={{ accentColor: colors.primary }}
/>
</div>
@@ -1174,7 +1169,7 @@ const TypographyTab: React.FC<TypographyTabProps> = ({ brandKit, onUpdate }) =>
value={styles.letterSpacing}
onChange={(e) => updateStyles({ letterSpacing: Number(e.target.value) })}
className="w-full"
- style={{ accentColor: FINCEPT_COLORS.ORANGE }}
+ style={{ accentColor: colors.primary }}
/>
</div>
@@ -1192,7 +1187,7 @@ const TypographyTab: React.FC<TypographyTabProps> = ({ brandKit, onUpdate }) =>
value={styles.wordSpacing}
onChange={(e) => updateStyles({ wordSpacing: Number(e.target.value) })}
className="w-full"
- style={{ accentColor: FINCEPT_COLORS.ORANGE }}
+ style={{ accentColor: colors.primary }}
/>
</div>
@@ -1320,6 +1315,7 @@ interface CustomCSSTabProps {
}
const CustomCSSTab: React.FC<CustomCSSTabProps> = ({ brandKit, onUpdate }) => {
+ const { colors } = useTerminalTheme();
const [localCSS, setLocalCSS] = useState(brandKit?.customCSS || '');
const [showGenerated, setShowGenerated] = useState(false);
@@ -1345,7 +1341,7 @@ const CustomCSSTab: React.FC<CustomCSSTabProps> = ({ brandKit, onUpdate }) => {
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
- <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.ORANGE }}>
+ <label className="text-xs font-semibold" style={{ color: colors.primary }}>
CUSTOM CSS
</label>
<button
@@ -1422,7 +1418,7 @@ const CustomCSSTab: React.FC<CustomCSSTabProps> = ({ brandKit, onUpdate }) => {
<button
onClick={handleApply}
className="w-full py-2 text-xs font-semibold rounded transition-colors flex items-center justify-center gap-2"
- style={{ backgroundColor: FINCEPT_COLORS.ORANGE, color: FINCEPT_COLORS.BLACK }}
+ style={{ backgroundColor: colors.primary, color: '#000' }}
>
<Check size={14} />
Apply Custom CSS
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/ComponentToolbar.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/ComponentToolbar.tsx
index 580212a29..f5478d215 100644
--- a/fincept-terminal-desktop/src/components/tabs/report-builder/ComponentToolbar.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/ComponentToolbar.tsx
@@ -27,9 +27,10 @@ import {
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from '@dnd-kit/core';
import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { SortableComponent } from './SortableComponent';
import { ComponentToolbarProps } from './types';
-import { FINCEPT_COLORS, PAGE_THEMES, FONT_FAMILIES, PRESET_COLORS } from './constants';
+import { PAGE_THEMES, FONT_FAMILIES, PRESET_COLORS } from './constants';
export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
onAddComponent,
@@ -55,6 +56,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
onIsItalicChange,
}) => {
const { t } = useTranslation('reportBuilder');
+ const { colors, fontSize } = useTerminalTheme();
const sensors = useSensors(
useSensor(PointerSensor),
@@ -76,88 +78,88 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
};
return (
- <div className="w-1/5 border-r overflow-y-auto" style={{ borderColor: FINCEPT_COLORS.BORDER, backgroundColor: FINCEPT_COLORS.PANEL_BG }}>
+ <div className="w-1/5 border-r overflow-y-auto" style={{ borderColor: colors.panel, backgroundColor: colors.panel }}>
<div className="p-3">
{/* Add Components */}
<div className="mb-4">
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>{t('components.title')}</h3>
+ <h3 className="font-bold mb-2" style={{ fontSize: fontSize.small, color: colors.primary }}>{t('components.title')}</h3>
<div className="space-y-1">
<button
onClick={() => onAddComponent('heading')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="w-full px-3 py-2 text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<Type size={14} />
Heading
</button>
<button
onClick={() => onAddComponent('subheading')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="w-full px-3 py-2 text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<Type size={12} />
Subheading
</button>
<button
onClick={() => onAddComponent('text')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="w-full px-3 py-2 text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<AlignLeft size={14} />
Text
</button>
<button
onClick={() => onAddComponent('chart')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="w-full px-3 py-2 text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<BarChart3 size={14} />
Chart
</button>
<button
onClick={() => onAddComponent('table')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="w-full px-3 py-2 text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<Table size={14} />
Table
</button>
<button
onClick={() => onAddComponent('image')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="w-full px-3 py-2 text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<ImageIcon size={14} />
Image
</button>
<button
onClick={() => onAddComponent('code')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="w-full px-3 py-2 text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<Code size={14} />
Code Block
</button>
<button
onClick={() => onAddComponent('divider')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="w-full px-3 py-2 text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<Minus size={14} />
Divider
</button>
<button
onClick={() => onAddComponent('quote')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="w-full px-3 py-2 text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<Quote size={14} />
Quote/Callout
</button>
<button
onClick={() => onAddComponent('list')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="w-full px-3 py-2 text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<List size={14} />
List
@@ -167,36 +169,36 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
{/* Data Components */}
<div className="mb-4">
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>DATA</h3>
+ <h3 className="font-bold mb-2" style={{ fontSize: fontSize.small, color: colors.primary }}>DATA</h3>
<div className="grid grid-cols-2 gap-1">
<button
onClick={() => onAddComponent('kpi')}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="px-2 py-2 rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<TrendingUp size={14} />
- <span className="text-[9px]">KPI</span>
+ <span style={{ fontSize: fontSize.tiny }}>KPI</span>
</button>
<button
onClick={() => onAddComponent('sparkline')}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="px-2 py-2 rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<Activity size={14} />
- <span className="text-[9px]">Sparkline</span>
+ <span style={{ fontSize: fontSize.tiny }}>Sparkline</span>
</button>
<button
onClick={() => onAddComponent('liveTable')}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="px-2 py-2 rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<Database size={14} />
- <span className="text-[9px]">Data Table</span>
+ <span style={{ fontSize: fontSize.tiny }}>Data Table</span>
</button>
<button
onClick={() => onAddComponent('dynamicChart')}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ className="px-2 py-2 rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<BarChart3 size={14} />
<span className="text-[9px]">Chart</span>
@@ -206,12 +208,12 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
{/* Document Components */}
<div className="mb-4">
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>DOCUMENT</h3>
+ <h3 className="text-xs font-bold mb-2" style={{ fontSize: fontSize.small, color: colors.primary }}>DOCUMENT</h3>
<div className="grid grid-cols-2 gap-1">
<button
onClick={() => onAddComponent('toc')}
className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<Hash size={14} />
<span className="text-[9px]">TOC</span>
@@ -219,7 +221,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
<button
onClick={() => onAddComponent('signature')}
className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<PenTool size={14} />
<span className="text-[9px]">Signature</span>
@@ -227,7 +229,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
<button
onClick={() => onAddComponent('disclaimer')}
className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<AlertTriangle size={14} />
<span className="text-[9px]">Disclaimer</span>
@@ -235,7 +237,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
<button
onClick={() => onAddComponent('qrcode')}
className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<QrCode size={14} />
<span className="text-[9px]">QR Code</span>
@@ -243,7 +245,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
<button
onClick={() => onAddComponent('watermark')}
className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<Stamp size={14} />
<span className="text-[9px]">Watermark</span>
@@ -253,12 +255,12 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
{/* Layout Components */}
<div className="mb-4">
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>{t('layout.title')}</h3>
+ <h3 className="text-xs font-bold mb-2" style={{ fontSize: fontSize.small, color: colors.primary }}>{t('layout.title')}</h3>
<div className="grid grid-cols-2 gap-1">
<button
onClick={() => onAddComponent('section')}
className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<Layout size={14} />
<span className="text-[9px]">Section</span>
@@ -266,7 +268,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
<button
onClick={() => onAddComponent('columns')}
className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<ColumnsIcon size={14} />
<span className="text-[9px]">Columns</span>
@@ -274,7 +276,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
<button
onClick={() => onAddComponent('coverpage')}
className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<BookOpen size={14} />
<span className="text-[9px]">Cover</span>
@@ -282,7 +284,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
<button
onClick={() => onAddComponent('pagebreak')}
className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
<FileX size={14} />
<span className="text-[9px]">Break</span>
@@ -292,17 +294,17 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
{/* Settings */}
<div className="mb-4">
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>{t('settings.title')}</h3>
+ <h3 className="text-xs font-bold mb-2" style={{ fontSize: fontSize.small, color: colors.primary }}>{t('settings.title')}</h3>
<div className="space-y-2">
<div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-[9px] block mb-1" style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
Page Theme
</label>
<select
value={pageTheme}
onChange={(e) => onPageThemeChange(e.target.value as any)}
className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
{Object.entries(PAGE_THEMES).map(([value, label]) => (
<option key={value} value={value}>{label}</option>
@@ -314,13 +316,13 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
{pageTheme === 'classic' && (
<div>
<div className="flex items-center justify-between mb-1">
- <label className="text-[9px]" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-[9px]" style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
Background Color
</label>
<button
onClick={() => onShowColorPickerChange(!showColorPicker)}
className="text-[9px] px-2 py-1 rounded hover:bg-[#2a2a2a]"
- style={{ color: FINCEPT_COLORS.ORANGE }}
+ style={{ fontSize: fontSize.small, color: colors.primary }}
>
{showColorPicker ? 'Hide Picker' : 'Show Picker'}
</button>
@@ -337,7 +339,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
value={customBgColor}
onChange={(e) => onCustomBgColorChange(e.target.value)}
className="flex-1 px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
placeholder="#ffffff"
/>
</div>
@@ -347,7 +349,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
<div className="p-3 rounded bg-[#0a0a0a] border border-[#333333] space-y-3">
{/* Main Gradient Palette */}
<div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-[9px] mb-1 block" style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
Color Palette
</label>
<div
@@ -382,7 +384,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
{/* Hue Slider */}
<div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-[9px] mb-1 block" style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
Hue
</label>
<div
@@ -402,7 +404,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
{/* Lightness Slider */}
<div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-[9px] mb-1 block" style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
Lightness
</label>
<div
@@ -422,7 +424,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
{/* Preset Colors */}
<div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-[9px] mb-1 block" style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
Preset Colors
</label>
<div className="grid grid-cols-8 gap-1">
@@ -447,7 +449,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
)}
<div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-[9px] block mb-1" style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
Report Title
</label>
<input
@@ -455,20 +457,20 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
value={template.metadata.title}
readOnly
className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] outline-none opacity-60"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
placeholder="Edit in Properties panel..."
/>
</div>
<div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-[9px] block mb-1" style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
Font Family
</label>
<select
value={fontFamily}
onChange={(e) => onFontFamilyChange(e.target.value)}
className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ fontSize: fontSize.small, color: colors.text }}
>
{FONT_FAMILIES.map(font => (
<option key={font.value} value={font.value}>{font.label}</option>
@@ -477,7 +479,7 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
</div>
<div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-[9px] block mb-1" style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
Base Font Size
</label>
<div className="flex items-center gap-2">
@@ -488,16 +490,16 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
value={defaultFontSize}
onChange={(e) => onDefaultFontSizeChange(Number(e.target.value))}
className="flex-1"
- style={{ accentColor: FINCEPT_COLORS.ORANGE }}
+ style={{ accentColor: colors.primary }}
/>
- <span className="text-xs" style={{ color: FINCEPT_COLORS.TEXT_PRIMARY, minWidth: '30px' }}>
+ <span style={{ fontSize: fontSize.small, color: colors.text, minWidth: '30px' }}>
{defaultFontSize}pt
</span>
</div>
</div>
<div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-[9px] block mb-1" style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
Text Style
</label>
<div className="flex gap-2">
@@ -530,10 +532,10 @@ export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
{/* Document Structure */}
<div>
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>DOCUMENT STRUCTURE</h3>
+ <h3 className="text-xs font-bold mb-2" style={{ fontSize: fontSize.small, color: colors.primary }}>DOCUMENT STRUCTURE</h3>
<div className="space-y-0">
{template.components.length === 0 ? (
- <p className="text-xs text-center py-4" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <p className="text-xs text-center py-4" style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
No components yet
</p>
) : (
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/PropertiesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/PropertiesPanel.tsx
index 132d034b7..29916abf4 100644
--- a/fincept-terminal-desktop/src/components/tabs/report-builder/PropertiesPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/PropertiesPanel.tsx
@@ -8,8 +8,9 @@ import {
BookmarkPlus,
FileX,
} from 'lucide-react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { PropertiesPanelProps } from './types';
-import { FINCEPT_COLORS, FONT_SIZES, CHART_TYPES } from './constants';
+import { FONT_SIZES, CHART_TYPES } from './constants';
export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
selectedComponent,
@@ -20,9 +21,11 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
onSaveAsTemplate,
onImageUpload,
}) => {
+ const { colors, fontSize } = useTerminalTheme();
+
if (!selectedComponent) {
return (
- <div className="p-4 text-center" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <div className="p-4 text-center" style={{ color: colors.textMuted }}>
<SettingsIcon size={32} className="mx-auto mb-2 opacity-30" />
<p className="text-xs">Select a component to edit properties</p>
</div>
@@ -32,11 +35,11 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
return (
<div className="p-4">
<div className="flex items-center justify-between mb-4">
- <h3 className="text-sm font-bold" style={{ color: FINCEPT_COLORS.ORANGE }}>PROPERTIES</h3>
+ <h3 className="text-sm font-bold" style={{ color: colors.primary }}>PROPERTIES</h3>
<button
onClick={onClearSelection}
className="p-1 hover:bg-[#2a2a2a] rounded"
- style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}
+ style={{ color: colors.textMuted }}
>
<X size={16} />
</button>
@@ -45,7 +48,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
<div className="space-y-4">
{/* Component Type */}
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Type
</label>
<div className="px-3 py-2 text-xs rounded bg-[#0a0a0a] capitalize">
@@ -56,14 +59,14 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{/* Content Editor */}
{(selectedComponent.type === 'heading' || selectedComponent.type === 'text' || selectedComponent.type === 'code') && (
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Content
</label>
<textarea
value={selectedComponent.content || ''}
onChange={(e) => onUpdateComponent(selectedComponent.id, { content: e.target.value })}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
rows={selectedComponent.type === 'code' ? 10 : 4}
placeholder="Enter content..."
/>
@@ -74,20 +77,20 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'quote' && (
<>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Quote Text
</label>
<textarea
value={selectedComponent.content || ''}
onChange={(e) => onUpdateComponent(selectedComponent.id, { content: e.target.value })}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
rows={3}
placeholder="Enter quote text..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Author
</label>
<input
@@ -97,12 +100,12 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, author: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Enter author name..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Style
</label>
<select
@@ -111,7 +114,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, quoteType: e.target.value as 'quote' | 'info' | 'warning' | 'success' | 'error' }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<option value="quote">Quote</option>
<option value="info">Info</option>
@@ -127,20 +130,20 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'disclaimer' && (
<>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Disclaimer Text
</label>
<textarea
value={selectedComponent.content || ''}
onChange={(e) => onUpdateComponent(selectedComponent.id, { content: e.target.value })}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
rows={4}
placeholder="Enter disclaimer text..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Disclaimer Type
</label>
<div className="flex gap-2">
@@ -167,7 +170,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{/* Alignment */}
{(selectedComponent.type === 'heading' || selectedComponent.type === 'text') && (
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Alignment
</label>
<div className="flex gap-2">
@@ -193,7 +196,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{/* Font Size */}
{(selectedComponent.type === 'heading' || selectedComponent.type === 'text') && (
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Font Size
</label>
<select
@@ -202,7 +205,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, fontSize: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
{FONT_SIZES.map(size => (
<option key={size.value} value={size.value}>{size.label}</option>
@@ -214,7 +217,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{/* Image Upload */}
{selectedComponent.type === 'image' && (
<div>
- <label className="text-xs font-semibold mb-2 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-2 block" style={{ color: colors.textMuted }}>
Image
</label>
{selectedComponent.config.imageUrl ? (
@@ -243,7 +246,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
<button
onClick={onImageUpload}
className="w-full px-3 py-2 text-xs rounded transition-colors flex items-center justify-center gap-2"
- style={{ backgroundColor: FINCEPT_COLORS.ORANGE, color: FINCEPT_COLORS.BLACK }}
+ style={{ backgroundColor: colors.primary, color: '#000' }}
>
<Plus size={14} />
Upload Image
@@ -255,7 +258,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{/* Table Columns */}
{selectedComponent.type === 'table' && (
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Columns (comma-separated)
</label>
<input
@@ -265,7 +268,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, columns: e.target.value.split(',').map(s => s.trim()) }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Column 1, Column 2, Column 3"
/>
</div>
@@ -274,7 +277,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{/* Chart Type */}
{selectedComponent.type === 'chart' && (
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Chart Type
</label>
<select
@@ -283,7 +286,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, chartType: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
{CHART_TYPES.map(chart => (
<option key={chart.value} value={chart.value}>{chart.label}</option>
@@ -296,7 +299,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'section' && (
<>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Section Title
</label>
<input
@@ -306,12 +309,12 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, sectionTitle: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Enter section title..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Border Color
</label>
<input
@@ -324,7 +327,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Background Color
</label>
<input
@@ -342,7 +345,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{/* Columns Count */}
{selectedComponent.type === 'columns' && (
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Number of Columns
</label>
<select
@@ -351,7 +354,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, columnCount: Number(e.target.value) as 2 | 3 }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<option value={2}>2 Columns</option>
<option value={3}>3 Columns</option>
@@ -362,14 +365,14 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{/* KPI Settings */}
{selectedComponent.type === 'kpi' && (
<div>
- <label className="text-xs font-semibold mb-2 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-2 block" style={{ color: colors.textMuted }}>
KPI Cards
</label>
<div className="space-y-3">
{(selectedComponent.config.kpis || []).map((kpi: any, idx: number) => (
<div key={idx} className="p-3 bg-[#0a0a0a] rounded border border-[#333333] space-y-2">
<div className="flex items-center justify-between mb-2">
- <span className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.ORANGE }}>KPI {idx + 1}</span>
+ <span className="text-xs font-semibold" style={{ color: colors.primary }}>KPI {idx + 1}</span>
<button
onClick={() => {
const newKpis = [...(selectedComponent.config.kpis || [])];
@@ -394,7 +397,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
});
}}
className="w-full px-2 py-1 text-xs rounded bg-[#1a1a1a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Label (e.g., Revenue)"
/>
<input
@@ -408,7 +411,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
});
}}
className="w-full px-2 py-1 text-xs rounded bg-[#1a1a1a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Value (e.g., $1.2M)"
/>
<div className="flex gap-2">
@@ -427,7 +430,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
}
}}
className="flex-1 px-2 py-1 text-xs rounded bg-[#1a1a1a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Change %"
/>
<select
@@ -440,7 +443,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
});
}}
className="flex-1 px-2 py-1 text-xs rounded bg-[#1a1a1a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<option value="up">Up</option>
<option value="down">Down</option>
@@ -456,7 +459,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
});
}}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors flex items-center justify-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<Plus size={14} />
Add KPI Card
@@ -468,7 +471,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{/* Sparkline Settings */}
{selectedComponent.type === 'sparkline' && (
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Data (comma-separated numbers)
</label>
<input
@@ -481,11 +484,11 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
});
}}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="10, 25, 15, 30, 20, 35, 28"
/>
<div className="mt-2">
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Color
</label>
<input
@@ -504,7 +507,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'liveTable' && (
<>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Data Source
</label>
<select
@@ -513,7 +516,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, dataSource: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<option value="portfolio">Portfolio</option>
<option value="watchlist">Watchlist</option>
@@ -521,7 +524,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
</select>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Columns (comma-separated)
</label>
<input
@@ -531,7 +534,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, columns: e.target.value.split(',').map(s => s.trim()) }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Symbol, Price, Change"
/>
</div>
@@ -542,7 +545,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'dynamicChart' && (
<>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Chart Type
</label>
<select
@@ -551,7 +554,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, chartType: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<option value="line">Line Chart</option>
<option value="bar">Bar Chart</option>
@@ -560,7 +563,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
</select>
</div>
<div>
- <label className="text-xs font-semibold mb-2 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-2 block" style={{ color: colors.textMuted }}>
Chart Data
</label>
<div className="space-y-2">
@@ -577,7 +580,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
});
}}
className="flex-1 px-2 py-1 text-xs rounded bg-[#1a1a1a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Label"
/>
<input
@@ -595,7 +598,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
}
}}
className="w-20 px-2 py-1 text-xs rounded bg-[#1a1a1a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Value"
/>
<button
@@ -620,7 +623,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
});
}}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors flex items-center justify-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<Plus size={14} />
Add Data Point
@@ -634,7 +637,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'list' && (
<>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
List Type
</label>
<div className="flex gap-2">
@@ -665,7 +668,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
</div>
</div>
<div>
- <label className="text-xs font-semibold mb-2 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-2 block" style={{ color: colors.textMuted }}>
Items
</label>
<div className="space-y-2">
@@ -682,7 +685,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
});
}}
className="flex-1 px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder={`Item ${idx + 1}`}
/>
<button
@@ -707,7 +710,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
});
}}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors flex items-center justify-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<Plus size={14} />
Add Item
@@ -720,7 +723,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{/* Table of Contents Settings */}
{selectedComponent.type === 'toc' && (
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Show Page Numbers
</label>
<div className="flex gap-2">
@@ -758,7 +761,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{/* Divider Settings */}
{selectedComponent.type === 'divider' && (
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Color
</label>
<input
@@ -779,7 +782,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'pagebreak' && (
<div className="text-center py-4">
<div className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-[#0a0a0a] mb-2">
- <FileX size={24} style={{ color: FINCEPT_COLORS.ORANGE }} />
+ <FileX size={24} style={{ color: colors.primary }} />
</div>
<p className="text-xs text-gray-400">
Page Break
@@ -794,7 +797,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'coverpage' && (
<>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Title
</label>
<input
@@ -802,12 +805,12 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
value={selectedComponent.content || ''}
onChange={(e) => onUpdateComponent(selectedComponent.id, { content: e.target.value })}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Enter cover page title..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Subtitle
</label>
<input
@@ -817,12 +820,12 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, subtitle: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Enter subtitle..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Background Color
</label>
<input
@@ -835,7 +838,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
/>
</div>
<div>
- <label className="text-xs font-semibold mb-2 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-2 block" style={{ color: colors.textMuted }}>
Logo
</label>
{selectedComponent.config.logo ? (
@@ -864,7 +867,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
<button
onClick={onImageUpload}
className="w-full px-3 py-2 text-xs rounded transition-colors flex items-center justify-center gap-2"
- style={{ backgroundColor: FINCEPT_COLORS.ORANGE, color: FINCEPT_COLORS.BLACK }}
+ style={{ backgroundColor: colors.primary, color: '#000' }}
>
<Plus size={14} />
Upload Logo
@@ -878,7 +881,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'subheading' && (
<>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Content
</label>
<input
@@ -886,12 +889,12 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
value={selectedComponent.content || ''}
onChange={(e) => onUpdateComponent(selectedComponent.id, { content: e.target.value })}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Enter subheading..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Alignment
</label>
<div className="flex gap-2">
@@ -919,7 +922,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'signature' && (
<>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Name
</label>
<input
@@ -929,12 +932,12 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, name: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Enter name..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Title
</label>
<input
@@ -944,12 +947,12 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, title: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Enter title..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Signature Line
</label>
<div className="flex gap-2">
@@ -986,7 +989,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'qrcode' && (
<>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
URL/Value
</label>
<input
@@ -996,12 +999,12 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, value: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Enter URL..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Label
</label>
<input
@@ -1011,12 +1014,12 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, label: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Enter label..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Size
</label>
<div className="flex items-center gap-2">
@@ -1030,9 +1033,9 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, size: Number(e.target.value) }
})}
className="flex-1"
- style={{ accentColor: FINCEPT_COLORS.ORANGE }}
+ style={{ accentColor: colors.primary }}
/>
- <span className="text-xs" style={{ color: FINCEPT_COLORS.TEXT_PRIMARY, minWidth: '35px' }}>
+ <span className="text-xs" style={{ color: colors.text, minWidth: '35px' }}>
{selectedComponent.config.size || 100}px
</span>
</div>
@@ -1044,7 +1047,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
{selectedComponent.type === 'watermark' && (
<>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Text
</label>
<input
@@ -1054,12 +1057,12 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, text: e.target.value }
})}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
placeholder="Enter watermark text..."
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Opacity ({Math.round((selectedComponent.config.opacity || 0.1) * 100)}%)
</label>
<input
@@ -1072,11 +1075,11 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, opacity: Number(e.target.value) }
})}
className="w-full"
- style={{ accentColor: FINCEPT_COLORS.ORANGE }}
+ style={{ accentColor: colors.primary }}
/>
</div>
<div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: colors.textMuted }}>
Rotation ({selectedComponent.config.rotation || -45}°)
</label>
<input
@@ -1089,14 +1092,14 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
config: { ...selectedComponent.config, rotation: Number(e.target.value) }
})}
className="w-full"
- style={{ accentColor: FINCEPT_COLORS.ORANGE }}
+ style={{ accentColor: colors.primary }}
/>
</div>
</>
)}
{/* Actions */}
- <div className="pt-4 border-t" style={{ borderColor: FINCEPT_COLORS.BORDER }}>
+ <div className="pt-4 border-t" style={{ borderColor: colors.panel }}>
<div className="flex gap-2 mb-2">
<button
onClick={() => onDuplicateComponent(selectedComponent.id)}
@@ -1116,7 +1119,7 @@ export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
<button
onClick={onSaveAsTemplate}
className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors flex items-center justify-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<BookmarkPlus size={14} />
Save as Template
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/ReportBuilderTab.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/ReportBuilderTab.tsx
index 0ba3c295d..963c09adb 100644
--- a/fincept-terminal-desktop/src/components/tabs/report-builder/ReportBuilderTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/ReportBuilderTab.tsx
@@ -11,6 +11,7 @@ import {
import { toast } from '@/components/ui/terminal-toast';
import { useTranslation } from 'react-i18next';
import { showPrompt } from '@/utils/notifications';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { ReportComponent } from '@/services/core/reportService';
import { ComponentTemplate, brandKitService, BrandKit, HeaderFooterTemplate, ParagraphStyles } from '@/services/core/brandKitService';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
@@ -51,10 +52,10 @@ import {
// Import types and constants
import { PageTheme, RightPanelView } from './types';
-import { FINCEPT_COLORS } from './constants';
const ReportBuilderTab: React.FC = () => {
const { t } = useTranslation('reportBuilder');
+ const { colors, fontSize } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
// Template management hook
@@ -320,7 +321,7 @@ const ReportBuilderTab: React.FC = () => {
}, [addComponent, template, setTemplateWithHistory]);
return (
- <div className="h-full flex flex-col" style={{ backgroundColor: FINCEPT_COLORS.DARK_BG, color: FINCEPT_COLORS.TEXT_PRIMARY }}>
+ <div className="h-full flex flex-col" style={{ backgroundColor: colors.background, color: colors.text }}>
{/* Header */}
<ReportHeader
canUndo={canUndo}
@@ -383,15 +384,19 @@ const ReportBuilderTab: React.FC = () => {
/>
{/* Right Panel - Properties, AI Chat, and Advanced Styling */}
- <div className="w-1/5 border-l flex flex-col min-h-0" style={{ borderColor: FINCEPT_COLORS.BORDER, backgroundColor: FINCEPT_COLORS.PANEL_BG }}>
+ <div className="w-1/5 border-l flex flex-col min-h-0" style={{ borderColor: colors.panel, backgroundColor: colors.panel }}>
{/* Toggle Buttons */}
- <div className="flex flex-wrap border-b" style={{ borderColor: FINCEPT_COLORS.BORDER }}>
+ <div className="flex flex-wrap border-b" style={{ borderColor: colors.panel }}>
<button
onClick={() => setRightPanelView('properties')}
- className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${
- rightPanelView === 'properties' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
+ className={`flex-1 px-2 py-2 font-semibold transition-colors flex items-center justify-center gap-1 ${
+ rightPanelView === 'properties' ? 'hover:opacity-90' : 'bg-transparent hover:bg-[#2a2a2a]'
}`}
- style={{ color: rightPanelView === 'properties' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{
+ fontSize: fontSize.tiny,
+ backgroundColor: rightPanelView === 'properties' ? colors.primary : 'transparent',
+ color: rightPanelView === 'properties' ? '#000' : colors.text
+ }}
title="Component Properties"
>
<SettingsIcon size={12} />
@@ -399,10 +404,14 @@ const ReportBuilderTab: React.FC = () => {
</button>
<button
onClick={() => setRightPanelView('styling')}
- className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${
- rightPanelView === 'styling' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
+ className={`flex-1 px-2 py-2 font-semibold transition-colors flex items-center justify-center gap-1 ${
+ rightPanelView === 'styling' ? 'hover:opacity-90' : 'bg-transparent hover:bg-[#2a2a2a]'
}`}
- style={{ color: rightPanelView === 'styling' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{
+ fontSize: fontSize.tiny,
+ backgroundColor: rightPanelView === 'styling' ? colors.primary : 'transparent',
+ color: rightPanelView === 'styling' ? '#000' : colors.text
+ }}
title="Advanced Styling"
>
<Palette size={12} />
@@ -410,10 +419,14 @@ const ReportBuilderTab: React.FC = () => {
</button>
<button
onClick={() => setRightPanelView('chat')}
- className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${
- rightPanelView === 'chat' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
+ className={`flex-1 px-2 py-2 font-semibold transition-colors flex items-center justify-center gap-1 ${
+ rightPanelView === 'chat' ? 'hover:opacity-90' : 'bg-transparent hover:bg-[#2a2a2a]'
}`}
- style={{ color: rightPanelView === 'chat' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{
+ fontSize: fontSize.tiny,
+ backgroundColor: rightPanelView === 'chat' ? colors.primary : 'transparent',
+ color: rightPanelView === 'chat' ? '#000' : colors.text
+ }}
title="AI Writing Assistant"
>
<Bot size={12} />
@@ -421,20 +434,28 @@ const ReportBuilderTab: React.FC = () => {
</button>
<button
onClick={() => setRightPanelView('comments')}
- className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${
- rightPanelView === 'comments' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
+ className={`flex-1 px-2 py-2 font-semibold transition-colors flex items-center justify-center gap-1 ${
+ rightPanelView === 'comments' ? 'hover:opacity-90' : 'bg-transparent hover:bg-[#2a2a2a]'
}`}
- style={{ color: rightPanelView === 'comments' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{
+ fontSize: fontSize.tiny,
+ backgroundColor: rightPanelView === 'comments' ? colors.primary : 'transparent',
+ color: rightPanelView === 'comments' ? '#000' : colors.text
+ }}
title="Comments"
>
<MessageCircle size={12} />
</button>
<button
onClick={() => setRightPanelView('history')}
- className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${
- rightPanelView === 'history' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
+ className={`flex-1 px-2 py-2 font-semibold transition-colors flex items-center justify-center gap-1 ${
+ rightPanelView === 'history' ? 'hover:opacity-90' : 'bg-transparent hover:bg-[#2a2a2a]'
}`}
- style={{ color: rightPanelView === 'history' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{
+ fontSize: fontSize.tiny,
+ backgroundColor: rightPanelView === 'history' ? colors.primary : 'transparent',
+ color: rightPanelView === 'history' ? '#000' : colors.text
+ }}
title="Version History"
>
<History size={12} />
@@ -443,7 +464,7 @@ const ReportBuilderTab: React.FC = () => {
{/* Properties Section */}
{(rightPanelView === 'properties' || rightPanelView === 'split') && (
- <div className={`${rightPanelView === 'split' ? 'flex-1 border-b' : 'flex-1'} overflow-y-auto min-h-0`} style={{ borderColor: FINCEPT_COLORS.BORDER }}>
+ <div className={`${rightPanelView === 'split' ? 'flex-1 border-b' : 'flex-1'} overflow-y-auto min-h-0`} style={{ borderColor: colors.panel }}>
<PropertiesPanel
selectedComponent={selectedComp}
onUpdateComponent={updateComponent}
@@ -595,13 +616,13 @@ const ReportBuilderTab: React.FC = () => {
<TabFooter
tabName="REPORT BUILDER"
leftInfo={[
- { label: `Components: ${template.components.length}`, color: FINCEPT_COLORS.TEXT_PRIMARY },
- { label: `Theme: ${pageTheme.charAt(0).toUpperCase() + pageTheme.slice(1)}`, color: FINCEPT_COLORS.TEXT_PRIMARY },
- ...(activeBrandKit ? [{ label: `Brand: ${activeBrandKit.name}`, color: FINCEPT_COLORS.ORANGE }] : []),
+ { label: `Components: ${template.components.length}`, color: colors.text },
+ { label: `Theme: ${pageTheme.charAt(0).toUpperCase() + pageTheme.slice(1)}`, color: colors.text },
+ ...(activeBrandKit ? [{ label: `Brand: ${activeBrandKit.name}`, color: colors.primary }] : []),
]}
statusInfo={`${currentTime.toLocaleTimeString()} | Multi-format Export`}
- backgroundColor={FINCEPT_COLORS.PANEL_BG}
- borderColor={FINCEPT_COLORS.ORANGE}
+ backgroundColor={colors.panel}
+ borderColor={colors.primary}
/>
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/ReportHeader.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/ReportHeader.tsx
index 3fda3188b..4a908f47e 100644
--- a/fincept-terminal-desktop/src/components/tabs/report-builder/ReportHeader.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/ReportHeader.tsx
@@ -11,8 +11,8 @@ import {
LayoutTemplate,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { ReportHeaderProps } from './types';
-import { FINCEPT_COLORS } from './constants';
export const ReportHeader: React.FC<ReportHeaderProps> = ({
canUndo,
@@ -31,16 +31,17 @@ export const ReportHeader: React.FC<ReportHeaderProps> = ({
hasComponents,
}) => {
const { t } = useTranslation('reportBuilder');
+ const { colors, fontSize } = useTerminalTheme();
return (
<div
className="flex items-center justify-between px-4 py-2 border-b"
- style={{ borderColor: FINCEPT_COLORS.BORDER, backgroundColor: FINCEPT_COLORS.PANEL_BG }}
+ style={{ borderColor: colors.panel, backgroundColor: colors.panel }}
>
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
- <FileText className="w-5 h-5" style={{ color: FINCEPT_COLORS.ORANGE }} />
- <span className="font-bold text-sm" style={{ color: FINCEPT_COLORS.ORANGE }}>
+ <FileText className="w-5 h-5" style={{ color: colors.primary }} />
+ <span className="font-bold text-sm" style={{ color: colors.primary }}>
{t('title')}
</span>
</div>
@@ -81,7 +82,7 @@ export const ReportHeader: React.FC<ReportHeaderProps> = ({
{/* Auto-save status */}
{lastSaved && (
- <span className="text-[10px]" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <span className="text-[10px]" style={{ color: colors.textMuted }}>
{isAutoSaving ? 'Saving...' : `Saved ${lastSaved.toLocaleTimeString()}`}
</span>
)}
@@ -91,7 +92,7 @@ export const ReportHeader: React.FC<ReportHeaderProps> = ({
<button
onClick={onTemplateGallery}
className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<LayoutTemplate size={14} />
Templates
@@ -99,7 +100,7 @@ export const ReportHeader: React.FC<ReportHeaderProps> = ({
<button
onClick={onLoad}
className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<FolderOpen size={14} />
{t('header.load')}
@@ -108,7 +109,7 @@ export const ReportHeader: React.FC<ReportHeaderProps> = ({
onClick={onSave}
disabled={isSaving}
className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1 disabled:opacity-50"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ style={{ color: colors.text }}
>
<Save size={14} />
{isSaving ? t('header.saving') : t('header.save')}
@@ -118,8 +119,8 @@ export const ReportHeader: React.FC<ReportHeaderProps> = ({
disabled={!hasComponents}
className="px-3 py-1 text-xs rounded transition-colors flex items-center gap-1 disabled:opacity-50"
style={{
- backgroundColor: FINCEPT_COLORS.ORANGE,
- color: FINCEPT_COLORS.BLACK,
+ backgroundColor: colors.primary,
+ color: '#000',
fontWeight: 'bold'
}}
>
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/constants.ts b/fincept-terminal-desktop/src/components/tabs/report-builder/constants.ts
index 5ecbffed4..8c4c0d02a 100644
--- a/fincept-terminal-desktop/src/components/tabs/report-builder/constants.ts
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/constants.ts
@@ -1,15 +1,5 @@
-// Fincept color palette for Report Builder
-export const FINCEPT_COLORS = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- BLACK: '#000000',
- DARK_BG: '#0a0a0a',
- PANEL_BG: '#1a1a1a',
- BORDER: '#333333',
- HOVER: '#2a2a2a',
- TEXT_PRIMARY: '#FFFFFF',
- TEXT_SECONDARY: '#999999',
-} as const;
+// Theme colors are now provided by useTerminalTheme() hook
+// Import with: import { useTerminalTheme } from '@/contexts/ThemeContext';
// Page theme options
export const PAGE_THEMES = {
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/LLMConfigSection.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/LLMConfigSection.tsx
deleted file mode 100644
index 4c032350f..000000000
--- a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/LLMConfigSection.tsx
+++ /dev/null
@@ -1,1474 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { Save, RefreshCw, Bot, Edit3, Zap, Key, Check, Plus, X, Trash2, ToggleLeft, ToggleRight, Eye, EyeOff, Settings as SettingsIcon } from 'lucide-react';
-import { sqliteService, type LLMConfig, type LLMGlobalSettings, type LLMModelConfig } from '@/services/core/sqliteService';
-import { ollamaService } from '@/services/chat/ollamaService';
-import { LLMModelsService, type ModelInfo } from '@/services/llmModelsService';
-import type { SettingsColors } from '../types';
-
-// Fincept Design System Colors
-const FINCEPT = {
- 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',
-};
-
-interface LLMConfigSectionProps {
- colors: SettingsColors;
- llmConfigs: LLMConfig[];
- setLlmConfigs: React.Dispatch<React.SetStateAction<LLMConfig[]>>;
- llmGlobalSettings: LLMGlobalSettings;
- setLlmGlobalSettings: React.Dispatch<React.SetStateAction<LLMGlobalSettings>>;
- modelConfigs: LLMModelConfig[];
- loading: boolean;
- setLoading: (loading: boolean) => void;
- showMessage: (type: 'success' | 'error', text: string) => void;
- loadLLMConfigs: () => Promise<{ configs: LLMConfig[]; modelCfgs: LLMModelConfig[] }>;
- sessionApiKey?: string;
-}
-
-export function LLMConfigSection({
- colors,
- llmConfigs,
- setLlmConfigs,
- llmGlobalSettings,
- setLlmGlobalSettings,
- modelConfigs: initialModelConfigs,
- loading,
- setLoading,
- showMessage,
- loadLLMConfigs,
- sessionApiKey,
-}: LLMConfigSectionProps) {
- const [activeProvider, setActiveProvider] = useState<string>('fincept');
- const [ollamaModels, setOllamaModels] = useState<string[]>([]);
- const [ollamaLoading, setOllamaLoading] = useState(false);
- const [ollamaError, setOllamaError] = useState<string | null>(null);
- const [useManualEntry, setUseManualEntry] = useState(false);
- const [providerModels, setProviderModels] = useState<ModelInfo[]>([]);
- const [providerModelsLoading, setProviderModelsLoading] = useState(false);
- const [providerModelsError, setProviderModelsError] = useState<string | null>(null);
- const [modelConfigs, setModelConfigs] = useState<LLMModelConfig[]>(initialModelConfigs);
- const [showAddModel, setShowAddModel] = useState(false);
- const [newModelConfig, setNewModelConfig] = useState({
- provider: 'openai',
- model_id: '',
- display_name: '',
- api_key: '',
- base_url: ''
- });
- const [newModelConfigModels, setNewModelConfigModels] = useState<ModelInfo[]>([]);
- const [showApiKeys, setShowApiKeys] = useState<Record<string, boolean>>({});
-
- useEffect(() => {
- setModelConfigs(initialModelConfigs);
- }, [initialModelConfigs]);
-
- useEffect(() => {
- const activeConfig = llmConfigs.find(c => c.is_active);
- const specialProviders = ['fincept', 'ollama'];
- const providersWithModels = new Set(modelConfigs.filter(m => m.is_enabled).map(m => m.provider));
-
- const isProviderVisible = (provider: string, config?: LLMConfig) => {
- if (specialProviders.includes(provider)) return true;
- if (config?.api_key && config.api_key.trim() !== '') return true;
- if (providersWithModels.has(provider)) return true;
- return false;
- };
-
- if (activeConfig && isProviderVisible(activeConfig.provider, activeConfig)) {
- setActiveProvider(activeConfig.provider);
- } else {
- setActiveProvider('fincept');
- }
- }, [llmConfigs, modelConfigs]);
-
- const getCurrentLLMConfig = () => {
- if (activeProvider.startsWith('model:')) {
- const modelId = activeProvider.replace('model:', '');
- const modelConfig = modelConfigs.find(m => m.id === modelId);
- if (modelConfig) {
- return {
- provider: modelConfig.provider,
- api_key: modelConfig.api_key || '',
- base_url: modelConfig.base_url || '',
- model: modelConfig.model_id,
- is_active: true,
- created_at: modelConfig.created_at || new Date().toISOString(),
- updated_at: modelConfig.updated_at || new Date().toISOString()
- } as LLMConfig;
- }
- }
- return llmConfigs.find(c => c.provider === activeProvider);
- };
-
- const getSelectedModelConfig = () => {
- if (activeProvider.startsWith('model:')) {
- const modelId = activeProvider.replace('model:', '');
- return modelConfigs.find(m => m.id === modelId);
- }
- return null;
- };
-
- const getVisibleProviderConfigs = () => {
- const specialProviders = ['fincept', 'ollama'];
- const providersWithModels = new Set(modelConfigs.filter(m => m.is_enabled).map(m => m.provider));
-
- return llmConfigs.filter(config => {
- if (specialProviders.includes(config.provider)) return true;
- if (config.api_key && config.api_key.trim() !== '') return true;
- if (providersWithModels.has(config.provider)) return true;
- return false;
- });
- };
-
- const visibleProviderConfigs = getVisibleProviderConfigs();
-
- const updateLLMConfig = (provider: string, field: keyof LLMConfig, value: any) => {
- setLlmConfigs(prev => prev.map(config =>
- config.provider === provider ? { ...config, [field]: value } : config
- ));
- };
-
- const fetchOllamaModels = async () => {
- setOllamaLoading(true);
- setOllamaError(null);
-
- const currentConfig = getCurrentLLMConfig();
- const baseUrl = currentConfig?.base_url || 'http://localhost:11434';
-
- const result = await ollamaService.listModels(baseUrl);
-
- if (result.success && result.models) {
- setOllamaModels(result.models);
- setOllamaError(null);
- } else {
- setOllamaModels([]);
- setOllamaError(result.error || 'Failed to fetch models');
- }
-
- setOllamaLoading(false);
- };
-
- const fetchProviderModels = async (forceRefresh: boolean = false) => {
- const currentConfig = getCurrentLLMConfig();
- if (!currentConfig) return;
-
- const provider = currentConfig.provider;
- if (provider === 'ollama' || provider === 'fincept') return;
-
- setProviderModelsLoading(true);
- setProviderModelsError(null);
-
- try {
- const result = await LLMModelsService.getModels(
- provider,
- currentConfig.api_key || undefined,
- currentConfig.base_url || undefined
- );
-
- if (result.models && result.models.length > 0) {
- setProviderModels(result.models);
- setProviderModelsError(null);
- } else if (result.error) {
- setProviderModelsError(result.error);
- setProviderModels([]);
- } else {
- setProviderModels([]);
- setProviderModelsError('No models available for this provider');
- }
- } catch (error) {
- setProviderModelsError(error instanceof Error ? error.message : 'Failed to fetch models');
- setProviderModels([]);
- } finally {
- setProviderModelsLoading(false);
- }
- };
-
- useEffect(() => {
- const loadModels = async () => {
- const currentConfig = getCurrentLLMConfig();
- if (!currentConfig) return;
-
- const provider = currentConfig.provider;
- setProviderModels([]);
- setProviderModelsError(null);
-
- if (provider === 'ollama') {
- fetchOllamaModels();
- } else if (provider !== 'fincept') {
- setProviderModelsLoading(true);
- try {
- const result = await LLMModelsService.getModels(
- provider,
- currentConfig.api_key || undefined,
- currentConfig.base_url || undefined
- );
- if (result.models && result.models.length > 0) {
- setProviderModels(result.models);
- }
- } catch (error) {
- console.error('Error fetching models:', error);
- } finally {
- setProviderModelsLoading(false);
- }
- }
- };
-
- loadModels();
- }, [activeProvider]);
-
- useEffect(() => {
- const loadNewModelConfigModels = async () => {
- if (!showAddModel) return;
-
- try {
- const models = await LLMModelsService.getModelsByProvider(newModelConfig.provider);
- if (models && models.length > 0) {
- setNewModelConfigModels(models);
- } else {
- setNewModelConfigModels([]);
- }
- } catch (error) {
- setNewModelConfigModels([]);
- }
- };
-
- loadNewModelConfigModels();
- }, [newModelConfig.provider, showAddModel]);
-
- const handleSaveLLMConfig = async () => {
- try {
- setLoading(true);
-
- if (activeProvider.startsWith('model:')) {
- const modelId = activeProvider.replace('model:', '');
- const selectedModel = modelConfigs.find(m => m.id === modelId);
-
- if (selectedModel) {
- const modelLLMConfig: LLMConfig = {
- provider: selectedModel.provider,
- api_key: selectedModel.api_key || '',
- base_url: selectedModel.base_url || LLMModelsService.getProviderBaseUrl(selectedModel.provider),
- model: selectedModel.model_id.includes('/')
- ? selectedModel.model_id.split('/').pop() || selectedModel.model_id
- : selectedModel.model_id,
- is_active: true,
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString()
- };
-
- await sqliteService.saveLLMConfig(modelLLMConfig);
- await sqliteService.setActiveLLMProvider(selectedModel.provider);
- }
- } else {
- for (const config of llmConfigs) {
- await sqliteService.saveLLMConfig(config);
- }
- await sqliteService.setActiveLLMProvider(activeProvider);
- }
-
- await sqliteService.saveLLMGlobalSettings(llmGlobalSettings);
- showMessage('success', 'LLM configuration saved successfully');
- await loadLLMConfigs();
- } catch (error) {
- showMessage('error', 'Failed to save LLM configuration');
- } finally {
- setLoading(false);
- }
- };
-
- const handleAddModelConfig = async () => {
- if (!newModelConfig.model_id) {
- showMessage('error', 'Model ID is required');
- return;
- }
-
- try {
- setLoading(true);
- const id = crypto.randomUUID();
- const displayName = newModelConfig.display_name || `${newModelConfig.provider.toUpperCase()}: ${newModelConfig.model_id}`;
-
- const result = await sqliteService.saveLLMModelConfig({
- id,
- provider: newModelConfig.provider,
- model_id: newModelConfig.model_id,
- display_name: displayName,
- api_key: newModelConfig.api_key || undefined,
- base_url: newModelConfig.base_url || undefined,
- is_enabled: true,
- is_default: modelConfigs.filter(m => m.provider === newModelConfig.provider).length === 0
- });
-
- if (result.success) {
- showMessage('success', 'Model configuration added');
- setNewModelConfig({
- provider: 'openai',
- model_id: '',
- display_name: '',
- api_key: '',
- base_url: ''
- });
- setShowAddModel(false);
- await loadLLMConfigs();
- } else {
- showMessage('error', result.message);
- }
- } catch (error) {
- showMessage('error', 'Failed to add model configuration');
- } finally {
- setLoading(false);
- }
- };
-
- const handleDeleteModelConfig = async (id: string) => {
- try {
- setLoading(true);
- const modelToDelete = modelConfigs.find(m => m.id === id);
- const deletedProvider = modelToDelete?.provider;
-
- const result = await sqliteService.deleteLLMModelConfig(id);
- if (result.success) {
- showMessage('success', 'Model configuration deleted');
-
- if (activeProvider === `model:${id}`) {
- setActiveProvider('fincept');
- } else if (deletedProvider && activeProvider === deletedProvider) {
- const remainingModelsForProvider = modelConfigs.filter(
- m => m.id !== id && m.provider === deletedProvider && m.is_enabled
- );
- const providerConfig = llmConfigs.find(c => c.provider === deletedProvider);
- const hasApiKey = providerConfig?.api_key && providerConfig.api_key.trim() !== '';
- const isSpecial = ['fincept', 'ollama'].includes(deletedProvider);
-
- if (remainingModelsForProvider.length === 0 && !hasApiKey && !isSpecial) {
- setActiveProvider('fincept');
- }
- }
-
- await loadLLMConfigs();
- } else {
- showMessage('error', result.message);
- }
- } catch (error) {
- showMessage('error', 'Failed to delete model configuration');
- } finally {
- setLoading(false);
- }
- };
-
- const handleToggleModelEnabled = async (id: string) => {
- try {
- const modelToToggle = modelConfigs.find(m => m.id === id);
-
- const result = await sqliteService.toggleLLMModelConfigEnabled(id);
- if (result.success) {
- if (modelToToggle?.is_enabled && activeProvider === `model:${id}`) {
- const defaultProvider = llmConfigs.find(c => c.is_active)?.provider || 'fincept';
- setActiveProvider(defaultProvider);
- }
-
- await loadLLMConfigs();
- }
- } catch (error) {
- showMessage('error', 'Failed to toggle model');
- }
- };
-
- const currentConfig = getCurrentLLMConfig();
-
- return (
- <div style={{
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- display: 'flex',
- flexDirection: 'column',
- gap: '20px'
- }}>
- {/* Header */}
- <div style={{
- borderBottom: `2px solid ${colors.primary}`,
- padding: '16px 0',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <Bot size={24} color={colors.primary} />
- <div>
- <div style={{
- color: colors.primary,
- fontWeight: 700,
- fontSize: '16px',
- letterSpacing: '0.5px',
- }}>
- LLM CONFIGURATION
- </div>
- <div style={{ color: '#888', fontSize: '12px', marginTop: '2px' }}>
- Configure AI providers, models, and global settings
- </div>
- </div>
- </div>
- <button
- onClick={handleSaveLLMConfig}
- disabled={loading}
- style={{
- background: loading ? '#2A2A2A' : colors.primary,
- color: loading ? '#666' : '#000',
- border: 'none',
- padding: '10px 20px',
- fontSize: '12px',
- fontWeight: 700,
- letterSpacing: '0.5px',
- cursor: loading ? 'not-allowed' : 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}
- >
- <Save size={14} />
- {loading ? 'SAVING...' : 'SAVE ALL SETTINGS'}
- </button>
- </div>
-
- {/* Provider Selection */}
- <div style={{
- backgroundColor: '#0F0F0F',
- border: `1px solid #2A2A2A`,
- padding: '20px'
- }}>
- <div style={{
- color: colors.primary,
- fontSize: '13px',
- fontWeight: 700,
- marginBottom: '16px',
- letterSpacing: '0.5px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}>
- <Zap size={16} color={colors.primary} />
- SELECT AI PROVIDER
- </div>
-
- <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', marginBottom: '16px' }}>
- {visibleProviderConfigs.map(config => (
- <button
- key={config.provider}
- onClick={() => setActiveProvider(config.provider)}
- style={{
- padding: '12px 20px',
- backgroundColor: activeProvider === config.provider ? colors.primary : '#1A1A1A',
- border: `2px solid ${activeProvider === config.provider ? colors.primary : '#2A2A2A'}`,
- color: activeProvider === config.provider ? '#000' : '#FFF',
- cursor: 'pointer',
- fontSize: '13px',
- fontWeight: 700,
- letterSpacing: '0.5px',
- transition: 'all 0.2s',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}
- >
- {config.provider === 'fincept' && <span style={{ color: activeProvider === config.provider ? '#000' : colors.success }}>●</span>}
- {config.provider.toUpperCase()}
- </button>
- ))}
- </div>
-
- {/* Custom Models from Model Library */}
- {modelConfigs.filter(m => m.is_enabled).length > 0 && (
- <div>
- <div style={{
- color: '#888',
- fontSize: '11px',
- fontWeight: 600,
- marginBottom: '10px',
- letterSpacing: '0.5px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}>
- <Bot size={14} color="#888" />
- CUSTOM MODELS (from Model Library)
- </div>
- <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
- {modelConfigs.filter(m => m.is_enabled).map(model => {
- const isSelected = activeProvider === `model:${model.id}`;
- return (
- <button
- key={model.id}
- onClick={() => setActiveProvider(`model:${model.id}`)}
- style={{
- padding: '10px 16px',
- backgroundColor: isSelected ? colors.secondary : '#1A1A1A',
- border: `2px solid ${isSelected ? colors.secondary : '#2A2A2A'}`,
- color: isSelected ? '#000' : '#FFF',
- cursor: 'pointer',
- fontSize: '12px',
- fontWeight: 600,
- letterSpacing: '0.5px',
- transition: 'all 0.2s',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}
- >
- <span style={{
- padding: '2px 6px',
- background: colors.primary + '30',
- border: `1px solid ${colors.primary}`,
- fontSize: '9px',
- fontWeight: 700,
- color: colors.primary
- }}>
- {model.provider.toUpperCase()}
- </span>
- {model.display_name || model.model_id.split('/').pop()}
- </button>
- );
- })}
- </div>
- </div>
- )}
- </div>
-
- {/* Main Content Grid */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
- {/* Left Column - Provider Config */}
- <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
- {/* Fincept Auto-Configured */}
- {currentConfig && currentConfig.provider === 'fincept' && (
- <div style={{
- backgroundColor: '#0a2a0a',
- border: `2px solid ${colors.success}`,
- padding: '20px'
- }}>
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '10px',
- marginBottom: '12px'
- }}>
- <Check size={20} color={colors.success} />
- <span style={{ color: colors.success, fontSize: '14px', fontWeight: 700 }}>
- FINCEPT LLM - AUTO CONFIGURED
- </span>
- </div>
- <div style={{ color: '#AAA', fontSize: '12px', lineHeight: 1.6 }}>
- <div style={{ marginBottom: '8px' }}>
- Your Fincept API is automatically configured and ready to use.
- </div>
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '16px',
- padding: '12px',
- backgroundColor: '#000',
- border: `1px solid #2A2A2A`
- }}>
- <div>
- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>API KEY</div>
- <div style={{ color: colors.primary, fontSize: '12px', fontFamily: 'monospace' }}>
- {sessionApiKey?.substring(0, 12)}...
- </div>
- </div>
- <div>
- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>COST</div>
- <div style={{ color: '#FFF', fontSize: '12px' }}>5 credits/response</div>
- </div>
- <div>
- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>MODEL</div>
- <div style={{ color: '#FFF', fontSize: '12px' }}>fincept-llm</div>
- </div>
- </div>
- </div>
- </div>
- )}
-
- {/* Custom Model from Model Library */}
- {getSelectedModelConfig() && (
- <div style={{
- backgroundColor: '#0a1a2a',
- border: `2px solid ${colors.secondary}`,
- padding: '20px'
- }}>
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '10px',
- marginBottom: '12px'
- }}>
- <Bot size={20} color={colors.secondary} />
- <span style={{ color: colors.secondary, fontSize: '14px', fontWeight: 700 }}>
- CUSTOM MODEL - {getSelectedModelConfig()!.display_name || getSelectedModelConfig()!.model_id}
- </span>
- </div>
- <div style={{ color: '#AAA', fontSize: '12px', lineHeight: 1.6 }}>
- <div style={{ marginBottom: '8px' }}>
- This model uses the native <strong style={{ color: colors.primary }}>{getSelectedModelConfig()!.provider.toUpperCase()}</strong> API directly.
- </div>
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '16px',
- padding: '12px',
- backgroundColor: '#000',
- border: `1px solid #2A2A2A`,
- flexWrap: 'wrap'
- }}>
- <div>
- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>PROVIDER</div>
- <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 600 }}>
- {getSelectedModelConfig()!.provider.toUpperCase()}
- </div>
- </div>
- <div>
- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>MODEL</div>
- <div style={{ color: '#FFF', fontSize: '12px', fontFamily: 'monospace' }}>
- {getSelectedModelConfig()!.model_id.includes('/')
- ? getSelectedModelConfig()!.model_id.split('/').pop()
- : getSelectedModelConfig()!.model_id}
- </div>
- </div>
- <div>
- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>API KEY</div>
- <div style={{ color: getSelectedModelConfig()!.api_key ? colors.success : colors.alert, fontSize: '12px' }}>
- {getSelectedModelConfig()!.api_key ? 'Custom key set' : 'No API key'}
- </div>
- </div>
- </div>
- {!getSelectedModelConfig()!.api_key && (
- <div style={{
- marginTop: '12px',
- padding: '10px',
- background: '#3a0a0a',
- border: `1px solid ${colors.alert}`,
- color: colors.alert,
- fontSize: '11px'
- }}>
- Warning: No API key set for this model. Add your {getSelectedModelConfig()!.provider.toUpperCase()} API key in the Model Library or main provider config.
- </div>
- )}
- </div>
- </div>
- )}
-
- {/* Provider Configuration */}
- {currentConfig && currentConfig.provider !== 'fincept' && !getSelectedModelConfig() && (
- <div style={{
- backgroundColor: '#0F0F0F',
- border: `1px solid #2A2A2A`,
- padding: '20px'
- }}>
- <div style={{
- color: colors.primary,
- fontSize: '13px',
- fontWeight: 700,
- marginBottom: '20px',
- letterSpacing: '0.5px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- paddingBottom: '12px',
- borderBottom: `1px solid #2A2A2A`
- }}>
- <Key size={16} color={colors.primary} />
- {currentConfig.provider.toUpperCase()} CONFIGURATION
- </div>
-
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {/* API Key */}
- {currentConfig.provider !== 'ollama' && (
- <div>
- <label style={{
- color: '#FFF',
- fontSize: '11px',
- display: 'block',
- marginBottom: '8px',
- fontWeight: 600,
- letterSpacing: '0.5px'
- }}>
- API KEY <span style={{ color: colors.alert }}>*</span>
- </label>
- <input
- type="password"
- value={currentConfig.api_key || ''}
- onChange={(e) => updateLLMConfig(activeProvider, 'api_key', e.target.value)}
- placeholder={`Enter your ${activeProvider} API key`}
- style={{
- width: '100%',
- background: '#000',
- border: `1px solid #2A2A2A`,
- color: '#FFF',
- padding: '12px 14px',
- fontSize: '13px',
- fontFamily: '"IBM Plex Mono", monospace',
- outline: 'none'
- }}
- />
- </div>
- )}
-
- {/* Base URL */}
- {(currentConfig.provider === 'ollama' || currentConfig.provider === 'deepseek' || currentConfig.provider === 'openrouter') && (
- <div>
- <label style={{
- color: '#FFF',
- fontSize: '11px',
- display: 'block',
- marginBottom: '8px',
- fontWeight: 600,
- letterSpacing: '0.5px'
- }}>
- BASE URL
- </label>
- <input
- type="text"
- value={currentConfig.base_url || ''}
- onChange={(e) => updateLLMConfig(activeProvider, 'base_url', e.target.value)}
- placeholder={currentConfig.provider === 'ollama' ? 'http://localhost:11434' : 'https://api.example.com'}
- style={{
- width: '100%',
- background: '#000',
- border: `1px solid #2A2A2A`,
- color: '#FFF',
- padding: '12px 14px',
- fontSize: '13px',
- fontFamily: '"IBM Plex Mono", monospace',
- outline: 'none'
- }}
- />
- </div>
- )}
-
- {/* Model Selection */}
- <div>
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- marginBottom: '8px'
- }}>
- <label style={{
- color: '#FFF',
- fontSize: '11px',
- fontWeight: 600,
- letterSpacing: '0.5px'
- }}>
- MODEL
- </label>
- <div style={{ display: 'flex', gap: '8px' }}>
- {currentConfig.provider === 'ollama' ? (
- <button
- onClick={fetchOllamaModels}
- disabled={ollamaLoading}
- style={{
- background: '#1A1A1A',
- border: `1px solid #2A2A2A`,
- color: colors.primary,
- padding: '6px 12px',
- fontSize: '11px',
- cursor: ollamaLoading ? 'not-allowed' : 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontWeight: 600
- }}
- >
- <RefreshCw size={12} className={ollamaLoading ? 'animate-spin' : ''} />
- {ollamaLoading ? 'LOADING...' : 'REFRESH MODELS'}
- </button>
- ) : currentConfig.provider !== 'fincept' && (
- <button
- onClick={() => fetchProviderModels(true)}
- disabled={providerModelsLoading}
- style={{
- background: '#1A1A1A',
- border: `1px solid #2A2A2A`,
- color: colors.primary,
- padding: '6px 12px',
- fontSize: '11px',
- cursor: providerModelsLoading ? 'not-allowed' : 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontWeight: 600
- }}
- >
- <RefreshCw size={12} className={providerModelsLoading ? 'animate-spin' : ''} />
- {providerModelsLoading ? 'LOADING...' : 'REFRESH MODELS'}
- </button>
- )}
- <button
- onClick={() => setUseManualEntry(!useManualEntry)}
- style={{
- background: useManualEntry ? colors.primary : '#1A1A1A',
- border: `1px solid ${useManualEntry ? colors.primary : '#2A2A2A'}`,
- color: useManualEntry ? '#000' : '#FFF',
- padding: '6px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontWeight: 600
- }}
- >
- <Edit3 size={12} />
- {useManualEntry ? 'USE DROPDOWN' : 'MANUAL ENTRY'}
- </button>
- </div>
- </div>
-
- {!useManualEntry ? (
- <div>
- <select
- value={currentConfig.model}
- onChange={(e) => updateLLMConfig(activeProvider, 'model', e.target.value)}
- disabled={
- (currentConfig.provider === 'ollama' && (ollamaLoading || ollamaModels.length === 0)) ||
- (currentConfig.provider !== 'ollama' && currentConfig.provider !== 'fincept' && (providerModelsLoading || providerModels.length === 0))
- }
- style={{
- width: '100%',
- background: '#000',
- border: `1px solid #2A2A2A`,
- color: '#FFF',
- padding: '12px 14px',
- fontSize: '13px',
- cursor: 'pointer'
- }}
- >
- {currentConfig.provider === 'ollama' ? (
- <>
- {ollamaModels.length === 0 && !ollamaLoading && <option value="">No models found - Click REFRESH</option>}
- {ollamaLoading && <option value="">Loading models...</option>}
- {ollamaModels.map((model) => (
- <option key={model} value={model}>{model}</option>
- ))}
- </>
- ) : (
- <>
- {providerModels.length === 0 && !providerModelsLoading && <option value="">No models found - Click REFRESH</option>}
- {providerModelsLoading && <option value="">Loading models...</option>}
- {providerModels.map((model) => (
- <option key={model.id} value={model.id}>
- {model.name} {model.context_window ? `(${(model.context_window / 1000).toFixed(0)}K)` : ''}
- </option>
- ))}
- </>
- )}
- </select>
- {currentConfig.provider === 'ollama' && ollamaError && (
- <div style={{
- marginTop: '8px',
- padding: '10px 12px',
- background: '#3a0a0a',
- border: `1px solid ${colors.alert}`,
- fontSize: '12px',
- color: colors.alert
- }}>
- {ollamaError}
- </div>
- )}
- {currentConfig.provider !== 'ollama' && providerModelsError && (
- <div style={{
- marginTop: '8px',
- padding: '10px 12px',
- background: '#3a0a0a',
- border: `1px solid ${colors.alert}`,
- fontSize: '12px',
- color: colors.alert
- }}>
- {providerModelsError}
- </div>
- )}
- {currentConfig.provider === 'ollama' && ollamaModels.length > 0 && (
- <div style={{
- marginTop: '8px',
- fontSize: '12px',
- color: colors.success,
- display: 'flex',
- alignItems: 'center',
- gap: '6px'
- }}>
- <Check size={14} />
- {ollamaModels.length} model{ollamaModels.length !== 1 ? 's' : ''} available
- </div>
- )}
- {currentConfig.provider !== 'ollama' && currentConfig.provider !== 'fincept' && providerModels.length > 0 && (
- <div style={{
- marginTop: '8px',
- fontSize: '11px',
- color: '#AAA',
- display: 'flex',
- flexDirection: 'column',
- gap: '4px'
- }}>
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- color: colors.success
- }}>
- <Check size={14} />
- {providerModels.length} model{providerModels.length !== 1 ? 's' : ''} available
- </div>
- <div style={{ fontSize: '10px', color: '#666' }}>
- Models fetched from {currentConfig.provider.toUpperCase()} API
- {providerModelsLoading && ' (updating...)'}
- </div>
- </div>
- )}
- </div>
- ) : (
- <input
- type="text"
- value={currentConfig.model}
- onChange={(e) => updateLLMConfig(activeProvider, 'model', e.target.value)}
- placeholder="Enter model name (e.g., gpt-4, claude-3-sonnet)"
- style={{
- width: '100%',
- background: '#000',
- border: `1px solid #2A2A2A`,
- color: '#FFF',
- padding: '12px 14px',
- fontSize: '13px',
- outline: 'none'
- }}
- />
- )}
- </div>
- </div>
- </div>
- )}
-
- {/* Global Settings */}
- <div style={{
- backgroundColor: '#0F0F0F',
- border: `1px solid #2A2A2A`,
- padding: '20px'
- }}>
- <div style={{
- color: colors.primary,
- fontSize: '13px',
- fontWeight: 700,
- marginBottom: '20px',
- letterSpacing: '0.5px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- paddingBottom: '12px',
- borderBottom: `1px solid #2A2A2A`
- }}>
- <SettingsIcon size={16} color={colors.primary} />
- GLOBAL SETTINGS
- </div>
-
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {/* Temperature */}
- <div>
- <label style={{
- color: '#FFF',
- fontSize: '11px',
- display: 'block',
- marginBottom: '8px',
- fontWeight: 600,
- letterSpacing: '0.5px'
- }}>
- TEMPERATURE (Creativity)
- </label>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <input
- type="range"
- min="0"
- max="2"
- step="0.1"
- value={llmGlobalSettings.temperature}
- onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, temperature: parseFloat(e.target.value) })}
- style={{ flex: 1, height: '6px', cursor: 'pointer' }}
- />
- <div style={{
- minWidth: '50px',
- padding: '8px 12px',
- background: colors.primary + '20',
- border: `1px solid ${colors.primary}`,
- color: colors.primary,
- fontSize: '13px',
- fontWeight: 700,
- textAlign: 'center'
- }}>
- {llmGlobalSettings.temperature.toFixed(1)}
- </div>
- </div>
- <div style={{ color: '#666', fontSize: '10px', marginTop: '6px' }}>
- Lower = More focused, Higher = More creative
- </div>
- </div>
-
- {/* Max Tokens */}
- <div>
- <label style={{
- color: '#FFF',
- fontSize: '11px',
- display: 'block',
- marginBottom: '8px',
- fontWeight: 600,
- letterSpacing: '0.5px'
- }}>
- MAX TOKENS (Response Length)
- </label>
- <input
- type="text"
- inputMode="numeric"
- value={String(llmGlobalSettings.max_tokens)}
- onChange={(e) => {
- const v = e.target.value;
- if (v === '' || /^\d+$/.test(v)) {
- setLlmGlobalSettings({ ...llmGlobalSettings, max_tokens: v === '' ? 2048 : parseInt(v) });
- }
- }}
- style={{
- width: '100%',
- background: '#000',
- border: `1px solid #2A2A2A`,
- color: '#FFF',
- padding: '12px 14px',
- fontSize: '13px',
- outline: 'none'
- }}
- />
- </div>
-
- {/* System Prompt */}
- <div>
- <label style={{
- color: '#FFF',
- fontSize: '11px',
- display: 'block',
- marginBottom: '8px',
- fontWeight: 600,
- letterSpacing: '0.5px'
- }}>
- SYSTEM PROMPT (Optional)
- </label>
- <textarea
- value={llmGlobalSettings.system_prompt}
- onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, system_prompt: e.target.value })}
- rows={4}
- placeholder="Custom instructions for the AI assistant..."
- style={{
- width: '100%',
- background: '#000',
- border: `1px solid #2A2A2A`,
- color: '#FFF',
- padding: '12px 14px',
- fontSize: '12px',
- resize: 'vertical',
- fontFamily: '"IBM Plex Mono", monospace',
- lineHeight: '1.5',
- outline: 'none'
- }}
- />
- </div>
- </div>
- </div>
- </div>
-
- {/* Right Column - Model Library */}
- <div style={{
- backgroundColor: '#0F0F0F',
- border: `1px solid #2A2A2A`,
- padding: '20px',
- display: 'flex',
- flexDirection: 'column'
- }}>
- {/* Header */}
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- marginBottom: '20px',
- paddingBottom: '12px',
- borderBottom: `1px solid #2A2A2A`
- }}>
- <div>
- <div style={{
- color: colors.primary,
- fontSize: '13px',
- fontWeight: 700,
- letterSpacing: '0.5px',
- marginBottom: '4px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}>
- <Bot size={16} color={colors.primary} />
- MODEL LIBRARY
- </div>
- <div style={{ color: '#888', fontSize: '11px' }}>
- Add custom models for different use cases
- </div>
- </div>
- <button
- onClick={() => setShowAddModel(!showAddModel)}
- style={{
- background: showAddModel ? '#3a0a0a' : colors.primary,
- color: showAddModel ? colors.alert : '#000',
- border: 'none',
- padding: '8px 16px',
- fontSize: '12px',
- fontWeight: 700,
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '6px'
- }}
- >
- {showAddModel ? <><X size={14} /> CANCEL</> : <><Plus size={14} /> ADD MODEL</>}
- </button>
- </div>
-
- {/* Add Model Form */}
- {showAddModel && (
- <div style={{
- background: '#000',
- border: `1px solid ${colors.primary}`,
- padding: '16px',
- marginBottom: '16px'
- }}>
- <div style={{
- color: colors.primary,
- fontSize: '12px',
- fontWeight: 700,
- marginBottom: '16px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}>
- <Plus size={14} />
- ADD NEW MODEL CONFIGURATION
- </div>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>
- <div>
- <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>
- PROVIDER
- </label>
- <select
- value={newModelConfig.provider}
- onChange={(e) => setNewModelConfig({ ...newModelConfig, provider: e.target.value })}
- style={{
- width: '100%',
- background: '#1A1A1A',
- border: `1px solid #2A2A2A`,
- color: '#FFF',
- padding: '10px 12px',
- fontSize: '12px',
- cursor: 'pointer'
- }}
- >
- <option value="openai">OpenAI</option>
- <option value="anthropic">Anthropic</option>
- <option value="google">Google</option>
- <option value="meta-llama">Meta (Llama)</option>
- <option value="mistralai">Mistral AI</option>
- <option value="x-ai">xAI (Grok)</option>
- <option value="cohere">Cohere</option>
- <option value="deepseek">DeepSeek</option>
- <option value="qwen">Qwen (Alibaba)</option>
- <option value="nvidia">NVIDIA</option>
- <option value="microsoft">Microsoft</option>
- <option value="perplexity">Perplexity</option>
- <option value="groq">Groq</option>
- <option value="ai21">AI21 Labs</option>
- <option value="nousresearch">Nous Research</option>
- <option value="cognitivecomputations">Cognitive Computations</option>
- </select>
- </div>
- <div>
- <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>
- MODEL ID <span style={{ color: colors.alert }}>*</span>
- </label>
- <div style={{ display: 'flex', gap: '8px', alignItems: 'stretch' }}>
- <div style={{ flex: 1 }}>
- {useManualEntry ? (
- <input
- type="text"
- value={newModelConfig.model_id}
- onChange={(e) => setNewModelConfig({ ...newModelConfig, model_id: e.target.value })}
- placeholder="e.g. gpt-4o or openai/gpt-4o"
- style={{
- width: '100%',
- background: '#1A1A1A',
- border: `1px solid #2A2A2A`,
- color: '#FFF',
- padding: '10px 12px',
- fontSize: '12px'
- }}
- />
- ) : (
- <select
- value={newModelConfig.model_id}
- onChange={(e) => setNewModelConfig({ ...newModelConfig, model_id: e.target.value })}
- style={{
- width: '100%',
- background: '#1A1A1A',
- border: `1px solid #2A2A2A`,
- color: '#FFF',
- padding: '10px 12px',
- fontSize: '12px',
- cursor: 'pointer'
- }}
- >
- <option value="">Select a model...</option>
- {newModelConfigModels.map((model) => (
- <option key={model.id} value={model.id}>
- {model.name} {model.context_window ? `(${(model.context_window / 1000).toFixed(0)}K)` : ''}
- </option>
- ))}
- </select>
- )}
- </div>
- <button
- onClick={() => setUseManualEntry(!useManualEntry)}
- style={{
- background: useManualEntry ? colors.primary : '#1A1A1A',
- border: `1px solid ${useManualEntry ? colors.primary : '#2A2A2A'}`,
- color: useManualEntry ? '#000' : colors.primary,
- padding: '10px 12px',
- fontSize: '9px',
- cursor: 'pointer',
- fontWeight: 600,
- whiteSpace: 'nowrap'
- }}
- >
- {useManualEntry ? 'DROPDOWN' : 'MANUAL'}
- </button>
- </div>
- </div>
- </div>
-
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '16px' }}>
- <div>
- <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>
- DISPLAY NAME
- </label>
- <input
- type="text"
- value={newModelConfig.display_name}
- onChange={(e) => setNewModelConfig({ ...newModelConfig, display_name: e.target.value })}
- placeholder="e.g. GPT-4o Mini"
- style={{
- width: '100%',
- background: '#1A1A1A',
- border: `1px solid #2A2A2A`,
- color: '#FFF',
- padding: '10px 12px',
- fontSize: '12px'
- }}
- />
- </div>
- <div>
- <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>
- API KEY (Optional)
- </label>
- <input
- type="password"
- value={newModelConfig.api_key}
- onChange={(e) => setNewModelConfig({ ...newModelConfig, api_key: e.target.value })}
- placeholder="Uses provider key if empty"
- style={{
- width: '100%',
- background: '#1A1A1A',
- border: `1px solid #2A2A2A`,
- color: '#FFF',
- padding: '10px 12px',
- fontSize: '12px',
- fontFamily: 'monospace'
- }}
- />
- </div>
- </div>
-
- <button
- onClick={handleAddModelConfig}
- disabled={loading || !newModelConfig.model_id}
- style={{
- background: loading || !newModelConfig.model_id ? '#2A2A2A' : colors.success,
- color: loading || !newModelConfig.model_id ? '#666' : '#000',
- border: 'none',
- padding: '10px 20px',
- fontSize: '12px',
- fontWeight: 700,
- cursor: loading || !newModelConfig.model_id ? 'not-allowed' : 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}
- >
- <Plus size={14} />
- ADD MODEL
- </button>
- </div>
- )}
-
- {/* Models List */}
- <div style={{ flex: 1, overflowY: 'auto' }}>
- {modelConfigs.length === 0 ? (
- <div style={{
- padding: '40px 20px',
- textAlign: 'center',
- color: '#666',
- border: `1px dashed #2A2A2A`,
- background: '#000'
- }}>
- <Bot size={40} color="#2A2A2A" style={{ marginBottom: '16px' }} />
- <div style={{ fontSize: '13px', marginBottom: '8px', fontWeight: 600, color: '#888' }}>
- No Custom Models Configured
- </div>
- <div style={{ fontSize: '11px', color: '#666' }}>
- Click "ADD MODEL" to add custom model configurations
- </div>
- </div>
- ) : (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
- {modelConfigs.map((model) => (
- <div
- key={model.id}
- style={{
- display: 'flex',
- alignItems: 'center',
- gap: '12px',
- padding: '12px 14px',
- background: model.is_enabled ? '#1A1A1A' : '#0A0A0A',
- border: `1px solid ${model.is_enabled ? '#2A2A2A' : '#1A1A1A'}`,
- opacity: model.is_enabled ? 1 : 0.6
- }}
- >
- <button
- onClick={() => handleToggleModelEnabled(model.id)}
- style={{
- background: 'transparent',
- border: 'none',
- cursor: 'pointer',
- padding: 0
- }}
- >
- {model.is_enabled ? (
- <ToggleRight size={24} color={colors.success} />
- ) : (
- <ToggleLeft size={24} color="#666" />
- )}
- </button>
- <div style={{ flex: 1 }}>
- <div style={{
- fontSize: '13px',
- fontWeight: 600,
- color: model.is_enabled ? '#FFF' : '#666',
- marginBottom: '4px'
- }}>
- {model.display_name || model.model_id}
- </div>
- <div style={{
- fontSize: '11px',
- color: '#888',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}>
- <span style={{
- padding: '2px 8px',
- background: colors.primary + '20',
- border: `1px solid ${colors.primary}`,
- color: colors.primary,
- fontWeight: 600,
- fontSize: '10px'
- }}>
- {model.provider.toUpperCase()}
- </span>
- <span style={{ fontFamily: 'monospace' }}>{model.model_id}</span>
- {model.api_key && (
- <span style={{
- padding: '2px 8px',
- background: colors.success + '20',
- border: `1px solid ${colors.success}`,
- color: colors.success,
- fontWeight: 600,
- fontSize: '10px'
- }}>
- HAS KEY
- </span>
- )}
- </div>
- </div>
- <div style={{ display: 'flex', gap: '8px' }}>
- {model.api_key && (
- <button
- onClick={() => setShowApiKeys(prev => ({ ...prev, [model.id]: !prev[model.id] }))}
- style={{
- background: '#1A1A1A',
- border: `1px solid #2A2A2A`,
- color: '#888',
- padding: '6px 8px',
- cursor: 'pointer'
- }}
- >
- {showApiKeys[model.id] ? <EyeOff size={14} /> : <Eye size={14} />}
- </button>
- )}
- <button
- onClick={() => handleDeleteModelConfig(model.id)}
- style={{
- background: '#1A1A1A',
- border: `1px solid #2A2A2A`,
- color: colors.alert,
- padding: '6px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontWeight: 600
- }}
- >
- <Trash2 size={12} />
- DELETE
- </button>
- </div>
- </div>
- ))}
- </div>
- )}
- </div>
-
- {/* Summary */}
- {modelConfigs.length > 0 && (
- <div style={{
- marginTop: '16px',
- padding: '12px 14px',
- background: '#0a2a0a',
- border: `1px solid ${colors.success}`,
- display: 'flex',
- alignItems: 'center',
- gap: '10px'
- }}>
- <Check size={16} color={colors.success} />
- <div style={{ fontSize: '12px', color: colors.success, fontWeight: 600 }}>
- {modelConfigs.filter(m => m.is_enabled).length} ENABLED · {modelConfigs.length} TOTAL MODELS
- </div>
- </div>
- )}
- </div>
- </div>
- </div>
- );
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/index.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/index.ts
index 565c7736f..434c8c9bc 100644
--- a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/index.ts
@@ -1,5 +1,5 @@
export { CredentialsSection } from './CredentialsSection';
-export { LLMConfigSection } from './LLMConfigSection';
+export { LLMConfigSection } from './llm-config';
export { TerminalAppearanceSection } from './TerminalAppearanceSection';
export { StorageCacheSection } from './StorageCacheSection';
export { NotificationsSection } from './NotificationsSection';
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/LLMConfigSection.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/LLMConfigSection.tsx
new file mode 100644
index 000000000..730707f8e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/LLMConfigSection.tsx
@@ -0,0 +1,167 @@
+import React from 'react';
+import { Save, Bot } from 'lucide-react';
+import type { LLMConfigSectionProps } from './types';
+import { createStyles } from './styles';
+import { LLM_PROVIDERS } from './constants';
+import { useLLMConfigState } from './hooks/useLLMConfigState';
+import { useLLMConfigActions } from './hooks/useLLMConfigActions';
+import {
+ ProviderSelector,
+ FinceptConfigPanel,
+ CustomModelConfigPanel,
+ ProviderConfigPanel,
+ GlobalSettingsPanel,
+ ModelLibraryPanel,
+} from './components';
+
+export function LLMConfigSection({
+ colors,
+ llmConfigs,
+ setLlmConfigs,
+ llmGlobalSettings,
+ setLlmGlobalSettings,
+ modelConfigs: initialModelConfigs,
+ loading,
+ setLoading,
+ showMessage,
+ loadLLMConfigs,
+ sessionApiKey,
+}: LLMConfigSectionProps) {
+ const styles = createStyles(colors);
+
+ // Initialize state management
+ const state = useLLMConfigState({
+ llmConfigs,
+ setLlmConfigs,
+ modelConfigs: initialModelConfigs,
+ setLoading,
+ showMessage,
+ loadLLMConfigs,
+ });
+
+ // Initialize actions
+ const actions = useLLMConfigActions({
+ llmConfigs,
+ llmGlobalSettings,
+ modelConfigs: state.modelConfigs,
+ activeProvider: state.activeProvider,
+ setActiveProvider: state.setActiveProvider,
+ setLoading,
+ showMessage,
+ loadLLMConfigs,
+ setShowAddModel: state.setShowAddModel,
+ resetNewModelConfig: state.resetNewModelConfig,
+ });
+
+ const currentConfig = state.getCurrentLLMConfig();
+ const selectedModelConfig = state.getSelectedModelConfig();
+
+ // Determine which panel to show
+ const showFinceptPanel = currentConfig?.provider === LLM_PROVIDERS.FINCEPT;
+ const showCustomModelPanel = !!selectedModelConfig;
+ const showProviderConfigPanel = currentConfig &&
+ currentConfig.provider !== LLM_PROVIDERS.FINCEPT &&
+ !selectedModelConfig;
+
+ return (
+ <div style={styles.container}>
+ {/* Header */}
+ <div style={styles.header}>
+ <div style={styles.headerTitle}>
+ <Bot size={24} color={colors.primary} />
+ <div>
+ <div style={styles.headerTitleText}>LLM CONFIGURATION</div>
+ <div style={styles.headerSubtext}>
+ Configure AI providers, models, and global settings
+ </div>
+ </div>
+ </div>
+ <button
+ onClick={actions.handleSaveLLMConfig}
+ disabled={loading}
+ style={styles.primaryButton(loading)}
+ >
+ <Save size={14} />
+ {loading ? 'SAVING...' : 'SAVE ALL SETTINGS'}
+ </button>
+ </div>
+
+ {/* Provider Selection */}
+ <ProviderSelector
+ colors={colors}
+ activeProvider={state.activeProvider}
+ setActiveProvider={state.setActiveProvider}
+ visibleProviderConfigs={state.visibleProviderConfigs}
+ modelConfigs={state.modelConfigs}
+ />
+
+ {/* Main Content Grid */}
+ <div style={styles.twoColumnGrid}>
+ {/* Left Column - Provider Config */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
+ {/* Fincept Auto-Configured */}
+ {showFinceptPanel && (
+ <FinceptConfigPanel
+ colors={colors}
+ sessionApiKey={sessionApiKey}
+ />
+ )}
+
+ {/* Custom Model from Model Library */}
+ {showCustomModelPanel && selectedModelConfig && (
+ <CustomModelConfigPanel
+ colors={colors}
+ modelConfig={selectedModelConfig}
+ />
+ )}
+
+ {/* Provider Configuration */}
+ {showProviderConfigPanel && (
+ <ProviderConfigPanel
+ colors={colors}
+ currentConfig={currentConfig}
+ activeProvider={state.activeProvider}
+ updateLLMConfig={state.updateLLMConfig}
+ ollamaModels={state.ollamaModels}
+ ollamaLoading={state.ollamaLoading}
+ ollamaError={state.ollamaError}
+ fetchOllamaModels={state.fetchOllamaModels}
+ providerModels={state.providerModels}
+ providerModelsLoading={state.providerModelsLoading}
+ providerModelsError={state.providerModelsError}
+ fetchProviderModels={state.fetchProviderModels}
+ useManualEntry={state.useManualEntryProvider}
+ setUseManualEntry={state.setUseManualEntryProvider}
+ />
+ )}
+
+ {/* Global Settings */}
+ <GlobalSettingsPanel
+ colors={colors}
+ llmGlobalSettings={llmGlobalSettings}
+ setLlmGlobalSettings={setLlmGlobalSettings}
+ />
+ </div>
+
+ {/* Right Column - Model Library */}
+ <ModelLibraryPanel
+ colors={colors}
+ modelConfigs={state.modelConfigs}
+ showAddModel={state.showAddModel}
+ setShowAddModel={state.setShowAddModel}
+ loading={loading}
+ handleAddModelConfig={() => actions.handleAddModelConfig(state.newModelConfig)}
+ handleDeleteModelConfig={actions.handleDeleteModelConfig}
+ handleToggleModelEnabled={actions.handleToggleModelEnabled}
+ newModelConfig={state.newModelConfig}
+ setNewModelConfig={state.setNewModelConfig}
+ newModelConfigModels={state.newModelConfigModels}
+ useManualEntry={state.useManualEntryAddModel}
+ setUseManualEntry={state.setUseManualEntryAddModel}
+ showApiKeys={state.showApiKeys}
+ setShowApiKeys={state.setShowApiKeys}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/AddModelForm.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/AddModelForm.tsx
new file mode 100644
index 000000000..cdfba73a9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/AddModelForm.tsx
@@ -0,0 +1,184 @@
+import React from 'react';
+import { Plus } from 'lucide-react';
+import type { AddModelFormProps } from '../types';
+import { createStyles } from '../styles';
+import { PROVIDER_OPTIONS } from '../constants';
+
+export function AddModelForm({
+ colors,
+ loading,
+ newModelConfig,
+ setNewModelConfig,
+ newModelConfigModels,
+ useManualEntry,
+ setUseManualEntry,
+ onSubmit,
+}: AddModelFormProps) {
+ const styles = createStyles(colors);
+
+ const isSubmitDisabled = loading || !newModelConfig.model_id.trim();
+
+ return (
+ <div style={{
+ background: '#000',
+ border: `1px solid ${colors.primary}`,
+ padding: '16px',
+ marginBottom: '16px'
+ }}>
+ <div style={{
+ color: colors.primary,
+ fontSize: '12px',
+ fontWeight: 700,
+ marginBottom: '16px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <Plus size={14} />
+ ADD NEW MODEL CONFIGURATION
+ </div>
+
+ {/* Provider and Model ID Row */}
+ <div style={styles.formGrid}>
+ <div>
+ <label style={{ ...styles.label, fontSize: '10px', marginBottom: '6px' }}>
+ PROVIDER
+ </label>
+ <select
+ value={newModelConfig.provider}
+ onChange={(e) => setNewModelConfig({ ...newModelConfig, provider: e.target.value, model_id: '' })}
+ style={{
+ ...styles.select,
+ background: '#1A1A1A',
+ padding: '10px 12px',
+ fontSize: '12px'
+ }}
+ >
+ {PROVIDER_OPTIONS.map(option => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <div>
+ <label style={{ ...styles.label, fontSize: '10px', marginBottom: '6px' }}>
+ MODEL ID <span style={styles.labelRequired}>*</span>
+ </label>
+ <div style={{ display: 'flex', gap: '8px', alignItems: 'stretch' }}>
+ <div style={{ flex: 1 }}>
+ {useManualEntry ? (
+ <input
+ type="text"
+ value={newModelConfig.model_id}
+ onChange={(e) => setNewModelConfig({ ...newModelConfig, model_id: e.target.value })}
+ placeholder="e.g. gpt-4o or openai/gpt-4o"
+ style={{
+ ...styles.input,
+ background: '#1A1A1A',
+ padding: '10px 12px',
+ fontSize: '12px'
+ }}
+ />
+ ) : (
+ <select
+ value={newModelConfig.model_id}
+ onChange={(e) => setNewModelConfig({ ...newModelConfig, model_id: e.target.value })}
+ style={{
+ ...styles.select,
+ background: '#1A1A1A',
+ padding: '10px 12px',
+ fontSize: '12px'
+ }}
+ >
+ <option value="">Select a model...</option>
+ {newModelConfigModels.map((model) => (
+ <option key={model.id} value={model.id}>
+ {model.name} {model.context_window ? `(${(model.context_window / 1000).toFixed(0)}K)` : ''}
+ </option>
+ ))}
+ </select>
+ )}
+ </div>
+ <button
+ onClick={() => setUseManualEntry(!useManualEntry)}
+ style={{
+ background: useManualEntry ? colors.primary : '#1A1A1A',
+ border: `1px solid ${useManualEntry ? colors.primary : '#2A2A2A'}`,
+ color: useManualEntry ? '#000' : colors.primary,
+ padding: '10px 12px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: 600,
+ whiteSpace: 'nowrap'
+ }}
+ >
+ {useManualEntry ? 'DROPDOWN' : 'MANUAL'}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Display Name and API Key Row */}
+ <div style={{ ...styles.formGrid, marginBottom: '16px' }}>
+ <div>
+ <label style={{ ...styles.label, fontSize: '10px', marginBottom: '6px' }}>
+ DISPLAY NAME
+ </label>
+ <input
+ type="text"
+ value={newModelConfig.display_name}
+ onChange={(e) => setNewModelConfig({ ...newModelConfig, display_name: e.target.value })}
+ placeholder="e.g. GPT-4o Mini"
+ style={{
+ ...styles.input,
+ background: '#1A1A1A',
+ padding: '10px 12px',
+ fontSize: '12px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ ...styles.label, fontSize: '10px', marginBottom: '6px' }}>
+ API KEY (Optional)
+ </label>
+ <input
+ type="password"
+ value={newModelConfig.api_key}
+ onChange={(e) => setNewModelConfig({ ...newModelConfig, api_key: e.target.value })}
+ placeholder="Uses provider key if empty"
+ style={{
+ ...styles.input,
+ background: '#1A1A1A',
+ padding: '10px 12px',
+ fontSize: '12px',
+ fontFamily: 'monospace'
+ }}
+ />
+ </div>
+ </div>
+
+ {/* Submit Button */}
+ <button
+ onClick={onSubmit}
+ disabled={isSubmitDisabled}
+ style={{
+ background: isSubmitDisabled ? '#2A2A2A' : colors.success,
+ color: isSubmitDisabled ? '#666' : '#000',
+ border: 'none',
+ padding: '10px 20px',
+ fontSize: '12px',
+ fontWeight: 700,
+ cursor: isSubmitDisabled ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}
+ >
+ <Plus size={14} />
+ ADD MODEL
+ </button>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/CustomModelConfigPanel.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/CustomModelConfigPanel.tsx
new file mode 100644
index 000000000..980d6af9e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/CustomModelConfigPanel.tsx
@@ -0,0 +1,65 @@
+import React from 'react';
+import { Bot } from 'lucide-react';
+import type { CustomModelConfigPanelProps } from '../types';
+import { createStyles } from '../styles';
+
+export function CustomModelConfigPanel({ colors, modelConfig }: CustomModelConfigPanelProps) {
+ const styles = createStyles(colors);
+ const displayName = modelConfig.display_name || modelConfig.model_id;
+ const modelIdDisplay = modelConfig.model_id.includes('/')
+ ? modelConfig.model_id.split('/').pop()
+ : modelConfig.model_id;
+
+ return (
+ <div style={styles.infoBox}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ marginBottom: '12px'
+ }}>
+ <Bot size={20} color={colors.secondary} />
+ <span style={{ color: colors.secondary, fontSize: '14px', fontWeight: 700 }}>
+ CUSTOM MODEL - {displayName}
+ </span>
+ </div>
+ <div style={{ color: '#AAA', fontSize: '12px', lineHeight: 1.6 }}>
+ <div style={{ marginBottom: '8px' }}>
+ This model uses the native{' '}
+ <strong style={{ color: colors.primary }}>
+ {modelConfig.provider.toUpperCase()}
+ </strong>{' '}
+ API directly.
+ </div>
+ <div style={{ ...styles.dataRow, flexWrap: 'wrap' }}>
+ <div>
+ <div style={styles.dataLabel}>PROVIDER</div>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 600 }}>
+ {modelConfig.provider.toUpperCase()}
+ </div>
+ </div>
+ <div>
+ <div style={styles.dataLabel}>MODEL</div>
+ <div style={{ ...styles.dataValue, fontFamily: 'monospace' }}>
+ {modelIdDisplay}
+ </div>
+ </div>
+ <div>
+ <div style={styles.dataLabel}>API KEY</div>
+ <div style={{
+ color: modelConfig.api_key ? colors.success : colors.alert,
+ fontSize: '12px'
+ }}>
+ {modelConfig.api_key ? 'Custom key set' : 'No API key'}
+ </div>
+ </div>
+ </div>
+ {!modelConfig.api_key && (
+ <div style={styles.warningBox}>
+ Warning: No API key set for this model. Add your {modelConfig.provider.toUpperCase()} API key in the Model Library or main provider config.
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/FinceptConfigPanel.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/FinceptConfigPanel.tsx
new file mode 100644
index 000000000..192e3e879
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/FinceptConfigPanel.tsx
@@ -0,0 +1,45 @@
+import React from 'react';
+import { Check } from 'lucide-react';
+import type { FinceptConfigPanelProps } from '../types';
+import { createStyles } from '../styles';
+
+export function FinceptConfigPanel({ colors, sessionApiKey }: FinceptConfigPanelProps) {
+ const styles = createStyles(colors);
+
+ return (
+ <div style={styles.successBox}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ marginBottom: '12px'
+ }}>
+ <Check size={20} color={colors.success} />
+ <span style={{ color: colors.success, fontSize: '14px', fontWeight: 700 }}>
+ FINCEPT LLM - AUTO CONFIGURED
+ </span>
+ </div>
+ <div style={{ color: '#AAA', fontSize: '12px', lineHeight: 1.6 }}>
+ <div style={{ marginBottom: '8px' }}>
+ Your Fincept API is automatically configured and ready to use.
+ </div>
+ <div style={styles.dataRow}>
+ <div>
+ <div style={styles.dataLabel}>API KEY</div>
+ <div style={{ color: colors.primary, fontSize: '12px', fontFamily: 'monospace' }}>
+ {sessionApiKey?.substring(0, 12)}...
+ </div>
+ </div>
+ <div>
+ <div style={styles.dataLabel}>COST</div>
+ <div style={styles.dataValue}>5 credits/response</div>
+ </div>
+ <div>
+ <div style={styles.dataLabel}>MODEL</div>
+ <div style={styles.dataValue}>fincept-llm</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/GlobalSettingsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/GlobalSettingsPanel.tsx
new file mode 100644
index 000000000..dcf6d5450
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/GlobalSettingsPanel.tsx
@@ -0,0 +1,93 @@
+import React from 'react';
+import { Settings as SettingsIcon } from 'lucide-react';
+import type { GlobalSettingsPanelProps } from '../types';
+import { createStyles } from '../styles';
+
+export function GlobalSettingsPanel({
+ colors,
+ llmGlobalSettings,
+ setLlmGlobalSettings,
+}: GlobalSettingsPanelProps) {
+ const styles = createStyles(colors);
+
+ const handleTemperatureChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ setLlmGlobalSettings({
+ ...llmGlobalSettings,
+ temperature: parseFloat(e.target.value)
+ });
+ };
+
+ const handleMaxTokensChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const value = e.target.value;
+ if (value === '' || /^\d+$/.test(value)) {
+ setLlmGlobalSettings({
+ ...llmGlobalSettings,
+ max_tokens: value === '' ? 2048 : parseInt(value)
+ });
+ }
+ };
+
+ const handleSystemPromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
+ setLlmGlobalSettings({
+ ...llmGlobalSettings,
+ system_prompt: e.target.value
+ });
+ };
+
+ return (
+ <div style={styles.panel}>
+ <div style={{ ...styles.panelHeader, ...styles.sectionDivider, marginBottom: '20px' }}>
+ <SettingsIcon size={16} color={colors.primary} />
+ GLOBAL SETTINGS
+ </div>
+
+ <div style={styles.flexColumn}>
+ {/* Temperature */}
+ <div>
+ <label style={styles.label}>TEMPERATURE (Creativity)</label>
+ <div style={styles.sliderContainer}>
+ <input
+ type="range"
+ min="0"
+ max="2"
+ step="0.1"
+ value={llmGlobalSettings.temperature}
+ onChange={handleTemperatureChange}
+ style={{ flex: 1, height: '6px', cursor: 'pointer' }}
+ />
+ <div style={styles.sliderValue as React.CSSProperties}>
+ {llmGlobalSettings.temperature.toFixed(1)}
+ </div>
+ </div>
+ <div style={{ color: '#666', fontSize: '10px', marginTop: '6px' }}>
+ Lower = More focused, Higher = More creative
+ </div>
+ </div>
+
+ {/* Max Tokens */}
+ <div>
+ <label style={styles.label}>MAX TOKENS (Response Length)</label>
+ <input
+ type="text"
+ inputMode="numeric"
+ value={String(llmGlobalSettings.max_tokens)}
+ onChange={handleMaxTokensChange}
+ style={styles.input}
+ />
+ </div>
+
+ {/* System Prompt */}
+ <div>
+ <label style={styles.label}>SYSTEM PROMPT (Optional)</label>
+ <textarea
+ value={llmGlobalSettings.system_prompt}
+ onChange={handleSystemPromptChange}
+ rows={4}
+ placeholder="Custom instructions for the AI assistant..."
+ style={styles.textarea as React.CSSProperties}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ModelLibraryPanel.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ModelLibraryPanel.tsx
new file mode 100644
index 000000000..53eb61744
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ModelLibraryPanel.tsx
@@ -0,0 +1,139 @@
+import React from 'react';
+import { Bot, Plus, X, Check } from 'lucide-react';
+import type { ModelLibraryPanelProps } from '../types';
+import { createStyles } from '../styles';
+import { AddModelForm } from './AddModelForm';
+import { ModelListItem } from './ModelListItem';
+
+export function ModelLibraryPanel({
+ colors,
+ modelConfigs,
+ showAddModel,
+ setShowAddModel,
+ loading,
+ handleAddModelConfig,
+ handleDeleteModelConfig,
+ handleToggleModelEnabled,
+ newModelConfig,
+ setNewModelConfig,
+ newModelConfigModels,
+ useManualEntry,
+ setUseManualEntry,
+ showApiKeys,
+ setShowApiKeys,
+}: ModelLibraryPanelProps) {
+ const styles = createStyles(colors);
+ const enabledCount = modelConfigs.filter(m => m.is_enabled).length;
+
+ return (
+ <div style={{
+ ...styles.panel,
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '20px',
+ ...styles.sectionDivider
+ }}>
+ <div>
+ <div style={{
+ ...styles.panelHeader,
+ marginBottom: '4px'
+ }}>
+ <Bot size={16} color={colors.primary} />
+ MODEL LIBRARY
+ </div>
+ <div style={{ color: '#888', fontSize: '11px' }}>
+ Add custom models for different use cases
+ </div>
+ </div>
+ <button
+ onClick={() => setShowAddModel(!showAddModel)}
+ style={{
+ background: showAddModel ? '#3a0a0a' : colors.primary,
+ color: showAddModel ? colors.alert : '#000',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '12px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px'
+ }}
+ >
+ {showAddModel ? (
+ <>
+ <X size={14} /> CANCEL
+ </>
+ ) : (
+ <>
+ <Plus size={14} /> ADD MODEL
+ </>
+ )}
+ </button>
+ </div>
+
+ {/* Add Model Form */}
+ {showAddModel && (
+ <AddModelForm
+ colors={colors}
+ loading={loading}
+ newModelConfig={newModelConfig}
+ setNewModelConfig={setNewModelConfig}
+ newModelConfigModels={newModelConfigModels}
+ useManualEntry={useManualEntry}
+ setUseManualEntry={setUseManualEntry}
+ onSubmit={handleAddModelConfig}
+ onCancel={() => setShowAddModel(false)}
+ />
+ )}
+
+ {/* Models List */}
+ <div style={{ flex: 1, overflowY: 'auto' }}>
+ {modelConfigs.length === 0 ? (
+ <div style={styles.emptyState as React.CSSProperties}>
+ <Bot size={40} color="#2A2A2A" style={{ marginBottom: '16px' }} />
+ <div style={{ fontSize: '13px', marginBottom: '8px', fontWeight: 600, color: '#888' }}>
+ No Custom Models Configured
+ </div>
+ <div style={{ fontSize: '11px', color: '#666' }}>
+ Click "ADD MODEL" to add custom model configurations
+ </div>
+ </div>
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {modelConfigs.map((model) => (
+ <ModelListItem
+ key={model.id}
+ colors={colors}
+ model={model}
+ showApiKey={showApiKeys[model.id] || false}
+ onToggleApiKey={() => setShowApiKeys(prev => ({
+ ...prev,
+ [model.id]: !prev[model.id]
+ }))}
+ onToggleEnabled={() => handleToggleModelEnabled(model.id)}
+ onDelete={() => handleDeleteModelConfig(model.id)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Summary */}
+ {modelConfigs.length > 0 && (
+ <div style={styles.summaryBar}>
+ <Check size={16} color={colors.success} />
+ <div style={{ fontSize: '12px', color: colors.success, fontWeight: 600 }}>
+ {enabledCount} ENABLED · {modelConfigs.length} TOTAL MODELS
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ModelListItem.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ModelListItem.tsx
new file mode 100644
index 000000000..c841090e5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ModelListItem.tsx
@@ -0,0 +1,112 @@
+import React from 'react';
+import { ToggleLeft, ToggleRight, Eye, EyeOff, Trash2 } from 'lucide-react';
+import type { ModelListItemProps } from '../types';
+import { createStyles } from '../styles';
+
+export function ModelListItem({
+ colors,
+ model,
+ showApiKey,
+ onToggleApiKey,
+ onToggleEnabled,
+ onDelete,
+}: ModelListItemProps) {
+ const styles = createStyles(colors);
+
+ return (
+ <div style={styles.modelListItem(model.is_enabled)}>
+ {/* Toggle Button */}
+ <button
+ onClick={onToggleEnabled}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ cursor: 'pointer',
+ padding: 0
+ }}
+ aria-label={model.is_enabled ? 'Disable model' : 'Enable model'}
+ >
+ {model.is_enabled ? (
+ <ToggleRight size={24} color={colors.success} />
+ ) : (
+ <ToggleLeft size={24} color="#666" />
+ )}
+ </button>
+
+ {/* Model Info */}
+ <div style={{ flex: 1 }}>
+ <div style={{
+ fontSize: '13px',
+ fontWeight: 600,
+ color: model.is_enabled ? '#FFF' : '#666',
+ marginBottom: '4px'
+ }}>
+ {model.display_name || model.model_id}
+ </div>
+ <div style={{
+ fontSize: '11px',
+ color: '#888',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ flexWrap: 'wrap'
+ }}>
+ <span style={styles.providerBadge}>
+ {model.provider.toUpperCase()}
+ </span>
+ <span style={{ fontFamily: 'monospace' }}>{model.model_id}</span>
+ {model.api_key && (
+ <span style={{
+ padding: '2px 8px',
+ background: colors.success + '20',
+ border: `1px solid ${colors.success}`,
+ color: colors.success,
+ fontWeight: 600,
+ fontSize: '10px'
+ }}>
+ HAS KEY
+ </span>
+ )}
+ </div>
+ </div>
+
+ {/* Action Buttons */}
+ <div style={{ display: 'flex', gap: '8px' }}>
+ {model.api_key && (
+ <button
+ onClick={onToggleApiKey}
+ style={{
+ background: '#1A1A1A',
+ border: '1px solid #2A2A2A',
+ color: '#888',
+ padding: '6px 8px',
+ cursor: 'pointer'
+ }}
+ aria-label={showApiKey ? 'Hide API key' : 'Show API key'}
+ >
+ {showApiKey ? <EyeOff size={14} /> : <Eye size={14} />}
+ </button>
+ )}
+ <button
+ onClick={onDelete}
+ style={{
+ background: '#1A1A1A',
+ border: '1px solid #2A2A2A',
+ color: colors.alert,
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontWeight: 600
+ }}
+ aria-label="Delete model"
+ >
+ <Trash2 size={12} />
+ DELETE
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ProviderConfigPanel.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ProviderConfigPanel.tsx
new file mode 100644
index 000000000..3ba0d7e49
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ProviderConfigPanel.tsx
@@ -0,0 +1,240 @@
+import React, { useState, useEffect } from 'react';
+import { Key, RefreshCw, Edit3, Check } from 'lucide-react';
+import type { ProviderConfigPanelProps } from '../types';
+import { createStyles } from '../styles';
+import { LLM_PROVIDERS, DEFAULT_OLLAMA_BASE_URL, CUSTOM_MODEL_VALUE } from '../constants';
+
+export function ProviderConfigPanel({
+ colors,
+ currentConfig,
+ activeProvider,
+ updateLLMConfig,
+ ollamaModels,
+ ollamaLoading,
+ ollamaError,
+ fetchOllamaModels,
+ providerModels,
+ providerModelsLoading,
+ providerModelsError,
+ fetchProviderModels,
+ useManualEntry,
+ setUseManualEntry,
+}: ProviderConfigPanelProps) {
+ const styles = createStyles(colors);
+ const [customModelId, setCustomModelId] = useState('');
+ const [isCustomSelected, setIsCustomSelected] = useState(false);
+
+ // Check if current model is a custom one (not in the list)
+ useEffect(() => {
+ if (currentConfig?.model) {
+ const isInOllamaList = ollamaModels.includes(currentConfig.model);
+ const isInProviderList = providerModels.some(m => m.id === currentConfig.model);
+ const isCustom = currentConfig.model && !isInOllamaList && !isInProviderList && currentConfig.model !== '';
+
+ if (isCustom) {
+ setIsCustomSelected(true);
+ setCustomModelId(currentConfig.model);
+ }
+ }
+ }, [currentConfig?.model, ollamaModels, providerModels]);
+
+ if (!currentConfig) return null;
+
+ const isOllama = currentConfig.provider === LLM_PROVIDERS.OLLAMA;
+ const isFincept = currentConfig.provider === LLM_PROVIDERS.FINCEPT;
+ const needsBaseUrl = isOllama ||
+ currentConfig.provider === LLM_PROVIDERS.DEEPSEEK ||
+ currentConfig.provider === 'openrouter';
+
+ const isModelSelectDisabled = isOllama
+ ? ollamaLoading || ollamaModels.length === 0
+ : !isFincept && (providerModelsLoading || providerModels.length === 0);
+
+ const handleSelectChange = (value: string) => {
+ if (value === CUSTOM_MODEL_VALUE) {
+ setIsCustomSelected(true);
+ setCustomModelId('');
+ } else {
+ setIsCustomSelected(false);
+ setCustomModelId('');
+ updateLLMConfig(activeProvider, 'model', value);
+ }
+ };
+
+ const handleCustomModelChange = (value: string) => {
+ setCustomModelId(value);
+ updateLLMConfig(activeProvider, 'model', value);
+ };
+
+ return (
+ <div style={styles.panel}>
+ <div style={{ ...styles.panelHeader, ...styles.sectionDivider, marginBottom: '20px' }}>
+ <Key size={16} color={colors.primary} />
+ {currentConfig.provider.toUpperCase()} CONFIGURATION
+ </div>
+
+ <div style={styles.flexColumn}>
+ {/* API Key - not for Ollama */}
+ {!isOllama && (
+ <div>
+ <label style={styles.label}>
+ API KEY <span style={styles.labelRequired}>*</span>
+ </label>
+ <input
+ type="password"
+ value={currentConfig.api_key || ''}
+ onChange={(e) => updateLLMConfig(activeProvider, 'api_key', e.target.value)}
+ placeholder={`Enter your ${activeProvider} API key`}
+ style={styles.input}
+ />
+ </div>
+ )}
+
+ {/* Base URL - only for specific providers */}
+ {needsBaseUrl && (
+ <div>
+ <label style={styles.label}>BASE URL</label>
+ <input
+ type="text"
+ value={currentConfig.base_url || ''}
+ onChange={(e) => updateLLMConfig(activeProvider, 'base_url', e.target.value)}
+ placeholder={isOllama ? DEFAULT_OLLAMA_BASE_URL : 'https://api.example.com'}
+ style={styles.input}
+ />
+ </div>
+ )}
+
+ {/* Model Selection */}
+ <div>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '8px'
+ }}>
+ <label style={{ ...styles.label, marginBottom: 0 }}>MODEL</label>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ {isOllama ? (
+ <button
+ onClick={fetchOllamaModels}
+ disabled={ollamaLoading}
+ style={styles.secondaryButton(false)}
+ >
+ <RefreshCw size={12} className={ollamaLoading ? 'animate-spin' : ''} />
+ {ollamaLoading ? 'LOADING...' : 'REFRESH MODELS'}
+ </button>
+ ) : !isFincept && (
+ <button
+ onClick={fetchProviderModels}
+ disabled={providerModelsLoading}
+ style={styles.secondaryButton(false)}
+ >
+ <RefreshCw size={12} className={providerModelsLoading ? 'animate-spin' : ''} />
+ {providerModelsLoading ? 'LOADING...' : 'REFRESH MODELS'}
+ </button>
+ )}
+ <button
+ onClick={() => setUseManualEntry(!useManualEntry)}
+ style={styles.secondaryButton(useManualEntry)}
+ >
+ <Edit3 size={12} />
+ {useManualEntry ? 'USE DROPDOWN' : 'MANUAL ENTRY'}
+ </button>
+ </div>
+ </div>
+
+ {!useManualEntry ? (
+ <div>
+ <select
+ value={isCustomSelected ? CUSTOM_MODEL_VALUE : currentConfig.model}
+ onChange={(e) => handleSelectChange(e.target.value)}
+ disabled={isModelSelectDisabled}
+ style={styles.select}
+ >
+ {isOllama ? (
+ <>
+ {ollamaModels.length === 0 && !ollamaLoading && (
+ <option value="">No models found - Click REFRESH</option>
+ )}
+ {ollamaLoading && <option value="">Loading models...</option>}
+ {ollamaModels.map((model) => (
+ <option key={model} value={model}>{model}</option>
+ ))}
+ <option value={CUSTOM_MODEL_VALUE}>── Custom Model ──</option>
+ </>
+ ) : (
+ <>
+ {providerModels.length === 0 && !providerModelsLoading && (
+ <option value="">No models found - Click REFRESH</option>
+ )}
+ {providerModelsLoading && <option value="">Loading models...</option>}
+ {providerModels.map((model) => (
+ <option key={model.id} value={model.id}>
+ {model.name} {model.context_window ? `(${(model.context_window / 1000).toFixed(0)}K)` : ''}
+ </option>
+ ))}
+ <option value={CUSTOM_MODEL_VALUE}>── Custom Model ──</option>
+ </>
+ )}
+ </select>
+
+ {/* Custom Model Input */}
+ {isCustomSelected && (
+ <input
+ type="text"
+ value={customModelId}
+ onChange={(e) => handleCustomModelChange(e.target.value)}
+ placeholder="Enter custom model ID (e.g., gpt-4-turbo-preview)"
+ style={{ ...styles.input, marginTop: '8px' }}
+ />
+ )}
+
+ {/* Error Messages */}
+ {isOllama && ollamaError && (
+ <div style={styles.errorMessage}>{ollamaError}</div>
+ )}
+ {!isOllama && providerModelsError && (
+ <div style={styles.errorMessage}>{providerModelsError}</div>
+ )}
+
+ {/* Success Messages */}
+ {isOllama && ollamaModels.length > 0 && (
+ <div style={styles.successMessage}>
+ <Check size={14} />
+ {ollamaModels.length} model{ollamaModels.length !== 1 ? 's' : ''} available
+ </div>
+ )}
+ {!isOllama && !isFincept && providerModels.length > 0 && (
+ <div style={{
+ marginTop: '8px',
+ fontSize: '11px',
+ color: '#AAA',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '4px'
+ }}>
+ <div style={styles.successMessage}>
+ <Check size={14} />
+ {providerModels.length} model{providerModels.length !== 1 ? 's' : ''} available
+ </div>
+ <div style={{ fontSize: '10px', color: '#666' }}>
+ Models fetched from {currentConfig.provider.toUpperCase()} API
+ {providerModelsLoading && ' (updating...)'}
+ </div>
+ </div>
+ )}
+ </div>
+ ) : (
+ <input
+ type="text"
+ value={currentConfig.model}
+ onChange={(e) => updateLLMConfig(activeProvider, 'model', e.target.value)}
+ placeholder="Enter model name (e.g., gpt-4, claude-3-sonnet)"
+ style={styles.input}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ProviderSelector.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ProviderSelector.tsx
new file mode 100644
index 000000000..161da334d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/ProviderSelector.tsx
@@ -0,0 +1,79 @@
+import React from 'react';
+import { Zap, Bot } from 'lucide-react';
+import type { ProviderSelectorProps } from '../types';
+import { createStyles } from '../styles';
+import { LLM_PROVIDERS } from '../constants';
+
+export function ProviderSelector({
+ colors,
+ activeProvider,
+ setActiveProvider,
+ visibleProviderConfigs,
+ modelConfigs,
+}: ProviderSelectorProps) {
+ const styles = createStyles(colors);
+ const enabledModelConfigs = modelConfigs.filter(m => m.is_enabled);
+
+ return (
+ <div style={styles.panel}>
+ <div style={styles.panelHeader}>
+ <Zap size={16} color={colors.primary} />
+ SELECT AI PROVIDER
+ </div>
+
+ {/* Provider Buttons */}
+ <div style={{ ...styles.flexRow, marginBottom: '16px' }}>
+ {visibleProviderConfigs.map(config => (
+ <button
+ key={config.provider}
+ onClick={() => setActiveProvider(config.provider)}
+ style={styles.providerButton(activeProvider === config.provider)}
+ >
+ {config.provider === LLM_PROVIDERS.FINCEPT && (
+ <span style={{ color: activeProvider === config.provider ? '#000' : colors.success }}>
+ ●
+ </span>
+ )}
+ {config.provider.toUpperCase()}
+ </button>
+ ))}
+ </div>
+
+ {/* Custom Models from Model Library */}
+ {enabledModelConfigs.length > 0 && (
+ <div>
+ <div style={{
+ color: '#888',
+ fontSize: '11px',
+ fontWeight: 600,
+ marginBottom: '10px',
+ letterSpacing: '0.5px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <Bot size={14} color="#888" />
+ CUSTOM MODELS (from Model Library)
+ </div>
+ <div style={styles.flexRow}>
+ {enabledModelConfigs.map(model => {
+ const isSelected = activeProvider === `model:${model.id}`;
+ return (
+ <button
+ key={model.id}
+ onClick={() => setActiveProvider(`model:${model.id}`)}
+ style={styles.customModelButton(isSelected, colors.secondary)}
+ >
+ <span style={styles.providerBadge}>
+ {model.provider.toUpperCase()}
+ </span>
+ {model.display_name || model.model_id.split('/').pop()}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/index.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/index.ts
new file mode 100644
index 000000000..1b6815bb0
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/components/index.ts
@@ -0,0 +1,8 @@
+export { ProviderSelector } from './ProviderSelector';
+export { FinceptConfigPanel } from './FinceptConfigPanel';
+export { CustomModelConfigPanel } from './CustomModelConfigPanel';
+export { ProviderConfigPanel } from './ProviderConfigPanel';
+export { GlobalSettingsPanel } from './GlobalSettingsPanel';
+export { ModelLibraryPanel } from './ModelLibraryPanel';
+export { AddModelForm } from './AddModelForm';
+export { ModelListItem } from './ModelListItem';
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/constants.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/constants.ts
new file mode 100644
index 000000000..676886970
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/constants.ts
@@ -0,0 +1,69 @@
+// LLM Configuration Constants
+
+// Provider identifiers
+export const LLM_PROVIDERS = {
+ FINCEPT: 'fincept',
+ OLLAMA: 'ollama',
+ OPENAI: 'openai',
+ ANTHROPIC: 'anthropic',
+ GOOGLE: 'google',
+ META_LLAMA: 'meta-llama',
+ MISTRAL: 'mistralai',
+ XAI: 'x-ai',
+ COHERE: 'cohere',
+ DEEPSEEK: 'deepseek',
+ QWEN: 'qwen',
+ NVIDIA: 'nvidia',
+ MICROSOFT: 'microsoft',
+ PERPLEXITY: 'perplexity',
+ GROQ: 'groq',
+ AI21: 'ai21',
+ NOUS_RESEARCH: 'nousresearch',
+ COGNITIVE_COMPUTATIONS: 'cognitivecomputations',
+ OPENROUTER: 'openrouter',
+} as const;
+
+// Special providers that are always visible (don't require API key)
+export const SPECIAL_PROVIDERS = [LLM_PROVIDERS.FINCEPT, LLM_PROVIDERS.OLLAMA] as const;
+
+// Providers that require base URL configuration
+export const PROVIDERS_WITH_BASE_URL = [
+ LLM_PROVIDERS.OLLAMA,
+ LLM_PROVIDERS.DEEPSEEK,
+ LLM_PROVIDERS.OPENROUTER,
+] as const;
+
+// Provider options for the Add Model form dropdown
+export const PROVIDER_OPTIONS = [
+ { value: LLM_PROVIDERS.OPENAI, label: 'OpenAI' },
+ { value: LLM_PROVIDERS.ANTHROPIC, label: 'Anthropic' },
+ { value: LLM_PROVIDERS.GOOGLE, label: 'Google' },
+ { value: LLM_PROVIDERS.META_LLAMA, label: 'Meta (Llama)' },
+ { value: LLM_PROVIDERS.MISTRAL, label: 'Mistral AI' },
+ { value: LLM_PROVIDERS.XAI, label: 'xAI (Grok)' },
+ { value: LLM_PROVIDERS.COHERE, label: 'Cohere' },
+ { value: LLM_PROVIDERS.DEEPSEEK, label: 'DeepSeek' },
+ { value: LLM_PROVIDERS.QWEN, label: 'Qwen (Alibaba)' },
+ { value: LLM_PROVIDERS.NVIDIA, label: 'NVIDIA' },
+ { value: LLM_PROVIDERS.MICROSOFT, label: 'Microsoft' },
+ { value: LLM_PROVIDERS.PERPLEXITY, label: 'Perplexity' },
+ { value: LLM_PROVIDERS.GROQ, label: 'Groq' },
+ { value: LLM_PROVIDERS.AI21, label: 'AI21 Labs' },
+ { value: LLM_PROVIDERS.NOUS_RESEARCH, label: 'Nous Research' },
+ { value: LLM_PROVIDERS.COGNITIVE_COMPUTATIONS, label: 'Cognitive Computations' },
+] as const;
+
+// Default new model configuration
+export const DEFAULT_NEW_MODEL_CONFIG = {
+ provider: LLM_PROVIDERS.OPENAI,
+ model_id: '',
+ display_name: '',
+ api_key: '',
+ base_url: '',
+} as const;
+
+// Default Ollama base URL
+export const DEFAULT_OLLAMA_BASE_URL = 'http://localhost:11434';
+
+// Special value for custom model entry
+export const CUSTOM_MODEL_VALUE = '__custom__';
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/hooks/index.ts
new file mode 100644
index 000000000..08195ed61
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/hooks/index.ts
@@ -0,0 +1,2 @@
+export { useLLMConfigState } from './useLLMConfigState';
+export { useLLMConfigActions } from './useLLMConfigActions';
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/hooks/useLLMConfigActions.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/hooks/useLLMConfigActions.ts
new file mode 100644
index 000000000..b24aba13f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/hooks/useLLMConfigActions.ts
@@ -0,0 +1,187 @@
+import { useCallback } from 'react';
+import type { LLMConfig, LLMGlobalSettings, LLMModelConfig } from '@/services/core/sqliteService';
+import { sqliteService } from '@/services/core/sqliteService';
+import { LLMModelsService } from '@/services/llmModelsService';
+import { LLM_PROVIDERS } from '../constants';
+import type { NewModelConfig } from '../types';
+
+interface UseLLMConfigActionsProps {
+ llmConfigs: LLMConfig[];
+ llmGlobalSettings: LLMGlobalSettings;
+ modelConfigs: LLMModelConfig[];
+ activeProvider: string;
+ setActiveProvider: (provider: string) => void;
+ setLoading: (loading: boolean) => void;
+ showMessage: (type: 'success' | 'error', text: string) => void;
+ loadLLMConfigs: () => Promise<{ configs: LLMConfig[]; modelCfgs: LLMModelConfig[] }>;
+ setShowAddModel: (show: boolean) => void;
+ resetNewModelConfig: () => void;
+}
+
+export function useLLMConfigActions({
+ llmConfigs,
+ llmGlobalSettings,
+ modelConfigs,
+ activeProvider,
+ setActiveProvider,
+ setLoading,
+ showMessage,
+ loadLLMConfigs,
+ setShowAddModel,
+ resetNewModelConfig,
+}: UseLLMConfigActionsProps) {
+ // Save all LLM configurations
+ const handleSaveLLMConfig = useCallback(async () => {
+ try {
+ setLoading(true);
+
+ if (activeProvider.startsWith('model:')) {
+ const modelId = activeProvider.replace('model:', '');
+ const selectedModel = modelConfigs.find(m => m.id === modelId);
+
+ if (selectedModel) {
+ const modelLLMConfig: LLMConfig = {
+ provider: selectedModel.provider,
+ api_key: selectedModel.api_key || '',
+ base_url: selectedModel.base_url || LLMModelsService.getProviderBaseUrl(selectedModel.provider),
+ model: selectedModel.model_id.includes('/')
+ ? selectedModel.model_id.split('/').pop() || selectedModel.model_id
+ : selectedModel.model_id,
+ is_active: true,
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString()
+ };
+
+ await sqliteService.saveLLMConfig(modelLLMConfig);
+ await sqliteService.setActiveLLMProvider(selectedModel.provider);
+ }
+ } else {
+ for (const config of llmConfigs) {
+ await sqliteService.saveLLMConfig(config);
+ }
+ await sqliteService.setActiveLLMProvider(activeProvider);
+ }
+
+ await sqliteService.saveLLMGlobalSettings(llmGlobalSettings);
+ showMessage('success', 'LLM configuration saved successfully');
+ await loadLLMConfigs();
+
+ // Notify other components (like ChatTab) that LLM config has changed
+ window.dispatchEvent(new CustomEvent('llm-config-changed'));
+ } catch (error) {
+ console.error('Failed to save LLM config:', error);
+ showMessage('error', 'Failed to save LLM configuration');
+ } finally {
+ setLoading(false);
+ }
+ }, [activeProvider, llmConfigs, llmGlobalSettings, modelConfigs, setLoading, showMessage, loadLLMConfigs]);
+
+ // Add new model configuration
+ const handleAddModelConfig = useCallback(async (newModelConfig: NewModelConfig) => {
+ if (!newModelConfig.model_id.trim()) {
+ showMessage('error', 'Model ID is required');
+ return;
+ }
+
+ try {
+ setLoading(true);
+ const id = crypto.randomUUID();
+ const displayName = newModelConfig.display_name.trim() ||
+ `${newModelConfig.provider.toUpperCase()}: ${newModelConfig.model_id}`;
+
+ const result = await sqliteService.saveLLMModelConfig({
+ id,
+ provider: newModelConfig.provider,
+ model_id: newModelConfig.model_id,
+ display_name: displayName,
+ api_key: newModelConfig.api_key || undefined,
+ base_url: newModelConfig.base_url || undefined,
+ is_enabled: true,
+ is_default: modelConfigs.filter(m => m.provider === newModelConfig.provider).length === 0
+ });
+
+ if (result.success) {
+ showMessage('success', 'Model configuration added');
+ resetNewModelConfig();
+ setShowAddModel(false);
+ await loadLLMConfigs();
+ } else {
+ showMessage('error', result.message);
+ }
+ } catch (error) {
+ console.error('Failed to add model config:', error);
+ showMessage('error', 'Failed to add model configuration');
+ } finally {
+ setLoading(false);
+ }
+ }, [modelConfigs, setLoading, showMessage, loadLLMConfigs, resetNewModelConfig, setShowAddModel]);
+
+ // Delete model configuration
+ const handleDeleteModelConfig = useCallback(async (id: string) => {
+ try {
+ setLoading(true);
+ const modelToDelete = modelConfigs.find(m => m.id === id);
+ const deletedProvider = modelToDelete?.provider;
+
+ const result = await sqliteService.deleteLLMModelConfig(id);
+ if (result.success) {
+ showMessage('success', 'Model configuration deleted');
+
+ // Handle active provider changes after deletion
+ if (activeProvider === `model:${id}`) {
+ setActiveProvider(LLM_PROVIDERS.FINCEPT);
+ } else if (deletedProvider && activeProvider === deletedProvider) {
+ const remainingModelsForProvider = modelConfigs.filter(
+ m => m.id !== id && m.provider === deletedProvider && m.is_enabled
+ );
+ const providerConfig = llmConfigs.find(c => c.provider === deletedProvider);
+ const hasApiKey = providerConfig?.api_key && providerConfig.api_key.trim() !== '';
+ const isSpecial = [LLM_PROVIDERS.FINCEPT, LLM_PROVIDERS.OLLAMA].includes(
+ deletedProvider as typeof LLM_PROVIDERS.FINCEPT
+ );
+
+ if (remainingModelsForProvider.length === 0 && !hasApiKey && !isSpecial) {
+ setActiveProvider(LLM_PROVIDERS.FINCEPT);
+ }
+ }
+
+ await loadLLMConfigs();
+ } else {
+ showMessage('error', result.message);
+ }
+ } catch (error) {
+ console.error('Failed to delete model config:', error);
+ showMessage('error', 'Failed to delete model configuration');
+ } finally {
+ setLoading(false);
+ }
+ }, [activeProvider, llmConfigs, modelConfigs, setActiveProvider, setLoading, showMessage, loadLLMConfigs]);
+
+ // Toggle model enabled state
+ const handleToggleModelEnabled = useCallback(async (id: string) => {
+ try {
+ const modelToToggle = modelConfigs.find(m => m.id === id);
+
+ const result = await sqliteService.toggleLLMModelConfigEnabled(id);
+ if (result.success) {
+ // If disabling the currently selected model, switch to default
+ if (modelToToggle?.is_enabled && activeProvider === `model:${id}`) {
+ const defaultProvider = llmConfigs.find(c => c.is_active)?.provider || LLM_PROVIDERS.FINCEPT;
+ setActiveProvider(defaultProvider);
+ }
+
+ await loadLLMConfigs();
+ }
+ } catch (error) {
+ console.error('Failed to toggle model:', error);
+ showMessage('error', 'Failed to toggle model');
+ }
+ }, [activeProvider, llmConfigs, modelConfigs, setActiveProvider, showMessage, loadLLMConfigs]);
+
+ return {
+ handleSaveLLMConfig,
+ handleAddModelConfig,
+ handleDeleteModelConfig,
+ handleToggleModelEnabled,
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/hooks/useLLMConfigState.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/hooks/useLLMConfigState.ts
new file mode 100644
index 000000000..05d419b28
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/hooks/useLLMConfigState.ts
@@ -0,0 +1,275 @@
+import { useState, useEffect, useCallback, useMemo } from 'react';
+import type { LLMConfig, LLMModelConfig } from '@/services/core/sqliteService';
+import { sqliteService } from '@/services/core/sqliteService';
+import { ollamaService } from '@/services/chat/ollamaService';
+import { LLMModelsService, type ModelInfo } from '@/services/llmModelsService';
+import { LLM_PROVIDERS, SPECIAL_PROVIDERS, DEFAULT_NEW_MODEL_CONFIG, DEFAULT_OLLAMA_BASE_URL } from '../constants';
+import type { NewModelConfig } from '../types';
+
+interface UseLLMConfigStateProps {
+ llmConfigs: LLMConfig[];
+ setLlmConfigs: React.Dispatch<React.SetStateAction<LLMConfig[]>>;
+ modelConfigs: LLMModelConfig[];
+ setLoading: (loading: boolean) => void;
+ showMessage: (type: 'success' | 'error', text: string) => void;
+ loadLLMConfigs: () => Promise<{ configs: LLMConfig[]; modelCfgs: LLMModelConfig[] }>;
+}
+
+export function useLLMConfigState({
+ llmConfigs,
+ setLlmConfigs,
+ modelConfigs: initialModelConfigs,
+ setLoading,
+ showMessage,
+ loadLLMConfigs,
+}: UseLLMConfigStateProps) {
+ // Provider selection state
+ const [activeProvider, setActiveProvider] = useState<string>(LLM_PROVIDERS.FINCEPT);
+
+ // Model configs local state (synced with props)
+ const [modelConfigs, setModelConfigs] = useState<LLMModelConfig[]>(initialModelConfigs);
+
+ // Ollama specific state
+ const [ollamaModels, setOllamaModels] = useState<string[]>([]);
+ const [ollamaLoading, setOllamaLoading] = useState(false);
+ const [ollamaError, setOllamaError] = useState<string | null>(null);
+
+ // Provider models state (for non-Ollama providers)
+ const [providerModels, setProviderModels] = useState<ModelInfo[]>([]);
+ const [providerModelsLoading, setProviderModelsLoading] = useState(false);
+ const [providerModelsError, setProviderModelsError] = useState<string | null>(null);
+
+ // Manual entry state - SEPARATE states for provider config and add model form
+ const [useManualEntryProvider, setUseManualEntryProvider] = useState(false);
+ const [useManualEntryAddModel, setUseManualEntryAddModel] = useState(false);
+
+ // Add model form state
+ const [showAddModel, setShowAddModel] = useState(false);
+ const [newModelConfig, setNewModelConfig] = useState<NewModelConfig>({ ...DEFAULT_NEW_MODEL_CONFIG });
+ const [newModelConfigModels, setNewModelConfigModels] = useState<ModelInfo[]>([]);
+
+ // API key visibility state
+ const [showApiKeys, setShowApiKeys] = useState<Record<string, boolean>>({});
+
+ // Sync model configs with props
+ useEffect(() => {
+ setModelConfigs(initialModelConfigs);
+ }, [initialModelConfigs]);
+
+ // Set active provider based on current configs
+ useEffect(() => {
+ const activeConfig = llmConfigs.find(c => c.is_active);
+ const providersWithModels = new Set(
+ modelConfigs.filter(m => m.is_enabled).map(m => m.provider)
+ );
+
+ const isProviderVisible = (provider: string, config?: LLMConfig) => {
+ if (SPECIAL_PROVIDERS.includes(provider as typeof SPECIAL_PROVIDERS[number])) return true;
+ if (config?.api_key && config.api_key.trim() !== '') return true;
+ if (providersWithModels.has(provider)) return true;
+ return false;
+ };
+
+ if (activeConfig && isProviderVisible(activeConfig.provider, activeConfig)) {
+ setActiveProvider(activeConfig.provider);
+ } else {
+ setActiveProvider(LLM_PROVIDERS.FINCEPT);
+ }
+ }, [llmConfigs, modelConfigs]);
+
+ // Get visible provider configs
+ const visibleProviderConfigs = useMemo(() => {
+ const providersWithModels = new Set(
+ modelConfigs.filter(m => m.is_enabled).map(m => m.provider)
+ );
+
+ return llmConfigs.filter(config => {
+ if (SPECIAL_PROVIDERS.includes(config.provider as typeof SPECIAL_PROVIDERS[number])) return true;
+ if (config.api_key && config.api_key.trim() !== '') return true;
+ if (providersWithModels.has(config.provider)) return true;
+ return false;
+ });
+ }, [llmConfigs, modelConfigs]);
+
+ // Get current LLM config based on active provider
+ const getCurrentLLMConfig = useCallback((): LLMConfig | undefined => {
+ if (activeProvider.startsWith('model:')) {
+ const modelId = activeProvider.replace('model:', '');
+ const modelConfig = modelConfigs.find(m => m.id === modelId);
+ if (modelConfig) {
+ return {
+ provider: modelConfig.provider,
+ api_key: modelConfig.api_key || '',
+ base_url: modelConfig.base_url || '',
+ model: modelConfig.model_id,
+ is_active: true,
+ created_at: modelConfig.created_at || new Date().toISOString(),
+ updated_at: modelConfig.updated_at || new Date().toISOString()
+ } as LLMConfig;
+ }
+ }
+ return llmConfigs.find(c => c.provider === activeProvider);
+ }, [activeProvider, llmConfigs, modelConfigs]);
+
+ // Get selected model config (for custom models)
+ const getSelectedModelConfig = useCallback((): LLMModelConfig | undefined => {
+ if (activeProvider.startsWith('model:')) {
+ const modelId = activeProvider.replace('model:', '');
+ return modelConfigs.find(m => m.id === modelId);
+ }
+ return undefined;
+ }, [activeProvider, modelConfigs]);
+
+ // Update LLM config helper
+ const updateLLMConfig = useCallback((provider: string, field: keyof LLMConfig, value: any) => {
+ setLlmConfigs(prev => prev.map(config =>
+ config.provider === provider ? { ...config, [field]: value } : config
+ ));
+ }, [setLlmConfigs]);
+
+ // Fetch Ollama models
+ const fetchOllamaModels = useCallback(async () => {
+ setOllamaLoading(true);
+ setOllamaError(null);
+
+ const currentConfig = getCurrentLLMConfig();
+ const baseUrl = currentConfig?.base_url || DEFAULT_OLLAMA_BASE_URL;
+
+ const result = await ollamaService.listModels(baseUrl);
+
+ if (result.success && result.models) {
+ setOllamaModels(result.models);
+ setOllamaError(null);
+ } else {
+ setOllamaModels([]);
+ setOllamaError(result.error || 'Failed to fetch models');
+ }
+
+ setOllamaLoading(false);
+ }, [getCurrentLLMConfig]);
+
+ // Fetch provider models (for non-Ollama/Fincept providers)
+ const fetchProviderModels = useCallback(async () => {
+ const currentConfig = getCurrentLLMConfig();
+ if (!currentConfig) return;
+
+ const provider = currentConfig.provider;
+ if (provider === LLM_PROVIDERS.OLLAMA || provider === LLM_PROVIDERS.FINCEPT) return;
+
+ setProviderModelsLoading(true);
+ setProviderModelsError(null);
+
+ try {
+ const result = await LLMModelsService.getModels(
+ provider,
+ currentConfig.api_key || undefined,
+ currentConfig.base_url || undefined
+ );
+
+ if (result.models && result.models.length > 0) {
+ setProviderModels(result.models);
+ setProviderModelsError(null);
+ } else if (result.error) {
+ setProviderModelsError(result.error);
+ setProviderModels([]);
+ } else {
+ setProviderModels([]);
+ setProviderModelsError('No models available for this provider');
+ }
+ } catch (error) {
+ setProviderModelsError(error instanceof Error ? error.message : 'Failed to fetch models');
+ setProviderModels([]);
+ } finally {
+ setProviderModelsLoading(false);
+ }
+ }, [getCurrentLLMConfig]);
+
+ // Load models when active provider changes
+ useEffect(() => {
+ const loadModels = async () => {
+ const currentConfig = getCurrentLLMConfig();
+ if (!currentConfig) return;
+
+ const provider = currentConfig.provider;
+ setProviderModels([]);
+ setProviderModelsError(null);
+
+ if (provider === LLM_PROVIDERS.OLLAMA) {
+ fetchOllamaModels();
+ } else if (provider !== LLM_PROVIDERS.FINCEPT) {
+ fetchProviderModels();
+ }
+ };
+
+ loadModels();
+ }, [activeProvider, getCurrentLLMConfig, fetchOllamaModels, fetchProviderModels]);
+
+ // Load models for new model config form
+ useEffect(() => {
+ const loadNewModelConfigModels = async () => {
+ if (!showAddModel) return;
+
+ try {
+ const models = await LLMModelsService.getModelsByProvider(newModelConfig.provider);
+ if (models && models.length > 0) {
+ setNewModelConfigModels(models);
+ } else {
+ setNewModelConfigModels([]);
+ }
+ } catch {
+ setNewModelConfigModels([]);
+ }
+ };
+
+ loadNewModelConfigModels();
+ }, [newModelConfig.provider, showAddModel]);
+
+ // Reset new model config when closing form
+ const resetNewModelConfig = useCallback(() => {
+ setNewModelConfig({ ...DEFAULT_NEW_MODEL_CONFIG });
+ setUseManualEntryAddModel(false);
+ }, []);
+
+ return {
+ // Provider state
+ activeProvider,
+ setActiveProvider,
+ visibleProviderConfigs,
+ getCurrentLLMConfig,
+ getSelectedModelConfig,
+ updateLLMConfig,
+
+ // Model configs
+ modelConfigs,
+
+ // Ollama state
+ ollamaModels,
+ ollamaLoading,
+ ollamaError,
+ fetchOllamaModels,
+
+ // Provider models state
+ providerModels,
+ providerModelsLoading,
+ providerModelsError,
+ fetchProviderModels,
+
+ // Manual entry state (separate for each form)
+ useManualEntryProvider,
+ setUseManualEntryProvider,
+ useManualEntryAddModel,
+ setUseManualEntryAddModel,
+
+ // Add model form state
+ showAddModel,
+ setShowAddModel,
+ newModelConfig,
+ setNewModelConfig,
+ newModelConfigModels,
+ resetNewModelConfig,
+
+ // API key visibility
+ showApiKeys,
+ setShowApiKeys,
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/index.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/index.ts
new file mode 100644
index 000000000..208ed4894
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/index.ts
@@ -0,0 +1,3 @@
+export { LLMConfigSection } from './LLMConfigSection';
+export * from './constants';
+export * from './types';
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/styles.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/styles.ts
new file mode 100644
index 000000000..618669550
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/styles.ts
@@ -0,0 +1,325 @@
+// LLM Configuration Styles
+import type { CSSProperties } from 'react';
+import type { SettingsColors } from '../../types';
+
+// Base font family for the component
+const FONT_FAMILY = '"IBM Plex Mono", "Consolas", monospace';
+
+// Create style factory functions that accept colors from props
+export const createStyles = (colors: SettingsColors) => ({
+ // Container styles
+ container: {
+ fontFamily: FONT_FAMILY,
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '20px',
+ } as CSSProperties,
+
+ // Header styles
+ header: {
+ borderBottom: `2px solid ${colors.primary}`,
+ padding: '16px 0',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ } as CSSProperties,
+
+ headerTitle: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ } as CSSProperties,
+
+ headerTitleText: {
+ color: colors.primary,
+ fontWeight: 700,
+ fontSize: '16px',
+ letterSpacing: '0.5px',
+ } as CSSProperties,
+
+ headerSubtext: {
+ color: '#888',
+ fontSize: '12px',
+ marginTop: '2px',
+ } as CSSProperties,
+
+ // Panel styles
+ panel: {
+ backgroundColor: '#0F0F0F',
+ border: '1px solid #2A2A2A',
+ padding: '20px',
+ } as CSSProperties,
+
+ panelHeader: {
+ color: colors.primary,
+ fontSize: '13px',
+ fontWeight: 700,
+ marginBottom: '16px',
+ letterSpacing: '0.5px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ } as CSSProperties,
+
+ // Button styles
+ primaryButton: (disabled: boolean) => ({
+ background: disabled ? '#2A2A2A' : colors.primary,
+ color: disabled ? '#666' : '#000',
+ border: 'none',
+ padding: '10px 20px',
+ fontSize: '12px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ } as CSSProperties),
+
+ secondaryButton: (active: boolean) => ({
+ background: active ? colors.primary : '#1A1A1A',
+ border: `1px solid ${active ? colors.primary : '#2A2A2A'}`,
+ color: active ? '#000' : '#FFF',
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontWeight: 600,
+ } as CSSProperties),
+
+ providerButton: (active: boolean) => ({
+ padding: '12px 20px',
+ backgroundColor: active ? colors.primary : '#1A1A1A',
+ border: `2px solid ${active ? colors.primary : '#2A2A2A'}`,
+ color: active ? '#000' : '#FFF',
+ cursor: 'pointer',
+ fontSize: '13px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ } as CSSProperties),
+
+ customModelButton: (selected: boolean, secondaryColor: string) => ({
+ padding: '10px 16px',
+ backgroundColor: selected ? secondaryColor : '#1A1A1A',
+ border: `2px solid ${selected ? secondaryColor : '#2A2A2A'}`,
+ color: selected ? '#000' : '#FFF',
+ cursor: 'pointer',
+ fontSize: '12px',
+ fontWeight: 600,
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ } as CSSProperties),
+
+ // Input styles
+ input: {
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2A2A2A',
+ color: '#FFF',
+ padding: '12px 14px',
+ fontSize: '13px',
+ fontFamily: FONT_FAMILY,
+ outline: 'none',
+ } as CSSProperties,
+
+ select: {
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2A2A2A',
+ color: '#FFF',
+ padding: '12px 14px',
+ fontSize: '13px',
+ cursor: 'pointer',
+ } as CSSProperties,
+
+ textarea: {
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2A2A2A',
+ color: '#FFF',
+ padding: '12px 14px',
+ fontSize: '12px',
+ resize: 'vertical',
+ fontFamily: FONT_FAMILY,
+ lineHeight: '1.5',
+ outline: 'none',
+ } as CSSProperties,
+
+ // Label styles
+ label: {
+ color: '#FFF',
+ fontSize: '11px',
+ display: 'block',
+ marginBottom: '8px',
+ fontWeight: 600,
+ letterSpacing: '0.5px',
+ } as CSSProperties,
+
+ labelRequired: {
+ color: colors.alert,
+ } as CSSProperties,
+
+ // Info box styles
+ successBox: {
+ backgroundColor: '#0a2a0a',
+ border: `2px solid ${colors.success}`,
+ padding: '20px',
+ } as CSSProperties,
+
+ infoBox: {
+ backgroundColor: '#0a1a2a',
+ border: `2px solid ${colors.secondary}`,
+ padding: '20px',
+ } as CSSProperties,
+
+ warningBox: {
+ marginTop: '12px',
+ padding: '10px',
+ background: '#3a0a0a',
+ border: `1px solid ${colors.alert}`,
+ color: colors.alert,
+ fontSize: '11px',
+ } as CSSProperties,
+
+ errorMessage: {
+ marginTop: '8px',
+ padding: '10px 12px',
+ background: '#3a0a0a',
+ border: `1px solid ${colors.alert}`,
+ fontSize: '12px',
+ color: colors.alert,
+ } as CSSProperties,
+
+ successMessage: {
+ marginTop: '8px',
+ fontSize: '12px',
+ color: colors.success,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ } as CSSProperties,
+
+ // Data display styles
+ dataRow: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: '16px',
+ padding: '12px',
+ backgroundColor: '#000',
+ border: '1px solid #2A2A2A',
+ } as CSSProperties,
+
+ dataLabel: {
+ color: '#666',
+ fontSize: '10px',
+ marginBottom: '4px',
+ } as CSSProperties,
+
+ dataValue: {
+ color: '#FFF',
+ fontSize: '12px',
+ } as CSSProperties,
+
+ // Provider badge
+ providerBadge: {
+ padding: '2px 6px',
+ background: colors.primary + '30',
+ border: `1px solid ${colors.primary}`,
+ fontSize: '9px',
+ fontWeight: 700,
+ color: colors.primary,
+ } as CSSProperties,
+
+ // Grid layouts
+ twoColumnGrid: {
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr',
+ gap: '20px',
+ } as CSSProperties,
+
+ formGrid: {
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr',
+ gap: '12px',
+ marginBottom: '12px',
+ } as CSSProperties,
+
+ // Flex containers
+ flexRow: {
+ display: 'flex',
+ gap: '10px',
+ flexWrap: 'wrap',
+ } as CSSProperties,
+
+ flexColumn: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '16px',
+ } as CSSProperties,
+
+ // Model list item
+ modelListItem: (enabled: boolean) => ({
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ padding: '12px 14px',
+ background: enabled ? '#1A1A1A' : '#0A0A0A',
+ border: `1px solid ${enabled ? '#2A2A2A' : '#1A1A1A'}`,
+ opacity: enabled ? 1 : 0.6,
+ } as CSSProperties),
+
+ // Empty state
+ emptyState: {
+ padding: '40px 20px',
+ textAlign: 'center',
+ color: '#666',
+ border: '1px dashed #2A2A2A',
+ background: '#000',
+ } as CSSProperties,
+
+ // Slider container
+ sliderContainer: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ } as CSSProperties,
+
+ sliderValue: {
+ minWidth: '50px',
+ padding: '8px 12px',
+ background: colors.primary + '20',
+ border: `1px solid ${colors.primary}`,
+ color: colors.primary,
+ fontSize: '13px',
+ fontWeight: 700,
+ textAlign: 'center',
+ } as CSSProperties,
+
+ // Section divider
+ sectionDivider: {
+ paddingBottom: '12px',
+ borderBottom: '1px solid #2A2A2A',
+ } as CSSProperties,
+
+ // Summary bar
+ summaryBar: {
+ marginTop: '16px',
+ padding: '12px 14px',
+ background: '#0a2a0a',
+ border: `1px solid ${colors.success}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ } as CSSProperties,
+});
+
+export type LLMConfigStyles = ReturnType<typeof createStyles>;
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/types.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/types.ts
new file mode 100644
index 000000000..a0b657621
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/llm-config/types.ts
@@ -0,0 +1,106 @@
+// LLM Configuration Types
+import type { LLMConfig, LLMGlobalSettings, LLMModelConfig } from '@/services/core/sqliteService';
+import type { ModelInfo } from '@/services/llmModelsService';
+import type { SettingsColors } from '../../types';
+
+export interface LLMConfigSectionProps {
+ colors: SettingsColors;
+ llmConfigs: LLMConfig[];
+ setLlmConfigs: React.Dispatch<React.SetStateAction<LLMConfig[]>>;
+ llmGlobalSettings: LLMGlobalSettings;
+ setLlmGlobalSettings: React.Dispatch<React.SetStateAction<LLMGlobalSettings>>;
+ modelConfigs: LLMModelConfig[];
+ loading: boolean;
+ setLoading: (loading: boolean) => void;
+ showMessage: (type: 'success' | 'error', text: string) => void;
+ loadLLMConfigs: () => Promise<{ configs: LLMConfig[]; modelCfgs: LLMModelConfig[] }>;
+ sessionApiKey?: string;
+}
+
+export interface NewModelConfig {
+ provider: string;
+ model_id: string;
+ display_name: string;
+ api_key: string;
+ base_url: string;
+}
+
+export interface ProviderSelectorProps {
+ colors: SettingsColors;
+ activeProvider: string;
+ setActiveProvider: (provider: string) => void;
+ visibleProviderConfigs: LLMConfig[];
+ modelConfigs: LLMModelConfig[];
+}
+
+export interface ProviderConfigPanelProps {
+ colors: SettingsColors;
+ currentConfig: LLMConfig | undefined;
+ activeProvider: string;
+ updateLLMConfig: (provider: string, field: keyof LLMConfig, value: any) => void;
+ ollamaModels: string[];
+ ollamaLoading: boolean;
+ ollamaError: string | null;
+ fetchOllamaModels: () => void;
+ providerModels: ModelInfo[];
+ providerModelsLoading: boolean;
+ providerModelsError: string | null;
+ fetchProviderModels: () => void;
+ useManualEntry: boolean;
+ setUseManualEntry: (value: boolean) => void;
+}
+
+export interface FinceptConfigPanelProps {
+ colors: SettingsColors;
+ sessionApiKey?: string;
+}
+
+export interface CustomModelConfigPanelProps {
+ colors: SettingsColors;
+ modelConfig: LLMModelConfig;
+}
+
+export interface GlobalSettingsPanelProps {
+ colors: SettingsColors;
+ llmGlobalSettings: LLMGlobalSettings;
+ setLlmGlobalSettings: React.Dispatch<React.SetStateAction<LLMGlobalSettings>>;
+}
+
+export interface ModelLibraryPanelProps {
+ colors: SettingsColors;
+ modelConfigs: LLMModelConfig[];
+ showAddModel: boolean;
+ setShowAddModel: (value: boolean) => void;
+ loading: boolean;
+ handleAddModelConfig: () => void;
+ handleDeleteModelConfig: (id: string) => void;
+ handleToggleModelEnabled: (id: string) => void;
+ newModelConfig: NewModelConfig;
+ setNewModelConfig: React.Dispatch<React.SetStateAction<NewModelConfig>>;
+ newModelConfigModels: ModelInfo[];
+ useManualEntry: boolean;
+ setUseManualEntry: (value: boolean) => void;
+ showApiKeys: Record<string, boolean>;
+ setShowApiKeys: React.Dispatch<React.SetStateAction<Record<string, boolean>>>;
+}
+
+export interface AddModelFormProps {
+ colors: SettingsColors;
+ loading: boolean;
+ newModelConfig: NewModelConfig;
+ setNewModelConfig: React.Dispatch<React.SetStateAction<NewModelConfig>>;
+ newModelConfigModels: ModelInfo[];
+ useManualEntry: boolean;
+ setUseManualEntry: (value: boolean) => void;
+ onSubmit: () => void;
+ onCancel: () => void;
+}
+
+export interface ModelListItemProps {
+ colors: SettingsColors;
+ model: LLMModelConfig;
+ showApiKey: boolean;
+ onToggleApiKey: () => void;
+ onToggleEnabled: () => void;
+ onDelete: () => void;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/SurfaceAnalyticsTab.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/SurfaceAnalyticsTab.tsx
index 3348f32dd..eed8da77c 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/SurfaceAnalyticsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/SurfaceAnalyticsTab.tsx
@@ -35,7 +35,7 @@ import type {
YieldCurveData,
PCAData,
} from './types';
-import { CORRELATION_ASSETS, FINCEPT_COLORS, TREASURY_MATURITIES, TYPOGRAPHY } from './constants';
+import { CORRELATION_ASSETS, TREASURY_MATURITIES } from './constants';
// Default configuration
const DEFAULT_CONFIG: SurfaceAnalyticsConfig = {
@@ -57,9 +57,11 @@ const DEFAULT_CONFIG: SurfaceAnalyticsConfig = {
const ApiKeySetupScreen: React.FC<{
onOpenSettings: () => void;
onUseDemoData: () => void;
- accentColor: string;
- textColor: string;
-}> = ({ onOpenSettings, onUseDemoData, accentColor, textColor }) => (
+ colors: { primary: string; text: string; textMuted: string; background: string; panel: string; info: string; success: string; warning: string };
+ fontSize: { heading: string; subheading: string; body: string; small: string; tiny: string };
+ fontFamily: string;
+ t: (key: string) => string;
+}> = ({ onOpenSettings, onUseDemoData, colors, fontSize, fontFamily, t }) => (
<div
style={{
display: 'flex',
@@ -68,7 +70,7 @@ const ApiKeySetupScreen: React.FC<{
justifyContent: 'center',
height: '100%',
padding: '48px',
- backgroundColor: FINCEPT_COLORS.BLACK,
+ backgroundColor: colors.background,
}}
>
{/* Main Container */}
@@ -76,9 +78,9 @@ const ApiKeySetupScreen: React.FC<{
style={{
maxWidth: '560px',
padding: '32px',
- backgroundColor: FINCEPT_COLORS.PANEL_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
textAlign: 'center',
}}
>
@@ -91,40 +93,38 @@ const ApiKeySetupScreen: React.FC<{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- backgroundColor: accentColor + '15',
+ backgroundColor: colors.primary + '15',
borderRadius: '50%',
}}
>
- <Database size={32} style={{ color: accentColor }} />
+ <Database size={32} style={{ color: colors.primary }} />
</div>
{/* Title */}
<h2
style={{
- fontSize: '16px',
+ fontSize: fontSize.heading,
fontWeight: 700,
- color: textColor,
+ color: colors.text,
marginBottom: '12px',
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontFamily,
letterSpacing: '0.5px',
}}
>
- DATABENTO API KEY REQUIRED
+ {t('surfaceAnalytics.apiKeyRequired')}
</h2>
{/* Description */}
<p
style={{
- fontSize: '11px',
- color: FINCEPT_COLORS.GRAY,
+ fontSize: fontSize.body,
+ color: colors.textMuted,
marginBottom: '24px',
lineHeight: '1.6',
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontFamily,
}}
>
- Surface Analytics requires a Databento API key to fetch real-time options data,
- historical prices, and market information. Databento provides institutional-grade
- market data for professional financial analysis.
+ {t('surfaceAnalytics.apiKeyDescription')}
</p>
{/* Features List */}
@@ -138,10 +138,10 @@ const ApiKeySetupScreen: React.FC<{
}}
>
{[
- { icon: TrendingUp, label: 'Volatility Surfaces', desc: 'Options IV analysis' },
- { icon: Network, label: 'Correlation Matrix', desc: 'Multi-asset correlations' },
- { icon: Activity, label: 'Yield Curves', desc: 'Treasury rate evolution' },
- { icon: BarChart3, label: 'PCA Factors', desc: 'Factor decomposition' },
+ { icon: TrendingUp, label: t('surfaceAnalytics.features.volatility'), desc: t('surfaceAnalytics.features.volatilityDesc') },
+ { icon: Network, label: t('surfaceAnalytics.features.correlation'), desc: t('surfaceAnalytics.features.correlationDesc') },
+ { icon: Activity, label: t('surfaceAnalytics.features.yieldCurves'), desc: t('surfaceAnalytics.features.yieldCurvesDesc') },
+ { icon: BarChart3, label: t('surfaceAnalytics.features.pca'), desc: t('surfaceAnalytics.features.pcaDesc') },
].map(({ icon: Icon, label, desc }) => (
<div
key={label}
@@ -150,17 +150,17 @@ const ApiKeySetupScreen: React.FC<{
alignItems: 'flex-start',
gap: '8px',
padding: '8px',
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
- <Icon size={14} style={{ color: accentColor, marginTop: '2px' }} />
+ <Icon size={14} style={{ color: colors.primary, marginTop: '2px' }} />
<div>
- <div style={{ fontSize: '9px', fontWeight: 700, color: textColor, letterSpacing: '0.5px' }}>
+ <div style={{ fontSize: fontSize.tiny, fontWeight: 700, color: colors.text, letterSpacing: '0.5px' }}>
{label}
</div>
- <div style={{ fontSize: '9px', color: FINCEPT_COLORS.MUTED }}>
+ <div style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>
{desc}
</div>
</div>
@@ -179,19 +179,19 @@ const ApiKeySetupScreen: React.FC<{
alignItems: 'center',
gap: '8px',
padding: '10px 20px',
- backgroundColor: accentColor,
- color: FINCEPT_COLORS.BLACK,
+ backgroundColor: colors.primary,
+ color: colors.background,
border: 'none',
- borderRadius: '2px',
- fontSize: '10px',
+ borderRadius: 'var(--ft-border-radius)',
+ fontSize: fontSize.small,
fontWeight: 700,
cursor: 'pointer',
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontFamily,
letterSpacing: '0.5px',
}}
>
<Key size={14} />
- CONFIGURE API KEY
+ {t('surfaceAnalytics.configureApiKey')}
</button>
<a
@@ -204,25 +204,25 @@ const ApiKeySetupScreen: React.FC<{
gap: '8px',
padding: '10px 20px',
backgroundColor: 'transparent',
- color: FINCEPT_COLORS.CYAN,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
- fontSize: '10px',
+ color: colors.info,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
+ fontSize: fontSize.small,
fontWeight: 700,
cursor: 'pointer',
textDecoration: 'none',
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontFamily,
letterSpacing: '0.5px',
}}
>
<ExternalLink size={14} />
- GET API KEY
+ {t('surfaceAnalytics.getApiKey')}
</a>
</div>
{/* Demo mode option */}
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <span style={{ fontSize: '9px', color: FINCEPT_COLORS.MUTED }}>or</span>
+ <span style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>{t('common.or')}</span>
<button
onClick={onUseDemoData}
style={{
@@ -231,20 +231,20 @@ const ApiKeySetupScreen: React.FC<{
gap: '6px',
padding: '8px 16px',
backgroundColor: 'transparent',
- color: FINCEPT_COLORS.GREEN,
- border: `1px solid ${FINCEPT_COLORS.GREEN}50`,
- borderRadius: '2px',
- fontSize: '9px',
+ color: colors.success,
+ border: `1px solid ${colors.success}50`,
+ borderRadius: 'var(--ft-border-radius)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
cursor: 'pointer',
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontFamily,
letterSpacing: '0.5px',
}}
>
<BarChart3 size={12} />
- USE DEMO DATA
+ {t('surfaceAnalytics.useDemoData')}
</button>
- <span style={{ fontSize: '9px', color: FINCEPT_COLORS.MUTED }}>(synthetic data for visualization)</span>
+ <span style={{ fontSize: fontSize.tiny, color: colors.textMuted }}>({t('surfaceAnalytics.syntheticData')})</span>
</div>
</div>
@@ -253,18 +253,17 @@ const ApiKeySetupScreen: React.FC<{
style={{
marginTop: '20px',
padding: '10px',
- backgroundColor: FINCEPT_COLORS.YELLOW + '10',
- border: `1px solid ${FINCEPT_COLORS.YELLOW}30`,
- borderRadius: '2px',
+ backgroundColor: colors.warning + '10',
+ border: `1px solid ${colors.warning}30`,
+ borderRadius: 'var(--ft-border-radius)',
display: 'flex',
alignItems: 'flex-start',
gap: '8px',
}}
>
- <AlertTriangle size={14} style={{ color: FINCEPT_COLORS.YELLOW, flexShrink: 0, marginTop: '2px' }} />
- <span style={{ fontSize: '9px', color: FINCEPT_COLORS.GRAY, textAlign: 'left' }}>
- <strong style={{ color: FINCEPT_COLORS.YELLOW }}>Note:</strong> Databento is a paid service.
- API calls consume data credits. Review their pricing at databento.com/pricing before proceeding.
+ <AlertTriangle size={14} style={{ color: colors.warning, flexShrink: 0, marginTop: '2px' }} />
+ <span style={{ fontSize: fontSize.tiny, color: colors.textMuted, textAlign: 'left' }}>
+ <strong style={{ color: colors.warning }}>{t('common.note')}:</strong> {t('surfaceAnalytics.paidServiceNotice')}
</span>
</div>
</div>
@@ -272,9 +271,23 @@ const ApiKeySetupScreen: React.FC<{
);
const SurfaceAnalyticsTab: React.FC = () => {
- const { t } = useTranslation();
+ const { t } = useTranslation('surfaceAnalytics');
const { colors, fontSize, fontFamily } = useTerminalTheme();
+ // Theme-aware color mappings
+ const themeColors = {
+ primary: colors.primary,
+ text: colors.text,
+ textMuted: colors.textMuted,
+ background: colors.background,
+ panel: colors.panel,
+ info: colors.info,
+ success: colors.success,
+ warning: colors.warning,
+ alert: colors.alert,
+ accent: colors.accent,
+ };
+
// State
const [activeChart, setActiveChart] = useState<ChartType>('volatility');
@@ -598,14 +611,14 @@ const SurfaceAnalyticsTab: React.FC = () => {
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
- backgroundColor: FINCEPT_COLORS.BLACK,
+ backgroundColor: colors.background,
color: colors.text,
fontFamily,
}}
>
<RefreshCw size={32} className="animate-spin" style={{ color: colors.accent }} />
- <span style={{ marginTop: '16px', fontSize: '11px', color: FINCEPT_COLORS.MUTED }}>
- INITIALIZING SURFACE ANALYTICS...
+ <span style={{ marginTop: '16px', fontSize: fontSize.body, color: colors.textMuted }}>
+ {t('initializing')}
</span>
</div>
);
@@ -619,7 +632,7 @@ const SurfaceAnalyticsTab: React.FC = () => {
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: FINCEPT_COLORS.BLACK,
+ backgroundColor: colors.background,
color: colors.text,
fontFamily,
overflow: 'hidden',
@@ -632,15 +645,15 @@ const SurfaceAnalyticsTab: React.FC = () => {
alignItems: 'center',
justifyContent: 'space-between',
padding: '8px 16px',
- backgroundColor: FINCEPT_COLORS.HEADER_BG,
+ backgroundColor: colors.panel,
borderBottom: `2px solid ${colors.accent}`,
boxShadow: `0 2px 8px ${colors.accent}20`,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Database size={14} style={{ color: colors.accent }} />
- <span style={{ fontSize: '11px', fontWeight: 700, color: colors.accent, letterSpacing: '0.5px' }}>
- SURFACE ANALYTICS
+ <span style={{ fontSize: fontSize.body, fontWeight: 700, color: colors.accent, letterSpacing: '0.5px' }}>
+ {t('title')}
</span>
</div>
<button
@@ -651,16 +664,16 @@ const SurfaceAnalyticsTab: React.FC = () => {
gap: '6px',
padding: '6px 12px',
backgroundColor: colors.accent,
- color: FINCEPT_COLORS.BLACK,
+ color: colors.background,
border: 'none',
- borderRadius: '2px',
- fontSize: '9px',
+ borderRadius: 'var(--ft-border-radius)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
cursor: 'pointer',
}}
>
<Settings size={12} />
- SETTINGS
+ {t('common:settings')}
</button>
</div>
@@ -668,15 +681,17 @@ const SurfaceAnalyticsTab: React.FC = () => {
<ApiKeySetupScreen
onOpenSettings={() => setShowSettings(true)}
onUseDemoData={handleUseDemoData}
- accentColor={colors.accent}
- textColor={colors.text}
+ colors={themeColors}
+ fontSize={fontSize}
+ fontFamily={fontFamily}
+ t={t}
/>
{/* Footer */}
<div style={{ flexShrink: 0 }}>
<TabFooter
- tabName="SURFACE ANALYTICS"
- statusInfo="API KEY REQUIRED | Configure Databento credentials or use demo data"
+ tabName={t('title')}
+ statusInfo={t('apiKeyRequiredStatus')}
/>
</div>
@@ -700,7 +715,7 @@ const SurfaceAnalyticsTab: React.FC = () => {
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: FINCEPT_COLORS.BLACK,
+ backgroundColor: colors.background,
color: colors.text,
fontFamily,
overflow: 'hidden',
@@ -725,9 +740,9 @@ const SurfaceAnalyticsTab: React.FC = () => {
<MetricsPanel
chartType={activeChart}
metrics={currentMetrics}
- dataSource={isDemoMode ? 'DEMO DATA' : 'DATABENTO'}
- frequency={isDemoMode ? 'SYNTHETIC' : (config.refreshInterval > 0 ? `${config.refreshInterval / 60000}M AUTO` : 'MANUAL')}
- quality={dataError ? 'ERROR' : (isDemoMode ? 'SYNTHETIC' : (lastUpdate ? '99.8%' : 'READY'))}
+ dataSource={isDemoMode ? t('demoData') : 'DATABENTO'}
+ frequency={isDemoMode ? t('synthetic') : (config.refreshInterval > 0 ? `${config.refreshInterval / 60000}M AUTO` : t('manual'))}
+ quality={dataError ? t('error') : (isDemoMode ? t('synthetic') : (lastUpdate ? '99.8%' : t('ready')))}
symbol={activeChart === 'volatility' ? config.selectedSymbol : undefined}
textColor={colors.text}
accentColor={colors.accent}
@@ -752,8 +767,8 @@ const SurfaceAnalyticsTab: React.FC = () => {
{/* Footer */}
<div style={{ flexShrink: 0 }}>
<TabFooter
- tabName="SURFACE ANALYTICS"
- statusInfo={`${activeChart.toUpperCase()} | ${currentMetrics.length} Metrics | ${isDemoMode ? 'DEMO DATA (synthetic)' : 'DATABENTO'} | ${lastUpdate ? `Updated: ${lastUpdate.toLocaleTimeString()}` : 'Click REFRESH to load data'}`}
+ tabName={t('title')}
+ statusInfo={`${activeChart.toUpperCase()} | ${currentMetrics.length} ${t('metrics')} | ${isDemoMode ? t('demoDataSynthetic') : 'DATABENTO'} | ${lastUpdate ? `${t('updated')}: ${lastUpdate.toLocaleTimeString()}` : t('clickRefresh')}`}
/>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/AdditionalSchemasPanel.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/AdditionalSchemasPanel.tsx
index 9e6582da1..6919b8646 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/AdditionalSchemasPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/AdditionalSchemasPanel.tsx
@@ -18,7 +18,8 @@ import {
ChevronUp,
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
-import { FINCEPT_COLORS } from '../constants';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface TradeRecord {
ts_event: string;
@@ -81,6 +82,8 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
accentColor,
textColor,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors } = useTerminalTheme();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [activeSchema, setActiveSchema] = useState<SchemaType>('trades');
@@ -265,13 +268,13 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
<div
className="p-4 text-center"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
- <Activity size={24} style={{ color: FINCEPT_COLORS.MUTED, margin: '0 auto 8px' }} />
- <div className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <Activity size={24} style={{ color: colors.textMuted, margin: '0 auto 8px' }} />
+ <div className="text-xs" style={{ color: colors.textMuted }}>
Configure Databento API key for additional schemas
</div>
</div>
@@ -281,9 +284,9 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
return (
<div
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
overflow: 'hidden',
}}
>
@@ -291,8 +294,8 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
<div
className="flex items-center justify-between p-2"
style={{
- backgroundColor: FINCEPT_COLORS.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
}}
>
<div className="flex items-center gap-2">
@@ -304,7 +307,7 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
<button
onClick={handleRefresh}
disabled={loading}
- style={{ color: loading ? FINCEPT_COLORS.MUTED : accentColor }}
+ style={{ color: loading ? colors.textMuted : accentColor }}
>
<RefreshCw size={12} className={loading ? 'animate-spin' : ''} />
</button>
@@ -313,7 +316,7 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
{/* Schema Tabs */}
<div
className="flex items-center gap-1 p-2"
- style={{ borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}` }}
+ style={{ borderBottom: `1px solid ${colors.textMuted}` }}
>
{SCHEMA_TABS.map((tab) => (
<button
@@ -321,9 +324,9 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
onClick={() => handleSchemaChange(tab.id)}
className="flex items-center gap-1 px-2 py-1 text-[10px] font-bold"
style={{
- backgroundColor: activeSchema === tab.id ? accentColor : FINCEPT_COLORS.BORDER,
- color: activeSchema === tab.id ? FINCEPT_COLORS.BLACK : textColor,
- borderRadius: '2px',
+ backgroundColor: activeSchema === tab.id ? accentColor : colors.textMuted,
+ color: activeSchema === tab.id ? colors.background : textColor,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{tab.icon}
@@ -337,10 +340,10 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
<div
className="flex items-center gap-2 m-2 p-2 text-xs"
style={{
- backgroundColor: `${FINCEPT_COLORS.RED}15`,
- border: `1px solid ${FINCEPT_COLORS.RED}50`,
- borderRadius: '2px',
- color: FINCEPT_COLORS.RED,
+ backgroundColor: `${colors.alert}15`,
+ border: `1px solid ${colors.alert}50`,
+ borderRadius: 'var(--ft-border-radius)',
+ color: colors.alert,
}}
>
<AlertCircle size={12} />
@@ -359,12 +362,12 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
{/* Trades View */}
{activeSchema === 'trades' && (
trades.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
Click refresh to load trades data
</div>
) : (
<div>
- <div className="grid grid-cols-5 gap-2 mb-1 text-[9px]" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="grid grid-cols-5 gap-2 mb-1 text-[9px]" style={{ color: colors.textMuted }}>
<div>TIME</div>
<div>SYMBOL</div>
<div className="text-right">PRICE</div>
@@ -373,17 +376,17 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
</div>
{trades.slice(0, 20).map((trade, idx) => (
<div key={idx} className="grid grid-cols-5 gap-2 py-0.5 text-[10px]">
- <div style={{ color: FINCEPT_COLORS.MUTED }}>{formatTime(trade.ts_event)}</div>
+ <div style={{ color: colors.textMuted }}>{formatTime(trade.ts_event)}</div>
<div style={{ color: accentColor, fontWeight: 'bold' }}>{trade.symbol}</div>
- <div className="text-right font-mono" style={{ color: FINCEPT_COLORS.WHITE }}>{formatPrice(trade.price)}</div>
- <div className="text-right" style={{ color: FINCEPT_COLORS.MUTED }}>{formatQty(trade.size)}</div>
+ <div className="text-right font-mono" style={{ color: textColor }}>{formatPrice(trade.price)}</div>
+ <div className="text-right" style={{ color: colors.textMuted }}>{formatQty(trade.size)}</div>
<div className="text-right flex items-center justify-end">
{trade.side === 'B' || trade.side === 'BUY' ? (
- <TrendingUp size={10} style={{ color: FINCEPT_COLORS.GREEN }} />
+ <TrendingUp size={10} style={{ color: colors.success }} />
) : trade.side === 'S' || trade.side === 'SELL' ? (
- <TrendingDown size={10} style={{ color: FINCEPT_COLORS.RED }} />
+ <TrendingDown size={10} style={{ color: colors.alert }} />
) : (
- <ArrowRight size={10} style={{ color: FINCEPT_COLORS.MUTED }} />
+ <ArrowRight size={10} style={{ color: colors.textMuted }} />
)}
</div>
</div>
@@ -395,12 +398,12 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
{/* Imbalance View */}
{activeSchema === 'imbalance' && (
imbalances.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
Click refresh to load imbalance data (available at market open/close)
</div>
) : (
<div>
- <div className="grid grid-cols-5 gap-2 mb-1 text-[9px]" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="grid grid-cols-5 gap-2 mb-1 text-[9px]" style={{ color: colors.textMuted }}>
<div>TIME</div>
<div>SYMBOL</div>
<div className="text-right">REF PRICE</div>
@@ -409,13 +412,13 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
</div>
{imbalances.slice(0, 20).map((imb, idx) => (
<div key={idx} className="grid grid-cols-5 gap-2 py-0.5 text-[10px]">
- <div style={{ color: FINCEPT_COLORS.MUTED }}>{formatTime(imb.ts_event)}</div>
+ <div style={{ color: colors.textMuted }}>{formatTime(imb.ts_event)}</div>
<div style={{ color: accentColor, fontWeight: 'bold' }}>{imb.symbol}</div>
- <div className="text-right font-mono" style={{ color: FINCEPT_COLORS.WHITE }}>{formatPrice(imb.ref_price)}</div>
- <div className="text-right" style={{ color: imb.imbalance_side === 'B' ? FINCEPT_COLORS.GREEN : FINCEPT_COLORS.RED }}>
+ <div className="text-right font-mono" style={{ color: textColor }}>{formatPrice(imb.ref_price)}</div>
+ <div className="text-right" style={{ color: imb.imbalance_side === 'B' ? colors.success : colors.alert }}>
{formatQty(imb.imbalance_qty)} {imb.imbalance_side}
</div>
- <div className="text-right" style={{ color: FINCEPT_COLORS.MUTED }}>{imb.auction_type || '--'}</div>
+ <div className="text-right" style={{ color: colors.textMuted }}>{imb.auction_type || '--'}</div>
</div>
))}
</div>
@@ -425,12 +428,12 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
{/* Statistics View */}
{activeSchema === 'statistics' && (
statistics.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
Click refresh to load statistics (trading halts, circuit breakers)
</div>
) : (
<div>
- <div className="grid grid-cols-4 gap-2 mb-1 text-[9px]" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="grid grid-cols-4 gap-2 mb-1 text-[9px]" style={{ color: colors.textMuted }}>
<div>TIME</div>
<div>SYMBOL</div>
<div>TYPE</div>
@@ -438,10 +441,10 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
</div>
{statistics.slice(0, 20).map((stat, idx) => (
<div key={idx} className="grid grid-cols-4 gap-2 py-0.5 text-[10px]">
- <div style={{ color: FINCEPT_COLORS.MUTED }}>{formatTime(stat.ts_event)}</div>
+ <div style={{ color: colors.textMuted }}>{formatTime(stat.ts_event)}</div>
<div style={{ color: accentColor, fontWeight: 'bold' }}>{stat.symbol}</div>
- <div style={{ color: FINCEPT_COLORS.YELLOW }}>{stat.stat_type || '--'}</div>
- <div className="text-right font-mono" style={{ color: FINCEPT_COLORS.WHITE }}>
+ <div style={{ color: colors.warning }}>{stat.stat_type || '--'}</div>
+ <div className="text-right font-mono" style={{ color: textColor }}>
{stat.price > 0 ? formatPrice(stat.price) : formatQty(stat.quantity)}
</div>
</div>
@@ -453,12 +456,12 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
{/* Status View */}
{activeSchema === 'status' && (
statuses.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
Click refresh to load trading status (halts, Reg SHO)
</div>
) : (
<div>
- <div className="grid grid-cols-4 gap-2 mb-1 text-[9px]" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="grid grid-cols-4 gap-2 mb-1 text-[9px]" style={{ color: colors.textMuted }}>
<div>TIME</div>
<div>SYMBOL</div>
<div>ACTION</div>
@@ -466,16 +469,16 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
</div>
{statuses.slice(0, 20).map((status, idx) => (
<div key={idx} className="grid grid-cols-4 gap-2 py-0.5 text-[10px]">
- <div style={{ color: FINCEPT_COLORS.MUTED }}>{formatTime(status.ts_event)}</div>
+ <div style={{ color: colors.textMuted }}>{formatTime(status.ts_event)}</div>
<div style={{ color: accentColor, fontWeight: 'bold' }}>{status.symbol}</div>
- <div style={{ color: status.action === 'HALT' ? FINCEPT_COLORS.RED : FINCEPT_COLORS.GREEN }}>
+ <div style={{ color: status.action === 'HALT' ? colors.alert : colors.success }}>
{status.action || '--'}
</div>
- <div style={{ color: FINCEPT_COLORS.MUTED }}>{status.reason || status.trading_event || '--'}</div>
+ <div style={{ color: colors.textMuted }}>{status.reason || status.trading_event || '--'}</div>
</div>
))}
{statuses.some(s => s.is_short_sell_restricted) && (
- <div className="mt-2 p-1 text-[9px]" style={{ backgroundColor: FINCEPT_COLORS.RED + '20', borderRadius: '2px', color: FINCEPT_COLORS.RED }}>
+ <div className="mt-2 p-1 text-[9px]" style={{ backgroundColor: colors.alert + '20', borderRadius: 'var(--ft-border-radius)', color: colors.alert }}>
Some symbols have Reg SHO restrictions
</div>
)}
@@ -490,8 +493,8 @@ export const AdditionalSchemasPanel: React.FC<AdditionalSchemasPanelProps> = ({
<div
className="flex items-center justify-between p-2 text-[9px]"
style={{
- borderTop: `1px solid ${FINCEPT_COLORS.BORDER}`,
- color: FINCEPT_COLORS.MUTED,
+ borderTop: `1px solid ${colors.textMuted}`,
+ color: colors.textMuted,
}}
>
<span>Symbols: {symbols.join(', ')}</span>
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/BatchDownloadPanel.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/BatchDownloadPanel.tsx
index 22abcdcdc..50ba70bf6 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/BatchDownloadPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/BatchDownloadPanel.tsx
@@ -22,7 +22,8 @@ import {
FileText,
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
-import { FINCEPT_COLORS } from '../constants';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { showSuccess } from '@/utils/notifications';
interface BatchJob {
@@ -56,12 +57,7 @@ interface BatchDownloadPanelProps {
textColor: string;
}
-const JOB_STATE_COLORS: Record<string, string> = {
- queued: FINCEPT_COLORS.YELLOW,
- processing: FINCEPT_COLORS.CYAN,
- done: FINCEPT_COLORS.GREEN,
- expired: FINCEPT_COLORS.RED,
-};
+// Colors will be set dynamically from theme
const JOB_STATE_ICONS: Record<string, React.ReactNode> = {
queued: <Clock size={12} />,
@@ -103,6 +99,15 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
accentColor,
textColor,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors, fontSize } = useTerminalTheme();
+
+ const JOB_STATE_COLORS: Record<string, string> = {
+ queued: colors.warning,
+ processing: colors.info,
+ done: colors.success,
+ expired: colors.alert,
+ };
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [jobs, setJobs] = useState<BatchJob[]>([]);
@@ -290,14 +295,14 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
<div
className="p-4 text-center"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
- <Download size={24} style={{ color: FINCEPT_COLORS.MUTED, margin: '0 auto 8px' }} />
- <div className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
- Configure Databento API key for batch downloads
+ <Download size={24} style={{ color: colors.textMuted, margin: '0 auto 8px' }} />
+ <div className="text-xs" style={{ color: colors.textMuted }}>
+ {t('batchDownload.configureApiKey')}
</div>
</div>
);
@@ -306,9 +311,9 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
return (
<div
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
overflow: 'hidden',
}}
>
@@ -316,16 +321,16 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
<div
className="flex items-center justify-between p-2"
style={{
- backgroundColor: FINCEPT_COLORS.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
}}
>
<div className="flex items-center gap-2">
<Archive size={14} style={{ color: accentColor }} />
<span className="text-xs font-bold" style={{ color: accentColor }}>
- BATCH DOWNLOADS
+ {t('batchDownload.title')}
</span>
- <span className="text-[9px] px-1" style={{ backgroundColor: FINCEPT_COLORS.BORDER, color: FINCEPT_COLORS.MUTED, borderRadius: '2px' }}>
+ <span className="text-[9px] px-1" style={{ backgroundColor: colors.textMuted, color: colors.textMuted, borderRadius: 'var(--ft-border-radius)' }}>
{jobs.length}
</span>
</div>
@@ -333,7 +338,7 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
<button
onClick={() => setShowNewJobForm(!showNewJobForm)}
className="p-1"
- style={{ color: showNewJobForm ? FINCEPT_COLORS.GREEN : accentColor }}
+ style={{ color: showNewJobForm ? colors.success : accentColor }}
title="New Job"
>
<Plus size={12} />
@@ -341,7 +346,7 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
<button
onClick={fetchJobs}
disabled={loading}
- style={{ color: loading ? FINCEPT_COLORS.MUTED : accentColor }}
+ style={{ color: loading ? colors.textMuted : accentColor }}
>
<RefreshCw size={12} className={loading ? 'animate-spin' : ''} />
</button>
@@ -353,10 +358,10 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
<div
className="flex items-center gap-2 m-2 p-2 text-xs"
style={{
- backgroundColor: `${FINCEPT_COLORS.RED}15`,
- border: `1px solid ${FINCEPT_COLORS.RED}50`,
- borderRadius: '2px',
- color: FINCEPT_COLORS.RED,
+ backgroundColor: `${colors.alert}15`,
+ border: `1px solid ${colors.alert}50`,
+ borderRadius: 'var(--ft-border-radius)',
+ color: colors.alert,
}}
>
<AlertCircle size={12} />
@@ -366,24 +371,24 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
{/* New Job Form */}
{showNewJobForm && (
- <div className="p-2" style={{ borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`, backgroundColor: FINCEPT_COLORS.BLACK }}>
+ <div className="p-2" style={{ borderBottom: `1px solid ${colors.textMuted}`, backgroundColor: colors.background }}>
<div className="text-[10px] font-bold mb-2" style={{ color: accentColor }}>
- NEW BATCH JOB
+ {t('batchDownload.newBatchJob')}
</div>
<div className="grid grid-cols-2 gap-2 mb-2">
{/* Dataset */}
<div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.MUTED }}>Dataset</label>
+ <label className="text-[9px] mb-1 block" style={{ color: colors.textMuted }}>{t('batchDownload.dataset')}</label>
<select
value={newJobDataset}
onChange={(e) => setNewJobDataset(e.target.value)}
className="w-full text-[10px] p-1"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
color: textColor,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{POPULAR_DATASETS.map((ds) => (
@@ -394,16 +399,16 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
{/* Schema */}
<div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.MUTED }}>Schema</label>
+ <label className="text-[9px] mb-1 block" style={{ color: colors.textMuted }}>{t('batchDownload.schema')}</label>
<select
value={newJobSchema}
onChange={(e) => setNewJobSchema(e.target.value)}
className="w-full text-[10px] p-1"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
color: textColor,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{SCHEMA_OPTIONS.map((s) => (
@@ -415,7 +420,7 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
{/* Symbols */}
<div className="mb-2">
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.MUTED }}>Symbols (comma-separated)</label>
+ <label className="text-[9px] mb-1 block" style={{ color: colors.textMuted }}>{t('batchDownload.symbolsCommaSeparated')}</label>
<input
type="text"
value={newJobSymbols}
@@ -423,10 +428,10 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
placeholder="SPY, QQQ, AAPL"
className="w-full text-[10px] p-1"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
color: textColor,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
/>
</div>
@@ -434,34 +439,34 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
<div className="grid grid-cols-2 gap-2 mb-2">
{/* Start Date */}
<div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.MUTED }}>Start Date</label>
+ <label className="text-[9px] mb-1 block" style={{ color: colors.textMuted }}>{t('batchDownload.startDate')}</label>
<input
type="date"
value={newJobStartDate}
onChange={(e) => setNewJobStartDate(e.target.value)}
className="w-full text-[10px] p-1"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
color: textColor,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
/>
</div>
{/* End Date */}
<div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.MUTED }}>End Date</label>
+ <label className="text-[9px] mb-1 block" style={{ color: colors.textMuted }}>{t('batchDownload.endDate')}</label>
<input
type="date"
value={newJobEndDate}
onChange={(e) => setNewJobEndDate(e.target.value)}
className="w-full text-[10px] p-1"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
color: textColor,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
/>
</div>
@@ -470,16 +475,16 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
<div className="grid grid-cols-2 gap-2 mb-2">
{/* Encoding */}
<div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.MUTED }}>Encoding</label>
+ <label className="text-[9px] mb-1 block" style={{ color: colors.textMuted }}>{t('batchDownload.encoding')}</label>
<select
value={newJobEncoding}
onChange={(e) => setNewJobEncoding(e.target.value)}
className="w-full text-[10px] p-1"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
color: textColor,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{ENCODING_OPTIONS.map((e) => (
@@ -490,16 +495,16 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
{/* Compression */}
<div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.MUTED }}>Compression</label>
+ <label className="text-[9px] mb-1 block" style={{ color: colors.textMuted }}>{t('batchDownload.compression')}</label>
<select
value={newJobCompression}
onChange={(e) => setNewJobCompression(e.target.value)}
className="w-full text-[10px] p-1"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
color: textColor,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{COMPRESSION_OPTIONS.map((c) => (
@@ -514,13 +519,13 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
disabled={loading}
className="w-full py-1.5 text-[10px] font-bold flex items-center justify-center gap-1"
style={{
- backgroundColor: loading ? FINCEPT_COLORS.BORDER : accentColor,
- color: FINCEPT_COLORS.BLACK,
- borderRadius: '2px',
+ backgroundColor: loading ? colors.textMuted : accentColor,
+ color: colors.background,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{loading ? <Loader2 size={12} className="animate-spin" /> : <Plus size={12} />}
- SUBMIT JOB
+ {t('batchDownload.submitJob')}
</button>
</div>
)}
@@ -532,8 +537,8 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
<RefreshCw size={16} className="animate-spin" style={{ color: accentColor }} />
</div>
) : jobs.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
- No batch jobs found. Click + to create one.
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
+ {t('batchDownload.noBatchJobs')}
</div>
) : (
<div className="space-y-2">
@@ -542,9 +547,9 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
key={job.job_id}
className="p-2"
style={{
- backgroundColor: selectedJob?.job_id === job.job_id ? `${accentColor}15` : FINCEPT_COLORS.BLACK,
- borderRadius: '2px',
- border: `1px solid ${selectedJob?.job_id === job.job_id ? accentColor : FINCEPT_COLORS.BORDER}`,
+ backgroundColor: selectedJob?.job_id === job.job_id ? `${accentColor}15` : colors.background,
+ borderRadius: 'var(--ft-border-radius)',
+ border: `1px solid ${selectedJob?.job_id === job.job_id ? accentColor : colors.textMuted}`,
}}
>
{/* Job Header */}
@@ -556,7 +561,7 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
<span className="text-[10px] font-bold" style={{ color: textColor }}>
{job.dataset}
</span>
- <span className="text-[9px] px-1" style={{ backgroundColor: FINCEPT_COLORS.BORDER, borderRadius: '2px', color: FINCEPT_COLORS.MUTED }}>
+ <span className="text-[9px] px-1" style={{ backgroundColor: colors.textMuted, borderRadius: 'var(--ft-border-radius)', color: colors.textMuted }}>
{job.schema}
</span>
</div>
@@ -566,7 +571,7 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
</div>
{/* Job Details */}
- <div className="grid grid-cols-3 gap-1 text-[9px] mb-1" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="grid grid-cols-3 gap-1 text-[9px] mb-1" style={{ color: colors.textMuted }}>
<div className="flex items-center gap-1">
<FileText size={9} />
<span>{job.symbols?.slice(0, 3).join(', ')}{job.symbols?.length > 3 ? '...' : ''}</span>
@@ -577,16 +582,16 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
</div>
<div className="flex items-center gap-1">
<Database size={9} />
- <span>{formatRecordCount(job.record_count)} records</span>
+ <span>{formatRecordCount(job.record_count)} {t('batchDownload.records')}</span>
</div>
</div>
{/* Job Size & Cost */}
<div className="flex items-center justify-between">
- <div className="flex items-center gap-2 text-[9px]" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="flex items-center gap-2 text-[9px]" style={{ color: colors.textMuted }}>
<span>{formatBytes(job.size_bytes)}</span>
{job.cost > 0 && (
- <span style={{ color: FINCEPT_COLORS.YELLOW }}>${job.cost.toFixed(2)}</span>
+ <span style={{ color: colors.warning }}>${job.cost.toFixed(2)}</span>
)}
</div>
@@ -599,8 +604,8 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
className="p-1 text-[9px] flex items-center gap-1"
style={{
backgroundColor: accentColor,
- color: FINCEPT_COLORS.BLACK,
- borderRadius: '2px',
+ color: colors.background,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{downloadingJob === job.job_id ? (
@@ -608,7 +613,7 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
) : (
<FileDown size={10} />
)}
- Download
+ {t('batchDownload.download')}
</button>
)}
<button
@@ -624,7 +629,7 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
}
}}
className="p-1"
- style={{ color: FINCEPT_COLORS.MUTED }}
+ style={{ color: colors.textMuted }}
>
<ChevronRight
size={12}
@@ -639,19 +644,19 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
{/* Expanded Job Files */}
{selectedJob?.job_id === job.job_id && job.state === 'done' && jobFiles.length > 0 && (
- <div className="mt-2 pt-2" style={{ borderTop: `1px solid ${FINCEPT_COLORS.BORDER}` }}>
- <div className="text-[9px] mb-1" style={{ color: FINCEPT_COLORS.MUTED }}>
- FILES ({jobFiles.length})
+ <div className="mt-2 pt-2" style={{ borderTop: `1px solid ${colors.textMuted}` }}>
+ <div className="text-[9px] mb-1" style={{ color: colors.textMuted }}>
+ {t('batchDownload.files')} ({jobFiles.length})
</div>
<div className="space-y-1 max-h-32 overflow-y-auto">
{jobFiles.map((file, idx) => (
<div
key={idx}
className="flex items-center justify-between p-1 text-[9px]"
- style={{ backgroundColor: FINCEPT_COLORS.DARK_BG, borderRadius: '2px' }}
+ style={{ backgroundColor: colors.background, borderRadius: 'var(--ft-border-radius)' }}
>
<span style={{ color: textColor }}>{file.filename}</span>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>{formatBytes(file.size_bytes)}</span>
+ <span style={{ color: colors.textMuted }}>{formatBytes(file.size_bytes)}</span>
</div>
))}
</div>
@@ -667,12 +672,12 @@ export const BatchDownloadPanel: React.FC<BatchDownloadPanelProps> = ({
<div
className="flex items-center gap-1 p-2 text-[9px]"
style={{
- borderTop: `1px solid ${FINCEPT_COLORS.BORDER}`,
- color: FINCEPT_COLORS.MUTED,
+ borderTop: `1px solid ${colors.textMuted}`,
+ color: colors.textMuted,
}}
>
<Info size={10} />
- <span>Jobs expire after 7 days. Download completed jobs promptly.</span>
+ <span>{t('batchDownload.jobsExpireNotice')}</span>
</div>
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/ControlBar.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/ControlBar.tsx
index 4da08d0b8..b328503a9 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/ControlBar.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/ControlBar.tsx
@@ -1,7 +1,6 @@
/**
* Surface Analytics - Control Bar Component
* Top navigation with chart type selection and controls
- * Follows UI Design System (UI_DESIGN_SYSTEM.md)
*/
import React from 'react';
@@ -14,8 +13,9 @@ import {
Settings,
AlertCircle,
} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import type { ChartType } from '../types';
-import { FINCEPT_COLORS, TYPOGRAPHY } from '../constants';
interface ControlBarProps {
activeChart: ChartType;
@@ -38,13 +38,15 @@ export const ControlBar: React.FC<ControlBarProps> = ({
loading,
hasApiKey,
accentColor,
- textColor,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+
const chartButtons = [
- { id: 'volatility' as ChartType, icon: TrendingUp, label: 'VOL SURFACE' },
- { id: 'correlation' as ChartType, icon: Network, label: 'CORRELATION' },
- { id: 'yield-curve' as ChartType, icon: Activity, label: 'YIELD CURVE' },
- { id: 'pca' as ChartType, icon: BarChart3, label: 'PCA FACTORS' },
+ { id: 'volatility' as ChartType, icon: TrendingUp, label: t('charts.volatility') },
+ { id: 'correlation' as ChartType, icon: Network, label: t('charts.correlation') },
+ { id: 'yield-curve' as ChartType, icon: Activity, label: t('charts.yieldCurve') },
+ { id: 'pca' as ChartType, icon: BarChart3, label: t('charts.pca') },
];
return (
@@ -54,7 +56,7 @@ export const ControlBar: React.FC<ControlBarProps> = ({
alignItems: 'center',
justifyContent: 'space-between',
padding: '8px 16px',
- backgroundColor: FINCEPT_COLORS.HEADER_BG,
+ backgroundColor: colors.panel,
borderBottom: `2px solid ${accentColor}`,
boxShadow: `0 2px 8px ${accentColor}20`,
flexShrink: 0,
@@ -65,17 +67,17 @@ export const ControlBar: React.FC<ControlBarProps> = ({
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<BarChart3 size={14} style={{ color: accentColor }} />
<span style={{
- fontSize: TYPOGRAPHY.HEADER_SIZE,
+ fontSize: fontSize.body,
fontWeight: 700,
color: accentColor,
letterSpacing: '0.5px',
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontFamily,
}}>
- SURFACE ANALYTICS
+ {t('title')}
</span>
</div>
- <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT_COLORS.BORDER }} />
+ <div style={{ height: '16px', width: '1px', backgroundColor: colors.textMuted }} />
{/* Chart Type Buttons - Tab style */}
<div style={{ display: 'flex', gap: '4px' }}>
@@ -89,14 +91,14 @@ export const ControlBar: React.FC<ControlBarProps> = ({
gap: '6px',
padding: '6px 12px',
backgroundColor: activeChart === id ? accentColor : 'transparent',
- color: activeChart === id ? FINCEPT_COLORS.BLACK : FINCEPT_COLORS.GRAY,
+ color: activeChart === id ? colors.background : colors.textMuted,
border: 'none',
- borderRadius: '2px',
- fontSize: TYPOGRAPHY.LABEL_SIZE,
+ borderRadius: 'var(--ft-border-radius)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
letterSpacing: '0.5px',
cursor: 'pointer',
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontFamily,
transition: 'all 0.2s',
}}
>
@@ -115,26 +117,26 @@ export const ControlBar: React.FC<ControlBarProps> = ({
alignItems: 'center',
gap: '4px',
padding: '2px 6px',
- backgroundColor: `${FINCEPT_COLORS.RED}20`,
- color: FINCEPT_COLORS.RED,
- fontSize: '8px',
+ backgroundColor: `${colors.alert}20`,
+ color: colors.alert,
+ fontSize: fontSize.tiny,
fontWeight: 700,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}>
<AlertCircle size={10} />
- <span>NO API KEY</span>
+ <span>{t('noApiKey')}</span>
</div>
)}
{/* Last Update */}
<span style={{
- fontSize: TYPOGRAPHY.LABEL_SIZE,
- color: FINCEPT_COLORS.GRAY,
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontSize: fontSize.tiny,
+ color: colors.textMuted,
+ fontFamily,
letterSpacing: '0.5px',
}}>
- LAST UPDATE:{' '}
- <span style={{ color: FINCEPT_COLORS.CYAN }}>
+ {t('lastUpdate')}:{' '}
+ <span style={{ color: colors.info }}>
{lastUpdate.toLocaleTimeString()}
</span>
</span>
@@ -148,11 +150,11 @@ export const ControlBar: React.FC<ControlBarProps> = ({
gap: '4px',
padding: '6px 10px',
backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- color: FINCEPT_COLORS.GRAY,
- fontSize: TYPOGRAPHY.LABEL_SIZE,
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.textMuted,
+ fontSize: fontSize.tiny,
fontWeight: 700,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
cursor: 'pointer',
transition: 'all 0.2s',
}}
@@ -170,18 +172,18 @@ export const ControlBar: React.FC<ControlBarProps> = ({
gap: '6px',
padding: '8px 16px',
backgroundColor: accentColor,
- color: FINCEPT_COLORS.BLACK,
+ color: colors.background,
border: 'none',
- borderRadius: '2px',
- fontSize: TYPOGRAPHY.LABEL_SIZE,
+ borderRadius: 'var(--ft-border-radius)',
+ fontSize: fontSize.tiny,
fontWeight: 700,
cursor: loading ? 'not-allowed' : 'pointer',
opacity: loading ? 0.7 : 1,
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontFamily,
}}
>
<RefreshCw size={12} className={loading ? 'animate-spin' : ''} />
- {loading ? 'LOADING' : 'REFRESH'}
+ {loading ? t('common:loading') : t('refresh')}
</button>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/CostEstimator.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/CostEstimator.tsx
index 057561af1..6bb3abb23 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/CostEstimator.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/CostEstimator.tsx
@@ -6,7 +6,8 @@
import React, { useState, useCallback } from 'react';
import { DollarSign, Calculator, AlertTriangle, CheckCircle, RefreshCw, FileText } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
-import { FINCEPT_COLORS } from '../constants';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface CostEstimate {
dataset: string;
@@ -53,6 +54,8 @@ export const CostEstimator: React.FC<CostEstimatorProps> = ({
textColor,
onEstimate,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors } = useTerminalTheme();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [estimate, setEstimate] = useState<CostEstimate | null>(null);
@@ -102,9 +105,9 @@ export const CostEstimator: React.FC<CostEstimatorProps> = ({
const getCostLevelColor = (level: 'low' | 'medium' | 'high') => {
switch (level) {
- case 'low': return FINCEPT_COLORS.GREEN;
- case 'medium': return FINCEPT_COLORS.YELLOW;
- case 'high': return FINCEPT_COLORS.RED;
+ case 'low': return colors.success;
+ case 'medium': return colors.warning;
+ case 'high': return colors.alert;
}
};
@@ -127,9 +130,9 @@ export const CostEstimator: React.FC<CostEstimatorProps> = ({
return (
<div
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
padding: '12px',
}}
>
@@ -147,9 +150,9 @@ export const CostEstimator: React.FC<CostEstimatorProps> = ({
className="flex items-center gap-1 px-2 py-1 text-xs"
style={{
backgroundColor: accentColor,
- color: FINCEPT_COLORS.BLACK,
+ color: colors.background,
border: 'none',
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
opacity: loading || !dataset || symbols.length === 0 ? 0.5 : 1,
}}
>
@@ -166,25 +169,25 @@ export const CostEstimator: React.FC<CostEstimatorProps> = ({
<div
className="grid grid-cols-2 gap-2 mb-3 p-2 text-xs"
style={{
- backgroundColor: FINCEPT_COLORS.BLACK,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<div>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Dataset: </span>
+ <span style={{ color: colors.textMuted }}>Dataset: </span>
<span style={{ color: textColor }}>{dataset || 'Not selected'}</span>
</div>
<div>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Schema: </span>
+ <span style={{ color: colors.textMuted }}>Schema: </span>
<span style={{ color: getCostLevelColor(schemaInfo.costLevel) }}>{schemaInfo.name}</span>
</div>
<div>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Symbols: </span>
+ <span style={{ color: colors.textMuted }}>Symbols: </span>
<span style={{ color: textColor }}>{symbols.length > 0 ? symbols.join(', ') : 'None'}</span>
</div>
<div>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Range: </span>
+ <span style={{ color: colors.textMuted }}>Range: </span>
<span style={{ color: textColor }}>{startDate} → {endDate}</span>
</div>
</div>
@@ -194,10 +197,10 @@ export const CostEstimator: React.FC<CostEstimatorProps> = ({
<div
className="flex items-center gap-2 mb-3 p-2 text-xs"
style={{
- backgroundColor: `${FINCEPT_COLORS.YELLOW}15`,
- border: `1px solid ${FINCEPT_COLORS.YELLOW}50`,
- borderRadius: '2px',
- color: FINCEPT_COLORS.YELLOW,
+ backgroundColor: `${colors.warning}15`,
+ border: `1px solid ${colors.warning}50`,
+ borderRadius: 'var(--ft-border-radius)',
+ color: colors.warning,
}}
>
<AlertTriangle size={12} />
@@ -210,10 +213,10 @@ export const CostEstimator: React.FC<CostEstimatorProps> = ({
<div
className="flex items-center gap-2 mb-3 p-2 text-xs"
style={{
- backgroundColor: `${FINCEPT_COLORS.RED}15`,
- border: `1px solid ${FINCEPT_COLORS.RED}50`,
- borderRadius: '2px',
- color: FINCEPT_COLORS.RED,
+ backgroundColor: `${colors.alert}15`,
+ border: `1px solid ${colors.alert}50`,
+ borderRadius: 'var(--ft-border-radius)',
+ color: colors.alert,
}}
>
<AlertTriangle size={12} />
@@ -226,15 +229,15 @@ export const CostEstimator: React.FC<CostEstimatorProps> = ({
<div
className="p-3"
style={{
- backgroundColor: FINCEPT_COLORS.BLACK,
- border: `1px solid ${FINCEPT_COLORS.GREEN}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.success}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
- <CheckCircle size={14} style={{ color: FINCEPT_COLORS.GREEN }} />
- <span className="text-xs font-bold" style={{ color: FINCEPT_COLORS.GREEN }}>
+ <CheckCircle size={14} style={{ color: colors.success }} />
+ <span className="text-xs font-bold" style={{ color: colors.success }}>
ESTIMATE READY
</span>
</div>
@@ -244,12 +247,12 @@ export const CostEstimator: React.FC<CostEstimatorProps> = ({
{/* Record Count */}
<div className="text-center">
<div className="flex items-center justify-center gap-1 mb-1">
- <FileText size={12} style={{ color: FINCEPT_COLORS.CYAN }} />
- <span className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <FileText size={12} style={{ color: colors.info }} />
+ <span className="text-xs" style={{ color: colors.textMuted }}>
RECORDS
</span>
</div>
- <div className="text-lg font-bold" style={{ color: FINCEPT_COLORS.CYAN }}>
+ <div className="text-lg font-bold" style={{ color: colors.info }}>
{formatRecordCount(estimate.record_count)}
</div>
</div>
@@ -257,14 +260,14 @@ export const CostEstimator: React.FC<CostEstimatorProps> = ({
{/* Cost */}
<div className="text-center">
<div className="flex items-center justify-center gap-1 mb-1">
- <DollarSign size={12} style={{ color: FINCEPT_COLORS.GREEN }} />
- <span className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <DollarSign size={12} style={{ color: colors.success }} />
+ <span className="text-xs" style={{ color: colors.textMuted }}>
ESTIMATED COST
</span>
</div>
<div
className="text-lg font-bold"
- style={{ color: estimate.cost_usd === 0 ? FINCEPT_COLORS.GREEN : FINCEPT_COLORS.YELLOW }}
+ style={{ color: estimate.cost_usd === 0 ? colors.success : colors.warning }}
>
{formatCost(estimate.cost_usd)}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/DatasetBrowser.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/DatasetBrowser.tsx
index 2a3ad1405..036be136b 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/DatasetBrowser.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/DatasetBrowser.tsx
@@ -6,7 +6,8 @@
import React, { useState, useEffect, useCallback } from 'react';
import { Database, ChevronRight, RefreshCw, AlertCircle, Calendar, FileText, DollarSign } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
-import { FINCEPT_COLORS, TYPOGRAPHY } from '../constants';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface DatasetInfo {
id: string;
@@ -52,6 +53,8 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
accentColor,
textColor,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors } = useTerminalTheme();
const [datasets, setDatasets] = useState<DatasetInfo[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -157,13 +160,13 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
<div
className="p-4 text-center"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
- <Database size={24} style={{ color: FINCEPT_COLORS.MUTED, margin: '0 auto 8px' }} />
- <div className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <Database size={24} style={{ color: colors.textMuted, margin: '0 auto 8px' }} />
+ <div className="text-xs" style={{ color: colors.textMuted }}>
Configure Databento API key to browse datasets
</div>
</div>
@@ -173,9 +176,9 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
return (
<div
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
overflow: 'hidden',
}}
>
@@ -183,8 +186,8 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
<div
className="flex items-center justify-between p-2"
style={{
- backgroundColor: FINCEPT_COLORS.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
}}
>
<div className="flex items-center gap-2">
@@ -192,14 +195,14 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
<span className="text-xs font-bold" style={{ color: accentColor }}>
AVAILABLE DATASETS
</span>
- <span className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <span className="text-xs" style={{ color: colors.textMuted }}>
({datasets.length})
</span>
</div>
<button
onClick={fetchDatasets}
disabled={loading}
- style={{ color: FINCEPT_COLORS.MUTED }}
+ style={{ color: colors.textMuted }}
>
<RefreshCw size={12} className={loading ? 'animate-spin' : ''} />
</button>
@@ -208,7 +211,7 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
{/* Content */}
<div className="max-h-64 overflow-y-auto p-2">
{error ? (
- <div className="flex items-center gap-2 p-2 text-xs" style={{ color: FINCEPT_COLORS.RED }}>
+ <div className="flex items-center gap-2 p-2 text-xs" style={{ color: colors.alert }}>
<AlertCircle size={14} />
{error}
</div>
@@ -217,7 +220,7 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
<RefreshCw size={16} className="animate-spin" style={{ color: accentColor }} />
</div>
) : datasets.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
No datasets available
</div>
) : (
@@ -228,7 +231,7 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
<div key={category} className="mb-3">
<div
className="text-xs font-bold mb-1 px-1"
- style={{ color: FINCEPT_COLORS.MUTED, letterSpacing: '0.5px' }}
+ style={{ color: colors.textMuted, letterSpacing: '0.5px' }}
>
{category.toUpperCase()}
</div>
@@ -243,9 +246,9 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
<div
key={dataset.id}
style={{
- backgroundColor: isSelected ? `${accentColor}20` : FINCEPT_COLORS.BLACK,
- border: `1px solid ${isSelected ? accentColor : FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: isSelected ? `${accentColor}20` : colors.background,
+ border: `1px solid ${isSelected ? accentColor : colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
marginBottom: '4px',
}}
>
@@ -258,7 +261,7 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
<ChevronRight
size={12}
style={{
- color: FINCEPT_COLORS.MUTED,
+ color: colors.textMuted,
transform: isExpanded ? 'rotate(90deg)' : 'none',
transition: 'transform 0.2s',
}}
@@ -275,9 +278,9 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
className="px-2 py-0.5 text-xs"
style={{
backgroundColor: isSelected ? accentColor : 'transparent',
- color: isSelected ? FINCEPT_COLORS.BLACK : accentColor,
+ color: isSelected ? colors.background : accentColor,
border: `1px solid ${accentColor}`,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{isSelected ? 'SELECTED' : 'SELECT'}
@@ -288,34 +291,34 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
{isExpanded && (
<div
className="px-2 pb-2"
- style={{ borderTop: `1px solid ${FINCEPT_COLORS.BORDER}` }}
+ style={{ borderTop: `1px solid ${colors.textMuted}` }}
>
- <div className="text-xs mt-2 mb-2" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs mt-2 mb-2" style={{ color: colors.textMuted }}>
{description}
</div>
{loadingDetails === dataset.id ? (
- <div className="flex items-center gap-2 text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="flex items-center gap-2 text-xs" style={{ color: colors.textMuted }}>
<RefreshCw size={10} className="animate-spin" />
Loading details...
</div>
) : details ? (
<div className="grid grid-cols-2 gap-2 text-xs">
{details.start_date && (
- <div className="flex items-center gap-1" style={{ color: FINCEPT_COLORS.CYAN }}>
+ <div className="flex items-center gap-1" style={{ color: colors.info }}>
<Calendar size={10} />
<span>From: {details.start_date}</span>
</div>
)}
{details.end_date && (
- <div className="flex items-center gap-1" style={{ color: FINCEPT_COLORS.CYAN }}>
+ <div className="flex items-center gap-1" style={{ color: colors.info }}>
<Calendar size={10} />
<span>To: {details.end_date}</span>
</div>
)}
{details.schemas && details.schemas.length > 0 && (
<div className="col-span-2">
- <div className="flex items-center gap-1 mb-1" style={{ color: FINCEPT_COLORS.GREEN }}>
+ <div className="flex items-center gap-1 mb-1" style={{ color: colors.success }}>
<FileText size={10} />
<span>Schemas:</span>
</div>
@@ -325,17 +328,17 @@ export const DatasetBrowser: React.FC<DatasetBrowserProps> = ({
key={schema}
className="px-1 py-0.5"
style={{
- backgroundColor: FINCEPT_COLORS.BORDER,
+ backgroundColor: colors.textMuted,
color: textColor,
fontSize: '9px',
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{schema}
</span>
))}
{details.schemas.length > 8 && (
- <span className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <span className="text-xs" style={{ color: colors.textMuted }}>
+{details.schemas.length - 8} more
</span>
)}
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/FuturesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/FuturesPanel.tsx
index d8fff0f63..b213187b4 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/FuturesPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/FuturesPanel.tsx
@@ -14,7 +14,8 @@ import {
ChevronRight,
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
-import { FINCEPT_COLORS } from '../constants';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface FuturesContract {
symbol: string;
@@ -52,6 +53,8 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
accentColor,
textColor,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors } = useTerminalTheme();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [selectedFuture, setSelectedFuture] = useState('ES');
@@ -145,13 +148,13 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
<div
className="p-4 text-center"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
- <LineChart size={24} style={{ color: FINCEPT_COLORS.MUTED, margin: '0 auto 8px' }} />
- <div className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <LineChart size={24} style={{ color: colors.textMuted, margin: '0 auto 8px' }} />
+ <div className="text-xs" style={{ color: colors.textMuted }}>
Configure Databento API key for futures data
</div>
</div>
@@ -163,9 +166,9 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
return (
<div
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
overflow: 'hidden',
}}
>
@@ -173,8 +176,8 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
<div
className="flex items-center justify-between p-2"
style={{
- backgroundColor: FINCEPT_COLORS.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
}}
>
<div className="flex items-center gap-2">
@@ -186,15 +189,15 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
<button
onClick={fetchContracts}
disabled={loading}
- style={{ color: loading ? FINCEPT_COLORS.MUTED : accentColor }}
+ style={{ color: loading ? colors.textMuted : accentColor }}
>
<RefreshCw size={12} className={loading ? 'animate-spin' : ''} />
</button>
</div>
{/* Popular Futures Selector */}
- <div className="flex flex-wrap items-center gap-1 p-2" style={{ borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}` }}>
- <span className="text-[9px]" style={{ color: FINCEPT_COLORS.MUTED }}>Popular:</span>
+ <div className="flex flex-wrap items-center gap-1 p-2" style={{ borderBottom: `1px solid ${colors.textMuted}` }}>
+ <span className="text-[9px]" style={{ color: colors.textMuted }}>Popular:</span>
{POPULAR_FUTURES.map((f) => (
<button
key={f.symbol}
@@ -204,9 +207,9 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
}}
className="px-2 py-0.5 text-[9px] font-bold"
style={{
- backgroundColor: selectedFuture === f.symbol ? accentColor : FINCEPT_COLORS.BORDER,
- color: selectedFuture === f.symbol ? FINCEPT_COLORS.BLACK : textColor,
- borderRadius: '2px',
+ backgroundColor: selectedFuture === f.symbol ? accentColor : colors.textMuted,
+ color: selectedFuture === f.symbol ? colors.background : textColor,
+ borderRadius: 'var(--ft-border-radius)',
}}
title={f.name}
>
@@ -220,10 +223,10 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
<div
className="flex items-center gap-2 m-2 p-2 text-xs"
style={{
- backgroundColor: `${FINCEPT_COLORS.RED}15`,
- border: `1px solid ${FINCEPT_COLORS.RED}50`,
- borderRadius: '2px',
- color: FINCEPT_COLORS.RED,
+ backgroundColor: `${colors.alert}15`,
+ border: `1px solid ${colors.alert}50`,
+ borderRadius: 'var(--ft-border-radius)',
+ color: colors.alert,
}}
>
<AlertCircle size={12} />
@@ -238,7 +241,7 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
<RefreshCw size={16} className="animate-spin" style={{ color: accentColor }} />
</div>
) : termStructure.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
Click a futures symbol to view term structure
</div>
) : (
@@ -248,34 +251,34 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
<div
className="flex items-center justify-between mb-2 p-2 text-xs"
style={{
- backgroundColor: FINCEPT_COLORS.BLACK,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<div className="flex items-center gap-2">
{contango.isContango ? (
- <TrendingUp size={12} style={{ color: FINCEPT_COLORS.YELLOW }} />
+ <TrendingUp size={12} style={{ color: colors.warning }} />
) : (
- <TrendingDown size={12} style={{ color: FINCEPT_COLORS.CYAN }} />
+ <TrendingDown size={12} style={{ color: colors.info }} />
)}
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Market Structure:</span>
+ <span style={{ color: colors.textMuted }}>Market Structure:</span>
<span
style={{
- color: contango.isContango ? FINCEPT_COLORS.YELLOW : FINCEPT_COLORS.CYAN,
+ color: contango.isContango ? colors.warning : colors.info,
fontWeight: 'bold',
}}
>
{contango.isContango ? 'CONTANGO' : 'BACKWARDATION'}
</span>
</div>
- <span style={{ color: contango.isContango ? FINCEPT_COLORS.YELLOW : FINCEPT_COLORS.CYAN }}>
+ <span style={{ color: contango.isContango ? colors.warning : colors.info }}>
{contango.spread > 0 ? '+' : ''}{contango.spread.toFixed(2)}%
</span>
</div>
)}
{/* Header Row */}
- <div className="grid grid-cols-4 gap-2 mb-1 text-[9px]" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="grid grid-cols-4 gap-2 mb-1 text-[9px]" style={{ color: colors.textMuted }}>
<div>CONTRACT</div>
<div className="text-right">PRICE</div>
<div className="text-right">VOLUME</div>
@@ -293,7 +296,7 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
className="grid grid-cols-4 gap-2 py-1 text-[10px]"
style={{
backgroundColor: idx === 0 ? `${accentColor}15` : 'transparent',
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<div className="flex items-center gap-1">
@@ -302,21 +305,21 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
{point.smart_symbol}
</span>
{idx === 0 && (
- <span className="text-[8px] px-1" style={{ backgroundColor: accentColor, color: FINCEPT_COLORS.BLACK, borderRadius: '2px' }}>
+ <span className="text-[8px] px-1" style={{ backgroundColor: accentColor, color: colors.background, borderRadius: 'var(--ft-border-radius)' }}>
FRONT
</span>
)}
</div>
- <div className="text-right font-mono" style={{ color: FINCEPT_COLORS.WHITE }}>
+ <div className="text-right font-mono" style={{ color: textColor }}>
{formatPrice(point.close)}
</div>
- <div className="text-right" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-right" style={{ color: colors.textMuted }}>
{formatVolume(point.volume)}
</div>
<div
className="text-right font-mono"
style={{
- color: idx === 0 ? FINCEPT_COLORS.MUTED : spread > 0 ? FINCEPT_COLORS.GREEN : spread < 0 ? FINCEPT_COLORS.RED : FINCEPT_COLORS.MUTED,
+ color: idx === 0 ? colors.textMuted : spread > 0 ? colors.success : spread < 0 ? colors.alert : colors.textMuted,
}}
>
{idx === 0 ? '--' : `${spread > 0 ? '+' : ''}${spread.toFixed(3)}%`}
@@ -329,11 +332,11 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
</div>
{/* All Contracts Section */}
- <div style={{ borderTop: `1px solid ${FINCEPT_COLORS.BORDER}` }}>
+ <div style={{ borderTop: `1px solid ${colors.textMuted}` }}>
<button
onClick={() => setShowAllContracts(!showAllContracts)}
className="flex items-center justify-between w-full p-2 text-[10px]"
- style={{ color: FINCEPT_COLORS.MUTED }}
+ style={{ color: colors.textMuted }}
>
<div className="flex items-center gap-1">
<Info size={10} />
@@ -349,7 +352,7 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
</button>
{showAllContracts && (
- <div className="p-2 max-h-48 overflow-y-auto" style={{ backgroundColor: FINCEPT_COLORS.BLACK }}>
+ <div className="p-2 max-h-48 overflow-y-auto" style={{ backgroundColor: colors.background }}>
<div className="grid grid-cols-3 gap-1">
{contracts.map((c) => (
<button
@@ -362,14 +365,14 @@ export const FuturesPanel: React.FC<FuturesPanelProps> = ({
className="text-left p-1 text-[9px]"
style={{
backgroundColor: selectedFuture === c.symbol ? `${accentColor}30` : 'transparent',
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
title={`${c.name} (${c.exchange})`}
>
<div className="font-bold" style={{ color: selectedFuture === c.symbol ? accentColor : textColor }}>
{c.symbol}
</div>
- <div style={{ color: FINCEPT_COLORS.MUTED, fontSize: '8px' }}>
+ <div style={{ color: colors.textMuted, fontSize: '8px' }}>
{c.name.length > 15 ? c.name.substring(0, 15) + '...' : c.name}
</div>
</button>
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/LiveStreamPanel.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/LiveStreamPanel.tsx
index a81cc78c4..894ace06e 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/LiveStreamPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/LiveStreamPanel.tsx
@@ -17,7 +17,8 @@ import {
Clock,
Trash2,
} from 'lucide-react';
-import { FINCEPT_COLORS } from '../constants';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface LiveStreamRecord {
type: 'data' | 'status' | 'error' | 'info';
@@ -88,6 +89,8 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
onStopAllStreams,
activeStreams,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors } = useTerminalTheme();
const [selectedDataset, setSelectedDataset] = useState('XNAS.ITCH');
const [selectedSchema, setSelectedSchema] = useState('trades');
const [selectedSymbol, setSelectedSymbol] = useState(symbols[0] || 'SPY');
@@ -193,13 +196,13 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
<div
className="p-4 text-center"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
- <Radio size={24} style={{ color: FINCEPT_COLORS.MUTED, margin: '0 auto 8px' }} />
- <div className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <Radio size={24} style={{ color: colors.textMuted, margin: '0 auto 8px' }} />
+ <div className="text-xs" style={{ color: colors.textMuted }}>
Configure Databento API key for live streaming
</div>
</div>
@@ -209,9 +212,9 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
return (
<div
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
overflow: 'hidden',
}}
>
@@ -219,38 +222,38 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
<div
className="flex items-center justify-between p-2"
style={{
- backgroundColor: FINCEPT_COLORS.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
}}
>
<div className="flex items-center gap-2">
{isConnected ? (
- <Wifi size={14} style={{ color: FINCEPT_COLORS.GREEN }} />
+ <Wifi size={14} style={{ color: colors.success }} />
) : (
- <WifiOff size={14} style={{ color: FINCEPT_COLORS.MUTED }} />
+ <WifiOff size={14} style={{ color: colors.textMuted }} />
)}
<span className="text-xs font-bold" style={{ color: accentColor }}>
LIVE STREAM
</span>
{isConnected && (
- <span className="text-[9px] px-1" style={{ color: FINCEPT_COLORS.GREEN, backgroundColor: `${FINCEPT_COLORS.GREEN}20`, borderRadius: '2px' }}>
+ <span className="text-[9px] px-1" style={{ color: colors.success, backgroundColor: `${colors.success}20`, borderRadius: 'var(--ft-border-radius)' }}>
CONNECTED
</span>
)}
</div>
<div className="flex items-center gap-2">
- <Activity size={12} style={{ color: isConnected ? FINCEPT_COLORS.GREEN : FINCEPT_COLORS.MUTED }} />
- <span className="text-[10px]" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <Activity size={12} style={{ color: isConnected ? colors.success : colors.textMuted }} />
+ <span className="text-[10px]" style={{ color: colors.textMuted }}>
{recordCount} msgs
</span>
</div>
</div>
{/* Controls */}
- <div className="p-2 space-y-2" style={{ borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}` }}>
+ <div className="p-2 space-y-2" style={{ borderBottom: `1px solid ${colors.textMuted}` }}>
{/* Dataset Selection */}
<div className="flex items-center gap-1 flex-wrap">
- <span className="text-[9px]" style={{ color: FINCEPT_COLORS.MUTED, width: '45px' }}>Dataset:</span>
+ <span className="text-[9px]" style={{ color: colors.textMuted, width: '45px' }}>Dataset:</span>
{LIVE_DATASETS.slice(0, 4).map((ds) => (
<button
key={ds.id}
@@ -258,9 +261,9 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
disabled={isConnected}
className="px-2 py-0.5 text-[9px]"
style={{
- backgroundColor: selectedDataset === ds.id ? accentColor : FINCEPT_COLORS.BORDER,
- color: selectedDataset === ds.id ? FINCEPT_COLORS.BLACK : textColor,
- borderRadius: '2px',
+ backgroundColor: selectedDataset === ds.id ? accentColor : colors.textMuted,
+ color: selectedDataset === ds.id ? colors.background : textColor,
+ borderRadius: 'var(--ft-border-radius)',
opacity: isConnected ? 0.5 : 1,
}}
title={ds.description}
@@ -272,7 +275,7 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
{/* Schema Selection */}
<div className="flex items-center gap-1 flex-wrap">
- <span className="text-[9px]" style={{ color: FINCEPT_COLORS.MUTED, width: '45px' }}>Schema:</span>
+ <span className="text-[9px]" style={{ color: colors.textMuted, width: '45px' }}>Schema:</span>
{LIVE_SCHEMAS.map((schema) => (
<button
key={schema.id}
@@ -280,10 +283,10 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
disabled={isConnected}
className="px-2 py-0.5 text-[9px]"
style={{
- backgroundColor: selectedSchema === schema.id ? FINCEPT_COLORS.BORDER : 'transparent',
- color: selectedSchema === schema.id ? textColor : FINCEPT_COLORS.MUTED,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: selectedSchema === schema.id ? colors.textMuted : 'transparent',
+ color: selectedSchema === schema.id ? textColor : colors.textMuted,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
opacity: isConnected ? 0.5 : 1,
}}
title={schema.description}
@@ -295,7 +298,7 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
{/* Symbol Input */}
<div className="flex items-center gap-2">
- <span className="text-[9px]" style={{ color: FINCEPT_COLORS.MUTED, width: '45px' }}>Symbol:</span>
+ <span className="text-[9px]" style={{ color: colors.textMuted, width: '45px' }}>Symbol:</span>
<div className="flex items-center gap-1">
{symbols.slice(0, 3).map((sym) => (
<button
@@ -307,9 +310,9 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
disabled={isConnected}
className="px-2 py-0.5 text-[9px] font-bold"
style={{
- backgroundColor: selectedSymbol === sym && !customSymbol ? accentColor : FINCEPT_COLORS.BORDER,
- color: selectedSymbol === sym && !customSymbol ? FINCEPT_COLORS.BLACK : textColor,
- borderRadius: '2px',
+ backgroundColor: selectedSymbol === sym && !customSymbol ? accentColor : colors.textMuted,
+ color: selectedSymbol === sym && !customSymbol ? colors.background : textColor,
+ borderRadius: 'var(--ft-border-radius)',
opacity: isConnected ? 0.5 : 1,
}}
>
@@ -325,9 +328,9 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
disabled={isConnected}
className="px-2 py-0.5 text-[10px] w-20"
style={{
- backgroundColor: FINCEPT_COLORS.BLACK,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
color: textColor,
opacity: isConnected ? 0.5 : 1,
}}
@@ -342,9 +345,9 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
disabled={isConnecting}
className="flex items-center gap-1 px-3 py-1 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.GREEN,
- color: FINCEPT_COLORS.BLACK,
- borderRadius: '2px',
+ backgroundColor: colors.success,
+ color: colors.background,
+ borderRadius: 'var(--ft-border-radius)',
opacity: isConnecting ? 0.5 : 1,
}}
>
@@ -356,9 +359,9 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
onClick={stopStream}
className="flex items-center gap-1 px-3 py-1 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.RED,
- color: FINCEPT_COLORS.WHITE,
- borderRadius: '2px',
+ backgroundColor: colors.alert,
+ color: textColor,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<Square size={12} />
@@ -370,9 +373,9 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
onClick={clearRecords}
className="flex items-center gap-1 px-2 py-1 text-xs"
style={{
- backgroundColor: FINCEPT_COLORS.BORDER,
+ backgroundColor: colors.textMuted,
color: textColor,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<Trash2 size={10} />
@@ -384,9 +387,9 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
onClick={onStopAllStreams}
className="px-2 py-1 text-[9px]"
style={{
- backgroundColor: `${FINCEPT_COLORS.RED}30`,
- color: FINCEPT_COLORS.RED,
- borderRadius: '2px',
+ backgroundColor: `${colors.alert}30`,
+ color: colors.alert,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
Stop All ({activeStreams.length})
@@ -400,10 +403,10 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
<div
className="flex items-center gap-2 m-2 p-2 text-xs"
style={{
- backgroundColor: `${FINCEPT_COLORS.RED}15`,
- border: `1px solid ${FINCEPT_COLORS.RED}50`,
- borderRadius: '2px',
- color: FINCEPT_COLORS.RED,
+ backgroundColor: `${colors.alert}15`,
+ border: `1px solid ${colors.alert}50`,
+ borderRadius: 'var(--ft-border-radius)',
+ color: colors.alert,
}}
>
<AlertCircle size={12} />
@@ -421,13 +424,13 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
}}
>
{records.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
{isConnected ? 'Waiting for data...' : 'Click Start Stream to begin receiving live data'}
</div>
) : (
<div className="space-y-1">
{records.map((record, idx) => (
- <RecordRow key={idx} record={record} formatPrice={formatPrice} formatSize={formatSize} formatTime={formatTime} />
+ <RecordRow key={idx} record={record} formatPrice={formatPrice} formatSize={formatSize} formatTime={formatTime} colors={colors} textColor={textColor} />
))}
</div>
)}
@@ -438,9 +441,9 @@ export const LiveStreamPanel: React.FC<LiveStreamPanelProps> = ({
<div
className="flex items-center justify-between p-2 text-[9px]"
style={{
- backgroundColor: FINCEPT_COLORS.BLACK,
- borderTop: `1px solid ${FINCEPT_COLORS.BORDER}`,
- color: FINCEPT_COLORS.MUTED,
+ backgroundColor: colors.background,
+ borderTop: `1px solid ${colors.textMuted}`,
+ color: colors.textMuted,
}}
>
<div className="flex items-center gap-2">
@@ -462,7 +465,9 @@ const RecordRow: React.FC<{
formatPrice: (p: number | undefined) => string;
formatSize: (s: number | undefined) => string;
formatTime: (t: string | number) => string;
-}> = ({ record, formatPrice, formatSize, formatTime }) => {
+ colors: ReturnType<typeof useTerminalTheme>['colors'];
+ textColor: string;
+}> = ({ record, formatPrice, formatSize, formatTime, colors, textColor }) => {
if (record.type !== 'data' || !record.record) return null;
const { record: data } = record;
@@ -475,26 +480,26 @@ const RecordRow: React.FC<{
<div
className="flex items-center justify-between py-0.5 px-1 text-[10px]"
style={{
- backgroundColor: isBuy ? `${FINCEPT_COLORS.GREEN}10` : isSell ? `${FINCEPT_COLORS.RED}10` : 'transparent',
- borderRadius: '2px',
+ backgroundColor: isBuy ? `${colors.success}10` : isSell ? `${colors.alert}10` : 'transparent',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<div className="flex items-center gap-2">
{isBuy ? (
- <TrendingUp size={10} style={{ color: FINCEPT_COLORS.GREEN }} />
+ <TrendingUp size={10} style={{ color: colors.success }} />
) : isSell ? (
- <TrendingDown size={10} style={{ color: FINCEPT_COLORS.RED }} />
+ <TrendingDown size={10} style={{ color: colors.alert }} />
) : (
- <Activity size={10} style={{ color: FINCEPT_COLORS.MUTED }} />
+ <Activity size={10} style={{ color: colors.textMuted }} />
)}
- <span className="font-bold" style={{ color: FINCEPT_COLORS.CYAN }}>{data.symbol}</span>
+ <span className="font-bold" style={{ color: colors.info }}>{data.symbol}</span>
</div>
<div className="flex items-center gap-3">
- <span style={{ color: isBuy ? FINCEPT_COLORS.GREEN : isSell ? FINCEPT_COLORS.RED : FINCEPT_COLORS.WHITE }}>
+ <span style={{ color: isBuy ? colors.success : isSell ? colors.alert : textColor }}>
{formatPrice(data.price)}
</span>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>{formatSize(data.size)}</span>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>{formatTime(data.ts_event)}</span>
+ <span style={{ color: colors.textMuted }}>{formatSize(data.size)}</span>
+ <span style={{ color: colors.textMuted }}>{formatTime(data.ts_event)}</span>
</div>
</div>
);
@@ -508,14 +513,14 @@ const RecordRow: React.FC<{
return (
<div
className="flex items-center justify-between py-0.5 px-1 text-[10px]"
- style={{ backgroundColor: `${FINCEPT_COLORS.BORDER}50`, borderRadius: '2px' }}
+ style={{ backgroundColor: `${colors.textMuted}50`, borderRadius: 'var(--ft-border-radius)' }}
>
- <span className="font-bold" style={{ color: FINCEPT_COLORS.CYAN }}>{data.symbol}</span>
+ <span className="font-bold" style={{ color: colors.info }}>{data.symbol}</span>
<div className="flex items-center gap-2">
- <span style={{ color: FINCEPT_COLORS.GREEN }}>{formatPrice(level.bid_px)}</span>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>×</span>
- <span style={{ color: FINCEPT_COLORS.RED }}>{formatPrice(level.ask_px)}</span>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>{formatTime(data.ts_event)}</span>
+ <span style={{ color: colors.success }}>{formatPrice(level.bid_px)}</span>
+ <span style={{ color: colors.textMuted }}>×</span>
+ <span style={{ color: colors.alert }}>{formatPrice(level.ask_px)}</span>
+ <span style={{ color: colors.textMuted }}>{formatTime(data.ts_event)}</span>
</div>
</div>
);
@@ -527,15 +532,15 @@ const RecordRow: React.FC<{
return (
<div
className="flex items-center justify-between py-0.5 px-1 text-[10px]"
- style={{ backgroundColor: `${FINCEPT_COLORS.BORDER}30`, borderRadius: '2px' }}
+ style={{ backgroundColor: `${colors.textMuted}30`, borderRadius: 'var(--ft-border-radius)' }}
>
- <span className="font-bold" style={{ color: FINCEPT_COLORS.CYAN }}>{data.symbol}</span>
+ <span className="font-bold" style={{ color: colors.info }}>{data.symbol}</span>
<div className="flex items-center gap-2 font-mono">
- <span style={{ color: FINCEPT_COLORS.MUTED }}>O:{formatPrice(ohlcv.open)}</span>
- <span style={{ color: FINCEPT_COLORS.GREEN }}>H:{formatPrice(ohlcv.high)}</span>
- <span style={{ color: FINCEPT_COLORS.RED }}>L:{formatPrice(ohlcv.low)}</span>
- <span style={{ color: FINCEPT_COLORS.WHITE }}>C:{formatPrice(ohlcv.close)}</span>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>V:{formatSize(ohlcv.volume)}</span>
+ <span style={{ color: colors.textMuted }}>O:{formatPrice(ohlcv.open)}</span>
+ <span style={{ color: colors.success }}>H:{formatPrice(ohlcv.high)}</span>
+ <span style={{ color: colors.alert }}>L:{formatPrice(ohlcv.low)}</span>
+ <span style={{ color: textColor }}>C:{formatPrice(ohlcv.close)}</span>
+ <span style={{ color: colors.textMuted }}>V:{formatSize(ohlcv.volume)}</span>
</div>
</div>
);
@@ -543,7 +548,7 @@ const RecordRow: React.FC<{
// Generic record
return (
- <div className="py-0.5 px-1 text-[10px]" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="py-0.5 px-1 text-[10px]" style={{ color: colors.textMuted }}>
{data.symbol}: {data.record_type}
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/MetricsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/MetricsPanel.tsx
index 7b4bad7b8..9a7490df0 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/MetricsPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/MetricsPanel.tsx
@@ -1,12 +1,12 @@
/**
* Surface Analytics - Metrics Panel Component
* Left sidebar with key metrics and data info
- * Follows UI Design System (UI_DESIGN_SYSTEM.md)
*/
import React from 'react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import type { ChartMetric, ChartType } from '../types';
-import { FINCEPT_COLORS, TYPOGRAPHY } from '../constants';
interface MetricsPanelProps {
chartType: ChartType;
@@ -29,42 +29,45 @@ export const MetricsPanel: React.FC<MetricsPanelProps> = ({
textColor,
accentColor,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+
const chartTitles: Record<ChartType, string> = {
- volatility: 'IV SURFACE METRICS',
- correlation: 'CORRELATION METRICS',
- 'yield-curve': 'YIELD CURVE METRICS',
- pca: 'PCA FACTOR METRICS',
+ volatility: t('metricsPanel.ivSurfaceMetrics'),
+ correlation: t('metricsPanel.correlationMetrics'),
+ 'yield-curve': t('metricsPanel.yieldCurveMetrics'),
+ pca: t('metricsPanel.pcaFactorMetrics'),
};
return (
<div
style={{
width: '280px',
- borderRight: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ borderRight: `1px solid ${colors.textMuted}`,
display: 'flex',
flexDirection: 'column',
flexShrink: 0,
- backgroundColor: FINCEPT_COLORS.PANEL_BG,
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ backgroundColor: colors.panel,
+ fontFamily,
}}
>
{/* Header */}
<div style={{
padding: '12px',
- backgroundColor: FINCEPT_COLORS.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
}}>
<span style={{
- fontSize: TYPOGRAPHY.LABEL_SIZE,
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT_COLORS.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px',
}}>
{chartTitles[chartType]}
</span>
{symbol && (
<div style={{
- fontSize: TYPOGRAPHY.HEADER_SIZE,
+ fontSize: fontSize.body,
fontWeight: 700,
color: accentColor,
marginTop: '4px',
@@ -81,13 +84,13 @@ export const MetricsPanel: React.FC<MetricsPanelProps> = ({
key={idx}
style={{
padding: '10px 12px',
- borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ borderBottom: `1px solid ${colors.textMuted}`,
}}
>
<div style={{
- fontSize: TYPOGRAPHY.LABEL_SIZE,
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT_COLORS.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px',
}}>
{metric.label}
@@ -99,31 +102,31 @@ export const MetricsPanel: React.FC<MetricsPanelProps> = ({
marginTop: '4px',
}}>
<span style={{
- fontSize: '14px',
+ fontSize: fontSize.subheading,
fontWeight: 700,
- color: FINCEPT_COLORS.CYAN,
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ color: colors.info,
+ fontFamily,
}}>
{metric.value}
</span>
<span
style={{
- fontSize: '8px',
+ fontSize: fontSize.tiny,
fontWeight: 700,
padding: '2px 6px',
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
backgroundColor:
metric.positive === null
- ? `${FINCEPT_COLORS.MUTED}20`
+ ? `${colors.textMuted}20`
: metric.positive
- ? `${FINCEPT_COLORS.GREEN}20`
- : `${FINCEPT_COLORS.RED}20`,
+ ? `${colors.success}20`
+ : `${colors.alert}20`,
color:
metric.positive === null
- ? FINCEPT_COLORS.MUTED
+ ? colors.textMuted
: metric.positive
- ? FINCEPT_COLORS.GREEN
- : FINCEPT_COLORS.RED,
+ ? colors.success
+ : colors.alert,
}}
>
{metric.change}
@@ -135,26 +138,26 @@ export const MetricsPanel: React.FC<MetricsPanelProps> = ({
{/* Data Info Section */}
<div style={{ padding: '12px', marginTop: '8px' }}>
<div style={{
- fontSize: TYPOGRAPHY.LABEL_SIZE,
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT_COLORS.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px',
marginBottom: '8px',
}}>
- DATA INFO
+ {t('metricsPanel.dataInfo')}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: TYPOGRAPHY.DATA_SIZE }}>
- <span style={{ color: FINCEPT_COLORS.GRAY }}>SOURCE:</span>
- <span style={{ color: FINCEPT_COLORS.CYAN }}>{dataSource}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: fontSize.small }}>
+ <span style={{ color: colors.textMuted }}>{t('metricsPanel.source')}:</span>
+ <span style={{ color: colors.info }}>{dataSource}</span>
</div>
- <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: TYPOGRAPHY.DATA_SIZE }}>
- <span style={{ color: FINCEPT_COLORS.GRAY }}>FREQUENCY:</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: fontSize.small }}>
+ <span style={{ color: colors.textMuted }}>{t('metricsPanel.frequency')}:</span>
<span style={{ color: textColor }}>{frequency}</span>
</div>
- <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: TYPOGRAPHY.DATA_SIZE }}>
- <span style={{ color: FINCEPT_COLORS.GRAY }}>QUALITY:</span>
- <span style={{ color: quality === 'ERROR' ? FINCEPT_COLORS.RED : FINCEPT_COLORS.GREEN }}>{quality}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: fontSize.small }}>
+ <span style={{ color: colors.textMuted }}>{t('metricsPanel.quality')}:</span>
+ <span style={{ color: quality === 'ERROR' ? colors.alert : colors.success }}>{quality}</span>
</div>
</div>
</div>
@@ -163,26 +166,26 @@ export const MetricsPanel: React.FC<MetricsPanelProps> = ({
{chartType === 'correlation' && (
<div style={{ padding: '12px', marginTop: '8px' }}>
<div style={{
- fontSize: TYPOGRAPHY.LABEL_SIZE,
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT_COLORS.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px',
marginBottom: '8px',
}}>
- CORRELATION SCALE
+ {t('metricsPanel.correlationScale')}
</div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', fontSize: TYPOGRAPHY.DATA_SIZE }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', fontSize: fontSize.small }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <div style={{ width: '12px', height: '12px', backgroundColor: '#2e7d32', borderRadius: '2px' }} />
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Strong Positive (0.7-1.0)</span>
+ <div style={{ width: '12px', height: '12px', backgroundColor: colors.success, borderRadius: 'var(--ft-border-radius)' }} />
+ <span style={{ color: colors.textMuted }}>{t('metricsPanel.strongPositive')}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <div style={{ width: '12px', height: '12px', backgroundColor: '#ffeb3b', borderRadius: '2px' }} />
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Neutral (0.3-0.7)</span>
+ <div style={{ width: '12px', height: '12px', backgroundColor: colors.warning, borderRadius: 'var(--ft-border-radius)' }} />
+ <span style={{ color: colors.textMuted }}>{t('metricsPanel.neutral')}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <div style={{ width: '12px', height: '12px', backgroundColor: '#b71c1c', borderRadius: '2px' }} />
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Strong Negative (-1.0-0.3)</span>
+ <div style={{ width: '12px', height: '12px', backgroundColor: colors.alert, borderRadius: 'var(--ft-border-radius)' }} />
+ <span style={{ color: colors.textMuted }}>{t('metricsPanel.strongNegative')}</span>
</div>
</div>
</div>
@@ -192,19 +195,19 @@ export const MetricsPanel: React.FC<MetricsPanelProps> = ({
{chartType === 'volatility' && (
<div style={{ padding: '12px', marginTop: '8px' }}>
<div style={{
- fontSize: TYPOGRAPHY.LABEL_SIZE,
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT_COLORS.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px',
marginBottom: '8px',
}}>
- IV INTERPRETATION
+ {t('metricsPanel.ivInterpretation')}
</div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: TYPOGRAPHY.DATA_SIZE, color: FINCEPT_COLORS.MUTED }}>
- <div>• High IV = Expensive Options</div>
- <div>• Low IV = Cheap Options</div>
- <div>• Skew = Put/Call IV Diff</div>
- <div>• Term Structure = Time Effect</div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: fontSize.small, color: colors.textMuted }}>
+ <div>{t('metricsPanel.highIv')}</div>
+ <div>{t('metricsPanel.lowIv')}</div>
+ <div>{t('metricsPanel.skew')}</div>
+ <div>{t('metricsPanel.termStructure')}</div>
</div>
</div>
)}
@@ -213,19 +216,19 @@ export const MetricsPanel: React.FC<MetricsPanelProps> = ({
{chartType === 'pca' && (
<div style={{ padding: '12px', marginTop: '8px' }}>
<div style={{
- fontSize: TYPOGRAPHY.LABEL_SIZE,
+ fontSize: fontSize.tiny,
fontWeight: 700,
- color: FINCEPT_COLORS.GRAY,
+ color: colors.textMuted,
letterSpacing: '0.5px',
marginBottom: '8px',
}}>
- PCA INTERPRETATION
+ {t('metricsPanel.pcaInterpretation')}
</div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: TYPOGRAPHY.DATA_SIZE, color: FINCEPT_COLORS.MUTED }}>
- <div>• PC1 = Market Factor</div>
- <div>• PC2 = Size/Value Factor</div>
- <div>• PC3 = Sector Rotation</div>
- <div>• Higher Var = More Explanatory</div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: fontSize.small, color: colors.textMuted }}>
+ <div>{t('metricsPanel.pc1')}</div>
+ <div>{t('metricsPanel.pc2')}</div>
+ <div>{t('metricsPanel.pc3')}</div>
+ <div>{t('metricsPanel.higherVar')}</div>
</div>
</div>
)}
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/OrderBookPanel.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/OrderBookPanel.tsx
index 7955e28e0..e1e5bdc60 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/OrderBookPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/OrderBookPanel.tsx
@@ -12,7 +12,8 @@ import {
TrendingDown,
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
-import { FINCEPT_COLORS } from '../constants';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface OrderBookLevel {
bid_px: number;
@@ -44,6 +45,8 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
accentColor,
textColor,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors } = useTerminalTheme();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [selectedSchema, setSelectedSchema] = useState<SchemaType>('mbp-10');
@@ -115,13 +118,13 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
<div
className="p-4 text-center"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
- <BookOpen size={24} style={{ color: FINCEPT_COLORS.MUTED, margin: '0 auto 8px' }} />
- <div className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <BookOpen size={24} style={{ color: colors.textMuted, margin: '0 auto 8px' }} />
+ <div className="text-xs" style={{ color: colors.textMuted }}>
Configure Databento API key to view order book
</div>
</div>
@@ -135,9 +138,9 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
return (
<div
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
overflow: 'hidden',
}}
>
@@ -145,8 +148,8 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
<div
className="flex items-center justify-between p-2"
style={{
- backgroundColor: FINCEPT_COLORS.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
}}
>
<div className="flex items-center gap-2">
@@ -158,14 +161,14 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
<button
onClick={fetchOrderBook}
disabled={loading}
- style={{ color: loading ? FINCEPT_COLORS.MUTED : accentColor }}
+ style={{ color: loading ? colors.textMuted : accentColor }}
>
<RefreshCw size={12} className={loading ? 'animate-spin' : ''} />
</button>
</div>
{/* Controls */}
- <div className="flex items-center justify-between p-2" style={{ borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}` }}>
+ <div className="flex items-center justify-between p-2" style={{ borderBottom: `1px solid ${colors.textMuted}` }}>
{/* Symbol selector */}
<div className="flex items-center gap-1">
{symbols.slice(0, 4).map(sym => (
@@ -174,9 +177,9 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
onClick={() => setSelectedSymbol(sym)}
className="px-2 py-0.5 text-[9px] font-bold"
style={{
- backgroundColor: selectedSymbol === sym ? accentColor : FINCEPT_COLORS.BORDER,
- color: selectedSymbol === sym ? FINCEPT_COLORS.BLACK : textColor,
- borderRadius: '2px',
+ backgroundColor: selectedSymbol === sym ? accentColor : colors.textMuted,
+ color: selectedSymbol === sym ? colors.background : textColor,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{sym}
@@ -192,10 +195,10 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
onClick={() => setSelectedSchema(schema)}
className="px-2 py-0.5 text-[9px]"
style={{
- backgroundColor: selectedSchema === schema ? FINCEPT_COLORS.BORDER : 'transparent',
- color: selectedSchema === schema ? textColor : FINCEPT_COLORS.MUTED,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: selectedSchema === schema ? colors.textMuted : 'transparent',
+ color: selectedSchema === schema ? textColor : colors.textMuted,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{schema === 'mbp-1' ? 'TOP' : '10-LVL'}
@@ -209,10 +212,10 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
<div
className="flex items-center gap-2 m-2 p-2 text-xs"
style={{
- backgroundColor: `${FINCEPT_COLORS.RED}15`,
- border: `1px solid ${FINCEPT_COLORS.RED}50`,
- borderRadius: '2px',
- color: FINCEPT_COLORS.RED,
+ backgroundColor: `${colors.alert}15`,
+ border: `1px solid ${colors.alert}50`,
+ borderRadius: 'var(--ft-border-radius)',
+ color: colors.alert,
}}
>
<AlertCircle size={12} />
@@ -224,10 +227,10 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
{currentSnapshot && (
<div
className="flex items-center justify-between p-2 text-xs"
- style={{ backgroundColor: FINCEPT_COLORS.BLACK, borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}` }}
+ style={{ backgroundColor: colors.background, borderBottom: `1px solid ${colors.textMuted}` }}
>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Spread:</span>
- <span style={{ color: FINCEPT_COLORS.YELLOW }}>
+ <span style={{ color: colors.textMuted }}>Spread:</span>
+ <span style={{ color: colors.warning }}>
${spread.toFixed(2)} ({spreadPct.toFixed(3)}%)
</span>
</div>
@@ -240,13 +243,13 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
<RefreshCw size={16} className="animate-spin" style={{ color: accentColor }} />
</div>
) : !currentSnapshot || currentSnapshot.levels.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
Click refresh to load order book data
</div>
) : (
<div>
{/* Header Row */}
- <div className="grid grid-cols-4 gap-1 mb-1 text-[9px]" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="grid grid-cols-4 gap-1 mb-1 text-[9px]" style={{ color: colors.textMuted }}>
<div className="text-right">BID SIZE</div>
<div className="text-right">BID</div>
<div className="text-left">ASK</div>
@@ -263,33 +266,33 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
key={idx}
className="grid grid-cols-4 gap-1 py-0.5 text-[10px] relative"
style={{
- backgroundColor: idx === 0 ? `${FINCEPT_COLORS.BORDER}50` : 'transparent',
+ backgroundColor: idx === 0 ? `${colors.textMuted}50` : 'transparent',
}}
>
{/* Bid side visualization */}
- <div className="relative text-right pr-1" style={{ color: FINCEPT_COLORS.GREEN }}>
+ <div className="relative text-right pr-1" style={{ color: colors.success }}>
<div
className="absolute right-0 top-0 bottom-0"
style={{
width: `${bidWidth}%`,
- backgroundColor: `${FINCEPT_COLORS.GREEN}20`,
+ backgroundColor: `${colors.success}20`,
}}
/>
<span className="relative z-10">{formatSize(level.bid_sz)}</span>
</div>
- <div className="text-right font-mono" style={{ color: FINCEPT_COLORS.GREEN }}>
+ <div className="text-right font-mono" style={{ color: colors.success }}>
{formatPrice(level.bid_px)}
</div>
- <div className="text-left font-mono" style={{ color: FINCEPT_COLORS.RED }}>
+ <div className="text-left font-mono" style={{ color: colors.alert }}>
{formatPrice(level.ask_px)}
</div>
{/* Ask side visualization */}
- <div className="relative text-left pl-1" style={{ color: FINCEPT_COLORS.RED }}>
+ <div className="relative text-left pl-1" style={{ color: colors.alert }}>
<div
className="absolute left-0 top-0 bottom-0"
style={{
width: `${askWidth}%`,
- backgroundColor: `${FINCEPT_COLORS.RED}20`,
+ backgroundColor: `${colors.alert}20`,
}}
/>
<span className="relative z-10">{formatSize(level.ask_sz)}</span>
@@ -301,19 +304,19 @@ export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({
{/* Summary Stats */}
<div
className="grid grid-cols-2 gap-2 mt-2 pt-2 text-[9px]"
- style={{ borderTop: `1px solid ${FINCEPT_COLORS.BORDER}` }}
+ style={{ borderTop: `1px solid ${colors.textMuted}` }}
>
<div className="flex items-center gap-1">
- <TrendingUp size={10} style={{ color: FINCEPT_COLORS.GREEN }} />
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Total Bid:</span>
- <span style={{ color: FINCEPT_COLORS.GREEN }}>
+ <TrendingUp size={10} style={{ color: colors.success }} />
+ <span style={{ color: colors.textMuted }}>Total Bid:</span>
+ <span style={{ color: colors.success }}>
{formatSize(currentSnapshot.levels.reduce((sum, l) => sum + l.bid_sz, 0))}
</span>
</div>
<div className="flex items-center gap-1">
- <TrendingDown size={10} style={{ color: FINCEPT_COLORS.RED }} />
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Total Ask:</span>
- <span style={{ color: FINCEPT_COLORS.RED }}>
+ <TrendingDown size={10} style={{ color: colors.alert }} />
+ <span style={{ color: colors.textMuted }}>Total Ask:</span>
+ <span style={{ color: colors.alert }}>
{formatSize(currentSnapshot.levels.reduce((sum, l) => sum + l.ask_sz, 0))}
</span>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/ReferenceDataPanel.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/ReferenceDataPanel.tsx
index 11871d402..2d315918b 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/ReferenceDataPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/ReferenceDataPanel.tsx
@@ -17,7 +17,8 @@ import {
Globe,
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
-import { FINCEPT_COLORS } from '../constants';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface SecurityMaster {
raw_symbol: string;
@@ -68,6 +69,8 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
accentColor,
textColor,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors } = useTerminalTheme();
const [activeTab, setActiveTab] = useState<TabType>('security');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -186,15 +189,15 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
const formatActionType = (type: string): { label: string; color: string } => {
switch (type.toLowerCase()) {
case 'dividend':
- return { label: 'DIVIDEND', color: FINCEPT_COLORS.GREEN };
+ return { label: 'DIVIDEND', color: colors.success };
case 'split':
- return { label: 'SPLIT', color: FINCEPT_COLORS.CYAN };
+ return { label: 'SPLIT', color: colors.info };
case 'spinoff':
- return { label: 'SPINOFF', color: FINCEPT_COLORS.YELLOW };
+ return { label: 'SPINOFF', color: colors.warning };
case 'merger':
- return { label: 'MERGER', color: FINCEPT_COLORS.PURPLE };
+ return { label: 'MERGER', color: colors.info };
default:
- return { label: type.toUpperCase(), color: FINCEPT_COLORS.MUTED };
+ return { label: type.toUpperCase(), color: colors.textMuted };
}
};
@@ -203,13 +206,13 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
<div
className="p-4 text-center"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
- <Building2 size={24} style={{ color: FINCEPT_COLORS.MUTED, margin: '0 auto 8px' }} />
- <div className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <Building2 size={24} style={{ color: colors.textMuted, margin: '0 auto 8px' }} />
+ <div className="text-xs" style={{ color: colors.textMuted }}>
Configure Databento API key to access reference data
</div>
</div>
@@ -219,9 +222,9 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
return (
<div
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
overflow: 'hidden',
}}
>
@@ -229,8 +232,8 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
<div
className="flex items-center justify-between p-2"
style={{
- backgroundColor: FINCEPT_COLORS.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
}}
>
<div className="flex items-center gap-1">
@@ -245,9 +248,9 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
className="flex items-center gap-1 px-2 py-1 text-[9px] font-bold"
style={{
backgroundColor: activeTab === id ? accentColor : 'transparent',
- color: activeTab === id ? FINCEPT_COLORS.BLACK : FINCEPT_COLORS.MUTED,
- border: `1px solid ${activeTab === id ? accentColor : FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ color: activeTab === id ? colors.background : colors.textMuted,
+ border: `1px solid ${activeTab === id ? accentColor : colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<Icon size={10} />
@@ -258,30 +261,30 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
<button
onClick={handleRefresh}
disabled={loading || symbols.length === 0}
- style={{ color: loading ? FINCEPT_COLORS.MUTED : accentColor }}
+ style={{ color: loading ? colors.textMuted : accentColor }}
>
<RefreshCw size={12} className={loading ? 'animate-spin' : ''} />
</button>
</div>
{/* Symbols Badge */}
- <div className="flex flex-wrap gap-1 p-2" style={{ borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}` }}>
- <span className="text-[9px]" style={{ color: FINCEPT_COLORS.MUTED }}>SYMBOLS:</span>
+ <div className="flex flex-wrap gap-1 p-2" style={{ borderBottom: `1px solid ${colors.textMuted}` }}>
+ <span className="text-[9px]" style={{ color: colors.textMuted }}>SYMBOLS:</span>
{symbols.slice(0, 5).map(sym => (
<span
key={sym}
className="px-1 py-0.5 text-[9px]"
style={{
- backgroundColor: FINCEPT_COLORS.BORDER,
+ backgroundColor: colors.textMuted,
color: textColor,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{sym}
</span>
))}
{symbols.length > 5 && (
- <span className="text-[9px]" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <span className="text-[9px]" style={{ color: colors.textMuted }}>
+{symbols.length - 5} more
</span>
)}
@@ -292,10 +295,10 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
<div
className="flex items-center gap-2 m-2 p-2 text-xs"
style={{
- backgroundColor: `${FINCEPT_COLORS.RED}15`,
- border: `1px solid ${FINCEPT_COLORS.RED}50`,
- borderRadius: '2px',
- color: FINCEPT_COLORS.RED,
+ backgroundColor: `${colors.alert}15`,
+ border: `1px solid ${colors.alert}50`,
+ borderRadius: 'var(--ft-border-radius)',
+ color: colors.alert,
}}
>
<AlertCircle size={12} />
@@ -311,7 +314,7 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
</div>
) : activeTab === 'security' ? (
securityData.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
Click refresh to load security master data
</div>
) : (
@@ -320,9 +323,9 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
key={`${sec.raw_symbol}-${idx}`}
className="mb-2"
style={{
- backgroundColor: FINCEPT_COLORS.BLACK,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<div
@@ -333,40 +336,40 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
<span className="text-xs font-bold" style={{ color: accentColor }}>
{sec.raw_symbol}
</span>
- <span className="text-[9px]" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <span className="text-[9px]" style={{ color: colors.textMuted }}>
{sec.name || sec.description}
</span>
</div>
{expandedRow === sec.raw_symbol ? (
- <ChevronUp size={12} style={{ color: FINCEPT_COLORS.MUTED }} />
+ <ChevronUp size={12} style={{ color: colors.textMuted }} />
) : (
- <ChevronDown size={12} style={{ color: FINCEPT_COLORS.MUTED }} />
+ <ChevronDown size={12} style={{ color: colors.textMuted }} />
)}
</div>
{expandedRow === sec.raw_symbol && (
- <div className="grid grid-cols-2 gap-2 p-2 text-[9px]" style={{ borderTop: `1px solid ${FINCEPT_COLORS.BORDER}` }}>
+ <div className="grid grid-cols-2 gap-2 p-2 text-[9px]" style={{ borderTop: `1px solid ${colors.textMuted}` }}>
<div>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Exchange: </span>
+ <span style={{ color: colors.textMuted }}>Exchange: </span>
<span style={{ color: textColor }}>{sec.exchange || 'N/A'}</span>
</div>
<div>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Currency: </span>
+ <span style={{ color: colors.textMuted }}>Currency: </span>
<span style={{ color: textColor }}>{sec.currency || 'USD'}</span>
</div>
<div>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Sector: </span>
+ <span style={{ color: colors.textMuted }}>Sector: </span>
<span style={{ color: textColor }}>{sec.sector || 'N/A'}</span>
</div>
<div>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Industry: </span>
+ <span style={{ color: colors.textMuted }}>Industry: </span>
<span style={{ color: textColor }}>{sec.industry || 'N/A'}</span>
</div>
<div>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Market Cap: </span>
- <span style={{ color: FINCEPT_COLORS.GREEN }}>{formatMarketCap(sec.market_cap)}</span>
+ <span style={{ color: colors.textMuted }}>Market Cap: </span>
+ <span style={{ color: colors.success }}>{formatMarketCap(sec.market_cap)}</span>
</div>
<div>
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Type: </span>
+ <span style={{ color: colors.textMuted }}>Type: </span>
<span style={{ color: textColor }}>{sec.security_type || 'Equity'}</span>
</div>
</div>
@@ -376,7 +379,7 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
)
) : activeTab === 'corporate' ? (
corporateActions.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
Click refresh to load corporate actions
</div>
) : (
@@ -387,9 +390,9 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
key={`${action.raw_symbol}-${action.ex_date}-${idx}`}
className="flex items-center justify-between p-2 mb-1"
style={{
- backgroundColor: FINCEPT_COLORS.BLACK,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<div className="flex items-center gap-2">
@@ -401,7 +404,7 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
style={{
backgroundColor: `${color}20`,
color: color,
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{label}
@@ -409,18 +412,18 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
</div>
<div className="flex items-center gap-3 text-[9px]">
{action.amount && (
- <div className="flex items-center gap-1" style={{ color: FINCEPT_COLORS.GREEN }}>
+ <div className="flex items-center gap-1" style={{ color: colors.success }}>
<DollarSign size={10} />
<span>{action.amount.toFixed(4)} {action.currency}</span>
</div>
)}
{action.ratio && (
- <div className="flex items-center gap-1" style={{ color: FINCEPT_COLORS.CYAN }}>
+ <div className="flex items-center gap-1" style={{ color: colors.info }}>
<Percent size={10} />
<span>{action.ratio}</span>
</div>
)}
- <span style={{ color: FINCEPT_COLORS.MUTED }}>{action.ex_date}</span>
+ <span style={{ color: colors.textMuted }}>{action.ex_date}</span>
</div>
</div>
);
@@ -428,21 +431,21 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
)
) : (
adjustmentFactors.length === 0 ? (
- <div className="text-xs text-center p-4" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="text-xs text-center p-4" style={{ color: colors.textMuted }}>
Click refresh to load adjustment factors
</div>
) : (
<div
className="overflow-x-auto"
style={{
- backgroundColor: FINCEPT_COLORS.BLACK,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<table className="w-full text-[9px]">
<thead>
- <tr style={{ backgroundColor: FINCEPT_COLORS.HEADER_BG }}>
+ <tr style={{ backgroundColor: colors.panel }}>
<th className="p-1 text-left" style={{ color: accentColor }}>SYMBOL</th>
<th className="p-1 text-left" style={{ color: accentColor }}>DATE</th>
<th className="p-1 text-right" style={{ color: accentColor }}>SPLIT</th>
@@ -454,17 +457,17 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
{adjustmentFactors.slice(0, 20).map((factor, idx) => (
<tr
key={`${factor.raw_symbol}-${factor.date}-${idx}`}
- style={{ borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}` }}
+ style={{ borderBottom: `1px solid ${colors.textMuted}` }}
>
<td className="p-1" style={{ color: textColor }}>{factor.raw_symbol}</td>
- <td className="p-1" style={{ color: FINCEPT_COLORS.MUTED }}>{factor.date}</td>
- <td className="p-1 text-right" style={{ color: factor.split_factor !== 1 ? FINCEPT_COLORS.CYAN : textColor }}>
+ <td className="p-1" style={{ color: colors.textMuted }}>{factor.date}</td>
+ <td className="p-1 text-right" style={{ color: factor.split_factor !== 1 ? colors.info : textColor }}>
{factor.split_factor.toFixed(6)}
</td>
- <td className="p-1 text-right" style={{ color: factor.dividend_factor !== 1 ? FINCEPT_COLORS.GREEN : textColor }}>
+ <td className="p-1 text-right" style={{ color: factor.dividend_factor !== 1 ? colors.success : textColor }}>
{factor.dividend_factor.toFixed(6)}
</td>
- <td className="p-1 text-right" style={{ color: FINCEPT_COLORS.YELLOW }}>
+ <td className="p-1 text-right" style={{ color: colors.warning }}>
{factor.cumulative_factor.toFixed(6)}
</td>
</tr>
@@ -472,7 +475,7 @@ export const ReferenceDataPanel: React.FC<ReferenceDataPanelProps> = ({
</tbody>
</table>
{adjustmentFactors.length > 20 && (
- <div className="p-1 text-[9px] text-center" style={{ color: FINCEPT_COLORS.MUTED }}>
+ <div className="p-1 text-[9px] text-center" style={{ color: colors.textMuted }}>
Showing 20 of {adjustmentFactors.length} records
</div>
)}
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/SettingsModal.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/SettingsModal.tsx
index a102bfad8..f72b0e15e 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/SettingsModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/SettingsModal.tsx
@@ -6,8 +6,10 @@
import React, { useState, useEffect, useCallback } from 'react';
import { X, Plus, Trash2, Key, Eye, EyeOff, AlertCircle, CheckCircle, Search, Loader2, Database, ChevronDown, ChevronUp, Clock } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import type { SurfaceAnalyticsConfig, OHLCVTimeframe } from '../types';
-import { VOL_SURFACE_SYMBOLS, CORRELATION_ASSETS, FINCEPT_COLORS, TYPOGRAPHY } from '../constants';
+import { VOL_SURFACE_SYMBOLS, CORRELATION_ASSETS } from '../constants';
import { sqliteService } from '@/services/core/sqliteService';
import { DatasetBrowser } from './DatasetBrowser';
import { CostEstimator } from './CostEstimator';
@@ -39,6 +41,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
accentColor,
textColor,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
const [localConfig, setLocalConfig] = useState<SurfaceAnalyticsConfig>(config);
const [newAsset, setNewAsset] = useState('');
const [apiKey, setApiKey] = useState('');
@@ -227,12 +231,12 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
const inputStyle: React.CSSProperties = {
width: '100%',
padding: '8px 10px',
- backgroundColor: FINCEPT_COLORS.BLACK,
+ backgroundColor: colors.background,
color: textColor,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
- fontSize: '11px',
- fontFamily: '"IBM Plex Mono", monospace',
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
+ fontSize: fontSize.body,
+ fontFamily,
outline: 'none',
};
@@ -245,17 +249,17 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
<div
className="w-full max-w-lg p-4 overflow-hidden"
style={{
- backgroundColor: FINCEPT_COLORS.PANEL_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
}}
onClick={e => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-center justify-between mb-4">
<h2 className="text-sm font-bold" style={{ color: accentColor }}>
- SURFACE ANALYTICS SETTINGS
+ {t('settings.title')}
</h2>
- <button onClick={onClose} style={{ color: FINCEPT_COLORS.MUTED }}>
+ <button onClick={onClose} style={{ color: colors.textMuted }}>
<X size={16} />
</button>
</div>
@@ -264,44 +268,44 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
<div
className="mb-4 p-3"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${apiKeyStatus === 'valid' ? FINCEPT_COLORS.GREEN : apiKeyStatus === 'invalid' ? FINCEPT_COLORS.RED : FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${apiKeyStatus === 'valid' ? colors.success : apiKeyStatus === 'invalid' ? colors.alert : colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<div className="flex items-center gap-2 mb-2">
<Key size={14} style={{ color: accentColor }} />
<label className="text-xs font-bold" style={{ color: accentColor, letterSpacing: '0.5px' }}>
- DATABENTO API KEY
+ {t('settings.databentoApiKey')}
</label>
{apiKeyStatus === 'valid' && (
- <span className="flex items-center gap-1 text-xs" style={{ color: FINCEPT_COLORS.GREEN }}>
- <CheckCircle size={12} /> CONFIGURED
+ <span className="flex items-center gap-1 text-xs" style={{ color: colors.success }}>
+ <CheckCircle size={12} /> {t('settings.configured')}
</span>
)}
{apiKeyStatus === 'invalid' && (
- <span className="flex items-center gap-1 text-xs" style={{ color: FINCEPT_COLORS.RED }}>
- <AlertCircle size={12} /> INVALID FORMAT
+ <span className="flex items-center gap-1 text-xs" style={{ color: colors.alert }}>
+ <AlertCircle size={12} /> {t('settings.invalidFormat')}
</span>
)}
</div>
{hasExistingKey ? (
<div className="flex items-center justify-between">
- <span className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
- API key is configured (db-*****)
+ <span className="text-xs" style={{ color: colors.textMuted }}>
+ {t('settings.apiKeyConfigured')}
</span>
<button
onClick={handleRemoveApiKey}
className="flex items-center gap-1 px-2 py-1 text-xs"
style={{
- backgroundColor: FINCEPT_COLORS.RED + '20',
- color: FINCEPT_COLORS.RED,
- border: `1px solid ${FINCEPT_COLORS.RED}`,
- borderRadius: '2px',
+ backgroundColor: colors.alert + '20',
+ color: colors.alert,
+ border: `1px solid ${colors.alert}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
- <Trash2 size={10} /> REMOVE
+ <Trash2 size={10} /> {t('settings.remove')}
</button>
</div>
) : (
@@ -315,7 +319,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
setApiKey(e.target.value);
setApiKeyStatus('none');
}}
- placeholder="Enter your Databento API key (db-*****)"
+ placeholder={t('settings.enterApiKey')}
style={{
...inputStyle,
paddingRight: '36px',
@@ -324,7 +328,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
<button
onClick={() => setShowApiKey(!showApiKey)}
className="absolute right-2 top-1/2 transform -translate-y-1/2"
- style={{ color: FINCEPT_COLORS.MUTED }}
+ style={{ color: colors.textMuted }}
>
{showApiKey ? <EyeOff size={14} /> : <Eye size={14} />}
</button>
@@ -334,27 +338,27 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
disabled={!apiKey.trim() || apiKeyStatus === 'saving'}
className="px-3 text-xs font-bold"
style={{
- backgroundColor: apiKey.trim() ? accentColor : FINCEPT_COLORS.MUTED,
- color: FINCEPT_COLORS.BLACK,
+ backgroundColor: apiKey.trim() ? accentColor : colors.textMuted,
+ color: colors.background,
border: 'none',
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
opacity: apiKey.trim() ? 1 : 0.5,
}}
>
- {apiKeyStatus === 'saving' ? 'SAVING...' : 'SAVE'}
+ {apiKeyStatus === 'saving' ? t('settings.saving') : t('settings.save')}
</button>
</div>
- <div className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
- Get your API key from{' '}
+ <div className="text-xs" style={{ color: colors.textMuted }}>
+ {t('settings.getApiKeyFrom')}{' '}
<a
href="https://databento.com"
target="_blank"
rel="noopener noreferrer"
- style={{ color: FINCEPT_COLORS.CYAN, textDecoration: 'underline' }}
+ style={{ color: colors.info, textDecoration: 'underline' }}
>
databento.com
</a>
- {' '}→ Dashboard → API Keys
+ {' '}→ {t('settings.dashboardApiKeys')}
</div>
</>
)}
@@ -362,23 +366,23 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
{/* Volatility Surface Symbol */}
<div className="mb-4">
- <label className="block text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.MUTED }}>
- VOLATILITY SURFACE SYMBOL
+ <label className="block text-xs font-bold mb-2" style={{ color: colors.textMuted }}>
+ {t('settings.volatilitySurfaceSymbol')}
</label>
{/* Current selected symbol */}
<div
className="flex items-center justify-between p-2 mb-2"
style={{
- backgroundColor: FINCEPT_COLORS.BLACK,
- border: `1px solid ${FINCEPT_COLORS.GREEN}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.success}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
- <span className="text-sm font-bold" style={{ color: FINCEPT_COLORS.GREEN }}>
+ <span className="text-sm font-bold" style={{ color: colors.success }}>
{localConfig.selectedSymbol}
</span>
- <CheckCircle size={14} style={{ color: FINCEPT_COLORS.GREEN }} />
+ <CheckCircle size={14} style={{ color: colors.success }} />
</div>
{/* Symbol search input */}
@@ -388,7 +392,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
type="text"
value={symbolSearchQuery}
onChange={e => setSymbolSearchQuery(e.target.value.toUpperCase())}
- placeholder="Search any symbol (e.g., MSFT, GOOGL, META)"
+ placeholder={t('settings.searchSymbol')}
style={inputStyle}
onKeyPress={e => e.key === 'Enter' && handleSymbolSearch()}
/>
@@ -398,10 +402,10 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
disabled={!symbolSearchQuery.trim() || symbolSearching}
className="px-3 flex items-center gap-1"
style={{
- backgroundColor: symbolSearchQuery.trim() ? accentColor : FINCEPT_COLORS.MUTED,
- color: FINCEPT_COLORS.BLACK,
+ backgroundColor: symbolSearchQuery.trim() ? accentColor : colors.textMuted,
+ color: colors.background,
border: 'none',
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
opacity: symbolSearchQuery.trim() ? 1 : 0.5,
}}
>
@@ -421,10 +425,10 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onClick={() => setLocalConfig({ ...localConfig, selectedSymbol: sym.value })}
className="px-2 py-0.5 text-xs"
style={{
- backgroundColor: localConfig.selectedSymbol === sym.value ? accentColor : FINCEPT_COLORS.BORDER,
- color: localConfig.selectedSymbol === sym.value ? FINCEPT_COLORS.BLACK : textColor,
+ backgroundColor: localConfig.selectedSymbol === sym.value ? accentColor : colors.textMuted,
+ color: localConfig.selectedSymbol === sym.value ? colors.background : textColor,
border: 'none',
- borderRadius: '2px',
+ borderRadius: 'var(--ft-border-radius)',
}}
>
{sym.value}
@@ -435,15 +439,15 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
{/* Correlation Assets */}
<div className="mb-4">
- <label className="block text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.MUTED }}>
- CORRELATION ASSETS ({localConfig.correlationAssets.length})
+ <label className="block text-xs font-bold mb-2" style={{ color: colors.textMuted }}>
+ {t('settings.correlationAssets')} ({localConfig.correlationAssets.length})
</label>
<div className="flex gap-2 mb-2">
<input
type="text"
value={newAsset}
onChange={e => setNewAsset(e.target.value)}
- placeholder="Add symbol (e.g., AAPL)"
+ placeholder={t('settings.addSymbol')}
style={inputStyle}
onKeyPress={e => e.key === 'Enter' && handleAddAsset()}
/>
@@ -452,7 +456,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
className="px-3"
style={{
backgroundColor: accentColor,
- color: FINCEPT_COLORS.BLACK,
+ color: colors.background,
border: 'none',
}}
>
@@ -465,14 +469,14 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
key={asset}
className="flex items-center gap-1 px-2 py-0.5 text-xs"
style={{
- backgroundColor: FINCEPT_COLORS.BORDER,
+ backgroundColor: colors.textMuted,
color: textColor,
}}
>
{asset}
<button
onClick={() => handleRemoveAsset(asset)}
- style={{ color: FINCEPT_COLORS.RED }}
+ style={{ color: colors.alert }}
>
<Trash2 size={10} />
</button>
@@ -481,7 +485,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
</div>
<button
className="mt-2 text-xs underline"
- style={{ color: FINCEPT_COLORS.MUTED }}
+ style={{ color: colors.textMuted }}
onClick={() =>
setLocalConfig({
...localConfig,
@@ -489,19 +493,19 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
})
}
>
- Reset to defaults
+ {t('settings.resetToDefaults')}
</button>
</div>
{/* Date Range */}
<div className="mb-4">
- <label className="block text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.MUTED }}>
- HISTORICAL DATE RANGE
+ <label className="block text-xs font-bold mb-2" style={{ color: colors.textMuted }}>
+ {t('settings.historicalDateRange')}
</label>
<div className="flex gap-2">
<div className="flex-1">
- <label className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
- Start
+ <label className="text-xs" style={{ color: colors.textMuted }}>
+ {t('settings.start')}
</label>
<input
type="date"
@@ -516,8 +520,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
/>
</div>
<div className="flex-1">
- <label className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
- End
+ <label className="text-xs" style={{ color: colors.textMuted }}>
+ {t('settings.end')}
</label>
<input
type="date"
@@ -536,8 +540,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
{/* Auto Refresh */}
<div className="mb-4">
- <label className="block text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.MUTED }}>
- AUTO REFRESH INTERVAL
+ <label className="block text-xs font-bold mb-2" style={{ color: colors.textMuted }}>
+ {t('settings.autoRefreshInterval')}
</label>
<select
value={localConfig.refreshInterval}
@@ -549,11 +553,11 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
}
style={inputStyle}
>
- <option value={0}>Manual Only</option>
- <option value={60000}>Every 1 minute</option>
- <option value={300000}>Every 5 minutes</option>
- <option value={900000}>Every 15 minutes</option>
- <option value={3600000}>Every 1 hour</option>
+ <option value={0}>{t('settings.manualOnly')}</option>
+ <option value={60000}>{t('settings.every1min')}</option>
+ <option value={300000}>{t('settings.every5min')}</option>
+ <option value={900000}>{t('settings.every15min')}</option>
+ <option value={3600000}>{t('settings.every1hour')}</option>
</select>
</div>
@@ -563,18 +567,18 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onClick={() => setShowTimeframeSelector(!showTimeframeSelector)}
className="flex items-center justify-between w-full p-2 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
color: accentColor,
}}
>
<div className="flex items-center gap-2">
<Clock size={14} />
- DATA TIMEFRAME
+ {t('timeframe.dataTimeframe')}
<span className="px-1 py-0.5 text-[9px]" style={{
- backgroundColor: FINCEPT_COLORS.BORDER,
- borderRadius: '2px',
+ backgroundColor: colors.textMuted,
+ borderRadius: 'var(--ft-border-radius)',
color: textColor,
}}>
{localConfig.timeframe?.toUpperCase().replace('OHLCV-', '') || '1D'}
@@ -600,18 +604,18 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onClick={() => setShowDatasetBrowser(!showDatasetBrowser)}
className="flex items-center justify-between w-full p-2 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
color: accentColor,
}}
>
<div className="flex items-center gap-2">
<Database size={14} />
- BROWSE DATASETS
+ {t('settings.browseDatasets')}
<span className="px-1 py-0.5 text-[9px]" style={{
- backgroundColor: FINCEPT_COLORS.BORDER,
- borderRadius: '2px',
+ backgroundColor: colors.textMuted,
+ borderRadius: 'var(--ft-border-radius)',
color: textColor,
}}>
{localConfig.dataset || 'DBEQ.BASIC'}
@@ -638,15 +642,15 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onClick={() => setShowCostEstimator(!showCostEstimator)}
className="flex items-center justify-between w-full p-2 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
color: accentColor,
}}
>
<div className="flex items-center gap-2">
- <span>💰</span>
- COST ESTIMATOR
+ <span>$</span>
+ {t('settings.costEstimator')}
</div>
{showCostEstimator ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
</button>
@@ -672,15 +676,15 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onClick={() => setShowReferenceData(!showReferenceData)}
className="flex items-center justify-between w-full p-2 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
color: accentColor,
}}
>
<div className="flex items-center gap-2">
- <span>📋</span>
- REFERENCE DATA
+ <span>#</span>
+ {t('settings.referenceData')}
</div>
{showReferenceData ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
</button>
@@ -702,15 +706,15 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onClick={() => setShowOrderBook(!showOrderBook)}
className="flex items-center justify-between w-full p-2 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
color: accentColor,
}}
>
<div className="flex items-center gap-2">
- <span>📊</span>
- ORDER BOOK
+ <span>=</span>
+ {t('settings.orderBook')}
</div>
{showOrderBook ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
</button>
@@ -732,25 +736,25 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onClick={() => setShowLiveStream(!showLiveStream)}
className="flex items-center justify-between w-full p-2 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${activeStreams.length > 0 ? FINCEPT_COLORS.GREEN : FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
- color: activeStreams.length > 0 ? FINCEPT_COLORS.GREEN : accentColor,
+ backgroundColor: colors.background,
+ border: `1px solid ${activeStreams.length > 0 ? colors.success : colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
+ color: activeStreams.length > 0 ? colors.success : accentColor,
}}
>
<div className="flex items-center gap-2">
- <span>📡</span>
- LIVE STREAMING
+ <span>~</span>
+ {t('settings.liveStreaming')}
{activeStreams.length > 0 && (
<span
className="px-1 text-[9px]"
style={{
- backgroundColor: FINCEPT_COLORS.GREEN,
- color: FINCEPT_COLORS.BLACK,
- borderRadius: '2px',
+ backgroundColor: colors.success,
+ color: colors.background,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
- {activeStreams.length} ACTIVE
+ {activeStreams.length} {t('settings.active')}
</span>
)}
</div>
@@ -778,15 +782,15 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onClick={() => setShowFutures(!showFutures)}
className="flex items-center justify-between w-full p-2 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
color: accentColor,
}}
>
<div className="flex items-center gap-2">
- <span>📈</span>
- FUTURES (CME GLOBEX)
+ <span>^</span>
+ {t('settings.futuresCme')}
</div>
{showFutures ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
</button>
@@ -807,15 +811,15 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onClick={() => setShowBatchDownload(!showBatchDownload)}
className="flex items-center justify-between w-full p-2 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
color: accentColor,
}}
>
<div className="flex items-center gap-2">
- <span>📦</span>
- BATCH DOWNLOADS
+ <span>*</span>
+ {t('settings.batchDownloads')}
</div>
{showBatchDownload ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
</button>
@@ -836,17 +840,17 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onClick={() => setShowAdditionalSchemas(!showAdditionalSchemas)}
className="flex items-center justify-between w-full p-2 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
color: accentColor,
}}
>
<div className="flex items-center gap-2">
- <span>📊</span>
- ADDITIONAL SCHEMAS
- <span className="px-1 py-0.5 text-[8px]" style={{ backgroundColor: FINCEPT_COLORS.BORDER, borderRadius: '2px', color: FINCEPT_COLORS.MUTED }}>
- TRADES, IMBALANCE, STATUS
+ <span>+</span>
+ {t('settings.additionalSchemas')}
+ <span className="px-1 py-0.5 text-[8px]" style={{ backgroundColor: colors.textMuted, borderRadius: 'var(--ft-border-radius)', color: colors.textMuted }}>
+ {t('settings.tradesImbalanceStatus')}
</span>
</div>
{showAdditionalSchemas ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
@@ -869,23 +873,23 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onClick={onClose}
className="px-4 py-1 text-xs font-bold"
style={{
- backgroundColor: FINCEPT_COLORS.BORDER,
+ backgroundColor: colors.textMuted,
color: textColor,
- border: `1px solid ${FINCEPT_COLORS.MUTED}`,
+ border: `1px solid ${colors.textMuted}`,
}}
>
- CANCEL
+ {t('settings.cancel')}
</button>
<button
onClick={handleSave}
className="px-4 py-1 text-xs font-bold"
style={{
backgroundColor: accentColor,
- color: FINCEPT_COLORS.BLACK,
+ color: colors.background,
border: `1px solid ${accentColor}`,
}}
>
- SAVE CHANGES
+ {t('settings.saveChanges')}
</button>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/SurfaceChart.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/SurfaceChart.tsx
index 8a343b70d..f24dc7bf1 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/SurfaceChart.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/SurfaceChart.tsx
@@ -1,13 +1,13 @@
/**
* Surface Analytics - 3D Surface Chart Component
* Renders Plotly 3D surface visualizations
- * Follows UI Design System (UI_DESIGN_SYSTEM.md)
*/
import React, { Suspense, lazy, useMemo } from 'react';
import { RefreshCw, AlertCircle, TrendingUp } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import type { ChartType, VolatilitySurfaceData, CorrelationMatrixData, YieldCurveData, PCAData } from '../types';
-import { FINCEPT_COLORS, TYPOGRAPHY } from '../constants';
// Lazy load Plotly
const Plot = lazy(() => import('react-plotly.js'));
@@ -59,6 +59,9 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
fontFamily,
isDemoMode = false,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors, fontSize } = useTerminalTheme();
+
const plotConfig = useMemo(() => ({
displayModeBar: true,
displaylogo: false,
@@ -71,42 +74,42 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
len: 0.85,
thickness: 18,
x: 1.02,
- bgcolor: FINCEPT_COLORS.BLACK,
+ bgcolor: colors.background,
bordercolor: accentColor,
borderwidth: 1,
- }), [textColor, accentColor]);
+ }), [textColor, accentColor, colors.background]);
const sceneConfig = useMemo(() => ({
- bgcolor: FINCEPT_COLORS.BLACK,
+ bgcolor: colors.background,
xaxis: {
- gridcolor: FINCEPT_COLORS.BORDER,
+ gridcolor: colors.textMuted,
color: textColor,
titlefont: { size: 12, color: accentColor },
tickfont: { size: 10 },
showbackground: true,
- backgroundcolor: FINCEPT_COLORS.PANEL_BG,
+ backgroundcolor: colors.panel,
},
yaxis: {
- gridcolor: FINCEPT_COLORS.BORDER,
+ gridcolor: colors.textMuted,
color: textColor,
titlefont: { size: 12, color: accentColor },
tickfont: { size: 10 },
showbackground: true,
- backgroundcolor: FINCEPT_COLORS.PANEL_BG,
+ backgroundcolor: colors.panel,
},
zaxis: {
- gridcolor: FINCEPT_COLORS.BORDER,
+ gridcolor: colors.textMuted,
color: textColor,
titlefont: { size: 12, color: accentColor },
tickfont: { size: 10 },
showbackground: true,
- backgroundcolor: FINCEPT_COLORS.PANEL_BG,
+ backgroundcolor: colors.panel,
},
camera: {
eye: { x: 1.6, y: 1.6, z: 1.4 },
center: { x: 0, y: 0, z: 0 },
},
- }), [textColor, accentColor]);
+ }), [textColor, accentColor, colors.background, colors.panel, colors.textMuted]);
const baseLayout = useMemo(() => ({
autosize: true,
@@ -115,11 +118,11 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
plot_bgcolor: 'transparent',
margin: { l: 10, r: 10, t: 10, b: 10 },
hoverlabel: {
- bgcolor: FINCEPT_COLORS.BORDER,
+ bgcolor: colors.textMuted,
bordercolor: accentColor,
font: { family: fontFamily, color: textColor, size: 11 },
},
- }), [textColor, accentColor, fontFamily]);
+ }), [textColor, accentColor, fontFamily, colors.textMuted]);
const renderVolatilitySurface = () => {
if (!volatilityData) return null;
@@ -136,15 +139,15 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
title: { text: 'IV %', font: { size: 11, color: accentColor } },
...colorbarConfig,
},
- hovertemplate: '<b>STRIKE:</b> %{x:.1f}<br><b>DTE:</b> %{y:.0f}<br><b>IV:</b> %{z:.2f}%<extra></extra>'
+ hovertemplate: `<b>${t('chart.strike')}:</b> %{x:.1f}<br><b>${t('chart.dte')}:</b> %{y:.0f}<br><b>${t('chart.iv')}:</b> %{z:.2f}%<extra></extra>`
} as any]}
layout={{
...baseLayout,
scene: {
...sceneConfig,
- xaxis: { ...sceneConfig.xaxis, title: 'STRIKE PRICE' },
- yaxis: { ...sceneConfig.yaxis, title: 'DAYS TO EXPIRY' },
- zaxis: { ...sceneConfig.zaxis, title: 'IMPLIED VOL (%)' },
+ xaxis: { ...sceneConfig.xaxis, title: t('chart.strikePrice') },
+ yaxis: { ...sceneConfig.yaxis, title: t('chart.daysToExpiry') },
+ zaxis: { ...sceneConfig.zaxis, title: t('chart.impliedVol') },
}
} as any}
config={plotConfig}
@@ -167,15 +170,15 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
title: { text: 'ρ', font: { size: 12, color: accentColor } },
...colorbarConfig,
},
- hovertemplate: '<b>CORRELATION:</b> %{z:.3f}<extra></extra>'
+ hovertemplate: `<b>${t('chart.correlation')}:</b> %{z:.3f}<extra></extra>`
} as any]}
layout={{
...baseLayout,
scene: {
...sceneConfig,
- xaxis: { ...sceneConfig.xaxis, title: 'ASSET PAIR INDEX' },
- yaxis: { ...sceneConfig.yaxis, title: 'TIME (DAYS)' },
- zaxis: { ...sceneConfig.zaxis, title: 'CORRELATION COEFF' },
+ xaxis: { ...sceneConfig.xaxis, title: t('chart.assetPairIndex') },
+ yaxis: { ...sceneConfig.yaxis, title: t('chart.timeDays') },
+ zaxis: { ...sceneConfig.zaxis, title: t('chart.correlationCoeff') },
}
} as any}
config={plotConfig}
@@ -200,15 +203,15 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
title: { text: 'YIELD %', font: { size: 11, color: accentColor } },
...colorbarConfig,
},
- hovertemplate: '<b>MATURITY:</b> %{x}M<br><b>YIELD:</b> %{z:.2f}%<extra></extra>'
+ hovertemplate: `<b>${t('chart.maturity')}:</b> %{x}M<br><b>${t('chart.yield')}:</b> %{z:.2f}%<extra></extra>`
} as any]}
layout={{
...baseLayout,
scene: {
...sceneConfig,
- xaxis: { ...sceneConfig.xaxis, title: 'MATURITY (MONTHS)' },
- yaxis: { ...sceneConfig.yaxis, title: 'HISTORICAL DAYS' },
- zaxis: { ...sceneConfig.zaxis, title: 'YIELD (%)' },
+ xaxis: { ...sceneConfig.xaxis, title: t('chart.maturityMonths') },
+ yaxis: { ...sceneConfig.yaxis, title: t('chart.historicalDays') },
+ zaxis: { ...sceneConfig.zaxis, title: t('chart.yieldPercent') },
}
} as any}
config={plotConfig}
@@ -228,18 +231,18 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
z: pcaData.z,
colorscale: COLOR_SCALES.pca,
colorbar: {
- title: { text: 'LOADING', font: { size: 11, color: accentColor } },
+ title: { text: t('chart.loading'), font: { size: 11, color: accentColor } },
...colorbarConfig,
},
- hovertemplate: '<b>LOADING:</b> %{z:.3f}<extra></extra>'
+ hovertemplate: `<b>${t('chart.loading')}:</b> %{z:.3f}<extra></extra>`
} as any]}
layout={{
...baseLayout,
scene: {
...sceneConfig,
- xaxis: { ...sceneConfig.xaxis, title: 'PRINCIPAL COMPONENT' },
- yaxis: { ...sceneConfig.yaxis, title: 'ASSET INDEX' },
- zaxis: { ...sceneConfig.zaxis, title: 'FACTOR LOADING' },
+ xaxis: { ...sceneConfig.xaxis, title: t('chart.principalComponent') },
+ yaxis: { ...sceneConfig.yaxis, title: t('chart.assetIndex') },
+ zaxis: { ...sceneConfig.zaxis, title: t('chart.factorLoading') },
}
} as any}
config={plotConfig}
@@ -253,16 +256,16 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
switch (chartType) {
case 'volatility':
return volatilityData
- ? `${volatilityData.underlying} OPTIONS - IMPLIED VOLATILITY SURFACE`
- : 'IMPLIED VOLATILITY SURFACE';
+ ? `${volatilityData.underlying} ${t('chartTitles.optionsIvSurface')}`
+ : t('chartTitles.ivSurface');
case 'correlation':
return correlationData
- ? `MULTI-ASSET CORRELATION MATRIX - ${correlationData.window} DAY ROLLING`
- : 'MULTI-ASSET CORRELATION MATRIX';
+ ? `${t('chartTitles.correlationMatrix')} - ${correlationData.window} ${t('chartTitles.dayRolling')}`
+ : t('chartTitles.correlationMatrix');
case 'yield-curve':
- return 'U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION';
+ return t('chartTitles.yieldCurve');
case 'pca':
- return 'PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS';
+ return t('chartTitles.pcaFactors');
default:
return '';
}
@@ -270,7 +273,7 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
const getDataSource = (): string => {
if (isDemoMode) {
- return 'DEMO DATA (SYNTHETIC)';
+ return t('demoDataSynthetic');
}
switch (chartType) {
case 'volatility':
@@ -299,12 +302,12 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
<RefreshCw size={32} className="animate-spin" style={{ color: accentColor }} />
<span style={{
marginTop: '16px',
- fontSize: TYPOGRAPHY.BODY_SIZE,
- color: FINCEPT_COLORS.MUTED,
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontSize: fontSize.body,
+ color: colors.textMuted,
+ fontFamily,
letterSpacing: '0.5px',
}}>
- LOADING DATA...
+ {t('loadingData')}
</span>
</div>
);
@@ -346,18 +349,18 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
const isAccessError = error.toLowerCase().includes('403') || error.toLowerCase().includes('access');
const isNotFoundError = error.toLowerCase().includes('404') || error.toLowerCase().includes('not found');
- let errorTitle = 'FAILED TO LOAD DATA';
+ let errorTitle = t('errors.failedToLoad');
let errorHelp = '';
if (isAuthError) {
- errorTitle = 'AUTHENTICATION FAILED';
- errorHelp = 'Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys';
+ errorTitle = t('errors.authFailed');
+ errorHelp = t('errors.authFailedHelp');
} else if (isAccessError) {
- errorTitle = 'ACCESS DENIED';
- errorHelp = 'Your API key may not have access to this dataset. OPRA options data requires specific permissions.';
+ errorTitle = t('errors.accessDenied');
+ errorHelp = t('errors.accessDeniedHelp');
} else if (isNotFoundError) {
- errorTitle = 'SYMBOL NOT FOUND';
- errorHelp = 'The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ.';
+ errorTitle = t('errors.symbolNotFound');
+ errorHelp = t('errors.symbolNotFoundHelp');
}
return (
@@ -375,24 +378,24 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- backgroundColor: `${FINCEPT_COLORS.RED}20`,
+ backgroundColor: `${colors.alert}20`,
borderRadius: '50%',
marginBottom: '16px',
}}>
- <AlertCircle size={24} style={{ color: FINCEPT_COLORS.RED }} />
+ <AlertCircle size={24} style={{ color: colors.alert }} />
</div>
<div style={{
- fontSize: TYPOGRAPHY.HEADER_SIZE,
+ fontSize: fontSize.body,
fontWeight: 700,
- color: FINCEPT_COLORS.RED,
+ color: colors.alert,
marginBottom: '8px',
}}>
{errorTitle}
</div>
{errorHelp && (
<span style={{
- fontSize: TYPOGRAPHY.BODY_SIZE,
- color: FINCEPT_COLORS.YELLOW,
+ fontSize: fontSize.body,
+ color: colors.warning,
textAlign: 'center',
maxWidth: '500px',
lineHeight: '1.5',
@@ -402,15 +405,15 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
</span>
)}
<span style={{
- fontSize: '9px',
- color: FINCEPT_COLORS.MUTED,
+ fontSize: fontSize.tiny,
+ color: colors.textMuted,
textAlign: 'center',
maxWidth: '500px',
lineHeight: '1.5',
padding: '8px',
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
fontFamily: 'monospace',
}}>
{error}
@@ -427,13 +430,13 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
alignItems: 'center',
justifyContent: 'center',
height: '100%',
- color: FINCEPT_COLORS.MUTED,
- fontSize: TYPOGRAPHY.BODY_SIZE,
+ color: colors.textMuted,
+ fontSize: fontSize.body,
textAlign: 'center',
}}>
<TrendingUp size={48} style={{ marginBottom: '16px', opacity: 0.3 }} />
- <div style={{ fontWeight: 700, marginBottom: '8px' }}>NO DATA LOADED</div>
- <span>Click REFRESH to fetch data</span>
+ <div style={{ fontWeight: 700, marginBottom: '8px' }}>{t('noDataLoaded')}</div>
+ <span>{t('clickRefresh')}</span>
</div>
);
};
@@ -453,24 +456,24 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
alignItems: 'center',
justifyContent: 'space-between',
padding: '8px 12px',
- backgroundColor: FINCEPT_COLORS.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT_COLORS.BORDER}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
flexShrink: 0,
}}
>
<div style={{
- fontSize: TYPOGRAPHY.LABEL_SIZE,
+ fontSize: fontSize.tiny,
fontWeight: 700,
color: accentColor,
letterSpacing: '0.5px',
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontFamily,
}}>
{getChartTitle()}
</div>
<div style={{
- fontSize: TYPOGRAPHY.LABEL_SIZE,
- color: FINCEPT_COLORS.CYAN,
- fontFamily: TYPOGRAPHY.FONT_FAMILY,
+ fontSize: fontSize.tiny,
+ color: colors.info,
+ fontFamily,
}}>
{getDataSource()}
</div>
@@ -480,7 +483,7 @@ export const SurfaceChart: React.FC<SurfaceChartProps> = ({
<div style={{
flex: 1,
overflow: 'hidden',
- backgroundColor: FINCEPT_COLORS.BLACK,
+ backgroundColor: colors.background,
}}>
{renderContent()}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/TimeframeSelector.tsx b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/TimeframeSelector.tsx
index ea538a7ad..078882952 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/TimeframeSelector.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/components/TimeframeSelector.tsx
@@ -5,7 +5,8 @@
import React from 'react';
import { Clock, AlertTriangle, TrendingUp } from 'lucide-react';
-import { FINCEPT_COLORS } from '../constants';
+import { useTranslation } from 'react-i18next';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import type { OHLCVTimeframe, TimeframeInfo } from '../types';
interface TimeframeSelectorProps {
@@ -55,22 +56,6 @@ const TIMEFRAMES: TimeframeInfo[] = [
},
];
-const getCostLevelColor = (level: 'low' | 'medium' | 'high') => {
- switch (level) {
- case 'low': return FINCEPT_COLORS.GREEN;
- case 'medium': return FINCEPT_COLORS.YELLOW;
- case 'high': return FINCEPT_COLORS.RED;
- }
-};
-
-const getCostLevelLabel = (level: 'low' | 'medium' | 'high') => {
- switch (level) {
- case 'low': return '$';
- case 'medium': return '$$';
- case 'high': return '$$$';
- }
-};
-
export const TimeframeSelector: React.FC<TimeframeSelectorProps> = ({
value,
onChange,
@@ -78,14 +63,33 @@ export const TimeframeSelector: React.FC<TimeframeSelectorProps> = ({
textColor,
disabled = false,
}) => {
+ const { t } = useTranslation('surfaceAnalytics');
+ const { colors } = useTerminalTheme();
+
+ const getCostLevelColor = (level: 'low' | 'medium' | 'high') => {
+ switch (level) {
+ case 'low': return colors.success;
+ case 'medium': return colors.warning;
+ case 'high': return colors.alert;
+ }
+ };
+
+ const getCostLevelLabel = (level: 'low' | 'medium' | 'high') => {
+ switch (level) {
+ case 'low': return '$';
+ case 'medium': return '$$';
+ case 'high': return '$$$';
+ }
+ };
+
const selectedTimeframe = TIMEFRAMES.find(tf => tf.value === value) || TIMEFRAMES[0];
return (
<div
style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
padding: '12px',
opacity: disabled ? 0.6 : 1,
}}
@@ -94,7 +98,7 @@ export const TimeframeSelector: React.FC<TimeframeSelectorProps> = ({
<div className="flex items-center gap-2 mb-3">
<Clock size={14} style={{ color: accentColor }} />
<span className="text-xs font-bold" style={{ color: accentColor, letterSpacing: '0.5px' }}>
- DATA TIMEFRAME
+ {t('timeframe.dataTimeframe')}
</span>
</div>
@@ -109,21 +113,21 @@ export const TimeframeSelector: React.FC<TimeframeSelectorProps> = ({
disabled={disabled}
className="flex flex-col items-center p-2 transition-all"
style={{
- backgroundColor: isSelected ? accentColor : FINCEPT_COLORS.BLACK,
- border: `1px solid ${isSelected ? accentColor : FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: isSelected ? accentColor : colors.background,
+ border: `1px solid ${isSelected ? accentColor : colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
cursor: disabled ? 'not-allowed' : 'pointer',
}}
>
<span
className="text-xs font-bold"
- style={{ color: isSelected ? FINCEPT_COLORS.BLACK : textColor }}
+ style={{ color: isSelected ? colors.background : textColor }}
>
{tf.label}
</span>
<span
className="text-[9px] mt-0.5"
- style={{ color: isSelected ? FINCEPT_COLORS.BLACK : getCostLevelColor(tf.costLevel) }}
+ style={{ color: isSelected ? colors.background : getCostLevelColor(tf.costLevel) }}
>
{getCostLevelLabel(tf.costLevel)}
</span>
@@ -136,21 +140,21 @@ export const TimeframeSelector: React.FC<TimeframeSelectorProps> = ({
<div
className="p-2 text-xs"
style={{
- backgroundColor: FINCEPT_COLORS.BLACK,
- border: `1px solid ${FINCEPT_COLORS.BORDER}`,
- borderRadius: '2px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: 'var(--ft-border-radius)',
}}
>
<div className="flex items-center justify-between mb-1">
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Schema:</span>
+ <span style={{ color: colors.textMuted }}>{t('timeframe.schema')}:</span>
<span className="font-mono" style={{ color: textColor }}>{selectedTimeframe.value}</span>
</div>
<div className="flex items-center justify-between mb-1">
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Description:</span>
+ <span style={{ color: colors.textMuted }}>{t('timeframe.description')}:</span>
<span style={{ color: textColor }}>{selectedTimeframe.description}</span>
</div>
<div className="flex items-center justify-between">
- <span style={{ color: FINCEPT_COLORS.MUTED }}>Records/Day:</span>
+ <span style={{ color: colors.textMuted }}>{t('timeframe.recordsPerDay')}:</span>
<span style={{ color: textColor }}>{selectedTimeframe.recordsPerDay}</span>
</div>
</div>
@@ -160,22 +164,22 @@ export const TimeframeSelector: React.FC<TimeframeSelectorProps> = ({
<div
className="flex items-center gap-2 mt-2 p-2 text-xs"
style={{
- backgroundColor: `${FINCEPT_COLORS.YELLOW}15`,
- border: `1px solid ${FINCEPT_COLORS.YELLOW}50`,
- borderRadius: '2px',
- color: FINCEPT_COLORS.YELLOW,
+ backgroundColor: `${colors.warning}15`,
+ border: `1px solid ${colors.warning}50`,
+ borderRadius: 'var(--ft-border-radius)',
+ color: colors.warning,
}}
>
<AlertTriangle size={12} />
- <span>High-frequency data generates many records and may incur higher costs</span>
+ <span>{t('timeframe.highFrequencyWarning')}</span>
</div>
)}
{/* Data Volume Indicator */}
<div className="mt-3">
<div className="flex items-center justify-between mb-1">
- <span className="text-xs" style={{ color: FINCEPT_COLORS.MUTED }}>
- Data Volume
+ <span className="text-xs" style={{ color: colors.textMuted }}>
+ {t('timeframe.dataVolume')}
</span>
<div className="flex items-center gap-1">
<TrendingUp size={10} style={{ color: getCostLevelColor(selectedTimeframe.costLevel) }} />
@@ -186,7 +190,7 @@ export const TimeframeSelector: React.FC<TimeframeSelectorProps> = ({
</div>
<div
className="h-1 rounded"
- style={{ backgroundColor: FINCEPT_COLORS.BORDER }}
+ style={{ backgroundColor: colors.textMuted }}
>
<div
className="h-full rounded transition-all"
diff --git a/fincept-terminal-desktop/src/components/tabs/surface-analytics/constants.ts b/fincept-terminal-desktop/src/components/tabs/surface-analytics/constants.ts
index 36cdc015e..477c4268f 100644
--- a/fincept-terminal-desktop/src/components/tabs/surface-analytics/constants.ts
+++ b/fincept-terminal-desktop/src/components/tabs/surface-analytics/constants.ts
@@ -98,32 +98,5 @@ export const PLOTLY_CONFIG = {
responsive: true,
} as const;
-// Terminal styling - UI Design System compliant
-export const FINCEPT_COLORS = {
- ORANGE: '#FF8800', // Primary accent, CTAs, selected states
- WHITE: '#FFFFFF', // Primary text
- BLACK: '#000000', // Main background
- RED: '#FF3B3B', // Negative, errors, sell
- GREEN: '#00D66F', // Positive, success, buy
- GRAY: '#787878', // Secondary text, labels
- DARK_BG: '#000000', // Main background
- PANEL_BG: '#0F0F0F', // Card/panel background
- HEADER_BG: '#1A1A1A', // Header/toolbar background
- BORDER: '#2A2A2A', // Borders, dividers
- HOVER: '#1F1F1F', // Hover state background
- MUTED: '#4A4A4A', // Disabled, inactive
- CYAN: '#00E5FF', // Info, data values
- YELLOW: '#FFD700', // Alerts, prices
- BLUE: '#0088FF', // Secondary accent
- PURPLE: '#9D4EDD', // Tertiary accent
- ACCENT: '#FF8800',
-} as const;
-
-// Typography
-export const TYPOGRAPHY = {
- FONT_FAMILY: '"IBM Plex Mono", "Consolas", monospace',
- LABEL_SIZE: '9px',
- BODY_SIZE: '10px',
- HEADER_SIZE: '11px',
- DATA_SIZE: '10px',
-} as const;
+// Note: Colors and typography are now sourced from ThemeContext (useTerminalTheme hook)
+// Old FINCEPT_COLORS and TYPOGRAPHY constants have been removed in favor of the theme system
diff --git a/fincept-terminal-desktop/src/components/tabs/trade-visualization/TradeVisualizationTab.tsx b/fincept-terminal-desktop/src/components/tabs/trade-visualization/TradeVisualizationTab.tsx
index 217eccb26..b8afa3752 100644
--- a/fincept-terminal-desktop/src/components/tabs/trade-visualization/TradeVisualizationTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trade-visualization/TradeVisualizationTab.tsx
@@ -76,10 +76,20 @@ export default function TradeVisualizationTab() {
return () => clearInterval(timer);
}, []);
- // Load initial data
+ // Check API health and load initial data
useEffect(() => {
- loadCountries();
- loadProducts();
+ const initializeTab = async () => {
+ // First check API health
+ const healthStatus = await tradeService.isApiHealthy();
+ if (!healthStatus.healthy) {
+ setError(`Trade API is currently unavailable: ${healthStatus.error || 'Service temporarily down'}. Please try again later.`);
+ return;
+ }
+ // If healthy, load data
+ loadCountries();
+ loadProducts();
+ };
+ initializeTab();
}, []);
// Load chord data when parameters change
@@ -499,16 +509,46 @@ export default function TradeVisualizationTab() {
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
{error && (
<div style={{
- padding: '12px 16px',
- backgroundColor: `${FINCEPT.RED}20`,
+ padding: '16px 20px',
+ backgroundColor: `${FINCEPT.RED}15`,
border: `1px solid ${FINCEPT.RED}`,
+ borderLeft: `4px solid ${FINCEPT.RED}`,
margin: '16px',
- display: 'flex',
- alignItems: 'center',
- gap: '12px'
+ borderRadius: '4px'
}}>
- <AlertCircle size={16} color={FINCEPT.RED} />
- <span style={{ fontSize: '11px', color: FINCEPT.RED }}>{error}</span>
+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px' }}>
+ <AlertCircle size={20} color={FINCEPT.RED} style={{ flexShrink: 0, marginTop: '2px' }} />
+ <div>
+ <div style={{ fontSize: '13px', fontWeight: 600, color: FINCEPT.RED, marginBottom: '6px' }}>
+ Trade Data Unavailable
+ </div>
+ <div style={{ fontSize: '11px', color: FINCEPT.GRAY, lineHeight: '1.5' }}>
+ {error}
+ </div>
+ <button
+ onClick={() => {
+ setError(null);
+ loadChordData();
+ }}
+ style={{
+ marginTop: '12px',
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ color: FINCEPT.CYAN,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '10px',
+ fontWeight: 600,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px'
+ }}
+ >
+ <RefreshCw size={10} />
+ RETRY
+ </button>
+ </div>
+ </div>
</div>
)}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/PositionsTable.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/PositionsTable.tsx
index f43a049da..9484d972a 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/PositionsTable.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/PositionsTable.tsx
@@ -80,6 +80,12 @@ export function PositionsTable() {
);
}
+ // Calculate totals
+ const totalPnl = positions.reduce((sum, pos) => sum + (pos.unrealizedPnl || 0), 0);
+ const totalNotional = positions.reduce((sum, pos) => sum + (pos.notionalValue || pos.entryPrice * pos.quantity || 0), 0);
+ const totalPnlPercent = totalNotional > 0 ? (totalPnl / totalNotional) * 100 : 0;
+ const totalPnlFormatted = formatPnL(totalPnl);
+
return (
<div style={{ width: '100%', overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>
@@ -205,6 +211,39 @@ export function PositionsTable() {
);
})}
</tbody>
+ {/* Total Row */}
+ {positions.length > 0 && (
+ <tfoot>
+ <tr style={{
+ borderTop: `2px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.HEADER_BG,
+ }}>
+ <td style={{ padding: '10px', color: FINCEPT.ORANGE, fontWeight: 700, fontSize: '10px' }}>
+ TOTAL
+ </td>
+ <td style={{ padding: '10px', color: FINCEPT.GRAY, fontSize: '9px' }}>
+ {positions.length} position{positions.length !== 1 ? 's' : ''}
+ </td>
+ <td style={{ padding: '10px' }} />
+ <td style={{ padding: '10px' }} />
+ <td style={{ padding: '10px' }} />
+ <td style={{
+ padding: '10px',
+ textAlign: 'right',
+ color: totalPnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ fontWeight: 700,
+ fontSize: '11px',
+ }}>
+ {totalPnlFormatted.text}
+ <div style={{ fontSize: '8px', color: totalPnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED }}>
+ ({totalPnl >= 0 ? '+' : ''}{totalPnlPercent.toFixed(2)}%)
+ </div>
+ </td>
+ {capabilities.supportsLeverage && <td style={{ padding: '10px' }} />}
+ <td style={{ padding: '10px' }} />
+ </tr>
+ </tfoot>
+ )}
</table>
</div>
);
diff --git a/fincept-terminal-desktop/src/contexts/BrokerContext.tsx b/fincept-terminal-desktop/src/contexts/BrokerContext.tsx
index 0d210d543..02e44b980 100644
--- a/fincept-terminal-desktop/src/contexts/BrokerContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/BrokerContext.tsx
@@ -20,6 +20,7 @@ import type { IExchangeAdapter } from '../brokers/crypto/types';
import { websocketBridge, type ProviderConfig } from '../services/trading/websocketBridge';
import { saveSetting, getSetting } from '@/services/core/sqliteService';
import { initializeMarketDataService, getMarketDataService } from '../services/trading/UnifiedMarketDataService';
+import { brokerMCPBridge } from '@/services/mcp/internal';
// Constants
const CONNECTION_TIMEOUT = 10000; // 10 seconds
@@ -276,6 +277,9 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
console.error('[BrokerContext] Real adapter disconnect error:', err);
}
}
+ // Disconnect BrokerMCPBridge when cleaning up
+ brokerMCPBridge.disconnect();
+ console.log('[BrokerContext] BrokerMCPBridge disconnected');
} catch (err) {
console.error('[BrokerContext] Cleanup error:', err);
}
@@ -293,6 +297,10 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
setIsConnecting(true);
+ // Declare adapter references outside try-catch so they're accessible for bridge connection
+ let newRealAdapter: IExchangeAdapter | null = null;
+ let newPaperAdapter: PaperTradingAdapter | null = null;
+
try {
// Clean up old adapters first
await cleanupAdapters(realAdapter);
@@ -300,10 +308,10 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
if (signal.aborted) return;
// Create real adapter
- const newRealAdapter = createBrokerAdapter(activeBroker);
+ newRealAdapter = createBrokerAdapter(activeBroker);
try {
- await retryConnect(() => newRealAdapter.connect());
+ await retryConnect(() => newRealAdapter!.connect());
} catch (connectError) {
console.error(`[BrokerContext] [WARN] Failed to connect ${activeBroker} real adapter after retries:`, connectError);
}
@@ -327,7 +335,7 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
// Create paper trading adapter with market data service (NO realAdapter dependency)
// This allows paper trading to work independently of real broker connection
const marketDataService = getMarketDataService();
- const newPaperAdapter = createPaperTradingAdapter(
+ newPaperAdapter = createPaperTradingAdapter(
{
portfolioId: '',
portfolioName,
@@ -358,6 +366,7 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
setPaperPortfolio(portfolio);
} catch (error) {
console.error('[BrokerContext] Failed to create paper adapter:', error);
+ newPaperAdapter = null;
setPaperAdapter(null);
setPaperPortfolio(null);
}
@@ -368,12 +377,33 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
console.error(`[BrokerContext] [FAIL] Failed to initialize ${activeBroker}:`, error);
setRealAdapter(null);
+ newRealAdapter = null;
+ newPaperAdapter = null;
setPaperAdapter(null);
setPaperPortfolio(null);
- } finally {
- setIsConnecting(false);
+ brokerMCPBridge.disconnect();
}
- }, [activeBroker, paperPortfolioMode, activeBrokerMetadata, cleanupAdapters, realAdapter, getBrokerFees]);
+
+ // Connect BrokerMCPBridge AFTER adapters are created (outside try-catch for proper scoping)
+ if (!signal.aborted) {
+ const adapterForMode = tradingMode === 'paper' ? newPaperAdapter : newRealAdapter;
+ if (adapterForMode && adapterForMode.isConnected()) {
+ brokerMCPBridge.connect({
+ activeAdapter: adapterForMode,
+ // In paper mode, also pass the real adapter for market discovery & price fetching
+ realAdapter: tradingMode === 'paper' ? newRealAdapter : null,
+ tradingMode: tradingMode,
+ activeBroker: activeBroker,
+ });
+ console.log(`[BrokerContext] BrokerMCPBridge connected (${tradingMode} mode, adapter: ${adapterForMode.constructor.name}, realAdapter: ${newRealAdapter ? 'available' : 'none'})`);
+ } else {
+ console.warn(`[BrokerContext] Adapter for ${tradingMode} mode not available or not connected - bridge not connected`);
+ brokerMCPBridge.disconnect();
+ }
+ }
+
+ setIsConnecting(false);
+ }, [activeBroker, tradingMode, paperPortfolioMode, activeBrokerMetadata, cleanupAdapters, realAdapter, getBrokerFees]);
// Set active broker
const setActiveBroker = useCallback(async (brokerId: string) => {
@@ -399,7 +429,18 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
const setTradingMode = useCallback(async (mode: 'live' | 'paper') => {
setTradingModeState(mode);
await safeStorageSet('trading_mode', mode);
- }, []);
+
+ // Update BrokerMCPBridge with new trading mode
+ const adapter = mode === 'paper' ? paperAdapter : realAdapter;
+ if (adapter) {
+ brokerMCPBridge.connect({
+ activeAdapter: adapter,
+ tradingMode: mode,
+ activeBroker: activeBroker
+ });
+ console.log(`[BrokerContext] BrokerMCPBridge switched to ${mode} mode`);
+ }
+ }, [paperAdapter, realAdapter, activeBroker]);
// Set paper portfolio mode
const setPaperPortfolioMode = useCallback(async (mode: 'separate' | 'unified') => {
diff --git a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx
index 49010c4b0..cf12187f1 100644
--- a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx
@@ -53,6 +53,7 @@ import {
type UnifiedPosition,
type PaperOrder,
} from '@/services/unifiedTradingService';
+import * as symbolMaster from '@/services/symbolMasterService';
// ============================================================================
// CONSTANTS
@@ -619,6 +620,17 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
// Fetch initial data
await refreshAllData(adapterToUse);
+ // Auto-download master contract if needed (background task)
+ symbolMaster.ensureMasterContract(activeBroker).then((result) => {
+ if (result.success) {
+ console.log(`[StockBrokerContext] ✓ Master contract ready: ${result.total_symbols} symbols`);
+ } else {
+ console.warn(`[StockBrokerContext] Master contract download issue: ${result.message}`);
+ }
+ }).catch((err) => {
+ console.warn(`[StockBrokerContext] Master contract download failed:`, err);
+ });
+
// Connect WebSocket for real-time data streaming
try {
await adapterToUse.connectWebSocket();
@@ -719,6 +731,17 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
// Fetch initial data
await refreshAllData(adapter);
+ // Auto-download master contract if needed (background task)
+ symbolMaster.ensureMasterContract(activeBroker).then((result) => {
+ if (result.success) {
+ console.log(`[StockBrokerContext] ✓ Master contract ready: ${result.total_symbols} symbols`);
+ } else {
+ console.warn(`[StockBrokerContext] Master contract download issue: ${result.message}`);
+ }
+ }).catch((err) => {
+ console.warn(`[StockBrokerContext] Master contract download failed:`, err);
+ });
+
// Connect WebSocket for real-time data streaming
try {
await adapter.connectWebSocket();
diff --git a/fincept-terminal-desktop/src/nodes/core/Filter.node.ts b/fincept-terminal-desktop/src/nodes/core/Filter.node.ts
deleted file mode 100644
index edc5f53df..000000000
--- a/fincept-terminal-desktop/src/nodes/core/Filter.node.ts
+++ /dev/null
@@ -1,283 +0,0 @@
-/**
- * Filter Node
- * Remove items that don't match specified conditions
- *
- * Use cases:
- * - Filter stocks by price range
- * - Remove rows with missing data
- * - Select only profitable trades
- * - Filter news by sentiment
- */
-
-import {
- INodeType,
- INodeTypeDescription,
- IExecuteFunctions,
- NodeOutput,
- NodeConnectionType,
- NodePropertyType,
- IDataObject,
-} from '../../services/nodeSystem/types';
-
-export class FilterNode implements INodeType {
- description: INodeTypeDescription = {
- displayName: 'Filter',
- name: 'filter',
- icon: 'fa:filter',
- iconColor: '#60a5fa',
- group: ['transform'],
- version: 1,
- description: 'Remove items that do not match specified conditions',
- subtitle: '={{$parameter["operation"]}}',
- defaults: {
- name: 'Filter',
- color: '#60a5fa',
- },
- inputs: [NodeConnectionType.Main],
- outputs: [NodeConnectionType.Main],
- properties: [
- {
- displayName: 'Operation',
- name: 'operation',
- type: NodePropertyType.Options,
- noDataExpression: true,
- options: [
- {
- name: 'Keep Matching Items',
- value: 'keep',
- description: 'Keep only items that match the conditions',
- },
- {
- name: 'Remove Matching Items',
- value: 'remove',
- description: 'Remove items that match the conditions',
- },
- ],
- default: 'keep',
- },
- {
- displayName: 'Conditions',
- name: 'conditions',
- placeholder: 'Add Condition',
- type: NodePropertyType.Collection,
- typeOptions: {
- multipleValues: true,
- },
- default: [],
- options: [
- {
- name: 'condition',
- description: 'Condition',
- values: [
- {
- displayName: 'Field',
- name: 'field',
- type: NodePropertyType.String,
- default: '',
- placeholder: 'e.g., price',
- description: 'The field name to check',
- required: true,
- },
- {
- displayName: 'Operation',
- name: 'operator',
- type: NodePropertyType.Options,
- options: [
- {
- name: 'Equal',
- value: 'equal',
- },
- {
- name: 'Not Equal',
- value: 'notEqual',
- },
- {
- name: 'Greater Than',
- value: 'greaterThan',
- },
- {
- name: 'Greater Than or Equal',
- value: 'greaterThanOrEqual',
- },
- {
- name: 'Less Than',
- value: 'lessThan',
- },
- {
- name: 'Less Than or Equal',
- value: 'lessThanOrEqual',
- },
- {
- name: 'Contains',
- value: 'contains',
- },
- {
- name: 'Not Contains',
- value: 'notContains',
- },
- {
- name: 'Starts With',
- value: 'startsWith',
- },
- {
- name: 'Ends With',
- value: 'endsWith',
- },
- {
- name: 'Is Empty',
- value: 'isEmpty',
- },
- {
- name: 'Is Not Empty',
- value: 'isNotEmpty',
- },
- ],
- default: 'equal',
- },
- {
- displayName: 'Value',
- name: 'value',
- type: NodePropertyType.String,
- default: '',
- description: 'The value to compare against',
- displayOptions: {
- hide: {
- operator: ['isEmpty', 'isNotEmpty'],
- },
- },
- },
- ],
- },
- ],
- },
- {
- displayName: 'Combine Conditions',
- name: 'combineOperation',
- type: NodePropertyType.Options,
- options: [
- {
- name: 'AND (All conditions must match)',
- value: 'and',
- },
- {
- name: 'OR (Any condition can match)',
- value: 'or',
- },
- ],
- default: 'and',
- description: 'How to combine multiple conditions',
- },
- ],
- };
-
- async execute(this: IExecuteFunctions): Promise<NodeOutput> {
- const items = this.getInputData();
- const returnData: IDataObject[] = [];
-
- const operation = this.getNodeParameter('operation', 0) as string;
- const combineOperation = this.getNodeParameter('combineOperation', 0) as string;
-
- for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
- const item = items[itemIndex];
- const conditions = this.getNodeParameter('conditions.condition', itemIndex, []) as Array<{
- field: string;
- operator: string;
- value: string;
- }>;
-
- // Evaluate all conditions
- const conditionResults = conditions.map((condition) => {
- return evaluateCondition(item.json, condition);
- });
-
- // Combine conditions based on combineOperation
- let matches = false;
- if (combineOperation === 'and') {
- matches = conditionResults.every((result) => result === true);
- } else {
- matches = conditionResults.some((result) => result === true);
- }
-
- // Apply operation
- const shouldKeep =
- (operation === 'keep' && matches) || (operation === 'remove' && !matches);
-
- if (shouldKeep) {
- returnData.push(item.json);
- }
- }
-
- return [this.helpers.returnJsonArray(returnData)];
- }
-}
-
-/**
- * Evaluate a single condition
- */
-function evaluateCondition(
- data: IDataObject,
- condition: { field: string; operator: string; value: string }
-): boolean {
- const { field, operator, value } = condition;
-
- // Get field value (supports dot notation like "price.close")
- const fieldValue = getNestedValue(data, field);
-
- switch (operator) {
- case 'equal':
- return String(fieldValue) === String(value);
-
- case 'notEqual':
- return String(fieldValue) !== String(value);
-
- case 'greaterThan':
- return Number(fieldValue) > Number(value);
-
- case 'greaterThanOrEqual':
- return Number(fieldValue) >= Number(value);
-
- case 'lessThan':
- return Number(fieldValue) < Number(value);
-
- case 'lessThanOrEqual':
- return Number(fieldValue) <= Number(value);
-
- case 'contains':
- return String(fieldValue).toLowerCase().includes(String(value).toLowerCase());
-
- case 'notContains':
- return !String(fieldValue).toLowerCase().includes(String(value).toLowerCase());
-
- case 'startsWith':
- return String(fieldValue).toLowerCase().startsWith(String(value).toLowerCase());
-
- case 'endsWith':
- return String(fieldValue).toLowerCase().endsWith(String(value).toLowerCase());
-
- case 'isEmpty':
- return fieldValue === null || fieldValue === undefined || fieldValue === '';
-
- case 'isNotEmpty':
- return fieldValue !== null && fieldValue !== undefined && fieldValue !== '';
-
- default:
- return false;
- }
-}
-
-/**
- * Get nested value from object using dot notation
- */
-function getNestedValue(obj: IDataObject, path: string): any {
- const keys = path.split('.');
- let current: any = obj;
-
- for (const key of keys) {
- if (current === null || current === undefined) {
- return undefined;
- }
- current = current[key];
- }
-
- return current;
-}
diff --git a/fincept-terminal-desktop/src/nodes/core/Merge.node.ts b/fincept-terminal-desktop/src/nodes/core/Merge.node.ts
deleted file mode 100644
index 94d6b7245..000000000
--- a/fincept-terminal-desktop/src/nodes/core/Merge.node.ts
+++ /dev/null
@@ -1,371 +0,0 @@
-/**
- * Merge Node
- * Combine data from multiple inputs
- *
- * Use cases:
- * - Combine price data from multiple sources
- * - Merge technical indicators with price data
- * - Join fundamental data with market data
- * - Append multiple datasets
- */
-
-import {
- INodeType,
- INodeTypeDescription,
- IExecuteFunctions,
- NodeOutput,
- NodeConnectionType,
- NodePropertyType,
- IDataObject,
- INodeExecutionData,
-} from '../../services/nodeSystem/types';
-
-export class MergeNode implements INodeType {
- description: INodeTypeDescription = {
- displayName: 'Merge',
- name: 'merge',
- icon: 'fa:code-branch',
- iconColor: '#10b981',
- group: ['transform'],
- version: 1,
- description: 'Combine data from multiple inputs',
- subtitle: '={{$parameter["mode"]}}',
- defaults: {
- name: 'Merge',
- color: '#10b981',
- },
- inputs: [NodeConnectionType.Main, NodeConnectionType.Main],
- outputs: [NodeConnectionType.Main],
- properties: [
- {
- displayName: 'Mode',
- name: 'mode',
- type: NodePropertyType.Options,
- noDataExpression: true,
- options: [
- {
- name: 'Append',
- value: 'append',
- description: 'Combine all items from both inputs into one output',
- },
- {
- name: 'Merge By Position',
- value: 'mergeByPosition',
- description: 'Merge items at the same position (1st with 1st, 2nd with 2nd, etc.)',
- },
- {
- name: 'Merge By Key',
- value: 'mergeByKey',
- description: 'Join items based on matching field values (like SQL JOIN)',
- },
- {
- name: 'Choose Branch',
- value: 'chooseBranch',
- description: 'Output items from only one input',
- },
- ],
- default: 'append',
- },
-
- // Merge By Key options
- {
- displayName: 'Join',
- name: 'joinMode',
- type: NodePropertyType.Options,
- displayOptions: {
- show: {
- mode: ['mergeByKey'],
- },
- },
- options: [
- {
- name: 'Inner Join',
- value: 'inner',
- description: 'Keep only items that have matches in both inputs',
- },
- {
- name: 'Left Join',
- value: 'left',
- description: 'Keep all items from input 1, add matching data from input 2',
- },
- {
- name: 'Outer Join',
- value: 'outer',
- description: 'Keep all items from both inputs',
- },
- ],
- default: 'inner',
- },
- {
- displayName: 'Key (Input 1)',
- name: 'key1',
- type: NodePropertyType.String,
- displayOptions: {
- show: {
- mode: ['mergeByKey'],
- },
- },
- default: '',
- placeholder: 'e.g., symbol',
- required: true,
- description: 'Field name to match on in Input 1',
- },
- {
- displayName: 'Key (Input 2)',
- name: 'key2',
- type: NodePropertyType.String,
- displayOptions: {
- show: {
- mode: ['mergeByKey'],
- },
- },
- default: '',
- placeholder: 'e.g., ticker',
- required: true,
- description: 'Field name to match on in Input 2',
- },
-
- // Choose Branch options
- {
- displayName: 'Output',
- name: 'output',
- type: NodePropertyType.Options,
- displayOptions: {
- show: {
- mode: ['chooseBranch'],
- },
- },
- options: [
- {
- name: 'Input 1',
- value: 'input1',
- },
- {
- name: 'Input 2',
- value: 'input2',
- },
- ],
- default: 'input1',
- },
-
- // Merge By Position options
- {
- displayName: 'Clash Handling',
- name: 'clashHandling',
- type: NodePropertyType.Options,
- displayOptions: {
- show: {
- mode: ['mergeByPosition'],
- },
- },
- options: [
- {
- name: 'Prefer Input 1',
- value: 'preferInput1',
- description: 'If both inputs have the same field, use value from Input 1',
- },
- {
- name: 'Prefer Input 2',
- value: 'preferInput2',
- description: 'If both inputs have the same field, use value from Input 2',
- },
- {
- name: 'Add Suffix',
- value: 'addSuffix',
- description: 'If both inputs have the same field, add suffix (_1, _2)',
- },
- ],
- default: 'preferInput1',
- },
- ],
- };
-
- async execute(this: IExecuteFunctions): Promise<NodeOutput> {
- const mode = this.getNodeParameter('mode', 0) as string;
-
- // Get input data
- const input1 = this.getInputData(0) || [];
- const input2 = this.getInputData(1) || [];
-
- let returnData: INodeExecutionData[] = [];
-
- switch (mode) {
- case 'append':
- returnData = mergeAppend(input1, input2);
- break;
-
- case 'mergeByPosition':
- const clashHandling = this.getNodeParameter('clashHandling', 0) as string;
- returnData = mergeByPosition(input1, input2, clashHandling);
- break;
-
- case 'mergeByKey':
- const joinMode = this.getNodeParameter('joinMode', 0) as string;
- const key1 = this.getNodeParameter('key1', 0) as string;
- const key2 = this.getNodeParameter('key2', 0) as string;
- returnData = mergeByKey(input1, input2, key1, key2, joinMode);
- break;
-
- case 'chooseBranch':
- const output = this.getNodeParameter('output', 0) as string;
- returnData = output === 'input1' ? input1 : input2;
- break;
-
- default:
- returnData = input1;
- }
-
- return [returnData];
- }
-}
-
-/**
- * Append: Combine all items from both inputs
- */
-function mergeAppend(
- input1: INodeExecutionData[],
- input2: INodeExecutionData[]
-): INodeExecutionData[] {
- return [...input1, ...input2];
-}
-
-/**
- * Merge By Position: Merge items at the same index
- */
-function mergeByPosition(
- input1: INodeExecutionData[],
- input2: INodeExecutionData[],
- clashHandling: string
-): INodeExecutionData[] {
- const result: INodeExecutionData[] = [];
- const maxLength = Math.max(input1.length, input2.length);
-
- for (let i = 0; i < maxLength; i++) {
- const item1 = input1[i]?.json || {};
- const item2 = input2[i]?.json || {};
-
- let merged: IDataObject = {};
-
- if (clashHandling === 'preferInput1') {
- merged = { ...item2, ...item1 };
- } else if (clashHandling === 'preferInput2') {
- merged = { ...item1, ...item2 };
- } else if (clashHandling === 'addSuffix') {
- // Add suffix to conflicting fields
- const keys1 = Object.keys(item1);
- const keys2 = Object.keys(item2);
- const commonKeys = keys1.filter((key) => keys2.includes(key));
-
- merged = { ...item1, ...item2 };
-
- for (const key of commonKeys) {
- merged[`${key}_1`] = item1[key];
- merged[`${key}_2`] = item2[key];
- delete merged[key];
- }
- }
-
- result.push({ json: merged });
- }
-
- return result;
-}
-
-/**
- * Merge By Key: Join items based on matching field values
- */
-function mergeByKey(
- input1: INodeExecutionData[],
- input2: INodeExecutionData[],
- key1: string,
- key2: string,
- joinMode: string
-): INodeExecutionData[] {
- const result: INodeExecutionData[] = [];
-
- // Create lookup map for input2
- const input2Map = new Map<any, IDataObject[]>();
- for (const item of input2) {
- const keyValue = getNestedValue(item.json, key2);
- if (!input2Map.has(keyValue)) {
- input2Map.set(keyValue, []);
- }
- input2Map.get(keyValue)!.push(item.json);
- }
-
- if (joinMode === 'inner' || joinMode === 'left') {
- // Process input1 items
- for (const item1 of input1) {
- const keyValue = getNestedValue(item1.json, key1);
- const matches = input2Map.get(keyValue) || [];
-
- if (matches.length > 0) {
- // Found matches - merge with each
- for (const item2 of matches) {
- result.push({
- json: { ...item1.json, ...item2 },
- });
- }
- } else if (joinMode === 'left') {
- // Left join - keep item1 even without matches
- result.push({
- json: { ...item1.json },
- });
- }
- }
- }
-
- if (joinMode === 'outer') {
- // Outer join - include all items from both inputs
- const processedKeys = new Set<any>();
-
- // Process input1
- for (const item1 of input1) {
- const keyValue = getNestedValue(item1.json, key1);
- processedKeys.add(keyValue);
- const matches = input2Map.get(keyValue) || [];
-
- if (matches.length > 0) {
- for (const item2 of matches) {
- result.push({
- json: { ...item1.json, ...item2 },
- });
- }
- } else {
- result.push({
- json: { ...item1.json },
- });
- }
- }
-
- // Add unmatched items from input2
- for (const [keyValue, items] of input2Map) {
- if (!processedKeys.has(keyValue)) {
- for (const item of items) {
- result.push({
- json: { ...item },
- });
- }
- }
- }
- }
-
- return result;
-}
-
-/**
- * Get nested value from object using dot notation
- */
-function getNestedValue(obj: IDataObject, path: string): any {
- const keys = path.split('.');
- let current: any = obj;
-
- for (const key of keys) {
- if (current === null || current === undefined) {
- return undefined;
- }
- current = current[key];
- }
-
- return current;
-}
diff --git a/fincept-terminal-desktop/src/nodes/core/Switch.node.ts b/fincept-terminal-desktop/src/nodes/core/Switch.node.ts
deleted file mode 100644
index c9a385451..000000000
--- a/fincept-terminal-desktop/src/nodes/core/Switch.node.ts
+++ /dev/null
@@ -1,295 +0,0 @@
-/**
- * Switch Node
- * Route items to different outputs based on conditions
- *
- * Use cases:
- * - Route stocks by sector
- * - Separate buy/sell signals
- * - Split data by price range
- * - Classify trades by profitability
- */
-
-import {
- INodeType,
- INodeTypeDescription,
- IExecuteFunctions,
- NodeOutput,
- NodeConnectionType,
- NodePropertyType,
- IDataObject,
- INodeExecutionData,
-} from '../../services/nodeSystem/types';
-
-export class SwitchNode implements INodeType {
- description: INodeTypeDescription = {
- displayName: 'Switch',
- name: 'switch',
- icon: 'fa:map-signs',
- iconColor: '#f59e0b',
- group: ['transform'],
- version: 1,
- description: 'Route items to different outputs based on conditions',
- subtitle: '={{$parameter["mode"]}} Mode',
- defaults: {
- name: 'Switch',
- color: '#f59e0b',
- },
- inputs: [NodeConnectionType.Main],
- outputs: [
- NodeConnectionType.Main,
- NodeConnectionType.Main,
- NodeConnectionType.Main,
- NodeConnectionType.Main,
- ],
- outputNames: ['Output 1', 'Output 2', 'Output 3', 'Fallback'],
- properties: [
- {
- displayName: 'Mode',
- name: 'mode',
- type: NodePropertyType.Options,
- noDataExpression: true,
- options: [
- {
- name: 'Rules',
- value: 'rules',
- description: 'Route based on conditional rules',
- },
- {
- name: 'Expression',
- value: 'expression',
- description: 'Route based on expression result',
- },
- ],
- default: 'rules',
- },
-
- // Rules mode
- {
- displayName: 'Routing Rules',
- name: 'rules',
- placeholder: 'Add Routing Rule',
- type: NodePropertyType.FixedCollection,
- typeOptions: {
- multipleValues: true,
- },
- displayOptions: {
- show: {
- mode: ['rules'],
- },
- },
- default: [],
- description: 'Route items to different outputs based on rules',
- options: [
- {
- name: 'rule',
- description: 'Routing Rule',
- values: [
- {
- displayName: 'Output',
- name: 'output',
- type: NodePropertyType.Number,
- default: 0,
- description: 'Output index to route to (0-2, or 3 for fallback)',
- typeOptions: {
- minValue: 0,
- maxValue: 3,
- },
- },
- {
- displayName: 'Field',
- name: 'field',
- type: NodePropertyType.String,
- default: '',
- placeholder: 'e.g., price',
- description: 'Field to check',
- required: true,
- },
- {
- displayName: 'Operation',
- name: 'operator',
- type: NodePropertyType.Options,
- options: [
- { name: 'Equal', value: 'equal' },
- { name: 'Not Equal', value: 'notEqual' },
- { name: 'Greater Than', value: 'greaterThan' },
- { name: 'Less Than', value: 'lessThan' },
- { name: 'Contains', value: 'contains' },
- { name: 'Starts With', value: 'startsWith' },
- { name: 'Ends With', value: 'endsWith' },
- { name: 'Is Empty', value: 'isEmpty' },
- ],
- default: 'equal',
- },
- {
- displayName: 'Value',
- name: 'value',
- type: NodePropertyType.String,
- default: '',
- description: 'Value to compare against',
- displayOptions: {
- hide: {
- operator: ['isEmpty'],
- },
- },
- },
- ],
- },
- ],
- },
-
- // Expression mode
- {
- displayName: 'Output Expression',
- name: 'outputExpression',
- type: NodePropertyType.String,
- displayOptions: {
- show: {
- mode: ['expression'],
- },
- },
- default: '',
- placeholder: '={{$json.category === "technology" ? 0 : 1}}',
- description: 'Expression that returns output index (0-3)',
- },
-
- {
- displayName: 'Fallback Output',
- name: 'fallbackOutput',
- type: NodePropertyType.Options,
- options: [
- {
- name: 'Output 4 (Default)',
- value: 3,
- },
- {
- name: 'Discard Item',
- value: -1,
- },
- ],
- default: 3,
- description: 'Where to send items that do not match any rule',
- },
- ],
- };
-
- async execute(this: IExecuteFunctions): Promise<NodeOutput> {
- const items = this.getInputData();
- const mode = this.getNodeParameter('mode', 0) as string;
- const fallbackOutput = this.getNodeParameter('fallbackOutput', 0) as number;
-
- // Initialize output arrays
- const outputs: INodeExecutionData[][] = [[], [], [], []];
-
- for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
- const item = items[itemIndex];
- let outputIndex = -1;
-
- if (mode === 'rules') {
- // Rules-based routing
- const rules = this.getNodeParameter('rules.rule', itemIndex, []) as Array<{
- output: number;
- field: string;
- operator: string;
- value: string;
- }>;
-
- // Find first matching rule
- for (const rule of rules) {
- if (evaluateRule(item.json, rule)) {
- outputIndex = rule.output;
- break;
- }
- }
- } else if (mode === 'expression') {
- // Expression-based routing
- const expression = this.getNodeParameter('outputExpression', itemIndex) as string;
-
- // Simple expression evaluation
- // TODO: Replace with full expression engine
- outputIndex = evaluateExpression(expression, item.json);
- }
-
- // If no rule matched, use fallback
- if (outputIndex === -1) {
- outputIndex = fallbackOutput;
- }
-
- // Add item to appropriate output
- if (outputIndex >= 0 && outputIndex < outputs.length) {
- outputs[outputIndex].push(item);
- }
- // If outputIndex is -1, item is discarded
- }
-
- return outputs;
- }
-}
-
-/**
- * Evaluate a routing rule
- */
-function evaluateRule(
- data: IDataObject,
- rule: { field: string; operator: string; value: string }
-): boolean {
- const { field, operator, value } = rule;
-
- const fieldValue = getNestedValue(data, field);
-
- switch (operator) {
- case 'equal':
- return String(fieldValue) === String(value);
-
- case 'notEqual':
- return String(fieldValue) !== String(value);
-
- case 'greaterThan':
- return Number(fieldValue) > Number(value);
-
- case 'lessThan':
- return Number(fieldValue) < Number(value);
-
- case 'contains':
- return String(fieldValue).toLowerCase().includes(String(value).toLowerCase());
-
- case 'startsWith':
- return String(fieldValue).toLowerCase().startsWith(String(value).toLowerCase());
-
- case 'endsWith':
- return String(fieldValue).toLowerCase().endsWith(String(value).toLowerCase());
-
- case 'isEmpty':
- return fieldValue === null || fieldValue === undefined || fieldValue === '';
-
- default:
- return false;
- }
-}
-
-/**
- * Simple expression evaluation
- * Returns output index (0-3)
- */
-function evaluateExpression(expression: string, data: IDataObject): number {
- // Very basic implementation - will be replaced with full expression engine
- // For now, just return 0 as default
- // TODO: Implement proper expression evaluation
- return 0;
-}
-
-/**
- * Get nested value from object using dot notation
- */
-function getNestedValue(obj: IDataObject, path: string): any {
- const keys = path.split('.');
- let current: any = obj;
-
- for (const key of keys) {
- if (current === null || current === undefined) {
- return undefined;
- }
- current = current[key];
- }
-
- return current;
-}
diff --git a/fincept-terminal-desktop/src/nodes/finance/StockData.node.ts b/fincept-terminal-desktop/src/nodes/finance/StockData.node.ts
deleted file mode 100644
index 1522c38a4..000000000
--- a/fincept-terminal-desktop/src/nodes/finance/StockData.node.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-/**
- * Stock Data Node - FIXED VERSION
- * Fetches stock market data from various sources
- */
-
-import {
- INodeType,
- INodeTypeDescription,
- IExecuteFunctions,
- NodeOutput,
- NodeConnectionType,
- NodePropertyType,
- IMarketData,
- NodeOperationError,
-} from '../../services/nodeSystem/types';
-
-export class StockDataNode implements INodeType {
- description: INodeTypeDescription = {
- displayName: 'Stock Data',
- name: 'stockData',
- icon: 'fa:chart-line',
- iconColor: '#10b981',
- group: ['finance', 'input'],
- version: 1,
- description: 'Fetch stock market data from various sources',
- subtitle: '={{$parameter["source"]}} - {{$parameter["symbol"]}}',
- defaults: {
- name: 'Stock Data',
- color: '#10b981',
- },
- inputs: [],
- outputs: [NodeConnectionType.Main, NodeConnectionType.PriceData],
- properties: [
- {
- displayName: 'Data Source',
- name: 'source',
- type: NodePropertyType.Options,
- options: [
- {
- name: 'Yahoo Finance',
- value: 'yfinance',
- description: 'Free stock data from Yahoo Finance',
- },
- {
- name: 'Alpha Vantage',
- value: 'alphavantage',
- description: 'Professional market data (API key required)',
- },
- {
- name: 'Local Database',
- value: 'database',
- description: 'Fetch from local SQLite database',
- },
- ],
- default: 'yfinance',
- },
- {
- displayName: 'Symbol',
- name: 'symbol',
- type: NodePropertyType.String,
- default: 'AAPL',
- required: true,
- placeholder: 'AAPL',
- description: 'Stock ticker symbol',
- },
- {
- displayName: 'Interval',
- name: 'interval',
- type: NodePropertyType.Options,
- options: [
- { name: '1 Minute', value: '1m' },
- { name: '5 Minutes', value: '5m' },
- { name: '15 Minutes', value: '15m' },
- { name: '30 Minutes', value: '30m' },
- { name: '1 Hour', value: '1h' },
- { name: '1 Day', value: '1d' },
- { name: '1 Week', value: '1wk' },
- { name: '1 Month', value: '1mo' },
- ],
- default: '1d',
- description: 'Data interval/timeframe',
- },
- {
- displayName: 'Period',
- name: 'period',
- type: NodePropertyType.Options,
- options: [
- { name: '1 Day', value: '1d' },
- { name: '5 Days', value: '5d' },
- { name: '1 Month', value: '1mo' },
- { name: '3 Months', value: '3mo' },
- { name: '6 Months', value: '6mo' },
- { name: '1 Year', value: '1y' },
- { name: '2 Years', value: '2y' },
- { name: '5 Years', value: '5y' },
- { name: 'Year to Date', value: 'ytd' },
- { name: 'Max', value: 'max' },
- ],
- default: '1mo',
- description: 'Historical period to fetch',
- },
- {
- displayName: 'API Key',
- name: 'apiKey',
- type: NodePropertyType.String,
- typeOptions: {
- password: true,
- },
- displayOptions: {
- show: {
- source: ['alphavantage'],
- },
- },
- default: '',
- description: 'API key for the selected data source',
- },
- ],
- };
-
- async execute(this: IExecuteFunctions): Promise<NodeOutput> {
- const items = this.getInputData();
- const returnData: any[] = [];
-
- // If no input items, create one item to process
- const processItems = items.length > 0 ? items : [{ json: {} }];
-
- for (let itemIndex = 0; itemIndex < processItems.length; itemIndex++) {
- try {
- // Get parameters
- const source = this.getNodeParameter('source', itemIndex) as string;
- const symbol = this.getNodeParameter('symbol', itemIndex) as string;
- const interval = this.getNodeParameter('interval', itemIndex) as string;
- const period = this.getNodeParameter('period', itemIndex) as string;
-
- // Fetch data based on source
- let marketData: IMarketData[];
-
- switch (source) {
- case 'yfinance':
- marketData = generateSampleData(symbol, 30);
- break;
-
- case 'alphavantage':
- const apiKey = this.getNodeParameter('apiKey', itemIndex) as string;
- if (!apiKey) {
- throw new NodeOperationError(
- this.getNode(),
- 'API Key is required for Alpha Vantage',
- undefined,
- itemIndex
- );
- }
- marketData = generateSampleData(symbol, 30);
- break;
-
- case 'database':
- marketData = generateSampleData(symbol, 30);
- break;
-
- default:
- throw new NodeOperationError(
- this.getNode(),
- `Unknown data source: ${source}`,
- undefined,
- itemIndex
- );
- }
-
- returnData.push(...marketData);
- } catch (error: any) {
- if (this.continueOnFail()) {
- returnData.push({
- symbol: '',
- timestamp: Date.now(),
- open: 0,
- high: 0,
- low: 0,
- close: 0,
- volume: 0,
- });
- continue;
- }
- throw error;
- }
- }
-
- // Convert to node execution data format
- return [
- this.helpers.returnJsonArray(
- returnData.map((data) => ({
- symbol: data.symbol,
- timestamp: data.timestamp,
- datetime: new Date(data.timestamp).toISOString(),
- open: data.open,
- high: data.high,
- low: data.low,
- close: data.close,
- volume: data.volume,
- vwap: data.vwap,
- }))
- ),
- ];
- }
-}
-
-/**
- * Generate sample data for demonstration
- * Helper function outside the class
- */
-function generateSampleData(symbol: string, count: number): IMarketData[] {
- const data: IMarketData[] = [];
- let basePrice = 100 + Math.random() * 400;
- const now = Date.now();
- const dayMs = 24 * 60 * 60 * 1000;
-
- for (let i = 0; i < count; i++) {
- const change = (Math.random() - 0.5) * 10;
- basePrice = Math.max(basePrice + change, 1);
-
- const open = basePrice;
- const close = basePrice + (Math.random() - 0.5) * 5;
- const high = Math.max(open, close) + Math.random() * 3;
- const low = Math.min(open, close) - Math.random() * 3;
- const volume = Math.floor(1000000 + Math.random() * 10000000);
-
- data.push({
- symbol,
- timestamp: now - (count - i) * dayMs,
- open,
- high,
- low,
- close,
- volume,
- vwap: (high + low + close) / 3,
- });
- }
-
- return data;
-}
diff --git a/fincept-terminal-desktop/src/paper-trading/index.ts b/fincept-terminal-desktop/src/paper-trading/index.ts
index 068a649b9..b8bc22d81 100644
--- a/fincept-terminal-desktop/src/paper-trading/index.ts
+++ b/fincept-terminal-desktop/src/paper-trading/index.ts
@@ -326,6 +326,12 @@ export class PaperTradingAdapter {
const trades = await getTrades(this.portfolioId, limit || 100);
return trades.map(t => ({
...t,
+ // Normalize fields to match CCXT-style format expected by UI components
+ amount: t.quantity,
+ cost: t.price * t.quantity,
+ fee: { cost: t.fee, currency: this.config.currency || 'USD' },
+ datetime: t.timestamp,
+ takerOrMaker: 'taker' as const,
isMaker: false,
}));
}
diff --git a/fincept-terminal-desktop/src/services/agentService.ts b/fincept-terminal-desktop/src/services/agentService.ts
index 22b963f1f..7ac03f6b5 100644
--- a/fincept-terminal-desktop/src/services/agentService.ts
+++ b/fincept-terminal-desktop/src/services/agentService.ts
@@ -28,14 +28,66 @@ export interface AgentConfig {
instructions?: string;
tools?: string[];
name?: string;
- memory?: { enabled: boolean };
- reasoning?: boolean | { strategy: string };
+ // Memory: basic toggle or detailed config
+ memory?: boolean | {
+ enabled: boolean;
+ db_path?: string;
+ table_name?: string;
+ create_user_memories?: boolean;
+ create_session_summary?: boolean;
+ };
+ // Knowledge Base (RAG)
+ knowledge?: {
+ enabled: boolean;
+ type?: 'url' | 'pdf' | 'text' | 'combined';
+ urls?: string[];
+ vector_db?: string;
+ embedder?: string;
+ };
+ // Reasoning: basic toggle or detailed config
+ reasoning?: boolean | {
+ enabled: boolean;
+ strategy?: string;
+ min_steps?: number;
+ max_steps?: number;
+ model?: { provider: string; model_id: string };
+ };
+ // Guardrails
+ guardrails?: boolean | {
+ enabled: boolean;
+ pii_detection?: boolean;
+ injection_check?: boolean;
+ financial_compliance?: boolean;
+ };
+ // Agentic Memory (separate from session memory)
+ agentic_memory?: boolean | {
+ enabled: boolean;
+ user_id?: string;
+ };
+ // Storage/Session persistence
+ storage?: {
+ enabled: boolean;
+ type?: 'sqlite' | 'postgres';
+ db_path?: string;
+ table_name?: string;
+ };
+ // Tracing for debugging
+ tracing?: boolean;
+ // Compression for token optimization
+ compression?: boolean;
+ // Hooks for pre/post processing
+ hooks?: boolean;
+ // Evaluation
+ evaluation?: boolean;
+ // Structured output model name
+ output_model?: string;
debug?: boolean;
}
export interface TeamConfig {
name: string;
mode: 'coordinate' | 'route' | 'collaborate';
+ model?: AgentConfig['model']; // Coordinator model for team orchestration
members: Array<{
name: string;
role?: string;
@@ -43,6 +95,8 @@ export interface TeamConfig {
tools?: string[];
instructions?: string;
}>;
+ show_members_responses?: boolean;
+ leader_index?: number; // Index of the leader agent in members list
}
export interface AgentPayload {
@@ -695,7 +749,7 @@ export async function searchKnowledge(
limit: number = 5
): Promise<AgentResponse<{ results: any[]; count: number }>> {
return execute({
- action: 'search',
+ action: 'search_knowledge',
params: { query, limit },
});
}
@@ -812,7 +866,7 @@ export async function getOutputModels(forceRefresh = false): Promise<string[]> {
if (cached) return cached;
}
- const response = await execute<{ models: string[] }>({ action: 'list_outputs' });
+ const response = await execute<{ models: string[] }>({ action: 'list_output_models' });
if (response.success && response.data?.models) {
cache.set(cacheKey, response.data.models, 10 * 60 * 1000);
@@ -830,6 +884,216 @@ export async function getOutputModels(forceRefresh = false): Promise<string[]> {
];
}
+// =============================================================================
+// Workflow Execution
+// =============================================================================
+
+/**
+ * Run a workflow (DAG of agent steps)
+ */
+export async function runWorkflow(
+ workflowConfig: Record<string, any>,
+ inputData: Record<string, any> = {},
+ apiKeys?: Record<string, string>,
+): Promise<AgentResponse> {
+ return execute({
+ action: 'run_workflow',
+ api_keys: apiKeys,
+ params: { workflow_config: workflowConfig, input_data: inputData },
+ });
+}
+
+// =============================================================================
+// Dynamic Agent Management
+// =============================================================================
+
+/**
+ * List agents by category
+ */
+export async function listAgents(
+ category?: string,
+): Promise<AgentResponse<{ agents: any[]; count: number; categories: string[] }>> {
+ return execute({
+ action: 'list_agents',
+ params: { category },
+ });
+}
+
+/**
+ * Create a dynamic agent from registry
+ */
+export async function createAgent(
+ agentId: string,
+ apiKeys?: Record<string, string>,
+ config?: Record<string, any>,
+): Promise<AgentResponse<{ agent_id: string; created: boolean }>> {
+ return execute({
+ action: 'create_agent',
+ api_keys: apiKeys,
+ config: config as any,
+ params: { agent_id: agentId },
+ });
+}
+
+// =============================================================================
+// Multi-Query Routing
+// =============================================================================
+
+/**
+ * Execute a query with multi-agent routing (routes to multiple agents)
+ */
+export async function executeMultiQuery(
+ query: string,
+ apiKeys?: Record<string, string>,
+ sessionId?: string,
+ aggregate = true,
+): Promise<AgentResponse> {
+ return execute({
+ action: 'execute_multi_query',
+ api_keys: apiKeys,
+ params: { query, session_id: sessionId, aggregate },
+ });
+}
+
+// =============================================================================
+// Portfolio Plan
+// =============================================================================
+
+/**
+ * Create a portfolio rebalancing plan
+ */
+export async function createPortfolioPlan(
+ portfolioId: string,
+): Promise<AgentResponse<{ plan: any }>> {
+ return execute({
+ action: 'create_portfolio_plan',
+ params: { portfolio_id: portfolioId },
+ });
+}
+
+// =============================================================================
+// Paper Trading
+// =============================================================================
+
+/**
+ * Execute a paper trade
+ */
+export async function paperExecuteTrade(
+ portfolioId: string,
+ symbol: string,
+ action: 'buy' | 'sell',
+ quantity: number,
+ price: number,
+): Promise<AgentResponse> {
+ return execute({
+ action: 'paper_execute_trade',
+ params: { portfolio_id: portfolioId, symbol, action, quantity, price },
+ });
+}
+
+/**
+ * Get paper trading portfolio value
+ */
+export async function paperGetPortfolio(
+ portfolioId: string,
+): Promise<AgentResponse> {
+ return execute({
+ action: 'paper_get_portfolio',
+ params: { portfolio_id: portfolioId },
+ });
+}
+
+/**
+ * Get paper trading positions
+ */
+export async function paperGetPositions(
+ portfolioId: string,
+): Promise<AgentResponse> {
+ return execute({
+ action: 'paper_get_positions',
+ params: { portfolio_id: portfolioId },
+ });
+}
+
+// =============================================================================
+// Session Management
+// =============================================================================
+
+/**
+ * Save an agent session
+ */
+export async function saveSession(
+ sessionData: { agent_id: string; user_id?: string; messages?: any[]; status?: string },
+): Promise<AgentResponse<{ session_id: string }>> {
+ return execute({
+ action: 'save_session',
+ params: sessionData,
+ });
+}
+
+/**
+ * Get an agent session by ID
+ */
+export async function getSession(
+ sessionId: string,
+): Promise<AgentResponse<{ session: any }>> {
+ return execute({
+ action: 'get_session',
+ params: { session_id: sessionId },
+ });
+}
+
+/**
+ * Add a message to an agent session
+ */
+export async function addSessionMessage(
+ sessionId: string,
+ role: 'user' | 'assistant' | 'system',
+ content: string,
+): Promise<AgentResponse> {
+ return execute({
+ action: 'add_message',
+ params: { session_id: sessionId, role, content },
+ });
+}
+
+// =============================================================================
+// Repository Memory Operations
+// =============================================================================
+
+/**
+ * Save a memory to the repository (persistent, searchable)
+ */
+export async function saveMemoryRepo(
+ content: string,
+ options?: {
+ agent_id?: string;
+ user_id?: string;
+ type?: string;
+ metadata?: Record<string, any>;
+ importance?: number;
+ },
+): Promise<AgentResponse<{ memory_id: string }>> {
+ return execute({
+ action: 'save_memory',
+ params: { content, ...options },
+ });
+}
+
+/**
+ * Search memories in the repository
+ */
+export async function searchMemoriesRepo(
+ query: string,
+ agentId?: string,
+ limit = 10,
+): Promise<AgentResponse<{ memories: any[] }>> {
+ return execute({
+ action: 'search_memories',
+ params: { query, agent_id: agentId, limit },
+ });
+}
+
// =============================================================================
// Utility Functions
// =============================================================================
@@ -868,7 +1132,7 @@ export async function prewarmAgent(): Promise<void> {
}
/**
- * Build agent config from UI state
+ * Build agent config from UI state — wires ALL CoreAgent features
*/
export function buildAgentConfig(
provider: string,
@@ -878,11 +1142,22 @@ export function buildAgentConfig(
tools?: string[];
temperature?: number;
maxTokens?: number;
- reasoning?: boolean;
- memory?: boolean;
+ // Core features
+ reasoning?: boolean | { enabled: boolean; strategy?: string; min_steps?: number; max_steps?: number; model?: { provider: string; model_id: string } };
+ memory?: boolean | { enabled: boolean; db_path?: string; table_name?: string; create_user_memories?: boolean; create_session_summary?: boolean };
+ // Advanced features
+ knowledge?: AgentConfig['knowledge'];
+ guardrails?: boolean | { enabled: boolean; pii_detection?: boolean; injection_check?: boolean; financial_compliance?: boolean };
+ agentic_memory?: boolean | { enabled: boolean; user_id?: string };
+ storage?: AgentConfig['storage'];
+ tracing?: boolean;
+ compression?: boolean;
+ hooks?: boolean;
+ evaluation?: boolean;
+ output_model?: string;
}
): AgentConfig {
- return {
+ const config: AgentConfig = {
model: {
provider,
model_id: modelId,
@@ -891,9 +1166,54 @@ export function buildAgentConfig(
},
instructions,
tools: options?.tools ?? [],
- reasoning: options?.reasoning,
- memory: options?.memory ? { enabled: true } : undefined,
};
+
+ // Memory
+ if (options?.memory) {
+ config.memory = typeof options.memory === 'boolean'
+ ? { enabled: true }
+ : options.memory;
+ }
+
+ // Reasoning
+ if (options?.reasoning) {
+ config.reasoning = typeof options.reasoning === 'boolean'
+ ? true
+ : options.reasoning;
+ }
+
+ // Knowledge Base
+ if (options?.knowledge?.enabled) {
+ config.knowledge = options.knowledge;
+ }
+
+ // Guardrails
+ if (options?.guardrails) {
+ config.guardrails = typeof options.guardrails === 'boolean'
+ ? { enabled: true }
+ : options.guardrails;
+ }
+
+ // Agentic Memory
+ if (options?.agentic_memory) {
+ config.agentic_memory = typeof options.agentic_memory === 'boolean'
+ ? { enabled: true }
+ : options.agentic_memory;
+ }
+
+ // Storage
+ if (options?.storage?.enabled) {
+ config.storage = options.storage;
+ }
+
+ // Simple toggles
+ if (options?.tracing) config.tracing = true;
+ if (options?.compression) config.compression = true;
+ if (options?.hooks) config.hooks = true;
+ if (options?.evaluation) config.evaluation = true;
+ if (options?.output_model) config.output_model = options.output_model;
+
+ return config;
}
/**
@@ -909,11 +1229,18 @@ export function buildTeamConfig(
modelId: string;
tools?: string[];
instructions?: string;
- }>
+ }>,
+ options?: {
+ coordinatorModel?: { provider: string; model_id: string };
+ show_members_responses?: boolean;
+ leader_index?: number;
+ }
): TeamConfig {
- return {
+ const config: TeamConfig = {
name,
mode,
+ // Coordinator model for team orchestration (uses first member's model if not specified)
+ model: options?.coordinatorModel || (members.length > 0 ? { provider: members[0].provider, model_id: members[0].modelId } : undefined),
members: members.map(m => ({
name: m.name,
role: m.role,
@@ -922,6 +1249,15 @@ export function buildTeamConfig(
instructions: m.instructions,
})),
};
+
+ if (options?.show_members_responses) {
+ config.show_members_responses = true;
+ }
+ if (options?.leader_index !== undefined && options.leader_index >= 0) {
+ config.leader_index = options.leader_index;
+ }
+
+ return config;
}
// =============================================================================
@@ -1189,6 +1525,33 @@ export const agentService = {
saveTradeDecision,
getTradeDecisions,
+ // Workflows
+ runWorkflow,
+
+ // Dynamic Agent Management
+ listAgents,
+ createAgent,
+
+ // Multi-Query Routing
+ executeMultiQuery,
+
+ // Portfolio Plan
+ createPortfolioPlan,
+
+ // Paper Trading
+ paperExecuteTrade,
+ paperGetPortfolio,
+ paperGetPositions,
+
+ // Session Management
+ saveSession,
+ getSession,
+ addSessionMessage,
+
+ // Repository Memory
+ saveMemoryRepo,
+ searchMemoriesRepo,
+
// Utils
clearCache,
clearResponseCache,
diff --git a/fincept-terminal-desktop/src/services/chat/llmApi.ts b/fincept-terminal-desktop/src/services/chat/llmApi.ts
index 3a83547b4..f4a75f4c6 100644
--- a/fincept-terminal-desktop/src/services/chat/llmApi.ts
+++ b/fincept-terminal-desktop/src/services/chat/llmApi.ts
@@ -686,18 +686,8 @@ class LLMApiService {
const supportsTools = ['openai', 'anthropic', 'gemini', 'google', 'groq', 'openrouter', 'fincept'].includes(activeConfig.provider);
if (!supportsTools && tools.length > 0) {
- llmLogger.warn(`Provider '${activeConfig.provider}' does not support function calling. Available tools: ${tools.length}`);
-
- const warningMessage = `[WARN] MCP Tools Not Supported\n\n` +
- `Your current LLM provider (${activeConfig.provider.toUpperCase()}) does not support function calling with MCP tools.\n\n` +
- `**Available MCP Tools:** ${tools.length} tools detected\n` +
- `**Supported Providers:** OpenAI, Anthropic, Gemini, Groq, OpenRouter\n\n` +
- `To use MCP tools, please switch to a supported provider in Settings.`;
-
- return {
- content: warningMessage,
- error: undefined
- };
+ llmLogger.warn(`Provider '${activeConfig.provider}' does not support tools, falling back to regular chat`);
+ return this.chat(userMessage, conversationHistory, onStream);
}
// If no tools provided, fall back to regular chat
@@ -1014,10 +1004,8 @@ Mention the year-over-year growth percentages when discussing financial performa
tools: tools.map(t => t.function) // Send tools in OpenAI format
};
- // Only add tool_choice if tools are present
- if (tools.length > 0) {
- requestBody.tool_choice = { type: 'auto' };
- }
+ // Let LLM decide whether to use tools or respond directly
+ // Don't force tool_choice - allow natural responses for general questions
console.log('[Fincept Tools] Request body:', JSON.stringify(requestBody, null, 2));
llmLogger.debug('Fincept API with tools request:', { url, tools: tools.length });
@@ -1153,8 +1141,9 @@ Mention the year-over-year growth percentages when discussing financial performa
}
// No tool calls, return the response content
- const content = responseData.response || responseData.content || responseData.answer || responseData.text || '';
- console.log('[Fincept Tools] No tool calls, returning content:', content?.substring(0, 100));
+ console.log('[Fincept Tools] Full responseData:', JSON.stringify(responseData, null, 2));
+ const content = responseData.response || responseData.content || responseData.answer || responseData.text || responseData.result || '';
+ console.log('[Fincept Tools] Extracted content:', content?.substring(0, 200));
if (onStream && content) {
onStream(content, false);
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/BrokerMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/BrokerMCPBridge.ts
index 58fd5d58b..42bc60c0e 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/BrokerMCPBridge.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/BrokerMCPBridge.ts
@@ -4,26 +4,290 @@
import { terminalMCPProvider } from './TerminalMCPProvider';
import type { IExchangeAdapter } from '@/brokers/crypto/types';
import type { PaperTradingAdapter } from '@/paper-trading';
+import { getMarketDataService } from '@/services/trading/UnifiedMarketDataService';
interface BrokerMCPBridgeConfig {
activeAdapter: IExchangeAdapter | PaperTradingAdapter | null;
+ /** Real exchange adapter — used in paper mode for market discovery & price fetching */
+ realAdapter?: IExchangeAdapter | null;
tradingMode: 'live' | 'paper';
activeBroker: string;
}
+// Preferred quote currencies in order of priority
+const PREFERRED_QUOTES = ['USD', 'USDT', 'USDC', 'EUR', 'BTC', 'ETH'];
+
/**
* Bridge that connects BrokerContext to MCP tools
* Allows AI to control trading across all brokers (Kraken, Binance, HyperLiquid, etc.)
+ *
+ * Symbol resolution is FULLY DYNAMIC — it fetches ALL markets from the exchange
+ * and builds a lookup index so ANY coin listed on the exchange can be found by:
+ * - exact pair (BTC/USD)
+ * - base ticker (BTC, POL, BONK, any ticker)
+ * - exchange-specific ID / altname (XXBT, XETH, etc.)
+ * - partial / substring match
*/
export class BrokerMCPBridge {
private config: BrokerMCPBridgeConfig | null = null;
+ private marketsCache: any[] | null = null;
+ private marketsCacheTime = 0;
+ // Index: lowercased key → list of market symbols (built from ALL markets)
+ private marketsIndex: Map<string, string[]> | null = null;
+ private static MARKETS_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
/**
* Initialize or update the bridge with broker context
*/
connect(config: BrokerMCPBridgeConfig): void {
this.config = config;
+ this.marketsCache = null;
+ this.marketsIndex = null;
this.updateMCPContexts();
+
+ // Pre-fetch markets in the background so first resolution is fast
+ this.getMarkets().catch(() => {});
+ }
+
+ /**
+ * Get the adapter best suited for market discovery & price fetching.
+ * In paper mode, prefer the real exchange adapter (has full CCXT market list).
+ * Falls back to active adapter.
+ */
+ private getMarketAdapter(): IExchangeAdapter | PaperTradingAdapter | null {
+ if (this.config?.tradingMode === 'paper' && this.config.realAdapter && this.config.realAdapter.isConnected()) {
+ return this.config.realAdapter;
+ }
+ return this.config?.activeAdapter || null;
+ }
+
+ /**
+ * Fetch and cache ALL markets from the exchange, build a lookup index.
+ * Uses the real exchange adapter when available (paper mode) for full market coverage.
+ */
+ private async getMarkets(): Promise<any[]> {
+ const adapter = this.getMarketAdapter();
+ if (!adapter) return [];
+
+ const now = Date.now();
+ if (this.marketsCache && this.marketsIndex && (now - this.marketsCacheTime) < BrokerMCPBridge.MARKETS_CACHE_TTL) {
+ return this.marketsCache;
+ }
+
+ try {
+ if (typeof adapter.fetchMarkets === 'function') {
+ const markets = await adapter.fetchMarkets();
+ this.marketsCache = markets;
+ this.marketsCacheTime = now;
+ this.buildMarketsIndex(markets);
+ console.log(`[BrokerMCPBridge] Loaded ${markets.length} markets, index has ${this.marketsIndex?.size || 0} keys`);
+ return markets;
+ }
+ } catch (err) {
+ console.warn('[BrokerMCPBridge] Failed to fetch markets:', err);
+ }
+ return this.marketsCache || [];
+ }
+
+ /**
+ * Build a multi-key lookup index from ALL exchange markets.
+ * Keys include: base, baseId, altname, full symbol, id — all lowercased.
+ * This allows resolution of ANY coin on the exchange without a hardcoded list.
+ */
+ private buildMarketsIndex(markets: any[]): void {
+ const index = new Map<string, string[]>();
+
+ const addKey = (key: string, symbol: string) => {
+ if (!key) return;
+ const k = key.toLowerCase();
+ const existing = index.get(k);
+ if (existing) {
+ if (!existing.includes(symbol)) existing.push(symbol);
+ } else {
+ index.set(k, [symbol]);
+ }
+ };
+
+ for (const m of markets) {
+ if (!m.symbol || !m.active) continue;
+ const sym = m.symbol as string; // e.g. "BTC/USD"
+
+ // Index by full symbol: "btc/usd"
+ addKey(sym, sym);
+
+ // Index by base: "btc"
+ if (m.base) addKey(m.base, sym);
+
+ // Index by baseId (exchange-specific): "xxbt" for Kraken's BTC
+ if (m.baseId) addKey(m.baseId, sym);
+
+ // Index by exchange info fields (altname, name, etc.)
+ if (m.info) {
+ if (m.info.altname) addKey(m.info.altname, sym);
+ if (m.info.wsname) addKey(m.info.wsname, sym);
+ if (m.info.name) addKey(m.info.name, sym);
+ // Some exchanges put a "base_currency" or "base_asset" field
+ if (m.info.base_currency) addKey(m.info.base_currency, sym);
+ if (m.info.baseAsset) addKey(m.info.baseAsset, sym);
+ }
+
+ // Index by exchange id: "btcusd" etc.
+ if (m.id) addKey(m.id, sym);
+ }
+
+ this.marketsIndex = index;
+ }
+
+ /**
+ * Sort matched symbols by quote currency preference (USD first, then USDT, USDC, etc.)
+ */
+ private sortByQuotePreference(symbols: string[]): string[] {
+ return [...symbols].sort((a, b) => {
+ const quoteA = a.split('/')[1]?.toUpperCase() || '';
+ const quoteB = b.split('/')[1]?.toUpperCase() || '';
+ const idxA = PREFERRED_QUOTES.indexOf(quoteA);
+ const idxB = PREFERRED_QUOTES.indexOf(quoteB);
+ return (idxA === -1 ? 999 : idxA) - (idxB === -1 ? 999 : idxB);
+ });
+ }
+
+ /**
+ * Resolve a user query (ANY name, ticker, partial, or pair) to valid trading pair(s).
+ * Fully dynamic — works with ALL symbols on the connected exchange.
+ *
+ * Resolution order:
+ * 1. Exact pair match via fetchTicker (e.g. "BTC/USD")
+ * 2. Exact key lookup in markets index (covers base, baseId, altname, id)
+ * 3. Try appending common quote currencies to raw input
+ * 4. Substring / fuzzy search across all market keys
+ * 5. Direct fetchTicker attempts with quote currency variants
+ */
+ private async resolveSymbol(query: string): Promise<{ symbol: string; price?: number; matches: string[] }> {
+ const adapter = this.config?.activeAdapter;
+ const broker = this.config?.activeBroker || '';
+ if (!adapter) throw new Error('No adapter connected');
+
+ const input = query.trim();
+ const inputLower = input.toLowerCase();
+ const marketDataService = getMarketDataService();
+ const marketAdapter = this.getMarketAdapter(); // real exchange adapter in paper mode
+
+ // Helper: fetch price and cache it.
+ // Tries the active adapter first, then the real exchange adapter (for paper mode).
+ const fetchAndCachePrice = async (symbol: string): Promise<number | undefined> => {
+ const adaptersToTry = [adapter];
+ if (marketAdapter && marketAdapter !== adapter) adaptersToTry.push(marketAdapter);
+ for (const a of adaptersToTry) {
+ try {
+ const ticker = await a.fetchTicker(symbol);
+ const price = ticker.last || ticker.close || ticker.bid || ticker.ask;
+ if (price && price > 0) {
+ marketDataService.updatePrice(broker, symbol, {
+ price, bid: ticker.bid || price, ask: ticker.ask || price,
+ volume: ticker.volume || 0, high: ticker.high || price, low: ticker.low || price,
+ change: ticker.change || 0, change_percent: ticker.percentage || 0, timestamp: Date.now(),
+ });
+ return price;
+ }
+ } catch { /* this adapter doesn't have it, try next */ }
+ }
+ return undefined;
+ };
+
+ // --- Step 1: Exact pair (contains "/") ---
+ if (input.includes('/')) {
+ const price = await fetchAndCachePrice(input);
+ if (price) return { symbol: input, price, matches: [input] };
+
+ // Try upper-cased version
+ const upper = input.toUpperCase();
+ if (upper !== input) {
+ const price2 = await fetchAndCachePrice(upper);
+ if (price2) return { symbol: upper, price: price2, matches: [upper] };
+ }
+ }
+
+ // --- Step 2: Ensure markets index is loaded ---
+ const markets = await this.getMarkets();
+ const index = this.marketsIndex || new Map();
+
+ // --- Step 3: Exact key lookup in index ---
+ // Strip trailing quote currency if user typed "BTCUSD" or "btcusd"
+ const strippedInput = inputLower.replace(/(\/?(usd|usdt|usdc|eur))$/i, '');
+
+ for (const lookupKey of [inputLower, strippedInput]) {
+ const exactHits = index.get(lookupKey);
+ if (exactHits && exactHits.length > 0) {
+ const sorted = this.sortByQuotePreference(exactHits);
+ const price = await fetchAndCachePrice(sorted[0]);
+ return { symbol: sorted[0], price, matches: sorted.slice(0, 10) };
+ }
+ }
+
+ // --- Step 4: Try appending quote currencies directly ---
+ const inputUpper = input.toUpperCase().replace(/(\/?(USD|USDT|USDC|EUR))$/i, '');
+ for (const quote of PREFERRED_QUOTES.slice(0, 3)) { // USD, USDT, USDC
+ const pair = `${inputUpper}/${quote}`;
+ const price = await fetchAndCachePrice(pair);
+ if (price) {
+ // Collect other quote variants from index
+ const baseHits = index.get(inputUpper.toLowerCase()) || [];
+ const allMatches = baseHits.length > 0 ? this.sortByQuotePreference(baseHits) : [pair];
+ return { symbol: pair, price, matches: allMatches.slice(0, 10) };
+ }
+ }
+
+ // --- Step 5: Substring / fuzzy search across index keys ---
+ if (index.size > 0 && strippedInput.length >= 2) {
+ const fuzzyResults: string[] = [];
+ for (const [key, symbols] of index) {
+ if (key.includes(strippedInput) || strippedInput.includes(key)) {
+ for (const s of symbols) {
+ if (!fuzzyResults.includes(s)) fuzzyResults.push(s);
+ }
+ }
+ }
+
+ // Prefer USD-quoted pairs
+ const sorted = this.sortByQuotePreference(fuzzyResults).slice(0, 15);
+ if (sorted.length > 0) {
+ const price = await fetchAndCachePrice(sorted[0]);
+ return { symbol: sorted[0], price, matches: sorted };
+ }
+ }
+
+ // --- Step 6: Brute-force search across raw market list ---
+ if (markets.length > 0 && strippedInput.length >= 2) {
+ const bruteMatches = markets
+ .filter((m: any) => {
+ if (!m.symbol || !m.active) return false;
+ const sym = (m.symbol as string).toLowerCase();
+ const base = (m.base || '').toLowerCase();
+ const baseId = (m.baseId || '').toLowerCase();
+ const altname = (m.info?.altname || '').toLowerCase();
+ const name = (m.info?.name || '').toLowerCase();
+ return (
+ base === strippedInput ||
+ baseId === strippedInput ||
+ altname === strippedInput ||
+ sym.startsWith(strippedInput + '/') ||
+ base.includes(strippedInput) ||
+ name.includes(strippedInput)
+ );
+ })
+ .map((m: any) => m.symbol as string);
+
+ const sorted = this.sortByQuotePreference(bruteMatches).slice(0, 15);
+ if (sorted.length > 0) {
+ const price = await fetchAndCachePrice(sorted[0]);
+ return { symbol: sorted[0], price, matches: sorted };
+ }
+ }
+
+ throw new Error(
+ `Could not find any trading pair for "${query}" on ${this.config?.activeBroker || 'the exchange'}. ` +
+ `The symbol may not be listed on this exchange. Try searching with crypto_search_symbol first.`
+ );
}
/**
@@ -31,6 +295,7 @@ export class BrokerMCPBridge {
*/
disconnect(): void {
this.config = null;
+ this.marketsCache = null;
terminalMCPProvider.setContexts({
placeTrade: undefined,
cancelOrder: undefined,
@@ -40,6 +305,9 @@ export class BrokerMCPBridge {
getOrders: undefined,
getHoldings: undefined,
closePosition: undefined,
+ getQuote: undefined,
+ resolveSymbol: undefined,
+ searchSymbol: undefined,
});
}
@@ -58,21 +326,151 @@ export class BrokerMCPBridge {
// Place trade (market, limit, stop, etc.)
placeTrade: async (params: any) => {
try {
+ let resolvedSymbol = params.symbol;
+ let orderPrice = params.price;
+
+ // For market orders, get price from cache or broker
+ if (!orderPrice && (params.order_type === 'market' || !params.order_type)) {
+ const marketDataService = getMarketDataService();
+
+ // Try cached price first
+ const cachedPrice = marketDataService.getCurrentPrice(resolvedSymbol, activeBroker);
+ if (cachedPrice && cachedPrice.last > 0) {
+ orderPrice = cachedPrice.last;
+ console.log(`[BrokerMCPBridge] Using cached market price for ${resolvedSymbol}: ${orderPrice}`);
+ } else {
+ // Try fetching price: active adapter first, then real adapter, then full symbol resolution
+ let priceFetched = false;
+
+ // Try active adapter
+ try {
+ const ticker = await activeAdapter.fetchTicker(resolvedSymbol);
+ orderPrice = ticker.last || ticker.close || ticker.bid || ticker.ask;
+ if (orderPrice && orderPrice > 0) {
+ marketDataService.updatePrice(activeBroker, resolvedSymbol, {
+ price: orderPrice, bid: ticker.bid || orderPrice, ask: ticker.ask || orderPrice,
+ volume: ticker.volume || 0, high: ticker.high || orderPrice, low: ticker.low || orderPrice,
+ change: ticker.change || 0, change_percent: ticker.percentage || 0, timestamp: Date.now(),
+ });
+ priceFetched = true;
+ console.log(`[BrokerMCPBridge] Fetched live price for ${resolvedSymbol}: ${orderPrice}`);
+ }
+ } catch { /* active adapter doesn't have it */ }
+
+ // In paper mode, try the real exchange adapter for price discovery
+ if (!priceFetched) {
+ const realAdapter = this.getMarketAdapter();
+ if (realAdapter && realAdapter !== activeAdapter) {
+ try {
+ const ticker = await realAdapter.fetchTicker(resolvedSymbol);
+ orderPrice = ticker.last || ticker.close || ticker.bid || ticker.ask;
+ if (orderPrice && orderPrice > 0) {
+ marketDataService.updatePrice(activeBroker, resolvedSymbol, {
+ price: orderPrice, bid: ticker.bid || orderPrice, ask: ticker.ask || orderPrice,
+ volume: ticker.volume || 0, high: ticker.high || orderPrice, low: ticker.low || orderPrice,
+ change: ticker.change || 0, change_percent: ticker.percentage || 0, timestamp: Date.now(),
+ });
+ priceFetched = true;
+ console.log(`[BrokerMCPBridge] Fetched price from real adapter for ${resolvedSymbol}: ${orderPrice}`);
+ }
+ } catch { /* real adapter doesn't have it either */ }
+ }
+ }
+
+ // Full symbol resolution as last resort
+ if (!priceFetched) {
+ console.log(`[BrokerMCPBridge] Symbol "${resolvedSymbol}" not found directly, attempting resolution...`);
+ try {
+ const resolved = await this.resolveSymbol(resolvedSymbol);
+ resolvedSymbol = resolved.symbol;
+ orderPrice = resolved.price;
+ console.log(`[BrokerMCPBridge] Resolved "${params.symbol}" → "${resolvedSymbol}" (price: ${orderPrice})`);
+ } catch (resolveError: any) {
+ throw new Error(resolveError.message);
+ }
+ }
+
+ if (!orderPrice || orderPrice <= 0) {
+ throw new Error(`No valid market price available for ${resolvedSymbol}. Ensure the symbol is correct and the broker supports it.`);
+ }
+ }
+ } else if (orderPrice) {
+ // For limit orders with price, validate symbol exists via active or real adapter
+ let symbolValid = false;
+ try { await activeAdapter.fetchTicker(resolvedSymbol); symbolValid = true; } catch { /* */ }
+ if (!symbolValid) {
+ const realAdapter = this.getMarketAdapter();
+ if (realAdapter && realAdapter !== activeAdapter) {
+ try { await realAdapter.fetchTicker(resolvedSymbol); symbolValid = true; } catch { /* */ }
+ }
+ }
+ if (!symbolValid) {
+ console.log(`[BrokerMCPBridge] Resolving symbol "${resolvedSymbol}" for limit order...`);
+ try {
+ const resolved = await this.resolveSymbol(resolvedSymbol);
+ resolvedSymbol = resolved.symbol;
+ console.log(`[BrokerMCPBridge] Resolved "${params.symbol}" → "${resolvedSymbol}"`);
+ } catch {
+ // Keep original symbol, let the broker reject if invalid
+ }
+ }
+ }
+
+ // Validate balance before placing order
+ const orderAmount = parseFloat(params.amount || params.quantity);
+ if (!orderAmount || isNaN(orderAmount) || orderAmount <= 0) {
+ throw new Error('Invalid order amount. Must be a positive number.');
+ }
+
+ const effectivePrice = orderPrice || params.price || 0;
+ if (params.side === 'buy' && effectivePrice > 0) {
+ try {
+ const balance = await activeAdapter.fetchBalance();
+ const freeUSD = balance.free?.USD || balance.free?.USDT || 0;
+ const orderCost = orderAmount * effectivePrice;
+
+ if (orderCost > freeUSD) {
+ throw new Error(
+ `Insufficient balance. Order cost: $${orderCost.toFixed(2)}, Available: $${freeUSD.toFixed(2)}`
+ );
+ }
+ console.log(`[BrokerMCPBridge] Balance check passed: cost=$${orderCost.toFixed(2)}, available=$${freeUSD.toFixed(2)}`);
+ } catch (balanceError: any) {
+ if (balanceError.message.includes('Insufficient balance')) {
+ throw balanceError;
+ }
+ // Non-fatal: if balance fetch fails, let the broker reject it
+ console.warn(`[BrokerMCPBridge] Balance check skipped:`, balanceError.message);
+ }
+ }
+
const order = await activeAdapter.createOrder(
- params.symbol,
+ resolvedSymbol,
params.order_type || 'market',
params.side,
- params.amount || params.quantity,
- params.price,
+ orderAmount,
+ orderPrice,
{
stopPrice: params.stop_price,
...params
}
);
+
+ console.log(`[BrokerMCPBridge] Order executed:`, {
+ orderId: order.id,
+ symbol: order.symbol,
+ side: order.side,
+ type: order.type,
+ amount: order.amount,
+ price: order.price,
+ status: order.status
+ });
+
return {
success: true,
orderId: order.id,
- symbol: order.symbol,
+ symbol: order.symbol || resolvedSymbol,
+ resolvedFrom: params.symbol !== resolvedSymbol ? params.symbol : undefined,
side: order.side,
type: order.type,
amount: order.amount,
@@ -230,6 +628,90 @@ export class BrokerMCPBridge {
}
},
+ // Get quote/ticker for a symbol
+ getQuote: async (symbol: string) => {
+ try {
+ // Try direct fetch first
+ try {
+ const ticker = await activeAdapter.fetchTicker(symbol);
+ return ticker;
+ } catch {
+ // Try resolving the symbol
+ const resolved = await this.resolveSymbol(symbol);
+ const ticker = await activeAdapter.fetchTicker(resolved.symbol);
+ return { ...ticker, resolvedFrom: symbol, resolvedTo: resolved.symbol };
+ }
+ } catch (error: any) {
+ throw new Error(`Failed to get ticker for ${symbol}: ${error.message}`);
+ }
+ },
+
+ // Resolve symbol - fuzzy match crypto names/tickers to valid trading pairs
+ resolveSymbol: async (query: string) => {
+ return this.resolveSymbol(query);
+ },
+
+ // Search symbol - search ALL available markets dynamically
+ searchSymbol: async (query: string) => {
+ const markets = await this.getMarkets();
+ if (markets.length === 0) {
+ // Fallback: try resolve
+ try {
+ const resolved = await this.resolveSymbol(query);
+ return resolved.matches.map((s: string) => ({ symbol: s }));
+ } catch {
+ return [];
+ }
+ }
+
+ const searchLower = query.trim().toLowerCase();
+ const index = this.marketsIndex || new Map();
+
+ // 1. Exact index lookup first
+ const exactHits = index.get(searchLower);
+ if (exactHits && exactHits.length > 0) {
+ const sorted = this.sortByQuotePreference(exactHits);
+ return sorted.slice(0, 20).map(sym => {
+ const m = markets.find((mk: any) => mk.symbol === sym);
+ return { symbol: sym, base: m?.base, quote: m?.quote, active: m?.active ?? true };
+ });
+ }
+
+ // 2. Substring search across all keys in the index
+ const matchedSymbols: string[] = [];
+ for (const [key, symbols] of index) {
+ if (key.includes(searchLower) || searchLower.includes(key)) {
+ for (const s of symbols) {
+ if (!matchedSymbols.includes(s)) matchedSymbols.push(s);
+ }
+ }
+ }
+
+ // 3. Also search raw market fields (catches any fields not indexed)
+ for (const m of markets) {
+ if (!m.symbol || !m.active) continue;
+ if (matchedSymbols.includes(m.symbol)) continue;
+ const sym = (m.symbol as string).toLowerCase();
+ const base = (m.base || '').toLowerCase();
+ const baseId = (m.baseId || '').toLowerCase();
+ const altname = (m.info?.altname || '').toLowerCase();
+ const name = (m.info?.name || '').toLowerCase();
+ if (
+ sym.includes(searchLower) || base.includes(searchLower) ||
+ baseId.includes(searchLower) || altname.includes(searchLower) ||
+ name.includes(searchLower)
+ ) {
+ matchedSymbols.push(m.symbol);
+ }
+ }
+
+ const sorted = this.sortByQuotePreference(matchedSymbols);
+ return sorted.slice(0, 20).map(sym => {
+ const m = markets.find((mk: any) => mk.symbol === sym);
+ return { symbol: sym, base: m?.base, quote: m?.quote, active: m?.active ?? true };
+ });
+ },
+
// Close position
closePosition: async (symbol: string) => {
try {
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/crypto-trading.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/crypto-trading.ts
index ba943559c..4711244ca 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/tools/crypto-trading.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/crypto-trading.ts
@@ -5,25 +5,44 @@ export const cryptoTradingTools: InternalTool[] = [
// === ORDER MANAGEMENT ===
{
name: 'crypto_place_market_order',
- description: 'Place a market order for crypto (buy/sell at current market price)',
+ description: 'Place a market order for crypto (buy/sell at current market price). Supports auto symbol resolution — if the exact pair is not found, the system will try to resolve it (e.g., "bitcoin" → BTC/USD, "POL" → POL/USD). For ambiguous symbols, use crypto_resolve_symbol first and confirm with the user.',
inputSchema: {
type: 'object',
properties: {
- symbol: { type: 'string', description: 'Trading pair (e.g., BTC/USD, ETH/USDT)' },
+ symbol: { type: 'string', description: 'Trading pair (e.g., BTC/USD, ETH/USDT) or crypto name/ticker (e.g., bitcoin, POL). Auto-resolves to valid pair.' },
side: { type: 'string', description: 'Order side', enum: ['buy', 'sell'] },
amount: { type: 'number', description: 'Amount in base currency (e.g., 0.1 BTC)' },
+ quantity: { type: 'number', description: 'Quantity in base currency (alias for amount)' },
},
- required: ['symbol', 'side', 'amount'],
+ required: ['symbol', 'side'],
},
handler: async (args, contexts) => {
if (!contexts.placeTrade) {
return { success: false, error: 'Trading context not available. Ensure broker is connected.' };
}
- const result = await contexts.placeTrade({
- ...args,
- order_type: 'market',
- });
- return { success: true, data: result, message: `Market ${args.side} order placed: ${args.amount} ${args.symbol}` };
+ // Accept both 'amount' and 'quantity' (normalize to 'amount')
+ // Convert to number in case it's passed as string
+ const orderAmount = parseFloat(args.amount || args.quantity);
+ if (!orderAmount || isNaN(orderAmount) || orderAmount <= 0) {
+ return { success: false, error: 'Amount or quantity is required and must be a valid number greater than 0' };
+ }
+
+ try {
+ const result = await contexts.placeTrade({
+ symbol: args.symbol,
+ side: args.side,
+ amount: orderAmount,
+ order_type: 'market',
+ });
+ const resolvedInfo = result.resolvedFrom ? ` (resolved from "${result.resolvedFrom}")` : '';
+ return {
+ success: true,
+ data: result,
+ message: `Market ${args.side} order placed: ${orderAmount} ${result.symbol || args.symbol}${resolvedInfo}`,
+ };
+ } catch (error: any) {
+ return { success: false, error: error.message };
+ }
},
},
{
@@ -35,19 +54,34 @@ export const cryptoTradingTools: InternalTool[] = [
symbol: { type: 'string', description: 'Trading pair (e.g., BTC/USD, ETH/USDT)' },
side: { type: 'string', description: 'Order side', enum: ['buy', 'sell'] },
amount: { type: 'number', description: 'Amount in base currency' },
+ quantity: { type: 'number', description: 'Quantity in base currency (alias for amount)' },
price: { type: 'number', description: 'Limit price' },
},
- required: ['symbol', 'side', 'amount', 'price'],
+ required: ['symbol', 'side', 'price'],
},
handler: async (args, contexts) => {
if (!contexts.placeTrade) {
return { success: false, error: 'Trading context not available' };
}
+ // Accept both 'amount' and 'quantity', convert to number
+ const orderAmount = parseFloat(args.amount || args.quantity);
+ const limitPrice = parseFloat(args.price);
+
+ if (!orderAmount || isNaN(orderAmount) || orderAmount <= 0) {
+ return { success: false, error: 'Amount or quantity is required and must be a valid number greater than 0' };
+ }
+ if (!limitPrice || isNaN(limitPrice) || limitPrice <= 0) {
+ return { success: false, error: 'Price is required and must be a valid number greater than 0' };
+ }
+
const result = await contexts.placeTrade({
- ...args,
+ symbol: args.symbol,
+ side: args.side,
+ amount: orderAmount,
+ price: limitPrice,
order_type: 'limit',
});
- return { success: true, data: result, message: `Limit ${args.side} order placed: ${args.amount} ${args.symbol} @ ${args.price}` };
+ return { success: true, data: result, message: `Limit ${args.side} order placed: ${orderAmount} ${args.symbol} @ ${limitPrice}` };
},
},
{
@@ -68,11 +102,26 @@ export const cryptoTradingTools: InternalTool[] = [
if (!contexts.placeTrade) {
return { success: false, error: 'Trading context not available' };
}
+ const orderAmount = parseFloat(args.amount);
+ const stopPrice = parseFloat(args.stop_price);
+ const limitPrice = args.limit_price ? parseFloat(args.limit_price) : undefined;
+
+ if (!orderAmount || isNaN(orderAmount) || orderAmount <= 0) {
+ return { success: false, error: 'Amount is required and must be a valid number greater than 0' };
+ }
+ if (!stopPrice || isNaN(stopPrice) || stopPrice <= 0) {
+ return { success: false, error: 'Stop price is required and must be a valid number greater than 0' };
+ }
+
const result = await contexts.placeTrade({
- ...args,
- order_type: args.limit_price ? 'stop_limit' : 'stop',
+ symbol: args.symbol,
+ side: args.side,
+ amount: orderAmount,
+ stop_price: stopPrice,
+ limit_price: limitPrice,
+ order_type: limitPrice ? 'stop_limit' : 'stop',
});
- return { success: true, data: result, message: `Stop order placed: ${args.side} ${args.amount} ${args.symbol} @ stop ${args.stop_price}` };
+ return { success: true, data: result, message: `Stop order placed: ${args.side} ${orderAmount} ${args.symbol} @ stop ${stopPrice}` };
},
},
{
@@ -227,20 +276,24 @@ export const cryptoTradingTools: InternalTool[] = [
// === MARKET DATA ===
{
name: 'crypto_get_ticker',
- description: 'Get real-time ticker data for a crypto pair',
+ description: 'Get real-time ticker data for a crypto pair. Supports auto symbol resolution (e.g., "bitcoin" → BTC/USD).',
inputSchema: {
type: 'object',
properties: {
- symbol: { type: 'string', description: 'Trading pair (e.g., BTC/USD)' },
+ symbol: { type: 'string', description: 'Trading pair (e.g., BTC/USD) or crypto name/ticker' },
},
required: ['symbol'],
},
handler: async (args, contexts) => {
if (!contexts.getQuote) {
- return { success: false, error: 'Market data context not available' };
+ return { success: false, error: 'Market data context not available. Ensure broker is connected.' };
+ }
+ try {
+ const ticker = await contexts.getQuote(args.symbol);
+ return { success: true, data: ticker };
+ } catch (error: any) {
+ return { success: false, error: error.message };
}
- const ticker = await contexts.getQuote(args.symbol);
- return { success: true, data: ticker };
},
},
{
@@ -297,22 +350,70 @@ export const cryptoTradingTools: InternalTool[] = [
return { success: true, message: `${args.symbol} removed from watchlist` };
},
},
+ {
+ name: 'crypto_resolve_symbol',
+ description: 'Resolve a crypto name, ticker, or partial input to a valid trading pair with current price. Use this BEFORE placing an order when the user mentions a crypto by name (e.g., "bitcoin", "polygon", "solana") or uses an ambiguous symbol. Returns the resolved trading pair, current price, and any alternative matches. You MUST confirm the resolved symbol with the user before placing the order.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Crypto name, ticker, or partial symbol to resolve (e.g., "bitcoin", "POL", "ETH/USD", "solana")' },
+ },
+ required: ['query'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.resolveSymbol) {
+ return { success: false, error: 'Symbol resolution not available. Ensure broker is connected.' };
+ }
+ try {
+ const result = await contexts.resolveSymbol(args.query);
+ return {
+ success: true,
+ data: {
+ resolved_symbol: result.symbol,
+ current_price: result.price || null,
+ alternative_matches: result.matches || [],
+ query: args.query,
+ },
+ message: result.price
+ ? `Resolved "${args.query}" → ${result.symbol} (current price: $${result.price.toFixed(2)}). Please confirm with the user before placing the order.`
+ : `Resolved "${args.query}" → ${result.symbol}. Price unavailable — confirm with user before proceeding.`,
+ };
+ } catch (error: any) {
+ return {
+ success: false,
+ error: error.message,
+ suggestion: 'Try a more specific query like "BTC/USD" or a full crypto name like "bitcoin".',
+ };
+ }
+ },
+ },
{
name: 'crypto_search_symbol',
- description: 'Search for crypto trading pairs by keyword',
+ description: 'Search for available crypto trading pairs by keyword. Returns a list of matching pairs from the connected exchange.',
inputSchema: {
type: 'object',
properties: {
- query: { type: 'string', description: 'Search query (e.g., BTC, ethereum)' },
+ query: { type: 'string', description: 'Search query (e.g., BTC, ethereum, sol)' },
},
required: ['query'],
},
handler: async (args, contexts) => {
if (!contexts.searchSymbol) {
- return { success: false, error: 'Search context not available' };
+ return { success: false, error: 'Search context not available. Ensure broker is connected.' };
+ }
+ try {
+ const results = await contexts.searchSymbol(args.query);
+ return {
+ success: true,
+ data: results,
+ count: results.length,
+ message: results.length > 0
+ ? `Found ${results.length} matching pairs for "${args.query}".`
+ : `No matching pairs found for "${args.query}". Try a different search term.`,
+ };
+ } catch (error: any) {
+ return { success: false, error: error.message };
}
- const results = await contexts.searchSymbol(args.query);
- return { success: true, data: results };
},
},
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts
index 5d181d9da..569ea2db8 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts
@@ -157,4 +157,454 @@ export const navigationTools: InternalTool[] = [
return { success: true, message: 'Navigated to Markets tab' };
},
},
+ {
+ name: 'open_dashboard_tab',
+ description: 'Navigate to the Dashboard tab - the main overview page with customizable widgets showing portfolio summary, market overview, and key metrics',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('dashboard');
+ return { success: true, message: 'Navigated to Dashboard tab' };
+ },
+ },
+ {
+ name: 'open_watchlist_tab',
+ description: 'Navigate to the Watchlist tab to view and manage custom ticker watchlists with real-time price updates',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('watchlist');
+ return { success: true, message: 'Navigated to Watchlist tab' };
+ },
+ },
+ {
+ name: 'open_research_tab',
+ description: 'Navigate to the Equity Research tab for fundamental analysis, company research, financial statements, and stock valuation',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('research');
+ return { success: true, message: 'Navigated to Equity Research tab' };
+ },
+ },
+ {
+ name: 'open_economics_tab',
+ description: 'Navigate to the Economics tab to view economic indicators, central bank data, GDP, inflation, unemployment, and macroeconomic analysis',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('economics');
+ return { success: true, message: 'Navigated to Economics tab' };
+ },
+ },
+ {
+ name: 'open_dbnomics_tab',
+ description: 'Navigate to the DBnomics tab for comprehensive economic database access with 1000+ providers and millions of time series',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('dbnomics');
+ return { success: true, message: 'Navigated to DBnomics tab' };
+ },
+ },
+ {
+ name: 'open_geopolitics_tab',
+ description: 'Navigate to the Geopolitics tab for geopolitical analysis, risk assessment, global events tracking, and international relations impact on markets',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('geopolitics');
+ return { success: true, message: 'Navigated to Geopolitics tab' };
+ },
+ },
+ {
+ name: 'open_maritime_tab',
+ description: 'Navigate to the Maritime tab for shipping routes, port activity, maritime trade data, and supply chain tracking',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('maritime');
+ return { success: true, message: 'Navigated to Maritime tab' };
+ },
+ },
+ {
+ name: 'open_screener_tab',
+ description: 'Navigate to the Screener tab for stock screening, filtering tools, and custom criteria-based stock discovery',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('screener');
+ return { success: true, message: 'Navigated to Screener tab' };
+ },
+ },
+ {
+ name: 'open_chat_tab',
+ description: 'Navigate to the AI Chat tab for conversational AI assistant with market analysis, research, and terminal automation capabilities',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('chat');
+ return { success: true, message: 'Navigated to AI Chat tab' };
+ },
+ },
+ {
+ name: 'open_docs_tab',
+ description: 'Navigate to the Documentation tab for terminal guides, API reference, tutorials, and help documentation',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('docs');
+ return { success: true, message: 'Navigated to Documentation tab' };
+ },
+ },
+ {
+ name: 'open_nodes_tab',
+ description: 'Navigate to the Node Editor tab for visual workflow creation, automation pipelines, and no-code data processing',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('nodes');
+ return { success: true, message: 'Navigated to Node Editor tab' };
+ },
+ },
+ {
+ name: 'open_code_tab',
+ description: 'Navigate to the Code Editor tab for writing and executing custom trading scripts, strategies, and analytics code',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('code');
+ return { success: true, message: 'Navigated to Code Editor tab' };
+ },
+ },
+ {
+ name: 'open_forum_tab',
+ description: 'Navigate to the Forum tab for community discussions, trading ideas, and collaboration with other traders',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('forum');
+ return { success: true, message: 'Navigated to Forum tab' };
+ },
+ },
+ {
+ name: 'open_marketplace_tab',
+ description: 'Navigate to the Marketplace tab to browse and install extensions, indicators, strategies, and premium features',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('marketplace');
+ return { success: true, message: 'Navigated to Marketplace tab' };
+ },
+ },
+ {
+ name: 'open_profile_tab',
+ description: 'Navigate to the Profile tab for user account settings, subscription management, and personal information',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('profile');
+ return { success: true, message: 'Navigated to Profile tab' };
+ },
+ },
+ {
+ name: 'open_support_tab',
+ description: 'Navigate to the Support tab to create support tickets, track issues, and get help from the Fincept team',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('support');
+ return { success: true, message: 'Navigated to Support tab' };
+ },
+ },
+ {
+ name: 'open_settings_tab',
+ description: 'Navigate to the Settings tab for terminal configuration, API credentials, themes, language, and preferences',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('settings');
+ return { success: true, message: 'Navigated to Settings tab' };
+ },
+ },
+ {
+ name: 'open_backtesting_tab',
+ description: 'Navigate to the Backtesting tab for strategy backtesting, optimization, walk-forward analysis, and performance metrics',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('backtesting');
+ return { success: true, message: 'Navigated to Backtesting tab' };
+ },
+ },
+ {
+ name: 'open_mcp_tab',
+ description: 'Navigate to the MCP Servers tab for Model Context Protocol server management, tool discovery, and integration configuration',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('mcp');
+ return { success: true, message: 'Navigated to MCP Servers tab' };
+ },
+ },
+ {
+ name: 'open_reportbuilder_tab',
+ description: 'Navigate to the Report Builder tab for creating professional investment reports, presentations, and research documents',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('reportbuilder');
+ return { success: true, message: 'Navigated to Report Builder tab' };
+ },
+ },
+ {
+ name: 'open_equity_trading_tab',
+ description: 'Navigate to the Equity Trading tab for stock trading with broker integration, order placement, and position management',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('equity-trading');
+ return { success: true, message: 'Navigated to Equity Trading tab' };
+ },
+ },
+ {
+ name: 'open_datasources_tab',
+ description: 'Navigate to the Data Sources tab for managing data connections, API integrations, databases, and data feeds',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('datasources');
+ return { success: true, message: 'Navigated to Data Sources tab' };
+ },
+ },
+ {
+ name: 'open_ai_quant_lab_tab',
+ description: 'Navigate to the AI Quant Lab tab for machine learning, quantitative research, AI-powered trading strategies, and advanced analytics',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('ai-quant-lab');
+ return { success: true, message: 'Navigated to AI Quant Lab tab' };
+ },
+ },
+ {
+ name: 'open_notes_tab',
+ description: 'Navigate to the Notes tab for creating and managing trading notes, market observations, and research documentation',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('notes');
+ return { success: true, message: 'Navigated to Notes tab' };
+ },
+ },
+ {
+ name: 'open_agents_tab',
+ description: 'Navigate to the Agents tab for configuring AI trading agents, investor personas, and automated decision-making systems',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('agents');
+ return { success: true, message: 'Navigated to Agents tab' };
+ },
+ },
+ {
+ name: 'open_monitoring_tab',
+ description: 'Navigate to the Monitoring tab for real-time system monitoring, alerts, performance tracking, and diagnostics',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('monitoring');
+ return { success: true, message: 'Navigated to Monitoring tab' };
+ },
+ },
+ {
+ name: 'open_polymarket_tab',
+ description: 'Navigate to the Polymarket tab for prediction markets, event contracts, and decentralized forecasting',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('polymarket');
+ return { success: true, message: 'Navigated to Polymarket tab' };
+ },
+ },
+ {
+ name: 'open_derivatives_tab',
+ description: 'Navigate to the Derivatives tab for options, futures, swaps trading and analysis with Greeks calculation and risk metrics',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('derivatives');
+ return { success: true, message: 'Navigated to Derivatives tab' };
+ },
+ },
+ {
+ name: 'open_asia_markets_tab',
+ description: 'Navigate to the Asia Markets tab for Asian stock exchanges, market data, and regional trading opportunities',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('asia-markets');
+ return { success: true, message: 'Navigated to Asia Markets tab' };
+ },
+ },
+ {
+ name: 'open_akshare_tab',
+ description: 'Navigate to the AKShare Data tab for comprehensive Chinese financial data, A-shares, and Asian market datasets',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('akshare');
+ return { success: true, message: 'Navigated to AKShare Data tab' };
+ },
+ },
];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/types.ts b/fincept-terminal-desktop/src/services/mcp/internal/types.ts
index f9cd02008..cabcdbfcc 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/types.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/types.ts
@@ -24,6 +24,8 @@ export interface InternalToolResult {
data?: any;
message?: string;
error?: string;
+ suggestion?: string;
+ count?: number;
// Additional metadata for financial tools
chart_data?: any;
ticker?: string;
@@ -127,6 +129,7 @@ export interface TerminalContexts {
addToWatchlist?: (symbol: string) => Promise<void>;
removeFromWatchlist?: (symbol: string) => Promise<void>;
searchSymbol?: (query: string) => Promise<any[]>;
+ resolveSymbol?: (query: string) => Promise<{ symbol: string; price?: number; matches: string[] }>;
// Workflow
createWorkflow?: (params: any) => Promise<any>;
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/NodeLoader.ts b/fincept-terminal-desktop/src/services/nodeSystem/NodeLoader.ts
index 903917b4d..08cdff516 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/NodeLoader.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/NodeLoader.ts
@@ -11,15 +11,8 @@
import { NodeRegistry } from './NodeRegistry';
import { INodeType } from './types';
-// Import finance nodes
-import { StockDataNode } from '../../nodes/finance/StockData.node';
-
// Import core nodes
-import { FilterNode as CoreFilterNode } from '../../nodes/core/Filter.node';
-import { MergeNode as CoreMergeNode } from '../../nodes/core/Merge.node';
-import { SetNode } from '../../nodes/core/Set.node';
-import { SwitchNode as CoreSwitchNode } from '../../nodes/core/Switch.node';
-import { CodeNode as CoreCodeNode } from '../../nodes/core/Code.node';
+import { SetNode, CodeNode } from './nodes/core';
// Import analytics nodes
import {
@@ -34,9 +27,7 @@ import {
// Import market data nodes
import {
- YFinanceNode,
GetQuoteNode,
- GetHistoricalDataNode,
GetMarketDepthNode,
StreamQuotesNode,
GetFundamentalsNode,
@@ -177,34 +168,19 @@ class NodeLoaderClass {
/**
* Load core nodes (basic workflow nodes)
+ * Note: Filter, Merge, Switch are now in transform/controlFlow - removed duplicates
*/
private async loadCoreNodes(): Promise<void> {
-
try {
- // Filter Node - Remove items based on conditions
- const filterNode = new CoreFilterNode();
- NodeRegistry.registerNodeType(filterNode, 'CoreFilterNode');
- this.loadedNodes.set('filter', filterNode);
-
- // Merge Node - Combine data from multiple inputs
- const mergeNode = new CoreMergeNode();
- NodeRegistry.registerNodeType(mergeNode, 'CoreMergeNode');
- this.loadedNodes.set('coreMerge', mergeNode);
-
- // Set Node - Add/edit/remove fields
- const setNode = new SetNode();
- NodeRegistry.registerNodeType(setNode, 'SetNode');
- this.loadedNodes.set('set', setNode);
-
- // Switch Node - Route items based on conditions
- const switchNode = new CoreSwitchNode();
- NodeRegistry.registerNodeType(switchNode, 'CoreSwitchNode');
- this.loadedNodes.set('coreSwitch', switchNode);
-
- // Code Node - Execute custom JavaScript
- const codeNode = new CoreCodeNode();
- NodeRegistry.registerNodeType(codeNode, 'CoreCodeNode');
- this.loadedNodes.set('coreCode', codeNode);
+ const nodes = [
+ { instance: new SetNode(), name: 'SetNode' },
+ { instance: new CodeNode(), name: 'CodeNode' },
+ ];
+
+ for (const { instance, name } of nodes) {
+ NodeRegistry.registerNodeType(instance, name);
+ this.loadedNodes.set(instance.description.name, instance);
+ }
} catch (error) {
console.error('[NodeLoader] Error loading core nodes:', error);
}
@@ -212,27 +188,10 @@ class NodeLoaderClass {
/**
* Load finance-specific nodes
+ * Note: StockData removed - use GetQuote, GetFundamentals instead
*/
private async loadFinanceNodes(): Promise<void> {
-
- try {
- // Stock Data Node
- const stockDataNode = new StockDataNode();
- NodeRegistry.registerNodeType(stockDataNode, 'StockDataNode');
- this.loadedNodes.set('stockData', stockDataNode);
-
- // More finance nodes will be added:
- // - TechnicalIndicators Node
- // - PortfolioOptimizer Node
- // - RiskCalculator Node
- // - BacktestStrategy Node
- // - OptionsAnalysis Node
- // - FundamentalAnalysis Node
- // - SentimentAnalysis Node
- // - EconomicData Node
- } catch (error) {
- console.error('[NodeLoader] Error loading finance nodes:', error);
- }
+ // Finance nodes are now loaded via analytics and marketData categories
}
/**
@@ -297,9 +256,7 @@ class NodeLoaderClass {
try {
const nodes = [
- { instance: new YFinanceNode(), name: 'YFinanceNode' },
{ instance: new GetQuoteNode(), name: 'GetQuoteNode' },
- { instance: new GetHistoricalDataNode(), name: 'GetHistoricalDataNode' },
{ instance: new GetMarketDepthNode(), name: 'GetMarketDepthNode' },
{ instance: new StreamQuotesNode(), name: 'StreamQuotesNode' },
{ instance: new GetFundamentalsNode(), name: 'GetFundamentalsNode' },
diff --git a/fincept-terminal-desktop/src/nodes/core/Code.node.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/core/CodeNode.ts
similarity index 99%
rename from fincept-terminal-desktop/src/nodes/core/Code.node.ts
rename to fincept-terminal-desktop/src/services/nodeSystem/nodes/core/CodeNode.ts
index 678b1a1bc..c472c1d2a 100644
--- a/fincept-terminal-desktop/src/nodes/core/Code.node.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/nodes/core/CodeNode.ts
@@ -18,7 +18,7 @@ import {
NodePropertyType,
IDataObject,
INodeExecutionData,
-} from '../../services/nodeSystem/types';
+} from '../../types';
export class CodeNode implements INodeType {
description: INodeTypeDescription = {
diff --git a/fincept-terminal-desktop/src/nodes/core/Set.node.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/core/SetNode.ts
similarity index 99%
rename from fincept-terminal-desktop/src/nodes/core/Set.node.ts
rename to fincept-terminal-desktop/src/services/nodeSystem/nodes/core/SetNode.ts
index 74be65224..1d93f780b 100644
--- a/fincept-terminal-desktop/src/nodes/core/Set.node.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/nodes/core/SetNode.ts
@@ -18,7 +18,7 @@ import {
NodeConnectionType,
NodePropertyType,
IDataObject,
-} from '../../services/nodeSystem/types';
+} from '../../types';
export class SetNode implements INodeType {
description: INodeTypeDescription = {
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/nodes/core/index.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/core/index.ts
new file mode 100644
index 000000000..5b046e8e1
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/nodes/core/index.ts
@@ -0,0 +1,22 @@
+/**
+ * Core Nodes Index
+ * Basic workflow utility nodes
+ */
+
+export * from './CodeNode';
+export * from './SetNode';
+
+import { CodeNode } from './CodeNode';
+import { SetNode } from './SetNode';
+
+export const CoreNodes = {
+ CodeNode,
+ SetNode,
+};
+
+export const CoreNodeTypes = [
+ 'code',
+ 'set',
+] as const;
+
+export type CoreNodeType = typeof CoreNodeTypes[number];
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/GetHistoricalDataNode.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/GetHistoricalDataNode.ts
deleted file mode 100644
index c880193db..000000000
--- a/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/GetHistoricalDataNode.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-/**
- * Get Historical Data Node
- * Fetches OHLCV historical price data for symbols
- */
-
-import {
- INodeType,
- INodeTypeDescription,
- IExecuteFunctions,
- NodeOutput,
- NodeConnectionType,
- NodePropertyType,
-} from '../../types';
-import { MarketDataBridge } from '../../adapters/MarketDataBridge';
-
-export class GetHistoricalDataNode implements INodeType {
- description: INodeTypeDescription = {
- displayName: 'Get Historical Data',
- name: 'getHistoricalData',
- icon: 'file:chart.svg',
- group: ['marketData'],
- version: 1,
- subtitle: '={{$parameter["symbol"]}} {{$parameter["interval"]}}',
- description: 'Fetches historical OHLCV price data',
- defaults: {
- name: 'Historical Data',
- color: '#10b981',
- },
- inputs: [NodeConnectionType.Main],
- outputs: [NodeConnectionType.Main],
- properties: [
- {
- displayName: 'Symbol',
- name: 'symbol',
- type: NodePropertyType.String,
- default: '',
- required: true,
- placeholder: 'AAPL',
- description: 'Symbol to fetch historical data for',
- },
- {
- displayName: 'Use Input Symbol',
- name: 'useInputSymbol',
- type: NodePropertyType.Boolean,
- default: false,
- description: 'Use symbol from input data',
- },
- {
- displayName: 'Interval',
- name: 'interval',
- type: NodePropertyType.Options,
- default: '1d',
- options: [
- { name: '1 Minute', value: '1m' },
- { name: '5 Minutes', value: '5m' },
- { name: '15 Minutes', value: '15m' },
- { name: '30 Minutes', value: '30m' },
- { name: '1 Hour', value: '1h' },
- { name: '4 Hours', value: '4h' },
- { name: '1 Day', value: '1d' },
- { name: '1 Week', value: '1wk' },
- { name: '1 Month', value: '1mo' },
- ],
- description: 'Time interval for candles',
- },
- {
- displayName: 'Period Type',
- name: 'periodType',
- type: NodePropertyType.Options,
- default: 'preset',
- options: [
- { name: 'Preset Period', value: 'preset' },
- { name: 'Custom Date Range', value: 'custom' },
- { name: 'Last N Bars', value: 'bars' },
- ],
- description: 'How to specify the time period',
- },
- {
- displayName: 'Period',
- name: 'period',
- type: NodePropertyType.Options,
- default: '1mo',
- options: [
- { name: '1 Day', value: '1d' },
- { name: '5 Days', value: '5d' },
- { name: '1 Month', value: '1mo' },
- { name: '3 Months', value: '3mo' },
- { name: '6 Months', value: '6mo' },
- { name: '1 Year', value: '1y' },
- { name: '2 Years', value: '2y' },
- { name: '5 Years', value: '5y' },
- { name: '10 Years', value: '10y' },
- { name: 'Year to Date', value: 'ytd' },
- { name: 'Max', value: 'max' },
- ],
- description: 'Preset time period',
- displayOptions: {
- show: { periodType: ['preset'] },
- },
- },
- {
- displayName: 'Start Date',
- name: 'startDate',
- type: NodePropertyType.String,
- default: '',
- placeholder: '2024-01-01',
- description: 'Start date (YYYY-MM-DD)',
- displayOptions: {
- show: { periodType: ['custom'] },
- },
- },
- {
- displayName: 'End Date',
- name: 'endDate',
- type: NodePropertyType.String,
- default: '',
- placeholder: '2024-12-31',
- description: 'End date (YYYY-MM-DD)',
- displayOptions: {
- show: { periodType: ['custom'] },
- },
- },
- {
- displayName: 'Number of Bars',
- name: 'numBars',
- type: NodePropertyType.Number,
- default: 100,
- description: 'Number of historical bars to fetch',
- displayOptions: {
- show: { periodType: ['bars'] },
- },
- },
- {
- displayName: 'Data Provider',
- name: 'provider',
- type: NodePropertyType.Options,
- default: 'yahoo',
- options: [
- { name: 'Yahoo Finance', value: 'yahoo' },
- { name: 'Alpha Vantage', value: 'alphavantage' },
- { name: 'Twelve Data', value: 'twelvedata' },
- { name: 'Binance', value: 'binance' },
- { name: 'Kraken', value: 'kraken' },
- ],
- description: 'Market data provider',
- },
- {
- displayName: 'Include Extended Hours',
- name: 'includeExtendedHours',
- type: NodePropertyType.Boolean,
- default: false,
- description: 'Include pre-market and after-hours data',
- },
- {
- displayName: 'Adjust for Splits',
- name: 'adjustForSplits',
- type: NodePropertyType.Boolean,
- default: true,
- description: 'Adjust prices for stock splits',
- },
- {
- displayName: 'Adjust for Dividends',
- name: 'adjustForDividends',
- type: NodePropertyType.Boolean,
- default: true,
- description: 'Adjust prices for dividends',
- },
- {
- displayName: 'Output Format',
- name: 'outputFormat',
- type: NodePropertyType.Options,
- default: 'array',
- options: [
- { name: 'Array of Candles', value: 'array' },
- { name: 'Single Object with Arrays', value: 'object' },
- { name: 'Latest Bar Only', value: 'latest' },
- ],
- description: 'How to format the output data',
- },
- ],
- };
-
- async execute(this: IExecuteFunctions): Promise<NodeOutput> {
- const useInputSymbol = this.getNodeParameter('useInputSymbol', 0) as boolean;
- const interval = this.getNodeParameter('interval', 0) as string;
- const periodType = this.getNodeParameter('periodType', 0) as string;
- const provider = this.getNodeParameter('provider', 0) as string;
- const outputFormat = this.getNodeParameter('outputFormat', 0) as string;
- const adjustForSplits = this.getNodeParameter('adjustForSplits', 0) as boolean;
- const adjustForDividends = this.getNodeParameter('adjustForDividends', 0) as boolean;
-
- let symbol: string;
-
- if (useInputSymbol) {
- const inputData = this.getInputData();
- symbol = inputData[0]?.json?.symbol as string || '';
- } else {
- symbol = this.getNodeParameter('symbol', 0) as string;
- }
-
- if (!symbol) {
- return [[{
- json: {
- error: 'No symbol provided',
- timestamp: new Date().toISOString(),
- },
- }]];
- }
-
- // Build period configuration
- let period: string | undefined;
- let startDate: string | undefined;
- let endDate: string | undefined;
- let numBars: number | undefined;
-
- switch (periodType) {
- case 'preset':
- period = this.getNodeParameter('period', 0) as string;
- break;
- case 'custom':
- startDate = this.getNodeParameter('startDate', 0) as string;
- endDate = this.getNodeParameter('endDate', 0) as string;
- break;
- case 'bars':
- numBars = this.getNodeParameter('numBars', 0) as number;
- break;
- }
-
- // Fetch historical data using the bridge
-
-
- try {
- const data = await MarketDataBridge.getHistoricalData({
- symbol,
- interval,
- period,
- startDate,
- endDate,
- provider,
- });
-
- const candles = data || [];
-
- // Format output based on preference
- switch (outputFormat) {
- case 'latest':
- if (candles.length === 0) {
- return [[{
- json: {
- symbol,
- error: 'No data available',
- timestamp: new Date().toISOString(),
- },
- }]];
- }
- const latest = candles[candles.length - 1];
- return [[{
- json: {
- symbol,
- ...latest,
- interval,
- provider,
- fetchedAt: new Date().toISOString(),
- },
- }]];
-
- case 'object':
- return [[{
- json: {
- symbol,
- interval,
- period: period || `${startDate} to ${endDate}`,
- totalBars: candles.length,
- timestamps: candles.map((c: any) => c.timestamp),
- open: candles.map((c: any) => c.open),
- high: candles.map((c: any) => c.high),
- low: candles.map((c: any) => c.low),
- close: candles.map((c: any) => c.close),
- volume: candles.map((c: any) => c.volume),
- provider,
- adjustedForSplits: adjustForSplits,
- adjustedForDividends: adjustForDividends,
- fetchedAt: new Date().toISOString(),
- },
- }]];
-
- case 'array':
- default:
- return [candles.map((candle: any) => ({
- json: {
- symbol,
- ...candle,
- interval,
- provider,
- },
- }))];
- }
- } catch (error) {
- return [[{
- json: {
- symbol,
- error: error instanceof Error ? error.message : 'Unknown error',
- timestamp: new Date().toISOString(),
- },
- }]];
- }
- }
-}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/YFinanceNode.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/YFinanceNode.ts
deleted file mode 100644
index 502faf074..000000000
--- a/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/YFinanceNode.ts
+++ /dev/null
@@ -1,345 +0,0 @@
-/**
- * YFinance Data Source Node
- * Comprehensive Yahoo Finance data fetching with all yfinance features
- */
-
-import {
- INodeType,
- INodeTypeDescription,
- IExecuteFunctions,
- NodeOutput,
- NodeConnectionType,
- NodePropertyType,
-} from '../../types';
-
-export class YFinanceNode implements INodeType {
- description: INodeTypeDescription = {
- displayName: 'Yahoo Finance',
- name: 'yfinance',
- icon: 'fa:yahoo',
- iconColor: '#7B0099',
- group: ['marketData'],
- version: 1,
- subtitle: '={{$parameter["operation"]}} - {{$parameter["symbol"]}}',
- description: 'Fetch comprehensive market data from Yahoo Finance',
- defaults: {
- name: 'Yahoo Finance',
- color: '#7B0099',
- },
- inputs: [NodeConnectionType.Main],
- outputs: [NodeConnectionType.Main],
- properties: [
- {
- displayName: 'Operation',
- name: 'operation',
- type: NodePropertyType.Options,
- options: [
- { name: 'Get Historical Data', value: 'history' },
- { name: 'Get Quote', value: 'quote' },
- { name: 'Get Info', value: 'info' },
- { name: 'Get Financials', value: 'financials' },
- { name: 'Get Balance Sheet', value: 'balanceSheet' },
- { name: 'Get Cash Flow', value: 'cashFlow' },
- { name: 'Get Earnings', value: 'earnings' },
- { name: 'Get Dividends', value: 'dividends' },
- { name: 'Get Splits', value: 'splits' },
- { name: 'Get Actions', value: 'actions' },
- { name: 'Get Recommendations', value: 'recommendations' },
- { name: 'Get Options Chain', value: 'options' },
- { name: 'Get Institutional Holders', value: 'institutionalHolders' },
- { name: 'Get Major Holders', value: 'majorHolders' },
- { name: 'Get Sustainability', value: 'sustainability' },
- ],
- default: 'history',
- description: 'Type of data to fetch from Yahoo Finance',
- },
- {
- displayName: 'Symbol',
- name: 'symbol',
- type: NodePropertyType.String,
- default: '',
- required: true,
- placeholder: 'AAPL',
- description: 'Stock ticker symbol',
- },
- {
- displayName: 'Use Input Symbol',
- name: 'useInputSymbol',
- type: NodePropertyType.Boolean,
- default: false,
- description: 'Use symbol from input data instead',
- },
-
- // Historical Data Parameters
- {
- displayName: 'Period',
- name: 'period',
- type: NodePropertyType.Options,
- options: [
- { name: '1 Day', value: '1d' },
- { name: '5 Days', value: '5d' },
- { name: '1 Month', value: '1mo' },
- { name: '3 Months', value: '3mo' },
- { name: '6 Months', value: '6mo' },
- { name: '1 Year', value: '1y' },
- { name: '2 Years', value: '2y' },
- { name: '5 Years', value: '5y' },
- { name: '10 Years', value: '10y' },
- { name: 'Year to Date', value: 'ytd' },
- { name: 'Max', value: 'max' },
- ],
- default: '1mo',
- description: 'Historical period to fetch',
- displayOptions: {
- show: {
- operation: ['history'],
- },
- },
- },
- {
- displayName: 'Interval',
- name: 'interval',
- type: NodePropertyType.Options,
- options: [
- { name: '1 Minute', value: '1m' },
- { name: '2 Minutes', value: '2m' },
- { name: '5 Minutes', value: '5m' },
- { name: '15 Minutes', value: '15m' },
- { name: '30 Minutes', value: '30m' },
- { name: '60 Minutes', value: '60m' },
- { name: '90 Minutes', value: '90m' },
- { name: '1 Hour', value: '1h' },
- { name: '1 Day', value: '1d' },
- { name: '5 Days', value: '5d' },
- { name: '1 Week', value: '1wk' },
- { name: '1 Month', value: '1mo' },
- { name: '3 Months', value: '3mo' },
- ],
- default: '1d',
- description: 'Data interval/timeframe',
- displayOptions: {
- show: {
- operation: ['history'],
- },
- },
- },
- {
- displayName: 'Start Date',
- name: 'startDate',
- type: NodePropertyType.String,
- default: '',
- placeholder: '2024-01-01',
- description: 'Start date (YYYY-MM-DD) - overrides period',
- displayOptions: {
- show: {
- operation: ['history'],
- },
- },
- },
- {
- displayName: 'End Date',
- name: 'endDate',
- type: NodePropertyType.String,
- default: '',
- placeholder: '2024-12-31',
- description: 'End date (YYYY-MM-DD) - overrides period',
- displayOptions: {
- show: {
- operation: ['history'],
- },
- },
- },
- {
- displayName: 'Prepost',
- name: 'prepost',
- type: NodePropertyType.Boolean,
- default: false,
- description: 'Include pre and post market data',
- displayOptions: {
- show: {
- operation: ['history'],
- },
- },
- },
- {
- displayName: 'Auto Adjust',
- name: 'autoAdjust',
- type: NodePropertyType.Boolean,
- default: true,
- description: 'Adjust all OHLC automatically',
- displayOptions: {
- show: {
- operation: ['history'],
- },
- },
- },
- {
- displayName: 'Actions',
- name: 'actions',
- type: NodePropertyType.Boolean,
- default: true,
- description: 'Download stock dividends and stock splits events',
- displayOptions: {
- show: {
- operation: ['history'],
- },
- },
- },
-
- // Financials Parameters
- {
- displayName: 'Frequency',
- name: 'frequency',
- type: NodePropertyType.Options,
- options: [
- { name: 'Annual', value: 'annual' },
- { name: 'Quarterly', value: 'quarterly' },
- ],
- default: 'annual',
- description: 'Financial statement frequency',
- displayOptions: {
- show: {
- operation: ['financials', 'balanceSheet', 'cashFlow'],
- },
- },
- },
-
- // Options Parameters
- {
- displayName: 'Expiration Date',
- name: 'expirationDate',
- type: NodePropertyType.String,
- default: '',
- placeholder: '2024-12-20 or leave empty for nearest',
- description: 'Options expiration date (YYYY-MM-DD)',
- displayOptions: {
- show: {
- operation: ['options'],
- },
- },
- },
- {
- displayName: 'Options Type',
- name: 'optionsType',
- type: NodePropertyType.Options,
- options: [
- { name: 'Both', value: 'both' },
- { name: 'Calls', value: 'calls' },
- { name: 'Puts', value: 'puts' },
- ],
- default: 'both',
- description: 'Type of options to fetch',
- displayOptions: {
- show: {
- operation: ['options'],
- },
- },
- },
-
- // Output Format
- {
- displayName: 'Output Format',
- name: 'outputFormat',
- type: NodePropertyType.Options,
- options: [
- { name: 'Array (One Item Per Row)', value: 'array' },
- { name: 'Single Object', value: 'object' },
- ],
- default: 'array',
- description: 'How to format the output data',
- },
- ],
- };
-
- async execute(this: IExecuteFunctions): Promise<NodeOutput> {
- // Import Tauri invoke at runtime
- const { invoke } = await import('@tauri-apps/api/core');
-
- const items = this.getInputData();
- const operation = this.getNodeParameter('operation', 0) as string;
- const useInputSymbol = this.getNodeParameter('useInputSymbol', 0) as boolean;
- const outputFormat = this.getNodeParameter('outputFormat', 0) as string;
-
- let symbol: string;
- if (useInputSymbol && items.length > 0) {
- symbol = items[0].json.symbol as string || '';
- } else {
- symbol = this.getNodeParameter('symbol', 0) as string;
- }
-
- if (!symbol) {
- return [[{
- json: {
- error: 'No symbol provided',
- timestamp: new Date().toISOString(),
- },
- }]];
- }
-
- try {
- // Build Python script arguments based on operation
- const args: string[] = [symbol, operation];
-
- // Add operation-specific parameters
- if (operation === 'history') {
- const period = this.getNodeParameter('period', 0) as string;
- const interval = this.getNodeParameter('interval', 0) as string;
- const startDate = this.getNodeParameter('startDate', 0, '') as string;
- const endDate = this.getNodeParameter('endDate', 0, '') as string;
- const prepost = this.getNodeParameter('prepost', 0) as boolean;
- const autoAdjust = this.getNodeParameter('autoAdjust', 0) as boolean;
- const actions = this.getNodeParameter('actions', 0) as boolean;
-
- if (startDate && endDate) {
- args.push('--start', startDate, '--end', endDate);
- } else {
- args.push('--period', period);
- }
- args.push('--interval', interval);
- if (prepost) args.push('--prepost', 'true');
- if (!autoAdjust) args.push('--auto_adjust', 'false');
- if (!actions) args.push('--actions', 'false');
- } else if (['financials', 'balanceSheet', 'cashFlow'].includes(operation)) {
- const frequency = this.getNodeParameter('frequency', 0) as string;
- args.push(frequency);
- } else if (operation === 'options') {
- const expirationDate = this.getNodeParameter('expirationDate', 0, '') as string;
- if (expirationDate) args.push(expirationDate);
- }
-
- // Execute Python script
- const result = await invoke('execute_python_command', {
- script: 'yfinance_comprehensive.py',
- args,
- });
-
- // Parse result
- const data = typeof result === 'string' ? JSON.parse(result) : result;
-
- // Check for errors
- if (data.error) {
- throw new Error(data.error);
- }
-
- // Format output
- if (outputFormat === 'object' || !Array.isArray(data)) {
- return [[{ json: { symbol, operation, data, timestamp: new Date().toISOString() } }]];
- } else {
- return [data.map((item: any) => ({ json: { symbol, operation, ...item } }))];
- }
- } catch (error) {
- if (this.continueOnFail()) {
- return [[{
- json: {
- symbol,
- operation,
- error: error instanceof Error ? error.message : 'Unknown error',
- timestamp: new Date().toISOString(),
- },
- }]];
- }
- throw error;
- }
- }
-
-}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/index.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/index.ts
index 7f1fab023..38a357cf5 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/index.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/index.ts
@@ -4,40 +4,32 @@
*/
export * from './GetQuoteNode';
-export * from './GetHistoricalDataNode';
export * from './GetMarketDepthNode';
export * from './StreamQuotesNode';
export * from './GetFundamentalsNode';
export * from './GetTickerStatsNode';
-export * from './YFinanceNode';
// Re-export for convenience
import { GetQuoteNode } from './GetQuoteNode';
-import { GetHistoricalDataNode } from './GetHistoricalDataNode';
import { GetMarketDepthNode } from './GetMarketDepthNode';
import { StreamQuotesNode } from './StreamQuotesNode';
import { GetFundamentalsNode } from './GetFundamentalsNode';
import { GetTickerStatsNode } from './GetTickerStatsNode';
-import { YFinanceNode } from './YFinanceNode';
export const MarketDataNodes = {
GetQuoteNode,
- GetHistoricalDataNode,
GetMarketDepthNode,
StreamQuotesNode,
GetFundamentalsNode,
GetTickerStatsNode,
- YFinanceNode,
};
export const MarketDataNodeTypes = [
'getQuote',
- 'getHistoricalData',
'getMarketDepth',
'streamQuotes',
'getFundamentals',
'getTickerStats',
- 'yfinance',
] as const;
export type MarketDataNodeType = typeof MarketDataNodeTypes[number];
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/nodes/transform/FilterNode.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/transform/FilterNode.ts
index e96ef3b24..99855513a 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/nodes/transform/FilterNode.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/nodes/transform/FilterNode.ts
@@ -22,56 +22,204 @@ export class FilterTransformNode implements INodeType {
inputs: [NodeConnectionType.Main],
outputs: [NodeConnectionType.Main],
properties: [
+ {
+ displayName: 'Filter Mode',
+ name: 'filterMode',
+ type: NodePropertyType.Options,
+ options: [
+ { name: 'Field vs Value', value: 'fieldValue' },
+ { name: 'Field vs Field', value: 'fieldField' },
+ { name: 'Preset Filter', value: 'preset' },
+ ],
+ default: 'fieldValue',
+ description: 'How to compare: field against static value, or field against another field',
+ },
+ {
+ displayName: 'Preset',
+ name: 'preset',
+ type: NodePropertyType.Options,
+ options: [
+ { name: 'Positive Days (close > open)', value: 'positiveDays' },
+ { name: 'Negative Days (close < open)', value: 'negativeDays' },
+ { name: 'High Volume (> average)', value: 'highVolume' },
+ { name: 'Price Up (close > previous close)', value: 'priceUp' },
+ { name: 'Price Down (close < previous close)', value: 'priceDown' },
+ ],
+ default: 'positiveDays',
+ description: 'Common financial filters',
+ displayOptions: {
+ show: { filterMode: ['preset'] },
+ },
+ },
{
displayName: 'Field',
name: 'field',
type: NodePropertyType.String,
default: '',
required: true,
+ placeholder: 'close',
+ description: 'Field to compare (left side)',
+ displayOptions: {
+ show: { filterMode: ['fieldValue', 'fieldField'] },
+ },
},
{
displayName: 'Operation',
name: 'operation',
type: NodePropertyType.Options,
options: [
- { name: 'Greater Than', value: 'gt' },
- { name: 'Less Than', value: 'lt' },
- { name: 'Equals', value: 'eq' },
+ { name: 'Greater Than (>)', value: 'gt' },
+ { name: 'Greater Than or Equal (>=)', value: 'gte' },
+ { name: 'Less Than (<)', value: 'lt' },
+ { name: 'Less Than or Equal (<=)', value: 'lte' },
+ { name: 'Equals (==)', value: 'eq' },
+ { name: 'Not Equals (!=)', value: 'neq' },
{ name: 'Contains', value: 'contains' },
],
default: 'gt',
+ displayOptions: {
+ show: { filterMode: ['fieldValue', 'fieldField'] },
+ },
+ },
+ {
+ displayName: 'Compare To Field',
+ name: 'compareField',
+ type: NodePropertyType.String,
+ default: '',
+ placeholder: 'open',
+ description: 'Field to compare against (right side)',
+ displayOptions: {
+ show: { filterMode: ['fieldField'] },
+ },
},
{
displayName: 'Value',
name: 'value',
type: NodePropertyType.String,
default: '',
+ placeholder: '0',
+ description: 'Static value to compare against',
+ displayOptions: {
+ show: { filterMode: ['fieldValue'] },
+ },
},
],
};
async execute(this: IExecuteFunctions): Promise<NodeOutput> {
const items = this.getInputData();
- const field = this.getNodeParameter('field', 0) as string;
- const operation = this.getNodeParameter('operation', 0) as string;
- const value = this.getNodeParameter('value', 0);
-
- const filtered = items.filter((item, i) => {
- const fieldValue = getFieldValue(item.json, field);
-
- switch (operation) {
- case 'gt': return Number(fieldValue) > Number(value);
- case 'lt': return Number(fieldValue) < Number(value);
- case 'eq': return fieldValue == value;
- case 'contains': return String(fieldValue).includes(String(value));
- default: return true;
- }
- });
+ const filterMode = this.getNodeParameter('filterMode', 0) as string;
+
+ if (!items || items.length === 0) {
+ return [[]];
+ }
+
+ let filtered: any[] = [];
+
+ if (filterMode === 'preset') {
+ const preset = this.getNodeParameter('preset', 0) as string;
+ filtered = applyPresetFilter(items, preset);
+ } else if (filterMode === 'fieldField') {
+ const field = this.getNodeParameter('field', 0) as string;
+ const operation = this.getNodeParameter('operation', 0) as string;
+ const compareField = this.getNodeParameter('compareField', 0) as string;
+
+ filtered = items.filter((item) => {
+ const leftValue = getFieldValue(item.json, field);
+ const rightValue = getFieldValue(item.json, compareField);
+ return compareValues(leftValue, operation, rightValue);
+ });
+ } else {
+ // fieldValue mode (default)
+ const field = this.getNodeParameter('field', 0) as string;
+ const operation = this.getNodeParameter('operation', 0) as string;
+ const value = this.getNodeParameter('value', 0);
+
+ filtered = items.filter((item) => {
+ const fieldValue = getFieldValue(item.json, field);
+ return compareValues(fieldValue, operation, value);
+ });
+ }
return [filtered.map((item, i) => ({ ...item, pairedItem: i }))];
}
}
function getFieldValue(obj: any, path: string): any {
+ if (!obj || !path) return undefined;
return path.split('.').reduce((o, k) => o?.[k], obj);
}
+
+function compareValues(left: any, operation: string, right: any): boolean {
+ const leftNum = Number(left);
+ const rightNum = Number(right);
+ const useNumbers = !isNaN(leftNum) && !isNaN(rightNum);
+
+ switch (operation) {
+ case 'gt':
+ return useNumbers ? leftNum > rightNum : left > right;
+ case 'gte':
+ return useNumbers ? leftNum >= rightNum : left >= right;
+ case 'lt':
+ return useNumbers ? leftNum < rightNum : left < right;
+ case 'lte':
+ return useNumbers ? leftNum <= rightNum : left <= right;
+ case 'eq':
+ return left == right;
+ case 'neq':
+ return left != right;
+ case 'contains':
+ return String(left).includes(String(right));
+ default:
+ return true;
+ }
+}
+
+function applyPresetFilter(items: any[], preset: string): any[] {
+ switch (preset) {
+ case 'positiveDays':
+ // Close > Open (bullish/green candle)
+ return items.filter((item) => {
+ const close = Number(getFieldValue(item.json, 'close'));
+ const open = Number(getFieldValue(item.json, 'open'));
+ return !isNaN(close) && !isNaN(open) && close > open;
+ });
+
+ case 'negativeDays':
+ // Close < Open (bearish/red candle)
+ return items.filter((item) => {
+ const close = Number(getFieldValue(item.json, 'close'));
+ const open = Number(getFieldValue(item.json, 'open'));
+ return !isNaN(close) && !isNaN(open) && close < open;
+ });
+
+ case 'highVolume':
+ // Volume > average volume
+ const volumes = items.map((item) => Number(getFieldValue(item.json, 'volume'))).filter((v) => !isNaN(v));
+ const avgVolume = volumes.length > 0 ? volumes.reduce((a, b) => a + b, 0) / volumes.length : 0;
+ return items.filter((item) => {
+ const volume = Number(getFieldValue(item.json, 'volume'));
+ return !isNaN(volume) && volume > avgVolume;
+ });
+
+ case 'priceUp':
+ case 'priceDown':
+ // Compare with previous close - requires sorted data
+ const sorted = [...items].sort((a, b) => {
+ const dateA = new Date(getFieldValue(a.json, 'timestamp') || getFieldValue(a.json, 'date') || 0);
+ const dateB = new Date(getFieldValue(b.json, 'timestamp') || getFieldValue(b.json, 'date') || 0);
+ return dateA.getTime() - dateB.getTime();
+ });
+
+ return sorted.filter((item, index) => {
+ if (index === 0) return false; // First item has no previous
+ const currentClose = Number(getFieldValue(item.json, 'close'));
+ const prevClose = Number(getFieldValue(sorted[index - 1].json, 'close'));
+ if (isNaN(currentClose) || isNaN(prevClose)) return false;
+ return preset === 'priceUp' ? currentClose > prevClose : currentClose < prevClose;
+ });
+
+ default:
+ return items;
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/symbolMasterService.ts b/fincept-terminal-desktop/src/services/symbolMasterService.ts
new file mode 100644
index 000000000..565da61cc
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/symbolMasterService.ts
@@ -0,0 +1,487 @@
+/**
+ * Symbol Master Service
+ *
+ * Unified service for managing broker symbol databases.
+ * Provides search, status tracking, and auto-download functionality.
+ */
+
+import { invoke } from '@tauri-apps/api/core';
+
+// ============================================================================
+// TYPES
+// ============================================================================
+
+export interface SymbolSearchResult {
+ symbol: string;
+ br_symbol: string;
+ name: string | null;
+ exchange: string;
+ token: string;
+ expiry: string | null;
+ strike: number | null;
+ lot_size: number | null;
+ instrument_type: string | null;
+ tick_size: number | null;
+ relevance_score: number;
+}
+
+export interface MasterContractStatus {
+ broker_id: string;
+ status: 'pending' | 'downloading' | 'success' | 'error' | 'unknown';
+ message: string | null;
+ last_updated: number;
+ total_symbols: number;
+ is_ready: boolean;
+}
+
+export interface SymbolSearchResponse {
+ success: boolean;
+ symbols: SymbolSearchResult[];
+ total: number;
+ error?: string;
+}
+
+export interface StatusResponse {
+ success: boolean;
+ status: MasterContractStatus | null;
+ error?: string;
+}
+
+export interface CacheValidityResponse {
+ success: boolean;
+ is_valid: boolean;
+ age_seconds: number | null;
+ ttl_seconds: number;
+ error?: string;
+}
+
+export interface DownloadResponse {
+ success: boolean;
+ message: string;
+ total_symbols: number;
+}
+
+// ============================================================================
+// SEARCH FUNCTIONS
+// ============================================================================
+
+/**
+ * Search symbols for a broker
+ */
+export async function searchSymbols(
+ brokerId: string,
+ query: string,
+ options?: {
+ exchange?: string;
+ instrumentType?: string;
+ limit?: number;
+ }
+): Promise<SymbolSearchResponse> {
+ try {
+ return await invoke<SymbolSearchResponse>('symbol_master_search', {
+ brokerId,
+ query,
+ exchange: options?.exchange,
+ instrumentType: options?.instrumentType,
+ limit: options?.limit || 50,
+ });
+ } catch (error) {
+ console.error('[symbolMaster] Search error:', error);
+ return {
+ success: false,
+ symbols: [],
+ total: 0,
+ error: String(error),
+ };
+ }
+}
+
+/**
+ * Get symbol by exact match
+ */
+export async function getSymbol(
+ brokerId: string,
+ symbol: string,
+ exchange: string
+): Promise<SymbolSearchResult | null> {
+ try {
+ const result = await invoke<{ success: boolean; symbol: SymbolSearchResult | null }>(
+ 'symbol_master_get_symbol',
+ { brokerId, symbol, exchange }
+ );
+ return result.symbol;
+ } catch (error) {
+ console.error('[symbolMaster] Get symbol error:', error);
+ return null;
+ }
+}
+
+/**
+ * Get symbol by token
+ */
+export async function getSymbolByToken(
+ brokerId: string,
+ token: string
+): Promise<SymbolSearchResult | null> {
+ try {
+ const result = await invoke<{ success: boolean; symbol: SymbolSearchResult | null }>(
+ 'symbol_master_get_by_token',
+ { brokerId, token }
+ );
+ return result.symbol;
+ } catch (error) {
+ console.error('[symbolMaster] Get by token error:', error);
+ return null;
+ }
+}
+
+/**
+ * Get token for a symbol (useful for WebSocket subscriptions)
+ */
+export async function getToken(
+ brokerId: string,
+ symbol: string,
+ exchange: string
+): Promise<string | null> {
+ try {
+ const result = await invoke<{ success: boolean; token: string | null }>(
+ 'symbol_master_get_token',
+ { brokerId, symbol, exchange }
+ );
+ return result.token;
+ } catch (error) {
+ console.error('[symbolMaster] Get token error:', error);
+ return null;
+ }
+}
+
+// ============================================================================
+// STATUS FUNCTIONS
+// ============================================================================
+
+/**
+ * Get master contract status for a broker
+ */
+export async function getStatus(brokerId: string): Promise<MasterContractStatus | null> {
+ try {
+ const result = await invoke<StatusResponse>('symbol_master_get_status', { brokerId });
+ return result.status;
+ } catch (error) {
+ console.error('[symbolMaster] Get status error:', error);
+ return null;
+ }
+}
+
+/**
+ * Check if master contracts are ready (cached and valid)
+ */
+export async function isReady(brokerId: string): Promise<CacheValidityResponse> {
+ try {
+ return await invoke<CacheValidityResponse>('symbol_master_is_ready', { brokerId });
+ } catch (error) {
+ console.error('[symbolMaster] Is ready error:', error);
+ return {
+ success: false,
+ is_valid: false,
+ age_seconds: null,
+ ttl_seconds: 86400,
+ error: String(error),
+ };
+ }
+}
+
+/**
+ * Initialize broker status (should be called on login)
+ */
+export async function initBroker(brokerId: string): Promise<StatusResponse> {
+ try {
+ return await invoke<StatusResponse>('symbol_master_init_broker', { brokerId });
+ } catch (error) {
+ console.error('[symbolMaster] Init broker error:', error);
+ return {
+ success: false,
+ status: null,
+ error: String(error),
+ };
+ }
+}
+
+// ============================================================================
+// METADATA FUNCTIONS
+// ============================================================================
+
+/**
+ * Get symbol count for a broker
+ */
+export async function getSymbolCount(brokerId: string): Promise<number> {
+ try {
+ const result = await invoke<{ success: boolean; count: number }>('symbol_master_get_count', { brokerId });
+ return result.count;
+ } catch (error) {
+ console.error('[symbolMaster] Get count error:', error);
+ return 0;
+ }
+}
+
+/**
+ * Get available exchanges for a broker
+ */
+export async function getExchanges(brokerId: string): Promise<string[]> {
+ try {
+ const result = await invoke<{ success: boolean; exchanges: string[] }>('symbol_master_get_exchanges', { brokerId });
+ return result.exchanges;
+ } catch (error) {
+ console.error('[symbolMaster] Get exchanges error:', error);
+ return [];
+ }
+}
+
+/**
+ * Get available expiries for FNO symbols
+ */
+export async function getExpiries(
+ brokerId: string,
+ options?: { exchange?: string; underlying?: string }
+): Promise<string[]> {
+ try {
+ const result = await invoke<{ success: boolean; expiries: string[] }>('symbol_master_get_expiries', {
+ brokerId,
+ exchange: options?.exchange,
+ underlying: options?.underlying,
+ });
+ return result.expiries;
+ } catch (error) {
+ console.error('[symbolMaster] Get expiries error:', error);
+ return [];
+ }
+}
+
+/**
+ * Get available underlyings (for option chain)
+ */
+export async function getUnderlyings(
+ brokerId: string,
+ exchange?: string
+): Promise<string[]> {
+ try {
+ const result = await invoke<{ success: boolean; underlyings: string[] }>('symbol_master_get_underlyings', {
+ brokerId,
+ exchange,
+ });
+ return result.underlyings;
+ } catch (error) {
+ console.error('[symbolMaster] Get underlyings error:', error);
+ return [];
+ }
+}
+
+// ============================================================================
+// DOWNLOAD FUNCTIONS
+// ============================================================================
+
+/**
+ * Download master contract for a broker
+ * Automatically selects the correct download function based on broker ID
+ */
+export async function downloadMasterContract(
+ brokerId: string,
+ credentials?: { apiKey?: string; accessToken?: string }
+): Promise<DownloadResponse> {
+ try {
+ switch (brokerId.toLowerCase()) {
+ case 'fyers':
+ return await invoke<DownloadResponse>('fyers_download_symbols');
+
+ case 'zerodha':
+ if (!credentials?.apiKey || !credentials?.accessToken) {
+ return {
+ success: false,
+ message: 'Zerodha requires API key and access token',
+ total_symbols: 0,
+ };
+ }
+ return await invoke<DownloadResponse>('zerodha_download_symbols', {
+ apiKey: credentials.apiKey,
+ accessToken: credentials.accessToken,
+ });
+
+ case 'angelone':
+ case 'angel':
+ return await invoke<DownloadResponse>('angelone_download_symbols');
+
+ case 'upstox':
+ return await invoke<DownloadResponse>('upstox_download_symbols');
+
+ case 'dhan':
+ return await invoke<DownloadResponse>('dhan_download_symbols');
+
+ case 'shoonya':
+ case 'finvasia':
+ return await invoke<DownloadResponse>('shoonya_download_symbols');
+
+ default:
+ return {
+ success: false,
+ message: `No download implementation for broker: ${brokerId}`,
+ total_symbols: 0,
+ };
+ }
+ } catch (error) {
+ console.error(`[symbolMaster] Download error for ${brokerId}:`, error);
+ return {
+ success: false,
+ message: String(error),
+ total_symbols: 0,
+ };
+ }
+}
+
+/**
+ * Check and download master contract if needed
+ * Auto-downloads if cache is expired or empty
+ */
+export async function ensureMasterContract(
+ brokerId: string,
+ credentials?: { apiKey?: string; accessToken?: string }
+): Promise<DownloadResponse> {
+ try {
+ // Check if cache is valid
+ const cacheStatus = await isReady(brokerId);
+
+ if (cacheStatus.is_valid) {
+ console.log(`[symbolMaster] Cache valid for ${brokerId}, skipping download`);
+ const count = await getSymbolCount(brokerId);
+ return {
+ success: true,
+ message: `Using cached symbols (${formatAge(cacheStatus.age_seconds)} old)`,
+ total_symbols: count,
+ };
+ }
+
+ console.log(`[symbolMaster] Cache expired/empty for ${brokerId}, downloading...`);
+ return await downloadMasterContract(brokerId, credentials);
+ } catch (error) {
+ console.error(`[symbolMaster] Ensure master contract error for ${brokerId}:`, error);
+ return {
+ success: false,
+ message: String(error),
+ total_symbols: 0,
+ };
+ }
+}
+
+// ============================================================================
+// UTILITY FUNCTIONS
+// ============================================================================
+
+/**
+ * Normalize index symbol to unified format
+ */
+export async function normalizeIndexSymbol(symbol: string): Promise<string> {
+ try {
+ return await invoke<string>('symbol_master_normalize_index', { symbol });
+ } catch (error) {
+ console.error('[symbolMaster] Normalize index error:', error);
+ return symbol;
+ }
+}
+
+/**
+ * Format expiry date to DD-MMM-YY format
+ */
+export async function formatExpiry(expiry: string): Promise<string> {
+ try {
+ return await invoke<string>('symbol_master_format_expiry', { expiry });
+ } catch (error) {
+ console.error('[symbolMaster] Format expiry error:', error);
+ return expiry;
+ }
+}
+
+/**
+ * Build unified futures symbol
+ */
+export async function buildFuturesSymbol(underlying: string, expiry: string): Promise<string> {
+ try {
+ return await invoke<string>('symbol_master_build_futures_symbol', { underlying, expiry });
+ } catch (error) {
+ console.error('[symbolMaster] Build futures symbol error:', error);
+ return underlying;
+ }
+}
+
+/**
+ * Build unified options symbol
+ */
+export async function buildOptionsSymbol(
+ underlying: string,
+ expiry: string,
+ strike: number,
+ optionType: 'CE' | 'PE'
+): Promise<string> {
+ try {
+ return await invoke<string>('symbol_master_build_options_symbol', {
+ underlying,
+ expiry,
+ strike,
+ optionType,
+ });
+ } catch (error) {
+ console.error('[symbolMaster] Build options symbol error:', error);
+ return underlying;
+ }
+}
+
+/**
+ * Format age in human-readable format
+ */
+function formatAge(seconds: number | null): string {
+ if (seconds === null) return 'unknown';
+ if (seconds < 60) return `${seconds}s`;
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
+ return `${Math.floor(seconds / 86400)}d`;
+}
+
+// ============================================================================
+// BROKER-SPECIFIC HELPERS
+// ============================================================================
+
+/**
+ * List of brokers that require authentication for master contract download
+ */
+export const BROKERS_REQUIRING_AUTH = ['zerodha'] as const;
+
+/**
+ * List of brokers with public master contract endpoints (no auth needed)
+ */
+export const BROKERS_WITH_PUBLIC_MASTER = [
+ 'fyers',
+ 'angelone',
+ 'angel',
+ 'upstox',
+ 'dhan',
+ 'shoonya',
+ 'finvasia',
+] as const;
+
+/**
+ * Check if broker requires authentication for master contract download
+ */
+export function requiresAuthForDownload(brokerId: string): boolean {
+ return BROKERS_REQUIRING_AUTH.includes(brokerId.toLowerCase() as any);
+}
+
+/**
+ * Get list of supported brokers for master contract
+ */
+export function getSupportedBrokers(): string[] {
+ return [
+ 'fyers',
+ 'zerodha',
+ 'angelone',
+ 'upstox',
+ 'dhan',
+ 'shoonya',
+ ];
+}
diff --git a/fincept-terminal-desktop/src/services/trading/tradeService.ts b/fincept-terminal-desktop/src/services/trading/tradeService.ts
index e35775ffe..560f9d57f 100644
--- a/fincept-terminal-desktop/src/services/trading/tradeService.ts
+++ b/fincept-terminal-desktop/src/services/trading/tradeService.ts
@@ -297,25 +297,53 @@ class TradeService {
});
}
+ /**
+ * Check if trade API is healthy
+ */
+ async isApiHealthy(): Promise<{ healthy: boolean; error?: string }> {
+ try {
+ const response: any = await this.apiRequest('/trade/health');
+ const status = response.data?.status;
+ if (status === 'healthy') {
+ return { healthy: true };
+ }
+ return { healthy: false, error: response.data?.error || 'Trade API is unavailable' };
+ } catch (error: any) {
+ return { healthy: false, error: error.message || 'Trade API is unavailable' };
+ }
+ }
+
/**
* Get list of all countries
*/
async getCountries(continent?: string, search?: string): Promise<Country[]> {
- const response: any = await this.apiRequest('/trade/countries', {
- continent,
- search,
- });
- return response.data?.countries || [];
+ try {
+ const response: any = await this.apiRequest('/trade/countries', {
+ continent,
+ search,
+ });
+ return response.data?.countries || [];
+ } catch (error: any) {
+ // Return empty array on failure to prevent tab from crashing
+ console.error('[TradeService] getCountries failed:', error);
+ return [];
+ }
}
/**
* Get list of products (HS codes)
*/
async getProducts(level?: number, parent?: string): Promise<Product[]> {
- return this.apiRequest<Product[]>('/trade/products', {
- level,
- parent,
- });
+ try {
+ return await this.apiRequest<Product[]>('/trade/products', {
+ level,
+ parent,
+ });
+ } catch (error: any) {
+ // Return empty array on failure to prevent tab from crashing
+ console.error('[TradeService] getProducts failed:', error);
+ return [];
+ }
}
/**
diff --git a/fincept-terminal-desktop/src/services/voice/ttsService.ts b/fincept-terminal-desktop/src/services/voice/ttsService.ts
index 7b9369750..5347cddef 100644
--- a/fincept-terminal-desktop/src/services/voice/ttsService.ts
+++ b/fincept-terminal-desktop/src/services/voice/ttsService.ts
@@ -124,11 +124,34 @@ class TTSService {
return this.isSpeaking;
}
- // Clean text for TTS
+ // Clean and preprocess text for TTS - makes content more natural to listen to
private cleanText(text: string): string {
- return text
+ let result = text;
+
+ // 1. Handle LaTeX formulas - convert to spoken math
+ result = this.convertFormulasToSpeech(result);
+
+ // 2. Handle markdown tables - convert to spoken format
+ result = this.convertTablesToSpeech(result);
+
+ // 3. Handle dates and times
+ result = this.convertDatesToSpeech(result);
+
+ // 4. Handle numbers and financial data
+ result = this.convertNumbersToSpeech(result);
+
+ // 5. Handle common abbreviations
+ result = this.expandAbbreviations(result);
+
+ // 6. Clean remaining markdown
+ result = result
.replace(/```[\s\S]*?```/g, '') // Remove code blocks
- .replace(/[`*#\[\](){}]/g, '') // Remove markdown
+ .replace(/`([^`]+)`/g, '$1') // Keep inline code content
+ .replace(/\*\*([^*]+)\*\*/g, '$1') // Bold
+ .replace(/\*([^*]+)\*/g, '$1') // Italic
+ .replace(/#{1,6}\s*/g, '') // Headers
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // Links - keep text
+ .replace(/[[\](){}]/g, '') // Remove brackets
.replace(/\n+/g, '. ') // Replace newlines
.replace(/[\u{1F300}-\u{1F9FF}]/gu, '') // Remove emojis
.replace(/[\u{2600}-\u{26FF}]/gu, '')
@@ -136,9 +159,273 @@ class TTSService {
.replace(/[\u{1F600}-\u{1F64F}]/gu, '')
.replace(/[\u{1F680}-\u{1F6FF}]/gu, '')
.replace(/[\u{1F1E0}-\u{1F1FF}]/gu, '')
- .replace(/\s+/g, ' ')
- .trim()
- .slice(0, 1000);
+ .replace(/\.+/g, '.') // Multiple periods to single
+ .replace(/\s+/g, ' ') // Multiple spaces to single
+ .trim();
+
+ // Limit length for TTS (can be longer since we're summarizing)
+ return result.slice(0, 2000);
+ }
+
+ // Convert LaTeX formulas to spoken math
+ private convertFormulasToSpeech(text: string): string {
+ // Block formulas: \[ ... \] or $$ ... $$
+ text = text.replace(/\\\[([\s\S]*?)\\\]|\$\$([\s\S]*?)\$\$/g, (_, b1, b2) => {
+ const formula = b1 || b2;
+ return '. The formula is: ' + this.latexToSpeech(formula) + '. ';
+ });
+
+ // Inline formulas: \( ... \) or $ ... $
+ text = text.replace(/\\\((.*?)\\\)|\$([^\$\n]+?)\$/g, (_, i1, i2) => {
+ const formula = i1 || i2;
+ return ' ' + this.latexToSpeech(formula) + ' ';
+ });
+
+ return text;
+ }
+
+ // Convert LaTeX to speakable text
+ private latexToSpeech(latex: string): string {
+ let speech = latex.trim();
+
+ // Fractions
+ speech = speech.replace(/\\frac\{([^}]+)\}\{([^}]+)\}/g, '$1 divided by $2');
+ speech = speech.replace(/\\dfrac\{([^}]+)\}\{([^}]+)\}/g, '$1 divided by $2');
+
+ // Square roots
+ speech = speech.replace(/\\sqrt\[(\d+)\]\{([^}]+)\}/g, 'the $1th root of $2');
+ speech = speech.replace(/\\sqrt\{([^}]+)\}/g, 'the square root of $1');
+
+ // Exponents and subscripts
+ speech = speech.replace(/\^{([^}]+)}/g, ' to the power of $1');
+ speech = speech.replace(/\^(\d)/g, ' to the power of $1');
+ speech = speech.replace(/_{([^}]+)}/g, ' subscript $1');
+ speech = speech.replace(/_(\w)/g, ' subscript $1');
+
+ // Summation and integrals
+ speech = speech.replace(/\\sum_\{([^}]+)\}\^\{([^}]+)\}/g, 'the sum from $1 to $2 of');
+ speech = speech.replace(/\\sum/g, 'the sum of');
+ speech = speech.replace(/\\int_\{([^}]+)\}\^\{([^}]+)\}/g, 'the integral from $1 to $2 of');
+ speech = speech.replace(/\\int/g, 'the integral of');
+ speech = speech.replace(/\\prod/g, 'the product of');
+
+ // Limits
+ speech = speech.replace(/\\lim_\{([^}]+)\}/g, 'the limit as $1 of');
+
+ // Greek letters
+ const greekLetters: Record<string, string> = {
+ '\\alpha': 'alpha', '\\beta': 'beta', '\\gamma': 'gamma', '\\delta': 'delta',
+ '\\epsilon': 'epsilon', '\\zeta': 'zeta', '\\eta': 'eta', '\\theta': 'theta',
+ '\\iota': 'iota', '\\kappa': 'kappa', '\\lambda': 'lambda', '\\mu': 'mu',
+ '\\nu': 'nu', '\\xi': 'xi', '\\pi': 'pi', '\\rho': 'rho',
+ '\\sigma': 'sigma', '\\tau': 'tau', '\\upsilon': 'upsilon', '\\phi': 'phi',
+ '\\chi': 'chi', '\\psi': 'psi', '\\omega': 'omega',
+ '\\Delta': 'Delta', '\\Sigma': 'Sigma', '\\Pi': 'Pi', '\\Omega': 'Omega',
+ };
+ for (const [latex, spoken] of Object.entries(greekLetters)) {
+ speech = speech.replace(new RegExp(latex.replace(/\\/g, '\\\\'), 'g'), spoken);
+ }
+
+ // Operators
+ speech = speech.replace(/\\times/g, ' times ');
+ speech = speech.replace(/\\div/g, ' divided by ');
+ speech = speech.replace(/\\pm/g, ' plus or minus ');
+ speech = speech.replace(/\\mp/g, ' minus or plus ');
+ speech = speech.replace(/\\cdot/g, ' times ');
+ speech = speech.replace(/\\leq/g, ' less than or equal to ');
+ speech = speech.replace(/\\geq/g, ' greater than or equal to ');
+ speech = speech.replace(/\\neq/g, ' not equal to ');
+ speech = speech.replace(/\\approx/g, ' approximately equal to ');
+ speech = speech.replace(/\\equiv/g, ' is equivalent to ');
+ speech = speech.replace(/\\rightarrow/g, ' approaches ');
+ speech = speech.replace(/\\to/g, ' to ');
+ speech = speech.replace(/\\infty/g, ' infinity ');
+
+ // Text commands
+ speech = speech.replace(/\\text\{([^}]+)\}/g, '$1');
+ speech = speech.replace(/\\textbf\{([^}]+)\}/g, '$1');
+ speech = speech.replace(/\\mathrm\{([^}]+)\}/g, '$1');
+
+ // Trig functions
+ speech = speech.replace(/\\(sin|cos|tan|cot|sec|csc|log|ln|exp)/g, ' $1 of ');
+
+ // Clean up remaining backslashes and braces
+ speech = speech.replace(/\\[a-zA-Z]+/g, ' ');
+ speech = speech.replace(/[{}]/g, '');
+ speech = speech.replace(/\s+/g, ' ');
+
+ return speech.trim();
+ }
+
+ // Convert markdown tables to spoken format
+ private convertTablesToSpeech(text: string): string {
+ // Match markdown tables
+ const tableRegex = /\|(.+)\|\n\|[-:\s|]+\|\n((?:\|.+\|\n?)+)/g;
+
+ return text.replace(tableRegex, (match) => {
+ const lines = match.trim().split('\n');
+ if (lines.length < 3) return match;
+
+ // Parse header
+ const headers = lines[0].split('|').filter(h => h.trim()).map(h => h.trim());
+
+ // Parse rows (skip header and separator)
+ const rows = lines.slice(2).map(line =>
+ line.split('|').filter(c => c.trim()).map(c => c.trim())
+ );
+
+ // Build spoken table
+ let spoken = '. Here is a table with columns: ' + headers.join(', ') + '. ';
+
+ rows.forEach((row, idx) => {
+ spoken += `Row ${idx + 1}: `;
+ row.forEach((cell, cellIdx) => {
+ if (headers[cellIdx]) {
+ spoken += `${headers[cellIdx]} is ${cell}. `;
+ } else {
+ spoken += `${cell}. `;
+ }
+ });
+ });
+
+ return spoken;
+ });
+ }
+
+ // Convert dates and times to spoken format
+ private convertDatesToSpeech(text: string): string {
+ // ISO dates: 2024-01-15 or 2024/01/15
+ text = text.replace(/(\d{4})[-/](\d{2})[-/](\d{2})/g, (_, year, month, day) => {
+ const months = ['', 'January', 'February', 'March', 'April', 'May', 'June',
+ 'July', 'August', 'September', 'October', 'November', 'December'];
+ const m = parseInt(month, 10);
+ const d = parseInt(day, 10);
+ return `${months[m]} ${d}, ${year}`;
+ });
+
+ // US dates: 01/15/2024 or 01-15-2024
+ text = text.replace(/(\d{2})[-/](\d{2})[-/](\d{4})/g, (_, month, day, year) => {
+ const months = ['', 'January', 'February', 'March', 'April', 'May', 'June',
+ 'July', 'August', 'September', 'October', 'November', 'December'];
+ const m = parseInt(month, 10);
+ const d = parseInt(day, 10);
+ if (m > 0 && m <= 12) {
+ return `${months[m]} ${d}, ${year}`;
+ }
+ return `${month}/${day}/${year}`;
+ });
+
+ // Times: 14:30 or 14:30:00
+ text = text.replace(/(\d{1,2}):(\d{2})(?::(\d{2}))?(?!\d)/g, (_, hours, minutes, seconds) => {
+ const h = parseInt(hours, 10);
+ const m = parseInt(minutes, 10);
+ const ampm = h >= 12 ? 'PM' : 'AM';
+ const h12 = h % 12 || 12;
+ let spoken = `${h12}:${minutes} ${ampm}`;
+ if (seconds) {
+ spoken += ` and ${seconds} seconds`;
+ }
+ return spoken;
+ });
+
+ return text;
+ }
+
+ // Convert numbers to spoken format
+ private convertNumbersToSpeech(text: string): string {
+ // Percentages
+ text = text.replace(/(\d+\.?\d*)%/g, '$1 percent');
+
+ // Currency with large numbers: $1,234,567.89
+ text = text.replace(/\$(\d{1,3}(?:,\d{3})*(?:\.\d+)?)/g, (_, num) => {
+ const value = parseFloat(num.replace(/,/g, ''));
+ return this.numberToWords(value, 'dollars');
+ });
+
+ // Large numbers with commas: 1,234,567
+ text = text.replace(/\b(\d{1,3}(?:,\d{3})+)\b/g, (_, num) => {
+ const value = parseFloat(num.replace(/,/g, ''));
+ return this.numberToWords(value);
+ });
+
+ // Basis points
+ text = text.replace(/(\d+)\s*(?:bps|basis points)/gi, '$1 basis points');
+
+ // Ratios: 1:2 or 3:1
+ text = text.replace(/(\d+):(\d+)/g, '$1 to $2');
+
+ return text;
+ }
+
+ // Convert number to spoken words for large numbers
+ private numberToWords(num: number, unit?: string): string {
+ if (num >= 1e12) {
+ const val = (num / 1e12).toFixed(2);
+ return `${val} trillion${unit ? ' ' + unit : ''}`;
+ } else if (num >= 1e9) {
+ const val = (num / 1e9).toFixed(2);
+ return `${val} billion${unit ? ' ' + unit : ''}`;
+ } else if (num >= 1e6) {
+ const val = (num / 1e6).toFixed(2);
+ return `${val} million${unit ? ' ' + unit : ''}`;
+ } else if (num >= 1e3) {
+ const val = (num / 1e3).toFixed(1);
+ return `${val} thousand${unit ? ' ' + unit : ''}`;
+ }
+ return unit ? `${num} ${unit}` : num.toString();
+ }
+
+ // Expand common abbreviations
+ private expandAbbreviations(text: string): string {
+ const abbreviations: Record<string, string> = {
+ // Financial
+ 'P/E': 'price to earnings ratio',
+ 'EPS': 'earnings per share',
+ 'ROI': 'return on investment',
+ 'ROE': 'return on equity',
+ 'ROA': 'return on assets',
+ 'ROCE': 'return on capital employed',
+ 'EBIT': 'earnings before interest and taxes',
+ 'EBITDA': 'earnings before interest, taxes, depreciation and amortization',
+ 'DCF': 'discounted cash flow',
+ 'NPV': 'net present value',
+ 'IRR': 'internal rate of return',
+ 'WACC': 'weighted average cost of capital',
+ 'CAGR': 'compound annual growth rate',
+ 'YoY': 'year over year',
+ 'QoQ': 'quarter over quarter',
+ 'MoM': 'month over month',
+ 'YTD': 'year to date',
+ 'TTM': 'trailing twelve months',
+ 'AUM': 'assets under management',
+ 'NAV': 'net asset value',
+ 'IPO': 'initial public offering',
+ 'M&A': 'mergers and acquisitions',
+ 'PE': 'private equity',
+ 'VC': 'venture capital',
+ 'ETF': 'exchange traded fund',
+ 'GDP': 'gross domestic product',
+ 'CPI': 'consumer price index',
+ 'PPI': 'producer price index',
+ 'Fed': 'Federal Reserve',
+ 'SEC': 'Securities and Exchange Commission',
+ 'NYSE': 'New York Stock Exchange',
+ 'NASDAQ': 'NASDAQ stock exchange',
+ // Technical
+ 'API': 'A P I',
+ 'URL': 'U R L',
+ 'AI': 'A I',
+ 'ML': 'machine learning',
+ 'NLP': 'natural language processing',
+ };
+
+ for (const [abbr, full] of Object.entries(abbreviations)) {
+ // Match whole words only
+ const regex = new RegExp(`\\b${abbr}\\b`, 'g');
+ text = text.replace(regex, full);
+ }
+
+ return text;
}
// Browser native TTS