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.

v3.3.3

tilakpatel228bfa332a4bae
diff --git a/fincept-terminal-desktop/Temppm_market.json b/fincept-terminal-desktop/Temppm_market.json
new file mode 100644
index 000000000..78c4e25d8
--- /dev/null
+++ b/fincept-terminal-desktop/Temppm_market.json
@@ -0,0 +1 @@
+[{"id":"1237864","question":"Counter-Strike: Acend vs Bebop (BO3) - CCT Europe Series #14 Play-In Group B","conditionId":"0xa6d544024ed0b1de9e0cd6c0327a7c18a872e5875f40ceafb61937bccd43f248","slug":"cs2-ace1-bbp-2026-01-23","resolutionSource":"https://www.sofascore.com/esports","endDate":"2026-01-23T18:30:00Z","startDate":"2026-01-22T00:01:27.770446Z","image":"https://polymarket-upload.s3.us-east-2.amazonaws.com/counter-strike-image-16c415c538.png","icon":"https://polymarket-upload.s3.us-east-2.amazonaws.com/counter-strike-image-16c415c538.png","description":"This market refers to the Counter-Strike match between Acend and Bebop in the CCT Europe Series #14 Play-In Group B, scheduled for January 23 at 7:30AM ET.\n\nThis market will resolve to \"Acend\" if Acend win the match against Bebop.\n\nThis market will resolve to \"Bebop\" if Bebop win the match against Acend.\n\nIf the match is canceled (not played at all), ends in a tie, or is delayed beyond 7 days from the scheduled date without a winner determined, this market will resolve to 50-50. \n\nIf the match begins but is not completed, and one team wins due to the opponent's forfeiture, disqualification, or walkover, this market will resolve to the team who wins. \n\nIf the match ends in a forfeit, disqualification, or walkover (team withdraws before the start and the other wins automatically), this market will resolve to 50-50. \n\nThe resolution source for this market will be official information from https://www.sofascore.com/esports.","outcomes":"[\"Acend\", \"Bebop\"]","outcomePrices":"[\"1\", \"0\"]","volume":"9999.995006","active":true,"closed":true,"marketMakerAddress":"","createdAt":"2026-01-22T00:00:11.064526Z","updatedAt":"2026-01-25T00:21:37.311045Z","closedTime":"2026-01-23 20:56:36+00","new":false,"featured":false,"submitted_by":"0x91430CaD2d3975766499717fA0D66A78D814E5c5","archived":false,"resolvedBy":"0x65070BE91477460D8A7AeEb94ef92fe056C2f2A7","restricted":true,"groupItemTitle":"Match Winner","questionID":"0x432ea6aab86e58e5413a12dc5b66a40cd5dfc82d85aec8ea006016008c565ded","umaEndDate":"2026-01-23T20:56:36Z","enableOrderBook":true,"orderPriceMinTickSize":0.001,"orderMinSize":5,"umaResolutionStatus":"resolved","volumeNum":9999.995006,"endDateIso":"2026-01-23","startDateIso":"2026-01-22","hasReviewedDates":true,"volume1wk":9999.995006,"volume1mo":9999.995006,"volume1yr":9999.995006,"gameStartTime":"2026-01-23 12:30:00+00","secondsDelay":3,"clobTokenIds":"[\"13915383147598038388500755196666377480504116216295452377454618635607632089106\", \"5279164082546013152208887890713787838941989595411752055506257404817056208535\"]","umaBond":"500","umaReward":"2","volume1wkClob":9999.995006,"volume1moClob":9999.995006,"volume1yrClob":9999.995006,"volumeClob":9999.995006,"customLiveness":0,"acceptingOrders":false,"negRisk":false,"negRiskRequestID":"","events":[{"id":"179909","ticker":"cs2-ace1-bbp-2026-01-23","slug":"cs2-ace1-bbp-2026-01-23","title":"Counter-Strike: Acend vs Bebop (BO3) - CCT Europe Series #14 Play-In Group B","description":"This market refers to the Counter-Strike match between Acend and Bebop in the CCT Europe Series #14 Play-In Group B, scheduled for January 23 at 7:30AM ET.\n\nThis market will resolve to \"Acend\" if Acend win the match against Bebop.\n\nThis market will resolve to \"Bebop\" if Bebop win the match against Acend.\n\nIf the match is canceled (not played at all), ends in a tie, or is delayed beyond 7 days from the scheduled date without a winner determined, this market will resolve to 50-50. \n\nIf the match begins but is not completed, and one team wins due to the opponent's forfeiture, disqualification, or walkover, this market will resolve to the team who wins. \n\nIf the match ends in a forfeit, disqualification, or walkover (team withdraws before the start and the other wins automatically), this market will resolve to 50-50. \n\nThe resolution source for this market will be official information from https://www.sofascore.com/esports.","resolutionSource":"https://kick.com/cct_cs2","startDate":"2026-01-22T00:03:11.698284Z","creationDate":"2026-01-22T00:03:11.698276Z","endDate":"2026-01-23T18:30:00Z","image":"https://polymarket-upload.s3.us-east-2.amazonaws.com/counter-strike-image-16c415c538.png","icon":"https://polymarket-upload.s3.us-east-2.amazonaws.com/counter-strike-image-16c415c538.png","active":true,"closed":true,"archived":false,"new":false,"featured":false,"restricted":true,"volume":15470.09001,"openInterest":0,"createdAt":"2026-01-22T00:00:10.690544Z","updatedAt":"2026-01-25T00:21:48.154672Z","volume1wk":15234.950009999999,"volume1mo":15234.950009999999,"volume1yr":15234.950009999999,"enableOrderBook":true,"negRisk":false,"commentCount":0,"series":[{"id":"10310","ticker":"counter-strike","slug":"counter-strike","title":"Counter Strike","seriesType":"single","recurrence":"daily","image":"","icon":"","active":true,"closed":false,"archived":false,"featured":false,"restricted":true,"createdAt":"2025-09-18T23:42:36.322544Z","updatedAt":"2026-02-21T08:36:06.139696Z","volume24hr":9491712.330936,"volume":900566.129542,"liquidity":3395878.92072,"commentCount":3263,"requiresTranslation":false}],"cyom":false,"closedTime":"2026-01-23T20:57:36Z","showAllOutcomes":true,"showMarketImages":false,"automaticallyResolved":true,"enableNegRisk":false,"automaticallyActive":true,"eventDate":"2026-01-23","startTime":"2026-01-23T12:30:00Z","eventWeek":1,"seriesSlug":"counter-strike","score":"000-000|2-1|Bo3","period":"3/3","live":false,"ended":true,"negRiskAugmented":false,"pendingDeployment":false,"deploying":false,"gameId":1324191,"requiresTranslation":false}],"ready":false,"funded":false,"acceptingOrdersTimestamp":"2026-01-22T00:01:04Z","cyom":false,"pagerDutyNotificationEnabled":false,"approved":true,"rewardsMinSize":0,"rewardsMaxSpread":0,"spread":0.001,"automaticallyResolved":true,"oneDayPriceChange":0.5145,"lastTradePrice":0.999,"bestBid":0.999,"bestAsk":1,"automaticallyActive":true,"clearBookOnStart":true,"manualActivation":false,"negRiskOther":false,"gameId":"1324191","sportsMarketType":"moneyline","umaResolutionStatuses":"[\"proposed\"]","pendingDeployment":false,"deploying":false,"deployingTimestamp":"2026-01-22T00:00:29.086484Z","rfqEnabled":false,"eventStartTime":"2026-01-23T12:30:00Z","holdingRewardsEnabled":false,"feesEnabled":false,"requiresTranslation":false,"feeType":null}]
diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.json
index 141a2c194..223f2dc95 100644
--- a/fincept-terminal-desktop/package.json
+++ b/fincept-terminal-desktop/package.json
@@ -1,7 +1,7 @@
{
"name": "fincept-terminal-desktop",
"private": true,
- "version": "3.3.1",
+ "version": "3.3.3",
"type": "module",
"license": "AGPL-3.0-or-later",
"scripts": {
diff --git a/fincept-terminal-desktop/public/locales/ar/codeEditor.json b/fincept-terminal-desktop/public/locales/ar/codeEditor.json
index 12710c00e..c557496ca 100644
--- a/fincept-terminal-desktop/public/locales/ar/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/ar/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "محرر الكود",
"header": {
- "packages": "الحزم"
+ "finscriptIde": "[AR] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "ملف جديد",
- "new": "جديد",
- "open": "فتح",
- "save": "حفظ",
"run": "تشغيل الكود",
"running": "جاري التشغيل...",
- "runAll": "تشغيل الكل",
- "history": "السجل"
+ "toggleExplorer": "[AR] Toggle Explorer (Ctrl+B)",
+ "openFile": "[AR] Open File",
+ "saveShortcut": "[AR] Save (Ctrl+S)",
+ "findShortcut": "[AR] Find (Ctrl+F)",
+ "runShortcut": "[AR] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "دفتر جوبيتر",
"finscript": "محرر فينسكريبت"
},
- "packages": {
- "clickToLoad": "انقر للتحميل...",
- "load": "تحميل الحزم"
+ "explorer": {
+ "title": "[AR] EXPLORER",
+ "openFiles": "[AR] OPEN FILES",
+ "examples": "[AR] EXAMPLES",
+ "runHistory": "[AR] RUN HISTORY",
+ "finscriptEngine": "[AR] FinScript Engine"
},
- "history": {
- "title": "سجل الدفاتر",
- "loading": "جاري تحميل السجل...",
- "empty": "لا يوجد سجل دفاتر"
+ "output": {
+ "title": "[AR] OUTPUT",
+ "success": "[AR] SUCCESS",
+ "error": "[AR] ERROR",
+ "executing": "[AR] EXECUTING FINSCRIPT...",
+ "noOutput": "[AR] No output yet",
+ "pressToRun": "[AR] Press Ctrl+Enter to run",
+ "completed": "[AR] COMPLETED",
+ "failed": "[AR] FAILED",
+ "signals": "[AR] signals",
+ "clear": "[AR] CLEAR",
+ "errors": "[AR] ERRORS",
+ "signalsSection": "[AR] SIGNALS",
+ "outputSection": "[AR] OUTPUT",
+ "charts": "[AR] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[AR] OHLC",
+ "histogram": "[AR] Histogram",
+ "line": "[AR] Line",
+ "points": "[AR] points"
+ },
+ "statusBar": {
+ "modified": "[AR] MODIFIED",
+ "showOutput": "[AR] SHOW OUTPUT",
+ "encoding": "[AR] UTF-8",
+ "spaces": "[AR] 4 Spaces",
+ "runShortcut": "[AR] Ctrl+Enter: Run",
+ "lines": "[AR] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[AR] Close file without saving?",
+ "unsavedChanges": "[AR] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/ar/common.json b/fincept-terminal-desktop/public/locales/ar/common.json
index db2ebc7a0..ad12e8861 100644
--- a/fincept-terminal-desktop/public/locales/ar/common.json
+++ b/fincept-terminal-desktop/public/locales/ar/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "جار التحميل...",
- "error": "خطأ",
- "success": "نجاح",
- "save": "حفظ",
- "cancel": "إلغاء",
- "delete": "حذف",
- "edit": "تعديل",
- "add": "إضافة",
- "search": "بحث",
- "filter": "تصفية",
- "back": "رجوع",
- "next": "التالي",
- "previous": "السابق",
- "submit": "إرسال",
- "close": "إغلاق",
- "open": "فتح",
- "yes": "نعم",
- "no": "لا",
- "ok": "حسناً",
- "confirm": "تأكيد",
- "language": "اللغة",
- "selectLanguage": "اختر اللغة"
-}
\ No newline at end of file
+ "settings": "[AR] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/ar/dashboard.json b/fincept-terminal-desktop/public/locales/ar/dashboard.json
index 71141bbbf..b3d44ba97 100644
--- a/fincept-terminal-desktop/public/locales/ar/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/ar/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "لوحة تحكم قابلة للتخصيص",
- "live": "يعيش",
- "widgets": "الحاجيات"
- },
- "buttons": {
- "addWidget": "إضافة القطعة",
- "saveLayout": "حفظ التخطيط",
- "reset": "إعادة ضبط",
- "help": "يساعد"
- },
"widgets": {
"loading": "تحميل...",
- "error": "خطأ",
"globalIndices": "المؤشرات العالمية - أعلى 12",
"forex": "الفوركس - الأزواج الرئيسية",
"crypto": "العملات المشفرة",
@@ -20,8 +8,6 @@
"news": "أخبار",
"forum": "المنتدى",
"watchlist": "قائمة المراقبة",
- "maritimeIntelligence": "الاستخبارات البحرية",
- "unknown": "نوع القطعة غير معروف",
"index": "فِهرِس",
"symbol": "رمز",
"price": "سعر",
@@ -38,41 +24,22 @@
"pair": "زوج",
"rate": "معدل",
"commodity": "سلعة",
- "globe3D": "الكرة الأرضية ثلاثية الأبعاد",
- "vessels": "السفن",
- "routes": "الطرق",
- "vol24h": "المجلد 24 ساعة",
- "topTradeCorridors": "أعلى الممرات التجارية",
- "ships": "السفن",
- "marketNews": "أخبار السوق",
- "secPressReleases": "البيانات الصحفية للجنة الأوراق المالية والبورصات",
- "cryptoNews": "أخبار التشفير",
- "trendingForum": "المنتدى الرائج",
- "techStocks": "أسهم التكنولوجيا"
- },
- "tips": {
- "drag": "اسحب الأدوات لإعادة ترتيبها",
- "resize": "تغيير الحجم من الزاوية اليمنى السفلى",
- "remove": "إزالة الحاجيات مع زر X",
- "responsive": "تخطيط سريع الاستجابة - يستخدم العرض الكامل"
- },
- "loading": {
- "title": "تهيئة لوحة المعلومات",
- "description": "جارٍ إعداد ذاكرة التخزين المؤقت لقاعدة البيانات لتحميل البيانات بشكل أسرع...",
- "note": "لن يستغرق هذا سوى لحظة واحدة عند الإطلاق الأول"
- },
- "empty": {
- "noWidgets": "لا الحاجيات على لوحة القيادة",
- "addFirst": "أضف القطعة الأولى الخاصة بك"
- },
- "status": {
- "version": "لوحة معلومات Fincept القابلة للتخصيص v2.0.0 | سحب وإسقاط مساحة العمل",
- "layout": "تَخطِيط",
- "custom": "مخصص",
- "empty": "فارغ",
- "active": "نشيط",
- "cache": "ذاكرة التخزين المؤقت: ممكّنة",
- "label": "حالة"
+ "noActiveMarkets": "[AR] No active markets found",
+ "indicator": "[AR] INDICATOR",
+ "value": "[AR] VALUE",
+ "chg": "[AR] CHG",
+ "overallRisk": "[AR] OVERALL RISK",
+ "openEconomicsTab": "[AR] Open Economics Tab",
+ "openGeopoliticsTab": "[AR] Open Geopolitics Tab",
+ "openPolymarketTab": "[AR] Open Polymarket Tab",
+ "noPortfolioFound": "[AR] No portfolio found",
+ "createPortfolioHint": "[AR] Create one in Portfolio tab",
+ "openPortfolioTab": "[AR] Open Portfolio Tab",
+ "action": "[AR] ACTION",
+ "markets": "[AR] MARKETS",
+ "performanceTracker": "[AR] PERFORMANCE TRACKER",
+ "totalPnL": "[AR] TOTAL P&L",
+ "viewDetailedAnalytics": "[AR] View Detailed Analytics"
},
"messages": {
"layoutSaved": "تم حفظ تخطيط لوحة المعلومات!",
diff --git a/fincept-terminal-desktop/public/locales/ar/geopolitics.json b/fincept-terminal-desktop/public/locales/ar/geopolitics.json
index 6ff6d6bb9..1d2c31e50 100644
--- a/fincept-terminal-desktop/public/locales/ar/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/ar/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "الجيوسياسية",
"messages": {
- "loading": "جاري تحميل البيانات..."
+ "retry": "[AR] RETRY"
+ },
+ "header": {
+ "prefix": "[AR] GEO>",
+ "title": "[AR] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[AR] EVENTS"
+ },
+ "status": {
+ "stale": "[AR] STALE",
+ "loading": "[AR] LOADING...",
+ "error": "[AR] ERROR:"
+ },
+ "filters": {
+ "country": "[AR] Country...",
+ "cities": "[AR] Cities...",
+ "category": "[AR] Category...",
+ "apply": "[AR] APPLY",
+ "clear": "[AR] CLEAR",
+ "clearAllCities": "[AR] Clear all cities",
+ "selectedLabel": "[AR] Selected:"
+ },
+ "panel": {
+ "title": "[AR] INFO PANEL",
+ "expand": "[AR] Expand panel",
+ "collapse": "[AR] Collapse panel",
+ "eventsLoaded": "[AR] EVENTS LOADED",
+ "onMapVisualization": "[AR] on map visualization",
+ "topCategories": "[AR] TOP CATEGORIES",
+ "topCountries": "[AR] TOP COUNTRIES",
+ "eventDetails": "[AR] EVENT DETAILS",
+ "close": "[AR] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[AR] Country:",
+ "city": "[AR] City:",
+ "keywords": "[AR] Keywords:",
+ "coords": "[AR] Coords:",
+ "date": "[AR] Date:",
+ "source": "[AR] Source:",
+ "viewArticle": "[AR] View Article"
+ },
+ "legend": {
+ "title": "[AR] EVENT CATEGORIES",
+ "armedConflict": "[AR] Armed Conflict",
+ "terrorism": "[AR] Terrorism",
+ "protests": "[AR] Protests",
+ "civilianViolence": "[AR] Civilian Violence",
+ "riots": "[AR] Riots",
+ "politicalViolence": "[AR] Political Violence",
+ "crisis": "[AR] Crisis",
+ "explosions": "[AR] Explosions",
+ "strategic": "[AR] Strategic",
+ "unclassified": "[AR] Unclassified"
+ },
+ "footer": {
+ "tabName": "[AR] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[AR] EVENTS",
+ "labelEngine": "[AR] ENGINE",
+ "engineValue": "[AR] DECK.GL v9.2",
+ "labelSource": "[AR] SOURCE",
+ "sourceValue": "[AR] NEWS-EVENTS API",
+ "labelSelected": "[AR] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ar/markets.json b/fincept-terminal-desktop/public/locales/ar/markets.json
index 28fbe43e3..78accefc5 100644
--- a/fincept-terminal-desktop/public/locales/ar/markets.json
+++ b/fincept-terminal-desktop/public/locales/ar/markets.json
@@ -9,13 +9,9 @@
"percentChange": "نسبة التغير",
"high": "الأعلى",
"low": "الأدنى",
- "loading": "جاري التحميل...",
"noData": "لا توجد بيانات",
"refresh": "تحديث",
"auto": "تلقائي",
"on": "مفعل",
- "off": "معطل",
- "lastUpdate": "آخر تحديث",
- "updating": "جاري التحديث",
- "live": "مباشر"
+ "off": "معطل"
}
diff --git a/fincept-terminal-desktop/public/locales/ar/news.json b/fincept-terminal-desktop/public/locales/ar/news.json
index 0d92bed4d..2618b3fbb 100644
--- a/fincept-terminal-desktop/public/locales/ar/news.json
+++ b/fincept-terminal-desktop/public/locales/ar/news.json
@@ -1,32 +1,63 @@
{
"title": "أخبار محطة FINCEPT الاحترافية",
"header": {
- "liveFeed": "بث مباشر",
- "live": "مباشر",
- "refresh": "تحديث",
- "updating": "جاري التحديث...",
- "alerts": "التنبيهات",
- "sources": "المصادر",
- "status": "الحالة",
- "demoMode": "وضع تجريبي",
- "articles": "المقالات",
- "activeSources": "المصادر النشطة"
- },
- "autoRefresh": {
- "title": "فترة التحديث التلقائي",
- "minute": "دقيقة",
- "minutes": "دقائق"
+ "refresh": "تحديث"
},
"messages": {
- "loadingFeeds": "جاري تحميل الموجزات...",
- "breaking": "عاجل"
- },
- "feeds": {
- "primary": "[AR] PRIMARY NEWS FEED",
- "secondary": "[AR] SECONDARY NEWS FEED",
- "additional": "[AR] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[AR] Loading feeds...",
+ "failedToLoad": "[AR] Failed to load RSS feeds",
+ "noCustomFeeds": "[AR] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[AR] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[AR] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[AR] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[AR] RSS FEED SETTINGS",
+ "subtitle": "[AR] MANAGE YOUR NEWS SOURCES",
+ "close": "[AR] CLOSE",
+ "myFeeds": "[AR] MY FEEDS",
+ "defaultFeeds": "[AR] DEFAULT FEEDS",
+ "noFeedsAvailable": "[AR] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[AR] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[AR] ADD NEW FEED",
+ "addNewRssFeed": "[AR] ADD NEW RSS FEED",
+ "editRssFeed": "[AR] EDIT RSS FEED",
+ "restoreDefaults": "[AR] RESTORE DEFAULTS",
+ "restoreAll": "[AR] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[AR] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[AR] DISPLAY NAME",
+ "sourceName": "[AR] SOURCE NAME (SHORT)",
+ "feedUrl": "[AR] RSS FEED URL",
+ "category": "[AR] CATEGORY",
+ "region": "[AR] REGION",
+ "required": "[AR] *",
+ "testUrl": "[AR] TEST URL",
+ "testing": "[AR] TESTING...",
+ "valid": "[AR] VALID",
+ "cancel": "[AR] CANCEL",
+ "saving": "[AR] SAVING...",
+ "addFeed": "[AR] ADD FEED",
+ "updateFeed": "[AR] UPDATE FEED",
+ "on": "[AR] ON",
+ "off": "[AR] OFF",
+ "default": "[AR] DEFAULT",
+ "total": "[AR] TOTAL",
+ "active": "[AR] ACTIVE",
+ "custom": "[AR] CUSTOM",
+ "placeholders": {
+ "displayName": "[AR] e.g., Bloomberg Markets",
+ "sourceName": "[AR] e.g., BLOOMBERG",
+ "feedUrl": "[AR] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[AR] Name is required",
+ "sourceRequired": "[AR] Source name is required",
+ "invalidUrl": "[AR] Please enter a valid URL",
+ "invalidRss": "[AR] URL does not appear to be a valid RSS feed",
+ "testFailed": "[AR] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[AR] Delete this RSS feed?",
+ "message": "[AR] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/ar/portfolio.json b/fincept-terminal-desktop/public/locales/ar/portfolio.json
index 32566772f..d5bb8ee46 100644
--- a/fincept-terminal-desktop/public/locales/ar/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/ar/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "مدير محفظة FINCEPT",
- "header": {
- "live": "مباشر",
- "updating": "جاري التحديث",
- "newPortfolio": "محفظة جديدة",
- "refresh": "تحديث",
- "exportCsv": "تصدير CSV"
- },
- "summary": {
- "totalValue": "القيمة الإجمالية",
- "dayPnl": "ربح/خسارة اليوم",
- "totalPnl": "إجمالي الربح/الخسارة",
- "positions": "المراكز"
- },
- "views": {
- "positions": "المراكز",
- "addAsset": "إضافة أصل",
- "sellAsset": "بيع أصل",
- "analytics": "التحليلات",
- "history": "السجل",
- "activeMgmt": "الإدارة النشطة",
- "performance": "الأداء",
- "rebalance": "إعادة التوازن",
- "reports": "التقارير",
- "alerts": "التنبيهات",
- "sectors": "القطاعات",
- "help": "المساعدة"
- },
- "sidebar": {
- "portfolios": "المحافظ",
- "loading": "جاري تحميل المحافظ...",
- "noPortfolios": "لا توجد محافظ بعد.",
- "clickCreate": "انقر على محفظة جديدة لإنشاء واحدة.",
- "owner": "المالك",
- "currency": "العملة"
- },
- "content": {
- "selectOrCreate": "اختر محفظة أو أنشئ واحدة جديدة للبدء",
- "loadingData": "جاري تحميل بيانات المحفظة...",
- "comingSoon": "العرض قريباً..."
- },
- "modals": {
- "createNew": "إنشاء محفظة جديدة",
- "portfolioName": "اسم المحفظة",
- "owner": "المالك",
- "currency": "العملة",
- "cancel": "إلغاء",
- "create": "إنشاء",
- "addAssetTitle": "إضافة أصل للمحفظة",
- "sellAssetTitle": "بيع أصل",
- "symbol": "الرمز",
- "quantity": "الكمية",
- "price": "السعر",
- "add": "إضافة",
- "sell": "بيع"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | تتبع فوري مع تكامل yfinance",
- "lastUpdated": "آخر تحديث",
- "connected": "متصل"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "إنشاء محفظة جديدة",
+ "portfolioName": "اسم المحفظة",
+ "owner": "المالك",
+ "currency": "العملة",
+ "cancel": "إلغاء",
+ "create": "إنشاء",
+ "addAssetTitle": "إضافة أصل للمحفظة",
+ "sellAssetTitle": "بيع أصل",
+ "symbol": "الرمز",
+ "quantity": "الكمية",
+ "price": "السعر",
+ "add": "إضافة",
+ "sell": "بيع"
+ },
+ "extracted": {
+ "areYouSureYou": "[AR] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/ar/reportBuilder.json b/fincept-terminal-desktop/public/locales/ar/reportBuilder.json
index a16d82dc0..16250dd36 100644
--- a/fincept-terminal-desktop/public/locales/ar/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/ar/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[AR] Load",
"save": "[AR] Save",
- "saving": "[AR] Saving...",
- "exportPdf": "[AR] Export PDF",
- "generating": "[AR] Generating..."
+ "saving": "[AR] Saving..."
},
"components": {
"title": "[AR] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/ar/settings.json b/fincept-terminal-desktop/public/locales/ar/settings.json
index 47481da24..b9fdfffee 100644
--- a/fincept-terminal-desktop/public/locales/ar/settings.json
+++ b/fincept-terminal-desktop/public/locales/ar/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "تخطيط علامة التبويب",
"appearance": "مظهر",
"language": "لغة",
- "storage": "التخزين وذاكرة التخزين المؤقت"
+ "storage": "التخزين وذاكرة التخزين المؤقت",
+ "notifications": "[AR] Notifications"
},
"credentials": {
"title": "إدارة بيانات اعتماد API",
@@ -46,7 +47,31 @@
"saveConfig": "حفظ التكوين",
"reset": "إعادة ضبط",
"saveSuccess": "تم حفظ مظهر المحطة الطرفية وتعيينات المفاتيح بنجاح",
- "resetSuccess": "إعادة التعيين إلى المظهر الافتراضي وتعيينات المفاتيح"
+ "resetSuccess": "إعادة التعيين إلى المظهر الافتراضي وتعيينات المفاتيح",
+ "customColors": "[AR] Custom Colors",
+ "customColorsTitle": "[AR] CUSTOM COLORS",
+ "colorPrimary": "[AR] Primary",
+ "colorSecondary": "[AR] Secondary",
+ "colorSuccess": "[AR] Success",
+ "colorAlert": "[AR] Alert",
+ "colorWarning": "[AR] Warning",
+ "colorInfo": "[AR] Info",
+ "colorAccent": "[AR] Accent",
+ "colorPurple": "[AR] Purple",
+ "colorText": "[AR] Text",
+ "colorTextMuted": "[AR] Text Muted",
+ "colorBackground": "[AR] Background",
+ "colorPanel": "[AR] Panel",
+ "layoutSpacing": "[AR] LAYOUT & SPACING",
+ "contentDensity": "[AR] CONTENT DENSITY",
+ "borderRadius": "[AR] BORDER RADIUS",
+ "borderStyle": "[AR] BORDER STYLE",
+ "lineHeight": "[AR] LINE HEIGHT",
+ "letterSpacing": "[AR] LETTER SPACING",
+ "effects": "[AR] EFFECTS",
+ "widgetOpacity": "[AR] WIDGET OPACITY",
+ "enableGlow": "[AR] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[AR] GLOW INTENSITY"
},
"stockSymbols": {
"title": "قاعدة بيانات رمز الأسهم",
@@ -65,17 +90,8 @@
"tip": "نصيحة: اسحب علامات التبويب لإعادة ترتيبها. استخدم أزرار الأسهم لتحريك علامات التبويب بين أقسام الرأس والقائمة. يتم حفظ التغييرات تلقائيا."
},
"llm": {
- "title": "تكوين ماجستير",
- "description": "تكوين نماذج وموفري الذكاء الاصطناعي",
"connected": "متصل",
- "disconnected": "غير متصل",
- "provider": "مزود الذكاء الاصطناعي",
- "globalSettings": "إعدادات الذكاء الاصطناعي العالمية",
- "temperature": "درجة حرارة",
- "maxTokens": "الحد الأقصى من الرموز",
- "systemPrompt": "موجه النظام",
- "modelLibrary": "المكتبة النموذجية",
- "multiModelConfigs": "تكوينات متعددة النماذج"
+ "disconnected": "غير متصل"
},
"buttons": {
"save": "يحفظ",
@@ -86,5 +102,18 @@
"database": "قاعدة البيانات: سكليتي",
"storage": "التخزين: قائم على الملفات",
"secureStorage": "جميع البيانات مخزنة بشكل آمن في fincept_terminal.db"
+ },
+ "notifications": {
+ "title": "[AR] NOTIFICATION PROVIDERS",
+ "description": "[AR] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[AR] Event Filters",
+ "eventFilterDescription": "[AR] Choose which notification types to forward to external providers.",
+ "providers": "[AR] Providers",
+ "enabled": "[AR] Enabled",
+ "disabled": "[AR] Disabled",
+ "testButton": "[AR] TEST",
+ "testSuccess": "[AR] Test notification sent successfully!",
+ "testFailed": "[AR] Failed to send test notification. Check your configuration.",
+ "saved": "[AR] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ar/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/ar/surfaceAnalytics.json
new file mode 100644
index 000000000..f111aaa0d
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/ar/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[AR] SURFACE ANALYTICS",
+ "initializing": "[AR] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[AR] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[AR] VOL SURFACE",
+ "correlation": "[AR] CORRELATION",
+ "yieldCurve": "[AR] YIELD CURVE",
+ "pca": "[AR] PCA FACTORS"
+ },
+ "demoData": "[AR] DEMO DATA",
+ "demoDataSynthetic": "[AR] DEMO DATA (synthetic)",
+ "synthetic": "[AR] SYNTHETIC",
+ "manual": "[AR] MANUAL",
+ "error": "[AR] ERROR",
+ "ready": "[AR] READY",
+ "metrics": "[AR] Metrics",
+ "updated": "[AR] Updated",
+ "clickRefresh": "[AR] Click REFRESH to load data",
+ "refresh": "[AR] REFRESH",
+ "noApiKey": "[AR] NO API KEY",
+ "lastUpdate": "[AR] LAST UPDATE",
+ "loadingData": "[AR] LOADING DATA...",
+ "noDataLoaded": "[AR] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[AR] IV SURFACE METRICS",
+ "correlationMetrics": "[AR] CORRELATION METRICS",
+ "yieldCurveMetrics": "[AR] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[AR] PCA FACTOR METRICS",
+ "dataInfo": "[AR] DATA INFO",
+ "source": "[AR] SOURCE",
+ "frequency": "[AR] FREQUENCY",
+ "quality": "[AR] QUALITY",
+ "correlationScale": "[AR] CORRELATION SCALE",
+ "strongPositive": "[AR] Strong Positive (0.7-1.0)",
+ "neutral": "[AR] Neutral (0.3-0.7)",
+ "strongNegative": "[AR] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[AR] IV INTERPRETATION",
+ "highIv": "[AR] High IV = Expensive Options",
+ "lowIv": "[AR] Low IV = Cheap Options",
+ "skew": "[AR] Skew = Put/Call IV Diff",
+ "termStructure": "[AR] Term Structure = Time Effect",
+ "pcaInterpretation": "[AR] PCA INTERPRETATION",
+ "pc1": "[AR] PC1 = Market Factor",
+ "pc2": "[AR] PC2 = Size/Value Factor",
+ "pc3": "[AR] PC3 = Sector Rotation",
+ "higherVar": "[AR] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[AR] STRIKE",
+ "dte": "[AR] DTE",
+ "iv": "[AR] IV",
+ "correlation": "[AR] CORRELATION",
+ "maturity": "[AR] MATURITY",
+ "yield": "[AR] YIELD",
+ "loading": "[AR] LOADING",
+ "strikePrice": "[AR] STRIKE PRICE",
+ "daysToExpiry": "[AR] DAYS TO EXPIRY",
+ "impliedVol": "[AR] IMPLIED VOL (%)",
+ "assetPairIndex": "[AR] ASSET PAIR INDEX",
+ "timeDays": "[AR] TIME (DAYS)",
+ "correlationCoeff": "[AR] CORRELATION COEFF",
+ "maturityMonths": "[AR] MATURITY (MONTHS)",
+ "historicalDays": "[AR] HISTORICAL DAYS",
+ "yieldPercent": "[AR] YIELD (%)",
+ "principalComponent": "[AR] PRINCIPAL COMPONENT",
+ "assetIndex": "[AR] ASSET INDEX",
+ "factorLoading": "[AR] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[AR] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[AR] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[AR] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[AR] DAY ROLLING",
+ "yieldCurve": "[AR] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[AR] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[AR] FAILED TO LOAD DATA",
+ "authFailed": "[AR] AUTHENTICATION FAILED",
+ "authFailedHelp": "[AR] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[AR] ACCESS DENIED",
+ "accessDeniedHelp": "[AR] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[AR] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[AR] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[AR] DATA TIMEFRAME",
+ "schema": "[AR] Schema",
+ "description": "[AR] Description",
+ "recordsPerDay": "[AR] Records/Day",
+ "highFrequencyWarning": "[AR] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[AR] Data Volume"
+ },
+ "settings": {
+ "title": "[AR] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[AR] DATABENTO API KEY",
+ "configured": "[AR] CONFIGURED",
+ "invalidFormat": "[AR] INVALID FORMAT",
+ "apiKeyConfigured": "[AR] API key is configured (db-*****)",
+ "remove": "[AR] REMOVE",
+ "enterApiKey": "[AR] Enter your Databento API key (db-*****)",
+ "save": "[AR] SAVE",
+ "saving": "[AR] SAVING...",
+ "getApiKeyFrom": "[AR] Get your API key from",
+ "dashboardApiKeys": "[AR] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[AR] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[AR] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[AR] CORRELATION ASSETS",
+ "addSymbol": "[AR] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[AR] Reset to defaults",
+ "historicalDateRange": "[AR] HISTORICAL DATE RANGE",
+ "start": "[AR] Start",
+ "end": "[AR] End",
+ "autoRefreshInterval": "[AR] AUTO REFRESH INTERVAL",
+ "manualOnly": "[AR] Manual Only",
+ "every1min": "[AR] Every 1 minute",
+ "every5min": "[AR] Every 5 minutes",
+ "every15min": "[AR] Every 15 minutes",
+ "every1hour": "[AR] Every 1 hour",
+ "browseDatasets": "[AR] BROWSE DATASETS",
+ "costEstimator": "[AR] COST ESTIMATOR",
+ "referenceData": "[AR] REFERENCE DATA",
+ "orderBook": "[AR] ORDER BOOK",
+ "liveStreaming": "[AR] LIVE STREAMING",
+ "active": "[AR] ACTIVE",
+ "futuresCme": "[AR] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[AR] BATCH DOWNLOADS",
+ "additionalSchemas": "[AR] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[AR] TRADES, IMBALANCE, STATUS",
+ "cancel": "[AR] CANCEL",
+ "saveChanges": "[AR] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[AR] BATCH DOWNLOADS",
+ "newBatchJob": "[AR] NEW BATCH JOB",
+ "dataset": "[AR] Dataset",
+ "schema": "[AR] Schema",
+ "symbolsCommaSeparated": "[AR] Symbols (comma-separated)",
+ "startDate": "[AR] Start Date",
+ "endDate": "[AR] End Date",
+ "encoding": "[AR] Encoding",
+ "compression": "[AR] Compression",
+ "submitJob": "[AR] SUBMIT JOB",
+ "noBatchJobs": "[AR] No batch jobs found. Click + to create one.",
+ "records": "[AR] records",
+ "download": "[AR] Download",
+ "files": "[AR] FILES",
+ "jobsExpireNotice": "[AR] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[AR] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[AR] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[AR] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[AR] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[AR] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[AR] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[AR] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[AR] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[AR] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[AR] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[AR] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[AR] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[AR] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[AR] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[AR] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[AR] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[AR] [EN] common.or",
+ "note": "[AR] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/ar/tabs.json b/fincept-terminal-desktop/public/locales/ar/tabs.json
index 673a623c5..58e8787f1 100644
--- a/fincept-terminal-desktop/public/locales/ar/tabs.json
+++ b/fincept-terminal-desktop/public/locales/ar/tabs.json
@@ -5,29 +5,7 @@
"news": "الأخبار",
"portfolio": "المحفظة",
"backtesting": "الاختبار الخلفي",
- "watchlist": "قائمة المراقبة",
- "research": "البحث",
- "screener": "الفرز",
"chat": "الذكاء الاصطناعي",
- "agents": "الوكلاء",
- "settings": "الإعدادات",
"profile": "الملف الشخصي"
- },
- "functionKeys": {
- "f1": "لوحة",
- "f2": "أسواق",
- "f3": "أخبار",
- "f4": "محفظة",
- "f5": "اختبار",
- "f6": "مراقبة",
- "f7": "بحث",
- "f8": "فرز",
- "f9": "تداول",
- "f10": "ذكاء",
- "f11": "كامل",
- "f12": "ملف"
- },
- "labels": {
- "moreTabs": "المزيد من علامات التبويب في قوائم شريط الأدوات"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ar/watchlist.json b/fincept-terminal-desktop/public/locales/ar/watchlist.json
index 7f4943015..c5ee8d8d9 100644
--- a/fincept-terminal-desktop/public/locales/ar/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/ar/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "قائمة المراقبة",
- "header": {
- "export": "تصدير",
- "updating": "تحديث",
- "live": "مباشر"
- },
"sidebar": {
- "groups": "مجموعات القوائم",
- "new": "جديد",
"noWatchlists": "لا توجد قوائم بعد.",
"clickNew": "انقر جديد للإنشاء.",
- "stocks": "أسهم",
- "marketMovers": "المحركون",
- "gainer": "الرابحون",
- "loser": "الخاسرون",
- "volumeLeaders": "الأعلى حجماً"
- },
- "emptyState": {
- "selectWatchlist": "اختر قائمة أو أنشئ واحدة جديدة"
- },
- "list": {
- "symbols": "الرموز"
+ "stocks": "أسهم"
}
}
diff --git a/fincept-terminal-desktop/public/locales/bn/codeEditor.json b/fincept-terminal-desktop/public/locales/bn/codeEditor.json
index 0bba8b3c3..a39787402 100644
--- a/fincept-terminal-desktop/public/locales/bn/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/bn/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "কোড এডিটর",
"header": {
- "packages": "প্যাকেজ"
+ "finscriptIde": "[BN] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "নতুন ফাইল",
- "new": "নতুন",
- "open": "খুলুন",
- "save": "সংরক্ষণ",
"run": "কোড চালান",
"running": "চলছে...",
- "runAll": "সব চালান",
- "history": "ইতিহাস"
+ "toggleExplorer": "[BN] Toggle Explorer (Ctrl+B)",
+ "openFile": "[BN] Open File",
+ "saveShortcut": "[BN] Save (Ctrl+S)",
+ "findShortcut": "[BN] Find (Ctrl+F)",
+ "runShortcut": "[BN] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "জুপিটার নোটবুক",
"finscript": "ফিনস্ক্রিপ্ট এডিটর"
},
- "packages": {
- "clickToLoad": "প্যাকেজ লোড করতে ক্লিক করুন...",
- "load": "প্যাকেজ লোড করুন"
+ "explorer": {
+ "title": "[BN] EXPLORER",
+ "openFiles": "[BN] OPEN FILES",
+ "examples": "[BN] EXAMPLES",
+ "runHistory": "[BN] RUN HISTORY",
+ "finscriptEngine": "[BN] FinScript Engine"
},
- "history": {
- "title": "নোটবুক ইতিহাস",
- "loading": "ইতিহাস লোড হচ্ছে...",
- "empty": "এখনো কোনো নোটবুক ইতিহাস নেই"
+ "output": {
+ "title": "[BN] OUTPUT",
+ "success": "[BN] SUCCESS",
+ "error": "[BN] ERROR",
+ "executing": "[BN] EXECUTING FINSCRIPT...",
+ "noOutput": "[BN] No output yet",
+ "pressToRun": "[BN] Press Ctrl+Enter to run",
+ "completed": "[BN] COMPLETED",
+ "failed": "[BN] FAILED",
+ "signals": "[BN] signals",
+ "clear": "[BN] CLEAR",
+ "errors": "[BN] ERRORS",
+ "signalsSection": "[BN] SIGNALS",
+ "outputSection": "[BN] OUTPUT",
+ "charts": "[BN] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[BN] OHLC",
+ "histogram": "[BN] Histogram",
+ "line": "[BN] Line",
+ "points": "[BN] points"
+ },
+ "statusBar": {
+ "modified": "[BN] MODIFIED",
+ "showOutput": "[BN] SHOW OUTPUT",
+ "encoding": "[BN] UTF-8",
+ "spaces": "[BN] 4 Spaces",
+ "runShortcut": "[BN] Ctrl+Enter: Run",
+ "lines": "[BN] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[BN] Close file without saving?",
+ "unsavedChanges": "[BN] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/bn/common.json b/fincept-terminal-desktop/public/locales/bn/common.json
index 701db02f6..e7dcfb394 100644
--- a/fincept-terminal-desktop/public/locales/bn/common.json
+++ b/fincept-terminal-desktop/public/locales/bn/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "লোড হচ্ছে...",
- "error": "ত্রুটি",
- "success": "সফল",
- "save": "সংরক্ষণ করুন",
- "cancel": "বাতিল",
- "delete": "মুছে ফেলুন",
- "edit": "সম্পাদনা",
- "add": "যোগ করুন",
- "search": "অনুসন্ধান",
- "filter": "ফিল্টার",
- "back": "পিছনে",
- "next": "পরবর্তী",
- "previous": "পূর্ববর্তী",
- "submit": "জমা দিন",
- "close": "বন্ধ করুন",
- "open": "খুলুন",
- "yes": "হ্যাঁ",
- "no": "না",
- "ok": "ঠিক আছে",
- "confirm": "নিশ্চিত করুন",
- "language": "ভাষা",
- "selectLanguage": "ভাষা নির্বাচন করুন"
-}
\ No newline at end of file
+ "settings": "[BN] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/bn/dashboard.json b/fincept-terminal-desktop/public/locales/bn/dashboard.json
index c5b44a6b2..c042baeb9 100644
--- a/fincept-terminal-desktop/public/locales/bn/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/bn/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "কাস্টমাইজেবল ড্যাশবোর্ড",
- "live": "লাইভ",
- "widgets": "উইজেটস"
- },
- "buttons": {
- "addWidget": "উইজেট যোগ করুন",
- "saveLayout": "লেআউট সংরক্ষণ করুন",
- "reset": "রিসেট",
- "help": "সাহায্য"
- },
"widgets": {
"loading": "লোড হচ্ছে...",
- "error": "ত্রুটি",
"globalIndices": "বৈশ্বিক সূচক - শীর্ষ 12",
"forex": "ফরেক্স - প্রধান জোড়া",
"crypto": "ক্রিপ্টোকারেন্সি",
@@ -20,8 +8,6 @@
"news": "সংবাদ",
"forum": "ফোরাম",
"watchlist": "ওয়াচলিস্ট",
- "maritimeIntelligence": "মেরিটাইম ইন্টেলিজেন্স",
- "unknown": "অজানা উইজেট প্রকার",
"index": "INDEX",
"symbol": "SYMBOL",
"price": "PRICE",
@@ -38,41 +24,22 @@
"pair": "জোড়া",
"rate": "হার",
"commodity": "কমোডিটি",
- "globe3D": "3D গ্লোব",
- "vessels": "জাহাজ",
- "routes": "রুট",
- "vol24h": "VOL 24H",
- "topTradeCorridors": "শীর্ষ বাণিজ্য করিডোর",
- "ships": "জাহাজ",
- "marketNews": "বাজারের খবর",
- "secPressReleases": "এসইসি প্রেস রিলিজ",
- "cryptoNews": "ক্রিপ্টো খবর",
- "trendingForum": "ট্রেন্ডিং ফোরাম",
- "techStocks": "টেক স্টক"
- },
- "tips": {
- "drag": "পুনরায় সাজাতে উইজেট টেনে আনুন",
- "resize": "নীচে-ডান কোণ থেকে আকার পরিবর্তন করুন",
- "remove": "এক্স বোতাম দিয়ে উইজেটগুলি সরান",
- "responsive": "প্রতিক্রিয়াশীল লেআউট - সম্পূর্ণ প্রস্থ ব্যবহার করে"
- },
- "loading": {
- "title": "ড্যাশবোর্ড শুরু করা হচ্ছে",
- "description": "দ্রুত ডেটা লোড করার জন্য ডাটাবেস ক্যাশে সেট আপ করা হচ্ছে...",
- "note": "প্রথম লঞ্চে এটি শুধুমাত্র একটি মুহূর্ত লাগবে"
- },
- "empty": {
- "noWidgets": "ড্যাশবোর্ডে কোন উইজেট নেই",
- "addFirst": "আপনার প্রথম উইজেট যোগ করুন"
- },
- "status": {
- "version": "Fincept কাস্টমাইজযোগ্য ড্যাশবোর্ড v2.0.0 | ওয়ার্কস্পেস টেনে আনুন",
- "layout": "লেআউট",
- "custom": "কাস্টম",
- "empty": "খালি",
- "active": "সক্রিয়",
- "cache": "ক্যাশে: সক্ষম",
- "label": "স্ট্যাটাস"
+ "noActiveMarkets": "[BN] No active markets found",
+ "indicator": "[BN] INDICATOR",
+ "value": "[BN] VALUE",
+ "chg": "[BN] CHG",
+ "overallRisk": "[BN] OVERALL RISK",
+ "openEconomicsTab": "[BN] Open Economics Tab",
+ "openGeopoliticsTab": "[BN] Open Geopolitics Tab",
+ "openPolymarketTab": "[BN] Open Polymarket Tab",
+ "noPortfolioFound": "[BN] No portfolio found",
+ "createPortfolioHint": "[BN] Create one in Portfolio tab",
+ "openPortfolioTab": "[BN] Open Portfolio Tab",
+ "action": "[BN] ACTION",
+ "markets": "[BN] MARKETS",
+ "performanceTracker": "[BN] PERFORMANCE TRACKER",
+ "totalPnL": "[BN] TOTAL P&L",
+ "viewDetailedAnalytics": "[BN] View Detailed Analytics"
},
"messages": {
"layoutSaved": "ড্যাশবোর্ড লেআউট সংরক্ষিত!",
diff --git a/fincept-terminal-desktop/public/locales/bn/geopolitics.json b/fincept-terminal-desktop/public/locales/bn/geopolitics.json
index 2dad0954d..9eaf6cbc4 100644
--- a/fincept-terminal-desktop/public/locales/bn/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/bn/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "ভূ-রাজনীতি",
"messages": {
- "loading": "ডেটা লোড হচ্ছে..."
+ "retry": "[BN] RETRY"
+ },
+ "header": {
+ "prefix": "[BN] GEO>",
+ "title": "[BN] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[BN] EVENTS"
+ },
+ "status": {
+ "stale": "[BN] STALE",
+ "loading": "[BN] LOADING...",
+ "error": "[BN] ERROR:"
+ },
+ "filters": {
+ "country": "[BN] Country...",
+ "cities": "[BN] Cities...",
+ "category": "[BN] Category...",
+ "apply": "[BN] APPLY",
+ "clear": "[BN] CLEAR",
+ "clearAllCities": "[BN] Clear all cities",
+ "selectedLabel": "[BN] Selected:"
+ },
+ "panel": {
+ "title": "[BN] INFO PANEL",
+ "expand": "[BN] Expand panel",
+ "collapse": "[BN] Collapse panel",
+ "eventsLoaded": "[BN] EVENTS LOADED",
+ "onMapVisualization": "[BN] on map visualization",
+ "topCategories": "[BN] TOP CATEGORIES",
+ "topCountries": "[BN] TOP COUNTRIES",
+ "eventDetails": "[BN] EVENT DETAILS",
+ "close": "[BN] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[BN] Country:",
+ "city": "[BN] City:",
+ "keywords": "[BN] Keywords:",
+ "coords": "[BN] Coords:",
+ "date": "[BN] Date:",
+ "source": "[BN] Source:",
+ "viewArticle": "[BN] View Article"
+ },
+ "legend": {
+ "title": "[BN] EVENT CATEGORIES",
+ "armedConflict": "[BN] Armed Conflict",
+ "terrorism": "[BN] Terrorism",
+ "protests": "[BN] Protests",
+ "civilianViolence": "[BN] Civilian Violence",
+ "riots": "[BN] Riots",
+ "politicalViolence": "[BN] Political Violence",
+ "crisis": "[BN] Crisis",
+ "explosions": "[BN] Explosions",
+ "strategic": "[BN] Strategic",
+ "unclassified": "[BN] Unclassified"
+ },
+ "footer": {
+ "tabName": "[BN] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[BN] EVENTS",
+ "labelEngine": "[BN] ENGINE",
+ "engineValue": "[BN] DECK.GL v9.2",
+ "labelSource": "[BN] SOURCE",
+ "sourceValue": "[BN] NEWS-EVENTS API",
+ "labelSelected": "[BN] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/bn/markets.json b/fincept-terminal-desktop/public/locales/bn/markets.json
index 82b78d094..2f9d7178a 100644
--- a/fincept-terminal-desktop/public/locales/bn/markets.json
+++ b/fincept-terminal-desktop/public/locales/bn/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%পরিবর্তন",
"high": "উচ্চ",
"low": "নিম্ন",
- "loading": "লোড হচ্ছে...",
"noData": "কোনো ডেটা নেই",
"refresh": "রিফ্রেশ",
"auto": "স্বয়ংক্রিয়",
"on": "চালু",
- "off": "বন্ধ",
- "lastUpdate": "শেষ আপডেট",
- "updating": "আপডেট হচ্ছে",
- "live": "লাইভ"
+ "off": "বন্ধ"
}
diff --git a/fincept-terminal-desktop/public/locales/bn/news.json b/fincept-terminal-desktop/public/locales/bn/news.json
index b50f5d5d9..50fe895de 100644
--- a/fincept-terminal-desktop/public/locales/bn/news.json
+++ b/fincept-terminal-desktop/public/locales/bn/news.json
@@ -1,32 +1,63 @@
{
"title": "FINCEPT টার্মিনাল পেশাদার সংবাদ",
"header": {
- "liveFeed": "লাইভ ফিড",
- "live": "লাইভ",
- "refresh": "রিফ্রেশ",
- "updating": "আপডেট হচ্ছে...",
- "alerts": "সতর্কতা",
- "sources": "উৎস",
- "status": "স্থিতি",
- "demoMode": "ডেমো মোড",
- "articles": "নিবন্ধ",
- "activeSources": "সক্রিয় উৎস"
- },
- "autoRefresh": {
- "title": "স্বয়ংক্রিয় রিফ্রেশ বিরতি",
- "minute": "মিনিট",
- "minutes": "মিনিট"
+ "refresh": "রিফ্রেশ"
},
"messages": {
- "loadingFeeds": "ফিড লোড হচ্ছে...",
- "breaking": "ব্রেকিং"
- },
- "feeds": {
- "primary": "[BN] PRIMARY NEWS FEED",
- "secondary": "[BN] SECONDARY NEWS FEED",
- "additional": "[BN] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[BN] Loading feeds...",
+ "failedToLoad": "[BN] Failed to load RSS feeds",
+ "noCustomFeeds": "[BN] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[BN] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[BN] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[BN] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[BN] RSS FEED SETTINGS",
+ "subtitle": "[BN] MANAGE YOUR NEWS SOURCES",
+ "close": "[BN] CLOSE",
+ "myFeeds": "[BN] MY FEEDS",
+ "defaultFeeds": "[BN] DEFAULT FEEDS",
+ "noFeedsAvailable": "[BN] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[BN] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[BN] ADD NEW FEED",
+ "addNewRssFeed": "[BN] ADD NEW RSS FEED",
+ "editRssFeed": "[BN] EDIT RSS FEED",
+ "restoreDefaults": "[BN] RESTORE DEFAULTS",
+ "restoreAll": "[BN] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[BN] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[BN] DISPLAY NAME",
+ "sourceName": "[BN] SOURCE NAME (SHORT)",
+ "feedUrl": "[BN] RSS FEED URL",
+ "category": "[BN] CATEGORY",
+ "region": "[BN] REGION",
+ "required": "[BN] *",
+ "testUrl": "[BN] TEST URL",
+ "testing": "[BN] TESTING...",
+ "valid": "[BN] VALID",
+ "cancel": "[BN] CANCEL",
+ "saving": "[BN] SAVING...",
+ "addFeed": "[BN] ADD FEED",
+ "updateFeed": "[BN] UPDATE FEED",
+ "on": "[BN] ON",
+ "off": "[BN] OFF",
+ "default": "[BN] DEFAULT",
+ "total": "[BN] TOTAL",
+ "active": "[BN] ACTIVE",
+ "custom": "[BN] CUSTOM",
+ "placeholders": {
+ "displayName": "[BN] e.g., Bloomberg Markets",
+ "sourceName": "[BN] e.g., BLOOMBERG",
+ "feedUrl": "[BN] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[BN] Name is required",
+ "sourceRequired": "[BN] Source name is required",
+ "invalidUrl": "[BN] Please enter a valid URL",
+ "invalidRss": "[BN] URL does not appear to be a valid RSS feed",
+ "testFailed": "[BN] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[BN] Delete this RSS feed?",
+ "message": "[BN] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/bn/portfolio.json b/fincept-terminal-desktop/public/locales/bn/portfolio.json
index 8bbda2482..f5218f7c9 100644
--- a/fincept-terminal-desktop/public/locales/bn/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/bn/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "FINCEPT পোর্টফোলিও ম্যানেজার",
- "header": {
- "live": "লাইভ",
- "updating": "আপডেট হচ্ছে",
- "newPortfolio": "নতুন পোর্টফোলিও",
- "refresh": "রিফ্রেশ",
- "exportCsv": "CSV এক্সপোর্ট"
- },
- "summary": {
- "totalValue": "মোট মূল্য",
- "dayPnl": "দৈনিক লাভ/ক্ষতি",
- "totalPnl": "মোট লাভ/ক্ষতি",
- "positions": "পজিশন"
- },
- "views": {
- "positions": "পজিশন",
- "addAsset": "সম্পদ যোগ করুন",
- "sellAsset": "সম্পদ বিক্রি করুন",
- "analytics": "বিশ্লেষণ",
- "history": "ইতিহাস",
- "activeMgmt": "সক্রিয় ব্যবস্থাপনা",
- "performance": "কর্মক্ষমতা",
- "rebalance": "পুনঃসমন্বয়",
- "reports": "রিপোর্ট",
- "alerts": "সতর্কতা",
- "sectors": "সেক্টর",
- "help": "সহায়তা"
- },
- "sidebar": {
- "portfolios": "পোর্টফোলিও",
- "loading": "পোর্টফোলিও লোড হচ্ছে...",
- "noPortfolios": "এখনও কোনো পোর্টফোলিও নেই।",
- "clickCreate": "তৈরি করতে নতুন পোর্টফোলিও-তে ক্লিক করুন।",
- "owner": "মালিক",
- "currency": "মুদ্রা"
- },
- "content": {
- "selectOrCreate": "শুরু করতে একটি পোর্টফোলিও নির্বাচন করুন বা নতুন তৈরি করুন",
- "loadingData": "পোর্টফোলিও ডেটা লোড হচ্ছে...",
- "comingSoon": "শীঘ্রই আসছে..."
- },
- "modals": {
- "createNew": "নতুন পোর্টফোলিও তৈরি করুন",
- "portfolioName": "পোর্টফোলিও নাম",
- "owner": "মালিক",
- "currency": "মুদ্রা",
- "cancel": "বাতিল",
- "create": "তৈরি করুন",
- "addAssetTitle": "পোর্টফোলিওতে সম্পদ যোগ করুন",
- "sellAssetTitle": "সম্পদ বিক্রি করুন",
- "symbol": "সিম্বল",
- "quantity": "পরিমাণ",
- "price": "মূল্য",
- "add": "যোগ করুন",
- "sell": "বিক্রি করুন"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | yfinance ইন্টিগ্রেশন সহ রিয়েল-টাইম ট্র্যাকিং",
- "lastUpdated": "সর্বশেষ আপডেট",
- "connected": "সংযুক্ত"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "নতুন পোর্টফোলিও তৈরি করুন",
+ "portfolioName": "পোর্টফোলিও নাম",
+ "owner": "মালিক",
+ "currency": "মুদ্রা",
+ "cancel": "বাতিল",
+ "create": "তৈরি করুন",
+ "addAssetTitle": "পোর্টফোলিওতে সম্পদ যোগ করুন",
+ "sellAssetTitle": "সম্পদ বিক্রি করুন",
+ "symbol": "সিম্বল",
+ "quantity": "পরিমাণ",
+ "price": "মূল্য",
+ "add": "যোগ করুন",
+ "sell": "বিক্রি করুন"
+ },
+ "extracted": {
+ "areYouSureYou": "[BN] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/bn/reportBuilder.json b/fincept-terminal-desktop/public/locales/bn/reportBuilder.json
index 9e131c66f..8e8534037 100644
--- a/fincept-terminal-desktop/public/locales/bn/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/bn/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[BN] Load",
"save": "[BN] Save",
- "saving": "[BN] Saving...",
- "exportPdf": "[BN] Export PDF",
- "generating": "[BN] Generating..."
+ "saving": "[BN] Saving..."
},
"components": {
"title": "[BN] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/bn/settings.json b/fincept-terminal-desktop/public/locales/bn/settings.json
index d3a2fdd5c..b75b8e700 100644
--- a/fincept-terminal-desktop/public/locales/bn/settings.json
+++ b/fincept-terminal-desktop/public/locales/bn/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "ট্যাব লেআউট",
"appearance": "চেহারা",
"language": "ভাষা",
- "storage": "স্টোরেজ এবং ক্যাশে"
+ "storage": "স্টোরেজ এবং ক্যাশে",
+ "notifications": "[BN] Notifications"
},
"credentials": {
"title": "এপিআই ক্রেডেনশিয়াল ম্যানেজমেন্ট",
@@ -46,7 +47,31 @@
"saveConfig": "কনফিগারেশন সংরক্ষণ করুন",
"reset": "রিসেট",
"saveSuccess": "টার্মিনাল উপস্থিতি এবং কী ম্যাপিং সফলভাবে সংরক্ষণ করা হয়েছে৷",
- "resetSuccess": "ডিফল্ট চেহারা এবং কী ম্যাপিং রিসেট করুন"
+ "resetSuccess": "ডিফল্ট চেহারা এবং কী ম্যাপিং রিসেট করুন",
+ "customColors": "[BN] Custom Colors",
+ "customColorsTitle": "[BN] CUSTOM COLORS",
+ "colorPrimary": "[BN] Primary",
+ "colorSecondary": "[BN] Secondary",
+ "colorSuccess": "[BN] Success",
+ "colorAlert": "[BN] Alert",
+ "colorWarning": "[BN] Warning",
+ "colorInfo": "[BN] Info",
+ "colorAccent": "[BN] Accent",
+ "colorPurple": "[BN] Purple",
+ "colorText": "[BN] Text",
+ "colorTextMuted": "[BN] Text Muted",
+ "colorBackground": "[BN] Background",
+ "colorPanel": "[BN] Panel",
+ "layoutSpacing": "[BN] LAYOUT & SPACING",
+ "contentDensity": "[BN] CONTENT DENSITY",
+ "borderRadius": "[BN] BORDER RADIUS",
+ "borderStyle": "[BN] BORDER STYLE",
+ "lineHeight": "[BN] LINE HEIGHT",
+ "letterSpacing": "[BN] LETTER SPACING",
+ "effects": "[BN] EFFECTS",
+ "widgetOpacity": "[BN] WIDGET OPACITY",
+ "enableGlow": "[BN] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[BN] GLOW INTENSITY"
},
"stockSymbols": {
"title": "স্টক সিম্বল ডাটাবেস",
@@ -65,17 +90,8 @@
"tip": "টিপ: ট্যাবগুলিকে পুনরায় সাজাতে টেনে আনুন৷ হেডার এবং মেনু বিভাগের মধ্যে ট্যাব সরাতে তীর বোতাম ব্যবহার করুন। পরিবর্তন স্বয়ংক্রিয়ভাবে সংরক্ষিত হয়."
},
"llm": {
- "title": "এলএলএম কনফিগারেশন",
- "description": "AI মডেল এবং প্রদানকারী কনফিগার করুন",
"connected": "সংযুক্ত",
- "disconnected": "সংযোগ বিচ্ছিন্ন",
- "provider": "এআই প্রদানকারী",
- "globalSettings": "গ্লোবাল এআই সেটিংস",
- "temperature": "তাপমাত্রা",
- "maxTokens": "সর্বোচ্চ টোকেন",
- "systemPrompt": "সিস্টেম প্রম্পট",
- "modelLibrary": "মডেল লাইব্রেরি",
- "multiModelConfigs": "মাল্টি-মডেল কনফিগারেশন"
+ "disconnected": "সংযোগ বিচ্ছিন্ন"
},
"buttons": {
"save": "সংরক্ষণ করুন",
@@ -86,5 +102,18 @@
"database": "ডাটাবেস: SQLite",
"storage": "স্টোরেজ: ফাইল-ভিত্তিক",
"secureStorage": "সমস্ত ডেটা fincept_terminal.db এ সুরক্ষিতভাবে সংরক্ষিত"
+ },
+ "notifications": {
+ "title": "[BN] NOTIFICATION PROVIDERS",
+ "description": "[BN] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[BN] Event Filters",
+ "eventFilterDescription": "[BN] Choose which notification types to forward to external providers.",
+ "providers": "[BN] Providers",
+ "enabled": "[BN] Enabled",
+ "disabled": "[BN] Disabled",
+ "testButton": "[BN] TEST",
+ "testSuccess": "[BN] Test notification sent successfully!",
+ "testFailed": "[BN] Failed to send test notification. Check your configuration.",
+ "saved": "[BN] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/bn/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/bn/surfaceAnalytics.json
new file mode 100644
index 000000000..53fef4d79
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/bn/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[BN] SURFACE ANALYTICS",
+ "initializing": "[BN] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[BN] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[BN] VOL SURFACE",
+ "correlation": "[BN] CORRELATION",
+ "yieldCurve": "[BN] YIELD CURVE",
+ "pca": "[BN] PCA FACTORS"
+ },
+ "demoData": "[BN] DEMO DATA",
+ "demoDataSynthetic": "[BN] DEMO DATA (synthetic)",
+ "synthetic": "[BN] SYNTHETIC",
+ "manual": "[BN] MANUAL",
+ "error": "[BN] ERROR",
+ "ready": "[BN] READY",
+ "metrics": "[BN] Metrics",
+ "updated": "[BN] Updated",
+ "clickRefresh": "[BN] Click REFRESH to load data",
+ "refresh": "[BN] REFRESH",
+ "noApiKey": "[BN] NO API KEY",
+ "lastUpdate": "[BN] LAST UPDATE",
+ "loadingData": "[BN] LOADING DATA...",
+ "noDataLoaded": "[BN] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[BN] IV SURFACE METRICS",
+ "correlationMetrics": "[BN] CORRELATION METRICS",
+ "yieldCurveMetrics": "[BN] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[BN] PCA FACTOR METRICS",
+ "dataInfo": "[BN] DATA INFO",
+ "source": "[BN] SOURCE",
+ "frequency": "[BN] FREQUENCY",
+ "quality": "[BN] QUALITY",
+ "correlationScale": "[BN] CORRELATION SCALE",
+ "strongPositive": "[BN] Strong Positive (0.7-1.0)",
+ "neutral": "[BN] Neutral (0.3-0.7)",
+ "strongNegative": "[BN] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[BN] IV INTERPRETATION",
+ "highIv": "[BN] High IV = Expensive Options",
+ "lowIv": "[BN] Low IV = Cheap Options",
+ "skew": "[BN] Skew = Put/Call IV Diff",
+ "termStructure": "[BN] Term Structure = Time Effect",
+ "pcaInterpretation": "[BN] PCA INTERPRETATION",
+ "pc1": "[BN] PC1 = Market Factor",
+ "pc2": "[BN] PC2 = Size/Value Factor",
+ "pc3": "[BN] PC3 = Sector Rotation",
+ "higherVar": "[BN] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[BN] STRIKE",
+ "dte": "[BN] DTE",
+ "iv": "[BN] IV",
+ "correlation": "[BN] CORRELATION",
+ "maturity": "[BN] MATURITY",
+ "yield": "[BN] YIELD",
+ "loading": "[BN] LOADING",
+ "strikePrice": "[BN] STRIKE PRICE",
+ "daysToExpiry": "[BN] DAYS TO EXPIRY",
+ "impliedVol": "[BN] IMPLIED VOL (%)",
+ "assetPairIndex": "[BN] ASSET PAIR INDEX",
+ "timeDays": "[BN] TIME (DAYS)",
+ "correlationCoeff": "[BN] CORRELATION COEFF",
+ "maturityMonths": "[BN] MATURITY (MONTHS)",
+ "historicalDays": "[BN] HISTORICAL DAYS",
+ "yieldPercent": "[BN] YIELD (%)",
+ "principalComponent": "[BN] PRINCIPAL COMPONENT",
+ "assetIndex": "[BN] ASSET INDEX",
+ "factorLoading": "[BN] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[BN] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[BN] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[BN] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[BN] DAY ROLLING",
+ "yieldCurve": "[BN] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[BN] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[BN] FAILED TO LOAD DATA",
+ "authFailed": "[BN] AUTHENTICATION FAILED",
+ "authFailedHelp": "[BN] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[BN] ACCESS DENIED",
+ "accessDeniedHelp": "[BN] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[BN] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[BN] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[BN] DATA TIMEFRAME",
+ "schema": "[BN] Schema",
+ "description": "[BN] Description",
+ "recordsPerDay": "[BN] Records/Day",
+ "highFrequencyWarning": "[BN] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[BN] Data Volume"
+ },
+ "settings": {
+ "title": "[BN] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[BN] DATABENTO API KEY",
+ "configured": "[BN] CONFIGURED",
+ "invalidFormat": "[BN] INVALID FORMAT",
+ "apiKeyConfigured": "[BN] API key is configured (db-*****)",
+ "remove": "[BN] REMOVE",
+ "enterApiKey": "[BN] Enter your Databento API key (db-*****)",
+ "save": "[BN] SAVE",
+ "saving": "[BN] SAVING...",
+ "getApiKeyFrom": "[BN] Get your API key from",
+ "dashboardApiKeys": "[BN] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[BN] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[BN] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[BN] CORRELATION ASSETS",
+ "addSymbol": "[BN] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[BN] Reset to defaults",
+ "historicalDateRange": "[BN] HISTORICAL DATE RANGE",
+ "start": "[BN] Start",
+ "end": "[BN] End",
+ "autoRefreshInterval": "[BN] AUTO REFRESH INTERVAL",
+ "manualOnly": "[BN] Manual Only",
+ "every1min": "[BN] Every 1 minute",
+ "every5min": "[BN] Every 5 minutes",
+ "every15min": "[BN] Every 15 minutes",
+ "every1hour": "[BN] Every 1 hour",
+ "browseDatasets": "[BN] BROWSE DATASETS",
+ "costEstimator": "[BN] COST ESTIMATOR",
+ "referenceData": "[BN] REFERENCE DATA",
+ "orderBook": "[BN] ORDER BOOK",
+ "liveStreaming": "[BN] LIVE STREAMING",
+ "active": "[BN] ACTIVE",
+ "futuresCme": "[BN] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[BN] BATCH DOWNLOADS",
+ "additionalSchemas": "[BN] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[BN] TRADES, IMBALANCE, STATUS",
+ "cancel": "[BN] CANCEL",
+ "saveChanges": "[BN] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[BN] BATCH DOWNLOADS",
+ "newBatchJob": "[BN] NEW BATCH JOB",
+ "dataset": "[BN] Dataset",
+ "schema": "[BN] Schema",
+ "symbolsCommaSeparated": "[BN] Symbols (comma-separated)",
+ "startDate": "[BN] Start Date",
+ "endDate": "[BN] End Date",
+ "encoding": "[BN] Encoding",
+ "compression": "[BN] Compression",
+ "submitJob": "[BN] SUBMIT JOB",
+ "noBatchJobs": "[BN] No batch jobs found. Click + to create one.",
+ "records": "[BN] records",
+ "download": "[BN] Download",
+ "files": "[BN] FILES",
+ "jobsExpireNotice": "[BN] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[BN] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[BN] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[BN] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[BN] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[BN] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[BN] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[BN] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[BN] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[BN] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[BN] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[BN] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[BN] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[BN] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[BN] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[BN] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[BN] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[BN] [EN] common.or",
+ "note": "[BN] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/bn/tabs.json b/fincept-terminal-desktop/public/locales/bn/tabs.json
index 2dacb7ff2..a7fd4d90e 100644
--- a/fincept-terminal-desktop/public/locales/bn/tabs.json
+++ b/fincept-terminal-desktop/public/locales/bn/tabs.json
@@ -5,29 +5,7 @@
"news": "সংবাদ",
"portfolio": "পোর্টফোলিও",
"backtesting": "ব্যাকটেস্টিং",
- "watchlist": "ওয়াচলিস্ট",
- "research": "গবেষণা",
- "screener": "স্ক্রিনার",
"chat": "AI Chat",
- "agents": "এজেন্ট",
- "settings": "সেটিংস",
"profile": "প্রোফাইল"
- },
- "functionKeys": {
- "f1": "ড্যাশ",
- "f2": "বাজর",
- "f3": "সংব",
- "f4": "পোর্ট",
- "f5": "বিটস",
- "f6": "ওয়াচ",
- "f7": "গবষ",
- "f8": "স্ক্রন",
- "f9": "ট্রডগ",
- "f10": "AI",
- "f11": "পূর্ণ",
- "f12": "প্রফ"
- },
- "labels": {
- "moreTabs": "টুলবার মেনুতে আরও ট্যাব"
}
}
diff --git a/fincept-terminal-desktop/public/locales/bn/watchlist.json b/fincept-terminal-desktop/public/locales/bn/watchlist.json
index 18ffe3f49..f87dbab6e 100644
--- a/fincept-terminal-desktop/public/locales/bn/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/bn/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "ওয়াচলিস্ট",
- "header": {
- "export": "রপ্তানি",
- "updating": "আপডেট হচ্ছে",
- "live": "লাইভ"
- },
"sidebar": {
- "groups": "ওয়াচলিস্ট গ্রুপ",
- "new": "নতুন",
"noWatchlists": "এখনো কোনো তালিকা নেই।",
"clickNew": "তৈরি করতে নতুন ক্লিক করুন।",
- "stocks": "স্টক",
- "marketMovers": "মার্কেট মুভার্স",
- "gainer": "গেইনার",
- "loser": "লুজার",
- "volumeLeaders": "ভলিউম লিডার"
- },
- "emptyState": {
- "selectWatchlist": "শুরু করতে একটি তালিকা নির্বাচন করুন বা নতুন তৈরি করুন"
- },
- "list": {
- "symbols": "সিম্বল"
+ "stocks": "স্টক"
}
}
diff --git a/fincept-terminal-desktop/public/locales/de/codeEditor.json b/fincept-terminal-desktop/public/locales/de/codeEditor.json
index 886439652..79fd1592a 100644
--- a/fincept-terminal-desktop/public/locales/de/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/de/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "CODE-EDITOR",
"header": {
- "packages": "PAKETE"
+ "finscriptIde": "[DE] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "NEUE DATEI",
- "new": "NEU",
- "open": "ÖFFNEN",
- "save": "SPEICHERN",
"run": "AUSFÜHREN",
"running": "LÄUFT...",
- "runAll": "ALLE AUSFÜHREN",
- "history": "VERLAUF"
+ "toggleExplorer": "[DE] Toggle Explorer (Ctrl+B)",
+ "openFile": "[DE] Open File",
+ "saveShortcut": "[DE] Save (Ctrl+S)",
+ "findShortcut": "[DE] Find (Ctrl+F)",
+ "runShortcut": "[DE] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "FINSCRIPT EDITOR"
},
- "packages": {
- "clickToLoad": "Klicken zum Laden...",
- "load": "PAKETE LADEN"
+ "explorer": {
+ "title": "[DE] EXPLORER",
+ "openFiles": "[DE] OPEN FILES",
+ "examples": "[DE] EXAMPLES",
+ "runHistory": "[DE] RUN HISTORY",
+ "finscriptEngine": "[DE] FinScript Engine"
},
- "history": {
- "title": "NOTEBOOK-VERLAUF",
- "loading": "Verlauf wird geladen...",
- "empty": "Kein Notebook-Verlauf"
+ "output": {
+ "title": "[DE] OUTPUT",
+ "success": "[DE] SUCCESS",
+ "error": "[DE] ERROR",
+ "executing": "[DE] EXECUTING FINSCRIPT...",
+ "noOutput": "[DE] No output yet",
+ "pressToRun": "[DE] Press Ctrl+Enter to run",
+ "completed": "[DE] COMPLETED",
+ "failed": "[DE] FAILED",
+ "signals": "[DE] signals",
+ "clear": "[DE] CLEAR",
+ "errors": "[DE] ERRORS",
+ "signalsSection": "[DE] SIGNALS",
+ "outputSection": "[DE] OUTPUT",
+ "charts": "[DE] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[DE] OHLC",
+ "histogram": "[DE] Histogram",
+ "line": "[DE] Line",
+ "points": "[DE] points"
+ },
+ "statusBar": {
+ "modified": "[DE] MODIFIED",
+ "showOutput": "[DE] SHOW OUTPUT",
+ "encoding": "[DE] UTF-8",
+ "spaces": "[DE] 4 Spaces",
+ "runShortcut": "[DE] Ctrl+Enter: Run",
+ "lines": "[DE] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[DE] Close file without saving?",
+ "unsavedChanges": "[DE] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/de/common.json b/fincept-terminal-desktop/public/locales/de/common.json
index 1220d5310..9f072571f 100644
--- a/fincept-terminal-desktop/public/locales/de/common.json
+++ b/fincept-terminal-desktop/public/locales/de/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Laden...",
- "error": "Fehler",
- "success": "Erfolg",
- "save": "Speichern",
- "cancel": "Abbrechen",
- "delete": "Löschen",
- "edit": "Bearbeiten",
- "add": "Hinzufügen",
- "search": "Suchen",
- "filter": "Filtern",
- "back": "Zurück",
- "next": "Weiter",
- "previous": "Zurück",
- "submit": "Absenden",
- "close": "Schließen",
- "open": "Öffnen",
- "yes": "Ja",
- "no": "Nein",
- "ok": "OK",
- "confirm": "Bestätigen",
- "language": "Sprache",
- "selectLanguage": "Sprache auswählen"
-}
\ No newline at end of file
+ "settings": "[DE] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/de/dashboard.json b/fincept-terminal-desktop/public/locales/de/dashboard.json
index 748b2d591..8cfcac51a 100644
--- a/fincept-terminal-desktop/public/locales/de/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/de/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "ANPASSBARES DASHBOARD",
- "live": "LIVE",
- "widgets": "WIDGETS"
- },
- "buttons": {
- "addWidget": "WIDGET HINZUFÜGEN",
- "saveLayout": "LAYOUT SPEICHERN",
- "reset": "ZURÜCKSETZEN",
- "help": "HELFEN"
- },
"widgets": {
"loading": "Laden...",
- "error": "Fehler",
"globalIndices": "Globale Indizes – Top 12",
"forex": "Forex – Hauptpaare",
"crypto": "KRYPTOWÄHRUNGEN",
@@ -20,8 +8,6 @@
"news": "NACHRICHT",
"forum": "FORUM",
"watchlist": "WATCHLISTE",
- "maritimeIntelligence": "Maritimer Geheimdienst",
- "unknown": "Unbekannter Widget-Typ",
"index": "INDEX",
"symbol": "SYMBOL",
"price": "PREIS",
@@ -38,41 +24,22 @@
"pair": "PAAR",
"rate": "RATE",
"commodity": "WARE",
- "globe3D": "3D-GLOBUS",
- "vessels": "SCHIFFE",
- "routes": "ROUTEN",
- "vol24h": "VOL 24H",
- "topTradeCorridors": "Top-Handelskorridore",
- "ships": "Schiffe",
- "marketNews": "Marktnachrichten",
- "secPressReleases": "Pressemitteilungen der SEC",
- "cryptoNews": "Krypto-Neuigkeiten",
- "trendingForum": "Trendforum",
- "techStocks": "Tech-Aktien"
- },
- "tips": {
- "drag": "Ziehen Sie Widgets, um sie neu anzuordnen",
- "resize": "Ändern Sie die Größe in der unteren rechten Ecke",
- "remove": "Entfernen Sie Widgets mit der X-Taste",
- "responsive": "Responsives Layout – nutzt die volle Breite"
- },
- "loading": {
- "title": "Dashboard wird initialisiert",
- "description": "Datenbank-Cache für schnelleres Laden von Daten einrichten ...",
- "note": "Dies dauert beim ersten Start nur einen Moment"
- },
- "empty": {
- "noWidgets": "Keine Widgets im Dashboard",
- "addFirst": "FÜGEN SIE IHR ERSTES WIDGET HINZU"
- },
- "status": {
- "version": "Fincept Anpassbares Dashboard v2.0.0 | Arbeitsbereich per Drag & Drop verschieben",
- "layout": "Layout",
- "custom": "Brauch",
- "empty": "Leer",
- "active": "AKTIV",
- "cache": "Cache: AKTIVIERT",
- "label": "Status"
+ "noActiveMarkets": "[DE] No active markets found",
+ "indicator": "[DE] INDICATOR",
+ "value": "[DE] VALUE",
+ "chg": "[DE] CHG",
+ "overallRisk": "[DE] OVERALL RISK",
+ "openEconomicsTab": "[DE] Open Economics Tab",
+ "openGeopoliticsTab": "[DE] Open Geopolitics Tab",
+ "openPolymarketTab": "[DE] Open Polymarket Tab",
+ "noPortfolioFound": "[DE] No portfolio found",
+ "createPortfolioHint": "[DE] Create one in Portfolio tab",
+ "openPortfolioTab": "[DE] Open Portfolio Tab",
+ "action": "[DE] ACTION",
+ "markets": "[DE] MARKETS",
+ "performanceTracker": "[DE] PERFORMANCE TRACKER",
+ "totalPnL": "[DE] TOTAL P&L",
+ "viewDetailedAnalytics": "[DE] View Detailed Analytics"
},
"messages": {
"layoutSaved": "Dashboard-Layout gespeichert!",
diff --git a/fincept-terminal-desktop/public/locales/de/geopolitics.json b/fincept-terminal-desktop/public/locales/de/geopolitics.json
index 496213ec2..f319f7e8e 100644
--- a/fincept-terminal-desktop/public/locales/de/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/de/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "GEOPOLITIK",
"messages": {
- "loading": "Lade geopolitische Daten..."
+ "retry": "[DE] RETRY"
+ },
+ "header": {
+ "prefix": "[DE] GEO>",
+ "title": "[DE] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[DE] EVENTS"
+ },
+ "status": {
+ "stale": "[DE] STALE",
+ "loading": "[DE] LOADING...",
+ "error": "[DE] ERROR:"
+ },
+ "filters": {
+ "country": "[DE] Country...",
+ "cities": "[DE] Cities...",
+ "category": "[DE] Category...",
+ "apply": "[DE] APPLY",
+ "clear": "[DE] CLEAR",
+ "clearAllCities": "[DE] Clear all cities",
+ "selectedLabel": "[DE] Selected:"
+ },
+ "panel": {
+ "title": "[DE] INFO PANEL",
+ "expand": "[DE] Expand panel",
+ "collapse": "[DE] Collapse panel",
+ "eventsLoaded": "[DE] EVENTS LOADED",
+ "onMapVisualization": "[DE] on map visualization",
+ "topCategories": "[DE] TOP CATEGORIES",
+ "topCountries": "[DE] TOP COUNTRIES",
+ "eventDetails": "[DE] EVENT DETAILS",
+ "close": "[DE] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[DE] Country:",
+ "city": "[DE] City:",
+ "keywords": "[DE] Keywords:",
+ "coords": "[DE] Coords:",
+ "date": "[DE] Date:",
+ "source": "[DE] Source:",
+ "viewArticle": "[DE] View Article"
+ },
+ "legend": {
+ "title": "[DE] EVENT CATEGORIES",
+ "armedConflict": "[DE] Armed Conflict",
+ "terrorism": "[DE] Terrorism",
+ "protests": "[DE] Protests",
+ "civilianViolence": "[DE] Civilian Violence",
+ "riots": "[DE] Riots",
+ "politicalViolence": "[DE] Political Violence",
+ "crisis": "[DE] Crisis",
+ "explosions": "[DE] Explosions",
+ "strategic": "[DE] Strategic",
+ "unclassified": "[DE] Unclassified"
+ },
+ "footer": {
+ "tabName": "[DE] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[DE] EVENTS",
+ "labelEngine": "[DE] ENGINE",
+ "engineValue": "[DE] DECK.GL v9.2",
+ "labelSource": "[DE] SOURCE",
+ "sourceValue": "[DE] NEWS-EVENTS API",
+ "labelSelected": "[DE] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/de/markets.json b/fincept-terminal-desktop/public/locales/de/markets.json
index e4d4bc5c5..4458551a3 100644
--- a/fincept-terminal-desktop/public/locales/de/markets.json
+++ b/fincept-terminal-desktop/public/locales/de/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%ÄND",
"high": "HOCH",
"low": "TIEF",
- "loading": "Laden...",
"noData": "Keine Daten verfügbar",
"refresh": "AKTUALISIEREN",
"auto": "AUTO",
"on": "AN",
- "off": "AUS",
- "lastUpdate": "LETZTE AKTUALISIERUNG",
- "updating": "AKTUALISIERUNG",
- "live": "LIVE"
+ "off": "AUS"
}
diff --git a/fincept-terminal-desktop/public/locales/de/news.json b/fincept-terminal-desktop/public/locales/de/news.json
index 5dcf8f199..5b4106aa0 100644
--- a/fincept-terminal-desktop/public/locales/de/news.json
+++ b/fincept-terminal-desktop/public/locales/de/news.json
@@ -1,32 +1,63 @@
{
"title": "FINCEPT TERMINAL PROFESSIONELLE NACHRICHTEN",
"header": {
- "liveFeed": "LIVE-FEED",
- "live": "LIVE",
- "refresh": "AKTUALISIEREN",
- "updating": "AKTUALISIERUNG...",
- "alerts": "WARNUNGEN",
- "sources": "QUELLEN",
- "status": "STATUS",
- "demoMode": "DEMO-MODUS",
- "articles": "ARTIKEL",
- "activeSources": "AKTIVE QUELLEN"
- },
- "autoRefresh": {
- "title": "AUTOMATISCHES AKTUALISIERUNGSINTERVALL",
- "minute": "Minute",
- "minutes": "Minuten"
+ "refresh": "AKTUALISIEREN"
},
"messages": {
- "loadingFeeds": "Feeds werden geladen...",
- "breaking": "EILMELDUNG"
- },
- "feeds": {
- "primary": "[DE] PRIMARY NEWS FEED",
- "secondary": "[DE] SECONDARY NEWS FEED",
- "additional": "[DE] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[DE] Loading feeds...",
+ "failedToLoad": "[DE] Failed to load RSS feeds",
+ "noCustomFeeds": "[DE] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[DE] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[DE] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[DE] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[DE] RSS FEED SETTINGS",
+ "subtitle": "[DE] MANAGE YOUR NEWS SOURCES",
+ "close": "[DE] CLOSE",
+ "myFeeds": "[DE] MY FEEDS",
+ "defaultFeeds": "[DE] DEFAULT FEEDS",
+ "noFeedsAvailable": "[DE] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[DE] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[DE] ADD NEW FEED",
+ "addNewRssFeed": "[DE] ADD NEW RSS FEED",
+ "editRssFeed": "[DE] EDIT RSS FEED",
+ "restoreDefaults": "[DE] RESTORE DEFAULTS",
+ "restoreAll": "[DE] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[DE] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[DE] DISPLAY NAME",
+ "sourceName": "[DE] SOURCE NAME (SHORT)",
+ "feedUrl": "[DE] RSS FEED URL",
+ "category": "[DE] CATEGORY",
+ "region": "[DE] REGION",
+ "required": "[DE] *",
+ "testUrl": "[DE] TEST URL",
+ "testing": "[DE] TESTING...",
+ "valid": "[DE] VALID",
+ "cancel": "[DE] CANCEL",
+ "saving": "[DE] SAVING...",
+ "addFeed": "[DE] ADD FEED",
+ "updateFeed": "[DE] UPDATE FEED",
+ "on": "[DE] ON",
+ "off": "[DE] OFF",
+ "default": "[DE] DEFAULT",
+ "total": "[DE] TOTAL",
+ "active": "[DE] ACTIVE",
+ "custom": "[DE] CUSTOM",
+ "placeholders": {
+ "displayName": "[DE] e.g., Bloomberg Markets",
+ "sourceName": "[DE] e.g., BLOOMBERG",
+ "feedUrl": "[DE] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[DE] Name is required",
+ "sourceRequired": "[DE] Source name is required",
+ "invalidUrl": "[DE] Please enter a valid URL",
+ "invalidRss": "[DE] URL does not appear to be a valid RSS feed",
+ "testFailed": "[DE] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[DE] Delete this RSS feed?",
+ "message": "[DE] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/de/portfolio.json b/fincept-terminal-desktop/public/locales/de/portfolio.json
index a69182910..bfeb1eb8b 100644
--- a/fincept-terminal-desktop/public/locales/de/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/de/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "FINCEPT PORTFOLIO-MANAGER",
- "header": {
- "live": "LIVE",
- "updating": "AKTUALISIERUNG",
- "newPortfolio": "NEUES PORTFOLIO",
- "refresh": "AKTUALISIEREN",
- "exportCsv": "CSV EXPORTIEREN"
- },
- "summary": {
- "totalValue": "GESAMTWERT",
- "dayPnl": "TAGES-G/V",
- "totalPnl": "GESAMT-G/V",
- "positions": "POSITIONEN"
- },
- "views": {
- "positions": "POSITIONEN",
- "addAsset": "ANLAGE HINZUFÜGEN",
- "sellAsset": "ANLAGE VERKAUFEN",
- "analytics": "ANALYTIK",
- "history": "VERLAUF",
- "activeMgmt": "AKTIVES MANAGEMENT",
- "performance": "PERFORMANCE",
- "rebalance": "REBALANCING",
- "reports": "BERICHTE",
- "alerts": "WARNUNGEN",
- "sectors": "SEKTOREN",
- "help": "HILFE"
- },
- "sidebar": {
- "portfolios": "PORTFOLIOS",
- "loading": "Portfolios werden geladen...",
- "noPortfolios": "Noch keine Portfolios.",
- "clickCreate": "Klicken Sie auf NEUES PORTFOLIO zum Erstellen.",
- "owner": "Eigentümer",
- "currency": "Währung"
- },
- "content": {
- "selectOrCreate": "Wählen Sie ein Portfolio oder erstellen Sie ein neues zum Starten",
- "loadingData": "Portfolio-Daten werden geladen...",
- "comingSoon": "Ansicht kommt bald..."
- },
- "modals": {
- "createNew": "NEUES PORTFOLIO ERSTELLEN",
- "portfolioName": "PORTFOLIO-NAME",
- "owner": "EIGENTÜMER",
- "currency": "WÄHRUNG",
- "cancel": "ABBRECHEN",
- "create": "ERSTELLEN",
- "addAssetTitle": "ANLAGE ZUM PORTFOLIO HINZUFÜGEN",
- "sellAssetTitle": "ANLAGE VERKAUFEN",
- "symbol": "SYMBOL",
- "quantity": "MENGE",
- "price": "PREIS",
- "add": "HINZUFÜGEN",
- "sell": "VERKAUFEN"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Echtzeit-Tracking mit yfinance-Integration",
- "lastUpdated": "Zuletzt Aktualisiert",
- "connected": "VERBUNDEN"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "NEUES PORTFOLIO ERSTELLEN",
+ "portfolioName": "PORTFOLIO-NAME",
+ "owner": "EIGENTÜMER",
+ "currency": "WÄHRUNG",
+ "cancel": "ABBRECHEN",
+ "create": "ERSTELLEN",
+ "addAssetTitle": "ANLAGE ZUM PORTFOLIO HINZUFÜGEN",
+ "sellAssetTitle": "ANLAGE VERKAUFEN",
+ "symbol": "SYMBOL",
+ "quantity": "MENGE",
+ "price": "PREIS",
+ "add": "HINZUFÜGEN",
+ "sell": "VERKAUFEN"
+ },
+ "extracted": {
+ "areYouSureYou": "[DE] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/de/reportBuilder.json b/fincept-terminal-desktop/public/locales/de/reportBuilder.json
index b36247ba6..9d826989d 100644
--- a/fincept-terminal-desktop/public/locales/de/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/de/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[DE] Load",
"save": "[DE] Save",
- "saving": "[DE] Saving...",
- "exportPdf": "[DE] Export PDF",
- "generating": "[DE] Generating..."
+ "saving": "[DE] Saving..."
},
"components": {
"title": "[DE] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/de/settings.json b/fincept-terminal-desktop/public/locales/de/settings.json
index ecd0d213f..d00669926 100644
--- a/fincept-terminal-desktop/public/locales/de/settings.json
+++ b/fincept-terminal-desktop/public/locales/de/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Tab-Layout",
"appearance": "Aussehen",
"language": "Sprache",
- "storage": "Speicherung und Cache"
+ "storage": "Speicherung und Cache",
+ "notifications": "[DE] Notifications"
},
"credentials": {
"title": "API-ANMELDUNGSVERWALTUNG",
@@ -46,7 +47,31 @@
"saveConfig": "KONFIGURATION SPEICHERN",
"reset": "ZURÜCKSETZEN",
"saveSuccess": "Terminal-Erscheinungsbild und Tastenzuordnungen erfolgreich gespeichert",
- "resetSuccess": "Auf Standarddarstellung und Tastenbelegung zurücksetzen"
+ "resetSuccess": "Auf Standarddarstellung und Tastenbelegung zurücksetzen",
+ "customColors": "[DE] Custom Colors",
+ "customColorsTitle": "[DE] CUSTOM COLORS",
+ "colorPrimary": "[DE] Primary",
+ "colorSecondary": "[DE] Secondary",
+ "colorSuccess": "[DE] Success",
+ "colorAlert": "[DE] Alert",
+ "colorWarning": "[DE] Warning",
+ "colorInfo": "[DE] Info",
+ "colorAccent": "[DE] Accent",
+ "colorPurple": "[DE] Purple",
+ "colorText": "[DE] Text",
+ "colorTextMuted": "[DE] Text Muted",
+ "colorBackground": "[DE] Background",
+ "colorPanel": "[DE] Panel",
+ "layoutSpacing": "[DE] LAYOUT & SPACING",
+ "contentDensity": "[DE] CONTENT DENSITY",
+ "borderRadius": "[DE] BORDER RADIUS",
+ "borderStyle": "[DE] BORDER STYLE",
+ "lineHeight": "[DE] LINE HEIGHT",
+ "letterSpacing": "[DE] LETTER SPACING",
+ "effects": "[DE] EFFECTS",
+ "widgetOpacity": "[DE] WIDGET OPACITY",
+ "enableGlow": "[DE] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[DE] GLOW INTENSITY"
},
"stockSymbols": {
"title": "Aktiensymboldatenbank",
@@ -65,17 +90,8 @@
"tip": "TIPP: Ziehen Sie die Registerkarten, um sie neu anzuordnen. Verwenden Sie die Pfeiltasten, um Registerkarten zwischen Kopfzeilen- und Menüabschnitten zu verschieben. Änderungen werden automatisch gespeichert."
},
"llm": {
- "title": "LLM-KONFIGURATION",
- "description": "Konfigurieren Sie KI-Modelle und -Anbieter",
"connected": "VERBUNDEN",
- "disconnected": "GETRENNT",
- "provider": "KI-ANBIETER",
- "globalSettings": "GLOBALE KI-EINSTELLUNGEN",
- "temperature": "TEMPERATUR",
- "maxTokens": "MAX. TOKEN",
- "systemPrompt": "SYSTEMAUFFORDERUNG",
- "modelLibrary": "MODELLBIBLIOTHEK",
- "multiModelConfigs": "Konfigurationen mit mehreren Modellen"
+ "disconnected": "GETRENNT"
},
"buttons": {
"save": "SPEICHERN",
@@ -86,5 +102,18 @@
"database": "Datenbank: SQLite",
"storage": "Speicherung: Dateibasiert",
"secureStorage": "Alle Daten werden sicher in fincept_terminal.db gespeichert"
+ },
+ "notifications": {
+ "title": "[DE] NOTIFICATION PROVIDERS",
+ "description": "[DE] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[DE] Event Filters",
+ "eventFilterDescription": "[DE] Choose which notification types to forward to external providers.",
+ "providers": "[DE] Providers",
+ "enabled": "[DE] Enabled",
+ "disabled": "[DE] Disabled",
+ "testButton": "[DE] TEST",
+ "testSuccess": "[DE] Test notification sent successfully!",
+ "testFailed": "[DE] Failed to send test notification. Check your configuration.",
+ "saved": "[DE] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/de/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/de/surfaceAnalytics.json
new file mode 100644
index 000000000..f1c963038
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/de/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[DE] SURFACE ANALYTICS",
+ "initializing": "[DE] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[DE] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[DE] VOL SURFACE",
+ "correlation": "[DE] CORRELATION",
+ "yieldCurve": "[DE] YIELD CURVE",
+ "pca": "[DE] PCA FACTORS"
+ },
+ "demoData": "[DE] DEMO DATA",
+ "demoDataSynthetic": "[DE] DEMO DATA (synthetic)",
+ "synthetic": "[DE] SYNTHETIC",
+ "manual": "[DE] MANUAL",
+ "error": "[DE] ERROR",
+ "ready": "[DE] READY",
+ "metrics": "[DE] Metrics",
+ "updated": "[DE] Updated",
+ "clickRefresh": "[DE] Click REFRESH to load data",
+ "refresh": "[DE] REFRESH",
+ "noApiKey": "[DE] NO API KEY",
+ "lastUpdate": "[DE] LAST UPDATE",
+ "loadingData": "[DE] LOADING DATA...",
+ "noDataLoaded": "[DE] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[DE] IV SURFACE METRICS",
+ "correlationMetrics": "[DE] CORRELATION METRICS",
+ "yieldCurveMetrics": "[DE] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[DE] PCA FACTOR METRICS",
+ "dataInfo": "[DE] DATA INFO",
+ "source": "[DE] SOURCE",
+ "frequency": "[DE] FREQUENCY",
+ "quality": "[DE] QUALITY",
+ "correlationScale": "[DE] CORRELATION SCALE",
+ "strongPositive": "[DE] Strong Positive (0.7-1.0)",
+ "neutral": "[DE] Neutral (0.3-0.7)",
+ "strongNegative": "[DE] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[DE] IV INTERPRETATION",
+ "highIv": "[DE] High IV = Expensive Options",
+ "lowIv": "[DE] Low IV = Cheap Options",
+ "skew": "[DE] Skew = Put/Call IV Diff",
+ "termStructure": "[DE] Term Structure = Time Effect",
+ "pcaInterpretation": "[DE] PCA INTERPRETATION",
+ "pc1": "[DE] PC1 = Market Factor",
+ "pc2": "[DE] PC2 = Size/Value Factor",
+ "pc3": "[DE] PC3 = Sector Rotation",
+ "higherVar": "[DE] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[DE] STRIKE",
+ "dte": "[DE] DTE",
+ "iv": "[DE] IV",
+ "correlation": "[DE] CORRELATION",
+ "maturity": "[DE] MATURITY",
+ "yield": "[DE] YIELD",
+ "loading": "[DE] LOADING",
+ "strikePrice": "[DE] STRIKE PRICE",
+ "daysToExpiry": "[DE] DAYS TO EXPIRY",
+ "impliedVol": "[DE] IMPLIED VOL (%)",
+ "assetPairIndex": "[DE] ASSET PAIR INDEX",
+ "timeDays": "[DE] TIME (DAYS)",
+ "correlationCoeff": "[DE] CORRELATION COEFF",
+ "maturityMonths": "[DE] MATURITY (MONTHS)",
+ "historicalDays": "[DE] HISTORICAL DAYS",
+ "yieldPercent": "[DE] YIELD (%)",
+ "principalComponent": "[DE] PRINCIPAL COMPONENT",
+ "assetIndex": "[DE] ASSET INDEX",
+ "factorLoading": "[DE] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[DE] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[DE] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[DE] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[DE] DAY ROLLING",
+ "yieldCurve": "[DE] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[DE] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[DE] FAILED TO LOAD DATA",
+ "authFailed": "[DE] AUTHENTICATION FAILED",
+ "authFailedHelp": "[DE] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[DE] ACCESS DENIED",
+ "accessDeniedHelp": "[DE] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[DE] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[DE] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[DE] DATA TIMEFRAME",
+ "schema": "[DE] Schema",
+ "description": "[DE] Description",
+ "recordsPerDay": "[DE] Records/Day",
+ "highFrequencyWarning": "[DE] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[DE] Data Volume"
+ },
+ "settings": {
+ "title": "[DE] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[DE] DATABENTO API KEY",
+ "configured": "[DE] CONFIGURED",
+ "invalidFormat": "[DE] INVALID FORMAT",
+ "apiKeyConfigured": "[DE] API key is configured (db-*****)",
+ "remove": "[DE] REMOVE",
+ "enterApiKey": "[DE] Enter your Databento API key (db-*****)",
+ "save": "[DE] SAVE",
+ "saving": "[DE] SAVING...",
+ "getApiKeyFrom": "[DE] Get your API key from",
+ "dashboardApiKeys": "[DE] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[DE] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[DE] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[DE] CORRELATION ASSETS",
+ "addSymbol": "[DE] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[DE] Reset to defaults",
+ "historicalDateRange": "[DE] HISTORICAL DATE RANGE",
+ "start": "[DE] Start",
+ "end": "[DE] End",
+ "autoRefreshInterval": "[DE] AUTO REFRESH INTERVAL",
+ "manualOnly": "[DE] Manual Only",
+ "every1min": "[DE] Every 1 minute",
+ "every5min": "[DE] Every 5 minutes",
+ "every15min": "[DE] Every 15 minutes",
+ "every1hour": "[DE] Every 1 hour",
+ "browseDatasets": "[DE] BROWSE DATASETS",
+ "costEstimator": "[DE] COST ESTIMATOR",
+ "referenceData": "[DE] REFERENCE DATA",
+ "orderBook": "[DE] ORDER BOOK",
+ "liveStreaming": "[DE] LIVE STREAMING",
+ "active": "[DE] ACTIVE",
+ "futuresCme": "[DE] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[DE] BATCH DOWNLOADS",
+ "additionalSchemas": "[DE] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[DE] TRADES, IMBALANCE, STATUS",
+ "cancel": "[DE] CANCEL",
+ "saveChanges": "[DE] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[DE] BATCH DOWNLOADS",
+ "newBatchJob": "[DE] NEW BATCH JOB",
+ "dataset": "[DE] Dataset",
+ "schema": "[DE] Schema",
+ "symbolsCommaSeparated": "[DE] Symbols (comma-separated)",
+ "startDate": "[DE] Start Date",
+ "endDate": "[DE] End Date",
+ "encoding": "[DE] Encoding",
+ "compression": "[DE] Compression",
+ "submitJob": "[DE] SUBMIT JOB",
+ "noBatchJobs": "[DE] No batch jobs found. Click + to create one.",
+ "records": "[DE] records",
+ "download": "[DE] Download",
+ "files": "[DE] FILES",
+ "jobsExpireNotice": "[DE] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[DE] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[DE] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[DE] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[DE] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[DE] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[DE] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[DE] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[DE] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[DE] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[DE] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[DE] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[DE] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[DE] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[DE] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[DE] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[DE] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[DE] [EN] common.or",
+ "note": "[DE] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/de/tabs.json b/fincept-terminal-desktop/public/locales/de/tabs.json
index 8ac59c7a0..b1020c2bb 100644
--- a/fincept-terminal-desktop/public/locales/de/tabs.json
+++ b/fincept-terminal-desktop/public/locales/de/tabs.json
@@ -5,29 +5,7 @@
"news": "Nachrichten",
"portfolio": "Portfolio",
"backtesting": "Backtesting",
- "watchlist": "Watchlist",
- "research": "Forschung",
- "screener": "Screener",
"chat": "AI Chat",
- "agents": "Agenten",
- "settings": "Einstellungen",
"profile": "Profil"
- },
- "functionKeys": {
- "f1": "DASH",
- "f2": "MRKT",
- "f3": "NEWS",
- "f4": "PORT",
- "f5": "BKTS",
- "f6": "WTCH",
- "f7": "FORS",
- "f8": "SCRN",
- "f9": "TRDG",
- "f10": "AI",
- "f11": "VOLL",
- "f12": "PROF"
- },
- "labels": {
- "moreTabs": "Weitere Tabs in Toolbar-Menüs"
}
}
diff --git a/fincept-terminal-desktop/public/locales/de/watchlist.json b/fincept-terminal-desktop/public/locales/de/watchlist.json
index 2de96d75a..1e60e2f25 100644
--- a/fincept-terminal-desktop/public/locales/de/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/de/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "BEOBACHTUNGSLISTE",
- "header": {
- "export": "EXPORTIEREN",
- "updating": "AKTUALISIERUNG",
- "live": "LIVE"
- },
"sidebar": {
- "groups": "LISTENGRUPPEN",
- "new": "NEU",
"noWatchlists": "Noch keine Listen vorhanden.",
"clickNew": "Klicken Sie NEU zum Erstellen.",
- "stocks": "Aktien",
- "marketMovers": "MARKTFÜHRER",
- "gainer": "GEWINNER",
- "loser": "VERLIERER",
- "volumeLeaders": "VOLUMEN-LEADER"
- },
- "emptyState": {
- "selectWatchlist": "Wählen Sie eine Liste oder erstellen Sie eine neue zum Starten"
- },
- "list": {
- "symbols": "Symbole"
+ "stocks": "Aktien"
}
}
diff --git a/fincept-terminal-desktop/public/locales/en/chat.json b/fincept-terminal-desktop/public/locales/en/chat.json
index cce5fe65e..aae49c696 100644
--- a/fincept-terminal-desktop/public/locales/en/chat.json
+++ b/fincept-terminal-desktop/public/locales/en/chat.json
@@ -11,47 +11,16 @@
},
"messages": {
"thinking": "Thinking...",
- "typing": "AI is typing...",
- "empty": "(Empty message)"
+ "typing": "AI is typing..."
},
"history": {
"clearAll": "CLEAR ALL",
"sessions": "SESSIONS",
- "deleteAll": "Delete all sessions",
- "search": "Search sessions..."
+ "deleteAll": "Delete all 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 c2ae7f590..090d1304b 100644
--- a/fincept-terminal-desktop/public/locales/en/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/en/codeEditor.json
@@ -1,19 +1,11 @@
{
- "title": "CODE EDITOR",
"header": {
- "packages": "PACKAGES",
- "finscriptIde": "FINSCRIPT IDE",
- "version": "v1.0"
+ "finscriptIde": "FINSCRIPT IDE"
},
"toolbar": {
"newFile": "NEW FILE",
- "new": "NEW",
- "open": "OPEN",
- "save": "SAVE",
"run": "RUN",
"running": "RUNNING...",
- "runAll": "RUN ALL",
- "history": "HISTORY",
"toggleExplorer": "Toggle Explorer (Ctrl+B)",
"openFile": "Open File",
"saveShortcut": "Save (Ctrl+S)",
@@ -24,15 +16,6 @@
"notebook": "JUPYTER NOTEBOOK",
"finscript": "FINSCRIPT EDITOR"
},
- "packages": {
- "clickToLoad": "Click to load packages...",
- "load": "LOAD PACKAGES"
- },
- "history": {
- "title": "NOTEBOOK HISTORY",
- "loading": "Loading history...",
- "empty": "No notebook history yet"
- },
"explorer": {
"title": "EXPLORER",
"openFiles": "OPEN FILES",
@@ -73,14 +56,5 @@
"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 bc075c241..f84a8362a 100644
--- a/fincept-terminal-desktop/public/locales/en/common.json
+++ b/fincept-terminal-desktop/public/locales/en/common.json
@@ -1,2156 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Loading...",
- "error": "Error",
- "success": "Success",
- "save": "Save",
- "cancel": "Cancel",
- "delete": "Delete",
- "edit": "Edit",
- "add": "Add",
- "search": "Search",
- "filter": "Filter",
- "back": "Back",
- "next": "Next",
- "previous": "Previous",
- "submit": "Submit",
- "close": "Close",
- "open": "Open",
- "yes": "Yes",
- "no": "No",
- "ok": "OK",
- "or": "or",
- "note": "Note",
- "settings": "Settings",
- "confirm": "Confirm",
- "language": "Language",
- "selectLanguage": "Select Language",
- "extracted": {
- "somethingWentWrong": "Something went wrong",
- "initializingFinceptTerminal": "Initializing Fincept Terminal...",
- "paymentUrlIsInvalid": "Payment URL is invalid. Please try again or contact support.",
- "invalidPaymentUrlPlease": "Invalid payment URL. Please contact support.",
- "tradingPartners": "TRADING PARTNERS",
- "sidebar": "Sidebar",
- "displaysTheMobileSidebar": "Displays the mobile sidebar.",
- "toggleSidebar": "Toggle Sidebar",
- "previousSlide": "Previous slide",
- "nextSlide": "Next slide",
- "more": "More",
- "strike": "STRIKE:",
- "dte": "DTE:",
- "iv": "IV:",
- "correlation": "CORRELATION:",
- "maturity": "MATURITY:",
- "yield": "YIELD:",
- "loading": "LOADING:",
- "volSurface": "VOL SURFACE",
- "yieldCurve": "YIELD CURVE",
- "pcaFactors": "PCA FACTORS",
- "lastUpdate": "LAST UPDATE:",
- "marketMetrics": "MARKET METRICS",
- "dataInfo": "DATA INFO",
- "source": "SOURCE:",
- "frequency": "FREQUENCY:",
- "quality": "QUALITY:",
- "globalTradeAnalysis": "GLOBAL TRADE ANALYSIS",
- "realtimeTradeFlowVisualization": "Real-time Trade Flow Visualization",
- "topPartners": "TOP PARTNERS",
- "top10": "Top 10",
- "top15": "Top 15",
- "top20": "Top 20",
- "top30": "Top 30",
- "top50": "Top 50",
- "loadingTradeData": "Loading trade data...",
- "tradingPartner": "TRADING PARTNER",
- "totalTrade": "TOTAL TRADE",
- "totalExports": "TOTAL EXPORTS",
- "outboundTradeFlows": "Outbound trade flows",
- "totalImports": "TOTAL IMPORTS",
- "inboundTradeFlows": "Inbound trade flows",
- "tradeBalance": "TRADE BALANCE",
- "topTradingPartner": "TOP TRADING PARTNER",
- "avgPerPartner": "AVG PER PARTNER",
- "meanTradeValue": "Mean trade value",
- "selectACountryTo": "Select a country to view trade relationships",
- "selectedCountry": "SELECTED COUNTRY",
- "dataDetails": "DATA DETAILS",
- "year": "Year:",
- "hsCode": "HS Code:",
- "partners": "Partners:",
- "exportsOutbound": "Exports (Outbound)",
- "importsInbound": "Imports (Inbound)",
- "hoverForDetails": "Hover for details",
- "searchCountries": "Search countries...",
- "toolCall": "TOOL CALL",
- "running": "Running...",
- "arguments": "Arguments:",
- "result": "Result:",
- "noTickersAddedAdd": "No tickers added. Add tickers using the form above.",
- "saveChanges": "SAVE CHANGES",
- "enterTickerSymbolEg": "Enter ticker symbol (e.g., AAPL)",
- "moveUp": "Move up",
- "moveDown": "Move down",
- "removeTicker": "Remove ticker",
- "relationshipMap": "Relationship Map",
- "enterTickerEgAapl": "Enter ticker (e.g., AAPL, TSLA, GOOGL)...",
- "vol": "VOL:",
- "loadingPriceChart": "Loading price chart...",
- "recentTrades": "RECENT TRADES",
- "tradeOnPolymarket": "TRADE ON POLYMARKET",
- "polymarketPredictionMarkets": "POLYMARKET PREDICTION MARKETS",
- "allCategories": "ALL CATEGORIES",
- "mostRecent": "MOST RECENT",
- "showClosed": "SHOW CLOSED",
- "loadingData": "LOADING DATA...",
- "noMarketsFound": "NO MARKETS FOUND",
- "noEventsFound": "NO EVENTS FOUND",
- "loadingMarkets": "LOADING MARKETS...",
- "noMarketsFoundFor": "NO MARKETS FOUND FOR THIS SPORT",
- "noSportsFound": "NO SPORTS FOUND",
- "clickToViewMarkets": "Click to view markets",
- "searchMarkets": "SEARCH MARKETS...",
- "failedToLoadInitial": "Failed to load initial data",
- "failedToLoadMarkets": "Failed to load markets",
- "failedToLoadEvents": "Failed to load events",
- "failedToLoadSports": "Failed to load sports",
- "searchFailed": "Search failed",
- "stepsToConfigure": "Steps to configure:",
- "getYourFreeApi": "Get your free API key at:",
- "addNewApiKey": "Add new API key with service name:",
- "pasteYourApiKey": "Paste your API key and save",
- "returnToThisTab": "Return to this tab and refresh",
- "goToSettings": "GO TO SETTINGS",
- "related": "RELATED:",
- "error1": "ERROR:",
- "open": "OPEN:",
- "high": "HIGH:",
- "low": "LOW:",
- "vol1": "VOL:",
- "lastTrade": "LAST TRADE",
- "macdSignal": "MACD Signal",
- "noNewsAvailable": "No news available",
- "lastQuote": "LAST QUOTE",
- "incomeStatement": "INCOME STATEMENT",
- "noData": "No data",
- "balanceSheet": "BALANCE SHEET",
- "noDividends": "No dividends",
- "noSplits": "No splits",
- "shortInterest": "SHORT INTEREST",
- "shortVolume": "SHORT VOLUME",
- "noResults": "No results",
- "noHolidays": "No holidays",
- "noTypes": "No types",
- "noExchanges": "No exchanges",
- "symbol": "Symbol...",
- "bidask": "BID/ASK",
- "marketStatus": "MARKET STATUS",
- "tradesQuotes": "TRADES & QUOTES",
- "_30dayChart": "30-DAY CHART",
- "marketMonitoring": "MARKET MONITORING",
- "realtimeAlertSystem": "Real-time Alert System",
- "newCondition": "NEW CONDITION",
- "value2": "VALUE 2",
- "allProviders": "ALL PROVIDERS",
- "allFields": "ALL FIELDS",
- "noMonitoringConditions": "NO MONITORING CONDITIONS",
- "addConditionsToStart": "Add conditions to start monitoring market events",
- "noAlertsYet": "NO ALERTS YET",
- "alertsWillAppearHere": "Alerts will appear here when conditions are triggered",
- "btcusd": "BTC/USD",
- "searchSymbols": "Search symbols...",
- "llmConfiguration": "LLM CONFIGURATION",
- "configureLlmSettings": "Configure LLM Settings",
- "llmConfigurationHasBeen": "LLM configuration has been moved to the Settings screen for a unified configuration experience.\n Please navigate to the Settings tab to configure your AI providers.",
- "whatYouCanConfigure": "What you can configure in Settings:",
- "selectActiveLlmProvider": "Select active LLM provider (OpenAI, Gemini, DeepSeek, Ollama, OpenRouter)",
- "configureApiKeysAnd": "Configure API keys and base URLs",
- "setModelNames": "Set model names",
- "adjustTemperatureAndMax": "Adjust temperature and max tokens",
- "customizeSystemPrompts": "Customize system prompts",
- "goToSettingsTab": "GO TO SETTINGS TAB",
- "geopoliticalRelationshipMap": "GEOPOLITICAL RELATIONSHIP MAP",
- "type": "Type:",
- "severity": "Severity:",
- "datasets": "Datasets:",
- "connections": "Connections:",
- "critical": "Critical",
- "high1": "High",
- "medium": "Medium",
- "organization": "Organization",
- "networkStats": "NETWORK STATS",
- "nodes": "Nodes:",
- "conflicts": "Conflicts:",
- "organizations": "Organizations:",
- "totalDatasets": "Total Datasets:",
- "globalCrisisOverview": "GLOBAL CRISIS OVERVIEW",
- "activeConflicts": "Active Conflicts",
- "totalDatasets1": "Total Datasets",
- "dataProviders": "Data Providers",
- "crisisTypeBreakdown": "CRISIS TYPE BREAKDOWN",
- "regionalConflictIntensity": "REGIONAL CONFLICT INTENSITY",
- "topDataProviders": "TOP DATA PROVIDERS",
- "filterByCountry": "FILTER BY COUNTRY",
- "allCountries": "All Countries",
- "filterByTopic": "FILTER BY TOPIC",
- "allTopics": "All Topics",
- "applyFilters": "APPLY FILTERS",
- "clearFilters": "CLEAR FILTERS",
- "loadingHdxData": "Loading HDX Data...",
- "hdxHumanitarianData": "HDX HUMANITARIAN DATA",
- "datasetDate": "Dataset Date:",
- "lastModified": "Last Modified:",
- "updateFrequency": "Update Frequency:",
- "license": "License:",
- "tags": "Tags:",
- "affectedRegions": "Affected Regions:",
- "description": "Description:",
- "searchHdxDatasets": "Search HDX datasets...",
- "current": "Current",
- "indicatorParameters": "Indicator Parameters",
- "upperThreshold": "Upper Threshold",
- "lowerThreshold": "Lower Threshold",
- "resetAllToDefaults": "Reset All to Defaults",
- "todaysTrading": "TODAY'S TRADING",
- "open1": "OPEN:",
- "high2": "HIGH:",
- "low1": "LOW:",
- "prevClose": "PREV CLOSE:",
- "volume": "VOLUME:",
- "marketCap": "MARKET CAP:",
- "pegRatio": "PEG RATIO:",
- "divYield": "DIV YIELD:",
- "beta": "BETA:",
- "shareStats": "SHARE STATS",
- "sharesOut": "SHARES OUT:",
- "float": "FLOAT:",
- "insiders": "INSIDERS:",
- "institutions": "INSTITUTIONS:",
- "period": "PERIOD:",
- "analystTargets": "ANALYST TARGETS",
- "mean": "MEAN:",
- "analysts": "ANALYSTS:",
- "avgVol": "AVG VOL:",
- "grossMargin": "GROSS MARGIN:",
- "operMargin": "OPER. MARGIN:",
- "profitMargin": "PROFIT MARGIN:",
- "roa": "ROA:",
- "roe": "ROE:",
- "growthRates": "GROWTH RATES",
- "revenue": "REVENUE:",
- "earnings": "EARNINGS:",
- "companyOverview": "COMPANY OVERVIEW",
- "companyInfo": "COMPANY INFO",
- "employees": "EMPLOYEES:",
- "website": "WEBSITE:",
- "currency": "CURRENCY:",
- "financialHealth": "FINANCIAL HEALTH",
- "cash": "CASH:",
- "debt": "DEBT:",
- "freeCf": "FREE CF:",
- "fontSize": "FONT SIZE:",
- "showYears": "SHOW YEARS:",
- "selectMetrics": "SELECT METRICS:",
- "selectMetricsToCompare": "SELECT METRICS TO COMPARE",
- "chart1Metrics": "CHART 1 METRICS:",
- "chart2Metrics": "CHART 2 METRICS:",
- "chart3Metrics": "CHART 3 METRICS:",
- "pleaseSelectAtLeast": "Please select at least one metric to compare",
- "incomeStatementLatest": "INCOME STATEMENT (Latest)",
- "noDataAvailable": "No data available",
- "balanceSheetLatest": "BALANCE SHEET (Latest)",
- "cashFlowStatementLatest": "CASH FLOW STATEMENT (Latest)",
- "totalCash": "TOTAL CASH",
- "totalDebt": "TOTAL DEBT",
- "freeCashflow": "FREE CASHFLOW",
- "operatingCashflow": "OPERATING CASHFLOW",
- "enterpriseValueMetrics": "ENTERPRISE VALUE METRICS",
- "enterpriseValue": "ENTERPRISE VALUE",
- "bookValue": "BOOK VALUE",
- "totalRevenue": "TOTAL REVENUE",
- "revenuePerShare": "REVENUE PER SHARE",
- "grossProfits": "GROSS PROFITS",
- "ebitdaMargins": "EBITDA MARGINS",
- "keyRatiosSummary": "KEY RATIOS SUMMARY",
- "pegRatio1": "PEG RATIO",
- "shortRatio": "SHORT RATIO",
- "fetchingLatestNews": "FETCHING LATEST NEWS...",
- "computingTechnicalIndicators": "COMPUTING TECHNICAL INDICATORS...",
- "pleaseWaitForHistorical": "Please wait for historical data to load",
- "technicalIndicatorsCouldNot": "Technical indicators could not be computed. Please try again or select a different symbol.",
- "enterSymbol": "Enter symbol...",
- "professionalFinancialIntelligencePlatform": "Professional Financial Intelligence Platform",
- "openSourceLicense": "OPEN SOURCE LICENSE",
- "agpl30License": "AGPL-3.0 License",
- "sourceSharingRequiredOn": "Source sharing required on distribution",
- "networkServiceDisclosureRequired": "Network service disclosure required",
- "commercialLicense": "COMMERCIAL LICENSE",
- "noSourceSharingObligation": "No source sharing obligation",
- "prioritySupportIncluded": "Priority support included",
- "customFeaturesAvailable": "Custom features available",
- "useRequiresWrittenPermission": "Use requires written permission except for AGPL-3.0 attribution.",
- "repository": "Repository",
- "license1": "License",
- "commercial": "Commercial",
- "trademarks": "Trademarks",
- "website1": "Website",
- "general": "General",
- "security": "Security",
- "legal": "Legal",
- "applicationInformationLegal": "Application Information & Legal",
- "createNewWatchlist": "Create new watchlist",
- "noStocksInThis": "No stocks in this watchlist yet",
- "clickAddStockTo": "Click \"ADD STOCK\" to add stocks",
- "noStockSelected": "NO STOCK SELECTED",
- "clickOnAStock": "Click on a stock to view details",
- "failedToLoadMarket": "Failed to load market data",
- "lastPrice": "LAST PRICE",
- "open2": "Open:",
- "prevClose1": "Prev Close:",
- "dayHigh": "Day High:",
- "dayLow": "Day Low:",
- "volume1": "Volume:",
- "createNewWatchlist1": "CREATE NEW WATCHLIST",
- "myWatchlist": "My Watchlist",
- "optionalDescription": "Optional description...",
- "pleaseEnterAWatchlist": "Please enter a watchlist name",
- "failedToCreateWatchlist": "Failed to create watchlist",
- "addStockToWatchlist": "ADD STOCK TO WATCHLIST",
- "enterStockTickerSymbol": "Enter stock ticker symbol (e.g., AAPL, MSFT, GOOGL)",
- "notesOptional": "NOTES (OPTIONAL)",
- "addNotesAboutThis": "Add notes about this stock...",
- "pleaseEnterAStock": "Please enter a stock symbol",
- "loadingChartData": "Loading chart data...",
- "failedToLoadChart": "Failed to Load Chart",
- "recentTrades1": "RECENT TRADES",
- "live": "Live",
- "time": "Time",
- "price": "Price",
- "size": "Size",
- "waitingForTrades": "Waiting for trades...",
- "noTradesExecuted": "No trades executed",
- "loadingTicker": "Loading ticker...",
- "quickOrders": "QUICK ORDERS",
- "quickBuy": "Quick Buy",
- "quickSell": "Quick Sell",
- "noOpenPositions": "No open positions",
- "performanceStatistics": "PERFORMANCE STATISTICS",
- "totalReturn": "Total Return",
- "winRate": "Win Rate",
- "totalTrades": "Total Trades",
- "profitFactor": "Profit Factor",
- "bestTrade": "Best Trade",
- "worstTrade": "Worst Trade",
- "balance": "Balance:",
- "noOpenOrders": "No open orders",
- "orderType": "ORDER TYPE",
- "stopMarket": "STOP MARKET",
- "stopLimit": "STOP LIMIT",
- "limitPrice": "LIMIT PRICE",
- "stopPrice": "STOP PRICE",
- "takeProfit": "TAKE PROFIT",
- "stopLoss": "STOP LOSS",
- "slRisk": "SL RISK:",
- "paperTradingNoReal": "Paper trading - No real money used",
- "optional": "Optional",
- "pleaseEnterAValid": "Please enter a valid quantity",
- "pleaseEnterAValid1": "Please enter a valid limit price",
- "pleaseEnterAValid2": "Please enter a valid stop price",
- "orderBook": "ORDER BOOK",
- "spread": "Spread:",
- "price1": "Price",
- "size1": "Size",
- "total": "Total",
- "waitingForData": "Waiting for data...",
- "marketDepth": "MARKET DEPTH",
- "loadingMarketDepth": "Loading market depth...",
- "bidsBuy": "Bids (Buy)",
- "price2": "Price",
- "size2": "Size",
- "total1": "Total",
- "noBidData": "No bid data",
- "asksSell": "Asks (Sell)",
- "noAskData": "No ask data",
- "bestBid": "Best Bid",
- "spread1": "Spread",
- "bestAsk": "Best Ask",
- "broker": "BROKER:",
- "broker1": "Broker:",
- "advanced": "Advanced:",
- "leverage": "Leverage:",
- "margin": "Margin:",
- "cross": "Cross",
- "isolated": "Isolated",
- "vaultsAvailable": "Vaults Available",
- "subaccounts": "Subaccounts",
- "paperModeChangesApply": "Paper mode - changes apply to virtual trading only",
- "openInterest": "Open Interest:",
- "loadingFundingRate": "Loading funding rate...",
- "fundingRate": "Funding Rate:",
- "krakenStaking": "KRAKEN STAKING",
- "noStakableAssetsFound": "NO STAKABLE ASSETS FOUND",
- "addFundsToYour": "Add funds to your Kraken account to start staking",
- "amountToStake": "AMOUNT TO STAKE",
- "estimatedYearlyEarnings": "ESTIMATED YEARLY EARNINGS:",
- "lockPeriod": "LOCK PERIOD:",
- "staking": "STAKING...",
- "unstaking": "UNSTAKING...",
- "note": "NOTE:",
- "stakingRewardsAreAutomatically": "Staking rewards are automatically paid out. Unstaking may take up to the lock period to complete. Check Kraken's terms for each asset's specific staking conditions.",
- "failedToFetchStaking": "Failed to fetch staking assets",
- "pleaseFillAllFields": "Please fill all fields",
- "insufficientBalance": "Insufficient balance",
- "stakingNotSupportedBy": "Staking not supported by current adapter",
- "pleaseEnterValidAmount": "Please enter valid amount",
- "insufficientStakedBalance": "Insufficient staked balance",
- "unstakingNotSupportedBy": "Unstaking not supported by current adapter",
- "krakenFutures": "KRAKEN FUTURES",
- "futuresTradingRiskWarning": "FUTURES TRADING RISK WARNING:",
- "futuresTradingInvolvesHigh": "Futures trading involves high risk and leverage. Only trade with funds you can afford to lose. Requires separate Kraken Futures account.",
- "noFuturesMarketsAvailable": "NO FUTURES MARKETS AVAILABLE",
- "markPrice": "MARK PRICE",
- "tradingVolume": "TRADING VOLUME",
- "openInterest1": "OPEN INTEREST",
- "totalPositions": "TOTAL POSITIONS",
- "fundingRate1": "FUNDING RATE",
- "every8Hours": "EVERY 8 HOURS",
- "nextFunding": "NEXT FUNDING",
- "maxLeverage": "MAX LEVERAGE",
- "contractDetails": "CONTRACT DETAILS",
- "contractType": "CONTRACT TYPE:",
- "perpetual": "Perpetual",
- "settlement": "SETTLEMENT:",
- "contractSize": "CONTRACT SIZE:",
- "minOrder": "MIN ORDER:",
- "howToTrade": "HOW TO TRADE:",
- "apiIntegration": "API INTEGRATION:",
- "toTradeFuturesDirectly": "To trade futures directly from this terminal, configure Kraken Futures API credentials in Settings.",
- "tradeOnKrakenFutures": "TRADE ON KRAKEN FUTURES",
- "failedToFetchFutures": "Failed to fetch futures markets",
- "vaultAddress": "VAULT ADDRESS",
- "subaccountAddress": "SUBACCOUNT ADDRESS",
- "_0x": "0x...",
- "marginMode": "MARGIN MODE",
- "crossexchangePortfolio": "CROSS-EXCHANGE PORTFOLIO",
- "totalPortfolioValue": "TOTAL PORTFOLIO VALUE",
- "assetBreakdown": "ASSET BREAKDOWN",
- "noBalancesFound": "NO BALANCES FOUND",
- "note1": "NOTE:",
- "thisViewAggregatesBalances": "This view aggregates balances from all connected exchanges. Values\n are updated every 30 seconds. Exchange-specific details are shown for each asset.",
- "arbitrageOpportunities": "ARBITRAGE OPPORTUNITIES",
- "riskWarning": "RISK WARNING:",
- "arbitrageOpportunitiesIncludeTrading": "Arbitrage opportunities include trading fees, withdrawal\n fees, and execution risk. Always calculate net profit after all costs. Prices can change\n rapidly.",
- "scanningForArbitrageOpportunities": "SCANNING FOR ARBITRAGE OPPORTUNITIES...",
- "noArbitrageOpportunitiesFound": "NO ARBITRAGE OPPORTUNITIES FOUND",
- "potentialProfit": "POTENTIAL PROFIT",
- "buyOn": "BUY ON",
- "sellOn": "SELL ON",
- "priceDifference": "PRICE DIFFERENCE:",
- "executeArbitrage": "EXECUTE ARBITRAGE",
- "howItWorks": "HOW IT WORKS",
- "costConsiderations": "COST CONSIDERATIONS:",
- "autoscan": "AUTO-SCAN:",
- "opportunitiesAreAutomaticallyScanned": "Opportunities are automatically scanned every 10 seconds.\n Click \"SCAN\" to manually refresh.",
- "loadingPositions": "Loading positions...",
- "noOpenPositions1": "No open positions",
- "loadingOrders": "Loading orders...",
- "cancelAll": "CANCEL ALL",
- "noOpenOrders1": "No open orders",
- "okAllOrdersCanceled": "[OK] All orders canceled",
- "thisExchangeDoesNot": "This exchange does not support closed orders history",
- "loadingOrderHistory": "Loading order history...",
- "noClosedOrders": "No closed orders",
- "avgFill": "AVG FILL",
- "orderType1": "ORDER TYPE",
- "marketPrice": "Market Price:",
- "advancedOptions": "ADVANCED OPTIONS",
- "stopLoss1": "STOP LOSS",
- "takeProfit1": "TAKE PROFIT",
- "optional1": "Optional",
- "marginTrading": "Margin Trading",
- "notAvailableOrNot": "Not available or not enabled on this account",
- "marginStatus": "Margin Status",
- "marginCallWarning": "Margin Call Warning!",
- "yourMarginLevelIs": "Your margin level is critically low. Add funds or close positions to avoid liquidation.",
- "marginLevel": "Margin Level",
- "totalMargin": "Total Margin",
- "usedMargin": "Used Margin",
- "availableMargin": "Available Margin",
- "maintenanceMargin": "Maintenance Margin",
- "tradingFees": "TRADING FEES",
- "noFeeInformationAvailable": "No fee information available",
- "makerFee": "MAKER FEE",
- "takerFee": "TAKER FEE",
- "maker": "Maker:",
- "taker": "Taker:",
- "feeForAddingLiquidity": "Fee for adding liquidity to the order book",
- "feeForTakingLiquidity": "Fee for taking liquidity from the order book",
- "avgWin": "AVG WIN",
- "avgLoss": "AVG LOSS",
- "profitFactor1": "PROFIT FACTOR",
- "largestWin": "LARGEST WIN",
- "largestLoss": "LARGEST LOSS",
- "sharpeRatio": "SHARPE RATIO",
- "totalFeesPaid": "TOTAL FEES PAID",
- "noVolumeDataAvailable": "No volume data available",
- "volumeByPrice": "VOLUME BY PRICE",
- "poc": "POC:",
- "totalVolume": "TOTAL VOLUME",
- "priceLevels": "PRICE LEVELS",
- "timeframe": "TIMEFRAME:",
- "trend": "Trend",
- "mark": "Mark",
- "trendLine": "Trend Line",
- "markCurrentTime": "Mark Current Time",
- "pluginSettings": "Plugin Settings",
- "timeframe1": "TIMEFRAME:",
- "noDataAvailable1": "No data available",
- "active": "Active:",
- "undoLastDrawingDeletebackspace": "Undo Last Drawing (Delete/Backspace)",
- "clearAllDrawings": "Clear All Drawings",
- "clearAllDrawingsAnd": "Clear all drawings and positions?",
- "clearAllDrawings1": "Clear all drawings?",
- "noOrderbookDataAvailable": "No orderbook data available",
- "marketDepth1": "MARKET DEPTH",
- "tradeHistory": "TRADE HISTORY",
- "noTradesYet": "No trades yet",
- "allModels": "ALL MODELS",
- "entry": "ENTRY:",
- "target": "TARGET:",
- "stop": "STOP:",
- "size3": "SIZE:",
- "sup": "SUP:",
- "res": "RES:",
- "risk": "RISK:",
- "conf": "CONF:",
- "winRate1": "WIN RATE",
- "pos": "POS:",
- "decisionFeed": "DECISION FEED",
- "debateArena": "DEBATE ARENA",
- "bullAgent": "BULL AGENT",
- "bearAgent": "BEAR AGENT",
- "analystAgent": "ANALYST AGENT",
- "debating": "DEBATING...",
- "startDebate": "START DEBATE",
- "finalDecision": "FINAL DECISION",
- "newDebate": "NEW DEBATE",
- "recentDebates": "RECENT DEBATES",
- "noSymbolSelected": "No symbol selected",
- "pleaseSelectDifferentModels": "Please select different models for each role",
- "aiTradingCompetition": "AI TRADING COMPETITION",
- "selectModelsMinimum2": "SELECT MODELS (minimum 2)",
- "failedToLoadModels": "Failed to load models. Configure API keys in Settings.",
- "selectAtLeast2": "Select at least 2 models",
- "aiAgents": "AI AGENTS",
- "quick": "Quick",
- "comprehensive": "Comprehensive",
- "deep": "Deep",
- "momentum": "Momentum",
- "breakout": "Breakout",
- "reversal": "Reversal",
- "trend1": "Trend",
- "action": "Action:",
- "modelDecisions": "MODEL DECISIONS",
- "symbol1": "Symbol:",
- "side": "Side:",
- "entry1": "Entry:",
- "quantity": "Quantity:",
- "stopLoss2": "Stop Loss:",
- "takeProfit2": "Take Profit:",
- "noAgents": "NO AGENTS",
- "createYourFirstAi": "Create your first AI agent",
- "portfolioDataNotAvailable": "Portfolio data not available",
- "needAtLeast2": "Need at least 2 configured models to start a competition",
- "generateATradeSignal": "Generate a trade signal first",
- "myTradingAgent": "My Trading Agent",
- "gpt4omini": "gpt-4o-mini",
- "btcusdEthusd": "BTC/USD, ETH/USD",
- "alwaysUseRiskManagement10never": "Always use risk management
Never trade during low volume
Focus on high confidence setups",
- "basicConfiguration": "BASIC CONFIGURATION",
- "llmConfiguration1": "LLM CONFIGURATION",
- "tradingConfiguration": "TRADING CONFIGURATION",
- "safetyLimits": "SAFETY LIMITS",
- "takeProfitStopLoss": "TAKE PROFIT / STOP LOSS",
- "advancedOptions1": "ADVANCED OPTIONS",
- "sectorAllocation": "SECTOR ALLOCATION",
- "noSectorDataAvailable": "No sector data available. Add holdings with sector information.",
- "sectorBreakdown": "SECTOR BREAKDOWN",
- "diversificationMetrics": "DIVERSIFICATION METRICS",
- "totalSectors": "Total Sectors",
- "largestSector": "Largest Sector",
- "concentrationRisk": "Concentration Risk",
- "diversification": "Diversification",
- "loadingRiskMetrics": "Loading risk metrics...",
- "calculatingPortfolioRiskFrom": "Calculating portfolio risk from historical data",
- "insufficientHistoricalData": "INSUFFICIENT HISTORICAL DATA:",
- "overallRisk": "OVERALL RISK",
- "marketSensitivity": "MARKET SENSITIVITY",
- "riskadjustedReturns": "RISK-ADJUSTED RETURNS",
- "sharpeRatio1": "SHARPE RATIO",
- "riskadjustedReturnMeasure": "Risk-adjusted return measure",
- "marketCorrelationCoefficient": "Market correlation coefficient",
- "annualizedStandardDeviation": "Annualized standard deviation",
- "lowerVolatilityIndicatesMore": "Lower volatility indicates more stable returns",
- "downsideRiskMetrics": "DOWNSIDE RISK METRICS",
- "maxDrawdown": "MAX DRAWDOWN",
- "largestPeaktotroughDecline": "Largest peak-to-trough decline",
- "maximumLossFromPeak": "Maximum loss from peak value",
- "compositeRiskScore": "COMPOSITE RISK SCORE",
- "weightedRiskAssessment": "Weighted risk assessment",
- "riskManagementRecommendations": "RISK MANAGEMENT RECOMMENDATIONS",
- "lowSharpeRatio": "LOW SHARPE RATIO:",
- "considerDiversifyingToImprove": "Consider diversifying to improve risk-adjusted returns",
- "highBeta": "HIGH BETA:",
- "portfolioIsMoreVolatile": "Portfolio is more volatile than market. Consider defensive assets",
- "highVolatility": "HIGH VOLATILITY:",
- "considerAddingBondsOr": "Consider adding bonds or stable assets to reduce swings",
- "largeDrawdown": "LARGE DRAWDOWN:",
- "reviewStoplossStrategiesAnd": "Review stop-loss strategies and position sizing",
- "excellentSharpe": "EXCELLENT SHARPE:",
- "portfolioShowsStrongRiskadjusted": "Portfolio shows strong risk-adjusted performance",
- "balancedBeta": "BALANCED BETA:",
- "goodMarketCorrelationNeither": "Good market correlation, neither too aggressive nor defensive",
- "disclaimer": "DISCLAIMER:",
- "totalTaxLiability": "TOTAL TAX LIABILITY",
- "longtermGains": "LONG-TERM GAINS",
- "shorttermGains": "SHORT-TERM GAINS",
- "unrealizedGains": "UNREALIZED GAINS",
- "notTaxableUntilSold": "Not taxable until sold",
- "taxBreakdownFifoMethod": "TAX BREAKDOWN (FIFO METHOD)",
- "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",
- "totalDividendsYtd": "Total Dividends (YTD):",
- "portfolioYield": "Portfolio Yield:",
- "exportOptions": "EXPORT OPTIONS",
- "exportTaxReportPdf": "EXPORT TAX REPORT (PDF)",
- "exportTransactionsCsv": "EXPORT TRANSACTIONS (CSV)",
- "exportHoldingsXlsx": "EXPORT HOLDINGS (XLSX)",
- "reportsAreGeneratedFor": "Reports are generated for the current tax year. Consult with a tax professional for accurate filing.",
- "currentPositions1": "CURRENT POSITIONS",
- "avgPrice": "AVG PRICE",
- "mktValue": "MKT VALUE",
- "costBasis": "COST BASIS",
- "dayChange": "DAY CHANGE",
- "noPositionsYetClick": "No positions yet. Click BUY to add your first position.",
- "optimizationConfiguration": "OPTIMIZATION CONFIGURATION",
- "optimizationLibrary": "OPTIMIZATION LIBRARY",
- "optimizingPortfolio": "OPTIMIZING PORTFOLIO",
- "noPortfolioSelectedUsing": "No portfolio selected. Using default symbols.",
- "optimizationMethod": "OPTIMIZATION METHOD",
- "objectiveFunction": "OBJECTIVE FUNCTION",
- "riskMeasure": "RISK MEASURE",
- "expectedReturnsMethod": "EXPECTED RETURNS METHOD",
- "riskModel": "RISK MODEL",
- "l2RegularizationGamma": "L2 REGULARIZATION (Gamma)",
- "runningOptimization": "Running optimization...",
- "optimizationResults": "OPTIMIZATION RESULTS",
- "performanceMetrics": "PERFORMANCE METRICS",
- "expectedAnnualReturn": "Expected Annual Return",
- "annualVolatility": "Annual Volatility",
- "sharpeRatio2": "Sharpe Ratio",
- "sortinoRatio": "Sortino Ratio",
- "calmarRatio": "Calmar Ratio",
- "maxDrawdown1": "Max Drawdown",
- "optimalWeights": "OPTIMAL WEIGHTS",
- "exportJson": "EXPORT JSON",
- "exportCsv": "EXPORT CSV",
- "configureParametersAndClick": "Configure parameters and click \"RUN OPTIMIZATION\" to see results",
- "frontierParameters": "FRONTIER PARAMETERS",
- "numberOfPoints": "NUMBER OF POINTS",
- "generatingFrontier": "Generating frontier...",
- "eachPointRepresentsAn": "Each point represents an optimal portfolio. Color indicates Sharpe ratio:",
- "runningBacktest": "Running backtest...",
- "calculatingAllocation": "Calculating allocation...",
- "totalValue": "Total Value",
- "allocated": "Allocated",
- "leftoverCash": "Leftover Cash",
- "shareAllocation": "SHARE ALLOCATION",
- "riskDecompositionAndCorrelation": "Risk decomposition and correlation matrix analysis coming soon...",
- "aaplgooglmsftamzntsla": "AAPL,GOOGL,MSFT,AMZN,TSLA",
- "runOptimizationFirst": "Run optimization first",
- "discreteAllocationIsOnly": "Discrete allocation is only available for PyPortfolioOpt",
- "loadingPerformanceData": "Loading performance data...",
- "fetchingPortfolioSnapshotsFrom": "Fetching portfolio snapshots from database",
- "noPerformanceDataAvailable": "No performance data available",
- "portfolioSnapshotsWillBe": "Portfolio snapshots will be created automatically as you use the application",
- "periodReturn": "PERIOD RETURN",
- "periodGain": "PERIOD GAIN",
- "currentValue": "CURRENT VALUE",
- "startValue": "START VALUE",
- "costBasis1": "COST BASIS",
- "portfolioValueOverTime": "PORTFOLIO VALUE OVER TIME",
- "dailyPerformanceData": "DAILY PERFORMANCE DATA",
- "tip": "TIP:",
- "transactionHistory": "TRANSACTION HISTORY",
- "noTransactionsYet": "No transactions yet",
- "portfolioAnalyticsDashboard": "PORTFOLIO ANALYTICS DASHBOARD",
- "advancedPortfolioMetricsPythonpowered": "ADVANCED PORTFOLIO METRICS (Python-Powered)",
- "sharpeRatio3": "SHARPE RATIO",
- "maxDrawdown2": "MAX DRAWDOWN",
- "annualReturn": "ANNUAL RETURN",
- "optimizedAllocationMaxSharpe": "OPTIMIZED ALLOCATION (Max Sharpe Ratio)",
- "optimizedSharpe": "Optimized Sharpe:",
- "loadingAdvancedAnalytics": "Loading advanced analytics...",
- "totalValue1": "TOTAL VALUE",
- "dayChange1": "DAY CHANGE",
- "activeHoldings": "Active Holdings",
- "topGainers": "TOP GAINERS",
- "noData1": "No data",
- "topLosers": "TOP LOSERS",
- "largestPositions": "LARGEST POSITIONS",
- "allocationBreakdown": "ALLOCATION BREAKDOWN",
- "priceAlertsFeature": "PRICE ALERTS FEATURE",
- "thisFeatureIsNot": "This feature is not yet implemented.",
- "priceAlertsWillAllow": "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",
- "smsNotificationsPremium": "SMS notifications (Premium)",
- "pushNotifications": "Push notifications",
- "suggestedAlertsForYour": "SUGGESTED ALERTS FOR YOUR POSITIONS (PREVIEW)",
- "comingSoon": "COMING SOON",
- "implementationStatus": "IMPLEMENTATION STATUS",
- "thePriceAlertsSystem": "The price alerts system requires backend implementation including:",
- "databaseSchemaForPrice": "Database schema for price alert conditions",
- "realtimePriceMonitoringService": "Real-time price monitoring service",
- "notificationDeliverySystem": "Notification delivery system",
- "alertCreationAndManagement": "Alert creation and management API endpoints",
- "advancedPortfolioManagement": "ADVANCED PORTFOLIO MANAGEMENT",
- "riskMetrics": "RISK METRICS",
- "downsideVol": "DOWNSIDE VOL",
- "maxDrawdown3": "MAX DRAWDOWN",
- "clickCalculateToAnalyze": "Click CALCULATE to analyze portfolio risk",
- "assetAllocation": "ASSET ALLOCATION",
- "conservative": "Conservative",
- "moderate": "Moderate",
- "aggressive": "Aggressive",
- "yearsToRet": "YEARS TO RET",
- "recommendedAllocation": "RECOMMENDED ALLOCATION",
- "totalEquity": "Total Equity:",
- "totalFixedIncome": "Total Fixed Income:",
- "retirementPlanning": "RETIREMENT PLANNING",
- "currentAge": "CURRENT AGE",
- "retirementAge": "RETIREMENT AGE",
- "currentSavings": "CURRENT SAVINGS",
- "annualContrib": "ANNUAL CONTRIB",
- "projectedSavings": "Projected Savings:",
- "monthlyIncome": "Monthly Income:",
- "behavioralBiases": "BEHAVIORAL BIASES",
- "noSignificantBiasesDetected": "No significant biases detected",
- "clickAnalyzeToDetect": "Click ANALYZE to detect behavioral biases",
- "runningActiveManagementAnalysis": "Running Active Management Analysis...",
- "noAnalysisDataYet": "No analysis data yet",
- "portfolioNeedsReturnData": "Portfolio needs return data to perform active management analysis",
- "activeManagementAnalytics": "ACTIVE MANAGEMENT ANALYTICS",
- "benchmark": "BENCHMARK:",
- "qualityRating": "QUALITY RATING:",
- "qualityScore": "QUALITY SCORE:",
- "valueAddedDecomposition": "VALUE ADDED DECOMPOSITION",
- "allocationEffect": "ALLOCATION EFFECT",
- "selectionEffect": "SELECTION EFFECT",
- "keyStrengths": "KEY STRENGTHS",
- "areasForImprovement": "AREAS FOR IMPROVEMENT",
- "improvementRecommendations": "IMPROVEMENT RECOMMENDATIONS",
- "activeReturn": "ACTIVE RETURN",
- "annualized": "Annualized",
- "informationRatio": "INFORMATION RATIO",
- "riskadjustedPerformance": "Risk-Adjusted Performance",
- "trackingError": "TRACKING ERROR",
- "hitRate": "HIT RATE",
- "positivePeriods": "Positive Periods",
- "tstatistic": "T-STATISTIC",
- "statisticalMeasure": "Statistical Measure",
- "noPortfolioReturnData": "No portfolio return data available",
- "unableToFetchBenchmark": "Unable to fetch benchmark returns. Please check your internet connection and try again.",
- "sellAssetFromPortfolio": "SELL ASSET FROM PORTFOLIO",
- "createNewPortfolio": "CREATE NEW PORTFOLIO",
- "usdUsDollar": "USD - US Dollar",
- "eurEuro": "EUR - Euro",
- "gbpBritishPound": "GBP - British Pound",
- "inrIndianRupee": "INR - Indian Rupee",
- "myPortfolio": "My Portfolio",
- "johnDoe": "John Doe",
- "addAssetToPortfolio": "ADD ASSET TO PORTFOLIO",
- "optimizationConfiguration1": "OPTIMIZATION CONFIGURATION",
- "optimizationLibrary1": "OPTIMIZATION LIBRARY",
- "assetSymbolsCommaseparated": "ASSET SYMBOLS (comma-separated)",
- "optimizationMethod1": "OPTIMIZATION METHOD",
- "objectiveFunction1": "OBJECTIVE FUNCTION",
- "riskMeasure1": "RISK MEASURE",
- "expectedReturnsMethod1": "EXPECTED RETURNS METHOD",
- "riskModel1": "RISK MODEL",
- "l2RegularizationGamma1": "L2 REGULARIZATION (Gamma)",
- "optimizationResults1": "OPTIMIZATION RESULTS",
- "performanceMetrics1": "PERFORMANCE METRICS",
- "expectedAnnualReturn1": "Expected Annual Return",
- "annualVolatility1": "Annual Volatility",
- "sharpeRatio4": "Sharpe Ratio",
- "optimalWeights1": "OPTIMAL WEIGHTS",
- "exportJson1": "EXPORT JSON",
- "exportCsv1": "EXPORT CSV",
- "configureParametersAndClick1": "Configure parameters and click \"RUN OPTIMIZATION\" to see results",
- "chartVisualizationWouldBe": "Chart visualization would be rendered here using Recharts or similar",
- "totalValue2": "Total Value",
- "allocated1": "Allocated",
- "leftoverCash1": "Leftover Cash",
- "shareAllocation1": "SHARE ALLOCATION",
- "riskDecompositionAndCorrelation1": "Risk decomposition and correlation matrix analysis coming soon...",
- "aaplgooglmsftamzntsla1": "AAPL,GOOGL,MSFT,AMZN,TSLA",
- "runOptimizationFirst1": "Run optimization first",
- "loadingWorkflows": "Loading workflows...",
- "createANewWorkflow": "Create a new workflow in the Editor tab",
- "failedToDeleteWorkflow": "Failed to delete workflow",
- "areYouSureYou": "Are you sure you want to delete this workflow?",
- "technicalAnalysis": "TECHNICAL ANALYSIS",
- "dataSource": "DATA SOURCE",
- "type1": "Type:",
- "symbol2": "Symbol:",
- "period1": "Period:",
- "file": "File:",
- "waitingForUpstreamData": "Waiting for upstream data...",
- "dataSource1": "Data Source",
- "yahooFinance": "Yahoo Finance",
- "csvFile": "CSV File",
- "jsonData": "JSON Data",
- "upstreamInput": "Upstream Input",
- "symbol3": "Symbol",
- "period2": "Period",
- "max": "Max",
- "csvFilePath": "CSV File Path",
- "indicatorCategories": "Indicator Categories",
- "running1": "RUNNING...",
- "unknownNodeType": "Unknown Node Type",
- "disabled": "Disabled",
- "configure": "Configure",
- "configureNode": "Configure node",
- "executeNode": "Execute node",
- "noDataReceivedYet": "No data received yet.",
- "connectThisNodeTo": "Connect this node to an output to see results.",
- "copyToClipboard": "Copy to clipboard",
- "dragToResize": "Drag to resize",
- "llmConfiguration2": "LLM CONFIGURATION",
- "llmProviderForAnalysis": "LLM Provider for Analysis",
- "useActiveProviderFrom": "Use Active Provider (from Settings)",
- "running2": "RUNNING...",
- "optimizationTarget": "Optimization Target",
- "sharpeRatio5": "Sharpe Ratio",
- "totalReturn1": "Total Return",
- "sortinoRatio1": "Sortino Ratio",
- "calmarRatio1": "Calmar Ratio",
- "profitFactor2": "Profit Factor",
- "method": "Method",
- "gridSearch": "Grid Search",
- "geneticAlgorithm": "Genetic Algorithm",
- "bayesianOptimization": "Bayesian Optimization",
- "maxIterations": "Max Iterations",
- "parameterRanges": "Parameter Ranges",
- "min": "Min",
- "max1": "Max",
- "step": "Step",
- "saveConfiguration": "Save Configuration",
- "configuration": "Configuration:",
- "bestParameters": "Best Parameters:",
- "iterations": "Iterations",
- "duration": "Duration",
- "error2": "Error:",
- "runOptimization": "Run Optimization",
- "strategy": "Strategy",
- "bestParams": "Best Params",
- "allResults": "All Results",
- "collectionAdvanced": "Collection (Advanced)",
- "fixedCollection": "Fixed Collection",
- "complexInputConfigureIn": "Complex input - configure in advanced editor",
- "byId": "By ID",
- "byUrl": "By URL",
- "fromList": "From List",
- "useExpressionsLike": "Use expressions like:",
- "jsonfield": "={{$json.field}}",
- "_000000": "#000000",
- "toggleExpressionMode": "Toggle expression mode",
- "nodePalette": "Node Palette",
- "noNodesFound": "No nodes found",
- "tryADifferentSearch": "Try a different search term",
- "dragNodesToThe": "Drag nodes to the canvas or click to add",
- "searchNodes": "Search nodes...",
- "selectANodeTo": "Select a node to configure",
- "nodeTypeNotFound": "Node type not found",
- "noParametersToConfigure": "No parameters to configure",
- "disabled1": "Disabled",
- "active1": "Active",
- "executing": "EXECUTING...",
- "executeTool": "EXECUTE TOOL",
- "executedSuccessfully": "Executed successfully",
- "failedToLoadTool": "Failed to load tool schema",
- "databaseConnection": "Database Connection",
- "sqlQuery": "SQL Query",
- "saveConfig": "SAVE CONFIG",
- "connection": "Connection",
- "noConnectionSelected": "No connection selected",
- "query": "Query",
- "noQueryDefined": "No query defined",
- "selectFromTableWhere": "SELECT * FROM table WHERE condition",
- "configureDataSource": "Configure data source",
- "startDate": "Start Date",
- "endDate": "End Date",
- "saveConfiguration1": "Save Configuration",
- "configuration1": "Configuration:",
- "results": "Results:",
- "totalReturn2": "Total Return",
- "sharpeRatio6": "Sharpe Ratio",
- "maxDd": "Max DD",
- "trades": "Trades",
- "error3": "Error:",
- "runningBacktest1": "Running Backtest...",
- "runBacktest": "Run Backtest",
- "strategy1": "Strategy",
- "results1": "Results",
- "llmMediator": "LLM MEDIATOR",
- "llmProvider": "LLM PROVIDER",
- "inputData": "INPUT DATA",
- "mediatedContext": "MEDIATED CONTEXT",
- "mediatorSettings": "MEDIATOR SETTINGS",
- "llmProvider1": "LLM Provider",
- "useActiveProvider": "Use Active Provider",
- "customMediationPromptOptional": "Custom Mediation Prompt (optional)",
- "saveConfig1": "SAVE CONFIG",
- "mediating": "MEDIATING...",
- "leaveEmptyForDefault": "Leave empty for default prompt",
- "autoscroll": "Auto-scroll",
- "clear": "Clear",
- "download": "Download",
- "noLogsAvailableServer": "No logs available. Server may not be running.",
- "autostartOnLaunch": "Auto-start on launch",
- "addCustomMcpServer": "ADD CUSTOM MCP SERVER",
- "environmentVariablesOnePer": "ENVIRONMENT VARIABLES (one per line)",
- "iconEmoji": "ICON (emoji)",
- "addServer": "ADD SERVER",
- "whatDoesThisServer": "What does this server do?",
- "bunxNodePythonEtc": "bunx, node, python, etc.",
- "pleaseFillInAll": "Please fill in all required fields",
- "mcpMarketplace": "MCP MARKETPLACE",
- "aiChat": "AI CHAT",
- "browseMarketplace": "BROWSE MARKETPLACE",
- "autostart": "Auto-start",
- "noToolsAvailableStart": "No tools available. Start an MCP server to see its tools.",
- "searchInstalledServers": "Search installed servers...",
- "goBackToAi": "Go back to AI Chat",
- "removeThisMcpServer": "Remove this MCP server? This will delete all associated data.",
- "noServersFoundMatching": "No servers found matching your search.",
- "tryADifferentSearch1": "Try a different search term or category.",
- "requiresConfiguration": "Requires Configuration",
- "searchMarketplace": "Search marketplace...",
- "configureYourQuestdbConnection": "Configure your QuestDB connection. QuestDB uses PostgreSQL wire protocol (default port 8812).",
- "requireSslConnection": "Require SSL Connection",
- "connectionStringPreview": "CONNECTION STRING PREVIEW:",
- "enterDatabasePassword": "Enter database password",
- "configureYourPostgresqlDatabase": "Configure your PostgreSQL database connection. The connection string will be passed securely to the MCP server.",
- "requireSslConnection1": "Require SSL Connection",
- "connectionStringPreview1": "CONNECTION STRING PREVIEW:",
- "enterDatabasePassword1": "Enter database password",
- "pleaseFillInAll1": "Please fill in all required fields",
- "equityTrading": "EQUITY TRADING",
- "resetPaperTradingAccount": "RESET PAPER TRADING ACCOUNT",
- "thisWill": "This will",
- "thisActionCannotBe": "This action cannot be undone.",
- "resetAccount": "RESET ACCOUNT",
- "quoteData": "QUOTE DATA",
- "enterASymbol": "ENTER A SYMBOL",
- "typeASymbolTo": "Type a symbol to view quote data",
- "lastTradedPrice": "LAST TRADED PRICE",
- "prevClose2": "PREV CLOSE",
- "totalEquity1": "TOTAL EQUITY",
- "winRate2": "WIN RATE",
- "totalTrades1": "TOTAL TRADES",
- "sharpeRatio7": "SHARPE RATIO",
- "orderEntry": "ORDER ENTRY",
- "selectASymbol": "SELECT A SYMBOL",
- "enterASymbolTo": "Enter a symbol to view chart data",
- "performanceMetrics2": "PERFORMANCE METRICS",
- "winRate3": "Win Rate",
- "profitFactor3": "Profit Factor",
- "sharpeRatio8": "Sharpe Ratio",
- "maxDrawdown4": "Max Drawdown",
- "tradeStatistics": "TRADE STATISTICS",
- "avgWin1": "Avg Win",
- "avgLoss1": "Avg Loss",
- "largestWin1": "Largest Win",
- "largestLoss1": "Largest Loss",
- "totalFees": "Total Fees",
- "pleaseEnterAValid3": "Please enter a valid symbol",
- "pleaseEnterAValid4": "Please enter a valid amount",
- "somethingWentWrong1": "Something went wrong",
- "anErrorOccurredWhile": "An error occurred while rendering this component. Please try refreshing or contact support if the issue persists.",
- "errorDetails": "Error details",
- "tryAgain": "Try Again",
- "orderType2": "ORDER TYPE",
- "stopLoss3": "STOP LOSS",
- "slm": "SL-M",
- "priceLtp": "PRICE (LTP)",
- "triggerPrice": "TRIGGER PRICE",
- "cncDelivery": "CNC (DELIVERY)",
- "misIntraday": "MIS (INTRADAY)",
- "nrmlNormal": "NRML (NORMAL)",
- "routingStrategy": "ROUTING STRATEGY",
- "bestLatency": "BEST LATENCY",
- "bestPrice": "BEST PRICE",
- "allBrokers": "ALL BROKERS",
- "roundRobin": "ROUND ROBIN",
- "selectBrokers": "SELECT BROKERS",
- "typeToSearchEg": "Type to search... (e.g., RELIANCE, TATAMOTORS)",
- "autofetching": "Auto-fetching...",
- "pleaseEnterASymbol": "Please enter a symbol",
- "pleaseEnterAValid5": "Please enter a valid quantity",
- "pleaseEnterAValid6": "Please enter a valid price for limit order",
- "loadingChart": "Loading chart...",
- "noChartDataAvailable": "No chart data available",
- "noPositions": "NO POSITIONS",
- "avgPrice1": "AVG PRICE",
- "paperTrading": "PAPER TRADING",
- "resetPaperTradingAccount1": "RESET PAPER TRADING ACCOUNT",
- "thisWillCloseAll": "This will close all positions, cancel all orders, and reset your balance.\r\n This action cannot be undone.",
- "paperTradingIsDisabled": "Paper Trading is Disabled",
- "enablePaperTradingTo": "Enable paper trading to practice trading without risking real money.\r\n All orders will be simulated with realistic execution.",
- "enablePaperTrading": "ENABLE PAPER TRADING",
- "performanceMetrics3": "PERFORMANCE METRICS",
- "noOpenPositions2": "No open positions",
- "noPendingOrders": "No pending orders",
- "noOrders": "NO ORDERS",
- "avgPrice2": "AVG PRICE",
- "waitingForMarketDepth": "Waiting for market depth data...",
- "table": "Table",
- "chart": "Chart",
- "spread2": "Spread:",
- "totalBid": "Total Bid:",
- "totalAsk": "Total Ask:",
- "bidQty": "Bid Qty",
- "bidPrice": "Bid Price",
- "askPrice": "Ask Price",
- "askQty": "Ask Qty",
- "noHoldings": "NO HOLDINGS",
- "avgPrice3": "AVG PRICE",
- "dayChange2": "DAY CHANGE",
- "performanceAnalytics": "PERFORMANCE ANALYTICS",
- "tradeStatistics1": "TRADE STATISTICS",
- "brokerPerformance": "BROKER PERFORMANCE",
- "winRate4": "WIN RATE",
- "recentTrades2": "RECENT TRADES",
- "noTradingDataAvailable": "NO TRADING DATA AVAILABLE",
- "startTradingToSee": "Start trading to see performance metrics",
- "nifty100LiveQuotes": "NIFTY 100 LIVE QUOTES",
- "sortBy": "SORT BY:",
- "lastPrice1": "LAST PRICE",
- "fetchingNifty100Quotes": "Fetching Nifty 100 quotes...",
- "searchSymbol": "Search symbol...",
- "liveQuote": "LIVE QUOTE",
- "getQuote": "Get Quote",
- "lastPrice2": "LAST PRICE",
- "historicalData": "HISTORICAL DATA",
- "fetchHistoricalData": "Fetch Historical Data",
- "symbolEgSbin": "Symbol (e.g., SBIN)",
- "liveStreaming": "LIVE STREAMING",
- "disconnect": "Disconnect",
- "lastPrice3": "LAST PRICE",
- "prevClose3": "PREV CLOSE",
- "volumeTraded": "VOLUME TRADED",
- "lastTradeQty": "LAST TRADE QTY",
- "totalBuyQty": "TOTAL BUY QTY",
- "totalSellQty": "TOTAL SELL QTY",
- "addSymbolEgRites": "Add symbol (e.g., RITES, IRCTC)",
- "searchStreamingSymbols": "Search streaming symbols...",
- "symbolAlreadyAdded": "Symbol already added!",
- "multibrokerComparison": "MULTI-BROKER COMPARISON",
- "enterASymbolAnd": "ENTER A SYMBOL AND CLICK COMPARE TO VIEW BROKER QUOTES",
- "lastPrice4": "LAST PRICE",
- "enterASymbolAnd1": "ENTER A SYMBOL AND CLICK COMPARE TO VIEW MARKET DEPTH",
- "runAComparisonTo": "RUN A COMPARISON TO VIEW LATENCY DATA",
- "averageSpread": "AVERAGE SPREAD",
- "minSpread": "MIN SPREAD",
- "maxSpread": "MAX SPREAD",
- "bestBroker": "BEST BROKER",
- "tightestSpread": "TIGHTEST SPREAD:",
- "recommendationUse": "RECOMMENDATION: USE",
- "forBestExecutionQuality": "FOR BEST EXECUTION QUALITY",
- "enterSymbolEgReliance": "ENTER SYMBOL (E.G., RELIANCE)",
- "brokerConfiguration": "BROKER CONFIGURATION",
- "allCredentialsEncryptedAnd": "ALL CREDENTIALS ENCRYPTED AND STORED SECURELY",
- "loadingSavedCredentials": "Loading saved credentials...",
- "appId": "APP ID",
- "appSecret": "APP SECRET",
- "clientId": "CLIENT ID",
- "totpKeyOptional": "TOTP KEY (OPTIONAL)",
- "forAutomatedLoginWithout": "For automated login without manual 2FA",
- "apiKey": "API KEY",
- "apiSecret": "API SECRET",
- "accessTokenRequired": "ACCESS TOKEN (REQUIRED)",
- "howToGetAccess": "HOW TO GET ACCESS TOKEN:",
- "tradingMode": "TRADING MODE",
- "secretKey": "SECRET KEY",
- "howToGetApi": "HOW TO GET API CREDENTIALS:",
- "yourFyersAppId": "Your Fyers App ID",
- "yourFyersAppSecret": "Your Fyers App Secret",
- "yourFyersClientId": "Your Fyers Client ID",
- "yourFyersPin": "Your Fyers PIN",
- "totpSecretFor2fa": "TOTP Secret for 2FA",
- "yourKiteApiKey": "Your Kite API Key",
- "yourKiteApiSecret": "Your Kite API Secret",
- "pasteYourAccessToken": "Paste your access token here",
- "yourAlpacaApiKey": "Your Alpaca API Key",
- "yourAlpacaSecretKey": "Your Alpaca Secret Key",
- "kiteZerodha": "KITE (ZERODHA)",
- "alpacaMarkets": "ALPACA MARKETS",
- "strategyBacktesting": "STRATEGY BACKTESTING",
- "testYourStrategiesWith": "Test your strategies with historical data",
- "backtestConfiguration": "BACKTEST CONFIGURATION",
- "dataSource2": "DATA SOURCE",
- "startDate1": "START DATE",
- "endDate1": "END DATE",
- "smaCrossover": "SMA Crossover",
- "custom": "Custom",
- "totalReturn3": "TOTAL RETURN",
- "winRate5": "WIN RATE",
- "sharpeRatio9": "SHARPE RATIO",
- "maxDrawdown5": "MAX DRAWDOWN",
- "detailedMetrics": "DETAILED METRICS",
- "exportCsv2": "EXPORT CSV",
- "equityCurve": "EQUITY CURVE",
- "chartVisualizationComingSoon": "CHART VISUALIZATION COMING SOON",
- "configureYourBacktestAnd": "CONFIGURE YOUR BACKTEST AND CLICK RUN BACKTEST",
- "egReliance": "E.G., RELIANCE",
- "momentumIndicatorsAnalysis": "Momentum Indicators Analysis",
- "overallSignal": "Overall Signal:",
- "error4": "Error:",
- "enterAStockSymbol": "Enter a stock symbol and click Search to analyze",
- "howToUse": "How to use:",
- "enterStockSymbolEg": "Enter stock symbol (e.g., AAPL)",
- "refreshData": "Refresh data",
- "cfaInstitutecompliantPeerComparison": "CFA Institute-compliant peer comparison and benchmarking",
- "roe1": "ROE:",
- "revenueGrowth": "Revenue Growth:",
- "peerSummary": "Peer Summary",
- "availablePeers": "Available Peers:",
- "selectedPeers": "Selected Peers:",
- "avgSimilarity": "Avg Similarity:",
- "overallRating": "Overall Rating",
- "runAPeerComparison": "Run a peer comparison to see percentile rankings",
- "goToPeerComparison": "Go to Peer Comparison",
- "searchForASymbol": "Search for a symbol to see sector analysis",
- "enterStockSymbolEg1": "Enter stock symbol (e.g., AAPL, MSFT)",
- "valuation": "Valuation",
- "profitability": "Profitability",
- "growth": "Growth",
- "overall": "Overall",
- "stockScreener": "Stock Screener",
- "filterStocksByFundamental": "Filter stocks by fundamental metrics and criteria",
- "exportCsv3": "Export CSV",
- "saveScreen": "Save Screen",
- "fetchingRealtimeDataFrom": "Fetching real-time data from FMP...",
- "screenTemplates": "Screen Templates",
- "savedScreens": "Saved Screens",
- "addFilter": "Add Filter",
- "noFiltersDefinedClick": "No filters defined. Click \"Add Filter\" to start building your screen.",
- "screeningResults": "Screening Results",
- "saveCustomScreen": "Save Custom Screen",
- "noStocksMatchThe": "No stocks match the screening criteria.",
- "enterScreenName": "Enter screen name...",
- "min1": "Min",
- "max2": "Max",
- "value": "Value",
- "removeFilter": "Remove filter",
- "noScreeningCriteriaDefined": "No screening criteria defined",
- "failedToExecuteScreen": "Failed to execute screen",
- "companies": "Companies:",
- "avgMarketCap": "Avg Market Cap:",
- "avgSimilarity1": "Avg Similarity:",
- "sectorDistribution": "Sector Distribution",
- "switchToTreemap": "Switch to Treemap",
- "avgCap": "Avg Cap:",
- "similarity": "Similarity:",
- "sectorHeatmap": "Sector Heatmap",
- "switchToGrid": "Switch to Grid",
- "avgRoe": "Avg ROE",
- "avgGrowth": "Avg Growth",
- "percentile": "Percentile:",
- "value1": "Value:",
- "peerMedian": "Peer Median:",
- "zscore": "Z-Score:",
- "metric": "Metric",
- "value3": "Value",
- "percentile1": "Percentile",
- "zscore1": "Z-Score",
- "peerMedian1": "Peer Median",
- "status": "Status",
- "peerComparison": "Peer Comparison",
- "targetCompanySymbol": "Target Company Symbol",
- "selectTargetCompanyAnd": "Select target company and add peer companies to compare",
- "exportCsv4": "Export CSV",
- "noPeersSelectedAdd": "No peers selected. Add peers manually using the input below.",
- "addPeerManually": "Add Peer Manually",
- "addPeer": "Add Peer",
- "availablePeers1": "Available Peers",
- "valuationAssessment": "Valuation Assessment",
- "sectorBenchmarks": "Sector Benchmarks",
- "medianRoe": "Median ROE",
- "medianRevenueGrowth": "Median Revenue Growth",
- "metricComparisonBarCharts": "Metric Comparison - Bar Charts",
- "compareKeyFinancialMetrics": "Compare key financial metrics across all companies",
- "metricComparison": "Metric Comparison",
- "valuesNormalized0100For": "Values normalized 0-100 for visualization",
- "percentileRankings": "Percentile Rankings",
- "limitedPeerSample": "Limited Peer Sample",
- "selectMetrics1": "Select Metrics",
- "metric1": "Metric",
- "enterSymbolEgAapl": "Enter symbol (e.g., AAPL, GOOGL)",
- "enterPeerSymbolEg": "Enter peer symbol (e.g., MSFT, GOOGL)",
- "period3": "Period",
- "overbought": "Overbought",
- "oversold": "Oversold",
- "current1": "Current:",
- "fastPeriod": "Fast Period",
- "slowPeriod": "Slow Period",
- "signalPeriod": "Signal Period",
- "histogram": "Histogram:",
- "kPeriod": "K Period",
- "dPeriod": "D Period",
- "momentumIndicators": "Momentum Indicators",
- "resetToDefaults": "Reset to defaults",
- "financialAnalysis": "Financial Analysis",
- "analyzing": "Analyzing...",
- "runAnalysis": "Run Analysis",
- "documentationTerminal": "DOCUMENTATION TERMINAL",
- "sections": "SECTIONS:",
- "topics": "TOPICS:",
- "codeExample": "CODE EXAMPLE",
- "finceptTerminalDocumentation": "FINCEPT TERMINAL DOCUMENTATION",
- "selectATopicFrom": "Select a topic from the navigation panel to view comprehensive guides and API reference.",
- "searchDocumentation": "Search documentation...",
- "searchDocumentation1": "Search documentation...",
- "selectATopicFrom1": "Select a topic from the sidebar",
- "codeExample1": "CODE EXAMPLE",
- "dataSources": "DATA SOURCES",
- "authRequired": "Auth Required",
- "testable": "Testable",
- "noConnectionsConfigured": "No connections configured",
- "addYourFirstData": "Add your first data source connection to get started",
- "browseDataSources": "BROWSE DATA SOURCES",
- "searchDataSources": "Search data sources...",
- "noSampleDataAvailable": "No sample data available",
- "pleaseFetchSampleData": "Please fetch sample data from API configuration",
- "runTestToVerify": "Run test to verify mapping configuration",
- "saveMappingConfiguration": "SAVE MAPPING CONFIGURATION",
- "dataMapping": "DATA MAPPING",
- "loadingMappings": "Loading mappings...",
- "noMappingsConfigured": "NO MAPPINGS CONFIGURED",
- "createYourFirstApi": "Create your first API data mapping to connect external data sources to Fincept Terminal",
- "createFirstMapping": "CREATE FIRST MAPPING",
- "pleaseFetchSampleData1": "Please fetch sample data first",
- "pleaseConfigureAtLeast": "Please configure at least one field mapping",
- "pleaseTestTheMapping": "Please test the mapping successfully before saving",
- "pleaseProvideAMapping": "Please provide a mapping name",
- "mappingSavedSuccessfully": "Mapping saved successfully!",
- "failedToDeleteMapping": "Failed to delete mapping",
- "pleaseCompleteTheCurrent": "Please complete the current step before proceeding",
- "deleteThisMappingThis": "Delete this mapping? This cannot be undone.",
- "sourceDataSampleResponse": "Source Data (Sample Response)",
- "clickOnAnyPath": "Click on any path to select it for mapping",
- "selectedPath": "SELECTED PATH",
- "parserEngine": "Parser Engine",
- "targetSchemaFields": "Target Schema Fields",
- "noFieldsDefined": "No fields defined",
- "previewValue": "PREVIEW VALUE",
- "remove": "Remove",
- "orEnterExpressionManually": "Or enter expression manually:",
- "pressEnterToCreate": "Press Enter to create mapping",
- "mappingStatus": "Mapping Status",
- "mapped": "Mapped:",
- "required": "Required:",
- "total2": "Total:",
- "expression": "Expression",
- "copyPath": "Copy path",
- "previewValue1": "Preview value",
- "templateLibrary": "Template Library",
- "prebuiltMappingsForPopular": "Pre-built mappings for popular brokers and data sources",
- "allBrokers1": "All Brokers",
- "useTemplate": "USE TEMPLATE",
- "noTemplatesFound": "No templates found",
- "tryAdjustingYourSearch": "Try adjusting your search or filter",
- "templateDetails": "Template Details",
- "usageInstructions": "USAGE INSTRUCTIONS",
- "fieldMappings": "FIELD MAPPINGS",
- "useThisTemplate": "USE THIS TEMPLATE",
- "searchTemplates": "Search templates...",
- "verified": "Verified",
- "official": "Official",
- "selectTargetSchema": "Select Target Schema",
- "chooseTheStandardizedFormat": "Choose the standardized format that your source data will be mapped to",
- "schemaDetails": "Schema Details",
- "chooseSchemaType": "Choose Schema Type",
- "predefinedSchema": "Predefined Schema",
- "useBuiltinSchemasOhlcv": "Use built-in schemas (OHLCV, QUOTE, ORDER, etc.)",
- "customSchema": "Custom Schema",
- "defineYourOwnFields": "Define your own fields for any data type",
- "clickTheGreenAutoadd": "Click the green \"AUTO-ADD ALL\" button to add all fields from your data array automatically",
- "expandTheTreeLeft": "Expand the tree (left), click any",
- "nestedFieldsGetFull": "Nested fields get full path names (e.g.,",
- "automaticallyFindsYourData": "Automatically finds your data array (looks for \"data\", \"results\", \"items\")",
- "noSampleDataAvailable1": "No Sample Data Available",
- "goBackToStep": "Go back to Step 1 and click \"Fetch Sample Data\" to see your API response here.\n This will make it much easier to create your schema!",
- "apiResponse": "API Response",
- "autoaddAll": "AUTO-ADD ALL",
- "noSampleData": "No sample data",
- "fetchSampleDataIn": "Fetch sample data in Step 1 to see it here",
- "addManually": "ADD MANUALLY",
- "noFieldsYet": "No fields yet",
- "type2": "Type",
- "description1": "Description",
- "required1": "Required",
- "fieldDescription": "Field description",
- "autoaddAllPrimitiveFields": "Auto-add all primitive fields",
- "removeField": "Remove field",
- "pleaseExpandThisField": "Please expand this field and select a specific property inside it.",
- "transformingData": "Transforming data...",
- "configureMappingAndTest": "Configure mapping and test to see preview",
- "transformationSuccessful": "TRANSFORMATION SUCCESSFUL",
- "transformationFailed": "TRANSFORMATION FAILED",
- "duration1": "Duration",
- "recordsProcessed": "Records Processed",
- "recordsReturned": "Records Returned",
- "rawInputData": "RAW INPUT DATA",
- "transformedOutput": "TRANSFORMED OUTPUT",
- "remove1": "Remove",
- "noDataToDisplay": "No data to display. Fetch sample data to begin.",
- "jsonStructure": "JSON STRUCTURE",
- "collapseAll": "Collapse All",
- "expandLevel1": "Expand Level 1",
- "copyPath1": "Copy path",
- "generateExpression": "Generate expression",
- "parserEngine1": "Parser Engine",
- "expression1": "Expression",
- "loadExample": "Load Example",
- "testDataJson": "Test Data (JSON)",
- "statusCode": "Status Code:",
- "suggestions": "Suggestions:",
- "technicalDetails": "Technical Details",
- "retryRequest": "RETRY REQUEST",
- "responseCaching": "Response Caching",
- "enableCaching": "Enable Caching",
- "cacheApiResponsesTo": "Cache API responses to reduce requests",
- "cacheDurationSeconds": "Cache Duration (seconds)",
- "commonValues601": "Common values: 60 (1 min), 300 (5 min), 3600 (1 hour)",
- "security1": "Security",
- "encryptApiCredentials": "Encrypt API Credentials",
- "storeApiKeysAnd": "Store API keys and tokens encrypted in local database",
- "encryptionIsEnabled": "Encryption is enabled.",
- "yourApiKeysAnd": "Your API keys and\n tokens are encrypted using AES-256-GCM before being stored.\n You can toggle this setting anytime.",
- "encryptionIsDisabled": "Encryption is disabled.",
- "yourApiKeysAnd1": "Your API keys and\n tokens will be stored in plain text. This is less secure but\n may be useful for debugging.",
- "failedToUpdateEncryption": "Failed to update encryption setting",
- "cacheClearedSuccessfully": "Cache cleared successfully",
- "failedToClearCache": "Failed to clear cache",
- "allCacheClearedSuccessfully": "All cache cleared successfully",
- "failedToClearAll": "Failed to clear all cache",
- "clearCacheForThis": "Clear cache for this mapping? This cannot be undone.",
- "mappingDetails": "Mapping Details",
- "description2": "Description",
- "apiEndpoint": "API Endpoint",
- "authentication": "Authentication",
- "noAuthentication": "No Authentication",
- "apiKey1": "API Key",
- "bearerToken": "Bearer Token",
- "basicAuth": "Basic Auth",
- "oauth20": "OAuth 2.0",
- "header": "Header",
- "queryParameter": "Query Parameter",
- "headersOptional": "Headers (Optional)",
- "queryParametersOptional": "Query Parameters (Optional)",
- "requestBodyJson": "Request Body (JSON)",
- "urlPreview": "URL PREVIEW",
- "testParameters": "Test Parameters",
- "myApiMapping": "My API Mapping",
- "briefDescriptionOfThis": "Brief description of this mapping",
- "keyNameEgXapikey": "Key name (e.g., X-API-Key, apiKey)",
- "apiKeyValue": "API Key value",
- "bearerToken1": "Bearer token",
- "username": "Username",
- "password": "Password",
- "widgetType": "WIDGET TYPE",
- "allNews": "All News",
- "markets": "Markets",
- "technology": "Technology",
- "earnings1": "Earnings",
- "economic": "Economic",
- "marketIndices": "Market Indices",
- "techStocks": "Tech Stocks",
- "commodities": "Commodities",
- "noWatchlistsAvailableCreate": "No watchlists available. Create one in the Watchlist tab first.",
- "trendingPosts": "Trending Posts",
- "recentPosts": "Recent Posts",
- "clickToOpenFull": "Click to open full Maritime Intelligence view",
- "loadData": "LOAD DATA",
- "configure1": "Configure",
- "refresh": "Refresh",
- "remove2": "Remove",
- "noTradeHistoryYet": "No trade history yet. Start the competition to see executed trades.",
- "loadingCompetitions": "Loading competitions...",
- "noCompetitionsYet": "NO COMPETITIONS YET",
- "createYourFirstAlpha": "Create your first Alpha Arena competition to pit AI models against each other in live trading simulations.",
- "createCompetition": "CREATE COMPETITION",
- "viewDetails": "View Details",
- "areYouSureYou1": "Are you sure you want to delete this competition? All data will be lost.",
- "noPerformanceDataYet": "No performance data yet. Start the competition to see the chart.",
- "modelLibrary": "MODEL LIBRARY",
- "modelType": "Model Type",
- "allModels1": "All Models",
- "treebased": "Tree-Based",
- "neuralNetworks": "Neural Networks",
- "loadingModels": "LOADING MODELS...",
- "noModelsFound": "No models found",
- "keyFeatures": "KEY FEATURES",
- "useCases": "USE CASES",
- "predictionConfiguration": "PREDICTION CONFIGURATION",
- "instrumentsCommaseparated": "Instruments (Comma-separated)",
- "startDate2": "Start Date",
- "endDate2": "End Date",
- "predictionResults": "PREDICTION RESULTS",
- "runningPredictions": "RUNNING PREDICTIONS...",
- "runPredictions": "RUN PREDICTIONS",
- "noModelSelected": "NO MODEL SELECTED",
- "selectAModelFrom": "Select a model from the library to view details and run predictions",
- "aaplmsftgoogl": "AAPL,MSFT,GOOGL",
- "refreshModels": "Refresh models",
- "liveSignals": "LIVE SIGNALS",
- "realtimePredictionsFromDeployed": "Real-time predictions from deployed models",
- "model": "Model",
- "xgboost": "XGBoost",
- "transformer": "Transformer",
- "instruments": "Instruments",
- "refreshIntervalSec": "Refresh Interval (sec)",
- "startStreaming": "START STREAMING",
- "stopStreaming": "STOP STREAMING",
- "signalFilter": "Signal Filter",
- "waitingForSignals": "WAITING FOR SIGNALS",
- "noSignalsYet": "NO SIGNALS YET",
- "configureYourModelAnd": "Configure your model and instruments, then start streaming",
- "functimeLibraryNotInstalled": "Functime Library Not Installed",
- "installFunctimeAndPolars": "Install functime and polars for ML time series forecasting",
- "checkAgain": "Check Again",
- "timeSeriesForecasting": "Time Series Forecasting",
- "dataSource3": "Data Source",
- "manual": "Manual",
- "portfolio": "Portfolio",
- "symbol4": "Symbol",
- "selectPortfolio": "SELECT PORTFOLIO",
- "noPortfoliosFound": "No portfolios found",
- "tickerSymbol": "TICKER SYMBOL",
- "historicalDays": "HISTORICAL DAYS",
- "fetchData": "Fetch Data",
- "assets": "Assets:",
- "dataPoints": "Data Points:",
- "range": "Range:",
- "forecast": "Forecast",
- "anomaly": "Anomaly",
- "season": "Season",
- "panelDataJson": "PANEL DATA (JSON)",
- "modelConfiguration": "Model Configuration",
- "forecastModel": "FORECAST MODEL",
- "forecastHorizon": "FORECAST HORIZON",
- "dataFrequency": "DATA FREQUENCY",
- "alphaRegularization": "ALPHA (REGULARIZATION)",
- "testSizeForEvaluation": "TEST SIZE (FOR EVALUATION)",
- "none": "None",
- "standardScaling": "Standard Scaling",
- "differencing": "Differencing",
- "anomalyDetectionSettings": "Anomaly Detection Settings",
- "detectionMethod": "DETECTION METHOD",
- "zscore2": "Z-Score",
- "iqrInterquartileRange": "IQR (Interquartile Range)",
- "isolationForest": "Isolation Forest",
- "seasonalityAnalysis": "Seasonality Analysis",
- "analyzesTimeSeriesFor": "Analyzes time series for seasonal patterns, trend strength, and periodicity.\r\n Uses FFT and ACF for automatic period detection.",
- "anomalyDetectionResults": "Anomaly Detection Results",
- "seasonalityAnalysisResults": "Seasonality Analysis Results",
- "period4": "Period:",
- "seasonalStrength": "Seasonal Strength:",
- "trendStrength": "Trend Strength:",
- "dataSummary": "Data Summary",
- "evaluationMetrics": "Evaluation Metrics",
- "forecastChart": "Forecast Chart",
- "forecastResults": "Forecast Results",
- "horizon": "Horizon:",
- "frequency1": "Frequency:",
- "autotuned": "Auto-tuned:",
- "bestParametersAutotuned": "Best Parameters (Auto-tuned)",
- "noDataToDisplay1": "No data to display",
- "reset": "Reset",
- "historical": "Historical",
- "date": "Date:",
- "value4": "Value:",
- "entity": "Entity:",
- "functimeLibraryNotInstalled1": "Functime library not installed. Run: pip install functime polars",
- "failedToCheckFunctime": "Failed to check functime status",
- "portfolioHasNoHoldings": "Portfolio has no holdings",
- "failedToFetchHistorical": "Failed to fetch historical data for portfolio",
- "fortitudotechNotInstalled": "FORTITUDO.TECH NOT INSTALLED",
- "installTheLibraryTo": "Install the library to enable portfolio risk analytics:",
- "fortitudotechRiskAnalytics": "FORTITUDO.TECH RISK ANALYTICS",
- "dataSource4": "DATA SOURCE",
- "sampleData": "SAMPLE DATA",
- "myPortfolios": "MY PORTFOLIOS",
- "selectPortfolio1": "SELECT PORTFOLIO",
- "historicalDays1": "HISTORICAL DAYS",
- "portfolio1": "Portfolio:",
- "holdings": "Holdings:",
- "dataPoints1": "Data Points:",
- "period5": "Period:",
- "noPortfoliosFoundCreate": "No portfolios found. Create a portfolio in the Portfolio tab first.",
- "portfolioWeights": "PORTFOLIO WEIGHTS",
- "halflifeDays": "HALF-LIFE (DAYS)",
- "riskMetrics1": "RISK METRICS",
- "equalWeightScenarios": "EQUAL WEIGHT SCENARIOS",
- "scenarios": "Scenarios:",
- "assets1": "Assets:",
- "alpha": "Alpha:",
- "spotPrice": "SPOT PRICE",
- "riskfreeRate": "RISK-FREE RATE",
- "divYield1": "DIV YIELD",
- "timeYears": "TIME (YEARS)",
- "callPrice": "CALL PRICE",
- "putPrice": "PUT PRICE",
- "optionGreeks": "OPTION GREEKS",
- "callOption": "CALL OPTION",
- "putOption": "PUT OPTION",
- "meanvariance": "MEAN-VARIANCE",
- "meancvar": "MEAN-CVaR",
- "maxSharpe": "Max Sharpe",
- "targetReturn": "Target Return",
- "maxWeight": "MAX WEIGHT",
- "targetReturn1": "TARGET RETURN",
- "cvarAlpha": "CVaR ALPHA",
- "longOnly": "LONG ONLY",
- "optimalPortfolio": "OPTIMAL PORTFOLIO",
- "type3": "Type:",
- "objective": "Objective:",
- "constraints": "Constraints:",
- "minRisk": "MIN RISK",
- "maxSharpe1": "MAX SHARPE",
- "expectedReturn": "Expected Return",
- "sharpeRatio10": "Sharpe Ratio",
- "position": "Position:",
- "minimumRiskPortfolio": "Minimum Risk Portfolio",
- "maximumReturnPortfolio": "Maximum Return Portfolio",
- "maximumSharpePortfolio": "Maximum Sharpe Portfolio",
- "intermediatePortfolio": "Intermediate Portfolio",
- "maxReturn": "MAX RETURN",
- "numberOfScenarios": "NUMBER OF SCENARIOS",
- "fortitudotechLibraryNotInstalled": "Fortitudo.tech library not installed. Run: pip install fortitudo.tech cvxopt",
- "failedToCheckFortitudotech": "Failed to check fortitudo.tech status",
- "ffnLibraryNotInstalled": "FFN Library Not Installed",
- "checkAgain1": "Check Again",
- "dataSource5": "Data Source",
- "manual1": "Manual",
- "portfolio2": "Portfolio",
- "symbol5": "Symbol",
- "selectPortfolio2": "SELECT PORTFOLIO",
- "historicalDays2": "HISTORICAL DAYS",
- "fetchData1": "Fetch Data",
- "analysisMode": "ANALYSIS MODE",
- "performance": "Performance",
- "monthly": "Monthly",
- "rolling": "Rolling",
- "compare": "Compare",
- "optimize": "Optimize",
- "benchmark1": "Benchmark",
- "optimizationMethod2": "OPTIMIZATION METHOD",
- "invVol": "Inv Vol",
- "meanvar": "Mean-Var",
- "equalWt": "Equal Wt",
- "benchmarkSymbol": "BENCHMARK SYMBOL",
- "commonSpyQqqIwm": "Common: SPY, QQQ, IWM, DIA",
- "priceDataJson": "PRICE DATA (JSON)",
- "riskfreeRate1": "RISK-FREE RATE",
- "drawdownThreshold": "DRAWDOWN THRESHOLD",
- "analyzing1": "ANALYZING...",
- "runAnalysis1": "RUN ANALYSIS",
- "performanceMetrics4": "Performance Metrics",
- "drawdownAnalysis": "Drawdown Analysis",
- "topDrawdownPeriods": "TOP DRAWDOWN PERIODS",
- "riskMetrics2": "Risk Metrics",
- "monthlyReturnsHeatmap": "Monthly Returns Heatmap",
- "year1": "Year",
- "rollingMetrics63day": "Rolling Metrics (63-Day)",
- "rollingSharpeRatio": "ROLLING SHARPE RATIO",
- "rollingVolatility": "ROLLING VOLATILITY",
- "assetComparison": "Asset Comparison",
- "correlationMatrix": "CORRELATION MATRIX",
- "performanceComparison": "PERFORMANCE COMPARISON",
- "asset": "Asset",
- "return": "Return",
- "vol2": "Vol",
- "sharpe": "Sharpe",
- "optimalWeights2": "OPTIMAL WEIGHTS",
- "optimizedPortfolioMetrics": "OPTIMIZED PORTFOLIO METRICS",
- "assetContributions": "ASSET CONTRIBUTIONS",
- "weight": "Weight",
- "riskContrib": "Risk Contrib",
- "totalReturn4": "Total Return",
- "volatility": "Volatility",
- "sharpeRatio11": "Sharpe Ratio",
- "maxDrawdown6": "Max Drawdown",
- "relativeMetrics": "RELATIVE METRICS",
- "ffnLibraryNotInstalled1": "FFN library not installed. Run: pip install ffn",
- "failedToCheckFfn": "Failed to check FFN status",
- "portfolioHasNoHoldings1": "Portfolio has no holdings",
- "failedToFetchHistorical1": "Failed to fetch historical data for portfolio",
- "failedToFetchData": "Failed to fetch data for any symbols",
- "autonomousFactorMining": "AUTONOMOUS FACTOR MINING",
- "aipoweredDiscoveryOfProfitable": "AI-powered discovery of profitable trading factors",
- "researchObjective": "Research Objective",
- "examples": "Examples:",
- "requiredForAipoweredFactor": "Required for AI-powered factor generation",
- "targetMarket": "Target Market",
- "usMarkets": "US Markets",
- "chinaAshares": "China (A-shares)",
- "cryptocurrency": "Cryptocurrency",
- "budgetUsd": "Budget (USD)",
- "mining": "MINING...",
- "taskStatus": "TASK STATUS",
- "factorsGenerated": "FACTORS GENERATED",
- "factorsTested": "FACTORS TESTED",
- "bestIc": "BEST IC",
- "elapsedTime": "ELAPSED TIME",
- "discoveredFactors": "DISCOVERED FACTORS",
- "sharpe1": "SHARPE:",
- "ret": "RET:",
- "performanceMetrics5": "PERFORMANCE METRICS",
- "factorImplementation": "FACTOR IMPLEMENTATION",
- "deployToLiveTrading": "DEPLOY TO LIVE TRADING",
- "noFactorsDiscoveredYet": "NO FACTORS DISCOVERED YET",
- "configureYourResearchObjective": "Configure your research objective and start factor mining",
- "describeTheTypeOf": "Describe the type of factors you want to discover...",
- "skproj": "sk-proj-...",
- "pleaseProvideTaskDescription": "Please provide task description and OpenAI API key",
- "copiedToClipboard": "Copied to clipboard!",
- "strategyBacktesting1": "STRATEGY BACKTESTING",
- "testTradingStrategiesWith": "Test trading strategies with historical data",
- "strategyConfiguration": "STRATEGY CONFIGURATION",
- "strategyType": "Strategy Type",
- "topkDropout": "Top-K Dropout",
- "weightbased": "Weight-Based",
- "enhancedIndexing": "Enhanced Indexing",
- "universeCommaseparated": "Universe (Comma-separated)",
- "startDate3": "Start Date",
- "endDate3": "End Date",
- "topKPositions": "Top K Positions",
- "portfolioSettings": "PORTFOLIO SETTINGS",
- "initialCapitalUsd": "Initial Capital (USD)",
- "benchmark2": "Benchmark",
- "runningBacktest2": "RUNNING BACKTEST...",
- "runBacktest1": "RUN BACKTEST",
- "backtestError": "BACKTEST ERROR",
- "backtestResults": "BACKTEST RESULTS",
- "performanceMetrics6": "PERFORMANCE METRICS",
- "tradeStatistics2": "TRADE STATISTICS",
- "detailedResults": "DETAILED RESULTS",
- "noBacktestResults": "NO BACKTEST RESULTS",
- "configureYourStrategyParameters": "Configure your strategy parameters and run a backtest",
- "aiQuantLab": "AI QUANT LAB",
- "rdagent": "RD-AGENT",
- "initializingAiQuantLab": "INITIALIZING AI QUANT LAB",
- "settingUpQlibAnd": "Setting up Qlib and RD-Agent (this may take 10-30 seconds)",
- "dependenciesNotInstalled": "DEPENDENCIES NOT INSTALLED",
- "aiQuantLabRequires": "AI Quant Lab requires Microsoft Qlib and RD-Agent Python packages",
- "installMicrosoftQlib": "INSTALL MICROSOFT QLIB",
- "installRdagent": "INSTALL RD-AGENT",
- "autonomousAiAgentFor": "Autonomous AI agent for factor mining and model optimization",
- "downloadQlibDataOptional": "DOWNLOAD QLIB DATA (OPTIONAL)",
- "downloadHistoricalMarketData": "Download historical market data for China (CN) or US markets",
- "reloadAfterInstallation": "RELOAD AFTER INSTALLATION",
- "initializeAiQuantLab": "INITIALIZE AI QUANT LAB",
- "qlibAndRdagentAre": "Qlib and RD-Agent are installed but need to be initialized.",
- "thisWillSetUp": "This will set up data providers and configure the services.",
- "initializing": "INITIALIZING...",
- "initializeServices": "INITIALIZE SERVICES",
- "refreshStatus": "Refresh status",
- "settings": "Settings",
- "finceptTerminal": "FINCEPT TERMINAL",
- "checkingSystemRequirements": "CHECKING SYSTEM REQUIREMENTS...",
- "beginSetup": "BEGIN SETUP",
- "python3127EmbeddedRuntime": "PYTHON 3.12.7 EMBEDDED RUNTIME",
- "bunV110Runtime": "BUN v1.1.0 RUNTIME",
- "setupError": "SETUP ERROR",
- "retrySetup": "RETRY SETUP",
- "estimated515MinutesDepending": "ESTIMATED: 5-15 MINUTES DEPENDING ON NETWORK SPEED AND CPU",
- "doNotCloseApplication": "DO NOT CLOSE APPLICATION DURING INSTALLATION",
- "installationLogs": "INSTALLATION LOGS",
- "sectionName": "Section name...",
- "moveToMenuSection": "Move to menu section",
- "moveToHeader": "Move to header",
- "resetTabConfigurationTo": "Reset tab configuration to default? This cannot be undone.",
- "polymarketApiCredentials": "Polymarket API Credentials",
- "manageYourPolymarketApi": "Manage your Polymarket API credentials for trading and portfolio access",
- "twoWaysToGet": "Two ways to get credentials:",
- "walletConnection": "Wallet Connection",
- "manualEntry": "Manual Entry",
- "learnMoreAboutAuthentication": "Learn more about authentication",
- "credentialsActive": "Credentials Active",
- "walletAddress": "Wallet Address",
- "apiKey2": "API Key",
- "apiSecret1": "API Secret",
- "apiPassphrase": "API Passphrase",
- "export": "Export",
- "update": "Update",
- "connectMetamaskToAutomatically": "Connect MetaMask to automatically generate API credentials",
- "recommended": "Recommended",
- "connecting": "Connecting...",
- "enterExistingApiCredentials": "Enter existing API credentials from Polymarket",
- "forExistingCredentials": "For existing credentials",
- "enterApiCredentials": "Enter API Credentials",
- "orImportFromFile": "Or import from file",
- "saveCredentials": "Save Credentials",
- "needHelp": "Need Help?",
- "noCredentials": "No credentials?",
- "useWalletConnectionTo": "Use wallet connection to automatically generate them",
- "alreadyHaveCredentials": "Already have credentials?",
- "enterThemManuallyOr": "Enter them manually or import from file",
- "security2": "Security:",
- "credentialsAreStoredLocally": "Credentials are stored locally and never sent to our servers",
- "polymarketDocs": "Polymarket Docs",
- "enterYourApiKey": "Enter your API key",
- "enterYourApiSecret": "Enter your API secret",
- "enterYourApiPassphrase": "Enter your API passphrase",
- "allFieldsAreRequired": "All fields are required",
- "areYouSureYou2": "Are you sure you want to delete your Polymarket credentials?",
- "languageChangesWillApply": "Language changes will apply immediately across the entire terminal interface.\n All menus, labels, and system messages will be displayed in the selected language.",
- "dataSources1": "DATA SOURCES",
- "manageWebsocketConnectionsAnd": "Manage WebSocket connections and REST API integrations. Create aliases to easily reference data sources across the terminal.",
- "restApi": "REST API",
- "allTypes": "All Types",
- "addSource": "ADD SOURCE",
- "loadingDataSources": "Loading data sources...",
- "createFirstDataSource": "Create First Data Source",
- "type4": "Type:",
- "provider": "Provider:",
- "topic": "Topic:",
- "addWebsocketDataSource": "Add WebSocket Data Source",
- "aliasShortName": "ALIAS (short name)",
- "displayName": "DISPLAY NAME",
- "symbolOptional": "SYMBOL (optional)",
- "createDataSource": "CREATE DATA SOURCE",
- "editWebsocketDataSource": "Edit WebSocket Data Source",
- "updateDataSource": "UPDATE DATA SOURCE",
- "searchDataSources1": "Search data sources...",
- "bitcoinPrice": "Bitcoin Price",
- "realtimeBitcoinPriceFrom": "Real-time Bitcoin price from Kraken",
- "btcusd1": "BTC/USD",
- "failedToToggleData": "Failed to toggle data source",
- "failedToDeleteData": "Failed to delete data source",
- "pleaseFillInAll2": "Please fill in all required fields",
- "failedToCreateData": "Failed to create data source",
- "failedToUpdateData": "Failed to update data source",
- "deleteThisDataSource": "Delete this data source? This cannot be undone.",
- "dataStorageLocation": "DATA STORAGE LOCATION",
- "platform": "Platform:",
- "loadingProviders": "LOADING PROVIDERS...",
- "backtestingProviders": "BACKTESTING PROVIDERS",
- "manageBacktestingEnginesSwitch": "Manage backtesting engines. Switch between Lean, Backtrader, and other providers seamlessly.",
- "addProvider": "ADD PROVIDER",
- "addNewProvider": "ADD NEW PROVIDER",
- "providerType": "PROVIDER TYPE",
- "backtrader": "Backtrader",
- "backtestingpy": "Backtesting.py",
- "custom1": "Custom",
- "configurationJson": "CONFIGURATION (JSON)",
- "noProvidersConfigured": "NO PROVIDERS CONFIGURED",
- "clickAddProviderTo": "Click \"ADD PROVIDER\" to configure your first backtesting engine",
- "testing": "TESTING...",
- "registeredProviders": "REGISTERED PROVIDERS",
- "activeProvider": "ACTIVE PROVIDER",
- "areYouSureYou3": "Are you sure you want to delete this provider?",
- "confirmingPayment": "Confirming Payment",
- "activatingYourSubscription": "Activating your subscription...",
- "paymentConfirmationError": "Payment Confirmation Error",
- "continueToDashboard": "Continue to Dashboard",
- "checkYourAccountDashboard": "Check your account dashboard for subscription status",
- "paymentSuccessful": "Payment Successful!",
- "redirectingToDashboardIn": "Redirecting to dashboard in",
- "continueToDashboardNow": "Continue to Dashboard Now",
- "downloadReceipt": "Download Receipt",
- "failedToConfirmPayment": "Failed to confirm payment. Please contact support if you were charged.",
- "securePaymentProcessing": "Secure Payment Processing",
- "continueToDashboard1": "Continue to Dashboard",
- "checkStatusNow": "Check Status Now",
- "backToPlans": "Back to Plans",
- "checkAgain2": "Check Again",
- "completeYourPaymentIn": "Complete your payment in the opened browser window.",
- "thisPageWillAutomatically": "This page will automatically update when payment is confirmed.",
- "paymentProcessingMayTake": "Payment processing may take up to 10 minutes.",
- "youCanSafelyClose": "You can safely close this window and check your account later.",
- "ifYouCompletedThe": "If you completed the payment, please wait a few minutes and check again.",
- "contactSupportIfIssues": "Contact support if issues persist.",
- "authenticationRequired": "Authentication required",
- "failedToCheckPayment": "Failed to check payment status",
- "completeYourPayment": "Complete Your Payment",
- "securePayment": "Secure Payment",
- "loadingPaymentPage": "Loading Payment Page",
- "pleaseWaitWhileWe": "Please wait while we prepare your checkout...",
- "paymentPageFailedTo": "Payment Page Failed to Load",
- "tryAgain1": "Try Again",
- "openInBrowser": "Open in Browser",
- "sslEncrypted": "SSL Encrypted",
- "pciCompliant": "PCI Compliant",
- "securePaymentProcessing1": "Secure Payment Processing",
- "needHelpContactSupport": "Need help? Contact support",
- "openInBrowser1": "Open in browser",
- "paymentCheckout": "Payment Checkout",
- "trademarks1": "Trademarks",
- "informationAboutTrademarksAnd": "Information about trademarks and intellectual property rights.",
- "lastUpdatedJanuary1": "Last updated: January 1, 2026",
- "finceptTrademarks": "Fincept Trademarks",
- "theFollowingMarksAre": "The following marks are trademarks or registered trademarks of Fincept LP in the United States and other countries:",
- "registeredTrademark": "Registered Trademark",
- "trademark": "Trademark",
- "allRightsInThese": "All rights in these trademarks are reserved. Unauthorized use is strictly prohibited.",
- "thirdpartyTrademarks": "Third-Party Trademarks",
- "theFollowingAreTrademarks": "The following are trademarks or registered trademarks of their respective owners:",
- "thomsonReutersCorporation": "Thomson Reuters Corporation",
- "nasdaqInc": "NASDAQ, Inc.",
- "nyseGroupInc": "NYSE Group, Inc.",
- "ftseInternationalLimited": "FTSE International Limited",
- "allThirdpartyTrademarksMentioned": "All third-party trademarks mentioned are the property of their respective owners. Use of these marks does not imply endorsement by or affiliation with Fincept.",
- "trademarkGuidelines": "Trademark Guidelines",
- "ifYouWishTo": "If you wish to use any Fincept trademark, please follow these guidelines:",
- "permittedUses": "Permitted Uses:",
- "referentialUseToIdentify": "Referential use to identify Fincept products or services",
- "academicOrJournalisticReferences": "Academic or journalistic references with proper attribution",
- "useInComparativeAdvertising": "Use in comparative advertising when truthful and not misleading",
- "prohibitedUses": "Prohibited Uses:",
- "useAsPartOf": "Use as part of your own trademark or business name",
- "useThatImpliesSponsorship": "Use that implies sponsorship, endorsement, or affiliation",
- "modificationAlterationOrCombination": "Modification, alteration, or combination with other marks",
- "useInAWay": "Use in a way that disparages or damages Fincept's reputation",
- "copyrightNotice": "Copyright Notice",
- "theContentFeaturesAnd": "The content, features, and functionality of Fincept Terminal are protected by copyright, trademark, patent, and other intellectual property laws.",
- "reproductionModificationOrDistribution": "Reproduction, modification, or distribution of any content without written permission is strictly prohibited.",
- "dataProviderAcknowledgments": "Data Provider Acknowledgments",
- "marketDataAndFinancial": "Market data and financial information are provided by various third-party sources. Each data provider retains all rights to their content:",
- "usersMustComplyWith": "Users must comply with all third-party data provider terms and conditions.",
- "reportingTrademarkInfringement": "Reporting Trademark Infringement",
- "ifYouBelieveYour": "If you believe your trademark rights have been infringed, or if you discover unauthorized use of Fincept trademarks, please contact us:",
- "legalDepartment": "Legal Department",
- "phone1800fincept3462378": "Phone: 1-800-FINCEPT (346-2378)",
- "addressFinceptLp123": "Address: Fincept LP, 123 Financial District, New York, NY 10004",
- "backToLogin": "Back to Login",
- "termsOfService": "Terms of Service",
- "privacyPolicy": "Privacy Policy",
- "termsOfService1": "Terms of Service",
- "pleaseReadTheseTerms": "Please read these terms carefully before using Fincept services.",
- "lastUpdatedJanuary11": "Last updated: January 1, 2026",
- "byAccessingAndUsing": "By accessing and using Fincept Terminal (\"Service\"), you accept and agree to be bound by the terms and provision of this agreement.",
- "ifYouDoNot": "If you do not agree to abide by the above, please do not use this service.",
- "finceptTerminalIsA": "Fincept Terminal is a professional financial analytics and data platform that provides real-time market data, financial analysis tools, and portfolio management capabilities.",
- "theServiceIncludesBoth": "The Service includes both free guest access with limited features and paid subscription tiers with enhanced functionality.",
- "toAccessCertainFeatures": "To access certain features of the Service, you must register for an account. You agree to provide accurate, current, and complete information during the registration process.",
- "youAreResponsibleFor": "You are responsible for safeguarding the password and all activities that occur under your account.",
- "youMustNotifyUs": "You must notify us immediately of any unauthorized use of your account.",
- "youAgreeNotTo": "You agree not to use the Service to:",
- "violateAnyApplicableLaws": "Violate any applicable laws or regulations",
- "transmitAnyHarmfulOffensive": "Transmit any harmful, offensive, or disruptive content",
- "attemptToGainUnauthorized": "Attempt to gain unauthorized access to our systems",
- "useAutomatedScriptsOr": "Use automated scripts or bots without permission",
- "redistributeOrResellOur": "Redistribute or resell our data without authorization",
- "yourPrivacyIsImportant": "Your privacy is important to us. Our data collection and usage practices are detailed in our Privacy Policy, which forms part of these Terms.",
- "marketDataProvidedThrough": "Market data provided through the Service is sourced from third-party providers and is subject to their respective terms and conditions.",
- "paidSubscriptionsAreBilled": "Paid subscriptions are billed in advance on a monthly or annual basis. All fees are non-refundable except as required by law.",
- "weReserveTheRight": "We reserve the right to change our pricing with 30 days' notice to existing subscribers.",
- "yourSubscriptionWillAutomatically": "Your subscription will automatically renew unless cancelled before the renewal date.",
- "theServiceIsProvided": "The Service is provided \"as is\" without any warranties, express or implied. We do not guarantee the accuracy, completeness, or timeliness of market data.",
- "investmentDecisionsShouldNot": "Investment decisions should not be based solely on information provided by our Service. Always consult with qualified financial advisors.",
- "ourLiabilityIsLimited": "Our liability is limited to the amount paid for the Service in the preceding 12 months.",
- "weMayTerminateOr": "We may terminate or suspend your account immediately, without prior notice, for conduct that we believe violates these Terms or is harmful to other users, us, or third parties.",
- "youMayTerminateYour": "You may terminate your account at any time by contacting our support team.",
- "weReserveTheRight1": "We reserve the right to modify these Terms at any time. We will notify users of significant changes via email or through the Service.",
- "continuedUseOfThe": "Continued use of the Service after changes constitutes acceptance of the new Terms.",
- "ifYouHaveQuestions": "If you have questions about these Terms, please contact us at:",
- "phone1800fincept34623781": "Phone: 1-800-FINCEPT (346-2378)",
- "addressFinceptLp1231": "Address: Fincept LP, 123 Financial District, New York, NY 10004",
- "backToLogin1": "Back to Login",
- "privacyPolicy1": "Privacy Policy",
- "contactUs": "Contact Us",
- "privacyPolicy2": "Privacy Policy",
- "learnHowWeCollect": "Learn how we collect, use, and protect your personal information.",
- "lastUpdatedJanuary12": "Last updated: January 1, 2026",
- "ourCommitmentToPrivacy": "Our Commitment to Privacy",
- "weBelieveInTransparency": "We believe in transparency and will never sell, rent, or trade your personal information to third parties for marketing purposes.",
- "informationWeCollect": "Information We Collect",
- "personalInformation": "Personal Information",
- "nameEmailAddressAnd": "Name, email address, and phone number",
- "companyInformationAndJob": "Company information and job title",
- "accountCredentialsAndAuthentication": "Account credentials and authentication data",
- "billingAndPaymentInformation": "Billing and payment information",
- "communicationPreferences": "Communication preferences",
- "usageInformation": "Usage Information",
- "terminalUsagePatternsAnd": "Terminal usage patterns and feature interactions",
- "searchQueriesAndData": "Search queries and data requests",
- "sessionDurationAndFrequency": "Session duration and frequency of use",
- "deviceInformationAndBrowser": "Device information and browser type",
- "ipAddressAndLocation": "IP address and location data",
- "financialData": "Financial Data",
- "portfolioCompositionsAndHoldings": "Portfolio compositions and holdings",
- "tradingPreferencesAndStrategies": "Trading preferences and strategies",
- "watchlistsAndSavedAnalyses": "Watchlists and saved analyses",
- "customDashboardConfigurations": "Custom dashboard configurations",
- "howWeUseYour": "How We Use Your Information",
- "weUseYourInformation": "We use your information to:",
- "serviceDelivery": "Service Delivery",
- "communication": "Communication",
- "improvement": "Improvement",
- "informationSharing": "Information Sharing",
- "weMayShareYour": "We may share your information in the following circumstances:",
- "serviceProviders": "Service Providers:",
- "withTrustedThirdParties": "With trusted third parties who help deliver our services",
- "legalRequirements": "Legal Requirements:",
- "whenRequiredByLaw": "When required by law, regulation, or legal process",
- "businessTransfer": "Business Transfer:",
- "inConnectionWithA": "In connection with a merger, acquisition, or sale of assets",
- "consent": "Consent:",
- "whenYouExplicitlyConsent": "When you explicitly consent to sharing",
- "weNeverSellPersonal": "We never sell personal information to data brokers or advertising companies.",
- "dataSecurity": "Data Security",
- "weImplementIndustrystandardSecurity": "We implement industry-standard security measures to protect your data:",
- "yourRights": "Your Rights",
- "youHaveTheFollowing": "You have the following rights regarding your personal data:",
- "access": "Access:",
- "requestACopyOf": "Request a copy of your personal data",
- "correction": "Correction:",
- "updateInaccurateOrIncomplete": "Update inaccurate or incomplete information",
- "deletion": "Deletion:",
- "requestDeletionOfYour": "Request deletion of your personal data",
- "portability": "Portability:",
- "receiveYourDataIn": "Receive your data in a machine-readable format",
- "optout": "Opt-out:",
- "withdrawConsentForData": "Withdraw consent for data processing",
- "contactUs1": "Contact Us",
- "ifYouHaveQuestions1": "If you have questions about this Privacy Policy or our data practices:",
- "privacyOfficer": "Privacy Officer",
- "phone1800fincept34623782": "Phone: 1-800-FINCEPT (346-2378)",
- "addressFinceptLp1232": "Address: Fincept LP, 123 Financial District, New York, NY 10004",
- "backToLogin2": "Back to Login",
- "termsOfService2": "Terms of Service",
- "contactUs2": "Contact Us",
- "getInTouchWith": "Get in touch with our support team for assistance with your Fincept account.",
- "contactInformation": "Contact Information",
- "emailSupport": "Email Support",
- "averageResponseTime46": "Average response time: 4-6 hours",
- "phoneSupport": "Phone Support",
- "forUrgentTechnicalIssues": "For urgent technical issues",
- "supportHours": "Support Hours",
- "mondayFriday900Am": "Monday - Friday: 9:00 AM - 6:00 PM EST",
- "saturday1000Am400": "Saturday: 10:00 AM - 4:00 PM EST",
- "officeAddress": "Office Address",
- "finceptLp": "Fincept LP",
- "newYorkNy10004": "New York, NY 10004",
- "unitedStates": "United States",
- "quickActions": "Quick Actions",
- "startLiveChat": "Start Live Chat",
- "usuallyRespondsInMinutes": "Usually responds in minutes",
- "sendEmail": "Send Email",
- "forDetailedInquiries": "For detailed inquiries",
- "callSupport": "Call Support",
- "forUrgentIssues": "For urgent issues",
- "commonIssues": "Common Issues",
- "accountLoginProblems": "Account login problems",
- "passwordResetAccountLockouts": "Password reset, account lockouts, 2FA issues",
- "technicalDifficulties": "Technical difficulties",
- "platformErrorsConnectivityPerformance": "Platform errors, connectivity, performance",
- "billingInquiries": "Billing inquiries",
- "subscriptionPaymentsInvoices": "Subscription, payments, invoices",
- "backToLogin3": "Back to Login",
- "openingLiveChat": "Opening live chat...",
- "loadingTab": "Loading tab...",
- "unknownSession": "Unknown Session",
- "finceptProfessional": "FINCEPT PROFESSIONAL",
- "chatMode": "CHAT MODE",
- "monitoring": "Monitoring",
- "cryptoTrading": "Crypto Trading",
- "equityTrading1": "Equity Trading",
- "finxeptProfessional": "FINXEPT PROFESSIONAL",
- "updateAvailable": "Update Available",
- "aNewVersionOf": "A new version of FinceptTerminal is available.",
- "currentVersion": "Current Version:",
- "newVersion": "New Version:",
- "releaseDate": "Release Date:",
- "releaseNotes": "Release Notes:",
- "updateReady": "Update Ready!",
- "theApplicationWillRestart": "The application will restart in a moment...",
- "theUpdateWillDownload": "The update will download and install automatically. Your app will restart after installation.",
- "later": "Later",
- "updateNow": "Update Now",
- "goToProfile": "Go to Profile",
- "viewPlans": "View Plans",
- "viewCredits": "View Credits",
- "logout": "Logout",
- "help": "Help",
- "dashboardF1": "Dashboard (F1)",
- "marketsF2": "Markets (F2)",
- "newsF3": "News (F3)",
- "portfolioF4": "Portfolio (F4)",
- "backtestingF5": "Backtesting (F5)",
- "watchlistF6": "Watchlist (F6)",
- "equityResearchF7": "Equity Research (F7)",
- "screenerF8": "Screener (F8)",
- "cryptoTradingF9": "Crypto Trading (F9)",
- "aiChatF10": "AI Chat (F10)",
- "agentConfig": "Agent Config",
- "settings1": "Settings",
- "profileF12": "Profile (F12)",
- "reloadPage": "Reload Page",
- "selectTimezone": "SELECT TIMEZONE",
- "recordingSettings": "RECORDING SETTINGS",
- "configureDataCaptureOptions": "Configure data capture options",
- "autoRecord": "Auto Record",
- "dataTypes": "DATA TYPES",
- "sessionLabel": "SESSION LABEL",
- "tagsCommaseparated": "TAGS (comma-separated)",
- "recordingSettings1": "Recording Settings",
- "recordedContexts": "RECORDED CONTEXTS",
- "manageAllRecordedData": "Manage all recorded data contexts from tabs",
- "totalContexts": "TOTAL CONTEXTS:",
- "storageUsed": "STORAGE USED:",
- "allTabs": "ALL TABS",
- "allTypes1": "ALL TYPES",
- "loadingContexts": "Loading contexts...",
- "noRecordedContextsFound": "No recorded contexts found",
- "searchContexts": "Search contexts...",
- "preview": "Preview",
- "export1": "Export",
- "areYouSureYou4": "Are you sure you want to delete this recorded context?",
- "errorRenderingMarkdownContent": "Error rendering markdown content",
- "fincept": "Fincept",
- "help1": "Help",
- "contactUs3": "Contact Us",
- "termsOfService3": "Terms of Service",
- "trademarks2": "Trademarks",
- "privacyPolicy3": "Privacy Policy",
- "helpCenter": "Help Center",
- "startAChatSession": "Start a chat session to use contexts",
- "noContextsLinkedClick": "No contexts linked. Click \"ADD\" to include recorded data.",
- "addContextToChat": "ADD CONTEXT TO CHAT",
- "selectRecordedContextsTo": "Select recorded contexts to provide additional information to the AI",
- "noRecordedContextsAvailable": "No recorded contexts available. Start recording data from tabs.",
- "updateAvailable1": "Update Available",
- "aNewVersionOf1": "A new version of FinceptTerminal is available.",
- "currentVersion1": "Current Version:",
- "newVersion1": "New Version:",
- "releaseDate1": "Release Date:",
- "releaseNotes1": "Release Notes:",
- "downloadingUpdate": "Downloading update...",
- "updateReady1": "Update Ready!",
- "theApplicationWillRestart1": "The application will restart in a moment...",
- "later1": "Later",
- "installing": "Installing...",
- "checking": "Checking...",
- "checkForUpdates": "Check for Updates",
- "youAreRunningThe": "You are running the latest version!",
- "enterCommand": "Enter Command...",
- "finceptAiTerminal": "FINCEPT AI TERMINAL",
- "aiReady": "AI READY",
- "session": "SESSION:",
- "queries": "QUERIES:",
- "time1": "TIME:",
- "quickAccess": "QUICK ACCESS",
- "systemStatus": "SYSTEM STATUS",
- "api": "API:",
- "latency": "LATENCY:",
- "uptime": "UPTIME:",
- "processingQuery": "PROCESSING QUERY...",
- "poweredByFinceptAi": "POWERED BY FINCEPT AI ENGINE",
- "enterQuery": "ENTER QUERY...",
- "tryAsking": "TRY ASKING:",
- "totalValue3": "TOTAL VALUE",
- "noChartDataAvailable1": "No chart data available",
- "currentPlan": "Current Plan",
- "popular": "Popular",
- "bestValue": "Best Value",
- "credits": "Credits",
- "validity": "Validity",
- "allApiEndpoints": "All API endpoints",
- "realtimeDataAccess": "Real-time data access",
- "loadingPlans": "Loading Plans",
- "fetchingSubscriptionOptions": "Fetching subscription options...",
- "unableToLoadPlans": "Unable to Load Plans",
- "confirmPlanDowngrade": "Confirm Plan Downgrade",
- "youAreAboutTo": "You are about to downgrade from",
- "whatHappensWhenYou": "What happens when you downgrade:",
- "areYouSureYou5": "Are you sure you want to continue with the downgrade?",
- "confirmDowngrade": "Confirm Downgrade",
- "noSubscriptionPlansAvailable": "No subscription plans available at the moment.",
- "processing": "Processing...",
- "unableToLoadPlans1": "Unable to load plans after multiple attempts. Please try again later or continue with free plan.",
- "failedToLoadSubscription": "Failed to load subscription plans",
- "pleaseSelectAPlan": "Please select a plan",
- "authenticationRequiredPleaseLog": "Authentication required. Please log in again.",
- "anUnexpectedErrorOccurred": "An unexpected error occurred. Please try again.",
- "helpCenter1": "Help Center",
- "findAnswersToCommon": "Find answers to common questions and get support for your Fincept account.",
- "frequentlyAskedQuestions": "Frequently Asked Questions",
- "howDoIReset": "How do I reset my password?",
- "clickForgotPasswordOn": "Click \"Forgot Password\" on the login screen, enter your email, and follow the reset link we send you.",
- "whatIsGuestAccess": "What is Guest Access?",
- "guestAccessAllowsYou": "Guest Access allows you to explore Fincept with 50 API requests and 24-hour access without creating an account.",
- "howDoIContact": "How do I contact support?",
- "whatIsABunit": "What is a B-Unit?",
- "bunitIsOurBiometric": "B-Unit is our biometric authentication device that provides an additional layer of security for your terminal access.",
- "systemRequirements": "System Requirements",
- "finceptTerminalWorksOn": "Fincept Terminal works on modern web browsers. We recommend Chrome, Firefox, Safari, or Edge for the best experience.",
- "quickActions1": "Quick Actions",
- "createAccount": "Create Account",
- "getStartedWithFincept": "Get started with Fincept",
- "resetPassword": "Reset Password",
- "recoverYourAccount": "Recover your account",
- "contactInformation1": "Contact Information",
- "supportHoursMonfri9am6pm": "Support Hours: Mon-Fri 9AM-6PM EST",
- "backToLogin4": "Back to Login",
- "liveChat": "Live Chat",
- "openingLiveChat1": "Opening live chat...",
- "resetPassword1": "Reset Password",
- "enterYourEmailAddress": "Enter your email address and we'll send you a verification code to reset your password.",
- "emailAddress": "Email Address",
- "sending": "Sending...",
- "signIn": "Sign In",
- "checkYourEmail": "Check Your Email",
- "weveSentAVerification": "We've sent a verification code to",
- "iHaveTheCode": "I Have the Code",
- "useADifferentEmail": "Use a different email",
- "enterTheVerificationCode": "Enter the verification code and your new password.",
- "verificationCode": "Verification Code",
- "newPassword": "New Password",
- "confirmPassword": "Confirm Password",
- "resetting": "Resetting...",
- "passwordReset": "Password Reset",
- "yourPasswordHasBeen": "Your password has been successfully reset. You can now sign in with your new password.",
- "continueToLogin": "Continue to Login",
- "enterYourEmail": "Enter your email",
- "enterCodeFromEmail": "Enter code from email",
- "enterNewPassword": "Enter new password",
- "confirmNewPassword": "Confirm new password",
- "pleaseEnterYourEmail": "Please enter your email address",
- "anUnexpectedErrorOccurred1": "An unexpected error occurred. Please try again.",
- "pleaseEnterTheVerification": "Please enter the verification code",
- "pleaseEnterANew": "Please enter a new password",
- "passwordMustBeAt": "Password must be at least 8 characters long",
- "passwordsDoNotMatch": "Passwords do not match",
- "failedToResendCode": "Failed to resend code. Please try again."
- }
+ "settings": "Settings"
}
diff --git a/fincept-terminal-desktop/public/locales/en/dashboard.json b/fincept-terminal-desktop/public/locales/en/dashboard.json
index f049b27ce..57da79e07 100644
--- a/fincept-terminal-desktop/public/locales/en/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/en/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "CUSTOMIZABLE DASHBOARD",
- "live": "LIVE",
- "widgets": "WIDGETS"
- },
- "buttons": {
- "addWidget": "ADD WIDGET",
- "saveLayout": "SAVE LAYOUT",
- "reset": "RESET",
- "help": "HELP"
- },
"widgets": {
"loading": "Loading...",
- "error": "Error",
"globalIndices": "Global Indices - Top 12",
"forex": "Forex - Major Pairs",
"crypto": "CRYPTOCURRENCIES",
@@ -20,8 +8,6 @@
"news": "NEWS",
"forum": "FORUM",
"watchlist": "WATCHLIST",
- "maritimeIntelligence": "Maritime Intelligence",
- "unknown": "Unknown widget type",
"index": "INDEX",
"symbol": "SYMBOL",
"price": "PRICE",
@@ -36,110 +22,25 @@
"noWatchlistSelected": "No watchlist selected",
"noData": "No data available",
"noActiveMarkets": "No active markets found",
- "noAlertsConfigured": "No alerts configured",
- "alertsSetupHint": "Set up alerts in Monitoring tab",
- "noEventsScheduled": "No events scheduled",
"indicator": "INDICATOR",
"value": "VALUE",
"chg": "CHG",
- "time": "TIME",
- "event": "EVENT",
- "impact": "IMPACT",
- "impactHigh": "High",
- "impactMedium": "Medium",
- "impactLow": "Low",
"overallRisk": "OVERALL RISK",
- "active": "Active",
- "triggered": "Triggered",
"openEconomicsTab": "Open Economics Tab",
"openGeopoliticsTab": "Open Geopolitics Tab",
"openPolymarketTab": "Open Polymarket Tab",
- "viewFullCalendar": "View Full Calendar",
- "manageAlerts": "Manage Alerts",
"pair": "PAIR",
"rate": "RATE",
"commodity": "COMMODITY",
- "globe3D": "3D GLOBE",
- "vessels": "VESSELS",
- "routes": "ROUTES",
- "vol24h": "VOL 24H",
- "topTradeCorridors": "TOP TRADE CORRIDORS",
- "ships": "ships",
- "marketNews": "Market News",
- "secPressReleases": "SEC Press Releases",
- "cryptoNews": "Crypto News",
- "trendingForum": "Trending Forum",
- "techStocks": "Tech Stocks",
"noPortfolioFound": "No portfolio found",
"createPortfolioHint": "Create one in Portfolio tab",
"openPortfolioTab": "Open Portfolio Tab",
"action": "ACTION",
"markets": "MARKETS",
- "indexSP500": "S&P 500",
- "indexDowJones": "Dow Jones",
- "indexNasdaq": "NASDAQ",
- "indexRussell2000": "Russell 2000",
- "indexFTSE100": "FTSE 100",
- "indexDAX": "DAX",
- "indexCAC40": "CAC 40",
- "indexNikkei225": "Nikkei 225",
- "indexHangSeng": "Hang Seng",
- "indexShanghai": "Shanghai",
- "indexSensex": "Sensex",
- "indexNifty50": "Nifty 50",
- "forexEURUSD": "EUR/USD",
- "forexGBPUSD": "GBP/USD",
- "forexUSDJPY": "USD/JPY",
- "forexAUDUSD": "AUD/USD",
- "forexUSDCAD": "USD/CAD",
- "forexUSDCHF": "USD/CHF",
- "forexNZDUSD": "NZD/USD",
- "forexEURCHF": "EUR/CHF",
- "commodityGold": "Gold",
- "commoditySilver": "Silver",
- "commodityCrudeOil": "Crude Oil",
- "commodityNatGas": "Nat Gas",
- "commodityCopper": "Copper",
- "commodityCorn": "Corn",
- "commoditySoybeans": "Soybeans",
- "commodityWheat": "Wheat",
- "categoryAll": "ALL",
- "categoryMarket": "Market",
- "categoryCrypto": "Crypto",
- "categorySEC": "SEC",
"performanceTracker": "PERFORMANCE TRACKER",
"totalPnL": "TOTAL P&L",
- "winRate": "WIN RATE",
- "period": "PERIOD",
- "pnl": "P&L",
- "trades": "TRADES",
- "winPercent": "WIN%",
"viewDetailedAnalytics": "View Detailed Analytics"
},
- "tips": {
- "drag": "Drag widgets to rearrange",
- "resize": "Resize from bottom-right corner",
- "remove": "Remove widgets with X button",
- "responsive": "Responsive layout - uses full width"
- },
- "loading": {
- "title": "Initializing Dashboard",
- "description": "Setting up database cache for faster data loading...",
- "note": "This will only take a moment on first launch"
- },
- "empty": {
- "noWidgets": "No widgets on dashboard",
- "addFirst": "ADD YOUR FIRST WIDGET"
- },
- "status": {
- "version": "Fincept Customizable Dashboard v2.0.0 | Drag & drop workspace",
- "layout": "Layout",
- "custom": "Custom",
- "empty": "Empty",
- "active": "ACTIVE",
- "cache": "Cache: ENABLED",
- "label": "Status"
- },
"messages": {
"layoutSaved": "Dashboard layout saved!",
"resetConfirm": "Reset dashboard to default layout? This will remove all custom widgets."
diff --git a/fincept-terminal-desktop/public/locales/en/geopolitics.json b/fincept-terminal-desktop/public/locales/en/geopolitics.json
index 8330811d9..ac30e1c48 100644
--- a/fincept-terminal-desktop/public/locales/en/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/en/geopolitics.json
@@ -1,5 +1,4 @@
{
- "title": "GEOPOLITICS",
"header": {
"prefix": "GEO>",
"title": "GEOPOLITICAL CONFLICT MONITOR",
@@ -8,13 +7,11 @@
"status": {
"stale": "STALE",
"loading": "LOADING...",
- "complete": "Complete",
"error": "ERROR:"
},
"filters": {
"country": "Country...",
"cities": "Cities...",
- "citiesSelected": "{{count}} cities",
"category": "Category...",
"apply": "APPLY",
"clear": "CLEAR",
@@ -22,11 +19,7 @@
"selectedLabel": "Selected:"
},
"messages": {
- "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"
+ "retry": "RETRY"
},
"panel": {
"title": "INFO PANEL",
@@ -68,7 +61,6 @@
"engineValue": "DECK.GL v9.2",
"labelSource": "SOURCE",
"sourceValue": "NEWS-EVENTS API",
- "labelSelected": "SELECTED",
- "statusInfo": "REAL-TIME GLOBAL INTELLIGENCE | AUTO-REFRESH: 5MIN | {{time}}"
+ "labelSelected": "SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/en/markets.json b/fincept-terminal-desktop/public/locales/en/markets.json
index ca99ea184..46cfd9746 100644
--- a/fincept-terminal-desktop/public/locales/en/markets.json
+++ b/fincept-terminal-desktop/public/locales/en/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%CHG",
"high": "HIGH",
"low": "LOW",
- "loading": "Loading...",
"noData": "No data available",
"refresh": "REFRESH",
"auto": "AUTO",
"on": "ON",
- "off": "OFF",
- "lastUpdate": "LAST UPDATE",
- "updating": "UPDATING",
- "live": "LIVE"
+ "off": "OFF"
}
diff --git a/fincept-terminal-desktop/public/locales/en/news.json b/fincept-terminal-desktop/public/locales/en/news.json
index c24013c85..3010c0373 100644
--- a/fincept-terminal-desktop/public/locales/en/news.json
+++ b/fincept-terminal-desktop/public/locales/en/news.json
@@ -1,40 +1,15 @@
{
"title": "FINCEPT TERMINAL PROFESSIONAL NEWS",
"header": {
- "liveFeed": "LIVE FEED",
- "live": "LIVE",
- "refresh": "REFRESH",
- "updating": "UPDATING...",
- "alerts": "ALERTS",
- "sources": "SOURCES",
- "status": "STATUS",
- "demoMode": "DEMO MODE",
- "articles": "ARTICLES",
- "activeSources": "ACTIVE SOURCES"
- },
- "autoRefresh": {
- "title": "AUTO-REFRESH INTERVAL",
- "minute": "minute",
- "minutes": "minutes"
+ "refresh": "REFRESH"
},
"messages": {
- "loadingFeeds": "Loading news feeds...",
- "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",
- "secondary": "SECONDARY NEWS FEED",
- "additional": "ADDITIONAL HEADLINES"
- },
- "analytics": {
- "title": "REAL-TIME NEWS ANALYTICS"
- },
"rssSettings": {
"title": "RSS FEED SETTINGS",
"subtitle": "MANAGE YOUR NEWS SOURCES",
@@ -78,9 +53,7 @@
"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"
+ "testFailed": "Failed to test URL"
},
"confirmDelete": {
"title": "Delete this RSS feed?",
diff --git a/fincept-terminal-desktop/public/locales/en/portfolio.json b/fincept-terminal-desktop/public/locales/en/portfolio.json
index e96bc9b92..3980f7af2 100644
--- a/fincept-terminal-desktop/public/locales/en/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/en/portfolio.json
@@ -1,87 +1,4 @@
{
- "title": "FINCEPT PORTFOLIO MANAGER",
- "header": {
- "live": "LIVE",
- "updating": "UPDATING",
- "newPortfolio": "NEW PORTFOLIO",
- "refresh": "REFRESH",
- "exportCsv": "EXPORT CSV",
- "exportJson": "EXPORT JSON",
- "import": "IMPORT"
- },
- "import": {
- "title": "IMPORT PORTFOLIO",
- "dropOrClick": "Drop file here or click to browse",
- "supportedFormats": "Supports Fincept CSV and JSON exports",
- "fileDetected": "FILE DETECTED",
- "configure": "CONFIGURE IMPORT",
- "modeNew": "Create new portfolio",
- "modeNewDesc": "Import as a fresh portfolio",
- "modeMerge": "Merge into existing",
- "modeMergeDesc": "Add transactions to an existing portfolio",
- "portfolioName": "PORTFOLIO NAME",
- "targetPortfolio": "TARGET PORTFOLIO",
- "importButton": "IMPORT {{count}} TRANSACTIONS",
- "importing": "IMPORTING...",
- "complete": "IMPORT COMPLETE",
- "failed": "IMPORT FAILED",
- "transactionsReplayed": "transactions replayed",
- "errors": "ERRORS",
- "openPortfolio": "OPEN PORTFOLIO",
- "currencyWarning": "Currency mismatch: file is {{fileCurrency}}, target is {{targetCurrency}}. Prices will be imported as-is.",
- "cancel": "CANCEL",
- "close": "CLOSE"
- },
- "summary": {
- "totalValue": "TOTAL VALUE",
- "dayPnl": "DAY P&L",
- "totalPnl": "TOTAL P&L",
- "positions": "POSITIONS",
- "portfolioSummary": "PORTFOLIO SUMMARY",
- "unrealizedPnl": "UNREALIZED P&L",
- "costBasis": "COST BASIS",
- "dayChange": "DAY CHANGE",
- "topHoldings": "TOP HOLDINGS"
- },
- "views": {
- "positions": "POSITIONS",
- "addAsset": "ADD ASSET",
- "sellAsset": "SELL ASSET",
- "analytics": "ANALYTICS",
- "history": "HISTORY",
- "activeMgmt": "ACTIVE MGMT",
- "performance": "PERFORMANCE",
- "rebalance": "REBALANCE",
- "reports": "REPORTS",
- "alerts": "ALERTS",
- "sectors": "SECTORS",
- "help": "HELP",
- "indices": "INDICES",
- "risk": "RISK",
- "optimization": "OPTIMIZATION",
- "quantstats": "QUANTSTATS"
- },
- "sidebar": {
- "portfolios": "PORTFOLIOS",
- "loading": "Loading portfolios...",
- "noPortfolios": "No portfolios yet.",
- "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...",
- "selectPortfolio": "Select a portfolio"
- },
- "actions": {
- "buy": "BUY",
- "sell": "SELL",
- "new": "NEW",
- "refresh": "REFRESH",
- "export": "EXPORT"
- },
"modals": {
"createNew": "CREATE NEW PORTFOLIO",
"portfolioName": "PORTFOLIO NAME",
@@ -97,303 +14,7 @@
"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"
- },
- "commandBar": {
- "selectPortfolio": "SELECT PORTFOLIO",
- "searchPortfolios": "Search portfolios...",
- "newPortfolio": "NEW PORTFOLIO",
- "nav": "NAV",
- "pnl": "P&L",
- "day": "DAY",
- "pos": "POS",
- "wl": "W/L"
- },
- "ribbon": {
- "totalValue": "TOTAL VALUE",
- "unrealizedPnl": "UNREALIZED P&L",
- "dayChange": "DAY CHANGE",
- "costBasis": "COST BASIS",
- "positions": "POSITIONS",
- "concTop3": "CONC. TOP3",
- "sharpe": "SHARPE",
- "beta": "BETA",
- "volatility": "VOLATILITY",
- "maxDrawdown": "MAX DRAWDOWN",
- "riskScore": "RISK SCORE",
- "var95": "VAR (95%)",
- "annualized": "ANNUALIZED",
- "vsSpy": "VS SPY",
- "ann30d": "30D ANN.",
- "sinceIncep": "SINCE INCEP.",
- "composite": "COMPOSITE",
- "oneDay": "1-DAY",
- "fifo": "FIFO",
- "weight": "WEIGHT"
- },
- "heatmap": {
- "holdings": "HOLDINGS",
- "pnl": "PNL",
- "weight": "WEIGHT",
- "day": "DAY",
- "noHoldings": "No holdings yet. Click BUY to add positions.",
- "riskScore": "RISK SCORE",
- "low": "LOW",
- "high": "HIGH",
- "topMovers": "TOP MOVERS",
- "quickStats": "QUICK STATS",
- "concTop3": "CONC. TOP3",
- "volatility": "VOLATILITY",
- "newPortfolio": "NEW PORTFOLIO",
- "price": "PRICE",
- "chg": "CHG",
- "qty": "QTY",
- "cost": "COST",
- "mktVal": "MKT VAL",
- "pnlLabel": "P&L",
- "pnlPct": "P&L%",
- "dayChg": "DAY CHG",
- "costBasis": "COST BASIS"
- },
- "chart": {
- "performance": "PERFORMANCE",
- "awaitingSnapshots": "(awaiting snapshots)",
- "portfolio": "PORTFOLIO",
- "totalReturn": "TOTAL RETURN",
- "historyMessage": "Performance history builds over time as portfolio snapshots are recorded",
- "pts": "pts"
- },
- "allocation": {
- "sectorAllocation": "SECTOR ALLOCATION",
- "sectors": "sectors",
- "correlation": "CORRELATION",
- "dayChangeProxy": "(day change proxy)",
- "needTwoHoldings": "Need at least 2 holdings for correlation"
- },
- "blotter": {
- "positionsBlotter": "POSITIONS BLOTTER",
- "instruments": "instruments",
- "symbol": "SYMBOL",
- "qty": "QTY",
- "last": "LAST",
- "avgCost": "AVG COST",
- "mktVal": "MKT VAL",
- "costBasis": "COST BASIS",
- "pnl": "P&L",
- "pnlPct": "P&L%",
- "chgPct": "CHG%",
- "trend": "TREND",
- "wtPct": "WT%"
- },
- "tabs": {
- "quick": "QUICK",
- "analytics": "ANALYTICS",
- "transactions": "TRANSACTIONS",
- "attribution": "P&L ATTRIBUTION",
- "exposure": "EXPOSURE",
- "cashflows": "CASH FLOWS",
- "positions": "POSITIONS",
- "history": "HISTORY",
- "analyticsTab": "ANALYTICS",
- "sectors": "SECTORS",
- "performance": "PERFORMANCE",
- "risk": "RISK",
- "optimize": "OPTIMIZE",
- "activeMgmt": "ACTIVE MGMT",
- "quantstats": "QUANTSTATS",
- "pme": "PME",
- "skfolio": "SKFOLIO",
- "reports": "REPORTS",
- "indices": "INDICES",
- "noTransactions": "No transactions recorded",
- "totalInvested": "TOTAL INVESTED",
- "totalSold": "TOTAL SOLD",
- "netCashFlow": "NET CASH FLOW"
- },
- "order": {
- "orderEntry": "ORDER ENTRY",
- "buy": "BUY",
- "sell": "SELL",
- "price": "PRICE",
- "qtyHeld": "QTY HELD",
- "mktVal": "MKT VAL",
- "clickToBuyMore": "Click to buy more",
- "clickToSell": "Click to sell",
- "clickToBuy": "Click to buy an asset",
- "clickToSellAsset": "Click to sell an asset",
- "openBuyOrder": "OPEN BUY ORDER",
- "openSellOrder": "OPEN SELL ORDER",
- "ordersRecorded": "Orders are recorded in your portfolio"
- },
- "statusBar": {
- "fincept": "FINCEPT",
- "portfolioTerminal": "PORTFOLIO TERMINAL",
- "live": "LIVE",
- "pos": "POS",
- "ins": "INS",
- "nav": "NAV",
- "pnl": "P&L",
- "day": "DAY"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Real-time tracking with yfinance integration",
- "lastUpdated": "Last Updated",
- "connected": "CONNECTED"
- },
"extracted": {
- "noPortfolioSelected": "NO PORTFOLIO SELECTED",
- "loadingPortfolioData": "LOADING PORTFOLIO DATA...",
- "failedToDeletePortfolio": "Failed to delete portfolio",
"areYouSureYou": "Are you sure you want to delete this portfolio? This action cannot be undone."
}
}
diff --git a/fincept-terminal-desktop/public/locales/en/reportBuilder.json b/fincept-terminal-desktop/public/locales/en/reportBuilder.json
index 683253792..e78ef7de6 100644
--- a/fincept-terminal-desktop/public/locales/en/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/en/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "Load",
"save": "Save",
- "saving": "Saving...",
- "exportPdf": "Export PDF",
- "generating": "Generating..."
+ "saving": "Saving..."
},
"components": {
"title": "ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/en/settings.json b/fincept-terminal-desktop/public/locales/en/settings.json
index a57bb48ae..89f020c9c 100644
--- a/fincept-terminal-desktop/public/locales/en/settings.json
+++ b/fincept-terminal-desktop/public/locales/en/settings.json
@@ -49,15 +49,8 @@
"colorPanel": "Panel",
"layoutSpacing": "LAYOUT & SPACING",
"contentDensity": "CONTENT DENSITY",
- "densityCompact": "Compact",
- "densityDefault": "Default",
- "densityComfortable": "Comfortable",
"borderRadius": "BORDER RADIUS",
"borderStyle": "BORDER STYLE",
- "borderNone": "None",
- "borderSubtle": "Subtle",
- "borderNormal": "Normal",
- "borderProminent": "Prominent",
"lineHeight": "LINE HEIGHT",
"letterSpacing": "LETTER SPACING",
"effects": "EFFECTS",
@@ -97,17 +90,8 @@
"tip": "TIP: Drag tabs to reorder them. Use arrow buttons to move tabs between header and menu sections. Changes are saved automatically."
},
"llm": {
- "title": "LLM CONFIGURATION",
- "description": "Configure AI models and providers",
"connected": "CONNECTED",
- "disconnected": "DISCONNECTED",
- "provider": "AI PROVIDER",
- "globalSettings": "GLOBAL AI SETTINGS",
- "temperature": "TEMPERATURE",
- "maxTokens": "MAX TOKENS",
- "systemPrompt": "SYSTEM PROMPT",
- "modelLibrary": "MODEL LIBRARY",
- "multiModelConfigs": "Multi-model configs"
+ "disconnected": "DISCONNECTED"
},
"buttons": {
"save": "SAVE",
diff --git a/fincept-terminal-desktop/public/locales/en/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/en/surfaceAnalytics.json
index 85a572a64..ca4859548 100644
--- a/fincept-terminal-desktop/public/locales/en/surfaceAnalytics.json
+++ b/fincept-terminal-desktop/public/locales/en/surfaceAnalytics.json
@@ -1,24 +1,7 @@
{
"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",
@@ -166,129 +149,27 @@
"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"
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[EN] surfaceAnalytics.paidServiceNotice"
},
- "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"
+ "common": {
+ "or": "[EN] common.or",
+ "note": "[EN] common.note"
}
}
diff --git a/fincept-terminal-desktop/public/locales/en/tabs.json b/fincept-terminal-desktop/public/locales/en/tabs.json
index fbd6c59c7..d3cfd1ceb 100644
--- a/fincept-terminal-desktop/public/locales/en/tabs.json
+++ b/fincept-terminal-desktop/public/locales/en/tabs.json
@@ -5,29 +5,7 @@
"news": "News",
"portfolio": "Portfolio",
"backtesting": "Backtesting",
- "watchlist": "Watchlist",
- "research": "Research",
- "screener": "Screener",
"chat": "AI Chat",
- "agents": "Agents",
- "settings": "Settings",
"profile": "Profile"
- },
- "functionKeys": {
- "f1": "DASH",
- "f2": "MKTS",
- "f3": "NEWS",
- "f4": "PORT",
- "f5": "BKTEST",
- "f6": "WATCH",
- "f7": "RSRCH",
- "f8": "SCRN",
- "f9": "TRADE",
- "f10": "AI",
- "f11": "FULL",
- "f12": "PROF"
- },
- "labels": {
- "moreTabs": "More tabs in toolbar menus"
}
}
diff --git a/fincept-terminal-desktop/public/locales/en/watchlist.json b/fincept-terminal-desktop/public/locales/en/watchlist.json
index 6af253392..0704ea86a 100644
--- a/fincept-terminal-desktop/public/locales/en/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/en/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "WATCHLIST",
- "header": {
- "export": "EXPORT",
- "updating": "UPDATING",
- "live": "LIVE"
- },
"sidebar": {
- "groups": "WATCHLIST GROUPS",
- "new": "NEW",
"noWatchlists": "No watchlists yet.",
"clickNew": "Click NEW to create one.",
- "stocks": "stocks",
- "marketMovers": "MARKET MOVERS",
- "gainer": "GAINER",
- "loser": "LOSER",
- "volumeLeaders": "VOLUME LEADERS"
- },
- "emptyState": {
- "selectWatchlist": "Select a watchlist or create a new one to get started"
- },
- "list": {
- "symbols": "Symbols"
+ "stocks": "stocks"
}
}
diff --git a/fincept-terminal-desktop/public/locales/es/codeEditor.json b/fincept-terminal-desktop/public/locales/es/codeEditor.json
index 0b0ec45e4..25ab64be5 100644
--- a/fincept-terminal-desktop/public/locales/es/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/es/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "EDITOR DE CÓDIGO",
"header": {
- "packages": "PAQUETES"
+ "finscriptIde": "[ES] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "NUEVO ARCHIVO",
- "new": "NUEVO",
- "open": "ABRIR",
- "save": "GUARDAR",
"run": "EJECUTAR",
"running": "EJECUTANDO...",
- "runAll": "EJECUTAR TODO",
- "history": "HISTORIAL"
+ "toggleExplorer": "[ES] Toggle Explorer (Ctrl+B)",
+ "openFile": "[ES] Open File",
+ "saveShortcut": "[ES] Save (Ctrl+S)",
+ "findShortcut": "[ES] Find (Ctrl+F)",
+ "runShortcut": "[ES] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "EDITOR FINSCRIPT"
},
- "packages": {
- "clickToLoad": "Clic para cargar paquetes...",
- "load": "CARGAR PAQUETES"
+ "explorer": {
+ "title": "[ES] EXPLORER",
+ "openFiles": "[ES] OPEN FILES",
+ "examples": "[ES] EXAMPLES",
+ "runHistory": "[ES] RUN HISTORY",
+ "finscriptEngine": "[ES] FinScript Engine"
},
- "history": {
- "title": "HISTORIAL DE NOTEBOOKS",
- "loading": "Cargando historial...",
- "empty": "Sin historial de notebooks"
+ "output": {
+ "title": "[ES] OUTPUT",
+ "success": "[ES] SUCCESS",
+ "error": "[ES] ERROR",
+ "executing": "[ES] EXECUTING FINSCRIPT...",
+ "noOutput": "[ES] No output yet",
+ "pressToRun": "[ES] Press Ctrl+Enter to run",
+ "completed": "[ES] COMPLETED",
+ "failed": "[ES] FAILED",
+ "signals": "[ES] signals",
+ "clear": "[ES] CLEAR",
+ "errors": "[ES] ERRORS",
+ "signalsSection": "[ES] SIGNALS",
+ "outputSection": "[ES] OUTPUT",
+ "charts": "[ES] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[ES] OHLC",
+ "histogram": "[ES] Histogram",
+ "line": "[ES] Line",
+ "points": "[ES] points"
+ },
+ "statusBar": {
+ "modified": "[ES] MODIFIED",
+ "showOutput": "[ES] SHOW OUTPUT",
+ "encoding": "[ES] UTF-8",
+ "spaces": "[ES] 4 Spaces",
+ "runShortcut": "[ES] Ctrl+Enter: Run",
+ "lines": "[ES] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[ES] Close file without saving?",
+ "unsavedChanges": "[ES] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/es/common.json b/fincept-terminal-desktop/public/locales/es/common.json
index ce16351d4..d634c232e 100644
--- a/fincept-terminal-desktop/public/locales/es/common.json
+++ b/fincept-terminal-desktop/public/locales/es/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Cargando...",
- "error": "Error",
- "success": "Éxito",
- "save": "Guardar",
- "cancel": "Cancelar",
- "delete": "Eliminar",
- "edit": "Editar",
- "add": "Agregar",
- "search": "Buscar",
- "filter": "Filtrar",
- "back": "Atrás",
- "next": "Siguiente",
- "previous": "Anterior",
- "submit": "Enviar",
- "close": "Cerrar",
- "open": "Abrir",
- "yes": "Sí",
- "no": "No",
- "ok": "OK",
- "confirm": "Confirmar",
- "language": "Idioma",
- "selectLanguage": "Seleccionar idioma"
+ "settings": "[ES] Settings"
}
diff --git a/fincept-terminal-desktop/public/locales/es/dashboard.json b/fincept-terminal-desktop/public/locales/es/dashboard.json
index 590fa1d77..0a932c555 100644
--- a/fincept-terminal-desktop/public/locales/es/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/es/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "TABLERO PERSONALIZABLE",
- "live": "VIVIR",
- "widgets": "APARATOS"
- },
- "buttons": {
- "addWidget": "AÑADIR WIDGET",
- "saveLayout": "GUARDAR DISEÑO",
- "reset": "REINICIAR",
- "help": "AYUDA"
- },
"widgets": {
"loading": "Cargando...",
- "error": "Error",
"globalIndices": "Índices globales - Top 12",
"forex": "Forex - Pares principales",
"crypto": "CRIPTOMONEDAS",
@@ -20,8 +8,6 @@
"news": "NOTICIAS",
"forum": "FORO",
"watchlist": "LISTA DE SEGURIDAD",
- "maritimeIntelligence": "Inteligencia Marítima",
- "unknown": "Tipo de widget desconocido",
"index": "ÍNDICE",
"symbol": "SÍMBOLO",
"price": "PRECIO",
@@ -38,41 +24,22 @@
"pair": "PAR",
"rate": "TASA",
"commodity": "PRODUCTO",
- "globe3D": "GLOBO 3D",
- "vessels": "BUQUES",
- "routes": "RUTAS",
- "vol24h": "VOL 24H",
- "topTradeCorridors": "PRINCIPALES CORREDORES COMERCIALES",
- "ships": "barcos",
- "marketNews": "Noticias del mercado",
- "secPressReleases": "Comunicados de prensa de la SEC",
- "cryptoNews": "Noticias criptográficas",
- "trendingForum": "Foro de tendencias",
- "techStocks": "Acciones tecnológicas"
- },
- "tips": {
- "drag": "Arrastre los widgets para reorganizarlos",
- "resize": "Cambiar tamaño desde la esquina inferior derecha",
- "remove": "Eliminar widgets con el botón X",
- "responsive": "Diseño responsivo: utiliza el ancho completo"
- },
- "loading": {
- "title": "Inicializando el panel",
- "description": "Configurando el caché de la base de datos para una carga de datos más rápida...",
- "note": "Esto sólo tomará un momento en el primer lanzamiento."
- },
- "empty": {
- "noWidgets": "No hay widgets en el tablero",
- "addFirst": "AÑADE TU PRIMER WIDGET"
- },
- "status": {
- "version": "Panel personalizable de Fincept v2.0.0 | Espacio de trabajo de arrastrar y soltar",
- "layout": "Disposición",
- "custom": "Costumbre",
- "empty": "Vacío",
- "active": "ACTIVO",
- "cache": "Caché: HABILITADO",
- "label": "Estado"
+ "noActiveMarkets": "[ES] No active markets found",
+ "indicator": "[ES] INDICATOR",
+ "value": "[ES] VALUE",
+ "chg": "[ES] CHG",
+ "overallRisk": "[ES] OVERALL RISK",
+ "openEconomicsTab": "[ES] Open Economics Tab",
+ "openGeopoliticsTab": "[ES] Open Geopolitics Tab",
+ "openPolymarketTab": "[ES] Open Polymarket Tab",
+ "noPortfolioFound": "[ES] No portfolio found",
+ "createPortfolioHint": "[ES] Create one in Portfolio tab",
+ "openPortfolioTab": "[ES] Open Portfolio Tab",
+ "action": "[ES] ACTION",
+ "markets": "[ES] MARKETS",
+ "performanceTracker": "[ES] PERFORMANCE TRACKER",
+ "totalPnL": "[ES] TOTAL P&L",
+ "viewDetailedAnalytics": "[ES] View Detailed Analytics"
},
"messages": {
"layoutSaved": "¡Diseño del panel guardado!",
diff --git a/fincept-terminal-desktop/public/locales/es/geopolitics.json b/fincept-terminal-desktop/public/locales/es/geopolitics.json
index 185e98492..58186a70d 100644
--- a/fincept-terminal-desktop/public/locales/es/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/es/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "GEOPOLÍTICA",
"messages": {
- "loading": "Cargando datos..."
+ "retry": "[ES] RETRY"
+ },
+ "header": {
+ "prefix": "[ES] GEO>",
+ "title": "[ES] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[ES] EVENTS"
+ },
+ "status": {
+ "stale": "[ES] STALE",
+ "loading": "[ES] LOADING...",
+ "error": "[ES] ERROR:"
+ },
+ "filters": {
+ "country": "[ES] Country...",
+ "cities": "[ES] Cities...",
+ "category": "[ES] Category...",
+ "apply": "[ES] APPLY",
+ "clear": "[ES] CLEAR",
+ "clearAllCities": "[ES] Clear all cities",
+ "selectedLabel": "[ES] Selected:"
+ },
+ "panel": {
+ "title": "[ES] INFO PANEL",
+ "expand": "[ES] Expand panel",
+ "collapse": "[ES] Collapse panel",
+ "eventsLoaded": "[ES] EVENTS LOADED",
+ "onMapVisualization": "[ES] on map visualization",
+ "topCategories": "[ES] TOP CATEGORIES",
+ "topCountries": "[ES] TOP COUNTRIES",
+ "eventDetails": "[ES] EVENT DETAILS",
+ "close": "[ES] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[ES] Country:",
+ "city": "[ES] City:",
+ "keywords": "[ES] Keywords:",
+ "coords": "[ES] Coords:",
+ "date": "[ES] Date:",
+ "source": "[ES] Source:",
+ "viewArticle": "[ES] View Article"
+ },
+ "legend": {
+ "title": "[ES] EVENT CATEGORIES",
+ "armedConflict": "[ES] Armed Conflict",
+ "terrorism": "[ES] Terrorism",
+ "protests": "[ES] Protests",
+ "civilianViolence": "[ES] Civilian Violence",
+ "riots": "[ES] Riots",
+ "politicalViolence": "[ES] Political Violence",
+ "crisis": "[ES] Crisis",
+ "explosions": "[ES] Explosions",
+ "strategic": "[ES] Strategic",
+ "unclassified": "[ES] Unclassified"
+ },
+ "footer": {
+ "tabName": "[ES] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[ES] EVENTS",
+ "labelEngine": "[ES] ENGINE",
+ "engineValue": "[ES] DECK.GL v9.2",
+ "labelSource": "[ES] SOURCE",
+ "sourceValue": "[ES] NEWS-EVENTS API",
+ "labelSelected": "[ES] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/es/markets.json b/fincept-terminal-desktop/public/locales/es/markets.json
index 9105f2843..df7ecf1a4 100644
--- a/fincept-terminal-desktop/public/locales/es/markets.json
+++ b/fincept-terminal-desktop/public/locales/es/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%CAM",
"high": "ALTO",
"low": "BAJO",
- "loading": "Cargando...",
"noData": "Sin datos disponibles",
"refresh": "ACTUALIZAR",
"auto": "AUTO",
"on": "ON",
- "off": "OFF",
- "lastUpdate": "ÚLTIMA ACTUALIZACIÓN",
- "updating": "ACTUALIZANDO",
- "live": "EN VIVO"
+ "off": "OFF"
}
diff --git a/fincept-terminal-desktop/public/locales/es/news.json b/fincept-terminal-desktop/public/locales/es/news.json
index 8510ec8fa..7314b5bb6 100644
--- a/fincept-terminal-desktop/public/locales/es/news.json
+++ b/fincept-terminal-desktop/public/locales/es/news.json
@@ -1,32 +1,63 @@
{
"title": "NOTICIAS PROFESIONALES DE TERMINAL FINCEPT",
"header": {
- "liveFeed": "FEED EN VIVO",
- "live": "EN VIVO",
- "refresh": "ACTUALIZAR",
- "updating": "ACTUALIZANDO...",
- "alerts": "ALERTAS",
- "sources": "FUENTES",
- "status": "ESTADO",
- "demoMode": "MODO DEMO",
- "articles": "ARTÍCULOS",
- "activeSources": "FUENTES ACTIVAS"
- },
- "autoRefresh": {
- "title": "INTERVALO DE ACTUALIZACIÓN AUTOMÁTICA",
- "minute": "minuto",
- "minutes": "minutos"
+ "refresh": "ACTUALIZAR"
},
"messages": {
- "loadingFeeds": "Cargando feeds...",
- "breaking": "ÚLTIMA HORA"
- },
- "feeds": {
- "primary": "[ES] PRIMARY NEWS FEED",
- "secondary": "[ES] SECONDARY NEWS FEED",
- "additional": "[ES] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[ES] Loading feeds...",
+ "failedToLoad": "[ES] Failed to load RSS feeds",
+ "noCustomFeeds": "[ES] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[ES] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[ES] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[ES] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[ES] RSS FEED SETTINGS",
+ "subtitle": "[ES] MANAGE YOUR NEWS SOURCES",
+ "close": "[ES] CLOSE",
+ "myFeeds": "[ES] MY FEEDS",
+ "defaultFeeds": "[ES] DEFAULT FEEDS",
+ "noFeedsAvailable": "[ES] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[ES] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[ES] ADD NEW FEED",
+ "addNewRssFeed": "[ES] ADD NEW RSS FEED",
+ "editRssFeed": "[ES] EDIT RSS FEED",
+ "restoreDefaults": "[ES] RESTORE DEFAULTS",
+ "restoreAll": "[ES] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[ES] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[ES] DISPLAY NAME",
+ "sourceName": "[ES] SOURCE NAME (SHORT)",
+ "feedUrl": "[ES] RSS FEED URL",
+ "category": "[ES] CATEGORY",
+ "region": "[ES] REGION",
+ "required": "[ES] *",
+ "testUrl": "[ES] TEST URL",
+ "testing": "[ES] TESTING...",
+ "valid": "[ES] VALID",
+ "cancel": "[ES] CANCEL",
+ "saving": "[ES] SAVING...",
+ "addFeed": "[ES] ADD FEED",
+ "updateFeed": "[ES] UPDATE FEED",
+ "on": "[ES] ON",
+ "off": "[ES] OFF",
+ "default": "[ES] DEFAULT",
+ "total": "[ES] TOTAL",
+ "active": "[ES] ACTIVE",
+ "custom": "[ES] CUSTOM",
+ "placeholders": {
+ "displayName": "[ES] e.g., Bloomberg Markets",
+ "sourceName": "[ES] e.g., BLOOMBERG",
+ "feedUrl": "[ES] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[ES] Name is required",
+ "sourceRequired": "[ES] Source name is required",
+ "invalidUrl": "[ES] Please enter a valid URL",
+ "invalidRss": "[ES] URL does not appear to be a valid RSS feed",
+ "testFailed": "[ES] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[ES] Delete this RSS feed?",
+ "message": "[ES] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/es/portfolio.json b/fincept-terminal-desktop/public/locales/es/portfolio.json
index d50a0e2d0..b988eee55 100644
--- a/fincept-terminal-desktop/public/locales/es/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/es/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "GESTOR DE CARTERA FINCEPT",
- "header": {
- "live": "EN VIVO",
- "updating": "ACTUALIZANDO",
- "newPortfolio": "NUEVA CARTERA",
- "refresh": "ACTUALIZAR",
- "exportCsv": "EXPORTAR CSV"
- },
- "summary": {
- "totalValue": "VALOR TOTAL",
- "dayPnl": "G/P DÍA",
- "totalPnl": "G/P TOTAL",
- "positions": "POSICIONES"
- },
- "views": {
- "positions": "POSICIONES",
- "addAsset": "AÑADIR ACTIVO",
- "sellAsset": "VENDER ACTIVO",
- "analytics": "ANALÍTICA",
- "history": "HISTORIAL",
- "activeMgmt": "GESTIÓN ACTIVA",
- "performance": "RENDIMIENTO",
- "rebalance": "REBALANCEO",
- "reports": "INFORMES",
- "alerts": "ALERTAS",
- "sectors": "SECTORES",
- "help": "AYUDA"
- },
- "sidebar": {
- "portfolios": "CARTERAS",
- "loading": "Cargando carteras...",
- "noPortfolios": "Aún no hay carteras.",
- "clickCreate": "Haz clic en NUEVA CARTERA para crear una.",
- "owner": "Propietario",
- "currency": "Moneda"
- },
- "content": {
- "selectOrCreate": "Selecciona una cartera o crea una nueva para comenzar",
- "loadingData": "Cargando datos de cartera...",
- "comingSoon": "vista próximamente..."
- },
- "modals": {
- "createNew": "CREAR NUEVA CARTERA",
- "portfolioName": "NOMBRE DE CARTERA",
- "owner": "PROPIETARIO",
- "currency": "MONEDA",
- "cancel": "CANCELAR",
- "create": "CREAR",
- "addAssetTitle": "AÑADIR ACTIVO A CARTERA",
- "sellAssetTitle": "VENDER ACTIVO",
- "symbol": "SÍMBOLO",
- "quantity": "CANTIDAD",
- "price": "PRECIO",
- "add": "AÑADIR",
- "sell": "VENDER"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Seguimiento en tiempo real con integración yfinance",
- "lastUpdated": "Última Actualización",
- "connected": "CONECTADO"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "CREAR NUEVA CARTERA",
+ "portfolioName": "NOMBRE DE CARTERA",
+ "owner": "PROPIETARIO",
+ "currency": "MONEDA",
+ "cancel": "CANCELAR",
+ "create": "CREAR",
+ "addAssetTitle": "AÑADIR ACTIVO A CARTERA",
+ "sellAssetTitle": "VENDER ACTIVO",
+ "symbol": "SÍMBOLO",
+ "quantity": "CANTIDAD",
+ "price": "PRECIO",
+ "add": "AÑADIR",
+ "sell": "VENDER"
+ },
+ "extracted": {
+ "areYouSureYou": "[ES] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/es/reportBuilder.json b/fincept-terminal-desktop/public/locales/es/reportBuilder.json
index 44f995abd..efa16594c 100644
--- a/fincept-terminal-desktop/public/locales/es/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/es/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[ES] Load",
"save": "[ES] Save",
- "saving": "[ES] Saving...",
- "exportPdf": "[ES] Export PDF",
- "generating": "[ES] Generating..."
+ "saving": "[ES] Saving..."
},
"components": {
"title": "[ES] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/es/settings.json b/fincept-terminal-desktop/public/locales/es/settings.json
index 10a0d9116..a9017207b 100644
--- a/fincept-terminal-desktop/public/locales/es/settings.json
+++ b/fincept-terminal-desktop/public/locales/es/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Diseño de pestañas",
"appearance": "Apariencia",
"language": "Idioma",
- "storage": "Almacenamiento y caché"
+ "storage": "Almacenamiento y caché",
+ "notifications": "[ES] Notifications"
},
"credentials": {
"title": "GESTIÓN DE CREDENCIALES API",
@@ -46,7 +47,31 @@
"saveConfig": "GUARDAR CONFIGURACIÓN",
"reset": "REINICIAR",
"saveSuccess": "La apariencia del terminal y las asignaciones de teclas se guardaron correctamente",
- "resetSuccess": "Restablecer la apariencia predeterminada y las asignaciones de teclas"
+ "resetSuccess": "Restablecer la apariencia predeterminada y las asignaciones de teclas",
+ "customColors": "[ES] Custom Colors",
+ "customColorsTitle": "[ES] CUSTOM COLORS",
+ "colorPrimary": "[ES] Primary",
+ "colorSecondary": "[ES] Secondary",
+ "colorSuccess": "[ES] Success",
+ "colorAlert": "[ES] Alert",
+ "colorWarning": "[ES] Warning",
+ "colorInfo": "[ES] Info",
+ "colorAccent": "[ES] Accent",
+ "colorPurple": "[ES] Purple",
+ "colorText": "[ES] Text",
+ "colorTextMuted": "[ES] Text Muted",
+ "colorBackground": "[ES] Background",
+ "colorPanel": "[ES] Panel",
+ "layoutSpacing": "[ES] LAYOUT & SPACING",
+ "contentDensity": "[ES] CONTENT DENSITY",
+ "borderRadius": "[ES] BORDER RADIUS",
+ "borderStyle": "[ES] BORDER STYLE",
+ "lineHeight": "[ES] LINE HEIGHT",
+ "letterSpacing": "[ES] LETTER SPACING",
+ "effects": "[ES] EFFECTS",
+ "widgetOpacity": "[ES] WIDGET OPACITY",
+ "enableGlow": "[ES] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[ES] GLOW INTENSITY"
},
"stockSymbols": {
"title": "Base de datos de símbolos bursátiles",
@@ -65,17 +90,8 @@
"tip": "SUGERENCIA: arrastre las pestañas para reordenarlas. Utilice los botones de flecha para mover pestañas entre las secciones del encabezado y del menú. Los cambios se guardan automáticamente."
},
"llm": {
- "title": "CONFIGURACIÓN DEL LLM",
- "description": "Configurar modelos y proveedores de IA",
"connected": "CONECTADO",
- "disconnected": "DESCONECTADO",
- "provider": "PROVEEDOR DE IA",
- "globalSettings": "AJUSTES GLOBALES DE IA",
- "temperature": "TEMPERATURA",
- "maxTokens": "FICHAS MÁXIMAS",
- "systemPrompt": "AVISO DEL SISTEMA",
- "modelLibrary": "BIBLIOTECA DE MODELOS",
- "multiModelConfigs": "Configuraciones multimodelo"
+ "disconnected": "DESCONECTADO"
},
"buttons": {
"save": "AHORRAR",
@@ -86,5 +102,18 @@
"database": "Base de datos: SQLite",
"storage": "Almacenamiento: basado en archivos",
"secureStorage": "Todos los datos almacenados de forma segura en fincept_terminal.db"
+ },
+ "notifications": {
+ "title": "[ES] NOTIFICATION PROVIDERS",
+ "description": "[ES] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[ES] Event Filters",
+ "eventFilterDescription": "[ES] Choose which notification types to forward to external providers.",
+ "providers": "[ES] Providers",
+ "enabled": "[ES] Enabled",
+ "disabled": "[ES] Disabled",
+ "testButton": "[ES] TEST",
+ "testSuccess": "[ES] Test notification sent successfully!",
+ "testFailed": "[ES] Failed to send test notification. Check your configuration.",
+ "saved": "[ES] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/es/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/es/surfaceAnalytics.json
new file mode 100644
index 000000000..2b832858e
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/es/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[ES] SURFACE ANALYTICS",
+ "initializing": "[ES] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[ES] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[ES] VOL SURFACE",
+ "correlation": "[ES] CORRELATION",
+ "yieldCurve": "[ES] YIELD CURVE",
+ "pca": "[ES] PCA FACTORS"
+ },
+ "demoData": "[ES] DEMO DATA",
+ "demoDataSynthetic": "[ES] DEMO DATA (synthetic)",
+ "synthetic": "[ES] SYNTHETIC",
+ "manual": "[ES] MANUAL",
+ "error": "[ES] ERROR",
+ "ready": "[ES] READY",
+ "metrics": "[ES] Metrics",
+ "updated": "[ES] Updated",
+ "clickRefresh": "[ES] Click REFRESH to load data",
+ "refresh": "[ES] REFRESH",
+ "noApiKey": "[ES] NO API KEY",
+ "lastUpdate": "[ES] LAST UPDATE",
+ "loadingData": "[ES] LOADING DATA...",
+ "noDataLoaded": "[ES] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[ES] IV SURFACE METRICS",
+ "correlationMetrics": "[ES] CORRELATION METRICS",
+ "yieldCurveMetrics": "[ES] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[ES] PCA FACTOR METRICS",
+ "dataInfo": "[ES] DATA INFO",
+ "source": "[ES] SOURCE",
+ "frequency": "[ES] FREQUENCY",
+ "quality": "[ES] QUALITY",
+ "correlationScale": "[ES] CORRELATION SCALE",
+ "strongPositive": "[ES] Strong Positive (0.7-1.0)",
+ "neutral": "[ES] Neutral (0.3-0.7)",
+ "strongNegative": "[ES] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[ES] IV INTERPRETATION",
+ "highIv": "[ES] High IV = Expensive Options",
+ "lowIv": "[ES] Low IV = Cheap Options",
+ "skew": "[ES] Skew = Put/Call IV Diff",
+ "termStructure": "[ES] Term Structure = Time Effect",
+ "pcaInterpretation": "[ES] PCA INTERPRETATION",
+ "pc1": "[ES] PC1 = Market Factor",
+ "pc2": "[ES] PC2 = Size/Value Factor",
+ "pc3": "[ES] PC3 = Sector Rotation",
+ "higherVar": "[ES] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[ES] STRIKE",
+ "dte": "[ES] DTE",
+ "iv": "[ES] IV",
+ "correlation": "[ES] CORRELATION",
+ "maturity": "[ES] MATURITY",
+ "yield": "[ES] YIELD",
+ "loading": "[ES] LOADING",
+ "strikePrice": "[ES] STRIKE PRICE",
+ "daysToExpiry": "[ES] DAYS TO EXPIRY",
+ "impliedVol": "[ES] IMPLIED VOL (%)",
+ "assetPairIndex": "[ES] ASSET PAIR INDEX",
+ "timeDays": "[ES] TIME (DAYS)",
+ "correlationCoeff": "[ES] CORRELATION COEFF",
+ "maturityMonths": "[ES] MATURITY (MONTHS)",
+ "historicalDays": "[ES] HISTORICAL DAYS",
+ "yieldPercent": "[ES] YIELD (%)",
+ "principalComponent": "[ES] PRINCIPAL COMPONENT",
+ "assetIndex": "[ES] ASSET INDEX",
+ "factorLoading": "[ES] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[ES] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[ES] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[ES] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[ES] DAY ROLLING",
+ "yieldCurve": "[ES] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[ES] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[ES] FAILED TO LOAD DATA",
+ "authFailed": "[ES] AUTHENTICATION FAILED",
+ "authFailedHelp": "[ES] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[ES] ACCESS DENIED",
+ "accessDeniedHelp": "[ES] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[ES] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[ES] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[ES] DATA TIMEFRAME",
+ "schema": "[ES] Schema",
+ "description": "[ES] Description",
+ "recordsPerDay": "[ES] Records/Day",
+ "highFrequencyWarning": "[ES] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[ES] Data Volume"
+ },
+ "settings": {
+ "title": "[ES] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[ES] DATABENTO API KEY",
+ "configured": "[ES] CONFIGURED",
+ "invalidFormat": "[ES] INVALID FORMAT",
+ "apiKeyConfigured": "[ES] API key is configured (db-*****)",
+ "remove": "[ES] REMOVE",
+ "enterApiKey": "[ES] Enter your Databento API key (db-*****)",
+ "save": "[ES] SAVE",
+ "saving": "[ES] SAVING...",
+ "getApiKeyFrom": "[ES] Get your API key from",
+ "dashboardApiKeys": "[ES] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[ES] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[ES] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[ES] CORRELATION ASSETS",
+ "addSymbol": "[ES] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[ES] Reset to defaults",
+ "historicalDateRange": "[ES] HISTORICAL DATE RANGE",
+ "start": "[ES] Start",
+ "end": "[ES] End",
+ "autoRefreshInterval": "[ES] AUTO REFRESH INTERVAL",
+ "manualOnly": "[ES] Manual Only",
+ "every1min": "[ES] Every 1 minute",
+ "every5min": "[ES] Every 5 minutes",
+ "every15min": "[ES] Every 15 minutes",
+ "every1hour": "[ES] Every 1 hour",
+ "browseDatasets": "[ES] BROWSE DATASETS",
+ "costEstimator": "[ES] COST ESTIMATOR",
+ "referenceData": "[ES] REFERENCE DATA",
+ "orderBook": "[ES] ORDER BOOK",
+ "liveStreaming": "[ES] LIVE STREAMING",
+ "active": "[ES] ACTIVE",
+ "futuresCme": "[ES] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[ES] BATCH DOWNLOADS",
+ "additionalSchemas": "[ES] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[ES] TRADES, IMBALANCE, STATUS",
+ "cancel": "[ES] CANCEL",
+ "saveChanges": "[ES] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[ES] BATCH DOWNLOADS",
+ "newBatchJob": "[ES] NEW BATCH JOB",
+ "dataset": "[ES] Dataset",
+ "schema": "[ES] Schema",
+ "symbolsCommaSeparated": "[ES] Symbols (comma-separated)",
+ "startDate": "[ES] Start Date",
+ "endDate": "[ES] End Date",
+ "encoding": "[ES] Encoding",
+ "compression": "[ES] Compression",
+ "submitJob": "[ES] SUBMIT JOB",
+ "noBatchJobs": "[ES] No batch jobs found. Click + to create one.",
+ "records": "[ES] records",
+ "download": "[ES] Download",
+ "files": "[ES] FILES",
+ "jobsExpireNotice": "[ES] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[ES] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[ES] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[ES] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[ES] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[ES] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[ES] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[ES] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[ES] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[ES] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[ES] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[ES] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[ES] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[ES] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[ES] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[ES] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[ES] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[ES] [EN] common.or",
+ "note": "[ES] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/es/tabs.json b/fincept-terminal-desktop/public/locales/es/tabs.json
index 1c95713c4..db69d879e 100644
--- a/fincept-terminal-desktop/public/locales/es/tabs.json
+++ b/fincept-terminal-desktop/public/locales/es/tabs.json
@@ -5,29 +5,7 @@
"news": "Noticias",
"portfolio": "Portafolio",
"backtesting": "Backtesting",
- "watchlist": "Lista de Seguimiento",
- "research": "Investigación",
- "screener": "Screener",
"chat": "AI Chat",
- "agents": "Agentes",
- "settings": "Configuración",
"profile": "Perfil"
- },
- "functionKeys": {
- "f1": "PANL",
- "f2": "MERC",
- "f3": "NOTI",
- "f4": "PORT",
- "f5": "BKTS",
- "f6": "SEGU",
- "f7": "INVS",
- "f8": "SCRN",
- "f9": "TRDG",
- "f10": "AI",
- "f11": "FULL",
- "f12": "PERF"
- },
- "labels": {
- "moreTabs": "Más pestañas en menús de herramientas"
}
}
diff --git a/fincept-terminal-desktop/public/locales/es/watchlist.json b/fincept-terminal-desktop/public/locales/es/watchlist.json
index 4cb864f5a..f842107f8 100644
--- a/fincept-terminal-desktop/public/locales/es/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/es/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "LISTA DE SEGUIMIENTO",
- "header": {
- "export": "EXPORTAR",
- "updating": "ACTUALIZANDO",
- "live": "EN VIVO"
- },
"sidebar": {
- "groups": "GRUPOS DE LISTAS",
- "new": "NUEVA",
"noWatchlists": "Aún no hay listas.",
"clickNew": "Haga clic en NUEVA para crear.",
- "stocks": "acciones",
- "marketMovers": "LÍDERES DEL MERCADO",
- "gainer": "AL ALZA",
- "loser": "A LA BAJA",
- "volumeLeaders": "LÍDERES DE VOLUMEN"
- },
- "emptyState": {
- "selectWatchlist": "Seleccione una lista o cree una nueva para comenzar"
- },
- "list": {
- "symbols": "Símbolos"
+ "stocks": "acciones"
}
}
diff --git a/fincept-terminal-desktop/public/locales/fr/codeEditor.json b/fincept-terminal-desktop/public/locales/fr/codeEditor.json
index 7c262c3bb..204e2a9cc 100644
--- a/fincept-terminal-desktop/public/locales/fr/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/fr/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "ÉDITEUR DE CODE",
"header": {
- "packages": "PAQUETS"
+ "finscriptIde": "[FR] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "NOUVEAU FICHIER",
- "new": "NOUVEAU",
- "open": "OUVRIR",
- "save": "ENREGISTRER",
"run": "EXÉCUTER",
"running": "EXÉCUTION...",
- "runAll": "TOUT EXÉCUTER",
- "history": "HISTORIQUE"
+ "toggleExplorer": "[FR] Toggle Explorer (Ctrl+B)",
+ "openFile": "[FR] Open File",
+ "saveShortcut": "[FR] Save (Ctrl+S)",
+ "findShortcut": "[FR] Find (Ctrl+F)",
+ "runShortcut": "[FR] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "ÉDITEUR FINSCRIPT"
},
- "packages": {
- "clickToLoad": "Cliquez pour charger...",
- "load": "CHARGER LES PAQUETS"
+ "explorer": {
+ "title": "[FR] EXPLORER",
+ "openFiles": "[FR] OPEN FILES",
+ "examples": "[FR] EXAMPLES",
+ "runHistory": "[FR] RUN HISTORY",
+ "finscriptEngine": "[FR] FinScript Engine"
},
- "history": {
- "title": "HISTORIQUE DES NOTEBOOKS",
- "loading": "Chargement de l'historique...",
- "empty": "Aucun historique de notebooks"
+ "output": {
+ "title": "[FR] OUTPUT",
+ "success": "[FR] SUCCESS",
+ "error": "[FR] ERROR",
+ "executing": "[FR] EXECUTING FINSCRIPT...",
+ "noOutput": "[FR] No output yet",
+ "pressToRun": "[FR] Press Ctrl+Enter to run",
+ "completed": "[FR] COMPLETED",
+ "failed": "[FR] FAILED",
+ "signals": "[FR] signals",
+ "clear": "[FR] CLEAR",
+ "errors": "[FR] ERRORS",
+ "signalsSection": "[FR] SIGNALS",
+ "outputSection": "[FR] OUTPUT",
+ "charts": "[FR] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[FR] OHLC",
+ "histogram": "[FR] Histogram",
+ "line": "[FR] Line",
+ "points": "[FR] points"
+ },
+ "statusBar": {
+ "modified": "[FR] MODIFIED",
+ "showOutput": "[FR] SHOW OUTPUT",
+ "encoding": "[FR] UTF-8",
+ "spaces": "[FR] 4 Spaces",
+ "runShortcut": "[FR] Ctrl+Enter: Run",
+ "lines": "[FR] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[FR] Close file without saving?",
+ "unsavedChanges": "[FR] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/fr/common.json b/fincept-terminal-desktop/public/locales/fr/common.json
index 4d36664d1..3bfd9b5a4 100644
--- a/fincept-terminal-desktop/public/locales/fr/common.json
+++ b/fincept-terminal-desktop/public/locales/fr/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Chargement...",
- "error": "Erreur",
- "success": "Succès",
- "save": "Enregistrer",
- "cancel": "Annuler",
- "delete": "Supprimer",
- "edit": "Modifier",
- "add": "Ajouter",
- "search": "Rechercher",
- "filter": "Filtrer",
- "back": "Retour",
- "next": "Suivant",
- "previous": "Précédent",
- "submit": "Soumettre",
- "close": "Fermer",
- "open": "Ouvrir",
- "yes": "Oui",
- "no": "Non",
- "ok": "OK",
- "confirm": "Confirmer",
- "language": "Langue",
- "selectLanguage": "Sélectionner la langue"
-}
\ No newline at end of file
+ "settings": "[FR] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/fr/dashboard.json b/fincept-terminal-desktop/public/locales/fr/dashboard.json
index 270637b6d..c53491cfa 100644
--- a/fincept-terminal-desktop/public/locales/fr/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/fr/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "TABLEAU DE BORD PERSONNALISABLE",
- "live": "EN DIRECT",
- "widgets": "WIDGETS"
- },
- "buttons": {
- "addWidget": "AJOUTER UN WIDGET",
- "saveLayout": "ENREGISTRER LA MISE EN PAGE",
- "reset": "RÉINITIALISER",
- "help": "AIDE"
- },
"widgets": {
"loading": "Chargement...",
- "error": "Erreur",
"globalIndices": "Indices mondiaux - Top 12",
"forex": "Forex - Paires majeures",
"crypto": "CRYPTOMONNAIES",
@@ -20,8 +8,6 @@
"news": "NOUVELLES",
"forum": "FORUM",
"watchlist": "LISTE DE SURVEILLANCE",
- "maritimeIntelligence": "Renseignement maritime",
- "unknown": "Type de widget inconnu",
"index": "INDICE",
"symbol": "SYMBOLE",
"price": "PRIX",
@@ -38,41 +24,22 @@
"pair": "PAIRE",
"rate": "TAUX",
"commodity": "MARCHANDISE",
- "globe3D": "GLOBE 3D",
- "vessels": "NAVIRES",
- "routes": "ITINÉRAIRES",
- "vol24h": "VOL 24H",
- "topTradeCorridors": "PRINCIPAUX CORRIDORS COMMERCIAUX",
- "ships": "navires",
- "marketNews": "Actualités du marché",
- "secPressReleases": "Communiqués de presse de la SEC",
- "cryptoNews": "Actualités cryptographiques",
- "trendingForum": "Forum des tendances",
- "techStocks": "Actions technologiques"
- },
- "tips": {
- "drag": "Faites glisser les widgets pour les réorganiser",
- "resize": "Redimensionner à partir du coin inférieur droit",
- "remove": "Supprimer les widgets avec le bouton X",
- "responsive": "Mise en page réactive - utilise toute la largeur"
- },
- "loading": {
- "title": "Initialisation du tableau de bord",
- "description": "Configuration du cache de base de données pour un chargement plus rapide des données...",
- "note": "Cela ne prendra qu'un instant au premier lancement"
- },
- "empty": {
- "noWidgets": "Aucun widget sur le tableau de bord",
- "addFirst": "AJOUTEZ VOTRE PREMIER WIDGET"
- },
- "status": {
- "version": "Tableau de bord personnalisable Fincept v2.0.0 | Glisser-déposer l'espace de travail",
- "layout": "Mise en page",
- "custom": "Coutume",
- "empty": "Vide",
- "active": "ACTIF",
- "cache": "Cache : ACTIVÉ",
- "label": "Statut"
+ "noActiveMarkets": "[FR] No active markets found",
+ "indicator": "[FR] INDICATOR",
+ "value": "[FR] VALUE",
+ "chg": "[FR] CHG",
+ "overallRisk": "[FR] OVERALL RISK",
+ "openEconomicsTab": "[FR] Open Economics Tab",
+ "openGeopoliticsTab": "[FR] Open Geopolitics Tab",
+ "openPolymarketTab": "[FR] Open Polymarket Tab",
+ "noPortfolioFound": "[FR] No portfolio found",
+ "createPortfolioHint": "[FR] Create one in Portfolio tab",
+ "openPortfolioTab": "[FR] Open Portfolio Tab",
+ "action": "[FR] ACTION",
+ "markets": "[FR] MARKETS",
+ "performanceTracker": "[FR] PERFORMANCE TRACKER",
+ "totalPnL": "[FR] TOTAL P&L",
+ "viewDetailedAnalytics": "[FR] View Detailed Analytics"
},
"messages": {
"layoutSaved": "Disposition du tableau de bord enregistrée !",
diff --git a/fincept-terminal-desktop/public/locales/fr/geopolitics.json b/fincept-terminal-desktop/public/locales/fr/geopolitics.json
index 49e734444..7f7f16515 100644
--- a/fincept-terminal-desktop/public/locales/fr/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/fr/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "GÉOPOLITIQUE",
"messages": {
- "loading": "Chargement des données..."
+ "retry": "[FR] RETRY"
+ },
+ "header": {
+ "prefix": "[FR] GEO>",
+ "title": "[FR] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[FR] EVENTS"
+ },
+ "status": {
+ "stale": "[FR] STALE",
+ "loading": "[FR] LOADING...",
+ "error": "[FR] ERROR:"
+ },
+ "filters": {
+ "country": "[FR] Country...",
+ "cities": "[FR] Cities...",
+ "category": "[FR] Category...",
+ "apply": "[FR] APPLY",
+ "clear": "[FR] CLEAR",
+ "clearAllCities": "[FR] Clear all cities",
+ "selectedLabel": "[FR] Selected:"
+ },
+ "panel": {
+ "title": "[FR] INFO PANEL",
+ "expand": "[FR] Expand panel",
+ "collapse": "[FR] Collapse panel",
+ "eventsLoaded": "[FR] EVENTS LOADED",
+ "onMapVisualization": "[FR] on map visualization",
+ "topCategories": "[FR] TOP CATEGORIES",
+ "topCountries": "[FR] TOP COUNTRIES",
+ "eventDetails": "[FR] EVENT DETAILS",
+ "close": "[FR] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[FR] Country:",
+ "city": "[FR] City:",
+ "keywords": "[FR] Keywords:",
+ "coords": "[FR] Coords:",
+ "date": "[FR] Date:",
+ "source": "[FR] Source:",
+ "viewArticle": "[FR] View Article"
+ },
+ "legend": {
+ "title": "[FR] EVENT CATEGORIES",
+ "armedConflict": "[FR] Armed Conflict",
+ "terrorism": "[FR] Terrorism",
+ "protests": "[FR] Protests",
+ "civilianViolence": "[FR] Civilian Violence",
+ "riots": "[FR] Riots",
+ "politicalViolence": "[FR] Political Violence",
+ "crisis": "[FR] Crisis",
+ "explosions": "[FR] Explosions",
+ "strategic": "[FR] Strategic",
+ "unclassified": "[FR] Unclassified"
+ },
+ "footer": {
+ "tabName": "[FR] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[FR] EVENTS",
+ "labelEngine": "[FR] ENGINE",
+ "engineValue": "[FR] DECK.GL v9.2",
+ "labelSource": "[FR] SOURCE",
+ "sourceValue": "[FR] NEWS-EVENTS API",
+ "labelSelected": "[FR] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/fr/markets.json b/fincept-terminal-desktop/public/locales/fr/markets.json
index 3af118983..44c3be3c1 100644
--- a/fincept-terminal-desktop/public/locales/fr/markets.json
+++ b/fincept-terminal-desktop/public/locales/fr/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%VAR",
"high": "HAUT",
"low": "BAS",
- "loading": "Chargement...",
"noData": "Aucune donnée disponible",
"refresh": "ACTUALISER",
"auto": "AUTO",
"on": "ON",
- "off": "OFF",
- "lastUpdate": "DERNIÈRE MISE À JOUR",
- "updating": "MISE À JOUR",
- "live": "EN DIRECT"
+ "off": "OFF"
}
diff --git a/fincept-terminal-desktop/public/locales/fr/news.json b/fincept-terminal-desktop/public/locales/fr/news.json
index 29f457324..4eeeb9d33 100644
--- a/fincept-terminal-desktop/public/locales/fr/news.json
+++ b/fincept-terminal-desktop/public/locales/fr/news.json
@@ -1,32 +1,63 @@
{
"title": "ACTUALITÉS PROFESSIONNELLES TERMINAL FINCEPT",
"header": {
- "liveFeed": "FLUX EN DIRECT",
- "live": "EN DIRECT",
- "refresh": "ACTUALISER",
- "updating": "MISE À JOUR...",
- "alerts": "ALERTES",
- "sources": "SOURCES",
- "status": "STATUT",
- "demoMode": "MODE DÉMO",
- "articles": "ARTICLES",
- "activeSources": "SOURCES ACTIVES"
- },
- "autoRefresh": {
- "title": "INTERVALLE D'ACTUALISATION AUTOMATIQUE",
- "minute": "minute",
- "minutes": "minutes"
+ "refresh": "ACTUALISER"
},
"messages": {
- "loadingFeeds": "Chargement des flux...",
- "breaking": "DERNIÈRE HEURE"
- },
- "feeds": {
- "primary": "[FR] PRIMARY NEWS FEED",
- "secondary": "[FR] SECONDARY NEWS FEED",
- "additional": "[FR] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[FR] Loading feeds...",
+ "failedToLoad": "[FR] Failed to load RSS feeds",
+ "noCustomFeeds": "[FR] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[FR] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[FR] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[FR] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[FR] RSS FEED SETTINGS",
+ "subtitle": "[FR] MANAGE YOUR NEWS SOURCES",
+ "close": "[FR] CLOSE",
+ "myFeeds": "[FR] MY FEEDS",
+ "defaultFeeds": "[FR] DEFAULT FEEDS",
+ "noFeedsAvailable": "[FR] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[FR] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[FR] ADD NEW FEED",
+ "addNewRssFeed": "[FR] ADD NEW RSS FEED",
+ "editRssFeed": "[FR] EDIT RSS FEED",
+ "restoreDefaults": "[FR] RESTORE DEFAULTS",
+ "restoreAll": "[FR] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[FR] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[FR] DISPLAY NAME",
+ "sourceName": "[FR] SOURCE NAME (SHORT)",
+ "feedUrl": "[FR] RSS FEED URL",
+ "category": "[FR] CATEGORY",
+ "region": "[FR] REGION",
+ "required": "[FR] *",
+ "testUrl": "[FR] TEST URL",
+ "testing": "[FR] TESTING...",
+ "valid": "[FR] VALID",
+ "cancel": "[FR] CANCEL",
+ "saving": "[FR] SAVING...",
+ "addFeed": "[FR] ADD FEED",
+ "updateFeed": "[FR] UPDATE FEED",
+ "on": "[FR] ON",
+ "off": "[FR] OFF",
+ "default": "[FR] DEFAULT",
+ "total": "[FR] TOTAL",
+ "active": "[FR] ACTIVE",
+ "custom": "[FR] CUSTOM",
+ "placeholders": {
+ "displayName": "[FR] e.g., Bloomberg Markets",
+ "sourceName": "[FR] e.g., BLOOMBERG",
+ "feedUrl": "[FR] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[FR] Name is required",
+ "sourceRequired": "[FR] Source name is required",
+ "invalidUrl": "[FR] Please enter a valid URL",
+ "invalidRss": "[FR] URL does not appear to be a valid RSS feed",
+ "testFailed": "[FR] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[FR] Delete this RSS feed?",
+ "message": "[FR] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/fr/portfolio.json b/fincept-terminal-desktop/public/locales/fr/portfolio.json
index 656835967..680ac5583 100644
--- a/fincept-terminal-desktop/public/locales/fr/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/fr/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "GESTIONNAIRE DE PORTEFEUILLE FINCEPT",
- "header": {
- "live": "EN DIRECT",
- "updating": "MISE À JOUR",
- "newPortfolio": "NOUVEAU PORTEFEUILLE",
- "refresh": "ACTUALISER",
- "exportCsv": "EXPORTER CSV"
- },
- "summary": {
- "totalValue": "VALEUR TOTALE",
- "dayPnl": "G/P JOUR",
- "totalPnl": "G/P TOTAL",
- "positions": "POSITIONS"
- },
- "views": {
- "positions": "POSITIONS",
- "addAsset": "AJOUTER ACTIF",
- "sellAsset": "VENDRE ACTIF",
- "analytics": "ANALYTIQUE",
- "history": "HISTORIQUE",
- "activeMgmt": "GESTION ACTIVE",
- "performance": "PERFORMANCE",
- "rebalance": "RÉÉQUILIBRAGE",
- "reports": "RAPPORTS",
- "alerts": "ALERTES",
- "sectors": "SECTEURS",
- "help": "AIDE"
- },
- "sidebar": {
- "portfolios": "PORTEFEUILLES",
- "loading": "Chargement des portefeuilles...",
- "noPortfolios": "Aucun portefeuille encore.",
- "clickCreate": "Cliquez sur NOUVEAU PORTEFEUILLE pour en créer un.",
- "owner": "Propriétaire",
- "currency": "Devise"
- },
- "content": {
- "selectOrCreate": "Sélectionnez un portefeuille ou créez-en un nouveau pour commencer",
- "loadingData": "Chargement des données du portefeuille...",
- "comingSoon": "vue à venir..."
- },
- "modals": {
- "createNew": "CRÉER NOUVEAU PORTEFEUILLE",
- "portfolioName": "NOM DU PORTEFEUILLE",
- "owner": "PROPRIÉTAIRE",
- "currency": "DEVISE",
- "cancel": "ANNULER",
- "create": "CRÉER",
- "addAssetTitle": "AJOUTER ACTIF AU PORTEFEUILLE",
- "sellAssetTitle": "VENDRE ACTIF",
- "symbol": "SYMBOLE",
- "quantity": "QUANTITÉ",
- "price": "PRIX",
- "add": "AJOUTER",
- "sell": "VENDRE"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Suivi en temps réel avec intégration yfinance",
- "lastUpdated": "Dernière Mise à Jour",
- "connected": "CONNECTÉ"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "CRÉER NOUVEAU PORTEFEUILLE",
+ "portfolioName": "NOM DU PORTEFEUILLE",
+ "owner": "PROPRIÉTAIRE",
+ "currency": "DEVISE",
+ "cancel": "ANNULER",
+ "create": "CRÉER",
+ "addAssetTitle": "AJOUTER ACTIF AU PORTEFEUILLE",
+ "sellAssetTitle": "VENDRE ACTIF",
+ "symbol": "SYMBOLE",
+ "quantity": "QUANTITÉ",
+ "price": "PRIX",
+ "add": "AJOUTER",
+ "sell": "VENDRE"
+ },
+ "extracted": {
+ "areYouSureYou": "[FR] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/fr/reportBuilder.json b/fincept-terminal-desktop/public/locales/fr/reportBuilder.json
index 6f7bd9428..dd7f0999e 100644
--- a/fincept-terminal-desktop/public/locales/fr/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/fr/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[FR] Load",
"save": "[FR] Save",
- "saving": "[FR] Saving...",
- "exportPdf": "[FR] Export PDF",
- "generating": "[FR] Generating..."
+ "saving": "[FR] Saving..."
},
"components": {
"title": "[FR] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/fr/settings.json b/fincept-terminal-desktop/public/locales/fr/settings.json
index 1964514c3..2249b037b 100644
--- a/fincept-terminal-desktop/public/locales/fr/settings.json
+++ b/fincept-terminal-desktop/public/locales/fr/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Disposition des onglets",
"appearance": "Apparence",
"language": "Langue",
- "storage": "Stockage et cache"
+ "storage": "Stockage et cache",
+ "notifications": "[FR] Notifications"
},
"credentials": {
"title": "GESTION DES CRÉDENTIELS API",
@@ -46,7 +47,31 @@
"saveConfig": "ENREGISTRER LA CONFIGURATION",
"reset": "RÉINITIALISER",
"saveSuccess": "L'apparence du terminal et les mappages de touches ont été enregistrés avec succès",
- "resetSuccess": "Réinitialiser l'apparence et les mappages de touches par défaut"
+ "resetSuccess": "Réinitialiser l'apparence et les mappages de touches par défaut",
+ "customColors": "[FR] Custom Colors",
+ "customColorsTitle": "[FR] CUSTOM COLORS",
+ "colorPrimary": "[FR] Primary",
+ "colorSecondary": "[FR] Secondary",
+ "colorSuccess": "[FR] Success",
+ "colorAlert": "[FR] Alert",
+ "colorWarning": "[FR] Warning",
+ "colorInfo": "[FR] Info",
+ "colorAccent": "[FR] Accent",
+ "colorPurple": "[FR] Purple",
+ "colorText": "[FR] Text",
+ "colorTextMuted": "[FR] Text Muted",
+ "colorBackground": "[FR] Background",
+ "colorPanel": "[FR] Panel",
+ "layoutSpacing": "[FR] LAYOUT & SPACING",
+ "contentDensity": "[FR] CONTENT DENSITY",
+ "borderRadius": "[FR] BORDER RADIUS",
+ "borderStyle": "[FR] BORDER STYLE",
+ "lineHeight": "[FR] LINE HEIGHT",
+ "letterSpacing": "[FR] LETTER SPACING",
+ "effects": "[FR] EFFECTS",
+ "widgetOpacity": "[FR] WIDGET OPACITY",
+ "enableGlow": "[FR] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[FR] GLOW INTENSITY"
},
"stockSymbols": {
"title": "Base de données des symboles boursiers",
@@ -65,17 +90,8 @@
"tip": "CONSEIL : faites glisser les onglets pour les réorganiser. Utilisez les boutons fléchés pour déplacer les onglets entre les sections d’en-tête et de menu. Les modifications sont enregistrées automatiquement."
},
"llm": {
- "title": "CONFIGURATION LLM",
- "description": "Configurer les modèles et les fournisseurs d'IA",
"connected": "CONNECTÉ",
- "disconnected": "DÉCONNECTÉ",
- "provider": "FOURNISSEUR D'IA",
- "globalSettings": "PARAMÈTRES GLOBAUX DE L'IA",
- "temperature": "TEMPÉRATURE",
- "maxTokens": "MAXI DE JETONS",
- "systemPrompt": "INVITE SYSTÈME",
- "modelLibrary": "BIBLIOTHÈQUE DE MODÈLES",
- "multiModelConfigs": "Configurations multimodèles"
+ "disconnected": "DÉCONNECTÉ"
},
"buttons": {
"save": "SAUVEGARDER",
@@ -86,5 +102,18 @@
"database": "Base de données : SQLite",
"storage": "Stockage : basé sur des fichiers",
"secureStorage": "Toutes les données stockées en toute sécurité dans fincept_terminal.db"
+ },
+ "notifications": {
+ "title": "[FR] NOTIFICATION PROVIDERS",
+ "description": "[FR] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[FR] Event Filters",
+ "eventFilterDescription": "[FR] Choose which notification types to forward to external providers.",
+ "providers": "[FR] Providers",
+ "enabled": "[FR] Enabled",
+ "disabled": "[FR] Disabled",
+ "testButton": "[FR] TEST",
+ "testSuccess": "[FR] Test notification sent successfully!",
+ "testFailed": "[FR] Failed to send test notification. Check your configuration.",
+ "saved": "[FR] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/fr/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/fr/surfaceAnalytics.json
new file mode 100644
index 000000000..b9afefc5a
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/fr/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[FR] SURFACE ANALYTICS",
+ "initializing": "[FR] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[FR] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[FR] VOL SURFACE",
+ "correlation": "[FR] CORRELATION",
+ "yieldCurve": "[FR] YIELD CURVE",
+ "pca": "[FR] PCA FACTORS"
+ },
+ "demoData": "[FR] DEMO DATA",
+ "demoDataSynthetic": "[FR] DEMO DATA (synthetic)",
+ "synthetic": "[FR] SYNTHETIC",
+ "manual": "[FR] MANUAL",
+ "error": "[FR] ERROR",
+ "ready": "[FR] READY",
+ "metrics": "[FR] Metrics",
+ "updated": "[FR] Updated",
+ "clickRefresh": "[FR] Click REFRESH to load data",
+ "refresh": "[FR] REFRESH",
+ "noApiKey": "[FR] NO API KEY",
+ "lastUpdate": "[FR] LAST UPDATE",
+ "loadingData": "[FR] LOADING DATA...",
+ "noDataLoaded": "[FR] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[FR] IV SURFACE METRICS",
+ "correlationMetrics": "[FR] CORRELATION METRICS",
+ "yieldCurveMetrics": "[FR] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[FR] PCA FACTOR METRICS",
+ "dataInfo": "[FR] DATA INFO",
+ "source": "[FR] SOURCE",
+ "frequency": "[FR] FREQUENCY",
+ "quality": "[FR] QUALITY",
+ "correlationScale": "[FR] CORRELATION SCALE",
+ "strongPositive": "[FR] Strong Positive (0.7-1.0)",
+ "neutral": "[FR] Neutral (0.3-0.7)",
+ "strongNegative": "[FR] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[FR] IV INTERPRETATION",
+ "highIv": "[FR] High IV = Expensive Options",
+ "lowIv": "[FR] Low IV = Cheap Options",
+ "skew": "[FR] Skew = Put/Call IV Diff",
+ "termStructure": "[FR] Term Structure = Time Effect",
+ "pcaInterpretation": "[FR] PCA INTERPRETATION",
+ "pc1": "[FR] PC1 = Market Factor",
+ "pc2": "[FR] PC2 = Size/Value Factor",
+ "pc3": "[FR] PC3 = Sector Rotation",
+ "higherVar": "[FR] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[FR] STRIKE",
+ "dte": "[FR] DTE",
+ "iv": "[FR] IV",
+ "correlation": "[FR] CORRELATION",
+ "maturity": "[FR] MATURITY",
+ "yield": "[FR] YIELD",
+ "loading": "[FR] LOADING",
+ "strikePrice": "[FR] STRIKE PRICE",
+ "daysToExpiry": "[FR] DAYS TO EXPIRY",
+ "impliedVol": "[FR] IMPLIED VOL (%)",
+ "assetPairIndex": "[FR] ASSET PAIR INDEX",
+ "timeDays": "[FR] TIME (DAYS)",
+ "correlationCoeff": "[FR] CORRELATION COEFF",
+ "maturityMonths": "[FR] MATURITY (MONTHS)",
+ "historicalDays": "[FR] HISTORICAL DAYS",
+ "yieldPercent": "[FR] YIELD (%)",
+ "principalComponent": "[FR] PRINCIPAL COMPONENT",
+ "assetIndex": "[FR] ASSET INDEX",
+ "factorLoading": "[FR] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[FR] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[FR] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[FR] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[FR] DAY ROLLING",
+ "yieldCurve": "[FR] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[FR] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[FR] FAILED TO LOAD DATA",
+ "authFailed": "[FR] AUTHENTICATION FAILED",
+ "authFailedHelp": "[FR] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[FR] ACCESS DENIED",
+ "accessDeniedHelp": "[FR] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[FR] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[FR] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[FR] DATA TIMEFRAME",
+ "schema": "[FR] Schema",
+ "description": "[FR] Description",
+ "recordsPerDay": "[FR] Records/Day",
+ "highFrequencyWarning": "[FR] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[FR] Data Volume"
+ },
+ "settings": {
+ "title": "[FR] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[FR] DATABENTO API KEY",
+ "configured": "[FR] CONFIGURED",
+ "invalidFormat": "[FR] INVALID FORMAT",
+ "apiKeyConfigured": "[FR] API key is configured (db-*****)",
+ "remove": "[FR] REMOVE",
+ "enterApiKey": "[FR] Enter your Databento API key (db-*****)",
+ "save": "[FR] SAVE",
+ "saving": "[FR] SAVING...",
+ "getApiKeyFrom": "[FR] Get your API key from",
+ "dashboardApiKeys": "[FR] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[FR] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[FR] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[FR] CORRELATION ASSETS",
+ "addSymbol": "[FR] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[FR] Reset to defaults",
+ "historicalDateRange": "[FR] HISTORICAL DATE RANGE",
+ "start": "[FR] Start",
+ "end": "[FR] End",
+ "autoRefreshInterval": "[FR] AUTO REFRESH INTERVAL",
+ "manualOnly": "[FR] Manual Only",
+ "every1min": "[FR] Every 1 minute",
+ "every5min": "[FR] Every 5 minutes",
+ "every15min": "[FR] Every 15 minutes",
+ "every1hour": "[FR] Every 1 hour",
+ "browseDatasets": "[FR] BROWSE DATASETS",
+ "costEstimator": "[FR] COST ESTIMATOR",
+ "referenceData": "[FR] REFERENCE DATA",
+ "orderBook": "[FR] ORDER BOOK",
+ "liveStreaming": "[FR] LIVE STREAMING",
+ "active": "[FR] ACTIVE",
+ "futuresCme": "[FR] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[FR] BATCH DOWNLOADS",
+ "additionalSchemas": "[FR] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[FR] TRADES, IMBALANCE, STATUS",
+ "cancel": "[FR] CANCEL",
+ "saveChanges": "[FR] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[FR] BATCH DOWNLOADS",
+ "newBatchJob": "[FR] NEW BATCH JOB",
+ "dataset": "[FR] Dataset",
+ "schema": "[FR] Schema",
+ "symbolsCommaSeparated": "[FR] Symbols (comma-separated)",
+ "startDate": "[FR] Start Date",
+ "endDate": "[FR] End Date",
+ "encoding": "[FR] Encoding",
+ "compression": "[FR] Compression",
+ "submitJob": "[FR] SUBMIT JOB",
+ "noBatchJobs": "[FR] No batch jobs found. Click + to create one.",
+ "records": "[FR] records",
+ "download": "[FR] Download",
+ "files": "[FR] FILES",
+ "jobsExpireNotice": "[FR] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[FR] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[FR] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[FR] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[FR] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[FR] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[FR] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[FR] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[FR] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[FR] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[FR] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[FR] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[FR] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[FR] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[FR] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[FR] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[FR] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[FR] [EN] common.or",
+ "note": "[FR] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/fr/tabs.json b/fincept-terminal-desktop/public/locales/fr/tabs.json
index 86917128d..1826d4d6e 100644
--- a/fincept-terminal-desktop/public/locales/fr/tabs.json
+++ b/fincept-terminal-desktop/public/locales/fr/tabs.json
@@ -5,29 +5,7 @@
"news": "Actualités",
"portfolio": "Portefeuille",
"backtesting": "Backtesting",
- "watchlist": "Liste de Suivi",
- "research": "Recherche",
- "screener": "Screener",
"chat": "AI Chat",
- "agents": "Agents",
- "settings": "Paramètres",
"profile": "Profil"
- },
- "functionKeys": {
- "f1": "TABL",
- "f2": "MARC",
- "f3": "ACTU",
- "f4": "PORT",
- "f5": "BKTS",
- "f6": "SUIV",
- "f7": "RECH",
- "f8": "SCRN",
- "f9": "TRDG",
- "f10": "AI",
- "f11": "FULL",
- "f12": "PROF"
- },
- "labels": {
- "moreTabs": "Plus d'onglets dans les menus d'outils"
}
}
diff --git a/fincept-terminal-desktop/public/locales/fr/watchlist.json b/fincept-terminal-desktop/public/locales/fr/watchlist.json
index f808c9470..9b13608ec 100644
--- a/fincept-terminal-desktop/public/locales/fr/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/fr/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "LISTE DE SUIVI",
- "header": {
- "export": "EXPORTER",
- "updating": "MISE À JOUR",
- "live": "EN DIRECT"
- },
"sidebar": {
- "groups": "GROUPES DE LISTES",
- "new": "NOUVEAU",
"noWatchlists": "Pas encore de listes.",
"clickNew": "Cliquez NOUVEAU pour créer.",
- "stocks": "actions",
- "marketMovers": "LEADERS DU MARCHÉ",
- "gainer": "HAUSSE",
- "loser": "BAISSE",
- "volumeLeaders": "LEADERS DE VOLUME"
- },
- "emptyState": {
- "selectWatchlist": "Sélectionnez une liste ou créez-en une nouvelle pour commencer"
- },
- "list": {
- "symbols": "Symboles"
+ "stocks": "actions"
}
}
diff --git a/fincept-terminal-desktop/public/locales/hi/codeEditor.json b/fincept-terminal-desktop/public/locales/hi/codeEditor.json
index 9bd2d96a3..0396a438d 100644
--- a/fincept-terminal-desktop/public/locales/hi/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/hi/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "कोड एडिटर",
"header": {
- "packages": "पैकेज"
+ "finscriptIde": "[HI] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "नई फाइल",
- "new": "नया",
- "open": "खोलें",
- "save": "सहेजें",
"run": "कोड चलाएं",
"running": "चल रहा है...",
- "runAll": "सभी चलाएं",
- "history": "इतिहास"
+ "toggleExplorer": "[HI] Toggle Explorer (Ctrl+B)",
+ "openFile": "[HI] Open File",
+ "saveShortcut": "[HI] Save (Ctrl+S)",
+ "findShortcut": "[HI] Find (Ctrl+F)",
+ "runShortcut": "[HI] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "ज्यूपिटर नोटबुक",
"finscript": "फिनस्क्रिप्ट एडिटर"
},
- "packages": {
- "clickToLoad": "पैकेज लोड करने के लिए क्लिक करें...",
- "load": "पैकेज लोड करें"
+ "explorer": {
+ "title": "[HI] EXPLORER",
+ "openFiles": "[HI] OPEN FILES",
+ "examples": "[HI] EXAMPLES",
+ "runHistory": "[HI] RUN HISTORY",
+ "finscriptEngine": "[HI] FinScript Engine"
},
- "history": {
- "title": "नोटबुक इतिहास",
- "loading": "इतिहास लोड हो रहा है...",
- "empty": "अभी तक कोई नोटबुक इतिहास नहीं"
+ "output": {
+ "title": "[HI] OUTPUT",
+ "success": "[HI] SUCCESS",
+ "error": "[HI] ERROR",
+ "executing": "[HI] EXECUTING FINSCRIPT...",
+ "noOutput": "[HI] No output yet",
+ "pressToRun": "[HI] Press Ctrl+Enter to run",
+ "completed": "[HI] COMPLETED",
+ "failed": "[HI] FAILED",
+ "signals": "[HI] signals",
+ "clear": "[HI] CLEAR",
+ "errors": "[HI] ERRORS",
+ "signalsSection": "[HI] SIGNALS",
+ "outputSection": "[HI] OUTPUT",
+ "charts": "[HI] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[HI] OHLC",
+ "histogram": "[HI] Histogram",
+ "line": "[HI] Line",
+ "points": "[HI] points"
+ },
+ "statusBar": {
+ "modified": "[HI] MODIFIED",
+ "showOutput": "[HI] SHOW OUTPUT",
+ "encoding": "[HI] UTF-8",
+ "spaces": "[HI] 4 Spaces",
+ "runShortcut": "[HI] Ctrl+Enter: Run",
+ "lines": "[HI] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[HI] Close file without saving?",
+ "unsavedChanges": "[HI] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/hi/common.json b/fincept-terminal-desktop/public/locales/hi/common.json
index e540026cc..6a3b782a4 100644
--- a/fincept-terminal-desktop/public/locales/hi/common.json
+++ b/fincept-terminal-desktop/public/locales/hi/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "लोड हो रहा है...",
- "error": "त्रुटि",
- "success": "सफलता",
- "save": "सहेजें",
- "cancel": "रद्द करें",
- "delete": "हटाएं",
- "edit": "संपादित करें",
- "add": "जोड़ें",
- "search": "खोजें",
- "filter": "फ़िल्टर",
- "back": "पीछे",
- "next": "अगला",
- "previous": "पिछला",
- "submit": "जमा करें",
- "close": "बंद करें",
- "open": "खोलें",
- "yes": "हां",
- "no": "नहीं",
- "ok": "ठीक है",
- "confirm": "पुष्टि करें",
- "language": "भाषा",
- "selectLanguage": "भाषा चुनें"
-}
\ No newline at end of file
+ "settings": "[HI] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/hi/dashboard.json b/fincept-terminal-desktop/public/locales/hi/dashboard.json
index 945d5ef50..e6ab955a0 100644
--- a/fincept-terminal-desktop/public/locales/hi/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/hi/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "अनुकूलन योग्य डैशबोर्ड",
- "live": "रहना",
- "widgets": "विजेट्स"
- },
- "buttons": {
- "addWidget": "विजेट जोड़ें",
- "saveLayout": "लेआउट सहेजें",
- "reset": "रीसेट करें",
- "help": "मदद"
- },
"widgets": {
"loading": "लोड हो रहा है...",
- "error": "गलती",
"globalIndices": "वैश्विक सूचकांक - शीर्ष 12",
"forex": "विदेशी मुद्रा - प्रमुख जोड़े",
"crypto": "क्रिप्टोमुद्राएँ",
@@ -20,8 +8,6 @@
"news": "समाचार",
"forum": "मंच",
"watchlist": "सभी आँकड़े",
- "maritimeIntelligence": "समुद्री खुफिया",
- "unknown": "अज्ञात विजेट प्रकार",
"index": "अनुक्रमणिका",
"symbol": "प्रतीक",
"price": "कीमत",
@@ -38,41 +24,22 @@
"pair": "जोड़ा",
"rate": "दर",
"commodity": "माल",
- "globe3D": "3डी ग्लोब",
- "vessels": "जहाजों",
- "routes": "मार्ग",
- "vol24h": "वॉल्यूम 24एच",
- "topTradeCorridors": "शीर्ष व्यापार गलियारे",
- "ships": "जहाज",
- "marketNews": "बाज़ार समाचार",
- "secPressReleases": "एसईसी प्रेस विज्ञप्तियाँ",
- "cryptoNews": "क्रिप्टो समाचार",
- "trendingForum": "ट्रेंडिंग फोरम",
- "techStocks": "टेक स्टॉक"
- },
- "tips": {
- "drag": "पुनर्व्यवस्थित करने के लिए विजेट खींचें",
- "resize": "नीचे-दाएँ कोने से आकार बदलें",
- "remove": "X बटन से विजेट हटाएँ",
- "responsive": "उत्तरदायी लेआउट - पूरी चौड़ाई का उपयोग करता है"
- },
- "loading": {
- "title": "डैशबोर्ड प्रारंभ किया जा रहा है",
- "description": "तेज़ डेटा लोडिंग के लिए डेटाबेस कैश सेट अप किया जा रहा है...",
- "note": "पहले लॉन्च में इसमें केवल एक क्षण लगेगा"
- },
- "empty": {
- "noWidgets": "डैशबोर्ड पर कोई विजेट नहीं",
- "addFirst": "अपना पहला विजेट जोड़ें"
- },
- "status": {
- "version": "फिनसेप्ट अनुकूलन योग्य डैशबोर्ड v2.0.0 | कार्यक्षेत्र को खींचें और छोड़ें",
- "layout": "लेआउट",
- "custom": "रिवाज़",
- "empty": "खाली",
- "active": "सक्रिय",
- "cache": "कैश: सक्षम",
- "label": "स्थिति"
+ "noActiveMarkets": "[HI] No active markets found",
+ "indicator": "[HI] INDICATOR",
+ "value": "[HI] VALUE",
+ "chg": "[HI] CHG",
+ "overallRisk": "[HI] OVERALL RISK",
+ "openEconomicsTab": "[HI] Open Economics Tab",
+ "openGeopoliticsTab": "[HI] Open Geopolitics Tab",
+ "openPolymarketTab": "[HI] Open Polymarket Tab",
+ "noPortfolioFound": "[HI] No portfolio found",
+ "createPortfolioHint": "[HI] Create one in Portfolio tab",
+ "openPortfolioTab": "[HI] Open Portfolio Tab",
+ "action": "[HI] ACTION",
+ "markets": "[HI] MARKETS",
+ "performanceTracker": "[HI] PERFORMANCE TRACKER",
+ "totalPnL": "[HI] TOTAL P&L",
+ "viewDetailedAnalytics": "[HI] View Detailed Analytics"
},
"messages": {
"layoutSaved": "डैशबोर्ड लेआउट सहेजा गया!",
diff --git a/fincept-terminal-desktop/public/locales/hi/geopolitics.json b/fincept-terminal-desktop/public/locales/hi/geopolitics.json
index f4075ebcd..1553c8ca9 100644
--- a/fincept-terminal-desktop/public/locales/hi/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/hi/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "भू-राजनीति",
"messages": {
- "loading": "भू-राजनीतिक डेटा लोड हो रहा है..."
+ "retry": "[HI] RETRY"
+ },
+ "header": {
+ "prefix": "[HI] GEO>",
+ "title": "[HI] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[HI] EVENTS"
+ },
+ "status": {
+ "stale": "[HI] STALE",
+ "loading": "[HI] LOADING...",
+ "error": "[HI] ERROR:"
+ },
+ "filters": {
+ "country": "[HI] Country...",
+ "cities": "[HI] Cities...",
+ "category": "[HI] Category...",
+ "apply": "[HI] APPLY",
+ "clear": "[HI] CLEAR",
+ "clearAllCities": "[HI] Clear all cities",
+ "selectedLabel": "[HI] Selected:"
+ },
+ "panel": {
+ "title": "[HI] INFO PANEL",
+ "expand": "[HI] Expand panel",
+ "collapse": "[HI] Collapse panel",
+ "eventsLoaded": "[HI] EVENTS LOADED",
+ "onMapVisualization": "[HI] on map visualization",
+ "topCategories": "[HI] TOP CATEGORIES",
+ "topCountries": "[HI] TOP COUNTRIES",
+ "eventDetails": "[HI] EVENT DETAILS",
+ "close": "[HI] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[HI] Country:",
+ "city": "[HI] City:",
+ "keywords": "[HI] Keywords:",
+ "coords": "[HI] Coords:",
+ "date": "[HI] Date:",
+ "source": "[HI] Source:",
+ "viewArticle": "[HI] View Article"
+ },
+ "legend": {
+ "title": "[HI] EVENT CATEGORIES",
+ "armedConflict": "[HI] Armed Conflict",
+ "terrorism": "[HI] Terrorism",
+ "protests": "[HI] Protests",
+ "civilianViolence": "[HI] Civilian Violence",
+ "riots": "[HI] Riots",
+ "politicalViolence": "[HI] Political Violence",
+ "crisis": "[HI] Crisis",
+ "explosions": "[HI] Explosions",
+ "strategic": "[HI] Strategic",
+ "unclassified": "[HI] Unclassified"
+ },
+ "footer": {
+ "tabName": "[HI] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[HI] EVENTS",
+ "labelEngine": "[HI] ENGINE",
+ "engineValue": "[HI] DECK.GL v9.2",
+ "labelSource": "[HI] SOURCE",
+ "sourceValue": "[HI] NEWS-EVENTS API",
+ "labelSelected": "[HI] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/hi/markets.json b/fincept-terminal-desktop/public/locales/hi/markets.json
index ad4a83e1a..0d43d55ed 100644
--- a/fincept-terminal-desktop/public/locales/hi/markets.json
+++ b/fincept-terminal-desktop/public/locales/hi/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%बदलाव",
"high": "उच्च",
"low": "निम्न",
- "loading": "लोड हो रहा है...",
"noData": "कोई डेटा नहीं",
"refresh": "रीफ्रेश",
"auto": "ऑटो",
"on": "चालू",
- "off": "बंद",
- "lastUpdate": "अंतिम अपडेट",
- "updating": "अपडेट हो रहा है",
- "live": "लाइव"
+ "off": "बंद"
}
diff --git a/fincept-terminal-desktop/public/locales/hi/news.json b/fincept-terminal-desktop/public/locales/hi/news.json
index f29d60ead..6b38dbb60 100644
--- a/fincept-terminal-desktop/public/locales/hi/news.json
+++ b/fincept-terminal-desktop/public/locales/hi/news.json
@@ -1,32 +1,63 @@
{
"title": "FINCEPT टर्मिनल प्रोफेशनल न्यूज़",
"header": {
- "liveFeed": "लाइव फ़ीड",
- "live": "लाइव",
- "refresh": "रीफ्रेश",
- "updating": "अपडेट हो रहा है...",
- "alerts": "अलर्ट",
- "sources": "स्रोत",
- "status": "स्थिति",
- "demoMode": "डेमो मोड",
- "articles": "लेख",
- "activeSources": "सक्रिय स्रोत"
- },
- "autoRefresh": {
- "title": "ऑटो-रीफ्रेश अंतराल",
- "minute": "मिनट",
- "minutes": "मिनट"
+ "refresh": "रीफ्रेश"
},
"messages": {
- "loadingFeeds": "फ़ीड लोड हो रहे हैं...",
- "breaking": "ब्रेकिंग"
- },
- "feeds": {
- "primary": "[HI] PRIMARY NEWS FEED",
- "secondary": "[HI] SECONDARY NEWS FEED",
- "additional": "[HI] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[HI] Loading feeds...",
+ "failedToLoad": "[HI] Failed to load RSS feeds",
+ "noCustomFeeds": "[HI] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[HI] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[HI] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[HI] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[HI] RSS FEED SETTINGS",
+ "subtitle": "[HI] MANAGE YOUR NEWS SOURCES",
+ "close": "[HI] CLOSE",
+ "myFeeds": "[HI] MY FEEDS",
+ "defaultFeeds": "[HI] DEFAULT FEEDS",
+ "noFeedsAvailable": "[HI] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[HI] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[HI] ADD NEW FEED",
+ "addNewRssFeed": "[HI] ADD NEW RSS FEED",
+ "editRssFeed": "[HI] EDIT RSS FEED",
+ "restoreDefaults": "[HI] RESTORE DEFAULTS",
+ "restoreAll": "[HI] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[HI] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[HI] DISPLAY NAME",
+ "sourceName": "[HI] SOURCE NAME (SHORT)",
+ "feedUrl": "[HI] RSS FEED URL",
+ "category": "[HI] CATEGORY",
+ "region": "[HI] REGION",
+ "required": "[HI] *",
+ "testUrl": "[HI] TEST URL",
+ "testing": "[HI] TESTING...",
+ "valid": "[HI] VALID",
+ "cancel": "[HI] CANCEL",
+ "saving": "[HI] SAVING...",
+ "addFeed": "[HI] ADD FEED",
+ "updateFeed": "[HI] UPDATE FEED",
+ "on": "[HI] ON",
+ "off": "[HI] OFF",
+ "default": "[HI] DEFAULT",
+ "total": "[HI] TOTAL",
+ "active": "[HI] ACTIVE",
+ "custom": "[HI] CUSTOM",
+ "placeholders": {
+ "displayName": "[HI] e.g., Bloomberg Markets",
+ "sourceName": "[HI] e.g., BLOOMBERG",
+ "feedUrl": "[HI] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[HI] Name is required",
+ "sourceRequired": "[HI] Source name is required",
+ "invalidUrl": "[HI] Please enter a valid URL",
+ "invalidRss": "[HI] URL does not appear to be a valid RSS feed",
+ "testFailed": "[HI] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[HI] Delete this RSS feed?",
+ "message": "[HI] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/hi/portfolio.json b/fincept-terminal-desktop/public/locales/hi/portfolio.json
index 7107eb73b..e12dfe404 100644
--- a/fincept-terminal-desktop/public/locales/hi/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/hi/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "FINCEPT पोर्टफोलियो मैनेजर",
- "header": {
- "live": "लाइव",
- "updating": "अपडेट हो रहा है",
- "newPortfolio": "नया पोर्टफोलियो",
- "refresh": "रीफ्रेश",
- "exportCsv": "CSV एक्सपोर्ट"
- },
- "summary": {
- "totalValue": "कुल मूल्य",
- "dayPnl": "दैनिक लाभ/हानि",
- "totalPnl": "कुल लाभ/हानि",
- "positions": "पोजीशन"
- },
- "views": {
- "positions": "पोजीशन",
- "addAsset": "एसेट जोड़ें",
- "sellAsset": "एसेट बेचें",
- "analytics": "एनालिटिक्स",
- "history": "इतिहास",
- "activeMgmt": "सक्रिय प्रबंधन",
- "performance": "प्रदर्शन",
- "rebalance": "रीबैलेंस",
- "reports": "रिपोर्ट",
- "alerts": "अलर्ट",
- "sectors": "सेक्टर",
- "help": "सहायता"
- },
- "sidebar": {
- "portfolios": "पोर्टफोलियो",
- "loading": "पोर्टफोलियो लोड हो रहे हैं...",
- "noPortfolios": "अभी तक कोई पोर्टफोलियो नहीं।",
- "clickCreate": "बनाने के लिए नया पोर्टफोलियो पर क्लिक करें।",
- "owner": "मालिक",
- "currency": "मुद्रा"
- },
- "content": {
- "selectOrCreate": "शुरू करने के लिए पोर्टफोलियो चुनें या नया बनाएं",
- "loadingData": "पोर्टफोलियो डेटा लोड हो रहा है...",
- "comingSoon": "जल्द आ रहा है..."
- },
- "modals": {
- "createNew": "नया पोर्टफोलियो बनाएं",
- "portfolioName": "पोर्टफोलियो नाम",
- "owner": "मालिक",
- "currency": "मुद्रा",
- "cancel": "रद्द करें",
- "create": "बनाएं",
- "addAssetTitle": "पोर्टफोलियो में एसेट जोड़ें",
- "sellAssetTitle": "एसेट बेचें",
- "symbol": "सिम्बल",
- "quantity": "मात्रा",
- "price": "मूल्य",
- "add": "जोड़ें",
- "sell": "बेचें"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | yfinance इंटीग्रेशन के साथ रियल-टाइम ट्रैकिंग",
- "lastUpdated": "अंतिम अपडेट",
- "connected": "कनेक्टेड"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "नया पोर्टफोलियो बनाएं",
+ "portfolioName": "पोर्टफोलियो नाम",
+ "owner": "मालिक",
+ "currency": "मुद्रा",
+ "cancel": "रद्द करें",
+ "create": "बनाएं",
+ "addAssetTitle": "पोर्टफोलियो में एसेट जोड़ें",
+ "sellAssetTitle": "एसेट बेचें",
+ "symbol": "सिम्बल",
+ "quantity": "मात्रा",
+ "price": "मूल्य",
+ "add": "जोड़ें",
+ "sell": "बेचें"
+ },
+ "extracted": {
+ "areYouSureYou": "[HI] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/hi/reportBuilder.json b/fincept-terminal-desktop/public/locales/hi/reportBuilder.json
index 14a5872ff..54db5a04a 100644
--- a/fincept-terminal-desktop/public/locales/hi/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/hi/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[HI] Load",
"save": "[HI] Save",
- "saving": "[HI] Saving...",
- "exportPdf": "[HI] Export PDF",
- "generating": "[HI] Generating..."
+ "saving": "[HI] Saving..."
},
"components": {
"title": "[HI] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/hi/settings.json b/fincept-terminal-desktop/public/locales/hi/settings.json
index f04a38447..d6b446f4f 100644
--- a/fincept-terminal-desktop/public/locales/hi/settings.json
+++ b/fincept-terminal-desktop/public/locales/hi/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "टैब लेआउट",
"appearance": "उपस्थिति",
"language": "भाषा",
- "storage": "भंडारण एवं कैश"
+ "storage": "भंडारण एवं कैश",
+ "notifications": "[HI] Notifications"
},
"credentials": {
"title": "एपीआई क्रेडेंशियल प्रबंधन",
@@ -46,7 +47,31 @@
"saveConfig": "कॉन्फ़िगरेशन सहेजें",
"reset": "रीसेट करें",
"saveSuccess": "टर्मिनल उपस्थिति और कुंजी मैपिंग सफलतापूर्वक सहेजी गई",
- "resetSuccess": "डिफ़ॉल्ट उपस्थिति और कुंजी मैपिंग पर रीसेट करें"
+ "resetSuccess": "डिफ़ॉल्ट उपस्थिति और कुंजी मैपिंग पर रीसेट करें",
+ "customColors": "[HI] Custom Colors",
+ "customColorsTitle": "[HI] CUSTOM COLORS",
+ "colorPrimary": "[HI] Primary",
+ "colorSecondary": "[HI] Secondary",
+ "colorSuccess": "[HI] Success",
+ "colorAlert": "[HI] Alert",
+ "colorWarning": "[HI] Warning",
+ "colorInfo": "[HI] Info",
+ "colorAccent": "[HI] Accent",
+ "colorPurple": "[HI] Purple",
+ "colorText": "[HI] Text",
+ "colorTextMuted": "[HI] Text Muted",
+ "colorBackground": "[HI] Background",
+ "colorPanel": "[HI] Panel",
+ "layoutSpacing": "[HI] LAYOUT & SPACING",
+ "contentDensity": "[HI] CONTENT DENSITY",
+ "borderRadius": "[HI] BORDER RADIUS",
+ "borderStyle": "[HI] BORDER STYLE",
+ "lineHeight": "[HI] LINE HEIGHT",
+ "letterSpacing": "[HI] LETTER SPACING",
+ "effects": "[HI] EFFECTS",
+ "widgetOpacity": "[HI] WIDGET OPACITY",
+ "enableGlow": "[HI] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[HI] GLOW INTENSITY"
},
"stockSymbols": {
"title": "स्टॉक प्रतीक डेटाबेस",
@@ -65,17 +90,8 @@
"tip": "सुझाव: टैब को पुन: व्यवस्थित करने के लिए उन्हें खींचें। हेडर और मेनू अनुभागों के बीच टैब को स्थानांतरित करने के लिए तीर बटन का उपयोग करें। परिवर्तन स्वचालित रूप से सहेजे जाते हैं."
},
"llm": {
- "title": "एलएलएम कॉन्फ़िगरेशन",
- "description": "एआई मॉडल और प्रदाताओं को कॉन्फ़िगर करें",
"connected": "जुड़े हुए",
- "disconnected": "डिस्कनेक्ट किया गया",
- "provider": "एआई प्रदाता",
- "globalSettings": "वैश्विक एआई सेटिंग्स",
- "temperature": "तापमान",
- "maxTokens": "अधिकतम टोकन",
- "systemPrompt": "सिस्टम प्रॉम्प्ट",
- "modelLibrary": "मॉडल लाइब्रेरी",
- "multiModelConfigs": "मल्टी-मॉडल कॉन्फ़िगरेशन"
+ "disconnected": "डिस्कनेक्ट किया गया"
},
"buttons": {
"save": "बचाना",
@@ -86,5 +102,18 @@
"database": "डेटाबेस: SQLite",
"storage": "भंडारण: फ़ाइल-आधारित",
"secureStorage": "सभी डेटा fincept_terminal.db में सुरक्षित रूप से संग्रहीत हैं"
+ },
+ "notifications": {
+ "title": "[HI] NOTIFICATION PROVIDERS",
+ "description": "[HI] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[HI] Event Filters",
+ "eventFilterDescription": "[HI] Choose which notification types to forward to external providers.",
+ "providers": "[HI] Providers",
+ "enabled": "[HI] Enabled",
+ "disabled": "[HI] Disabled",
+ "testButton": "[HI] TEST",
+ "testSuccess": "[HI] Test notification sent successfully!",
+ "testFailed": "[HI] Failed to send test notification. Check your configuration.",
+ "saved": "[HI] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/hi/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/hi/surfaceAnalytics.json
new file mode 100644
index 000000000..f9ad9a625
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/hi/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[HI] SURFACE ANALYTICS",
+ "initializing": "[HI] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[HI] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[HI] VOL SURFACE",
+ "correlation": "[HI] CORRELATION",
+ "yieldCurve": "[HI] YIELD CURVE",
+ "pca": "[HI] PCA FACTORS"
+ },
+ "demoData": "[HI] DEMO DATA",
+ "demoDataSynthetic": "[HI] DEMO DATA (synthetic)",
+ "synthetic": "[HI] SYNTHETIC",
+ "manual": "[HI] MANUAL",
+ "error": "[HI] ERROR",
+ "ready": "[HI] READY",
+ "metrics": "[HI] Metrics",
+ "updated": "[HI] Updated",
+ "clickRefresh": "[HI] Click REFRESH to load data",
+ "refresh": "[HI] REFRESH",
+ "noApiKey": "[HI] NO API KEY",
+ "lastUpdate": "[HI] LAST UPDATE",
+ "loadingData": "[HI] LOADING DATA...",
+ "noDataLoaded": "[HI] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[HI] IV SURFACE METRICS",
+ "correlationMetrics": "[HI] CORRELATION METRICS",
+ "yieldCurveMetrics": "[HI] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[HI] PCA FACTOR METRICS",
+ "dataInfo": "[HI] DATA INFO",
+ "source": "[HI] SOURCE",
+ "frequency": "[HI] FREQUENCY",
+ "quality": "[HI] QUALITY",
+ "correlationScale": "[HI] CORRELATION SCALE",
+ "strongPositive": "[HI] Strong Positive (0.7-1.0)",
+ "neutral": "[HI] Neutral (0.3-0.7)",
+ "strongNegative": "[HI] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[HI] IV INTERPRETATION",
+ "highIv": "[HI] High IV = Expensive Options",
+ "lowIv": "[HI] Low IV = Cheap Options",
+ "skew": "[HI] Skew = Put/Call IV Diff",
+ "termStructure": "[HI] Term Structure = Time Effect",
+ "pcaInterpretation": "[HI] PCA INTERPRETATION",
+ "pc1": "[HI] PC1 = Market Factor",
+ "pc2": "[HI] PC2 = Size/Value Factor",
+ "pc3": "[HI] PC3 = Sector Rotation",
+ "higherVar": "[HI] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[HI] STRIKE",
+ "dte": "[HI] DTE",
+ "iv": "[HI] IV",
+ "correlation": "[HI] CORRELATION",
+ "maturity": "[HI] MATURITY",
+ "yield": "[HI] YIELD",
+ "loading": "[HI] LOADING",
+ "strikePrice": "[HI] STRIKE PRICE",
+ "daysToExpiry": "[HI] DAYS TO EXPIRY",
+ "impliedVol": "[HI] IMPLIED VOL (%)",
+ "assetPairIndex": "[HI] ASSET PAIR INDEX",
+ "timeDays": "[HI] TIME (DAYS)",
+ "correlationCoeff": "[HI] CORRELATION COEFF",
+ "maturityMonths": "[HI] MATURITY (MONTHS)",
+ "historicalDays": "[HI] HISTORICAL DAYS",
+ "yieldPercent": "[HI] YIELD (%)",
+ "principalComponent": "[HI] PRINCIPAL COMPONENT",
+ "assetIndex": "[HI] ASSET INDEX",
+ "factorLoading": "[HI] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[HI] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[HI] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[HI] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[HI] DAY ROLLING",
+ "yieldCurve": "[HI] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[HI] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[HI] FAILED TO LOAD DATA",
+ "authFailed": "[HI] AUTHENTICATION FAILED",
+ "authFailedHelp": "[HI] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[HI] ACCESS DENIED",
+ "accessDeniedHelp": "[HI] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[HI] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[HI] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[HI] DATA TIMEFRAME",
+ "schema": "[HI] Schema",
+ "description": "[HI] Description",
+ "recordsPerDay": "[HI] Records/Day",
+ "highFrequencyWarning": "[HI] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[HI] Data Volume"
+ },
+ "settings": {
+ "title": "[HI] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[HI] DATABENTO API KEY",
+ "configured": "[HI] CONFIGURED",
+ "invalidFormat": "[HI] INVALID FORMAT",
+ "apiKeyConfigured": "[HI] API key is configured (db-*****)",
+ "remove": "[HI] REMOVE",
+ "enterApiKey": "[HI] Enter your Databento API key (db-*****)",
+ "save": "[HI] SAVE",
+ "saving": "[HI] SAVING...",
+ "getApiKeyFrom": "[HI] Get your API key from",
+ "dashboardApiKeys": "[HI] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[HI] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[HI] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[HI] CORRELATION ASSETS",
+ "addSymbol": "[HI] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[HI] Reset to defaults",
+ "historicalDateRange": "[HI] HISTORICAL DATE RANGE",
+ "start": "[HI] Start",
+ "end": "[HI] End",
+ "autoRefreshInterval": "[HI] AUTO REFRESH INTERVAL",
+ "manualOnly": "[HI] Manual Only",
+ "every1min": "[HI] Every 1 minute",
+ "every5min": "[HI] Every 5 minutes",
+ "every15min": "[HI] Every 15 minutes",
+ "every1hour": "[HI] Every 1 hour",
+ "browseDatasets": "[HI] BROWSE DATASETS",
+ "costEstimator": "[HI] COST ESTIMATOR",
+ "referenceData": "[HI] REFERENCE DATA",
+ "orderBook": "[HI] ORDER BOOK",
+ "liveStreaming": "[HI] LIVE STREAMING",
+ "active": "[HI] ACTIVE",
+ "futuresCme": "[HI] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[HI] BATCH DOWNLOADS",
+ "additionalSchemas": "[HI] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[HI] TRADES, IMBALANCE, STATUS",
+ "cancel": "[HI] CANCEL",
+ "saveChanges": "[HI] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[HI] BATCH DOWNLOADS",
+ "newBatchJob": "[HI] NEW BATCH JOB",
+ "dataset": "[HI] Dataset",
+ "schema": "[HI] Schema",
+ "symbolsCommaSeparated": "[HI] Symbols (comma-separated)",
+ "startDate": "[HI] Start Date",
+ "endDate": "[HI] End Date",
+ "encoding": "[HI] Encoding",
+ "compression": "[HI] Compression",
+ "submitJob": "[HI] SUBMIT JOB",
+ "noBatchJobs": "[HI] No batch jobs found. Click + to create one.",
+ "records": "[HI] records",
+ "download": "[HI] Download",
+ "files": "[HI] FILES",
+ "jobsExpireNotice": "[HI] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[HI] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[HI] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[HI] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[HI] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[HI] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[HI] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[HI] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[HI] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[HI] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[HI] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[HI] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[HI] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[HI] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[HI] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[HI] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[HI] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[HI] [EN] common.or",
+ "note": "[HI] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/hi/tabs.json b/fincept-terminal-desktop/public/locales/hi/tabs.json
index af7ad2ee2..3c5b27249 100644
--- a/fincept-terminal-desktop/public/locales/hi/tabs.json
+++ b/fincept-terminal-desktop/public/locales/hi/tabs.json
@@ -5,29 +5,7 @@
"news": "समाचार",
"portfolio": "पोर्टफोलियो",
"backtesting": "बैकटेस्टिंग",
- "watchlist": "वॉचलिस्ट",
- "research": "रिसर्च",
- "screener": "स्क्रीनर",
"chat": "AI Chat",
- "agents": "एजेंट",
- "settings": "सेटिंग्स",
"profile": "प्रोफ़ाइल"
- },
- "functionKeys": {
- "f1": "डैश",
- "f2": "बाज़र",
- "f3": "समा",
- "f4": "पोर्ट",
- "f5": "बीटी",
- "f6": "वॉच",
- "f7": "रिसच",
- "f8": "स्क्रन",
- "f9": "ट्रेड",
- "f10": "AI",
- "f11": "फ़ुल",
- "f12": "प्रोफ"
- },
- "labels": {
- "moreTabs": "टूलबार मेन्यू में अधिक टैब"
}
}
diff --git a/fincept-terminal-desktop/public/locales/hi/watchlist.json b/fincept-terminal-desktop/public/locales/hi/watchlist.json
index 83ba9d3c6..e572a899e 100644
--- a/fincept-terminal-desktop/public/locales/hi/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/hi/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "वॉचलिस्ट",
- "header": {
- "export": "निर्यात",
- "updating": "अपडेट हो रहा है",
- "live": "लाइव"
- },
"sidebar": {
- "groups": "वॉचलिस्ट समूह",
- "new": "नया",
"noWatchlists": "अभी तक कोई वॉचलिस्ट नहीं।",
"clickNew": "बनाने के लिए नया क्लिक करें।",
- "stocks": "स्टॉक",
- "marketMovers": "मार्केट मूवर्स",
- "gainer": "गेनर",
- "loser": "लूज़र",
- "volumeLeaders": "वॉल्यूम लीडर्स"
- },
- "emptyState": {
- "selectWatchlist": "शुरू करने के लिए वॉचलिस्ट चुनें या नई बनाएं"
- },
- "list": {
- "symbols": "सिम्बल"
+ "stocks": "स्टॉक"
}
}
diff --git a/fincept-terminal-desktop/public/locales/id/codeEditor.json b/fincept-terminal-desktop/public/locales/id/codeEditor.json
index bbd888af0..fc655a12c 100644
--- a/fincept-terminal-desktop/public/locales/id/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/id/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "EDITOR KODE",
"header": {
- "packages": "PAKET"
+ "finscriptIde": "[ID] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "FILE BARU",
- "new": "BARU",
- "open": "BUKA",
- "save": "SIMPAN",
"run": "JALANKAN",
"running": "MENJALANKAN...",
- "runAll": "JALANKAN SEMUA",
- "history": "RIWAYAT"
+ "toggleExplorer": "[ID] Toggle Explorer (Ctrl+B)",
+ "openFile": "[ID] Open File",
+ "saveShortcut": "[ID] Save (Ctrl+S)",
+ "findShortcut": "[ID] Find (Ctrl+F)",
+ "runShortcut": "[ID] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "EDITOR FINSCRIPT"
},
- "packages": {
- "clickToLoad": "Klik untuk memuat...",
- "load": "MUAT PAKET"
+ "explorer": {
+ "title": "[ID] EXPLORER",
+ "openFiles": "[ID] OPEN FILES",
+ "examples": "[ID] EXAMPLES",
+ "runHistory": "[ID] RUN HISTORY",
+ "finscriptEngine": "[ID] FinScript Engine"
},
- "history": {
- "title": "RIWAYAT NOTEBOOK",
- "loading": "Memuat riwayat...",
- "empty": "Tidak ada riwayat notebook"
+ "output": {
+ "title": "[ID] OUTPUT",
+ "success": "[ID] SUCCESS",
+ "error": "[ID] ERROR",
+ "executing": "[ID] EXECUTING FINSCRIPT...",
+ "noOutput": "[ID] No output yet",
+ "pressToRun": "[ID] Press Ctrl+Enter to run",
+ "completed": "[ID] COMPLETED",
+ "failed": "[ID] FAILED",
+ "signals": "[ID] signals",
+ "clear": "[ID] CLEAR",
+ "errors": "[ID] ERRORS",
+ "signalsSection": "[ID] SIGNALS",
+ "outputSection": "[ID] OUTPUT",
+ "charts": "[ID] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[ID] OHLC",
+ "histogram": "[ID] Histogram",
+ "line": "[ID] Line",
+ "points": "[ID] points"
+ },
+ "statusBar": {
+ "modified": "[ID] MODIFIED",
+ "showOutput": "[ID] SHOW OUTPUT",
+ "encoding": "[ID] UTF-8",
+ "spaces": "[ID] 4 Spaces",
+ "runShortcut": "[ID] Ctrl+Enter: Run",
+ "lines": "[ID] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[ID] Close file without saving?",
+ "unsavedChanges": "[ID] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/id/common.json b/fincept-terminal-desktop/public/locales/id/common.json
index efa38b047..3132e0716 100644
--- a/fincept-terminal-desktop/public/locales/id/common.json
+++ b/fincept-terminal-desktop/public/locales/id/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Memuat...",
- "error": "Kesalahan",
- "success": "Berhasil",
- "save": "Simpan",
- "cancel": "Batal",
- "delete": "Hapus",
- "edit": "Edit",
- "add": "Tambah",
- "search": "Cari",
- "filter": "Filter",
- "back": "Kembali",
- "next": "Lanjut",
- "previous": "Sebelumnya",
- "submit": "Kirim",
- "close": "Tutup",
- "open": "Buka",
- "yes": "Ya",
- "no": "Tidak",
- "ok": "OK",
- "confirm": "Konfirmasi",
- "language": "Bahasa",
- "selectLanguage": "Pilih bahasa"
-}
\ No newline at end of file
+ "settings": "[ID] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/id/dashboard.json b/fincept-terminal-desktop/public/locales/id/dashboard.json
index af4454cd3..1996f7f77 100644
--- a/fincept-terminal-desktop/public/locales/id/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/id/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "DAsbor yang dapat disesuaikan",
- "live": "HIDUP",
- "widgets": "WIDGET"
- },
- "buttons": {
- "addWidget": "TAMBAHKAN WIDGET",
- "saveLayout": "SIMPAN TATA LETAK",
- "reset": "MENGATUR ULANG",
- "help": "MEMBANTU"
- },
"widgets": {
"loading": "Memuat...",
- "error": "Kesalahan",
"globalIndices": "Indeks Global - 12 Teratas",
"forex": "Forex - Pasangan Utama",
"crypto": "MATA UANG KRIPTO",
@@ -20,8 +8,6 @@
"news": "BERITA",
"forum": "FORUM",
"watchlist": "DAFTAR PERHATIAN",
- "maritimeIntelligence": "Intelijen Maritim",
- "unknown": "Jenis widget tidak diketahui",
"index": "INDEKS",
"symbol": "SIMBOL",
"price": "HARGA",
@@ -38,41 +24,22 @@
"pair": "PASANGAN",
"rate": "KECEPATAN",
"commodity": "KOMODITI",
- "globe3D": "DUNIA 3D",
- "vessels": "KAPAL",
- "routes": "RUTE",
- "vol24h": "VOL 24JAM",
- "topTradeCorridors": "KORIDOR PERDAGANGAN TERATAS",
- "ships": "kapal",
- "marketNews": "Berita Pasar",
- "secPressReleases": "Siaran Pers SEC",
- "cryptoNews": "Berita Kripto",
- "trendingForum": "Forum Tren",
- "techStocks": "Saham Teknologi"
- },
- "tips": {
- "drag": "Seret widget untuk mengatur ulang",
- "resize": "Ubah ukuran dari sudut kanan bawah",
- "remove": "Hapus widget dengan tombol X",
- "responsive": "Tata letak responsif - menggunakan lebar penuh"
- },
- "loading": {
- "title": "Inisialisasi Dasbor",
- "description": "Menyiapkan cache database untuk memuat data lebih cepat...",
- "note": "Ini hanya akan memakan waktu beberapa saat pada peluncuran pertama"
- },
- "empty": {
- "noWidgets": "Tidak ada widget di dasbor",
- "addFirst": "TAMBAHKAN WIDGET PERTAMA ANDA"
- },
- "status": {
- "version": "Dasbor Fincept yang Dapat Disesuaikan v2.0.0 | Seret & lepas ruang kerja",
- "layout": "Tata Letak",
- "custom": "Kebiasaan",
- "empty": "Kosong",
- "active": "AKTIF",
- "cache": "Tembolok: DIAKTIFKAN",
- "label": "Status"
+ "noActiveMarkets": "[ID] No active markets found",
+ "indicator": "[ID] INDICATOR",
+ "value": "[ID] VALUE",
+ "chg": "[ID] CHG",
+ "overallRisk": "[ID] OVERALL RISK",
+ "openEconomicsTab": "[ID] Open Economics Tab",
+ "openGeopoliticsTab": "[ID] Open Geopolitics Tab",
+ "openPolymarketTab": "[ID] Open Polymarket Tab",
+ "noPortfolioFound": "[ID] No portfolio found",
+ "createPortfolioHint": "[ID] Create one in Portfolio tab",
+ "openPortfolioTab": "[ID] Open Portfolio Tab",
+ "action": "[ID] ACTION",
+ "markets": "[ID] MARKETS",
+ "performanceTracker": "[ID] PERFORMANCE TRACKER",
+ "totalPnL": "[ID] TOTAL P&L",
+ "viewDetailedAnalytics": "[ID] View Detailed Analytics"
},
"messages": {
"layoutSaved": "Tata letak dasbor disimpan!",
diff --git a/fincept-terminal-desktop/public/locales/id/geopolitics.json b/fincept-terminal-desktop/public/locales/id/geopolitics.json
index 6f590136e..2705ddf77 100644
--- a/fincept-terminal-desktop/public/locales/id/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/id/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "GEOPOLITIK",
"messages": {
- "loading": "Memuat data..."
+ "retry": "[ID] RETRY"
+ },
+ "header": {
+ "prefix": "[ID] GEO>",
+ "title": "[ID] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[ID] EVENTS"
+ },
+ "status": {
+ "stale": "[ID] STALE",
+ "loading": "[ID] LOADING...",
+ "error": "[ID] ERROR:"
+ },
+ "filters": {
+ "country": "[ID] Country...",
+ "cities": "[ID] Cities...",
+ "category": "[ID] Category...",
+ "apply": "[ID] APPLY",
+ "clear": "[ID] CLEAR",
+ "clearAllCities": "[ID] Clear all cities",
+ "selectedLabel": "[ID] Selected:"
+ },
+ "panel": {
+ "title": "[ID] INFO PANEL",
+ "expand": "[ID] Expand panel",
+ "collapse": "[ID] Collapse panel",
+ "eventsLoaded": "[ID] EVENTS LOADED",
+ "onMapVisualization": "[ID] on map visualization",
+ "topCategories": "[ID] TOP CATEGORIES",
+ "topCountries": "[ID] TOP COUNTRIES",
+ "eventDetails": "[ID] EVENT DETAILS",
+ "close": "[ID] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[ID] Country:",
+ "city": "[ID] City:",
+ "keywords": "[ID] Keywords:",
+ "coords": "[ID] Coords:",
+ "date": "[ID] Date:",
+ "source": "[ID] Source:",
+ "viewArticle": "[ID] View Article"
+ },
+ "legend": {
+ "title": "[ID] EVENT CATEGORIES",
+ "armedConflict": "[ID] Armed Conflict",
+ "terrorism": "[ID] Terrorism",
+ "protests": "[ID] Protests",
+ "civilianViolence": "[ID] Civilian Violence",
+ "riots": "[ID] Riots",
+ "politicalViolence": "[ID] Political Violence",
+ "crisis": "[ID] Crisis",
+ "explosions": "[ID] Explosions",
+ "strategic": "[ID] Strategic",
+ "unclassified": "[ID] Unclassified"
+ },
+ "footer": {
+ "tabName": "[ID] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[ID] EVENTS",
+ "labelEngine": "[ID] ENGINE",
+ "engineValue": "[ID] DECK.GL v9.2",
+ "labelSource": "[ID] SOURCE",
+ "sourceValue": "[ID] NEWS-EVENTS API",
+ "labelSelected": "[ID] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/id/markets.json b/fincept-terminal-desktop/public/locales/id/markets.json
index 09596c2fe..304c9444e 100644
--- a/fincept-terminal-desktop/public/locales/id/markets.json
+++ b/fincept-terminal-desktop/public/locales/id/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%UBH",
"high": "TINGGI",
"low": "RENDAH",
- "loading": "Memuat...",
"noData": "Tidak ada data tersedia",
"refresh": "SEGARKAN",
"auto": "OTOMATIS",
"on": "AKTIF",
- "off": "MATI",
- "lastUpdate": "UPDATE TERAKHIR",
- "updating": "MEMPERBARUI",
- "live": "LANGSUNG"
+ "off": "MATI"
}
diff --git a/fincept-terminal-desktop/public/locales/id/news.json b/fincept-terminal-desktop/public/locales/id/news.json
index 7a9a54dcb..333a2be71 100644
--- a/fincept-terminal-desktop/public/locales/id/news.json
+++ b/fincept-terminal-desktop/public/locales/id/news.json
@@ -1,32 +1,63 @@
{
"title": "BERITA PROFESIONAL TERMINAL FINCEPT",
"header": {
- "liveFeed": "FEED LANGSUNG",
- "live": "LANGSUNG",
- "refresh": "SEGARKAN",
- "updating": "MEMPERBARUI...",
- "alerts": "PERINGATAN",
- "sources": "SUMBER",
- "status": "STATUS",
- "demoMode": "MODE DEMO",
- "articles": "ARTIKEL",
- "activeSources": "SUMBER AKTIF"
- },
- "autoRefresh": {
- "title": "INTERVAL PEMBARUAN OTOMATIS",
- "minute": "menit",
- "minutes": "menit"
+ "refresh": "SEGARKAN"
},
"messages": {
- "loadingFeeds": "Memuat feed berita...",
- "breaking": "BREAKING"
- },
- "feeds": {
- "primary": "[ID] PRIMARY NEWS FEED",
- "secondary": "[ID] SECONDARY NEWS FEED",
- "additional": "[ID] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[ID] Loading feeds...",
+ "failedToLoad": "[ID] Failed to load RSS feeds",
+ "noCustomFeeds": "[ID] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[ID] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[ID] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[ID] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[ID] RSS FEED SETTINGS",
+ "subtitle": "[ID] MANAGE YOUR NEWS SOURCES",
+ "close": "[ID] CLOSE",
+ "myFeeds": "[ID] MY FEEDS",
+ "defaultFeeds": "[ID] DEFAULT FEEDS",
+ "noFeedsAvailable": "[ID] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[ID] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[ID] ADD NEW FEED",
+ "addNewRssFeed": "[ID] ADD NEW RSS FEED",
+ "editRssFeed": "[ID] EDIT RSS FEED",
+ "restoreDefaults": "[ID] RESTORE DEFAULTS",
+ "restoreAll": "[ID] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[ID] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[ID] DISPLAY NAME",
+ "sourceName": "[ID] SOURCE NAME (SHORT)",
+ "feedUrl": "[ID] RSS FEED URL",
+ "category": "[ID] CATEGORY",
+ "region": "[ID] REGION",
+ "required": "[ID] *",
+ "testUrl": "[ID] TEST URL",
+ "testing": "[ID] TESTING...",
+ "valid": "[ID] VALID",
+ "cancel": "[ID] CANCEL",
+ "saving": "[ID] SAVING...",
+ "addFeed": "[ID] ADD FEED",
+ "updateFeed": "[ID] UPDATE FEED",
+ "on": "[ID] ON",
+ "off": "[ID] OFF",
+ "default": "[ID] DEFAULT",
+ "total": "[ID] TOTAL",
+ "active": "[ID] ACTIVE",
+ "custom": "[ID] CUSTOM",
+ "placeholders": {
+ "displayName": "[ID] e.g., Bloomberg Markets",
+ "sourceName": "[ID] e.g., BLOOMBERG",
+ "feedUrl": "[ID] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[ID] Name is required",
+ "sourceRequired": "[ID] Source name is required",
+ "invalidUrl": "[ID] Please enter a valid URL",
+ "invalidRss": "[ID] URL does not appear to be a valid RSS feed",
+ "testFailed": "[ID] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[ID] Delete this RSS feed?",
+ "message": "[ID] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/id/portfolio.json b/fincept-terminal-desktop/public/locales/id/portfolio.json
index 1f48a0b6a..d974ebdde 100644
--- a/fincept-terminal-desktop/public/locales/id/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/id/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "MANAJER PORTOFOLIO FINCEPT",
- "header": {
- "live": "LANGSUNG",
- "updating": "MEMPERBARUI",
- "newPortfolio": "PORTOFOLIO BARU",
- "refresh": "SEGARKAN",
- "exportCsv": "EKSPOR CSV"
- },
- "summary": {
- "totalValue": "TOTAL NILAI",
- "dayPnl": "P&L HARI INI",
- "totalPnl": "TOTAL P&L",
- "positions": "POSISI"
- },
- "views": {
- "positions": "POSISI",
- "addAsset": "TAMBAH ASET",
- "sellAsset": "JUAL ASET",
- "analytics": "ANALITIK",
- "history": "RIWAYAT",
- "activeMgmt": "MANAJEMEN AKTIF",
- "performance": "KINERJA",
- "rebalance": "REBALANCE",
- "reports": "LAPORAN",
- "alerts": "PERINGATAN",
- "sectors": "SEKTOR",
- "help": "BANTUAN"
- },
- "sidebar": {
- "portfolios": "PORTOFOLIO",
- "loading": "Memuat portofolio...",
- "noPortfolios": "Belum ada portofolio.",
- "clickCreate": "Klik PORTOFOLIO BARU untuk membuat.",
- "owner": "Pemilik",
- "currency": "Mata Uang"
- },
- "content": {
- "selectOrCreate": "Pilih portofolio atau buat yang baru untuk memulai",
- "loadingData": "Memuat data portofolio...",
- "comingSoon": "tampilan segera hadir..."
- },
- "modals": {
- "createNew": "BUAT PORTOFOLIO BARU",
- "portfolioName": "NAMA PORTOFOLIO",
- "owner": "PEMILIK",
- "currency": "MATA UANG",
- "cancel": "BATAL",
- "create": "BUAT",
- "addAssetTitle": "TAMBAH ASET KE PORTOFOLIO",
- "sellAssetTitle": "JUAL ASET",
- "symbol": "SIMBOL",
- "quantity": "KUANTITAS",
- "price": "HARGA",
- "add": "TAMBAH",
- "sell": "JUAL"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Pelacakan real-time dengan integrasi yfinance",
- "lastUpdated": "Terakhir Diperbarui",
- "connected": "TERHUBUNG"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "BUAT PORTOFOLIO BARU",
+ "portfolioName": "NAMA PORTOFOLIO",
+ "owner": "PEMILIK",
+ "currency": "MATA UANG",
+ "cancel": "BATAL",
+ "create": "BUAT",
+ "addAssetTitle": "TAMBAH ASET KE PORTOFOLIO",
+ "sellAssetTitle": "JUAL ASET",
+ "symbol": "SIMBOL",
+ "quantity": "KUANTITAS",
+ "price": "HARGA",
+ "add": "TAMBAH",
+ "sell": "JUAL"
+ },
+ "extracted": {
+ "areYouSureYou": "[ID] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/id/reportBuilder.json b/fincept-terminal-desktop/public/locales/id/reportBuilder.json
index a9eeef4b7..c8806dbd1 100644
--- a/fincept-terminal-desktop/public/locales/id/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/id/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[ID] Load",
"save": "[ID] Save",
- "saving": "[ID] Saving...",
- "exportPdf": "[ID] Export PDF",
- "generating": "[ID] Generating..."
+ "saving": "[ID] Saving..."
},
"components": {
"title": "[ID] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/id/settings.json b/fincept-terminal-desktop/public/locales/id/settings.json
index 45c14a87d..b40176bed 100644
--- a/fincept-terminal-desktop/public/locales/id/settings.json
+++ b/fincept-terminal-desktop/public/locales/id/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Tata Letak Tab",
"appearance": "Penampilan",
"language": "Bahasa",
- "storage": "Penyimpanan & Cache"
+ "storage": "Penyimpanan & Cache",
+ "notifications": "[ID] Notifications"
},
"credentials": {
"title": "MANAJEMEN KREDENSIAL API",
@@ -46,7 +47,31 @@
"saveConfig": "SIMPAN KONFIGURASI",
"reset": "MENGATUR ULANG",
"saveSuccess": "Tampilan terminal dan pemetaan kunci berhasil disimpan",
- "resetSuccess": "Reset ke tampilan default dan pemetaan kunci"
+ "resetSuccess": "Reset ke tampilan default dan pemetaan kunci",
+ "customColors": "[ID] Custom Colors",
+ "customColorsTitle": "[ID] CUSTOM COLORS",
+ "colorPrimary": "[ID] Primary",
+ "colorSecondary": "[ID] Secondary",
+ "colorSuccess": "[ID] Success",
+ "colorAlert": "[ID] Alert",
+ "colorWarning": "[ID] Warning",
+ "colorInfo": "[ID] Info",
+ "colorAccent": "[ID] Accent",
+ "colorPurple": "[ID] Purple",
+ "colorText": "[ID] Text",
+ "colorTextMuted": "[ID] Text Muted",
+ "colorBackground": "[ID] Background",
+ "colorPanel": "[ID] Panel",
+ "layoutSpacing": "[ID] LAYOUT & SPACING",
+ "contentDensity": "[ID] CONTENT DENSITY",
+ "borderRadius": "[ID] BORDER RADIUS",
+ "borderStyle": "[ID] BORDER STYLE",
+ "lineHeight": "[ID] LINE HEIGHT",
+ "letterSpacing": "[ID] LETTER SPACING",
+ "effects": "[ID] EFFECTS",
+ "widgetOpacity": "[ID] WIDGET OPACITY",
+ "enableGlow": "[ID] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[ID] GLOW INTENSITY"
},
"stockSymbols": {
"title": "Basis Data Simbol Saham",
@@ -65,17 +90,8 @@
"tip": "TIPS: Seret tab untuk menyusun ulang tab. Gunakan tombol panah untuk memindahkan tab antara header dan bagian menu. Perubahan disimpan secara otomatis."
},
"llm": {
- "title": "KONFIGURASI LLM",
- "description": "Konfigurasikan model dan penyedia AI",
"connected": "TERHUBUNG",
- "disconnected": "TERHUBUNG",
- "provider": "PENYEDIA AI",
- "globalSettings": "PENGATURAN AI GLOBAL",
- "temperature": "SUHU",
- "maxTokens": "TOKEN MAKS",
- "systemPrompt": "PERINTAH SISTEM",
- "modelLibrary": "PERPUSTAKAAN MODEL",
- "multiModelConfigs": "Konfigurasi multi-model"
+ "disconnected": "TERHUBUNG"
},
"buttons": {
"save": "MENYIMPAN",
@@ -86,5 +102,18 @@
"database": "Basis Data: SQLite",
"storage": "Penyimpanan: Berbasis file",
"secureStorage": "Semua data disimpan dengan aman di fincept_terminal.db"
+ },
+ "notifications": {
+ "title": "[ID] NOTIFICATION PROVIDERS",
+ "description": "[ID] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[ID] Event Filters",
+ "eventFilterDescription": "[ID] Choose which notification types to forward to external providers.",
+ "providers": "[ID] Providers",
+ "enabled": "[ID] Enabled",
+ "disabled": "[ID] Disabled",
+ "testButton": "[ID] TEST",
+ "testSuccess": "[ID] Test notification sent successfully!",
+ "testFailed": "[ID] Failed to send test notification. Check your configuration.",
+ "saved": "[ID] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/id/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/id/surfaceAnalytics.json
new file mode 100644
index 000000000..444d193dd
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/id/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[ID] SURFACE ANALYTICS",
+ "initializing": "[ID] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[ID] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[ID] VOL SURFACE",
+ "correlation": "[ID] CORRELATION",
+ "yieldCurve": "[ID] YIELD CURVE",
+ "pca": "[ID] PCA FACTORS"
+ },
+ "demoData": "[ID] DEMO DATA",
+ "demoDataSynthetic": "[ID] DEMO DATA (synthetic)",
+ "synthetic": "[ID] SYNTHETIC",
+ "manual": "[ID] MANUAL",
+ "error": "[ID] ERROR",
+ "ready": "[ID] READY",
+ "metrics": "[ID] Metrics",
+ "updated": "[ID] Updated",
+ "clickRefresh": "[ID] Click REFRESH to load data",
+ "refresh": "[ID] REFRESH",
+ "noApiKey": "[ID] NO API KEY",
+ "lastUpdate": "[ID] LAST UPDATE",
+ "loadingData": "[ID] LOADING DATA...",
+ "noDataLoaded": "[ID] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[ID] IV SURFACE METRICS",
+ "correlationMetrics": "[ID] CORRELATION METRICS",
+ "yieldCurveMetrics": "[ID] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[ID] PCA FACTOR METRICS",
+ "dataInfo": "[ID] DATA INFO",
+ "source": "[ID] SOURCE",
+ "frequency": "[ID] FREQUENCY",
+ "quality": "[ID] QUALITY",
+ "correlationScale": "[ID] CORRELATION SCALE",
+ "strongPositive": "[ID] Strong Positive (0.7-1.0)",
+ "neutral": "[ID] Neutral (0.3-0.7)",
+ "strongNegative": "[ID] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[ID] IV INTERPRETATION",
+ "highIv": "[ID] High IV = Expensive Options",
+ "lowIv": "[ID] Low IV = Cheap Options",
+ "skew": "[ID] Skew = Put/Call IV Diff",
+ "termStructure": "[ID] Term Structure = Time Effect",
+ "pcaInterpretation": "[ID] PCA INTERPRETATION",
+ "pc1": "[ID] PC1 = Market Factor",
+ "pc2": "[ID] PC2 = Size/Value Factor",
+ "pc3": "[ID] PC3 = Sector Rotation",
+ "higherVar": "[ID] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[ID] STRIKE",
+ "dte": "[ID] DTE",
+ "iv": "[ID] IV",
+ "correlation": "[ID] CORRELATION",
+ "maturity": "[ID] MATURITY",
+ "yield": "[ID] YIELD",
+ "loading": "[ID] LOADING",
+ "strikePrice": "[ID] STRIKE PRICE",
+ "daysToExpiry": "[ID] DAYS TO EXPIRY",
+ "impliedVol": "[ID] IMPLIED VOL (%)",
+ "assetPairIndex": "[ID] ASSET PAIR INDEX",
+ "timeDays": "[ID] TIME (DAYS)",
+ "correlationCoeff": "[ID] CORRELATION COEFF",
+ "maturityMonths": "[ID] MATURITY (MONTHS)",
+ "historicalDays": "[ID] HISTORICAL DAYS",
+ "yieldPercent": "[ID] YIELD (%)",
+ "principalComponent": "[ID] PRINCIPAL COMPONENT",
+ "assetIndex": "[ID] ASSET INDEX",
+ "factorLoading": "[ID] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[ID] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[ID] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[ID] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[ID] DAY ROLLING",
+ "yieldCurve": "[ID] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[ID] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[ID] FAILED TO LOAD DATA",
+ "authFailed": "[ID] AUTHENTICATION FAILED",
+ "authFailedHelp": "[ID] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[ID] ACCESS DENIED",
+ "accessDeniedHelp": "[ID] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[ID] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[ID] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[ID] DATA TIMEFRAME",
+ "schema": "[ID] Schema",
+ "description": "[ID] Description",
+ "recordsPerDay": "[ID] Records/Day",
+ "highFrequencyWarning": "[ID] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[ID] Data Volume"
+ },
+ "settings": {
+ "title": "[ID] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[ID] DATABENTO API KEY",
+ "configured": "[ID] CONFIGURED",
+ "invalidFormat": "[ID] INVALID FORMAT",
+ "apiKeyConfigured": "[ID] API key is configured (db-*****)",
+ "remove": "[ID] REMOVE",
+ "enterApiKey": "[ID] Enter your Databento API key (db-*****)",
+ "save": "[ID] SAVE",
+ "saving": "[ID] SAVING...",
+ "getApiKeyFrom": "[ID] Get your API key from",
+ "dashboardApiKeys": "[ID] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[ID] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[ID] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[ID] CORRELATION ASSETS",
+ "addSymbol": "[ID] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[ID] Reset to defaults",
+ "historicalDateRange": "[ID] HISTORICAL DATE RANGE",
+ "start": "[ID] Start",
+ "end": "[ID] End",
+ "autoRefreshInterval": "[ID] AUTO REFRESH INTERVAL",
+ "manualOnly": "[ID] Manual Only",
+ "every1min": "[ID] Every 1 minute",
+ "every5min": "[ID] Every 5 minutes",
+ "every15min": "[ID] Every 15 minutes",
+ "every1hour": "[ID] Every 1 hour",
+ "browseDatasets": "[ID] BROWSE DATASETS",
+ "costEstimator": "[ID] COST ESTIMATOR",
+ "referenceData": "[ID] REFERENCE DATA",
+ "orderBook": "[ID] ORDER BOOK",
+ "liveStreaming": "[ID] LIVE STREAMING",
+ "active": "[ID] ACTIVE",
+ "futuresCme": "[ID] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[ID] BATCH DOWNLOADS",
+ "additionalSchemas": "[ID] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[ID] TRADES, IMBALANCE, STATUS",
+ "cancel": "[ID] CANCEL",
+ "saveChanges": "[ID] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[ID] BATCH DOWNLOADS",
+ "newBatchJob": "[ID] NEW BATCH JOB",
+ "dataset": "[ID] Dataset",
+ "schema": "[ID] Schema",
+ "symbolsCommaSeparated": "[ID] Symbols (comma-separated)",
+ "startDate": "[ID] Start Date",
+ "endDate": "[ID] End Date",
+ "encoding": "[ID] Encoding",
+ "compression": "[ID] Compression",
+ "submitJob": "[ID] SUBMIT JOB",
+ "noBatchJobs": "[ID] No batch jobs found. Click + to create one.",
+ "records": "[ID] records",
+ "download": "[ID] Download",
+ "files": "[ID] FILES",
+ "jobsExpireNotice": "[ID] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[ID] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[ID] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[ID] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[ID] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[ID] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[ID] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[ID] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[ID] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[ID] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[ID] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[ID] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[ID] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[ID] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[ID] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[ID] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[ID] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[ID] [EN] common.or",
+ "note": "[ID] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/id/tabs.json b/fincept-terminal-desktop/public/locales/id/tabs.json
index 1ce652302..cba937e7c 100644
--- a/fincept-terminal-desktop/public/locales/id/tabs.json
+++ b/fincept-terminal-desktop/public/locales/id/tabs.json
@@ -5,29 +5,7 @@
"news": "Berita",
"portfolio": "Portofolio",
"backtesting": "Backtesting",
- "watchlist": "Watchlist",
- "research": "Riset",
- "screener": "Screener",
"chat": "AI Chat",
- "agents": "Agen",
- "settings": "Pengaturan",
"profile": "Profil"
- },
- "functionKeys": {
- "f1": "DASH",
- "f2": "PRSR",
- "f3": "BRTA",
- "f4": "PORT",
- "f5": "BKTS",
- "f6": "WTCH",
- "f7": "RSRT",
- "f8": "SCRN",
- "f9": "TRDG",
- "f10": "AI",
- "f11": "FULL",
- "f12": "PROF"
- },
- "labels": {
- "moreTabs": "Tab lainnya di menu toolbar"
}
}
diff --git a/fincept-terminal-desktop/public/locales/id/watchlist.json b/fincept-terminal-desktop/public/locales/id/watchlist.json
index d4d1519f9..40b3e726b 100644
--- a/fincept-terminal-desktop/public/locales/id/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/id/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "DAFTAR PANTAU",
- "header": {
- "export": "EKSPOR",
- "updating": "MEMPERBARUI",
- "live": "LANGSUNG"
- },
"sidebar": {
- "groups": "GRUP DAFTAR PANTAU",
- "new": "BARU",
"noWatchlists": "Belum ada daftar pantau.",
"clickNew": "Klik BARU untuk membuat.",
- "stocks": "saham",
- "marketMovers": "PENGGERAK PASAR",
- "gainer": "NAIK",
- "loser": "TURUN",
- "volumeLeaders": "VOLUME TERTINGGI"
- },
- "emptyState": {
- "selectWatchlist": "Pilih daftar pantau atau buat yang baru untuk memulai"
- },
- "list": {
- "symbols": "Simbol"
+ "stocks": "saham"
}
}
diff --git a/fincept-terminal-desktop/public/locales/it/codeEditor.json b/fincept-terminal-desktop/public/locales/it/codeEditor.json
index 674ad9a95..fa5345567 100644
--- a/fincept-terminal-desktop/public/locales/it/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/it/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "EDITOR CODICE",
"header": {
- "packages": "PACCHETTI"
+ "finscriptIde": "[IT] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "NUOVO FILE",
- "new": "NUOVO",
- "open": "APRI",
- "save": "SALVA",
"run": "ESEGUI",
"running": "IN ESECUZIONE...",
- "runAll": "ESEGUI TUTTO",
- "history": "CRONOLOGIA"
+ "toggleExplorer": "[IT] Toggle Explorer (Ctrl+B)",
+ "openFile": "[IT] Open File",
+ "saveShortcut": "[IT] Save (Ctrl+S)",
+ "findShortcut": "[IT] Find (Ctrl+F)",
+ "runShortcut": "[IT] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "EDITOR FINSCRIPT"
},
- "packages": {
- "clickToLoad": "Clicca per caricare...",
- "load": "CARICA PACCHETTI"
+ "explorer": {
+ "title": "[IT] EXPLORER",
+ "openFiles": "[IT] OPEN FILES",
+ "examples": "[IT] EXAMPLES",
+ "runHistory": "[IT] RUN HISTORY",
+ "finscriptEngine": "[IT] FinScript Engine"
},
- "history": {
- "title": "CRONOLOGIA NOTEBOOK",
- "loading": "Caricamento cronologia...",
- "empty": "Nessuna cronologia notebook"
+ "output": {
+ "title": "[IT] OUTPUT",
+ "success": "[IT] SUCCESS",
+ "error": "[IT] ERROR",
+ "executing": "[IT] EXECUTING FINSCRIPT...",
+ "noOutput": "[IT] No output yet",
+ "pressToRun": "[IT] Press Ctrl+Enter to run",
+ "completed": "[IT] COMPLETED",
+ "failed": "[IT] FAILED",
+ "signals": "[IT] signals",
+ "clear": "[IT] CLEAR",
+ "errors": "[IT] ERRORS",
+ "signalsSection": "[IT] SIGNALS",
+ "outputSection": "[IT] OUTPUT",
+ "charts": "[IT] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[IT] OHLC",
+ "histogram": "[IT] Histogram",
+ "line": "[IT] Line",
+ "points": "[IT] points"
+ },
+ "statusBar": {
+ "modified": "[IT] MODIFIED",
+ "showOutput": "[IT] SHOW OUTPUT",
+ "encoding": "[IT] UTF-8",
+ "spaces": "[IT] 4 Spaces",
+ "runShortcut": "[IT] Ctrl+Enter: Run",
+ "lines": "[IT] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[IT] Close file without saving?",
+ "unsavedChanges": "[IT] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/it/common.json b/fincept-terminal-desktop/public/locales/it/common.json
index 4eaa5df03..5424092c0 100644
--- a/fincept-terminal-desktop/public/locales/it/common.json
+++ b/fincept-terminal-desktop/public/locales/it/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Caricamento...",
- "error": "Errore",
- "success": "Successo",
- "save": "Salva",
- "cancel": "Annulla",
- "delete": "Elimina",
- "edit": "Modifica",
- "add": "Aggiungi",
- "search": "Cerca",
- "filter": "Filtra",
- "back": "Indietro",
- "next": "Avanti",
- "previous": "Precedente",
- "submit": "Invia",
- "close": "Chiudi",
- "open": "Apri",
- "yes": "Sì",
- "no": "No",
- "ok": "OK",
- "confirm": "Conferma",
- "language": "Lingua",
- "selectLanguage": "Seleziona lingua"
-}
\ No newline at end of file
+ "settings": "[IT] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/it/dashboard.json b/fincept-terminal-desktop/public/locales/it/dashboard.json
index 540caf581..a771c265c 100644
--- a/fincept-terminal-desktop/public/locales/it/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/it/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "CRUSCOTTO PERSONALIZZABILE",
- "live": "VIVERE",
- "widgets": "WIDGET"
- },
- "buttons": {
- "addWidget": "AGGIUNGI WIDGET",
- "saveLayout": "SALVA LAYOUT",
- "reset": "RESET",
- "help": "AIUTO"
- },
"widgets": {
"loading": "Caricamento...",
- "error": "Errore",
"globalIndices": "Indici globali - Primi 12",
"forex": "Forex - Coppie principali",
"crypto": "CRIPTOVALUTE",
@@ -20,8 +8,6 @@
"news": "NOTIZIA",
"forum": "FORO",
"watchlist": "LISTA DEI PREFERITI",
- "maritimeIntelligence": "Intelligenza marittima",
- "unknown": "Tipo di widget sconosciuto",
"index": "INDICE",
"symbol": "SIMBOLO",
"price": "PREZZO",
@@ -38,41 +24,22 @@
"pair": "PAIO",
"rate": "VALUTARE",
"commodity": "MERCE",
- "globe3D": "GLOBO 3D",
- "vessels": "VASI",
- "routes": "PERCORSI",
- "vol24h": "VOLUME 24 ORE",
- "topTradeCorridors": "I MIGLIORI CORRIDOI COMMERCIALI",
- "ships": "navi",
- "marketNews": "Notizie di mercato",
- "secPressReleases": "Comunicati stampa della SEC",
- "cryptoNews": "Notizie sulle criptovalute",
- "trendingForum": "Forum di tendenza",
- "techStocks": "Titoli tecnologici"
- },
- "tips": {
- "drag": "Trascina i widget per riorganizzarli",
- "resize": "Ridimensiona dall'angolo in basso a destra",
- "remove": "Rimuovi i widget con il pulsante X",
- "responsive": "Layout reattivo: utilizza l'intera larghezza"
- },
- "loading": {
- "title": "Inizializzazione del dashboard",
- "description": "Configurazione della cache del database per un caricamento più rapido dei dati...",
- "note": "Ciò richiederà solo un momento al primo avvio"
- },
- "empty": {
- "noWidgets": "Nessun widget sulla dashboard",
- "addFirst": "AGGIUNGI IL TUO PRIMO WIDGET"
- },
- "status": {
- "version": "Dashboard personalizzabile Fincept v2.0.0 | Trascina e rilascia l'area di lavoro",
- "layout": "Disposizione",
- "custom": "Costume",
- "empty": "Vuoto",
- "active": "ATTIVO",
- "cache": "Cache: ABILITATA",
- "label": "Stato"
+ "noActiveMarkets": "[IT] No active markets found",
+ "indicator": "[IT] INDICATOR",
+ "value": "[IT] VALUE",
+ "chg": "[IT] CHG",
+ "overallRisk": "[IT] OVERALL RISK",
+ "openEconomicsTab": "[IT] Open Economics Tab",
+ "openGeopoliticsTab": "[IT] Open Geopolitics Tab",
+ "openPolymarketTab": "[IT] Open Polymarket Tab",
+ "noPortfolioFound": "[IT] No portfolio found",
+ "createPortfolioHint": "[IT] Create one in Portfolio tab",
+ "openPortfolioTab": "[IT] Open Portfolio Tab",
+ "action": "[IT] ACTION",
+ "markets": "[IT] MARKETS",
+ "performanceTracker": "[IT] PERFORMANCE TRACKER",
+ "totalPnL": "[IT] TOTAL P&L",
+ "viewDetailedAnalytics": "[IT] View Detailed Analytics"
},
"messages": {
"layoutSaved": "Layout della dashboard salvato!",
diff --git a/fincept-terminal-desktop/public/locales/it/geopolitics.json b/fincept-terminal-desktop/public/locales/it/geopolitics.json
index b38283fb4..36ce35047 100644
--- a/fincept-terminal-desktop/public/locales/it/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/it/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "GEOPOLITICA",
"messages": {
- "loading": "Caricamento dati..."
+ "retry": "[IT] RETRY"
+ },
+ "header": {
+ "prefix": "[IT] GEO>",
+ "title": "[IT] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[IT] EVENTS"
+ },
+ "status": {
+ "stale": "[IT] STALE",
+ "loading": "[IT] LOADING...",
+ "error": "[IT] ERROR:"
+ },
+ "filters": {
+ "country": "[IT] Country...",
+ "cities": "[IT] Cities...",
+ "category": "[IT] Category...",
+ "apply": "[IT] APPLY",
+ "clear": "[IT] CLEAR",
+ "clearAllCities": "[IT] Clear all cities",
+ "selectedLabel": "[IT] Selected:"
+ },
+ "panel": {
+ "title": "[IT] INFO PANEL",
+ "expand": "[IT] Expand panel",
+ "collapse": "[IT] Collapse panel",
+ "eventsLoaded": "[IT] EVENTS LOADED",
+ "onMapVisualization": "[IT] on map visualization",
+ "topCategories": "[IT] TOP CATEGORIES",
+ "topCountries": "[IT] TOP COUNTRIES",
+ "eventDetails": "[IT] EVENT DETAILS",
+ "close": "[IT] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[IT] Country:",
+ "city": "[IT] City:",
+ "keywords": "[IT] Keywords:",
+ "coords": "[IT] Coords:",
+ "date": "[IT] Date:",
+ "source": "[IT] Source:",
+ "viewArticle": "[IT] View Article"
+ },
+ "legend": {
+ "title": "[IT] EVENT CATEGORIES",
+ "armedConflict": "[IT] Armed Conflict",
+ "terrorism": "[IT] Terrorism",
+ "protests": "[IT] Protests",
+ "civilianViolence": "[IT] Civilian Violence",
+ "riots": "[IT] Riots",
+ "politicalViolence": "[IT] Political Violence",
+ "crisis": "[IT] Crisis",
+ "explosions": "[IT] Explosions",
+ "strategic": "[IT] Strategic",
+ "unclassified": "[IT] Unclassified"
+ },
+ "footer": {
+ "tabName": "[IT] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[IT] EVENTS",
+ "labelEngine": "[IT] ENGINE",
+ "engineValue": "[IT] DECK.GL v9.2",
+ "labelSource": "[IT] SOURCE",
+ "sourceValue": "[IT] NEWS-EVENTS API",
+ "labelSelected": "[IT] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/it/markets.json b/fincept-terminal-desktop/public/locales/it/markets.json
index e86fa25e5..65efc2329 100644
--- a/fincept-terminal-desktop/public/locales/it/markets.json
+++ b/fincept-terminal-desktop/public/locales/it/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%VAR",
"high": "ALTO",
"low": "BASSO",
- "loading": "Caricamento...",
"noData": "Nessun dato disponibile",
"refresh": "AGGIORNA",
"auto": "AUTO",
"on": "ON",
- "off": "OFF",
- "lastUpdate": "ULTIMO AGGIORNAMENTO",
- "updating": "AGGIORNAMENTO",
- "live": "LIVE"
+ "off": "OFF"
}
diff --git a/fincept-terminal-desktop/public/locales/it/news.json b/fincept-terminal-desktop/public/locales/it/news.json
index eb72506c6..dff05adcb 100644
--- a/fincept-terminal-desktop/public/locales/it/news.json
+++ b/fincept-terminal-desktop/public/locales/it/news.json
@@ -1,32 +1,63 @@
{
"title": "NOTIZIE PROFESSIONALI TERMINALE FINCEPT",
"header": {
- "liveFeed": "FEED LIVE",
- "live": "LIVE",
- "refresh": "AGGIORNA",
- "updating": "AGGIORNAMENTO...",
- "alerts": "AVVISI",
- "sources": "FONTI",
- "status": "STATO",
- "demoMode": "MODALITÀ DEMO",
- "articles": "ARTICOLI",
- "activeSources": "FONTI ATTIVE"
- },
- "autoRefresh": {
- "title": "INTERVALLO AGGIORNAMENTO AUTOMATICO",
- "minute": "minuto",
- "minutes": "minuti"
+ "refresh": "AGGIORNA"
},
"messages": {
- "loadingFeeds": "Caricamento feed...",
- "breaking": "URGENTE"
- },
- "feeds": {
- "primary": "[IT] PRIMARY NEWS FEED",
- "secondary": "[IT] SECONDARY NEWS FEED",
- "additional": "[IT] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[IT] Loading feeds...",
+ "failedToLoad": "[IT] Failed to load RSS feeds",
+ "noCustomFeeds": "[IT] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[IT] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[IT] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[IT] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[IT] RSS FEED SETTINGS",
+ "subtitle": "[IT] MANAGE YOUR NEWS SOURCES",
+ "close": "[IT] CLOSE",
+ "myFeeds": "[IT] MY FEEDS",
+ "defaultFeeds": "[IT] DEFAULT FEEDS",
+ "noFeedsAvailable": "[IT] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[IT] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[IT] ADD NEW FEED",
+ "addNewRssFeed": "[IT] ADD NEW RSS FEED",
+ "editRssFeed": "[IT] EDIT RSS FEED",
+ "restoreDefaults": "[IT] RESTORE DEFAULTS",
+ "restoreAll": "[IT] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[IT] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[IT] DISPLAY NAME",
+ "sourceName": "[IT] SOURCE NAME (SHORT)",
+ "feedUrl": "[IT] RSS FEED URL",
+ "category": "[IT] CATEGORY",
+ "region": "[IT] REGION",
+ "required": "[IT] *",
+ "testUrl": "[IT] TEST URL",
+ "testing": "[IT] TESTING...",
+ "valid": "[IT] VALID",
+ "cancel": "[IT] CANCEL",
+ "saving": "[IT] SAVING...",
+ "addFeed": "[IT] ADD FEED",
+ "updateFeed": "[IT] UPDATE FEED",
+ "on": "[IT] ON",
+ "off": "[IT] OFF",
+ "default": "[IT] DEFAULT",
+ "total": "[IT] TOTAL",
+ "active": "[IT] ACTIVE",
+ "custom": "[IT] CUSTOM",
+ "placeholders": {
+ "displayName": "[IT] e.g., Bloomberg Markets",
+ "sourceName": "[IT] e.g., BLOOMBERG",
+ "feedUrl": "[IT] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[IT] Name is required",
+ "sourceRequired": "[IT] Source name is required",
+ "invalidUrl": "[IT] Please enter a valid URL",
+ "invalidRss": "[IT] URL does not appear to be a valid RSS feed",
+ "testFailed": "[IT] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[IT] Delete this RSS feed?",
+ "message": "[IT] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/it/portfolio.json b/fincept-terminal-desktop/public/locales/it/portfolio.json
index 27129e9e4..56685b722 100644
--- a/fincept-terminal-desktop/public/locales/it/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/it/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "GESTORE PORTAFOGLIO FINCEPT",
- "header": {
- "live": "LIVE",
- "updating": "AGGIORNAMENTO",
- "newPortfolio": "NUOVO PORTAFOGLIO",
- "refresh": "AGGIORNA",
- "exportCsv": "ESPORTA CSV"
- },
- "summary": {
- "totalValue": "VALORE TOTALE",
- "dayPnl": "P/L GIORNO",
- "totalPnl": "P/L TOTALE",
- "positions": "POSIZIONI"
- },
- "views": {
- "positions": "POSIZIONI",
- "addAsset": "AGGIUNGI ASSET",
- "sellAsset": "VENDI ASSET",
- "analytics": "ANALITICA",
- "history": "STORICO",
- "activeMgmt": "GESTIONE ATTIVA",
- "performance": "PERFORMANCE",
- "rebalance": "RIBILANCIAMENTO",
- "reports": "REPORT",
- "alerts": "AVVISI",
- "sectors": "SETTORI",
- "help": "AIUTO"
- },
- "sidebar": {
- "portfolios": "PORTAFOGLI",
- "loading": "Caricamento portafogli...",
- "noPortfolios": "Nessun portafoglio ancora.",
- "clickCreate": "Clicca NUOVO PORTAFOGLIO per crearne uno.",
- "owner": "Proprietario",
- "currency": "Valuta"
- },
- "content": {
- "selectOrCreate": "Seleziona un portafoglio o creane uno nuovo per iniziare",
- "loadingData": "Caricamento dati portafoglio...",
- "comingSoon": "vista in arrivo..."
- },
- "modals": {
- "createNew": "CREA NUOVO PORTAFOGLIO",
- "portfolioName": "NOME PORTAFOGLIO",
- "owner": "PROPRIETARIO",
- "currency": "VALUTA",
- "cancel": "ANNULLA",
- "create": "CREA",
- "addAssetTitle": "AGGIUNGI ASSET AL PORTAFOGLIO",
- "sellAssetTitle": "VENDI ASSET",
- "symbol": "SIMBOLO",
- "quantity": "QUANTITÀ",
- "price": "PREZZO",
- "add": "AGGIUNGI",
- "sell": "VENDI"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Tracciamento in tempo reale con integrazione yfinance",
- "lastUpdated": "Ultimo Aggiornamento",
- "connected": "CONNESSO"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "CREA NUOVO PORTAFOGLIO",
+ "portfolioName": "NOME PORTAFOGLIO",
+ "owner": "PROPRIETARIO",
+ "currency": "VALUTA",
+ "cancel": "ANNULLA",
+ "create": "CREA",
+ "addAssetTitle": "AGGIUNGI ASSET AL PORTAFOGLIO",
+ "sellAssetTitle": "VENDI ASSET",
+ "symbol": "SIMBOLO",
+ "quantity": "QUANTITÀ",
+ "price": "PREZZO",
+ "add": "AGGIUNGI",
+ "sell": "VENDI"
+ },
+ "extracted": {
+ "areYouSureYou": "[IT] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/it/reportBuilder.json b/fincept-terminal-desktop/public/locales/it/reportBuilder.json
index 52c225e39..3cf2f5d67 100644
--- a/fincept-terminal-desktop/public/locales/it/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/it/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[IT] Load",
"save": "[IT] Save",
- "saving": "[IT] Saving...",
- "exportPdf": "[IT] Export PDF",
- "generating": "[IT] Generating..."
+ "saving": "[IT] Saving..."
},
"components": {
"title": "[IT] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/it/settings.json b/fincept-terminal-desktop/public/locales/it/settings.json
index 8d6772654..645db1a51 100644
--- a/fincept-terminal-desktop/public/locales/it/settings.json
+++ b/fincept-terminal-desktop/public/locales/it/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Disposizione scheda",
"appearance": "Aspetto",
"language": "Lingua",
- "storage": "Archiviazione e cache"
+ "storage": "Archiviazione e cache",
+ "notifications": "[IT] Notifications"
},
"credentials": {
"title": "GESTIONE CREDENZIALI API",
@@ -46,7 +47,31 @@
"saveConfig": "SALVA CONFIGURAZIONE",
"reset": "RESET",
"saveSuccess": "Aspetto del terminale e mappature dei tasti salvate correttamente",
- "resetSuccess": "Ripristina l'aspetto predefinito e le mappature dei tasti"
+ "resetSuccess": "Ripristina l'aspetto predefinito e le mappature dei tasti",
+ "customColors": "[IT] Custom Colors",
+ "customColorsTitle": "[IT] CUSTOM COLORS",
+ "colorPrimary": "[IT] Primary",
+ "colorSecondary": "[IT] Secondary",
+ "colorSuccess": "[IT] Success",
+ "colorAlert": "[IT] Alert",
+ "colorWarning": "[IT] Warning",
+ "colorInfo": "[IT] Info",
+ "colorAccent": "[IT] Accent",
+ "colorPurple": "[IT] Purple",
+ "colorText": "[IT] Text",
+ "colorTextMuted": "[IT] Text Muted",
+ "colorBackground": "[IT] Background",
+ "colorPanel": "[IT] Panel",
+ "layoutSpacing": "[IT] LAYOUT & SPACING",
+ "contentDensity": "[IT] CONTENT DENSITY",
+ "borderRadius": "[IT] BORDER RADIUS",
+ "borderStyle": "[IT] BORDER STYLE",
+ "lineHeight": "[IT] LINE HEIGHT",
+ "letterSpacing": "[IT] LETTER SPACING",
+ "effects": "[IT] EFFECTS",
+ "widgetOpacity": "[IT] WIDGET OPACITY",
+ "enableGlow": "[IT] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[IT] GLOW INTENSITY"
},
"stockSymbols": {
"title": "Database dei simboli azionari",
@@ -65,17 +90,8 @@
"tip": "SUGGERIMENTO: trascina le schede per riordinarle. Utilizza i pulsanti freccia per spostare le schede tra le sezioni dell'intestazione e del menu. Le modifiche vengono salvate automaticamente."
},
"llm": {
- "title": "CONFIGURAZIONE LLM",
- "description": "Configura modelli e fornitori di intelligenza artificiale",
"connected": "COLLEGATO",
- "disconnected": "DISCONNESSO",
- "provider": "FORNITORE DI IA",
- "globalSettings": "IMPOSTAZIONI AI GLOBALI",
- "temperature": "TEMPERATURA",
- "maxTokens": "GETTONI MAX",
- "systemPrompt": "RICHIESTA DI SISTEMA",
- "modelLibrary": "BIBLIOTECA DI MODELLI",
- "multiModelConfigs": "Configurazioni multi-modello"
+ "disconnected": "DISCONNESSO"
},
"buttons": {
"save": "SALVA",
@@ -86,5 +102,18 @@
"database": "Base dati: SQLite",
"storage": "Archiviazione: basata su file",
"secureStorage": "Tutti i dati archiviati in modo sicuro in fincept_terminal.db"
+ },
+ "notifications": {
+ "title": "[IT] NOTIFICATION PROVIDERS",
+ "description": "[IT] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[IT] Event Filters",
+ "eventFilterDescription": "[IT] Choose which notification types to forward to external providers.",
+ "providers": "[IT] Providers",
+ "enabled": "[IT] Enabled",
+ "disabled": "[IT] Disabled",
+ "testButton": "[IT] TEST",
+ "testSuccess": "[IT] Test notification sent successfully!",
+ "testFailed": "[IT] Failed to send test notification. Check your configuration.",
+ "saved": "[IT] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/it/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/it/surfaceAnalytics.json
new file mode 100644
index 000000000..7708cb44c
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/it/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[IT] SURFACE ANALYTICS",
+ "initializing": "[IT] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[IT] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[IT] VOL SURFACE",
+ "correlation": "[IT] CORRELATION",
+ "yieldCurve": "[IT] YIELD CURVE",
+ "pca": "[IT] PCA FACTORS"
+ },
+ "demoData": "[IT] DEMO DATA",
+ "demoDataSynthetic": "[IT] DEMO DATA (synthetic)",
+ "synthetic": "[IT] SYNTHETIC",
+ "manual": "[IT] MANUAL",
+ "error": "[IT] ERROR",
+ "ready": "[IT] READY",
+ "metrics": "[IT] Metrics",
+ "updated": "[IT] Updated",
+ "clickRefresh": "[IT] Click REFRESH to load data",
+ "refresh": "[IT] REFRESH",
+ "noApiKey": "[IT] NO API KEY",
+ "lastUpdate": "[IT] LAST UPDATE",
+ "loadingData": "[IT] LOADING DATA...",
+ "noDataLoaded": "[IT] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[IT] IV SURFACE METRICS",
+ "correlationMetrics": "[IT] CORRELATION METRICS",
+ "yieldCurveMetrics": "[IT] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[IT] PCA FACTOR METRICS",
+ "dataInfo": "[IT] DATA INFO",
+ "source": "[IT] SOURCE",
+ "frequency": "[IT] FREQUENCY",
+ "quality": "[IT] QUALITY",
+ "correlationScale": "[IT] CORRELATION SCALE",
+ "strongPositive": "[IT] Strong Positive (0.7-1.0)",
+ "neutral": "[IT] Neutral (0.3-0.7)",
+ "strongNegative": "[IT] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[IT] IV INTERPRETATION",
+ "highIv": "[IT] High IV = Expensive Options",
+ "lowIv": "[IT] Low IV = Cheap Options",
+ "skew": "[IT] Skew = Put/Call IV Diff",
+ "termStructure": "[IT] Term Structure = Time Effect",
+ "pcaInterpretation": "[IT] PCA INTERPRETATION",
+ "pc1": "[IT] PC1 = Market Factor",
+ "pc2": "[IT] PC2 = Size/Value Factor",
+ "pc3": "[IT] PC3 = Sector Rotation",
+ "higherVar": "[IT] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[IT] STRIKE",
+ "dte": "[IT] DTE",
+ "iv": "[IT] IV",
+ "correlation": "[IT] CORRELATION",
+ "maturity": "[IT] MATURITY",
+ "yield": "[IT] YIELD",
+ "loading": "[IT] LOADING",
+ "strikePrice": "[IT] STRIKE PRICE",
+ "daysToExpiry": "[IT] DAYS TO EXPIRY",
+ "impliedVol": "[IT] IMPLIED VOL (%)",
+ "assetPairIndex": "[IT] ASSET PAIR INDEX",
+ "timeDays": "[IT] TIME (DAYS)",
+ "correlationCoeff": "[IT] CORRELATION COEFF",
+ "maturityMonths": "[IT] MATURITY (MONTHS)",
+ "historicalDays": "[IT] HISTORICAL DAYS",
+ "yieldPercent": "[IT] YIELD (%)",
+ "principalComponent": "[IT] PRINCIPAL COMPONENT",
+ "assetIndex": "[IT] ASSET INDEX",
+ "factorLoading": "[IT] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[IT] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[IT] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[IT] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[IT] DAY ROLLING",
+ "yieldCurve": "[IT] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[IT] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[IT] FAILED TO LOAD DATA",
+ "authFailed": "[IT] AUTHENTICATION FAILED",
+ "authFailedHelp": "[IT] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[IT] ACCESS DENIED",
+ "accessDeniedHelp": "[IT] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[IT] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[IT] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[IT] DATA TIMEFRAME",
+ "schema": "[IT] Schema",
+ "description": "[IT] Description",
+ "recordsPerDay": "[IT] Records/Day",
+ "highFrequencyWarning": "[IT] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[IT] Data Volume"
+ },
+ "settings": {
+ "title": "[IT] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[IT] DATABENTO API KEY",
+ "configured": "[IT] CONFIGURED",
+ "invalidFormat": "[IT] INVALID FORMAT",
+ "apiKeyConfigured": "[IT] API key is configured (db-*****)",
+ "remove": "[IT] REMOVE",
+ "enterApiKey": "[IT] Enter your Databento API key (db-*****)",
+ "save": "[IT] SAVE",
+ "saving": "[IT] SAVING...",
+ "getApiKeyFrom": "[IT] Get your API key from",
+ "dashboardApiKeys": "[IT] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[IT] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[IT] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[IT] CORRELATION ASSETS",
+ "addSymbol": "[IT] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[IT] Reset to defaults",
+ "historicalDateRange": "[IT] HISTORICAL DATE RANGE",
+ "start": "[IT] Start",
+ "end": "[IT] End",
+ "autoRefreshInterval": "[IT] AUTO REFRESH INTERVAL",
+ "manualOnly": "[IT] Manual Only",
+ "every1min": "[IT] Every 1 minute",
+ "every5min": "[IT] Every 5 minutes",
+ "every15min": "[IT] Every 15 minutes",
+ "every1hour": "[IT] Every 1 hour",
+ "browseDatasets": "[IT] BROWSE DATASETS",
+ "costEstimator": "[IT] COST ESTIMATOR",
+ "referenceData": "[IT] REFERENCE DATA",
+ "orderBook": "[IT] ORDER BOOK",
+ "liveStreaming": "[IT] LIVE STREAMING",
+ "active": "[IT] ACTIVE",
+ "futuresCme": "[IT] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[IT] BATCH DOWNLOADS",
+ "additionalSchemas": "[IT] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[IT] TRADES, IMBALANCE, STATUS",
+ "cancel": "[IT] CANCEL",
+ "saveChanges": "[IT] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[IT] BATCH DOWNLOADS",
+ "newBatchJob": "[IT] NEW BATCH JOB",
+ "dataset": "[IT] Dataset",
+ "schema": "[IT] Schema",
+ "symbolsCommaSeparated": "[IT] Symbols (comma-separated)",
+ "startDate": "[IT] Start Date",
+ "endDate": "[IT] End Date",
+ "encoding": "[IT] Encoding",
+ "compression": "[IT] Compression",
+ "submitJob": "[IT] SUBMIT JOB",
+ "noBatchJobs": "[IT] No batch jobs found. Click + to create one.",
+ "records": "[IT] records",
+ "download": "[IT] Download",
+ "files": "[IT] FILES",
+ "jobsExpireNotice": "[IT] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[IT] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[IT] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[IT] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[IT] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[IT] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[IT] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[IT] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[IT] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[IT] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[IT] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[IT] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[IT] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[IT] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[IT] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[IT] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[IT] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[IT] [EN] common.or",
+ "note": "[IT] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/it/tabs.json b/fincept-terminal-desktop/public/locales/it/tabs.json
index 8aca5d270..af2bee613 100644
--- a/fincept-terminal-desktop/public/locales/it/tabs.json
+++ b/fincept-terminal-desktop/public/locales/it/tabs.json
@@ -5,29 +5,7 @@
"news": "Notizie",
"portfolio": "Portafoglio",
"backtesting": "Backtesting",
- "watchlist": "Lista Preferiti",
- "research": "Ricerca",
- "screener": "Screener",
"chat": "AI Chat",
- "agents": "Agenti",
- "settings": "Impostazioni",
"profile": "Profilo"
- },
- "functionKeys": {
- "f1": "DASH",
- "f2": "MERC",
- "f3": "NOTI",
- "f4": "PORT",
- "f5": "BKTS",
- "f6": "PREF",
- "f7": "RICE",
- "f8": "SCRN",
- "f9": "TRDG",
- "f10": "AI",
- "f11": "FULL",
- "f12": "PROF"
- },
- "labels": {
- "moreTabs": "Più schede nei menu della barra degli strumenti"
}
}
diff --git a/fincept-terminal-desktop/public/locales/it/watchlist.json b/fincept-terminal-desktop/public/locales/it/watchlist.json
index 96a4ba871..9bb29b934 100644
--- a/fincept-terminal-desktop/public/locales/it/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/it/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "LISTA DI CONTROLLO",
- "header": {
- "export": "ESPORTA",
- "updating": "AGGIORNAMENTO",
- "live": "LIVE"
- },
"sidebar": {
- "groups": "GRUPPI DI LISTE",
- "new": "NUOVA",
"noWatchlists": "Nessuna lista ancora.",
"clickNew": "Clicca NUOVA per crearne una.",
- "stocks": "azioni",
- "marketMovers": "LEADER DI MERCATO",
- "gainer": "IN RIALZO",
- "loser": "IN RIBASSO",
- "volumeLeaders": "LEADER DI VOLUME"
- },
- "emptyState": {
- "selectWatchlist": "Seleziona una lista o creane una nuova per iniziare"
- },
- "list": {
- "symbols": "Simboli"
+ "stocks": "azioni"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ja/codeEditor.json b/fincept-terminal-desktop/public/locales/ja/codeEditor.json
index ebf7a1a15..0903d6705 100644
--- a/fincept-terminal-desktop/public/locales/ja/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/ja/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "コードエディタ",
"header": {
- "packages": "パッケージ"
+ "finscriptIde": "[JA] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "新規ファイル",
- "new": "新規",
- "open": "開く",
- "save": "保存",
"run": "コード実行",
"running": "実行中...",
- "runAll": "すべて実行",
- "history": "履歴"
+ "toggleExplorer": "[JA] Toggle Explorer (Ctrl+B)",
+ "openFile": "[JA] Open File",
+ "saveShortcut": "[JA] Save (Ctrl+S)",
+ "findShortcut": "[JA] Find (Ctrl+F)",
+ "runShortcut": "[JA] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTERノートブック",
"finscript": "FINSCRIPTエディタ"
},
- "packages": {
- "clickToLoad": "クリックしてロード...",
- "load": "パッケージをロード"
+ "explorer": {
+ "title": "[JA] EXPLORER",
+ "openFiles": "[JA] OPEN FILES",
+ "examples": "[JA] EXAMPLES",
+ "runHistory": "[JA] RUN HISTORY",
+ "finscriptEngine": "[JA] FinScript Engine"
},
- "history": {
- "title": "ノートブック履歴",
- "loading": "履歴を読込中...",
- "empty": "ノートブック履歴なし"
+ "output": {
+ "title": "[JA] OUTPUT",
+ "success": "[JA] SUCCESS",
+ "error": "[JA] ERROR",
+ "executing": "[JA] EXECUTING FINSCRIPT...",
+ "noOutput": "[JA] No output yet",
+ "pressToRun": "[JA] Press Ctrl+Enter to run",
+ "completed": "[JA] COMPLETED",
+ "failed": "[JA] FAILED",
+ "signals": "[JA] signals",
+ "clear": "[JA] CLEAR",
+ "errors": "[JA] ERRORS",
+ "signalsSection": "[JA] SIGNALS",
+ "outputSection": "[JA] OUTPUT",
+ "charts": "[JA] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[JA] OHLC",
+ "histogram": "[JA] Histogram",
+ "line": "[JA] Line",
+ "points": "[JA] points"
+ },
+ "statusBar": {
+ "modified": "[JA] MODIFIED",
+ "showOutput": "[JA] SHOW OUTPUT",
+ "encoding": "[JA] UTF-8",
+ "spaces": "[JA] 4 Spaces",
+ "runShortcut": "[JA] Ctrl+Enter: Run",
+ "lines": "[JA] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[JA] Close file without saving?",
+ "unsavedChanges": "[JA] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/ja/common.json b/fincept-terminal-desktop/public/locales/ja/common.json
index 4abbb1b66..8de40c20a 100644
--- a/fincept-terminal-desktop/public/locales/ja/common.json
+++ b/fincept-terminal-desktop/public/locales/ja/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "読み込み中...",
- "error": "エラー",
- "success": "成功",
- "save": "保存",
- "cancel": "キャンセル",
- "delete": "削除",
- "edit": "編集",
- "add": "追加",
- "search": "検索",
- "filter": "フィルター",
- "back": "戻る",
- "next": "次へ",
- "previous": "前へ",
- "submit": "送信",
- "close": "閉じる",
- "open": "開く",
- "yes": "はい",
- "no": "いいえ",
- "ok": "OK",
- "confirm": "確認",
- "language": "言語",
- "selectLanguage": "言語を選択"
-}
\ No newline at end of file
+ "settings": "[JA] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/ja/dashboard.json b/fincept-terminal-desktop/public/locales/ja/dashboard.json
index bdd75b006..04b0a87bd 100644
--- a/fincept-terminal-desktop/public/locales/ja/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/ja/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "カスタマイズ可能なダッシュボード",
- "live": "ライブ",
- "widgets": "ウィジェット"
- },
- "buttons": {
- "addWidget": "ウィジェットを追加",
- "saveLayout": "レイアウトの保存",
- "reset": "リセット",
- "help": "ヘルプ"
- },
"widgets": {
"loading": "読み込み中...",
- "error": "エラー",
"globalIndices": "グローバル指数 - トップ 12",
"forex": "外国為替 - 主要ペア",
"crypto": "暗号通貨",
@@ -20,8 +8,6 @@
"news": "ニュース",
"forum": "フォーラム",
"watchlist": "ウォッチリスト",
- "maritimeIntelligence": "海洋インテリジェンス",
- "unknown": "不明なウィジェットの種類",
"index": "索引",
"symbol": "シンボル",
"price": "価格",
@@ -38,41 +24,22 @@
"pair": "ペア",
"rate": "レート",
"commodity": "商品",
- "globe3D": "3Dグローブ",
- "vessels": "容器",
- "routes": "ルート",
- "vol24h": "24H巻",
- "topTradeCorridors": "トップ貿易回廊",
- "ships": "船",
- "marketNews": "マーケットニュース",
- "secPressReleases": "SEC プレスリリース",
- "cryptoNews": "暗号ニュース",
- "trendingForum": "トレンドフォーラム",
- "techStocks": "ハイテク株"
- },
- "tips": {
- "drag": "ウィジェットをドラッグして並べ替えます",
- "resize": "右下隅からサイズを変更します",
- "remove": "Xボタンでウィジェットを削除",
- "responsive": "レスポンシブ レイアウト - 全幅を使用します"
- },
- "loading": {
- "title": "ダッシュボードを初期化しています",
- "description": "データの読み込みを高速化するためにデータベース キャッシュを設定しています...",
- "note": "初回起動時はほんの少しだけかかります"
- },
- "empty": {
- "noWidgets": "ダッシュボードにウィジェットがありません",
- "addFirst": "最初のウィジェットを追加する"
- },
- "status": {
- "version": "Fincept カスタマイズ可能なダッシュボード v2.0.0 |ワークスペースをドラッグ&ドロップ",
- "layout": "レイアウト",
- "custom": "カスタム",
- "empty": "空の",
- "active": "アクティブ",
- "cache": "キャッシュ: 有効",
- "label": "状態"
+ "noActiveMarkets": "[JA] No active markets found",
+ "indicator": "[JA] INDICATOR",
+ "value": "[JA] VALUE",
+ "chg": "[JA] CHG",
+ "overallRisk": "[JA] OVERALL RISK",
+ "openEconomicsTab": "[JA] Open Economics Tab",
+ "openGeopoliticsTab": "[JA] Open Geopolitics Tab",
+ "openPolymarketTab": "[JA] Open Polymarket Tab",
+ "noPortfolioFound": "[JA] No portfolio found",
+ "createPortfolioHint": "[JA] Create one in Portfolio tab",
+ "openPortfolioTab": "[JA] Open Portfolio Tab",
+ "action": "[JA] ACTION",
+ "markets": "[JA] MARKETS",
+ "performanceTracker": "[JA] PERFORMANCE TRACKER",
+ "totalPnL": "[JA] TOTAL P&L",
+ "viewDetailedAnalytics": "[JA] View Detailed Analytics"
},
"messages": {
"layoutSaved": "ダッシュボードのレイアウトが保存されました。",
diff --git a/fincept-terminal-desktop/public/locales/ja/geopolitics.json b/fincept-terminal-desktop/public/locales/ja/geopolitics.json
index 2294d5bb1..851de7959 100644
--- a/fincept-terminal-desktop/public/locales/ja/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/ja/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "地政学",
"messages": {
- "loading": "地政学データ読み込み中..."
+ "retry": "[JA] RETRY"
+ },
+ "header": {
+ "prefix": "[JA] GEO>",
+ "title": "[JA] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[JA] EVENTS"
+ },
+ "status": {
+ "stale": "[JA] STALE",
+ "loading": "[JA] LOADING...",
+ "error": "[JA] ERROR:"
+ },
+ "filters": {
+ "country": "[JA] Country...",
+ "cities": "[JA] Cities...",
+ "category": "[JA] Category...",
+ "apply": "[JA] APPLY",
+ "clear": "[JA] CLEAR",
+ "clearAllCities": "[JA] Clear all cities",
+ "selectedLabel": "[JA] Selected:"
+ },
+ "panel": {
+ "title": "[JA] INFO PANEL",
+ "expand": "[JA] Expand panel",
+ "collapse": "[JA] Collapse panel",
+ "eventsLoaded": "[JA] EVENTS LOADED",
+ "onMapVisualization": "[JA] on map visualization",
+ "topCategories": "[JA] TOP CATEGORIES",
+ "topCountries": "[JA] TOP COUNTRIES",
+ "eventDetails": "[JA] EVENT DETAILS",
+ "close": "[JA] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[JA] Country:",
+ "city": "[JA] City:",
+ "keywords": "[JA] Keywords:",
+ "coords": "[JA] Coords:",
+ "date": "[JA] Date:",
+ "source": "[JA] Source:",
+ "viewArticle": "[JA] View Article"
+ },
+ "legend": {
+ "title": "[JA] EVENT CATEGORIES",
+ "armedConflict": "[JA] Armed Conflict",
+ "terrorism": "[JA] Terrorism",
+ "protests": "[JA] Protests",
+ "civilianViolence": "[JA] Civilian Violence",
+ "riots": "[JA] Riots",
+ "politicalViolence": "[JA] Political Violence",
+ "crisis": "[JA] Crisis",
+ "explosions": "[JA] Explosions",
+ "strategic": "[JA] Strategic",
+ "unclassified": "[JA] Unclassified"
+ },
+ "footer": {
+ "tabName": "[JA] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[JA] EVENTS",
+ "labelEngine": "[JA] ENGINE",
+ "engineValue": "[JA] DECK.GL v9.2",
+ "labelSource": "[JA] SOURCE",
+ "sourceValue": "[JA] NEWS-EVENTS API",
+ "labelSelected": "[JA] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ja/markets.json b/fincept-terminal-desktop/public/locales/ja/markets.json
index 7374e9fcd..43d898e31 100644
--- a/fincept-terminal-desktop/public/locales/ja/markets.json
+++ b/fincept-terminal-desktop/public/locales/ja/markets.json
@@ -9,13 +9,9 @@
"percentChange": "変動%",
"high": "高値",
"low": "安値",
- "loading": "読み込み中...",
"noData": "データなし",
"refresh": "更新",
"auto": "自動",
"on": "オン",
- "off": "オフ",
- "lastUpdate": "最終更新",
- "updating": "更新中",
- "live": "ライブ"
+ "off": "オフ"
}
diff --git a/fincept-terminal-desktop/public/locales/ja/news.json b/fincept-terminal-desktop/public/locales/ja/news.json
index ab23ac530..347acc7b4 100644
--- a/fincept-terminal-desktop/public/locales/ja/news.json
+++ b/fincept-terminal-desktop/public/locales/ja/news.json
@@ -1,32 +1,63 @@
{
"title": "FINCEPTターミナルプロフェッショナルニュース",
"header": {
- "liveFeed": "ライブフィード",
- "live": "ライブ",
- "refresh": "更新",
- "updating": "更新中...",
- "alerts": "アラート",
- "sources": "ソース",
- "status": "ステータス",
- "demoMode": "デモモード",
- "articles": "記事",
- "activeSources": "アクティブソース"
- },
- "autoRefresh": {
- "title": "自動更新間隔",
- "minute": "分",
- "minutes": "分"
+ "refresh": "更新"
},
"messages": {
- "loadingFeeds": "フィードを読み込み中...",
- "breaking": "速報"
- },
- "feeds": {
- "primary": "[JA] PRIMARY NEWS FEED",
- "secondary": "[JA] SECONDARY NEWS FEED",
- "additional": "[JA] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[JA] Loading feeds...",
+ "failedToLoad": "[JA] Failed to load RSS feeds",
+ "noCustomFeeds": "[JA] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[JA] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[JA] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[JA] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[JA] RSS FEED SETTINGS",
+ "subtitle": "[JA] MANAGE YOUR NEWS SOURCES",
+ "close": "[JA] CLOSE",
+ "myFeeds": "[JA] MY FEEDS",
+ "defaultFeeds": "[JA] DEFAULT FEEDS",
+ "noFeedsAvailable": "[JA] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[JA] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[JA] ADD NEW FEED",
+ "addNewRssFeed": "[JA] ADD NEW RSS FEED",
+ "editRssFeed": "[JA] EDIT RSS FEED",
+ "restoreDefaults": "[JA] RESTORE DEFAULTS",
+ "restoreAll": "[JA] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[JA] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[JA] DISPLAY NAME",
+ "sourceName": "[JA] SOURCE NAME (SHORT)",
+ "feedUrl": "[JA] RSS FEED URL",
+ "category": "[JA] CATEGORY",
+ "region": "[JA] REGION",
+ "required": "[JA] *",
+ "testUrl": "[JA] TEST URL",
+ "testing": "[JA] TESTING...",
+ "valid": "[JA] VALID",
+ "cancel": "[JA] CANCEL",
+ "saving": "[JA] SAVING...",
+ "addFeed": "[JA] ADD FEED",
+ "updateFeed": "[JA] UPDATE FEED",
+ "on": "[JA] ON",
+ "off": "[JA] OFF",
+ "default": "[JA] DEFAULT",
+ "total": "[JA] TOTAL",
+ "active": "[JA] ACTIVE",
+ "custom": "[JA] CUSTOM",
+ "placeholders": {
+ "displayName": "[JA] e.g., Bloomberg Markets",
+ "sourceName": "[JA] e.g., BLOOMBERG",
+ "feedUrl": "[JA] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[JA] Name is required",
+ "sourceRequired": "[JA] Source name is required",
+ "invalidUrl": "[JA] Please enter a valid URL",
+ "invalidRss": "[JA] URL does not appear to be a valid RSS feed",
+ "testFailed": "[JA] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[JA] Delete this RSS feed?",
+ "message": "[JA] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/ja/portfolio.json b/fincept-terminal-desktop/public/locales/ja/portfolio.json
index fe75a6837..bea0f3c14 100644
--- a/fincept-terminal-desktop/public/locales/ja/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/ja/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "FINCEPTポートフォリオマネージャー",
- "header": {
- "live": "ライブ",
- "updating": "更新中",
- "newPortfolio": "新規ポートフォリオ",
- "refresh": "更新",
- "exportCsv": "CSVエクスポート"
- },
- "summary": {
- "totalValue": "総価値",
- "dayPnl": "当日損益",
- "totalPnl": "総損益",
- "positions": "ポジション"
- },
- "views": {
- "positions": "ポジション",
- "addAsset": "資産追加",
- "sellAsset": "資産売却",
- "analytics": "分析",
- "history": "履歴",
- "activeMgmt": "アクティブ運用",
- "performance": "パフォーマンス",
- "rebalance": "リバランス",
- "reports": "レポート",
- "alerts": "アラート",
- "sectors": "セクター",
- "help": "ヘルプ"
- },
- "sidebar": {
- "portfolios": "ポートフォリオ",
- "loading": "ポートフォリオを読み込み中...",
- "noPortfolios": "ポートフォリオがありません。",
- "clickCreate": "新規ポートフォリオをクリックして作成。",
- "owner": "オーナー",
- "currency": "通貨"
- },
- "content": {
- "selectOrCreate": "ポートフォリオを選択または新規作成して開始",
- "loadingData": "ポートフォリオデータを読み込み中...",
- "comingSoon": "近日公開..."
- },
- "modals": {
- "createNew": "新規ポートフォリオ作成",
- "portfolioName": "ポートフォリオ名",
- "owner": "オーナー",
- "currency": "通貨",
- "cancel": "キャンセル",
- "create": "作成",
- "addAssetTitle": "ポートフォリオに資産追加",
- "sellAssetTitle": "資産売却",
- "symbol": "シンボル",
- "quantity": "数量",
- "price": "価格",
- "add": "追加",
- "sell": "売却"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | yfinance統合によるリアルタイム追跡",
- "lastUpdated": "最終更新",
- "connected": "接続済み"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "新規ポートフォリオ作成",
+ "portfolioName": "ポートフォリオ名",
+ "owner": "オーナー",
+ "currency": "通貨",
+ "cancel": "キャンセル",
+ "create": "作成",
+ "addAssetTitle": "ポートフォリオに資産追加",
+ "sellAssetTitle": "資産売却",
+ "symbol": "シンボル",
+ "quantity": "数量",
+ "price": "価格",
+ "add": "追加",
+ "sell": "売却"
+ },
+ "extracted": {
+ "areYouSureYou": "[JA] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/ja/reportBuilder.json b/fincept-terminal-desktop/public/locales/ja/reportBuilder.json
index d6b29fd2e..faf3558fe 100644
--- a/fincept-terminal-desktop/public/locales/ja/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/ja/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[JA] Load",
"save": "[JA] Save",
- "saving": "[JA] Saving...",
- "exportPdf": "[JA] Export PDF",
- "generating": "[JA] Generating..."
+ "saving": "[JA] Saving..."
},
"components": {
"title": "[JA] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/ja/settings.json b/fincept-terminal-desktop/public/locales/ja/settings.json
index 82c107608..e6df5f4c5 100644
--- a/fincept-terminal-desktop/public/locales/ja/settings.json
+++ b/fincept-terminal-desktop/public/locales/ja/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "タブのレイアウト",
"appearance": "外観",
"language": "言語",
- "storage": "ストレージとキャッシュ"
+ "storage": "ストレージとキャッシュ",
+ "notifications": "[JA] Notifications"
},
"credentials": {
"title": "API 認証情報の管理",
@@ -46,7 +47,31 @@
"saveConfig": "設定の保存",
"reset": "リセット",
"saveSuccess": "端末の外観とキーマッピングが正常に保存されました",
- "resetSuccess": "デフォルトの外観とキーマッピングにリセットします"
+ "resetSuccess": "デフォルトの外観とキーマッピングにリセットします",
+ "customColors": "[JA] Custom Colors",
+ "customColorsTitle": "[JA] CUSTOM COLORS",
+ "colorPrimary": "[JA] Primary",
+ "colorSecondary": "[JA] Secondary",
+ "colorSuccess": "[JA] Success",
+ "colorAlert": "[JA] Alert",
+ "colorWarning": "[JA] Warning",
+ "colorInfo": "[JA] Info",
+ "colorAccent": "[JA] Accent",
+ "colorPurple": "[JA] Purple",
+ "colorText": "[JA] Text",
+ "colorTextMuted": "[JA] Text Muted",
+ "colorBackground": "[JA] Background",
+ "colorPanel": "[JA] Panel",
+ "layoutSpacing": "[JA] LAYOUT & SPACING",
+ "contentDensity": "[JA] CONTENT DENSITY",
+ "borderRadius": "[JA] BORDER RADIUS",
+ "borderStyle": "[JA] BORDER STYLE",
+ "lineHeight": "[JA] LINE HEIGHT",
+ "letterSpacing": "[JA] LETTER SPACING",
+ "effects": "[JA] EFFECTS",
+ "widgetOpacity": "[JA] WIDGET OPACITY",
+ "enableGlow": "[JA] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[JA] GLOW INTENSITY"
},
"stockSymbols": {
"title": "銘柄記号データベース",
@@ -65,17 +90,8 @@
"tip": "ヒント: タブをドラッグして順序を変更します。矢印ボタンを使用して、ヘッダー セクションとメニュー セクション間でタブを移動します。変更は自動的に保存されます。"
},
"llm": {
- "title": "LLM の構成",
- "description": "AI モデルとプロバイダーを構成する",
"connected": "接続済み",
- "disconnected": "切断されました",
- "provider": "AIプロバイダー",
- "globalSettings": "グローバル AI 設定",
- "temperature": "温度",
- "maxTokens": "最大トークン",
- "systemPrompt": "システムプロンプト",
- "modelLibrary": "モデルライブラリ",
- "multiModelConfigs": "マルチモデル構成"
+ "disconnected": "切断されました"
},
"buttons": {
"save": "保存",
@@ -86,5 +102,18 @@
"database": "データベース: SQLite",
"storage": "ストレージ: ファイルベース",
"secureStorage": "すべてのデータは fincept_terminal.db に安全に保存されます"
+ },
+ "notifications": {
+ "title": "[JA] NOTIFICATION PROVIDERS",
+ "description": "[JA] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[JA] Event Filters",
+ "eventFilterDescription": "[JA] Choose which notification types to forward to external providers.",
+ "providers": "[JA] Providers",
+ "enabled": "[JA] Enabled",
+ "disabled": "[JA] Disabled",
+ "testButton": "[JA] TEST",
+ "testSuccess": "[JA] Test notification sent successfully!",
+ "testFailed": "[JA] Failed to send test notification. Check your configuration.",
+ "saved": "[JA] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ja/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/ja/surfaceAnalytics.json
new file mode 100644
index 000000000..69dd088dc
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/ja/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[JA] SURFACE ANALYTICS",
+ "initializing": "[JA] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[JA] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[JA] VOL SURFACE",
+ "correlation": "[JA] CORRELATION",
+ "yieldCurve": "[JA] YIELD CURVE",
+ "pca": "[JA] PCA FACTORS"
+ },
+ "demoData": "[JA] DEMO DATA",
+ "demoDataSynthetic": "[JA] DEMO DATA (synthetic)",
+ "synthetic": "[JA] SYNTHETIC",
+ "manual": "[JA] MANUAL",
+ "error": "[JA] ERROR",
+ "ready": "[JA] READY",
+ "metrics": "[JA] Metrics",
+ "updated": "[JA] Updated",
+ "clickRefresh": "[JA] Click REFRESH to load data",
+ "refresh": "[JA] REFRESH",
+ "noApiKey": "[JA] NO API KEY",
+ "lastUpdate": "[JA] LAST UPDATE",
+ "loadingData": "[JA] LOADING DATA...",
+ "noDataLoaded": "[JA] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[JA] IV SURFACE METRICS",
+ "correlationMetrics": "[JA] CORRELATION METRICS",
+ "yieldCurveMetrics": "[JA] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[JA] PCA FACTOR METRICS",
+ "dataInfo": "[JA] DATA INFO",
+ "source": "[JA] SOURCE",
+ "frequency": "[JA] FREQUENCY",
+ "quality": "[JA] QUALITY",
+ "correlationScale": "[JA] CORRELATION SCALE",
+ "strongPositive": "[JA] Strong Positive (0.7-1.0)",
+ "neutral": "[JA] Neutral (0.3-0.7)",
+ "strongNegative": "[JA] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[JA] IV INTERPRETATION",
+ "highIv": "[JA] High IV = Expensive Options",
+ "lowIv": "[JA] Low IV = Cheap Options",
+ "skew": "[JA] Skew = Put/Call IV Diff",
+ "termStructure": "[JA] Term Structure = Time Effect",
+ "pcaInterpretation": "[JA] PCA INTERPRETATION",
+ "pc1": "[JA] PC1 = Market Factor",
+ "pc2": "[JA] PC2 = Size/Value Factor",
+ "pc3": "[JA] PC3 = Sector Rotation",
+ "higherVar": "[JA] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[JA] STRIKE",
+ "dte": "[JA] DTE",
+ "iv": "[JA] IV",
+ "correlation": "[JA] CORRELATION",
+ "maturity": "[JA] MATURITY",
+ "yield": "[JA] YIELD",
+ "loading": "[JA] LOADING",
+ "strikePrice": "[JA] STRIKE PRICE",
+ "daysToExpiry": "[JA] DAYS TO EXPIRY",
+ "impliedVol": "[JA] IMPLIED VOL (%)",
+ "assetPairIndex": "[JA] ASSET PAIR INDEX",
+ "timeDays": "[JA] TIME (DAYS)",
+ "correlationCoeff": "[JA] CORRELATION COEFF",
+ "maturityMonths": "[JA] MATURITY (MONTHS)",
+ "historicalDays": "[JA] HISTORICAL DAYS",
+ "yieldPercent": "[JA] YIELD (%)",
+ "principalComponent": "[JA] PRINCIPAL COMPONENT",
+ "assetIndex": "[JA] ASSET INDEX",
+ "factorLoading": "[JA] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[JA] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[JA] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[JA] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[JA] DAY ROLLING",
+ "yieldCurve": "[JA] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[JA] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[JA] FAILED TO LOAD DATA",
+ "authFailed": "[JA] AUTHENTICATION FAILED",
+ "authFailedHelp": "[JA] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[JA] ACCESS DENIED",
+ "accessDeniedHelp": "[JA] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[JA] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[JA] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[JA] DATA TIMEFRAME",
+ "schema": "[JA] Schema",
+ "description": "[JA] Description",
+ "recordsPerDay": "[JA] Records/Day",
+ "highFrequencyWarning": "[JA] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[JA] Data Volume"
+ },
+ "settings": {
+ "title": "[JA] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[JA] DATABENTO API KEY",
+ "configured": "[JA] CONFIGURED",
+ "invalidFormat": "[JA] INVALID FORMAT",
+ "apiKeyConfigured": "[JA] API key is configured (db-*****)",
+ "remove": "[JA] REMOVE",
+ "enterApiKey": "[JA] Enter your Databento API key (db-*****)",
+ "save": "[JA] SAVE",
+ "saving": "[JA] SAVING...",
+ "getApiKeyFrom": "[JA] Get your API key from",
+ "dashboardApiKeys": "[JA] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[JA] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[JA] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[JA] CORRELATION ASSETS",
+ "addSymbol": "[JA] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[JA] Reset to defaults",
+ "historicalDateRange": "[JA] HISTORICAL DATE RANGE",
+ "start": "[JA] Start",
+ "end": "[JA] End",
+ "autoRefreshInterval": "[JA] AUTO REFRESH INTERVAL",
+ "manualOnly": "[JA] Manual Only",
+ "every1min": "[JA] Every 1 minute",
+ "every5min": "[JA] Every 5 minutes",
+ "every15min": "[JA] Every 15 minutes",
+ "every1hour": "[JA] Every 1 hour",
+ "browseDatasets": "[JA] BROWSE DATASETS",
+ "costEstimator": "[JA] COST ESTIMATOR",
+ "referenceData": "[JA] REFERENCE DATA",
+ "orderBook": "[JA] ORDER BOOK",
+ "liveStreaming": "[JA] LIVE STREAMING",
+ "active": "[JA] ACTIVE",
+ "futuresCme": "[JA] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[JA] BATCH DOWNLOADS",
+ "additionalSchemas": "[JA] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[JA] TRADES, IMBALANCE, STATUS",
+ "cancel": "[JA] CANCEL",
+ "saveChanges": "[JA] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[JA] BATCH DOWNLOADS",
+ "newBatchJob": "[JA] NEW BATCH JOB",
+ "dataset": "[JA] Dataset",
+ "schema": "[JA] Schema",
+ "symbolsCommaSeparated": "[JA] Symbols (comma-separated)",
+ "startDate": "[JA] Start Date",
+ "endDate": "[JA] End Date",
+ "encoding": "[JA] Encoding",
+ "compression": "[JA] Compression",
+ "submitJob": "[JA] SUBMIT JOB",
+ "noBatchJobs": "[JA] No batch jobs found. Click + to create one.",
+ "records": "[JA] records",
+ "download": "[JA] Download",
+ "files": "[JA] FILES",
+ "jobsExpireNotice": "[JA] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[JA] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[JA] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[JA] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[JA] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[JA] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[JA] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[JA] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[JA] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[JA] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[JA] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[JA] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[JA] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[JA] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[JA] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[JA] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[JA] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[JA] [EN] common.or",
+ "note": "[JA] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/ja/tabs.json b/fincept-terminal-desktop/public/locales/ja/tabs.json
index 8f224e284..7af2b92fd 100644
--- a/fincept-terminal-desktop/public/locales/ja/tabs.json
+++ b/fincept-terminal-desktop/public/locales/ja/tabs.json
@@ -5,29 +5,7 @@
"news": "ニュース",
"portfolio": "ポートフォリオ",
"backtesting": "バックテスト",
- "watchlist": "ウォッチリスト",
- "research": "リサーチ",
- "screener": "スクリーナー",
"chat": "AIチャット",
- "agents": "エージェント",
- "settings": "設定",
"profile": "プロフィール"
- },
- "functionKeys": {
- "f1": "ダッシ",
- "f2": "マーケ",
- "f3": "ニュス",
- "f4": "ポート",
- "f5": "バック",
- "f6": "ウォチ",
- "f7": "リサチ",
- "f8": "スクリ",
- "f9": "トレド",
- "f10": "AI",
- "f11": "フル",
- "f12": "プロフ"
- },
- "labels": {
- "moreTabs": "ツールバーメニューにタブを追加"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ja/watchlist.json b/fincept-terminal-desktop/public/locales/ja/watchlist.json
index bfb4516b4..093370a05 100644
--- a/fincept-terminal-desktop/public/locales/ja/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/ja/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "ウォッチリスト",
- "header": {
- "export": "エクスポート",
- "updating": "更新中",
- "live": "ライブ"
- },
"sidebar": {
- "groups": "ウォッチリストグループ",
- "new": "新規",
"noWatchlists": "まだウォッチリストがありません。",
"clickNew": "新規をクリックして作成。",
- "stocks": "銘柄",
- "marketMovers": "マーケットムーバー",
- "gainer": "上昇",
- "loser": "下落",
- "volumeLeaders": "出来高リーダー"
- },
- "emptyState": {
- "selectWatchlist": "ウォッチリストを選択するか新規作成してください"
- },
- "list": {
- "symbols": "銘柄"
+ "stocks": "銘柄"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ko/codeEditor.json b/fincept-terminal-desktop/public/locales/ko/codeEditor.json
index a0257b2c0..f9733f75a 100644
--- a/fincept-terminal-desktop/public/locales/ko/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/ko/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "코드 에디터",
"header": {
- "packages": "패키지"
+ "finscriptIde": "[KO] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "새 파일",
- "new": "새로 만들기",
- "open": "열기",
- "save": "저장",
"run": "코드 실행",
"running": "실행 중...",
- "runAll": "모두 실행",
- "history": "기록"
+ "toggleExplorer": "[KO] Toggle Explorer (Ctrl+B)",
+ "openFile": "[KO] Open File",
+ "saveShortcut": "[KO] Save (Ctrl+S)",
+ "findShortcut": "[KO] Find (Ctrl+F)",
+ "runShortcut": "[KO] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER 노트북",
"finscript": "FINSCRIPT 에디터"
},
- "packages": {
- "clickToLoad": "클릭하여 로드...",
- "load": "패키지 로드"
+ "explorer": {
+ "title": "[KO] EXPLORER",
+ "openFiles": "[KO] OPEN FILES",
+ "examples": "[KO] EXAMPLES",
+ "runHistory": "[KO] RUN HISTORY",
+ "finscriptEngine": "[KO] FinScript Engine"
},
- "history": {
- "title": "노트북 기록",
- "loading": "기록 로딩 중...",
- "empty": "노트북 기록 없음"
+ "output": {
+ "title": "[KO] OUTPUT",
+ "success": "[KO] SUCCESS",
+ "error": "[KO] ERROR",
+ "executing": "[KO] EXECUTING FINSCRIPT...",
+ "noOutput": "[KO] No output yet",
+ "pressToRun": "[KO] Press Ctrl+Enter to run",
+ "completed": "[KO] COMPLETED",
+ "failed": "[KO] FAILED",
+ "signals": "[KO] signals",
+ "clear": "[KO] CLEAR",
+ "errors": "[KO] ERRORS",
+ "signalsSection": "[KO] SIGNALS",
+ "outputSection": "[KO] OUTPUT",
+ "charts": "[KO] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[KO] OHLC",
+ "histogram": "[KO] Histogram",
+ "line": "[KO] Line",
+ "points": "[KO] points"
+ },
+ "statusBar": {
+ "modified": "[KO] MODIFIED",
+ "showOutput": "[KO] SHOW OUTPUT",
+ "encoding": "[KO] UTF-8",
+ "spaces": "[KO] 4 Spaces",
+ "runShortcut": "[KO] Ctrl+Enter: Run",
+ "lines": "[KO] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[KO] Close file without saving?",
+ "unsavedChanges": "[KO] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/ko/common.json b/fincept-terminal-desktop/public/locales/ko/common.json
index e49c1e047..dd040c251 100644
--- a/fincept-terminal-desktop/public/locales/ko/common.json
+++ b/fincept-terminal-desktop/public/locales/ko/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "로딩 중...",
- "error": "오류",
- "success": "성공",
- "save": "저장",
- "cancel": "취소",
- "delete": "삭제",
- "edit": "편집",
- "add": "추가",
- "search": "검색",
- "filter": "필터",
- "back": "뒤로",
- "next": "다음",
- "previous": "이전",
- "submit": "제출",
- "close": "닫기",
- "open": "열기",
- "yes": "예",
- "no": "아니요",
- "ok": "확인",
- "confirm": "확인",
- "language": "언어",
- "selectLanguage": "언어 선택"
-}
\ No newline at end of file
+ "settings": "[KO] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/ko/dashboard.json b/fincept-terminal-desktop/public/locales/ko/dashboard.json
index 867bb539b..3092ec5e0 100644
--- a/fincept-terminal-desktop/public/locales/ko/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/ko/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "맞춤형 대시보드",
- "live": "살다",
- "widgets": "위젯"
- },
- "buttons": {
- "addWidget": "위젯 추가",
- "saveLayout": "레이아웃 저장",
- "reset": "다시 놓기",
- "help": "돕다"
- },
"widgets": {
"loading": "로드 중...",
- "error": "오류",
"globalIndices": "글로벌 지수 - 상위 12위",
"forex": "외환 - 주요 쌍",
"crypto": "암호화폐",
@@ -20,8 +8,6 @@
"news": "소식",
"forum": "법정",
"watchlist": "관심 목록",
- "maritimeIntelligence": "해양 인텔리전스",
- "unknown": "알 수 없는 위젯 유형",
"index": "색인",
"symbol": "상징",
"price": "가격",
@@ -38,41 +24,22 @@
"pair": "쌍",
"rate": "비율",
"commodity": "상품",
- "globe3D": "3D 글로브",
- "vessels": "선박",
- "routes": "노선",
- "vol24h": "24시간 볼륨",
- "topTradeCorridors": "상위 무역 통로",
- "ships": "배송",
- "marketNews": "시장 뉴스",
- "secPressReleases": "SEC 보도자료",
- "cryptoNews": "암호화폐 뉴스",
- "trendingForum": "인기 포럼",
- "techStocks": "기술주"
- },
- "tips": {
- "drag": "재정렬하려면 위젯을 드래그하세요.",
- "resize": "오른쪽 하단에서 크기 조정",
- "remove": "X 버튼으로 위젯 제거",
- "responsive": "반응형 레이아웃 - 전체 너비 사용"
- },
- "loading": {
- "title": "대시보드 초기화 중",
- "description": "더 빠른 데이터 로드를 위해 데이터베이스 캐시를 설정하는 중...",
- "note": "처음 시작할 때 시간이 조금 걸립니다."
- },
- "empty": {
- "noWidgets": "대시보드에 위젯이 없습니다",
- "addFirst": "첫 번째 위젯을 추가하세요"
- },
- "status": {
- "version": "Fincept 맞춤형 대시보드 v2.0.0 | 드래그 앤 드롭 작업 공간",
- "layout": "공들여 나열한 것",
- "custom": "관습",
- "empty": "비어 있는",
- "active": "활동적인",
- "cache": "캐시: 활성화됨",
- "label": "상태"
+ "noActiveMarkets": "[KO] No active markets found",
+ "indicator": "[KO] INDICATOR",
+ "value": "[KO] VALUE",
+ "chg": "[KO] CHG",
+ "overallRisk": "[KO] OVERALL RISK",
+ "openEconomicsTab": "[KO] Open Economics Tab",
+ "openGeopoliticsTab": "[KO] Open Geopolitics Tab",
+ "openPolymarketTab": "[KO] Open Polymarket Tab",
+ "noPortfolioFound": "[KO] No portfolio found",
+ "createPortfolioHint": "[KO] Create one in Portfolio tab",
+ "openPortfolioTab": "[KO] Open Portfolio Tab",
+ "action": "[KO] ACTION",
+ "markets": "[KO] MARKETS",
+ "performanceTracker": "[KO] PERFORMANCE TRACKER",
+ "totalPnL": "[KO] TOTAL P&L",
+ "viewDetailedAnalytics": "[KO] View Detailed Analytics"
},
"messages": {
"layoutSaved": "대시보드 레이아웃이 저장되었습니다!",
diff --git a/fincept-terminal-desktop/public/locales/ko/geopolitics.json b/fincept-terminal-desktop/public/locales/ko/geopolitics.json
index ea1b8405d..87aaae8d4 100644
--- a/fincept-terminal-desktop/public/locales/ko/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/ko/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "지정학",
"messages": {
- "loading": "지정학 데이터 로딩..."
+ "retry": "[KO] RETRY"
+ },
+ "header": {
+ "prefix": "[KO] GEO>",
+ "title": "[KO] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[KO] EVENTS"
+ },
+ "status": {
+ "stale": "[KO] STALE",
+ "loading": "[KO] LOADING...",
+ "error": "[KO] ERROR:"
+ },
+ "filters": {
+ "country": "[KO] Country...",
+ "cities": "[KO] Cities...",
+ "category": "[KO] Category...",
+ "apply": "[KO] APPLY",
+ "clear": "[KO] CLEAR",
+ "clearAllCities": "[KO] Clear all cities",
+ "selectedLabel": "[KO] Selected:"
+ },
+ "panel": {
+ "title": "[KO] INFO PANEL",
+ "expand": "[KO] Expand panel",
+ "collapse": "[KO] Collapse panel",
+ "eventsLoaded": "[KO] EVENTS LOADED",
+ "onMapVisualization": "[KO] on map visualization",
+ "topCategories": "[KO] TOP CATEGORIES",
+ "topCountries": "[KO] TOP COUNTRIES",
+ "eventDetails": "[KO] EVENT DETAILS",
+ "close": "[KO] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[KO] Country:",
+ "city": "[KO] City:",
+ "keywords": "[KO] Keywords:",
+ "coords": "[KO] Coords:",
+ "date": "[KO] Date:",
+ "source": "[KO] Source:",
+ "viewArticle": "[KO] View Article"
+ },
+ "legend": {
+ "title": "[KO] EVENT CATEGORIES",
+ "armedConflict": "[KO] Armed Conflict",
+ "terrorism": "[KO] Terrorism",
+ "protests": "[KO] Protests",
+ "civilianViolence": "[KO] Civilian Violence",
+ "riots": "[KO] Riots",
+ "politicalViolence": "[KO] Political Violence",
+ "crisis": "[KO] Crisis",
+ "explosions": "[KO] Explosions",
+ "strategic": "[KO] Strategic",
+ "unclassified": "[KO] Unclassified"
+ },
+ "footer": {
+ "tabName": "[KO] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[KO] EVENTS",
+ "labelEngine": "[KO] ENGINE",
+ "engineValue": "[KO] DECK.GL v9.2",
+ "labelSource": "[KO] SOURCE",
+ "sourceValue": "[KO] NEWS-EVENTS API",
+ "labelSelected": "[KO] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ko/markets.json b/fincept-terminal-desktop/public/locales/ko/markets.json
index dd49de513..7a62fd8b6 100644
--- a/fincept-terminal-desktop/public/locales/ko/markets.json
+++ b/fincept-terminal-desktop/public/locales/ko/markets.json
@@ -9,13 +9,9 @@
"percentChange": "변동%",
"high": "고가",
"low": "저가",
- "loading": "로딩 중...",
"noData": "데이터 없음",
"refresh": "새로고침",
"auto": "자동",
"on": "켜기",
- "off": "끄기",
- "lastUpdate": "마지막 업데이트",
- "updating": "업데이트 중",
- "live": "실시간"
+ "off": "끄기"
}
diff --git a/fincept-terminal-desktop/public/locales/ko/news.json b/fincept-terminal-desktop/public/locales/ko/news.json
index 3b5e6b758..ddacc37e6 100644
--- a/fincept-terminal-desktop/public/locales/ko/news.json
+++ b/fincept-terminal-desktop/public/locales/ko/news.json
@@ -1,32 +1,63 @@
{
"title": "FINCEPT 터미널 전문 뉴스",
"header": {
- "liveFeed": "실시간 피드",
- "live": "라이브",
- "refresh": "새로고침",
- "updating": "업데이트 중...",
- "alerts": "알림",
- "sources": "소스",
- "status": "상태",
- "demoMode": "데모 모드",
- "articles": "기사",
- "activeSources": "활성 소스"
- },
- "autoRefresh": {
- "title": "자동 새로고침 간격",
- "minute": "분",
- "minutes": "분"
+ "refresh": "새로고침"
},
"messages": {
- "loadingFeeds": "피드 로딩 중...",
- "breaking": "속보"
- },
- "feeds": {
- "primary": "[KO] PRIMARY NEWS FEED",
- "secondary": "[KO] SECONDARY NEWS FEED",
- "additional": "[KO] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[KO] Loading feeds...",
+ "failedToLoad": "[KO] Failed to load RSS feeds",
+ "noCustomFeeds": "[KO] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[KO] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[KO] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[KO] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[KO] RSS FEED SETTINGS",
+ "subtitle": "[KO] MANAGE YOUR NEWS SOURCES",
+ "close": "[KO] CLOSE",
+ "myFeeds": "[KO] MY FEEDS",
+ "defaultFeeds": "[KO] DEFAULT FEEDS",
+ "noFeedsAvailable": "[KO] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[KO] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[KO] ADD NEW FEED",
+ "addNewRssFeed": "[KO] ADD NEW RSS FEED",
+ "editRssFeed": "[KO] EDIT RSS FEED",
+ "restoreDefaults": "[KO] RESTORE DEFAULTS",
+ "restoreAll": "[KO] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[KO] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[KO] DISPLAY NAME",
+ "sourceName": "[KO] SOURCE NAME (SHORT)",
+ "feedUrl": "[KO] RSS FEED URL",
+ "category": "[KO] CATEGORY",
+ "region": "[KO] REGION",
+ "required": "[KO] *",
+ "testUrl": "[KO] TEST URL",
+ "testing": "[KO] TESTING...",
+ "valid": "[KO] VALID",
+ "cancel": "[KO] CANCEL",
+ "saving": "[KO] SAVING...",
+ "addFeed": "[KO] ADD FEED",
+ "updateFeed": "[KO] UPDATE FEED",
+ "on": "[KO] ON",
+ "off": "[KO] OFF",
+ "default": "[KO] DEFAULT",
+ "total": "[KO] TOTAL",
+ "active": "[KO] ACTIVE",
+ "custom": "[KO] CUSTOM",
+ "placeholders": {
+ "displayName": "[KO] e.g., Bloomberg Markets",
+ "sourceName": "[KO] e.g., BLOOMBERG",
+ "feedUrl": "[KO] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[KO] Name is required",
+ "sourceRequired": "[KO] Source name is required",
+ "invalidUrl": "[KO] Please enter a valid URL",
+ "invalidRss": "[KO] URL does not appear to be a valid RSS feed",
+ "testFailed": "[KO] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[KO] Delete this RSS feed?",
+ "message": "[KO] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/ko/portfolio.json b/fincept-terminal-desktop/public/locales/ko/portfolio.json
index e0ebacfd1..ab18d4476 100644
--- a/fincept-terminal-desktop/public/locales/ko/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/ko/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "FINCEPT 포트폴리오 매니저",
- "header": {
- "live": "실시간",
- "updating": "업데이트 중",
- "newPortfolio": "새 포트폴리오",
- "refresh": "새로고침",
- "exportCsv": "CSV 내보내기"
- },
- "summary": {
- "totalValue": "총 가치",
- "dayPnl": "당일 손익",
- "totalPnl": "총 손익",
- "positions": "포지션"
- },
- "views": {
- "positions": "포지션",
- "addAsset": "자산 추가",
- "sellAsset": "자산 매도",
- "analytics": "분석",
- "history": "내역",
- "activeMgmt": "적극적 관리",
- "performance": "성과",
- "rebalance": "리밸런싱",
- "reports": "리포트",
- "alerts": "알림",
- "sectors": "섹터",
- "help": "도움말"
- },
- "sidebar": {
- "portfolios": "포트폴리오",
- "loading": "포트폴리오 로딩 중...",
- "noPortfolios": "아직 포트폴리오가 없습니다.",
- "clickCreate": "새 포트폴리오 클릭하여 생성.",
- "owner": "소유자",
- "currency": "통화"
- },
- "content": {
- "selectOrCreate": "포트폴리오를 선택하거나 새로 만들어 시작하세요",
- "loadingData": "포트폴리오 데이터 로딩 중...",
- "comingSoon": "곧 제공 예정..."
- },
- "modals": {
- "createNew": "새 포트폴리오 생성",
- "portfolioName": "포트폴리오 이름",
- "owner": "소유자",
- "currency": "통화",
- "cancel": "취소",
- "create": "생성",
- "addAssetTitle": "포트폴리오에 자산 추가",
- "sellAssetTitle": "자산 매도",
- "symbol": "심볼",
- "quantity": "수량",
- "price": "가격",
- "add": "추가",
- "sell": "매도"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | yfinance 연동 실시간 추적",
- "lastUpdated": "마지막 업데이트",
- "connected": "연결됨"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "새 포트폴리오 생성",
+ "portfolioName": "포트폴리오 이름",
+ "owner": "소유자",
+ "currency": "통화",
+ "cancel": "취소",
+ "create": "생성",
+ "addAssetTitle": "포트폴리오에 자산 추가",
+ "sellAssetTitle": "자산 매도",
+ "symbol": "심볼",
+ "quantity": "수량",
+ "price": "가격",
+ "add": "추가",
+ "sell": "매도"
+ },
+ "extracted": {
+ "areYouSureYou": "[KO] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/ko/reportBuilder.json b/fincept-terminal-desktop/public/locales/ko/reportBuilder.json
index 6a5b5af4d..a9442cc6d 100644
--- a/fincept-terminal-desktop/public/locales/ko/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/ko/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[KO] Load",
"save": "[KO] Save",
- "saving": "[KO] Saving...",
- "exportPdf": "[KO] Export PDF",
- "generating": "[KO] Generating..."
+ "saving": "[KO] Saving..."
},
"components": {
"title": "[KO] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/ko/settings.json b/fincept-terminal-desktop/public/locales/ko/settings.json
index c5e7c271d..97c533cc7 100644
--- a/fincept-terminal-desktop/public/locales/ko/settings.json
+++ b/fincept-terminal-desktop/public/locales/ko/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "탭 레이아웃",
"appearance": "모습",
"language": "언어",
- "storage": "스토리지 및 캐시"
+ "storage": "스토리지 및 캐시",
+ "notifications": "[KO] Notifications"
},
"credentials": {
"title": "API 자격 증명 관리",
@@ -46,7 +47,31 @@
"saveConfig": "구성 저장",
"reset": "다시 놓기",
"saveSuccess": "터미널 모양 및 키 매핑이 성공적으로 저장되었습니다.",
- "resetSuccess": "기본 모양 및 키 매핑으로 재설정"
+ "resetSuccess": "기본 모양 및 키 매핑으로 재설정",
+ "customColors": "[KO] Custom Colors",
+ "customColorsTitle": "[KO] CUSTOM COLORS",
+ "colorPrimary": "[KO] Primary",
+ "colorSecondary": "[KO] Secondary",
+ "colorSuccess": "[KO] Success",
+ "colorAlert": "[KO] Alert",
+ "colorWarning": "[KO] Warning",
+ "colorInfo": "[KO] Info",
+ "colorAccent": "[KO] Accent",
+ "colorPurple": "[KO] Purple",
+ "colorText": "[KO] Text",
+ "colorTextMuted": "[KO] Text Muted",
+ "colorBackground": "[KO] Background",
+ "colorPanel": "[KO] Panel",
+ "layoutSpacing": "[KO] LAYOUT & SPACING",
+ "contentDensity": "[KO] CONTENT DENSITY",
+ "borderRadius": "[KO] BORDER RADIUS",
+ "borderStyle": "[KO] BORDER STYLE",
+ "lineHeight": "[KO] LINE HEIGHT",
+ "letterSpacing": "[KO] LETTER SPACING",
+ "effects": "[KO] EFFECTS",
+ "widgetOpacity": "[KO] WIDGET OPACITY",
+ "enableGlow": "[KO] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[KO] GLOW INTENSITY"
},
"stockSymbols": {
"title": "주식 기호 데이터베이스",
@@ -65,17 +90,8 @@
"tip": "팁: 탭을 끌어서 순서를 바꾸세요. 화살표 버튼을 사용하여 헤더와 메뉴 섹션 간에 탭을 이동하세요. 변경 사항은 자동으로 저장됩니다."
},
"llm": {
- "title": "LLM 구성",
- "description": "AI 모델 및 공급자 구성",
"connected": "연결됨",
- "disconnected": "연결이 끊김",
- "provider": "AI 제공자",
- "globalSettings": "글로벌 AI 설정",
- "temperature": "온도",
- "maxTokens": "최대 토큰",
- "systemPrompt": "시스템 프롬프트",
- "modelLibrary": "모델 라이브러리",
- "multiModelConfigs": "다중 모델 구성"
+ "disconnected": "연결이 끊김"
},
"buttons": {
"save": "구하다",
@@ -86,5 +102,18 @@
"database": "데이터베이스: SQLite",
"storage": "저장: 파일 기반",
"secureStorage": "모든 데이터는 fincept_terminal.db에 안전하게 저장됩니다."
+ },
+ "notifications": {
+ "title": "[KO] NOTIFICATION PROVIDERS",
+ "description": "[KO] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[KO] Event Filters",
+ "eventFilterDescription": "[KO] Choose which notification types to forward to external providers.",
+ "providers": "[KO] Providers",
+ "enabled": "[KO] Enabled",
+ "disabled": "[KO] Disabled",
+ "testButton": "[KO] TEST",
+ "testSuccess": "[KO] Test notification sent successfully!",
+ "testFailed": "[KO] Failed to send test notification. Check your configuration.",
+ "saved": "[KO] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ko/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/ko/surfaceAnalytics.json
new file mode 100644
index 000000000..684284097
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/ko/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[KO] SURFACE ANALYTICS",
+ "initializing": "[KO] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[KO] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[KO] VOL SURFACE",
+ "correlation": "[KO] CORRELATION",
+ "yieldCurve": "[KO] YIELD CURVE",
+ "pca": "[KO] PCA FACTORS"
+ },
+ "demoData": "[KO] DEMO DATA",
+ "demoDataSynthetic": "[KO] DEMO DATA (synthetic)",
+ "synthetic": "[KO] SYNTHETIC",
+ "manual": "[KO] MANUAL",
+ "error": "[KO] ERROR",
+ "ready": "[KO] READY",
+ "metrics": "[KO] Metrics",
+ "updated": "[KO] Updated",
+ "clickRefresh": "[KO] Click REFRESH to load data",
+ "refresh": "[KO] REFRESH",
+ "noApiKey": "[KO] NO API KEY",
+ "lastUpdate": "[KO] LAST UPDATE",
+ "loadingData": "[KO] LOADING DATA...",
+ "noDataLoaded": "[KO] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[KO] IV SURFACE METRICS",
+ "correlationMetrics": "[KO] CORRELATION METRICS",
+ "yieldCurveMetrics": "[KO] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[KO] PCA FACTOR METRICS",
+ "dataInfo": "[KO] DATA INFO",
+ "source": "[KO] SOURCE",
+ "frequency": "[KO] FREQUENCY",
+ "quality": "[KO] QUALITY",
+ "correlationScale": "[KO] CORRELATION SCALE",
+ "strongPositive": "[KO] Strong Positive (0.7-1.0)",
+ "neutral": "[KO] Neutral (0.3-0.7)",
+ "strongNegative": "[KO] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[KO] IV INTERPRETATION",
+ "highIv": "[KO] High IV = Expensive Options",
+ "lowIv": "[KO] Low IV = Cheap Options",
+ "skew": "[KO] Skew = Put/Call IV Diff",
+ "termStructure": "[KO] Term Structure = Time Effect",
+ "pcaInterpretation": "[KO] PCA INTERPRETATION",
+ "pc1": "[KO] PC1 = Market Factor",
+ "pc2": "[KO] PC2 = Size/Value Factor",
+ "pc3": "[KO] PC3 = Sector Rotation",
+ "higherVar": "[KO] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[KO] STRIKE",
+ "dte": "[KO] DTE",
+ "iv": "[KO] IV",
+ "correlation": "[KO] CORRELATION",
+ "maturity": "[KO] MATURITY",
+ "yield": "[KO] YIELD",
+ "loading": "[KO] LOADING",
+ "strikePrice": "[KO] STRIKE PRICE",
+ "daysToExpiry": "[KO] DAYS TO EXPIRY",
+ "impliedVol": "[KO] IMPLIED VOL (%)",
+ "assetPairIndex": "[KO] ASSET PAIR INDEX",
+ "timeDays": "[KO] TIME (DAYS)",
+ "correlationCoeff": "[KO] CORRELATION COEFF",
+ "maturityMonths": "[KO] MATURITY (MONTHS)",
+ "historicalDays": "[KO] HISTORICAL DAYS",
+ "yieldPercent": "[KO] YIELD (%)",
+ "principalComponent": "[KO] PRINCIPAL COMPONENT",
+ "assetIndex": "[KO] ASSET INDEX",
+ "factorLoading": "[KO] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[KO] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[KO] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[KO] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[KO] DAY ROLLING",
+ "yieldCurve": "[KO] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[KO] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[KO] FAILED TO LOAD DATA",
+ "authFailed": "[KO] AUTHENTICATION FAILED",
+ "authFailedHelp": "[KO] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[KO] ACCESS DENIED",
+ "accessDeniedHelp": "[KO] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[KO] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[KO] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[KO] DATA TIMEFRAME",
+ "schema": "[KO] Schema",
+ "description": "[KO] Description",
+ "recordsPerDay": "[KO] Records/Day",
+ "highFrequencyWarning": "[KO] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[KO] Data Volume"
+ },
+ "settings": {
+ "title": "[KO] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[KO] DATABENTO API KEY",
+ "configured": "[KO] CONFIGURED",
+ "invalidFormat": "[KO] INVALID FORMAT",
+ "apiKeyConfigured": "[KO] API key is configured (db-*****)",
+ "remove": "[KO] REMOVE",
+ "enterApiKey": "[KO] Enter your Databento API key (db-*****)",
+ "save": "[KO] SAVE",
+ "saving": "[KO] SAVING...",
+ "getApiKeyFrom": "[KO] Get your API key from",
+ "dashboardApiKeys": "[KO] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[KO] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[KO] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[KO] CORRELATION ASSETS",
+ "addSymbol": "[KO] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[KO] Reset to defaults",
+ "historicalDateRange": "[KO] HISTORICAL DATE RANGE",
+ "start": "[KO] Start",
+ "end": "[KO] End",
+ "autoRefreshInterval": "[KO] AUTO REFRESH INTERVAL",
+ "manualOnly": "[KO] Manual Only",
+ "every1min": "[KO] Every 1 minute",
+ "every5min": "[KO] Every 5 minutes",
+ "every15min": "[KO] Every 15 minutes",
+ "every1hour": "[KO] Every 1 hour",
+ "browseDatasets": "[KO] BROWSE DATASETS",
+ "costEstimator": "[KO] COST ESTIMATOR",
+ "referenceData": "[KO] REFERENCE DATA",
+ "orderBook": "[KO] ORDER BOOK",
+ "liveStreaming": "[KO] LIVE STREAMING",
+ "active": "[KO] ACTIVE",
+ "futuresCme": "[KO] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[KO] BATCH DOWNLOADS",
+ "additionalSchemas": "[KO] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[KO] TRADES, IMBALANCE, STATUS",
+ "cancel": "[KO] CANCEL",
+ "saveChanges": "[KO] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[KO] BATCH DOWNLOADS",
+ "newBatchJob": "[KO] NEW BATCH JOB",
+ "dataset": "[KO] Dataset",
+ "schema": "[KO] Schema",
+ "symbolsCommaSeparated": "[KO] Symbols (comma-separated)",
+ "startDate": "[KO] Start Date",
+ "endDate": "[KO] End Date",
+ "encoding": "[KO] Encoding",
+ "compression": "[KO] Compression",
+ "submitJob": "[KO] SUBMIT JOB",
+ "noBatchJobs": "[KO] No batch jobs found. Click + to create one.",
+ "records": "[KO] records",
+ "download": "[KO] Download",
+ "files": "[KO] FILES",
+ "jobsExpireNotice": "[KO] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[KO] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[KO] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[KO] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[KO] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[KO] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[KO] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[KO] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[KO] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[KO] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[KO] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[KO] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[KO] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[KO] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[KO] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[KO] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[KO] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[KO] [EN] common.or",
+ "note": "[KO] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/ko/tabs.json b/fincept-terminal-desktop/public/locales/ko/tabs.json
index 5a738e501..8848b6f85 100644
--- a/fincept-terminal-desktop/public/locales/ko/tabs.json
+++ b/fincept-terminal-desktop/public/locales/ko/tabs.json
@@ -5,29 +5,7 @@
"news": "뉴스",
"portfolio": "포트폴리오",
"backtesting": "백테스팅",
- "watchlist": "관심목록",
- "research": "리서치",
- "screener": "스크리너",
"chat": "AI 채팅",
- "agents": "에이전트",
- "settings": "설정",
"profile": "프로필"
- },
- "functionKeys": {
- "f1": "대시",
- "f2": "시장",
- "f3": "뉴스",
- "f4": "포트",
- "f5": "백테",
- "f6": "관심",
- "f7": "리서",
- "f8": "스크",
- "f9": "트레",
- "f10": "AI",
- "f11": "전체",
- "f12": "프로"
- },
- "labels": {
- "moreTabs": "도구 모음 메뉴에 더 많은 탭"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ko/watchlist.json b/fincept-terminal-desktop/public/locales/ko/watchlist.json
index 852a15407..ef776a494 100644
--- a/fincept-terminal-desktop/public/locales/ko/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/ko/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "관심목록",
- "header": {
- "export": "내보내기",
- "updating": "업데이트 중",
- "live": "실시간"
- },
"sidebar": {
- "groups": "관심목록 그룹",
- "new": "새로 만들기",
"noWatchlists": "관심목록이 없습니다.",
"clickNew": "새로 만들기를 클릭하세요.",
- "stocks": "종목",
- "marketMovers": "시장 주도주",
- "gainer": "상승",
- "loser": "하락",
- "volumeLeaders": "거래량 상위"
- },
- "emptyState": {
- "selectWatchlist": "관심목록을 선택하거나 새로 만들어 시작하세요"
- },
- "list": {
- "symbols": "심볼"
+ "stocks": "종목"
}
}
diff --git a/fincept-terminal-desktop/public/locales/pl/codeEditor.json b/fincept-terminal-desktop/public/locales/pl/codeEditor.json
index 90b53e5b3..e7264bc5c 100644
--- a/fincept-terminal-desktop/public/locales/pl/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/pl/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "EDYTOR KODU",
"header": {
- "packages": "PAKIETY"
+ "finscriptIde": "[PL] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "NOWY PLIK",
- "new": "NOWY",
- "open": "OTWÓRZ",
- "save": "ZAPISZ",
"run": "URUCHOM",
"running": "URUCHAMIANIE...",
- "runAll": "URUCHOM WSZYSTKO",
- "history": "HISTORIA"
+ "toggleExplorer": "[PL] Toggle Explorer (Ctrl+B)",
+ "openFile": "[PL] Open File",
+ "saveShortcut": "[PL] Save (Ctrl+S)",
+ "findShortcut": "[PL] Find (Ctrl+F)",
+ "runShortcut": "[PL] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "EDYTOR FINSCRIPT"
},
- "packages": {
- "clickToLoad": "Kliknij aby załadować...",
- "load": "ZAŁADUJ PAKIETY"
+ "explorer": {
+ "title": "[PL] EXPLORER",
+ "openFiles": "[PL] OPEN FILES",
+ "examples": "[PL] EXAMPLES",
+ "runHistory": "[PL] RUN HISTORY",
+ "finscriptEngine": "[PL] FinScript Engine"
},
- "history": {
- "title": "HISTORIA NOTEBOOKÓW",
- "loading": "Ładowanie historii...",
- "empty": "Brak historii notebooków"
+ "output": {
+ "title": "[PL] OUTPUT",
+ "success": "[PL] SUCCESS",
+ "error": "[PL] ERROR",
+ "executing": "[PL] EXECUTING FINSCRIPT...",
+ "noOutput": "[PL] No output yet",
+ "pressToRun": "[PL] Press Ctrl+Enter to run",
+ "completed": "[PL] COMPLETED",
+ "failed": "[PL] FAILED",
+ "signals": "[PL] signals",
+ "clear": "[PL] CLEAR",
+ "errors": "[PL] ERRORS",
+ "signalsSection": "[PL] SIGNALS",
+ "outputSection": "[PL] OUTPUT",
+ "charts": "[PL] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[PL] OHLC",
+ "histogram": "[PL] Histogram",
+ "line": "[PL] Line",
+ "points": "[PL] points"
+ },
+ "statusBar": {
+ "modified": "[PL] MODIFIED",
+ "showOutput": "[PL] SHOW OUTPUT",
+ "encoding": "[PL] UTF-8",
+ "spaces": "[PL] 4 Spaces",
+ "runShortcut": "[PL] Ctrl+Enter: Run",
+ "lines": "[PL] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[PL] Close file without saving?",
+ "unsavedChanges": "[PL] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/pl/common.json b/fincept-terminal-desktop/public/locales/pl/common.json
index 54e8f994e..5261dba73 100644
--- a/fincept-terminal-desktop/public/locales/pl/common.json
+++ b/fincept-terminal-desktop/public/locales/pl/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Ładowanie...",
- "error": "Błąd",
- "success": "Sukces",
- "save": "Zapisz",
- "cancel": "Anuluj",
- "delete": "Usuń",
- "edit": "Edytuj",
- "add": "Dodaj",
- "search": "Szukaj",
- "filter": "Filtruj",
- "back": "Wstecz",
- "next": "Dalej",
- "previous": "Poprzedni",
- "submit": "Wyślij",
- "close": "Zamknij",
- "open": "Otwórz",
- "yes": "Tak",
- "no": "Nie",
- "ok": "OK",
- "confirm": "Potwierdź",
- "language": "Język",
- "selectLanguage": "Wybierz język"
-}
\ No newline at end of file
+ "settings": "[PL] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/pl/dashboard.json b/fincept-terminal-desktop/public/locales/pl/dashboard.json
index 9d6fe6fbe..ee7123541 100644
--- a/fincept-terminal-desktop/public/locales/pl/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/pl/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "DOSTOSOWALNY PANEL ROZDZIELNY",
- "live": "NA ŻYWO",
- "widgets": "WIDŻETY"
- },
- "buttons": {
- "addWidget": "DODAJ WIDŻET",
- "saveLayout": "ZAPISZ UKŁAD",
- "reset": "NASTAWIĆ",
- "help": "POMOC"
- },
"widgets": {
"loading": "Załadunek...",
- "error": "Błąd",
"globalIndices": "Globalne indeksy - Top 12",
"forex": "Forex – główne pary",
"crypto": "KRYPTOWALUTY",
@@ -20,8 +8,6 @@
"news": "AKTUALNOŚCI",
"forum": "FORUM",
"watchlist": "LISTA OBSERWOWANYCH",
- "maritimeIntelligence": "Wywiad Morski",
- "unknown": "Nieznany typ widżetu",
"index": "INDEKS",
"symbol": "SYMBOL",
"price": "CENA",
@@ -38,41 +24,22 @@
"pair": "PARA",
"rate": "WSKAŹNIK",
"commodity": "TOWAR",
- "globe3D": "GLOB 3D",
- "vessels": "STATKI",
- "routes": "TRASY",
- "vol24h": "TOM 24H",
- "topTradeCorridors": "NAJLEPSZE KORYTARZE HANDLOWE",
- "ships": "statki",
- "marketNews": "Wiadomości rynkowe",
- "secPressReleases": "Komunikaty prasowe SEC",
- "cryptoNews": "Wiadomości kryptograficzne",
- "trendingForum": "Forum trendów",
- "techStocks": "Akcje technologiczne"
- },
- "tips": {
- "drag": "Przeciągnij widżety, aby zmienić ich kolejność",
- "resize": "Zmień rozmiar od prawego dolnego rogu",
- "remove": "Usuń widżety za pomocą przycisku X",
- "responsive": "Układ responsywny - wykorzystuje całą szerokość"
- },
- "loading": {
- "title": "Inicjowanie pulpitu nawigacyjnego",
- "description": "Konfigurowanie pamięci podręcznej bazy danych w celu szybszego ładowania danych...",
- "note": "Przy pierwszym uruchomieniu zajmie to tylko chwilę"
- },
- "empty": {
- "noWidgets": "Brak widżetów na desce rozdzielczej",
- "addFirst": "DODAJ SWOJ PIERWSZY WIDŻET"
- },
- "status": {
- "version": "Konfigurowalny pulpit nawigacyjny Fincept v2.0.0 | Przeciągnij i upuść obszar roboczy",
- "layout": "Układ",
- "custom": "Zwyczaj",
- "empty": "Pusty",
- "active": "AKTYWNY",
- "cache": "Pamięć podręczna: WŁĄCZONA",
- "label": "Status"
+ "noActiveMarkets": "[PL] No active markets found",
+ "indicator": "[PL] INDICATOR",
+ "value": "[PL] VALUE",
+ "chg": "[PL] CHG",
+ "overallRisk": "[PL] OVERALL RISK",
+ "openEconomicsTab": "[PL] Open Economics Tab",
+ "openGeopoliticsTab": "[PL] Open Geopolitics Tab",
+ "openPolymarketTab": "[PL] Open Polymarket Tab",
+ "noPortfolioFound": "[PL] No portfolio found",
+ "createPortfolioHint": "[PL] Create one in Portfolio tab",
+ "openPortfolioTab": "[PL] Open Portfolio Tab",
+ "action": "[PL] ACTION",
+ "markets": "[PL] MARKETS",
+ "performanceTracker": "[PL] PERFORMANCE TRACKER",
+ "totalPnL": "[PL] TOTAL P&L",
+ "viewDetailedAnalytics": "[PL] View Detailed Analytics"
},
"messages": {
"layoutSaved": "Układ pulpitu nawigacyjnego został zapisany!",
diff --git a/fincept-terminal-desktop/public/locales/pl/geopolitics.json b/fincept-terminal-desktop/public/locales/pl/geopolitics.json
index 43982685f..9c4d8b423 100644
--- a/fincept-terminal-desktop/public/locales/pl/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/pl/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "GEOPOLITYKA",
"messages": {
- "loading": "Ładowanie danych..."
+ "retry": "[PL] RETRY"
+ },
+ "header": {
+ "prefix": "[PL] GEO>",
+ "title": "[PL] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[PL] EVENTS"
+ },
+ "status": {
+ "stale": "[PL] STALE",
+ "loading": "[PL] LOADING...",
+ "error": "[PL] ERROR:"
+ },
+ "filters": {
+ "country": "[PL] Country...",
+ "cities": "[PL] Cities...",
+ "category": "[PL] Category...",
+ "apply": "[PL] APPLY",
+ "clear": "[PL] CLEAR",
+ "clearAllCities": "[PL] Clear all cities",
+ "selectedLabel": "[PL] Selected:"
+ },
+ "panel": {
+ "title": "[PL] INFO PANEL",
+ "expand": "[PL] Expand panel",
+ "collapse": "[PL] Collapse panel",
+ "eventsLoaded": "[PL] EVENTS LOADED",
+ "onMapVisualization": "[PL] on map visualization",
+ "topCategories": "[PL] TOP CATEGORIES",
+ "topCountries": "[PL] TOP COUNTRIES",
+ "eventDetails": "[PL] EVENT DETAILS",
+ "close": "[PL] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[PL] Country:",
+ "city": "[PL] City:",
+ "keywords": "[PL] Keywords:",
+ "coords": "[PL] Coords:",
+ "date": "[PL] Date:",
+ "source": "[PL] Source:",
+ "viewArticle": "[PL] View Article"
+ },
+ "legend": {
+ "title": "[PL] EVENT CATEGORIES",
+ "armedConflict": "[PL] Armed Conflict",
+ "terrorism": "[PL] Terrorism",
+ "protests": "[PL] Protests",
+ "civilianViolence": "[PL] Civilian Violence",
+ "riots": "[PL] Riots",
+ "politicalViolence": "[PL] Political Violence",
+ "crisis": "[PL] Crisis",
+ "explosions": "[PL] Explosions",
+ "strategic": "[PL] Strategic",
+ "unclassified": "[PL] Unclassified"
+ },
+ "footer": {
+ "tabName": "[PL] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[PL] EVENTS",
+ "labelEngine": "[PL] ENGINE",
+ "engineValue": "[PL] DECK.GL v9.2",
+ "labelSource": "[PL] SOURCE",
+ "sourceValue": "[PL] NEWS-EVENTS API",
+ "labelSelected": "[PL] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/pl/markets.json b/fincept-terminal-desktop/public/locales/pl/markets.json
index 6e9f24d1e..a1e7a1915 100644
--- a/fincept-terminal-desktop/public/locales/pl/markets.json
+++ b/fincept-terminal-desktop/public/locales/pl/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%ZM",
"high": "MAX",
"low": "MIN",
- "loading": "Ładowanie...",
"noData": "Brak danych",
"refresh": "ODŚWIEŻ",
"auto": "AUTO",
"on": "WŁ",
- "off": "WYŁ",
- "lastUpdate": "OSTATNIA AKTUALIZACJA",
- "updating": "AKTUALIZACJA",
- "live": "NA ŻYWO"
+ "off": "WYŁ"
}
diff --git a/fincept-terminal-desktop/public/locales/pl/news.json b/fincept-terminal-desktop/public/locales/pl/news.json
index 63462d924..f380921e9 100644
--- a/fincept-terminal-desktop/public/locales/pl/news.json
+++ b/fincept-terminal-desktop/public/locales/pl/news.json
@@ -1,32 +1,63 @@
{
"title": "PROFESJONALNE WIADOMOŚCI TERMINALA FINCEPT",
"header": {
- "liveFeed": "NA ŻYWO",
- "live": "LIVE",
- "refresh": "ODŚWIEŻ",
- "updating": "AKTUALIZACJA...",
- "alerts": "ALERTY",
- "sources": "ŹRÓDŁA",
- "status": "STATUS",
- "demoMode": "TRYB DEMO",
- "articles": "ARTYKUŁY",
- "activeSources": "AKTYWNE ŹRÓDŁA"
- },
- "autoRefresh": {
- "title": "INTERWAŁ AUTOMATYCZNEGO ODŚWIEŻANIA",
- "minute": "minuta",
- "minutes": "minut"
+ "refresh": "ODŚWIEŻ"
},
"messages": {
- "loadingFeeds": "Ładowanie kanałów...",
- "breaking": "PILNE"
- },
- "feeds": {
- "primary": "[PL] PRIMARY NEWS FEED",
- "secondary": "[PL] SECONDARY NEWS FEED",
- "additional": "[PL] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[PL] Loading feeds...",
+ "failedToLoad": "[PL] Failed to load RSS feeds",
+ "noCustomFeeds": "[PL] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[PL] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[PL] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[PL] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[PL] RSS FEED SETTINGS",
+ "subtitle": "[PL] MANAGE YOUR NEWS SOURCES",
+ "close": "[PL] CLOSE",
+ "myFeeds": "[PL] MY FEEDS",
+ "defaultFeeds": "[PL] DEFAULT FEEDS",
+ "noFeedsAvailable": "[PL] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[PL] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[PL] ADD NEW FEED",
+ "addNewRssFeed": "[PL] ADD NEW RSS FEED",
+ "editRssFeed": "[PL] EDIT RSS FEED",
+ "restoreDefaults": "[PL] RESTORE DEFAULTS",
+ "restoreAll": "[PL] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[PL] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[PL] DISPLAY NAME",
+ "sourceName": "[PL] SOURCE NAME (SHORT)",
+ "feedUrl": "[PL] RSS FEED URL",
+ "category": "[PL] CATEGORY",
+ "region": "[PL] REGION",
+ "required": "[PL] *",
+ "testUrl": "[PL] TEST URL",
+ "testing": "[PL] TESTING...",
+ "valid": "[PL] VALID",
+ "cancel": "[PL] CANCEL",
+ "saving": "[PL] SAVING...",
+ "addFeed": "[PL] ADD FEED",
+ "updateFeed": "[PL] UPDATE FEED",
+ "on": "[PL] ON",
+ "off": "[PL] OFF",
+ "default": "[PL] DEFAULT",
+ "total": "[PL] TOTAL",
+ "active": "[PL] ACTIVE",
+ "custom": "[PL] CUSTOM",
+ "placeholders": {
+ "displayName": "[PL] e.g., Bloomberg Markets",
+ "sourceName": "[PL] e.g., BLOOMBERG",
+ "feedUrl": "[PL] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[PL] Name is required",
+ "sourceRequired": "[PL] Source name is required",
+ "invalidUrl": "[PL] Please enter a valid URL",
+ "invalidRss": "[PL] URL does not appear to be a valid RSS feed",
+ "testFailed": "[PL] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[PL] Delete this RSS feed?",
+ "message": "[PL] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/pl/portfolio.json b/fincept-terminal-desktop/public/locales/pl/portfolio.json
index f02f9cd48..e5de652b0 100644
--- a/fincept-terminal-desktop/public/locales/pl/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/pl/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "MENEDŻER PORTFELA FINCEPT",
- "header": {
- "live": "NA ŻYWO",
- "updating": "AKTUALIZACJA",
- "newPortfolio": "NOWY PORTFEL",
- "refresh": "ODŚWIEŻ",
- "exportCsv": "EKSPORT CSV"
- },
- "summary": {
- "totalValue": "WARTOŚĆ CAŁKOWITA",
- "dayPnl": "Z/S DNIA",
- "totalPnl": "CAŁKOWITY Z/S",
- "positions": "POZYCJE"
- },
- "views": {
- "positions": "POZYCJE",
- "addAsset": "DODAJ AKTYWO",
- "sellAsset": "SPRZEDAJ AKTYWO",
- "analytics": "ANALITYKA",
- "history": "HISTORIA",
- "activeMgmt": "AKTYWNE ZARZĄDZANIE",
- "performance": "WYDAJNOŚĆ",
- "rebalance": "REBALANS",
- "reports": "RAPORTY",
- "alerts": "ALERTY",
- "sectors": "SEKTORY",
- "help": "POMOC"
- },
- "sidebar": {
- "portfolios": "PORTFELE",
- "loading": "Ładowanie portfeli...",
- "noPortfolios": "Brak portfeli.",
- "clickCreate": "Kliknij NOWY PORTFEL aby utworzyć.",
- "owner": "Właściciel",
- "currency": "Waluta"
- },
- "content": {
- "selectOrCreate": "Wybierz portfel lub utwórz nowy aby rozpocząć",
- "loadingData": "Ładowanie danych portfela...",
- "comingSoon": "widok wkrótce..."
- },
- "modals": {
- "createNew": "UTWÓRZ NOWY PORTFEL",
- "portfolioName": "NAZWA PORTFELA",
- "owner": "WŁAŚCICIEL",
- "currency": "WALUTA",
- "cancel": "ANULUJ",
- "create": "UTWÓRZ",
- "addAssetTitle": "DODAJ AKTYWO DO PORTFELA",
- "sellAssetTitle": "SPRZEDAJ AKTYWO",
- "symbol": "SYMBOL",
- "quantity": "ILOŚĆ",
- "price": "CENA",
- "add": "DODAJ",
- "sell": "SPRZEDAJ"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Śledzenie w czasie rzeczywistym z integracją yfinance",
- "lastUpdated": "Ostatnia Aktualizacja",
- "connected": "POŁĄCZONY"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "UTWÓRZ NOWY PORTFEL",
+ "portfolioName": "NAZWA PORTFELA",
+ "owner": "WŁAŚCICIEL",
+ "currency": "WALUTA",
+ "cancel": "ANULUJ",
+ "create": "UTWÓRZ",
+ "addAssetTitle": "DODAJ AKTYWO DO PORTFELA",
+ "sellAssetTitle": "SPRZEDAJ AKTYWO",
+ "symbol": "SYMBOL",
+ "quantity": "ILOŚĆ",
+ "price": "CENA",
+ "add": "DODAJ",
+ "sell": "SPRZEDAJ"
+ },
+ "extracted": {
+ "areYouSureYou": "[PL] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/pl/reportBuilder.json b/fincept-terminal-desktop/public/locales/pl/reportBuilder.json
index 607602a1e..bec8a623f 100644
--- a/fincept-terminal-desktop/public/locales/pl/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/pl/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[PL] Load",
"save": "[PL] Save",
- "saving": "[PL] Saving...",
- "exportPdf": "[PL] Export PDF",
- "generating": "[PL] Generating..."
+ "saving": "[PL] Saving..."
},
"components": {
"title": "[PL] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/pl/settings.json b/fincept-terminal-desktop/public/locales/pl/settings.json
index 2982e58ba..b0bffa7a4 100644
--- a/fincept-terminal-desktop/public/locales/pl/settings.json
+++ b/fincept-terminal-desktop/public/locales/pl/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Układ zakładek",
"appearance": "Wygląd",
"language": "Język",
- "storage": "Przechowywanie i pamięć podręczna"
+ "storage": "Przechowywanie i pamięć podręczna",
+ "notifications": "[PL] Notifications"
},
"credentials": {
"title": "ZARZĄDZANIE UPRAWNIENIAMI API",
@@ -46,7 +47,31 @@
"saveConfig": "ZAPISZ KONFIGURACJĘ",
"reset": "NASTAWIĆ",
"saveSuccess": "Wygląd terminala i mapowania klawiszy zostały pomyślnie zapisane",
- "resetSuccess": "Przywróć domyślny wygląd i mapowania klawiszy"
+ "resetSuccess": "Przywróć domyślny wygląd i mapowania klawiszy",
+ "customColors": "[PL] Custom Colors",
+ "customColorsTitle": "[PL] CUSTOM COLORS",
+ "colorPrimary": "[PL] Primary",
+ "colorSecondary": "[PL] Secondary",
+ "colorSuccess": "[PL] Success",
+ "colorAlert": "[PL] Alert",
+ "colorWarning": "[PL] Warning",
+ "colorInfo": "[PL] Info",
+ "colorAccent": "[PL] Accent",
+ "colorPurple": "[PL] Purple",
+ "colorText": "[PL] Text",
+ "colorTextMuted": "[PL] Text Muted",
+ "colorBackground": "[PL] Background",
+ "colorPanel": "[PL] Panel",
+ "layoutSpacing": "[PL] LAYOUT & SPACING",
+ "contentDensity": "[PL] CONTENT DENSITY",
+ "borderRadius": "[PL] BORDER RADIUS",
+ "borderStyle": "[PL] BORDER STYLE",
+ "lineHeight": "[PL] LINE HEIGHT",
+ "letterSpacing": "[PL] LETTER SPACING",
+ "effects": "[PL] EFFECTS",
+ "widgetOpacity": "[PL] WIDGET OPACITY",
+ "enableGlow": "[PL] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[PL] GLOW INTENSITY"
},
"stockSymbols": {
"title": "Baza danych symboli giełdowych",
@@ -65,17 +90,8 @@
"tip": "WSKAZÓWKA: Przeciągnij karty, aby zmienić ich kolejność. Użyj przycisków strzałek, aby przenosić karty pomiędzy sekcjami nagłówka i menu. Zmiany są zapisywane automatycznie."
},
"llm": {
- "title": "KONFIGURACJA LLM",
- "description": "Skonfiguruj modele i dostawców AI",
"connected": "POŁĄCZONY",
- "disconnected": "BEZŁADNY",
- "provider": "DOSTAWCA AI",
- "globalSettings": "GLOBALNE USTAWIENIA AI",
- "temperature": "TEMPERATURA",
- "maxTokens": "MAX ŻETONÓW",
- "systemPrompt": "WSKAZÓWKA SYSTEMOWA",
- "modelLibrary": "BIBLIOTEKA MODELI",
- "multiModelConfigs": "Konfiguracje wielu modeli"
+ "disconnected": "BEZŁADNY"
},
"buttons": {
"save": "RATOWAĆ",
@@ -86,5 +102,18 @@
"database": "Baza danych: SQLite",
"storage": "Przechowywanie: oparte na plikach",
"secureStorage": "Wszystkie dane są bezpiecznie przechowywane w fincept_terminal.db"
+ },
+ "notifications": {
+ "title": "[PL] NOTIFICATION PROVIDERS",
+ "description": "[PL] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[PL] Event Filters",
+ "eventFilterDescription": "[PL] Choose which notification types to forward to external providers.",
+ "providers": "[PL] Providers",
+ "enabled": "[PL] Enabled",
+ "disabled": "[PL] Disabled",
+ "testButton": "[PL] TEST",
+ "testSuccess": "[PL] Test notification sent successfully!",
+ "testFailed": "[PL] Failed to send test notification. Check your configuration.",
+ "saved": "[PL] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/pl/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/pl/surfaceAnalytics.json
new file mode 100644
index 000000000..10ec0d157
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/pl/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[PL] SURFACE ANALYTICS",
+ "initializing": "[PL] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[PL] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[PL] VOL SURFACE",
+ "correlation": "[PL] CORRELATION",
+ "yieldCurve": "[PL] YIELD CURVE",
+ "pca": "[PL] PCA FACTORS"
+ },
+ "demoData": "[PL] DEMO DATA",
+ "demoDataSynthetic": "[PL] DEMO DATA (synthetic)",
+ "synthetic": "[PL] SYNTHETIC",
+ "manual": "[PL] MANUAL",
+ "error": "[PL] ERROR",
+ "ready": "[PL] READY",
+ "metrics": "[PL] Metrics",
+ "updated": "[PL] Updated",
+ "clickRefresh": "[PL] Click REFRESH to load data",
+ "refresh": "[PL] REFRESH",
+ "noApiKey": "[PL] NO API KEY",
+ "lastUpdate": "[PL] LAST UPDATE",
+ "loadingData": "[PL] LOADING DATA...",
+ "noDataLoaded": "[PL] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[PL] IV SURFACE METRICS",
+ "correlationMetrics": "[PL] CORRELATION METRICS",
+ "yieldCurveMetrics": "[PL] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[PL] PCA FACTOR METRICS",
+ "dataInfo": "[PL] DATA INFO",
+ "source": "[PL] SOURCE",
+ "frequency": "[PL] FREQUENCY",
+ "quality": "[PL] QUALITY",
+ "correlationScale": "[PL] CORRELATION SCALE",
+ "strongPositive": "[PL] Strong Positive (0.7-1.0)",
+ "neutral": "[PL] Neutral (0.3-0.7)",
+ "strongNegative": "[PL] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[PL] IV INTERPRETATION",
+ "highIv": "[PL] High IV = Expensive Options",
+ "lowIv": "[PL] Low IV = Cheap Options",
+ "skew": "[PL] Skew = Put/Call IV Diff",
+ "termStructure": "[PL] Term Structure = Time Effect",
+ "pcaInterpretation": "[PL] PCA INTERPRETATION",
+ "pc1": "[PL] PC1 = Market Factor",
+ "pc2": "[PL] PC2 = Size/Value Factor",
+ "pc3": "[PL] PC3 = Sector Rotation",
+ "higherVar": "[PL] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[PL] STRIKE",
+ "dte": "[PL] DTE",
+ "iv": "[PL] IV",
+ "correlation": "[PL] CORRELATION",
+ "maturity": "[PL] MATURITY",
+ "yield": "[PL] YIELD",
+ "loading": "[PL] LOADING",
+ "strikePrice": "[PL] STRIKE PRICE",
+ "daysToExpiry": "[PL] DAYS TO EXPIRY",
+ "impliedVol": "[PL] IMPLIED VOL (%)",
+ "assetPairIndex": "[PL] ASSET PAIR INDEX",
+ "timeDays": "[PL] TIME (DAYS)",
+ "correlationCoeff": "[PL] CORRELATION COEFF",
+ "maturityMonths": "[PL] MATURITY (MONTHS)",
+ "historicalDays": "[PL] HISTORICAL DAYS",
+ "yieldPercent": "[PL] YIELD (%)",
+ "principalComponent": "[PL] PRINCIPAL COMPONENT",
+ "assetIndex": "[PL] ASSET INDEX",
+ "factorLoading": "[PL] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[PL] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[PL] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[PL] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[PL] DAY ROLLING",
+ "yieldCurve": "[PL] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[PL] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[PL] FAILED TO LOAD DATA",
+ "authFailed": "[PL] AUTHENTICATION FAILED",
+ "authFailedHelp": "[PL] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[PL] ACCESS DENIED",
+ "accessDeniedHelp": "[PL] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[PL] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[PL] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[PL] DATA TIMEFRAME",
+ "schema": "[PL] Schema",
+ "description": "[PL] Description",
+ "recordsPerDay": "[PL] Records/Day",
+ "highFrequencyWarning": "[PL] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[PL] Data Volume"
+ },
+ "settings": {
+ "title": "[PL] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[PL] DATABENTO API KEY",
+ "configured": "[PL] CONFIGURED",
+ "invalidFormat": "[PL] INVALID FORMAT",
+ "apiKeyConfigured": "[PL] API key is configured (db-*****)",
+ "remove": "[PL] REMOVE",
+ "enterApiKey": "[PL] Enter your Databento API key (db-*****)",
+ "save": "[PL] SAVE",
+ "saving": "[PL] SAVING...",
+ "getApiKeyFrom": "[PL] Get your API key from",
+ "dashboardApiKeys": "[PL] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[PL] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[PL] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[PL] CORRELATION ASSETS",
+ "addSymbol": "[PL] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[PL] Reset to defaults",
+ "historicalDateRange": "[PL] HISTORICAL DATE RANGE",
+ "start": "[PL] Start",
+ "end": "[PL] End",
+ "autoRefreshInterval": "[PL] AUTO REFRESH INTERVAL",
+ "manualOnly": "[PL] Manual Only",
+ "every1min": "[PL] Every 1 minute",
+ "every5min": "[PL] Every 5 minutes",
+ "every15min": "[PL] Every 15 minutes",
+ "every1hour": "[PL] Every 1 hour",
+ "browseDatasets": "[PL] BROWSE DATASETS",
+ "costEstimator": "[PL] COST ESTIMATOR",
+ "referenceData": "[PL] REFERENCE DATA",
+ "orderBook": "[PL] ORDER BOOK",
+ "liveStreaming": "[PL] LIVE STREAMING",
+ "active": "[PL] ACTIVE",
+ "futuresCme": "[PL] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[PL] BATCH DOWNLOADS",
+ "additionalSchemas": "[PL] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[PL] TRADES, IMBALANCE, STATUS",
+ "cancel": "[PL] CANCEL",
+ "saveChanges": "[PL] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[PL] BATCH DOWNLOADS",
+ "newBatchJob": "[PL] NEW BATCH JOB",
+ "dataset": "[PL] Dataset",
+ "schema": "[PL] Schema",
+ "symbolsCommaSeparated": "[PL] Symbols (comma-separated)",
+ "startDate": "[PL] Start Date",
+ "endDate": "[PL] End Date",
+ "encoding": "[PL] Encoding",
+ "compression": "[PL] Compression",
+ "submitJob": "[PL] SUBMIT JOB",
+ "noBatchJobs": "[PL] No batch jobs found. Click + to create one.",
+ "records": "[PL] records",
+ "download": "[PL] Download",
+ "files": "[PL] FILES",
+ "jobsExpireNotice": "[PL] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[PL] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[PL] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[PL] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[PL] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[PL] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[PL] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[PL] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[PL] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[PL] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[PL] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[PL] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[PL] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[PL] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[PL] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[PL] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[PL] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[PL] [EN] common.or",
+ "note": "[PL] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/pl/tabs.json b/fincept-terminal-desktop/public/locales/pl/tabs.json
index 8f24702b1..8a2878333 100644
--- a/fincept-terminal-desktop/public/locales/pl/tabs.json
+++ b/fincept-terminal-desktop/public/locales/pl/tabs.json
@@ -5,29 +5,7 @@
"news": "Wiadomości",
"portfolio": "Portfel",
"backtesting": "Backtesting",
- "watchlist": "Lista obserwowanych",
- "research": "Badania",
- "screener": "Skaner",
"chat": "AI Chat",
- "agents": "Agenci",
- "settings": "Ustawienia",
"profile": "Profil"
- },
- "functionKeys": {
- "f1": "PULT",
- "f2": "RNKI",
- "f3": "NEWS",
- "f4": "PORT",
- "f5": "BKTS",
- "f6": "OBSW",
- "f7": "BAD",
- "f8": "SKAN",
- "f9": "TRDG",
- "f10": "AI",
- "f11": "FULL",
- "f12": "PROF"
- },
- "labels": {
- "moreTabs": "Więcej kart w menu paska narzędzi"
}
}
diff --git a/fincept-terminal-desktop/public/locales/pl/watchlist.json b/fincept-terminal-desktop/public/locales/pl/watchlist.json
index fa7e5cdbd..80c86328f 100644
--- a/fincept-terminal-desktop/public/locales/pl/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/pl/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "LISTA OBSERWOWANYCH",
- "header": {
- "export": "EKSPORTUJ",
- "updating": "AKTUALIZACJA",
- "live": "NA ŻYWO"
- },
"sidebar": {
- "groups": "GRUPY LIST",
- "new": "NOWA",
"noWatchlists": "Brak list obserwowanych.",
"clickNew": "Kliknij NOWA aby utworzyć.",
- "stocks": "akcje",
- "marketMovers": "LIDERZY RYNKU",
- "gainer": "ZYSKUJĄ",
- "loser": "TRACĄ",
- "volumeLeaders": "LIDERZY WOLUMENU"
- },
- "emptyState": {
- "selectWatchlist": "Wybierz listę lub utwórz nową aby rozpocząć"
- },
- "list": {
- "symbols": "Symbole"
+ "stocks": "akcje"
}
}
diff --git a/fincept-terminal-desktop/public/locales/pt/codeEditor.json b/fincept-terminal-desktop/public/locales/pt/codeEditor.json
index e2efba140..d25199cb4 100644
--- a/fincept-terminal-desktop/public/locales/pt/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/pt/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "EDITOR DE CÓDIGO",
"header": {
- "packages": "PACOTES"
+ "finscriptIde": "[PT] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "NOVO ARQUIVO",
- "new": "NOVO",
- "open": "ABRIR",
- "save": "SALVAR",
"run": "EXECUTAR",
"running": "EXECUTANDO...",
- "runAll": "EXECUTAR TUDO",
- "history": "HISTÓRICO"
+ "toggleExplorer": "[PT] Toggle Explorer (Ctrl+B)",
+ "openFile": "[PT] Open File",
+ "saveShortcut": "[PT] Save (Ctrl+S)",
+ "findShortcut": "[PT] Find (Ctrl+F)",
+ "runShortcut": "[PT] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "EDITOR FINSCRIPT"
},
- "packages": {
- "clickToLoad": "Clique para carregar...",
- "load": "CARREGAR PACOTES"
+ "explorer": {
+ "title": "[PT] EXPLORER",
+ "openFiles": "[PT] OPEN FILES",
+ "examples": "[PT] EXAMPLES",
+ "runHistory": "[PT] RUN HISTORY",
+ "finscriptEngine": "[PT] FinScript Engine"
},
- "history": {
- "title": "HISTÓRICO DE NOTEBOOKS",
- "loading": "Carregando histórico...",
- "empty": "Sem histórico de notebooks"
+ "output": {
+ "title": "[PT] OUTPUT",
+ "success": "[PT] SUCCESS",
+ "error": "[PT] ERROR",
+ "executing": "[PT] EXECUTING FINSCRIPT...",
+ "noOutput": "[PT] No output yet",
+ "pressToRun": "[PT] Press Ctrl+Enter to run",
+ "completed": "[PT] COMPLETED",
+ "failed": "[PT] FAILED",
+ "signals": "[PT] signals",
+ "clear": "[PT] CLEAR",
+ "errors": "[PT] ERRORS",
+ "signalsSection": "[PT] SIGNALS",
+ "outputSection": "[PT] OUTPUT",
+ "charts": "[PT] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[PT] OHLC",
+ "histogram": "[PT] Histogram",
+ "line": "[PT] Line",
+ "points": "[PT] points"
+ },
+ "statusBar": {
+ "modified": "[PT] MODIFIED",
+ "showOutput": "[PT] SHOW OUTPUT",
+ "encoding": "[PT] UTF-8",
+ "spaces": "[PT] 4 Spaces",
+ "runShortcut": "[PT] Ctrl+Enter: Run",
+ "lines": "[PT] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[PT] Close file without saving?",
+ "unsavedChanges": "[PT] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/pt/common.json b/fincept-terminal-desktop/public/locales/pt/common.json
index 9f399b2af..7c6182d18 100644
--- a/fincept-terminal-desktop/public/locales/pt/common.json
+++ b/fincept-terminal-desktop/public/locales/pt/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Carregando...",
- "error": "Erro",
- "success": "Sucesso",
- "save": "Salvar",
- "cancel": "Cancelar",
- "delete": "Excluir",
- "edit": "Editar",
- "add": "Adicionar",
- "search": "Pesquisar",
- "filter": "Filtrar",
- "back": "Voltar",
- "next": "Próximo",
- "previous": "Anterior",
- "submit": "Enviar",
- "close": "Fechar",
- "open": "Abrir",
- "yes": "Sim",
- "no": "Não",
- "ok": "OK",
- "confirm": "Confirmar",
- "language": "Idioma",
- "selectLanguage": "Selecionar idioma"
-}
\ No newline at end of file
+ "settings": "[PT] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/pt/dashboard.json b/fincept-terminal-desktop/public/locales/pt/dashboard.json
index 6474af12e..a56edac40 100644
--- a/fincept-terminal-desktop/public/locales/pt/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/pt/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "PAINEL PERSONALIZÁVEL",
- "live": "AO VIVO",
- "widgets": "WIDGETS"
- },
- "buttons": {
- "addWidget": "ADICIONAR WIDGET",
- "saveLayout": "SALVAR LAYOUT",
- "reset": "REINICIAR",
- "help": "AJUDA"
- },
"widgets": {
"loading": "Carregando...",
- "error": "Erro",
"globalIndices": "Índices Globais - Top 12",
"forex": "Forex - Pares Principais",
"crypto": "CRIPTOMOEDAS",
@@ -20,8 +8,6 @@
"news": "NOTÍCIAS",
"forum": "FÓRUM",
"watchlist": "LISTA DE ASSISTIR",
- "maritimeIntelligence": "Inteligência Marítima",
- "unknown": "Tipo de widget desconhecido",
"index": "ÍNDICE",
"symbol": "SÍMBOLO",
"price": "PREÇO",
@@ -38,41 +24,22 @@
"pair": "PAR",
"rate": "AVALIAR",
"commodity": "MERCADORIA",
- "globe3D": "GLOBO 3D",
- "vessels": "NAVIOS",
- "routes": "ROTAS",
- "vol24h": "VOL 24H",
- "topTradeCorridors": "PRINCIPAIS CORREDORES COMERCIAIS",
- "ships": "navios",
- "marketNews": "Notícias do mercado",
- "secPressReleases": "Comunicados de imprensa da SEC",
- "cryptoNews": "Notícias criptográficas",
- "trendingForum": "Fórum de tendências",
- "techStocks": "Ações de tecnologia"
- },
- "tips": {
- "drag": "Arraste os widgets para reorganizar",
- "resize": "Redimensionar do canto inferior direito",
- "remove": "Remova widgets com o botão X",
- "responsive": "Layout responsivo – usa largura total"
- },
- "loading": {
- "title": "Inicializando o painel",
- "description": "Configurando o cache do banco de dados para carregamento mais rápido de dados...",
- "note": "Isso levará apenas um momento no primeiro lançamento"
- },
- "empty": {
- "noWidgets": "Nenhum widget no painel",
- "addFirst": "ADICIONE SEU PRIMEIRO WIDGET"
- },
- "status": {
- "version": "Painel personalizável Fincept v2.0.0 | Arrastar e soltar espaço de trabalho",
- "layout": "Disposição",
- "custom": "Personalizado",
- "empty": "Vazio",
- "active": "ATIVO",
- "cache": "Cache: ATIVADO",
- "label": "Status"
+ "noActiveMarkets": "[PT] No active markets found",
+ "indicator": "[PT] INDICATOR",
+ "value": "[PT] VALUE",
+ "chg": "[PT] CHG",
+ "overallRisk": "[PT] OVERALL RISK",
+ "openEconomicsTab": "[PT] Open Economics Tab",
+ "openGeopoliticsTab": "[PT] Open Geopolitics Tab",
+ "openPolymarketTab": "[PT] Open Polymarket Tab",
+ "noPortfolioFound": "[PT] No portfolio found",
+ "createPortfolioHint": "[PT] Create one in Portfolio tab",
+ "openPortfolioTab": "[PT] Open Portfolio Tab",
+ "action": "[PT] ACTION",
+ "markets": "[PT] MARKETS",
+ "performanceTracker": "[PT] PERFORMANCE TRACKER",
+ "totalPnL": "[PT] TOTAL P&L",
+ "viewDetailedAnalytics": "[PT] View Detailed Analytics"
},
"messages": {
"layoutSaved": "Layout do painel salvo!",
diff --git a/fincept-terminal-desktop/public/locales/pt/geopolitics.json b/fincept-terminal-desktop/public/locales/pt/geopolitics.json
index e60099060..ee1223f19 100644
--- a/fincept-terminal-desktop/public/locales/pt/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/pt/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "GEOPOLÍTICA",
"messages": {
- "loading": "Carregando dados..."
+ "retry": "[PT] RETRY"
+ },
+ "header": {
+ "prefix": "[PT] GEO>",
+ "title": "[PT] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[PT] EVENTS"
+ },
+ "status": {
+ "stale": "[PT] STALE",
+ "loading": "[PT] LOADING...",
+ "error": "[PT] ERROR:"
+ },
+ "filters": {
+ "country": "[PT] Country...",
+ "cities": "[PT] Cities...",
+ "category": "[PT] Category...",
+ "apply": "[PT] APPLY",
+ "clear": "[PT] CLEAR",
+ "clearAllCities": "[PT] Clear all cities",
+ "selectedLabel": "[PT] Selected:"
+ },
+ "panel": {
+ "title": "[PT] INFO PANEL",
+ "expand": "[PT] Expand panel",
+ "collapse": "[PT] Collapse panel",
+ "eventsLoaded": "[PT] EVENTS LOADED",
+ "onMapVisualization": "[PT] on map visualization",
+ "topCategories": "[PT] TOP CATEGORIES",
+ "topCountries": "[PT] TOP COUNTRIES",
+ "eventDetails": "[PT] EVENT DETAILS",
+ "close": "[PT] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[PT] Country:",
+ "city": "[PT] City:",
+ "keywords": "[PT] Keywords:",
+ "coords": "[PT] Coords:",
+ "date": "[PT] Date:",
+ "source": "[PT] Source:",
+ "viewArticle": "[PT] View Article"
+ },
+ "legend": {
+ "title": "[PT] EVENT CATEGORIES",
+ "armedConflict": "[PT] Armed Conflict",
+ "terrorism": "[PT] Terrorism",
+ "protests": "[PT] Protests",
+ "civilianViolence": "[PT] Civilian Violence",
+ "riots": "[PT] Riots",
+ "politicalViolence": "[PT] Political Violence",
+ "crisis": "[PT] Crisis",
+ "explosions": "[PT] Explosions",
+ "strategic": "[PT] Strategic",
+ "unclassified": "[PT] Unclassified"
+ },
+ "footer": {
+ "tabName": "[PT] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[PT] EVENTS",
+ "labelEngine": "[PT] ENGINE",
+ "engineValue": "[PT] DECK.GL v9.2",
+ "labelSource": "[PT] SOURCE",
+ "sourceValue": "[PT] NEWS-EVENTS API",
+ "labelSelected": "[PT] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/pt/markets.json b/fincept-terminal-desktop/public/locales/pt/markets.json
index 1f2cc86c7..7269a0ead 100644
--- a/fincept-terminal-desktop/public/locales/pt/markets.json
+++ b/fincept-terminal-desktop/public/locales/pt/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%VAR",
"high": "ALTA",
"low": "BAIXA",
- "loading": "Carregando...",
"noData": "Sem dados disponíveis",
"refresh": "ATUALIZAR",
"auto": "AUTO",
"on": "ON",
- "off": "OFF",
- "lastUpdate": "ÚLTIMA ATUALIZAÇÃO",
- "updating": "ATUALIZANDO",
- "live": "AO VIVO"
+ "off": "OFF"
}
diff --git a/fincept-terminal-desktop/public/locales/pt/news.json b/fincept-terminal-desktop/public/locales/pt/news.json
index 9d48fd4bd..a96c1cab4 100644
--- a/fincept-terminal-desktop/public/locales/pt/news.json
+++ b/fincept-terminal-desktop/public/locales/pt/news.json
@@ -1,32 +1,63 @@
{
"title": "NOTÍCIAS PROFISSIONAIS DO TERMINAL FINCEPT",
"header": {
- "liveFeed": "FEED AO VIVO",
- "live": "AO VIVO",
- "refresh": "ATUALIZAR",
- "updating": "ATUALIZANDO...",
- "alerts": "ALERTAS",
- "sources": "FONTES",
- "status": "STATUS",
- "demoMode": "MODO DEMO",
- "articles": "ARTIGOS",
- "activeSources": "FONTES ATIVAS"
- },
- "autoRefresh": {
- "title": "INTERVALO DE ATUALIZAÇÃO AUTOMÁTICA",
- "minute": "minuto",
- "minutes": "minutos"
+ "refresh": "ATUALIZAR"
},
"messages": {
- "loadingFeeds": "Carregando feeds...",
- "breaking": "URGENTE"
- },
- "feeds": {
- "primary": "[PT] PRIMARY NEWS FEED",
- "secondary": "[PT] SECONDARY NEWS FEED",
- "additional": "[PT] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[PT] Loading feeds...",
+ "failedToLoad": "[PT] Failed to load RSS feeds",
+ "noCustomFeeds": "[PT] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[PT] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[PT] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[PT] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[PT] RSS FEED SETTINGS",
+ "subtitle": "[PT] MANAGE YOUR NEWS SOURCES",
+ "close": "[PT] CLOSE",
+ "myFeeds": "[PT] MY FEEDS",
+ "defaultFeeds": "[PT] DEFAULT FEEDS",
+ "noFeedsAvailable": "[PT] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[PT] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[PT] ADD NEW FEED",
+ "addNewRssFeed": "[PT] ADD NEW RSS FEED",
+ "editRssFeed": "[PT] EDIT RSS FEED",
+ "restoreDefaults": "[PT] RESTORE DEFAULTS",
+ "restoreAll": "[PT] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[PT] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[PT] DISPLAY NAME",
+ "sourceName": "[PT] SOURCE NAME (SHORT)",
+ "feedUrl": "[PT] RSS FEED URL",
+ "category": "[PT] CATEGORY",
+ "region": "[PT] REGION",
+ "required": "[PT] *",
+ "testUrl": "[PT] TEST URL",
+ "testing": "[PT] TESTING...",
+ "valid": "[PT] VALID",
+ "cancel": "[PT] CANCEL",
+ "saving": "[PT] SAVING...",
+ "addFeed": "[PT] ADD FEED",
+ "updateFeed": "[PT] UPDATE FEED",
+ "on": "[PT] ON",
+ "off": "[PT] OFF",
+ "default": "[PT] DEFAULT",
+ "total": "[PT] TOTAL",
+ "active": "[PT] ACTIVE",
+ "custom": "[PT] CUSTOM",
+ "placeholders": {
+ "displayName": "[PT] e.g., Bloomberg Markets",
+ "sourceName": "[PT] e.g., BLOOMBERG",
+ "feedUrl": "[PT] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[PT] Name is required",
+ "sourceRequired": "[PT] Source name is required",
+ "invalidUrl": "[PT] Please enter a valid URL",
+ "invalidRss": "[PT] URL does not appear to be a valid RSS feed",
+ "testFailed": "[PT] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[PT] Delete this RSS feed?",
+ "message": "[PT] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/pt/portfolio.json b/fincept-terminal-desktop/public/locales/pt/portfolio.json
index 8d3dda5df..58531b681 100644
--- a/fincept-terminal-desktop/public/locales/pt/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/pt/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "GERENCIADOR DE CARTEIRA FINCEPT",
- "header": {
- "live": "AO VIVO",
- "updating": "ATUALIZANDO",
- "newPortfolio": "NOVA CARTEIRA",
- "refresh": "ATUALIZAR",
- "exportCsv": "EXPORTAR CSV"
- },
- "summary": {
- "totalValue": "VALOR TOTAL",
- "dayPnl": "L/P DIA",
- "totalPnl": "L/P TOTAL",
- "positions": "POSIÇÕES"
- },
- "views": {
- "positions": "POSIÇÕES",
- "addAsset": "ADICIONAR ATIVO",
- "sellAsset": "VENDER ATIVO",
- "analytics": "ANÁLISE",
- "history": "HISTÓRICO",
- "activeMgmt": "GESTÃO ATIVA",
- "performance": "DESEMPENHO",
- "rebalance": "REBALANCEAMENTO",
- "reports": "RELATÓRIOS",
- "alerts": "ALERTAS",
- "sectors": "SETORES",
- "help": "AJUDA"
- },
- "sidebar": {
- "portfolios": "CARTEIRAS",
- "loading": "Carregando carteiras...",
- "noPortfolios": "Nenhuma carteira ainda.",
- "clickCreate": "Clique em NOVA CARTEIRA para criar.",
- "owner": "Proprietário",
- "currency": "Moeda"
- },
- "content": {
- "selectOrCreate": "Selecione uma carteira ou crie uma nova para começar",
- "loadingData": "Carregando dados da carteira...",
- "comingSoon": "visualização em breve..."
- },
- "modals": {
- "createNew": "CRIAR NOVA CARTEIRA",
- "portfolioName": "NOME DA CARTEIRA",
- "owner": "PROPRIETÁRIO",
- "currency": "MOEDA",
- "cancel": "CANCELAR",
- "create": "CRIAR",
- "addAssetTitle": "ADICIONAR ATIVO À CARTEIRA",
- "sellAssetTitle": "VENDER ATIVO",
- "symbol": "SÍMBOLO",
- "quantity": "QUANTIDADE",
- "price": "PREÇO",
- "add": "ADICIONAR",
- "sell": "VENDER"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Rastreamento em tempo real com integração yfinance",
- "lastUpdated": "Última Atualização",
- "connected": "CONECTADO"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "CRIAR NOVA CARTEIRA",
+ "portfolioName": "NOME DA CARTEIRA",
+ "owner": "PROPRIETÁRIO",
+ "currency": "MOEDA",
+ "cancel": "CANCELAR",
+ "create": "CRIAR",
+ "addAssetTitle": "ADICIONAR ATIVO À CARTEIRA",
+ "sellAssetTitle": "VENDER ATIVO",
+ "symbol": "SÍMBOLO",
+ "quantity": "QUANTIDADE",
+ "price": "PREÇO",
+ "add": "ADICIONAR",
+ "sell": "VENDER"
+ },
+ "extracted": {
+ "areYouSureYou": "[PT] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/pt/reportBuilder.json b/fincept-terminal-desktop/public/locales/pt/reportBuilder.json
index 7608a8e93..03357c298 100644
--- a/fincept-terminal-desktop/public/locales/pt/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/pt/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[PT] Load",
"save": "[PT] Save",
- "saving": "[PT] Saving...",
- "exportPdf": "[PT] Export PDF",
- "generating": "[PT] Generating..."
+ "saving": "[PT] Saving..."
},
"components": {
"title": "[PT] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/pt/settings.json b/fincept-terminal-desktop/public/locales/pt/settings.json
index 6eb0973e1..1878cc1b3 100644
--- a/fincept-terminal-desktop/public/locales/pt/settings.json
+++ b/fincept-terminal-desktop/public/locales/pt/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Layout da guia",
"appearance": "Aparência",
"language": "Linguagem",
- "storage": "Armazenamento e Cache"
+ "storage": "Armazenamento e Cache",
+ "notifications": "[PT] Notifications"
},
"credentials": {
"title": "GERENCIAMENTO DE CREDENCIAIS API",
@@ -46,7 +47,31 @@
"saveConfig": "SALVAR CONFIGURAÇÃO",
"reset": "REINICIAR",
"saveSuccess": "Aparência do terminal e mapeamentos de teclas salvos com sucesso",
- "resetSuccess": "Redefinir para a aparência padrão e mapeamentos de teclas"
+ "resetSuccess": "Redefinir para a aparência padrão e mapeamentos de teclas",
+ "customColors": "[PT] Custom Colors",
+ "customColorsTitle": "[PT] CUSTOM COLORS",
+ "colorPrimary": "[PT] Primary",
+ "colorSecondary": "[PT] Secondary",
+ "colorSuccess": "[PT] Success",
+ "colorAlert": "[PT] Alert",
+ "colorWarning": "[PT] Warning",
+ "colorInfo": "[PT] Info",
+ "colorAccent": "[PT] Accent",
+ "colorPurple": "[PT] Purple",
+ "colorText": "[PT] Text",
+ "colorTextMuted": "[PT] Text Muted",
+ "colorBackground": "[PT] Background",
+ "colorPanel": "[PT] Panel",
+ "layoutSpacing": "[PT] LAYOUT & SPACING",
+ "contentDensity": "[PT] CONTENT DENSITY",
+ "borderRadius": "[PT] BORDER RADIUS",
+ "borderStyle": "[PT] BORDER STYLE",
+ "lineHeight": "[PT] LINE HEIGHT",
+ "letterSpacing": "[PT] LETTER SPACING",
+ "effects": "[PT] EFFECTS",
+ "widgetOpacity": "[PT] WIDGET OPACITY",
+ "enableGlow": "[PT] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[PT] GLOW INTENSITY"
},
"stockSymbols": {
"title": "Banco de dados de símbolos de ações",
@@ -65,17 +90,8 @@
"tip": "DICA: arraste as guias para reordená-las. Use os botões de seta para mover as guias entre as seções do cabeçalho e do menu. As alterações são salvas automaticamente."
},
"llm": {
- "title": "CONFIGURAÇÃO LLM",
- "description": "Configurar modelos e provedores de IA",
"connected": "CONECTADO",
- "disconnected": "DESCONECTADO",
- "provider": "FORNECEDOR DE IA",
- "globalSettings": "CONFIGURAÇÕES GLOBAIS DE IA",
- "temperature": "TEMPERATURA",
- "maxTokens": "MÁXIMO DE TOKENS",
- "systemPrompt": "AVISO DO SISTEMA",
- "modelLibrary": "BIBLIOTECA DE MODELOS",
- "multiModelConfigs": "Configurações de vários modelos"
+ "disconnected": "DESCONECTADO"
},
"buttons": {
"save": "SALVAR",
@@ -86,5 +102,18 @@
"database": "Banco de dados: SQLite",
"storage": "Armazenamento: baseado em arquivo",
"secureStorage": "Todos os dados armazenados com segurança em fincept_terminal.db"
+ },
+ "notifications": {
+ "title": "[PT] NOTIFICATION PROVIDERS",
+ "description": "[PT] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[PT] Event Filters",
+ "eventFilterDescription": "[PT] Choose which notification types to forward to external providers.",
+ "providers": "[PT] Providers",
+ "enabled": "[PT] Enabled",
+ "disabled": "[PT] Disabled",
+ "testButton": "[PT] TEST",
+ "testSuccess": "[PT] Test notification sent successfully!",
+ "testFailed": "[PT] Failed to send test notification. Check your configuration.",
+ "saved": "[PT] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/pt/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/pt/surfaceAnalytics.json
new file mode 100644
index 000000000..5b409a973
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/pt/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[PT] SURFACE ANALYTICS",
+ "initializing": "[PT] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[PT] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[PT] VOL SURFACE",
+ "correlation": "[PT] CORRELATION",
+ "yieldCurve": "[PT] YIELD CURVE",
+ "pca": "[PT] PCA FACTORS"
+ },
+ "demoData": "[PT] DEMO DATA",
+ "demoDataSynthetic": "[PT] DEMO DATA (synthetic)",
+ "synthetic": "[PT] SYNTHETIC",
+ "manual": "[PT] MANUAL",
+ "error": "[PT] ERROR",
+ "ready": "[PT] READY",
+ "metrics": "[PT] Metrics",
+ "updated": "[PT] Updated",
+ "clickRefresh": "[PT] Click REFRESH to load data",
+ "refresh": "[PT] REFRESH",
+ "noApiKey": "[PT] NO API KEY",
+ "lastUpdate": "[PT] LAST UPDATE",
+ "loadingData": "[PT] LOADING DATA...",
+ "noDataLoaded": "[PT] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[PT] IV SURFACE METRICS",
+ "correlationMetrics": "[PT] CORRELATION METRICS",
+ "yieldCurveMetrics": "[PT] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[PT] PCA FACTOR METRICS",
+ "dataInfo": "[PT] DATA INFO",
+ "source": "[PT] SOURCE",
+ "frequency": "[PT] FREQUENCY",
+ "quality": "[PT] QUALITY",
+ "correlationScale": "[PT] CORRELATION SCALE",
+ "strongPositive": "[PT] Strong Positive (0.7-1.0)",
+ "neutral": "[PT] Neutral (0.3-0.7)",
+ "strongNegative": "[PT] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[PT] IV INTERPRETATION",
+ "highIv": "[PT] High IV = Expensive Options",
+ "lowIv": "[PT] Low IV = Cheap Options",
+ "skew": "[PT] Skew = Put/Call IV Diff",
+ "termStructure": "[PT] Term Structure = Time Effect",
+ "pcaInterpretation": "[PT] PCA INTERPRETATION",
+ "pc1": "[PT] PC1 = Market Factor",
+ "pc2": "[PT] PC2 = Size/Value Factor",
+ "pc3": "[PT] PC3 = Sector Rotation",
+ "higherVar": "[PT] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[PT] STRIKE",
+ "dte": "[PT] DTE",
+ "iv": "[PT] IV",
+ "correlation": "[PT] CORRELATION",
+ "maturity": "[PT] MATURITY",
+ "yield": "[PT] YIELD",
+ "loading": "[PT] LOADING",
+ "strikePrice": "[PT] STRIKE PRICE",
+ "daysToExpiry": "[PT] DAYS TO EXPIRY",
+ "impliedVol": "[PT] IMPLIED VOL (%)",
+ "assetPairIndex": "[PT] ASSET PAIR INDEX",
+ "timeDays": "[PT] TIME (DAYS)",
+ "correlationCoeff": "[PT] CORRELATION COEFF",
+ "maturityMonths": "[PT] MATURITY (MONTHS)",
+ "historicalDays": "[PT] HISTORICAL DAYS",
+ "yieldPercent": "[PT] YIELD (%)",
+ "principalComponent": "[PT] PRINCIPAL COMPONENT",
+ "assetIndex": "[PT] ASSET INDEX",
+ "factorLoading": "[PT] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[PT] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[PT] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[PT] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[PT] DAY ROLLING",
+ "yieldCurve": "[PT] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[PT] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[PT] FAILED TO LOAD DATA",
+ "authFailed": "[PT] AUTHENTICATION FAILED",
+ "authFailedHelp": "[PT] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[PT] ACCESS DENIED",
+ "accessDeniedHelp": "[PT] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[PT] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[PT] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[PT] DATA TIMEFRAME",
+ "schema": "[PT] Schema",
+ "description": "[PT] Description",
+ "recordsPerDay": "[PT] Records/Day",
+ "highFrequencyWarning": "[PT] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[PT] Data Volume"
+ },
+ "settings": {
+ "title": "[PT] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[PT] DATABENTO API KEY",
+ "configured": "[PT] CONFIGURED",
+ "invalidFormat": "[PT] INVALID FORMAT",
+ "apiKeyConfigured": "[PT] API key is configured (db-*****)",
+ "remove": "[PT] REMOVE",
+ "enterApiKey": "[PT] Enter your Databento API key (db-*****)",
+ "save": "[PT] SAVE",
+ "saving": "[PT] SAVING...",
+ "getApiKeyFrom": "[PT] Get your API key from",
+ "dashboardApiKeys": "[PT] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[PT] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[PT] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[PT] CORRELATION ASSETS",
+ "addSymbol": "[PT] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[PT] Reset to defaults",
+ "historicalDateRange": "[PT] HISTORICAL DATE RANGE",
+ "start": "[PT] Start",
+ "end": "[PT] End",
+ "autoRefreshInterval": "[PT] AUTO REFRESH INTERVAL",
+ "manualOnly": "[PT] Manual Only",
+ "every1min": "[PT] Every 1 minute",
+ "every5min": "[PT] Every 5 minutes",
+ "every15min": "[PT] Every 15 minutes",
+ "every1hour": "[PT] Every 1 hour",
+ "browseDatasets": "[PT] BROWSE DATASETS",
+ "costEstimator": "[PT] COST ESTIMATOR",
+ "referenceData": "[PT] REFERENCE DATA",
+ "orderBook": "[PT] ORDER BOOK",
+ "liveStreaming": "[PT] LIVE STREAMING",
+ "active": "[PT] ACTIVE",
+ "futuresCme": "[PT] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[PT] BATCH DOWNLOADS",
+ "additionalSchemas": "[PT] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[PT] TRADES, IMBALANCE, STATUS",
+ "cancel": "[PT] CANCEL",
+ "saveChanges": "[PT] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[PT] BATCH DOWNLOADS",
+ "newBatchJob": "[PT] NEW BATCH JOB",
+ "dataset": "[PT] Dataset",
+ "schema": "[PT] Schema",
+ "symbolsCommaSeparated": "[PT] Symbols (comma-separated)",
+ "startDate": "[PT] Start Date",
+ "endDate": "[PT] End Date",
+ "encoding": "[PT] Encoding",
+ "compression": "[PT] Compression",
+ "submitJob": "[PT] SUBMIT JOB",
+ "noBatchJobs": "[PT] No batch jobs found. Click + to create one.",
+ "records": "[PT] records",
+ "download": "[PT] Download",
+ "files": "[PT] FILES",
+ "jobsExpireNotice": "[PT] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[PT] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[PT] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[PT] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[PT] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[PT] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[PT] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[PT] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[PT] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[PT] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[PT] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[PT] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[PT] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[PT] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[PT] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[PT] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[PT] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[PT] [EN] common.or",
+ "note": "[PT] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/pt/tabs.json b/fincept-terminal-desktop/public/locales/pt/tabs.json
index dd3def32a..9242f5b0f 100644
--- a/fincept-terminal-desktop/public/locales/pt/tabs.json
+++ b/fincept-terminal-desktop/public/locales/pt/tabs.json
@@ -5,29 +5,7 @@
"news": "Notícias",
"portfolio": "Portfólio",
"backtesting": "Backtesting",
- "watchlist": "Lista de Acompanhamento",
- "research": "Pesquisa",
- "screener": "Screener",
"chat": "AI Chat",
- "agents": "Agentes",
- "settings": "Configurações",
"profile": "Perfil"
- },
- "functionKeys": {
- "f1": "PANL",
- "f2": "MERC",
- "f3": "NOTI",
- "f4": "PORT",
- "f5": "BKTS",
- "f6": "ACOM",
- "f7": "PESQ",
- "f8": "SCRN",
- "f9": "TRDG",
- "f10": "AI",
- "f11": "FULL",
- "f12": "PERF"
- },
- "labels": {
- "moreTabs": "Mais abas nos menus da barra de ferramentas"
}
}
diff --git a/fincept-terminal-desktop/public/locales/pt/watchlist.json b/fincept-terminal-desktop/public/locales/pt/watchlist.json
index a553398a6..ca2f7037c 100644
--- a/fincept-terminal-desktop/public/locales/pt/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/pt/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "LISTA DE INTERESSE",
- "header": {
- "export": "EXPORTAR",
- "updating": "ATUALIZANDO",
- "live": "AO VIVO"
- },
"sidebar": {
- "groups": "GRUPOS DE LISTAS",
- "new": "NOVA",
"noWatchlists": "Ainda não há listas.",
"clickNew": "Clique NOVA para criar.",
- "stocks": "ações",
- "marketMovers": "LÍDERES DO MERCADO",
- "gainer": "EM ALTA",
- "loser": "EM BAIXA",
- "volumeLeaders": "LÍDERES DE VOLUME"
- },
- "emptyState": {
- "selectWatchlist": "Selecione uma lista ou crie uma nova para começar"
- },
- "list": {
- "symbols": "Símbolos"
+ "stocks": "ações"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ro/codeEditor.json b/fincept-terminal-desktop/public/locales/ro/codeEditor.json
index 60823e7b8..7bf94862d 100644
--- a/fincept-terminal-desktop/public/locales/ro/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/ro/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "EDITOR COD",
"header": {
- "packages": "PACHETE"
+ "finscriptIde": "[RO] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "FIȘIER NOU",
- "new": "NOU",
- "open": "DESCHIDE",
- "save": "SALVEAZĂ",
"run": "RULEAZĂ",
"running": "RULEAZĂ...",
- "runAll": "RULEAZĂ TOT",
- "history": "ISTORIC"
+ "toggleExplorer": "[RO] Toggle Explorer (Ctrl+B)",
+ "openFile": "[RO] Open File",
+ "saveShortcut": "[RO] Save (Ctrl+S)",
+ "findShortcut": "[RO] Find (Ctrl+F)",
+ "runShortcut": "[RO] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "EDITOR FINSCRIPT"
},
- "packages": {
- "clickToLoad": "Click pentru a încărca...",
- "load": "ÎNCARCĂ PACHETE"
+ "explorer": {
+ "title": "[RO] EXPLORER",
+ "openFiles": "[RO] OPEN FILES",
+ "examples": "[RO] EXAMPLES",
+ "runHistory": "[RO] RUN HISTORY",
+ "finscriptEngine": "[RO] FinScript Engine"
},
- "history": {
- "title": "ISTORIC NOTEBOOK",
- "loading": "Încarcă istoric...",
- "empty": "Niciun istoric notebook"
+ "output": {
+ "title": "[RO] OUTPUT",
+ "success": "[RO] SUCCESS",
+ "error": "[RO] ERROR",
+ "executing": "[RO] EXECUTING FINSCRIPT...",
+ "noOutput": "[RO] No output yet",
+ "pressToRun": "[RO] Press Ctrl+Enter to run",
+ "completed": "[RO] COMPLETED",
+ "failed": "[RO] FAILED",
+ "signals": "[RO] signals",
+ "clear": "[RO] CLEAR",
+ "errors": "[RO] ERRORS",
+ "signalsSection": "[RO] SIGNALS",
+ "outputSection": "[RO] OUTPUT",
+ "charts": "[RO] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[RO] OHLC",
+ "histogram": "[RO] Histogram",
+ "line": "[RO] Line",
+ "points": "[RO] points"
+ },
+ "statusBar": {
+ "modified": "[RO] MODIFIED",
+ "showOutput": "[RO] SHOW OUTPUT",
+ "encoding": "[RO] UTF-8",
+ "spaces": "[RO] 4 Spaces",
+ "runShortcut": "[RO] Ctrl+Enter: Run",
+ "lines": "[RO] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[RO] Close file without saving?",
+ "unsavedChanges": "[RO] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/ro/common.json b/fincept-terminal-desktop/public/locales/ro/common.json
index ace2dc548..91b39f4be 100644
--- a/fincept-terminal-desktop/public/locales/ro/common.json
+++ b/fincept-terminal-desktop/public/locales/ro/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Se încarcă...",
- "error": "Eroare",
- "success": "Succes",
- "save": "Salvează",
- "cancel": "Anulează",
- "delete": "Șterge",
- "edit": "Editează",
- "add": "Adaugă",
- "search": "Caută",
- "filter": "Filtrează",
- "back": "Înapoi",
- "next": "Următorul",
- "previous": "Anterior",
- "submit": "Trimite",
- "close": "Închide",
- "open": "Deschide",
- "yes": "Da",
- "no": "Nu",
- "ok": "OK",
- "confirm": "Confirmă",
- "language": "Limbă",
- "selectLanguage": "Selectați limba"
-}
\ No newline at end of file
+ "settings": "[RO] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/ro/dashboard.json b/fincept-terminal-desktop/public/locales/ro/dashboard.json
index 49f6693c3..c7fc1e84c 100644
--- a/fincept-terminal-desktop/public/locales/ro/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/ro/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "TABLA DE BORD PERSONIZABILĂ",
- "live": "TRĂI",
- "widgets": "WIDGET-uri"
- },
- "buttons": {
- "addWidget": "ADAUGĂ WIDGET",
- "saveLayout": "SALVAȚI ASPECTUL",
- "reset": "RESET",
- "help": "AJUTOR"
- },
"widgets": {
"loading": "Încărcare...",
- "error": "Eroare",
"globalIndices": "Indici globali - Top 12",
"forex": "Forex - Perechi majore",
"crypto": "CRIPTOMONEDE",
@@ -20,8 +8,6 @@
"news": "ŞTIRI",
"forum": "FORUM",
"watchlist": "LISTĂ DE CERINȚARE",
- "maritimeIntelligence": "Informații maritime",
- "unknown": "Tip necunoscut de widget",
"index": "INDEX",
"symbol": "SIMBOL",
"price": "PREŢ",
@@ -38,41 +24,22 @@
"pair": "PERECHE",
"rate": "RATA",
"commodity": "MARFĂ",
- "globe3D": "GLOBUL 3D",
- "vessels": "NAVE",
- "routes": "RUTE",
- "vol24h": "VOL 24H",
- "topTradeCorridors": "CORidoarele comerciale de top",
- "ships": "navelor",
- "marketNews": "Știri de piață",
- "secPressReleases": "Comunicate de presă SEC",
- "cryptoNews": "Știri Crypto",
- "trendingForum": "Forum de tendințe",
- "techStocks": "Stocuri de tehnologie"
- },
- "tips": {
- "drag": "Trageți widget-uri pentru a rearanja",
- "resize": "Redimensionați din colțul din dreapta jos",
- "remove": "Eliminați widget-urile cu butonul X",
- "responsive": "Aspect receptiv - folosește lățimea completă"
- },
- "loading": {
- "title": "Inițializarea tabloului de bord",
- "description": "Se configurează memoria cache a bazei de date pentru o încărcare mai rapidă a datelor...",
- "note": "Acest lucru va dura doar un moment la prima lansare"
- },
- "empty": {
- "noWidgets": "Fără widget-uri pe tabloul de bord",
- "addFirst": "ADAUGĂ PRIMUL TĂU WIDGET"
- },
- "status": {
- "version": "Tabloul de bord personalizabil Fincept v2.0.0 | Trageți și plasați spațiul de lucru",
- "layout": "Aspect",
- "custom": "Personalizat",
- "empty": "Gol",
- "active": "ACTIV",
- "cache": "Cache: ACTIVAT",
- "label": "Stare"
+ "noActiveMarkets": "[RO] No active markets found",
+ "indicator": "[RO] INDICATOR",
+ "value": "[RO] VALUE",
+ "chg": "[RO] CHG",
+ "overallRisk": "[RO] OVERALL RISK",
+ "openEconomicsTab": "[RO] Open Economics Tab",
+ "openGeopoliticsTab": "[RO] Open Geopolitics Tab",
+ "openPolymarketTab": "[RO] Open Polymarket Tab",
+ "noPortfolioFound": "[RO] No portfolio found",
+ "createPortfolioHint": "[RO] Create one in Portfolio tab",
+ "openPortfolioTab": "[RO] Open Portfolio Tab",
+ "action": "[RO] ACTION",
+ "markets": "[RO] MARKETS",
+ "performanceTracker": "[RO] PERFORMANCE TRACKER",
+ "totalPnL": "[RO] TOTAL P&L",
+ "viewDetailedAnalytics": "[RO] View Detailed Analytics"
},
"messages": {
"layoutSaved": "Aspectul tabloului de bord a fost salvat!",
diff --git a/fincept-terminal-desktop/public/locales/ro/geopolitics.json b/fincept-terminal-desktop/public/locales/ro/geopolitics.json
index 866025b87..ad1a01174 100644
--- a/fincept-terminal-desktop/public/locales/ro/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/ro/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "GEOPOLITICĂ",
"messages": {
- "loading": "Se încarcă datele..."
+ "retry": "[RO] RETRY"
+ },
+ "header": {
+ "prefix": "[RO] GEO>",
+ "title": "[RO] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[RO] EVENTS"
+ },
+ "status": {
+ "stale": "[RO] STALE",
+ "loading": "[RO] LOADING...",
+ "error": "[RO] ERROR:"
+ },
+ "filters": {
+ "country": "[RO] Country...",
+ "cities": "[RO] Cities...",
+ "category": "[RO] Category...",
+ "apply": "[RO] APPLY",
+ "clear": "[RO] CLEAR",
+ "clearAllCities": "[RO] Clear all cities",
+ "selectedLabel": "[RO] Selected:"
+ },
+ "panel": {
+ "title": "[RO] INFO PANEL",
+ "expand": "[RO] Expand panel",
+ "collapse": "[RO] Collapse panel",
+ "eventsLoaded": "[RO] EVENTS LOADED",
+ "onMapVisualization": "[RO] on map visualization",
+ "topCategories": "[RO] TOP CATEGORIES",
+ "topCountries": "[RO] TOP COUNTRIES",
+ "eventDetails": "[RO] EVENT DETAILS",
+ "close": "[RO] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[RO] Country:",
+ "city": "[RO] City:",
+ "keywords": "[RO] Keywords:",
+ "coords": "[RO] Coords:",
+ "date": "[RO] Date:",
+ "source": "[RO] Source:",
+ "viewArticle": "[RO] View Article"
+ },
+ "legend": {
+ "title": "[RO] EVENT CATEGORIES",
+ "armedConflict": "[RO] Armed Conflict",
+ "terrorism": "[RO] Terrorism",
+ "protests": "[RO] Protests",
+ "civilianViolence": "[RO] Civilian Violence",
+ "riots": "[RO] Riots",
+ "politicalViolence": "[RO] Political Violence",
+ "crisis": "[RO] Crisis",
+ "explosions": "[RO] Explosions",
+ "strategic": "[RO] Strategic",
+ "unclassified": "[RO] Unclassified"
+ },
+ "footer": {
+ "tabName": "[RO] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[RO] EVENTS",
+ "labelEngine": "[RO] ENGINE",
+ "engineValue": "[RO] DECK.GL v9.2",
+ "labelSource": "[RO] SOURCE",
+ "sourceValue": "[RO] NEWS-EVENTS API",
+ "labelSelected": "[RO] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ro/markets.json b/fincept-terminal-desktop/public/locales/ro/markets.json
index 1919a2402..92e4eaa65 100644
--- a/fincept-terminal-desktop/public/locales/ro/markets.json
+++ b/fincept-terminal-desktop/public/locales/ro/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%SCH",
"high": "MAX",
"low": "MIN",
- "loading": "Se încarcă...",
"noData": "Nu există date",
"refresh": "REÎMPROSPĂTEAZĂ",
"auto": "AUTO",
"on": "PORNIT",
- "off": "OPRIT",
- "lastUpdate": "ULTIMA ACTUALIZARE",
- "updating": "SE ACTUALIZEAZĂ",
- "live": "LIVE"
+ "off": "OPRIT"
}
diff --git a/fincept-terminal-desktop/public/locales/ro/news.json b/fincept-terminal-desktop/public/locales/ro/news.json
index 43332ada7..cd13d7675 100644
--- a/fincept-terminal-desktop/public/locales/ro/news.json
+++ b/fincept-terminal-desktop/public/locales/ro/news.json
@@ -1,32 +1,63 @@
{
"title": "ȘTIRI PROFESIONALE TERMINAL FINCEPT",
"header": {
- "liveFeed": "FEED LIVE",
- "live": "LIVE",
- "refresh": "REÎMPROSPĂTEAZĂ",
- "updating": "SE ACTUALIZEAZĂ...",
- "alerts": "ALERTE",
- "sources": "SURSE",
- "status": "STATUS",
- "demoMode": "MOD DEMO",
- "articles": "ARTICOLE",
- "activeSources": "SURSE ACTIVE"
- },
- "autoRefresh": {
- "title": "INTERVAL DE REÎMPROSPĂTARE AUTOMATĂ",
- "minute": "minut",
- "minutes": "minute"
+ "refresh": "REÎMPROSPĂTEAZĂ"
},
"messages": {
- "loadingFeeds": "Se încarcă fluxurile...",
- "breaking": "BREAKING"
- },
- "feeds": {
- "primary": "[RO] PRIMARY NEWS FEED",
- "secondary": "[RO] SECONDARY NEWS FEED",
- "additional": "[RO] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[RO] Loading feeds...",
+ "failedToLoad": "[RO] Failed to load RSS feeds",
+ "noCustomFeeds": "[RO] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[RO] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[RO] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[RO] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[RO] RSS FEED SETTINGS",
+ "subtitle": "[RO] MANAGE YOUR NEWS SOURCES",
+ "close": "[RO] CLOSE",
+ "myFeeds": "[RO] MY FEEDS",
+ "defaultFeeds": "[RO] DEFAULT FEEDS",
+ "noFeedsAvailable": "[RO] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[RO] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[RO] ADD NEW FEED",
+ "addNewRssFeed": "[RO] ADD NEW RSS FEED",
+ "editRssFeed": "[RO] EDIT RSS FEED",
+ "restoreDefaults": "[RO] RESTORE DEFAULTS",
+ "restoreAll": "[RO] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[RO] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[RO] DISPLAY NAME",
+ "sourceName": "[RO] SOURCE NAME (SHORT)",
+ "feedUrl": "[RO] RSS FEED URL",
+ "category": "[RO] CATEGORY",
+ "region": "[RO] REGION",
+ "required": "[RO] *",
+ "testUrl": "[RO] TEST URL",
+ "testing": "[RO] TESTING...",
+ "valid": "[RO] VALID",
+ "cancel": "[RO] CANCEL",
+ "saving": "[RO] SAVING...",
+ "addFeed": "[RO] ADD FEED",
+ "updateFeed": "[RO] UPDATE FEED",
+ "on": "[RO] ON",
+ "off": "[RO] OFF",
+ "default": "[RO] DEFAULT",
+ "total": "[RO] TOTAL",
+ "active": "[RO] ACTIVE",
+ "custom": "[RO] CUSTOM",
+ "placeholders": {
+ "displayName": "[RO] e.g., Bloomberg Markets",
+ "sourceName": "[RO] e.g., BLOOMBERG",
+ "feedUrl": "[RO] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[RO] Name is required",
+ "sourceRequired": "[RO] Source name is required",
+ "invalidUrl": "[RO] Please enter a valid URL",
+ "invalidRss": "[RO] URL does not appear to be a valid RSS feed",
+ "testFailed": "[RO] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[RO] Delete this RSS feed?",
+ "message": "[RO] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/ro/portfolio.json b/fincept-terminal-desktop/public/locales/ro/portfolio.json
index 02c117142..8f49223d8 100644
--- a/fincept-terminal-desktop/public/locales/ro/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/ro/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "MANAGER PORTOFOLIU FINCEPT",
- "header": {
- "live": "LIVE",
- "updating": "SE ACTUALIZEAZĂ",
- "newPortfolio": "PORTOFOLIU NOU",
- "refresh": "REÎMPROSPĂTEAZĂ",
- "exportCsv": "EXPORTĂ CSV"
- },
- "summary": {
- "totalValue": "VALOARE TOTALĂ",
- "dayPnl": "P&L ZI",
- "totalPnl": "P&L TOTAL",
- "positions": "POZIȚII"
- },
- "views": {
- "positions": "POZIȚII",
- "addAsset": "ADAUGĂ ACTIV",
- "sellAsset": "VINDE ACTIV",
- "analytics": "ANALIZĂ",
- "history": "ISTORIC",
- "activeMgmt": "MANAGEMENT ACTIV",
- "performance": "PERFORMANȚĂ",
- "rebalance": "REBALANSARE",
- "reports": "RAPOARTE",
- "alerts": "ALERTE",
- "sectors": "SECTOARE",
- "help": "AJUTOR"
- },
- "sidebar": {
- "portfolios": "PORTOFOLII",
- "loading": "Se încarcă portofoliile...",
- "noPortfolios": "Niciun portofoliu încă.",
- "clickCreate": "Click PORTOFOLIU NOU pentru a crea.",
- "owner": "Proprietar",
- "currency": "Monedă"
- },
- "content": {
- "selectOrCreate": "Selectați un portofoliu sau creați unul nou pentru a începe",
- "loadingData": "Se încarcă datele portofoliului...",
- "comingSoon": "vizualizare în curând..."
- },
- "modals": {
- "createNew": "CREEAZĂ PORTOFOLIU NOU",
- "portfolioName": "NUME PORTOFOLIU",
- "owner": "PROPRIETAR",
- "currency": "MONEDĂ",
- "cancel": "ANULEAZĂ",
- "create": "CREEAZĂ",
- "addAssetTitle": "ADAUGĂ ACTIV LA PORTOFOLIU",
- "sellAssetTitle": "VINDE ACTIV",
- "symbol": "SIMBOL",
- "quantity": "CANTITATE",
- "price": "PREȚ",
- "add": "ADAUGĂ",
- "sell": "VINDE"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Urmărire în timp real cu integrare yfinance",
- "lastUpdated": "Ultima Actualizare",
- "connected": "CONECTAT"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "CREEAZĂ PORTOFOLIU NOU",
+ "portfolioName": "NUME PORTOFOLIU",
+ "owner": "PROPRIETAR",
+ "currency": "MONEDĂ",
+ "cancel": "ANULEAZĂ",
+ "create": "CREEAZĂ",
+ "addAssetTitle": "ADAUGĂ ACTIV LA PORTOFOLIU",
+ "sellAssetTitle": "VINDE ACTIV",
+ "symbol": "SIMBOL",
+ "quantity": "CANTITATE",
+ "price": "PREȚ",
+ "add": "ADAUGĂ",
+ "sell": "VINDE"
+ },
+ "extracted": {
+ "areYouSureYou": "[RO] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/ro/reportBuilder.json b/fincept-terminal-desktop/public/locales/ro/reportBuilder.json
index f348ac69c..bb80b95ee 100644
--- a/fincept-terminal-desktop/public/locales/ro/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/ro/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[RO] Load",
"save": "[RO] Save",
- "saving": "[RO] Saving...",
- "exportPdf": "[RO] Export PDF",
- "generating": "[RO] Generating..."
+ "saving": "[RO] Saving..."
},
"components": {
"title": "[RO] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/ro/settings.json b/fincept-terminal-desktop/public/locales/ro/settings.json
index e2dc0b17a..fdb2baef2 100644
--- a/fincept-terminal-desktop/public/locales/ro/settings.json
+++ b/fincept-terminal-desktop/public/locales/ro/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Aspect fila",
"appearance": "Aspect",
"language": "Limbă",
- "storage": "Stocare și cache"
+ "storage": "Stocare și cache",
+ "notifications": "[RO] Notifications"
},
"credentials": {
"title": "GESTIUNEA CREDENTIALS API",
@@ -46,7 +47,31 @@
"saveConfig": "SALVAȚI CONFIGURAȚIA",
"reset": "RESET",
"saveSuccess": "Aspectul terminalului și mapările cheilor au fost salvate cu succes",
- "resetSuccess": "Resetați la aspectul implicit și mapările tastelor"
+ "resetSuccess": "Resetați la aspectul implicit și mapările tastelor",
+ "customColors": "[RO] Custom Colors",
+ "customColorsTitle": "[RO] CUSTOM COLORS",
+ "colorPrimary": "[RO] Primary",
+ "colorSecondary": "[RO] Secondary",
+ "colorSuccess": "[RO] Success",
+ "colorAlert": "[RO] Alert",
+ "colorWarning": "[RO] Warning",
+ "colorInfo": "[RO] Info",
+ "colorAccent": "[RO] Accent",
+ "colorPurple": "[RO] Purple",
+ "colorText": "[RO] Text",
+ "colorTextMuted": "[RO] Text Muted",
+ "colorBackground": "[RO] Background",
+ "colorPanel": "[RO] Panel",
+ "layoutSpacing": "[RO] LAYOUT & SPACING",
+ "contentDensity": "[RO] CONTENT DENSITY",
+ "borderRadius": "[RO] BORDER RADIUS",
+ "borderStyle": "[RO] BORDER STYLE",
+ "lineHeight": "[RO] LINE HEIGHT",
+ "letterSpacing": "[RO] LETTER SPACING",
+ "effects": "[RO] EFFECTS",
+ "widgetOpacity": "[RO] WIDGET OPACITY",
+ "enableGlow": "[RO] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[RO] GLOW INTENSITY"
},
"stockSymbols": {
"title": "Baza de date cu simboluri bursiere",
@@ -65,17 +90,8 @@
"tip": "SFAT: Trageți filele pentru a le reordona. Folosiți butoanele săgeată pentru a muta filele între antet și secțiunile de meniu. Modificările sunt salvate automat."
},
"llm": {
- "title": "CONFIGURARE LLM",
- "description": "Configurați modelele și furnizorii AI",
"connected": "CONECTAT",
- "disconnected": "DECONECTAT",
- "provider": "FURNIZOR AI",
- "globalSettings": "SETĂRI GLOBALE AI",
- "temperature": "TEMPERATURĂ",
- "maxTokens": "MAX JETONE",
- "systemPrompt": "PROMPT DE SISTEM",
- "modelLibrary": "BIBLIOTECA DE MODELE",
- "multiModelConfigs": "Configurații cu mai multe modele"
+ "disconnected": "DECONECTAT"
},
"buttons": {
"save": "SALVA",
@@ -86,5 +102,18 @@
"database": "Baza de date: SQLite",
"storage": "Stocare: pe bază de fișiere",
"secureStorage": "Toate datele stocate în siguranță în fincept_terminal.db"
+ },
+ "notifications": {
+ "title": "[RO] NOTIFICATION PROVIDERS",
+ "description": "[RO] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[RO] Event Filters",
+ "eventFilterDescription": "[RO] Choose which notification types to forward to external providers.",
+ "providers": "[RO] Providers",
+ "enabled": "[RO] Enabled",
+ "disabled": "[RO] Disabled",
+ "testButton": "[RO] TEST",
+ "testSuccess": "[RO] Test notification sent successfully!",
+ "testFailed": "[RO] Failed to send test notification. Check your configuration.",
+ "saved": "[RO] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ro/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/ro/surfaceAnalytics.json
new file mode 100644
index 000000000..73da06f07
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/ro/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[RO] SURFACE ANALYTICS",
+ "initializing": "[RO] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[RO] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[RO] VOL SURFACE",
+ "correlation": "[RO] CORRELATION",
+ "yieldCurve": "[RO] YIELD CURVE",
+ "pca": "[RO] PCA FACTORS"
+ },
+ "demoData": "[RO] DEMO DATA",
+ "demoDataSynthetic": "[RO] DEMO DATA (synthetic)",
+ "synthetic": "[RO] SYNTHETIC",
+ "manual": "[RO] MANUAL",
+ "error": "[RO] ERROR",
+ "ready": "[RO] READY",
+ "metrics": "[RO] Metrics",
+ "updated": "[RO] Updated",
+ "clickRefresh": "[RO] Click REFRESH to load data",
+ "refresh": "[RO] REFRESH",
+ "noApiKey": "[RO] NO API KEY",
+ "lastUpdate": "[RO] LAST UPDATE",
+ "loadingData": "[RO] LOADING DATA...",
+ "noDataLoaded": "[RO] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[RO] IV SURFACE METRICS",
+ "correlationMetrics": "[RO] CORRELATION METRICS",
+ "yieldCurveMetrics": "[RO] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[RO] PCA FACTOR METRICS",
+ "dataInfo": "[RO] DATA INFO",
+ "source": "[RO] SOURCE",
+ "frequency": "[RO] FREQUENCY",
+ "quality": "[RO] QUALITY",
+ "correlationScale": "[RO] CORRELATION SCALE",
+ "strongPositive": "[RO] Strong Positive (0.7-1.0)",
+ "neutral": "[RO] Neutral (0.3-0.7)",
+ "strongNegative": "[RO] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[RO] IV INTERPRETATION",
+ "highIv": "[RO] High IV = Expensive Options",
+ "lowIv": "[RO] Low IV = Cheap Options",
+ "skew": "[RO] Skew = Put/Call IV Diff",
+ "termStructure": "[RO] Term Structure = Time Effect",
+ "pcaInterpretation": "[RO] PCA INTERPRETATION",
+ "pc1": "[RO] PC1 = Market Factor",
+ "pc2": "[RO] PC2 = Size/Value Factor",
+ "pc3": "[RO] PC3 = Sector Rotation",
+ "higherVar": "[RO] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[RO] STRIKE",
+ "dte": "[RO] DTE",
+ "iv": "[RO] IV",
+ "correlation": "[RO] CORRELATION",
+ "maturity": "[RO] MATURITY",
+ "yield": "[RO] YIELD",
+ "loading": "[RO] LOADING",
+ "strikePrice": "[RO] STRIKE PRICE",
+ "daysToExpiry": "[RO] DAYS TO EXPIRY",
+ "impliedVol": "[RO] IMPLIED VOL (%)",
+ "assetPairIndex": "[RO] ASSET PAIR INDEX",
+ "timeDays": "[RO] TIME (DAYS)",
+ "correlationCoeff": "[RO] CORRELATION COEFF",
+ "maturityMonths": "[RO] MATURITY (MONTHS)",
+ "historicalDays": "[RO] HISTORICAL DAYS",
+ "yieldPercent": "[RO] YIELD (%)",
+ "principalComponent": "[RO] PRINCIPAL COMPONENT",
+ "assetIndex": "[RO] ASSET INDEX",
+ "factorLoading": "[RO] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[RO] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[RO] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[RO] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[RO] DAY ROLLING",
+ "yieldCurve": "[RO] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[RO] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[RO] FAILED TO LOAD DATA",
+ "authFailed": "[RO] AUTHENTICATION FAILED",
+ "authFailedHelp": "[RO] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[RO] ACCESS DENIED",
+ "accessDeniedHelp": "[RO] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[RO] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[RO] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[RO] DATA TIMEFRAME",
+ "schema": "[RO] Schema",
+ "description": "[RO] Description",
+ "recordsPerDay": "[RO] Records/Day",
+ "highFrequencyWarning": "[RO] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[RO] Data Volume"
+ },
+ "settings": {
+ "title": "[RO] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[RO] DATABENTO API KEY",
+ "configured": "[RO] CONFIGURED",
+ "invalidFormat": "[RO] INVALID FORMAT",
+ "apiKeyConfigured": "[RO] API key is configured (db-*****)",
+ "remove": "[RO] REMOVE",
+ "enterApiKey": "[RO] Enter your Databento API key (db-*****)",
+ "save": "[RO] SAVE",
+ "saving": "[RO] SAVING...",
+ "getApiKeyFrom": "[RO] Get your API key from",
+ "dashboardApiKeys": "[RO] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[RO] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[RO] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[RO] CORRELATION ASSETS",
+ "addSymbol": "[RO] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[RO] Reset to defaults",
+ "historicalDateRange": "[RO] HISTORICAL DATE RANGE",
+ "start": "[RO] Start",
+ "end": "[RO] End",
+ "autoRefreshInterval": "[RO] AUTO REFRESH INTERVAL",
+ "manualOnly": "[RO] Manual Only",
+ "every1min": "[RO] Every 1 minute",
+ "every5min": "[RO] Every 5 minutes",
+ "every15min": "[RO] Every 15 minutes",
+ "every1hour": "[RO] Every 1 hour",
+ "browseDatasets": "[RO] BROWSE DATASETS",
+ "costEstimator": "[RO] COST ESTIMATOR",
+ "referenceData": "[RO] REFERENCE DATA",
+ "orderBook": "[RO] ORDER BOOK",
+ "liveStreaming": "[RO] LIVE STREAMING",
+ "active": "[RO] ACTIVE",
+ "futuresCme": "[RO] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[RO] BATCH DOWNLOADS",
+ "additionalSchemas": "[RO] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[RO] TRADES, IMBALANCE, STATUS",
+ "cancel": "[RO] CANCEL",
+ "saveChanges": "[RO] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[RO] BATCH DOWNLOADS",
+ "newBatchJob": "[RO] NEW BATCH JOB",
+ "dataset": "[RO] Dataset",
+ "schema": "[RO] Schema",
+ "symbolsCommaSeparated": "[RO] Symbols (comma-separated)",
+ "startDate": "[RO] Start Date",
+ "endDate": "[RO] End Date",
+ "encoding": "[RO] Encoding",
+ "compression": "[RO] Compression",
+ "submitJob": "[RO] SUBMIT JOB",
+ "noBatchJobs": "[RO] No batch jobs found. Click + to create one.",
+ "records": "[RO] records",
+ "download": "[RO] Download",
+ "files": "[RO] FILES",
+ "jobsExpireNotice": "[RO] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[RO] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[RO] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[RO] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[RO] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[RO] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[RO] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[RO] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[RO] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[RO] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[RO] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[RO] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[RO] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[RO] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[RO] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[RO] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[RO] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[RO] [EN] common.or",
+ "note": "[RO] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/ro/tabs.json b/fincept-terminal-desktop/public/locales/ro/tabs.json
index d1cdf4c14..9f41c9906 100644
--- a/fincept-terminal-desktop/public/locales/ro/tabs.json
+++ b/fincept-terminal-desktop/public/locales/ro/tabs.json
@@ -5,29 +5,7 @@
"news": "Știri",
"portfolio": "Portofoliu",
"backtesting": "Backtesting",
- "watchlist": "Listă urmărire",
- "research": "Cercetare",
- "screener": "Screener",
"chat": "AI Chat",
- "agents": "Agenți",
- "settings": "Setări",
"profile": "Profil"
- },
- "functionKeys": {
- "f1": "TABL",
- "f2": "PIET",
- "f3": "STIR",
- "f4": "PORT",
- "f5": "BKTS",
- "f6": "WACH",
- "f7": "CERC",
- "f8": "SCRN",
- "f9": "TRDG",
- "f10": "AI",
- "f11": "FULL",
- "f12": "PROF"
- },
- "labels": {
- "moreTabs": "Mai multe file în meniurile toolbar"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ro/watchlist.json b/fincept-terminal-desktop/public/locales/ro/watchlist.json
index 61993e4a3..71a8c2cc9 100644
--- a/fincept-terminal-desktop/public/locales/ro/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/ro/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "LISTĂ URMĂRIRE",
- "header": {
- "export": "EXPORTĂ",
- "updating": "ACTUALIZARE",
- "live": "ÎN DIRECT"
- },
"sidebar": {
- "groups": "GRUPURI DE LISTE",
- "new": "NOUĂ",
"noWatchlists": "Nicio listă încă.",
"clickNew": "Click NOUĂ pentru a crea.",
- "stocks": "acțiuni",
- "marketMovers": "LIDERI PIAȚĂ",
- "gainer": "ÎN CREȘTERE",
- "loser": "ÎN SCĂDERE",
- "volumeLeaders": "LIDERI VOLUM"
- },
- "emptyState": {
- "selectWatchlist": "Selectați o listă sau creați una nouă pentru a începe"
- },
- "list": {
- "symbols": "Simboluri"
+ "stocks": "acțiuni"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ru/codeEditor.json b/fincept-terminal-desktop/public/locales/ru/codeEditor.json
index 35a0dcbe2..e2f5ffa91 100644
--- a/fincept-terminal-desktop/public/locales/ru/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/ru/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "РЕДАКТОР КОДА",
"header": {
- "packages": "ПАКЕТЫ"
+ "finscriptIde": "[RU] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "НОВЫЙ ФАЙЛ",
- "new": "НОВЫЙ",
- "open": "ОТКРЫТЬ",
- "save": "СОХРАНИТЬ",
"run": "ВЫПОЛНИТЬ",
"running": "ВЫПОЛНЯЕТСЯ...",
- "runAll": "ВЫПОЛНИТЬ ВСЁ",
- "history": "ИСТОРИЯ"
+ "toggleExplorer": "[RU] Toggle Explorer (Ctrl+B)",
+ "openFile": "[RU] Open File",
+ "saveShortcut": "[RU] Save (Ctrl+S)",
+ "findShortcut": "[RU] Find (Ctrl+F)",
+ "runShortcut": "[RU] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "РЕДАКТОР FINSCRIPT"
},
- "packages": {
- "clickToLoad": "Нажмите для загрузки...",
- "load": "ЗАГРУЗИТЬ ПАКЕТЫ"
+ "explorer": {
+ "title": "[RU] EXPLORER",
+ "openFiles": "[RU] OPEN FILES",
+ "examples": "[RU] EXAMPLES",
+ "runHistory": "[RU] RUN HISTORY",
+ "finscriptEngine": "[RU] FinScript Engine"
},
- "history": {
- "title": "ИСТОРИЯ НОУТБУКОВ",
- "loading": "Загрузка истории...",
- "empty": "История ноутбуков пуста"
+ "output": {
+ "title": "[RU] OUTPUT",
+ "success": "[RU] SUCCESS",
+ "error": "[RU] ERROR",
+ "executing": "[RU] EXECUTING FINSCRIPT...",
+ "noOutput": "[RU] No output yet",
+ "pressToRun": "[RU] Press Ctrl+Enter to run",
+ "completed": "[RU] COMPLETED",
+ "failed": "[RU] FAILED",
+ "signals": "[RU] signals",
+ "clear": "[RU] CLEAR",
+ "errors": "[RU] ERRORS",
+ "signalsSection": "[RU] SIGNALS",
+ "outputSection": "[RU] OUTPUT",
+ "charts": "[RU] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[RU] OHLC",
+ "histogram": "[RU] Histogram",
+ "line": "[RU] Line",
+ "points": "[RU] points"
+ },
+ "statusBar": {
+ "modified": "[RU] MODIFIED",
+ "showOutput": "[RU] SHOW OUTPUT",
+ "encoding": "[RU] UTF-8",
+ "spaces": "[RU] 4 Spaces",
+ "runShortcut": "[RU] Ctrl+Enter: Run",
+ "lines": "[RU] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[RU] Close file without saving?",
+ "unsavedChanges": "[RU] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/ru/common.json b/fincept-terminal-desktop/public/locales/ru/common.json
index 7a145c79b..efb409a53 100644
--- a/fincept-terminal-desktop/public/locales/ru/common.json
+++ b/fincept-terminal-desktop/public/locales/ru/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Загрузка...",
- "error": "Ошибка",
- "success": "Успех",
- "save": "Сохранить",
- "cancel": "Отмена",
- "delete": "Удалить",
- "edit": "Редактировать",
- "add": "Добавить",
- "search": "Поиск",
- "filter": "Фильтр",
- "back": "Назад",
- "next": "Далее",
- "previous": "Назад",
- "submit": "Отправить",
- "close": "Закрыть",
- "open": "Открыть",
- "yes": "Да",
- "no": "Нет",
- "ok": "ОК",
- "confirm": "Подтвердить",
- "language": "Язык",
- "selectLanguage": "Выбрать язык"
-}
\ No newline at end of file
+ "settings": "[RU] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/ru/dashboard.json b/fincept-terminal-desktop/public/locales/ru/dashboard.json
index 098272224..6a6a007f2 100644
--- a/fincept-terminal-desktop/public/locales/ru/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/ru/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "НАСТРАИВАЕМАЯ ПАНЕЛЬ",
- "live": "ЖИТЬ",
- "widgets": "ВИДЖЕТЫ"
- },
- "buttons": {
- "addWidget": "ДОБАВИТЬ ВИДЖЕТ",
- "saveLayout": "СОХРАНИТЬ МАКЕТ",
- "reset": "ПЕРЕЗАГРУЗИТЬ",
- "help": "ПОМОЩЬ"
- },
"widgets": {
"loading": "Загрузка...",
- "error": "Ошибка",
"globalIndices": "Глобальные индексы - Топ-12",
"forex": "Форекс — основные пары",
"crypto": "КРИПТОВАЛЮТЫ",
@@ -20,8 +8,6 @@
"news": "НОВОСТИ",
"forum": "ФОРУМ",
"watchlist": "СПИСОК ПРОСМОТРА",
- "maritimeIntelligence": "Морская разведка",
- "unknown": "Неизвестный тип виджета",
"index": "ИНДЕКС",
"symbol": "СИМВОЛ",
"price": "ЦЕНА",
@@ -38,41 +24,22 @@
"pair": "ПАРА",
"rate": "СТАВКА",
"commodity": "ТОВАР",
- "globe3D": "3D ГЛОБУС",
- "vessels": "СУДЫ",
- "routes": "МАРШРУТЫ",
- "vol24h": "ОБЪЕМ 24Ч",
- "topTradeCorridors": "ТОП ТОРГОВЫХ КОРИДОРОВ",
- "ships": "корабли",
- "marketNews": "Новости рынка",
- "secPressReleases": "Пресс-релизы SEC",
- "cryptoNews": "Крипто-новости",
- "trendingForum": "Трендовый форум",
- "techStocks": "Технологические акции"
- },
- "tips": {
- "drag": "Перетащите виджеты, чтобы изменить их порядок",
- "resize": "Изменение размера в правом нижнем углу",
- "remove": "Удаление виджетов с помощью кнопки X",
- "responsive": "Адаптивный макет — используется полная ширина."
- },
- "loading": {
- "title": "Инициализация информационной панели",
- "description": "Настройка кэша базы данных для более быстрой загрузки данных...",
- "note": "Это займет всего минуту при первом запуске."
- },
- "empty": {
- "noWidgets": "Нет виджетов на панели управления",
- "addFirst": "ДОБАВЬТЕ СВОЙ ПЕРВЫЙ ВИДЖЕТ"
- },
- "status": {
- "version": "Настраиваемая информационная панель Fincept v2.0.0 | Перетащите рабочую область",
- "layout": "Макет",
- "custom": "Обычай",
- "empty": "Пустой",
- "active": "АКТИВНЫЙ",
- "cache": "Кэш: ВКЛЮЧЕН",
- "label": "Статус"
+ "noActiveMarkets": "[RU] No active markets found",
+ "indicator": "[RU] INDICATOR",
+ "value": "[RU] VALUE",
+ "chg": "[RU] CHG",
+ "overallRisk": "[RU] OVERALL RISK",
+ "openEconomicsTab": "[RU] Open Economics Tab",
+ "openGeopoliticsTab": "[RU] Open Geopolitics Tab",
+ "openPolymarketTab": "[RU] Open Polymarket Tab",
+ "noPortfolioFound": "[RU] No portfolio found",
+ "createPortfolioHint": "[RU] Create one in Portfolio tab",
+ "openPortfolioTab": "[RU] Open Portfolio Tab",
+ "action": "[RU] ACTION",
+ "markets": "[RU] MARKETS",
+ "performanceTracker": "[RU] PERFORMANCE TRACKER",
+ "totalPnL": "[RU] TOTAL P&L",
+ "viewDetailedAnalytics": "[RU] View Detailed Analytics"
},
"messages": {
"layoutSaved": "Макет панели управления сохранен!",
diff --git a/fincept-terminal-desktop/public/locales/ru/geopolitics.json b/fincept-terminal-desktop/public/locales/ru/geopolitics.json
index 1e65d83ee..cfd57c7ac 100644
--- a/fincept-terminal-desktop/public/locales/ru/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/ru/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "ГЕОПОЛИТИКА",
"messages": {
- "loading": "Загрузка данных..."
+ "retry": "[RU] RETRY"
+ },
+ "header": {
+ "prefix": "[RU] GEO>",
+ "title": "[RU] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[RU] EVENTS"
+ },
+ "status": {
+ "stale": "[RU] STALE",
+ "loading": "[RU] LOADING...",
+ "error": "[RU] ERROR:"
+ },
+ "filters": {
+ "country": "[RU] Country...",
+ "cities": "[RU] Cities...",
+ "category": "[RU] Category...",
+ "apply": "[RU] APPLY",
+ "clear": "[RU] CLEAR",
+ "clearAllCities": "[RU] Clear all cities",
+ "selectedLabel": "[RU] Selected:"
+ },
+ "panel": {
+ "title": "[RU] INFO PANEL",
+ "expand": "[RU] Expand panel",
+ "collapse": "[RU] Collapse panel",
+ "eventsLoaded": "[RU] EVENTS LOADED",
+ "onMapVisualization": "[RU] on map visualization",
+ "topCategories": "[RU] TOP CATEGORIES",
+ "topCountries": "[RU] TOP COUNTRIES",
+ "eventDetails": "[RU] EVENT DETAILS",
+ "close": "[RU] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[RU] Country:",
+ "city": "[RU] City:",
+ "keywords": "[RU] Keywords:",
+ "coords": "[RU] Coords:",
+ "date": "[RU] Date:",
+ "source": "[RU] Source:",
+ "viewArticle": "[RU] View Article"
+ },
+ "legend": {
+ "title": "[RU] EVENT CATEGORIES",
+ "armedConflict": "[RU] Armed Conflict",
+ "terrorism": "[RU] Terrorism",
+ "protests": "[RU] Protests",
+ "civilianViolence": "[RU] Civilian Violence",
+ "riots": "[RU] Riots",
+ "politicalViolence": "[RU] Political Violence",
+ "crisis": "[RU] Crisis",
+ "explosions": "[RU] Explosions",
+ "strategic": "[RU] Strategic",
+ "unclassified": "[RU] Unclassified"
+ },
+ "footer": {
+ "tabName": "[RU] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[RU] EVENTS",
+ "labelEngine": "[RU] ENGINE",
+ "engineValue": "[RU] DECK.GL v9.2",
+ "labelSource": "[RU] SOURCE",
+ "sourceValue": "[RU] NEWS-EVENTS API",
+ "labelSelected": "[RU] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ru/markets.json b/fincept-terminal-desktop/public/locales/ru/markets.json
index c8d5ffd5a..96edd3988 100644
--- a/fincept-terminal-desktop/public/locales/ru/markets.json
+++ b/fincept-terminal-desktop/public/locales/ru/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%ИЗМ",
"high": "МАКС",
"low": "МИН",
- "loading": "Загрузка...",
"noData": "Нет данных",
"refresh": "ОБНОВИТЬ",
"auto": "АВТО",
"on": "ВКЛ",
- "off": "ВЫКЛ",
- "lastUpdate": "ПОСЛЕДНЕЕ ОБНОВЛЕНИЕ",
- "updating": "ОБНОВЛЕНИЕ",
- "live": "LIVE"
+ "off": "ВЫКЛ"
}
diff --git a/fincept-terminal-desktop/public/locales/ru/news.json b/fincept-terminal-desktop/public/locales/ru/news.json
index 29c87dbc7..c70003102 100644
--- a/fincept-terminal-desktop/public/locales/ru/news.json
+++ b/fincept-terminal-desktop/public/locales/ru/news.json
@@ -1,32 +1,63 @@
{
"title": "ПРОФЕССИОНАЛЬНЫЕ НОВОСТИ ТЕРМИНАЛА FINCEPT",
"header": {
- "liveFeed": "ЖИВАЯ ЛЕНТА",
- "live": "ЖИВОЙ",
- "refresh": "ОБНОВИТЬ",
- "updating": "ОБНОВЛЕНИЕ...",
- "alerts": "ОПОВЕЩЕНИЯ",
- "sources": "ИСТОЧНИКИ",
- "status": "СТАТУС",
- "demoMode": "ДЕМО РЕЖИМ",
- "articles": "СТАТЬИ",
- "activeSources": "АКТИВНЫЕ ИСТОЧНИКИ"
- },
- "autoRefresh": {
- "title": "ИНТЕРВАЛ АВТООБНОВЛЕНИЯ",
- "minute": "минута",
- "minutes": "минут"
+ "refresh": "ОБНОВИТЬ"
},
"messages": {
- "loadingFeeds": "Загрузка лент...",
- "breaking": "СРОЧНО"
- },
- "feeds": {
- "primary": "[RU] PRIMARY NEWS FEED",
- "secondary": "[RU] SECONDARY NEWS FEED",
- "additional": "[RU] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[RU] Loading feeds...",
+ "failedToLoad": "[RU] Failed to load RSS feeds",
+ "noCustomFeeds": "[RU] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[RU] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[RU] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[RU] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[RU] RSS FEED SETTINGS",
+ "subtitle": "[RU] MANAGE YOUR NEWS SOURCES",
+ "close": "[RU] CLOSE",
+ "myFeeds": "[RU] MY FEEDS",
+ "defaultFeeds": "[RU] DEFAULT FEEDS",
+ "noFeedsAvailable": "[RU] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[RU] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[RU] ADD NEW FEED",
+ "addNewRssFeed": "[RU] ADD NEW RSS FEED",
+ "editRssFeed": "[RU] EDIT RSS FEED",
+ "restoreDefaults": "[RU] RESTORE DEFAULTS",
+ "restoreAll": "[RU] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[RU] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[RU] DISPLAY NAME",
+ "sourceName": "[RU] SOURCE NAME (SHORT)",
+ "feedUrl": "[RU] RSS FEED URL",
+ "category": "[RU] CATEGORY",
+ "region": "[RU] REGION",
+ "required": "[RU] *",
+ "testUrl": "[RU] TEST URL",
+ "testing": "[RU] TESTING...",
+ "valid": "[RU] VALID",
+ "cancel": "[RU] CANCEL",
+ "saving": "[RU] SAVING...",
+ "addFeed": "[RU] ADD FEED",
+ "updateFeed": "[RU] UPDATE FEED",
+ "on": "[RU] ON",
+ "off": "[RU] OFF",
+ "default": "[RU] DEFAULT",
+ "total": "[RU] TOTAL",
+ "active": "[RU] ACTIVE",
+ "custom": "[RU] CUSTOM",
+ "placeholders": {
+ "displayName": "[RU] e.g., Bloomberg Markets",
+ "sourceName": "[RU] e.g., BLOOMBERG",
+ "feedUrl": "[RU] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[RU] Name is required",
+ "sourceRequired": "[RU] Source name is required",
+ "invalidUrl": "[RU] Please enter a valid URL",
+ "invalidRss": "[RU] URL does not appear to be a valid RSS feed",
+ "testFailed": "[RU] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[RU] Delete this RSS feed?",
+ "message": "[RU] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/ru/portfolio.json b/fincept-terminal-desktop/public/locales/ru/portfolio.json
index 31c64c37c..92a09ee92 100644
--- a/fincept-terminal-desktop/public/locales/ru/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/ru/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "МЕНЕДЖЕР ПОРТФЕЛЯ FINCEPT",
- "header": {
- "live": "ЖИВОЙ",
- "updating": "ОБНОВЛЕНИЕ",
- "newPortfolio": "НОВЫЙ ПОРТФЕЛЬ",
- "refresh": "ОБНОВИТЬ",
- "exportCsv": "ЭКСПОРТ CSV"
- },
- "summary": {
- "totalValue": "ОБЩАЯ СТОИМОСТЬ",
- "dayPnl": "П/У ЗА ДЕНЬ",
- "totalPnl": "ОБЩИЙ П/У",
- "positions": "ПОЗИЦИИ"
- },
- "views": {
- "positions": "ПОЗИЦИИ",
- "addAsset": "ДОБАВИТЬ АКТИВ",
- "sellAsset": "ПРОДАТЬ АКТИВ",
- "analytics": "АНАЛИТИКА",
- "history": "ИСТОРИЯ",
- "activeMgmt": "АКТИВНОЕ УПРАВЛЕНИЕ",
- "performance": "ЭФФЕКТИВНОСТЬ",
- "rebalance": "РЕБАЛАНСИРОВКА",
- "reports": "ОТЧЕТЫ",
- "alerts": "ОПОВЕЩЕНИЯ",
- "sectors": "СЕКТОРЫ",
- "help": "ПОМОЩЬ"
- },
- "sidebar": {
- "portfolios": "ПОРТФЕЛИ",
- "loading": "Загрузка портфелей...",
- "noPortfolios": "Портфелей пока нет.",
- "clickCreate": "Нажмите НОВЫЙ ПОРТФЕЛЬ для создания.",
- "owner": "Владелец",
- "currency": "Валюта"
- },
- "content": {
- "selectOrCreate": "Выберите портфель или создайте новый для начала",
- "loadingData": "Загрузка данных портфеля...",
- "comingSoon": "вид скоро..."
- },
- "modals": {
- "createNew": "СОЗДАТЬ НОВЫЙ ПОРТФЕЛЬ",
- "portfolioName": "НАЗВАНИЕ ПОРТФЕЛЯ",
- "owner": "ВЛАДЕЛЕЦ",
- "currency": "ВАЛЮТА",
- "cancel": "ОТМЕНА",
- "create": "СОЗДАТЬ",
- "addAssetTitle": "ДОБАВИТЬ АКТИВ В ПОРТФЕЛЬ",
- "sellAssetTitle": "ПРОДАТЬ АКТИВ",
- "symbol": "СИМВОЛ",
- "quantity": "КОЛИЧЕСТВО",
- "price": "ЦЕНА",
- "add": "ДОБАВИТЬ",
- "sell": "ПРОДАТЬ"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Отслеживание в реальном времени с интеграцией yfinance",
- "lastUpdated": "Последнее Обновление",
- "connected": "ПОДКЛЮЧЕН"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "СОЗДАТЬ НОВЫЙ ПОРТФЕЛЬ",
+ "portfolioName": "НАЗВАНИЕ ПОРТФЕЛЯ",
+ "owner": "ВЛАДЕЛЕЦ",
+ "currency": "ВАЛЮТА",
+ "cancel": "ОТМЕНА",
+ "create": "СОЗДАТЬ",
+ "addAssetTitle": "ДОБАВИТЬ АКТИВ В ПОРТФЕЛЬ",
+ "sellAssetTitle": "ПРОДАТЬ АКТИВ",
+ "symbol": "СИМВОЛ",
+ "quantity": "КОЛИЧЕСТВО",
+ "price": "ЦЕНА",
+ "add": "ДОБАВИТЬ",
+ "sell": "ПРОДАТЬ"
+ },
+ "extracted": {
+ "areYouSureYou": "[RU] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/ru/reportBuilder.json b/fincept-terminal-desktop/public/locales/ru/reportBuilder.json
index cea152311..7860be9c3 100644
--- a/fincept-terminal-desktop/public/locales/ru/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/ru/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[RU] Load",
"save": "[RU] Save",
- "saving": "[RU] Saving...",
- "exportPdf": "[RU] Export PDF",
- "generating": "[RU] Generating..."
+ "saving": "[RU] Saving..."
},
"components": {
"title": "[RU] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/ru/settings.json b/fincept-terminal-desktop/public/locales/ru/settings.json
index 7478a1790..4587c9268 100644
--- a/fincept-terminal-desktop/public/locales/ru/settings.json
+++ b/fincept-terminal-desktop/public/locales/ru/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Макет вкладок",
"appearance": "Появление",
"language": "Язык",
- "storage": "Хранение и кэш"
+ "storage": "Хранение и кэш",
+ "notifications": "[RU] Notifications"
},
"credentials": {
"title": "Управление учетными данными API",
@@ -46,7 +47,31 @@
"saveConfig": "СОХРАНИТЬ КОНФИГУРАЦИЯ",
"reset": "ПЕРЕЗАГРУЗИТЬ",
"saveSuccess": "Внешний вид терминала и сопоставление клавиш успешно сохранены.",
- "resetSuccess": "Сброс к внешнему виду и сопоставлению клавиш по умолчанию"
+ "resetSuccess": "Сброс к внешнему виду и сопоставлению клавиш по умолчанию",
+ "customColors": "[RU] Custom Colors",
+ "customColorsTitle": "[RU] CUSTOM COLORS",
+ "colorPrimary": "[RU] Primary",
+ "colorSecondary": "[RU] Secondary",
+ "colorSuccess": "[RU] Success",
+ "colorAlert": "[RU] Alert",
+ "colorWarning": "[RU] Warning",
+ "colorInfo": "[RU] Info",
+ "colorAccent": "[RU] Accent",
+ "colorPurple": "[RU] Purple",
+ "colorText": "[RU] Text",
+ "colorTextMuted": "[RU] Text Muted",
+ "colorBackground": "[RU] Background",
+ "colorPanel": "[RU] Panel",
+ "layoutSpacing": "[RU] LAYOUT & SPACING",
+ "contentDensity": "[RU] CONTENT DENSITY",
+ "borderRadius": "[RU] BORDER RADIUS",
+ "borderStyle": "[RU] BORDER STYLE",
+ "lineHeight": "[RU] LINE HEIGHT",
+ "letterSpacing": "[RU] LETTER SPACING",
+ "effects": "[RU] EFFECTS",
+ "widgetOpacity": "[RU] WIDGET OPACITY",
+ "enableGlow": "[RU] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[RU] GLOW INTENSITY"
},
"stockSymbols": {
"title": "База данных биржевых символов",
@@ -65,17 +90,8 @@
"tip": "СОВЕТ: Перетаскивайте вкладки, чтобы изменить их порядок. Используйте кнопки со стрелками для перемещения вкладок между разделами заголовка и меню. Изменения сохраняются автоматически."
},
"llm": {
- "title": "КОНФИГУРАЦИЯ LLM",
- "description": "Настройка моделей и поставщиков ИИ",
"connected": "ПОДКЛЮЧЕНО",
- "disconnected": "ОТКЛЮЧЕНО",
- "provider": "ИИ-ПРОВАЙДЕР",
- "globalSettings": "ГЛОБАЛЬНЫЕ НАСТРОЙКИ ИИ",
- "temperature": "ТЕМПЕРАТУРА",
- "maxTokens": "МАКС. ТОКЕНОВ",
- "systemPrompt": "СИСТЕМНАЯ ПОДСКАЗКА",
- "modelLibrary": "МОДЕЛЬНАЯ БИБЛИОТЕКА",
- "multiModelConfigs": "Мультимодельные конфигурации"
+ "disconnected": "ОТКЛЮЧЕНО"
},
"buttons": {
"save": "СОХРАНЯТЬ",
@@ -86,5 +102,18 @@
"database": "База данных: SQLite.",
"storage": "Хранение: файловое",
"secureStorage": "Все данные надежно хранятся в fincept_terminal.db."
+ },
+ "notifications": {
+ "title": "[RU] NOTIFICATION PROVIDERS",
+ "description": "[RU] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[RU] Event Filters",
+ "eventFilterDescription": "[RU] Choose which notification types to forward to external providers.",
+ "providers": "[RU] Providers",
+ "enabled": "[RU] Enabled",
+ "disabled": "[RU] Disabled",
+ "testButton": "[RU] TEST",
+ "testSuccess": "[RU] Test notification sent successfully!",
+ "testFailed": "[RU] Failed to send test notification. Check your configuration.",
+ "saved": "[RU] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ru/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/ru/surfaceAnalytics.json
new file mode 100644
index 000000000..9ba33db17
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/ru/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[RU] SURFACE ANALYTICS",
+ "initializing": "[RU] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[RU] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[RU] VOL SURFACE",
+ "correlation": "[RU] CORRELATION",
+ "yieldCurve": "[RU] YIELD CURVE",
+ "pca": "[RU] PCA FACTORS"
+ },
+ "demoData": "[RU] DEMO DATA",
+ "demoDataSynthetic": "[RU] DEMO DATA (synthetic)",
+ "synthetic": "[RU] SYNTHETIC",
+ "manual": "[RU] MANUAL",
+ "error": "[RU] ERROR",
+ "ready": "[RU] READY",
+ "metrics": "[RU] Metrics",
+ "updated": "[RU] Updated",
+ "clickRefresh": "[RU] Click REFRESH to load data",
+ "refresh": "[RU] REFRESH",
+ "noApiKey": "[RU] NO API KEY",
+ "lastUpdate": "[RU] LAST UPDATE",
+ "loadingData": "[RU] LOADING DATA...",
+ "noDataLoaded": "[RU] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[RU] IV SURFACE METRICS",
+ "correlationMetrics": "[RU] CORRELATION METRICS",
+ "yieldCurveMetrics": "[RU] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[RU] PCA FACTOR METRICS",
+ "dataInfo": "[RU] DATA INFO",
+ "source": "[RU] SOURCE",
+ "frequency": "[RU] FREQUENCY",
+ "quality": "[RU] QUALITY",
+ "correlationScale": "[RU] CORRELATION SCALE",
+ "strongPositive": "[RU] Strong Positive (0.7-1.0)",
+ "neutral": "[RU] Neutral (0.3-0.7)",
+ "strongNegative": "[RU] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[RU] IV INTERPRETATION",
+ "highIv": "[RU] High IV = Expensive Options",
+ "lowIv": "[RU] Low IV = Cheap Options",
+ "skew": "[RU] Skew = Put/Call IV Diff",
+ "termStructure": "[RU] Term Structure = Time Effect",
+ "pcaInterpretation": "[RU] PCA INTERPRETATION",
+ "pc1": "[RU] PC1 = Market Factor",
+ "pc2": "[RU] PC2 = Size/Value Factor",
+ "pc3": "[RU] PC3 = Sector Rotation",
+ "higherVar": "[RU] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[RU] STRIKE",
+ "dte": "[RU] DTE",
+ "iv": "[RU] IV",
+ "correlation": "[RU] CORRELATION",
+ "maturity": "[RU] MATURITY",
+ "yield": "[RU] YIELD",
+ "loading": "[RU] LOADING",
+ "strikePrice": "[RU] STRIKE PRICE",
+ "daysToExpiry": "[RU] DAYS TO EXPIRY",
+ "impliedVol": "[RU] IMPLIED VOL (%)",
+ "assetPairIndex": "[RU] ASSET PAIR INDEX",
+ "timeDays": "[RU] TIME (DAYS)",
+ "correlationCoeff": "[RU] CORRELATION COEFF",
+ "maturityMonths": "[RU] MATURITY (MONTHS)",
+ "historicalDays": "[RU] HISTORICAL DAYS",
+ "yieldPercent": "[RU] YIELD (%)",
+ "principalComponent": "[RU] PRINCIPAL COMPONENT",
+ "assetIndex": "[RU] ASSET INDEX",
+ "factorLoading": "[RU] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[RU] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[RU] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[RU] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[RU] DAY ROLLING",
+ "yieldCurve": "[RU] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[RU] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[RU] FAILED TO LOAD DATA",
+ "authFailed": "[RU] AUTHENTICATION FAILED",
+ "authFailedHelp": "[RU] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[RU] ACCESS DENIED",
+ "accessDeniedHelp": "[RU] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[RU] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[RU] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[RU] DATA TIMEFRAME",
+ "schema": "[RU] Schema",
+ "description": "[RU] Description",
+ "recordsPerDay": "[RU] Records/Day",
+ "highFrequencyWarning": "[RU] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[RU] Data Volume"
+ },
+ "settings": {
+ "title": "[RU] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[RU] DATABENTO API KEY",
+ "configured": "[RU] CONFIGURED",
+ "invalidFormat": "[RU] INVALID FORMAT",
+ "apiKeyConfigured": "[RU] API key is configured (db-*****)",
+ "remove": "[RU] REMOVE",
+ "enterApiKey": "[RU] Enter your Databento API key (db-*****)",
+ "save": "[RU] SAVE",
+ "saving": "[RU] SAVING...",
+ "getApiKeyFrom": "[RU] Get your API key from",
+ "dashboardApiKeys": "[RU] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[RU] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[RU] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[RU] CORRELATION ASSETS",
+ "addSymbol": "[RU] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[RU] Reset to defaults",
+ "historicalDateRange": "[RU] HISTORICAL DATE RANGE",
+ "start": "[RU] Start",
+ "end": "[RU] End",
+ "autoRefreshInterval": "[RU] AUTO REFRESH INTERVAL",
+ "manualOnly": "[RU] Manual Only",
+ "every1min": "[RU] Every 1 minute",
+ "every5min": "[RU] Every 5 minutes",
+ "every15min": "[RU] Every 15 minutes",
+ "every1hour": "[RU] Every 1 hour",
+ "browseDatasets": "[RU] BROWSE DATASETS",
+ "costEstimator": "[RU] COST ESTIMATOR",
+ "referenceData": "[RU] REFERENCE DATA",
+ "orderBook": "[RU] ORDER BOOK",
+ "liveStreaming": "[RU] LIVE STREAMING",
+ "active": "[RU] ACTIVE",
+ "futuresCme": "[RU] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[RU] BATCH DOWNLOADS",
+ "additionalSchemas": "[RU] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[RU] TRADES, IMBALANCE, STATUS",
+ "cancel": "[RU] CANCEL",
+ "saveChanges": "[RU] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[RU] BATCH DOWNLOADS",
+ "newBatchJob": "[RU] NEW BATCH JOB",
+ "dataset": "[RU] Dataset",
+ "schema": "[RU] Schema",
+ "symbolsCommaSeparated": "[RU] Symbols (comma-separated)",
+ "startDate": "[RU] Start Date",
+ "endDate": "[RU] End Date",
+ "encoding": "[RU] Encoding",
+ "compression": "[RU] Compression",
+ "submitJob": "[RU] SUBMIT JOB",
+ "noBatchJobs": "[RU] No batch jobs found. Click + to create one.",
+ "records": "[RU] records",
+ "download": "[RU] Download",
+ "files": "[RU] FILES",
+ "jobsExpireNotice": "[RU] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[RU] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[RU] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[RU] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[RU] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[RU] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[RU] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[RU] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[RU] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[RU] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[RU] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[RU] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[RU] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[RU] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[RU] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[RU] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[RU] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[RU] [EN] common.or",
+ "note": "[RU] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/ru/tabs.json b/fincept-terminal-desktop/public/locales/ru/tabs.json
index 7a50bf7ca..ce4d444c7 100644
--- a/fincept-terminal-desktop/public/locales/ru/tabs.json
+++ b/fincept-terminal-desktop/public/locales/ru/tabs.json
@@ -5,29 +5,7 @@
"news": "Новости",
"portfolio": "Портфель",
"backtesting": "Бэктестинг",
- "watchlist": "Список наблюдения",
- "research": "Исследования",
- "screener": "Скринер",
"chat": "AI Чат",
- "agents": "Агенты",
- "settings": "Настройки",
"profile": "Профиль"
- },
- "functionKeys": {
- "f1": "ПАНЛ",
- "f2": "РЫНК",
- "f3": "НОВС",
- "f4": "ПОРТ",
- "f5": "БКТС",
- "f6": "НАБЛ",
- "f7": "ИССЛ",
- "f8": "СКРН",
- "f9": "ТРДГ",
- "f10": "AI",
- "f11": "ПОЛН",
- "f12": "ПРОФ"
- },
- "labels": {
- "moreTabs": "Больше вкладок в меню панели инструментов"
}
}
diff --git a/fincept-terminal-desktop/public/locales/ru/watchlist.json b/fincept-terminal-desktop/public/locales/ru/watchlist.json
index dbc869311..d1afee96e 100644
--- a/fincept-terminal-desktop/public/locales/ru/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/ru/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "СПИСОК НАБЛЮДЕНИЯ",
- "header": {
- "export": "ЭКСПОРТ",
- "updating": "ОБНОВЛЕНИЕ",
- "live": "ЖИВОЙ"
- },
"sidebar": {
- "groups": "ГРУППЫ СПИСКОВ",
- "new": "НОВЫЙ",
"noWatchlists": "Пока нет списков.",
"clickNew": "Нажмите НОВЫЙ для создания.",
- "stocks": "акции",
- "marketMovers": "ЛИДЕРЫ РЫНКА",
- "gainer": "РАСТУТ",
- "loser": "ПАДАЮТ",
- "volumeLeaders": "ЛИДЕРЫ ОБЪЕМА"
- },
- "emptyState": {
- "selectWatchlist": "Выберите список или создайте новый для начала"
- },
- "list": {
- "symbols": "Символы"
+ "stocks": "акции"
}
}
diff --git a/fincept-terminal-desktop/public/locales/th/codeEditor.json b/fincept-terminal-desktop/public/locales/th/codeEditor.json
index 2a5eec591..9659c4dfa 100644
--- a/fincept-terminal-desktop/public/locales/th/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/th/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "ตัวแก้ไขโค้ด",
"header": {
- "packages": "แพ็คเกจ"
+ "finscriptIde": "[TH] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "ไฟล์ใหม่",
- "new": "ใหม่",
- "open": "เปิด",
- "save": "บันทึก",
"run": "รันโค้ด",
"running": "กำลังรัน...",
- "runAll": "รันทั้งหมด",
- "history": "ประวัติ"
+ "toggleExplorer": "[TH] Toggle Explorer (Ctrl+B)",
+ "openFile": "[TH] Open File",
+ "saveShortcut": "[TH] Save (Ctrl+S)",
+ "findShortcut": "[TH] Find (Ctrl+F)",
+ "runShortcut": "[TH] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "ตัวแก้ไข FINSCRIPT"
},
- "packages": {
- "clickToLoad": "คลิกเพื่อโหลด...",
- "load": "โหลดแพ็คเกจ"
+ "explorer": {
+ "title": "[TH] EXPLORER",
+ "openFiles": "[TH] OPEN FILES",
+ "examples": "[TH] EXAMPLES",
+ "runHistory": "[TH] RUN HISTORY",
+ "finscriptEngine": "[TH] FinScript Engine"
},
- "history": {
- "title": "ประวัติ NOTEBOOK",
- "loading": "กำลังโหลดประวัติ...",
- "empty": "ไม่มีประวัติ notebook"
+ "output": {
+ "title": "[TH] OUTPUT",
+ "success": "[TH] SUCCESS",
+ "error": "[TH] ERROR",
+ "executing": "[TH] EXECUTING FINSCRIPT...",
+ "noOutput": "[TH] No output yet",
+ "pressToRun": "[TH] Press Ctrl+Enter to run",
+ "completed": "[TH] COMPLETED",
+ "failed": "[TH] FAILED",
+ "signals": "[TH] signals",
+ "clear": "[TH] CLEAR",
+ "errors": "[TH] ERRORS",
+ "signalsSection": "[TH] SIGNALS",
+ "outputSection": "[TH] OUTPUT",
+ "charts": "[TH] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[TH] OHLC",
+ "histogram": "[TH] Histogram",
+ "line": "[TH] Line",
+ "points": "[TH] points"
+ },
+ "statusBar": {
+ "modified": "[TH] MODIFIED",
+ "showOutput": "[TH] SHOW OUTPUT",
+ "encoding": "[TH] UTF-8",
+ "spaces": "[TH] 4 Spaces",
+ "runShortcut": "[TH] Ctrl+Enter: Run",
+ "lines": "[TH] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[TH] Close file without saving?",
+ "unsavedChanges": "[TH] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/th/common.json b/fincept-terminal-desktop/public/locales/th/common.json
index e0f0669f8..5aa1405c6 100644
--- a/fincept-terminal-desktop/public/locales/th/common.json
+++ b/fincept-terminal-desktop/public/locales/th/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "กำลังโหลด...",
- "error": "ข้อผิดพลาด",
- "success": "สำเร็จ",
- "save": "บันทึก",
- "cancel": "ยกเลิก",
- "delete": "ลบ",
- "edit": "แก้ไข",
- "add": "เพิ่ม",
- "search": "ค้นหา",
- "filter": "กรอง",
- "back": "กลับ",
- "next": "ถัดไป",
- "previous": "ก่อนหน้า",
- "submit": "ส่ง",
- "close": "ปิด",
- "open": "เปิด",
- "yes": "ใช่",
- "no": "ไม่",
- "ok": "ตกลง",
- "confirm": "ยืนยัน",
- "language": "ภาษา",
- "selectLanguage": "เลือกภาษา"
-}
\ No newline at end of file
+ "settings": "[TH] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/th/dashboard.json b/fincept-terminal-desktop/public/locales/th/dashboard.json
index d82a0fb0e..62ba7aa63 100644
--- a/fincept-terminal-desktop/public/locales/th/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/th/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "แดชบอร์ดที่ปรับแต่งได้",
- "live": "สด",
- "widgets": "วิดเจ็ต"
- },
- "buttons": {
- "addWidget": "เพิ่มวิดเจ็ต",
- "saveLayout": "บันทึกเค้าโครง",
- "reset": "รีเซ็ต",
- "help": "ช่วย"
- },
"widgets": {
"loading": "กำลังโหลด...",
- "error": "ข้อผิดพลาด",
"globalIndices": "ดัชนีระดับโลก - 12 อันดับแรก",
"forex": "ฟอเร็กซ์ - คู่หลัก",
"crypto": "สกุลเงินดิจิทัล",
@@ -20,8 +8,6 @@
"news": "ข่าว",
"forum": "ฟอรัม",
"watchlist": "รายการเฝ้าดู",
- "maritimeIntelligence": "หน่วยสืบราชการลับทางทะเล",
- "unknown": "ประเภทวิดเจ็ตที่ไม่รู้จัก",
"index": "ดัชนี",
"symbol": "เครื่องหมาย",
"price": "ราคา",
@@ -38,41 +24,22 @@
"pair": "คู่",
"rate": "ประเมิน",
"commodity": "สินค้าโภคภัณฑ์",
- "globe3D": "ลูกโลก 3 มิติ",
- "vessels": "เรือ",
- "routes": "เส้นทาง",
- "vol24h": "ฉบับ 24H",
- "topTradeCorridors": "ทางเดินการค้าชั้นนำ",
- "ships": "เรือ",
- "marketNews": "ข่าวการตลาด",
- "secPressReleases": "ข่าวประชาสัมพันธ์ ก.ล.ต",
- "cryptoNews": "ข่าวการเข้ารหัสลับ",
- "trendingForum": "ฟอรั่มที่กำลังมาแรง",
- "techStocks": "หุ้นเทคโนโลยี"
- },
- "tips": {
- "drag": "ลากวิดเจ็ตเพื่อจัดเรียงใหม่",
- "resize": "ปรับขนาดจากมุมขวาล่าง",
- "remove": "ลบวิดเจ็ตด้วยปุ่ม X",
- "responsive": "รูปแบบที่ปรับเปลี่ยนตามอุปกรณ์ - ใช้ความกว้างเต็ม"
- },
- "loading": {
- "title": "กำลังเริ่มต้นแดชบอร์ด",
- "description": "การตั้งค่าแคชฐานข้อมูลเพื่อให้โหลดข้อมูลได้เร็วขึ้น...",
- "note": "ขั้นตอนนี้จะใช้เวลาสักครู่ในการเปิดตัวครั้งแรก"
- },
- "empty": {
- "noWidgets": "ไม่มีวิดเจ็ตบนแดชบอร์ด",
- "addFirst": "เพิ่มวิดเจ็ตแรกของคุณ"
- },
- "status": {
- "version": "Fincept แดชบอร์ดที่ปรับแต่งได้ v2.0.0 | ลากและวางพื้นที่ทำงาน",
- "layout": "เค้าโครง",
- "custom": "กำหนดเอง",
- "empty": "ว่างเปล่า",
- "active": "คล่องแคล่ว",
- "cache": "แคช: เปิดใช้งานแล้ว",
- "label": "สถานะ"
+ "noActiveMarkets": "[TH] No active markets found",
+ "indicator": "[TH] INDICATOR",
+ "value": "[TH] VALUE",
+ "chg": "[TH] CHG",
+ "overallRisk": "[TH] OVERALL RISK",
+ "openEconomicsTab": "[TH] Open Economics Tab",
+ "openGeopoliticsTab": "[TH] Open Geopolitics Tab",
+ "openPolymarketTab": "[TH] Open Polymarket Tab",
+ "noPortfolioFound": "[TH] No portfolio found",
+ "createPortfolioHint": "[TH] Create one in Portfolio tab",
+ "openPortfolioTab": "[TH] Open Portfolio Tab",
+ "action": "[TH] ACTION",
+ "markets": "[TH] MARKETS",
+ "performanceTracker": "[TH] PERFORMANCE TRACKER",
+ "totalPnL": "[TH] TOTAL P&L",
+ "viewDetailedAnalytics": "[TH] View Detailed Analytics"
},
"messages": {
"layoutSaved": "บันทึกเค้าโครงแดชบอร์ดแล้ว!",
diff --git a/fincept-terminal-desktop/public/locales/th/geopolitics.json b/fincept-terminal-desktop/public/locales/th/geopolitics.json
index 3afd4be09..7e455cab4 100644
--- a/fincept-terminal-desktop/public/locales/th/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/th/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "ภูมิรัฐศาสตร์",
"messages": {
- "loading": "กำลังโหลดข้อมูล..."
+ "retry": "[TH] RETRY"
+ },
+ "header": {
+ "prefix": "[TH] GEO>",
+ "title": "[TH] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[TH] EVENTS"
+ },
+ "status": {
+ "stale": "[TH] STALE",
+ "loading": "[TH] LOADING...",
+ "error": "[TH] ERROR:"
+ },
+ "filters": {
+ "country": "[TH] Country...",
+ "cities": "[TH] Cities...",
+ "category": "[TH] Category...",
+ "apply": "[TH] APPLY",
+ "clear": "[TH] CLEAR",
+ "clearAllCities": "[TH] Clear all cities",
+ "selectedLabel": "[TH] Selected:"
+ },
+ "panel": {
+ "title": "[TH] INFO PANEL",
+ "expand": "[TH] Expand panel",
+ "collapse": "[TH] Collapse panel",
+ "eventsLoaded": "[TH] EVENTS LOADED",
+ "onMapVisualization": "[TH] on map visualization",
+ "topCategories": "[TH] TOP CATEGORIES",
+ "topCountries": "[TH] TOP COUNTRIES",
+ "eventDetails": "[TH] EVENT DETAILS",
+ "close": "[TH] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[TH] Country:",
+ "city": "[TH] City:",
+ "keywords": "[TH] Keywords:",
+ "coords": "[TH] Coords:",
+ "date": "[TH] Date:",
+ "source": "[TH] Source:",
+ "viewArticle": "[TH] View Article"
+ },
+ "legend": {
+ "title": "[TH] EVENT CATEGORIES",
+ "armedConflict": "[TH] Armed Conflict",
+ "terrorism": "[TH] Terrorism",
+ "protests": "[TH] Protests",
+ "civilianViolence": "[TH] Civilian Violence",
+ "riots": "[TH] Riots",
+ "politicalViolence": "[TH] Political Violence",
+ "crisis": "[TH] Crisis",
+ "explosions": "[TH] Explosions",
+ "strategic": "[TH] Strategic",
+ "unclassified": "[TH] Unclassified"
+ },
+ "footer": {
+ "tabName": "[TH] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[TH] EVENTS",
+ "labelEngine": "[TH] ENGINE",
+ "engineValue": "[TH] DECK.GL v9.2",
+ "labelSource": "[TH] SOURCE",
+ "sourceValue": "[TH] NEWS-EVENTS API",
+ "labelSelected": "[TH] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/th/markets.json b/fincept-terminal-desktop/public/locales/th/markets.json
index c92062d23..dea07fff7 100644
--- a/fincept-terminal-desktop/public/locales/th/markets.json
+++ b/fincept-terminal-desktop/public/locales/th/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%เปลี่ยน",
"high": "สูง",
"low": "ต่ำ",
- "loading": "กำลังโหลด...",
"noData": "ไม่มีข้อมูล",
"refresh": "รีเฟรช",
"auto": "อัตโนมัติ",
"on": "เปิด",
- "off": "ปิด",
- "lastUpdate": "อัปเดตล่าสุด",
- "updating": "กำลังอัปเดต",
- "live": "สด"
+ "off": "ปิด"
}
diff --git a/fincept-terminal-desktop/public/locales/th/news.json b/fincept-terminal-desktop/public/locales/th/news.json
index 6919065a1..b6a2c5732 100644
--- a/fincept-terminal-desktop/public/locales/th/news.json
+++ b/fincept-terminal-desktop/public/locales/th/news.json
@@ -1,32 +1,63 @@
{
"title": "ข่าวมืออาชีพเทอร์มินัล FINCEPT",
"header": {
- "liveFeed": "ฟีดสด",
- "live": "สด",
- "refresh": "รีเฟรช",
- "updating": "กำลังอัปเดต...",
- "alerts": "การแจ้งเตือน",
- "sources": "แหล่งข่าว",
- "status": "สถานะ",
- "demoMode": "โหมดสาธิต",
- "articles": "บทความ",
- "activeSources": "แหล่งข่าวที่ใช้งาน"
- },
- "autoRefresh": {
- "title": "ช่วงเวลาอัปเดตอัตโนมัติ",
- "minute": "นาที",
- "minutes": "นาที"
+ "refresh": "รีเฟรช"
},
"messages": {
- "loadingFeeds": "กำลังโหลดฟีดข่าว...",
- "breaking": "ด่วน"
- },
- "feeds": {
- "primary": "[TH] PRIMARY NEWS FEED",
- "secondary": "[TH] SECONDARY NEWS FEED",
- "additional": "[TH] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[TH] Loading feeds...",
+ "failedToLoad": "[TH] Failed to load RSS feeds",
+ "noCustomFeeds": "[TH] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[TH] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[TH] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[TH] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[TH] RSS FEED SETTINGS",
+ "subtitle": "[TH] MANAGE YOUR NEWS SOURCES",
+ "close": "[TH] CLOSE",
+ "myFeeds": "[TH] MY FEEDS",
+ "defaultFeeds": "[TH] DEFAULT FEEDS",
+ "noFeedsAvailable": "[TH] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[TH] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[TH] ADD NEW FEED",
+ "addNewRssFeed": "[TH] ADD NEW RSS FEED",
+ "editRssFeed": "[TH] EDIT RSS FEED",
+ "restoreDefaults": "[TH] RESTORE DEFAULTS",
+ "restoreAll": "[TH] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[TH] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[TH] DISPLAY NAME",
+ "sourceName": "[TH] SOURCE NAME (SHORT)",
+ "feedUrl": "[TH] RSS FEED URL",
+ "category": "[TH] CATEGORY",
+ "region": "[TH] REGION",
+ "required": "[TH] *",
+ "testUrl": "[TH] TEST URL",
+ "testing": "[TH] TESTING...",
+ "valid": "[TH] VALID",
+ "cancel": "[TH] CANCEL",
+ "saving": "[TH] SAVING...",
+ "addFeed": "[TH] ADD FEED",
+ "updateFeed": "[TH] UPDATE FEED",
+ "on": "[TH] ON",
+ "off": "[TH] OFF",
+ "default": "[TH] DEFAULT",
+ "total": "[TH] TOTAL",
+ "active": "[TH] ACTIVE",
+ "custom": "[TH] CUSTOM",
+ "placeholders": {
+ "displayName": "[TH] e.g., Bloomberg Markets",
+ "sourceName": "[TH] e.g., BLOOMBERG",
+ "feedUrl": "[TH] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[TH] Name is required",
+ "sourceRequired": "[TH] Source name is required",
+ "invalidUrl": "[TH] Please enter a valid URL",
+ "invalidRss": "[TH] URL does not appear to be a valid RSS feed",
+ "testFailed": "[TH] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[TH] Delete this RSS feed?",
+ "message": "[TH] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/th/portfolio.json b/fincept-terminal-desktop/public/locales/th/portfolio.json
index 254f06816..18baa3bce 100644
--- a/fincept-terminal-desktop/public/locales/th/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/th/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "ตัวจัดการพอร์ตโฟลิโอ FINCEPT",
- "header": {
- "live": "สด",
- "updating": "กำลังอัปเดต",
- "newPortfolio": "พอร์ตใหม่",
- "refresh": "รีเฟรช",
- "exportCsv": "ส่งออก CSV"
- },
- "summary": {
- "totalValue": "มูลค่ารวม",
- "dayPnl": "กำไร/ขาดทุนวันนี้",
- "totalPnl": "กำไร/ขาดทุนรวม",
- "positions": "ตำแหน่ง"
- },
- "views": {
- "positions": "ตำแหน่ง",
- "addAsset": "เพิ่มสินทรัพย์",
- "sellAsset": "ขายสินทรัพย์",
- "analytics": "การวิเคราะห์",
- "history": "ประวัติ",
- "activeMgmt": "การจัดการเชิงรุก",
- "performance": "ผลการดำเนินงาน",
- "rebalance": "ปรับสมดุล",
- "reports": "รายงาน",
- "alerts": "การแจ้งเตือน",
- "sectors": "กลุ่มอุตสาหกรรม",
- "help": "ช่วยเหลือ"
- },
- "sidebar": {
- "portfolios": "พอร์ตโฟลิโอ",
- "loading": "กำลังโหลดพอร์ต...",
- "noPortfolios": "ยังไม่มีพอร์ต",
- "clickCreate": "คลิก พอร์ตใหม่ เพื่อสร้าง",
- "owner": "เจ้าของ",
- "currency": "สกุลเงิน"
- },
- "content": {
- "selectOrCreate": "เลือกพอร์ตหรือสร้างใหม่เพื่อเริ่มต้น",
- "loadingData": "กำลังโหลดข้อมูลพอร์ต...",
- "comingSoon": "มาเร็วๆ นี้..."
- },
- "modals": {
- "createNew": "สร้างพอร์ตใหม่",
- "portfolioName": "ชื่อพอร์ต",
- "owner": "เจ้าของ",
- "currency": "สกุลเงิน",
- "cancel": "ยกเลิก",
- "create": "สร้าง",
- "addAssetTitle": "เพิ่มสินทรัพย์ในพอร์ต",
- "sellAssetTitle": "ขายสินทรัพย์",
- "symbol": "สัญลักษณ์",
- "quantity": "จำนวน",
- "price": "ราคา",
- "add": "เพิ่ม",
- "sell": "ขาย"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | ติดตามเรียลไทม์พร้อมการรวม yfinance",
- "lastUpdated": "อัปเดตล่าสุด",
- "connected": "เชื่อมต่อแล้ว"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "สร้างพอร์ตใหม่",
+ "portfolioName": "ชื่อพอร์ต",
+ "owner": "เจ้าของ",
+ "currency": "สกุลเงิน",
+ "cancel": "ยกเลิก",
+ "create": "สร้าง",
+ "addAssetTitle": "เพิ่มสินทรัพย์ในพอร์ต",
+ "sellAssetTitle": "ขายสินทรัพย์",
+ "symbol": "สัญลักษณ์",
+ "quantity": "จำนวน",
+ "price": "ราคา",
+ "add": "เพิ่ม",
+ "sell": "ขาย"
+ },
+ "extracted": {
+ "areYouSureYou": "[TH] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/th/reportBuilder.json b/fincept-terminal-desktop/public/locales/th/reportBuilder.json
index b367c53f7..42e8c156b 100644
--- a/fincept-terminal-desktop/public/locales/th/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/th/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[TH] Load",
"save": "[TH] Save",
- "saving": "[TH] Saving...",
- "exportPdf": "[TH] Export PDF",
- "generating": "[TH] Generating..."
+ "saving": "[TH] Saving..."
},
"components": {
"title": "[TH] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/th/settings.json b/fincept-terminal-desktop/public/locales/th/settings.json
index 4d3abcc70..f02a6462c 100644
--- a/fincept-terminal-desktop/public/locales/th/settings.json
+++ b/fincept-terminal-desktop/public/locales/th/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "เค้าโครงแท็บ",
"appearance": "รูปร่าง",
"language": "ภาษา",
- "storage": "พื้นที่เก็บข้อมูลและแคช"
+ "storage": "พื้นที่เก็บข้อมูลและแคช",
+ "notifications": "[TH] Notifications"
},
"credentials": {
"title": "การจัดการข้อมูลรับรอง API",
@@ -46,7 +47,31 @@
"saveConfig": "บันทึกการกำหนดค่า",
"reset": "รีเซ็ต",
"saveSuccess": "บันทึกลักษณะเทอร์มินัลและการแมปคีย์เรียบร้อยแล้ว",
- "resetSuccess": "รีเซ็ตเป็นรูปลักษณ์เริ่มต้นและการแมปคีย์"
+ "resetSuccess": "รีเซ็ตเป็นรูปลักษณ์เริ่มต้นและการแมปคีย์",
+ "customColors": "[TH] Custom Colors",
+ "customColorsTitle": "[TH] CUSTOM COLORS",
+ "colorPrimary": "[TH] Primary",
+ "colorSecondary": "[TH] Secondary",
+ "colorSuccess": "[TH] Success",
+ "colorAlert": "[TH] Alert",
+ "colorWarning": "[TH] Warning",
+ "colorInfo": "[TH] Info",
+ "colorAccent": "[TH] Accent",
+ "colorPurple": "[TH] Purple",
+ "colorText": "[TH] Text",
+ "colorTextMuted": "[TH] Text Muted",
+ "colorBackground": "[TH] Background",
+ "colorPanel": "[TH] Panel",
+ "layoutSpacing": "[TH] LAYOUT & SPACING",
+ "contentDensity": "[TH] CONTENT DENSITY",
+ "borderRadius": "[TH] BORDER RADIUS",
+ "borderStyle": "[TH] BORDER STYLE",
+ "lineHeight": "[TH] LINE HEIGHT",
+ "letterSpacing": "[TH] LETTER SPACING",
+ "effects": "[TH] EFFECTS",
+ "widgetOpacity": "[TH] WIDGET OPACITY",
+ "enableGlow": "[TH] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[TH] GLOW INTENSITY"
},
"stockSymbols": {
"title": "ฐานข้อมูลสัญลักษณ์หุ้น",
@@ -65,17 +90,8 @@
"tip": "เคล็ดลับ: ลากแท็บเพื่อจัดเรียงใหม่ ใช้ปุ่มลูกศรเพื่อย้ายแท็บระหว่างส่วนหัวและส่วนเมนู การเปลี่ยนแปลงจะถูกบันทึกโดยอัตโนมัติ"
},
"llm": {
- "title": "การกำหนดค่า LLM",
- "description": "กำหนดค่าโมเดล AI และผู้ให้บริการ",
"connected": "เชื่อมต่อแล้ว",
- "disconnected": "ตัดการเชื่อมต่อแล้ว",
- "provider": "ผู้ให้บริการ AI",
- "globalSettings": "การตั้งค่า AI ทั่วโลก",
- "temperature": "อุณหภูมิ",
- "maxTokens": "โทเค็นสูงสุด",
- "systemPrompt": "พร้อมท์ระบบ",
- "modelLibrary": "ไลบรารีโมเดล",
- "multiModelConfigs": "การกำหนดค่าหลายรุ่น"
+ "disconnected": "ตัดการเชื่อมต่อแล้ว"
},
"buttons": {
"save": "บันทึก",
@@ -86,5 +102,18 @@
"database": "ฐานข้อมูล: SQLite",
"storage": "พื้นที่เก็บข้อมูล: ตามไฟล์",
"secureStorage": "ข้อมูลทั้งหมดเก็บไว้อย่างปลอดภัยใน fincept_terminal.db"
+ },
+ "notifications": {
+ "title": "[TH] NOTIFICATION PROVIDERS",
+ "description": "[TH] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[TH] Event Filters",
+ "eventFilterDescription": "[TH] Choose which notification types to forward to external providers.",
+ "providers": "[TH] Providers",
+ "enabled": "[TH] Enabled",
+ "disabled": "[TH] Disabled",
+ "testButton": "[TH] TEST",
+ "testSuccess": "[TH] Test notification sent successfully!",
+ "testFailed": "[TH] Failed to send test notification. Check your configuration.",
+ "saved": "[TH] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/th/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/th/surfaceAnalytics.json
new file mode 100644
index 000000000..d8899d769
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/th/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[TH] SURFACE ANALYTICS",
+ "initializing": "[TH] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[TH] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[TH] VOL SURFACE",
+ "correlation": "[TH] CORRELATION",
+ "yieldCurve": "[TH] YIELD CURVE",
+ "pca": "[TH] PCA FACTORS"
+ },
+ "demoData": "[TH] DEMO DATA",
+ "demoDataSynthetic": "[TH] DEMO DATA (synthetic)",
+ "synthetic": "[TH] SYNTHETIC",
+ "manual": "[TH] MANUAL",
+ "error": "[TH] ERROR",
+ "ready": "[TH] READY",
+ "metrics": "[TH] Metrics",
+ "updated": "[TH] Updated",
+ "clickRefresh": "[TH] Click REFRESH to load data",
+ "refresh": "[TH] REFRESH",
+ "noApiKey": "[TH] NO API KEY",
+ "lastUpdate": "[TH] LAST UPDATE",
+ "loadingData": "[TH] LOADING DATA...",
+ "noDataLoaded": "[TH] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[TH] IV SURFACE METRICS",
+ "correlationMetrics": "[TH] CORRELATION METRICS",
+ "yieldCurveMetrics": "[TH] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[TH] PCA FACTOR METRICS",
+ "dataInfo": "[TH] DATA INFO",
+ "source": "[TH] SOURCE",
+ "frequency": "[TH] FREQUENCY",
+ "quality": "[TH] QUALITY",
+ "correlationScale": "[TH] CORRELATION SCALE",
+ "strongPositive": "[TH] Strong Positive (0.7-1.0)",
+ "neutral": "[TH] Neutral (0.3-0.7)",
+ "strongNegative": "[TH] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[TH] IV INTERPRETATION",
+ "highIv": "[TH] High IV = Expensive Options",
+ "lowIv": "[TH] Low IV = Cheap Options",
+ "skew": "[TH] Skew = Put/Call IV Diff",
+ "termStructure": "[TH] Term Structure = Time Effect",
+ "pcaInterpretation": "[TH] PCA INTERPRETATION",
+ "pc1": "[TH] PC1 = Market Factor",
+ "pc2": "[TH] PC2 = Size/Value Factor",
+ "pc3": "[TH] PC3 = Sector Rotation",
+ "higherVar": "[TH] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[TH] STRIKE",
+ "dte": "[TH] DTE",
+ "iv": "[TH] IV",
+ "correlation": "[TH] CORRELATION",
+ "maturity": "[TH] MATURITY",
+ "yield": "[TH] YIELD",
+ "loading": "[TH] LOADING",
+ "strikePrice": "[TH] STRIKE PRICE",
+ "daysToExpiry": "[TH] DAYS TO EXPIRY",
+ "impliedVol": "[TH] IMPLIED VOL (%)",
+ "assetPairIndex": "[TH] ASSET PAIR INDEX",
+ "timeDays": "[TH] TIME (DAYS)",
+ "correlationCoeff": "[TH] CORRELATION COEFF",
+ "maturityMonths": "[TH] MATURITY (MONTHS)",
+ "historicalDays": "[TH] HISTORICAL DAYS",
+ "yieldPercent": "[TH] YIELD (%)",
+ "principalComponent": "[TH] PRINCIPAL COMPONENT",
+ "assetIndex": "[TH] ASSET INDEX",
+ "factorLoading": "[TH] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[TH] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[TH] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[TH] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[TH] DAY ROLLING",
+ "yieldCurve": "[TH] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[TH] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[TH] FAILED TO LOAD DATA",
+ "authFailed": "[TH] AUTHENTICATION FAILED",
+ "authFailedHelp": "[TH] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[TH] ACCESS DENIED",
+ "accessDeniedHelp": "[TH] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[TH] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[TH] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[TH] DATA TIMEFRAME",
+ "schema": "[TH] Schema",
+ "description": "[TH] Description",
+ "recordsPerDay": "[TH] Records/Day",
+ "highFrequencyWarning": "[TH] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[TH] Data Volume"
+ },
+ "settings": {
+ "title": "[TH] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[TH] DATABENTO API KEY",
+ "configured": "[TH] CONFIGURED",
+ "invalidFormat": "[TH] INVALID FORMAT",
+ "apiKeyConfigured": "[TH] API key is configured (db-*****)",
+ "remove": "[TH] REMOVE",
+ "enterApiKey": "[TH] Enter your Databento API key (db-*****)",
+ "save": "[TH] SAVE",
+ "saving": "[TH] SAVING...",
+ "getApiKeyFrom": "[TH] Get your API key from",
+ "dashboardApiKeys": "[TH] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[TH] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[TH] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[TH] CORRELATION ASSETS",
+ "addSymbol": "[TH] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[TH] Reset to defaults",
+ "historicalDateRange": "[TH] HISTORICAL DATE RANGE",
+ "start": "[TH] Start",
+ "end": "[TH] End",
+ "autoRefreshInterval": "[TH] AUTO REFRESH INTERVAL",
+ "manualOnly": "[TH] Manual Only",
+ "every1min": "[TH] Every 1 minute",
+ "every5min": "[TH] Every 5 minutes",
+ "every15min": "[TH] Every 15 minutes",
+ "every1hour": "[TH] Every 1 hour",
+ "browseDatasets": "[TH] BROWSE DATASETS",
+ "costEstimator": "[TH] COST ESTIMATOR",
+ "referenceData": "[TH] REFERENCE DATA",
+ "orderBook": "[TH] ORDER BOOK",
+ "liveStreaming": "[TH] LIVE STREAMING",
+ "active": "[TH] ACTIVE",
+ "futuresCme": "[TH] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[TH] BATCH DOWNLOADS",
+ "additionalSchemas": "[TH] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[TH] TRADES, IMBALANCE, STATUS",
+ "cancel": "[TH] CANCEL",
+ "saveChanges": "[TH] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[TH] BATCH DOWNLOADS",
+ "newBatchJob": "[TH] NEW BATCH JOB",
+ "dataset": "[TH] Dataset",
+ "schema": "[TH] Schema",
+ "symbolsCommaSeparated": "[TH] Symbols (comma-separated)",
+ "startDate": "[TH] Start Date",
+ "endDate": "[TH] End Date",
+ "encoding": "[TH] Encoding",
+ "compression": "[TH] Compression",
+ "submitJob": "[TH] SUBMIT JOB",
+ "noBatchJobs": "[TH] No batch jobs found. Click + to create one.",
+ "records": "[TH] records",
+ "download": "[TH] Download",
+ "files": "[TH] FILES",
+ "jobsExpireNotice": "[TH] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[TH] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[TH] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[TH] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[TH] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[TH] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[TH] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[TH] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[TH] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[TH] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[TH] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[TH] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[TH] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[TH] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[TH] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[TH] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[TH] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[TH] [EN] common.or",
+ "note": "[TH] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/th/tabs.json b/fincept-terminal-desktop/public/locales/th/tabs.json
index c53e8f1c0..f0e97fefb 100644
--- a/fincept-terminal-desktop/public/locales/th/tabs.json
+++ b/fincept-terminal-desktop/public/locales/th/tabs.json
@@ -5,29 +5,7 @@
"news": "ข่าว",
"portfolio": "พอร์ตโฟลิโอ",
"backtesting": "แบ็คเทสต์",
- "watchlist": "รายการติดตาม",
- "research": "วิจัย",
- "screener": "คัดกรอง",
"chat": "AI Chat",
- "agents": "เอเจนต์",
- "settings": "ตั้งค่า",
"profile": "โปรไฟล์"
- },
- "functionKeys": {
- "f1": "แดช",
- "f2": "ตลาด",
- "f3": "ข่าว",
- "f4": "พอร์ต",
- "f5": "ทดสอบ",
- "f6": "ติดตาม",
- "f7": "วิจัย",
- "f8": "คัด",
- "f9": "ขาย",
- "f10": "AI",
- "f11": "เต็ม",
- "f12": "โปร"
- },
- "labels": {
- "moreTabs": "แท็บเพิ่มเติมในเมนูแถบเครื่องมือ"
}
}
diff --git a/fincept-terminal-desktop/public/locales/th/watchlist.json b/fincept-terminal-desktop/public/locales/th/watchlist.json
index 8e6a598e1..c765fb600 100644
--- a/fincept-terminal-desktop/public/locales/th/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/th/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "รายการติดตาม",
- "header": {
- "export": "ส่งออก",
- "updating": "กำลังอัปเดต",
- "live": "สด"
- },
"sidebar": {
- "groups": "กลุ่มรายการติดตาม",
- "new": "ใหม่",
"noWatchlists": "ยังไม่มีรายการติดตาม",
"clickNew": "คลิก ใหม่ เพื่อสร้าง",
- "stocks": "หุ้น",
- "marketMovers": "ตัวขับเคลื่อนตลาด",
- "gainer": "ขึ้น",
- "loser": "ลง",
- "volumeLeaders": "ปริมาณสูงสุด"
- },
- "emptyState": {
- "selectWatchlist": "เลือกรายการติดตามหรือสร้างใหม่เพื่อเริ่มต้น"
- },
- "list": {
- "symbols": "สัญลักษณ์"
+ "stocks": "หุ้น"
}
}
diff --git a/fincept-terminal-desktop/public/locales/tr/codeEditor.json b/fincept-terminal-desktop/public/locales/tr/codeEditor.json
index 58e9e9e71..1291490c1 100644
--- a/fincept-terminal-desktop/public/locales/tr/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/tr/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "KOD EDİTÖRÜ",
"header": {
- "packages": "PAKETLER"
+ "finscriptIde": "[TR] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "YENİ DOSYA",
- "new": "YENİ",
- "open": "AÇ",
- "save": "KAYDET",
"run": "ÇALIŞTIR",
"running": "ÇALIŞIYOR...",
- "runAll": "TÜMÜNÜ ÇALIŞTIR",
- "history": "GEÇMİŞ"
+ "toggleExplorer": "[TR] Toggle Explorer (Ctrl+B)",
+ "openFile": "[TR] Open File",
+ "saveShortcut": "[TR] Save (Ctrl+S)",
+ "findShortcut": "[TR] Find (Ctrl+F)",
+ "runShortcut": "[TR] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "FINSCRIPT EDİTÖRÜ"
},
- "packages": {
- "clickToLoad": "Yüklemek için tıkla...",
- "load": "PAKETLERİ YÜKLE"
+ "explorer": {
+ "title": "[TR] EXPLORER",
+ "openFiles": "[TR] OPEN FILES",
+ "examples": "[TR] EXAMPLES",
+ "runHistory": "[TR] RUN HISTORY",
+ "finscriptEngine": "[TR] FinScript Engine"
},
- "history": {
- "title": "NOTEBOOK GEÇMİŞİ",
- "loading": "Geçmiş yükleniyor...",
- "empty": "Notebook geçmişi yok"
+ "output": {
+ "title": "[TR] OUTPUT",
+ "success": "[TR] SUCCESS",
+ "error": "[TR] ERROR",
+ "executing": "[TR] EXECUTING FINSCRIPT...",
+ "noOutput": "[TR] No output yet",
+ "pressToRun": "[TR] Press Ctrl+Enter to run",
+ "completed": "[TR] COMPLETED",
+ "failed": "[TR] FAILED",
+ "signals": "[TR] signals",
+ "clear": "[TR] CLEAR",
+ "errors": "[TR] ERRORS",
+ "signalsSection": "[TR] SIGNALS",
+ "outputSection": "[TR] OUTPUT",
+ "charts": "[TR] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[TR] OHLC",
+ "histogram": "[TR] Histogram",
+ "line": "[TR] Line",
+ "points": "[TR] points"
+ },
+ "statusBar": {
+ "modified": "[TR] MODIFIED",
+ "showOutput": "[TR] SHOW OUTPUT",
+ "encoding": "[TR] UTF-8",
+ "spaces": "[TR] 4 Spaces",
+ "runShortcut": "[TR] Ctrl+Enter: Run",
+ "lines": "[TR] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[TR] Close file without saving?",
+ "unsavedChanges": "[TR] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/tr/common.json b/fincept-terminal-desktop/public/locales/tr/common.json
index 9bb6cc432..9cf4c7d61 100644
--- a/fincept-terminal-desktop/public/locales/tr/common.json
+++ b/fincept-terminal-desktop/public/locales/tr/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Yükleniyor...",
- "error": "Hata",
- "success": "Başarılı",
- "save": "Kaydet",
- "cancel": "İptal",
- "delete": "Sil",
- "edit": "Düzenle",
- "add": "Ekle",
- "search": "Ara",
- "filter": "Filtrele",
- "back": "Geri",
- "next": "İleri",
- "previous": "Önceki",
- "submit": "Gönder",
- "close": "Kapat",
- "open": "Aç",
- "yes": "Evet",
- "no": "Hayır",
- "ok": "Tamam",
- "confirm": "Onayla",
- "language": "Dil",
- "selectLanguage": "Dil seçin"
-}
\ No newline at end of file
+ "settings": "[TR] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/tr/dashboard.json b/fincept-terminal-desktop/public/locales/tr/dashboard.json
index 96a01ca69..02053c7c4 100644
--- a/fincept-terminal-desktop/public/locales/tr/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/tr/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "ÖZELLEŞTİRİLEBİLİR GÖSTERGE PANELİ",
- "live": "CANLI",
- "widgets": "WIDGET'LAR"
- },
- "buttons": {
- "addWidget": "WIDGET EKLE",
- "saveLayout": "DÜZENİ KAYDET",
- "reset": "SIFIRLAMA",
- "help": "YARDIM"
- },
"widgets": {
"loading": "Yükleniyor...",
- "error": "Hata",
"globalIndices": "Küresel Endeksler - İlk 12",
"forex": "Forex - Ana Çiftler",
"crypto": "KRİPTO PARALAR",
@@ -20,8 +8,6 @@
"news": "HABERLER",
"forum": "FORUM",
"watchlist": "İZLEME LİSTESİ",
- "maritimeIntelligence": "Denizcilik İstihbaratı",
- "unknown": "Bilinmeyen widget türü",
"index": "DİZİN",
"symbol": "SEMBOL",
"price": "FİYAT",
@@ -38,41 +24,22 @@
"pair": "ÇİFT",
"rate": "ORAN",
"commodity": "EMTİA",
- "globe3D": "3D KÜRE",
- "vessels": "GEMİLER",
- "routes": "ROTALAR",
- "vol24h": "CİLT 24 SAAT",
- "topTradeCorridors": "EN ÜST TİCARET KORİDORLARI",
- "ships": "gemiler",
- "marketNews": "Piyasa Haberleri",
- "secPressReleases": "SEC Basın Bültenleri",
- "cryptoNews": "Kripto Haberleri",
- "trendingForum": "Trend Olan Forum",
- "techStocks": "Teknoloji Hisse Senetleri"
- },
- "tips": {
- "drag": "Yeniden düzenlemek için widget'ları sürükleyin",
- "resize": "Sağ alt köşeden yeniden boyutlandır",
- "remove": "X düğmesiyle widget'ları kaldırın",
- "responsive": "Duyarlı düzen - tam genişliği kullanır"
- },
- "loading": {
- "title": "Kontrol Paneli Başlatılıyor",
- "description": "Daha hızlı veri yükleme için veritabanı önbelleği ayarlanıyor...",
- "note": "Bu, ilk başlatmada yalnızca bir dakika sürecektir"
- },
- "empty": {
- "noWidgets": "Kontrol panelinde widget yok",
- "addFirst": "İLK WIDGETINIZI EKLEYİN"
- },
- "status": {
- "version": "Fincept Özelleştirilebilir Kontrol Paneli v2.0.0 | Sürükle ve bırak çalışma alanı",
- "layout": "Düzen",
- "custom": "Gelenek",
- "empty": "Boş",
- "active": "AKTİF",
- "cache": "Önbellek: ETKİN",
- "label": "Durum"
+ "noActiveMarkets": "[TR] No active markets found",
+ "indicator": "[TR] INDICATOR",
+ "value": "[TR] VALUE",
+ "chg": "[TR] CHG",
+ "overallRisk": "[TR] OVERALL RISK",
+ "openEconomicsTab": "[TR] Open Economics Tab",
+ "openGeopoliticsTab": "[TR] Open Geopolitics Tab",
+ "openPolymarketTab": "[TR] Open Polymarket Tab",
+ "noPortfolioFound": "[TR] No portfolio found",
+ "createPortfolioHint": "[TR] Create one in Portfolio tab",
+ "openPortfolioTab": "[TR] Open Portfolio Tab",
+ "action": "[TR] ACTION",
+ "markets": "[TR] MARKETS",
+ "performanceTracker": "[TR] PERFORMANCE TRACKER",
+ "totalPnL": "[TR] TOTAL P&L",
+ "viewDetailedAnalytics": "[TR] View Detailed Analytics"
},
"messages": {
"layoutSaved": "Kontrol paneli düzeni kaydedildi!",
diff --git a/fincept-terminal-desktop/public/locales/tr/geopolitics.json b/fincept-terminal-desktop/public/locales/tr/geopolitics.json
index 1f9a50764..755a8a0df 100644
--- a/fincept-terminal-desktop/public/locales/tr/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/tr/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "JEOPOLİTİK",
"messages": {
- "loading": "Veri yükleniyor..."
+ "retry": "[TR] RETRY"
+ },
+ "header": {
+ "prefix": "[TR] GEO>",
+ "title": "[TR] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[TR] EVENTS"
+ },
+ "status": {
+ "stale": "[TR] STALE",
+ "loading": "[TR] LOADING...",
+ "error": "[TR] ERROR:"
+ },
+ "filters": {
+ "country": "[TR] Country...",
+ "cities": "[TR] Cities...",
+ "category": "[TR] Category...",
+ "apply": "[TR] APPLY",
+ "clear": "[TR] CLEAR",
+ "clearAllCities": "[TR] Clear all cities",
+ "selectedLabel": "[TR] Selected:"
+ },
+ "panel": {
+ "title": "[TR] INFO PANEL",
+ "expand": "[TR] Expand panel",
+ "collapse": "[TR] Collapse panel",
+ "eventsLoaded": "[TR] EVENTS LOADED",
+ "onMapVisualization": "[TR] on map visualization",
+ "topCategories": "[TR] TOP CATEGORIES",
+ "topCountries": "[TR] TOP COUNTRIES",
+ "eventDetails": "[TR] EVENT DETAILS",
+ "close": "[TR] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[TR] Country:",
+ "city": "[TR] City:",
+ "keywords": "[TR] Keywords:",
+ "coords": "[TR] Coords:",
+ "date": "[TR] Date:",
+ "source": "[TR] Source:",
+ "viewArticle": "[TR] View Article"
+ },
+ "legend": {
+ "title": "[TR] EVENT CATEGORIES",
+ "armedConflict": "[TR] Armed Conflict",
+ "terrorism": "[TR] Terrorism",
+ "protests": "[TR] Protests",
+ "civilianViolence": "[TR] Civilian Violence",
+ "riots": "[TR] Riots",
+ "politicalViolence": "[TR] Political Violence",
+ "crisis": "[TR] Crisis",
+ "explosions": "[TR] Explosions",
+ "strategic": "[TR] Strategic",
+ "unclassified": "[TR] Unclassified"
+ },
+ "footer": {
+ "tabName": "[TR] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[TR] EVENTS",
+ "labelEngine": "[TR] ENGINE",
+ "engineValue": "[TR] DECK.GL v9.2",
+ "labelSource": "[TR] SOURCE",
+ "sourceValue": "[TR] NEWS-EVENTS API",
+ "labelSelected": "[TR] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/tr/markets.json b/fincept-terminal-desktop/public/locales/tr/markets.json
index fb8ab8f46..41fd39ed1 100644
--- a/fincept-terminal-desktop/public/locales/tr/markets.json
+++ b/fincept-terminal-desktop/public/locales/tr/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%DEĞ",
"high": "YÜKSEK",
"low": "DÜŞÜK",
- "loading": "Yükleniyor...",
"noData": "Veri yok",
"refresh": "YENİLE",
"auto": "OTOMATİK",
"on": "AÇIK",
- "off": "KAPALI",
- "lastUpdate": "SON GÜNCELLEME",
- "updating": "GÜNCELLENİYOR",
- "live": "CANLI"
+ "off": "KAPALI"
}
diff --git a/fincept-terminal-desktop/public/locales/tr/news.json b/fincept-terminal-desktop/public/locales/tr/news.json
index d193dd3bf..314efe54f 100644
--- a/fincept-terminal-desktop/public/locales/tr/news.json
+++ b/fincept-terminal-desktop/public/locales/tr/news.json
@@ -1,32 +1,63 @@
{
"title": "FINCEPT TERMİNAL PROFESYONEL HABERLER",
"header": {
- "liveFeed": "CANLI YAYIN",
- "live": "CANLI",
- "refresh": "YENİLE",
- "updating": "GÜNCELLENİYOR...",
- "alerts": "UYARILAR",
- "sources": "KAYNAKLAR",
- "status": "DURUM",
- "demoMode": "DEMO MODU",
- "articles": "MAKALELER",
- "activeSources": "AKTİF KAYNAKLAR"
- },
- "autoRefresh": {
- "title": "OTOMATİK YENİLEME ARALIĞI",
- "minute": "dakika",
- "minutes": "dakika"
+ "refresh": "YENİLE"
},
"messages": {
- "loadingFeeds": "Haber akışları yükleniyor...",
- "breaking": "SON DAKİKA"
- },
- "feeds": {
- "primary": "[TR] PRIMARY NEWS FEED",
- "secondary": "[TR] SECONDARY NEWS FEED",
- "additional": "[TR] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[TR] Loading feeds...",
+ "failedToLoad": "[TR] Failed to load RSS feeds",
+ "noCustomFeeds": "[TR] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[TR] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[TR] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[TR] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[TR] RSS FEED SETTINGS",
+ "subtitle": "[TR] MANAGE YOUR NEWS SOURCES",
+ "close": "[TR] CLOSE",
+ "myFeeds": "[TR] MY FEEDS",
+ "defaultFeeds": "[TR] DEFAULT FEEDS",
+ "noFeedsAvailable": "[TR] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[TR] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[TR] ADD NEW FEED",
+ "addNewRssFeed": "[TR] ADD NEW RSS FEED",
+ "editRssFeed": "[TR] EDIT RSS FEED",
+ "restoreDefaults": "[TR] RESTORE DEFAULTS",
+ "restoreAll": "[TR] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[TR] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[TR] DISPLAY NAME",
+ "sourceName": "[TR] SOURCE NAME (SHORT)",
+ "feedUrl": "[TR] RSS FEED URL",
+ "category": "[TR] CATEGORY",
+ "region": "[TR] REGION",
+ "required": "[TR] *",
+ "testUrl": "[TR] TEST URL",
+ "testing": "[TR] TESTING...",
+ "valid": "[TR] VALID",
+ "cancel": "[TR] CANCEL",
+ "saving": "[TR] SAVING...",
+ "addFeed": "[TR] ADD FEED",
+ "updateFeed": "[TR] UPDATE FEED",
+ "on": "[TR] ON",
+ "off": "[TR] OFF",
+ "default": "[TR] DEFAULT",
+ "total": "[TR] TOTAL",
+ "active": "[TR] ACTIVE",
+ "custom": "[TR] CUSTOM",
+ "placeholders": {
+ "displayName": "[TR] e.g., Bloomberg Markets",
+ "sourceName": "[TR] e.g., BLOOMBERG",
+ "feedUrl": "[TR] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[TR] Name is required",
+ "sourceRequired": "[TR] Source name is required",
+ "invalidUrl": "[TR] Please enter a valid URL",
+ "invalidRss": "[TR] URL does not appear to be a valid RSS feed",
+ "testFailed": "[TR] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[TR] Delete this RSS feed?",
+ "message": "[TR] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/tr/portfolio.json b/fincept-terminal-desktop/public/locales/tr/portfolio.json
index d35d9bbde..eba60fc0a 100644
--- a/fincept-terminal-desktop/public/locales/tr/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/tr/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "FINCEPT PORTFÖY YÖNETİCİSİ",
- "header": {
- "live": "CANLI",
- "updating": "GÜNCELLENİYOR",
- "newPortfolio": "YENİ PORTFÖY",
- "refresh": "YENİLE",
- "exportCsv": "CSV DIŞA AKTAR"
- },
- "summary": {
- "totalValue": "TOPLAM DEĞER",
- "dayPnl": "GÜNLÜK K/Z",
- "totalPnl": "TOPLAM K/Z",
- "positions": "POZİSYONLAR"
- },
- "views": {
- "positions": "POZİSYONLAR",
- "addAsset": "VARLİK EKLE",
- "sellAsset": "VARLIK SAT",
- "analytics": "ANALİTİK",
- "history": "GEÇMİŞ",
- "activeMgmt": "AKTİF YÖNETİM",
- "performance": "PERFORMANS",
- "rebalance": "YENİDEN DENGELEME",
- "reports": "RAPORLAR",
- "alerts": "UYARILAR",
- "sectors": "SEKTÖRLER",
- "help": "YARDIM"
- },
- "sidebar": {
- "portfolios": "PORTFÖYLER",
- "loading": "Portföyler yükleniyor...",
- "noPortfolios": "Henüz portföy yok.",
- "clickCreate": "Oluşturmak için YENİ PORTFÖY'e tıklayın.",
- "owner": "Sahip",
- "currency": "Para Birimi"
- },
- "content": {
- "selectOrCreate": "Başlamak için bir portföy seçin veya yeni oluşturun",
- "loadingData": "Portföy verileri yükleniyor...",
- "comingSoon": "görünüm yakında..."
- },
- "modals": {
- "createNew": "YENİ PORTFÖY OLUŞTUR",
- "portfolioName": "PORTFÖY ADI",
- "owner": "SAHİP",
- "currency": "PARA BİRİMİ",
- "cancel": "İPTAL",
- "create": "OLUŞTUR",
- "addAssetTitle": "PORTFÖYE VARLIK EKLE",
- "sellAssetTitle": "VARLIK SAT",
- "symbol": "SEMBOL",
- "quantity": "MİKTAR",
- "price": "FİYAT",
- "add": "EKLE",
- "sell": "SAT"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | yfinance entegrasyonu ile gerçek zamanlı takip",
- "lastUpdated": "Son Güncelleme",
- "connected": "BAĞLI"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "YENİ PORTFÖY OLUŞTUR",
+ "portfolioName": "PORTFÖY ADI",
+ "owner": "SAHİP",
+ "currency": "PARA BİRİMİ",
+ "cancel": "İPTAL",
+ "create": "OLUŞTUR",
+ "addAssetTitle": "PORTFÖYE VARLIK EKLE",
+ "sellAssetTitle": "VARLIK SAT",
+ "symbol": "SEMBOL",
+ "quantity": "MİKTAR",
+ "price": "FİYAT",
+ "add": "EKLE",
+ "sell": "SAT"
+ },
+ "extracted": {
+ "areYouSureYou": "[TR] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/tr/reportBuilder.json b/fincept-terminal-desktop/public/locales/tr/reportBuilder.json
index f547a054d..9e1a4f41f 100644
--- a/fincept-terminal-desktop/public/locales/tr/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/tr/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[TR] Load",
"save": "[TR] Save",
- "saving": "[TR] Saving...",
- "exportPdf": "[TR] Export PDF",
- "generating": "[TR] Generating..."
+ "saving": "[TR] Saving..."
},
"components": {
"title": "[TR] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/tr/settings.json b/fincept-terminal-desktop/public/locales/tr/settings.json
index 1fef21817..8a9bb4ca7 100644
--- a/fincept-terminal-desktop/public/locales/tr/settings.json
+++ b/fincept-terminal-desktop/public/locales/tr/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Sekme Düzeni",
"appearance": "Dış görünüş",
"language": "Dil",
- "storage": "Depolama ve Önbellek"
+ "storage": "Depolama ve Önbellek",
+ "notifications": "[TR] Notifications"
},
"credentials": {
"title": "API KİMLİK BİLGİLERİ YÖNETİMİ",
@@ -46,7 +47,31 @@
"saveConfig": "YAPILANDIRMAYI KAYDET",
"reset": "SIFIRLAMA",
"saveSuccess": "Terminal görünümü ve tuş eşlemeleri başarıyla kaydedildi",
- "resetSuccess": "Varsayılan görünüme ve tuş eşlemelerine sıfırla"
+ "resetSuccess": "Varsayılan görünüme ve tuş eşlemelerine sıfırla",
+ "customColors": "[TR] Custom Colors",
+ "customColorsTitle": "[TR] CUSTOM COLORS",
+ "colorPrimary": "[TR] Primary",
+ "colorSecondary": "[TR] Secondary",
+ "colorSuccess": "[TR] Success",
+ "colorAlert": "[TR] Alert",
+ "colorWarning": "[TR] Warning",
+ "colorInfo": "[TR] Info",
+ "colorAccent": "[TR] Accent",
+ "colorPurple": "[TR] Purple",
+ "colorText": "[TR] Text",
+ "colorTextMuted": "[TR] Text Muted",
+ "colorBackground": "[TR] Background",
+ "colorPanel": "[TR] Panel",
+ "layoutSpacing": "[TR] LAYOUT & SPACING",
+ "contentDensity": "[TR] CONTENT DENSITY",
+ "borderRadius": "[TR] BORDER RADIUS",
+ "borderStyle": "[TR] BORDER STYLE",
+ "lineHeight": "[TR] LINE HEIGHT",
+ "letterSpacing": "[TR] LETTER SPACING",
+ "effects": "[TR] EFFECTS",
+ "widgetOpacity": "[TR] WIDGET OPACITY",
+ "enableGlow": "[TR] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[TR] GLOW INTENSITY"
},
"stockSymbols": {
"title": "Hisse Senedi Sembol Veritabanı",
@@ -65,17 +90,8 @@
"tip": "İPUCU: Yeniden sıralamak için sekmeleri sürükleyin. Sekmeleri başlık ve menü bölümleri arasında taşımak için ok düğmelerini kullanın. Değişiklikler otomatik olarak kaydedilir."
},
"llm": {
- "title": "LLM YAPILANDIRMASI",
- "description": "Yapay zeka modellerini ve sağlayıcılarını yapılandırma",
"connected": "BAĞLI",
- "disconnected": "BAĞLANTI KESİLDİ",
- "provider": "Yapay Zeka Sağlayıcı",
- "globalSettings": "KÜRESEL YZ AYARLARI",
- "temperature": "SICAKLIK",
- "maxTokens": "MAKS TOKEN",
- "systemPrompt": "SİSTEM İSTEMİ",
- "modelLibrary": "MODEL KÜTÜPHANE",
- "multiModelConfigs": "Çok modelli yapılandırmalar"
+ "disconnected": "BAĞLANTI KESİLDİ"
},
"buttons": {
"save": "KAYDETMEK",
@@ -86,5 +102,18 @@
"database": "Veritabanı: SQLite",
"storage": "Depolama: Dosya tabanlı",
"secureStorage": "Tüm veriler fincept_terminal.db'de güvenli bir şekilde saklanır"
+ },
+ "notifications": {
+ "title": "[TR] NOTIFICATION PROVIDERS",
+ "description": "[TR] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[TR] Event Filters",
+ "eventFilterDescription": "[TR] Choose which notification types to forward to external providers.",
+ "providers": "[TR] Providers",
+ "enabled": "[TR] Enabled",
+ "disabled": "[TR] Disabled",
+ "testButton": "[TR] TEST",
+ "testSuccess": "[TR] Test notification sent successfully!",
+ "testFailed": "[TR] Failed to send test notification. Check your configuration.",
+ "saved": "[TR] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/tr/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/tr/surfaceAnalytics.json
new file mode 100644
index 000000000..424ef4416
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/tr/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[TR] SURFACE ANALYTICS",
+ "initializing": "[TR] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[TR] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[TR] VOL SURFACE",
+ "correlation": "[TR] CORRELATION",
+ "yieldCurve": "[TR] YIELD CURVE",
+ "pca": "[TR] PCA FACTORS"
+ },
+ "demoData": "[TR] DEMO DATA",
+ "demoDataSynthetic": "[TR] DEMO DATA (synthetic)",
+ "synthetic": "[TR] SYNTHETIC",
+ "manual": "[TR] MANUAL",
+ "error": "[TR] ERROR",
+ "ready": "[TR] READY",
+ "metrics": "[TR] Metrics",
+ "updated": "[TR] Updated",
+ "clickRefresh": "[TR] Click REFRESH to load data",
+ "refresh": "[TR] REFRESH",
+ "noApiKey": "[TR] NO API KEY",
+ "lastUpdate": "[TR] LAST UPDATE",
+ "loadingData": "[TR] LOADING DATA...",
+ "noDataLoaded": "[TR] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[TR] IV SURFACE METRICS",
+ "correlationMetrics": "[TR] CORRELATION METRICS",
+ "yieldCurveMetrics": "[TR] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[TR] PCA FACTOR METRICS",
+ "dataInfo": "[TR] DATA INFO",
+ "source": "[TR] SOURCE",
+ "frequency": "[TR] FREQUENCY",
+ "quality": "[TR] QUALITY",
+ "correlationScale": "[TR] CORRELATION SCALE",
+ "strongPositive": "[TR] Strong Positive (0.7-1.0)",
+ "neutral": "[TR] Neutral (0.3-0.7)",
+ "strongNegative": "[TR] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[TR] IV INTERPRETATION",
+ "highIv": "[TR] High IV = Expensive Options",
+ "lowIv": "[TR] Low IV = Cheap Options",
+ "skew": "[TR] Skew = Put/Call IV Diff",
+ "termStructure": "[TR] Term Structure = Time Effect",
+ "pcaInterpretation": "[TR] PCA INTERPRETATION",
+ "pc1": "[TR] PC1 = Market Factor",
+ "pc2": "[TR] PC2 = Size/Value Factor",
+ "pc3": "[TR] PC3 = Sector Rotation",
+ "higherVar": "[TR] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[TR] STRIKE",
+ "dte": "[TR] DTE",
+ "iv": "[TR] IV",
+ "correlation": "[TR] CORRELATION",
+ "maturity": "[TR] MATURITY",
+ "yield": "[TR] YIELD",
+ "loading": "[TR] LOADING",
+ "strikePrice": "[TR] STRIKE PRICE",
+ "daysToExpiry": "[TR] DAYS TO EXPIRY",
+ "impliedVol": "[TR] IMPLIED VOL (%)",
+ "assetPairIndex": "[TR] ASSET PAIR INDEX",
+ "timeDays": "[TR] TIME (DAYS)",
+ "correlationCoeff": "[TR] CORRELATION COEFF",
+ "maturityMonths": "[TR] MATURITY (MONTHS)",
+ "historicalDays": "[TR] HISTORICAL DAYS",
+ "yieldPercent": "[TR] YIELD (%)",
+ "principalComponent": "[TR] PRINCIPAL COMPONENT",
+ "assetIndex": "[TR] ASSET INDEX",
+ "factorLoading": "[TR] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[TR] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[TR] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[TR] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[TR] DAY ROLLING",
+ "yieldCurve": "[TR] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[TR] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[TR] FAILED TO LOAD DATA",
+ "authFailed": "[TR] AUTHENTICATION FAILED",
+ "authFailedHelp": "[TR] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[TR] ACCESS DENIED",
+ "accessDeniedHelp": "[TR] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[TR] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[TR] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[TR] DATA TIMEFRAME",
+ "schema": "[TR] Schema",
+ "description": "[TR] Description",
+ "recordsPerDay": "[TR] Records/Day",
+ "highFrequencyWarning": "[TR] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[TR] Data Volume"
+ },
+ "settings": {
+ "title": "[TR] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[TR] DATABENTO API KEY",
+ "configured": "[TR] CONFIGURED",
+ "invalidFormat": "[TR] INVALID FORMAT",
+ "apiKeyConfigured": "[TR] API key is configured (db-*****)",
+ "remove": "[TR] REMOVE",
+ "enterApiKey": "[TR] Enter your Databento API key (db-*****)",
+ "save": "[TR] SAVE",
+ "saving": "[TR] SAVING...",
+ "getApiKeyFrom": "[TR] Get your API key from",
+ "dashboardApiKeys": "[TR] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[TR] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[TR] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[TR] CORRELATION ASSETS",
+ "addSymbol": "[TR] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[TR] Reset to defaults",
+ "historicalDateRange": "[TR] HISTORICAL DATE RANGE",
+ "start": "[TR] Start",
+ "end": "[TR] End",
+ "autoRefreshInterval": "[TR] AUTO REFRESH INTERVAL",
+ "manualOnly": "[TR] Manual Only",
+ "every1min": "[TR] Every 1 minute",
+ "every5min": "[TR] Every 5 minutes",
+ "every15min": "[TR] Every 15 minutes",
+ "every1hour": "[TR] Every 1 hour",
+ "browseDatasets": "[TR] BROWSE DATASETS",
+ "costEstimator": "[TR] COST ESTIMATOR",
+ "referenceData": "[TR] REFERENCE DATA",
+ "orderBook": "[TR] ORDER BOOK",
+ "liveStreaming": "[TR] LIVE STREAMING",
+ "active": "[TR] ACTIVE",
+ "futuresCme": "[TR] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[TR] BATCH DOWNLOADS",
+ "additionalSchemas": "[TR] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[TR] TRADES, IMBALANCE, STATUS",
+ "cancel": "[TR] CANCEL",
+ "saveChanges": "[TR] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[TR] BATCH DOWNLOADS",
+ "newBatchJob": "[TR] NEW BATCH JOB",
+ "dataset": "[TR] Dataset",
+ "schema": "[TR] Schema",
+ "symbolsCommaSeparated": "[TR] Symbols (comma-separated)",
+ "startDate": "[TR] Start Date",
+ "endDate": "[TR] End Date",
+ "encoding": "[TR] Encoding",
+ "compression": "[TR] Compression",
+ "submitJob": "[TR] SUBMIT JOB",
+ "noBatchJobs": "[TR] No batch jobs found. Click + to create one.",
+ "records": "[TR] records",
+ "download": "[TR] Download",
+ "files": "[TR] FILES",
+ "jobsExpireNotice": "[TR] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[TR] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[TR] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[TR] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[TR] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[TR] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[TR] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[TR] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[TR] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[TR] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[TR] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[TR] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[TR] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[TR] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[TR] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[TR] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[TR] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[TR] [EN] common.or",
+ "note": "[TR] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/tr/tabs.json b/fincept-terminal-desktop/public/locales/tr/tabs.json
index e5991e35b..c66214e84 100644
--- a/fincept-terminal-desktop/public/locales/tr/tabs.json
+++ b/fincept-terminal-desktop/public/locales/tr/tabs.json
@@ -5,29 +5,7 @@
"news": "Haberler",
"portfolio": "Portföy",
"backtesting": "Backtesting",
- "watchlist": "İzleme Listesi",
- "research": "Araştırma",
- "screener": "Tarayıcı",
"chat": "AI Chat",
- "agents": "Ajanlar",
- "settings": "Ayarlar",
"profile": "Profil"
- },
- "functionKeys": {
- "f1": "PANL",
- "f2": "PYSA",
- "f3": "HABR",
- "f4": "PORT",
- "f5": "BKTS",
- "f6": "İZLE",
- "f7": "ARST",
- "f8": "TARA",
- "f9": "TRDG",
- "f10": "AI",
- "f11": "FULL",
- "f12": "PROF"
- },
- "labels": {
- "moreTabs": "Araç çubuğu menülerinde daha fazla sekme"
}
}
diff --git a/fincept-terminal-desktop/public/locales/tr/watchlist.json b/fincept-terminal-desktop/public/locales/tr/watchlist.json
index 01744cc1f..d8086da2c 100644
--- a/fincept-terminal-desktop/public/locales/tr/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/tr/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "İZLEME LİSTESİ",
- "header": {
- "export": "DIŞA AKTAR",
- "updating": "GÜNCELLEME",
- "live": "CANLI"
- },
"sidebar": {
- "groups": "LİSTE GRUPLARI",
- "new": "YENİ",
"noWatchlists": "Henüz liste yok.",
"clickNew": "Oluşturmak için YENİ'ye tıklayın.",
- "stocks": "hisse",
- "marketMovers": "PİYASA LİDERLERİ",
- "gainer": "YÜKSELENLER",
- "loser": "DÜŞENLER",
- "volumeLeaders": "HACİM LİDERLERİ"
- },
- "emptyState": {
- "selectWatchlist": "Başlamak için bir liste seçin veya yeni oluşturun"
- },
- "list": {
- "symbols": "Semboller"
+ "stocks": "hisse"
}
}
diff --git a/fincept-terminal-desktop/public/locales/uk/codeEditor.json b/fincept-terminal-desktop/public/locales/uk/codeEditor.json
index 320222832..831acbcf9 100644
--- a/fincept-terminal-desktop/public/locales/uk/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/uk/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "РЕДАКТОР КОДУ",
"header": {
- "packages": "ПАКЕТИ"
+ "finscriptIde": "[UK] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "НОВИЙ ФАЙЛ",
- "new": "НОВИЙ",
- "open": "ВІДКРИТИ",
- "save": "ЗБЕРЕГТИ",
"run": "ВИКОНАТИ",
"running": "ВИКОНУЄТЬСЯ...",
- "runAll": "ВИКОНАТИ ВСЕ",
- "history": "ІСТОРІЯ"
+ "toggleExplorer": "[UK] Toggle Explorer (Ctrl+B)",
+ "openFile": "[UK] Open File",
+ "saveShortcut": "[UK] Save (Ctrl+S)",
+ "findShortcut": "[UK] Find (Ctrl+F)",
+ "runShortcut": "[UK] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "РЕДАКТОР FINSCRIPT"
},
- "packages": {
- "clickToLoad": "Натисніть для завантаження...",
- "load": "ЗАВАНТАЖИТИ ПАКЕТИ"
+ "explorer": {
+ "title": "[UK] EXPLORER",
+ "openFiles": "[UK] OPEN FILES",
+ "examples": "[UK] EXAMPLES",
+ "runHistory": "[UK] RUN HISTORY",
+ "finscriptEngine": "[UK] FinScript Engine"
},
- "history": {
- "title": "ІСТОРІЯ НОУТБУКІВ",
- "loading": "Завантаження історії...",
- "empty": "Історія ноутбуків порожня"
+ "output": {
+ "title": "[UK] OUTPUT",
+ "success": "[UK] SUCCESS",
+ "error": "[UK] ERROR",
+ "executing": "[UK] EXECUTING FINSCRIPT...",
+ "noOutput": "[UK] No output yet",
+ "pressToRun": "[UK] Press Ctrl+Enter to run",
+ "completed": "[UK] COMPLETED",
+ "failed": "[UK] FAILED",
+ "signals": "[UK] signals",
+ "clear": "[UK] CLEAR",
+ "errors": "[UK] ERRORS",
+ "signalsSection": "[UK] SIGNALS",
+ "outputSection": "[UK] OUTPUT",
+ "charts": "[UK] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[UK] OHLC",
+ "histogram": "[UK] Histogram",
+ "line": "[UK] Line",
+ "points": "[UK] points"
+ },
+ "statusBar": {
+ "modified": "[UK] MODIFIED",
+ "showOutput": "[UK] SHOW OUTPUT",
+ "encoding": "[UK] UTF-8",
+ "spaces": "[UK] 4 Spaces",
+ "runShortcut": "[UK] Ctrl+Enter: Run",
+ "lines": "[UK] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[UK] Close file without saving?",
+ "unsavedChanges": "[UK] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/uk/common.json b/fincept-terminal-desktop/public/locales/uk/common.json
index e9bb382f4..6fe911c10 100644
--- a/fincept-terminal-desktop/public/locales/uk/common.json
+++ b/fincept-terminal-desktop/public/locales/uk/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Завантаження...",
- "error": "Помилка",
- "success": "Успіх",
- "save": "Зберегти",
- "cancel": "Скасувати",
- "delete": "Видалити",
- "edit": "Редагувати",
- "add": "Додати",
- "search": "Пошук",
- "filter": "Фільтр",
- "back": "Назад",
- "next": "Далі",
- "previous": "Попередній",
- "submit": "Надіслати",
- "close": "Закрити",
- "open": "Відкрити",
- "yes": "Так",
- "no": "Ні",
- "ok": "OK",
- "confirm": "Підтвердити",
- "language": "Мова",
- "selectLanguage": "Виберіть мову"
-}
\ No newline at end of file
+ "settings": "[UK] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/uk/dashboard.json b/fincept-terminal-desktop/public/locales/uk/dashboard.json
index 9c2b20fce..c9598cbc1 100644
--- a/fincept-terminal-desktop/public/locales/uk/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/uk/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "НАЛАШТУВАННЯ ПРИЛАДНОЇ ПАНЕЛІ",
- "live": "НАЖИВО",
- "widgets": "ВІДЖЕТИ"
- },
- "buttons": {
- "addWidget": "ДОДАТИ ВІДЖЕТ",
- "saveLayout": "ЗБЕРЕГТИ МАКЕТ",
- "reset": "СКИДАННЯ",
- "help": "ДОПОМОГА"
- },
"widgets": {
"loading": "Завантаження...",
- "error": "Помилка",
"globalIndices": "Глобальні індекси - Топ 12",
"forex": "Форекс - основні пари",
"crypto": "КРИПТОВАЛЮТИ",
@@ -20,8 +8,6 @@
"news": "НОВИНИ",
"forum": "ФОРУМ",
"watchlist": "СПИСОК ПЕРЕГЛЯДУ",
- "maritimeIntelligence": "Морська розвідка",
- "unknown": "Невідомий тип віджета",
"index": "ІНДЕКС",
"symbol": "СИМВОЛ",
"price": "ЦІНА",
@@ -38,41 +24,22 @@
"pair": "ПАРА",
"rate": "СТАВКА",
"commodity": "ТОВАРНИЙ",
- "globe3D": "3D ГЛОБУС",
- "vessels": "ПОСУДИ",
- "routes": "МАРШРУТИ",
- "vol24h": "VOL 24H",
- "topTradeCorridors": "ТОП ТОРГІВЕЛЬНИХ КОРИДОРОВ",
- "ships": "кораблі",
- "marketNews": "Новини ринку",
- "secPressReleases": "Прес-релізи SEC",
- "cryptoNews": "Крипто новини",
- "trendingForum": "Популярний форум",
- "techStocks": "Технологічні акції"
- },
- "tips": {
- "drag": "Перетягніть віджети, щоб змінити порядок",
- "resize": "Змінити розмір від нижнього правого кута",
- "remove": "Видаліть віджети за допомогою кнопки X",
- "responsive": "Адаптивний макет – використовується повна ширина"
- },
- "loading": {
- "title": "Ініціалізація інформаційної панелі",
- "description": "Налаштування кешу бази даних для швидшого завантаження даних...",
- "note": "Під час першого запуску це займе лише деякий час"
- },
- "empty": {
- "noWidgets": "На інформаційній панелі немає віджетів",
- "addFirst": "ДОДАТИ СВІЙ ПЕРШИЙ ВІДЖЕТ"
- },
- "status": {
- "version": "Fincept Customizable Dashboard v2.0.0 | Перетягніть робочу область",
- "layout": "Макет",
- "custom": "Custom",
- "empty": "Порожній",
- "active": "АКТИВНИЙ",
- "cache": "Кеш: УВІМКНЕНО",
- "label": "Статус"
+ "noActiveMarkets": "[UK] No active markets found",
+ "indicator": "[UK] INDICATOR",
+ "value": "[UK] VALUE",
+ "chg": "[UK] CHG",
+ "overallRisk": "[UK] OVERALL RISK",
+ "openEconomicsTab": "[UK] Open Economics Tab",
+ "openGeopoliticsTab": "[UK] Open Geopolitics Tab",
+ "openPolymarketTab": "[UK] Open Polymarket Tab",
+ "noPortfolioFound": "[UK] No portfolio found",
+ "createPortfolioHint": "[UK] Create one in Portfolio tab",
+ "openPortfolioTab": "[UK] Open Portfolio Tab",
+ "action": "[UK] ACTION",
+ "markets": "[UK] MARKETS",
+ "performanceTracker": "[UK] PERFORMANCE TRACKER",
+ "totalPnL": "[UK] TOTAL P&L",
+ "viewDetailedAnalytics": "[UK] View Detailed Analytics"
},
"messages": {
"layoutSaved": "Макет інформаційної панелі збережено!",
diff --git a/fincept-terminal-desktop/public/locales/uk/geopolitics.json b/fincept-terminal-desktop/public/locales/uk/geopolitics.json
index 973685772..9ed2e9fa0 100644
--- a/fincept-terminal-desktop/public/locales/uk/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/uk/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "ГЕОПОЛІТИКА",
"messages": {
- "loading": "Завантаження даних..."
+ "retry": "[UK] RETRY"
+ },
+ "header": {
+ "prefix": "[UK] GEO>",
+ "title": "[UK] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[UK] EVENTS"
+ },
+ "status": {
+ "stale": "[UK] STALE",
+ "loading": "[UK] LOADING...",
+ "error": "[UK] ERROR:"
+ },
+ "filters": {
+ "country": "[UK] Country...",
+ "cities": "[UK] Cities...",
+ "category": "[UK] Category...",
+ "apply": "[UK] APPLY",
+ "clear": "[UK] CLEAR",
+ "clearAllCities": "[UK] Clear all cities",
+ "selectedLabel": "[UK] Selected:"
+ },
+ "panel": {
+ "title": "[UK] INFO PANEL",
+ "expand": "[UK] Expand panel",
+ "collapse": "[UK] Collapse panel",
+ "eventsLoaded": "[UK] EVENTS LOADED",
+ "onMapVisualization": "[UK] on map visualization",
+ "topCategories": "[UK] TOP CATEGORIES",
+ "topCountries": "[UK] TOP COUNTRIES",
+ "eventDetails": "[UK] EVENT DETAILS",
+ "close": "[UK] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[UK] Country:",
+ "city": "[UK] City:",
+ "keywords": "[UK] Keywords:",
+ "coords": "[UK] Coords:",
+ "date": "[UK] Date:",
+ "source": "[UK] Source:",
+ "viewArticle": "[UK] View Article"
+ },
+ "legend": {
+ "title": "[UK] EVENT CATEGORIES",
+ "armedConflict": "[UK] Armed Conflict",
+ "terrorism": "[UK] Terrorism",
+ "protests": "[UK] Protests",
+ "civilianViolence": "[UK] Civilian Violence",
+ "riots": "[UK] Riots",
+ "politicalViolence": "[UK] Political Violence",
+ "crisis": "[UK] Crisis",
+ "explosions": "[UK] Explosions",
+ "strategic": "[UK] Strategic",
+ "unclassified": "[UK] Unclassified"
+ },
+ "footer": {
+ "tabName": "[UK] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[UK] EVENTS",
+ "labelEngine": "[UK] ENGINE",
+ "engineValue": "[UK] DECK.GL v9.2",
+ "labelSource": "[UK] SOURCE",
+ "sourceValue": "[UK] NEWS-EVENTS API",
+ "labelSelected": "[UK] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/uk/markets.json b/fincept-terminal-desktop/public/locales/uk/markets.json
index 038fc4b74..4aa30cfcd 100644
--- a/fincept-terminal-desktop/public/locales/uk/markets.json
+++ b/fincept-terminal-desktop/public/locales/uk/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%ЗМ",
"high": "МАКС",
"low": "МІН",
- "loading": "Завантаження...",
"noData": "Немає даних",
"refresh": "ОНОВИТИ",
"auto": "АВТО",
"on": "УВІМК",
- "off": "ВИМК",
- "lastUpdate": "ОСТАННЄ ОНОВЛЕННЯ",
- "updating": "ОНОВЛЕННЯ",
- "live": "НАЖИВО"
+ "off": "ВИМК"
}
diff --git a/fincept-terminal-desktop/public/locales/uk/news.json b/fincept-terminal-desktop/public/locales/uk/news.json
index 2d736c751..6e6f2c783 100644
--- a/fincept-terminal-desktop/public/locales/uk/news.json
+++ b/fincept-terminal-desktop/public/locales/uk/news.json
@@ -1,32 +1,63 @@
{
"title": "ПРОФЕСІЙНІ НОВИНИ ТЕРМІНАЛУ FINCEPT",
"header": {
- "liveFeed": "ЖИВИЙ ПОТІК",
- "live": "НАЖИВО",
- "refresh": "ОНОВИТИ",
- "updating": "ОНОВЛЕННЯ...",
- "alerts": "СПОВІЩЕННЯ",
- "sources": "ДЖЕРЕЛА",
- "status": "СТАТУС",
- "demoMode": "ДЕМО РЕЖИМ",
- "articles": "СТАТТІ",
- "activeSources": "АКТИВНІ ДЖЕРЕЛА"
- },
- "autoRefresh": {
- "title": "ІНТЕРВАЛ АВТООНОВЛЕННЯ",
- "minute": "хвилина",
- "minutes": "хвилин"
+ "refresh": "ОНОВИТИ"
},
"messages": {
- "loadingFeeds": "Завантаження стрічок...",
- "breaking": "ТЕРМІНОВЕ"
- },
- "feeds": {
- "primary": "[UK] PRIMARY NEWS FEED",
- "secondary": "[UK] SECONDARY NEWS FEED",
- "additional": "[UK] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[UK] Loading feeds...",
+ "failedToLoad": "[UK] Failed to load RSS feeds",
+ "noCustomFeeds": "[UK] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[UK] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[UK] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[UK] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[UK] RSS FEED SETTINGS",
+ "subtitle": "[UK] MANAGE YOUR NEWS SOURCES",
+ "close": "[UK] CLOSE",
+ "myFeeds": "[UK] MY FEEDS",
+ "defaultFeeds": "[UK] DEFAULT FEEDS",
+ "noFeedsAvailable": "[UK] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[UK] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[UK] ADD NEW FEED",
+ "addNewRssFeed": "[UK] ADD NEW RSS FEED",
+ "editRssFeed": "[UK] EDIT RSS FEED",
+ "restoreDefaults": "[UK] RESTORE DEFAULTS",
+ "restoreAll": "[UK] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[UK] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[UK] DISPLAY NAME",
+ "sourceName": "[UK] SOURCE NAME (SHORT)",
+ "feedUrl": "[UK] RSS FEED URL",
+ "category": "[UK] CATEGORY",
+ "region": "[UK] REGION",
+ "required": "[UK] *",
+ "testUrl": "[UK] TEST URL",
+ "testing": "[UK] TESTING...",
+ "valid": "[UK] VALID",
+ "cancel": "[UK] CANCEL",
+ "saving": "[UK] SAVING...",
+ "addFeed": "[UK] ADD FEED",
+ "updateFeed": "[UK] UPDATE FEED",
+ "on": "[UK] ON",
+ "off": "[UK] OFF",
+ "default": "[UK] DEFAULT",
+ "total": "[UK] TOTAL",
+ "active": "[UK] ACTIVE",
+ "custom": "[UK] CUSTOM",
+ "placeholders": {
+ "displayName": "[UK] e.g., Bloomberg Markets",
+ "sourceName": "[UK] e.g., BLOOMBERG",
+ "feedUrl": "[UK] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[UK] Name is required",
+ "sourceRequired": "[UK] Source name is required",
+ "invalidUrl": "[UK] Please enter a valid URL",
+ "invalidRss": "[UK] URL does not appear to be a valid RSS feed",
+ "testFailed": "[UK] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[UK] Delete this RSS feed?",
+ "message": "[UK] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/uk/portfolio.json b/fincept-terminal-desktop/public/locales/uk/portfolio.json
index 7e72f9ad6..22d678f4d 100644
--- a/fincept-terminal-desktop/public/locales/uk/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/uk/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "МЕНЕДЖЕР ПОРТФЕЛЯ FINCEPT",
- "header": {
- "live": "НАЖИВО",
- "updating": "ОНОВЛЮЄТЬСЯ",
- "newPortfolio": "НОВИЙ ПОРТФЕЛЬ",
- "refresh": "ОНОВИТИ",
- "exportCsv": "ЕКСПОРТ CSV"
- },
- "summary": {
- "totalValue": "ЗАГАЛЬНА ВАРТІСТЬ",
- "dayPnl": "P&L ЗА ДЕНЬ",
- "totalPnl": "ЗАГАЛЬНИЙ P&L",
- "positions": "ПОЗИЦІЇ"
- },
- "views": {
- "positions": "ПОЗИЦІЇ",
- "addAsset": "ДОДАТИ АКТИВ",
- "sellAsset": "ПРОДАТИ АКТИВ",
- "analytics": "АНАЛІТИКА",
- "history": "ІСТОРІЯ",
- "activeMgmt": "АКТИВНЕ УПРАВЛІННЯ",
- "performance": "ЕФЕКТИВНІСТЬ",
- "rebalance": "РЕБАЛАНСУВАННЯ",
- "reports": "ЗВІТИ",
- "alerts": "СПОВІЩЕННЯ",
- "sectors": "СЕКТОРИ",
- "help": "ДОПОМОГА"
- },
- "sidebar": {
- "portfolios": "ПОРТФЕЛІ",
- "loading": "Завантаження портфелів...",
- "noPortfolios": "Ще немає портфелів.",
- "clickCreate": "Натисніть НОВИЙ ПОРТФЕЛЬ для створення.",
- "owner": "Власник",
- "currency": "Валюта"
- },
- "content": {
- "selectOrCreate": "Виберіть портфель або створіть новий для початку",
- "loadingData": "Завантаження даних портфеля...",
- "comingSoon": "вигляд скоро..."
- },
- "modals": {
- "createNew": "СТВОРИТИ НОВИЙ ПОРТФЕЛЬ",
- "portfolioName": "НАЗВА ПОРТФЕЛЯ",
- "owner": "ВЛАСНИК",
- "currency": "ВАЛЮТА",
- "cancel": "СКАСУВАТИ",
- "create": "СТВОРИТИ",
- "addAssetTitle": "ДОДАТИ АКТИВ ДО ПОРТФЕЛЯ",
- "sellAssetTitle": "ПРОДАТИ АКТИВ",
- "symbol": "СИМВОЛ",
- "quantity": "КІЛЬКІСТЬ",
- "price": "ЦІНА",
- "add": "ДОДАТИ",
- "sell": "ПРОДАТИ"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Відстеження в реальному часі з інтеграцією yfinance",
- "lastUpdated": "Останнє Оновлення",
- "connected": "ПІД'ЄДНАНО"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "СТВОРИТИ НОВИЙ ПОРТФЕЛЬ",
+ "portfolioName": "НАЗВА ПОРТФЕЛЯ",
+ "owner": "ВЛАСНИК",
+ "currency": "ВАЛЮТА",
+ "cancel": "СКАСУВАТИ",
+ "create": "СТВОРИТИ",
+ "addAssetTitle": "ДОДАТИ АКТИВ ДО ПОРТФЕЛЯ",
+ "sellAssetTitle": "ПРОДАТИ АКТИВ",
+ "symbol": "СИМВОЛ",
+ "quantity": "КІЛЬКІСТЬ",
+ "price": "ЦІНА",
+ "add": "ДОДАТИ",
+ "sell": "ПРОДАТИ"
+ },
+ "extracted": {
+ "areYouSureYou": "[UK] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/uk/reportBuilder.json b/fincept-terminal-desktop/public/locales/uk/reportBuilder.json
index 156367d1d..38a07194a 100644
--- a/fincept-terminal-desktop/public/locales/uk/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/uk/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[UK] Load",
"save": "[UK] Save",
- "saving": "[UK] Saving...",
- "exportPdf": "[UK] Export PDF",
- "generating": "[UK] Generating..."
+ "saving": "[UK] Saving..."
},
"components": {
"title": "[UK] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/uk/settings.json b/fincept-terminal-desktop/public/locales/uk/settings.json
index 1b9f79931..40c20af63 100644
--- a/fincept-terminal-desktop/public/locales/uk/settings.json
+++ b/fincept-terminal-desktop/public/locales/uk/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Макет вкладки",
"appearance": "Зовнішній вигляд",
"language": "Мова",
- "storage": "Пам'ять і кеш"
+ "storage": "Пам'ять і кеш",
+ "notifications": "[UK] Notifications"
},
"credentials": {
"title": "КЕРУВАННЯ ОБЛІКОВИМИ ДАННИМИ API",
@@ -46,7 +47,31 @@
"saveConfig": "ЗБЕРЕГТИ КОНФІГУРАЦІЮ",
"reset": "СКИДАННЯ",
"saveSuccess": "Вигляд терміналу та зіставлення клавіш успішно збережено",
- "resetSuccess": "Відновити зовнішній вигляд і зіставлення клавіш за замовчуванням"
+ "resetSuccess": "Відновити зовнішній вигляд і зіставлення клавіш за замовчуванням",
+ "customColors": "[UK] Custom Colors",
+ "customColorsTitle": "[UK] CUSTOM COLORS",
+ "colorPrimary": "[UK] Primary",
+ "colorSecondary": "[UK] Secondary",
+ "colorSuccess": "[UK] Success",
+ "colorAlert": "[UK] Alert",
+ "colorWarning": "[UK] Warning",
+ "colorInfo": "[UK] Info",
+ "colorAccent": "[UK] Accent",
+ "colorPurple": "[UK] Purple",
+ "colorText": "[UK] Text",
+ "colorTextMuted": "[UK] Text Muted",
+ "colorBackground": "[UK] Background",
+ "colorPanel": "[UK] Panel",
+ "layoutSpacing": "[UK] LAYOUT & SPACING",
+ "contentDensity": "[UK] CONTENT DENSITY",
+ "borderRadius": "[UK] BORDER RADIUS",
+ "borderStyle": "[UK] BORDER STYLE",
+ "lineHeight": "[UK] LINE HEIGHT",
+ "letterSpacing": "[UK] LETTER SPACING",
+ "effects": "[UK] EFFECTS",
+ "widgetOpacity": "[UK] WIDGET OPACITY",
+ "enableGlow": "[UK] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[UK] GLOW INTENSITY"
},
"stockSymbols": {
"title": "База даних символів акцій",
@@ -65,17 +90,8 @@
"tip": "ПОРАДА. Перетягуйте вкладки, щоб змінити їх порядок. Використовуйте кнопки зі стрілками для переміщення вкладок між заголовками та розділами меню. Зміни зберігаються автоматично."
},
"llm": {
- "title": "КОНФІГУРАЦІЯ LLM",
- "description": "Налаштуйте моделі та постачальників AI",
"connected": "ПІДКЛЮЧЕНО",
- "disconnected": "ВІДКЛЮЧЕНО",
- "provider": "ПОСТАЧАЛЬНИК ШІ",
- "globalSettings": "ГЛОБАЛЬНІ НАЛАШТУВАННЯ ШІ",
- "temperature": "ТЕМПЕРАТУРА",
- "maxTokens": "МАКС. ЖЕТОНІВ",
- "systemPrompt": "СИСТЕМНА ПІДКАЗКА",
- "modelLibrary": "БІБЛІОТЕКА МОДЕЛЕЙ",
- "multiModelConfigs": "Багатомодельні конфігурації"
+ "disconnected": "ВІДКЛЮЧЕНО"
},
"buttons": {
"save": "ЗБЕРЕГТИ",
@@ -86,5 +102,18 @@
"database": "База даних: SQLite",
"storage": "Зберігання: файлове",
"secureStorage": "Усі дані безпечно зберігаються у fincept_terminal.db"
+ },
+ "notifications": {
+ "title": "[UK] NOTIFICATION PROVIDERS",
+ "description": "[UK] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[UK] Event Filters",
+ "eventFilterDescription": "[UK] Choose which notification types to forward to external providers.",
+ "providers": "[UK] Providers",
+ "enabled": "[UK] Enabled",
+ "disabled": "[UK] Disabled",
+ "testButton": "[UK] TEST",
+ "testSuccess": "[UK] Test notification sent successfully!",
+ "testFailed": "[UK] Failed to send test notification. Check your configuration.",
+ "saved": "[UK] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/uk/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/uk/surfaceAnalytics.json
new file mode 100644
index 000000000..a6f68f65f
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/uk/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[UK] SURFACE ANALYTICS",
+ "initializing": "[UK] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[UK] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[UK] VOL SURFACE",
+ "correlation": "[UK] CORRELATION",
+ "yieldCurve": "[UK] YIELD CURVE",
+ "pca": "[UK] PCA FACTORS"
+ },
+ "demoData": "[UK] DEMO DATA",
+ "demoDataSynthetic": "[UK] DEMO DATA (synthetic)",
+ "synthetic": "[UK] SYNTHETIC",
+ "manual": "[UK] MANUAL",
+ "error": "[UK] ERROR",
+ "ready": "[UK] READY",
+ "metrics": "[UK] Metrics",
+ "updated": "[UK] Updated",
+ "clickRefresh": "[UK] Click REFRESH to load data",
+ "refresh": "[UK] REFRESH",
+ "noApiKey": "[UK] NO API KEY",
+ "lastUpdate": "[UK] LAST UPDATE",
+ "loadingData": "[UK] LOADING DATA...",
+ "noDataLoaded": "[UK] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[UK] IV SURFACE METRICS",
+ "correlationMetrics": "[UK] CORRELATION METRICS",
+ "yieldCurveMetrics": "[UK] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[UK] PCA FACTOR METRICS",
+ "dataInfo": "[UK] DATA INFO",
+ "source": "[UK] SOURCE",
+ "frequency": "[UK] FREQUENCY",
+ "quality": "[UK] QUALITY",
+ "correlationScale": "[UK] CORRELATION SCALE",
+ "strongPositive": "[UK] Strong Positive (0.7-1.0)",
+ "neutral": "[UK] Neutral (0.3-0.7)",
+ "strongNegative": "[UK] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[UK] IV INTERPRETATION",
+ "highIv": "[UK] High IV = Expensive Options",
+ "lowIv": "[UK] Low IV = Cheap Options",
+ "skew": "[UK] Skew = Put/Call IV Diff",
+ "termStructure": "[UK] Term Structure = Time Effect",
+ "pcaInterpretation": "[UK] PCA INTERPRETATION",
+ "pc1": "[UK] PC1 = Market Factor",
+ "pc2": "[UK] PC2 = Size/Value Factor",
+ "pc3": "[UK] PC3 = Sector Rotation",
+ "higherVar": "[UK] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[UK] STRIKE",
+ "dte": "[UK] DTE",
+ "iv": "[UK] IV",
+ "correlation": "[UK] CORRELATION",
+ "maturity": "[UK] MATURITY",
+ "yield": "[UK] YIELD",
+ "loading": "[UK] LOADING",
+ "strikePrice": "[UK] STRIKE PRICE",
+ "daysToExpiry": "[UK] DAYS TO EXPIRY",
+ "impliedVol": "[UK] IMPLIED VOL (%)",
+ "assetPairIndex": "[UK] ASSET PAIR INDEX",
+ "timeDays": "[UK] TIME (DAYS)",
+ "correlationCoeff": "[UK] CORRELATION COEFF",
+ "maturityMonths": "[UK] MATURITY (MONTHS)",
+ "historicalDays": "[UK] HISTORICAL DAYS",
+ "yieldPercent": "[UK] YIELD (%)",
+ "principalComponent": "[UK] PRINCIPAL COMPONENT",
+ "assetIndex": "[UK] ASSET INDEX",
+ "factorLoading": "[UK] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[UK] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[UK] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[UK] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[UK] DAY ROLLING",
+ "yieldCurve": "[UK] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[UK] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[UK] FAILED TO LOAD DATA",
+ "authFailed": "[UK] AUTHENTICATION FAILED",
+ "authFailedHelp": "[UK] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[UK] ACCESS DENIED",
+ "accessDeniedHelp": "[UK] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[UK] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[UK] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[UK] DATA TIMEFRAME",
+ "schema": "[UK] Schema",
+ "description": "[UK] Description",
+ "recordsPerDay": "[UK] Records/Day",
+ "highFrequencyWarning": "[UK] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[UK] Data Volume"
+ },
+ "settings": {
+ "title": "[UK] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[UK] DATABENTO API KEY",
+ "configured": "[UK] CONFIGURED",
+ "invalidFormat": "[UK] INVALID FORMAT",
+ "apiKeyConfigured": "[UK] API key is configured (db-*****)",
+ "remove": "[UK] REMOVE",
+ "enterApiKey": "[UK] Enter your Databento API key (db-*****)",
+ "save": "[UK] SAVE",
+ "saving": "[UK] SAVING...",
+ "getApiKeyFrom": "[UK] Get your API key from",
+ "dashboardApiKeys": "[UK] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[UK] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[UK] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[UK] CORRELATION ASSETS",
+ "addSymbol": "[UK] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[UK] Reset to defaults",
+ "historicalDateRange": "[UK] HISTORICAL DATE RANGE",
+ "start": "[UK] Start",
+ "end": "[UK] End",
+ "autoRefreshInterval": "[UK] AUTO REFRESH INTERVAL",
+ "manualOnly": "[UK] Manual Only",
+ "every1min": "[UK] Every 1 minute",
+ "every5min": "[UK] Every 5 minutes",
+ "every15min": "[UK] Every 15 minutes",
+ "every1hour": "[UK] Every 1 hour",
+ "browseDatasets": "[UK] BROWSE DATASETS",
+ "costEstimator": "[UK] COST ESTIMATOR",
+ "referenceData": "[UK] REFERENCE DATA",
+ "orderBook": "[UK] ORDER BOOK",
+ "liveStreaming": "[UK] LIVE STREAMING",
+ "active": "[UK] ACTIVE",
+ "futuresCme": "[UK] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[UK] BATCH DOWNLOADS",
+ "additionalSchemas": "[UK] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[UK] TRADES, IMBALANCE, STATUS",
+ "cancel": "[UK] CANCEL",
+ "saveChanges": "[UK] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[UK] BATCH DOWNLOADS",
+ "newBatchJob": "[UK] NEW BATCH JOB",
+ "dataset": "[UK] Dataset",
+ "schema": "[UK] Schema",
+ "symbolsCommaSeparated": "[UK] Symbols (comma-separated)",
+ "startDate": "[UK] Start Date",
+ "endDate": "[UK] End Date",
+ "encoding": "[UK] Encoding",
+ "compression": "[UK] Compression",
+ "submitJob": "[UK] SUBMIT JOB",
+ "noBatchJobs": "[UK] No batch jobs found. Click + to create one.",
+ "records": "[UK] records",
+ "download": "[UK] Download",
+ "files": "[UK] FILES",
+ "jobsExpireNotice": "[UK] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[UK] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[UK] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[UK] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[UK] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[UK] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[UK] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[UK] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[UK] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[UK] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[UK] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[UK] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[UK] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[UK] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[UK] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[UK] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[UK] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[UK] [EN] common.or",
+ "note": "[UK] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/uk/tabs.json b/fincept-terminal-desktop/public/locales/uk/tabs.json
index 36bc9d091..48d657f20 100644
--- a/fincept-terminal-desktop/public/locales/uk/tabs.json
+++ b/fincept-terminal-desktop/public/locales/uk/tabs.json
@@ -5,29 +5,7 @@
"news": "Новини",
"portfolio": "Портфель",
"backtesting": "Бектестинг",
- "watchlist": "Список спостереження",
- "research": "Дослідження",
- "screener": "Скринер",
"chat": "AI Chat",
- "agents": "Агенти",
- "settings": "Налаштування",
"profile": "Профіль"
- },
- "functionKeys": {
- "f1": "ПАНЛ",
- "f2": "РНКИ",
- "f3": "НВНИ",
- "f4": "ПРТФ",
- "f5": "БКТС",
- "f6": "СПСН",
- "f7": "ДСЛД",
- "f8": "СКРН",
- "f9": "ТРДГ",
- "f10": "AI",
- "f11": "ПОВН",
- "f12": "ПРФЛ"
- },
- "labels": {
- "moreTabs": "Більше вкладок у меню панелі інструментів"
}
}
diff --git a/fincept-terminal-desktop/public/locales/uk/watchlist.json b/fincept-terminal-desktop/public/locales/uk/watchlist.json
index 642d00f9e..e783b5a74 100644
--- a/fincept-terminal-desktop/public/locales/uk/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/uk/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "СПИСОК СПОСТЕРЕЖЕННЯ",
- "header": {
- "export": "ЕКСПОРТ",
- "updating": "ОНОВЛЕННЯ",
- "live": "НАЖИВО"
- },
"sidebar": {
- "groups": "ГРУПИ СПИСКІВ",
- "new": "НОВИЙ",
"noWatchlists": "Ще немає списків.",
"clickNew": "Натисніть НОВИЙ для створення.",
- "stocks": "акції",
- "marketMovers": "ЛІДЕРИ РИНКУ",
- "gainer": "ЗРОСТАЮТЬ",
- "loser": "ПАДАЮТЬ",
- "volumeLeaders": "ЛІДЕРИ ОБСЯГУ"
- },
- "emptyState": {
- "selectWatchlist": "Виберіть список або створіть новий для початку"
- },
- "list": {
- "symbols": "Символи"
+ "stocks": "акції"
}
}
diff --git a/fincept-terminal-desktop/public/locales/vi/codeEditor.json b/fincept-terminal-desktop/public/locales/vi/codeEditor.json
index 367588253..9f1d2fe8f 100644
--- a/fincept-terminal-desktop/public/locales/vi/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/vi/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "TRÌNH SOẠN MÃ",
"header": {
- "packages": "GÓI"
+ "finscriptIde": "[VI] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "TỆP MỚI",
- "new": "MỚI",
- "open": "MỞ",
- "save": "LƯU",
"run": "CHẠY",
"running": "ĐANG CHẠY...",
- "runAll": "CHẠY TẤT CẢ",
- "history": "LỊCH SỬ"
+ "toggleExplorer": "[VI] Toggle Explorer (Ctrl+B)",
+ "openFile": "[VI] Open File",
+ "saveShortcut": "[VI] Save (Ctrl+S)",
+ "findShortcut": "[VI] Find (Ctrl+F)",
+ "runShortcut": "[VI] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER NOTEBOOK",
"finscript": "TRÌNH SOẠN FINSCRIPT"
},
- "packages": {
- "clickToLoad": "Nhấn để tải...",
- "load": "TẢI CÁC GÓI"
+ "explorer": {
+ "title": "[VI] EXPLORER",
+ "openFiles": "[VI] OPEN FILES",
+ "examples": "[VI] EXAMPLES",
+ "runHistory": "[VI] RUN HISTORY",
+ "finscriptEngine": "[VI] FinScript Engine"
},
- "history": {
- "title": "LỊCH SỬ NOTEBOOK",
- "loading": "Đang tải lịch sử...",
- "empty": "Không có lịch sử notebook"
+ "output": {
+ "title": "[VI] OUTPUT",
+ "success": "[VI] SUCCESS",
+ "error": "[VI] ERROR",
+ "executing": "[VI] EXECUTING FINSCRIPT...",
+ "noOutput": "[VI] No output yet",
+ "pressToRun": "[VI] Press Ctrl+Enter to run",
+ "completed": "[VI] COMPLETED",
+ "failed": "[VI] FAILED",
+ "signals": "[VI] signals",
+ "clear": "[VI] CLEAR",
+ "errors": "[VI] ERRORS",
+ "signalsSection": "[VI] SIGNALS",
+ "outputSection": "[VI] OUTPUT",
+ "charts": "[VI] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[VI] OHLC",
+ "histogram": "[VI] Histogram",
+ "line": "[VI] Line",
+ "points": "[VI] points"
+ },
+ "statusBar": {
+ "modified": "[VI] MODIFIED",
+ "showOutput": "[VI] SHOW OUTPUT",
+ "encoding": "[VI] UTF-8",
+ "spaces": "[VI] 4 Spaces",
+ "runShortcut": "[VI] Ctrl+Enter: Run",
+ "lines": "[VI] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[VI] Close file without saving?",
+ "unsavedChanges": "[VI] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/vi/common.json b/fincept-terminal-desktop/public/locales/vi/common.json
index e34ca340e..980f2d928 100644
--- a/fincept-terminal-desktop/public/locales/vi/common.json
+++ b/fincept-terminal-desktop/public/locales/vi/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "Đang tải...",
- "error": "Lỗi",
- "success": "Thành công",
- "save": "Lưu",
- "cancel": "Hủy",
- "delete": "Xóa",
- "edit": "Chỉnh sửa",
- "add": "Thêm",
- "search": "Tìm kiếm",
- "filter": "Lọc",
- "back": "Quay lại",
- "next": "Tiếp theo",
- "previous": "Trước đó",
- "submit": "Gửi",
- "close": "Đóng",
- "open": "Mở",
- "yes": "Có",
- "no": "Không",
- "ok": "OK",
- "confirm": "Xác nhận",
- "language": "Ngôn ngữ",
- "selectLanguage": "Chọn ngôn ngữ"
-}
\ No newline at end of file
+ "settings": "[VI] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/vi/dashboard.json b/fincept-terminal-desktop/public/locales/vi/dashboard.json
index 428950ad1..971adb1c9 100644
--- a/fincept-terminal-desktop/public/locales/vi/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/vi/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "BẢNG TỔNG QUAN CÓ THỂ TÙY CHỈNH",
- "live": "SỐNG",
- "widgets": "TIỆN ÍCH"
- },
- "buttons": {
- "addWidget": "THÊM TIỆN ÍCH",
- "saveLayout": "LƯU BỐ CỤC",
- "reset": "CÀI LẠI",
- "help": "GIÚP ĐỠ"
- },
"widgets": {
"loading": "Đang tải...",
- "error": "Lỗi",
"globalIndices": "Chỉ số toàn cầu - Top 12",
"forex": "Forex - Các cặp chính",
"crypto": "TIỀN ĐIỆN TỬ",
@@ -20,8 +8,6 @@
"news": "TIN TỨC",
"forum": "DIỄN ĐÀN",
"watchlist": "DANH SÁCH THEO DÕI",
- "maritimeIntelligence": "Tình báo hàng hải",
- "unknown": "Loại tiện ích không xác định",
"index": "CHỈ SỐ",
"symbol": "BIỂU TƯỢNG",
"price": "GIÁ",
@@ -38,41 +24,22 @@
"pair": "ĐÔI",
"rate": "TỶ LỆ",
"commodity": "HÀNG HÓA",
- "globe3D": "TOÀN CẦU 3D",
- "vessels": "TÀU",
- "routes": "TUYẾN ĐƯỜNG",
- "vol24h": "TẬP 24H",
- "topTradeCorridors": "HÀNH TRÌNH THƯƠNG MẠI HÀNG ĐẦU",
- "ships": "tàu thuyền",
- "marketNews": "Tin tức thị trường",
- "secPressReleases": "Thông cáo báo chí của SEC",
- "cryptoNews": "Tin tức tiền điện tử",
- "trendingForum": "Diễn đàn xu hướng",
- "techStocks": "Cổ phiếu công nghệ"
- },
- "tips": {
- "drag": "Kéo các widget để sắp xếp lại",
- "resize": "Thay đổi kích thước từ góc dưới bên phải",
- "remove": "Xóa widget bằng nút X",
- "responsive": "Bố cục đáp ứng - sử dụng toàn bộ chiều rộng"
- },
- "loading": {
- "title": "Đang khởi tạo bảng điều khiển",
- "description": "Thiết lập bộ đệm cơ sở dữ liệu để tải dữ liệu nhanh hơn...",
- "note": "Việc này sẽ chỉ mất một chút thời gian trong lần khởi chạy đầu tiên"
- },
- "empty": {
- "noWidgets": "Không có tiện ích nào trên bảng điều khiển",
- "addFirst": "THÊM TIỆN ÍCH ĐẦU TIÊN CỦA BẠN"
- },
- "status": {
- "version": "Bảng điều khiển có thể tùy chỉnh Fincept v2.0.0 | Kéo và thả không gian làm việc",
- "layout": "Cách trình bày",
- "custom": "Phong tục",
- "empty": "Trống",
- "active": "TÍCH CỰC",
- "cache": "Bộ nhớ đệm: ĐÃ BẬT",
- "label": "Trạng thái"
+ "noActiveMarkets": "[VI] No active markets found",
+ "indicator": "[VI] INDICATOR",
+ "value": "[VI] VALUE",
+ "chg": "[VI] CHG",
+ "overallRisk": "[VI] OVERALL RISK",
+ "openEconomicsTab": "[VI] Open Economics Tab",
+ "openGeopoliticsTab": "[VI] Open Geopolitics Tab",
+ "openPolymarketTab": "[VI] Open Polymarket Tab",
+ "noPortfolioFound": "[VI] No portfolio found",
+ "createPortfolioHint": "[VI] Create one in Portfolio tab",
+ "openPortfolioTab": "[VI] Open Portfolio Tab",
+ "action": "[VI] ACTION",
+ "markets": "[VI] MARKETS",
+ "performanceTracker": "[VI] PERFORMANCE TRACKER",
+ "totalPnL": "[VI] TOTAL P&L",
+ "viewDetailedAnalytics": "[VI] View Detailed Analytics"
},
"messages": {
"layoutSaved": "Đã lưu bố cục trang tổng quan!",
diff --git a/fincept-terminal-desktop/public/locales/vi/geopolitics.json b/fincept-terminal-desktop/public/locales/vi/geopolitics.json
index a6e266937..82a88566d 100644
--- a/fincept-terminal-desktop/public/locales/vi/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/vi/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "ĐỊA CHÍNH TRỊ",
"messages": {
- "loading": "Đang tải dữ liệu..."
+ "retry": "[VI] RETRY"
+ },
+ "header": {
+ "prefix": "[VI] GEO>",
+ "title": "[VI] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[VI] EVENTS"
+ },
+ "status": {
+ "stale": "[VI] STALE",
+ "loading": "[VI] LOADING...",
+ "error": "[VI] ERROR:"
+ },
+ "filters": {
+ "country": "[VI] Country...",
+ "cities": "[VI] Cities...",
+ "category": "[VI] Category...",
+ "apply": "[VI] APPLY",
+ "clear": "[VI] CLEAR",
+ "clearAllCities": "[VI] Clear all cities",
+ "selectedLabel": "[VI] Selected:"
+ },
+ "panel": {
+ "title": "[VI] INFO PANEL",
+ "expand": "[VI] Expand panel",
+ "collapse": "[VI] Collapse panel",
+ "eventsLoaded": "[VI] EVENTS LOADED",
+ "onMapVisualization": "[VI] on map visualization",
+ "topCategories": "[VI] TOP CATEGORIES",
+ "topCountries": "[VI] TOP COUNTRIES",
+ "eventDetails": "[VI] EVENT DETAILS",
+ "close": "[VI] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[VI] Country:",
+ "city": "[VI] City:",
+ "keywords": "[VI] Keywords:",
+ "coords": "[VI] Coords:",
+ "date": "[VI] Date:",
+ "source": "[VI] Source:",
+ "viewArticle": "[VI] View Article"
+ },
+ "legend": {
+ "title": "[VI] EVENT CATEGORIES",
+ "armedConflict": "[VI] Armed Conflict",
+ "terrorism": "[VI] Terrorism",
+ "protests": "[VI] Protests",
+ "civilianViolence": "[VI] Civilian Violence",
+ "riots": "[VI] Riots",
+ "politicalViolence": "[VI] Political Violence",
+ "crisis": "[VI] Crisis",
+ "explosions": "[VI] Explosions",
+ "strategic": "[VI] Strategic",
+ "unclassified": "[VI] Unclassified"
+ },
+ "footer": {
+ "tabName": "[VI] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[VI] EVENTS",
+ "labelEngine": "[VI] ENGINE",
+ "engineValue": "[VI] DECK.GL v9.2",
+ "labelSource": "[VI] SOURCE",
+ "sourceValue": "[VI] NEWS-EVENTS API",
+ "labelSelected": "[VI] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/vi/markets.json b/fincept-terminal-desktop/public/locales/vi/markets.json
index d2afdce75..b5bc72dde 100644
--- a/fincept-terminal-desktop/public/locales/vi/markets.json
+++ b/fincept-terminal-desktop/public/locales/vi/markets.json
@@ -9,13 +9,9 @@
"percentChange": "%THAY ĐỔI",
"high": "CAO",
"low": "THẤP",
- "loading": "Đang tải...",
"noData": "Không có dữ liệu",
"refresh": "LÀM MỚI",
"auto": "TỰ ĐỘNG",
"on": "BẬT",
- "off": "TẮT",
- "lastUpdate": "CẬP NHẬT CUỐI",
- "updating": "ĐANG CẬP NHẬT",
- "live": "TRỰC TIẾP"
+ "off": "TẮT"
}
diff --git a/fincept-terminal-desktop/public/locales/vi/news.json b/fincept-terminal-desktop/public/locales/vi/news.json
index a229f0a2b..92dd7fd63 100644
--- a/fincept-terminal-desktop/public/locales/vi/news.json
+++ b/fincept-terminal-desktop/public/locales/vi/news.json
@@ -1,32 +1,63 @@
{
"title": "TIN TỨC CHUYÊN NGHIỆP TERMINAL FINCEPT",
"header": {
- "liveFeed": "FEED TRỰC TIẾP",
- "live": "TRỰC TIẾP",
- "refresh": "LÀM MỚI",
- "updating": "ĐANG CẬP NHẬT...",
- "alerts": "CẢNH BÁO",
- "sources": "NGUỒN",
- "status": "TRẠNG THÁI",
- "demoMode": "CHẾ ĐỘ DEMO",
- "articles": "BÀI VIẾT",
- "activeSources": "NGUỒN HOẠT ĐỘNG"
- },
- "autoRefresh": {
- "title": "KHOẢNG CÁCH TỰ ĐỘNG CẬP NHẬT",
- "minute": "phút",
- "minutes": "phút"
+ "refresh": "LÀM MỚI"
},
"messages": {
- "loadingFeeds": "Đang tải nguồn cấp...",
- "breaking": "NÓNG"
- },
- "feeds": {
- "primary": "[VI] PRIMARY NEWS FEED",
- "secondary": "[VI] SECONDARY NEWS FEED",
- "additional": "[VI] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[VI] Loading feeds...",
+ "failedToLoad": "[VI] Failed to load RSS feeds",
+ "noCustomFeeds": "[VI] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[VI] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[VI] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[VI] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[VI] RSS FEED SETTINGS",
+ "subtitle": "[VI] MANAGE YOUR NEWS SOURCES",
+ "close": "[VI] CLOSE",
+ "myFeeds": "[VI] MY FEEDS",
+ "defaultFeeds": "[VI] DEFAULT FEEDS",
+ "noFeedsAvailable": "[VI] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[VI] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[VI] ADD NEW FEED",
+ "addNewRssFeed": "[VI] ADD NEW RSS FEED",
+ "editRssFeed": "[VI] EDIT RSS FEED",
+ "restoreDefaults": "[VI] RESTORE DEFAULTS",
+ "restoreAll": "[VI] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[VI] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[VI] DISPLAY NAME",
+ "sourceName": "[VI] SOURCE NAME (SHORT)",
+ "feedUrl": "[VI] RSS FEED URL",
+ "category": "[VI] CATEGORY",
+ "region": "[VI] REGION",
+ "required": "[VI] *",
+ "testUrl": "[VI] TEST URL",
+ "testing": "[VI] TESTING...",
+ "valid": "[VI] VALID",
+ "cancel": "[VI] CANCEL",
+ "saving": "[VI] SAVING...",
+ "addFeed": "[VI] ADD FEED",
+ "updateFeed": "[VI] UPDATE FEED",
+ "on": "[VI] ON",
+ "off": "[VI] OFF",
+ "default": "[VI] DEFAULT",
+ "total": "[VI] TOTAL",
+ "active": "[VI] ACTIVE",
+ "custom": "[VI] CUSTOM",
+ "placeholders": {
+ "displayName": "[VI] e.g., Bloomberg Markets",
+ "sourceName": "[VI] e.g., BLOOMBERG",
+ "feedUrl": "[VI] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[VI] Name is required",
+ "sourceRequired": "[VI] Source name is required",
+ "invalidUrl": "[VI] Please enter a valid URL",
+ "invalidRss": "[VI] URL does not appear to be a valid RSS feed",
+ "testFailed": "[VI] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[VI] Delete this RSS feed?",
+ "message": "[VI] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/vi/portfolio.json b/fincept-terminal-desktop/public/locales/vi/portfolio.json
index af23f7a4e..cdaaeca7b 100644
--- a/fincept-terminal-desktop/public/locales/vi/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/vi/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "QUẢN LÝ DANH MỤC ĐẦU TƯ FINCEPT",
- "header": {
- "live": "TRỰC TIẾP",
- "updating": "ĐANG CẬP NHẬT",
- "newPortfolio": "DANH MỤC MỚI",
- "refresh": "LÀM MỚI",
- "exportCsv": "XUẤT CSV"
- },
- "summary": {
- "totalValue": "TỔNG GIÁ TRỊ",
- "dayPnl": "LN/L NGÀY",
- "totalPnl": "TỔNG LN/L",
- "positions": "VỊ THẾ"
- },
- "views": {
- "positions": "VỊ THẾ",
- "addAsset": "THÊM TÀI SẢN",
- "sellAsset": "BÁN TÀI SẢN",
- "analytics": "PHÂN TÍCH",
- "history": "LỊCH SỬ",
- "activeMgmt": "QUẢN LÝ CHỦ ĐỘNG",
- "performance": "HIỆU SUẤT",
- "rebalance": "TÁI CÂN BẰNG",
- "reports": "BÁO CÁO",
- "alerts": "CẢNH BÁO",
- "sectors": "NGÀNH",
- "help": "TRỢ GIÚP"
- },
- "sidebar": {
- "portfolios": "DANH MỤC",
- "loading": "Đang tải danh mục...",
- "noPortfolios": "Chưa có danh mục.",
- "clickCreate": "Nhấp DANH MỤC MỚI để tạo.",
- "owner": "Chủ sở hữu",
- "currency": "Tiền tệ"
- },
- "content": {
- "selectOrCreate": "Chọn danh mục hoặc tạo mới để bắt đầu",
- "loadingData": "Đang tải dữ liệu danh mục...",
- "comingSoon": "sắp có..."
- },
- "modals": {
- "createNew": "TẠO DANH MỤC MỚI",
- "portfolioName": "TÊN DANH MỤC",
- "owner": "CHỦ SỞ HỮU",
- "currency": "TIỀN TỆ",
- "cancel": "HỦY",
- "create": "TẠO",
- "addAssetTitle": "THÊM TÀI SẢN VÀO DANH MỤC",
- "sellAssetTitle": "BÁN TÀI SẢN",
- "symbol": "MÃ",
- "quantity": "SỐ LƯỢNG",
- "price": "GIÁ",
- "add": "THÊM",
- "sell": "BÁN"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | Theo dõi thời gian thực với tích hợp yfinance",
- "lastUpdated": "Cập Nhật Lần Cuối",
- "connected": "ĐÃ KẾT NỐI"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "TẠO DANH MỤC MỚI",
+ "portfolioName": "TÊN DANH MỤC",
+ "owner": "CHỦ SỞ HỮU",
+ "currency": "TIỀN TỆ",
+ "cancel": "HỦY",
+ "create": "TẠO",
+ "addAssetTitle": "THÊM TÀI SẢN VÀO DANH MỤC",
+ "sellAssetTitle": "BÁN TÀI SẢN",
+ "symbol": "MÃ",
+ "quantity": "SỐ LƯỢNG",
+ "price": "GIÁ",
+ "add": "THÊM",
+ "sell": "BÁN"
+ },
+ "extracted": {
+ "areYouSureYou": "[VI] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/vi/reportBuilder.json b/fincept-terminal-desktop/public/locales/vi/reportBuilder.json
index 7d4935af5..5f53c15ac 100644
--- a/fincept-terminal-desktop/public/locales/vi/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/vi/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[VI] Load",
"save": "[VI] Save",
- "saving": "[VI] Saving...",
- "exportPdf": "[VI] Export PDF",
- "generating": "[VI] Generating..."
+ "saving": "[VI] Saving..."
},
"components": {
"title": "[VI] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/vi/settings.json b/fincept-terminal-desktop/public/locales/vi/settings.json
index bed7a9ec2..f513d8111 100644
--- a/fincept-terminal-desktop/public/locales/vi/settings.json
+++ b/fincept-terminal-desktop/public/locales/vi/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "Bố cục tab",
"appearance": "Vẻ bề ngoài",
"language": "Ngôn ngữ",
- "storage": "Bộ nhớ & Bộ nhớ đệm"
+ "storage": "Bộ nhớ & Bộ nhớ đệm",
+ "notifications": "[VI] Notifications"
},
"credentials": {
"title": "QUẢN LÝ CHỨNG NHẬN API",
@@ -46,7 +47,31 @@
"saveConfig": "LƯU CẤU HÌNH",
"reset": "CÀI LẠI",
"saveSuccess": "Đã lưu thành công giao diện thiết bị đầu cuối và ánh xạ khóa",
- "resetSuccess": "Đặt lại về giao diện mặc định và ánh xạ phím"
+ "resetSuccess": "Đặt lại về giao diện mặc định và ánh xạ phím",
+ "customColors": "[VI] Custom Colors",
+ "customColorsTitle": "[VI] CUSTOM COLORS",
+ "colorPrimary": "[VI] Primary",
+ "colorSecondary": "[VI] Secondary",
+ "colorSuccess": "[VI] Success",
+ "colorAlert": "[VI] Alert",
+ "colorWarning": "[VI] Warning",
+ "colorInfo": "[VI] Info",
+ "colorAccent": "[VI] Accent",
+ "colorPurple": "[VI] Purple",
+ "colorText": "[VI] Text",
+ "colorTextMuted": "[VI] Text Muted",
+ "colorBackground": "[VI] Background",
+ "colorPanel": "[VI] Panel",
+ "layoutSpacing": "[VI] LAYOUT & SPACING",
+ "contentDensity": "[VI] CONTENT DENSITY",
+ "borderRadius": "[VI] BORDER RADIUS",
+ "borderStyle": "[VI] BORDER STYLE",
+ "lineHeight": "[VI] LINE HEIGHT",
+ "letterSpacing": "[VI] LETTER SPACING",
+ "effects": "[VI] EFFECTS",
+ "widgetOpacity": "[VI] WIDGET OPACITY",
+ "enableGlow": "[VI] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[VI] GLOW INTENSITY"
},
"stockSymbols": {
"title": "Cơ sở dữ liệu ký hiệu chứng khoán",
@@ -65,17 +90,8 @@
"tip": "MẸO: Kéo các tab để sắp xếp lại chúng. Sử dụng các nút mũi tên để di chuyển các tab giữa phần tiêu đề và menu. Các thay đổi được lưu tự động."
},
"llm": {
- "title": "CẤU HÌNH LLM",
- "description": "Định cấu hình các mô hình và nhà cung cấp AI",
"connected": "ĐÃ KẾT NỐI",
- "disconnected": "ĐÃ NGẮT KẾT NỐI",
- "provider": "NHÀ CUNG CẤP AI",
- "globalSettings": "CÀI ĐẶT AI TOÀN CẦU",
- "temperature": "NHIỆT ĐỘ",
- "maxTokens": "TỐI ĐA",
- "systemPrompt": "NHẮC NHỞ HỆ THỐNG",
- "modelLibrary": "THƯ VIỆN MẪU",
- "multiModelConfigs": "Cấu hình đa mô hình"
+ "disconnected": "ĐÃ NGẮT KẾT NỐI"
},
"buttons": {
"save": "CỨU",
@@ -86,5 +102,18 @@
"database": "Cơ sở dữ liệu: SQLite",
"storage": "Lưu trữ: Dựa trên tệp",
"secureStorage": "Tất cả dữ liệu được lưu trữ an toàn trong fincept_terminal.db"
+ },
+ "notifications": {
+ "title": "[VI] NOTIFICATION PROVIDERS",
+ "description": "[VI] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[VI] Event Filters",
+ "eventFilterDescription": "[VI] Choose which notification types to forward to external providers.",
+ "providers": "[VI] Providers",
+ "enabled": "[VI] Enabled",
+ "disabled": "[VI] Disabled",
+ "testButton": "[VI] TEST",
+ "testSuccess": "[VI] Test notification sent successfully!",
+ "testFailed": "[VI] Failed to send test notification. Check your configuration.",
+ "saved": "[VI] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/vi/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/vi/surfaceAnalytics.json
new file mode 100644
index 000000000..79557066f
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/vi/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[VI] SURFACE ANALYTICS",
+ "initializing": "[VI] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[VI] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[VI] VOL SURFACE",
+ "correlation": "[VI] CORRELATION",
+ "yieldCurve": "[VI] YIELD CURVE",
+ "pca": "[VI] PCA FACTORS"
+ },
+ "demoData": "[VI] DEMO DATA",
+ "demoDataSynthetic": "[VI] DEMO DATA (synthetic)",
+ "synthetic": "[VI] SYNTHETIC",
+ "manual": "[VI] MANUAL",
+ "error": "[VI] ERROR",
+ "ready": "[VI] READY",
+ "metrics": "[VI] Metrics",
+ "updated": "[VI] Updated",
+ "clickRefresh": "[VI] Click REFRESH to load data",
+ "refresh": "[VI] REFRESH",
+ "noApiKey": "[VI] NO API KEY",
+ "lastUpdate": "[VI] LAST UPDATE",
+ "loadingData": "[VI] LOADING DATA...",
+ "noDataLoaded": "[VI] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[VI] IV SURFACE METRICS",
+ "correlationMetrics": "[VI] CORRELATION METRICS",
+ "yieldCurveMetrics": "[VI] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[VI] PCA FACTOR METRICS",
+ "dataInfo": "[VI] DATA INFO",
+ "source": "[VI] SOURCE",
+ "frequency": "[VI] FREQUENCY",
+ "quality": "[VI] QUALITY",
+ "correlationScale": "[VI] CORRELATION SCALE",
+ "strongPositive": "[VI] Strong Positive (0.7-1.0)",
+ "neutral": "[VI] Neutral (0.3-0.7)",
+ "strongNegative": "[VI] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[VI] IV INTERPRETATION",
+ "highIv": "[VI] High IV = Expensive Options",
+ "lowIv": "[VI] Low IV = Cheap Options",
+ "skew": "[VI] Skew = Put/Call IV Diff",
+ "termStructure": "[VI] Term Structure = Time Effect",
+ "pcaInterpretation": "[VI] PCA INTERPRETATION",
+ "pc1": "[VI] PC1 = Market Factor",
+ "pc2": "[VI] PC2 = Size/Value Factor",
+ "pc3": "[VI] PC3 = Sector Rotation",
+ "higherVar": "[VI] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[VI] STRIKE",
+ "dte": "[VI] DTE",
+ "iv": "[VI] IV",
+ "correlation": "[VI] CORRELATION",
+ "maturity": "[VI] MATURITY",
+ "yield": "[VI] YIELD",
+ "loading": "[VI] LOADING",
+ "strikePrice": "[VI] STRIKE PRICE",
+ "daysToExpiry": "[VI] DAYS TO EXPIRY",
+ "impliedVol": "[VI] IMPLIED VOL (%)",
+ "assetPairIndex": "[VI] ASSET PAIR INDEX",
+ "timeDays": "[VI] TIME (DAYS)",
+ "correlationCoeff": "[VI] CORRELATION COEFF",
+ "maturityMonths": "[VI] MATURITY (MONTHS)",
+ "historicalDays": "[VI] HISTORICAL DAYS",
+ "yieldPercent": "[VI] YIELD (%)",
+ "principalComponent": "[VI] PRINCIPAL COMPONENT",
+ "assetIndex": "[VI] ASSET INDEX",
+ "factorLoading": "[VI] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[VI] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[VI] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[VI] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[VI] DAY ROLLING",
+ "yieldCurve": "[VI] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[VI] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[VI] FAILED TO LOAD DATA",
+ "authFailed": "[VI] AUTHENTICATION FAILED",
+ "authFailedHelp": "[VI] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[VI] ACCESS DENIED",
+ "accessDeniedHelp": "[VI] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[VI] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[VI] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[VI] DATA TIMEFRAME",
+ "schema": "[VI] Schema",
+ "description": "[VI] Description",
+ "recordsPerDay": "[VI] Records/Day",
+ "highFrequencyWarning": "[VI] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[VI] Data Volume"
+ },
+ "settings": {
+ "title": "[VI] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[VI] DATABENTO API KEY",
+ "configured": "[VI] CONFIGURED",
+ "invalidFormat": "[VI] INVALID FORMAT",
+ "apiKeyConfigured": "[VI] API key is configured (db-*****)",
+ "remove": "[VI] REMOVE",
+ "enterApiKey": "[VI] Enter your Databento API key (db-*****)",
+ "save": "[VI] SAVE",
+ "saving": "[VI] SAVING...",
+ "getApiKeyFrom": "[VI] Get your API key from",
+ "dashboardApiKeys": "[VI] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[VI] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[VI] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[VI] CORRELATION ASSETS",
+ "addSymbol": "[VI] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[VI] Reset to defaults",
+ "historicalDateRange": "[VI] HISTORICAL DATE RANGE",
+ "start": "[VI] Start",
+ "end": "[VI] End",
+ "autoRefreshInterval": "[VI] AUTO REFRESH INTERVAL",
+ "manualOnly": "[VI] Manual Only",
+ "every1min": "[VI] Every 1 minute",
+ "every5min": "[VI] Every 5 minutes",
+ "every15min": "[VI] Every 15 minutes",
+ "every1hour": "[VI] Every 1 hour",
+ "browseDatasets": "[VI] BROWSE DATASETS",
+ "costEstimator": "[VI] COST ESTIMATOR",
+ "referenceData": "[VI] REFERENCE DATA",
+ "orderBook": "[VI] ORDER BOOK",
+ "liveStreaming": "[VI] LIVE STREAMING",
+ "active": "[VI] ACTIVE",
+ "futuresCme": "[VI] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[VI] BATCH DOWNLOADS",
+ "additionalSchemas": "[VI] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[VI] TRADES, IMBALANCE, STATUS",
+ "cancel": "[VI] CANCEL",
+ "saveChanges": "[VI] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[VI] BATCH DOWNLOADS",
+ "newBatchJob": "[VI] NEW BATCH JOB",
+ "dataset": "[VI] Dataset",
+ "schema": "[VI] Schema",
+ "symbolsCommaSeparated": "[VI] Symbols (comma-separated)",
+ "startDate": "[VI] Start Date",
+ "endDate": "[VI] End Date",
+ "encoding": "[VI] Encoding",
+ "compression": "[VI] Compression",
+ "submitJob": "[VI] SUBMIT JOB",
+ "noBatchJobs": "[VI] No batch jobs found. Click + to create one.",
+ "records": "[VI] records",
+ "download": "[VI] Download",
+ "files": "[VI] FILES",
+ "jobsExpireNotice": "[VI] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[VI] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[VI] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[VI] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[VI] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[VI] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[VI] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[VI] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[VI] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[VI] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[VI] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[VI] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[VI] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[VI] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[VI] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[VI] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[VI] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[VI] [EN] common.or",
+ "note": "[VI] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/vi/tabs.json b/fincept-terminal-desktop/public/locales/vi/tabs.json
index a24ab0e3a..223e0280e 100644
--- a/fincept-terminal-desktop/public/locales/vi/tabs.json
+++ b/fincept-terminal-desktop/public/locales/vi/tabs.json
@@ -5,29 +5,7 @@
"news": "Tin tức",
"portfolio": "Danh mục",
"backtesting": "Backtesting",
- "watchlist": "Theo dõi",
- "research": "Nghiên cứu",
- "screener": "Bộ lọc",
"chat": "AI Chat",
- "agents": "Đại lý",
- "settings": "Cài đặt",
"profile": "Hồ sơ"
- },
- "functionKeys": {
- "f1": "BẢNG",
- "f2": "TTNG",
- "f3": "TIN",
- "f4": "DMUC",
- "f5": "BKTS",
- "f6": "TDOI",
- "f7": "NCUU",
- "f8": "BLOC",
- "f9": "GDCH",
- "f10": "AI",
- "f11": "FULL",
- "f12": "PROF"
- },
- "labels": {
- "moreTabs": "Thêm tab trong menu thanh công cụ"
}
}
diff --git a/fincept-terminal-desktop/public/locales/vi/watchlist.json b/fincept-terminal-desktop/public/locales/vi/watchlist.json
index 1704e2795..2c0616a12 100644
--- a/fincept-terminal-desktop/public/locales/vi/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/vi/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "DANH SÁCH THEO DÕI",
- "header": {
- "export": "XUẤT",
- "updating": "ĐANG CẬP NHẬT",
- "live": "TRỰC TIẾP"
- },
"sidebar": {
- "groups": "NHÓM DANH SÁCH",
- "new": "MỚI",
"noWatchlists": "Chưa có danh sách nào.",
"clickNew": "Nhấn MỚI để tạo.",
- "stocks": "cổ phiếu",
- "marketMovers": "NGƯỜI DẪN ĐẦU",
- "gainer": "TĂNG",
- "loser": "GIẢM",
- "volumeLeaders": "KHỐI LƯỢNG CAO NHẤT"
- },
- "emptyState": {
- "selectWatchlist": "Chọn danh sách hoặc tạo mới để bắt đầu"
- },
- "list": {
- "symbols": "Mã"
+ "stocks": "cổ phiếu"
}
}
diff --git a/fincept-terminal-desktop/public/locales/zh/codeEditor.json b/fincept-terminal-desktop/public/locales/zh/codeEditor.json
index f55fc71db..764f0a640 100644
--- a/fincept-terminal-desktop/public/locales/zh/codeEditor.json
+++ b/fincept-terminal-desktop/public/locales/zh/codeEditor.json
@@ -1,29 +1,60 @@
{
- "title": "代码编辑器",
"header": {
- "packages": "包"
+ "finscriptIde": "[ZH] FINSCRIPT IDE"
},
"toolbar": {
"newFile": "新建文件",
- "new": "新建",
- "open": "打开",
- "save": "保存",
"run": "运行代码",
"running": "运行中...",
- "runAll": "全部运行",
- "history": "历史"
+ "toggleExplorer": "[ZH] Toggle Explorer (Ctrl+B)",
+ "openFile": "[ZH] Open File",
+ "saveShortcut": "[ZH] Save (Ctrl+S)",
+ "findShortcut": "[ZH] Find (Ctrl+F)",
+ "runShortcut": "[ZH] Run (Ctrl+Enter)"
},
"tabs": {
"notebook": "JUPYTER笔记本",
"finscript": "FINSCRIPT编辑器"
},
- "packages": {
- "clickToLoad": "点击加载包...",
- "load": "加载包"
+ "explorer": {
+ "title": "[ZH] EXPLORER",
+ "openFiles": "[ZH] OPEN FILES",
+ "examples": "[ZH] EXAMPLES",
+ "runHistory": "[ZH] RUN HISTORY",
+ "finscriptEngine": "[ZH] FinScript Engine"
},
- "history": {
- "title": "笔记本历史",
- "loading": "加载历史中...",
- "empty": "暂无笔记本历史"
+ "output": {
+ "title": "[ZH] OUTPUT",
+ "success": "[ZH] SUCCESS",
+ "error": "[ZH] ERROR",
+ "executing": "[ZH] EXECUTING FINSCRIPT...",
+ "noOutput": "[ZH] No output yet",
+ "pressToRun": "[ZH] Press Ctrl+Enter to run",
+ "completed": "[ZH] COMPLETED",
+ "failed": "[ZH] FAILED",
+ "signals": "[ZH] signals",
+ "clear": "[ZH] CLEAR",
+ "errors": "[ZH] ERRORS",
+ "signalsSection": "[ZH] SIGNALS",
+ "outputSection": "[ZH] OUTPUT",
+ "charts": "[ZH] CHARTS"
+ },
+ "chart": {
+ "ohlc": "[ZH] OHLC",
+ "histogram": "[ZH] Histogram",
+ "line": "[ZH] Line",
+ "points": "[ZH] points"
+ },
+ "statusBar": {
+ "modified": "[ZH] MODIFIED",
+ "showOutput": "[ZH] SHOW OUTPUT",
+ "encoding": "[ZH] UTF-8",
+ "spaces": "[ZH] 4 Spaces",
+ "runShortcut": "[ZH] Ctrl+Enter: Run",
+ "lines": "[ZH] lines"
+ },
+ "dialogs": {
+ "closeUnsaved": "[ZH] Close file without saving?",
+ "unsavedChanges": "[ZH] You have unsaved changes."
}
}
diff --git a/fincept-terminal-desktop/public/locales/zh/common.json b/fincept-terminal-desktop/public/locales/zh/common.json
index 75fac6a20..6c4e1cf55 100644
--- a/fincept-terminal-desktop/public/locales/zh/common.json
+++ b/fincept-terminal-desktop/public/locales/zh/common.json
@@ -1,25 +1,4 @@
{
- "appName": "Fincept Terminal",
"loading": "加载中...",
- "error": "错误",
- "success": "成功",
- "save": "保存",
- "cancel": "取消",
- "delete": "删除",
- "edit": "编辑",
- "add": "添加",
- "search": "搜索",
- "filter": "筛选",
- "back": "返回",
- "next": "下一步",
- "previous": "上一步",
- "submit": "提交",
- "close": "关闭",
- "open": "打开",
- "yes": "是",
- "no": "否",
- "ok": "确定",
- "confirm": "确认",
- "language": "语言",
- "selectLanguage": "选择语言"
-}
\ No newline at end of file
+ "settings": "[ZH] Settings"
+}
diff --git a/fincept-terminal-desktop/public/locales/zh/dashboard.json b/fincept-terminal-desktop/public/locales/zh/dashboard.json
index a0356f518..6cc8c25ca 100644
--- a/fincept-terminal-desktop/public/locales/zh/dashboard.json
+++ b/fincept-terminal-desktop/public/locales/zh/dashboard.json
@@ -1,18 +1,6 @@
{
- "header": {
- "title": "可定制的仪表板",
- "live": "居住",
- "widgets": "小部件"
- },
- "buttons": {
- "addWidget": "添加小部件",
- "saveLayout": "保存布局",
- "reset": "重置",
- "help": "帮助"
- },
"widgets": {
"loading": "加载中...",
- "error": "错误",
"globalIndices": "全球指数 - 前 12 名",
"forex": "外汇 - 主要货币对",
"crypto": "加密货币",
@@ -20,8 +8,6 @@
"news": "消息",
"forum": "论坛",
"watchlist": "观看列表",
- "maritimeIntelligence": "海事情报",
- "unknown": "未知的小部件类型",
"index": "指数",
"symbol": "象征",
"price": "价格",
@@ -38,41 +24,22 @@
"pair": "一对",
"rate": "速度",
"commodity": "商品",
- "globe3D": "3D地球仪",
- "vessels": "船舶",
- "routes": "航线",
- "vol24h": "24小时音量",
- "topTradeCorridors": "顶级贸易走廊",
- "ships": "船舶",
- "marketNews": "市场新闻",
- "secPressReleases": "美国证券交易委员会新闻稿",
- "cryptoNews": "加密新闻",
- "trendingForum": "热门论坛",
- "techStocks": "科技股"
- },
- "tips": {
- "drag": "拖动小部件以重新排列",
- "resize": "从右下角开始调整大小",
- "remove": "使用 X 按钮删除小部件",
- "responsive": "响应式布局 - 使用全宽"
- },
- "loading": {
- "title": "初始化仪表板",
- "description": "设置数据库缓存以加快数据加载速度...",
- "note": "首次启动时这只需要一点时间"
- },
- "empty": {
- "noWidgets": "仪表板上没有小部件",
- "addFirst": "添加您的第一个小部件"
- },
- "status": {
- "version": "Fincept可定制仪表板v2.0.0 |拖放工作区",
- "layout": "布局",
- "custom": "风俗",
- "empty": "空的",
- "active": "积极的",
- "cache": "缓存:已启用",
- "label": "地位"
+ "noActiveMarkets": "[ZH] No active markets found",
+ "indicator": "[ZH] INDICATOR",
+ "value": "[ZH] VALUE",
+ "chg": "[ZH] CHG",
+ "overallRisk": "[ZH] OVERALL RISK",
+ "openEconomicsTab": "[ZH] Open Economics Tab",
+ "openGeopoliticsTab": "[ZH] Open Geopolitics Tab",
+ "openPolymarketTab": "[ZH] Open Polymarket Tab",
+ "noPortfolioFound": "[ZH] No portfolio found",
+ "createPortfolioHint": "[ZH] Create one in Portfolio tab",
+ "openPortfolioTab": "[ZH] Open Portfolio Tab",
+ "action": "[ZH] ACTION",
+ "markets": "[ZH] MARKETS",
+ "performanceTracker": "[ZH] PERFORMANCE TRACKER",
+ "totalPnL": "[ZH] TOTAL P&L",
+ "viewDetailedAnalytics": "[ZH] View Detailed Analytics"
},
"messages": {
"layoutSaved": "仪表板布局已保存!",
diff --git a/fincept-terminal-desktop/public/locales/zh/geopolitics.json b/fincept-terminal-desktop/public/locales/zh/geopolitics.json
index e0c85341c..2f4817b8e 100644
--- a/fincept-terminal-desktop/public/locales/zh/geopolitics.json
+++ b/fincept-terminal-desktop/public/locales/zh/geopolitics.json
@@ -1,6 +1,66 @@
{
- "title": "地缘政治",
"messages": {
- "loading": "加载地缘政治数据..."
+ "retry": "[ZH] RETRY"
+ },
+ "header": {
+ "prefix": "[ZH] GEO>",
+ "title": "[ZH] GEOPOLITICAL CONFLICT MONITOR",
+ "events": "[ZH] EVENTS"
+ },
+ "status": {
+ "stale": "[ZH] STALE",
+ "loading": "[ZH] LOADING...",
+ "error": "[ZH] ERROR:"
+ },
+ "filters": {
+ "country": "[ZH] Country...",
+ "cities": "[ZH] Cities...",
+ "category": "[ZH] Category...",
+ "apply": "[ZH] APPLY",
+ "clear": "[ZH] CLEAR",
+ "clearAllCities": "[ZH] Clear all cities",
+ "selectedLabel": "[ZH] Selected:"
+ },
+ "panel": {
+ "title": "[ZH] INFO PANEL",
+ "expand": "[ZH] Expand panel",
+ "collapse": "[ZH] Collapse panel",
+ "eventsLoaded": "[ZH] EVENTS LOADED",
+ "onMapVisualization": "[ZH] on map visualization",
+ "topCategories": "[ZH] TOP CATEGORIES",
+ "topCountries": "[ZH] TOP COUNTRIES",
+ "eventDetails": "[ZH] EVENT DETAILS",
+ "close": "[ZH] CLOSE"
+ },
+ "eventDetails": {
+ "country": "[ZH] Country:",
+ "city": "[ZH] City:",
+ "keywords": "[ZH] Keywords:",
+ "coords": "[ZH] Coords:",
+ "date": "[ZH] Date:",
+ "source": "[ZH] Source:",
+ "viewArticle": "[ZH] View Article"
+ },
+ "legend": {
+ "title": "[ZH] EVENT CATEGORIES",
+ "armedConflict": "[ZH] Armed Conflict",
+ "terrorism": "[ZH] Terrorism",
+ "protests": "[ZH] Protests",
+ "civilianViolence": "[ZH] Civilian Violence",
+ "riots": "[ZH] Riots",
+ "politicalViolence": "[ZH] Political Violence",
+ "crisis": "[ZH] Crisis",
+ "explosions": "[ZH] Explosions",
+ "strategic": "[ZH] Strategic",
+ "unclassified": "[ZH] Unclassified"
+ },
+ "footer": {
+ "tabName": "[ZH] GEOPOLITICAL CONFLICT MONITOR",
+ "labelEvents": "[ZH] EVENTS",
+ "labelEngine": "[ZH] ENGINE",
+ "engineValue": "[ZH] DECK.GL v9.2",
+ "labelSource": "[ZH] SOURCE",
+ "sourceValue": "[ZH] NEWS-EVENTS API",
+ "labelSelected": "[ZH] SELECTED"
}
}
diff --git a/fincept-terminal-desktop/public/locales/zh/markets.json b/fincept-terminal-desktop/public/locales/zh/markets.json
index 0e71b5a2f..e13aca854 100644
--- a/fincept-terminal-desktop/public/locales/zh/markets.json
+++ b/fincept-terminal-desktop/public/locales/zh/markets.json
@@ -9,13 +9,9 @@
"percentChange": "涨跌%",
"high": "最高",
"low": "最低",
- "loading": "加载中...",
"noData": "无数据",
"refresh": "刷新",
"auto": "自动",
"on": "开",
- "off": "关",
- "lastUpdate": "最后更新",
- "updating": "更新中",
- "live": "实时"
+ "off": "关"
}
diff --git a/fincept-terminal-desktop/public/locales/zh/news.json b/fincept-terminal-desktop/public/locales/zh/news.json
index e452abf78..101b66aa3 100644
--- a/fincept-terminal-desktop/public/locales/zh/news.json
+++ b/fincept-terminal-desktop/public/locales/zh/news.json
@@ -1,32 +1,63 @@
{
"title": "FINCEPT 终端专业新闻",
"header": {
- "liveFeed": "实时动态",
- "live": "实时",
- "refresh": "刷新",
- "updating": "更新中...",
- "alerts": "提醒",
- "sources": "来源",
- "status": "状态",
- "demoMode": "演示模式",
- "articles": "文章",
- "activeSources": "活跃来源"
- },
- "autoRefresh": {
- "title": "自动刷新间隔",
- "minute": "分钟",
- "minutes": "分钟"
+ "refresh": "刷新"
},
"messages": {
- "loadingFeeds": "加载新闻源...",
- "breaking": "突发"
- },
- "feeds": {
- "primary": "[ZH] PRIMARY NEWS FEED",
- "secondary": "[ZH] SECONDARY NEWS FEED",
- "additional": "[ZH] ADDITIONAL HEADLINES"
+ "loadingFeedsModal": "[ZH] Loading feeds...",
+ "failedToLoad": "[ZH] Failed to load RSS feeds",
+ "noCustomFeeds": "[ZH] No custom feeds yet. Add your first RSS feed above.",
+ "allFeedsDeleted": "[ZH] All feeds have been deleted. Add a new feed or restore defaults.",
+ "defaultFeedsInfo": "[ZH] Default RSS feeds included with Fincept Terminal. Toggle or remove as needed."
},
- "analytics": {
- "title": "[ZH] REAL-TIME NEWS ANALYTICS"
+ "rssSettings": {
+ "title": "[ZH] RSS FEED SETTINGS",
+ "subtitle": "[ZH] MANAGE YOUR NEWS SOURCES",
+ "close": "[ZH] CLOSE",
+ "myFeeds": "[ZH] MY FEEDS",
+ "defaultFeeds": "[ZH] DEFAULT FEEDS",
+ "noFeedsAvailable": "[ZH] NO RSS FEEDS AVAILABLE",
+ "allDefaultsDeleted": "[ZH] ALL DEFAULT FEEDS DELETED",
+ "addNewFeed": "[ZH] ADD NEW FEED",
+ "addNewRssFeed": "[ZH] ADD NEW RSS FEED",
+ "editRssFeed": "[ZH] EDIT RSS FEED",
+ "restoreDefaults": "[ZH] RESTORE DEFAULTS",
+ "restoreAll": "[ZH] RESTORE ALL",
+ "restoreAllDefaultFeeds": "[ZH] RESTORE ALL DEFAULT FEEDS",
+ "displayName": "[ZH] DISPLAY NAME",
+ "sourceName": "[ZH] SOURCE NAME (SHORT)",
+ "feedUrl": "[ZH] RSS FEED URL",
+ "category": "[ZH] CATEGORY",
+ "region": "[ZH] REGION",
+ "required": "[ZH] *",
+ "testUrl": "[ZH] TEST URL",
+ "testing": "[ZH] TESTING...",
+ "valid": "[ZH] VALID",
+ "cancel": "[ZH] CANCEL",
+ "saving": "[ZH] SAVING...",
+ "addFeed": "[ZH] ADD FEED",
+ "updateFeed": "[ZH] UPDATE FEED",
+ "on": "[ZH] ON",
+ "off": "[ZH] OFF",
+ "default": "[ZH] DEFAULT",
+ "total": "[ZH] TOTAL",
+ "active": "[ZH] ACTIVE",
+ "custom": "[ZH] CUSTOM",
+ "placeholders": {
+ "displayName": "[ZH] e.g., Bloomberg Markets",
+ "sourceName": "[ZH] e.g., BLOOMBERG",
+ "feedUrl": "[ZH] https://example.com/rss/feed"
+ },
+ "errors": {
+ "nameRequired": "[ZH] Name is required",
+ "sourceRequired": "[ZH] Source name is required",
+ "invalidUrl": "[ZH] Please enter a valid URL",
+ "invalidRss": "[ZH] URL does not appear to be a valid RSS feed",
+ "testFailed": "[ZH] Failed to test URL"
+ },
+ "confirmDelete": {
+ "title": "[ZH] Delete this RSS feed?",
+ "message": "[ZH] This action cannot be undone."
+ }
}
}
diff --git a/fincept-terminal-desktop/public/locales/zh/portfolio.json b/fincept-terminal-desktop/public/locales/zh/portfolio.json
index 9d7c89dff..302aac6d5 100644
--- a/fincept-terminal-desktop/public/locales/zh/portfolio.json
+++ b/fincept-terminal-desktop/public/locales/zh/portfolio.json
@@ -1,63 +1,20 @@
{
- "title": "FINCEPT 投资组合管理器",
- "header": {
- "live": "实时",
- "updating": "更新中",
- "newPortfolio": "新建组合",
- "refresh": "刷新",
- "exportCsv": "导出CSV"
- },
- "summary": {
- "totalValue": "总价值",
- "dayPnl": "当日盈亏",
- "totalPnl": "总盈亏",
- "positions": "持仓"
- },
- "views": {
- "positions": "持仓",
- "addAsset": "添加资产",
- "sellAsset": "卖出资产",
- "analytics": "分析",
- "history": "历史",
- "activeMgmt": "主动管理",
- "performance": "业绩",
- "rebalance": "再平衡",
- "reports": "报告",
- "alerts": "提醒",
- "sectors": "板块",
- "help": "帮助"
- },
- "sidebar": {
- "portfolios": "投资组合",
- "loading": "加载组合...",
- "noPortfolios": "暂无组合。",
- "clickCreate": "点击新建组合创建一个。",
- "owner": "所有者",
- "currency": "货币"
- },
- "content": {
- "selectOrCreate": "选择组合或创建新组合开始",
- "loadingData": "加载组合数据...",
- "comingSoon": "即将推出..."
- },
- "modals": {
- "createNew": "创建新组合",
- "portfolioName": "组合名称",
- "owner": "所有者",
- "currency": "货币",
- "cancel": "取消",
- "create": "创建",
- "addAssetTitle": "添加资产到组合",
- "sellAssetTitle": "卖出资产",
- "symbol": "代码",
- "quantity": "数量",
- "price": "价格",
- "add": "添加",
- "sell": "卖出"
- },
- "status": {
- "version": "Fincept Portfolio Manager v2.1.0 | yfinance集成实时追踪",
- "lastUpdated": "最后更新",
- "connected": "已连接"
- }
-}
\ No newline at end of file
+ "modals": {
+ "createNew": "创建新组合",
+ "portfolioName": "组合名称",
+ "owner": "所有者",
+ "currency": "货币",
+ "cancel": "取消",
+ "create": "创建",
+ "addAssetTitle": "添加资产到组合",
+ "sellAssetTitle": "卖出资产",
+ "symbol": "代码",
+ "quantity": "数量",
+ "price": "价格",
+ "add": "添加",
+ "sell": "卖出"
+ },
+ "extracted": {
+ "areYouSureYou": "[ZH] Are you sure you want to delete this portfolio? This action cannot be undone."
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/zh/reportBuilder.json b/fincept-terminal-desktop/public/locales/zh/reportBuilder.json
index dc83ba453..3cba803ad 100644
--- a/fincept-terminal-desktop/public/locales/zh/reportBuilder.json
+++ b/fincept-terminal-desktop/public/locales/zh/reportBuilder.json
@@ -3,9 +3,7 @@
"header": {
"load": "[ZH] Load",
"save": "[ZH] Save",
- "saving": "[ZH] Saving...",
- "exportPdf": "[ZH] Export PDF",
- "generating": "[ZH] Generating..."
+ "saving": "[ZH] Saving..."
},
"components": {
"title": "[ZH] ADD COMPONENTS"
diff --git a/fincept-terminal-desktop/public/locales/zh/settings.json b/fincept-terminal-desktop/public/locales/zh/settings.json
index 6783719dd..d5fb6ee1f 100644
--- a/fincept-terminal-desktop/public/locales/zh/settings.json
+++ b/fincept-terminal-desktop/public/locales/zh/settings.json
@@ -10,7 +10,8 @@
"tabLayout": "选项卡布局",
"appearance": "外貌",
"language": "语言",
- "storage": "存储和缓存"
+ "storage": "存储和缓存",
+ "notifications": "[ZH] Notifications"
},
"credentials": {
"title": "API 凭证管理",
@@ -46,7 +47,31 @@
"saveConfig": "保存配置",
"reset": "重置",
"saveSuccess": "终端外观和按键映射已成功保存",
- "resetSuccess": "重置为默认外观和键映射"
+ "resetSuccess": "重置为默认外观和键映射",
+ "customColors": "[ZH] Custom Colors",
+ "customColorsTitle": "[ZH] CUSTOM COLORS",
+ "colorPrimary": "[ZH] Primary",
+ "colorSecondary": "[ZH] Secondary",
+ "colorSuccess": "[ZH] Success",
+ "colorAlert": "[ZH] Alert",
+ "colorWarning": "[ZH] Warning",
+ "colorInfo": "[ZH] Info",
+ "colorAccent": "[ZH] Accent",
+ "colorPurple": "[ZH] Purple",
+ "colorText": "[ZH] Text",
+ "colorTextMuted": "[ZH] Text Muted",
+ "colorBackground": "[ZH] Background",
+ "colorPanel": "[ZH] Panel",
+ "layoutSpacing": "[ZH] LAYOUT & SPACING",
+ "contentDensity": "[ZH] CONTENT DENSITY",
+ "borderRadius": "[ZH] BORDER RADIUS",
+ "borderStyle": "[ZH] BORDER STYLE",
+ "lineHeight": "[ZH] LINE HEIGHT",
+ "letterSpacing": "[ZH] LETTER SPACING",
+ "effects": "[ZH] EFFECTS",
+ "widgetOpacity": "[ZH] WIDGET OPACITY",
+ "enableGlow": "[ZH] ENABLE GLOW EFFECTS",
+ "glowIntensity": "[ZH] GLOW INTENSITY"
},
"stockSymbols": {
"title": "股票代码数据库",
@@ -65,17 +90,8 @@
"tip": "提示:拖动选项卡可对其重新排序。使用箭头按钮在标题和菜单部分之间移动选项卡。更改会自动保存。"
},
"llm": {
- "title": "法学硕士配置",
- "description": "配置 AI 模型和提供者",
"connected": "连接",
- "disconnected": "已断开连接",
- "provider": "人工智能提供商",
- "globalSettings": "全局人工智能设置",
- "temperature": "温度",
- "maxTokens": "最大代币数",
- "systemPrompt": "系统提示符",
- "modelLibrary": "模型库",
- "multiModelConfigs": "多模型配置"
+ "disconnected": "已断开连接"
},
"buttons": {
"save": "节省",
@@ -86,5 +102,18 @@
"database": "数据库:SQLite",
"storage": "存储:基于文件",
"secureStorage": "所有数据都安全地存储在fincept_terminal.db中"
+ },
+ "notifications": {
+ "title": "[ZH] NOTIFICATION PROVIDERS",
+ "description": "[ZH] Configure external notification channels. App notifications will be forwarded to enabled providers.",
+ "eventFilters": "[ZH] Event Filters",
+ "eventFilterDescription": "[ZH] Choose which notification types to forward to external providers.",
+ "providers": "[ZH] Providers",
+ "enabled": "[ZH] Enabled",
+ "disabled": "[ZH] Disabled",
+ "testButton": "[ZH] TEST",
+ "testSuccess": "[ZH] Test notification sent successfully!",
+ "testFailed": "[ZH] Failed to send test notification. Check your configuration.",
+ "saved": "[ZH] Configuration saved"
}
}
diff --git a/fincept-terminal-desktop/public/locales/zh/surfaceAnalytics.json b/fincept-terminal-desktop/public/locales/zh/surfaceAnalytics.json
new file mode 100644
index 000000000..b5d44d015
--- /dev/null
+++ b/fincept-terminal-desktop/public/locales/zh/surfaceAnalytics.json
@@ -0,0 +1,175 @@
+{
+ "title": "[ZH] SURFACE ANALYTICS",
+ "initializing": "[ZH] INITIALIZING SURFACE ANALYTICS...",
+ "apiKeyRequiredStatus": "[ZH] API KEY REQUIRED | Configure Databento credentials or use demo data",
+ "charts": {
+ "volatility": "[ZH] VOL SURFACE",
+ "correlation": "[ZH] CORRELATION",
+ "yieldCurve": "[ZH] YIELD CURVE",
+ "pca": "[ZH] PCA FACTORS"
+ },
+ "demoData": "[ZH] DEMO DATA",
+ "demoDataSynthetic": "[ZH] DEMO DATA (synthetic)",
+ "synthetic": "[ZH] SYNTHETIC",
+ "manual": "[ZH] MANUAL",
+ "error": "[ZH] ERROR",
+ "ready": "[ZH] READY",
+ "metrics": "[ZH] Metrics",
+ "updated": "[ZH] Updated",
+ "clickRefresh": "[ZH] Click REFRESH to load data",
+ "refresh": "[ZH] REFRESH",
+ "noApiKey": "[ZH] NO API KEY",
+ "lastUpdate": "[ZH] LAST UPDATE",
+ "loadingData": "[ZH] LOADING DATA...",
+ "noDataLoaded": "[ZH] NO DATA LOADED",
+ "metricsPanel": {
+ "ivSurfaceMetrics": "[ZH] IV SURFACE METRICS",
+ "correlationMetrics": "[ZH] CORRELATION METRICS",
+ "yieldCurveMetrics": "[ZH] YIELD CURVE METRICS",
+ "pcaFactorMetrics": "[ZH] PCA FACTOR METRICS",
+ "dataInfo": "[ZH] DATA INFO",
+ "source": "[ZH] SOURCE",
+ "frequency": "[ZH] FREQUENCY",
+ "quality": "[ZH] QUALITY",
+ "correlationScale": "[ZH] CORRELATION SCALE",
+ "strongPositive": "[ZH] Strong Positive (0.7-1.0)",
+ "neutral": "[ZH] Neutral (0.3-0.7)",
+ "strongNegative": "[ZH] Strong Negative (-1.0-0.3)",
+ "ivInterpretation": "[ZH] IV INTERPRETATION",
+ "highIv": "[ZH] High IV = Expensive Options",
+ "lowIv": "[ZH] Low IV = Cheap Options",
+ "skew": "[ZH] Skew = Put/Call IV Diff",
+ "termStructure": "[ZH] Term Structure = Time Effect",
+ "pcaInterpretation": "[ZH] PCA INTERPRETATION",
+ "pc1": "[ZH] PC1 = Market Factor",
+ "pc2": "[ZH] PC2 = Size/Value Factor",
+ "pc3": "[ZH] PC3 = Sector Rotation",
+ "higherVar": "[ZH] Higher Var = More Explanatory"
+ },
+ "chart": {
+ "strike": "[ZH] STRIKE",
+ "dte": "[ZH] DTE",
+ "iv": "[ZH] IV",
+ "correlation": "[ZH] CORRELATION",
+ "maturity": "[ZH] MATURITY",
+ "yield": "[ZH] YIELD",
+ "loading": "[ZH] LOADING",
+ "strikePrice": "[ZH] STRIKE PRICE",
+ "daysToExpiry": "[ZH] DAYS TO EXPIRY",
+ "impliedVol": "[ZH] IMPLIED VOL (%)",
+ "assetPairIndex": "[ZH] ASSET PAIR INDEX",
+ "timeDays": "[ZH] TIME (DAYS)",
+ "correlationCoeff": "[ZH] CORRELATION COEFF",
+ "maturityMonths": "[ZH] MATURITY (MONTHS)",
+ "historicalDays": "[ZH] HISTORICAL DAYS",
+ "yieldPercent": "[ZH] YIELD (%)",
+ "principalComponent": "[ZH] PRINCIPAL COMPONENT",
+ "assetIndex": "[ZH] ASSET INDEX",
+ "factorLoading": "[ZH] FACTOR LOADING"
+ },
+ "chartTitles": {
+ "optionsIvSurface": "[ZH] OPTIONS - IMPLIED VOLATILITY SURFACE",
+ "ivSurface": "[ZH] IMPLIED VOLATILITY SURFACE",
+ "correlationMatrix": "[ZH] MULTI-ASSET CORRELATION MATRIX",
+ "dayRolling": "[ZH] DAY ROLLING",
+ "yieldCurve": "[ZH] U.S. TREASURY YIELD CURVE - HISTORICAL EVOLUTION",
+ "pcaFactors": "[ZH] PRINCIPAL COMPONENT ANALYSIS - FACTOR LOADINGS"
+ },
+ "errors": {
+ "failedToLoad": "[ZH] FAILED TO LOAD DATA",
+ "authFailed": "[ZH] AUTHENTICATION FAILED",
+ "authFailedHelp": "[ZH] Your Databento API key may be invalid, expired, or missing required permissions. Please verify your key at databento.com/portal/api-keys",
+ "accessDenied": "[ZH] ACCESS DENIED",
+ "accessDeniedHelp": "[ZH] Your API key may not have access to this dataset. OPRA options data requires specific permissions.",
+ "symbolNotFound": "[ZH] SYMBOL NOT FOUND",
+ "symbolNotFoundHelp": "[ZH] The requested symbol was not found. Try a different symbol like SPY, AAPL, or QQQ."
+ },
+ "timeframe": {
+ "dataTimeframe": "[ZH] DATA TIMEFRAME",
+ "schema": "[ZH] Schema",
+ "description": "[ZH] Description",
+ "recordsPerDay": "[ZH] Records/Day",
+ "highFrequencyWarning": "[ZH] High-frequency data generates many records and may incur higher costs",
+ "dataVolume": "[ZH] Data Volume"
+ },
+ "settings": {
+ "title": "[ZH] SURFACE ANALYTICS SETTINGS",
+ "databentoApiKey": "[ZH] DATABENTO API KEY",
+ "configured": "[ZH] CONFIGURED",
+ "invalidFormat": "[ZH] INVALID FORMAT",
+ "apiKeyConfigured": "[ZH] API key is configured (db-*****)",
+ "remove": "[ZH] REMOVE",
+ "enterApiKey": "[ZH] Enter your Databento API key (db-*****)",
+ "save": "[ZH] SAVE",
+ "saving": "[ZH] SAVING...",
+ "getApiKeyFrom": "[ZH] Get your API key from",
+ "dashboardApiKeys": "[ZH] Dashboard → API Keys",
+ "volatilitySurfaceSymbol": "[ZH] VOLATILITY SURFACE SYMBOL",
+ "searchSymbol": "[ZH] Search any symbol (e.g., MSFT, GOOGL, META)",
+ "correlationAssets": "[ZH] CORRELATION ASSETS",
+ "addSymbol": "[ZH] Add symbol (e.g., AAPL)",
+ "resetToDefaults": "[ZH] Reset to defaults",
+ "historicalDateRange": "[ZH] HISTORICAL DATE RANGE",
+ "start": "[ZH] Start",
+ "end": "[ZH] End",
+ "autoRefreshInterval": "[ZH] AUTO REFRESH INTERVAL",
+ "manualOnly": "[ZH] Manual Only",
+ "every1min": "[ZH] Every 1 minute",
+ "every5min": "[ZH] Every 5 minutes",
+ "every15min": "[ZH] Every 15 minutes",
+ "every1hour": "[ZH] Every 1 hour",
+ "browseDatasets": "[ZH] BROWSE DATASETS",
+ "costEstimator": "[ZH] COST ESTIMATOR",
+ "referenceData": "[ZH] REFERENCE DATA",
+ "orderBook": "[ZH] ORDER BOOK",
+ "liveStreaming": "[ZH] LIVE STREAMING",
+ "active": "[ZH] ACTIVE",
+ "futuresCme": "[ZH] FUTURES (CME GLOBEX)",
+ "batchDownloads": "[ZH] BATCH DOWNLOADS",
+ "additionalSchemas": "[ZH] ADDITIONAL SCHEMAS",
+ "tradesImbalanceStatus": "[ZH] TRADES, IMBALANCE, STATUS",
+ "cancel": "[ZH] CANCEL",
+ "saveChanges": "[ZH] SAVE CHANGES"
+ },
+ "batchDownload": {
+ "title": "[ZH] BATCH DOWNLOADS",
+ "newBatchJob": "[ZH] NEW BATCH JOB",
+ "dataset": "[ZH] Dataset",
+ "schema": "[ZH] Schema",
+ "symbolsCommaSeparated": "[ZH] Symbols (comma-separated)",
+ "startDate": "[ZH] Start Date",
+ "endDate": "[ZH] End Date",
+ "encoding": "[ZH] Encoding",
+ "compression": "[ZH] Compression",
+ "submitJob": "[ZH] SUBMIT JOB",
+ "noBatchJobs": "[ZH] No batch jobs found. Click + to create one.",
+ "records": "[ZH] records",
+ "download": "[ZH] Download",
+ "files": "[ZH] FILES",
+ "jobsExpireNotice": "[ZH] Jobs expire after 7 days. Download completed jobs promptly.",
+ "configureApiKey": "[ZH] Configure Databento API key for batch downloads"
+ },
+ "surfaceAnalytics": {
+ "apiKeyRequired": "[ZH] [EN] surfaceAnalytics.apiKeyRequired",
+ "apiKeyDescription": "[ZH] [EN] surfaceAnalytics.apiKeyDescription",
+ "features": {
+ "volatility": "[ZH] [EN] surfaceAnalytics.features.volatility",
+ "volatilityDesc": "[ZH] [EN] surfaceAnalytics.features.volatilityDesc",
+ "correlation": "[ZH] [EN] surfaceAnalytics.features.correlation",
+ "correlationDesc": "[ZH] [EN] surfaceAnalytics.features.correlationDesc",
+ "yieldCurves": "[ZH] [EN] surfaceAnalytics.features.yieldCurves",
+ "yieldCurvesDesc": "[ZH] [EN] surfaceAnalytics.features.yieldCurvesDesc",
+ "pca": "[ZH] [EN] surfaceAnalytics.features.pca",
+ "pcaDesc": "[ZH] [EN] surfaceAnalytics.features.pcaDesc"
+ },
+ "configureApiKey": "[ZH] [EN] surfaceAnalytics.configureApiKey",
+ "getApiKey": "[ZH] [EN] surfaceAnalytics.getApiKey",
+ "useDemoData": "[ZH] [EN] surfaceAnalytics.useDemoData",
+ "syntheticData": "[ZH] [EN] surfaceAnalytics.syntheticData",
+ "paidServiceNotice": "[ZH] [EN] surfaceAnalytics.paidServiceNotice"
+ },
+ "common": {
+ "or": "[ZH] [EN] common.or",
+ "note": "[ZH] [EN] common.note"
+ }
+}
diff --git a/fincept-terminal-desktop/public/locales/zh/tabs.json b/fincept-terminal-desktop/public/locales/zh/tabs.json
index 6c885e430..c2831dee7 100644
--- a/fincept-terminal-desktop/public/locales/zh/tabs.json
+++ b/fincept-terminal-desktop/public/locales/zh/tabs.json
@@ -5,29 +5,7 @@
"news": "新闻",
"portfolio": "投资组合",
"backtesting": "回测",
- "watchlist": "自选股",
- "research": "研究",
- "screener": "筛选器",
"chat": "AI聊天",
- "agents": "代理",
- "settings": "设置",
"profile": "个人资料"
- },
- "functionKeys": {
- "f1": "仪表",
- "f2": "市场",
- "f3": "新闻",
- "f4": "组合",
- "f5": "回测",
- "f6": "自选",
- "f7": "研究",
- "f8": "筛选",
- "f9": "交易",
- "f10": "AI",
- "f11": "全屏",
- "f12": "资料"
- },
- "labels": {
- "moreTabs": "工具栏菜单中更多标签页"
}
}
diff --git a/fincept-terminal-desktop/public/locales/zh/watchlist.json b/fincept-terminal-desktop/public/locales/zh/watchlist.json
index 2a2463a90..3aeae4eec 100644
--- a/fincept-terminal-desktop/public/locales/zh/watchlist.json
+++ b/fincept-terminal-desktop/public/locales/zh/watchlist.json
@@ -1,25 +1,7 @@
{
- "title": "自选列表",
- "header": {
- "export": "导出",
- "updating": "更新中",
- "live": "实时"
- },
"sidebar": {
- "groups": "自选分组",
- "new": "新建",
"noWatchlists": "暂无自选列表",
"clickNew": "点击新建创建列表",
- "stocks": "股票",
- "marketMovers": "市场异动",
- "gainer": "涨幅榜",
- "loser": "跌幅榜",
- "volumeLeaders": "成交量榜"
- },
- "emptyState": {
- "selectWatchlist": "选择一个自选列表或创建新列表开始"
- },
- "list": {
- "symbols": "代码"
+ "stocks": "股票"
}
}
diff --git a/fincept-terminal-desktop/scripts/bump-version.ts b/fincept-terminal-desktop/scripts/bump-version.ts
index 9faf6fd3f..bb4c9be41 100644
--- a/fincept-terminal-desktop/scripts/bump-version.ts
+++ b/fincept-terminal-desktop/scripts/bump-version.ts
@@ -19,7 +19,6 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
-import { execSync } from 'child_process';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -115,14 +114,41 @@ function updatePackageJson(newVersion: string): string {
}
}
-// Run sync-version script
-function runSyncVersion(): void {
+// Sync version to all required files
+function runSyncVersion(newVersion: string): void {
+ logInfo('\nSyncing version across all files...\n');
+
+ // 1. src/constants/version.ts
try {
- logInfo('\nSyncing version across all files...\n');
- execSync('bun run sync-version', { stdio: 'inherit', cwd: rootDir });
+ const versionTsPath = path.join(rootDir, 'src/constants/version.ts');
+ let content = fs.readFileSync(versionTsPath, 'utf8');
+ content = content.replace(/export const APP_VERSION = '[^']+';/, `export const APP_VERSION = '${newVersion}';`);
+ fs.writeFileSync(versionTsPath, content, 'utf8');
+ logSuccess(`Updated src/constants/version.ts`);
} catch (error) {
- logError('Failed to run sync-version script');
- process.exit(1);
+ logError(`Failed to update version.ts: ${(error as Error).message}`);
+ }
+
+ // 2. src-tauri/tauri.conf.json
+ try {
+ const tauriConfPath = path.join(rootDir, 'src-tauri/tauri.conf.json');
+ const tauriConf = JSON.parse(fs.readFileSync(tauriConfPath, 'utf8'));
+ tauriConf.version = newVersion;
+ fs.writeFileSync(tauriConfPath, JSON.stringify(tauriConf, null, 2) + '\n', 'utf8');
+ logSuccess(`Updated src-tauri/tauri.conf.json`);
+ } catch (error) {
+ logError(`Failed to update tauri.conf.json: ${(error as Error).message}`);
+ }
+
+ // 3. src-tauri/Cargo.toml
+ try {
+ const cargoTomlPath = path.join(rootDir, 'src-tauri/Cargo.toml');
+ let content = fs.readFileSync(cargoTomlPath, 'utf8');
+ content = content.replace(/^version = "[^"]+"/m, `version = "${newVersion}"`);
+ fs.writeFileSync(cargoTomlPath, content, 'utf8');
+ logSuccess(`Updated src-tauri/Cargo.toml`);
+ } catch (error) {
+ logError(`Failed to update Cargo.toml: ${(error as Error).message}`);
}
}
@@ -156,8 +182,8 @@ function main(): void {
// Update package.json
updatePackageJson(newVersion);
- // Run sync-version to update all other files
- runSyncVersion();
+ // Sync version to all other files
+ runSyncVersion(newVersion);
log('\n' + '='.repeat(60), colors.bright);
logSuccess('Version bump completed!');
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lock
index ba779a733..5ccc22ce7 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.lock
+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock
@@ -1247,7 +1247,7 @@ dependencies = [
[[package]]
name = "fincept-terminal-desktop"
-version = "3.3.1"
+version = "3.3.3"
dependencies = [
"aes-gcm",
"ahash",
@@ -1258,6 +1258,7 @@ dependencies = [
"csv",
"dashmap",
"dirs 5.0.1",
+ "finscript",
"flate2",
"futures",
"futures-util",
@@ -1307,6 +1308,15 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844"
+[[package]]
+name = "finscript"
+version = "0.1.0"
+dependencies = [
+ "chrono",
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "flate2"
version = "1.1.5"
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.toml
index 99a39a1cb..6d08ac66d 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.toml
+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "fincept-terminal-desktop"
-version = "3.3.1"
+version = "3.3.3"
description = "Professional-grade financial analysis platform with AI-powered insights and real-time market data"
authors = ["Fincept Corporation <[email protected]>"]
edition = "2021"
@@ -72,6 +72,7 @@ base64 = "0.22" # Base64 encoding/decoding for encrypted data
csv = "1.3" # CSV parsing for master contract data
urlencoding = "2.1" # URL encoding for API parameters
totp-rs = { version = "5", features = ["gen_secret"] } # TOTP generation for AngelOne auto-auth
+finscript = { path = "finscript" } # FinScript language engine (linked library)
[target.'cfg(target_os = "windows")'.dependencies]
[target.'cfg(target_os = "macos")'.dependencies]
diff --git a/fincept-terminal-desktop/src-tauri/finscript/Cargo.toml b/fincept-terminal-desktop/src-tauri/finscript/Cargo.toml
index 25c85847f..17b293687 100644
--- a/fincept-terminal-desktop/src-tauri/finscript/Cargo.toml
+++ b/fincept-terminal-desktop/src-tauri/finscript/Cargo.toml
@@ -3,6 +3,14 @@ name = "finscript"
version = "0.1.0"
edition = "2021"
+[lib]
+name = "finscript"
+path = "src/lib.rs"
+
+[[bin]]
+name = "finscript"
+path = "src/main.rs"
+
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
diff --git a/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/builtin_integration.rs b/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/builtin_integration.rs
new file mode 100644
index 000000000..edee6225a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/builtin_integration.rs
@@ -0,0 +1,127 @@
+use crate::ast::*;
+use crate::types::*;
+use crate::IntegrationAction;
+use super::Interpreter;
+
+impl Interpreter {
+ /// watchlist_add(symbol, watchlist_name?) — Queue a symbol to be added to a watchlist
+ pub(crate) fn eval_watchlist_add(&mut self, args: &[Expr]) -> Result<Value, String> {
+ if args.is_empty() {
+ return Err("watchlist_add() requires at least 1 argument: symbol".to_string());
+ }
+ let symbol = self.resolve_symbol(&args[0])?;
+ let watchlist_name = if args.len() > 1 {
+ match self.evaluate_expr(&args[1])? {
+ Value::String(s) => s,
+ _ => "Default".to_string(),
+ }
+ } else {
+ "Default".to_string()
+ };
+
+ self.integration_actions.push(IntegrationAction {
+ action_type: "watchlist_add".to_string(),
+ payload: serde_json::json!({
+ "symbol": symbol,
+ "watchlist_name": watchlist_name,
+ }),
+ });
+ self.output_lines.push(format!("[WATCHLIST] Added {} to '{}'", symbol, watchlist_name));
+ Ok(Value::Bool(true))
+ }
+
+ /// paper_trade(symbol, side, quantity, price?) — Queue a paper trade order
+ pub(crate) fn eval_paper_trade(&mut self, args: &[Expr]) -> Result<Value, String> {
+ if args.len() < 3 {
+ return Err("paper_trade() requires 3 arguments: symbol, side, quantity".to_string());
+ }
+ let symbol = self.resolve_symbol(&args[0])?;
+ let side = match self.evaluate_expr(&args[1])? {
+ Value::String(s) => s,
+ v => self.value_to_string(&v),
+ };
+ if side != "buy" && side != "sell" {
+ return Err(format!("paper_trade() side must be 'buy' or 'sell', got '{}'", side));
+ }
+ let quantity = self.resolve_number(&args[2])?;
+ let price = if args.len() > 3 {
+ Some(self.resolve_number(&args[3])?)
+ } else {
+ self.get_last_close_price()
+ };
+
+ self.integration_actions.push(IntegrationAction {
+ action_type: "paper_trade".to_string(),
+ payload: serde_json::json!({
+ "symbol": symbol,
+ "side": side,
+ "quantity": quantity,
+ "price": price,
+ }),
+ });
+ self.output_lines.push(format!(
+ "[PAPER TRADE] {} {} {} @ {:.2}",
+ side.to_uppercase(),
+ quantity,
+ symbol,
+ price.unwrap_or(0.0)
+ ));
+ Ok(Value::Bool(true))
+ }
+
+ /// alert_create(message, type?) — Queue a terminal notification
+ pub(crate) fn eval_alert_create(&mut self, args: &[Expr]) -> Result<Value, String> {
+ if args.is_empty() {
+ return Err("alert_create() requires at least 1 argument: message".to_string());
+ }
+ let message = match self.evaluate_expr(&args[0])? {
+ Value::String(s) => s,
+ v => self.value_to_string(&v),
+ };
+ let alert_type = if args.len() > 1 {
+ match self.evaluate_expr(&args[1])? {
+ Value::String(s) => s,
+ _ => "info".to_string(),
+ }
+ } else {
+ "info".to_string()
+ };
+
+ self.integration_actions.push(IntegrationAction {
+ action_type: "alert_create".to_string(),
+ payload: serde_json::json!({
+ "message": message,
+ "alert_type": alert_type,
+ }),
+ });
+ self.output_lines.push(format!("[NOTIFY] {}", message));
+ Ok(Value::Bool(true))
+ }
+
+ /// screener_scan(symbols_array) — Queue a batch screener scan
+ pub(crate) fn eval_screener_scan(&mut self, args: &[Expr]) -> Result<Value, String> {
+ if args.is_empty() {
+ return Err("screener_scan() requires an array of symbols".to_string());
+ }
+ let symbols_val = self.evaluate_expr(&args[0])?;
+ let symbols = match symbols_val {
+ Value::Array(arr) => arr
+ .iter()
+ .map(|v| self.value_to_string(v))
+ .collect::<Vec<_>>(),
+ _ => {
+ return Err("screener_scan() expects an array of symbol strings".to_string());
+ }
+ };
+
+ self.integration_actions.push(IntegrationAction {
+ action_type: "screener_run".to_string(),
+ payload: serde_json::json!({ "symbols": symbols }),
+ });
+ self.output_lines.push(format!(
+ "[SCREENER] Queued scan for {} symbols",
+ symbols.len()
+ ));
+ Ok(Value::Bool(true))
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/builtin_risk.rs b/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/builtin_risk.rs
new file mode 100644
index 000000000..0c8b4fd44
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/builtin_risk.rs
@@ -0,0 +1,237 @@
+use crate::ast::*;
+use crate::types::*;
+use super::Interpreter;
+
+impl Interpreter {
+ /// sharpe(series, rf_rate?) — Annualized Sharpe ratio
+ pub(crate) fn eval_sharpe(&mut self, args: &[Expr]) -> Result<Value, String> {
+ if args.is_empty() {
+ return Err("sharpe() requires 1 argument: price series".to_string());
+ }
+ let val = self.evaluate_expr(&args[0])?;
+ let rf_rate = if args.len() > 1 {
+ self.resolve_number(&args[1])?
+ } else {
+ 0.0
+ };
+ match val {
+ Value::Series(s) => {
+ let returns = daily_returns(&s.values);
+ if returns.is_empty() {
+ return Ok(Value::Na);
+ }
+ let mean = mean_val(&returns);
+ let std = std_val(&returns);
+ if std == 0.0 {
+ return Ok(Value::Na);
+ }
+ let daily_rf = rf_rate / 252.0;
+ let sharpe = (mean - daily_rf) / std * (252.0_f64).sqrt();
+ Ok(Value::Number(sharpe))
+ }
+ _ => Err("sharpe() expects a price Series".to_string()),
+ }
+ }
+
+ /// sortino(series, rf_rate?) — Annualized Sortino ratio (downside deviation only)
+ pub(crate) fn eval_sortino(&mut self, args: &[Expr]) -> Result<Value, String> {
+ if args.is_empty() {
+ return Err("sortino() requires 1 argument: price series".to_string());
+ }
+ let val = self.evaluate_expr(&args[0])?;
+ let rf_rate = if args.len() > 1 {
+ self.resolve_number(&args[1])?
+ } else {
+ 0.0
+ };
+ match val {
+ Value::Series(s) => {
+ let returns = daily_returns(&s.values);
+ if returns.is_empty() {
+ return Ok(Value::Na);
+ }
+ let mean = mean_val(&returns);
+ let daily_rf = rf_rate / 252.0;
+ let downside: Vec<f64> = returns
+ .iter()
+ .filter(|&&r| r < daily_rf)
+ .map(|&r| (r - daily_rf).powi(2))
+ .collect();
+ if downside.is_empty() {
+ return Ok(Value::Na);
+ }
+ let dd_std =
+ (downside.iter().sum::<f64>() / downside.len() as f64).sqrt();
+ if dd_std == 0.0 {
+ return Ok(Value::Na);
+ }
+ Ok(Value::Number(
+ (mean - daily_rf) / dd_std * (252.0_f64).sqrt(),
+ ))
+ }
+ _ => Err("sortino() expects a price Series".to_string()),
+ }
+ }
+
+ /// max_drawdown(series) — Maximum drawdown as a positive fraction (0.0 to 1.0)
+ pub(crate) fn eval_max_drawdown(&mut self, args: &[Expr]) -> Result<Value, String> {
+ if args.is_empty() {
+ return Err("max_drawdown() requires 1 argument: price series".to_string());
+ }
+ let val = self.evaluate_expr(&args[0])?;
+ match val {
+ Value::Series(s) => {
+ let mut peak = f64::NEG_INFINITY;
+ let mut max_dd = 0.0_f64;
+ for &price in &s.values {
+ if price.is_nan() {
+ continue;
+ }
+ if price > peak {
+ peak = price;
+ }
+ if peak > 0.0 {
+ let dd = (peak - price) / peak;
+ if dd > max_dd {
+ max_dd = dd;
+ }
+ }
+ }
+ Ok(Value::Number(max_dd))
+ }
+ _ => Err("max_drawdown() expects a price Series".to_string()),
+ }
+ }
+
+ /// correlation(series_a, series_b) — Pearson correlation of daily returns
+ pub(crate) fn eval_correlation(&mut self, args: &[Expr]) -> Result<Value, String> {
+ if args.len() < 2 {
+ return Err("correlation() requires 2 arguments: two series".to_string());
+ }
+ let a = self.evaluate_expr(&args[0])?;
+ let b = self.evaluate_expr(&args[1])?;
+ match (a, b) {
+ (Value::Series(sa), Value::Series(sb)) => {
+ let ra = daily_returns(&sa.values);
+ let rb = daily_returns(&sb.values);
+ let len = ra.len().min(rb.len());
+ if len < 2 {
+ return Ok(Value::Na);
+ }
+ let ma = mean_val(&ra[..len]);
+ let mb = mean_val(&rb[..len]);
+ let mut cov = 0.0;
+ let mut va = 0.0;
+ let mut vb = 0.0;
+ for i in 0..len {
+ let da = ra[i] - ma;
+ let db = rb[i] - mb;
+ cov += da * db;
+ va += da * da;
+ vb += db * db;
+ }
+ let denom = (va * vb).sqrt();
+ if denom == 0.0 {
+ return Ok(Value::Na);
+ }
+ Ok(Value::Number(cov / denom))
+ }
+ _ => Err("correlation() expects two Series".to_string()),
+ }
+ }
+
+ /// beta(asset_series, benchmark_series) — Beta coefficient
+ pub(crate) fn eval_beta(&mut self, args: &[Expr]) -> Result<Value, String> {
+ if args.len() < 2 {
+ return Err(
+ "beta() requires 2 arguments: asset series and benchmark series".to_string(),
+ );
+ }
+ let asset = self.evaluate_expr(&args[0])?;
+ let benchmark = self.evaluate_expr(&args[1])?;
+ match (asset, benchmark) {
+ (Value::Series(sa), Value::Series(sb)) => {
+ let ra = daily_returns(&sa.values);
+ let rb = daily_returns(&sb.values);
+ let len = ra.len().min(rb.len());
+ if len < 2 {
+ return Ok(Value::Na);
+ }
+ let ma = mean_val(&ra[..len]);
+ let mb = mean_val(&rb[..len]);
+ let mut cov = 0.0;
+ let mut var_b = 0.0;
+ for i in 0..len {
+ let da = ra[i] - ma;
+ let db = rb[i] - mb;
+ cov += da * db;
+ var_b += db * db;
+ }
+ if var_b == 0.0 {
+ return Ok(Value::Na);
+ }
+ Ok(Value::Number(cov / var_b))
+ }
+ _ => Err("beta() expects two Series".to_string()),
+ }
+ }
+
+ /// returns(series) — Convert price series to daily return series
+ pub(crate) fn eval_returns(&mut self, args: &[Expr]) -> Result<Value, String> {
+ if args.is_empty() {
+ return Err("returns() requires 1 argument: price series".to_string());
+ }
+ let val = self.evaluate_expr(&args[0])?;
+ match val {
+ Value::Series(s) => {
+ let rets = daily_returns(&s.values);
+ let ts = if s.timestamps.len() > 1 {
+ s.timestamps[1..].to_vec()
+ } else {
+ vec![]
+ };
+ Ok(Value::Series(SeriesData {
+ values: rets,
+ timestamps: ts,
+ }))
+ }
+ _ => Err("returns() expects a price Series".to_string()),
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Helper functions
+// ---------------------------------------------------------------------------
+
+fn daily_returns(prices: &[f64]) -> Vec<f64> {
+ if prices.len() < 2 {
+ return vec![];
+ }
+ prices
+ .windows(2)
+ .map(|w| {
+ if w[0] != 0.0 && !w[0].is_nan() && !w[1].is_nan() {
+ (w[1] - w[0]) / w[0]
+ } else {
+ 0.0
+ }
+ })
+ .collect()
+}
+
+fn mean_val(data: &[f64]) -> f64 {
+ if data.is_empty() {
+ return 0.0;
+ }
+ data.iter().sum::<f64>() / data.len() as f64
+}
+
+fn std_val(data: &[f64]) -> f64 {
+ if data.len() < 2 {
+ return 0.0;
+ }
+ let m = mean_val(data);
+ let variance = data.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (data.len() - 1) as f64;
+ variance.sqrt()
+}
diff --git a/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/functions.rs b/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/functions.rs
index b9d10c20c..cd7aa3e0f 100644
--- a/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/functions.rs
+++ b/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/functions.rs
@@ -141,6 +141,18 @@ impl Interpreter {
// Alert function (also handled as statement, but can be called as function)
"alert" => self.eval_alert_fn(args),
"alertcondition" => self.eval_alertcondition(args),
+ // Risk & portfolio analytics
+ "sharpe" => self.eval_sharpe(args),
+ "sortino" => self.eval_sortino(args),
+ "max_drawdown" => self.eval_max_drawdown(args),
+ "correlation" => self.eval_correlation(args),
+ "beta" => self.eval_beta(args),
+ "returns" => self.eval_returns(args),
+ // Terminal integration functions
+ "watchlist_add" => self.eval_watchlist_add(args),
+ "paper_trade" => self.eval_paper_trade(args),
+ "alert_create" => self.eval_alert_create(args),
+ "screener_scan" => self.eval_screener_scan(args),
_ => Err(format!("Unknown function '{}'", name)),
}
}
diff --git a/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/mod.rs b/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/mod.rs
index 117487bfe..4fbdf99ad 100644
--- a/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/finscript/src/interpreter/mod.rs
@@ -3,6 +3,8 @@ mod functions;
mod builtin_indicators;
mod builtin_utils;
mod builtin_drawing;
+mod builtin_integration;
+mod builtin_risk;
mod strategy;
mod plotting;
mod methods;
@@ -18,7 +20,7 @@ pub use symbols::collect_symbols;
use std::collections::HashMap;
use crate::ast::*;
use crate::types::*;
-use crate::{Signal, PlotData, AlertInfo, DrawingInfo};
+use crate::{Signal, PlotData, AlertInfo, DrawingInfo, IntegrationAction};
pub struct InterpreterResult {
pub success: bool,
@@ -28,6 +30,7 @@ pub struct InterpreterResult {
pub errors: Vec<String>,
pub alerts: Vec<AlertInfo>,
pub drawings: Vec<DrawingInfo>,
+ pub integration_actions: Vec<IntegrationAction>,
pub execution_time_ms: u64,
}
@@ -57,6 +60,7 @@ pub struct Interpreter {
pub(crate) user_functions: HashMap<String, UserFunction>,
pub(crate) alerts: Vec<AlertInfo>,
pub(crate) drawings: Vec<DrawingInfo>,
+ pub(crate) integration_actions: Vec<IntegrationAction>,
// Strategy state
pub(crate) strategy_position: i64,
pub(crate) strategy_entry_price: f64,
@@ -75,6 +79,7 @@ impl Interpreter {
user_functions: HashMap::new(),
alerts: Vec::new(),
drawings: Vec::new(),
+ integration_actions: Vec::new(),
strategy_position: 0,
strategy_entry_price: 0.0,
strategy_equity: 10000.0,
@@ -103,6 +108,7 @@ impl Interpreter {
errors: self.errors.clone(),
alerts: self.alerts.clone(),
drawings: self.drawings.clone(),
+ integration_actions: self.integration_actions.clone(),
execution_time_ms,
}
}
diff --git a/fincept-terminal-desktop/src-tauri/finscript/src/lib.rs b/fincept-terminal-desktop/src-tauri/finscript/src/lib.rs
index 54fef4b3d..7d120c768 100644
--- a/fincept-terminal-desktop/src-tauri/finscript/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/finscript/src/lib.rs
@@ -8,7 +8,15 @@ pub mod types;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Instant;
-use types::OhlcvSeries;
+
+// Re-export core types for consumers
+pub use types::OhlcvSeries;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct IntegrationAction {
+ pub action_type: String,
+ pub payload: serde_json::Value,
+}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FinScriptResult {
@@ -19,6 +27,7 @@ pub struct FinScriptResult {
pub errors: Vec<String>,
pub alerts: Vec<AlertInfo>,
pub drawings: Vec<DrawingInfo>,
+ pub integration_actions: Vec<IntegrationAction>,
pub execution_time_ms: u64,
}
@@ -69,64 +78,85 @@ pub struct DrawingInfo {
pub width: f64,
}
-/// Execute a FinScript program and return the result as JSON-serializable struct.
+fn build_error_result(start: Instant, msg: String) -> FinScriptResult {
+ FinScriptResult {
+ success: false,
+ output: String::new(),
+ signals: vec![],
+ plots: vec![],
+ errors: vec![msg],
+ alerts: vec![],
+ drawings: vec![],
+ integration_actions: vec![],
+ execution_time_ms: start.elapsed().as_millis() as u64,
+ }
+}
+
+fn build_result(result: interpreter::InterpreterResult, start: Instant) -> FinScriptResult {
+ FinScriptResult {
+ success: result.errors.is_empty(),
+ output: result.output,
+ signals: result.signals,
+ plots: result.plots,
+ errors: result.errors,
+ alerts: result.alerts,
+ drawings: result.drawings,
+ integration_actions: result.integration_actions,
+ execution_time_ms: start.elapsed().as_millis() as u64,
+ }
+}
+
+/// Execute a FinScript program with synthetic demo data.
+/// Symbols referenced in the code get deterministic random-walk OHLCV data.
pub fn execute(code: &str) -> FinScriptResult {
let start = Instant::now();
- // 1. Tokenize
let tokens = match lexer::tokenize(code) {
Ok(t) => t,
- Err(e) => {
- return FinScriptResult {
- success: false,
- output: String::new(),
- signals: vec![],
- plots: vec![],
- errors: vec![format!("Lexer error: {}", e)],
- alerts: vec![],
- drawings: vec![],
- execution_time_ms: start.elapsed().as_millis() as u64,
- };
- }
+ Err(e) => return build_error_result(start, format!("Lexer error: {}", e)),
};
- // 2. Parse
let program = match parser::parse(tokens) {
Ok(p) => p,
- Err(e) => {
- return FinScriptResult {
- success: false,
- output: String::new(),
- signals: vec![],
- plots: vec![],
- errors: vec![format!("Parse error: {}", e)],
- alerts: vec![],
- drawings: vec![],
- execution_time_ms: start.elapsed().as_millis() as u64,
- };
- }
+ Err(e) => return build_error_result(start, format!("Parse error: {}", e)),
};
- // 3. Collect symbols & generate data
let symbols = interpreter::collect_symbols(&program);
let symbol_data = generate_symbol_data(&symbols);
- // 4. Interpret
let mut interp = interpreter::Interpreter::new(symbol_data);
let result = interp.execute(&program);
- let execution_time_ms = start.elapsed().as_millis() as u64;
+ build_result(result, start)
+}
- FinScriptResult {
- success: result.errors.is_empty(),
- output: result.output,
- signals: result.signals,
- plots: result.plots,
- errors: result.errors,
- alerts: result.alerts,
- drawings: result.drawings,
- execution_time_ms,
- }
+/// Execute a FinScript program with externally-provided OHLCV data.
+/// Used for live market data integration from the Tauri host.
+pub fn execute_with_data(code: &str, symbol_data: HashMap<String, OhlcvSeries>) -> FinScriptResult {
+ let start = Instant::now();
+
+ let tokens = match lexer::tokenize(code) {
+ Ok(t) => t,
+ Err(e) => return build_error_result(start, format!("Lexer error: {}", e)),
+ };
+
+ let program = match parser::parse(tokens) {
+ Ok(p) => p,
+ Err(e) => return build_error_result(start, format!("Parse error: {}", e)),
+ };
+
+ let mut interp = interpreter::Interpreter::new(symbol_data);
+ let result = interp.execute(&program);
+
+ build_result(result, start)
+}
+
+/// Parse code and return the list of ticker symbols referenced in the AST.
+/// The host uses this to know which symbols to fetch data for before execution.
+pub fn extract_symbols(code: &str) -> Result<Vec<String>, String> {
+ let tokens = lexer::tokenize(code).map_err(|e| format!("Lexer error: {}", e))?;
+ let program = parser::parse(tokens).map_err(|e| format!("Parse error: {}", e))?;
+ Ok(interpreter::collect_symbols(&program))
}
/// Generate synthetic OHLCV data for symbols using a deterministic random walk.
diff --git a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt
index 33fdb4435..0b784bc2a 100644
--- a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt
+++ b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt
@@ -73,6 +73,7 @@ wikipedia>=1.4.0
# PyTorch 2.3.1+ doesn't support macOS Intel, use 2.2.2 for compatibility
torch==2.2.2; platform_machine == "x86_64" and sys_platform == "darwin"
torch>=2.3.1; platform_machine != "x86_64" or sys_platform != "darwin"
+torchvision>=0.17.0
scikit-learn>=1.4.2,<1.7.0
scipy>=1.13.0,<1.16.0
lightgbm>=4.6.0,<5.0.0
@@ -142,3 +143,7 @@ stable-baselines3>=2.7.0
# MLflow
mlflow>=2.0.0
+
+# VisionQuant Pattern Intelligence
+faiss-cpu>=1.7.0
+mplfinance>=0.12.0
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/monte_carlo_valuation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/monte_carlo_valuation.py
index d0283e243..314ebe9c3 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/monte_carlo_valuation.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/monte_carlo_valuation.py
@@ -305,15 +305,51 @@ def main():
discount_rate = float(sys.argv[7])
simulations = int(sys.argv[8])
+ # Normalize: frontend sends percentages (15, 5), Python needs fractions (0.15, 0.05)
+ if revenue_growth_mean > 1:
+ revenue_growth_mean = revenue_growth_mean / 100.0
+ if revenue_growth_std > 1:
+ revenue_growth_std = revenue_growth_std / 100.0
+ if margin_mean > 1:
+ margin_mean = margin_mean / 100.0
+ if margin_std > 1:
+ margin_std = margin_std / 100.0
+ if discount_rate > 1:
+ discount_rate = discount_rate / 100.0
+
mc = MonteCarloValuation(num_simulations=simulations)
- analysis = mc.simulate_synergies(
- base_revenue_synergy=base_valuation * revenue_growth_mean,
- base_cost_synergy=base_valuation * margin_mean,
- revenue_std_dev_pct=revenue_growth_std,
- cost_std_dev_pct=margin_std
+ # Use DCF-based Monte Carlo: simulate enterprise value distribution
+ # Build base FCF from base_valuation * margin_mean, grow at revenue_growth_mean
+ base_fcf = [base_valuation * margin_mean * ((1 + revenue_growth_mean) ** i) for i in range(5)]
+ analysis_dcf = mc.simulate_dcf_valuation(
+ base_fcf=base_fcf,
+ fcf_growth_mean=revenue_growth_mean,
+ fcf_growth_std=revenue_growth_std,
+ terminal_growth_mean=min(revenue_growth_mean * 0.3, 0.03),
+ terminal_growth_std=revenue_growth_std * 0.5,
+ wacc_mean=discount_rate,
+ wacc_std=discount_rate * 0.1,
)
+ vs = analysis_dcf.get('valuation_statistics', {})
+
+ # Normalize to flat structure that frontend expects
+ analysis = {
+ 'mean': vs.get('mean', 0),
+ 'median': vs.get('median', 0),
+ 'std': vs.get('std', 0),
+ 'p5': vs.get('percentile_5', 0),
+ 'p25': vs.get('percentile_25', 0),
+ 'p75': vs.get('percentile_75', 0),
+ 'p95': vs.get('percentile_95', 0),
+ 'probability_positive': 100.0, # DCF values are positive
+ 'num_simulations': simulations,
+ 'input_assumptions': analysis_dcf.get('input_assumptions', {}),
+ 'base_valuation': base_valuation,
+ 'discount_rate_pct': discount_rate * 100,
+ }
+
result = {"success": True, "data": analysis}
print(json.dumps(result))
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/regression_analysis.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/regression_analysis.py
index 55787ae03..011830e81 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/regression_analysis.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/regression_analysis.py
@@ -311,18 +311,74 @@ def main():
# Positional args: comp_data subject_metrics regression_type
comp_data = params if isinstance(params, list) else json.loads(sys.argv[2])
subject_metrics = json.loads(sys.argv[3]) if len(sys.argv) > 3 else {}
- regression_type = sys.argv[4] if len(sys.argv) > 4 else "premium"
+ regression_type = sys.argv[4] if len(sys.argv) > 4 else "multiple"
analyzer = MARegression()
- if regression_type == "premium":
+ # Both 'ols' and 'multiple' use multiple_regression_valuation with frontend data format
+ # (comp_data has 'ev', 'revenue', 'ebitda', 'growth' keys)
+ # Only route to premium_regression if comp_data has 'premium' key
+ has_premium_key = comp_data and 'premium' in comp_data[0]
+ if has_premium_key and regression_type == "premium":
analysis = analyzer.premium_regression(comp_data)
- elif regression_type == "multiple":
- analysis = analyzer.multiple_regression(comp_data, subject_metrics)
else:
- analysis = analyzer.premium_regression(comp_data)
+ # Filter out non-numeric keys (like 'name') from comp_data for regression
+ numeric_keys = [k for k in comp_data[0].keys() if k != 'name'] if comp_data else []
+ filtered_comp = [{k: v for k, v in row.items() if k in numeric_keys} for row in comp_data]
+ # Also filter subject_metrics to only include keys that are features (not 'ev', not 'name')
+ feature_keys = [k for k in numeric_keys if k != 'ev']
+ filtered_subject = {k: v for k, v in subject_metrics.items() if k in feature_keys}
+ analysis_raw = analyzer.multiple_regression_valuation(filtered_comp, filtered_subject)
+
+ # Normalize output to what the frontend expects:
+ # result.implied_ev, result.r_squared, result.adj_r_squared,
+ # result.coefficients (key → plain number), result.implied_multiples
+ rs = analysis_raw.get('regression_statistics', {})
+ raw_coeffs = analysis_raw.get('coefficients', {})
+ predicted_ev = analysis_raw.get('predicted_value', 0)
+
+ # coefficients: flatten to {feature: coefficient_value}
+ flat_coeffs = {
+ feat: coeff_info['coefficient']
+ for feat, coeff_info in raw_coeffs.items()
+ }
+
+ # implied_multiples: compute EV / metric for subject company
+ implied_multiples = {}
+ if filtered_subject.get('revenue', 0) > 0:
+ implied_multiples['ev_revenue'] = predicted_ev / filtered_subject['revenue']
+ if filtered_subject.get('ebitda', 0) > 0:
+ implied_multiples['ev_ebitda'] = predicted_ev / filtered_subject['ebitda']
+
+ # prediction_interval
+ pi = analysis_raw.get('prediction_interval', {})
+
+ analysis = {
+ 'implied_ev': predicted_ev,
+ 'prediction_interval_low': pi.get('lower', 0),
+ 'prediction_interval_high': pi.get('upper', 0),
+ 'r_squared': rs.get('r_squared', 0),
+ 'adj_r_squared': rs.get('adjusted_r_squared', 0),
+ 'intercept': rs.get('intercept', 0),
+ 'coefficients': flat_coeffs,
+ 'implied_multiples': implied_multiples,
+ 'num_comparables': analysis_raw.get('num_comparables', len(comp_data)),
+ 'regression_type': regression_type,
+ 'raw_coefficients': raw_coeffs, # keep full detail for raw view
+ }
result = {"success": True, "data": analysis}
- print(json.dumps(result, default=lambda o: bool(o) if isinstance(o, np.bool_) else float(o) if isinstance(o, (np.floating, np.integer)) else str(o)))
+
+ def safe_json(o):
+ if isinstance(o, np.bool_):
+ return bool(o)
+ if isinstance(o, (np.floating, np.integer)):
+ v = float(o)
+ if v != v or v == float('inf') or v == float('-inf'): # nan or inf
+ return None
+ return v
+ return str(o)
+
+ print(json.dumps(result, default=safe_json))
else:
result = {"success": False, "error": f"Unknown command: {command}"}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_comparison/deal_comparator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_comparison/deal_comparator.py
index 9642e3eb2..928de20e1 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_comparison/deal_comparator.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_comparison/deal_comparator.py
@@ -293,11 +293,11 @@ def main():
deal_id=d.get('deal_id', ''),
target_name=d.get('target_name', d.get('target', '')),
acquirer_name=d.get('acquirer_name', d.get('acquirer', '')),
- deal_value=d.get('deal_value', 0),
+ deal_value=float(d.get('deal_value', 0) or 0),
offer_price_per_share=d.get('offer_price_per_share', d.get('offer_price', None)),
- premium_1day=d.get('premium_1day', d.get('premium', 0)),
- payment_cash_pct=d.get('payment_cash_pct', d.get('cash_pct', 0)),
- payment_stock_pct=d.get('payment_stock_pct', d.get('stock_pct', 0)),
+ premium_1day=float(d.get('premium_1day', d.get('premium', 0)) or 0),
+ payment_cash_pct=float(d.get('payment_cash_pct', d.get('cash_pct', 0)) or 0),
+ payment_stock_pct=float(d.get('payment_stock_pct', d.get('stock_pct', 0)) or 0),
ev_revenue=d.get('ev_revenue', None),
ev_ebitda=d.get('ev_ebitda', None),
synergies=d.get('synergies', None),
@@ -307,40 +307,122 @@ def main():
))
return deals
+ def _safe(v):
+ """Convert numpy types and non-finite floats to JSON-safe values"""
+ try:
+ import numpy as np
+ if isinstance(v, (np.floating, np.integer)):
+ v = v.item()
+ except ImportError:
+ pass
+ if isinstance(v, float) and (v != v or v == float('inf') or v == float('-inf')):
+ return None
+ return v
+
try:
if command == "compare":
- # Rust sends: "compare" deals_json
+ # Frontend expects: { comparison: {metric: [v1,v2,...]}, summary: {metric: value} }
if len(sys.argv) < 3:
raise ValueError("Deals data required")
deals_data = json.loads(sys.argv[2])
deals = _parse_deals(deals_data)
- comparator = DealComparator()
- if len(deals) >= 2:
- analysis = comparator.compare_deals(deals)
+ if len(deals) < 2:
+ analysis = {"comparison": {}, "summary": {}, "num_deals": len(deals)}
else:
- analysis = {"deals_count": len(deals), "deals_data": deals_data}
+ # Build comparison: metric -> list of values per deal (in deal order)
+ metrics = [
+ 'deal_value', 'premium_1day', 'ev_revenue', 'ev_ebitda',
+ 'synergies', 'payment_cash_pct', 'payment_stock_pct',
+ ]
+ comparison = {}
+ for metric in metrics:
+ vals = []
+ for d in deals:
+ v = getattr(d, metric, None)
+ vals.append(_safe(v) if v is not None else None)
+ comparison[metric] = vals
+
+ # Build summary: aggregate stats across all deals
+ deal_values = [d.deal_value for d in deals]
+ premiums = [d.premium_1day for d in deals]
+ ev_revenues = [d.ev_revenue for d in deals if d.ev_revenue is not None]
+ ev_ebitdas = [d.ev_ebitda for d in deals if d.ev_ebitda is not None]
+ synergies_list = [d.synergies for d in deals if d.synergies is not None]
+
+ summary = {
+ 'num_deals': len(deals),
+ 'avg_deal_value': float(np.mean(deal_values)) if deal_values else 0,
+ 'avg_premium': float(np.mean(premiums)) if premiums else 0,
+ 'median_premium': float(np.median(premiums)) if premiums else 0,
+ }
+ if ev_revenues:
+ summary['avg_ev_revenue'] = float(np.mean(ev_revenues))
+ if ev_ebitdas:
+ summary['avg_ev_ebitda'] = float(np.mean(ev_ebitdas))
+ if synergies_list:
+ summary['total_synergies'] = float(sum(synergies_list))
+
+ analysis = {
+ 'comparison': comparison,
+ 'summary': summary,
+ 'num_deals': len(deals),
+ }
result = {"success": True, "data": analysis}
print(json.dumps(result, default=str))
elif command == "rank":
- # Rust sends: "rank" deals_json criteria
+ # Frontend expects: { rankings: [{target_name, acquirer_name, premium_1day|deal_value|ev_revenue|ev_ebitda|synergies}] }
if len(sys.argv) < 4:
raise ValueError("Deals data and criteria required")
deals_data = json.loads(sys.argv[2])
criteria = sys.argv[3]
deals = _parse_deals(deals_data)
- comparator = DealComparator()
- analysis = comparator.rank_deals(deals, criteria=criteria)
+ criteria_map = {
+ 'premium': 'premium_1day',
+ 'deal_value': 'deal_value',
+ 'ev_revenue': 'ev_revenue',
+ 'ev_ebitda': 'ev_ebitda',
+ 'synergies': 'synergies',
+ }
+ attr = criteria_map.get(criteria, 'premium_1day')
+
+ def sort_key(d):
+ v = getattr(d, attr, None)
+ return float(v) if v is not None else -1
+
+ sorted_deals = sorted(deals, key=sort_key, reverse=True)
+
+ rankings = []
+ for rank, d in enumerate(sorted_deals, 1):
+ row = {
+ 'rank': rank,
+ 'deal_id': d.deal_id,
+ 'target_name': d.target_name,
+ 'acquirer_name': d.acquirer_name,
+ # Include the actual criteria field with real name so frontend can read it
+ 'premium_1day': _safe(d.premium_1day),
+ 'deal_value': _safe(d.deal_value),
+ 'ev_revenue': _safe(d.ev_revenue),
+ 'ev_ebitda': _safe(d.ev_ebitda),
+ 'synergies': _safe(d.synergies),
+ 'synergy_value': _safe(d.synergies), # alias for frontend compatibility
+ }
+ rankings.append(row)
+
+ analysis = {
+ 'ranking_criteria': criteria,
+ 'rankings': rankings,
+ }
result = {"success": True, "data": analysis}
print(json.dumps(result, default=str))
elif command == "benchmark":
- # Rust sends: "benchmark" target_deal_json comparable_deals_json
+ # Frontend expects: { premium_comparison: {target, median, percentile}, insight: str }
if len(sys.argv) < 4:
raise ValueError("Target deal and comparable deals required")
@@ -349,39 +431,156 @@ def main():
target_deals = _parse_deals([target_deal_data])
comparable_deals = _parse_deals(comparable_deals_data)
- comparator = DealComparator()
- if target_deals and comparable_deals:
- analysis = comparator.premium_benchmarking(target_deals[0], comparable_deals)
- else:
+ if not target_deals or not comparable_deals:
analysis = {"error": "Insufficient data for benchmarking"}
+ else:
+ target = target_deals[0]
+ comp_premiums = [d.premium_1day for d in comparable_deals]
+ target_premium = float(target.premium_1day)
+
+ p25 = float(np.percentile(comp_premiums, 25))
+ p50 = float(np.percentile(comp_premiums, 50))
+ p75 = float(np.percentile(comp_premiums, 75))
+ mean_prem = float(np.mean(comp_premiums))
+ min_prem = float(min(comp_premiums))
+ max_prem = float(max(comp_premiums))
+
+ # Calculate percentile rank of target within comparables
+ pct_below = float(np.mean([p < target_premium for p in comp_premiums]) * 100)
+
+ if target_premium < p25:
+ position = "below 25th percentile"
+ elif target_premium < p50:
+ position = "between 25th and 50th percentile"
+ elif target_premium < p75:
+ position = "between 50th and 75th percentile"
+ else:
+ position = "above 75th percentile"
+
+ insight = (
+ f"{target.target_name}'s acquisition premium of {target_premium:.1f}% is "
+ f"{position} relative to {len(comparable_deals)} comparable deals "
+ f"(median: {p50:.1f}%, mean: {mean_prem:.1f}%). "
+ f"The target's premium ranks at approximately the {pct_below:.0f}th percentile."
+ )
+
+ analysis = {
+ 'premium_comparison': {
+ 'target': target_premium,
+ 'median': p50,
+ 'mean': mean_prem,
+ 'percentile': pct_below,
+ 'p25': p25,
+ 'p75': p75,
+ 'min': min_prem,
+ 'max': max_prem,
+ },
+ 'target_deal': {
+ 'deal_id': target.deal_id,
+ 'target_name': target.target_name,
+ 'premium': target_premium,
+ },
+ 'target_position': position,
+ 'above_median': bool(target_premium > p50),
+ 'num_comparables': len(comparable_deals),
+ 'insight': insight,
+ }
result = {"success": True, "data": analysis}
print(json.dumps(result, default=str))
elif command == "payment_analysis":
- # Rust sends: "payment_analysis" deals_json
+ # Frontend expects:
+ # { distribution: {all_cash: count, all_stock: count, mixed: count},
+ # stats_by_type: {all_cash: {avg_premium, avg_value, count}, ...} }
if len(sys.argv) < 3:
raise ValueError("Deals data required")
deals_data = json.loads(sys.argv[2])
deals = _parse_deals(deals_data)
- comparator = DealComparator()
- analysis = comparator.payment_structure_analysis(deals)
+ # Categorize each deal
+ all_cash_deals = [d for d in deals if d.payment_cash_pct >= 100]
+ all_stock_deals = [d for d in deals if d.payment_stock_pct >= 100]
+ mixed_deals = [d for d in deals if d.payment_cash_pct < 100 and d.payment_stock_pct < 100]
+
+ def _type_stats(group):
+ if not group:
+ return None
+ premiums = [d.premium_1day for d in group]
+ values = [d.deal_value for d in group]
+ return {
+ 'count': len(group),
+ 'avg_premium': float(np.mean(premiums)),
+ 'avg_value': float(np.mean(values)),
+ }
+
+ # Build stats_by_type only for non-empty categories
+ stats_by_type = {}
+ s = _type_stats(all_cash_deals)
+ if s:
+ stats_by_type['all_cash'] = s
+ s = _type_stats(all_stock_deals)
+ if s:
+ stats_by_type['all_stock'] = s
+ s = _type_stats(mixed_deals)
+ if s:
+ stats_by_type['mixed'] = s
+
+ analysis = {
+ 'total_deals': len(deals),
+ 'distribution': {
+ 'all_cash': len(all_cash_deals),
+ 'all_stock': len(all_stock_deals),
+ 'mixed': len(mixed_deals),
+ },
+ 'stats_by_type': stats_by_type,
+ 'average_cash_pct': float(np.mean([d.payment_cash_pct for d in deals])),
+ 'average_stock_pct': float(np.mean([d.payment_stock_pct for d in deals])),
+ }
result = {"success": True, "data": analysis}
print(json.dumps(result, default=str))
elif command == "industry_analysis":
- # Rust sends: "industry_analysis" deals_json
+ # Frontend expects:
+ # { by_industry: {IndustryName: {count, avg_premium, avg_ev_revenue, avg_ev_ebitda, total_value}} }
if len(sys.argv) < 3:
raise ValueError("Deals data required")
deals_data = json.loads(sys.argv[2])
deals = _parse_deals(deals_data)
- comparator = DealComparator()
- analysis = comparator.industry_analysis(deals)
+ # Group by industry
+ industry_groups: dict = {}
+ for d in deals:
+ ind = d.industry or 'Unknown'
+ if ind not in industry_groups:
+ industry_groups[ind] = []
+ industry_groups[ind].append(d)
+
+ by_industry = {}
+ for ind, group in industry_groups.items():
+ premiums = [d.premium_1day for d in group]
+ deal_vals = [d.deal_value for d in group]
+ ev_revenues = [d.ev_revenue for d in group if d.ev_revenue is not None]
+ ev_ebitdas = [d.ev_ebitda for d in group if d.ev_ebitda is not None]
+
+ by_industry[ind] = {
+ 'count': len(group),
+ 'avg_premium': float(np.mean(premiums)),
+ 'median_premium': float(np.median(premiums)),
+ 'total_value': float(sum(deal_vals)),
+ 'avg_deal_value': float(np.mean(deal_vals)),
+ 'avg_ev_revenue': float(np.mean(ev_revenues)) if ev_revenues else None,
+ 'avg_ev_ebitda': float(np.mean(ev_ebitdas)) if ev_ebitdas else None,
+ }
+
+ analysis = {
+ 'by_industry': by_industry,
+ 'industries': list(industry_groups.keys()),
+ 'total_deals': len(deals),
+ }
result = {"success": True, "data": analysis}
print(json.dumps(result, default=str))
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/database_schema.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/database_schema.py
index 635b15b35..a5425b9ba 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/database_schema.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/database_schema.py
@@ -262,6 +262,20 @@ class MADatabase:
cursor.execute("CREATE INDEX IF NOT EXISTS idx_filings_type ON sec_filings(filing_type)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_filings_date ON sec_filings(filing_date)")
+ # Add new XBRL financial columns if they don't exist (safe migration)
+ xbrl_columns = [
+ ("target_revenue", "REAL"),
+ ("target_ebitda", "REAL"),
+ ("target_total_debt", "REAL"),
+ ("target_cash", "REAL"),
+ ("offer_price_per_share", "REAL"),
+ ]
+ for col_name, col_type in xbrl_columns:
+ try:
+ cursor.execute(f"ALTER TABLE ma_deals ADD COLUMN {col_name} {col_type}")
+ except Exception:
+ pass # Column already exists
+
conn.commit()
def insert_deal(self, deal_data: Dict[str, Any]) -> str:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_parser.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_parser.py
index 4503c28e4..33cd15bbf 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_parser.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_parser.py
@@ -13,25 +13,15 @@ sys.path.append(str(scripts_path))
analytics_path = Path(__file__).parent.parent.parent
sys.path.insert(0, str(analytics_path))
-try:
- from edgar_tools import Company, Filing
- EDGAR_AVAILABLE = True
-except ImportError:
- try:
- from edgartools import Company, Filing
- EDGAR_AVAILABLE = True
- except ImportError:
- EDGAR_AVAILABLE = False
- Company = None
- Filing = None
-
# Use absolute imports instead of relative imports
from corporateFinance.config import DEAL_TYPES, PAYMENT_METHODS, INDUSTRIES
from corporateFinance.deal_database.database_schema import MADatabase
+from corporateFinance.deal_database.edgar_fetcher import EdgarFetcher
class MADealParser:
- def __init__(self, db: Optional[MADatabase] = None):
+ def __init__(self, db: Optional[MADatabase] = None, fetcher=None):
self.db = db or MADatabase()
+ self.fetcher = fetcher or EdgarFetcher()
self.value_patterns = [
r'\$\s*(\d+(?:\.\d+)?)\s*(?:billion|bn)',
@@ -82,8 +72,14 @@ class MADealParser:
deal_data['data_source'] = 'SEC EDGAR'
deal_data['filing_url'] = filing_record['filing_url']
+ # Populate CIKs via name resolution (best-effort)
+ self._resolve_party_ciks(deal_data)
+
self.db.insert_deal(deal_data)
+ # XBRL enrichment - optional, adds financials + valuation multiples
+ self._enrich_deal_with_xbrl(deal_data, deal_id)
+
cursor.execute("""
UPDATE sec_filings
SET parsed_flag = 1, deal_id = ?
@@ -94,32 +90,21 @@ class MADealParser:
return deal_data
except Exception as e:
- print(f"Error parsing {accession_number}: {e}")
+ print(f"Error parsing {accession_number}: {e}", file=sys.stderr)
return None
def _get_filing_text(self, filing_record: Dict[str, Any]) -> str:
- """Get filing text from record or fetch from SEC"""
+ """Fetch filing text via EdgarFetcher."""
if filing_record.get('raw_text'):
return filing_record['raw_text']
- try:
- cik = filing_record['cik']
- company = Company(cik)
- filings = company.get_filings(form=filing_record['filing_type'])
-
- for filing in filings:
- if filing.accession_number == filing_record['accession_number']:
- if hasattr(filing, 'text'):
- return filing.text()[:100000]
- elif hasattr(filing, 'html'):
- html = filing.html()
- return re.sub('<[^<]+?>', ' ', html)[:100000]
- except:
- pass
+ accession_number = filing_record.get('accession_number', '')
+ cik = str(filing_record.get('cik', ''))
+ if accession_number and cik:
+ return self.fetcher.get_filing_text(accession_number, cik)
return ""
-
def _extract_deal_structure(self, text: str, filing_record: Dict[str, Any]) -> Dict[str, Any]:
"""Extract structured deal data from text"""
deal_data = {}
@@ -139,6 +124,16 @@ class MADealParser:
payment_method = self._extract_payment_method(text)
deal_data['payment_method'] = payment_method
+ # Derive percentage split from payment method string
+ if payment_method == 'Cash':
+ deal_data['cash_percentage'] = 100.0
+ deal_data['stock_percentage'] = 0.0
+ elif payment_method == 'Stock':
+ deal_data['cash_percentage'] = 0.0
+ deal_data['stock_percentage'] = 100.0
+ elif payment_method == 'Mixed':
+ deal_data['cash_percentage'] = 50.0
+ deal_data['stock_percentage'] = 50.0
deal_type = self._infer_deal_type(text)
deal_data['deal_type'] = deal_type
@@ -159,35 +154,139 @@ class MADealParser:
industry = self._infer_industry(text, filing_record)
deal_data['industry'] = industry
- advisors = self._extract_advisors(text)
+ self._extract_advisors(text)
+
+ # New extraction methods
+ per_share = self._extract_per_share_price(text)
+ if per_share:
+ deal_data['offer_price_per_share'] = per_share
+
+ expected_close = self._extract_expected_close(text)
+ if expected_close:
+ deal_data['expected_close_date'] = expected_close
- if not deal_data.get('acquirer_name') or not deal_data.get('target_name'):
+ breakup_fee = self._extract_breakup_fee(text)
+ if breakup_fee:
+ deal_data['breakup_fee'] = breakup_fee
+
+ flags = self._extract_deal_flags(text, filing_record)
+ deal_data.update(flags)
+
+ # Require at least one real company name
+ acquirer_ok = bool(deal_data.get('acquirer_name')) and deal_data['acquirer_name'] != 'Unknown Acquirer'
+ target_ok = bool(deal_data.get('target_name')) and deal_data['target_name'] != 'Unknown Target'
+ if not acquirer_ok and not target_ok:
+ return None
+
+ # For 8-K filings, require an identified target (Unknown Target = noise)
+ if filing_record.get('filing_type') == '8-K' and not target_ok:
return None
return deal_data
def _extract_parties(self, text: str, filing_record: Dict[str, Any]) -> Tuple[str, str]:
- """Extract acquirer and target names"""
- acquirer = filing_record['company_name']
- target = ""
+ """Extract acquirer and target names from filing text."""
+ company_name = filing_record.get('company_name', '')
+ filing_type = filing_record.get('filing_type', '')
+
+ # For proxy/merger forms the filer is typically the TARGET company
+ target_filer_forms = {'DEFM14A', 'PREM14A', 'S-4', 'SC 13E-3', 'SC TO-T'}
+ # SC TO-I = issuer tender offer — company buys back its own shares (self-tender)
+ # There is no separate target; both acquirer and target are the same entity.
+ self_tender_forms = {'SC TO-I'}
+ # 8-K filer completed or announced an acquisition of another company
+ acquirer_filer_forms = {'8-K'}
+
+ # SC TO-I: self-tender / share buyback — no separate target company
+ if filing_type in self_tender_forms:
+ return company_name, company_name
+
+ # Search in the first 15000 chars for better coverage
+ search_text = text[:15000]
+
+ # Patterns to find the acquirer name (used when filer is the target)
+ acquirer_patterns = [
+ # "Agreement and Plan of Merger, by and among [target], [acquirer], ..." — common in DEFM14A
+ # The first named company after the filer in the by-and-among list is the acquirer
+ r'by\s+and\s+among\s+\S[^,]+,\s+([A-Z][A-Za-z0-9\s,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.))',
+ # "acquired by X Inc." / "will be acquired by X Corp."
+ r'(?:will\s+be\s+acquired\s+by|to\s+be\s+acquired\s+by|acquired\s+by)\s+([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.|Company|Corporation|Holdings|Partners|Group|Media|Networks?))',
+ r'(?:acquir(?:ed|es|ing))\s+by\s+([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.|Holdings|Media|Networks?))',
+ # "Parent" / "Acquiror" defined terms in proxy filings
+ r'(?:Parent|Acquiror|Acquirer|Buyer)[,\s]+([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.|Company|Corporation|Holdings))',
+ r'(?:Parent|Acquiror|Acquirer|Buyer)[\s"]+(?:means|is|refers\s+to)\s+([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.))',
+ # "X agreed to acquire" / "X will acquire all"
+ r'([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.|Holdings|Media))\s+(?:has\s+)?agreed\s+to\s+acquire',
+ r'([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.|Holdings|Media))\s+(?:will\s+)?acquire[ds]?\s+(?:all|the)',
+ # Without suffix — 1-4 title-case words (catches "Skydance", "Apollo Global Management")
+ r'(?:merger\s+with|combination\s+with|transaction\s+with)\s+([A-Z][A-Za-z0-9]+(?:\s+[A-Z][A-Za-z0-9]+){0,3})',
+ r'(?:will\s+be\s+acquired\s+by|to\s+be\s+acquired\s+by|acquired\s+by)\s+([A-Z][A-Za-z0-9]+(?:\s+[A-Z][A-Za-z0-9]+){0,3})',
+ ]
- patterns = [
- r'acquire[ds]?\s+([A-Z][A-Za-z\s&]+(?:Inc\.|Corp\.|LLC|Ltd\.|Company|Corporation))',
- r'merger\s+(?:of|with)\s+([A-Z][A-Za-z\s&]+(?:Inc\.|Corp\.|LLC|Ltd\.))',
- r'purchase\s+(?:of|from)\s+([A-Z][A-Za-z\s&]+(?:Inc\.|Corp\.|LLC))',
+ # Patterns to find the target name (used when filer is the acquirer)
+ target_patterns = [
+ # "completed its previously announced merger with X" (8-K Item 2.01 completion)
+ r'completed\s+(?:its\s+)?(?:previously\s+announced\s+)?merger\s+(?:\([^)]+\)\s+)?with\s+([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.|Company|Corporation|Holdings))',
+ # "completed acquisition of X" / "completion of the acquisition of X" (8-K Item 2.01)
+ r'completed\s+(?:the\s+)?acquisition\s+of\s+([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.|Company|Corporation|Holdings))',
+ r'completion\s+of\s+(?:the\s+)?acquisition\s+of\s+([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.|Holdings))',
+ # "acquired all/the outstanding shares of X"
+ r'acquired\s+(?:all\s+(?:of\s+)?(?:the\s+)?(?:outstanding\s+)?(?:shares|stock)\s+of\s+)?([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.|Company|Corporation|Holdings))',
+ r'acquire[ds]?\s+([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.|Company|Corporation|Holdings))',
+ # Merger / tender offer descriptions
+ r'merger\s+(?:of|with|between)\s+([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.))',
+ r'purchase\s+(?:of|from)\s+([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC))',
+ r'tender\s+offer\s+for\s+(?:all\s+(?:outstanding\s+)?shares\s+of\s+)?([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.))',
+ # "Target" defined term common in 8-K acquisition filings
+ r'(?:the\s+)?(?:Target|Company)[,\s]+([A-Z][A-Za-z0-9\s&,\.]+?(?:Inc\.|Corp\.|LLC|Ltd\.|Company|Corporation|Holdings))',
+ # Without corporate suffix — 1-4 title-case words
+ r'completed\s+(?:the\s+)?acquisition\s+of\s+([A-Z][A-Za-z0-9]+(?:\s+[A-Z][A-Za-z0-9]+){0,3})',
+ r'acquired\s+([A-Z][A-Za-z0-9]+(?:\s+[A-Z][A-Za-z0-9]+){0,3})\s+(?:for|in\s+a\s+deal|in\s+a\s+transaction)',
]
- for pattern in patterns:
- match = re.search(pattern, text[:5000])
- if match:
- target = match.group(1).strip()
- break
+ acquirer = ""
+ target = ""
- if not target:
- target = "Unknown Target"
+ if filing_type in target_filer_forms:
+ # Filer is the target — search text for acquirer name
+ target = company_name
+ for pattern in acquirer_patterns:
+ match = re.search(pattern, search_text)
+ if match:
+ candidate = match.group(1).strip().rstrip(',.')
+ if candidate.lower() != target.lower() and self._is_valid_company_name(candidate):
+ acquirer = candidate
+ break
+ if not acquirer:
+ acquirer = "Unknown Acquirer"
+
+ elif filing_type in acquirer_filer_forms:
+ # Filer is the acquirer — search text for target name
+ acquirer = company_name
+ for pattern in target_patterns:
+ match = re.search(pattern, search_text)
+ if match:
+ candidate = match.group(1).strip().rstrip(',.')
+ if candidate.lower() != acquirer.lower() and self._is_valid_company_name(candidate):
+ target = candidate
+ break
+ if not target:
+ target = "Unknown Target"
- return acquirer, target
+ else:
+ # Unknown form type — treat filer as acquirer, try to find target
+ acquirer = company_name
+ for pattern in target_patterns:
+ match = re.search(pattern, search_text)
+ if match:
+ candidate = match.group(1).strip().rstrip(',.')
+ if self._is_valid_company_name(candidate):
+ target = candidate
+ break
+ if not target:
+ target = "Unknown Target"
+ return acquirer, target
def _extract_deal_value(self, text: str) -> Optional[float]:
"""Extract deal value from text"""
for pattern in self.value_patterns:
@@ -283,16 +382,35 @@ class MADealParser:
"""Extract acquisition premiums"""
premiums = {}
- patterns = {
- 'premium_1day': r'(\d+(?:\.\d+)?)\s*%\s*premium.*(?:prior|previous)\s+day',
- 'premium_1week': r'(\d+(?:\.\d+)?)\s*%\s*premium.*(?:prior|previous)\s+week',
- 'premium_4week': r'(\d+(?:\.\d+)?)\s*%\s*premium.*(?:prior|previous)\s+(?:four|4)\s+week'
+ # Multiple patterns per field; first match wins
+ pattern_groups = {
+ 'premium_1day': [
+ r'(\d+(?:\.\d+)?)\s*%\s*premium.*?(?:prior|previous|closing)\s+(?:trading\s+)?day',
+ r'(\d+(?:\.\d+)?)\s*%\s*premium\s+(?:to|over|above)\s+(?:the\s+)?(?:closing|last|prior)\s+(?:share\s+)?price',
+ r'premium\s+of\s+(?:approximately\s+)?(\d+(?:\.\d+)?)\s*%',
+ r'represents\s+(?:a\s+)?(?:premium\s+of\s+)?(?:approximately\s+)?(\d+(?:\.\d+)?)\s*%\s+(?:premium|above|over)',
+ ],
+ 'premium_1week': [
+ r'(\d+(?:\.\d+)?)\s*%\s*premium.*?(?:prior|previous)\s+week',
+ r'(\d+(?:\.\d+)?)\s*%\s*premium.*?(?:7|seven)[- ]day',
+ ],
+ 'premium_4week': [
+ r'(\d+(?:\.\d+)?)\s*%\s*premium.*?(?:prior|previous)\s+(?:four|4)\s+week',
+ r'(\d+(?:\.\d+)?)\s*%\s*premium.*?(?:30|thirty)[- ]day',
+ ],
}
- for key, pattern in patterns.items():
- match = re.search(pattern, text, re.IGNORECASE)
- if match:
- premiums[key] = float(match.group(1))
+ for key, patterns in pattern_groups.items():
+ for pattern in patterns:
+ match = re.search(pattern, text, re.IGNORECASE)
+ if match:
+ try:
+ val = float(match.group(1))
+ if 0 < val < 200: # sanity check
+ premiums[key] = val
+ break
+ except ValueError:
+ pass
return premiums
@@ -375,6 +493,189 @@ class MADealParser:
return advisors[:10]
+ def _is_valid_company_name(self, name: str) -> bool:
+ """Check if a candidate company name is a real company name (not boilerplate text)."""
+ if not name or len(name) < 4:
+ return False
+ # Reject names that are clearly boilerplate/fragment text (too long)
+ if len(name) > 80:
+ return False
+ # Reject names that start with lowercase (boilerplate sentence fragments)
+ stripped = name.strip()
+ if stripped and stripped[0].islower():
+ return False
+ # Reject names containing newlines or multiple spaces (formatting artifacts)
+ if any(c in name for c in (chr(10), chr(13))) or ' ' in name:
+ return False
+ # Reject names that are just legal/SEC boilerplate terms
+ boilerplate_keywords = [
+ 'entity emerging growth', 'agreement of', 'common shares sufficient',
+ 'additional written', 'preferred stock conversion', 'more information about',
+ 'surviving compan', 'pursuant to', 'in connection with', 'following the',
+ 'the company', 'the corporation', 'the acquiror', 'the acquirer', 'the parent',
+ 'each share of', 'all outstanding', 'table of contents', 'capitalization',
+ ]
+ name_lower = name.lower()
+ for kw in boilerplate_keywords:
+ if kw in name_lower:
+ return False
+ return True
+
+ # --- New extraction helpers ---
+
+ def _extract_per_share_price(self, text):
+ """Extract the stated offer price per share."""
+ patterns = [
+ r'\$\s*(\d+\.\d{2})\s+per\s+(?:common\s+)?share',
+ r'(\d+\.\d{2})\s+per\s+(?:common\s+)?share\s+in\s+cash',
+ r'price\s+of\s+\$\s*(\d+\.\d{2})\s+per\s+share',
+ r'consideration\s+of\s+\$\s*(\d+\.\d{2})\s+per\s+share',
+ r'per\s+share\s+(?:merger\s+)?consideration\s+of\s+\$\s*(\d+\.\d{2})',
+ ]
+ for pattern in patterns:
+ match = re.search(pattern, text, re.IGNORECASE)
+ if match:
+ try:
+ return float(match.group(1))
+ except ValueError:
+ pass
+ return None
+
+ def _extract_expected_close(self, text):
+ """Extract expected deal close date/period."""
+ patterns = [
+ r'expected\s+to\s+(?:close|be\s+completed?)\s+(?:in|by|during)\s+(?:the\s+)?([A-Za-z0-9\s]+?\d{4})',
+ r'anticipated\s+to\s+(?:close|be\s+completed?)\s+(?:in|by|during)\s+(?:the\s+)?([A-Za-z0-9\s]+?\d{4})',
+ r'expected\s+to\s+close\s+(?:by|on)\s+([A-Za-z]+\s+\d{1,2},\s*\d{4})',
+ ]
+ for pattern in patterns:
+ match = re.search(pattern, text, re.IGNORECASE)
+ if match:
+ raw2 = match.group(1).strip().rstrip('.')
+ if len(raw2) <= 40:
+ return raw2
+ return None
+
+ def _extract_breakup_fee(self, text):
+ """Extract termination / break-up fee."""
+ patterns = [
+ r'termination\s+fee\s+of\s+\$\s*(\d+(?:\.\d+)?)\s*(billion|million|mn|bn)',
+ r'break[\-\s]?up\s+fee\s+of\s+\$\s*(\d+(?:\.\d+)?)\s*(billion|million|mn|bn)',
+ r'reverse\s+termination\s+fee\s+of\s+\$\s*(\d+(?:\.\d+)?)\s*(billion|million|mn|bn)',
+ r'\$\s*(\d+(?:\.\d+)?)\s*(billion|million|mn|bn)\s+termination\s+fee',
+ ]
+ for pattern in patterns:
+ match = re.search(pattern, text, re.IGNORECASE)
+ if match:
+ try:
+ value = float(match.group(1))
+ unit = match.group(2).lower()
+ if unit in ('billion', 'bn'):
+ return value * 1_000_000_000
+ return value * 1_000_000
+ except (ValueError, IndexError):
+ pass
+ return None
+
+ def _extract_deal_flags(self, text, filing_record):
+ """Detect deal characteristic flags from filing text."""
+ text_lower = text.lower()
+ flags = {}
+ hostile_terms = ['unsolicited', 'without the approval of', 'hostile', 'unwanted bid', 'bear hug']
+ flags['hostile_flag'] = 1 if any(t in text_lower for t in hostile_terms) else 0
+ tender_terms = ['tender offer', 'sc to-t', 'all outstanding shares', 'any and all outstanding shares']
+ ft = filing_record.get('filing_type', '')
+ is_tender = any(t in text_lower for t in tender_terms) or ft in ('SC TO-T', 'SC TO-I')
+ flags['tender_offer_flag'] = 1 if is_tender else 0
+ cross_border_terms = [
+ 'foreign private issuer', 'cayman islands', 'bermuda', 'british columbia',
+ 'ontario', 'united kingdom', 'germany', 'france', 'japan', 'china', 'australia',
+ 'netherlands', 'ireland', 'switzerland', 'singapore', 'hong kong',
+ ]
+ flags['cross_border_flag'] = 1 if any(t in text_lower for t in cross_border_terms) else 0
+ return flags
+
+ # --- XBRL enrichment ---
+
+ def _resolve_party_ciks(self, deal_data):
+ """Populate acquirer_cik and target_cik via CIK resolution (best-effort)."""
+ acquirer = deal_data.get('acquirer_name', '')
+ target = deal_data.get('target_name', '')
+ if acquirer == target:
+ return
+ if acquirer and acquirer != 'Unknown Acquirer':
+ try:
+ cik = self.fetcher.resolve_cik(acquirer)
+ if cik:
+ deal_data['acquirer_cik'] = cik
+ except Exception:
+ pass
+ if target and target != 'Unknown Target':
+ try:
+ cik = self.fetcher.resolve_cik(target)
+ if cik:
+ deal_data['target_cik'] = cik
+ except Exception:
+ pass
+
+ def _enrich_deal_with_xbrl(self, deal_data, deal_id):
+ """Fetch XBRL financials for target company and store deal multiples (optional)."""
+ target_cik = deal_data.get('target_cik')
+ deal_value = deal_data.get('deal_value')
+ target = deal_data.get('target_name', '')
+ acquirer = deal_data.get('acquirer_name', '')
+ if target == acquirer or not target_cik or not deal_value:
+ return
+ try:
+ financials = self.fetcher.get_company_financials(target_cik)
+ if not financials:
+ return
+ annual = financials.get('annual', {})
+ announcement_date = deal_data.get('announcement_date', '')
+ fin_record = {
+ 'deal_id': deal_id, 'period_type': 'LTM', 'party': 'Target',
+ 'data_date': financials.get('period_end', announcement_date),
+ }
+ for key, col in [
+ ('revenue', 'revenue'), ('ebitda', 'ebitda'), ('net_income', 'net_income'),
+ ('total_debt', 'total_debt'), ('cash', 'cash_and_equivalents'),
+ ('shares_outstanding', 'shares_outstanding'), ('total_assets', 'total_assets')
+ ]:
+ if annual.get(key) is not None:
+ fin_record[col] = annual[key]
+ if len(fin_record) > 4:
+ self.db.insert_financials(fin_record)
+ multiples = self.fetcher.calculate_deal_multiples(
+ deal_value=deal_value, target_cik=target_cik, announcement_date=announcement_date)
+ if multiples:
+ mult_record = {
+ 'deal_id': deal_id,
+ 'calculation_date': announcement_date or datetime.now().strftime('%Y-%m-%d'),
+ 'ltm_or_ntm': 'LTM',
+ }
+ if multiples.get('ev_revenue') is not None:
+ mult_record['ev_revenue'] = multiples['ev_revenue']
+ mult_record['target_ev_revenue'] = multiples['ev_revenue']
+ if multiples.get('ev_ebitda') is not None:
+ mult_record['ev_ebitda'] = multiples['ev_ebitda']
+ mult_record['target_ev_ebitda'] = multiples['ev_ebitda']
+ if multiples.get('implied_pe') is not None:
+ mult_record['price_earnings'] = multiples['implied_pe']
+ mult_record['target_pe'] = multiples['implied_pe']
+ if multiples.get('implied_equity_value') is not None:
+ mult_record['implied_equity_value'] = multiples['implied_equity_value']
+ mult_record['implied_enterprise_value'] = deal_value
+ if len(mult_record) > 3:
+ self.db.insert_multiples(mult_record)
+ print(
+ "[Parser] XBRL enriched " + deal_id + ": EV/Rev=" + str(multiples.get('ev_revenue')) +
+ ", EV/EBITDA=" + str(multiples.get('ev_ebitda')),
+ file=sys.stderr
+ )
+ except Exception as e:
+ print("[Parser] XBRL enrichment failed for " + deal_id + ": " + str(e), file=sys.stderr)
+
+
def _generate_deal_id(self, deal_data: Dict[str, Any]) -> str:
"""Generate unique deal ID"""
acquirer = deal_data.get('acquirer_name', 'UNK')[:10].upper().replace(' ', '')
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_scanner.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_scanner.py
index 6337b6e70..920255d20 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_scanner.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_scanner.py
@@ -1,410 +1,494 @@
-"""SEC Filing Scanner for M&A Deal Detection"""
+"""SEC Filing Scanner for M&A Deal Detection
+
+Real data sources (no mocks, no demo data):
+ 1. SEC EDGAR Full-Text Search API (efts.sec.gov) — primary, no key needed
+ 2. SEC EDGAR XBRL/REST API (data.sec.gov) — company-level filing index
+ 3. SEC EDGAR submissions endpoint (data.sec.gov/submissions/) — per-CIK filing history
+
+The scanner works without any third-party library such as edgartools.
+All HTTP calls use the standard library (urllib) so there are zero extra deps.
+"""
import sys
import json
+import re
+import time
from pathlib import Path
-from typing import List, Dict, Any, Optional, Tuple
+from typing import List, Dict, Any, Optional
from datetime import datetime, timedelta
-import re
+from urllib.request import urlopen, Request
+from urllib.error import URLError, HTTPError
+from urllib.parse import urlencode, quote
from concurrent.futures import ThreadPoolExecutor, as_completed
scripts_path = Path(__file__).parent.parent.parent.parent
sys.path.append(str(scripts_path))
-# Add Analytics path for absolute imports
analytics_path = Path(__file__).parent.parent.parent
sys.path.insert(0, str(analytics_path))
-try:
- from edgar_tools import Company, get_filings, Filing
- EDGAR_AVAILABLE = True
-except ImportError:
- try:
- from edgartools import Company, get_filings, Filing
- EDGAR_AVAILABLE = True
- except ImportError:
- # Fallback when edgartools is not available
- EDGAR_AVAILABLE = False
- Company = None
- get_filings = None
- Filing = None
-
-# Use absolute imports instead of relative imports
from corporateFinance.config import MA_FILING_FORMS, MATERIAL_EVENT_ITEMS
from corporateFinance.deal_database.database_schema import MADatabase
-class MADealScanner:
- def __init__(self, db: Optional[MADatabase] = None):
- self.db = db or MADatabase()
- self.ma_keywords = [
- 'merger', 'acquisition', 'acquire', 'purchase', 'takeover',
- 'combination', 'consolidation', 'tender offer', 'definitive agreement',
- 'merger agreement', 'stock purchase', 'asset purchase', 'amalgamation'
- ]
- self.ma_patterns = [
- r'(?:definitive|merger)\s+agreement',
- r'acquire[ds]?\s+(?:all|substantially all)',
- r'tender\s+offer',
- r'cash\s+and\s+stock\s+(?:transaction|deal)',
- r'purchase\s+price\s+of\s+\$[\d,\.]+\s*(?:million|billion)',
- r'(?:merger|acquisition)\s+consideration'
- ]
-
- def scan_recent_filings(self, days_back: int = 30, max_workers: int = 5) -> List[Dict[str, Any]]:
- """Scan recent SEC filings for M&A activity
-
- Scans ALL companies in SEC EDGAR database for M&A-related filings:
- - 8-K (Current Reports - Material Events)
- - S-4 (Merger/Acquisition Registration)
- - DEFM14A (Definitive Merger Proxy)
- - PREM14A (Preliminary Merger Proxy)
- - SC 13D (Beneficial Ownership >5%)
- - 425 (Tender Offer/Merger Communication)
- """
-
- # If edgartools is not available, return mock/demo data
- if not EDGAR_AVAILABLE:
- print("[Scanner] edgartools not available, using demo data")
- return self._get_demo_filings(days_back)
-
- end_date = datetime.now()
- start_date = end_date - timedelta(days=days_back)
-
- potential_deals = []
-
- try:
- with ThreadPoolExecutor(max_workers=max_workers) as executor:
- futures = []
- for form_type in MA_FILING_FORMS:
- future = executor.submit(self._scan_filing_type, form_type, start_date, end_date)
- futures.append(future)
-
- for future in as_completed(futures):
- try:
- results = future.result()
- potential_deals.extend(results)
- except Exception as e:
- print(f"Error scanning filings: {e}")
-
- # If no real filings found, return demo data for demonstration
- if len(potential_deals) == 0:
- print(f"[Scanner] No real M&A filings found in last {days_back} days, using demo data")
- return self._get_demo_filings(days_back)
-
- except Exception as e:
- print(f"[Scanner] Error during scan: {e}, falling back to demo data")
- return self._get_demo_filings(days_back)
-
- return potential_deals
-
- def _scan_filing_type(self, form_type: str, start_date: datetime, end_date: datetime) -> List[Dict[str, Any]]:
- """Scan specific filing type for M&A deals"""
- potential_deals = []
-
- try:
- filings = get_filings(
- form=form_type,
- start_date=start_date.strftime('%Y-%m-%d'),
- end_date=end_date.strftime('%Y-%m-%d')
- )
-
- for filing in filings[:100]:
- deal_info = self._analyze_filing(filing)
- if deal_info and deal_info['confidence_score'] > 0.5:
- potential_deals.append(deal_info)
- self._store_filing(filing, deal_info)
-
- except Exception as e:
- print(f"Error scanning {form_type}: {e}")
+# ---------------------------------------------------------------------------
+# HTTP helpers
+# ---------------------------------------------------------------------------
- return potential_deals
-
- def _analyze_filing(self, filing) -> Optional[Dict[str, Any]]:
- """Analyze if filing contains M&A activity"""
- try:
- text = self._extract_filing_text(filing)
- if not text:
- return None
-
- text_lower = text.lower()
- confidence_score = 0.0
- deal_indicators = []
-
- for keyword in self.ma_keywords:
- if keyword in text_lower:
- confidence_score += 0.1
- deal_indicators.append(keyword)
-
- for pattern in self.ma_patterns:
- if re.search(pattern, text_lower):
- confidence_score += 0.2
- deal_indicators.append(pattern)
-
- if filing.form in ['S-4', 'DEFM14A', 'PREM14A']:
- confidence_score += 0.4
-
- if filing.form == '8-K':
- items = self._extract_8k_items(text)
- if any(item in ['1.01', '2.01'] for item in items):
- confidence_score += 0.3
-
- confidence_score = min(confidence_score, 1.0)
-
- if confidence_score > 0.5:
- return {
- 'accession_number': filing.accession_number,
- 'filing_type': filing.form,
- 'filing_date': filing.filing_date,
- 'company_name': filing.company,
- 'cik': filing.cik,
- 'filing_url': f"https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK={filing.cik}&type={filing.form}&dateb=&owner=exclude&count=100",
- 'confidence_score': confidence_score,
- 'contains_ma_flag': 1,
- 'deal_indicators': ','.join(deal_indicators[:5])
- }
-
- except Exception as e:
- print(f"Error analyzing filing {filing.accession_number}: {e}")
+_EDGAR_HEADERS = {
+ "User-Agent": "Fincept Terminal [email protected]", # SEC requires a valid UA
+ "Accept": "application/json",
+}
+def _get(url: str, timeout: int = 15) -> Optional[dict]:
+ """GET JSON from a URL, return parsed dict or None on error."""
+ try:
+ req = Request(url, headers=_EDGAR_HEADERS)
+ with urlopen(req, timeout=timeout) as resp:
+ return json.loads(resp.read().decode("utf-8"))
+ except HTTPError as exc:
+ if exc.code != 404: # 404s are expected for optional index files — suppress
+ print(f"[Scanner] HTTP {exc.code} {url}", file=sys.stderr)
+ return None
+ except (URLError, json.JSONDecodeError, Exception):
return None
- def _extract_filing_text(self, filing) -> str:
- """Extract text from SEC filing"""
- try:
- if hasattr(filing, 'text'):
- return filing.text()[:50000]
- elif hasattr(filing, 'html'):
- html = filing.html()
- text = re.sub('<[^<]+?>', ' ', html)
- return text[:50000]
- return ""
- except Exception as e:
- print(f"Error extracting text: {e}")
- return ""
-
- def _extract_8k_items(self, text: str) -> List[str]:
- """Extract Item numbers from 8-K filing"""
- items = []
- pattern = r'Item\s+(\d+\.\d+)'
- matches = re.findall(pattern, text)
- return list(set(matches))
-
- def scan_company_ma_history(self, ticker: str, years_back: int = 5) -> List[Dict[str, Any]]:
- """Scan specific company's M&A history"""
- try:
- company = Company(ticker)
- end_date = datetime.now()
- start_date = end_date - timedelta(days=years_back*365)
-
- all_deals = []
-
- for form_type in MA_FILING_FORMS:
- try:
- filings = company.get_filings(
- form=form_type
- ).filter(
- date=f"{start_date.strftime('%Y-%m-%d')}:{end_date.strftime('%Y-%m-%d')}"
- )
+def _get_text(url: str, timeout: int = 20) -> str:
+ """GET raw text from a URL."""
+ try:
+ req = Request(url, headers={**_EDGAR_HEADERS, "Accept": "text/html,text/plain"})
+ with urlopen(req, timeout=timeout) as resp:
+ raw = resp.read()
+ try:
+ return raw.decode("utf-8")[:80000]
+ except UnicodeDecodeError:
+ return raw.decode("latin-1")[:80000]
+ except Exception:
+ return ""
+
+
+# ---------------------------------------------------------------------------
+# M&A signal detection
+# ---------------------------------------------------------------------------
+
+_MA_KEYWORDS = [
+ 'merger', 'acquisition', 'acquire', 'acquiree', 'takeover',
+ 'definitive agreement', 'merger agreement', 'tender offer',
+ 'stock purchase agreement', 'asset purchase agreement',
+ 'combination', 'amalgamation', 'consolidation',
+]
+
+_MA_PATTERNS = [
+ r'definitive\s+(?:merger|acquisition|purchase)\s+agreement',
+ r'tender\s+offer',
+ r'acquire[ds]?\s+(?:all|substantially\s+all)',
+ r'purchase\s+price\s+of\s+\$[\d,\.]+\s*(?:million|billion)',
+ r'aggregate\s+(?:purchase|merger)\s+consideration',
+ r'merger\s+of\s+equals',
+ r'going[\s-]private\s+transaction',
+ r'leveraged\s+buy[-\s]?out',
+]
+
+_HIGH_CONFIDENCE_FORMS = {'S-4', 'DEFM14A', 'PREM14A', 'SC TO-T', 'SC TO-I', 'SC 13E-3'}
+_MEDIUM_CONFIDENCE_FORMS = {'8-K', '425', 'SC 13D'}
+
+def _score_text(text: str, form_type: str) -> tuple[float, list]:
+ """Return (confidence_score 0-1, indicators list) for a piece of filing text."""
+ text_lower = text.lower()
+ score = 0.0
+ indicators = []
+
+ # Form-type bonus
+ if form_type in _HIGH_CONFIDENCE_FORMS:
+ score += 0.45
+ elif form_type in _MEDIUM_CONFIDENCE_FORMS:
+ score += 0.15
+
+ # Keyword hits (cap contribution)
+ kw_hits = 0
+ for kw in _MA_KEYWORDS:
+ if kw in text_lower:
+ kw_hits += 1
+ indicators.append(kw)
+ score += min(kw_hits * 0.07, 0.35)
+
+ # Regex pattern hits
+ for pat in _MA_PATTERNS:
+ if re.search(pat, text_lower):
+ score += 0.10
+ indicators.append(pat[:40])
+
+ # 8-K item 1.01 / 2.01 boost
+ if form_type == '8-K':
+ items_found = re.findall(r'Item\s+(\d+\.\d+)', text)
+ if any(i in MATERIAL_EVENT_ITEMS for i in items_found):
+ score += 0.20
+
+ return min(score, 1.0), indicators[:8]
+
+
+# ---------------------------------------------------------------------------
+# EDGAR Full-Text Search (efts.sec.gov) — primary real-data source
+# ---------------------------------------------------------------------------
+
+_EFTS_BASE = "https://efts.sec.gov/LATEST/search-index"
+_EFTS_SEARCH = "https://efts.sec.gov/LATEST/search-index?q={query}&dateRange=custom&startdt={start}&enddt={end}&forms={forms}&hits.hits._source=file_date,period_of_report,entity_name,file_num,form_type,biz_location,inc_states&hits.hits.total.value=true&hits.hits.highlight=false&hits.hits.highlight.number_of_fragments=0&_source=false"
+
+_EFTS_API = "https://efts.sec.gov/LATEST/search-index?q={query}&dateRange=custom&startdt={start}&enddt={end}&forms={forms}&hits.hits.total.value=true"
+
+# Simpler, more reliable EFTS endpoint
+_EFTS_SIMPLE = "https://efts.sec.gov/LATEST/search-index?q=%22{query}%22&forms={forms}&dateRange=custom&startdt={start}&enddt={end}"
+
+
+def _efts_search(query_term: str, form_types: List[str],
+ start_date: str, end_date: str,
+ max_hits: int = 50) -> List[Dict[str, Any]]:
+ """
+ Search SEC EDGAR Full-Text Search API for filings matching query_term.
+ Returns list of hit dicts with accession_number, entity_name, form_type, etc.
+ """
+ # URL-encode each form name individually (handles spaces in "SC TO-T", "SC 13E-3", etc.)
+ forms_str = ",".join(quote(f, safe="") for f in form_types)
+ # EDGAR EFTS uses %22 for quotes in the q param
+ encoded_query = quote(query_term, safe="")
+ url = (
+ f"https://efts.sec.gov/LATEST/search-index"
+ f"?q=%22{encoded_query}%22"
+ f"&forms={forms_str}"
+ f"&dateRange=custom&startdt={start_date}&enddt={end_date}"
+ f"&hits.hits.total.value=true"
+ )
+ data = _get(url)
+ if not data:
+ return []
+
+ hits = data.get("hits", {}).get("hits", [])
+ results = []
+ seen_acc = set()
+ for hit in hits[:max_hits]:
+ src = hit.get("_source", {})
+ # `adsh` is the clean accession number (e.g. "0001193125-26-056047")
+ acc = src.get("adsh", "")
+ if not acc:
+ # fallback: _id is "accession:filename", strip the filename part
+ raw_id = hit.get("_id", "")
+ acc = raw_id.split(":")[0] if ":" in raw_id else raw_id
+ if not acc or acc in seen_acc:
+ continue
+ seen_acc.add(acc)
+
+ # display_names format: "Company Name (TICK) (CIK 0000XXXXXX)"
+ display_names = src.get("display_names", [])
+ entity_name = display_names[0].split("(")[0].strip() if display_names else ""
+
+ # ciks is a list of zero-padded CIK strings
+ ciks = src.get("ciks", [])
+ cik = ciks[0].lstrip("0") if ciks else ""
+
+ # root_forms is a list; form is the specific filing form
+ form_type = src.get("form", src.get("root_forms", [""])[0] if src.get("root_forms") else "")
+
+ results.append({
+ "accession_number": acc,
+ "entity_name": entity_name,
+ "form_type": form_type,
+ "file_date": src.get("file_date", ""),
+ "cik": cik,
+ "items": src.get("items", []),
+ })
+ return results
+
+
+# ---------------------------------------------------------------------------
+# EDGAR submissions endpoint — get filing index per CIK
+# ---------------------------------------------------------------------------
+
+def _get_company_recent_filings(cik_str: str, form_types: List[str],
+ start_date: str, end_date: str) -> List[Dict[str, Any]]:
+ """Fetch recent filings for a given CIK via data.sec.gov/submissions/."""
+ cik_padded = cik_str.zfill(10)
+ url = f"https://data.sec.gov/submissions/CIK{cik_padded}.json"
+ data = _get(url)
+ if not data:
+ return []
+
+ entity_name = data.get("name", "")
+ recent = data.get("filings", {}).get("recent", {})
+ forms = recent.get("form", [])
+ dates = recent.get("filingDate", [])
+ acc_nums = recent.get("accessionNumber", [])
+
+ results = []
+ for form, date_str, acc in zip(forms, dates, acc_nums):
+ if form not in form_types:
+ continue
+ if date_str < start_date or date_str > end_date:
+ continue
+ results.append({
+ "accession_number": acc,
+ "entity_name": entity_name,
+ "form_type": form,
+ "file_date": date_str,
+ "cik": cik_str,
+ })
+ return results
+
+
+# ---------------------------------------------------------------------------
+# Filing text fetcher — EDGAR viewer / raw document
+# ---------------------------------------------------------------------------
+
+def _fetch_filing_text(accession_number: str, cik: str) -> str:
+ """Fetch the primary document text for an accession number."""
+ # acc_clean removes dashes: "0001193125-26-056047" → "000119312526056047"
+ acc_clean = accession_number.replace("-", "")
+ cik_int = cik.lstrip("0") or "0" # numeric CIK without leading zeros for URL path
+
+ # 1. Try the JSON filing index: /Archives/edgar/data/{cik}/{acc_clean}/{acc}-index.json
+ index_url = (
+ f"https://www.sec.gov/Archives/edgar/data/{cik_int}"
+ f"/{acc_clean}/{accession_number}-index.json"
+ )
+ index_data = _get(index_url)
+ if index_data:
+ documents = index_data.get("directory", {}).get("item", [])
+ for doc in documents:
+ name = doc.get("name", "")
+ if name.endswith((".htm", ".txt", ".html")):
+ doc_url = f"https://www.sec.gov/Archives/edgar/data/{cik_int}/{acc_clean}/{name}"
+ text = _get_text(doc_url)
+ if text:
+ return re.sub(r'<[^>]+>', ' ', text)[:60000]
+
+ # 2. Fallback: directory listing page
+ if cik_int:
+ viewer_url = f"https://www.sec.gov/Archives/edgar/data/{cik_int}/{acc_clean}/"
+ text = _get_text(viewer_url)
+ if text:
+ return re.sub(r'<[^>]+>', ' ', text)[:60000]
+
+ return ""
+
+
+# ---------------------------------------------------------------------------
+# Main scanner class
+# ---------------------------------------------------------------------------
- for filing in filings:
- deal_info = self._analyze_filing(filing)
- if deal_info and deal_info['confidence_score'] > 0.5:
- all_deals.append(deal_info)
- self._store_filing(filing, deal_info)
+class MADealScanner:
+ """
+ Scan SEC EDGAR for real M&A deal signals.
+
+ Strategy (all free, no API key, no third-party library):
+ 1. Full-text search (efts.sec.gov) with M&A trigger phrases across
+ high-signal form types (S-4, DEFM14A, 8-K, 425, SC TO-T …).
+ 2. For each hit, optionally fetch the filing document to score text
+ and extract deal metadata.
+ 3. Persist discovered filings in the SQLite database.
+ """
+
+ # M&A trigger phrases sent to EFTS — each returns REAL matching filings
+ _SEARCH_QUERIES = [
+ "definitive merger agreement",
+ "definitive acquisition agreement",
+ "tender offer",
+ "merger of equals",
+ "acquire all outstanding shares",
+ "going private transaction",
+ "leveraged buyout",
+ "stock purchase agreement",
+ "asset purchase agreement",
+ "agreement and plan of merger",
+ ]
+
+ _SCAN_FORMS = ["S-4", "DEFM14A", "PREM14A", "8-K", "425", "SC TO-T", "SC TO-I", "SC 13E-3"]
- except Exception as e:
- print(f"Error getting {form_type} for {ticker}: {e}")
+ def __init__(self, db: Optional[MADatabase] = None):
+ self.db = db or MADatabase()
- return all_deals
+ # ------------------------------------------------------------------
+ # Public API
+ # ------------------------------------------------------------------
- except Exception as e:
- print(f"Error scanning company {ticker}: {e}")
- return []
+ def scan_recent_filings(self, days_back: int = 30,
+ max_workers: int = 4) -> List[Dict[str, Any]]:
+ """
+ Scan SEC EDGAR for M&A filings in the last `days_back` days.
+ Returns list of filing dicts suitable for storing in sec_filings table.
+ """
+ end_date = datetime.now()
+ start_date = end_date - timedelta(days=days_back)
+ start_str = start_date.strftime("%Y-%m-%d")
+ end_str = end_date.strftime("%Y-%m-%d")
- def scan_industry_ma_activity(self, industry_ciks: List[str], days_back: int = 90) -> List[Dict[str, Any]]:
- """Scan M&A activity for specific industry"""
- all_deals = []
+ print(f"[Scanner] Scanning EDGAR {start_str} → {end_str}", file=sys.stderr)
- with ThreadPoolExecutor(max_workers=10) as executor:
- futures = {executor.submit(self._scan_cik, cik, days_back): cik for cik in industry_ciks}
+ all_filings: Dict[str, Dict[str, Any]] = {} # keyed by accession_number to deduplicate
+ # Run all query terms in parallel
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
+ futures = {
+ pool.submit(self._search_one_query, q, start_str, end_str): q
+ for q in self._SEARCH_QUERIES
+ }
for future in as_completed(futures):
try:
- deals = future.result()
- all_deals.extend(deals)
- except Exception as e:
- print(f"Error scanning CIK: {e}")
-
- return all_deals
-
- def _scan_cik(self, cik: str, days_back: int) -> List[Dict[str, Any]]:
- """Scan specific CIK for M&A filings"""
- try:
- company = Company(cik)
- end_date = datetime.now()
- start_date = end_date - timedelta(days=days_back)
-
- deals = []
- for form_type in ['8-K', 'S-4', 'DEFM14A']:
- try:
- filings = company.get_filings(form=form_type)
- for filing in filings[:10]:
- if filing.filing_date >= start_date.date():
- deal_info = self._analyze_filing(filing)
- if deal_info and deal_info['confidence_score'] > 0.6:
- deals.append(deal_info)
- except:
- continue
-
- return deals
-
- except Exception as e:
+ hits = future.result()
+ for h in hits:
+ acc = h["accession_number"]
+ if acc and acc not in all_filings:
+ all_filings[acc] = h
+ except Exception as exc:
+ print(f"[Scanner] Query error: {exc}", file=sys.stderr)
+
+ results = list(all_filings.values())
+ print(f"[Scanner] Found {len(results)} unique filings", file=sys.stderr)
+
+ # Persist to DB
+ for filing in results:
+ self._store_filing(filing)
+
+ return results
+
+ def scan_company_ma_history(self, ticker_or_cik: str,
+ years_back: int = 5) -> List[Dict[str, Any]]:
+ """Scan a specific company's M&A filing history via data.sec.gov."""
+ end_date = datetime.now()
+ start_date = end_date - timedelta(days=years_back * 365)
+ start_str = start_date.strftime("%Y-%m-%d")
+ end_str = end_date.strftime("%Y-%m-%d")
+
+ # Resolve ticker → CIK using EDGAR company search
+ cik = self._resolve_cik(ticker_or_cik)
+ if not cik:
+ print(f"[Scanner] Could not resolve CIK for {ticker_or_cik}", file=sys.stderr)
return []
- def _store_filing(self, filing, deal_info: Dict[str, Any]):
- """Store filing information in database"""
- try:
- filing_data = {
- 'accession_number': deal_info['accession_number'],
- 'filing_type': deal_info['filing_type'],
- 'filing_date': deal_info['filing_date'],
- 'company_name': deal_info['company_name'],
- 'cik': deal_info['cik'],
- 'filing_url': deal_info['filing_url'],
- 'confidence_score': deal_info['confidence_score'],
- 'contains_ma_flag': deal_info['contains_ma_flag'],
- 'parsed_flag': 0
- }
-
- self.db.insert_sec_filing(filing_data)
-
- except Exception as e:
- print(f"Error storing filing: {e}")
+ raw = _get_company_recent_filings(cik, self._SCAN_FORMS, start_str, end_str)
+ results = []
+ for hit in raw:
+ scored = self._score_and_enrich(hit)
+ if scored and scored["confidence_score"] >= 0.5:
+ results.append(scored)
+ self._store_filing(scored)
+ return results
def get_high_confidence_deals(self, min_confidence: float = 0.75) -> List[Dict[str, Any]]:
- """Get high confidence M&A deals from database"""
+ """Return high-confidence M&A filings already stored in the DB."""
conn = self.db._get_connection()
cursor = conn.cursor()
-
cursor.execute("""
SELECT * FROM sec_filings
- WHERE contains_ma_flag = 1
- AND confidence_score >= ?
- AND parsed_flag = 0
+ WHERE contains_ma_flag = 1 AND confidence_score >= ?
+ AND parsed_flag = 0
ORDER BY filing_date DESC
""", (min_confidence,))
-
return [dict(row) for row in cursor.fetchall()]
- def batch_scan_sp500(self, days_back: int = 30) -> Dict[str, Any]:
- """Scan all S&P 500 companies for M&A activity"""
- sp500_tickers = self._get_sp500_tickers()
-
- total_deals = []
- successful_scans = 0
- failed_scans = 0
-
- with ThreadPoolExecutor(max_workers=10) as executor:
- futures = {executor.submit(self.scan_company_ma_history, ticker, days_back//365): ticker
- for ticker in sp500_tickers[:50]}
-
- for future in as_completed(futures):
- try:
- deals = future.result()
- total_deals.extend(deals)
- successful_scans += 1
- except:
- failed_scans += 1
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _search_one_query(self, query: str, start_str: str,
+ end_str: str) -> List[Dict[str, Any]]:
+ """Run one EFTS query and return enriched filing dicts."""
+ hits = _efts_search(query, self._SCAN_FORMS, start_str, end_str, max_hits=40)
+ enriched = []
+ for hit in hits:
+ scored = self._score_and_enrich(hit)
+ if scored and scored["confidence_score"] >= 0.5:
+ enriched.append(scored)
+ time.sleep(0.05) # Polite rate limiting for SEC servers
+ return enriched
+
+ def _score_and_enrich(self, hit: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ """
+ Given a raw EFTS/submissions hit, compute confidence score and
+ build the standard filing dict. Fetches document text only for
+ medium-confidence forms (8-K, 425) where text analysis adds value.
+ """
+ form_type = hit.get("form_type", "")
+ acc = hit.get("accession_number", "")
+ cik = hit.get("cik", "")
+ entity = hit.get("entity_name", "")
+ file_date = hit.get("file_date", "")
+
+ # For high-signal forms, score is already high from form type alone
+ if form_type in _HIGH_CONFIDENCE_FORMS:
+ score = 0.90
+ indicators = [f"form:{form_type}"]
+ else:
+ # Check 8-K items from EFTS metadata first (no text fetch needed)
+ items = hit.get("items", [])
+ if form_type == "8-K" and any(i in MATERIAL_EVENT_ITEMS for i in items):
+ # Item 1.01 = material definitive agreement, 2.01 = completion of acquisition
+ score = 0.80
+ indicators = [f"form:{form_type}", f"items:{','.join(items)}"]
+ else:
+ # Fetch document text for scoring (only for forms worth checking)
+ text = _fetch_filing_text(acc, cik) if cik else ""
+ score, indicators = _score_text(text or f"form_type:{form_type}", form_type)
+
+ if score < 0.50:
+ return None
+
+ filing_url = (
+ f"https://www.sec.gov/cgi-bin/browse-edgar"
+ f"?action=getcompany&CIK={cik}&type={form_type}&dateb=&owner=include&count=10"
+ ) if cik else f"https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&type={form_type}"
return {
- 'total_deals_found': len(total_deals),
- 'companies_scanned': successful_scans,
- 'failed_scans': failed_scans,
- 'deals': total_deals
+ "accession_number": acc,
+ "filing_type": form_type,
+ "filing_date": file_date,
+ "company_name": entity,
+ "cik": cik,
+ "filing_url": filing_url,
+ "confidence_score": round(score, 3),
+ "contains_ma_flag": 1,
+ "deal_indicators": ", ".join(indicators[:6]),
}
- def _get_sp500_tickers(self) -> List[str]:
- """Get S&P 500 tickers"""
- return [
- 'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'NVDA', 'META', 'TSLA', 'BRK.B', 'UNH', 'JNJ',
- 'XOM', 'V', 'PG', 'JPM', 'MA', 'HD', 'CVX', 'MRK', 'ABBV', 'PEP', 'COST', 'AVGO',
- 'KO', 'LLY', 'WMT', 'MCD', 'TMO', 'ABT', 'ACN', 'CSCO', 'DHR', 'CRM', 'VZ', 'NEE'
- ]
-
- def _get_demo_filings(self, days_back: int) -> List[Dict[str, Any]]:
- """Return demo filings when edgartools is not available"""
- today = datetime.now()
- demo_filings = [
- {
- 'accession_number': '0001193125-24-012345',
- 'filing_type': 'S-4',
- 'filing_date': (today - timedelta(days=5)).strftime('%Y-%m-%d'),
- 'company_name': 'ACME Corporation',
- 'cik': '0001234567',
- 'filing_url': 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0001234567',
- 'confidence_score': 0.92,
- 'contains_ma_flag': 1,
- 'deal_indicators': 'merger,definitive agreement,acquisition,purchase price'
- },
- {
- 'accession_number': '0001193125-24-012346',
- 'filing_type': '8-K',
- 'filing_date': (today - timedelta(days=12)).strftime('%Y-%m-%d'),
- 'company_name': 'TechCo Inc.',
- 'cik': '0001234568',
- 'filing_url': 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0001234568',
- 'confidence_score': 0.85,
- 'contains_ma_flag': 1,
- 'deal_indicators': 'acquisition,tender offer,merger agreement'
- },
- {
- 'accession_number': '0001193125-24-012347',
- 'filing_type': 'DEFM14A',
- 'filing_date': (today - timedelta(days=18)).strftime('%Y-%m-%d'),
- 'company_name': 'BioPharma Solutions',
- 'cik': '0001234569',
- 'filing_url': 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0001234569',
- 'confidence_score': 0.95,
- 'contains_ma_flag': 1,
- 'deal_indicators': 'definitive agreement,merger,cash and stock transaction'
- },
- {
- 'accession_number': '0001193125-24-012348',
- 'filing_type': '8-K',
- 'filing_date': (today - timedelta(days=22)).strftime('%Y-%m-%d'),
- 'company_name': 'FinTech Innovations LLC',
- 'cik': '0001234570',
- 'filing_url': 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0001234570',
- 'confidence_score': 0.78,
- 'contains_ma_flag': 1,
- 'deal_indicators': 'acquire,stock purchase,takeover'
- },
- {
- 'accession_number': '0001193125-24-012349',
- 'filing_type': 'PREM14A',
- 'filing_date': (today - timedelta(days=28)).strftime('%Y-%m-%d'),
- 'company_name': 'Global Energy Partners',
- 'cik': '0001234571',
- 'filing_url': 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0001234571',
- 'confidence_score': 0.88,
- 'contains_ma_flag': 1,
- 'deal_indicators': 'merger,combination,definitive agreement'
- }
- ]
+ def _resolve_cik(self, ticker_or_cik: str) -> Optional[str]:
+ """Resolve a ticker symbol or CIK string to a zero-padded CIK."""
+ # If it's already numeric, use directly
+ if ticker_or_cik.isdigit():
+ return ticker_or_cik
+
+ url = f"https://www.sec.gov/cgi-bin/browse-edgar?company={ticker_or_cik}&CIK=&type=&dateb=&owner=include&count=5&search_text=&action=getcompany&output=atom"
+ # Use company tickers JSON — faster and more reliable
+ tickers_url = "https://www.sec.gov/files/company_tickers.json"
+ data = _get(tickers_url)
+ if data:
+ for entry in data.values():
+ if entry.get("ticker", "").upper() == ticker_or_cik.upper():
+ return str(entry["cik_str"])
+ return None
- # Filter by days_back
- cutoff_date = today - timedelta(days=days_back)
- return [f for f in demo_filings if datetime.strptime(f['filing_date'], '%Y-%m-%d') >= cutoff_date]
+ def _store_filing(self, filing: Dict[str, Any]):
+ """Persist filing to sec_filings table (silently skip duplicates)."""
+ try:
+ self.db.insert_sec_filing({
+ "accession_number": filing["accession_number"],
+ "filing_type": filing["filing_type"],
+ "filing_date": filing["filing_date"],
+ "company_name": filing["company_name"],
+ "cik": filing.get("cik", ""),
+ "filing_url": filing.get("filing_url", ""),
+ "confidence_score": filing.get("confidence_score", 0.0),
+ "contains_ma_flag": filing.get("contains_ma_flag", 1),
+ "parsed_flag": 0,
+ })
+ except Exception as exc:
+ print(f"[Scanner] Store error: {exc}", file=sys.stderr)
+
+
+# ---------------------------------------------------------------------------
+# CLI entry point
+# ---------------------------------------------------------------------------
def main():
- """CLI entry point - outputs JSON for Tauri integration"""
- import json
+ import json as _json
if len(sys.argv) < 2:
- result = {
- "success": False,
- "error": "No command specified. Usage: deal_scanner.py <command> [args...]"
- }
- print(json.dumps(result))
+ print(_json.dumps({"success": False, "error": "No command. Usage: deal_scanner.py <scan|scan_company|high_confidence> [args]"}))
sys.exit(1)
command = sys.argv[1]
@@ -412,85 +496,31 @@ def main():
try:
if command == "scan":
- # scan_ma_filings(days_back, filing_types)
days_back = int(sys.argv[2]) if len(sys.argv) > 2 else 30
- filing_types = sys.argv[3] if len(sys.argv) > 3 else None
-
deals = scanner.scan_recent_filings(days_back=days_back)
-
- result = {
- "success": True,
- "data": deals,
- "count": len(deals),
- "days_scanned": days_back
- }
- print(json.dumps(result))
+ print(_json.dumps({"success": True, "data": deals, "count": len(deals), "days_scanned": days_back}))
elif command == "scan_company":
- # Scan specific company's M&A history
if len(sys.argv) < 3:
- raise ValueError("Ticker required for scan_company command")
-
+ raise ValueError("Ticker or CIK required")
ticker = sys.argv[2]
- years_back = int(sys.argv[3]) if len(sys.argv) > 3 else 5
-
+ years_back = int(sys.argv[3]) if len(sys.argv) > 3 else 3
deals = scanner.scan_company_ma_history(ticker, years_back)
-
- result = {
- "success": True,
- "data": deals,
- "ticker": ticker,
- "count": len(deals)
- }
- print(json.dumps(result))
-
- elif command == "scan_industry":
- # Scan industry M&A activity
- if len(sys.argv) < 3:
- raise ValueError("CIK list required for scan_industry command")
-
- import json as json_module
- cik_list = json_module.loads(sys.argv[2])
- days_back = int(sys.argv[3]) if len(sys.argv) > 3 else 90
-
- deals = scanner.scan_industry_ma_activity(cik_list, days_back)
-
- result = {
- "success": True,
- "data": deals,
- "count": len(deals)
- }
- print(json.dumps(result))
+ print(_json.dumps({"success": True, "data": deals, "ticker": ticker, "count": len(deals)}))
elif command == "high_confidence":
- # Get high confidence deals
- min_confidence = float(sys.argv[2]) if len(sys.argv) > 2 else 0.75
- deals = scanner.get_high_confidence_deals(min_confidence)
-
- result = {
- "success": True,
- "data": deals,
- "count": len(deals),
- "min_confidence": min_confidence
- }
- print(json.dumps(result))
+ min_conf = float(sys.argv[2]) if len(sys.argv) > 2 else 0.75
+ deals = scanner.get_high_confidence_deals(min_conf)
+ print(_json.dumps({"success": True, "data": deals, "count": len(deals), "min_confidence": min_conf}))
else:
- result = {
- "success": False,
- "error": f"Unknown command: {command}. Available: scan, scan_company, scan_industry, high_confidence"
- }
- print(json.dumps(result))
+ print(_json.dumps({"success": False, "error": f"Unknown command: {command}. Available: scan, scan_company, high_confidence"}))
sys.exit(1)
- except Exception as e:
- result = {
- "success": False,
- "error": str(e),
- "command": command
- }
- print(json.dumps(result))
+ except Exception as exc:
+ print(_json.dumps({"success": False, "error": str(exc), "command": command}))
sys.exit(1)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_tracker.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_tracker.py
index d7e5d0591..4ef369830 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_tracker.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_tracker.py
@@ -11,7 +11,7 @@ sys.path.insert(0, str(analytics_path))
# Use absolute imports instead of relative imports
from corporateFinance.deal_database.database_schema import MADatabase
-from corporateFinance.deal_database.deal_scanner import MADealScanner, EDGAR_AVAILABLE
+from corporateFinance.deal_database.deal_scanner import MADealScanner
try:
from corporateFinance.deal_database.deal_parser import MADealParser
@@ -20,99 +20,6 @@ except ImportError:
MADealParser = None
PARSER_AVAILABLE = False
-# Demo deal data that maps to MADeal schema for when edgartools is unavailable
-_DEMO_DEALS = [
- {
- 'deal_id': 'ACMECORP_WIDGETINC_20260205',
- 'acquirer_name': 'ACME Corporation',
- 'target_name': 'Widget Industries Inc.',
- 'deal_value': 4_200_000_000,
- 'deal_type': 'Merger',
- 'deal_status': 'Pending',
- 'payment_method': 'Mixed',
- 'cash_percentage': 60.0,
- 'stock_percentage': 40.0,
- 'industry': 'Technology',
- 'premium_1day': 32.5,
- 'premium_4week': 41.2,
- 'announcement_date': None, # filled dynamically
- 'data_source': 'SEC EDGAR (demo)',
- 'filing_url': 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0001234567',
- 'synergies_disclosed': 350_000_000,
- },
- {
- 'deal_id': 'TECHCO_CLOUDSYS_20260129',
- 'acquirer_name': 'TechCo Inc.',
- 'target_name': 'CloudSys Technologies',
- 'deal_value': 1_800_000_000,
- 'deal_type': 'Acquisition',
- 'deal_status': 'Announced',
- 'payment_method': 'Cash',
- 'cash_percentage': 100.0,
- 'stock_percentage': 0.0,
- 'industry': 'Technology',
- 'premium_1day': 28.0,
- 'premium_4week': 35.7,
- 'announcement_date': None,
- 'data_source': 'SEC EDGAR (demo)',
- 'filing_url': 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0001234568',
- 'synergies_disclosed': 120_000_000,
- },
- {
- 'deal_id': 'BIOPHRM_GENETHX_20260123',
- 'acquirer_name': 'BioPharma Solutions',
- 'target_name': 'GeneTherapeutics Corp.',
- 'deal_value': 6_500_000_000,
- 'deal_type': 'Merger',
- 'deal_status': 'Pending',
- 'payment_method': 'Mixed',
- 'cash_percentage': 75.0,
- 'stock_percentage': 25.0,
- 'industry': 'Healthcare',
- 'premium_1day': 45.3,
- 'premium_4week': 52.1,
- 'announcement_date': None,
- 'data_source': 'SEC EDGAR (demo)',
- 'filing_url': 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0001234569',
- 'synergies_disclosed': 800_000_000,
- },
- {
- 'deal_id': 'FINTECH_PAYNET_20260119',
- 'acquirer_name': 'FinTech Innovations LLC',
- 'target_name': 'PayNet Solutions',
- 'deal_value': 950_000_000,
- 'deal_type': 'Acquisition',
- 'deal_status': 'Announced',
- 'payment_method': 'Stock',
- 'cash_percentage': 0.0,
- 'stock_percentage': 100.0,
- 'industry': 'Financial Services',
- 'premium_1day': 22.0,
- 'premium_4week': 30.5,
- 'announcement_date': None,
- 'data_source': 'SEC EDGAR (demo)',
- 'filing_url': 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0001234570',
- 'synergies_disclosed': 75_000_000,
- },
- {
- 'deal_id': 'GLOBEN_SOLARMAX_20260113',
- 'acquirer_name': 'Global Energy Partners',
- 'target_name': 'SolarMax Renewables',
- 'deal_value': 3_100_000_000,
- 'deal_type': 'Merger',
- 'deal_status': 'Pending',
- 'payment_method': 'Mixed',
- 'cash_percentage': 50.0,
- 'stock_percentage': 50.0,
- 'industry': 'Energy',
- 'premium_1day': 38.7,
- 'premium_4week': 44.0,
- 'announcement_date': None,
- 'data_source': 'SEC EDGAR (demo)',
- 'filing_url': 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0001234571',
- 'synergies_disclosed': 250_000_000,
- },
-]
class MADealTracker:
def __init__(self, db_path: Optional[Path] = None):
@@ -168,22 +75,8 @@ class MADealTracker:
results['parsing_failed'] += 1
print(f"[DealTracker] Parse error: {e}", file=sys.stderr)
- # If parser unavailable or all parsing failed, create synthetic deals from demo data
- if results['deals_parsed'] == 0 and not EDGAR_AVAILABLE:
- print("[DealTracker] Parser unavailable, creating deals from demo data...", file=sys.stderr)
- today = datetime.now()
- for i, demo_deal in enumerate(_DEMO_DEALS):
- deal = dict(demo_deal)
- # Set announcement_date from corresponding filing date
- if i < len(filings):
- deal['announcement_date'] = filings[i]['filing_date']
- else:
- deal['announcement_date'] = (today - timedelta(days=5 * (i + 1))).strftime('%Y-%m-%d')
- try:
- self.db.insert_deal(deal)
- results['deals_created'] += 1
- except Exception as e:
- print(f"[DealTracker] Failed to create demo deal: {e}", file=sys.stderr)
+ if results['deals_parsed'] == 0:
+ print("[DealTracker] No deals parsed from filings.", file=sys.stderr)
return results
@@ -382,15 +275,33 @@ def main():
days_back = int(sys.argv[2]) if len(sys.argv) > 2 else 7
result = tracker.update_deal_database(days_back=days_back)
- # Also return current deals so frontend can use them
- all_deals = tracker.db.get_all_deals()
+ # Return only summary + slim filing list (no full deals query — frontend calls get_all separately)
+ filings = result.get('filings', [])
+ slim_filings = [
+ {
+ 'accession_number': f.get('accession_number', ''),
+ 'filing_type': f.get('filing_type', ''),
+ 'filing_date': f.get('filing_date', ''),
+ 'company_name': f.get('company_name', ''),
+ 'cik': f.get('cik', ''),
+ 'filing_url': f.get('filing_url', ''),
+ 'confidence_score': f.get('confidence_score', 0),
+ 'deal_indicators': f.get('deal_indicators', ''),
+ }
+ for f in filings
+ ]
output = {
"success": True,
"data": {
- **result,
- 'deals': all_deals,
- 'deals_count': len(all_deals),
+ 'filings_found': result.get('filings_found', 0),
+ 'deals_parsed': result.get('deals_parsed', 0),
+ 'deals_created': result.get('deals_created', 0),
+ 'parsing_failed': result.get('parsing_failed', 0),
+ 'timestamp': result.get('timestamp', ''),
+ 'filings': slim_filings,
+ 'deals': [],
+ 'deals_count': 0,
}
}
print(json.dumps(output, default=str))
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/edgar_fetcher.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/edgar_fetcher.py
new file mode 100644
index 000000000..19f3479c4
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/edgar_fetcher.py
@@ -0,0 +1,683 @@
+"""SEC EDGAR Fetcher - All HTTP operations, CIK resolution, XBRL financial data.
+
+Zero external dependencies — uses stdlib urllib only.
+Designed for M&A deal enrichment in Fincept Terminal.
+"""
+import json
+import re
+import sys
+import time
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
+from urllib.error import HTTPError, URLError
+from urllib.request import Request, urlopen
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+_HEADERS = {
+ "User-Agent": "Fincept Terminal [email protected]",
+ "Accept": "application/json,text/html,text/plain",
+ "Accept-Encoding": "gzip, deflate",
+}
+
+# XBRL tag fallback lists — companies use many different tag names for the same concept
+REVENUE_TAGS = [
+ "RevenueFromContractWithCustomerExcludingAssessedTax",
+ "RevenueFromContractWithCustomerIncludingAssessedTax",
+ "Revenues",
+ "RevenueNet",
+ "SalesRevenueNet",
+ "SalesRevenueGoodsNet",
+ "RevenuesNetOfInterestExpense", # banks
+ "InterestAndDividendIncomeOperating", # financial companies
+ "HealthCareOrganizationRevenue", # healthcare
+ "RealEstateRevenueNet", # REITs
+ "OilAndGasRevenue", # energy
+ "ElectricUtilityRevenue", # utilities
+ "GrossProfit", # last resort
+]
+
+NET_INCOME_TAGS = [
+ "NetIncomeLoss",
+ "NetIncomeLossAvailableToCommonStockholdersBasic",
+ "ProfitLoss",
+ "IncomeLossFromContinuingOperations",
+ "NetIncome",
+]
+
+INTEREST_EXPENSE_TAGS = [
+ "InterestExpense",
+ "InterestExpenseDebt",
+ "InterestAndDebtExpense",
+ "FinancingInterestExpense",
+]
+
+DA_TAGS = [
+ "DepreciationDepletionAndAmortization",
+ "Depreciation",
+ "DepreciationAndAmortization",
+ "AmortizationOfIntangibleAssets",
+ "DepreciationAmortizationAndAccretionNet",
+]
+
+INCOME_TAX_TAGS = [
+ "IncomeTaxExpenseBenefit",
+ "CurrentIncomeTaxExpenseBenefit",
+]
+
+TOTAL_DEBT_TAGS = [
+ "LongTermDebt",
+ "LongTermDebtNoncurrent",
+ "DebtLongtermAndShorttermCombinedAmount",
+ "LongTermDebtAndCapitalLeaseObligations",
+ "LongTermNotesPayable",
+ "NotesPayable",
+ "ConvertibleNotesPayable",
+]
+
+CASH_TAGS = [
+ "CashAndCashEquivalentsAtCarryingValue",
+ "CashCashEquivalentsAndShortTermInvestments",
+ "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents",
+ "Cash",
+]
+
+SHARES_TAGS = [
+ "CommonStockSharesOutstanding",
+ "CommonStockSharesIssued",
+ "EntityCommonStockSharesOutstanding",
+]
+
+TOTAL_ASSETS_TAGS = [
+ "Assets",
+ "AssetsCurrent",
+]
+
+EBIT_TAGS = [
+ "OperatingIncomeLoss",
+ "IncomeLossFromContinuingOperationsBeforeIncomeTaxesExtraordinaryItemsNoncontrollingInterest",
+]
+
+
+class EdgarFetcher:
+ """All SEC EDGAR HTTP operations for M&A deal enrichment."""
+
+ def __init__(self):
+ # In-memory cache: cik -> company-facts dict (large JSON, avoid re-fetching)
+ self._facts_cache: Dict[str, Optional[dict]] = {}
+ # Ticker -> CIK cache
+ self._ticker_cik_cache: Dict[str, str] = {}
+ self._last_request_time: float = 0.0
+
+ # -----------------------------------------------------------------------
+ # Core HTTP helpers
+ # -----------------------------------------------------------------------
+
+ def _rate_limit(self) -> None:
+ """Ensure minimum 0.15 s between requests (SEC allows ~10 req/sec)."""
+ elapsed = time.time() - self._last_request_time
+ if elapsed < 0.15:
+ time.sleep(0.15 - elapsed)
+ self._last_request_time = time.time()
+
+ def _get(self, url: str, timeout: int = 15, retries: int = 3) -> Optional[dict]:
+ """Fetch JSON from URL with retry on 429/503."""
+ for attempt in range(retries):
+ self._rate_limit()
+ try:
+ req = Request(url, headers=_HEADERS)
+ with urlopen(req, timeout=timeout) as resp:
+ return json.loads(resp.read().decode("utf-8"))
+ except HTTPError as e:
+ if e.code in (429, 503) and attempt < retries - 1:
+ time.sleep(2 ** attempt)
+ continue
+ return None
+ except Exception:
+ return None
+ return None
+
+ def _get_text(self, url: str, timeout: int = 20, retries: int = 3) -> str:
+ """Fetch plain/HTML text from URL with retry on 429/503."""
+ headers = {**_HEADERS, "Accept": "text/html,text/plain"}
+ for attempt in range(retries):
+ self._rate_limit()
+ try:
+ req = Request(url, headers=headers)
+ with urlopen(req, timeout=timeout) as resp:
+ raw = resp.read()
+ try:
+ return raw.decode("utf-8")[:120000]
+ except UnicodeDecodeError:
+ return raw.decode("latin-1")[:120000]
+ except HTTPError as e:
+ if e.code in (429, 503) and attempt < retries - 1:
+ time.sleep(2 ** attempt)
+ continue
+ return ""
+ except Exception:
+ return ""
+ return ""
+
+ # -----------------------------------------------------------------------
+ # Company resolution
+ # -----------------------------------------------------------------------
+
+ def resolve_cik(self, company_name_or_ticker: str) -> Optional[str]:
+ """Resolve company name or ticker to a 10-digit zero-padded CIK string.
+
+ Strategy:
+ 1. If it looks like a ticker (1-5 uppercase letters), use the ticker JSON file.
+ 2. Otherwise search the EFTS full-text search endpoint.
+ 3. Fallback: search the ticker JSON by partial name match.
+ """
+ if not company_name_or_ticker:
+ return None
+
+ query = company_name_or_ticker.strip()
+
+ # Check ticker cache first
+ ticker_upper = query.upper()
+ if ticker_upper in self._ticker_cik_cache:
+ return self._ticker_cik_cache[ticker_upper]
+
+ # 1. Try as ticker
+ if re.match(r'^[A-Z]{1,5}$', ticker_upper):
+ cik = self._cik_from_ticker_file(ticker_upper)
+ if cik:
+ self._ticker_cik_cache[ticker_upper] = cik
+ return cik
+
+ # 2. Try EFTS entity search
+ cik = self._cik_from_efts_search(query)
+ if cik:
+ self._ticker_cik_cache[ticker_upper] = cik
+ return cik
+
+ # 3. Fuzzy match in ticker file by company name
+ cik = self._cik_from_company_name_fuzzy(query)
+ if cik:
+ self._ticker_cik_cache[ticker_upper] = cik
+ return cik
+
+ def _cik_from_ticker_file(self, ticker: str) -> Optional[str]:
+ """Look up CIK from SEC company_tickers.json (fast, cached file)."""
+ data = self._get("https://www.sec.gov/files/company_tickers.json")
+ if not data:
+ return None
+ for entry in data.values():
+ if str(entry.get("ticker", "")).upper() == ticker:
+ return str(entry["cik_str"]).zfill(10)
+ return None
+
+ def _cik_from_efts_search(self, query: str) -> Optional[str]:
+ """Search SEC EFTS for company by name, return CIK."""
+ import urllib.parse
+ encoded = urllib.parse.quote(query)
+ url = f"https://efts.sec.gov/LATEST/search-index?q=%22{encoded}%22&dateRange=custom&startdt=2000-01-01&forms=10-K"
+ data = self._get(url)
+ if data and data.get("hits", {}).get("hits"):
+ hit = data["hits"]["hits"][0]
+ entity_id = hit.get("_source", {}).get("entity_id") or hit.get("_source", {}).get("cik")
+ if entity_id:
+ return str(entity_id).zfill(10)
+
+ # Try the submissions search endpoint
+ url2 = f"https://efts.sec.gov/LATEST/search-index?q={encoded}&forms=DEFM14A,PREM14A,8-K"
+ data2 = self._get(url2)
+ if data2 and data2.get("hits", {}).get("hits"):
+ hit = data2["hits"]["hits"][0]
+ src = hit.get("_source", {})
+ if src.get("entity_id"):
+ return str(src["entity_id"]).zfill(10)
+
+ return None
+
+ def _cik_from_company_name_fuzzy(self, query: str) -> Optional[str]:
+ """Fuzzy match company name against the SEC ticker list."""
+ data = self._get("https://www.sec.gov/files/company_tickers.json")
+ if not data:
+ return None
+ query_lower = query.lower()
+ # Remove common legal suffixes for matching
+ query_clean = re.sub(
+ r'\s*(,\s*)?(inc\.?|corp\.?|llc\.?|ltd\.?|co\.?|company|corporation|holdings?)\s*$',
+ '', query_lower, flags=re.IGNORECASE
+ ).strip()
+ for entry in data.values():
+ name = str(entry.get("title", "")).lower()
+ name_clean = re.sub(
+ r'\s*(,\s*)?(inc\.?|corp\.?|llc\.?|ltd\.?|co\.?|company|corporation|holdings?)\s*$',
+ '', name, flags=re.IGNORECASE
+ ).strip()
+ if query_clean and name_clean and (
+ query_clean == name_clean
+ or query_clean in name_clean
+ or name_clean in query_clean
+ ):
+ return str(entry["cik_str"]).zfill(10)
+ return None
+
+ def get_company_metadata(self, cik: str) -> Dict[str, Any]:
+ """Fetch company metadata from SEC submissions API.
+
+ Returns: {name, tickers, sic, sic_description, country, state_of_incorporation, fiscal_year_end}
+ """
+ padded = str(cik).zfill(10)
+ url = f"https://data.sec.gov/submissions/CIK{padded}.json"
+ data = self._get(url)
+ if not data:
+ return {}
+ tickers = data.get("tickers", [])
+ return {
+ "name": data.get("name", ""),
+ "ticker": tickers[0] if tickers else "",
+ "tickers": tickers,
+ "sic": data.get("sic", ""),
+ "sic_description": data.get("sicDescription", ""),
+ "country": data.get("insiderTransactionForOwnerExists", ""), # not ideal field
+ "state_of_incorporation": data.get("stateOfIncorporation", ""),
+ "fiscal_year_end": data.get("fiscalYearEnd", ""),
+ "entity_type": data.get("entityType", ""),
+ "cik": padded,
+ }
+
+ # -----------------------------------------------------------------------
+ # Filing text fetching (moved from deal_parser)
+ # -----------------------------------------------------------------------
+
+ def get_filing_text(self, accession_number: str, cik: str) -> str:
+ """Fetch primary document text for a filing from SEC EDGAR Archives.
+
+ Strategy:
+ 1. Fetch the filing -index.htm page, parse document links.
+ 2. Download the primary document (non-exhibit), strip HTML.
+ 3. Fallback: directory listing.
+ Returns up to 100 000 chars of plain text.
+ """
+ acc_clean = accession_number.replace("-", "")
+ cik_int = str(int(cik)) if cik.isdigit() else cik.lstrip("0") or "0"
+ base_url = f"https://www.sec.gov/Archives/edgar/data/{cik_int}/{acc_clean}"
+
+ # 1. Fetch the index HTML page
+ index_url = f"{base_url}/{accession_number}-index.htm"
+ index_html = self._get_text(index_url)
+
+ if index_html:
+ doc_links = re.findall(
+ r'href="(/Archives/edgar/data/[^"]+\.(?:htm|html|txt))"',
+ index_html, re.IGNORECASE
+ )
+ rel_links = re.findall(
+ r'href="([^/"][^"]*\.(?:htm|html|txt))"',
+ index_html, re.IGNORECASE
+ )
+
+ candidates: List[str] = []
+ for link in doc_links:
+ candidates.append(f"https://www.sec.gov{link}")
+ for link in rel_links:
+ if not link.startswith("http") and not link.startswith("/"):
+ candidates.append(f"{base_url}/{link}")
+
+ candidates = [u for u in candidates if "-index" not in u.lower()]
+
+ # Sort: exhibits last
+ primary_first = sorted(candidates, key=lambda u: (
+ 1 if any(x in u.lower() for x in ["ex-", "exhibit", "ex99", "ex10"]) else 0
+ ))
+
+ for doc_url in primary_first[:5]:
+ text = self._get_text(doc_url)
+ if text and len(text) > 1000:
+ return re.sub(r"<[^>]+>", " ", text)[:100000]
+
+ # 2. Fallback: directory listing
+ dir_html = self._get_text(f"{base_url}/")
+ if dir_html:
+ links = re.findall(r'href="([^"]+\.(?:htm|txt))"', dir_html, re.IGNORECASE)
+ for link in links[:5]:
+ full = (
+ link if link.startswith("http")
+ else (
+ f"https://www.sec.gov{link}" if link.startswith("/")
+ else f"{base_url}/{link}"
+ )
+ )
+ if "-index" not in full.lower():
+ text = self._get_text(full)
+ if text and len(text) > 1000:
+ return re.sub(r"<[^>]+>", " ", text)[:100000]
+
+ return ""
+
+ def get_filing_documents(self, accession_number: str, cik: str) -> List[Dict[str, Any]]:
+ """Return list of documents in a filing from -index.json.
+
+ Each item: {filename, type, description, url}
+ """
+ acc_clean = accession_number.replace("-", "")
+ cik_int = str(int(cik)) if cik.isdigit() else cik.lstrip("0") or "0"
+ url = f"https://www.sec.gov/Archives/edgar/data/{cik_int}/{acc_clean}/{accession_number}-index.json"
+ data = self._get(url)
+ if not data:
+ return []
+
+ base = f"https://www.sec.gov/Archives/edgar/data/{cik_int}/{acc_clean}/"
+ docs = []
+ for item in data.get("directory", {}).get("item", []):
+ name = item.get("name", "")
+ docs.append({
+ "filename": name,
+ "type": item.get("type", ""),
+ "description": item.get("name", ""),
+ "url": base + name,
+ })
+ return docs
+
+ # -----------------------------------------------------------------------
+ # XBRL Financial data
+ # -----------------------------------------------------------------------
+
+ def get_company_financials(self, cik: str, periods: int = 4) -> Dict[str, Any]:
+ """Fetch M&A-relevant financials from SEC XBRL company-facts API.
+
+ Returns:
+ {
+ 'annual': {revenue, ebitda, net_income, total_debt, cash, shares_outstanding, total_assets},
+ 'ttm': {...}, # trailing-12-month aggregate of last 4 quarters
+ 'period_end': '2024-09-30',
+ 'currency': 'USD'
+ }
+ If XBRL fetch fails, returns empty dict (XBRL enrichment is optional).
+ """
+ padded = str(cik).zfill(10)
+
+ # Use cached facts if available
+ if padded in self._facts_cache:
+ facts = self._facts_cache[padded]
+ else:
+ url = f"https://data.sec.gov/api/xbrl/companyfacts/CIK{padded}.json"
+ facts = self._get(url, timeout=30)
+ self._facts_cache[padded] = facts
+
+ if not facts:
+ return {}
+
+ us_gaap = facts.get("facts", {}).get("us-gaap", {})
+ if not us_gaap:
+ return {}
+
+ # Annual (12-month duration periods)
+ revenue = self._get_xbrl_value(us_gaap, REVENUE_TAGS, "annual")
+ net_income = self._get_xbrl_value(us_gaap, NET_INCOME_TAGS, "annual")
+ interest = self._get_xbrl_value(us_gaap, INTEREST_EXPENSE_TAGS, "annual")
+ da = self._get_xbrl_value(us_gaap, DA_TAGS, "annual")
+ tax = self._get_xbrl_value(us_gaap, INCOME_TAX_TAGS, "annual")
+ ebit = self._get_xbrl_value(us_gaap, EBIT_TAGS, "annual")
+
+ # Balance sheet (instantaneous / point-in-time)
+ total_debt = self._get_xbrl_value(us_gaap, TOTAL_DEBT_TAGS, "instant")
+ cash = self._get_xbrl_value(us_gaap, CASH_TAGS, "instant")
+ shares = self._get_xbrl_value(us_gaap, SHARES_TAGS, "instant")
+ total_assets = self._get_xbrl_value(us_gaap, TOTAL_ASSETS_TAGS, "instant")
+
+ # Derive EBITDA
+ ebitda = None
+ if net_income is not None and interest is not None and da is not None and tax is not None:
+ ebitda = self._derive_ebitda(net_income, tax, interest, da)
+ elif ebit is not None and da is not None:
+ ebitda = ebit + da
+
+ # TTM from last 4 quarters
+ ttm_revenue = self._get_xbrl_ttm(us_gaap, REVENUE_TAGS)
+ ttm_net_income = self._get_xbrl_ttm(us_gaap, NET_INCOME_TAGS)
+
+ period_end = self._get_latest_period_end(us_gaap, REVENUE_TAGS + NET_INCOME_TAGS)
+
+ annual = {}
+ if revenue is not None:
+ annual["revenue"] = revenue
+ if ebitda is not None:
+ annual["ebitda"] = ebitda
+ if net_income is not None:
+ annual["net_income"] = net_income
+ if total_debt is not None:
+ annual["total_debt"] = total_debt
+ if cash is not None:
+ annual["cash"] = cash
+ if shares is not None:
+ annual["shares_outstanding"] = shares
+ if total_assets is not None:
+ annual["total_assets"] = total_assets
+ if interest is not None:
+ annual["interest_expense"] = interest
+ if da is not None:
+ annual["depreciation_amortization"] = da
+
+ ttm = {}
+ if ttm_revenue is not None:
+ ttm["revenue"] = ttm_revenue
+ if ttm_net_income is not None:
+ ttm["net_income"] = ttm_net_income
+
+ return {
+ "annual": annual,
+ "ttm": ttm,
+ "period_end": period_end or "",
+ "currency": "USD",
+ "cik": padded,
+ }
+
+ def _get_xbrl_value(
+ self, us_gaap: dict, tags: List[str], period_type: str
+ ) -> Optional[float]:
+ """Try multiple XBRL tags until one returns a value for the requested period type.
+
+ period_type:
+ 'annual' → duration units with months=12
+ 'instant' → point-in-time (balance sheet items)
+ """
+ for tag in tags:
+ tag_data = us_gaap.get(tag, {})
+ if not tag_data:
+ continue
+ units = tag_data.get("units", {})
+ # Try USD first, then pure numbers (shares)
+ for unit_key in ("USD", "shares", "pure"):
+ entries = units.get(unit_key, [])
+ if not entries:
+ continue
+ if period_type == "annual":
+ # Want 12-month duration entries (form 10-K annual period)
+ annual_entries = [
+ e for e in entries
+ if e.get("form") in ("10-K", "10-K/A", "20-F", "20-F/A")
+ and e.get("start") and e.get("end")
+ and self._months_between(e["start"], e["end"]) in range(11, 14)
+ ]
+ if annual_entries:
+ latest = max(annual_entries, key=lambda e: e.get("end", ""))
+ val = latest.get("val")
+ if val is not None:
+ return float(val)
+ elif period_type == "instant":
+ instant_entries = [
+ e for e in entries
+ if not e.get("start") and e.get("end")
+ and e.get("form") in ("10-K", "10-K/A", "10-Q", "10-Q/A", "20-F")
+ ]
+ if instant_entries:
+ latest = max(instant_entries, key=lambda e: e.get("end", ""))
+ val = latest.get("val")
+ if val is not None:
+ return float(val)
+ return None
+
+ def _get_xbrl_ttm(self, us_gaap: dict, tags: List[str]) -> Optional[float]:
+ """Aggregate last 4 quarterly values for a trailing-12-month figure."""
+ for tag in tags:
+ tag_data = us_gaap.get(tag, {})
+ if not tag_data:
+ continue
+ units = tag_data.get("units", {})
+ entries = units.get("USD", [])
+ quarterly = [
+ e for e in entries
+ if e.get("form") in ("10-Q", "10-Q/A")
+ and e.get("start") and e.get("end")
+ and self._months_between(e["start"], e["end"]) in range(2, 5)
+ ]
+ if len(quarterly) >= 4:
+ quarterly.sort(key=lambda e: e.get("end", ""), reverse=True)
+ ttm = sum(e.get("val", 0) or 0 for e in quarterly[:4])
+ return float(ttm)
+ return None
+
+ def _get_latest_period_end(self, us_gaap: dict, tags: List[str]) -> Optional[str]:
+ """Return the latest period end date among a set of XBRL tags."""
+ latest = ""
+ for tag in tags:
+ tag_data = us_gaap.get(tag, {})
+ if not tag_data:
+ continue
+ for unit_entries in tag_data.get("units", {}).values():
+ for e in unit_entries:
+ end = e.get("end", "")
+ if end > latest:
+ latest = end
+ return latest or None
+
+ @staticmethod
+ def _months_between(start: str, end: str) -> int:
+ """Approximate months between two YYYY-MM-DD date strings."""
+ try:
+ sy, sm = int(start[:4]), int(start[5:7])
+ ey, em = int(end[:4]), int(end[5:7])
+ return (ey - sy) * 12 + (em - sm)
+ except Exception:
+ return 0
+
+ @staticmethod
+ def _derive_ebitda(
+ net_income: float, tax: float, interest: float, da: float
+ ) -> float:
+ """EBITDA = Net Income + Tax Expense + Interest Expense + D&A."""
+ return net_income + tax + interest + da
+
+ # -----------------------------------------------------------------------
+ # Valuation multiples
+ # -----------------------------------------------------------------------
+
+ def calculate_deal_multiples(
+ self,
+ deal_value: float,
+ target_cik: str,
+ announcement_date: str = "",
+ ) -> Dict[str, Any]:
+ """Calculate EV/Revenue, EV/EBITDA, implied P/E and price-per-share.
+
+ Args:
+ deal_value: Total deal value in USD (enterprise value proxy).
+ target_cik: CIK of the target company.
+ announcement_date: Deal announcement date (YYYY-MM-DD) — informational only.
+
+ Returns dict with multiples. All fields are optional (None if data unavailable).
+ """
+ financials = self.get_company_financials(target_cik)
+ if not financials:
+ return {}
+
+ annual = financials.get("annual", {})
+ ttm = financials.get("ttm", {})
+
+ revenue = ttm.get("revenue") or annual.get("revenue")
+ ebitda = annual.get("ebitda")
+ net_income = ttm.get("net_income") or annual.get("net_income")
+ total_debt = annual.get("total_debt", 0) or 0
+ cash = annual.get("cash", 0) or 0
+ shares = annual.get("shares_outstanding")
+
+ result: Dict[str, Any] = {}
+
+ if revenue and revenue > 0:
+ result["ev_revenue"] = round(deal_value / revenue, 2)
+
+ if ebitda and ebitda > 0:
+ result["ev_ebitda"] = round(deal_value / ebitda, 2)
+
+ # Implied equity value = EV - debt + cash
+ implied_equity = deal_value - total_debt + cash
+ result["implied_equity_value"] = implied_equity
+
+ if net_income and net_income > 0:
+ result["implied_pe"] = round(implied_equity / net_income, 2)
+
+ if shares and shares > 0:
+ result["price_per_share"] = round(implied_equity / shares, 2)
+
+ result["period_end"] = financials.get("period_end", "")
+ result["currency"] = "USD"
+ return result
+
+ # -----------------------------------------------------------------------
+ # Deal document discovery
+ # -----------------------------------------------------------------------
+
+ def find_merger_agreement(self, accession_number: str, cik: str) -> Optional[str]:
+ """Find the merger agreement exhibit URL (EX-2.1 or first large exhibit)."""
+ docs = self.get_filing_documents(accession_number, cik)
+ # Look for EX-2.1 first (the Agreement and Plan of Merger exhibit)
+ for doc in docs:
+ desc = (doc.get("description", "") + doc.get("type", "") + doc.get("filename", "")).lower()
+ if "ex-2" in desc or "ex2" in desc or "merger agreement" in desc:
+ return doc.get("url")
+ # Fallback: first non-index .htm file that isn't a small exhibit
+ for doc in docs:
+ fname = doc.get("filename", "").lower()
+ if fname.endswith((".htm", ".html")) and "index" not in fname:
+ return doc.get("url")
+ return None
+
+ def search_related_filings(
+ self,
+ company_name: str,
+ cik: str,
+ filing_types: Optional[List[str]] = None,
+ months_back: int = 12,
+ ) -> List[Dict[str, Any]]:
+ """Find related filings (S-4, SC TO-T, proxy amendments) for a deal.
+
+ Returns list of {accession_number, filing_type, filing_date, url}.
+ """
+ if filing_types is None:
+ filing_types = ["S-4", "SC TO-T", "DEFM14A", "PREM14A", "8-K"]
+
+ padded = str(cik).zfill(10)
+ url = f"https://data.sec.gov/submissions/CIK{padded}.json"
+ data = self._get(url)
+ if not data:
+ return []
+
+ recent = data.get("filings", {}).get("recent", {})
+ forms = recent.get("form", [])
+ dates = recent.get("filingDate", [])
+ accessions = recent.get("accessionNumber", [])
+
+ from datetime import datetime, timedelta
+ cutoff = (datetime.now() - timedelta(days=months_back * 30)).strftime("%Y-%m-%d")
+
+ results = []
+ for form, date, acc in zip(forms, dates, accessions):
+ if form in filing_types and date >= cutoff:
+ acc_clean = acc.replace("-", "")
+ cik_int = str(int(padded))
+ results.append({
+ "accession_number": acc,
+ "filing_type": form,
+ "filing_date": date,
+ "url": f"https://www.sec.gov/Archives/edgar/data/{cik_int}/{acc_clean}/{acc}-index.htm",
+ })
+ return results
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/payment_structure.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/payment_structure.py
index 08521e66d..1a63c0221 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/payment_structure.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/payment_structure.py
@@ -25,6 +25,14 @@ class PaymentStructureAnalyzer:
acquirer_share_price: float,
target_shares_outstanding: float,
target_share_price: float):
+ if acquirer_shares_outstanding <= 0:
+ raise ValueError("Acquirer shares outstanding must be positive")
+ if acquirer_share_price <= 0:
+ raise ValueError("Acquirer share price must be positive")
+ if target_shares_outstanding <= 0:
+ raise ValueError("Target shares outstanding must be positive")
+ if target_share_price <= 0:
+ raise ValueError("Target share price must be positive")
self.acquirer_shares = acquirer_shares_outstanding
self.acquirer_price = acquirer_share_price
self.target_shares = target_shares_outstanding
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/process_quality.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/process_quality.py
index 017aa863b..401946b2e 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/process_quality.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/process_quality.py
@@ -365,7 +365,38 @@ def main():
process_factors = json.loads(sys.argv[2])
- # Extract process_type from input, default to 'targeted_auction'
+ # Detect flat format: {board_independence:4, special_committee:5, ...} sent from frontend
+ # vs nested format: {market_check:{}, board_process:{}, timing:{}}
+ FLAT_KEYS = {'board_independence', 'special_committee', 'independent_advisor',
+ 'market_check', 'negotiation_process', 'due_diligence', 'disclosure', 'timing'}
+
+ is_flat = any(k in FLAT_KEYS and not isinstance(process_factors.get(k), dict)
+ for k in process_factors)
+
+ if is_flat:
+ # Convert flat 1-5 scores to a synthetic comprehensive result directly
+ def score_to_quality(s):
+ s = float(s)
+ if s >= 4.5: return 'excellent'
+ if s >= 3.5: return 'good'
+ if s >= 2.5: return 'adequate'
+ return 'deficient'
+
+ factor_scores = {k: float(v) for k, v in process_factors.items() if k != 'process_type'}
+ overall_score = sum(factor_scores.values()) / len(factor_scores) if factor_scores else 0
+ quality = score_to_quality(overall_score)
+
+ result_data = {
+ 'factor_scores': factor_scores,
+ 'overall_score': overall_score,
+ 'quality_rating': quality,
+ 'supports_fairness_conclusion': overall_score >= 3.0,
+ }
+ result = {"success": True, "data": result_data}
+ print(json.dumps(result))
+ return
+
+ # Nested format handling
process_type_str = process_factors.get('process_type', 'targeted_auction').upper().replace('-', '_').replace(' ', '_')
process_type = ProcessType[process_type_str] if process_type_str in ProcessType.__members__ else ProcessType.TARGETED_AUCTION
@@ -375,7 +406,7 @@ def main():
# Market check analysis
mc = process_factors.get('market_check', {})
- if mc:
+ if mc and isinstance(mc, dict):
result_data['market_check'] = assessment.evaluate_market_check(
parties_contacted=mc.get('parties_contacted', 0),
ndas_executed=mc.get('ndas_executed', 0),
@@ -386,7 +417,7 @@ def main():
# Board process analysis
bp = process_factors.get('board_process', {})
- if bp:
+ if bp and isinstance(bp, dict):
result_data['board_process'] = assessment.evaluate_board_process(
board_meetings=bp.get('board_meetings', 0),
special_committee=bp.get('special_committee', False),
@@ -398,7 +429,7 @@ def main():
# Timing analysis
tp = process_factors.get('timing', {})
- if tp:
+ if tp and isinstance(tp, dict):
result_data['timing_analysis'] = assessment.timing_pressure_analysis(
process_duration_days=tp.get('process_duration_days', 90),
termination_fee_pct=tp.get('termination_fee_pct', 3.0),
@@ -409,12 +440,20 @@ def main():
# Comprehensive evaluation if we have enough data
if 'market_check' in result_data and 'board_process' in result_data and 'timing_analysis' in result_data:
- result_data['comprehensive'] = assessment.comprehensive_process_evaluation(
+ comp = assessment.comprehensive_process_evaluation(
market_check=result_data['market_check'],
competitive_tension={'competitive_tension': process_factors.get('competitive_tension', 'moderate')},
board_process=result_data['board_process'],
timing_analysis=result_data['timing_analysis']
)
+ result_data['comprehensive'] = comp
+ # Add top-level fields for frontend convenience
+ result_data['overall_score'] = comp.get('overall_process_score', 0) / 20 # convert 0-100 to 0-5
+ result_data['quality_rating'] = comp.get('process_quality_rating', 'N/A')
+ result_data['factor_scores'] = {
+ k: round(v / 20, 1) for k, v in comp.get('component_scores', {}).items()
+ }
+ result_data['supports_fairness_conclusion'] = comp.get('supports_fairness_conclusion', False)
result = {"success": True, "data": result_data}
print(json.dumps(result))
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/valuation_framework.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/valuation_framework.py
index e5d37fc70..4d3e73e2f 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/valuation_framework.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/valuation_framework.py
@@ -373,14 +373,46 @@ def main():
)
# Convert valuation methods data to ValuationRange objects
+ # Handles both {low, high} format and {valuation, range: {min, max}} format
valuation_ranges = []
for method_data in methods_list:
- method_name = method_data.get('method', 'DCF').upper().replace(' ', '_')
+ method_name = method_data.get('method', 'DCF').upper().replace(' ', '_').replace(' ', '_')
+ # Map common method names to enum keys
+ method_name_map = {
+ 'TRADING_COMPS': 'TRADING_COMPS',
+ 'TRADING COMPS': 'TRADING_COMPS',
+ 'PRECEDENT_TRANSACTIONS': 'PRECEDENT_TRANSACTIONS',
+ 'PRECEDENT TRANSACTIONS': 'PRECEDENT_TRANSACTIONS',
+ 'LBO_ANALYSIS': 'LBO_ANALYSIS',
+ 'LBO ANALYSIS': 'LBO_ANALYSIS',
+ 'PREMIUMS_PAID': 'PREMIUMS_PAID',
+ 'PREMIUMS PAID': 'PREMIUMS_PAID',
+ 'REPLACEMENT_COST': 'REPLACEMENT_COST',
+ 'DCF': 'DCF',
+ }
+ enum_key = method_name_map.get(method_name, method_name)
+ try:
+ vm = ValuationMethod[enum_key]
+ except KeyError:
+ vm = ValuationMethod.DCF
+
+ # Support {low, high} or {valuation, range: {min, max}} formats
+ if 'low' in method_data and 'high' in method_data:
+ low = float(method_data['low'])
+ high = float(method_data['high'])
+ elif 'range' in method_data and isinstance(method_data['range'], dict):
+ low = float(method_data['range'].get('min', method_data.get('valuation', 0) * 0.9))
+ high = float(method_data['range'].get('max', method_data.get('valuation', 0) * 1.1))
+ else:
+ val = float(method_data.get('valuation', 0))
+ low, high = val * 0.9, val * 1.1
+
+ midpoint = float(method_data.get('midpoint', method_data.get('mid', method_data.get('valuation', (low + high) / 2))))
val_range = ValuationRange(
- method=ValuationMethod[method_name],
- low=method_data['low'],
- high=method_data['high'],
- midpoint=method_data.get('midpoint', method_data.get('mid', (method_data['low'] + method_data['high']) / 2)),
+ method=vm,
+ low=low,
+ high=high,
+ midpoint=midpoint,
weight=method_data.get('weight', 1.0)
)
valuation_ranges.append(val_range)
@@ -393,6 +425,12 @@ def main():
analysis = framework.weighted_valuation_summary(valuation_ranges)
+ # Also compute fairness determination for the frontend
+ fairness = framework.fairness_determination(analysis, qualitative_factors)
+ analysis['is_fair'] = fairness['fairness_conclusion']['is_fair']
+ analysis['fairness_conclusion'] = fairness['fairness_conclusion']['conclusion']
+ analysis['quantitative_analysis'] = fairness['quantitative_analysis']
+
result = {"success": True, "data": analysis}
print(json.dumps(result))
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/financial_services.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/financial_services.py
index 7b61315ff..03817d232 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/financial_services.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/financial_services.py
@@ -366,6 +366,87 @@ class FinancialServicesMetrics:
}
}
+def _build_financial_standard_output(analysis: dict, sector: str) -> dict:
+ """Build valuation_metrics, benchmarks, and insights for financial services output."""
+ benchmarks_db = {
+ 'banking': {
+ 'net_interest_margin': {'p25': 2.5, 'median': 3.2, 'p75': 3.8},
+ 'efficiency_ratio': {'p25': 50, 'median': 58, 'p75': 65},
+ 'roe': {'p25': 8, 'median': 12, 'p75': 16},
+ 'npa_ratio': {'p25': 0.4, 'median': 0.9, 'p75': 1.8},
+ },
+ 'insurance': {
+ 'combined_ratio': {'p25': 88, 'median': 95, 'p75': 101},
+ 'loss_ratio': {'p25': 58, 'median': 65, 'p75': 72},
+ 'roe': {'p25': 8, 'median': 12, 'p75': 16},
+ 'investment_yield': {'p25': 3.0, 'median': 4.2, 'p75': 5.5},
+ },
+ 'asset_management': {
+ 'aum': {'p25': 20, 'median': 80, 'p75': 500},
+ 'operating_margin': {'p25': 20, 'median': 32, 'p75': 42},
+ 'fee_rate': {'p25': 25, 'median': 45, 'p75': 70},
+ },
+ }
+
+ vm = {}
+ insights = []
+
+ if sector == 'banking':
+ vm = {
+ 'roe_pct': round(analysis.get('roe', 0), 1),
+ 'net_interest_margin_pct': round(analysis.get('net_interest_margin', 0), 2),
+ 'efficiency_ratio_pct': round(analysis.get('efficiency_ratio', 0), 1),
+ 'npa_ratio_pct': round(analysis.get('npa_ratio', 0), 2),
+ 'profitability_score': analysis.get('profitability_score', 0),
+ 'asset_quality_score': round(analysis.get('asset_quality_score', 0), 0),
+ }
+ mr = analysis.get('price_to_tangible_book_range', {})
+ vm['ptbv_mid'] = round(mr.get('mid', 0), 2)
+ insights.append(f"Price-to-tangible-book range: {mr.get('low', 0):.2f}x – {mr.get('high', 0):.2f}x based on ROE and asset quality.")
+ if analysis.get('roe', 0) >= 12:
+ insights.append("ROE >= 12% supports a premium valuation relative to book value for banking M&A.")
+ if analysis.get('npa_ratio', 0) <= 1.0:
+ insights.append("NPA ratio <= 1% indicates strong asset quality — low credit risk premium in valuation.")
+
+ elif sector == 'insurance':
+ vm = {
+ 'combined_ratio_pct': round(analysis.get('combined_ratio', 0), 1),
+ 'underwriting_margin_pct': round(analysis.get('underwriting_profit_margin', 0), 1),
+ 'loss_ratio_pct': round(analysis.get('loss_ratio', 0), 1),
+ 'roe_pct': round(analysis.get('roe', 0), 1),
+ 'insurance_quality_score': analysis.get('insurance_quality_score', 0),
+ }
+ mr = analysis.get('price_to_book_range', {})
+ vm['ptb_mid'] = round(mr.get('mid', 0), 2)
+ insights.append(f"Price-to-book range: {mr.get('low', 0):.2f}x – {mr.get('high', 0):.2f}x based on underwriting discipline and ROE.")
+ if analysis.get('combined_ratio', 100) <= 95:
+ insights.append("Combined ratio <= 95% indicates consistent underwriting profitability — key quality signal.")
+
+ elif sector == 'asset_management':
+ vm = {
+ 'aum': round(analysis.get('aum', 0), 1),
+ 'organic_growth_rate_pct': round(analysis.get('organic_growth_rate', 0), 2),
+ 'operating_margin_pct': round(analysis.get('operating_margin', 0), 1),
+ 'estimated_revenue': round(analysis.get('estimated_revenue', 0), 2),
+ 'wealth_quality_score': analysis.get('wealth_quality_score', 0),
+ }
+ aum_mr = analysis.get('aum_multiple_range', {})
+ vm['aum_multiple_pct_mid'] = round(aum_mr.get('mid', 0) * 100, 2)
+ rev_mr = analysis.get('revenue_multiple_range', {})
+ vm['revenue_multiple_mid'] = round(rev_mr.get('mid', 0), 1)
+ insights.append(f"AUM multiple range: {aum_mr.get('low', 0)*100:.1f}% – {aum_mr.get('high', 0)*100:.1f}% of AUM.")
+ insights.append(f"Revenue multiple range: {rev_mr.get('low', 0):.1f}x – {rev_mr.get('high', 0):.1f}x.")
+ if analysis.get('organic_growth_rate', 0) >= 5:
+ insights.append("Organic flow growth >= 5% demonstrates strong client acquisition and retention momentum.")
+
+ return {
+ **analysis,
+ 'valuation_metrics': vm,
+ 'benchmarks': benchmarks_db.get(sector, {}),
+ 'insights': insights,
+ }
+
+
def main():
"""CLI entry point - outputs JSON for Tauri integration"""
import sys
@@ -393,42 +474,78 @@ def main():
'total_deposits': 'deposits', 'total_loans': 'loans',
'net_interest_income': 'net_interest_margin',
'tier1_capital': 'tier1_capital_ratio',
+ 'cet1_ratio': 'tier1_capital_ratio', # frontend sends cet1_ratio
'loan_loss_provision_rate': 'npa_ratio',
'npl_ratio': 'npa_ratio',
'return_on_equity': 'roe',
+ 'gross_premiums': 'gross_written_premium', # frontend sends gross_premiums
}
for old_key, new_key in key_aliases.items():
if old_key in institution_data and new_key not in institution_data:
institution_data[new_key] = institution_data.pop(old_key)
+ import inspect
+ sector_key = sector.lower()
+
# Route to appropriate calculation based on sector
if 'bank' in sector.lower():
# Provide defaults for required bank params
- institution_data.setdefault('total_assets', institution_data.get('deposits', 0) * 1.2)
+ institution_data.setdefault('loans', institution_data.get('deposits', 0) * 0.75)
institution_data.setdefault('npa_ratio', 1.0)
institution_data.setdefault('roe', 10.0)
- # Filter to only valid params
- import inspect
+ institution_data.setdefault('tier1_capital_ratio', 12.0)
+ # Drop unknown keys
valid_params = set(inspect.signature(analyzer.calculate_bank_metrics).parameters.keys())
filtered = {k: v for k, v in institution_data.items() if k in valid_params}
analysis = analyzer.calculate_bank_metrics(**filtered)
+ sector_key = 'banking'
+
+ elif 'asset' in sector.lower() or 'asset_management' in sector.lower():
+ # Frontend sends: aum, net_flows, fee_rate (bps), operating_margin, active_vs_passive, alpha_generation
+ # Python expects: aum, net_flows, advisory_fee_rate (fraction), client_retention, advisor_productivity, operating_margin
+ if 'fee_rate' in institution_data and 'advisory_fee_rate' not in institution_data:
+ # Convert bps to fraction (45 bps = 0.0045)
+ institution_data['advisory_fee_rate'] = institution_data.pop('fee_rate') / 10000.0
+ institution_data.setdefault('client_retention', 92.0)
+ institution_data.setdefault('advisor_productivity', 80_000_000.0)
+ # Drop frontend-only keys
+ for drop_key in ('active_vs_passive', 'alpha_generation'):
+ institution_data.pop(drop_key, None)
+ valid_params = set(inspect.signature(analyzer.calculate_wealth_management_metrics).parameters.keys())
+ filtered = {k: v for k, v in institution_data.items() if k in valid_params}
+ analysis = analyzer.calculate_wealth_management_metrics(**filtered)
+ sector_key = 'asset_management'
+
elif 'wealth' in sector.lower():
- analysis = analyzer.calculate_wealth_management_metrics(**institution_data)
+ valid_params = set(inspect.signature(analyzer.calculate_wealth_management_metrics).parameters.keys())
+ filtered = {k: v for k, v in institution_data.items() if k in valid_params}
+ analysis = analyzer.calculate_wealth_management_metrics(**filtered)
+ sector_key = 'asset_management'
+
elif 'insurance' in sector.lower():
- import inspect
valid_params = set(inspect.signature(analyzer.calculate_insurance_metrics).parameters.keys())
filtered = {k: v for k, v in institution_data.items() if k in valid_params}
analysis = analyzer.calculate_insurance_metrics(**filtered)
+ sector_key = 'insurance'
+
elif 'fintech' in sector.lower():
- import inspect
valid_params = set(inspect.signature(analyzer.calculate_fintech_metrics).parameters.keys())
filtered = {k: v for k, v in institution_data.items() if k in valid_params}
analysis = analyzer.calculate_fintech_metrics(**filtered)
+ sector_key = 'fintech'
+
else:
# Default to bank metrics
- analysis = analyzer.calculate_bank_metrics(**institution_data)
+ institution_data.setdefault('loans', institution_data.get('deposits', 0) * 0.75)
+ institution_data.setdefault('npa_ratio', 1.0)
+ institution_data.setdefault('tier1_capital_ratio', 12.0)
+ valid_params = set(inspect.signature(analyzer.calculate_bank_metrics).parameters.keys())
+ filtered = {k: v for k, v in institution_data.items() if k in valid_params}
+ analysis = analyzer.calculate_bank_metrics(**filtered)
+ sector_key = 'banking'
- result = {"success": True, "data": analysis}
+ analysis_with_standard = _build_financial_standard_output(analysis, sector_key)
+ result = {"success": True, "data": analysis_with_standard}
print(json.dumps(result))
else:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/healthcare.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/healthcare.py
index 1b0ee257d..7e986349a 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/healthcare.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/healthcare.py
@@ -359,6 +359,153 @@ class HealthcareMetrics:
}
}
+def _calculate_pharma_company_metrics(data: dict) -> dict:
+ """Company-level pharma/biotech valuation from frontend inputs."""
+ revenue = float(data.get('revenue', 0))
+ pipeline_value = float(data.get('pipeline_value', 0))
+ phase3_count = int(data.get('phase3_count', 0))
+ patent_expiry_pct = float(data.get('patent_expiry_revenue', 0))
+ r_and_d_spend = float(data.get('r_and_d_spend', 0))
+ ebitda_margin_pct = float(data.get('ebitda_margin', 0))
+ ebitda = revenue * ebitda_margin_pct / 100.0
+ marketed_value = revenue * 4.0
+ pipeline_contribution = (pipeline_value / (marketed_value + pipeline_value) * 100) if (marketed_value + pipeline_value) > 0 else 0
+ r_and_d_efficiency = (pipeline_value / r_and_d_spend) if r_and_d_spend > 0 else 0
+ patent_cliff_risk = 'high' if patent_expiry_pct > 30 else ('moderate' if patent_expiry_pct > 15 else 'low')
+ return {
+ 'revenue': revenue,
+ 'pipeline_value': pipeline_value,
+ 'phase3_count': phase3_count,
+ 'marketed_products_value': marketed_value,
+ 'ebitda': ebitda,
+ 'ebitda_margin': ebitda_margin_pct,
+ 'pipeline_contribution_pct': pipeline_contribution,
+ 'r_and_d_efficiency': r_and_d_efficiency,
+ 'patent_cliff_risk': patent_cliff_risk,
+ 'patent_expiry_revenue_pct': patent_expiry_pct,
+ }
+
+
+def _calculate_biotech_company_metrics(data: dict) -> dict:
+ """Company-level biotech valuation from frontend inputs."""
+ cash_position = float(data.get('cash_position', 0))
+ burn_rate = float(data.get('burn_rate', 0))
+ pipeline_value = float(data.get('pipeline_value', 0))
+ lead_phase = int(data.get('lead_program_phase', 1))
+ platform_value = float(data.get('platform_value', 0))
+ partnership_revenue = float(data.get('partnership_revenue', 0))
+ cash_runway_months = (cash_position / burn_rate) if burn_rate > 0 else 999
+ total_value = pipeline_value + platform_value
+ phase_premium = {1: 0.3, 2: 0.55, 3: 0.8}.get(lead_phase, 0.3)
+ rnpv_estimate = total_value * phase_premium
+ return {
+ 'cash_position': cash_position,
+ 'burn_rate': burn_rate,
+ 'cash_runway_months': cash_runway_months,
+ 'pipeline_value': pipeline_value,
+ 'lead_program_phase': lead_phase,
+ 'platform_value': platform_value,
+ 'partnership_revenue': partnership_revenue,
+ 'total_asset_value': total_value,
+ 'rnpv_estimate': rnpv_estimate,
+ 'phase_success_premium': phase_premium * 100,
+ }
+
+
+def _build_healthcare_standard_output(analysis: dict, sector: str) -> dict:
+ """Build valuation_metrics, benchmarks, and insights for healthcare output."""
+ benchmarks_db = {
+ 'pharma': {
+ 'revenue': {'p25': 2000, 'median': 8000, 'p75': 25000},
+ 'ebitda_margin': {'p25': 20, 'median': 32, 'p75': 42},
+ 'r_and_d_efficiency': {'p25': 2, 'median': 4, 'p75': 8},
+ },
+ 'biotech': {
+ 'cash_position': {'p25': 100, 'median': 350, 'p75': 800},
+ 'cash_runway_months': {'p25': 12, 'median': 24, 'p75': 48},
+ 'pipeline_value': {'p25': 300, 'median': 900, 'p75': 2500},
+ },
+ 'devices': {
+ 'revenue': {'p25': 100, 'median': 400, 'p75': 1500},
+ 'gross_margin': {'p25': 55, 'median': 65, 'p75': 72},
+ 'recurring_revenue_pct': {'p25': 20, 'median': 35, 'p75': 55},
+ },
+ 'services': {
+ 'revenue': {'p25': 200, 'median': 700, 'p75': 2500},
+ 'ebitda_margin': {'p25': 10, 'median': 16, 'p75': 22},
+ 'same_store_growth': {'p25': 2, 'median': 4, 'p75': 7},
+ },
+ }
+
+ vm = {}
+ insights = []
+
+ if sector == 'pharma':
+ vm = {
+ 'revenue': round(analysis.get('revenue', 0), 1),
+ 'ebitda_margin_pct': round(analysis.get('ebitda_margin', 0), 1),
+ 'pipeline_contribution_pct': round(analysis.get('pipeline_contribution_pct', 0), 1),
+ 'r_and_d_efficiency': round(analysis.get('r_and_d_efficiency', 0), 2),
+ 'marketed_products_value': round(analysis.get('marketed_products_value', 0), 1),
+ }
+ if analysis.get('patent_cliff_risk') == 'high':
+ insights.append("High patent cliff risk — >30% of revenue faces near-term patent expiry. Pipeline strength is critical.")
+ else:
+ insights.append(f"Patent cliff risk: {analysis.get('patent_cliff_risk', 'unknown')}.")
+ insights.append(f"Pipeline contributes {vm['pipeline_contribution_pct']:.0f}% of total estimated enterprise value.")
+ if analysis.get('r_and_d_efficiency', 0) >= 4:
+ insights.append("R&D efficiency above 4x (pipeline NPV / R&D spend) — strong innovation productivity.")
+
+ elif sector == 'biotech':
+ vm = {
+ 'cash_position': round(analysis.get('cash_position', 0), 1),
+ 'cash_runway_months': round(analysis.get('cash_runway_months', 0), 1),
+ 'pipeline_value': round(analysis.get('pipeline_value', 0), 1),
+ 'rnpv_estimate': round(analysis.get('rnpv_estimate', 0), 1),
+ 'phase_success_premium_pct': round(analysis.get('phase_success_premium', 0), 0),
+ }
+ if analysis.get('cash_runway_months', 0) < 18:
+ insights.append("Cash runway below 18 months — financing risk is elevated; near-term dilution likely.")
+ else:
+ insights.append(f"Cash runway of {vm['cash_runway_months']:.0f} months provides adequate operational buffer.")
+ insights.append(f"Risk-adjusted NPV estimate: ${vm['rnpv_estimate']:.0f}M based on lead program phase {analysis.get('lead_program_phase', 1)}.")
+
+ elif sector == 'devices':
+ vm = {
+ 'revenue': round(analysis.get('revenue', 0), 1),
+ 'gross_margin_pct': round(analysis.get('gross_margin', 0), 1),
+ 'device_quality_score': analysis.get('device_quality_score', 0),
+ 'regulatory_score': analysis.get('regulatory_score', 0),
+ 'recurring_revenue_pct': round(analysis.get('recurring_revenue_pct') or 0, 1),
+ }
+ mr = analysis.get('revenue_multiple_range', {})
+ vm['revenue_multiple_mid'] = round(mr.get('mid', 0), 1)
+ insights.append(f"Revenue multiple range: {mr.get('low', 0):.1f}x – {mr.get('high', 0):.1f}x based on device quality profile.")
+ if analysis.get('device_quality_score', 0) >= 60:
+ insights.append("Strong device quality score reflects clinical evidence, regulatory approvals, and reimbursement coverage.")
+
+ elif sector == 'services':
+ vm = {
+ 'revenue': round(analysis.get('revenue', 0), 1),
+ 'ebitda_margin_pct': round(analysis.get('ebitda_margin', 0), 1),
+ 'same_store_growth': round(analysis.get('same_store_growth', 0), 1),
+ 'payor_quality_score': round(analysis.get('payor_quality_score', 0), 1),
+ 'services_quality_score': analysis.get('services_quality_score', 0),
+ }
+ mr = analysis.get('ebitda_multiple_range', {})
+ vm['ebitda_multiple_mid'] = round(mr.get('mid', 0), 1)
+ insights.append(f"EBITDA multiple range: {mr.get('low', 0):.1f}x – {mr.get('high', 0):.1f}x.")
+ if analysis.get('same_store_growth', 0) >= 4:
+ insights.append("Same-store growth above 4% demonstrates organic volume expansion without acquisition dependency.")
+
+ return {
+ **analysis,
+ 'valuation_metrics': vm,
+ 'benchmarks': benchmarks_db.get(sector, {}),
+ 'insights': insights,
+ }
+
+
def main():
"""CLI entry point - outputs JSON for Tauri integration"""
import sys
@@ -394,48 +541,83 @@ def main():
segment = HealthcareSegment.PHARMA # default
analyzer = HealthcareMetrics(segment)
+ sector_key = sector.lower()
- # Map alternative key names to expected parameter names
- pharma_aliases = {
- 'peak_sales_estimate': 'peak_sales',
- 'patent_years_remaining': 'patent_life_remaining',
- 'success_probability': 'probability_of_success',
- 'dev_costs': 'development_costs_remaining',
- 'target_market_size': None, # informational only, not a method param
- 'drug_name': None, # informational only
- 'phase': None, # informational only
- }
- for old_key, new_key in pharma_aliases.items():
- if old_key in company_data:
- if new_key:
- company_data[new_key] = company_data.pop(old_key)
- else:
- company_data.pop(old_key)
-
- # Route to appropriate calculation
import inspect
- if segment in (HealthcareSegment.PHARMA, HealthcareSegment.BIOTECH):
- # Provide defaults for required params
- company_data.setdefault('probability_of_success', 0.5)
- company_data.setdefault('development_costs_remaining', 0)
- # Filter to only accepted kwargs
- valid_params = set(inspect.signature(analyzer.value_drug_candidate).parameters.keys())
- filtered = {k: v for k, v in company_data.items() if k in valid_params}
- analysis = analyzer.value_drug_candidate(**filtered)
+
+ if segment == HealthcareSegment.PHARMA:
+ # Frontend sends company-level data — use company-level calculation
+ analysis = _calculate_pharma_company_metrics(company_data)
+
+ elif segment == HealthcareSegment.BIOTECH:
+ # Frontend sends company-level biotech data — use company-level calculation
+ analysis = _calculate_biotech_company_metrics(company_data)
+ sector_key = 'biotech'
+
elif segment == HealthcareSegment.MEDICAL_DEVICES:
+ # Map frontend keys to Python parameter names
+ # fda_clearances (int) → regulatory_approvals (List[str])
+ if 'fda_clearances' in company_data:
+ n = int(company_data.pop('fda_clearances'))
+ approvals = ['FDA'] if n >= 1 else []
+ if n >= 2:
+ approvals.append('CE_Mark')
+ company_data.setdefault('regulatory_approvals', approvals)
+
+ # gross_margin: normalize to fraction if given as percentage
+ if 'gross_margin' in company_data and company_data['gross_margin'] > 1:
+ company_data['gross_margin'] = company_data['gross_margin'] / 100.0
+
+ # recurring_revenue_pct: normalize to fraction
+ if 'recurring_revenue_pct' in company_data and company_data['recurring_revenue_pct'] > 1:
+ company_data['recurring_revenue_pct'] = company_data['recurring_revenue_pct'] / 100.0
+
+ # Provide defaults for required params not in frontend form
+ company_data.setdefault('regulatory_approvals', ['FDA'])
+ company_data.setdefault('clinical_evidence_strength', 60)
+ company_data.setdefault('reimbursement_coverage', 70.0)
+
+ # Drop unknown keys
valid_params = set(inspect.signature(analyzer.calculate_medical_device_metrics).parameters.keys())
filtered = {k: v for k, v in company_data.items() if k in valid_params}
analysis = analyzer.calculate_medical_device_metrics(**filtered)
+ sector_key = 'devices'
+
elif segment == HealthcareSegment.HEALTHCARE_SERVICES:
- valid_params = set(inspect.signature(analyzer.calculate_healthcare_services_metrics).parameters.keys())
- filtered = {k: v for k, v in company_data.items() if k in valid_params}
- analysis = analyzer.calculate_healthcare_services_metrics(**filtered)
+ # Map frontend keys to Python parameter names
+ revenue = float(company_data.get('revenue', 0))
+ ebitda_margin_pct = float(company_data.get('ebitda_margin', 0))
+ ebitda = revenue * ebitda_margin_pct / 100.0
+ same_store_growth = float(company_data.get('same_store_growth', 0))
+ commercial_pct = float(company_data.get('payor_mix_commercial', 55)) / 100.0
+ # Remaining split between medicare and medicaid
+ remaining = max(0.0, 1.0 - commercial_pct)
+ payor_mix = {
+ 'commercial': commercial_pct,
+ 'medicare': remaining * 0.6,
+ 'medicaid': remaining * 0.4,
+ }
+ quality_scores = {'patient_satisfaction': 4.0, 'clinical_quality': 4.0}
+ regulatory_compliance_score = 85
+
+ analysis = analyzer.calculate_healthcare_services_metrics(
+ revenue=revenue,
+ ebitda=ebitda,
+ same_store_growth=same_store_growth,
+ payor_mix=payor_mix,
+ quality_scores=quality_scores,
+ regulatory_compliance_score=regulatory_compliance_score,
+ )
+ sector_key = 'services'
+
elif segment == HealthcareSegment.HEALTHTECH:
valid_params = set(inspect.signature(analyzer.calculate_healthtech_metrics).parameters.keys())
filtered = {k: v for k, v in company_data.items() if k in valid_params}
analysis = analyzer.calculate_healthtech_metrics(**filtered)
+ sector_key = 'healthtech'
- result = {"success": True, "data": analysis}
+ analysis_with_standard = _build_healthcare_standard_output(analysis, sector_key)
+ result = {"success": True, "data": analysis_with_standard}
print(json.dumps(result))
else:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/technology.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/technology.py
index 16bbb8bf6..8a232cf57 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/technology.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/technology.py
@@ -345,6 +345,90 @@ class TechnologyMetrics:
}
}
+def _build_standard_output(analysis: dict, sector: str) -> dict:
+ """Build valuation_metrics, benchmarks, and insights from sector-specific analysis output."""
+ benchmarks_db = {
+ 'saas': {
+ 'arr': {'p25': 50, 'median': 150, 'p75': 500},
+ 'arr_growth': {'p25': 25, 'median': 40, 'p75': 65},
+ 'gross_margin': {'p25': 65, 'median': 75, 'p75': 82},
+ 'net_retention': {'p25': 100, 'median': 110, 'p75': 125},
+ 'ltv_cac': {'p25': 2.0, 'median': 3.5, 'p75': 5.5},
+ },
+ 'marketplace': {
+ 'gmv': {'p25': 200, 'median': 800, 'p75': 3000},
+ 'take_rate': {'p25': 10, 'median': 17, 'p75': 25},
+ 'repeat_rate': {'p25': 40, 'median': 58, 'p75': 72},
+ },
+ 'semiconductor': {
+ 'revenue': {'p25': 100, 'median': 500, 'p75': 2000},
+ 'gross_margin': {'p25': 45, 'median': 55, 'p75': 65},
+ 'r_and_d_intensity': {'p25': 12, 'median': 18, 'p75': 25},
+ },
+ }
+
+ vm = {}
+ insights = []
+
+ if sector == 'saas':
+ km = analysis.get('key_metrics', {})
+ vm = {
+ 'rule_of_40': round(km.get('rule_of_40', 0), 1),
+ 'ltv_cac_ratio': round(km.get('ltv_cac_ratio', 0), 2),
+ 'cac_payback_months': round(km.get('cac_payback_months', 0), 1),
+ 'efficiency_score': analysis.get('efficiency_score', 0),
+ 'gross_margin_pct': round(analysis.get('gross_margin', 0), 1),
+ 'net_retention_rate': round(analysis.get('net_retention_rate', 0), 1),
+ }
+ vi = analysis.get('valuation_implications', {})
+ mr = vi.get('suggested_multiple_range', {})
+ vm['arr_multiple_mid'] = round(mr.get('mid', 0), 1)
+ if km.get('rule_of_40', 0) >= 40:
+ insights.append(f"Rule of 40 score of {vm['rule_of_40']} indicates strong operational efficiency — premium multiple justified.")
+ if km.get('ltv_cac_ratio', 0) >= 3:
+ insights.append("LTV/CAC ratio >= 3x demonstrates healthy unit economics for SaaS growth.")
+ if analysis.get('net_retention_rate', 0) >= 110:
+ insights.append("Net revenue retention above 110% shows strong net expansion — customers spending more over time.")
+ insights.append(f"Suggested ARR multiple range: {mr.get('low', 0):.1f}x – {mr.get('high', 0):.1f}x based on efficiency profile.")
+
+ elif sector == 'marketplace':
+ vm = {
+ 'gmv': round(analysis.get('gmv', 0), 1),
+ 'take_rate_pct': round(analysis.get('implied_take_rate', analysis.get('take_rate', 0) * 100), 1),
+ 'network_strength': round(analysis.get('network_strength', 0), 1),
+ 'marketplace_quality_score': analysis.get('marketplace_quality_score', 0),
+ }
+ mr = analysis.get('gmv_multiple_range', {})
+ vm['gmv_multiple_mid'] = round(mr.get('mid', 0), 2)
+ insights.append(f"GMV multiple range: {mr.get('low', 0):.2f}x – {mr.get('high', 0):.2f}x of GMV.")
+ if analysis.get('take_rate', 0) >= 15:
+ insights.append("Take rate >= 15% indicates strong monetization power in the marketplace.")
+ insights.append(f"Network strength score of {vm['network_strength']:.0f}% reflects combined supply/demand retention.")
+
+ elif sector == 'semiconductor':
+ vm = {
+ 'revenue': round(analysis.get('revenue', 0), 1),
+ 'gross_margin_pct': round(analysis.get('gross_margin', 0), 1),
+ 'technology_leadership_score': analysis.get('technology_leadership_score', 0),
+ 'semiconductor_quality_score': analysis.get('semiconductor_quality_score', 0),
+ 'design_win_coverage_years': round(analysis.get('design_win_coverage_years', 0), 2),
+ }
+ mr = analysis.get('typical_revenue_multiple', {})
+ vm['revenue_multiple_mid'] = round(mr.get('mid', 0), 1)
+ insights.append(f"Revenue multiple range: {mr.get('low', 0):.1f}x – {mr.get('high', 0):.1f}x.")
+ if analysis.get('technology_leadership_score', 0) >= 70:
+ insights.append("Technology leadership score indicates competitive process node advantage.")
+ if analysis.get('design_win_coverage_years', 0) >= 1.5:
+ insights.append("Strong design win backlog provides revenue visibility for 1.5+ years.")
+
+ return {
+ **analysis,
+ 'valuation_metrics': vm,
+ 'benchmarks': benchmarks_db.get(sector, {}),
+ 'insights': insights,
+ }
+
+
def main():
"""CLI entry point - outputs JSON for Tauri integration"""
import sys
@@ -378,12 +462,14 @@ def main():
model = TechBusinessModel.SAAS # default
analyzer = TechnologyMetrics(model)
+ sector_key = sector.lower()
# Route to appropriate calculation based on model
if model == TechBusinessModel.SAAS:
- # Map common alternative key names for SaaS
+ # Map frontend keys to Python parameter names
saas_aliases = {
'revenue': 'arr', 'annual_recurring_revenue': 'arr',
+ 'arr_growth': 'revenue_growth_rate',
'growth_rate': 'revenue_growth_rate', 'growth': 'revenue_growth_rate',
'net_retention': 'net_retention_rate', 'nrr': 'net_retention_rate',
'customer_acquisition_cost': 'cac',
@@ -392,15 +478,114 @@ def main():
for old_key, new_key in saas_aliases.items():
if old_key in company_data and new_key not in company_data:
company_data[new_key] = company_data.pop(old_key)
- analysis = analyzer.calculate_saas_metrics(**company_data)
+
+ # ltv_cac ratio: split into ltv=ratio and cac=1 so ltv/cac = ratio
+ if 'ltv_cac' in company_data and 'cac' not in company_data:
+ company_data['cac'] = 1.0
+ company_data['ltv'] = float(company_data.pop('ltv_cac'))
+ elif 'ltv_cac' in company_data:
+ company_data.pop('ltv_cac')
+
+ # gross_margin: normalize to 0-1 fraction if given as percentage
+ if 'gross_margin' in company_data and company_data['gross_margin'] > 1:
+ company_data['gross_margin'] = company_data['gross_margin'] / 100.0
+
+ # net_retention_rate: keep as-is (Python compares >= 110 treating it as percentage)
+ # rule_of_40 and cac_payback are outputs, not inputs — drop them
+ for drop_key in ('rule_of_40', 'cac_payback'):
+ company_data.pop(drop_key, None)
+
+ # Set defaults for required params not provided by frontend
+ company_data.setdefault('revenue_growth_rate', 30.0)
+ company_data.setdefault('net_retention_rate', 100.0)
+ company_data.setdefault('cac', 1.0)
+ company_data.setdefault('ltv', 3.0)
+
+ import inspect
+ valid_params = set(inspect.signature(analyzer.calculate_saas_metrics).parameters.keys())
+ filtered = {k: v for k, v in company_data.items() if k in valid_params}
+ analysis = analyzer.calculate_saas_metrics(**filtered)
+ sector_key = 'saas'
+
elif model == TechBusinessModel.CONSUMER_SOFTWARE:
- analysis = analyzer.calculate_user_metrics(**company_data)
+ import inspect
+ valid_params = set(inspect.signature(analyzer.calculate_user_metrics).parameters.keys())
+ filtered = {k: v for k, v in company_data.items() if k in valid_params}
+ analysis = analyzer.calculate_user_metrics(**filtered)
+ sector_key = 'consumer'
+
elif model == TechBusinessModel.MARKETPLACE:
- analysis = analyzer.calculate_marketplace_metrics(**company_data)
- elif model == TechBusinessModel.SEMICONDUCTOR:
- analysis = analyzer.calculate_semiconductor_metrics(**company_data)
+ # Map frontend keys to Python parameter names
+ marketplace_aliases = {
+ 'gmv_growth': None, # computed metric, not an input — drop
+ 'active_buyers': None, # not a param — drop
+ 'active_sellers': None, # not a param — drop
+ 'repeat_rate': 'demand_side_retention',
+ }
+ for old_key, new_key in marketplace_aliases.items():
+ if old_key in company_data:
+ if new_key:
+ if new_key not in company_data:
+ company_data[new_key] = company_data.pop(old_key)
+ else:
+ company_data.pop(old_key)
+ else:
+ company_data.pop(old_key)
+
+ # take_rate: normalize to fraction if given as percentage
+ if 'take_rate' in company_data and company_data['take_rate'] > 1:
+ company_data['take_rate'] = company_data['take_rate'] / 100.0
+
+ # Provide defaults for params not in frontend form
+ company_data.setdefault('revenue', company_data.get('gmv', 0) * company_data.get('take_rate', 0.15))
+ company_data.setdefault('liquidity_score', 70.0)
+ company_data.setdefault('supply_side_retention', company_data.get('demand_side_retention', 70.0))
+ company_data.setdefault('demand_side_retention', 70.0)
+
+ import inspect
+ valid_params = set(inspect.signature(analyzer.calculate_marketplace_metrics).parameters.keys())
+ filtered = {k: v for k, v in company_data.items() if k in valid_params}
+ analysis = analyzer.calculate_marketplace_metrics(**filtered)
+ sector_key = 'marketplace'
- result = {"success": True, "data": analysis}
+ elif model == TechBusinessModel.SEMICONDUCTOR:
+ # Map frontend keys to Python parameter names
+ semi_aliases = {
+ 'r_and_d_intensity': 'r_and_d_pct',
+ 'design_wins': 'design_win_backlog',
+ 'revenue_growth': None, # computed metric, not an input — drop
+ 'book_to_bill': None, # not a param — drop
+ }
+ for old_key, new_key in semi_aliases.items():
+ if old_key in company_data:
+ if new_key:
+ if new_key not in company_data:
+ company_data[new_key] = company_data.pop(old_key)
+ else:
+ company_data.pop(old_key)
+ else:
+ company_data.pop(old_key)
+
+ # r_and_d_pct: normalize to fraction if given as percentage
+ if 'r_and_d_pct' in company_data and company_data['r_and_d_pct'] > 1:
+ company_data['r_and_d_pct'] = company_data['r_and_d_pct'] / 100.0
+
+ # gross_margin: normalize to fraction
+ if 'gross_margin' in company_data and company_data['gross_margin'] > 1:
+ company_data['gross_margin'] = company_data['gross_margin'] / 100.0
+
+ # Provide defaults for params not in frontend form
+ company_data.setdefault('process_node', 14) # nm — 14nm default (mature)
+ company_data.setdefault('fabless', True)
+
+ import inspect
+ valid_params = set(inspect.signature(analyzer.calculate_semiconductor_metrics).parameters.keys())
+ filtered = {k: v for k, v in company_data.items() if k in valid_params}
+ analysis = analyzer.calculate_semiconductor_metrics(**filtered)
+ sector_key = 'semiconductor'
+
+ analysis_with_standard = _build_standard_output(analysis, sector_key)
+ result = {"success": True, "data": analysis_with_standard}
print(json.dumps(result))
else:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/merger_model.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/merger_model.py
index 922b14251..999da8b59 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/merger_model.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/merger_model.py
@@ -80,9 +80,15 @@ class MergerModel:
sources_uses_table = self.sources_uses.auto_balance()
+ # Support both combined 'synergies' key and separate 'cost_synergies'/'revenue_synergies' keys
+ total_synergies = (
+ self.deal_terms.get('synergies') or
+ (self.deal_terms.get('cost_synergies', 0) + self.deal_terms.get('revenue_synergies', 0))
+ )
+
deal_structure = {
'new_debt': new_debt_needed,
- 'synergies': self.deal_terms.get('synergies', 0),
+ 'synergies': total_synergies,
'integration_costs': self.deal_terms.get('integration_costs', 0),
'tax_rate': self.deal_terms.get('tax_rate', 0.21),
'acquirer_stock_price': acquirer_stock_price,
@@ -134,7 +140,7 @@ class MergerModel:
synergy_sensitivity = self.sensitivity_analyzer.synergy_sensitivity(
min_synergies=0,
- max_synergies=self.deal_terms.get('synergies', 0) * 2,
+ max_synergies=total_synergies * 2,
steps=11
)
@@ -196,14 +202,20 @@ class MergerModel:
'pro_forma_net_income': pf_y1['net_income']
},
'key_assumptions': {
- 'synergies': self.deal_terms.get('synergies', 0),
+ 'synergies': (
+ self.deal_terms.get('synergies') or
+ (self.deal_terms.get('cost_synergies', 0) + self.deal_terms.get('revenue_synergies', 0))
+ ),
'integration_costs': self.deal_terms.get('integration_costs', 0),
'new_debt': model_results['sources_uses']['sources']['sources_breakdown']['new_debt']['amount'],
'new_shares_issued': model_results['new_shares_issued']
},
'breakeven_analysis': {
'breakeven_synergies': model_results['breakeven_synergies'],
- 'synergies_cushion': self.deal_terms.get('synergies', 0) - model_results['breakeven_synergies']
+ 'synergies_cushion': (
+ self.deal_terms.get('synergies') or
+ (self.deal_terms.get('cost_synergies', 0) + self.deal_terms.get('revenue_synergies', 0))
+ ) - model_results['breakeven_synergies']
}
}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/berkus_method.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/berkus_method.py
index 4aa33909e..790c5a7f6 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/berkus_method.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/berkus_method.py
@@ -151,7 +151,7 @@ def main():
factor_scores = json.loads(sys.argv[2])
berkus = BerkusMethod(max_value_per_factor=factor_scores.get('max_value_per_factor', 500_000))
- # Map frontend keys to quick_assessment params
+ # Map frontend keys to quick_assessment params (0-100 scale → 0-1)
key_map = {
'sound_idea': 'idea_score', 'idea_score': 'idea_score',
'prototype': 'prototype_score', 'prototype_score': 'prototype_score',
@@ -161,8 +161,16 @@ def main():
}
mapped = {}
for k, v in factor_scores.items():
- if k in key_map:
- mapped[key_map[k]] = v
+ if k in key_map and k != 'max_value_per_factor':
+ # Normalize: if score > 1, treat as percentage (0-100) → (0-1)
+ normalized = v / 100.0 if v > 1 else v
+ mapped[key_map[k]] = normalized
+ # Provide defaults for any missing required args
+ defaults = {'idea_score': 0.5, 'prototype_score': 0.5, 'team_score': 0.5,
+ 'relationships_score': 0.5, 'rollout_score': 0.5}
+ for param, default in defaults.items():
+ if param not in mapped:
+ mapped[param] = default
valuation = berkus.quick_assessment(**mapped)
result = {"success": True, "data": valuation}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/risk_factor_summation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/risk_factor_summation.py
index 5d267185a..7481810f5 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/risk_factor_summation.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/risk_factor_summation.py
@@ -197,24 +197,47 @@ def main():
risk_assessments = json.loads(sys.argv[3])
rfs = RiskFactorSummation(base_valuation=base_valuation)
- # Map frontend keys to quick_assessment params
- key_map = {
- 'management_risk': 'management_risk',
- 'stage_of_business': 'stage_risk', 'stage_risk': 'stage_risk',
- 'technology_risk': 'technology_risk',
- 'competition_risk': 'competition_risk',
- 'market_risk': 'market_risk', 'sales_risk': 'market_risk',
- 'funding_risk': 'funding_risk', 'funding_capital': 'funding_risk',
+ # Map all frontend key variants to RiskFactor enum values
+ enum_key_map = {
+ # management
+ 'management': RiskFactor.MANAGEMENT, 'management_risk': RiskFactor.MANAGEMENT,
+ # stage
+ 'stage': RiskFactor.STAGE_OF_BUSINESS, 'stage_of_business': RiskFactor.STAGE_OF_BUSINESS,
+ 'stage_risk': RiskFactor.STAGE_OF_BUSINESS,
+ # legislation/political
+ 'legislation': RiskFactor.LEGISLATION_POLITICAL,
+ 'legislation_political': RiskFactor.LEGISLATION_POLITICAL,
+ # manufacturing
+ 'manufacturing': RiskFactor.MANUFACTURING,
+ # sales/marketing
+ 'sales_marketing': RiskFactor.SALES_MARKETING, 'sales_risk': RiskFactor.SALES_MARKETING,
+ 'market_risk': RiskFactor.SALES_MARKETING, 'marketing': RiskFactor.SALES_MARKETING,
+ # funding
+ 'funding': RiskFactor.FUNDING_CAPITAL, 'funding_risk': RiskFactor.FUNDING_CAPITAL,
+ 'funding_capital': RiskFactor.FUNDING_CAPITAL,
+ # competition
+ 'competition': RiskFactor.COMPETITION, 'competition_risk': RiskFactor.COMPETITION,
+ # technology
+ 'technology': RiskFactor.TECHNOLOGY, 'technology_risk': RiskFactor.TECHNOLOGY,
+ # litigation
+ 'litigation': RiskFactor.LITIGATION,
+ # international
+ 'international': RiskFactor.INTERNATIONAL,
+ # reputation
+ 'reputation': RiskFactor.REPUTATION,
+ # exit
+ 'exit': RiskFactor.LUCRATIVE_EXIT, 'lucrative_exit': RiskFactor.LUCRATIVE_EXIT,
}
- mapped = {}
+ enum_assessments = {}
for k, v in risk_assessments.items():
- if k in key_map:
- mapped[key_map[k]] = v
- # Ensure all required params have defaults (0 = average risk)
- for required_key in ('management_risk', 'stage_risk', 'technology_risk', 'competition_risk', 'market_risk', 'funding_risk'):
- if required_key not in mapped:
- mapped[required_key] = 0
- valuation = rfs.quick_assessment(base_valuation=base_valuation, **mapped)
+ rf = enum_key_map.get(k)
+ if rf:
+ enum_assessments[rf] = int(v)
+ # Fill missing with 0 (average)
+ for rf in RiskFactor:
+ if rf not in enum_assessments:
+ enum_assessments[rf] = 0
+ valuation = rfs.calculate_valuation(enum_assessments)
result = {"success": True, "data": valuation}
print(json.dumps(result))
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/scorecard_method.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/scorecard_method.py
index df3ccc6b3..75b99b44c 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/scorecard_method.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/scorecard_method.py
@@ -171,17 +171,48 @@ def main():
region = sys.argv[3]
factor_assessments = json.loads(sys.argv[4])
- scorecard = ScorecardMethod(region=region)
- # Map alternative frontend key names to scorecard factor names
+ scorecard = ScorecardMethod(region=region.capitalize() if region.lower() in ('us','europe','asia') else 'US')
+ # Map all frontend key variants to internal scorecard factor names
key_map = {
- 'market_opportunity': 'size_of_opportunity', 'market_size': 'size_of_opportunity',
- 'marketing_channels': 'marketing_sales_channels', 'sales_channels': 'marketing_sales_channels',
+ # management team
+ 'team': 'management_team', 'management_team': 'management_team',
+ 'quality_team': 'management_team', 'team_strength': 'management_team',
+ # market size
+ 'market_size': 'size_of_opportunity', 'market_opportunity': 'size_of_opportunity',
+ 'size_of_opportunity': 'size_of_opportunity',
+ # product
+ 'product': 'product_technology', 'product_technology': 'product_technology',
+ 'product_strength': 'product_technology',
+ # competitive
+ 'competitive': 'competitive_environment', 'competitive_environment': 'competitive_environment',
+ 'competition': 'competitive_environment',
+ # marketing
+ 'marketing': 'marketing_sales_channels', 'marketing_channels': 'marketing_sales_channels',
+ 'sales_channels': 'marketing_sales_channels', 'marketing_sales_channels': 'marketing_sales_channels',
+ # need for investment
+ 'need_for_funding': 'need_for_additional_investment',
'need_for_investment': 'need_for_additional_investment',
- 'other': 'other_factors',
+ 'need_for_additional_investment': 'need_for_additional_investment',
+ # other
+ 'other': 'other_factors', 'other_factors': 'other_factors',
}
mapped = {}
for k, v in factor_assessments.items():
- mapped[key_map.get(k, k)] = v
+ internal_key = key_map.get(k)
+ if internal_key:
+ # Frontend sends multipliers (0.5-1.5); convert to comparison scores (-0.5 to +0.5)
+ # If value > 1.1 or < 0.9 it's clearly a multiplier, otherwise treat as comparison score
+ val = float(v)
+ if val > 1.1 or val < 0.4:
+ # It's a multiplier (e.g. 1.2 = 20% above avg) → comparison score = (val - 1.0) * 0.5 / 0.5 → clamped
+ mapped[internal_key] = max(-0.5, min(0.5, (val - 1.0)))
+ else:
+ # Already a comparison score (-0.5 to +0.5)
+ mapped[internal_key] = val
+ # Fill any missing required factors with 0 (average)
+ for factor in scorecard.factor_weights:
+ if factor not in mapped:
+ mapped[factor] = 0.0
valuation = scorecard.calculate_valuation(stage=stage, factor_assessments=mapped)
result = {"success": True, "data": valuation}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/startup_summary.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/startup_summary.py
index 9b6a72f39..61273226d 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/startup_summary.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/startup_summary.py
@@ -78,18 +78,42 @@ class StartupValuationSummary:
# Scorecard Method
if scorecard_inputs:
- scorecard = ScorecardMethod(region=scorecard_inputs.get('region', 'US'))
- # Map alternative frontend key names to scorecard factor names
+ raw_region = scorecard_inputs.get('region', 'US')
+ region = raw_region.capitalize() if raw_region.lower() in ('us', 'europe', 'asia') else 'US'
+ scorecard = ScorecardMethod(region=region)
assessments = scorecard_inputs.get('assessments', {})
+ # Full key map: frontend short names → internal factor names
key_map = {
- 'market_opportunity': 'size_of_opportunity', 'market_size': 'size_of_opportunity',
- 'marketing_channels': 'marketing_sales_channels', 'sales_channels': 'marketing_sales_channels',
+ 'team': 'management_team', 'management_team': 'management_team',
+ 'quality_team': 'management_team', 'team_strength': 'management_team',
+ 'market_size': 'size_of_opportunity', 'market_opportunity': 'size_of_opportunity',
+ 'size_of_opportunity': 'size_of_opportunity',
+ 'product': 'product_technology', 'product_technology': 'product_technology',
+ 'competitive': 'competitive_environment', 'competitive_environment': 'competitive_environment',
+ 'competition': 'competitive_environment',
+ 'marketing': 'marketing_sales_channels', 'marketing_channels': 'marketing_sales_channels',
+ 'sales_channels': 'marketing_sales_channels', 'marketing_sales_channels': 'marketing_sales_channels',
+ 'need_for_funding': 'need_for_additional_investment',
'need_for_investment': 'need_for_additional_investment',
- 'other': 'other_factors',
+ 'need_for_additional_investment': 'need_for_additional_investment',
+ 'other': 'other_factors', 'other_factors': 'other_factors',
}
- mapped_assessments = {key_map.get(k, k): v for k, v in assessments.items()}
+ mapped_assessments = {}
+ for k, v in assessments.items():
+ internal_key = key_map.get(k)
+ if internal_key:
+ val = float(v)
+ # Frontend sends multipliers (0.5-1.5) → convert to comparison scores (-0.5 to +0.5)
+ if val > 1.1 or val < 0.4:
+ mapped_assessments[internal_key] = max(-0.5, min(0.5, val - 1.0))
+ else:
+ mapped_assessments[internal_key] = val
+ # Fill missing factors with 0 (average)
+ for factor in scorecard.factor_weights:
+ if factor not in mapped_assessments:
+ mapped_assessments[factor] = 0.0
scorecard_result = scorecard.calculate_valuation(
- stage=scorecard_inputs['stage'],
+ stage=scorecard_inputs.get('stage', 'seed'),
factor_assessments=mapped_assessments
)
valuations['scorecard'] = {
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/quantstats_analytics.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/quantstats_analytics.py
index 0791fb7e5..c04ccbca0 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/quantstats_analytics.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/quantstats_analytics.py
@@ -336,8 +336,8 @@ def compute_stats(portfolio_returns: pd.Series, benchmark_returns: pd.Series, rf
dd_details = qs.stats.drawdown_details(qs.stats.to_drawdown_series(portfolio_returns))
if dd_details is not None and len(dd_details) > 0:
metrics["max_drawdown_duration"] = int(dd_details["days"].max()) if "days" in dd_details.columns else None
- except Exception:
- pass
+ except Exception as e:
+ sys.stderr.write(f"[QuantStats] max_drawdown_duration error: {e}\n")
# Benchmark comparison metrics
if benchmark_returns is not None and len(benchmark_returns) > 0:
@@ -489,7 +489,8 @@ def compute_drawdowns(portfolio_returns: pd.Series) -> dict:
result["drawdown_periods"] = periods
else:
result["drawdown_periods"] = []
- except Exception:
+ except Exception as e:
+ sys.stderr.write(f"[QuantStats] drawdown_periods error: {e}\n")
result["drawdown_periods"] = []
return result
@@ -518,8 +519,8 @@ def compute_rolling(portfolio_returns: pd.Series, benchmark_returns: pd.Series,
"value": safe_float(val)
})
result[f"rolling_sharpe_{label}"] = sharpe_data
- except Exception:
- pass
+ except Exception as e:
+ sys.stderr.write(f"[QuantStats] rolling_sharpe_{label} error: {e}\n")
# Rolling Volatility
try:
@@ -532,8 +533,8 @@ def compute_rolling(portfolio_returns: pd.Series, benchmark_returns: pd.Series,
"value": safe_float(val)
})
result[f"rolling_volatility_{label}"] = vol_data
- except Exception:
- pass
+ except Exception as e:
+ sys.stderr.write(f"[QuantStats] rolling_volatility_{label} error: {e}\n")
# Rolling Sortino
try:
@@ -546,8 +547,8 @@ def compute_rolling(portfolio_returns: pd.Series, benchmark_returns: pd.Series,
"value": safe_float(val)
})
result[f"rolling_sortino_{label}"] = sortino_data
- except Exception:
- pass
+ except Exception as e:
+ sys.stderr.write(f"[QuantStats] rolling_sortino_{label} error: {e}\n")
# Cumulative returns series
cum_returns = (1 + portfolio_returns).cumprod() - 1
@@ -577,131 +578,114 @@ def compute_rolling(portfolio_returns: pd.Series, benchmark_returns: pd.Series,
def compute_montecarlo(portfolio_returns: pd.Series, sims: int = 1000) -> dict:
- """Run Monte Carlo simulations on portfolio returns.
+ """Run Monte Carlo simulations via bootstrap resampling of historical returns.
- quantstats montecarlo_* functions return a dict with keys:
- min, max, mean, median, std, percentile_5, percentile_95
- We normalize these into our standard distribution format.
+ qs.stats.montecarlo* functions do not exist in quantstats 0.0.64.
+ We implement a bootstrap simulation: each path draws T daily returns
+ (with replacement) from the historical return distribution, then
+ compounds them to produce a cumulative return path.
"""
result = {}
- def _normalize_mc_dict(mc_dict):
- """Convert quantstats MC dict to our standard distribution format."""
- if mc_dict is None or not isinstance(mc_dict, dict):
- return None
- return {
- "mean": safe_float(mc_dict.get("mean")),
- "std": safe_float(mc_dict.get("std")),
- "min": safe_float(mc_dict.get("min")),
- "max": safe_float(mc_dict.get("max")),
- "p5": safe_float(mc_dict.get("percentile_5")),
- "p10": None, # not provided by quantstats
- "p25": None,
- "p50": safe_float(mc_dict.get("median")),
- "p75": None,
- "p90": None,
- "p95": safe_float(mc_dict.get("percentile_95")),
- "count": sims,
- }
-
- try:
- mc_sharpe = qs.stats.montecarlo_sharpe(portfolio_returns, sims=sims)
- result["sharpe_distribution"] = _normalize_mc_dict(mc_sharpe)
- except Exception as e:
- sys.stderr.write(f"[QuantStats] MC Sharpe error: {e}\n")
- result["sharpe_distribution"] = None
-
- try:
- mc_dd = qs.stats.montecarlo_drawdown(portfolio_returns, sims=sims)
- result["max_drawdown_distribution"] = _normalize_mc_dict(mc_dd)
- except Exception as e:
- sys.stderr.write(f"[QuantStats] MC Drawdown error: {e}\n")
- result["max_drawdown_distribution"] = None
+ returns_arr = portfolio_returns.dropna().values.astype(float)
+ n = len(returns_arr)
+ if n < 20:
+ null = {"wealth_distribution": None, "cagr_distribution": None,
+ "sharpe_distribution": None, "max_drawdown_distribution": None,
+ "simulation_paths": None}
+ result.update(null)
+ return result
- try:
- mc_cagr = qs.stats.montecarlo_cagr(portfolio_returns, sims=sims)
- result["cagr_distribution"] = _normalize_mc_dict(mc_cagr)
- except Exception as e:
- sys.stderr.write(f"[QuantStats] MC CAGR error: {e}\n")
- result["cagr_distribution"] = None
+ rng = np.random.default_rng()
+ # Each simulated path has the same length as the observed history
+ T = n
- # General Monte Carlo simulation - returns a MonteCarloResult with .data DataFrame
- try:
- mc_general = qs.stats.montecarlo(portfolio_returns, sims=sims)
- # Extract DataFrame from MonteCarloResult if needed
- mc_df = None
- if mc_general is not None:
- if isinstance(mc_general, pd.DataFrame):
- mc_df = mc_general
- elif hasattr(mc_general, 'data') and isinstance(mc_general.data, pd.DataFrame):
- mc_df = mc_general.data
-
- if mc_df is not None and not mc_df.empty:
- # Get final cumulative return for each simulation path
- final_values = mc_df.iloc[-1].values.astype(float)
- result["wealth_distribution"] = {
- "mean": safe_float(np.mean(final_values)),
- "std": safe_float(np.std(final_values)),
- "min": safe_float(np.min(final_values)),
- "max": safe_float(np.max(final_values)),
- "p5": safe_float(np.percentile(final_values, 5)),
- "p10": safe_float(np.percentile(final_values, 10)),
- "p25": safe_float(np.percentile(final_values, 25)),
- "p50": safe_float(np.percentile(final_values, 50)),
- "p75": safe_float(np.percentile(final_values, 75)),
- "p90": safe_float(np.percentile(final_values, 90)),
- "p95": safe_float(np.percentile(final_values, 95)),
- "count": int(len(final_values)),
- }
+ def _full_distribution(values: np.ndarray) -> dict:
+ return {
+ "mean": safe_float(np.mean(values)),
+ "std": safe_float(np.std(values)),
+ "min": safe_float(np.min(values)),
+ "max": safe_float(np.max(values)),
+ "p5": safe_float(np.percentile(values, 5)),
+ "p10": safe_float(np.percentile(values, 10)),
+ "p25": safe_float(np.percentile(values, 25)),
+ "p50": safe_float(np.percentile(values, 50)),
+ "p75": safe_float(np.percentile(values, 75)),
+ "p90": safe_float(np.percentile(values, 90)),
+ "p95": safe_float(np.percentile(values, 95)),
+ "count": int(sims),
+ }
- # Export simulation paths for chart visualization
- # Sample up to 100 paths and downsample time steps to keep JSON small
- num_cols = mc_df.shape[1]
- max_paths = min(100, num_cols)
- # Pick evenly spaced paths (sorted by final value for a nice fan shape)
- sorted_cols = sorted(range(num_cols), key=lambda i: mc_df.iloc[-1, i])
- step = max(1, num_cols // max_paths)
- selected = sorted_cols[::step][:max_paths]
-
- # Downsample time to ~100 points
- num_rows = mc_df.shape[0]
- max_points = min(100, num_rows)
- row_step = max(1, num_rows // max_points)
- row_indices = list(range(0, num_rows, row_step))
- if row_indices[-1] != num_rows - 1:
- row_indices.append(num_rows - 1)
-
- paths = []
- for col_idx in selected:
- path_vals = [safe_float(mc_df.iloc[r, col_idx]) for r in row_indices]
- paths.append(path_vals)
-
- # Also compute percentile bands at each time step
- p5_band = [safe_float(np.percentile(mc_df.iloc[r].values, 5)) for r in row_indices]
- p50_band = [safe_float(np.percentile(mc_df.iloc[r].values, 50)) for r in row_indices]
- p95_band = [safe_float(np.percentile(mc_df.iloc[r].values, 95)) for r in row_indices]
-
- # Include the original (actual) returns if available
- original_path = None
- if hasattr(mc_general, 'original') and mc_general.original is not None:
- orig = mc_general.original
- original_path = [safe_float(orig.iloc[r]) for r in row_indices]
-
- result["simulation_paths"] = {
- "paths": paths,
- "time_steps": len(row_indices),
- "num_paths": len(paths),
- "p5_band": p5_band,
- "p50_band": p50_band,
- "p95_band": p95_band,
- "original_path": original_path,
- }
- else:
- result["wealth_distribution"] = None
- result["simulation_paths"] = None
- except Exception as e:
- sys.stderr.write(f"[QuantStats] MC General error: {e}\n")
- result["wealth_distribution"] = None
+ # Generate all paths at once: shape (T, sims)
+ sampled = rng.choice(returns_arr, size=(T, sims), replace=True)
+
+ # Cumulative return paths: (T, sims) — values are cumulative returns (e.g. 0.15 = +15%)
+ cum_paths = np.cumprod(1 + sampled, axis=0) - 1
+
+ # Terminal wealth (final cumulative return per path)
+ final_values = cum_paths[-1, :]
+ result["wealth_distribution"] = _full_distribution(final_values)
+
+ # CAGR distribution
+ years = T / 252.0
+ cagr_values = np.where(
+ final_values > -1,
+ (1 + final_values) ** (1.0 / max(years, 1e-6)) - 1,
+ -1.0
+ )
+ result["cagr_distribution"] = _full_distribution(cagr_values)
+
+ # Sharpe distribution (annualised, per path)
+ path_means = sampled.mean(axis=0)
+ path_stds = sampled.std(axis=0)
+ with np.errstate(divide='ignore', invalid='ignore'):
+ sharpe_values = np.where(path_stds > 0, (path_means / path_stds) * np.sqrt(252), 0.0)
+ result["sharpe_distribution"] = _full_distribution(sharpe_values)
+
+ # Max drawdown distribution (per path)
+ wealth = 1 + cum_paths # absolute wealth index
+ running_max = np.maximum.accumulate(wealth, axis=0)
+ drawdowns = (wealth - running_max) / running_max
+ max_dd_values = drawdowns.min(axis=0)
+ result["max_drawdown_distribution"] = _full_distribution(max_dd_values)
+
+ # --- Simulation paths for chart (sample 100 evenly-spaced paths) ---
+ # Downsample to ~100 time points
+ max_points = min(100, T)
+ row_step = max(1, T // max_points)
+ row_indices = list(range(0, T, row_step))
+ if row_indices[-1] != T - 1:
+ row_indices.append(T - 1)
+
+ # Pick 100 paths sorted by final value (fan shape)
+ sorted_cols = np.argsort(final_values)
+ step = max(1, sims // 100)
+ selected = sorted_cols[::step][:100]
+
+ paths = []
+ for col_idx in selected:
+ path_vals = [safe_float(cum_paths[r, col_idx]) for r in row_indices]
+ paths.append(path_vals)
+
+ # Percentile bands at each sampled time step
+ cum_at_rows = cum_paths[row_indices, :]
+ p5_band = [safe_float(np.percentile(cum_at_rows[i], 5)) for i in range(len(row_indices))]
+ p50_band = [safe_float(np.percentile(cum_at_rows[i], 50)) for i in range(len(row_indices))]
+ p95_band = [safe_float(np.percentile(cum_at_rows[i], 95)) for i in range(len(row_indices))]
+
+ # Actual historical cumulative return path (same time-step sampling)
+ actual_cum = (np.cumprod(1 + returns_arr) - 1)
+ original_path = [safe_float(actual_cum[r]) for r in row_indices]
+
+ result["simulation_paths"] = {
+ "paths": paths,
+ "time_steps": len(row_indices),
+ "num_paths": len(paths),
+ "p5_band": p5_band,
+ "p50_band": p50_band,
+ "p95_band": p95_band,
+ "original_path": original_path,
+ }
return result
@@ -740,6 +724,7 @@ def main():
benchmark = sys.argv[3] if len(sys.argv) > 3 else "SPY"
period = sys.argv[4] if len(sys.argv) > 4 else "1y"
risk_free_rate = float(sys.argv[5]) if len(sys.argv) > 5 else 0.02
+ num_sims = int(sys.argv[6]) if len(sys.argv) > 6 else 1000
try:
tickers_weights = json.loads(tickers_json)
@@ -779,7 +764,7 @@ def main():
result["data"] = compute_rolling(portfolio_returns, benchmark_returns, risk_free_rate)
elif action == "montecarlo":
- result["data"] = compute_montecarlo(portfolio_returns)
+ result["data"] = compute_montecarlo(portfolio_returns, sims=num_sims)
elif action == "full_report":
result["data"] = {
@@ -787,7 +772,7 @@ def main():
"returns": compute_returns_analysis(portfolio_returns),
"drawdown": compute_drawdowns(portfolio_returns),
"rolling": compute_rolling(portfolio_returns, benchmark_returns, risk_free_rate),
- "montecarlo": compute_montecarlo(portfolio_returns),
+ "montecarlo": compute_montecarlo(portfolio_returns, sims=num_sims),
}
elif action == "html_report":
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/deepagents/fincept_llm_adapter.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/deepagents/fincept_llm_adapter.py
index 08a077ed3..6bf3af639 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/deepagents/fincept_llm_adapter.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/deepagents/fincept_llm_adapter.py
@@ -22,7 +22,7 @@ class FinceptLLMAdapter(BaseChatModel):
Supports streaming, function calling, and all DeepAgents features.
"""
- api_endpoint: str = "https://finceptbackend.share.zrok.io/research/llm"
+ api_endpoint: str = "https://api.fincept.in/research/llm"
api_key: Optional[str] = None
model_name: str = "fincept-default"
temperature: float = 0.7
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/deepagents/fincept_orchestrator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/deepagents/fincept_orchestrator.py
index 9ab8e46ff..daed67bee 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/deepagents/fincept_orchestrator.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/deepagents/fincept_orchestrator.py
@@ -17,7 +17,7 @@ from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
-BASE_URL = "https://finceptbackend.share.zrok.io"
+BASE_URL = "https://api.fincept.in"
POLL_INTERVAL = 4 # seconds between polls
POLL_MAX_WAIT = 180 # max seconds to wait for a single LLM call
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 15adb3bd3..f6687569f 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
@@ -185,45 +185,55 @@ class CoreAgent:
# Financial Workflows
# ============================================================
+ def _resolve_model_config(self) -> Dict[str, Any]:
+ """Derive provider from api_keys passed at runtime instead of hardcoding openai."""
+ keys = self.api_keys or {}
+ preferred = ["fincept", "ollama", "anthropic", "google", "groq",
+ "deepseek", "openai", "openrouter"]
+ for provider in preferred:
+ if keys.get(provider) or keys.get(f"{provider.upper()}_API_KEY"):
+ return {"provider": provider}
+ for k, v in keys.items():
+ if k.endswith("_API_KEY") and v:
+ return {"provider": k[:-8].lower()}
+ return {"provider": "openai"}
+
def run_stock_analysis(self, symbol: str, config: Dict[str, Any] = None) -> Dict[str, Any]:
"""Run stock analysis workflow."""
from finagent_core.modules import FinancialWorkflowTemplates
-
- config = config or {
- "model": {"provider": "openai", "model_id": "gpt-4-turbo"},
- "instructions": "You are a financial analyst"
- }
- agent = self._create_agent(config)
+ cfg = config or {}
+ model_config = cfg.get("model") or self._resolve_model_config()
workflow = FinancialWorkflowTemplates.stock_analysis_pipeline(
- fetch_agent=agent, analysis_agent=agent, report_agent=agent
+ api_keys=self.api_keys,
+ model_config=model_config,
+ terminal_endpoint=cfg.get("terminal_mcp_endpoint"),
+ terminal_tool_defs=cfg.get("terminal_tools", []),
)
- return workflow.run({"symbol": symbol})
+ return workflow.run(symbol)
def run_portfolio_rebalancing(self, portfolio_data: Dict[str, Any], config: Dict[str, Any] = None) -> Dict[str, Any]:
"""Run portfolio rebalancing workflow."""
from finagent_core.modules import FinancialWorkflowTemplates
-
- config = config or {
- "model": {"provider": "openai", "model_id": "gpt-4-turbo"},
- "instructions": "You are a portfolio manager"
- }
- agent = self._create_agent(config)
+ cfg = config or {}
+ model_config = cfg.get("model") or self._resolve_model_config()
workflow = FinancialWorkflowTemplates.portfolio_rebalancing(
- analysis_agent=agent, optimization_agent=agent, execution_agent=agent
+ api_keys=self.api_keys,
+ model_config=model_config,
+ terminal_endpoint=cfg.get("terminal_mcp_endpoint"),
+ terminal_tool_defs=cfg.get("terminal_tools", []),
)
return workflow.run(portfolio_data)
def run_risk_assessment(self, portfolio_data: Dict[str, Any], config: Dict[str, Any] = None) -> Dict[str, Any]:
"""Run risk assessment workflow."""
from finagent_core.modules import FinancialWorkflowTemplates
-
- config = config or {
- "model": {"provider": "openai", "model_id": "gpt-4-turbo"},
- "instructions": "You are a risk analyst"
- }
- agent = self._create_agent(config)
+ cfg = config or {}
+ model_config = cfg.get("model") or self._resolve_model_config()
workflow = FinancialWorkflowTemplates.risk_assessment(
- risk_agent=agent, market_agent=agent
+ api_keys=self.api_keys,
+ model_config=model_config,
+ terminal_endpoint=cfg.get("terminal_mcp_endpoint"),
+ terminal_tool_defs=cfg.get("terminal_tools", []),
)
return workflow.run(portfolio_data)
@@ -404,12 +414,48 @@ class CoreAgent:
# ============================================================
def get_response_content(self, response) -> str:
- """Extract text content from response."""
- # Try .content attribute (standard agno response)
- if hasattr(response, 'content'):
- return response.content
+ """Extract text content from response.
- # If response is a dict (from custom models), try to extract the text
+ For TeamRunOutput, combines member responses with the coordinator summary
+ so the user sees the full team output, not just the brief delegation message.
+ """
+ # TeamRunOutput: prefer member_responses + coordinator summary
+ if hasattr(response, 'member_responses') and response.member_responses:
+ parts = []
+ for i, member_resp in enumerate(response.member_responses):
+ member_content = None
+ # RunOutput has .content
+ if hasattr(member_resp, 'content') and member_resp.content:
+ member_content = str(member_resp.content)
+ # Nested TeamRunOutput — recurse
+ elif hasattr(member_resp, 'member_responses'):
+ member_content = self.get_response_content(member_resp)
+ if member_content and member_content.strip():
+ # Use agent name if available
+ name = None
+ if hasattr(member_resp, 'agent_name') and member_resp.agent_name:
+ name = member_resp.agent_name
+ elif hasattr(member_resp, 'team_name') and member_resp.team_name:
+ name = member_resp.team_name
+ header = f"### {name}\n" if name else f"### Agent {i + 1}\n"
+ parts.append(header + member_content.strip())
+ if parts:
+ # Append coordinator summary if it adds substance beyond delegation
+ coordinator_content = getattr(response, 'content', None)
+ if coordinator_content and str(coordinator_content).strip():
+ coord_str = str(coordinator_content).strip()
+ # Only append if it's not just a delegation notice
+ delegation_phrases = ['delegated', 'delegate', 'assigned', 'routed']
+ is_delegation = any(p in coord_str.lower() for p in delegation_phrases) and len(coord_str) < 300
+ if not is_delegation:
+ parts.append(f"### Summary\n{coord_str}")
+ return "\n\n---\n\n".join(parts)
+
+ # Standard RunResponse / single-agent: .content attribute
+ if hasattr(response, 'content') and response.content is not None:
+ return str(response.content)
+
+ # Dict response (from custom models)
if isinstance(response, dict):
for key in ['response', 'content', 'text', 'answer', 'message']:
if key in response:
@@ -434,8 +480,9 @@ class CoreAgent:
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
+ provider = model_config.get("provider") or self._resolve_model_config()["provider"]
return ModelsRegistry.create_model(
- provider=model_config.get("provider", "openai"),
+ provider=provider,
model_id=model_config.get("model_id"),
api_keys=self.api_keys,
temperature=model_config.get("temperature"),
@@ -462,8 +509,9 @@ class CoreAgent:
# 1. Create Model
# =================================================================
model_config = config.get("model", {})
+ provider = model_config.get("provider") or self._resolve_model_config()["provider"]
model = ModelsRegistry.create_model(
- provider=model_config.get("provider", "openai"),
+ provider=provider,
model_id=model_config.get("model_id"),
api_keys=self.api_keys,
temperature=model_config.get("temperature"),
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent_stream.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent_stream.py
index a50c9d051..7fc960e30 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent_stream.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent_stream.py
@@ -54,6 +54,19 @@ class StreamingCoreAgent:
"""Emit a stream chunk"""
self.stream_callback(chunk_type, content, metadata)
+ def _resolve_provider_from_keys(self) -> str:
+ """Derive provider from api_keys instead of defaulting to openai."""
+ keys = self.api_keys or {}
+ preferred = ["fincept", "ollama", "anthropic", "google", "groq",
+ "deepseek", "openai", "openrouter"]
+ for provider in preferred:
+ if keys.get(provider) or keys.get(f"{provider.upper()}_API_KEY"):
+ return provider
+ for k, v in keys.items():
+ if k.endswith("_API_KEY") and v:
+ return k[:-8].lower()
+ return "openai"
+
def run_streaming(
self,
query: str,
@@ -71,10 +84,12 @@ class StreamingCoreAgent:
# Check if model supports streaming
model_config = config.get("model", {})
- provider = model_config.get("provider", "openai")
+ # Resolve provider from api_keys if not explicitly set in config
+ provider = model_config.get("provider") or self._resolve_provider_from_keys()
# Providers that support native streaming
- streaming_providers = ["openai", "anthropic", "groq", "together", "fireworks", "ollama"]
+ streaming_providers = ["openai", "anthropic", "groq", "together", "fireworks", "ollama",
+ "fincept", "google", "deepseek", "openrouter"]
if provider in streaming_providers:
# Use native streaming
@@ -186,43 +201,37 @@ class StreamingCoreAgent:
team_config: Dict[str, Any],
session_id: Optional[str] = None
) -> Generator[Dict[str, Any], None, None]:
- """Stream team execution with agent-by-agent updates."""
+ """Stream team execution using CoreAgent.run_team (Agno Team orchestration)."""
try:
- self.emit("thinking", "Initializing team...")
+ from core_agent import CoreAgent
members = team_config.get("agents", team_config.get("members", []))
mode = team_config.get("mode", "coordinate")
- self.emit("thinking", f"Team mode: {mode} with {len(members)} agents")
-
- # Process each agent (simplified - real implementation would use Agno teams)
- results = []
- for i, member_config in enumerate(members):
- agent_name = member_config.get("name", f"Agent {i+1}")
- self.emit("thinking", f"Agent '{agent_name}' is working...")
-
- # Run individual agent
- for chunk in self.run_streaming(query, member_config, session_id):
- if chunk["type"] == "token":
- yield {
- "type": "agent_token",
- "agent": agent_name,
- "content": chunk["content"]
- }
- elif chunk["type"] == "done":
- results.append({
- "agent": agent_name,
- "response": chunk["content"]
- })
- self.emit("agent_done", f"Agent '{agent_name}' completed")
-
- # Emit final aggregated result
- final_result = "\n\n".join([
- f"**{r['agent']}:**\n{r['response']}"
- for r in results
- ])
- self.emit("done", final_result, {"agents": len(results)})
- yield {"type": "done", "content": final_result}
+ self.emit("thinking", f"Initializing team ({mode} mode, {len(members)} agents)...")
+
+ core = CoreAgent(api_keys=self.api_keys, user_id=self.user_id)
+
+ self.emit("thinking", "Running team via Agno Team orchestration...")
+
+ # run_team returns an Agno TeamRunOutput object (not a dict).
+ # Use get_response_content() to safely extract text — same as main.py does.
+ team_response = core.run_team(query, team_config, session_id)
+ content = core.get_response_content(team_response)
+
+ if content:
+ # Chunk the response for smoother streaming UI
+ chunk_size = 50
+ for i in range(0, len(content), chunk_size):
+ piece = content[i:i + chunk_size]
+ self.emit("token", piece)
+ yield {"type": "token", "content": piece}
+
+ self.emit("done", content, {"agents": len(members)})
+ yield {"type": "done", "content": content}
+ else:
+ self.emit("done", "", {"agents": len(members)})
+ yield {"type": "done", "content": ""}
except Exception as e:
self.emit("error", str(e))
@@ -252,7 +261,7 @@ def main(args=None):
chunks = []
def collect_callback(chunk_type: str, content: str, metadata: Optional[Dict] = None):
- """Collect chunks and print as JSON lines"""
+ """Collect chunks and print with prefixes Rust execute_with_stream_callback expects."""
nonlocal full_response
chunk = {
"stream_id": stream_id,
@@ -260,11 +269,27 @@ def main(args=None):
"content": content,
"metadata": metadata
}
- # Print as JSON line for real-time capture
- print(f"STREAM:{json.dumps(chunk)}", flush=True)
chunks.append(chunk)
+ # Escape backslashes first, then newlines so each printed line is one
+ # logical chunk. Rust unescapes \n -> newline after stripping prefix.
+ safe = content.replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "")
if chunk_type in ["token", "agent_token"]:
full_response += content
+ # Rust recognises TOKEN: prefix -> "token" chunk type
+ print(f"TOKEN:{safe}", flush=True)
+ elif chunk_type == "thinking":
+ print(f"THINKING:{safe}", flush=True)
+ elif chunk_type == "tool_call":
+ print(f"TOOL:{safe}", flush=True)
+ elif chunk_type == "tool_result":
+ print(f"TOOL_RESULT:{safe}", flush=True)
+ elif chunk_type in ["done", "agent_done"]:
+ print(f"DONE:{safe}", flush=True)
+ elif chunk_type == "error":
+ print(f"ERROR:{safe}", flush=True)
+ else:
+ # Fallback: emit as token so Rust forwards it
+ print(f"TOKEN:{safe}", flush=True)
agent = StreamingCoreAgent(
api_keys=api_keys,
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/execution_planner.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/execution_planner.py
index 13d02e18f..1cb84a4b0 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/execution_planner.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/execution_planner.py
@@ -570,6 +570,149 @@ class ExecutionPlanner:
return builder.build()
+# =========================================================================
+# Dynamic LLM-based Plan Generation
+# =========================================================================
+
+_PLAN_GENERATION_SYSTEM_PROMPT = """You are an expert financial analyst AI that creates structured execution plans.
+Given a user's analysis request, generate a step-by-step execution plan as a JSON object.
+
+The plan must follow this exact JSON schema:
+{
+ "name": "Human-readable plan title",
+ "description": "Brief description of what this plan does",
+ "steps": [
+ {
+ "id": "step_1",
+ "name": "Step Name",
+ "step_type": "agent",
+ "query": "The specific prompt/query this step will execute",
+ "tools": ["yfinance", "duckduckgo"],
+ "dependencies": [],
+ "reasoning": false
+ }
+ ]
+}
+
+Rules:
+- step_type must be one of: agent, tool, checkpoint
+- tools can include: yfinance, duckduckgo, calculator, edgar, fred, worldbank
+- dependencies is a list of step IDs that must complete before this step
+- Set reasoning=true for analysis/synthesis steps that require deep thinking
+- Keep steps focused — each step should do one clear thing
+- Use parallel steps (empty dependencies) for independent data fetching
+- Final steps should synthesize earlier results
+- Return ONLY valid JSON, no markdown fences, no extra text"""
+
+
+def generate_dynamic_plan(query: str, api_keys: Dict[str, str] = None) -> Dict[str, Any]:
+ """
+ Use an LLM to dynamically generate an execution plan from a natural language query.
+ Returns an ExecutionPlan dict ready for display and execution.
+ """
+ import time
+ api_keys = api_keys or {}
+
+ try:
+ from finagent_core.core_agent import CoreAgent
+
+ agent = CoreAgent(api_keys=api_keys)
+
+ # Build a minimal model config preferring fast/cheap models
+ config = {
+ "instructions": _PLAN_GENERATION_SYSTEM_PROMPT,
+ "markdown": False,
+ "reasoning": False,
+ }
+
+ prompt = (
+ f"Create an execution plan for the following financial analysis request:\n\n"
+ f"{query}\n\n"
+ f"Return ONLY the JSON plan object, no extra text."
+ )
+
+ response = agent.run(prompt, config)
+ raw = agent.get_response_content(response)
+
+ # Strip any accidental markdown fences
+ raw = raw.strip()
+ if raw.startswith("```"):
+ raw = raw.split("```", 2)[1]
+ if raw.startswith("json"):
+ raw = raw[4:]
+ raw = raw.rsplit("```", 1)[0].strip()
+
+ plan_spec = json.loads(raw)
+
+ # Build ExecutionPlan from LLM output
+ plan_id = f"dynamic_{int(time.time())}"
+ builder = PlanBuilder(
+ plan_id=plan_id,
+ name=plan_spec.get("name", "Custom Analysis Plan"),
+ description=plan_spec.get("description", query),
+ )
+
+ # First pass: add all steps, collect id mapping
+ step_id_map: Dict[str, str] = {}
+ for i, s in enumerate(plan_spec.get("steps", []), start=1):
+ logical_id = s.get("id", f"step_{i}")
+ tools = s.get("tools", [])
+ agent_cfg: Dict[str, Any] = {}
+ if tools:
+ agent_cfg["tools"] = tools
+ if s.get("reasoning"):
+ agent_cfg["reasoning"] = True
+
+ # Resolve dependencies to builder step IDs
+ deps = [step_id_map[d] for d in s.get("dependencies", []) if d in step_id_map]
+
+ step_type = s.get("step_type", "agent")
+ if step_type == "checkpoint":
+ real_id = builder.add_checkpoint(
+ name=s.get("name", f"Step {i}"),
+ dependencies=deps,
+ )
+ else:
+ real_id = builder.add_agent_step(
+ name=s.get("name", f"Step {i}"),
+ query=s.get("query", ""),
+ agent_config=agent_cfg,
+ dependencies=deps,
+ )
+
+ step_id_map[logical_id] = real_id
+
+ plan = builder.build()
+ return {"success": True, "plan": plan.to_dict(), "generated_by": "llm"}
+
+ except json.JSONDecodeError as e:
+ logger.warning(f"LLM returned invalid JSON for plan generation: {e}. Falling back to template.")
+ return _fallback_plan_from_query(query)
+ except Exception as e:
+ logger.warning(f"Dynamic plan generation failed: {e}. Falling back to template.")
+ return _fallback_plan_from_query(query)
+
+
+def _fallback_plan_from_query(query: str) -> Dict[str, Any]:
+ """Fallback: derive a reasonable plan from keywords in the query."""
+ import time
+ query_lower = query.lower()
+
+ # Detect symbol — first uppercase word-like token
+ import re
+ symbol_match = re.search(r'\b([A-Z]{1,5}(?:\.[A-Z]{1,2})?)\b', query)
+ symbol = symbol_match.group(1) if symbol_match else "AAPL"
+
+ if any(w in query_lower for w in ["portfolio", "rebalance", "holdings"]):
+ plan = ExecutionPlanner.portfolio_rebalance_plan(symbol)
+ else:
+ plan = ExecutionPlanner.stock_analysis_plan(symbol)
+
+ result = plan.to_dict()
+ result["id"] = f"fallback_{int(time.time())}"
+ return {"success": True, "plan": result, "generated_by": "fallback"}
+
+
# Entry points for Tauri commands
def create_stock_analysis_plan(symbol: str) -> Dict[str, Any]:
"""Create a stock analysis plan"""
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 10fa397ad..96dac8989 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
@@ -32,7 +32,7 @@ if parent_dir not in sys.path:
sys.path.insert(0, parent_dir)
# Timeout for discovery operations (seconds)
-DISCOVERY_TIMEOUT = 4.0
+DISCOVERY_TIMEOUT = 30.0
def stream_print(chunk_type: str, content: str):
@@ -40,6 +40,36 @@ def stream_print(chunk_type: str, content: str):
print(f"{chunk_type.upper()}: {content}", flush=True)
+def _extract_workflow_response(result: Any) -> str:
+ """Extract a human-readable string from a workflow result.
+
+ Workflow.run() can return:
+ - An Agno RunResponse object (has .content attribute)
+ - A dict (from SimpleWorkflowExecutor)
+ - A plain string
+ """
+ import json as _json
+ if result is None:
+ return "Workflow completed with no output."
+ # Agno RunResponse object
+ if hasattr(result, "content"):
+ content = result.content
+ if content:
+ return str(content)
+ # SimpleWorkflowExecutor dict: {"success": True, "results": [...], "context": {...}}
+ if isinstance(result, dict):
+ # Collect all step results into a readable string
+ parts = []
+ for step_result in result.get("results", []):
+ if step_result is not None:
+ parts.append(str(step_result))
+ if parts:
+ return "\n\n".join(parts)
+ # Fallback: render the whole dict
+ return _json.dumps(result, indent=2, default=str)
+ return str(result)
+
+
def _setup_agent_modules(agent, config: Dict[str, Any], params: Dict[str, Any]):
"""
Setup ALL optional CoreAgent modules from config/params.
@@ -362,6 +392,13 @@ def dispatch_action(
return {"success": False, "error": "Missing 'plan'"}
return execute_plan(plan_dict, api_keys)
+ if action == "generate_dynamic_plan":
+ from finagent_core.execution_planner import generate_dynamic_plan
+ query = params.get("query")
+ if not query:
+ return {"success": False, "error": "Missing 'query'"}
+ return generate_dynamic_plan(query, api_keys)
+
# =========================================================================
# Paper Trading Bridge
# =========================================================================
@@ -516,7 +553,8 @@ def dispatch_action(
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)}
+ response_text = _extract_workflow_response(result)
+ return {"success": True, "symbol": symbol, "response": response_text, "result": result if isinstance(result, dict) else None}
if action == "portfolio_rebal":
from finagent_core.core_agent import CoreAgent
@@ -524,7 +562,8 @@ def dispatch_action(
_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)}
+ response_text = _extract_workflow_response(result)
+ return {"success": True, "response": response_text, "result": result if isinstance(result, dict) else None}
if action == "risk_assessment":
from finagent_core.core_agent import CoreAgent
@@ -532,7 +571,8 @@ def dispatch_action(
_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)}
+ response_text = _extract_workflow_response(result)
+ return {"success": True, "response": response_text, "result": result if isinstance(result, dict) else None}
# =========================================================================
# Agent Memory (via CoreAgent module)
@@ -785,9 +825,14 @@ def dispatch_action_streaming(
core_agent.end_trace()
stream_print("done", "completed")
+ # response may be a generator (streaming) or a RunResponse/str (fallback)
resp_content = ""
- if response:
- resp_content = core_agent.get_response_content(response) if hasattr(response, 'content') else str(response)
+ if response is not None:
+ if hasattr(response, 'content'):
+ resp_content = core_agent.get_response_content(response)
+ elif not hasattr(response, '__iter__') or isinstance(response, str):
+ resp_content = str(response)
+ # generators are already consumed above — leave resp_content as ""
return {"success": True, "response": resp_content}
except Exception as e:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/evaluation_module.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/evaluation_module.py
index 60934f8b0..9647b7e75 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/evaluation_module.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/evaluation_module.py
@@ -298,7 +298,7 @@ class AgentJudgeEvaluator:
def __init__(
self,
- judge_model: str = "gpt-4-turbo",
+ judge_model: Optional[str] = None,
criteria: List[str] = None
):
"""
@@ -408,7 +408,7 @@ class EvaluationModule:
self.judge_eval: Optional[AgentJudgeEvaluator] = None
self._results: List[EvaluationResult] = []
- def enable_agent_judge(self, model: str = "gpt-4-turbo") -> "EvaluationModule":
+ def enable_agent_judge(self, model: Optional[str] = None) -> "EvaluationModule":
"""Enable agent-as-judge evaluation."""
self.judge_eval = AgentJudgeEvaluator(judge_model=model)
return self
@@ -502,7 +502,7 @@ class EvaluationModule:
if config.get("agent_judge"):
module.enable_agent_judge(
- model=config["agent_judge"].get("model", "gpt-4-turbo")
+ model=config["agent_judge"].get("model")
)
return module
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/hooks_module.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/hooks_module.py
index dc92642f7..64e29c72e 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/hooks_module.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/hooks_module.py
@@ -399,7 +399,7 @@ class CostTrackingHook(Hook):
input_tokens = usage.get("input_tokens", 0)
output_tokens = usage.get("output_tokens", 0)
- model = context.get("model", "gpt-3.5-turbo")
+ model = context.get("model") or context.get("provider", "unknown")
# Calculate cost
cost = self._calculate_cost(model, input_tokens, output_tokens)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/knowledge_module.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/knowledge_module.py
index 2c93cc516..e2bb05cc8 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/knowledge_module.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/knowledge_module.py
@@ -51,7 +51,7 @@ class KnowledgeModule:
def __init__(
self,
name: str = "Knowledge Base",
- embedder_provider: str = "openai",
+ embedder_provider: Optional[str] = None,
embedder_model: Optional[str] = None,
vectordb_type: str = "lancedb",
vectordb_config: Optional[Dict[str, Any]] = None,
@@ -77,6 +77,14 @@ class KnowledgeModule:
**kwargs: Additional configuration
"""
self.name = name
+ # Resolve embedder provider from api_keys if not explicitly set
+ if not embedder_provider:
+ _keys = api_keys or {}
+ _preferred = ["fincept", "ollama", "anthropic", "google", "groq", "deepseek", "openai"]
+ embedder_provider = next(
+ (p for p in _preferred if _keys.get(p) or _keys.get(f"{p.upper()}_API_KEY")),
+ "openai"
+ )
self.embedder_provider = embedder_provider
self.embedder_model = embedder_model
self.vectordb_type = vectordb_type
@@ -328,7 +336,7 @@ class KnowledgeModule:
"""
module = cls(
name=config.get("name", "Knowledge Base"),
- embedder_provider=config.get("embedder", {}).get("provider", "openai"),
+ embedder_provider=config.get("embedder", {}).get("provider"),
embedder_model=config.get("embedder", {}).get("model"),
vectordb_type=config.get("vectordb", {}).get("type", "lancedb"),
vectordb_config=config.get("vectordb", {}),
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/session_module.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/session_module.py
index 0258f2399..9bb8aa0aa 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/session_module.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/session_module.py
@@ -477,13 +477,20 @@ class SessionModule:
try:
from agno.session import SessionSummaryManager
- # Create model if not provided
+ # Create model if not provided — resolve from api_keys rather than hardcoding openai
if model is None and api_keys:
- from agno.models.openai import OpenAIChat
- model = OpenAIChat(
- id="gpt-3.5-turbo",
- api_key=api_keys.get("OPENAI_API_KEY")
- )
+ try:
+ from finagent_core.registries import ModelsRegistry
+ preferred = ["fincept", "ollama", "anthropic", "google", "groq",
+ "deepseek", "openai", "openrouter"]
+ provider = next(
+ (p for p in preferred if api_keys.get(p) or api_keys.get(f"{p.upper()}_API_KEY")),
+ None
+ )
+ if provider:
+ model = ModelsRegistry.create_model(provider=provider, api_keys=api_keys)
+ except Exception:
+ pass
if model:
manager = SessionSummaryManager(model=model)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/workflow_module.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/workflow_module.py
index 24f1096ea..737e33c0d 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/workflow_module.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/modules/workflow_module.py
@@ -1,899 +1,558 @@
"""
-Workflow Module - Complex task orchestration
-
-Provides:
-- Sequential and parallel step execution
-- Conditional branching
-- Loop support
-- Step dependencies
-- Agent workflow integration
+Workflow Module - Complex task orchestration using Agno's native subclass pattern.
+
+Each financial workflow is a proper Agno Workflow subclass with:
+- WorkflowAgent for LLM execution
+- Step / Parallel / Loop / Condition / Router primitives
+- StepInput / StepOutput typed I/O
+- Session state + streaming support
"""
-from typing import Dict, Any, Optional, List, Callable, Union
+from __future__ import annotations
+
+from datetime import date
+from typing import Any, Dict, Iterator, List, Optional, Callable, Union
import logging
logger = logging.getLogger(__name__)
-
-class WorkflowModule:
+# ─── Helpers ──────────────────────────────────────────────────────────────────
+
+def _today() -> str:
+ return date.today().strftime("%B %d, %Y")
+
+
+def _resolve_provider(api_keys: Dict[str, str]) -> str:
+ """Pick first configured provider from api_keys."""
+ preferred = ["fincept", "ollama", "anthropic", "google", "groq",
+ "deepseek", "openai", "openrouter"]
+ for p in preferred:
+ if api_keys.get(p) or api_keys.get(f"{p.upper()}_API_KEY"):
+ return p
+ for k, v in api_keys.items():
+ if k.endswith("_API_KEY") and v:
+ return k[:-8].lower()
+ return "openai"
+
+
+def _make_model(api_keys: Dict[str, str], model_config: Optional[Dict] = None):
+ """Create an agno Model from api_keys + optional model_config dict."""
+ from finagent_core.registries import ModelsRegistry
+ cfg = model_config or {}
+ provider = cfg.get("provider") or _resolve_provider(api_keys)
+ return ModelsRegistry.create_model(
+ provider=provider,
+ model_id=cfg.get("model_id"),
+ api_keys=api_keys,
+ temperature=cfg.get("temperature"),
+ max_tokens=cfg.get("max_tokens"),
+ )
+
+
+def _load_workflow_tools(api_keys: Dict[str, str],
+ terminal_endpoint: Optional[str] = None,
+ terminal_tool_defs: Optional[List] = None) -> List[Any]:
"""
- Workflow orchestration for complex multi-step tasks.
-
- Supports:
- - Sequential steps
- - Parallel execution
- - Conditional branching
- - Loops
- - Agent integration
+ Load tools for workflow agents:
+ - yfinance (real-time market data, prices, financials)
+ - duckduckgo (news and web search)
+ - TerminalToolkit (internal MCP: get_quote, portfolio, etc.)
+ Falls back gracefully if any tool fails to load.
"""
+ tools = []
+
+ # Core financial data tools via ToolsRegistry
+ try:
+ from finagent_core.registries import ToolsRegistry
+ financial_tools = ToolsRegistry.get_tools(
+ ["yfinance", "duckduckgo"],
+ api_keys=api_keys
+ )
+ tools.extend(financial_tools)
+ logger.debug(f"WorkflowTools: loaded {len(financial_tools)} financial tools")
+ except Exception as e:
+ logger.warning(f"WorkflowTools: ToolsRegistry load failed: {e}")
- def __init__(
- self,
- name: str = "Workflow",
- description: Optional[str] = None,
- **kwargs
- ):
- """
- Initialize workflow module.
-
- Args:
- name: Workflow name
- description: Workflow description
- **kwargs: Additional configuration
- """
- self.name = name
- self.description = description
- self.config = kwargs
-
- self._steps: List[Dict[str, Any]] = []
- self._workflow = None
-
- def add_step(
- self,
- name: str,
- agent: Optional[Any] = None,
- function: Optional[Callable] = None,
- prompt: Optional[str] = None,
- **kwargs
- ) -> "WorkflowModule":
- """
- Add a step to the workflow.
-
- Args:
- name: Step name
- agent: Agno Agent for this step
- function: Python function to execute
- prompt: Prompt template for agent
- **kwargs: Additional step configuration
-
- Returns:
- self for chaining
- """
- step = {
- "type": "step",
- "name": name,
- "agent": agent,
- "function": function,
- "prompt": prompt,
- **kwargs
- }
- self._steps.append(step)
- return self
-
- def add_parallel(
- self,
- name: str,
- steps: List[Dict[str, Any]],
- **kwargs
- ) -> "WorkflowModule":
- """
- Add parallel execution steps.
-
- Args:
- name: Parallel group name
- steps: List of steps to run in parallel
- **kwargs: Additional configuration
-
- Returns:
- self for chaining
- """
- parallel_step = {
- "type": "parallel",
- "name": name,
- "steps": steps,
- **kwargs
- }
- self._steps.append(parallel_step)
- return self
-
- def add_condition(
- self,
- name: str,
- condition: Callable[[Any], bool],
- if_true: Dict[str, Any],
- if_false: Optional[Dict[str, Any]] = None,
- **kwargs
- ) -> "WorkflowModule":
- """
- Add conditional branching.
-
- Args:
- name: Condition name
- condition: Function that returns True/False
- if_true: Step to execute if condition is True
- if_false: Step to execute if condition is False
- **kwargs: Additional configuration
-
- Returns:
- self for chaining
- """
- condition_step = {
- "type": "condition",
- "name": name,
- "condition": condition,
- "if_true": if_true,
- "if_false": if_false,
- **kwargs
- }
- self._steps.append(condition_step)
- return self
-
- def add_loop(
- self,
- name: str,
- steps: List[Dict[str, Any]],
- condition: Optional[Callable[[Any], bool]] = None,
- max_iterations: int = 10,
- **kwargs
- ) -> "WorkflowModule":
- """
- Add loop execution.
-
- Args:
- name: Loop name
- steps: Steps to repeat
- condition: Continue condition (loop while True)
- max_iterations: Maximum iterations
- **kwargs: Additional configuration
-
- Returns:
- self for chaining
- """
- loop_step = {
- "type": "loop",
- "name": name,
- "steps": steps,
- "condition": condition,
- "max_iterations": max_iterations,
- **kwargs
- }
- self._steps.append(loop_step)
- return self
-
- def add_router(
- self,
- name: str,
- routes: Dict[str, Dict[str, Any]],
- router_function: Callable[[Any], str],
- **kwargs
- ) -> "WorkflowModule":
- """
- Add router step for dynamic routing.
-
- Args:
- name: Router name
- routes: Dict of route_key -> step configuration
- router_function: Function that returns route key
- **kwargs: Additional configuration
-
- Returns:
- self for chaining
- """
- router_step = {
- "type": "router",
- "name": name,
- "routes": routes,
- "router_function": router_function,
- **kwargs
- }
- self._steps.append(router_step)
- return self
-
- def build(self) -> Any:
- """
- Build the Agno Workflow.
-
- Returns:
- Agno Workflow instance
- """
- if self._workflow:
- return self._workflow
-
- if not self._steps:
- raise ValueError("Cannot build workflow without steps")
-
+ # Terminal MCP bridge tools (get_quote, portfolio, navigation, etc.)
+ if terminal_endpoint and terminal_tool_defs:
try:
- from agno.workflow import Workflow, Step, Parallel, Condition, Loop, Router
-
- # Convert steps to Agno format
- agno_steps = self._convert_steps_to_agno(self._steps)
-
- self._workflow = Workflow(
- name=self.name,
- description=self.description,
- steps=agno_steps
+ from finagent_core.tools.terminal_toolkit import TerminalToolkit
+ toolkit = TerminalToolkit(
+ endpoint=terminal_endpoint,
+ tool_definitions=terminal_tool_defs,
)
-
- logger.debug(f"Built workflow '{self.name}' with {len(self._steps)} steps")
- return self._workflow
-
- except ImportError as e:
- logger.warning(f"Agno Workflow not available: {e}")
- # Return a simple executor fallback
- return self._create_fallback_executor()
+ tools.extend(toolkit.get_tools())
+ logger.debug(f"WorkflowTools: loaded {len(toolkit.functions)} terminal MCP tools")
except Exception as e:
- raise RuntimeError(f"Failed to build workflow: {e}")
-
- def _convert_steps_to_agno(self, steps: List[Dict[str, Any]]) -> List[Any]:
- """Convert internal step format to Agno steps"""
- from agno.workflow import Step, Parallel, Condition, Loop, Router
-
- agno_steps = []
-
- for step_config in steps:
- step_type = step_config.get("type", "step")
-
- if step_type == "step":
- agno_step = self._create_step(step_config)
- elif step_type == "parallel":
- agno_step = self._create_parallel(step_config)
- elif step_type == "condition":
- agno_step = self._create_condition(step_config)
- elif step_type == "loop":
- agno_step = self._create_loop(step_config)
- elif step_type == "router":
- agno_step = self._create_router(step_config)
- else:
- logger.warning(f"Unknown step type: {step_type}")
- continue
-
- if agno_step:
- agno_steps.append(agno_step)
-
- return agno_steps
-
- def _create_step(self, config: Dict[str, Any]) -> Any:
- """Create an Agno Step"""
- from agno.workflow import Step
+ logger.warning(f"WorkflowTools: TerminalToolkit load failed: {e}")
- step_kwargs = {"name": config["name"]}
+ return tools
- if config.get("agent"):
- step_kwargs["agent"] = config["agent"]
- if config.get("function"):
- step_kwargs["function"] = config["function"]
- if config.get("prompt"):
- step_kwargs["prompt"] = config["prompt"]
- return Step(**step_kwargs)
+def _make_workflow_agent(api_keys: Dict[str, str],
+ instructions: str,
+ model_config: Optional[Dict] = None,
+ tools: Optional[List] = None) -> Any:
+ """
+ Create an agent for workflow step execution.
+ Uses Agent (supports tools) when tools are provided,
+ falls back to WorkflowAgent when no tools are needed.
+ """
+ model = _make_model(api_keys, model_config)
+ if tools:
+ from agno.agent import Agent
+ return Agent(model=model, instructions=instructions, tools=tools, markdown=False)
+ else:
+ from agno.workflow import WorkflowAgent
+ return WorkflowAgent(model=model, instructions=instructions)
- def _create_parallel(self, config: Dict[str, Any]) -> Any:
- """Create an Agno Parallel step"""
- from agno.workflow import Parallel
- inner_steps = self._convert_steps_to_agno(config.get("steps", []))
- return Parallel(name=config["name"], steps=inner_steps)
+def _step_output(content: Any) -> Any:
+ from agno.workflow.types import StepOutput
+ return StepOutput(content=content)
- def _create_condition(self, config: Dict[str, Any]) -> Any:
- """Create an Agno Condition step"""
- from agno.workflow import Condition
- return Condition(
- name=config["name"],
- condition=config["condition"],
- if_true=self._create_step(config["if_true"]) if config.get("if_true") else None,
- if_false=self._create_step(config["if_false"]) if config.get("if_false") else None,
- )
+def _extract_content(step_input: Any) -> Any:
+ """Extract the input payload from a StepInput."""
+ return getattr(step_input, "input", None) or getattr(step_input, "previous_step_content", None) or {}
- def _create_loop(self, config: Dict[str, Any]) -> Any:
- """Create an Agno Loop step"""
- from agno.workflow import Loop
- inner_steps = self._convert_steps_to_agno(config.get("steps", []))
- return Loop(
- name=config["name"],
- steps=inner_steps,
- condition=config.get("condition"),
- max_iterations=config.get("max_iterations", 10),
- )
+# ─── Stock Analysis Workflow ──────────────────────────────────────────────────
- def _create_router(self, config: Dict[str, Any]) -> Any:
- """Create an Agno Router step"""
- from agno.workflow import Router
+class StockAnalysisWorkflow:
+ """
+ Multi-step stock analysis pipeline.
- routes = {}
- for key, step_config in config.get("routes", {}).items():
- routes[key] = self._create_step(step_config)
+ Steps:
+ 1. Fetch market data
+ 2. Technical + Fundamental analysis (Parallel)
+ 3. Generate recommendation
+ 4. Create report
+ """
- return Router(
- name=config["name"],
- routes=routes,
- router=config["router_function"],
+ def __init__(self, api_keys: Dict[str, str], model_config: Optional[Dict] = None,
+ tools: Optional[List] = None):
+ self.api_keys = api_keys
+ self._tools = tools
+ self.model_config = model_config or {}
+
+ def run(self, symbol: str) -> Dict[str, Any]:
+ from agno.workflow import Workflow, Step, Parallel
+ from agno.workflow.types import StepOutput
+
+ today = _today()
+ agent = _make_workflow_agent(
+ self.api_keys,
+ f"You are a professional financial analyst. Today is {today}. Always use today's date in reports.",
+ self.model_config,
+ tools=self._tools,
)
- def _create_fallback_executor(self) -> "SimpleWorkflowExecutor":
- """Create a simple fallback executor if Agno Workflow is not available"""
- return SimpleWorkflowExecutor(self._steps)
-
- def run(self, input_data: Optional[Dict[str, Any]] = None, **kwargs) -> Any:
- """
- Run the workflow.
-
- Args:
- input_data: Initial input data
- **kwargs: Additional arguments
-
- Returns:
- Workflow result
- """
- workflow = self.build()
+ def fetch_step(step_input):
+ inp = _extract_content(step_input)
+ sym = inp.get("symbol", symbol) if isinstance(inp, dict) else symbol
+ response = agent.run(
+ f"Today is {today}. Fetch and summarize current market data for {sym} "
+ f"including price, volume, recent news, and key metrics."
+ )
+ return _step_output(getattr(response, "content", str(response)))
- run_kwargs = {}
- if input_data:
- run_kwargs["input"] = input_data
- run_kwargs.update(kwargs)
+ def tech_step(step_input):
+ prev = getattr(step_input, "previous_step_content", "")
+ response = agent.run(
+ f"Today is {today}. Perform technical analysis for {symbol}. "
+ f"Market data context: {prev}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
- return workflow.run(**run_kwargs)
+ def fund_step(step_input):
+ prev = getattr(step_input, "previous_step_content", "")
+ response = agent.run(
+ f"Today is {today}. Perform fundamental analysis for {symbol} "
+ f"including valuation, financials, and competitive position. Context: {prev}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
- async def arun(self, input_data: Optional[Dict[str, Any]] = None, **kwargs) -> Any:
- """
- Run the workflow asynchronously.
+ def rec_step(step_input):
+ prev = getattr(step_input, "previous_step_content", "")
+ response = agent.run(
+ f"Today is {today}. Based on the analysis, provide a clear "
+ f"buy/sell/hold recommendation for {symbol}. Analysis: {prev}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
+
+ def report_step(step_input):
+ prev = getattr(step_input, "previous_step_content", "")
+ response = agent.run(
+ f"Today is {today}. Generate a comprehensive investment report for {symbol}. "
+ f"Report Date MUST be {today}. "
+ f"Include executive summary, business overview, financials, risks, and recommendation. "
+ f"Analysis: {prev}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
- Args:
- input_data: Initial input data
- **kwargs: Additional arguments
+ workflow = Workflow(
+ name=f"Stock Analysis: {symbol}",
+ steps=[
+ Step(name="fetch_market_data", executor=fetch_step),
+ Parallel(
+ Step(name="technical_analysis", executor=tech_step),
+ Step(name="fundamental_analysis", executor=fund_step),
+ ),
+ Step(name="generate_recommendation", executor=rec_step),
+ Step(name="create_report", executor=report_step),
+ ]
+ )
- Returns:
- Workflow result
- """
- workflow = self.build()
+ result = workflow.run(input={"symbol": symbol})
+ return {"success": True, "response": getattr(result, "content", str(result))}
- run_kwargs = {}
- if input_data:
- run_kwargs["input"] = input_data
- run_kwargs.update(kwargs)
- return await workflow.arun(**run_kwargs)
+# ─── Portfolio Rebalancing Workflow ───────────────────────────────────────────
- def get_steps(self) -> List[Dict[str, Any]]:
- """Get list of workflow steps"""
- return self._steps.copy()
+class PortfolioRebalancingWorkflow:
+ """Portfolio rebalancing using Condition for drift check."""
- @classmethod
- def from_config(cls, config: Dict[str, Any]) -> "WorkflowModule":
- """
- Create WorkflowModule from configuration.
+ def __init__(self, api_keys: Dict[str, str], model_config: Optional[Dict] = None,
+ tools: Optional[List] = None):
+ self.api_keys = api_keys
+ self.model_config = model_config or {}
+ self._tools = tools
- Args:
- config: Workflow configuration
+ def run(self, portfolio_data: Dict[str, Any]) -> Dict[str, Any]:
+ from agno.workflow import Workflow, Step, Condition
- Returns:
- WorkflowModule instance
- """
- module = cls(
- name=config.get("name", "Workflow"),
- description=config.get("description"),
+ today = _today()
+ agent = _make_workflow_agent(
+ self.api_keys,
+ f"You are a portfolio manager. Today is {today}.",
+ self.model_config,
+ tools=self._tools,
)
- for step_config in config.get("steps", []):
- step_type = step_config.get("type", "step")
-
- if step_type == "step":
- module.add_step(**step_config)
- elif step_type == "parallel":
- module.add_parallel(**step_config)
- elif step_type == "condition":
- module.add_condition(**step_config)
- elif step_type == "loop":
- module.add_loop(**step_config)
- elif step_type == "router":
- module.add_router(**step_config)
-
- return module
-
-
-class SimpleWorkflowExecutor:
- """
- Simple fallback workflow executor when Agno Workflow is not available.
- Executes steps sequentially.
- """
+ def analyze_step(step_input):
+ response = agent.run(
+ f"Today is {today}. Analyze this portfolio and calculate allocation drift: "
+ f"{portfolio_data}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
- def __init__(self, steps: List[Dict[str, Any]]):
- self.steps = steps
+ def rebalance_step(step_input):
+ prev = getattr(step_input, "previous_step_content", "")
+ response = agent.run(
+ f"Today is {today}. Calculate optimal rebalancing trades. Analysis: {prev}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
- def run(self, input: Optional[Dict[str, Any]] = None, **kwargs) -> Dict[str, Any]:
- """Execute workflow steps sequentially"""
- context = input or {}
- results = []
+ def no_action_step(step_input):
+ return _step_output("Portfolio is within tolerance. No rebalancing needed.")
- for step in self.steps:
- step_type = step.get("type", "step")
-
- if step_type == "step":
- result = self._execute_step(step, context)
- results.append(result)
- context["last_result"] = result
- elif step_type == "parallel":
- # Execute sequentially as fallback
- for inner_step in step.get("steps", []):
- result = self._execute_step(inner_step, context)
- results.append(result)
- # Add other step types as needed
-
- return {
- "success": True,
- "results": results,
- "context": context
- }
-
- def _execute_step(self, step: Dict[str, Any], context: Dict[str, Any]) -> Any:
- """Execute a single step"""
- if step.get("function"):
- return step["function"](context)
- elif step.get("agent"):
- prompt = step.get("prompt", "")
- return step["agent"].run(prompt.format(**context))
- return None
-
- async def arun(self, input: Optional[Dict[str, Any]] = None, **kwargs) -> Dict[str, Any]:
- """Async execution (falls back to sync)"""
- return self.run(input=input, **kwargs)
+ def orders_step(step_input):
+ prev = getattr(step_input, "previous_step_content", "")
+ response = agent.run(
+ f"Today is {today}. Generate specific trade orders for rebalancing. Plan: {prev}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
+ def needs_rebal(step_input):
+ prev = str(getattr(step_input, "previous_step_content", ""))
+ keywords = ["drift", "rebalance", "exceed", "above", "below", "overweight", "underweight"]
+ return any(k in prev.lower() for k in keywords)
-class WorkflowBuilder:
- """
- Fluent builder for creating workflows.
-
- Example:
- workflow = (WorkflowBuilder("Data Pipeline")
- .add_step("fetch", function=fetch_data)
- .add_step("process", agent=processor_agent)
- .add_step("save", function=save_results)
- .build())
- """
+ workflow = Workflow(
+ name="Portfolio Rebalancing",
+ steps=[
+ Step(name="analyze_portfolio", executor=analyze_step),
+ Condition(
+ needs_rebal,
+ steps=[Step(name="rebalance_plan", executor=rebalance_step)],
+ name="check_drift",
+ ),
+ Step(name="generate_orders", executor=orders_step),
+ ]
+ )
- def __init__(self, name: str):
- """Initialize workflow builder"""
- self._module = WorkflowModule(name=name)
+ result = workflow.run(input=portfolio_data)
+ return {"success": True, "response": getattr(result, "content", str(result))}
- def with_description(self, description: str) -> "WorkflowBuilder":
- """Set workflow description"""
- self._module.description = description
- return self
- def add_step(
- self,
- name: str,
- agent: Optional[Any] = None,
- function: Optional[Callable] = None,
- prompt: Optional[str] = None,
- **kwargs
- ) -> "WorkflowBuilder":
- """Add a step"""
- self._module.add_step(name, agent=agent, function=function, prompt=prompt, **kwargs)
- return self
+# ─── Risk Assessment Workflow ─────────────────────────────────────────────────
- def add_parallel(self, name: str, steps: List[Dict[str, Any]]) -> "WorkflowBuilder":
- """Add parallel steps"""
- self._module.add_parallel(name, steps)
- return self
+class RiskAssessmentWorkflow:
+ """Risk assessment using Router to route to the right risk analysis."""
- def add_condition(
- self,
- name: str,
- condition: Callable,
- if_true: Dict,
- if_false: Optional[Dict] = None
- ) -> "WorkflowBuilder":
- """Add conditional branching"""
- self._module.add_condition(name, condition, if_true, if_false)
- return self
+ def __init__(self, api_keys: Dict[str, str], model_config: Optional[Dict] = None,
+ tools: Optional[List] = None):
+ self.api_keys = api_keys
+ self.model_config = model_config or {}
+ self._tools = tools
- def add_loop(
- self,
- name: str,
- steps: List[Dict],
- condition: Optional[Callable] = None,
- max_iterations: int = 10
- ) -> "WorkflowBuilder":
- """Add a loop"""
- self._module.add_loop(name, steps, condition, max_iterations)
- return self
+ def run(self, portfolio_data: Dict[str, Any]) -> Dict[str, Any]:
+ from agno.workflow import Workflow, Step, Router
- def build(self) -> Any:
- """Build and return the workflow"""
- return self._module.build()
+ today = _today()
+ agent = _make_workflow_agent(
+ self.api_keys,
+ f"You are a risk analyst. Today is {today}.",
+ self.model_config,
+ tools=self._tools,
+ )
- def get_module(self) -> WorkflowModule:
- """Get the underlying WorkflowModule"""
- return self._module
+ def identify_step(step_input):
+ response = agent.run(
+ f"Today is {today}. Identify the primary risk type (market/credit/liquidity/operational) "
+ f"for this portfolio: {portfolio_data}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
+ def market_risk_step(step_input):
+ prev = getattr(step_input, "previous_step_content", "")
+ response = agent.run(
+ f"Today is {today}. Perform market risk analysis (VaR, beta, volatility). Context: {prev}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
-class FinancialWorkflowTemplates:
- """
- Pre-built workflow templates for common financial tasks.
-
- Templates:
- - Stock analysis pipeline
- - Portfolio rebalancing
- - Risk assessment
- - Market screening
- - Report generation
- """
+ def credit_risk_step(step_input):
+ prev = getattr(step_input, "previous_step_content", "")
+ response = agent.run(
+ f"Today is {today}. Perform credit risk analysis. Context: {prev}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
- @staticmethod
- def stock_analysis_pipeline(
- fetch_agent: Any = None,
- analysis_agent: Any = None,
- report_agent: Any = None
- ) -> WorkflowModule:
- """
- Create stock analysis workflow.
-
- Steps:
- 1. Fetch market data
- 2. Perform technical analysis
- 3. Perform fundamental analysis (parallel)
- 4. Generate recommendation
- 5. Create report
-
- Args:
- fetch_agent: Agent for fetching data
- analysis_agent: Agent for analysis
- report_agent: Agent for report generation
-
- Returns:
- Configured WorkflowModule
- """
- workflow = WorkflowModule(
- name="Stock Analysis Pipeline",
- description="Comprehensive stock analysis workflow"
- )
+ def liquidity_risk_step(step_input):
+ prev = getattr(step_input, "previous_step_content", "")
+ response = agent.run(
+ f"Today is {today}. Analyze liquidity risk (bid-ask, volume). Context: {prev}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
- # Step 1: Fetch data
- workflow.add_step(
- name="fetch_market_data",
- agent=fetch_agent,
- prompt="Fetch current market data for {symbol} including price, volume, and recent news"
- )
+ def general_risk_step(step_input):
+ prev = getattr(step_input, "previous_step_content", "")
+ response = agent.run(
+ f"Today is {today}. Perform general risk assessment. Context: {prev}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
- # Step 2: Parallel analysis
- workflow.add_parallel(
- name="analysis",
+ def report_step(step_input):
+ prev = getattr(step_input, "previous_step_content", "")
+ response = agent.run(
+ f"Today is {today}. Generate a comprehensive risk report. Report Date MUST be {today}. "
+ f"Analysis: {prev}"
+ )
+ return _step_output(getattr(response, "content", str(response)))
+
+ market_s = Step(name="market_risk", executor=market_risk_step)
+ credit_s = Step(name="credit_risk", executor=credit_risk_step)
+ liquid_s = Step(name="liquidity_risk", executor=liquidity_risk_step)
+ general_s = Step(name="general_risk", executor=general_risk_step)
+ choices = [market_s, credit_s, liquid_s, general_s]
+
+ def selector(step_input):
+ prev = str(getattr(step_input, "previous_step_content", "")).lower()
+ if "credit" in prev: return [credit_s]
+ if "liquidity" in prev: return [liquid_s]
+ if "general" in prev: return [general_s]
+ return [market_s]
+
+ workflow = Workflow(
+ name="Risk Assessment",
steps=[
- {
- "type": "step",
- "name": "technical_analysis",
- "agent": analysis_agent,
- "prompt": "Perform technical analysis on {symbol} using the market data: {last_result}"
- },
- {
- "type": "step",
- "name": "fundamental_analysis",
- "agent": analysis_agent,
- "prompt": "Perform fundamental analysis on {symbol} including valuation metrics"
- }
+ Step(name="identify_risk_type", executor=identify_step),
+ Router(selector, choices=choices, name="risk_router"),
+ Step(name="generate_risk_report", executor=report_step),
]
)
- # Step 3: Generate recommendation
- workflow.add_step(
- name="generate_recommendation",
- agent=analysis_agent,
- prompt="Based on the technical and fundamental analysis, provide a buy/sell/hold recommendation for {symbol}"
- )
-
- # Step 4: Create report
- workflow.add_step(
- name="create_report",
- agent=report_agent,
- prompt="Generate a comprehensive investment report for {symbol} summarizing all analysis and recommendations"
- )
-
- return workflow
-
- @staticmethod
- def portfolio_rebalancing(
- analysis_agent: Any = None,
- optimization_agent: Any = None,
- execution_agent: Any = None,
- risk_threshold: float = 0.05
- ) -> WorkflowModule:
- """
- Create portfolio rebalancing workflow.
-
- Steps:
- 1. Analyze current portfolio
- 2. Check if rebalancing needed (condition)
- 3. Calculate optimal allocation
- 4. Generate trade orders
- 5. Review and confirm
-
- Args:
- analysis_agent: Agent for portfolio analysis
- optimization_agent: Agent for optimization
- execution_agent: Agent for trade execution
- risk_threshold: Drift threshold for rebalancing
-
- Returns:
- Configured WorkflowModule
- """
- workflow = WorkflowModule(
- name="Portfolio Rebalancing",
- description="Automated portfolio rebalancing workflow"
- )
+ result = workflow.run(input=portfolio_data)
+ return {"success": True, "response": getattr(result, "content", str(result))}
- # Step 1: Analyze current portfolio
- workflow.add_step(
- name="analyze_portfolio",
- agent=analysis_agent,
- prompt="Analyze current portfolio holdings and calculate drift from target allocation"
- )
- # Step 2: Check if rebalancing needed
- def needs_rebalancing(context: Dict) -> bool:
- drift = context.get("max_drift", 0)
- return drift > risk_threshold
-
- workflow.add_condition(
- name="check_rebalancing_needed",
- condition=needs_rebalancing,
- if_true={
- "type": "step",
- "name": "calculate_optimal_allocation",
- "agent": optimization_agent,
- "prompt": "Calculate optimal trade orders to rebalance portfolio to target allocation"
- },
- if_false={
- "type": "step",
- "name": "no_action_needed",
- "function": lambda ctx: {"message": "Portfolio within tolerance, no rebalancing needed"}
- }
- )
+# ─── Backwards-compatible factory (used by core_agent.py) ────────────────────
- # Step 3: Generate trade orders
- workflow.add_step(
- name="generate_orders",
- agent=execution_agent,
- prompt="Generate specific trade orders based on the optimal allocation: {last_result}"
- )
-
- return workflow
+class FinancialWorkflowTemplates:
+ """Factory that returns workflow instances — keeps core_agent.py unchanged."""
@staticmethod
- def market_screening(
- screening_agent: Any = None,
- analysis_agent: Any = None,
- max_iterations: int = 5
- ) -> WorkflowModule:
- """
- Create market screening workflow with iterative refinement.
-
- Steps:
- 1. Initial broad screen
- 2. Apply filters (loop)
- 3. Deep analysis on top candidates
- 4. Rank and prioritize
-
- Args:
- screening_agent: Agent for screening
- analysis_agent: Agent for deep analysis
- max_iterations: Maximum screening iterations
-
- Returns:
- Configured WorkflowModule
- """
- workflow = WorkflowModule(
- name="Market Screening",
- description="Iterative market screening and analysis"
- )
-
- # Step 1: Initial screen
- workflow.add_step(
- name="initial_screen",
- agent=screening_agent,
- prompt="Screen the market for stocks matching criteria: {criteria}"
- )
+ def stock_analysis_pipeline(api_keys: Dict[str, str] = None,
+ model_config: Optional[Dict] = None,
+ tools: Optional[List] = None,
+ terminal_endpoint: Optional[str] = None,
+ terminal_tool_defs: Optional[List] = None,
+ **_) -> "StockAnalysisWorkflow":
+ _keys = api_keys or {}
+ _tools = tools or _load_workflow_tools(_keys, terminal_endpoint, terminal_tool_defs)
+ return StockAnalysisWorkflow(_keys, model_config, tools=_tools)
- # Step 2: Iterative filtering (loop)
- def has_more_filters(context: Dict) -> bool:
- filters = context.get("remaining_filters", [])
- return len(filters) > 0
-
- workflow.add_loop(
- name="apply_filters",
- steps=[
- {
- "type": "step",
- "name": "apply_filter",
- "agent": screening_agent,
- "prompt": "Apply filter {current_filter} to the stock list: {candidates}"
- }
- ],
- condition=has_more_filters,
- max_iterations=max_iterations
- )
+ @staticmethod
+ def portfolio_rebalancing(api_keys: Dict[str, str] = None,
+ model_config: Optional[Dict] = None,
+ tools: Optional[List] = None,
+ terminal_endpoint: Optional[str] = None,
+ terminal_tool_defs: Optional[List] = None,
+ **_) -> "PortfolioRebalancingWorkflow":
+ _keys = api_keys or {}
+ _tools = tools or _load_workflow_tools(_keys, terminal_endpoint, terminal_tool_defs)
+ return PortfolioRebalancingWorkflow(_keys, model_config, tools=_tools)
- # Step 3: Deep analysis on top candidates
- workflow.add_step(
- name="deep_analysis",
- agent=analysis_agent,
- prompt="Perform detailed analysis on top candidates: {last_result}"
- )
+ @staticmethod
+ def risk_assessment(api_keys: Dict[str, str] = None,
+ model_config: Optional[Dict] = None,
+ tools: Optional[List] = None,
+ terminal_endpoint: Optional[str] = None,
+ terminal_tool_defs: Optional[List] = None,
+ **_) -> "RiskAssessmentWorkflow":
+ _keys = api_keys or {}
+ _tools = tools or _load_workflow_tools(_keys, terminal_endpoint, terminal_tool_defs)
+ return RiskAssessmentWorkflow(_keys, model_config, tools=_tools)
- # Step 4: Rank and prioritize
- workflow.add_step(
- name="rank_candidates",
- agent=analysis_agent,
- prompt="Rank and prioritize the analyzed candidates based on investment potential"
- )
- return workflow
+# ─── Kept for any direct usage ────────────────────────────────────────────────
- @staticmethod
- def risk_assessment(
- risk_agent: Any = None,
- market_agent: Any = None
- ) -> WorkflowModule:
- """
- Create risk assessment workflow with routing.
-
- Steps:
- 1. Identify risk type
- 2. Route to appropriate analysis
- 3. Calculate risk metrics
- 4. Generate risk report
-
- Args:
- risk_agent: Agent for risk analysis
- market_agent: Agent for market analysis
-
- Returns:
- Configured WorkflowModule
- """
- workflow = WorkflowModule(
- name="Risk Assessment",
- description="Comprehensive risk assessment with dynamic routing"
- )
+class SimpleWorkflowExecutor:
+ """Fallback sequential executor (backwards compat)."""
+ def __init__(self, steps): self.steps = steps
+ def run(self, input=None, **kwargs):
+ context = input or {}
+ results = []
+ for step in self.steps:
+ fn = step.get("function")
+ agent = step.get("agent")
+ if fn:
+ r = fn(context)
+ elif agent:
+ r = agent.run(step.get("prompt", "").format(**context))
+ else:
+ r = None
+ results.append(r)
+ context["last_result"] = r
+ return {"success": True, "results": results}
+ async def arun(self, input=None, **kwargs): return self.run(input=input)
- # Step 1: Identify risk type
- workflow.add_step(
- name="identify_risk_type",
- agent=risk_agent,
- prompt="Identify the primary risk type for the portfolio: market, credit, liquidity, or operational"
- )
- # Step 2: Route to appropriate analysis
- def route_risk_analysis(context: Dict) -> str:
- risk_type = context.get("risk_type", "market").lower()
- if "market" in risk_type:
- return "market_risk"
- elif "credit" in risk_type:
- return "credit_risk"
- elif "liquidity" in risk_type:
- return "liquidity_risk"
- return "general_risk"
-
- workflow.add_router(
- name="risk_router",
- routes={
- "market_risk": {
- "type": "step",
- "name": "market_risk_analysis",
- "agent": market_agent,
- "prompt": "Perform market risk analysis including VaR, beta, and volatility"
- },
- "credit_risk": {
- "type": "step",
- "name": "credit_risk_analysis",
- "agent": risk_agent,
- "prompt": "Perform credit risk analysis on holdings"
- },
- "liquidity_risk": {
- "type": "step",
- "name": "liquidity_risk_analysis",
- "agent": risk_agent,
- "prompt": "Analyze liquidity risk including bid-ask spreads and volume"
- },
- "general_risk": {
- "type": "step",
- "name": "general_risk_analysis",
- "agent": risk_agent,
- "prompt": "Perform general risk assessment"
- }
- },
- router_function=route_risk_analysis
- )
+class WorkflowBuilder:
+ """Fluent builder (backwards compat) — delegates to WorkflowModule."""
+ def __init__(self, name: str):
+ self._module = WorkflowModule(name=name)
+ def with_description(self, d):
+ self._module.description = d; return self
+ def add_step(self, name, agent=None, function=None, prompt=None, **kw):
+ self._module.add_step(name, agent=agent, function=function, prompt=prompt, **kw); return self
+ def add_parallel(self, name, steps):
+ self._module.add_parallel(name, steps); return self
+ def add_condition(self, name, condition, if_true, if_false=None):
+ self._module.add_condition(name, condition, if_true, if_false); return self
+ def add_loop(self, name, steps, condition=None, max_iterations=10):
+ self._module.add_loop(name, steps, condition, max_iterations); return self
+ def build(self): return self._module.build()
+ def get_module(self): return self._module
- # Step 3: Generate risk report
- workflow.add_step(
- name="generate_risk_report",
- agent=risk_agent,
- prompt="Generate comprehensive risk report based on the analysis: {last_result}"
- )
- return workflow
+class WorkflowModule:
+ """Thin shim kept for backwards compatibility. Delegates to workflow classes."""
- @staticmethod
- def research_report_generation(
- research_agent: Any = None,
- writing_agent: Any = None
- ) -> WorkflowModule:
- """
- Create research report generation workflow.
-
- Steps:
- 1. Gather research data (parallel)
- 2. Analyze and synthesize
- 3. Write report sections
- 4. Review and finalize
-
- Args:
- research_agent: Agent for research
- writing_agent: Agent for writing
-
- Returns:
- Configured WorkflowModule
- """
- workflow = WorkflowModule(
- name="Research Report Generation",
- description="Generate comprehensive research reports"
- )
+ def __init__(self, name: str = "Workflow", description: Optional[str] = None, **_):
+ self.name = name
+ self.description = description
+ self._steps: List[Dict[str, Any]] = []
- # Step 1: Gather research data in parallel
- workflow.add_parallel(
- name="gather_research",
- steps=[
- {
- "type": "step",
- "name": "company_research",
- "agent": research_agent,
- "prompt": "Research company fundamentals, management, and competitive position for {symbol}"
- },
- {
- "type": "step",
- "name": "industry_research",
- "agent": research_agent,
- "prompt": "Research industry trends and competitive landscape for {symbol}'s sector"
- },
- {
- "type": "step",
- "name": "financial_research",
- "agent": research_agent,
- "prompt": "Analyze financial statements and metrics for {symbol}"
- }
- ]
- )
+ def add_step(self, name, agent=None, function=None, prompt=None, **kwargs):
+ self._steps.append({"type": "step", "name": name, "agent": agent,
+ "function": function, "prompt": prompt, **kwargs})
+ return self
- # Step 2: Synthesize findings
- workflow.add_step(
- name="synthesize_findings",
- agent=research_agent,
- prompt="Synthesize all research findings into key insights and investment thesis"
- )
+ def add_parallel(self, name, steps, **kwargs):
+ self._steps.append({"type": "parallel", "name": name, "steps": steps, **kwargs})
+ return self
- # Step 3: Write report
- workflow.add_step(
- name="write_report",
- agent=writing_agent,
- prompt="Write a professional investment research report based on the synthesized findings"
- )
+ def add_condition(self, name, condition, if_true, if_false=None, **kwargs):
+ self._steps.append({"type": "condition", "name": name, "condition": condition,
+ "if_true": if_true, "if_false": if_false, **kwargs})
+ return self
- # Step 4: Review and finalize
- workflow.add_step(
- name="review_report",
- agent=writing_agent,
- prompt="Review the report for accuracy, completeness, and clarity. Make necessary improvements."
- )
+ def add_loop(self, name, steps, condition=None, max_iterations=10, **kwargs):
+ self._steps.append({"type": "loop", "name": name, "steps": steps,
+ "condition": condition, "max_iterations": max_iterations, **kwargs})
+ return self
- return workflow
+ def build(self) -> Any:
+ from agno.workflow import Workflow, Step, Parallel, Loop, Condition, Router
+ if not self._steps:
+ raise ValueError("Cannot build workflow without steps")
+ agno_steps = self._convert(self._steps)
+ return Workflow(name=self.name, description=self.description, steps=agno_steps)
+
+ def run(self, input_data=None, **kwargs):
+ result = self.build().run(input=input_data, **kwargs)
+ return getattr(result, "content", str(result))
+
+ def _convert(self, steps):
+ from agno.workflow import Step, Parallel, Loop, Condition, Router
+ from agno.workflow.types import StepOutput
+ out = []
+ for cfg in steps:
+ t = cfg.get("type", "step")
+ if t == "step":
+ out.append(self._make_step(cfg))
+ elif t == "parallel":
+ inner = self._convert(cfg.get("steps", []))
+ out.append(Parallel(*inner, name=cfg["name"]))
+ elif t == "condition":
+ fn = cfg["condition"]
+ branches = []
+ if cfg.get("if_true"): branches.append(self._make_step(cfg["if_true"]))
+ if cfg.get("if_false"): branches.append(self._make_step(cfg["if_false"]))
+ def _ev(si, _fn=fn):
+ ctx = _extract_content(si)
+ return bool(_fn(ctx if isinstance(ctx, dict) else {}))
+ out.append(Condition(_ev, steps=branches, name=cfg["name"]))
+ elif t == "loop":
+ inner = self._convert(cfg.get("steps", []))
+ kw: Dict = {"name": cfg["name"], "steps": inner,
+ "max_iterations": cfg.get("max_iterations", 10)}
+ raw = cfg.get("condition")
+ if raw:
+ def _ec(outputs, _r=raw):
+ ctx = {"last_result": getattr(outputs[-1], "content", None)} if outputs else {}
+ return not bool(_r(ctx))
+ kw["end_condition"] = _ec
+ out.append(Loop(**kw))
+ elif t == "router":
+ routes = cfg.get("routes", {})
+ rfn = cfg["router_function"]
+ keys = list(routes.keys())
+ choices = self._convert(list(routes.values()))
+ def _sel(si, _keys=keys, _choices=choices, _rfn=rfn):
+ ctx = _extract_content(si)
+ key = _rfn(ctx if isinstance(ctx, dict) else {})
+ idx = _keys.index(key) if key in _keys else 0
+ return [_choices[idx]]
+ out.append(Router(_sel, choices=choices, name=cfg["name"]))
+ return out
+
+ def _make_step(self, cfg):
+ from agno.workflow import Step
+ from agno.workflow.types import StepOutput
+ name = cfg["name"]
+ fn = cfg.get("function")
+ agent = cfg.get("agent")
+ prompt = cfg.get("prompt")
+ if fn:
+ def _ex(si, _fn=fn):
+ ctx = _extract_content(si)
+ r = _fn(ctx if isinstance(ctx, dict) else {})
+ return r if isinstance(r, StepOutput) else StepOutput(content=r)
+ return Step(name=name, executor=_ex)
+ elif agent and prompt:
+ _a, _p = agent, prompt
+ def _ex(si, _a=_a, _p=_p):
+ ctx = _extract_content(si)
+ ctx = ctx if isinstance(ctx, dict) else {}
+ try: fmt = _p.format(**ctx)
+ except: fmt = _p
+ resp = _a.run(fmt)
+ return StepOutput(content=getattr(resp, "content", str(resp)))
+ return Step(name=name, executor=_ex)
+ elif agent:
+ return Step(name=name, agent=agent)
+ else:
+ return Step(name=name, executor=lambda si: StepOutput(content=None))
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py
index f3b7a0e33..846000f64 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py
@@ -63,9 +63,9 @@ def _rate_limit_fincept() -> None:
except Exception:
pass
- # Wait until 2.0 s have elapsed since last call
+ # Wait until 1.2 s have elapsed since last call
now = time.time()
- wait = 2.0 - (now - last_ts)
+ wait = 1.2 - (now - last_ts)
if wait > 0:
time.sleep(wait)
@@ -79,7 +79,7 @@ def _rate_limit_fincept() -> None:
except Exception:
pass
-FINCEPT_DEFAULT_URL = "https://finceptbackend.share.zrok.io/research/llm"
+FINCEPT_DEFAULT_URL = "https://api.fincept.in/research/llm"
# ── Anthropic tool schema builder ─────────────────────────────────────────────
@@ -182,64 +182,34 @@ class FinceptChat(Model):
# ── HTTP request ──────────────────────────────────────────────────────────
- def _call_endpoint(
+ def _try_url(
self,
- prompt: str,
- tools: Optional[List[Dict]] = None,
- tool_choice: Optional[Dict] = None,
- tool_results_context: Optional[str] = None,
+ url: str,
+ payload: Dict[str, Any],
+ headers: Dict[str, str],
) -> Dict[str, Any]:
"""
- Call /research/llm and return the parsed response dict.
-
- Returns the full data dict:
- {"response": str, "tool_calls": [...], "model": str, ...}
+ Attempt a single POST to `url`. Retries up to 3 times on 429/502/504/timeout.
+ Raises RuntimeError on persistent failure so the caller can try a fallback URL.
"""
- _rate_limit_fincept()
-
- headers = {"Content-Type": "application/json"}
- if self.api_key:
- headers["X-API-Key"] = self.api_key
-
- # Build the full prompt — include tool results from prior rounds
- full_prompt = prompt
- if tool_results_context:
- full_prompt = f"{prompt}\n\n{tool_results_context}"
-
- payload: Dict[str, Any] = {"prompt": full_prompt}
- if self.temperature is not None:
- payload["temperature"] = self.temperature
- if self.max_tokens is not None:
- payload["max_tokens"] = self.max_tokens
- if tools:
- payload["tools"] = tools
- if tool_choice:
- payload["tool_choice"] = tool_choice
-
last_error: Optional[RuntimeError] = None
for attempt in range(3):
try:
- with httpx.Client(timeout=120.0) as client:
- resp = client.post(self.base_url, json=payload, headers=headers)
+ with httpx.Client(timeout=250.0) as client:
+ resp = client.post(url, json=payload, headers=headers)
if resp.status_code == 429:
- # Rate limited — wait longer and retry (don't call _rate_limit_fincept
- # here since that would update the shared timestamp without a real call)
- wait = 5.0 * (attempt + 1) # 5s, 10s, 15s
- logger.warning(f"FinceptChat: 429 rate limit on attempt {attempt + 1}, waiting {wait}s")
+ wait = 3.0 * (attempt + 1) # 3s, 6s, 9s
+ logger.warning(f"FinceptChat: 429 from {url} attempt {attempt + 1}, waiting {wait}s")
time.sleep(wait)
- last_error = RuntimeError(
- f"Fincept API error (429): rate limit hit after {attempt + 1} attempts"
- )
+ last_error = RuntimeError(f"Fincept API error (429): rate limited")
continue
if resp.status_code in (502, 504):
- wait = 3.0 * (attempt + 1) # 3s, 6s, 9s
- logger.warning(f"FinceptChat: {resp.status_code} on attempt {attempt + 1}, waiting {wait}s")
+ wait = 2.0 * (attempt + 1) # 2s, 4s, 6s
+ logger.warning(f"FinceptChat: {resp.status_code} from {url} attempt {attempt + 1}, waiting {wait}s")
time.sleep(wait)
- last_error = RuntimeError(
- f"Fincept API error ({resp.status_code}): gateway error"
- )
+ last_error = RuntimeError(f"Fincept API error ({resp.status_code}): gateway error")
continue
if resp.status_code != 200:
@@ -249,28 +219,82 @@ class FinceptChat(Model):
error_detail = err_data.get("detail", err_data.get("message", ""))
except Exception:
error_detail = resp.text[:200]
- raise RuntimeError(
- f"Fincept API error ({resp.status_code}): {error_detail}"
- )
+ raise RuntimeError(f"Fincept API error ({resp.status_code}): {error_detail}")
outer = resp.json()
- # Unwrap: {"success": true, "data": {...}}
if isinstance(outer, dict) and "data" in outer:
return outer["data"]
return outer
except httpx.TimeoutException:
- last_error = RuntimeError("Fincept API request timed out (120s)")
- logger.warning(f"FinceptChat: timeout on attempt {attempt + 1}")
+ last_error = RuntimeError(f"Fincept API request timed out (250s) for {url}")
+ logger.warning(f"FinceptChat: timeout from {url} attempt {attempt + 1}")
continue
except httpx.ConnectError as e:
- raise RuntimeError(f"Cannot connect to Fincept API: {e}")
+ last_error = RuntimeError(f"Cannot connect to {url}: {e}")
+ logger.warning(f"FinceptChat: connect error for {url}: {e}")
+ break # Connection refused — no point retrying same URL
except RuntimeError:
raise
except Exception as e:
raise RuntimeError(f"Fincept API call failed: {e}")
- raise last_error or RuntimeError("Fincept API failed after 3 attempts")
+ raise last_error or RuntimeError(f"Fincept API failed after 3 attempts on {url}")
+
+ def _call_endpoint(
+ self,
+ prompt: str,
+ tools: Optional[List[Dict]] = None,
+ tool_choice: Optional[Dict] = None,
+ tool_results_context: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Call /research/llm and return the parsed response dict.
+
+ Tries self.base_url first. If that URL is different from the canonical
+ FINCEPT_DEFAULT_URL and it fails with a gateway error, automatically
+ falls back to the canonical URL so a misconfigured/expired custom
+ endpoint never permanently blocks the agent.
+
+ Returns the full data dict:
+ {"response": str, "tool_calls": [...], "model": str, ...}
+ """
+ _rate_limit_fincept()
+
+ headers = {"Content-Type": "application/json"}
+ if self.api_key:
+ headers["X-API-Key"] = self.api_key
+
+ # Build the full prompt — include tool results from prior rounds
+ full_prompt = prompt
+ if tool_results_context:
+ full_prompt = f"{prompt}\n\n{tool_results_context}"
+
+ payload: Dict[str, Any] = {"prompt": full_prompt}
+ if self.temperature is not None:
+ payload["temperature"] = self.temperature
+ if self.max_tokens is not None:
+ payload["max_tokens"] = self.max_tokens
+ if tools:
+ payload["tools"] = tools
+ if tool_choice:
+ payload["tool_choice"] = tool_choice
+
+ # Try the configured URL first
+ try:
+ return self._try_url(self.base_url, payload, headers)
+ except RuntimeError as primary_err:
+ # If we're already using the default URL, re-raise immediately
+ if self.base_url == FINCEPT_DEFAULT_URL:
+ raise
+
+ # Custom/tunnel URL failed — fall back to the real Fincept API
+ logger.warning(
+ f"FinceptChat: custom base_url '{self.base_url}' failed ({primary_err}). "
+ f"Falling back to {FINCEPT_DEFAULT_URL}"
+ )
+ _rate_limit_fincept() # honour rate limit before fallback attempt
+ return self._try_url(FINCEPT_DEFAULT_URL, payload, headers)
# ── Tool execution ────────────────────────────────────────────────────────
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.py
index a56e1cab5..1689693e3 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.py
@@ -273,7 +273,7 @@ class ModelsRegistry:
"models": ["fincept-llm"],
"api_key_env": "FINCEPT_API_KEY",
"default_model": "fincept-llm",
- "base_url": "https://finceptbackend.share.zrok.io/research/llm",
+ "base_url": "https://api.fincept.in/research/llm",
},
}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/super_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/super_agent.py
index 1bb61bd25..3f64bae4f 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/super_agent.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/super_agent.py
@@ -402,6 +402,19 @@ class SuperAgent:
if route.keywords:
self.classifier.keywords.setdefault(route.intent, []).extend(route.keywords)
+ def _resolve_model_config_from_keys(self, api_keys: Dict[str, Any]) -> Dict[str, Any]:
+ """Derive provider from available api_keys instead of hardcoding openai."""
+ keys = api_keys or {}
+ preferred = ["fincept", "ollama", "anthropic", "google", "groq",
+ "deepseek", "openai", "openrouter"]
+ for provider in preferred:
+ if keys.get(provider) or keys.get(f"{provider.upper()}_API_KEY"):
+ return {"provider": provider}
+ for k, v in keys.items():
+ if k.endswith("_API_KEY") and v:
+ return {"provider": k[:-8].lower()}
+ return {"provider": "openai"}
+
def route(self, query: str) -> RoutingResult:
"""
Route query to appropriate agent using LLM classification.
@@ -486,11 +499,11 @@ class SuperAgent:
routing = self.route(query)
logger.info(f"Routed to {routing.agent_id} with confidence {routing.confidence:.2f}")
- # Build config - use user's model config if provided, otherwise default
- model_config = (
- user_config.get("model", {}) if user_config
- else {"provider": "openai", "model_id": "gpt-4o-mini"}
- )
+ # Build config - use user's model config if provided, otherwise resolve from api_keys
+ if user_config and user_config.get("model"):
+ model_config = user_config["model"]
+ else:
+ model_config = self._resolve_model_config_from_keys(getattr(self, "api_keys", {}))
config = {
"model": model_config,
@@ -535,6 +548,26 @@ class SuperAgent:
response = agent.run(query, config, session_id)
content = agent.get_response_content(response) if hasattr(agent, 'get_response_content') else str(response)
+ # Detect when Agno swallowed an API error and returned it as response text
+ _ERROR_PREFIXES = (
+ "Fincept API error",
+ "Fincept API request timed out",
+ "Fincept API failed",
+ "Cannot connect to Fincept API",
+ )
+ if isinstance(content, str) and any(content.startswith(p) for p in _ERROR_PREFIXES):
+ return {
+ "success": False,
+ "error": content,
+ "routing": {
+ "intent": routing.intent.value,
+ "agent_id": routing.agent_id,
+ "confidence": routing.confidence,
+ "matched_keywords": routing.matched_keywords
+ },
+ "model_attempted": f"{model_provider}/{model_id}"
+ }
+
return {
"success": True,
"response": content,
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
index d2f26eb01..ceccb7b50 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/algo_live_runner.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/algo_live_runner.py
@@ -52,16 +52,41 @@ TIMEFRAME_SECONDS = {
}
-def load_strategy(db_path: str, strategy_id: str) -> dict:
+MAX_ORDER_VALUE_WARNING = 1_000_000 # Warn if order value exceeds this
+
+
+def _db_execute_with_retry(conn, sql, params=(), retries=3, commit=True):
+ """Execute a DB statement with retry logic for 'database is locked' errors."""
+ for attempt in range(retries):
+ try:
+ conn.execute(sql, params)
+ if commit:
+ conn.commit()
+ return
+ except sqlite3.OperationalError as e:
+ if 'locked' in str(e).lower() and attempt < retries - 1:
+ log.warning(f" DB locked, retry {attempt + 1}/{retries}...")
+ time.sleep(0.1 * (attempt + 1))
+ else:
+ raise
+
+
+def open_db_connection(db_path: str):
+ """Open a shared DB connection with WAL mode for concurrent access."""
+ conn = sqlite3.connect(db_path, timeout=10)
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("PRAGMA busy_timeout=5000")
+ return conn
+
+
+def load_strategy(conn, 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
@@ -78,27 +103,21 @@ def load_strategy(db_path: str, strategy_id: str) -> dict:
}
-def update_deployment_status(db_path: str, deploy_id: str, status: str, error: str = None):
+def update_deployment_status(conn, deploy_id: str, status: str, error: str = None):
"""Update deployment status in DB."""
- conn = sqlite3.connect(db_path)
if error:
- conn.execute(
+ _db_execute_with_retry(conn,
"UPDATE algo_deployments SET status = ?, error_message = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
- (status, error, deploy_id)
- )
+ (status, error, deploy_id))
else:
- conn.execute(
+ _db_execute_with_retry(conn,
"UPDATE algo_deployments SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
- (status, deploy_id)
- )
- conn.commit()
- conn.close()
+ (status, deploy_id))
-def update_metrics(db_path: str, deploy_id: str, metrics: dict):
+def update_metrics(conn, deploy_id: str, metrics: dict):
"""Update algo_metrics table."""
- conn = sqlite3.connect(db_path)
- conn.execute(
+ _db_execute_with_retry(conn,
"""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)
@@ -116,39 +135,28 @@ def update_metrics(db_path: str, deploy_id: str, metrics: dict):
(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()
+ metrics.get('current_position_side', ''), metrics.get('current_position_entry', 0)))
-def record_trade(db_path: str, deploy_id: str, symbol: str, side: str,
+def record_trade(conn, 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(
+ _db_execute_with_retry(conn,
"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()
+ (trade_id, deploy_id, symbol, side, quantity, price, pnl, reason))
return trade_id
-def create_order_signal(db_path: str, deploy_id: str, symbol: str, side: str,
+def create_order_signal(conn, 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(
+ _db_execute_with_retry(conn,
"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()
+ (signal_id, deploy_id, symbol, side, quantity, order_type, price))
return signal_id
@@ -157,20 +165,18 @@ def _normalize_symbol(s: str) -> str:
return s.replace('/', '').replace('-', '').replace('_', '').replace(':', '').upper()
-def get_current_price(db_path: str, symbol: str) -> float:
+def get_current_price(conn, symbol: str) -> float:
"""Get latest price from strategy_price_cache.
Tries exact match first, then normalized match to handle symbol format
differences (e.g., BTC/USD vs BTCUSD, NSE:RELIANCE vs RELIANCE).
"""
- conn = sqlite3.connect(db_path)
# Try exact match first
row = conn.execute(
"SELECT price FROM strategy_price_cache WHERE symbol = ? ORDER BY updated_at DESC LIMIT 1",
(symbol,)
).fetchone()
if row:
- conn.close()
log.debug(f" get_current_price({symbol}) = {row[0]} (exact match)")
return row[0]
@@ -179,7 +185,6 @@ def get_current_price(db_path: str, symbol: str) -> float:
rows = conn.execute(
"SELECT symbol, price FROM strategy_price_cache ORDER BY updated_at DESC"
).fetchall()
- conn.close()
log.debug(f" get_current_price({symbol}) exact miss. Normalized={norm}. Cache has {len(rows)} entries: {[(s, p) for s, p in rows[:10]]}")
@@ -250,18 +255,23 @@ def main():
log.info(f" pid = {os.getpid()}")
log.info("=" * 70)
+ # Open shared DB connection (WAL mode for concurrent Rust access)
+ conn = open_db_connection(args.db)
+ log.info("Shared DB connection opened (WAL mode)")
+
# Load strategy
- strategy = load_strategy(args.db, args.strategy_id)
+ strategy = load_strategy(conn, args.strategy_id)
if not strategy:
log.error(f"Strategy {args.strategy_id} NOT FOUND in DB!")
- update_deployment_status(args.db, args.deploy_id, 'error', 'Strategy not found')
+ update_deployment_status(conn, args.deploy_id, 'error', 'Strategy not found')
+ conn.close()
sys.exit(1)
log.info(f"Strategy loaded OK. Entry conditions: {json.dumps(strategy['entry_conditions'], indent=2)}")
log.info(f"Exit conditions: {json.dumps(strategy['exit_conditions'], indent=2)}")
log.info(f"Risk: SL={strategy.get('stop_loss')}, TP={strategy.get('take_profit')}, TS={strategy.get('trailing_stop')}")
- update_deployment_status(args.db, args.deploy_id, 'running')
+ update_deployment_status(conn, args.deploy_id, 'running')
# Inject logic operators into condition lists
entry_conds = strategy['entry_conditions']
@@ -293,14 +303,10 @@ def main():
log.warning(f"[loop#{loop_count}] Candle data insufficient: {len(df)} rows (need >=2) for {args.symbol}@{args.timeframe}")
# Dump what symbols exist in candle_cache
try:
- conn_debug = sqlite3.connect(args.db)
- syms = conn_debug.execute("SELECT DISTINCT symbol, timeframe, COUNT(*) FROM candle_cache GROUP BY symbol, timeframe").fetchall()
- conn_debug.close()
+ syms = conn.execute("SELECT DISTINCT symbol, timeframe, COUNT(*) FROM candle_cache GROUP BY symbol, timeframe").fetchall()
log.warning(f" candle_cache contents: {syms}")
# Also check strategy_price_cache for recent price updates
- conn_debug = sqlite3.connect(args.db)
- prices = conn_debug.execute("SELECT symbol, price, updated_at FROM strategy_price_cache ORDER BY updated_at DESC LIMIT 10").fetchall()
- conn_debug.close()
+ prices = conn.execute("SELECT symbol, price, updated_at FROM strategy_price_cache ORDER BY updated_at DESC LIMIT 10").fetchall()
log.warning(f" strategy_price_cache recent entries: {prices}")
except Exception as dbg_e:
log.warning(f" could not read cache tables: {dbg_e}")
@@ -322,7 +328,7 @@ def main():
log.info(f"[loop#{loop_count}] NEW candle detected! open_time={newest_time}, total candles={len(df)}")
log.debug(f" Last 3 candles: {df[['open_time','open','high','low','close','volume']].tail(3).to_string()}")
- current_price = get_current_price(args.db, args.symbol)
+ current_price = get_current_price(conn, args.symbol)
price_source = "price_cache"
if current_price <= 0:
current_price = float(df['close'].iloc[-1])
@@ -348,10 +354,10 @@ def main():
else (position['entry'] - current_price) * qty
if args.mode == 'paper':
- record_trade(args.db, args.deploy_id, args.symbol, 'SELL' if position['side'] == 'BUY' else 'BUY',
+ record_trade(conn, 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,
+ create_order_signal(conn, args.deploy_id, args.symbol,
'SELL' if position['side'] == 'BUY' else 'BUY',
abs(position['qty']))
@@ -382,12 +388,17 @@ def main():
'max_pnl_pct': 0,
}
+ # Position size warning (#18)
+ order_value = args.quantity * current_price
+ if order_value > MAX_ORDER_VALUE_WARNING:
+ log.warning(f" HIGH ORDER VALUE: {args.quantity} x {current_price} = {order_value:.2f} (exceeds {MAX_ORDER_VALUE_WARNING})")
+
if args.mode == 'paper':
- record_trade(args.db, args.deploy_id, args.symbol, 'BUY',
+ record_trade(conn, 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)
+ create_order_signal(conn, args.deploy_id, args.symbol, 'BUY', args.quantity)
else:
# In position: check exit conditions
@@ -406,12 +417,12 @@ def main():
else (position['entry'] - current_price) * qty
if args.mode == 'paper':
- record_trade(args.db, args.deploy_id, args.symbol,
+ record_trade(conn, 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,
+ create_order_signal(conn, args.deploy_id, args.symbol,
'SELL' if position['side'] == 'BUY' else 'BUY',
abs(position['qty']))
@@ -439,7 +450,7 @@ def main():
win_rate = (winning_trades / total_trades * 100) if total_trades > 0 else 0
- update_metrics(args.db, args.deploy_id, {
+ update_metrics(conn, args.deploy_id, {
'total_pnl': total_pnl,
'unrealized_pnl': unrealized,
'total_trades': total_trades,
@@ -459,8 +470,9 @@ def main():
log.error(f"[loop#{loop_count}] EXCEPTION: {e}", exc_info=True)
time.sleep(check_interval)
- # Shutdown: update status
- update_deployment_status(args.db, args.deploy_id, 'stopped')
+ # Shutdown: update status and close DB connection
+ update_deployment_status(conn, args.deploy_id, 'stopped')
+ conn.close()
log.info(f"Deployment {args.deploy_id} STOPPED. Total trades={total_trades}, PnL={total_pnl:.2f}")
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
index 62ec63fda..c3cf1513d 100644
--- 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
@@ -201,9 +201,11 @@ def run_backtest(
stop_loss_pct: float = 0,
take_profit_pct: float = 0,
initial_capital: float = 100000,
+ timeframe: str = '1d',
):
"""
Walk forward through candle data and generate trades.
+ Uses proper position sizing based on available capital.
Returns dict with trades, equity curve, and metrics.
"""
@@ -212,6 +214,7 @@ def run_backtest(
in_position = False
entry_price = 0.0
entry_bar = 0
+ position_shares = 0
capital = initial_capital
peak_capital = initial_capital
max_drawdown = 0.0
@@ -229,6 +232,12 @@ def run_backtest(
in_position = True
entry_price = current_price
entry_bar = current_bar
+ # Position sizing: invest all available capital
+ position_shares = math.floor(capital / entry_price) if entry_price > 0 else 0
+ if position_shares <= 0:
+ in_position = False # Can't afford even 1 share
+ continue
+ capital -= position_shares * entry_price
else:
# Check risk management first
pnl_pct = ((current_price - entry_price) / entry_price) * 100
@@ -236,60 +245,66 @@ def run_backtest(
# Stop loss
if stop_loss_pct > 0 and pnl_pct <= -stop_loss_pct:
exit_price = current_price
- pnl = exit_price - entry_price
- capital += pnl
+ pnl = (exit_price - entry_price) * position_shares
+ capital += position_shares * exit_price
trades.append({
'entry_bar': entry_bar,
'exit_bar': current_bar,
'entry_price': round(entry_price, 2),
'exit_price': round(exit_price, 2),
+ 'shares': position_shares,
'pnl': round(pnl, 2),
'pnl_pct': round(pnl_pct, 2),
'reason': 'stop_loss',
'bars_held': current_bar - entry_bar,
})
in_position = False
+ position_shares = 0
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
+ pnl = (exit_price - entry_price) * position_shares
+ capital += position_shares * exit_price
trades.append({
'entry_bar': entry_bar,
'exit_bar': current_bar,
'entry_price': round(entry_price, 2),
'exit_price': round(exit_price, 2),
+ 'shares': position_shares,
'pnl': round(pnl, 2),
'pnl_pct': round(pnl_pct, 2),
'reason': 'take_profit',
'bars_held': current_bar - entry_bar,
})
in_position = False
+ position_shares = 0
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
+ pnl = (exit_price - entry_price) * position_shares
+ capital += position_shares * exit_price
trades.append({
'entry_bar': entry_bar,
'exit_bar': current_bar,
'entry_price': round(entry_price, 2),
'exit_price': round(exit_price, 2),
+ 'shares': position_shares,
'pnl': round(pnl, 2),
'pnl_pct': round(pnl_pct, 2),
'reason': 'exit_signal',
'bars_held': current_bar - entry_bar,
})
in_position = False
+ position_shares = 0
# Track equity curve
- unrealized = (current_price - entry_price) if in_position else 0
- current_equity = capital + unrealized
+ unrealized = (current_price - entry_price) * position_shares if in_position else 0
+ current_equity = capital + (position_shares * current_price if in_position else 0)
equity_curve.append(round(current_equity, 2))
if current_equity > peak_capital:
@@ -301,14 +316,15 @@ def run_backtest(
# 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 = (exit_price - entry_price) * position_shares
pnl_pct = ((exit_price - entry_price) / entry_price) * 100
- capital += pnl
+ capital += position_shares * exit_price
trades.append({
'entry_bar': entry_bar,
'exit_bar': len(df) - 1,
'entry_price': round(entry_price, 2),
'exit_price': round(exit_price, 2),
+ 'shares': position_shares,
'pnl': round(pnl, 2),
'pnl_pct': round(pnl_pct, 2),
'reason': 'end_of_data',
@@ -348,7 +364,15 @@ def run_backtest(
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)
+ # Annualization factor based on timeframe (bars per year)
+ BARS_PER_YEAR = {
+ '1m': 252 * 390, '3m': 252 * 130, '5m': 252 * 78, '10m': 252 * 39,
+ '15m': 252 * 26, '30m': 252 * 13, '1h': int(252 * 6.5), '4h': int(252 * 1.625),
+ '1d': 252, '1D': 252, 'D': 252, '1w': 52, '1W': 52, '1M': 12,
+ }
+ ann_factor = BARS_PER_YEAR.get(timeframe, 252)
+
+ # Sharpe ratio (annualized using timeframe-aware factor)
if len(equity_curve) > 1:
returns = []
for i in range(1, len(equity_curve)):
@@ -357,7 +381,7 @@ def run_backtest(
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
+ sharpe = (mean_ret / std_ret) * (ann_factor ** 0.5) if std_ret > 0 else 0
else:
sharpe = 0
else:
@@ -367,9 +391,19 @@ def run_backtest(
if math.isinf(profit_factor):
profit_factor = 999.99
+ # Downsample equity curve if too large (keep full shape visible)
+ if len(equity_curve) > 500:
+ step = len(equity_curve) // 500
+ equity_curve_out = equity_curve[::step]
+ # Ensure the last point is always included
+ if equity_curve_out[-1] != equity_curve[-1]:
+ equity_curve_out.append(equity_curve[-1])
+ else:
+ equity_curve_out = equity_curve
+
return {
'trades': trades,
- 'equity_curve': equity_curve[-100:], # Last 100 points for chart
+ 'equity_curve': equity_curve_out,
'metrics': {
'total_trades': total_trades,
'winning_trades': len(wins),
@@ -473,6 +507,7 @@ def main():
stop_loss_pct=args.stop_loss,
take_profit_pct=args.take_profit,
initial_capital=args.initial_capital,
+ timeframe=args.timeframe,
)
debug(f"Backtest completed: {result.get('metrics', {}).get('total_trades', 'N/A')} trades")
except Exception as e:
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 34377a9ad..5273bafeb 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
@@ -20,6 +20,9 @@ from alpha_arena.types.models import (
PortfolioState,
TradeAction,
TradeResult,
+ PolymarketInfo,
+ PolymarketDecision,
+ PolymarketAction,
)
from alpha_arena.types.responses import StreamResponse, NotifyResponse
from alpha_arena.utils.logging import get_logger
@@ -238,6 +241,42 @@ class BaseTradingAgent(BaseAgent):
"""
raise NotImplementedError
+ async def make_polymarket_decision(
+ self,
+ markets: List[PolymarketInfo],
+ portfolio: PortfolioState,
+ cycle_number: int,
+ context: str = "",
+ ) -> List[PolymarketDecision]:
+ """
+ Make trading decisions for Polymarket prediction markets.
+
+ Args:
+ markets: List of Polymarket markets to analyze
+ portfolio: Current portfolio state
+ cycle_number: Current cycle number
+ context: Additional context string
+
+ Returns:
+ List of PolymarketDecision for each market
+ """
+ # Default implementation - subclasses should override for real LLM calls
+ decisions = []
+ for market in markets:
+ decisions.append(PolymarketDecision(
+ competition_id="",
+ model_name=self.name,
+ cycle_number=cycle_number,
+ market_id=market.id,
+ market_question=market.question,
+ action=PolymarketAction.HOLD,
+ amount_usd=0.0,
+ confidence=0.5,
+ estimated_probability=market.outcome_prices[0] if market.outcome_prices else 0.5,
+ reasoning="Default HOLD - no analysis performed",
+ ))
+ return decisions
+
async def stream(
self,
query: str,
@@ -1051,7 +1090,7 @@ Respond ONLY with the JSON object, nothing else.
import httpx
import json
- FINCEPT_URL = "https://finceptbackend.share.zrok.io/research/llm"
+ FINCEPT_URL = "https://api.fincept.in/research/llm"
try:
logger.info(f"Agent '{self.name}' calling Fincept LLM API...")
@@ -1123,3 +1162,229 @@ Respond ONLY with the JSON object, nothing else.
price_at_decision=market_data.price,
)
+ async def make_polymarket_decision(
+ self,
+ markets: List[PolymarketInfo],
+ portfolio: PortfolioState,
+ cycle_number: int,
+ context: str = "",
+ ) -> List[PolymarketDecision]:
+ """
+ Make trading decisions for Polymarket prediction markets using the LLM.
+
+ Args:
+ markets: List of Polymarket markets to analyze
+ portfolio: Current portfolio state
+ cycle_number: Current cycle number
+ context: Additional context string
+
+ Returns:
+ List of PolymarketDecision for each market
+ """
+ import json
+
+ if self._llm is None:
+ logger.warning(f"Agent '{self.name}' has no LLM, returning HOLD decisions")
+ return [
+ PolymarketDecision(
+ competition_id="",
+ model_name=self.name,
+ cycle_number=cycle_number,
+ market_id=m.id,
+ market_question=m.question,
+ action=PolymarketAction.HOLD,
+ amount_usd=0.0,
+ confidence=0.5,
+ estimated_probability=m.outcome_prices[0] if m.outcome_prices else 0.5,
+ reasoning="No LLM available",
+ )
+ for m in markets
+ ]
+
+ # Build Polymarket-specific prompt
+ prompt = self._build_polymarket_prompt(markets, portfolio, cycle_number, context)
+
+ try:
+ logger.info(f"Agent '{self.name}' requesting Polymarket decisions...")
+
+ # Get response from LLM
+ loop = asyncio.get_event_loop()
+ response = await loop.run_in_executor(None, self._llm.run, prompt)
+
+ content = self._extract_content(response)
+ logger.info(f"Agent '{self.name}' Polymarket response: {content[:300]}")
+
+ # Parse decisions from response
+ decisions = self._parse_polymarket_response(content, markets, cycle_number)
+ return decisions
+
+ except Exception as e:
+ logger.error(f"Error in Polymarket decision for '{self.name}': {e}")
+ return [
+ PolymarketDecision(
+ competition_id="",
+ model_name=self.name,
+ cycle_number=cycle_number,
+ market_id=m.id,
+ market_question=m.question,
+ action=PolymarketAction.HOLD,
+ amount_usd=0.0,
+ confidence=0.0,
+ estimated_probability=m.outcome_prices[0] if m.outcome_prices else 0.5,
+ reasoning=f"Error: {str(e)}",
+ )
+ for m in markets
+ ]
+
+ def _build_polymarket_prompt(
+ self,
+ markets: List[PolymarketInfo],
+ portfolio: PortfolioState,
+ cycle_number: int,
+ context: str = "",
+ ) -> str:
+ """Build prompt for Polymarket prediction market decisions."""
+ markets_info = []
+ for i, m in enumerate(markets):
+ yes_price = m.outcome_prices[0] if m.outcome_prices else 0.5
+ no_price = m.outcome_prices[1] if len(m.outcome_prices) > 1 else (1 - yes_price)
+ markets_info.append(f"""
+Market {i+1}:
+ ID: {m.id}
+ Question: {m.question}
+ YES Price: ${yes_price:.4f} ({yes_price*100:.1f}%)
+ NO Price: ${no_price:.4f} ({no_price*100:.1f}%)
+ Volume: ${m.volume:,.0f}
+ Liquidity: ${m.liquidity:,.0f}
+ End Date: {m.end_date or 'Unknown'}
+""")
+
+ return f"""You are an AI trading agent analyzing prediction markets on Polymarket.
+
+CURRENT PREDICTION MARKETS:
+{''.join(markets_info)}
+
+YOUR PORTFOLIO:
+ Cash: ${portfolio.cash:,.2f}
+ Total Value: ${portfolio.portfolio_value:,.2f}
+ Total P&L: ${portfolio.total_pnl:,.2f}
+
+CYCLE: {cycle_number}
+
+{context}
+
+YOUR TASK:
+Analyze each market and decide whether to:
+- BUY_YES: Buy YES shares (bet that the event will happen)
+- BUY_NO: Buy NO shares (bet that the event will NOT happen)
+- SELL_YES: Sell YES shares (if you hold any)
+- SELL_NO: Sell NO shares (if you hold any)
+- HOLD: Do nothing for this market
+
+For each market where you want to trade, estimate the TRUE probability and compare to the market price.
+If your estimated probability > market YES price, consider buying YES.
+If your estimated probability < market YES price, consider buying NO.
+
+RESPOND WITH VALID JSON ONLY - an array of decisions:
+[
+ {{
+ "market_id": "<market_id>",
+ "action": "buy_yes" | "buy_no" | "sell_yes" | "sell_no" | "hold",
+ "amount_usd": <amount to trade in USD, 0 for hold>,
+ "confidence": 0.0 to 1.0,
+ "estimated_probability": 0.0 to 1.0,
+ "reasoning": "brief explanation"
+ }}
+]
+
+RULES:
+- Maximum position per market: 25% of portfolio
+- Be selective - don't trade every market
+- Consider liquidity and volume
+- Factor in time to resolution
+- Respond ONLY with the JSON array, nothing else.
+"""
+
+ def _parse_polymarket_response(
+ self,
+ content: str,
+ markets: List[PolymarketInfo],
+ cycle_number: int,
+ ) -> List[PolymarketDecision]:
+ """Parse Polymarket decisions from LLM response."""
+ import json
+ import re
+
+ decisions = []
+ market_ids = {m.id: m for m in markets}
+
+ try:
+ # Try to parse as JSON array
+ content = content.strip()
+
+ # Remove markdown code blocks
+ if '```' in content:
+ parts = content.split('```')
+ for part in parts:
+ part = part.strip()
+ if part.startswith('json'):
+ part = part[4:].strip()
+ if part.startswith('['):
+ content = part
+ break
+
+ # Find JSON array
+ array_match = re.search(r'\[[\s\S]*\]', content)
+ if array_match:
+ content = array_match.group()
+
+ parsed = json.loads(content)
+
+ if isinstance(parsed, list):
+ for item in parsed:
+ market_id = item.get("market_id", "")
+ market = market_ids.get(market_id)
+ if not market:
+ continue
+
+ action_str = item.get("action", "hold").lower()
+ try:
+ action = PolymarketAction(action_str)
+ except ValueError:
+ action = PolymarketAction.HOLD
+
+ decisions.append(PolymarketDecision(
+ competition_id="",
+ model_name=self.name,
+ cycle_number=cycle_number,
+ market_id=market_id,
+ market_question=market.question,
+ action=action,
+ amount_usd=float(item.get("amount_usd", 0)),
+ confidence=float(item.get("confidence", 0.5)),
+ estimated_probability=float(item.get("estimated_probability", 0.5)),
+ reasoning=item.get("reasoning", ""),
+ ))
+
+ except Exception as e:
+ logger.warning(f"Failed to parse Polymarket response: {e}")
+
+ # Add HOLD decisions for any markets not in the response
+ responded_ids = {d.market_id for d in decisions}
+ for m in markets:
+ if m.id not in responded_ids:
+ decisions.append(PolymarketDecision(
+ competition_id="",
+ model_name=self.name,
+ cycle_number=cycle_number,
+ market_id=m.id,
+ market_question=m.question,
+ action=PolymarketAction.HOLD,
+ amount_usd=0.0,
+ confidence=0.5,
+ estimated_probability=m.outcome_prices[0] if m.outcome_prices else 0.5,
+ reasoning="No decision from LLM",
+ ))
+
+ return decisions
+
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 fdb3a5781..c06212b3f 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
@@ -15,12 +15,16 @@ from alpha_arena.types.models import (
CompetitionConfig,
CompetitionStatus,
CompetitionModel,
+ CompetitionType,
CycleResult,
LeaderboardEntry,
MarketData,
ModelDecision,
PortfolioState,
PerformanceSnapshot,
+ PolymarketInfo,
+ PolymarketDecision,
+ PolymarketAction,
)
from alpha_arena.types.responses import (
StreamResponse,
@@ -38,7 +42,12 @@ from alpha_arena.types.responses import (
)
from alpha_arena.core.base_agent import BaseTradingAgent, LLMTradingAgent
from alpha_arena.core.paper_trading_bridge import PaperTradingBridge, create_paper_trading_bridge
-from alpha_arena.core.market_data import MarketDataProvider, get_market_data_provider
+from alpha_arena.core.market_data import (
+ MarketDataProvider,
+ get_market_data_provider,
+ PolymarketDataProvider,
+ get_polymarket_provider,
+)
from alpha_arena.core.agent_manager import AgentManager, get_agent_manager
from alpha_arena.core.guardrails import TradingGuardrails, create_trading_guardrails
from alpha_arena.config.agent_cards import get_agent_card
@@ -72,6 +81,13 @@ class AlphaArenaCompetition:
self._agents: Dict[str, BaseTradingAgent] = {}
self._engines: Dict[str, PaperTradingBridge] = {}
self._market_provider: Optional[MarketDataProvider] = None
+ self._polymarket_provider: Optional[PolymarketDataProvider] = None
+
+ # Competition type
+ self._is_polymarket = (
+ hasattr(config, 'competition_type') and
+ config.competition_type == CompetitionType.POLYMARKET
+ )
# Guardrails
mode_str = config.mode if isinstance(config.mode, str) else config.mode.value
@@ -104,16 +120,30 @@ class AlphaArenaCompetition:
logger.info(f"API keys available for providers: {list(api_keys.keys())}")
# Initialize market data provider with timeout
- try:
- self._market_provider = await asyncio.wait_for(
- get_market_data_provider(self.config.exchange_id),
- timeout=30.0
- )
- logger.info(f"Market data provider initialized for {self.config.exchange_id}")
- except asyncio.TimeoutError:
- logger.error(f"Market data provider initialization timed out for {self.config.exchange_id}")
- self.status = CompetitionStatus.FAILED
- return False
+ if self._is_polymarket:
+ # Polymarket mode - use Polymarket provider
+ try:
+ self._polymarket_provider = await asyncio.wait_for(
+ get_polymarket_provider(),
+ timeout=30.0
+ )
+ logger.info("Polymarket data provider initialized")
+ except asyncio.TimeoutError:
+ logger.error("Polymarket data provider initialization timed out")
+ self.status = CompetitionStatus.FAILED
+ return False
+ else:
+ # Crypto mode - use exchange provider
+ try:
+ self._market_provider = await asyncio.wait_for(
+ get_market_data_provider(self.config.exchange_id),
+ timeout=30.0
+ )
+ logger.info(f"Market data provider initialized for {self.config.exchange_id}")
+ except asyncio.TimeoutError:
+ logger.error(f"Market data provider initialization timed out for {self.config.exchange_id}")
+ self.status = CompetitionStatus.FAILED
+ return False
# Auto-assign contrasting trading styles to models without explicit styles
_STYLE_ROTATION = [
@@ -274,6 +304,14 @@ class AlphaArenaCompetition:
)
try:
+ # Branch based on competition type
+ if self._is_polymarket:
+ # Polymarket mode - run prediction market cycle
+ async for response in self._run_polymarket_cycle(cycle_number, cycle_start):
+ yield response
+ return
+
+ # Crypto mode - original logic
# Fetch market data
symbol = self.config.symbols[0] if self.config.symbols else "BTC/USD"
@@ -557,6 +595,294 @@ class AlphaArenaCompetition:
"leaderboard": [e.model_dump() for e in self.get_leaderboard()],
}
+ # =========================================================================
+ # Polymarket Cycle Execution
+ # =========================================================================
+
+ async def _run_polymarket_cycle(
+ self,
+ cycle_number: int,
+ cycle_start: float
+ ) -> AsyncGenerator[StreamResponse, None]:
+ """
+ Run a single Polymarket prediction market cycle.
+
+ Similar to crypto cycle but uses Polymarket markets instead of crypto prices.
+ """
+ logger.info(f"Running Polymarket cycle {cycle_number}")
+
+ # Ensure Polymarket provider is initialized
+ if self._polymarket_provider is None:
+ yield error("Polymarket data provider not initialized")
+ return
+
+ # Get market IDs from config
+ market_ids = []
+ if self.config.polymarket_market_ids:
+ market_ids = self.config.polymarket_market_ids
+ elif self.config.polymarket_markets:
+ market_ids = [m.id for m in self.config.polymarket_markets]
+
+ if not market_ids:
+ yield error("No Polymarket markets configured for this competition")
+ return
+
+ try:
+ # Fetch current market data
+ markets = await self._polymarket_provider.get_markets(market_ids)
+
+ # Check for market resolutions
+ await self._check_market_resolutions(markets)
+
+ # Fetch live prices from CLOB API for more accurate data
+ all_token_ids = []
+ token_to_market = {} # token_id -> (market_id, outcome_index)
+ for m_id, m_info in markets.items():
+ for idx, token_id in enumerate(m_info.token_ids):
+ all_token_ids.append(token_id)
+ token_to_market[token_id] = (m_id, idx)
+
+ if all_token_ids:
+ try:
+ live_prices = await self._polymarket_provider.get_live_prices(all_token_ids)
+ for token_id, live_price in live_prices.items():
+ if token_id in token_to_market:
+ m_id, idx = token_to_market[token_id]
+ if idx < len(markets[m_id].outcome_prices):
+ markets[m_id].outcome_prices[idx] = live_price
+ logger.info(f"Updated {len(live_prices)} live prices from CLOB API")
+ except Exception as e:
+ logger.warning(f"Live price fetch failed (using Gamma prices): {e}")
+
+ # Emit market data for each market
+ for market_id, market_info in markets.items():
+ yes_price = market_info.outcome_prices[0] if market_info.outcome_prices else 0.5
+ yield market_data_response(
+ symbol=market_info.question[:30] if market_info.question else market_id[:8],
+ price=yes_price,
+ change_pct=0.0,
+ )
+
+ # Get decisions from each agent
+ decisions: Dict[str, List[PolymarketDecision]] = {}
+ errors_list: List[str] = []
+
+ for model_name, agent in self._agents.items():
+ engine = self._engines[model_name]
+
+ # Build portfolio state (using market IDs as pseudo-symbols)
+ prices = {m_id: markets[m_id].outcome_prices[0] for m_id in markets}
+ portfolio = engine.get_portfolio_state(prices)
+
+ yield decision_started(model_name, "POLYMARKET")
+
+ try:
+ # Build Polymarket-specific prompt context
+ market_context = self._build_polymarket_context(markets)
+
+ # Include existing positions in context
+ pm_positions = engine.get_polymarket_positions()
+ if pm_positions:
+ pos_lines = ["\nYOUR CURRENT POSITIONS:"]
+ for p in pm_positions:
+ edge = p.get("current_price", 0) - p.get("avg_price", 0)
+ pos_lines.append(
+ f" {p.get('market_question', '')[:50]} | "
+ f"{p.get('outcome', '')} {p.get('shares', 0):.1f} shares "
+ f"@ ${p.get('avg_price', 0):.4f} (now ${p.get('current_price', 0):.4f}, "
+ f"P&L: ${p.get('unrealized_pnl', 0):+.2f})"
+ )
+ market_context += "\n".join(pos_lines)
+
+ # Get decision from agent with Polymarket context
+ raw_decision = await agent.make_polymarket_decision(
+ markets=list(markets.values()),
+ portfolio=portfolio,
+ cycle_number=cycle_number,
+ context=market_context,
+ )
+
+ # Process and execute each decision
+ if raw_decision:
+ decisions[model_name] = raw_decision
+
+ for pm_decision in raw_decision:
+ pm_decision.competition_id = self.competition_id
+
+ # Emit reasoning
+ if pm_decision.reasoning:
+ yield reasoning(model_name, pm_decision.reasoning)
+
+ # Execute trade through paper trading bridge
+ action_val = pm_decision.action.value if hasattr(pm_decision.action, 'value') else str(pm_decision.action)
+ if action_val != "hold":
+ market_info = markets.get(pm_decision.market_id)
+ if market_info:
+ trade_result = engine.execute_polymarket_decision(
+ decision=pm_decision,
+ market=market_info,
+ max_exposure_pct=0.25,
+ )
+
+ # Emit trade execution
+ if trade_result.status == "executed":
+ yield trade_executed(
+ model_name=model_name,
+ action=action_val,
+ symbol=f"{trade_result.outcome}@{pm_decision.market_question[:30]}",
+ quantity=trade_result.shares,
+ price=trade_result.price,
+ pnl=trade_result.pnl,
+ )
+
+ # Emit decision
+ yield decision_completed(
+ model_name=model_name,
+ action=action_val,
+ symbol=pm_decision.market_id[:16],
+ quantity=pm_decision.amount_usd,
+ confidence=pm_decision.confidence,
+ reasoning=pm_decision.reasoning,
+ )
+
+ except Exception as agent_error:
+ logger.error(f"Agent {model_name} error in Polymarket cycle: {agent_error}")
+ errors_list.append(f"{model_name}: {agent_error}")
+
+ # Update positions with live prices
+ price_updates = {}
+ for m_id, m_info in markets.items():
+ yes_p = m_info.outcome_prices[0] if m_info.outcome_prices else 0.5
+ no_p = m_info.outcome_prices[1] if len(m_info.outcome_prices) > 1 else (1 - yes_p)
+ price_updates[m_id] = {"YES": yes_p, "NO": no_p}
+ engine.update_polymarket_prices(price_updates)
+
+ # Emit portfolio update with positions
+ pm_state = engine.get_polymarket_portfolio_state()
+ pm_pos_list = pm_state.get("positions", [])
+ yield portfolio_update(
+ model_name=model_name,
+ portfolio_value=pm_state.get("portfolio_value", 0),
+ cash=pm_state.get("cash", 0),
+ total_pnl=pm_state.get("total_pnl", 0),
+ positions=[
+ {
+ "symbol": f"{p.get('outcome', '')}@{p.get('market_question', '')[:30]}",
+ "side": "long",
+ "quantity": p.get("shares", 0),
+ "entry_price": p.get("avg_price", 0),
+ "current_price": p.get("current_price", 0),
+ "unrealized_pnl": p.get("unrealized_pnl", 0),
+ }
+ for p in pm_pos_list
+ ],
+ trades_count=pm_state.get("trades_count", 0),
+ cycle_number=cycle_number,
+ )
+
+ # Create snapshots for Polymarket
+ for model_name, engine in self._engines.items():
+ pm_state = engine.get_polymarket_portfolio_state()
+ snapshot = PerformanceSnapshot(
+ id=generate_snapshot_id(self.competition_id, model_name, cycle_number),
+ competition_id=self.competition_id,
+ cycle_number=cycle_number,
+ model_name=model_name,
+ portfolio_value=pm_state.get("portfolio_value", self.config.initial_capital),
+ cash=pm_state.get("cash", self.config.initial_capital),
+ pnl=pm_state.get("total_pnl", 0),
+ return_pct=((pm_state.get("portfolio_value", self.config.initial_capital) / self.config.initial_capital) - 1) * 100,
+ positions_count=len(pm_state.get("positions", [])),
+ trades_count=pm_state.get("trades_count", 0),
+ )
+ self._snapshots.append(snapshot)
+
+ # Calculate and emit leaderboard using Polymarket portfolio states
+ pm_leaderboard = self._calculate_polymarket_leaderboard()
+ yield leaderboard_update(
+ leaderboard=[e.model_dump() for e in pm_leaderboard],
+ cycle_number=cycle_number,
+ )
+
+ # Emit cycle completed
+ cycle_time = time.time() - cycle_start
+ yield cycle_completed(
+ cycle_number=cycle_number,
+ cycle_time=cycle_time,
+ decisions_count=sum(len(d) for d in decisions.values()),
+ errors=errors_list,
+ )
+
+ except Exception as e:
+ logger.exception(f"Polymarket cycle error: {e}")
+ yield error(f"Cycle error: {str(e)}")
+
+ def _calculate_polymarket_leaderboard(self) -> List[LeaderboardEntry]:
+ """Calculate leaderboard using Polymarket portfolio states."""
+ entries = []
+ for model_name, engine in self._engines.items():
+ pm_state = engine.get_polymarket_portfolio_state()
+ pv = pm_state.get("portfolio_value", self.config.initial_capital)
+ return_pct = ((pv / self.config.initial_capital) - 1) * 100
+
+ entries.append(LeaderboardEntry(
+ rank=0,
+ model_name=model_name,
+ portfolio_value=pv,
+ total_pnl=pm_state.get("total_pnl", 0),
+ return_pct=return_pct,
+ trades_count=pm_state.get("trades_count", 0),
+ cash=pm_state.get("cash", 0),
+ positions_count=len(pm_state.get("positions", [])),
+ ))
+
+ entries.sort(key=lambda x: x.portfolio_value, reverse=True)
+ for i, entry in enumerate(entries):
+ entry.rank = i + 1
+ return entries
+
+ async def _check_market_resolutions(self, markets: Dict[str, PolymarketInfo]):
+ """Check if any markets have resolved and settle positions."""
+ for market_id, info in markets.items():
+ # A market is resolved when one outcome price is very close to 1.0
+ if not info.outcome_prices:
+ continue
+ yes_price = info.outcome_prices[0]
+ no_price = info.outcome_prices[1] if len(info.outcome_prices) > 1 else (1 - yes_price)
+
+ resolved = False
+ winning_outcome = ""
+ if yes_price >= 0.99:
+ resolved = True
+ winning_outcome = "YES"
+ elif no_price >= 0.99:
+ resolved = True
+ winning_outcome = "NO"
+
+ if resolved:
+ logger.info(f"Market {market_id} resolved: {winning_outcome}")
+ for model_name, engine in self._engines.items():
+ pnl = engine.resolve_market(market_id, winning_outcome)
+ if pnl != 0:
+ logger.info(f"{model_name} resolution P&L for {market_id}: ${pnl:+.2f}")
+
+ def _build_polymarket_context(self, markets: Dict[str, PolymarketInfo]) -> str:
+ """Build context string for Polymarket agent decisions."""
+ lines = ["Current Prediction Markets:\n"]
+
+ for market_id, info in markets.items():
+ yes_price = info.outcome_prices[0] if info.outcome_prices else 0.5
+ no_price = info.outcome_prices[1] if len(info.outcome_prices) > 1 else (1 - yes_price)
+
+ lines.append(f"Market: {info.question}")
+ lines.append(f" YES: {yes_price*100:.1f}% | NO: {no_price*100:.1f}%")
+ lines.append(f" Volume: ${info.volume:,.0f} | Liquidity: ${info.liquidity:,.0f}")
+ if info.end_date:
+ lines.append(f" Ends: {info.end_date}")
+ lines.append("")
+
+ return "\n".join(lines)
+
# Competition registry
_competitions: Dict[str, AlphaArenaCompetition] = {}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py
index 4a47b751d..deb6d89af 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py
@@ -14,11 +14,15 @@ try:
except ImportError:
HTTPX_AVAILABLE = False
-from alpha_arena.types.models import MarketData
+from alpha_arena.types.models import MarketData, PolymarketInfo
from alpha_arena.utils.logging import get_logger
logger = get_logger("market_data")
+# Polymarket API endpoints
+POLYMARKET_GAMMA_API = "https://gamma-api.polymarket.com"
+POLYMARKET_CLOB_API = "https://clob.polymarket.com"
+
class MarketDataProvider:
"""
@@ -256,3 +260,191 @@ async def reset_market_data_provider():
logger.warning(f"Error closing market data provider: {e}")
_provider = None
logger.info("Market data provider reset")
+
+
+# =============================================================================
+# Polymarket Data Provider
+# =============================================================================
+
+class PolymarketDataProvider:
+ """
+ Async Polymarket data provider using httpx.
+
+ Fetches prediction market data from Polymarket's Gamma and CLOB APIs.
+ """
+
+ def __init__(self, timeout: float = 10.0):
+ self.timeout = timeout
+ self._client: Optional[Any] = None
+ self._cache: Dict[str, PolymarketInfo] = {}
+ self._cache_ttl = 5 # seconds
+ self._last_fetch: Dict[str, datetime] = {}
+
+ async def __aenter__(self):
+ await self.initialize()
+ return self
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
+ await self.close()
+
+ async def initialize(self):
+ """Initialize the HTTP client."""
+ if HTTPX_AVAILABLE:
+ self._client = httpx.AsyncClient(timeout=self.timeout)
+ logger.info("Polymarket data provider initialized")
+
+ async def close(self):
+ """Close the HTTP client."""
+ if self._client:
+ await self._client.aclose()
+ self._client = None
+
+ async def get_market(self, market_id: str) -> PolymarketInfo:
+ """
+ Get current data for a Polymarket market.
+
+ Args:
+ market_id: Polymarket market ID (condition_id)
+
+ Returns:
+ PolymarketInfo with current prices and metadata
+ """
+ # Check cache first
+ if market_id in self._cache and market_id in self._last_fetch:
+ age = (datetime.now() - self._last_fetch[market_id]).total_seconds()
+ if age < self._cache_ttl:
+ return self._cache[market_id]
+
+ if not HTTPX_AVAILABLE:
+ raise RuntimeError("httpx is not installed")
+ if not self._client:
+ raise RuntimeError("HTTP client not initialized")
+
+ try:
+ # Fetch from Gamma API
+ url = f"{POLYMARKET_GAMMA_API}/markets/{market_id}"
+ response = await self._client.get(url)
+ data = response.json()
+
+ # Parse outcomes and prices
+ outcomes = ["Yes", "No"]
+ outcome_prices = [0.5, 0.5]
+ token_ids = []
+
+ if "outcomes" in data:
+ raw_outcomes = data["outcomes"]
+ if isinstance(raw_outcomes, str):
+ import json
+ outcomes = json.loads(raw_outcomes)
+ elif isinstance(raw_outcomes, list):
+ outcomes = raw_outcomes
+
+ if "outcomePrices" in data:
+ raw_prices = data["outcomePrices"]
+ if isinstance(raw_prices, str):
+ import json
+ outcome_prices = [float(p) for p in json.loads(raw_prices)]
+ elif isinstance(raw_prices, list):
+ outcome_prices = [float(p) for p in raw_prices]
+
+ if "clobTokenIds" in data:
+ raw_tokens = data["clobTokenIds"]
+ if isinstance(raw_tokens, str):
+ import json
+ token_ids = json.loads(raw_tokens)
+ elif isinstance(raw_tokens, list):
+ token_ids = raw_tokens
+
+ market_info = PolymarketInfo(
+ id=market_id,
+ question=data.get("question", "Unknown"),
+ description=data.get("description"),
+ outcomes=outcomes,
+ outcome_prices=outcome_prices,
+ token_ids=token_ids,
+ volume=float(data.get("volumeNum", data.get("volume", 0)) or 0),
+ liquidity=float(data.get("liquidityNum", data.get("liquidity", 0)) or 0),
+ end_date=data.get("endDate"),
+ category=data.get("tags", [{}])[0].get("label") if data.get("tags") else None,
+ )
+
+ self._cache[market_id] = market_info
+ self._last_fetch[market_id] = datetime.now()
+ return market_info
+
+ except Exception as e:
+ logger.error(f"Polymarket fetch error for {market_id}: {e}")
+ raise RuntimeError(f"Failed to fetch market {market_id}: {e}") from e
+
+ async def get_markets(self, market_ids: List[str]) -> Dict[str, PolymarketInfo]:
+ """Get data for multiple markets."""
+ results = {}
+ errors = []
+ for market_id in market_ids:
+ try:
+ results[market_id] = await self.get_market(market_id)
+ except Exception as e:
+ logger.error(f"Failed to fetch {market_id}: {e}")
+ errors.append(f"{market_id}: {e}")
+ if errors and not results:
+ raise RuntimeError(f"Failed to fetch any markets: {'; '.join(errors)}")
+ return results
+
+ async def get_live_prices(self, token_ids: List[str]) -> Dict[str, float]:
+ """
+ Fetch live prices from CLOB API for given token IDs.
+
+ Returns dict of token_id -> price
+ """
+ if not token_ids:
+ return {}
+
+ if not HTTPX_AVAILABLE or not self._client:
+ return {}
+
+ try:
+ # CLOB prices endpoint
+ url = f"{POLYMARKET_CLOB_API}/prices"
+ params = {"token_ids": ",".join(token_ids)}
+ response = await self._client.get(url, params=params)
+ data = response.json()
+
+ prices = {}
+ for token_id, price_data in data.items():
+ if isinstance(price_data, dict) and "price" in price_data:
+ prices[token_id] = float(price_data["price"])
+ elif isinstance(price_data, (int, float, str)):
+ prices[token_id] = float(price_data)
+
+ return prices
+
+ except Exception as e:
+ logger.warning(f"Failed to fetch live prices: {e}")
+ return {}
+
+
+# Singleton instance for Polymarket
+_polymarket_provider: Optional[PolymarketDataProvider] = None
+
+
+async def get_polymarket_provider() -> PolymarketDataProvider:
+ """Get or create the Polymarket data provider."""
+ global _polymarket_provider
+
+ if _polymarket_provider is None:
+ _polymarket_provider = PolymarketDataProvider()
+ await _polymarket_provider.initialize()
+
+ return _polymarket_provider
+
+
+async def reset_polymarket_provider():
+ """Reset the Polymarket data provider singleton."""
+ global _polymarket_provider
+ if _polymarket_provider:
+ try:
+ await _polymarket_provider.close()
+ except Exception as e:
+ logger.warning(f"Error closing Polymarket provider: {e}")
+ _polymarket_provider = None
+ logger.info("Polymarket data provider reset")
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading_bridge.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading_bridge.py
index a22123dac..9dc268f64 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading_bridge.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading_bridge.py
@@ -20,6 +20,10 @@ from alpha_arena.types.models import (
ModelDecision,
TradeAction,
TradeResult,
+ PolymarketDecision,
+ PolymarketAction,
+ PolymarketTradeResult,
+ PolymarketInfo,
)
logger = get_logger("paper_trading_bridge")
@@ -271,6 +275,45 @@ class PaperTradingBridge:
CREATE INDEX IF NOT EXISTS idx_orders_portfolio ON pt_orders(portfolio_id);
CREATE INDEX IF NOT EXISTS idx_positions_portfolio ON pt_positions(portfolio_id);
CREATE INDEX IF NOT EXISTS idx_trades_portfolio ON pt_trades(portfolio_id);
+
+ -- Polymarket positions table
+ CREATE TABLE IF NOT EXISTS pt_polymarket_positions (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ market_id TEXT NOT NULL,
+ market_question TEXT NOT NULL,
+ outcome TEXT NOT NULL,
+ shares REAL NOT NULL,
+ avg_price REAL NOT NULL,
+ current_price REAL NOT NULL,
+ unrealized_pnl REAL DEFAULT 0,
+ realized_pnl REAL DEFAULT 0,
+ opened_at TEXT NOT NULL,
+ resolved INTEGER DEFAULT 0,
+ resolution_outcome TEXT,
+ FOREIGN KEY (portfolio_id) REFERENCES pt_portfolios(id),
+ UNIQUE(portfolio_id, market_id, outcome)
+ );
+
+ -- Polymarket trades table
+ CREATE TABLE IF NOT EXISTS pt_polymarket_trades (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ market_id TEXT NOT NULL,
+ market_question TEXT NOT NULL,
+ action TEXT NOT NULL,
+ outcome TEXT NOT NULL,
+ shares REAL NOT NULL,
+ price REAL NOT NULL,
+ cost REAL NOT NULL,
+ fee REAL NOT NULL,
+ pnl REAL DEFAULT 0,
+ timestamp TEXT NOT NULL,
+ FOREIGN KEY (portfolio_id) REFERENCES pt_portfolios(id)
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_pm_positions_portfolio ON pt_polymarket_positions(portfolio_id);
+ CREATE INDEX IF NOT EXISTS idx_pm_trades_portfolio ON pt_polymarket_trades(portfolio_id);
""")
def _initialize_portfolio(self):
@@ -1008,6 +1051,506 @@ class PaperTradingBridge:
)
+ def _ensure_polymarket_tables(self):
+ """Ensure Polymarket-specific tables exist."""
+ conn = get_connection()
+ try:
+ cursor = conn.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='pt_polymarket_positions'"
+ )
+ if not cursor.fetchone():
+ conn.executescript("""
+ CREATE TABLE IF NOT EXISTS pt_polymarket_positions (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ market_id TEXT NOT NULL,
+ market_question TEXT NOT NULL,
+ outcome TEXT NOT NULL,
+ shares REAL NOT NULL,
+ avg_price REAL NOT NULL,
+ current_price REAL NOT NULL,
+ unrealized_pnl REAL DEFAULT 0,
+ realized_pnl REAL DEFAULT 0,
+ opened_at TEXT NOT NULL,
+ resolved INTEGER DEFAULT 0,
+ resolution_outcome TEXT,
+ FOREIGN KEY (portfolio_id) REFERENCES pt_portfolios(id),
+ UNIQUE(portfolio_id, market_id, outcome)
+ );
+
+ CREATE TABLE IF NOT EXISTS pt_polymarket_trades (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ market_id TEXT NOT NULL,
+ market_question TEXT NOT NULL,
+ action TEXT NOT NULL,
+ outcome TEXT NOT NULL,
+ shares REAL NOT NULL,
+ price REAL NOT NULL,
+ cost REAL NOT NULL,
+ fee REAL NOT NULL,
+ pnl REAL DEFAULT 0,
+ timestamp TEXT NOT NULL,
+ FOREIGN KEY (portfolio_id) REFERENCES pt_portfolios(id)
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_pm_positions_portfolio ON pt_polymarket_positions(portfolio_id);
+ CREATE INDEX IF NOT EXISTS idx_pm_trades_portfolio ON pt_polymarket_trades(portfolio_id);
+ """)
+ conn.commit()
+ finally:
+ conn.close()
+
+ def get_polymarket_positions(self) -> List[Dict[str, Any]]:
+ """Get all open Polymarket positions."""
+ if not self.portfolio_id:
+ return []
+
+ self._ensure_polymarket_tables()
+ conn = get_connection()
+ try:
+ cursor = conn.execute(
+ """SELECT id, portfolio_id, market_id, market_question, outcome,
+ shares, avg_price, current_price, unrealized_pnl,
+ realized_pnl, opened_at, resolved, resolution_outcome
+ FROM pt_polymarket_positions
+ WHERE portfolio_id = ? AND resolved = 0""",
+ (self.portfolio_id,)
+ )
+ return [dict(row) for row in cursor.fetchall()]
+ finally:
+ conn.close()
+
+ def get_polymarket_trades(self, limit: int = 100) -> List[Dict[str, Any]]:
+ """Get recent Polymarket trades."""
+ if not self.portfolio_id:
+ return []
+
+ self._ensure_polymarket_tables()
+ conn = get_connection()
+ try:
+ cursor = conn.execute(
+ """SELECT id, portfolio_id, market_id, market_question, action,
+ outcome, shares, price, cost, fee, pnl, timestamp
+ FROM pt_polymarket_trades
+ WHERE portfolio_id = ?
+ ORDER BY timestamp DESC
+ LIMIT ?""",
+ (self.portfolio_id, limit)
+ )
+ return [dict(row) for row in cursor.fetchall()]
+ finally:
+ conn.close()
+
+ def execute_polymarket_decision(
+ self,
+ decision: PolymarketDecision,
+ market: PolymarketInfo,
+ max_exposure_pct: float = 0.25,
+ ) -> PolymarketTradeResult:
+ """
+ Execute a Polymarket trading decision.
+
+ Shares are priced between $0 and $1. Buying YES at $0.60 means
+ paying $0.60 per share; if the event resolves YES, each share pays $1.
+
+ Args:
+ decision: The Polymarket decision to execute
+ market: Current market data
+ max_exposure_pct: Max portfolio % per market (risk guardrail)
+
+ Returns:
+ PolymarketTradeResult with execution details
+ """
+ self._ensure_polymarket_tables()
+
+ action = decision.action
+ if isinstance(action, str):
+ try:
+ action = PolymarketAction(action.lower())
+ except ValueError:
+ return PolymarketTradeResult(
+ status="rejected",
+ market_id=decision.market_id,
+ action=PolymarketAction.HOLD,
+ outcome="",
+ shares=0,
+ price=0,
+ cost=0,
+ reason=f"Invalid action: {action}",
+ )
+
+ # HOLD
+ if action == PolymarketAction.HOLD:
+ return PolymarketTradeResult(
+ status="executed",
+ market_id=decision.market_id,
+ action=PolymarketAction.HOLD,
+ outcome="",
+ shares=0,
+ price=0,
+ cost=0,
+ reason="Hold - no trade",
+ )
+
+ portfolio = self.get_portfolio()
+ if not portfolio:
+ return PolymarketTradeResult(
+ status="rejected",
+ market_id=decision.market_id,
+ action=action,
+ outcome="",
+ shares=0,
+ price=0,
+ cost=0,
+ reason="Portfolio not initialized",
+ )
+
+ # Determine outcome and price
+ is_buy = action in (PolymarketAction.BUY_YES, PolymarketAction.BUY_NO)
+ if action in (PolymarketAction.BUY_YES, PolymarketAction.SELL_YES):
+ outcome = "YES"
+ price = market.outcome_prices[0] if market.outcome_prices else 0.5
+ else:
+ outcome = "NO"
+ price = market.outcome_prices[1] if len(market.outcome_prices) > 1 else 0.5
+
+ amount_usd = decision.amount_usd or 0
+ if amount_usd <= 0 and is_buy:
+ return PolymarketTradeResult(
+ status="rejected",
+ market_id=decision.market_id,
+ action=action,
+ outcome=outcome,
+ shares=0,
+ price=price,
+ cost=0,
+ reason="Amount must be > 0 for buy",
+ )
+
+ # Risk guardrail: max exposure per market
+ max_exposure = portfolio.balance * max_exposure_pct
+ if is_buy and amount_usd > max_exposure:
+ amount_usd = max_exposure
+ logger.warning(
+ f"Capped {decision.model_name} exposure on {decision.market_id} "
+ f"to ${max_exposure:.2f} ({max_exposure_pct:.0%} of portfolio)"
+ )
+
+ # Liquidity check
+ if market.liquidity > 0 and amount_usd > market.liquidity * 0.1:
+ amount_usd = min(amount_usd, market.liquidity * 0.1)
+ logger.warning(f"Capped trade to 10% of market liquidity: ${amount_usd:.2f}")
+
+ now = datetime.utcnow().isoformat() + "Z"
+ fee = amount_usd * self.fee_rate
+ conn = get_connection()
+
+ try:
+ if is_buy:
+ # Calculate shares: amount / price
+ shares = amount_usd / price if price > 0 else 0
+ total_cost = amount_usd + fee
+
+ if total_cost > portfolio.balance:
+ return PolymarketTradeResult(
+ status="rejected",
+ market_id=decision.market_id,
+ action=action,
+ outcome=outcome,
+ shares=0,
+ price=price,
+ cost=0,
+ reason=f"Insufficient funds: need ${total_cost:.2f}, have ${portfolio.balance:.2f}",
+ )
+
+ # Update or create position
+ cursor = conn.execute(
+ """SELECT id, shares, avg_price FROM pt_polymarket_positions
+ WHERE portfolio_id = ? AND market_id = ? AND outcome = ? AND resolved = 0""",
+ (self.portfolio_id, decision.market_id, outcome)
+ )
+ existing = cursor.fetchone()
+
+ if existing:
+ new_shares = existing["shares"] + shares
+ new_avg = (existing["avg_price"] * existing["shares"] + price * shares) / new_shares
+ conn.execute(
+ """UPDATE pt_polymarket_positions
+ SET shares = ?, avg_price = ?, current_price = ?
+ WHERE id = ?""",
+ (new_shares, new_avg, price, existing["id"])
+ )
+ else:
+ pos_id = str(uuid.uuid4())
+ conn.execute(
+ """INSERT INTO pt_polymarket_positions
+ (id, portfolio_id, market_id, market_question, outcome, shares,
+ avg_price, current_price, unrealized_pnl, realized_pnl, opened_at, resolved)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, 0)""",
+ (pos_id, self.portfolio_id, decision.market_id,
+ decision.market_question, outcome, shares, price, price, now)
+ )
+
+ # Deduct from balance
+ conn.execute(
+ "UPDATE pt_portfolios SET balance = balance - ? WHERE id = ?",
+ (total_cost, self.portfolio_id)
+ )
+
+ # Record trade
+ trade_id = str(uuid.uuid4())
+ conn.execute(
+ """INSERT INTO pt_polymarket_trades
+ (id, portfolio_id, market_id, market_question, action, outcome,
+ shares, price, cost, fee, pnl, timestamp)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)""",
+ (trade_id, self.portfolio_id, decision.market_id,
+ decision.market_question, action.value, outcome,
+ shares, price, total_cost, fee, now)
+ )
+
+ conn.commit()
+ logger.info(
+ f"{self.model_name}: {action.value.upper()} {shares:.2f} {outcome} shares "
+ f"@ ${price:.4f} for ${total_cost:.2f} (market: {decision.market_question[:50]})"
+ )
+
+ return PolymarketTradeResult(
+ status="executed",
+ market_id=decision.market_id,
+ action=action,
+ outcome=outcome,
+ shares=shares,
+ price=price,
+ cost=total_cost,
+ pnl=0,
+ )
+
+ else:
+ # SELL - close/reduce position
+ cursor = conn.execute(
+ """SELECT id, shares, avg_price FROM pt_polymarket_positions
+ WHERE portfolio_id = ? AND market_id = ? AND outcome = ? AND resolved = 0""",
+ (self.portfolio_id, decision.market_id, outcome)
+ )
+ existing = cursor.fetchone()
+
+ if not existing or existing["shares"] <= 0:
+ return PolymarketTradeResult(
+ status="rejected",
+ market_id=decision.market_id,
+ action=action,
+ outcome=outcome,
+ shares=0,
+ price=price,
+ cost=0,
+ reason=f"No {outcome} position to sell",
+ )
+
+ # Sell shares based on amount_usd or all
+ if amount_usd > 0:
+ sell_shares = min(amount_usd / price, existing["shares"]) if price > 0 else existing["shares"]
+ else:
+ sell_shares = existing["shares"]
+
+ proceeds = sell_shares * price
+ pnl = (price - existing["avg_price"]) * sell_shares
+ net_proceeds = proceeds - fee
+
+ # Update position
+ remaining = existing["shares"] - sell_shares
+ if remaining <= 0.0001:
+ conn.execute("DELETE FROM pt_polymarket_positions WHERE id = ?", (existing["id"],))
+ else:
+ conn.execute(
+ """UPDATE pt_polymarket_positions
+ SET shares = ?, current_price = ?, realized_pnl = realized_pnl + ?
+ WHERE id = ?""",
+ (remaining, price, pnl, existing["id"])
+ )
+
+ # Add proceeds to balance
+ conn.execute(
+ "UPDATE pt_portfolios SET balance = balance + ? WHERE id = ?",
+ (net_proceeds, self.portfolio_id)
+ )
+
+ # Record trade
+ trade_id = str(uuid.uuid4())
+ conn.execute(
+ """INSERT INTO pt_polymarket_trades
+ (id, portfolio_id, market_id, market_question, action, outcome,
+ shares, price, cost, fee, pnl, timestamp)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ (trade_id, self.portfolio_id, decision.market_id,
+ decision.market_question, action.value, outcome,
+ sell_shares, price, net_proceeds, fee, pnl, now)
+ )
+
+ conn.commit()
+ logger.info(
+ f"{self.model_name}: {action.value.upper()} {sell_shares:.2f} {outcome} shares "
+ f"@ ${price:.4f} P&L: ${pnl:+.2f}"
+ )
+
+ return PolymarketTradeResult(
+ status="executed",
+ market_id=decision.market_id,
+ action=action,
+ outcome=outcome,
+ shares=sell_shares,
+ price=price,
+ cost=net_proceeds,
+ pnl=pnl,
+ )
+
+ except Exception as e:
+ logger.error(f"Polymarket execution error: {e}")
+ conn.rollback()
+ return PolymarketTradeResult(
+ status="rejected",
+ market_id=decision.market_id,
+ action=action,
+ outcome=outcome,
+ shares=0,
+ price=price,
+ cost=0,
+ reason=f"Execution error: {str(e)}",
+ )
+ finally:
+ conn.close()
+
+ def resolve_market(self, market_id: str, winning_outcome: str) -> float:
+ """
+ Resolve a Polymarket market. Winning shares pay $1 each, losing shares pay $0.
+
+ Args:
+ market_id: The market ID to resolve
+ winning_outcome: "YES" or "NO"
+
+ Returns:
+ Total P&L from resolution
+ """
+ self._ensure_polymarket_tables()
+ conn = get_connection()
+ total_pnl = 0.0
+
+ try:
+ cursor = conn.execute(
+ """SELECT id, outcome, shares, avg_price
+ FROM pt_polymarket_positions
+ WHERE portfolio_id = ? AND market_id = ? AND resolved = 0""",
+ (self.portfolio_id, market_id)
+ )
+ positions = cursor.fetchall()
+ now = datetime.utcnow().isoformat() + "Z"
+
+ for pos in positions:
+ is_winner = pos["outcome"] == winning_outcome
+ settlement_price = 1.0 if is_winner else 0.0
+ pnl = (settlement_price - pos["avg_price"]) * pos["shares"]
+ total_pnl += pnl
+
+ # Credit winning positions
+ if is_winner:
+ proceeds = pos["shares"] * 1.0 # $1 per share
+ conn.execute(
+ "UPDATE pt_portfolios SET balance = balance + ? WHERE id = ?",
+ (proceeds, self.portfolio_id)
+ )
+
+ # Mark as resolved
+ conn.execute(
+ """UPDATE pt_polymarket_positions
+ SET resolved = 1, resolution_outcome = ?,
+ current_price = ?, realized_pnl = realized_pnl + ?
+ WHERE id = ?""",
+ (winning_outcome, settlement_price, pnl, pos["id"])
+ )
+
+ # Record resolution trade
+ trade_id = str(uuid.uuid4())
+ conn.execute(
+ """INSERT INTO pt_polymarket_trades
+ (id, portfolio_id, market_id, market_question, action, outcome,
+ shares, price, cost, fee, pnl, timestamp)
+ VALUES (?, ?, ?, 'Resolution', 'resolution', ?, ?, ?, 0, 0, ?, ?)""",
+ (trade_id, self.portfolio_id, market_id,
+ pos["outcome"], pos["shares"], settlement_price, pnl, now)
+ )
+
+ conn.commit()
+ logger.info(f"Resolved market {market_id}: winner={winning_outcome}, P&L=${total_pnl:+.2f}")
+
+ except Exception as e:
+ logger.error(f"Market resolution error: {e}")
+ conn.rollback()
+ finally:
+ conn.close()
+
+ return total_pnl
+
+ def update_polymarket_prices(self, price_updates: Dict[str, Dict[str, float]]):
+ """
+ Update Polymarket position prices.
+
+ Args:
+ price_updates: {market_id: {"YES": price, "NO": price}}
+ """
+ self._ensure_polymarket_tables()
+ if not self.portfolio_id:
+ return
+
+ conn = get_connection()
+ try:
+ for market_id, prices in price_updates.items():
+ for outcome, price in prices.items():
+ conn.execute(
+ """UPDATE pt_polymarket_positions
+ SET current_price = ?,
+ unrealized_pnl = (? - avg_price) * shares
+ WHERE portfolio_id = ? AND market_id = ? AND outcome = ? AND resolved = 0""",
+ (price, price, self.portfolio_id, market_id, outcome)
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+ def get_polymarket_portfolio_state(self) -> Dict[str, Any]:
+ """Get portfolio state including Polymarket positions."""
+ portfolio = self.get_portfolio()
+ pm_positions = self.get_polymarket_positions()
+ pm_trades = self.get_polymarket_trades()
+
+ if not portfolio:
+ return {
+ "model_name": self.model_name,
+ "portfolio_value": self.initial_capital,
+ "cash": self.initial_capital,
+ "total_pnl": 0.0,
+ "unrealized_pnl": 0.0,
+ "trades_count": 0,
+ "positions": [],
+ }
+
+ total_unrealized = sum(p.get("unrealized_pnl", 0) for p in pm_positions)
+ total_realized = sum(t.get("pnl", 0) for t in pm_trades)
+ positions_value = sum(p.get("shares", 0) * p.get("current_price", 0) for p in pm_positions)
+
+ return {
+ "model_name": self.model_name,
+ "portfolio_value": portfolio.balance + positions_value,
+ "cash": portfolio.balance,
+ "total_pnl": total_realized + total_unrealized,
+ "unrealized_pnl": total_unrealized,
+ "realized_pnl": total_realized,
+ "trades_count": len(pm_trades),
+ "positions": pm_positions,
+ "positions_value": positions_value,
+ }
+
+
# Convenience function to create bridge for a model
def create_paper_trading_bridge(
competition_id: str,
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 8ac559940..fa94a78f7 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
@@ -36,6 +36,21 @@ class TradeAction(str, Enum):
SHORT = "short"
+class CompetitionType(str, Enum):
+ """Competition type - crypto or prediction markets."""
+ CRYPTO = "crypto"
+ POLYMARKET = "polymarket"
+
+
+class PolymarketAction(str, Enum):
+ """Possible Polymarket trading actions."""
+ BUY_YES = "buy_yes"
+ BUY_NO = "buy_no"
+ SELL_YES = "sell_yes"
+ SELL_NO = "sell_no"
+ HOLD = "hold"
+
+
class ModelProvider(str, Enum):
"""Supported LLM providers."""
OPENAI = "openai"
@@ -271,6 +286,26 @@ class CompetitionConfig(BaseModel):
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")
+ # Competition type - crypto or polymarket
+ competition_type: CompetitionType = Field(
+ CompetitionType.CRYPTO,
+ description="Competition type: crypto trading or prediction markets"
+ )
+
+ # Polymarket-specific config
+ polymarket_markets: Optional[List[PolymarketInfo]] = Field(
+ None,
+ description="Polymarket markets for prediction market competitions"
+ )
+ polymarket_market_ids: Optional[List[str]] = Field(
+ None,
+ description="Polymarket market IDs (alternative to full market info)"
+ )
+ polymarket_category: Optional[str] = Field(
+ None,
+ description="Filter markets by category"
+ )
+
class Config:
use_enum_values = True
@@ -312,3 +347,73 @@ class PerformanceSnapshot(BaseModel):
positions_count: int = Field(0, description="Open positions")
trades_count: int = Field(0, description="Total trades")
timestamp: datetime = Field(default_factory=datetime.now, description="Snapshot time")
+
+
+# =============================================================================
+# Polymarket-specific Models
+# =============================================================================
+
+class PolymarketInfo(BaseModel):
+ """Polymarket prediction market information."""
+
+ id: str = Field(..., description="Market ID")
+ question: str = Field(..., description="Market question")
+ description: Optional[str] = Field(None, description="Market description")
+ outcomes: List[str] = Field(default=["Yes", "No"], description="Outcome names")
+ outcome_prices: List[float] = Field(default=[0.5, 0.5], description="Current outcome prices (0-1)")
+ token_ids: List[str] = Field(default_factory=list, description="CLOB token IDs")
+ volume: float = Field(0.0, description="Total trading volume")
+ liquidity: float = Field(0.0, description="Current liquidity")
+ end_date: Optional[str] = Field(None, description="Resolution date")
+ category: Optional[str] = Field(None, description="Market category")
+
+
+class PolymarketPosition(BaseModel):
+ """Position in a Polymarket prediction market."""
+
+ market_id: str = Field(..., description="Market ID")
+ market_question: str = Field(..., description="Market question for display")
+ outcome_index: int = Field(..., description="Outcome index (0=Yes, 1=No, etc.)")
+ outcome_name: str = Field(..., description="Outcome name")
+ shares: float = Field(..., description="Number of shares held")
+ entry_price: float = Field(..., description="Average entry price")
+ current_price: float = Field(0.0, description="Current price")
+ unrealized_pnl: float = Field(0.0, description="Unrealized P&L")
+
+
+class PolymarketDecision(BaseModel):
+ """Trading decision for a Polymarket prediction market."""
+
+ competition_id: str = Field(..., description="Competition ID")
+ model_name: str = Field(..., description="Model that made the decision")
+ cycle_number: int = Field(..., ge=0, description="Cycle number")
+ market_id: str = Field(..., description="Polymarket market ID")
+ market_question: str = Field(..., description="Market question")
+ action: PolymarketAction = Field(..., description="Trading action")
+ amount_usd: float = Field(0.0, ge=0, description="Amount in USD to trade")
+ confidence: float = Field(0.5, ge=0.0, le=1.0, description="Decision confidence")
+ estimated_probability: float = Field(0.5, ge=0.0, le=1.0, description="Agent's probability estimate")
+ reasoning: str = Field("", description="Explanation for the decision")
+ timestamp: datetime = Field(default_factory=datetime.now, description="Decision time")
+
+ class Config:
+ use_enum_values = True
+
+
+class PolymarketTradeResult(BaseModel):
+ """Result of a Polymarket trade execution."""
+
+ status: str = Field(..., description="executed, rejected, or partial")
+ action: PolymarketAction = Field(..., description="Trade action taken")
+ market_id: str = Field(..., description="Market ID")
+ outcome: str = Field("", description="Outcome traded (YES/NO)")
+ shares: float = Field(0, description="Shares traded")
+ price: float = Field(0, description="Execution price")
+ cost: Optional[float] = Field(None, description="Total cost")
+ proceeds: Optional[float] = Field(None, description="Proceeds from sale")
+ pnl: Optional[float] = Field(None, description="Realized P&L")
+ reason: Optional[str] = Field(None, description="Rejection reason if failed")
+ timestamp: datetime = Field(default_factory=datetime.now, description="Execution time")
+
+ class Config:
+ use_enum_values = True
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/bcb_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/bcb_data.py
new file mode 100644
index 000000000..5ffeaaed1
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/bcb_data.py
@@ -0,0 +1,504 @@
+"""
+Banco Central do Brasil (BCB) Data Wrapper
+Fetches data from the BCB SGS (Sistema Gerenciador de Series Temporais) API.
+
+API Reference:
+ Base URL: https://api.bcb.gov.br/dados/serie/bcdata.sgs.{series_id}/dados
+ Format: JSON array [{data: "DD/MM/YYYY", valor: "N.NN"}, ...]
+ Auth: None required — fully public
+
+Endpoint patterns:
+ All data: GET /dados/serie/bcdata.sgs.{id}/dados?formato=json
+ Date range: GET /dados/serie/bcdata.sgs.{id}/dados?formato=json&dataInicial=DD/MM/YYYY&dataFinal=DD/MM/YYYY
+ Last N: GET /dados/serie/bcdata.sgs.{id}/dados/ultimos/{n}?formato=json
+ Multiple SGS: GET /dados/conjuntos/dados?codigoseries={id1},{id2}&formato=json
+
+Key series IDs (verified):
+ 432 — Selic target rate (% per year)
+ 11 — Selic daily rate
+ 433 — IPCA monthly inflation (%)
+ 189 — IGP-M monthly inflation (%)
+ 1 — USD/BRL exchange rate (PTAX selling)
+ 21619 — EUR/BRL exchange rate
+ 4192 — EUR/BRL (older series)
+ 7326 — GDP annual growth rate (%)
+ 27791 — M1 (currency + demand deposits, R$ thousands)
+ 28000 — M2 monetary aggregate
+ 29037 — M3 monetary aggregate
+ 24369 — Unemployment rate (PNAD) %
+ 20539 — Total credit outstanding (R$ millions)
+ 13621 — International reserves (USD millions)
+ 4189 — Primary fiscal surplus/deficit (R$ millions)
+ 7478 — Net public debt (% GDP)
+ 4390 — Trade balance (USD millions, monthly)
+ 22707 — Current account (USD millions)
+ 3541 — TJLP (long-term interest rate)
+ 226 — TR (referential rate)
+ 1178 — CDB 1-day rate
+ 7809 — Bovespa index (monthly avg)
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime, timezone
+
+
+BASE_URL = "https://api.bcb.gov.br/dados/serie/bcdata.sgs"
+MULTI_URL = "https://api.bcb.gov.br/dados/conjuntos/dados"
+DEFAULT_TIMEOUT = 30
+
+# ---------------------------------------------------------------------------
+# Series catalogue
+# ---------------------------------------------------------------------------
+
+SERIES = {
+ # Monetary policy
+ "selic_target": {"id": 432, "name": "Selic Target Rate", "category": "monetary_policy", "unit": "% p.a.", "freq": "daily"},
+ "selic_daily": {"id": 11, "name": "Selic Daily Rate", "category": "monetary_policy", "unit": "% p.a.", "freq": "daily"},
+ "tjlp": {"id": 3541, "name": "TJLP Long-Term Rate", "category": "monetary_policy", "unit": "% p.a.", "freq": "monthly"},
+ "tr": {"id": 226, "name": "TR Referential Rate", "category": "monetary_policy", "unit": "%", "freq": "monthly"},
+ # Inflation
+ "ipca": {"id": 433, "name": "IPCA Monthly Inflation", "category": "inflation", "unit": "%", "freq": "monthly"},
+ "igpm": {"id": 189, "name": "IGP-M Monthly Inflation", "category": "inflation", "unit": "%", "freq": "monthly"},
+ # Exchange rates
+ "usd_brl": {"id": 1, "name": "USD/BRL PTAX (selling)", "category": "exchange_rates", "unit": "BRL per USD", "freq": "daily"},
+ "eur_brl": {"id": 21619, "name": "EUR/BRL PTAX (selling)", "category": "exchange_rates", "unit": "BRL per EUR", "freq": "daily"},
+ # Monetary aggregates
+ "m1": {"id": 27791, "name": "M1 Monetary Aggregate", "category": "monetary", "unit": "R$ thousands","freq": "monthly"},
+ "m2": {"id": 28000, "name": "M2 Monetary Aggregate", "category": "monetary", "unit": "R$ thousands","freq": "monthly"},
+ "m3": {"id": 29037, "name": "M3 Monetary Aggregate", "category": "monetary", "unit": "R$ thousands","freq": "monthly"},
+ # GDP / real economy
+ "gdp_growth": {"id": 7326, "name": "GDP Annual Growth Rate", "category": "gdp", "unit": "%", "freq": "annual"},
+ "unemployment": {"id": 24369, "name": "Unemployment Rate (PNAD)", "category": "labour", "unit": "%", "freq": "monthly"},
+ # Credit
+ "credit_total": {"id": 20539, "name": "Total Credit Outstanding", "category": "credit", "unit": "R$ millions", "freq": "monthly"},
+ # External sector
+ "reserves": {"id": 13621, "name": "International Reserves", "category": "external", "unit": "USD millions","freq": "daily"},
+ "trade_balance": {"id": 4390, "name": "Trade Balance (monthly)", "category": "external", "unit": "USD millions","freq": "monthly"},
+ "current_account": {"id": 22707, "name": "Current Account Balance", "category": "external", "unit": "USD millions","freq": "monthly"},
+ # Fiscal
+ "primary_surplus": {"id": 4189, "name": "Primary Fiscal Surplus/Deficit","category": "fiscal", "unit": "R$ millions", "freq": "monthly"},
+ "net_public_debt": {"id": 7478, "name": "Net Public Debt (% GDP)", "category": "fiscal", "unit": "% GDP", "freq": "monthly"},
+ # Capital markets
+ "bovespa": {"id": 7809, "name": "Bovespa Index Monthly Avg", "category": "markets", "unit": "index", "freq": "monthly"},
+ "cdb_1d": {"id": 1178, "name": "CDB 1-Day Rate", "category": "interest_rates", "unit": "% p.a.", "freq": "daily"},
+}
+
+# Convenience groups
+GROUPS = {
+ "monetary_policy": ["selic_target", "selic_daily", "tjlp"],
+ "inflation": ["ipca", "igpm"],
+ "exchange_rates": ["usd_brl", "eur_brl"],
+ "monetary": ["m1", "m2", "m3"],
+ "external": ["reserves", "trade_balance", "current_account"],
+ "fiscal": ["primary_surplus", "net_public_debt"],
+ "overview": ["selic_target", "ipca", "usd_brl", "gdp_growth", "unemployment", "reserves"],
+}
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class BCBError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "BCBError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class BCBWrapper:
+ """
+ Wrapper for Banco Central do Brasil SGS (Time Series Management System).
+
+ The BCB SGS API returns JSON arrays: [{data: "DD/MM/YYYY", valor: "N.NN"}]
+ All series are accessible without authentication.
+ """
+
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Accept": "*/*",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _fetch_series(self, series_id: int, start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ last_n: Optional[int] = None) -> List[Dict]:
+ """
+ Fetch a single SGS series.
+ start_date/end_date: "DD/MM/YYYY" format
+ last_n: fetch only last N observations
+ """
+ if last_n:
+ url = f"{BASE_URL}.{series_id}/dados/ultimos/{last_n}"
+ else:
+ url = f"{BASE_URL}.{series_id}/dados"
+
+ params: Dict[str, str] = {"formato": "json"}
+ if start_date and not last_n:
+ params["dataInicial"] = start_date
+ if end_date and not last_n:
+ params["dataFinal"] = end_date
+
+ resp = self.session.get(url, params=params, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.json()
+
+ def _parse_rows(self, raw: List[Dict], series_name: str) -> List[Dict]:
+ rows = []
+ for item in raw:
+ date_str = item.get("data", "")
+ val_str = item.get("valor", "")
+ val = None
+ if val_str not in ("", None):
+ try:
+ val = float(str(val_str).replace(",", "."))
+ except ValueError:
+ val = val_str
+ rows.append({"date": date_str, series_name: val})
+ return rows
+
+ def _get_series(self, series_key: str, start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ last_n: Optional[int] = None) -> Dict[str, Any]:
+ info = SERIES.get(series_key)
+ if not info:
+ return {"success": False, "error": f"Unknown series key: {series_key}",
+ "available_series": list(SERIES.keys())}
+ sid = info["id"]
+ # Daily series require a date window (BCB enforces max 10-year window)
+ if info.get("freq") == "daily" and not start_date and not last_n:
+ from datetime import timedelta
+ start_date = (datetime.now(timezone.utc) - timedelta(days=5*365)).strftime("%d/%m/%Y")
+ try:
+ raw = self._fetch_series(sid, start_date, end_date, last_n)
+ rows = self._parse_rows(raw, series_key)
+ return {
+ "success": True,
+ "series": series_key,
+ "series_id": sid,
+ "name": info["name"],
+ "category": info["category"],
+ "unit": info["unit"],
+ "frequency": info["freq"],
+ "data": rows,
+ "count": len(rows),
+ "source": "Banco Central do Brasil",
+ "url": f"{BASE_URL}.{sid}/dados",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BCBError(series_key, str(e), sc).to_dict()
+ except Exception as e:
+ return BCBError(series_key, str(e)).to_dict()
+
+ def _get_by_id(self, series_id: int, name: str, start_date: Optional[str] = None,
+ end_date: Optional[str] = None, last_n: Optional[int] = None) -> Dict[str, Any]:
+ try:
+ raw = self._fetch_series(series_id, start_date, end_date, last_n)
+ rows = self._parse_rows(raw, f"series_{series_id}")
+ return {
+ "success": True,
+ "series_id": series_id,
+ "name": name,
+ "data": rows,
+ "count": len(rows),
+ "source": "Banco Central do Brasil",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BCBError(str(series_id), str(e), sc).to_dict()
+ except Exception as e:
+ return BCBError(str(series_id), str(e)).to_dict()
+
+ # ------------------------------------------------------------------
+ # Public convenience methods
+ # ------------------------------------------------------------------
+
+ def get_selic(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Selic target rate — monetary policy rate."""
+ return self._get_series("selic_target", start_date, end_date)
+
+ def get_selic_daily(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Selic daily effective rate."""
+ return self._get_series("selic_daily", start_date, end_date)
+
+ def get_ipca(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """IPCA monthly consumer price inflation."""
+ return self._get_series("ipca", start_date, end_date)
+
+ def get_igpm(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """IGP-M monthly inflation index."""
+ return self._get_series("igpm", start_date, end_date)
+
+ def get_usd_brl(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """USD/BRL PTAX selling rate (daily)."""
+ return self._get_series("usd_brl", start_date, end_date)
+
+ def get_exchange_rates(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """USD/BRL and EUR/BRL exchange rates merged."""
+ usd = self._get_series("usd_brl", start_date, end_date)
+ eur = self._get_series("eur_brl", start_date, end_date)
+ merged: Dict[str, Dict] = {}
+ for row in usd.get("data", []):
+ d = row["date"]
+ merged[d] = {"date": d, "usd_brl": row.get("usd_brl")}
+ for row in eur.get("data", []):
+ d = row["date"]
+ merged.setdefault(d, {"date": d})
+ merged[d]["eur_brl"] = row.get("eur_brl")
+ rows = sorted(merged.values(), key=lambda r: datetime.strptime(r["date"], "%d/%m/%Y"))
+ return {
+ "success": True,
+ "data": rows,
+ "count": len(rows),
+ "source": "Banco Central do Brasil",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_monetary_aggregates(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """M1, M2, M3 monetary aggregates merged."""
+ merged: Dict[str, Dict] = {}
+ for key in ["m1", "m2", "m3"]:
+ r = self._get_series(key, start_date, end_date)
+ for row in r.get("data", []):
+ d = row["date"]
+ merged.setdefault(d, {"date": d})
+ merged[d].update({k: v for k, v in row.items() if k != "date"})
+ rows = sorted(merged.values(), key=lambda r: datetime.strptime(r["date"], "%d/%m/%Y"))
+ return {
+ "success": True,
+ "data": rows,
+ "count": len(rows),
+ "source": "Banco Central do Brasil",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_gdp(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """GDP annual growth rate."""
+ return self._get_series("gdp_growth", start_date, end_date)
+
+ def get_unemployment(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Unemployment rate (PNAD survey)."""
+ return self._get_series("unemployment", start_date, end_date)
+
+ def get_credit(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Total credit outstanding."""
+ return self._get_series("credit_total", start_date, end_date)
+
+ def get_reserves(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """International reserves (USD millions)."""
+ return self._get_series("reserves", start_date, end_date)
+
+ def get_trade_balance(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Monthly trade balance (USD millions)."""
+ return self._get_series("trade_balance", start_date, end_date)
+
+ def get_fiscal(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Primary fiscal surplus/deficit and net public debt merged."""
+ merged: Dict[str, Dict] = {}
+ for key in ["primary_surplus", "net_public_debt"]:
+ r = self._get_series(key, start_date, end_date)
+ for row in r.get("data", []):
+ d = row["date"]
+ merged.setdefault(d, {"date": d})
+ merged[d].update({k: v for k, v in row.items() if k != "date"})
+ rows = sorted(merged.values(), key=lambda r: r["date"])
+ return {
+ "success": True,
+ "data": rows,
+ "count": len(rows),
+ "source": "Banco Central do Brasil",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_overview(self) -> Dict[str, Any]:
+ """Latest values for key indicators."""
+ results: Dict[str, Any] = {}
+ for key in GROUPS["overview"]:
+ r = self._get_series(key, last_n=3)
+ info = SERIES.get(key, {})
+ results[key] = {
+ "name": info.get("name", key),
+ "unit": info.get("unit", ""),
+ "success": r.get("success"),
+ "latest": r.get("data", [{}])[-1] if r.get("data") else None,
+ }
+ return {
+ "success": True,
+ "data": results,
+ "source": "Banco Central do Brasil",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_series(self, series_key: str, start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ last_n: Optional[int] = None) -> Dict[str, Any]:
+ """Fetch any known series by key name."""
+ return self._get_series(series_key, start_date, end_date, last_n)
+
+ def get_series_by_id(self, series_id: int, start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ last_n: Optional[int] = None) -> Dict[str, Any]:
+ """Fetch any SGS series directly by numeric ID."""
+ return self._get_by_id(series_id, f"series_{series_id}", start_date, end_date, last_n)
+
+ def available_series(self) -> Dict[str, Any]:
+ """Return full catalogue of available series."""
+ by_cat: Dict[str, List] = {}
+ for key, info in SERIES.items():
+ cat = info["category"]
+ by_cat.setdefault(cat, []).append({
+ "key": key, "id": info["id"], "name": info["name"],
+ "unit": info["unit"], "frequency": info["freq"],
+ })
+ return {
+ "success": True,
+ "data": by_cat,
+ "groups": GROUPS,
+ "base_url": BASE_URL,
+ "source": "Banco Central do Brasil",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "selic": "[start DD/MM/YYYY] [end DD/MM/YYYY] — Selic target rate",
+ "selic_daily": "[start] [end] — Selic daily rate",
+ "ipca": "[start] [end] — IPCA monthly inflation",
+ "igpm": "[start] [end] — IGP-M inflation",
+ "usd_brl": "[start] [end] — USD/BRL PTAX rate",
+ "exchange_rates": "[start] [end] — USD/BRL + EUR/BRL merged",
+ "monetary": "[start] [end] — M1/M2/M3 aggregates",
+ "gdp": "[start] [end] — GDP annual growth",
+ "unemployment": "[start] [end] — Unemployment rate (PNAD)",
+ "credit": "[start] [end] — Total credit outstanding",
+ "reserves": "[start] [end] — International reserves",
+ "trade_balance": "[start] [end] — Monthly trade balance",
+ "fiscal": "[start] [end] — Fiscal surplus + public debt",
+ "overview": " — Latest key indicators",
+ "series": "<key> [start] [end] [last_n] — Any series by key name",
+ "series_id": "<id> [start] [end] [last_n] — Any series by SGS number",
+ "available": " — List all series",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python bcb_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = BCBWrapper()
+
+ try:
+ if cmd == "selic":
+ result = wrapper.get_selic(_a(2), _a(3))
+ elif cmd == "selic_daily":
+ result = wrapper.get_selic_daily(_a(2), _a(3))
+ elif cmd == "ipca":
+ result = wrapper.get_ipca(_a(2), _a(3))
+ elif cmd == "igpm":
+ result = wrapper.get_igpm(_a(2), _a(3))
+ elif cmd == "usd_brl":
+ result = wrapper.get_usd_brl(_a(2), _a(3))
+ elif cmd == "exchange_rates":
+ result = wrapper.get_exchange_rates(_a(2), _a(3))
+ elif cmd in ("monetary", "monetary_aggregates"):
+ result = wrapper.get_monetary_aggregates(_a(2), _a(3))
+ elif cmd == "gdp":
+ result = wrapper.get_gdp(_a(2), _a(3))
+ elif cmd == "unemployment":
+ result = wrapper.get_unemployment(_a(2), _a(3))
+ elif cmd == "credit":
+ result = wrapper.get_credit(_a(2), _a(3))
+ elif cmd == "reserves":
+ result = wrapper.get_reserves(_a(2), _a(3))
+ elif cmd == "trade_balance":
+ result = wrapper.get_trade_balance(_a(2), _a(3))
+ elif cmd == "fiscal":
+ result = wrapper.get_fiscal(_a(2), _a(3))
+ elif cmd == "overview":
+ result = wrapper.get_overview()
+ elif cmd == "series":
+ if len(sys.argv) < 3:
+ result = {"error": "series requires <key>", "available": list(SERIES.keys())}
+ else:
+ ln = int(_a(5)) if _a(5) else None
+ result = wrapper.get_series(sys.argv[2], _a(3), _a(4), ln)
+ elif cmd == "series_id":
+ if len(sys.argv) < 3:
+ result = {"error": "series_id requires <numeric_id>"}
+ else:
+ ln = int(_a(5)) if _a(5) else None
+ result = wrapper.get_series_by_id(int(sys.argv[2]), _a(3), _a(4), ln)
+ elif cmd in ("available", "list"):
+ result = wrapper.available_series()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/bnm_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/bnm_data.py
new file mode 100644
index 000000000..c6e7b3c7c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/bnm_data.py
@@ -0,0 +1,437 @@
+"""
+Bank Negara Malaysia (BNM) Data Wrapper
+Fetches data from the BNM Open API.
+
+API Reference:
+ Base URL: https://api.bnm.gov.my/public
+ Format: JSON
+ Auth: None required — fully public
+ Docs: https://api.bnm.gov.my/
+
+Accept header required: application/vnd.BNM.API.v1+json
+
+Endpoints:
+ GET /exchange-rate — All currency rates (current session)
+ ?session=0900|1200|1130 — Rate session (0900=morning, 1200=noon, 1130=closing)
+ GET /exchange-rate/{currency} — Single currency rate
+ ?session=0900|1200|1130
+ GET /interest-rate — Base rate, BLR, OPR, KLIBOR
+ GET /base-rate — Base rate and BLR
+ GET /kijang-emas — Gold coin (Kijang Emas) prices
+ GET /interbank-swap — Interbank FX swap
+ GET /opr — OPR (overnight policy rate) latest
+
+Exchange rates expressed as MYR per foreign currency unit.
+Some currencies use unit=100 (AED, HKD, IDR, INR, JPY, KHR, KRW, MMK,
+NPR, PHP, PKR, SAR, THB, TWD, VND); the wrapper normalises to MYR per 1 unit.
+
+27 currencies: AED, AUD, BND, CAD, CHF, CNY, EGP, EUR, GBP, HKD, IDR,
+ INR, JPY, KHR, KRW, MMK, NOK, NPR, NZD, PHP, PKR, SAR,
+ SDR, SGD, THB, TWD, USD, VND
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime, date, timedelta, timezone
+
+
+BASE_URL = "https://api.bnm.gov.my/public"
+ACCEPT_HEADER = "application/vnd.BNM.API.v1+json"
+DEFAULT_TIMEOUT = 30
+
+# Sessions: morning fixing, noon, 1130 closing
+SESSIONS = ["0900", "1200", "1130"]
+
+MAJOR_CURRENCIES = ["USD", "EUR", "GBP", "JPY", "CHF", "AUD", "CAD",
+ "SGD", "CNY", "HKD", "INR", "NZD"]
+ASEAN_CURRENCIES = ["SGD", "IDR", "THB", "PHP", "VND", "KHR", "MMK",
+ "BND", "AUD", "NZD"]
+
+# Unit multipliers per currency (unit=100 → divide by 100 to get MYR per 1 unit)
+UNIT_MAP: Dict[str, int] = {
+ "AED": 100, "HKD": 100, "IDR": 100, "INR": 100,
+ "JPY": 100, "KHR": 100, "KRW": 100, "MMK": 100,
+ "NPR": 100, "PHP": 100, "PKR": 100, "SAR": 100,
+ "THB": 100, "TWD": 100, "VND": 100,
+}
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class BNMError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "BNMError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class BNMWrapper:
+ """
+ Wrapper for the Bank Negara Malaysia (BNM) Open API.
+
+ Exchange rates are MYR (Malaysian Ringgit) per 1 unit of foreign currency.
+ Currencies with unit=100 are normalised by the wrapper.
+ Three rate sessions per day: 0900 (morning fix), 1200 (noon), 1130 (closing).
+ """
+
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Accept": ACCEPT_HEADER,
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _get(self, path: str, params: Optional[Dict] = None) -> Any:
+ url = f"{BASE_URL}/{path.lstrip('/')}"
+ resp = self.session.get(url, params=params or {}, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.json()
+
+ def _normalise_rate(self, value: Optional[float],
+ unit: int) -> Optional[float]:
+ """Normalise rate: if unit=100, divide by 100 to get per-1-unit."""
+ if value is None:
+ return None
+ return round(value / unit, 6) if unit > 1 else value
+
+ def _parse_fx_item(self, item: Dict[str, Any]) -> Dict[str, Any]:
+ """Parse a single FX item from BNM API into clean dict."""
+ code = item.get("currency_code", "")
+ raw = item.get("unit", 1)
+ unit = int(raw) if raw else UNIT_MAP.get(code, 1)
+ rate = item.get("rate", {})
+ return {
+ "currency": code,
+ "date": rate.get("date", ""),
+ "buying": self._normalise_rate(rate.get("buying_rate"), unit),
+ "selling": self._normalise_rate(rate.get("selling_rate"), unit),
+ "middle": self._normalise_rate(rate.get("middle_rate"), unit),
+ "unit": unit,
+ }
+
+ # ------------------------------------------------------------------
+ # Public methods
+ # ------------------------------------------------------------------
+
+ def get_exchange_rates(self, session: str = "1130") -> Dict[str, Any]:
+ """All currency rates vs MYR for the specified daily session."""
+ session = session.strip()
+ try:
+ data = self._get("exchange-rate", {"session": session})
+ items = data.get("data", [])
+ meta = data.get("meta", {})
+ parsed = [self._parse_fx_item(i) for i in items]
+ # Build simple flat dict: {USD: middle_rate, ...}
+ flat: Dict[str, Optional[float]] = {}
+ for p in parsed:
+ flat[p["currency"]] = p["middle"] or p["buying"]
+ return {
+ "success": True,
+ "session": session,
+ "date": parsed[0]["date"] if parsed else "",
+ "data": flat,
+ "full_data": parsed,
+ "count": len(parsed),
+ "note": "MYR per 1 unit of foreign currency (normalised from unit=100 where applicable)",
+ "source": "Bank Negara Malaysia",
+ "url": f"{BASE_URL}/exchange-rate",
+ "meta": meta,
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNMError("exchange-rate", str(e), sc).to_dict()
+ except Exception as e:
+ return BNMError("exchange-rate", str(e)).to_dict()
+
+ def get_currency(self, currency: str, session: str = "1130") -> Dict[str, Any]:
+ """Current rate for a single currency vs MYR."""
+ currency = currency.upper()
+ try:
+ data = self._get(f"exchange-rate/{currency}", {"session": session})
+ item = data.get("data", {})
+ meta = data.get("meta", {})
+ parsed = self._parse_fx_item(item)
+ return {
+ "success": True,
+ "session": session,
+ "data": parsed,
+ "note": f"MYR per 1 {currency}",
+ "source": "Bank Negara Malaysia",
+ "meta": meta,
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNMError(f"exchange-rate/{currency}", str(e), sc).to_dict()
+ except Exception as e:
+ return BNMError(f"exchange-rate/{currency}", str(e)).to_dict()
+
+ def get_all_sessions(self, currency: str = "USD") -> Dict[str, Any]:
+ """Fetch a currency rate across all three daily sessions."""
+ currency = currency.upper()
+ results: Dict[str, Any] = {}
+ for sess in SESSIONS:
+ r = self.get_currency(currency, sess)
+ if r.get("success"):
+ results[sess] = r.get("data", {})
+ else:
+ results[sess] = {"error": r.get("error", "failed")}
+ return {
+ "success": True,
+ "currency": currency,
+ "sessions": results,
+ "note": "MYR per 1 unit; sessions: 0900=morning fix, 1200=noon, 1130=closing",
+ "source": "Bank Negara Malaysia",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_interest_rates(self) -> Dict[str, Any]:
+ """Base rate, BLR, OPR, and KLIBOR rates."""
+ try:
+ data = self._get("interest-rate")
+ return {
+ "success": True,
+ "data": data.get("data", data),
+ "source": "Bank Negara Malaysia",
+ "url": f"{BASE_URL}/interest-rate",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNMError("interest-rate", str(e), sc).to_dict()
+ except Exception as e:
+ return BNMError("interest-rate", str(e)).to_dict()
+
+ def get_base_rate(self) -> Dict[str, Any]:
+ """Bank lending base rate (BR) and base lending rate (BLR)."""
+ try:
+ data = self._get("base-rate")
+ return {
+ "success": True,
+ "data": data.get("data", data),
+ "source": "Bank Negara Malaysia",
+ "url": f"{BASE_URL}/base-rate",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNMError("base-rate", str(e), sc).to_dict()
+ except Exception as e:
+ return BNMError("base-rate", str(e)).to_dict()
+
+ def get_opr(self) -> Dict[str, Any]:
+ """Overnight Policy Rate (OPR) — Malaysia's key policy rate."""
+ try:
+ data = self._get("opr")
+ return {
+ "success": True,
+ "data": data.get("data", data),
+ "note": "OPR is Bank Negara Malaysia's key monetary policy rate",
+ "source": "Bank Negara Malaysia",
+ "url": f"{BASE_URL}/opr",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNMError("opr", str(e), sc).to_dict()
+ except Exception as e:
+ return BNMError("opr", str(e)).to_dict()
+
+ def get_kijang_emas(self) -> Dict[str, Any]:
+ """Kijang Emas gold coin buying and selling prices (MYR)."""
+ try:
+ data = self._get("kijang-emas")
+ return {
+ "success": True,
+ "data": data.get("data", data),
+ "note": "Kijang Emas: Malaysian gold investment coin",
+ "source": "Bank Negara Malaysia",
+ "url": f"{BASE_URL}/kijang-emas",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNMError("kijang-emas", str(e), sc).to_dict()
+ except Exception as e:
+ return BNMError("kijang-emas", str(e)).to_dict()
+
+ def get_major_currencies(self, session: str = "1130") -> Dict[str, Any]:
+ """Major currencies vs MYR."""
+ result = self.get_exchange_rates(session)
+ if not result.get("success"):
+ return result
+ flat = result.get("data", {})
+ major = {c: flat[c] for c in MAJOR_CURRENCIES if c in flat}
+ return {
+ "success": True,
+ "session": session,
+ "date": result.get("date", ""),
+ "currencies": MAJOR_CURRENCIES,
+ "data": major,
+ "note": "MYR per 1 unit of foreign currency",
+ "source": "Bank Negara Malaysia",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_asean_currencies(self, session: str = "1130") -> Dict[str, Any]:
+ """ASEAN & Asia-Pacific currencies vs MYR."""
+ result = self.get_exchange_rates(session)
+ if not result.get("success"):
+ return result
+ flat = result.get("data", {})
+ asean = {c: flat[c] for c in ASEAN_CURRENCIES if c in flat}
+ return {
+ "success": True,
+ "session": session,
+ "date": result.get("date", ""),
+ "currencies": ASEAN_CURRENCIES,
+ "data": asean,
+ "note": "MYR per 1 unit of foreign currency",
+ "source": "Bank Negara Malaysia",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_overview(self) -> Dict[str, Any]:
+ """Snapshot: major rates + OPR + gold (Kijang Emas)."""
+ fx = self.get_major_currencies()
+ opr = self.get_opr()
+ gold = self.get_kijang_emas()
+ return {
+ "success": True,
+ "date": fx.get("date", ""),
+ "data": {
+ "exchange_rates": fx.get("data", {}),
+ "opr": opr.get("data", {}),
+ "kijang_emas": gold.get("data", {}),
+ },
+ "source": "Bank Negara Malaysia",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def available_currencies(self) -> Dict[str, Any]:
+ """List available currencies and their unit multipliers."""
+ return {
+ "success": True,
+ "all_currencies": [
+ "AED", "AUD", "BND", "CAD", "CHF", "CNY", "EGP", "EUR",
+ "GBP", "HKD", "IDR", "INR", "JPY", "KHR", "KRW", "MMK",
+ "NOK", "NPR", "NZD", "PHP", "PKR", "SAR", "SDR", "SGD",
+ "THB", "TWD", "USD", "VND",
+ ],
+ "major_currencies": MAJOR_CURRENCIES,
+ "asean_currencies": ASEAN_CURRENCIES,
+ "unit_100_currencies": list(UNIT_MAP.keys()),
+ "sessions": SESSIONS,
+ "note": "Rates expressed as MYR per 1 unit (unit=100 currencies are normalised)",
+ "source": "Bank Negara Malaysia",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "fx": "[session=1130] — All exchange rates vs MYR",
+ "currency": "<CCY> [session=1130] — Single currency vs MYR",
+ "sessions": "<CCY> — Currency across all 3 daily sessions",
+ "major": "[session=1130] — Major currencies vs MYR",
+ "asean": "[session=1130] — ASEAN/APAC currencies vs MYR",
+ "opr": " — Overnight Policy Rate history",
+ "base_rate": " — Base rate and BLR",
+ "interest": " — Interest rates (BR, BLR, OPR, KLIBOR)",
+ "gold": " — Kijang Emas gold coin prices",
+ "overview": " — Snapshot: FX + OPR + gold",
+ "available": " — List available currencies",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python bnm_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = BNMWrapper()
+
+ try:
+ if cmd in ("fx", "exchange_rates"):
+ result = wrapper.get_exchange_rates(_a(2, "1130"))
+ elif cmd == "currency":
+ if len(sys.argv) < 3:
+ result = {"error": "currency requires <CCY>"}
+ else:
+ result = wrapper.get_currency(sys.argv[2], _a(3, "1130"))
+ elif cmd == "sessions":
+ if len(sys.argv) < 3:
+ result = {"error": "sessions requires <CCY>"}
+ else:
+ result = wrapper.get_all_sessions(sys.argv[2])
+ elif cmd == "major":
+ result = wrapper.get_major_currencies(_a(2, "1130"))
+ elif cmd == "asean":
+ result = wrapper.get_asean_currencies(_a(2, "1130"))
+ elif cmd == "opr":
+ result = wrapper.get_opr()
+ elif cmd in ("base_rate", "base"):
+ result = wrapper.get_base_rate()
+ elif cmd in ("interest", "interest_rates"):
+ result = wrapper.get_interest_rates()
+ elif cmd in ("gold", "kijang_emas"):
+ result = wrapper.get_kijang_emas()
+ elif cmd == "overview":
+ result = wrapper.get_overview()
+ elif cmd in ("available", "currencies"):
+ result = wrapper.available_currencies()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=True))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/bnr_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/bnr_data.py
new file mode 100644
index 000000000..e43159762
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/bnr_data.py
@@ -0,0 +1,434 @@
+"""
+National Bank of Romania (BNR) Data Wrapper
+Fetches data from the BNR public XML API.
+
+API Reference:
+ Base URL: https://www.bnr.ro
+ Format: XML (utf-8)
+ Auth: None required — fully public
+ Docs: https://www.bnr.ro/Cursuri-de-schimb-524.aspx
+
+Endpoints:
+ GET /nbrfxrates.xml — Latest reference rates (today)
+ GET /nbrfxrates.xml?date=YYYYMMDD — Rates for a specific date
+ GET /files/xml/years/nbrfxrates{Y}.xml — All rates for a calendar year
+
+Exchange rates expressed as RON per foreign currency unit.
+Some currencies use a multiplier (e.g. JPY per 100, HUF per 100, KRW per 100).
+
+Currencies published (36+):
+ AED, AUD, BGN, BRL, CAD, CHF, CNY, CZK, DKK, EGP, EUR, GBP, HKD,
+ HUF, IDR, ILS, INR, ISK, JPY, KRW, MDL, MXN, MYR, NOK, NZD, PHP,
+ PLN, RON (1), RSD, RUB, SEK, SGD, THB, TRY, UAH, USD, XAU, XDR, ZAR
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import requests
+import traceback
+import xml.etree.ElementTree as ET
+from typing import Dict, Any, List, Optional
+from datetime import datetime, date, timedelta, timezone
+
+
+BASE_URL = "https://www.bnr.ro"
+XML_NS = "http://www.bnr.ro/xsd"
+DEFAULT_TIMEOUT = 30
+
+MAJOR_CURRENCIES = ["USD", "EUR", "GBP", "JPY", "CHF", "CAD", "AUD",
+ "NOK", "SEK", "DKK", "CNY", "PLN", "HUF", "CZK"]
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class BNRError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "BNRError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class BNRWrapper:
+ """
+ Wrapper for the National Bank of Romania XML data feed.
+
+ All rates are RON per 1 unit of foreign currency.
+ For currencies with multiplier > 1 (e.g. JPY, HUF, KRW, IDR, ISK):
+ actual_rate = obs_value / multiplier
+ The wrapper normalises all rates to RON per 1 unit.
+ """
+
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Accept": "application/xml, text/xml, */*",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _fetch_xml(self, url: str) -> bytes:
+ resp = self.session.get(url, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.content
+
+ def _parse_dataset(self, content: bytes) -> List[Dict[str, Any]]:
+ """
+ Parse a BNR XML DataSet (single date or full-year).
+ Returns list of {date, CCY1: rate, CCY2: rate, ...} rows.
+ RON rates are normalised: value / multiplier.
+ """
+ root = ET.fromstring(content)
+ ns = {"b": XML_NS}
+ rows: List[Dict[str, Any]] = []
+
+ for cube in root.findall(".//b:Cube", ns):
+ d = cube.get("date", "")
+ row: Dict[str, Any] = {"date": d}
+ for rate_el in cube.findall("b:Rate", ns):
+ ccy = rate_el.get("currency", "")
+ mult = int(rate_el.get("multiplier", "1"))
+ try:
+ val = float(rate_el.text or "0")
+ row[ccy] = round(val / mult, 6)
+ except (ValueError, TypeError):
+ pass
+ if d:
+ rows.append(row)
+
+ return sorted(rows, key=lambda r: r["date"])
+
+ def _parse_header(self, content: bytes) -> Dict[str, str]:
+ """Extract header metadata (publisher, publish date, message type)."""
+ root = ET.fromstring(content)
+ ns = {"b": XML_NS}
+ header = root.find("b:Header", ns)
+ if header is None:
+ return {}
+ return {
+ "publisher": (header.findtext("b:Publisher", namespaces=ns) or "").strip(),
+ "publish_date": (header.findtext("b:PublishingDate", namespaces=ns) or "").strip(),
+ "orig_currency": (header.findtext("b:Body/b:OrigCurrency", namespaces={"b": XML_NS}) or "RON").strip(),
+ }
+
+ def _today_url(self) -> str:
+ return f"{BASE_URL}/nbrfxrates.xml"
+
+ def _date_url(self, d: str) -> str:
+ # BNR expects YYYYMMDD
+ clean = d.replace("-", "")
+ return f"{BASE_URL}/nbrfxrates.xml?date={clean}"
+
+ def _year_url(self, year: int) -> str:
+ return f"{BASE_URL}/files/xml/years/nbrfxrates{year}.xml"
+
+ # ------------------------------------------------------------------
+ # Public methods
+ # ------------------------------------------------------------------
+
+ def get_today(self) -> Dict[str, Any]:
+ """Latest reference rates (today's publication)."""
+ url = self._today_url()
+ try:
+ content = self._fetch_xml(url)
+ rows = self._parse_dataset(content)
+ latest = rows[-1] if rows else {}
+ return {
+ "success": True,
+ "date": latest.get("date", ""),
+ "data": latest,
+ "note": "RON per 1 unit of foreign currency (normalised for multiplied currencies)",
+ "source": "National Bank of Romania",
+ "url": url,
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNRError("today", str(e), sc).to_dict()
+ except Exception as e:
+ return BNRError("today", str(e)).to_dict()
+
+ def get_date(self, rate_date: str) -> Dict[str, Any]:
+ """Reference rates for a specific date (YYYY-MM-DD)."""
+ url = self._date_url(rate_date)
+ try:
+ content = self._fetch_xml(url)
+ rows = self._parse_dataset(content)
+ entry = rows[-1] if rows else {}
+ return {
+ "success": True,
+ "date": entry.get("date", rate_date),
+ "data": entry,
+ "note": "RON per 1 unit of foreign currency",
+ "source": "National Bank of Romania",
+ "url": url,
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNRError(f"date/{rate_date}", str(e), sc).to_dict()
+ except Exception as e:
+ return BNRError(f"date/{rate_date}", str(e)).to_dict()
+
+ def get_year(self, year: Optional[int] = None) -> Dict[str, Any]:
+ """All reference rates for a full calendar year."""
+ if year is None:
+ year = date.today().year
+ url = self._year_url(year)
+ try:
+ content = self._fetch_xml(url)
+ rows = self._parse_dataset(content)
+ return {
+ "success": True,
+ "year": year,
+ "data": rows,
+ "count": len(rows),
+ "note": "RON per 1 unit of foreign currency",
+ "source": "National Bank of Romania",
+ "url": url,
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNRError(f"year/{year}", str(e), sc).to_dict()
+ except Exception as e:
+ return BNRError(f"year/{year}", str(e)).to_dict()
+
+ def get_range(self, start_date: str, end_date: Optional[str] = None) -> Dict[str, Any]:
+ """
+ Reference rates for a date range.
+ Fetches the relevant year file(s) and filters to the requested window.
+ """
+ try:
+ start = datetime.strptime(start_date, "%Y-%m-%d").date()
+ end = datetime.strptime(end_date, "%Y-%m-%d").date() if end_date else date.today()
+
+ years = list(range(start.year, end.year + 1))
+ all_rows: List[Dict[str, Any]] = []
+
+ for y in years:
+ content = self._fetch_xml(self._year_url(y))
+ rows = self._parse_dataset(content)
+ all_rows.extend(rows)
+
+ filtered = [r for r in all_rows
+ if start_date <= r.get("date", "") <= end.isoformat()]
+ return {
+ "success": True,
+ "start_date": start_date,
+ "end_date": end.isoformat(),
+ "data": filtered,
+ "count": len(filtered),
+ "note": "RON per 1 unit of foreign currency",
+ "source": "National Bank of Romania",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNRError("range", str(e), sc).to_dict()
+ except Exception as e:
+ return BNRError("range", str(e)).to_dict()
+
+ def get_currency(self, currency: str,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """
+ Historical rates for a single currency vs RON.
+ Defaults to current year if no dates given.
+ """
+ try:
+ currency = currency.upper()
+ if start_date is None:
+ start_date = date(date.today().year, 1, 1).isoformat()
+ end = end_date or date.today().isoformat()
+ start = datetime.strptime(start_date, "%Y-%m-%d").date()
+ endd = datetime.strptime(end, "%Y-%m-%d").date()
+
+ years = list(range(start.year, endd.year + 1))
+ all_rows: List[Dict[str, Any]] = []
+ for y in years:
+ content = self._fetch_xml(self._year_url(y))
+ rows = self._parse_dataset(content)
+ for r in rows:
+ if start_date <= r.get("date", "") <= end and currency in r:
+ all_rows.append({"date": r["date"], currency: r[currency]})
+
+ return {
+ "success": True,
+ "currency": currency,
+ "start_date": start_date,
+ "end_date": end,
+ "data": all_rows,
+ "count": len(all_rows),
+ "note": f"RON per 1 {currency}",
+ "source": "National Bank of Romania",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNRError(f"currency/{currency}", str(e), sc).to_dict()
+ except Exception as e:
+ return BNRError(f"currency/{currency}", str(e)).to_dict()
+
+ def get_major_currencies(self, start_date: Optional[str] = None) -> Dict[str, Any]:
+ """Major currencies vs RON for current year (or from start_date)."""
+ try:
+ if start_date is None:
+ start_date = date(date.today().year, 1, 1).isoformat()
+ content = self._fetch_xml(self._year_url(date.today().year))
+ rows = self._parse_dataset(content)
+ filtered = []
+ for r in rows:
+ if r.get("date", "") >= start_date:
+ entry = {"date": r["date"]}
+ for c in MAJOR_CURRENCIES:
+ if c in r:
+ entry[c] = r[c]
+ filtered.append(entry)
+ return {
+ "success": True,
+ "currencies": MAJOR_CURRENCIES,
+ "start_date": start_date,
+ "data": filtered,
+ "count": len(filtered),
+ "note": "RON per 1 unit of foreign currency",
+ "source": "National Bank of Romania",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BNRError("major_currencies", str(e), sc).to_dict()
+ except Exception as e:
+ return BNRError("major_currencies", str(e)).to_dict()
+
+ def get_overview(self) -> Dict[str, Any]:
+ """Snapshot: today's rates for major currencies."""
+ today = self.get_today()
+ if not today.get("success"):
+ return today
+ data = today.get("data", {})
+ snapshot = {c: data[c] for c in MAJOR_CURRENCIES if c in data}
+ return {
+ "success": True,
+ "date": today.get("date"),
+ "data": snapshot,
+ "full_data": data,
+ "note": "RON per 1 unit of foreign currency",
+ "source": "National Bank of Romania",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def available_currencies(self) -> Dict[str, Any]:
+ """List currencies available in BNR data."""
+ return {
+ "success": True,
+ "major_currencies": MAJOR_CURRENCIES,
+ "all_currencies": [
+ "AED", "AUD", "BRL", "CAD", "CHF", "CNY", "CZK", "DKK",
+ "EGP", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR",
+ "ISK", "JPY", "KRW", "MDL", "MXN", "MYR", "NOK", "NZD",
+ "PHP", "PLN", "RSD", "RUB", "SEK", "SGD", "THB", "TRY",
+ "UAH", "USD", "XAU", "XDR", "ZAR",
+ ],
+ "note": "Rates expressed as RON per 1 unit; multiplied currencies (JPY, HUF, KRW, IDR, ISK) are normalised",
+ "source": "National Bank of Romania",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "today": " — Today's reference rates (all currencies)",
+ "date": "<YYYY-MM-DD> — Rates for a specific date",
+ "year": "[year] — All rates for a calendar year",
+ "range": "<start YYYY-MM-DD> [end] — Rates for a date range",
+ "currency": "<CCY> [start] [end] — Single currency vs RON history",
+ "major": "[start YYYY-MM-DD] — Major currencies this year",
+ "overview": " — Today's major currency snapshot",
+ "available":" — List available currencies",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python bnr_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = BNRWrapper()
+
+ try:
+ if cmd == "today":
+ result = wrapper.get_today()
+ elif cmd == "date":
+ if len(sys.argv) < 3:
+ result = {"error": "date requires <YYYY-MM-DD>"}
+ else:
+ result = wrapper.get_date(sys.argv[2])
+ elif cmd == "year":
+ y = int(_a(2, date.today().year))
+ result = wrapper.get_year(y)
+ elif cmd == "range":
+ if len(sys.argv) < 3:
+ result = {"error": "range requires <start_date>"}
+ else:
+ result = wrapper.get_range(sys.argv[2], _a(3))
+ elif cmd == "currency":
+ if len(sys.argv) < 3:
+ result = {"error": "currency requires <CCY>"}
+ else:
+ result = wrapper.get_currency(sys.argv[2], _a(3), _a(4))
+ elif cmd == "major":
+ result = wrapper.get_major_currencies(_a(2))
+ elif cmd == "overview":
+ result = wrapper.get_overview()
+ elif cmd in ("available", "currencies"):
+ result = wrapper.available_currencies()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=True))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/boc_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/boc_data.py
new file mode 100644
index 000000000..2281fc35c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/boc_data.py
@@ -0,0 +1,400 @@
+"""
+Bank of Canada (BoC) Data Wrapper
+Fetches data from the Bank of Canada Valet API.
+
+API Reference:
+ Base URL: https://www.bankofcanada.ca/valet
+ Format: JSON
+ Auth: None required — fully public
+ Docs: https://www.bankofcanada.ca/valet/docs
+
+Endpoints:
+ GET /lists/series/json — Full catalogue of all 15,000+ series
+ GET /lists/groups/json — Groups/categories
+ GET /observations/{series}/json — Observation history
+ ?recent=N — Last N observations
+ ?start_date=YYYY-MM-DD — From date
+ ?end_date=YYYY-MM-DD — To date
+ GET /observations/group/{group}/json — All series in a group
+
+Key series IDs:
+ FXUSDCAD, FXEURCAD, FXGBPCAD, FXJPYCAD, FXCHFCAD, FXAUDCAD — Exchange rates
+ STATIC_ATABLE_V39079 — Overnight rate target (policy rate, end of month)
+ AVG.INTWO — CORRA (Canadian Overnight Repo Rate Average)
+ V80691342 — 1-month treasury bill yield
+ V80691344 — 3-month treasury bill yield
+ V80691346 — 6-month treasury bill yield
+ V80691348 — 1-year treasury bill yield
+ V122530 — Prime rate
+ A.BCPI — Bank of Canada commodity price index
+ A.ENER — Energy commodity price sub-index
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime, date, timedelta, timezone
+
+
+BASE_URL = "https://www.bankofcanada.ca/valet"
+DEFAULT_TIMEOUT = 30
+
+
+# ---------------------------------------------------------------------------
+# Key series catalogue
+# ---------------------------------------------------------------------------
+
+SERIES = {
+ # Exchange rates (CAD per 1 foreign currency unit)
+ "FXUSDCAD": {"label": "USD/CAD", "category": "exchange_rates"},
+ "FXEURCAD": {"label": "EUR/CAD", "category": "exchange_rates"},
+ "FXGBPCAD": {"label": "GBP/CAD", "category": "exchange_rates"},
+ "FXJPYCAD": {"label": "JPY/CAD", "category": "exchange_rates"},
+ "FXCHFCAD": {"label": "CHF/CAD", "category": "exchange_rates"},
+ "FXAUDCAD": {"label": "AUD/CAD", "category": "exchange_rates"},
+ "FXNZDCAD": {"label": "NZD/CAD", "category": "exchange_rates"},
+ "FXHKDCAD": {"label": "HKD/CAD", "category": "exchange_rates"},
+ "FXSEKCAD": {"label": "SEK/CAD", "category": "exchange_rates"},
+ "FXNOKCAD": {"label": "NOK/CAD", "category": "exchange_rates"},
+ "FXDKKCAD": {"label": "DKK/CAD", "category": "exchange_rates"},
+ "FXSGDCAD": {"label": "SGD/CAD", "category": "exchange_rates"},
+ "FXCNYCAD": {"label": "CNY/CAD", "category": "exchange_rates"},
+ "FXINRCAD": {"label": "INR/CAD", "category": "exchange_rates"},
+ "FXMXNCAD": {"label": "MXN/CAD", "category": "exchange_rates"},
+ # Interest rates / policy
+ "STATIC_ATABLE_V39079": {"label": "Overnight rate target", "category": "interest_rates"},
+ "AVG.INTWO": {"label": "CORRA overnight repo rate", "category": "interest_rates"},
+ "V80691342": {"label": "T-bill 1 month", "category": "interest_rates"},
+ "V80691344": {"label": "T-bill 3 month", "category": "interest_rates"},
+ "V80691346": {"label": "T-bill 6 month", "category": "interest_rates"},
+ "V80691348": {"label": "T-bill 1 year", "category": "interest_rates"},
+ "V122530": {"label": "Prime rate", "category": "interest_rates"},
+ # Commodity prices
+ "A.BCPI": {"label": "Commodity Price Index", "category": "commodities"},
+ "A.ENER": {"label": "Energy sub-index", "category": "commodities"},
+ "A.MTLS": {"label": "Metals sub-index", "category": "commodities"},
+ "A.AGRI": {"label": "Agriculture sub-index", "category": "commodities"},
+}
+
+FX_SERIES = [k for k, v in SERIES.items() if v["category"] == "exchange_rates"]
+RATE_SERIES = [k for k, v in SERIES.items() if v["category"] == "interest_rates"]
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class BoCError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "BoCError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class BoCWrapper:
+ """
+ Wrapper for the Bank of Canada Valet REST API.
+
+ All data is free, no authentication required.
+ Exchange rates are expressed as CAD per 1 unit of foreign currency.
+ """
+
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Accept": "application/json",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _get(self, path: str, params: Optional[Dict] = None) -> Any:
+ url = f"{BASE_URL}/{path.lstrip('/')}"
+ resp = self.session.get(url, params=params or {}, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.json()
+
+ def _parse_observations(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Flatten Valet observations into wide-format list of {date, series: value}."""
+ obs_raw = data.get("observations", [])
+ rows: List[Dict[str, Any]] = []
+ for o in obs_raw:
+ row: Dict[str, Any] = {"date": o.get("d", "")}
+ for k, v in o.items():
+ if k == "d":
+ continue
+ val = v.get("v") if isinstance(v, dict) else v
+ if val is not None:
+ try:
+ row[k] = float(val)
+ except (ValueError, TypeError):
+ row[k] = val
+ rows.append(row)
+ return rows
+
+ def _obs(self, series_ids: str, recent: Optional[int] = None,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Fetch observations for one or more comma-joined series IDs."""
+ params: Dict[str, Any] = {}
+ if recent:
+ params["recent"] = recent
+ if start_date:
+ params["start_date"] = start_date
+ if end_date:
+ params["end_date"] = end_date
+ try:
+ data = self._get(f"observations/{series_ids}/json", params)
+ rows = self._parse_observations(data)
+ detail = data.get("seriesDetail", {})
+ return {
+ "success": True,
+ "series": series_ids,
+ "detail": detail,
+ "data": rows,
+ "count": len(rows),
+ "source": "Bank of Canada",
+ "url": f"{BASE_URL}/observations/{series_ids}/json",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BoCError(series_ids, str(e), sc).to_dict()
+ except Exception as e:
+ return BoCError(series_ids, str(e)).to_dict()
+
+ # ------------------------------------------------------------------
+ # Public methods
+ # ------------------------------------------------------------------
+
+ def get_exchange_rates(self, currencies: Optional[List[str]] = None,
+ recent: int = 30,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Daily CAD exchange rates for major currencies."""
+ if currencies is None:
+ currencies = ["USD", "EUR", "GBP", "JPY", "CHF", "AUD", "CNY"]
+ ids = ",".join(f"FX{c}CAD" for c in currencies)
+ result = self._obs(ids, recent if not start_date else None, start_date, end_date)
+ result["currencies"] = currencies
+ result["note"] = "CAD per 1 unit of foreign currency"
+ return result
+
+ def get_usd_cad(self, recent: int = 30,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """USD/CAD exchange rate history."""
+ return self._obs("FXUSDCAD", recent if not start_date else None, start_date, end_date)
+
+ def get_eur_cad(self, recent: int = 30,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """EUR/CAD exchange rate history."""
+ return self._obs("FXEURCAD", recent if not start_date else None, start_date, end_date)
+
+ def get_policy_rate(self, recent: int = 24,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Overnight rate target (policy rate) history."""
+ return self._obs("STATIC_ATABLE_V39079",
+ recent if not start_date else None, start_date, end_date)
+
+ def get_corra(self, recent: int = 30,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """CORRA — Canadian Overnight Repo Rate Average."""
+ return self._obs("AVG.INTWO",
+ recent if not start_date else None, start_date, end_date)
+
+ def get_prime_rate(self, recent: int = 24,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Bank prime lending rate history."""
+ return self._obs("V122530",
+ recent if not start_date else None, start_date, end_date)
+
+ def get_tbill_yields(self, recent: int = 30,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Government of Canada T-bill yields: 1M, 3M, 6M, 1Y."""
+ ids = "V80691342,V80691344,V80691346,V80691348"
+ result = self._obs(ids, recent if not start_date else None, start_date, end_date)
+ result["tenors"] = ["1M", "3M", "6M", "1Y"]
+ return result
+
+ def get_commodity_prices(self, recent: int = 12,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Bank of Canada Commodity Price Index and sub-indices."""
+ ids = "A.BCPI,A.ENER,A.MTLS,A.AGRI"
+ return self._obs(ids, recent if not start_date else None, start_date, end_date)
+
+ def get_series(self, series_id: str, recent: Optional[int] = None,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Fetch any series by its Valet series ID."""
+ return self._obs(series_id, recent, start_date, end_date)
+
+ def get_overview(self) -> Dict[str, Any]:
+ """Snapshot: latest policy rate, USD/CAD, EUR/CAD, CORRA, prime rate."""
+ results: Dict[str, Any] = {}
+ for name, sid in [
+ ("policy_rate", "STATIC_ATABLE_V39079"),
+ ("corra", "AVG.INTWO"),
+ ("prime_rate", "V122530"),
+ ("usd_cad", "FXUSDCAD"),
+ ("eur_cad", "FXEURCAD"),
+ ("gbp_cad", "FXGBPCAD"),
+ ]:
+ r = self._obs(sid, recent=1)
+ results[name] = {
+ "success": r.get("success"),
+ "latest": r.get("data", [{}])[-1] if r.get("data") else None,
+ }
+ return {
+ "success": True,
+ "data": results,
+ "source": "Bank of Canada",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def available_series(self) -> Dict[str, Any]:
+ """Return the built-in series catalogue."""
+ by_cat: Dict[str, List] = {}
+ for sid, info in SERIES.items():
+ cat = info["category"]
+ by_cat.setdefault(cat, []).append({"series_id": sid, "label": info["label"]})
+ return {
+ "success": True,
+ "data": by_cat,
+ "total": len(SERIES),
+ "note": "Use get_series(series_id) for any of the 15,000+ Valet series",
+ "source": "Bank of Canada",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def list_all_series(self) -> Dict[str, Any]:
+ """Fetch the full Valet series catalogue (15,000+ series)."""
+ try:
+ data = self._get("lists/series/json")
+ items = data.get("series", {})
+ return {
+ "success": True,
+ "count": len(items),
+ "data": items,
+ "source": "Bank of Canada",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BoCError("lists/series", str(e), sc).to_dict()
+ except Exception as e:
+ return BoCError("lists/series", str(e)).to_dict()
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "fx": "[currencies...] [recent=30] [start] [end] — CAD exchange rates",
+ "usd": "[recent=30] [start] [end] — USD/CAD history",
+ "eur": "[recent=30] [start] [end] — EUR/CAD history",
+ "policy_rate": "[recent=24] [start] [end] — Overnight rate target",
+ "corra": "[recent=30] [start] [end] — CORRA overnight repo rate",
+ "prime": "[recent=24] [start] [end] — Prime lending rate",
+ "tbills": "[recent=30] [start] [end] — T-bill yields (1M-1Y)",
+ "commodities": "[recent=12] [start] [end] — Commodity price indices",
+ "series": "<series_id> [recent] [start] [end] — Any series by ID",
+ "overview": " — Key indicators snapshot",
+ "available": " — Built-in series catalogue",
+ "list": " — Full Valet series catalogue",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python boc_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = BoCWrapper()
+
+ try:
+ if cmd in ("fx", "exchange_rates"):
+ # fx [cur1,cur2,...] [recent] [start] [end]
+ raw = _a(2, "USD,EUR,GBP,JPY,CHF,AUD,CNY")
+ ccys = [c.strip().upper() for c in raw.split(",")]
+ n = int(_a(3, 30))
+ result = wrapper.get_exchange_rates(ccys, n, _a(4), _a(5))
+ elif cmd == "usd":
+ result = wrapper.get_usd_cad(int(_a(2, 30)), _a(3), _a(4))
+ elif cmd == "eur":
+ result = wrapper.get_eur_cad(int(_a(2, 30)), _a(3), _a(4))
+ elif cmd in ("policy_rate", "policy"):
+ result = wrapper.get_policy_rate(int(_a(2, 24)), _a(3), _a(4))
+ elif cmd == "corra":
+ result = wrapper.get_corra(int(_a(2, 30)), _a(3), _a(4))
+ elif cmd in ("prime", "prime_rate"):
+ result = wrapper.get_prime_rate(int(_a(2, 24)), _a(3), _a(4))
+ elif cmd in ("tbills", "tbill"):
+ result = wrapper.get_tbill_yields(int(_a(2, 30)), _a(3), _a(4))
+ elif cmd in ("commodities", "commodity"):
+ result = wrapper.get_commodity_prices(int(_a(2, 12)), _a(3), _a(4))
+ elif cmd == "series":
+ if len(sys.argv) < 3:
+ result = {"error": "series requires <series_id>"}
+ else:
+ n = int(_a(3)) if _a(3) else None
+ result = wrapper.get_series(sys.argv[2], n, _a(4), _a(5))
+ elif cmd == "overview":
+ result = wrapper.get_overview()
+ elif cmd in ("available", "catalogue"):
+ result = wrapper.available_series()
+ elif cmd in ("list", "list_all"):
+ result = wrapper.list_all_series()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=True))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/boe_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/boe_data.py
new file mode 100644
index 000000000..fd4fe3245
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/boe_data.py
@@ -0,0 +1,1454 @@
+#!/usr/bin/env python3
+"""
+Bank of England (BoE) Statistical Interactive Database (IADB) Wrapper
+
+Provides programmatic access to the Bank of England's IADB covering:
+- Official Bank Rate (base rate)
+- SONIA (Sterling Overnight Index Average)
+- Spot exchange rates (GBP vs 26+ currencies)
+- Sterling Exchange Rate Index (ERI / trade-weighted)
+- Gilt yield curves (nominal, real, inflation, OIS)
+- Quoted household interest rates (mortgages, deposits, consumer credit)
+- Effective interest rates
+- Monetary aggregates (M0, M4, M4Lx, notes & coin)
+- Balance sheet / Bankstats data
+
+API details:
+- Base URL: https://www.bankofengland.co.uk/boeapps/database/_iadb-fromshowcolumns.asp
+- No authentication required (completely free and open)
+- Response formats: CSV (primary), XML, HTML, Excel
+- Date format: DD/Mon/YYYY (e.g. 01/Jan/2000)
+- Up to 300 series codes per CSV/XML/HTML request; 250 for Excel
+- Missing values represented as ".." (two dots) -> converted to None/NaN
+
+Usage:
+ python boe_data.py available_categories
+ python boe_data.py bank_rate [--start 01/Jan/2000] [--end now]
+ python boe_data.py sonia [--start 01/Jan/2020] [--end now]
+ python boe_data.py exchange_rates [--start 01/Jan/2020] [--end now]
+ python boe_data.py exchange_rate_index [--start 01/Jan/2020] [--end now]
+ python boe_data.py quoted_rates [--start 01/Jan/2012] [--end now]
+ python boe_data.py effective_rates [--start 01/Jan/2012] [--end now]
+ python boe_data.py monetary_aggregates [--start 01/Jan/2010] [--end now]
+ python boe_data.py series --codes IUDBEDR,IUDSOIA [--start 01/Jan/2020] [--end now]
+ python boe_data.py overview
+"""
+
+import sys
+import json
+import io
+import csv
+import requests
+from datetime import datetime, date
+from typing import Dict, List, Optional, Any, Union
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+BOE_BASE_URL = "https://www.bankofengland.co.uk/boeapps/database/_iadb-fromshowcolumns.asp"
+
+# Reusable session with retry behaviour
+_session = requests.Session()
+_adapter = requests.adapters.HTTPAdapter(
+ pool_connections=5,
+ pool_maxsize=10,
+ max_retries=requests.adapters.Retry(total=3, backoff_factor=1),
+)
+_session.mount("https://", _adapter)
+_session.headers.update({
+ "User-Agent": (
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
+ "Chrome/120.0.0.0 Safari/537.36"
+ )
+})
+
+# ---------------------------------------------------------------------------
+# Key series-code reference catalogue
+# ---------------------------------------------------------------------------
+
+SERIES_CATALOGUE: Dict[str, Dict[str, Any]] = {
+ # --- Monetary Policy -------------------------------------------------------
+ "IUDBEDR": {
+ "name": "Official Bank Rate (Base Rate)",
+ "category": "interest_rates",
+ "subcategory": "monetary_policy",
+ "frequency": "daily",
+ "description": "Bank of England policy rate set by the Monetary Policy Committee (MPC).",
+ "unit": "percent",
+ },
+ "IUDSOIA": {
+ "name": "Daily SONIA Rate",
+ "category": "interest_rates",
+ "subcategory": "money_market",
+ "frequency": "daily",
+ "description": "Sterling Overnight Index Average – effective overnight interbank rate.",
+ "unit": "percent",
+ },
+ "IUASOIA": {
+ "name": "SONIA Compounded Index",
+ "category": "interest_rates",
+ "subcategory": "money_market",
+ "frequency": "daily",
+ "description": "SONIA Compounded Index published from 3 August 2020 for RFR transition.",
+ "unit": "index",
+ },
+
+ # --- Government Gilt Yield Curves (nominal par yields) ---------------------
+ "IUDSNPY": {
+ "name": "Nominal Par Yield – 5Y",
+ "category": "yield_curves",
+ "subcategory": "gilt_nominal",
+ "frequency": "daily",
+ "description": "UK gilt nominal par yield, 5-year maturity.",
+ "unit": "percent",
+ },
+ "IUDMNPY": {
+ "name": "Nominal Par Yield – 10Y",
+ "category": "yield_curves",
+ "subcategory": "gilt_nominal",
+ "frequency": "daily",
+ "description": "UK gilt nominal par yield, 10-year maturity.",
+ "unit": "percent",
+ },
+ "IUDLNPY": {
+ "name": "Nominal Par Yield – 20Y",
+ "category": "yield_curves",
+ "subcategory": "gilt_nominal",
+ "frequency": "daily",
+ "description": "UK gilt nominal par yield, 20-year maturity.",
+ "unit": "percent",
+ },
+ "IUDSIZC": {
+ "name": "Implied Zero-Coupon Inflation Curve – 5Y",
+ "category": "yield_curves",
+ "subcategory": "gilt_inflation",
+ "frequency": "daily",
+ "description": "Implied zero-coupon inflation term structure, 5-year maturity.",
+ "unit": "percent",
+ },
+ "IUDMIZC": {
+ "name": "Implied Zero-Coupon Inflation Curve – 10Y",
+ "category": "yield_curves",
+ "subcategory": "gilt_inflation",
+ "frequency": "daily",
+ "description": "Implied zero-coupon inflation term structure, 10-year maturity.",
+ "unit": "percent",
+ },
+
+ # --- OIS (Overnight Index Swap) Yield Curves ------------------------------
+ "IUDZOS2": {
+ "name": "OIS Zero-Coupon Spot Rate – 2Y",
+ "category": "yield_curves",
+ "subcategory": "ois",
+ "frequency": "daily",
+ "description": "SONIA-based OIS zero-coupon spot rate, 2-year maturity.",
+ "unit": "percent",
+ },
+ "IUDZLT2": {
+ "name": "OIS Zero-Coupon Spot Rate – 5Y",
+ "category": "yield_curves",
+ "subcategory": "ois",
+ "frequency": "daily",
+ "description": "SONIA-based OIS zero-coupon spot rate, 5-year maturity.",
+ "unit": "percent",
+ },
+ "IUDZLS6": {
+ "name": "OIS Zero-Coupon Spot Rate – 10Y",
+ "category": "yield_curves",
+ "subcategory": "ois",
+ "frequency": "daily",
+ "description": "SONIA-based OIS zero-coupon spot rate, 10-year maturity.",
+ "unit": "percent",
+ },
+ "IUDZLS7": {
+ "name": "OIS Zero-Coupon Spot Rate – 25Y",
+ "category": "yield_curves",
+ "subcategory": "ois",
+ "frequency": "daily",
+ "description": "SONIA-based OIS zero-coupon spot rate, 25-year maturity (extended in 2021).",
+ "unit": "percent",
+ },
+
+ # --- GBP Spot Exchange Rates (XUDL prefix) --------------------------------
+ "XUDLUSS": {
+ "name": "GBP/USD Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "US dollar into sterling – indicative 4pm mid-market rate.",
+ "unit": "GBP per 1 USD (inverted: USD per GBP in practice)",
+ },
+ "XUDLERS": {
+ "name": "GBP/EUR Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Euro into sterling – indicative 4pm mid-market rate.",
+ "unit": "GBP per 1 EUR",
+ },
+ "XUDLJYS": {
+ "name": "GBP/JPY Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Japanese yen into sterling – indicative 4pm mid-market rate.",
+ "unit": "GBP per 1 JPY",
+ },
+ "XUDLCDS": {
+ "name": "GBP/CAD Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Canadian dollar into sterling.",
+ "unit": "GBP per 1 CAD",
+ },
+ "XUDLSFS": {
+ "name": "GBP/CHF Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Swiss franc into sterling.",
+ "unit": "GBP per 1 CHF",
+ },
+ "XUDLADS": {
+ "name": "GBP/AUD Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Australian dollar into sterling.",
+ "unit": "GBP per 1 AUD",
+ },
+ "XUDLNKS": {
+ "name": "GBP/NOK Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Norwegian krone into sterling.",
+ "unit": "GBP per 1 NOK",
+ },
+ "XUDLSKS": {
+ "name": "GBP/SEK Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Swedish krona into sterling.",
+ "unit": "GBP per 1 SEK",
+ },
+ "XUDLDKS": {
+ "name": "GBP/DKK Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Danish krone into sterling.",
+ "unit": "GBP per 1 DKK",
+ },
+ "XUDLSGS": {
+ "name": "GBP/SGD Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Singapore dollar into sterling.",
+ "unit": "GBP per 1 SGD",
+ },
+ "XUDLHDS": {
+ "name": "GBP/HKD Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Hong Kong dollar into sterling.",
+ "unit": "GBP per 1 HKD",
+ },
+ "XUDLTWS": {
+ "name": "GBP/TWD Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "New Taiwan dollar into sterling.",
+ "unit": "GBP per 1 TWD",
+ },
+ "XUDLBK25": {
+ "name": "GBP/MYR Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Malaysian ringgit into sterling.",
+ "unit": "GBP per 1 MYR",
+ },
+ "XUDLBK47": {
+ "name": "GBP/HKD Spot Rate (alt)",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Alternative Hong Kong dollar spot rate series.",
+ "unit": "GBP per 1 HKD",
+ },
+ "XUDLBK83": {
+ "name": "GBP/INR Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "Indian rupee into sterling.",
+ "unit": "GBP per 1 INR",
+ },
+ "XUDLBK85": {
+ "name": "GBP/KRW Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "South Korean won into sterling.",
+ "unit": "GBP per 1 KRW",
+ },
+ "XUDLBK87": {
+ "name": "GBP/ZAR Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "gbp_spot",
+ "frequency": "daily",
+ "description": "South African rand into sterling.",
+ "unit": "GBP per 1 ZAR",
+ },
+
+ # --- USD Cross Rates (XUDL prefix) ----------------------------------------
+ "XUDLADD": {
+ "name": "USD/AUD Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "usd_cross",
+ "frequency": "daily",
+ "description": "Australian dollar into USD – BoE published cross rate.",
+ "unit": "USD per 1 AUD",
+ },
+ "XUDLBFD": {
+ "name": "USD/CHF Spot Rate",
+ "category": "exchange_rates",
+ "subcategory": "usd_cross",
+ "frequency": "daily",
+ "description": "Swiss franc into USD – BoE published cross rate.",
+ "unit": "USD per 1 CHF",
+ },
+
+ # --- Sterling Exchange Rate Index (ERI) -----------------------------------
+ "XUMAERS": {
+ "name": "Sterling ERI (Narrow, Chain-Linked)",
+ "category": "exchange_rates",
+ "subcategory": "eri",
+ "frequency": "daily",
+ "description": (
+ "Trade-weighted sterling exchange rate index (narrow basis). "
+ "Jan 2005 = 100. Annually re-weighted using world trade data."
+ ),
+ "unit": "index (Jan 2005=100)",
+ },
+ "XUMABRD": {
+ "name": "Sterling ERI (Broad, Chain-Linked)",
+ "category": "exchange_rates",
+ "subcategory": "eri",
+ "frequency": "daily",
+ "description": "Trade-weighted sterling exchange rate index (broad basis). Jan 2005 = 100.",
+ "unit": "index (Jan 2005=100)",
+ },
+
+ # --- USD/EUR Forward Discount Rates ---------------------------------------
+ "XUDLDF1": {
+ "name": "USD/GBP 1-Month Forward Discount",
+ "category": "exchange_rates",
+ "subcategory": "forward",
+ "frequency": "daily",
+ "description": "USD into sterling forward premium/discount, 1-month.",
+ "unit": "percent per annum",
+ },
+ "XUDLDF3": {
+ "name": "USD/GBP 3-Month Forward Discount",
+ "category": "exchange_rates",
+ "subcategory": "forward",
+ "frequency": "daily",
+ "description": "USD into sterling forward premium/discount, 3-month.",
+ "unit": "percent per annum",
+ },
+ "XUDLDF6": {
+ "name": "USD/GBP 6-Month Forward Discount",
+ "category": "exchange_rates",
+ "subcategory": "forward",
+ "frequency": "daily",
+ "description": "USD into sterling forward premium/discount, 6-month.",
+ "unit": "percent per annum",
+ },
+ "XUDLDFY": {
+ "name": "USD/GBP 12-Month Forward Discount",
+ "category": "exchange_rates",
+ "subcategory": "forward",
+ "frequency": "daily",
+ "description": "USD into sterling forward premium/discount, 12-month.",
+ "unit": "percent per annum",
+ },
+
+ # --- Quoted Household Interest Rates (IUM prefix) -------------------------
+ "IUMZICQ": {
+ "name": "Mortgage Rate – 2Y Fixed 60% LTV",
+ "category": "interest_rates",
+ "subcategory": "quoted_mortgage",
+ "frequency": "monthly",
+ "description": "2-year fixed-rate mortgage, 60% loan-to-value ratio.",
+ "unit": "percent per annum",
+ },
+ "IUMBV34": {
+ "name": "Mortgage Rate – 2Y Fixed 75% LTV",
+ "category": "interest_rates",
+ "subcategory": "quoted_mortgage",
+ "frequency": "monthly",
+ "description": "2-year fixed-rate mortgage, 75% LTV.",
+ "unit": "percent per annum",
+ },
+ "IUMZICR": {
+ "name": "Mortgage Rate – 2Y Fixed 85% LTV",
+ "category": "interest_rates",
+ "subcategory": "quoted_mortgage",
+ "frequency": "monthly",
+ "description": "2-year fixed-rate mortgage, 85% LTV.",
+ "unit": "percent per annum",
+ },
+ "IUMB482": {
+ "name": "Mortgage Rate – 2Y Fixed 90% LTV",
+ "category": "interest_rates",
+ "subcategory": "quoted_mortgage",
+ "frequency": "monthly",
+ "description": "2-year fixed-rate mortgage, 90% LTV.",
+ "unit": "percent per annum",
+ },
+ "IUM2WTL": {
+ "name": "Mortgage Rate – 2Y Fixed 95% LTV",
+ "category": "interest_rates",
+ "subcategory": "quoted_mortgage",
+ "frequency": "monthly",
+ "description": "2-year fixed-rate mortgage, 95% LTV.",
+ "unit": "percent per annum",
+ },
+ "IUMBV37": {
+ "name": "Mortgage Rate – 3Y Fixed",
+ "category": "interest_rates",
+ "subcategory": "quoted_mortgage",
+ "frequency": "monthly",
+ "description": "3-year fixed-rate mortgage.",
+ "unit": "percent per annum",
+ },
+ "IUMBV42": {
+ "name": "Mortgage Rate – 5Y Fixed 75% LTV",
+ "category": "interest_rates",
+ "subcategory": "quoted_mortgage",
+ "frequency": "monthly",
+ "description": "5-year fixed-rate mortgage, 75% LTV.",
+ "unit": "percent per annum",
+ },
+ "IUM5WTL": {
+ "name": "Mortgage Rate – 5Y Fixed 95% LTV",
+ "category": "interest_rates",
+ "subcategory": "quoted_mortgage",
+ "frequency": "monthly",
+ "description": "5-year fixed-rate mortgage, 95% LTV.",
+ "unit": "percent per annum",
+ },
+ "IUMBV45": {
+ "name": "Mortgage Rate – 10Y Fixed",
+ "category": "interest_rates",
+ "subcategory": "quoted_mortgage",
+ "frequency": "monthly",
+ "description": "10-year fixed-rate mortgage.",
+ "unit": "percent per annum",
+ },
+ "IUMB479": {
+ "name": "Mortgage Rate – Variable/Tracker",
+ "category": "interest_rates",
+ "subcategory": "quoted_mortgage",
+ "frequency": "monthly",
+ "description": "Variable or tracker mortgage rate.",
+ "unit": "percent per annum",
+ },
+ "IUMBV24": {
+ "name": "Mortgage Rate – Standard Variable Rate (SVR)",
+ "category": "interest_rates",
+ "subcategory": "quoted_mortgage",
+ "frequency": "monthly",
+ "description": "Bank/building society standard variable mortgage rate.",
+ "unit": "percent per annum",
+ },
+ "IUMZID4": {
+ "name": "Household Deposit Rate – Instant Access ISA",
+ "category": "interest_rates",
+ "subcategory": "quoted_deposit",
+ "frequency": "monthly",
+ "description": "Average rate on household instant-access ISA deposits.",
+ "unit": "percent per annum",
+ },
+ "IUMZID2": {
+ "name": "Household Deposit Rate – Time Deposits",
+ "category": "interest_rates",
+ "subcategory": "quoted_deposit",
+ "frequency": "monthly",
+ "description": "Average rate on household time/fixed-term deposits.",
+ "unit": "percent per annum",
+ },
+ "IUMHPTL": {
+ "name": "Personal Loan Rate",
+ "category": "interest_rates",
+ "subcategory": "quoted_consumer_credit",
+ "frequency": "monthly",
+ "description": "Quoted personal loan interest rate.",
+ "unit": "percent per annum",
+ },
+ "IUMCCTL": {
+ "name": "Credit Card Rate",
+ "category": "interest_rates",
+ "subcategory": "quoted_consumer_credit",
+ "frequency": "monthly",
+ "description": "Quoted credit card interest rate.",
+ "unit": "percent per annum",
+ },
+ "IUMODTL": {
+ "name": "Overdraft Rate",
+ "category": "interest_rates",
+ "subcategory": "quoted_consumer_credit",
+ "frequency": "monthly",
+ "description": "Quoted authorised overdraft interest rate.",
+ "unit": "percent per annum",
+ },
+
+ # --- Effective Interest Rates (CFM / CFQ prefix) --------------------------
+ "CFMZ6KO": {
+ "name": "Effective Rate – Mortgage Stock",
+ "category": "interest_rates",
+ "subcategory": "effective",
+ "frequency": "monthly",
+ "description": "Effective interest rate on the outstanding stock of household mortgages.",
+ "unit": "percent per annum",
+ },
+ "CFMHSCP": {
+ "name": "Effective Rate – Household Deposits (Outstanding)",
+ "category": "interest_rates",
+ "subcategory": "effective",
+ "frequency": "monthly",
+ "description": "Effective rate on outstanding household deposits.",
+ "unit": "percent per annum",
+ },
+ "CFMHSCQ": {
+ "name": "Effective Rate – Household Deposits (New Business)",
+ "category": "interest_rates",
+ "subcategory": "effective",
+ "frequency": "monthly",
+ "description": "Effective rate on new household deposit business.",
+ "unit": "percent per annum",
+ },
+
+ # --- Monetary Aggregates (LPM prefix) -------------------------------------
+ "LPMAUYN": {
+ "name": "M4 Liabilities – Total (Seasonally Adjusted, £mn)",
+ "category": "monetary_aggregates",
+ "subcategory": "m4",
+ "frequency": "monthly",
+ "description": "Monthly M4 liabilities to private sector – sterling millions, seasonally adjusted.",
+ "unit": "GBP millions",
+ },
+ "LPMAVAA": {
+ "name": "Notes & Coin in Circulation – Total (NSA, £mn)",
+ "category": "monetary_aggregates",
+ "subcategory": "notes_coin",
+ "frequency": "monthly",
+ "description": "Monthly average total sterling notes and coin in circulation (not seasonally adjusted).",
+ "unit": "GBP millions",
+ },
+ "LPMAVAB": {
+ "name": "Notes & Coin in Circulation – Total (SA, £mn)",
+ "category": "monetary_aggregates",
+ "subcategory": "notes_coin",
+ "frequency": "monthly",
+ "description": "Notes and coin in circulation excluding Scotland/Northern Ireland backing – seasonally adjusted.",
+ "unit": "GBP millions",
+ },
+ "LPMAVAF": {
+ "name": "Notes & Coin – Monthly Change (NSA, £mn)",
+ "category": "monetary_aggregates",
+ "subcategory": "notes_coin",
+ "frequency": "monthly",
+ "description": "Monthly changes in total sterling notes and coin in circulation outside the Bank of England (NSA).",
+ "unit": "GBP millions",
+ },
+ "LPMAVAG": {
+ "name": "Notes & Coin – Monthly Change (SA, £mn)",
+ "category": "monetary_aggregates",
+ "subcategory": "notes_coin",
+ "frequency": "monthly",
+ "description": "Monthly changes in notes and coin outside the Bank of England (seasonally adjusted).",
+ "unit": "GBP millions",
+ },
+ "LPMBL22": {
+ "name": "Bank of England Banking Dept Sterling Reserves",
+ "category": "monetary_aggregates",
+ "subcategory": "boe_balance_sheet",
+ "frequency": "monthly",
+ "description": "Monthly average amounts outstanding of BoE Banking Department sterling reserves balance liabilities.",
+ "unit": "GBP millions",
+ },
+ "LPMBI2O": {
+ "name": "Consumer Credit – Other Lending (Outstanding, £mn)",
+ "category": "monetary_aggregates",
+ "subcategory": "consumer_credit",
+ "frequency": "monthly",
+ "description": "Amounts outstanding of consumer credit other than credit cards (includes overdrafts and loans).",
+ "unit": "GBP millions",
+ },
+ "LPMB6VG": {
+ "name": "Consumer Credit – Total (Outstanding, £mn)",
+ "category": "monetary_aggregates",
+ "subcategory": "consumer_credit",
+ "frequency": "monthly",
+ "description": "Total amounts outstanding of consumer credit.",
+ "unit": "GBP millions",
+ },
+
+ # --- Quarterly BoE Balance Sheet / CFM prefix (effective rate sub-series) -
+ "CFMBI22": {
+ "name": "Effective Rate Component – CFM BI22",
+ "category": "interest_rates",
+ "subcategory": "effective",
+ "frequency": "monthly",
+ "description": "BoE effective interest rate sub-series (outstanding deposits/loans).",
+ "unit": "percent per annum",
+ },
+ "CFMBI23": {
+ "name": "Effective Rate Component – CFM BI23",
+ "category": "interest_rates",
+ "subcategory": "effective",
+ "frequency": "monthly",
+ "description": "BoE effective interest rate sub-series (outstanding deposits/loans).",
+ "unit": "percent per annum",
+ },
+ "CFMBJ59": {
+ "name": "Effective Rate Component – CFM BJ59",
+ "category": "interest_rates",
+ "subcategory": "effective",
+ "frequency": "monthly",
+ "description": "BoE effective interest rate sub-series (new business).",
+ "unit": "percent per annum",
+ },
+ "CFMBJ62": {
+ "name": "Effective Rate Component – CFM BJ62",
+ "category": "interest_rates",
+ "subcategory": "effective",
+ "frequency": "monthly",
+ "description": "BoE effective interest rate sub-series (new business).",
+ "unit": "percent per annum",
+ },
+
+ # --- VPQB – national accounts-compatible series ---------------------------
+ "VPQB432SI": {
+ "name": "Quarterly GDP-Related BoE Series",
+ "category": "national_accounts",
+ "subcategory": "gdp",
+ "frequency": "quarterly",
+ "description": "National accounts-compatible quarterly series published in the IADB.",
+ "unit": "index / GBP millions (series-dependent)",
+ },
+}
+
+# Convenience groupings for bulk queries
+SERIES_GROUPS: Dict[str, List[str]] = {
+ "monetary_policy": ["IUDBEDR", "IUDSOIA", "IUASOIA"],
+ "gilt_yields": ["IUDSNPY", "IUDMNPY", "IUDLNPY", "IUDSIZC", "IUDMIZC"],
+ "ois_yields": ["IUDZOS2", "IUDZLT2", "IUDZLS6", "IUDZLS7"],
+ "gbp_spot_rates": [
+ "XUDLUSS", "XUDLERS", "XUDLJYS", "XUDLCDS", "XUDLSFS",
+ "XUDLADS", "XUDLNKS", "XUDLSKS", "XUDLDKS", "XUDLSGS",
+ "XUDLHDS", "XUDLTWS", "XUDLBK83", "XUDLBK85", "XUDLBK87",
+ ],
+ "exchange_rate_index": ["XUMAERS", "XUMABRD"],
+ "forward_rates": ["XUDLDF1", "XUDLDF3", "XUDLDF6", "XUDLDFY"],
+ "quoted_mortgage_rates": [
+ "IUMZICQ", "IUMBV34", "IUMZICR", "IUMB482", "IUM2WTL",
+ "IUMBV37", "IUMBV42", "IUM5WTL", "IUMBV45", "IUMB479", "IUMBV24",
+ ],
+ "quoted_deposit_rates": ["IUMZID4", "IUMZID2"],
+ "quoted_consumer_credit_rates": ["IUMHPTL", "IUMCCTL", "IUMODTL"],
+ "effective_rates": ["CFMZ6KO", "CFMHSCP", "CFMHSCQ"],
+ "monetary_aggregates": [
+ "LPMAUYN", "LPMAVAA", "LPMAVAB", "LPMAVAF", "LPMAVAG",
+ "LPMBL22", "LPMBI2O", "LPMB6VG",
+ ],
+}
+
+
+# ---------------------------------------------------------------------------
+# Helper utilities
+# ---------------------------------------------------------------------------
+
+def _today_str() -> str:
+ """Return today's date in BoE format DD/Mon/YYYY."""
+ return datetime.now().strftime("%d/%b/%Y")
+
+
+def _parse_value(raw: str) -> Optional[float]:
+ """Convert raw cell string to float; return None for missing ('..' or empty)."""
+ if raw is None:
+ return None
+ stripped = raw.strip()
+ if stripped in ("", "..", "n/a", "N/A", "N.A.", "N/A."):
+ return None
+ try:
+ return float(stripped)
+ except (ValueError, TypeError):
+ return None
+
+
+def _fetch_csv(
+ series_codes: List[str],
+ date_from: str,
+ date_to: str,
+ csvf: str = "TT",
+ vpd: str = "Y",
+ vfd: str = "N",
+) -> Dict[str, Any]:
+ """
+ Fetch CSV data from the BoE IADB for the given series codes and date range.
+
+ Parameters
+ ----------
+ series_codes : list of str
+ IADB series code identifiers (max 300 per request).
+ date_from : str
+ Start date in DD/Mon/YYYY format (e.g. '01/Jan/2000').
+ date_to : str
+ End date in DD/Mon/YYYY format, or the literal string 'now'.
+ csvf : str
+ CSV format: 'TT' tabular+titles, 'TN' tabular no titles,
+ 'CT' columnar+titles, 'CN' columnar no titles.
+ vpd : str
+ 'Y' to include provisional data.
+ vfd : str
+ 'Y' to include observation footnotes.
+
+ Returns
+ -------
+ dict with keys:
+ success (bool), data (list of dicts), series_codes (list),
+ date_from, date_to, rows_returned (int), source (str)
+ """
+ if len(series_codes) > 300:
+ return {
+ "success": False,
+ "error": "Maximum 300 series codes per request (use 250 or fewer for safety).",
+ }
+
+ params = {
+ "csv.x": "yes",
+ "Datefrom": date_from,
+ "Dateto": date_to,
+ "SeriesCodes": ",".join(series_codes),
+ "CSVF": csvf,
+ "UsingCodes": "Y",
+ "VPD": vpd,
+ "VFD": vfd,
+ }
+
+ try:
+ resp = _session.get(BOE_BASE_URL, params=params, timeout=30)
+ resp.raise_for_status()
+
+ raw_bytes = resp.content
+ # Try UTF-8 first, fall back to latin-1
+ try:
+ text = raw_bytes.decode("utf-8")
+ except UnicodeDecodeError:
+ text = raw_bytes.decode("latin-1")
+
+ return _parse_csv_response(text, series_codes, date_from, date_to, csvf)
+
+ except requests.exceptions.Timeout:
+ return {"success": False, "error": "Request timed out (30s). Try a shorter date range."}
+ except requests.exceptions.HTTPError as exc:
+ return {"success": False, "error": f"HTTP {exc.response.status_code}: {str(exc)}"}
+ except requests.exceptions.RequestException as exc:
+ return {"success": False, "error": f"Network error: {str(exc)}"}
+
+
+def _parse_csv_response(
+ text: str,
+ series_codes: List[str],
+ date_from: str,
+ date_to: str,
+ csvf: str,
+) -> Dict[str, Any]:
+ """
+ Parse raw CSV text returned by the BoE IADB into a structured dict.
+
+ The BoE TT (tabular with titles) format has a preamble block before the
+ actual data table:
+
+ SERIES,DESCRIPTION <- literal header of the preamble
+ IUDBEDR,Official Bank Rate <- one row per requested series
+ IUDSOIA,Daily SONIA rate
+ <- blank separator line
+ DATE,IUDBEDR,IUDSOIA <- actual data header
+ 02 Jan 2025,4.75,4.70 <- data rows ...
+
+ TN (tabular no titles) skips the preamble entirely and starts with the
+ DATE header directly. CT/CN are columnar (code | date | value per row).
+ """
+ reader = csv.reader(io.StringIO(text))
+ rows = list(reader)
+
+ if not rows:
+ return {
+ "success": False,
+ "error": "Empty response from BoE IADB.",
+ }
+
+ is_tabular = csvf.upper().startswith("T")
+ has_titles = csvf.upper().endswith("T")
+
+ data_records: List[Dict[str, Any]] = []
+ series_descriptions: Dict[str, str] = {}
+
+ if is_tabular:
+ # Locate the data header row – it begins with "DATE" (case-insensitive).
+ data_header_idx: Optional[int] = None
+ col_codes: List[str] = []
+
+ for idx, row in enumerate(rows):
+ if row and row[0].strip().upper() == "DATE":
+ data_header_idx = idx
+ col_codes = [c.strip() for c in row[1:] if c.strip()]
+ break
+
+ if data_header_idx is None:
+ # Fallback: assume first row is header, no preamble
+ if rows:
+ col_codes = [c.strip() for c in rows[0][1:] if c.strip()] or series_codes[:]
+ data_header_idx = 0
+ else:
+ return {"success": False, "error": "Could not locate data header row."}
+
+ # If has_titles, the rows before data_header_idx are the SERIES/DESCRIPTION preamble
+ if has_titles:
+ in_preamble = False
+ for row in rows[:data_header_idx]:
+ if not row or not row[0].strip():
+ continue
+ if row[0].strip().upper() == "SERIES":
+ in_preamble = True
+ continue
+ if in_preamble and len(row) >= 2:
+ series_descriptions[row[0].strip()] = row[1].strip()
+
+ # If col_codes is empty (e.g. one-series TT), fall back to supplied codes
+ if not col_codes:
+ col_codes = series_codes[:]
+
+ for row in rows[data_header_idx + 1:]:
+ if not row or not row[0].strip():
+ continue
+ date_val = row[0].strip()
+ # Skip any residual header/separator rows
+ if date_val.upper() == "DATE":
+ continue
+ record: Dict[str, Any] = {"date": date_val}
+ for i, code in enumerate(col_codes):
+ cell = row[i + 1] if (i + 1) < len(row) else ""
+ record[code] = _parse_value(cell)
+ data_records.append(record)
+
+ else:
+ # Columnar (CT / CN): code | date | value
+ header_offset = 1 if has_titles else 0
+ for row in rows[header_offset:]:
+ if len(row) < 3 or not row[0].strip():
+ continue
+ code = row[0].strip()
+ date_val = row[1].strip()
+ val = _parse_value(row[2])
+ data_records.append({"series_code": code, "date": date_val, "value": val})
+
+ result: Dict[str, Any] = {
+ "success": True,
+ "data": data_records,
+ "series_codes": series_codes,
+ "date_from": date_from,
+ "date_to": date_to,
+ "rows_returned": len(data_records),
+ "source": "Bank of England IADB",
+ "url": "https://www.bankofengland.co.uk/boeapps/database/",
+ "notes": (
+ "Null/None values represent missing observations (originally '..' in BoE CSV). "
+ "Data represent indicative mid-market rates unless stated otherwise. "
+ "Exchange rates are as observed by the Bank's FX Desk at approx. 4pm London time."
+ ),
+ }
+ if series_descriptions:
+ result["series_descriptions"] = series_descriptions
+ return result
+
+
+# ---------------------------------------------------------------------------
+# High-level API methods
+# ---------------------------------------------------------------------------
+
+class BankOfEnglandWrapper:
+ """
+ Full-featured Python wrapper for the Bank of England Statistical Interactive
+ Database (IADB).
+
+ Authentication: None required. The IADB is a free, public data service.
+ Rate limits : Not officially published. Avoid batching more than 300 codes
+ per request and keep concurrent requests modest.
+ """
+
+ def __init__(
+ self,
+ default_start: str = "01/Jan/1970",
+ default_end: str = "now",
+ ) -> None:
+ self.default_start = default_start
+ self.default_end = default_end
+
+ # ------------------------------------------------------------------
+ # Core fetch methods
+ # ------------------------------------------------------------------
+
+ def get_series(
+ self,
+ series_codes: Union[str, List[str]],
+ start: Optional[str] = None,
+ end: Optional[str] = None,
+ csvf: str = "TT",
+ ) -> Dict[str, Any]:
+ """
+ Fetch one or more IADB series by code.
+
+ Parameters
+ ----------
+ series_codes : str or list of str
+ One or more 7-character IADB codes (comma-separated string or list).
+ start : str, optional
+ Start date DD/Mon/YYYY. Defaults to instance default_start.
+ end : str, optional
+ End date DD/Mon/YYYY or 'now'. Defaults to instance default_end.
+ csvf : str
+ Output layout: 'TT' (tabular+headers, default), 'TN', 'CT', 'CN'.
+
+ Returns
+ -------
+ dict
+ success, data (list of observation dicts), series_codes, metadata.
+ """
+ if isinstance(series_codes, str):
+ codes = [c.strip() for c in series_codes.split(",") if c.strip()]
+ else:
+ codes = list(series_codes)
+
+ date_from = start or self.default_start
+ date_to = end or self.default_end
+
+ result = _fetch_csv(codes, date_from, date_to, csvf=csvf)
+
+ # Enrich with catalogue metadata
+ if result.get("success"):
+ result["series_metadata"] = {
+ code: SERIES_CATALOGUE.get(code, {"name": code, "description": "Unknown series"})
+ for code in codes
+ }
+
+ return result
+
+ def get_series_group(
+ self,
+ group_name: str,
+ start: Optional[str] = None,
+ end: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch a pre-defined group of related series.
+
+ Available groups: monetary_policy, gilt_yields, ois_yields,
+ gbp_spot_rates, exchange_rate_index, forward_rates,
+ quoted_mortgage_rates, quoted_deposit_rates,
+ quoted_consumer_credit_rates, effective_rates, monetary_aggregates.
+ """
+ if group_name not in SERIES_GROUPS:
+ return {
+ "success": False,
+ "error": f"Unknown group '{group_name}'. Available: {list(SERIES_GROUPS.keys())}",
+ }
+ codes = SERIES_GROUPS[group_name]
+ result = self.get_series(codes, start=start, end=end)
+ result["group"] = group_name
+ return result
+
+ # ------------------------------------------------------------------
+ # Convenience methods (by topic)
+ # ------------------------------------------------------------------
+
+ def get_bank_rate(
+ self,
+ start: Optional[str] = None,
+ end: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Fetch the Official Bank Rate (IUDBEDR) history."""
+ result = self.get_series(["IUDBEDR"], start=start, end=end)
+ result["description"] = "Bank of England Official Bank Rate set by the MPC"
+ return result
+
+ def get_sonia(
+ self,
+ start: Optional[str] = None,
+ end: Optional[str] = None,
+ include_compounded_index: bool = False,
+ ) -> Dict[str, Any]:
+ """
+ Fetch SONIA (Sterling Overnight Index Average) daily rate.
+
+ Parameters
+ ----------
+ include_compounded_index : bool
+ If True, also fetches the SONIA Compounded Index (IUASOIA).
+ """
+ codes = ["IUDSOIA"]
+ if include_compounded_index:
+ codes.append("IUASOIA")
+ result = self.get_series(codes, start=start, end=end)
+ result["description"] = "Sterling Overnight Index Average (SONIA)"
+ return result
+
+ def get_exchange_rates(
+ self,
+ currencies: Optional[List[str]] = None,
+ start: Optional[str] = None,
+ end: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch GBP spot exchange rates against major currencies.
+
+ Parameters
+ ----------
+ currencies : list of str, optional
+ Subset of currency codes e.g. ['USD', 'EUR', 'JPY'].
+ If None, fetches all available GBP spot series.
+ """
+ currency_to_code: Dict[str, str] = {
+ "USD": "XUDLUSS",
+ "EUR": "XUDLERS",
+ "JPY": "XUDLJYS",
+ "CAD": "XUDLCDS",
+ "CHF": "XUDLSFS",
+ "AUD": "XUDLADS",
+ "NOK": "XUDLNKS",
+ "SEK": "XUDLSKS",
+ "DKK": "XUDLDKS",
+ "SGD": "XUDLSGS",
+ "HKD": "XUDLHDS",
+ "TWD": "XUDLTWS",
+ "MYR": "XUDLBK25",
+ "INR": "XUDLBK83",
+ "KRW": "XUDLBK85",
+ "ZAR": "XUDLBK87",
+ }
+
+ if currencies:
+ unknown = [c for c in currencies if c.upper() not in currency_to_code]
+ if unknown:
+ return {
+ "success": False,
+ "error": f"Unknown currency codes: {unknown}. "
+ f"Available: {list(currency_to_code.keys())}",
+ }
+ codes = [currency_to_code[c.upper()] for c in currencies]
+ else:
+ codes = SERIES_GROUPS["gbp_spot_rates"]
+
+ result = self.get_series(codes, start=start, end=end)
+ result["description"] = (
+ "GBP spot exchange rates – indicative mid-market rates observed by the "
+ "Bank of England FX Desk at approximately 4pm London time. "
+ "Not official rates; published for reference."
+ )
+ result["base_currency"] = "GBP"
+ return result
+
+ def get_exchange_rate_index(
+ self,
+ start: Optional[str] = None,
+ end: Optional[str] = None,
+ broad: bool = False,
+ ) -> Dict[str, Any]:
+ """
+ Fetch the Sterling Exchange Rate Index (ERI).
+
+ Parameters
+ ----------
+ broad : bool
+ If True, also fetches the broad ERI (XUMABRD) in addition to narrow (XUMAERS).
+ """
+ codes = ["XUMAERS"]
+ if broad:
+ codes.append("XUMABRD")
+ result = self.get_series(codes, start=start, end=end)
+ result["description"] = (
+ "Sterling trade-weighted Exchange Rate Index (ERI). "
+ "Jan 2005 = 100. Annually re-weighted with world trade data."
+ )
+ return result
+
+ def get_quoted_rates(
+ self,
+ include_mortgages: bool = True,
+ include_deposits: bool = True,
+ include_consumer_credit: bool = True,
+ start: Optional[str] = None,
+ end: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch quoted household interest rates (mortgages, deposits, consumer credit).
+ Coverage begins from approximately January 2000 (mortgage data) or January 2010
+ (combined bank + building society data).
+ """
+ codes: List[str] = []
+ if include_mortgages:
+ codes.extend(SERIES_GROUPS["quoted_mortgage_rates"])
+ if include_deposits:
+ codes.extend(SERIES_GROUPS["quoted_deposit_rates"])
+ if include_consumer_credit:
+ codes.extend(SERIES_GROUPS["quoted_consumer_credit_rates"])
+
+ if not codes:
+ return {"success": False, "error": "No rate categories selected."}
+
+ result = self.get_series(codes, start=start, end=end)
+ result["description"] = (
+ "Quoted household interest rates published monthly by the Bank of England. "
+ "From January 2010, rates cover combined bank and building society data."
+ )
+ return result
+
+ def get_effective_rates(
+ self,
+ start: Optional[str] = None,
+ end: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch effective interest rates (weighted average rates on outstanding balances
+ and new business for deposits and loans).
+ """
+ result = self.get_series_group("effective_rates", start=start, end=end)
+ result["description"] = (
+ "Effective interest rates: average rates actually paid or received by "
+ "households and companies on outstanding stock and new business."
+ )
+ return result
+
+ def get_monetary_aggregates(
+ self,
+ start: Optional[str] = None,
+ end: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch UK monetary aggregate data including M4, notes & coin in circulation,
+ consumer credit, and BoE reserve balance liabilities.
+ M4 data available monthly from June 1982.
+ """
+ result = self.get_series_group("monetary_aggregates", start=start, end=end)
+ result["description"] = (
+ "UK monetary aggregates: M4 liabilities, notes and coin in circulation, "
+ "consumer credit outstanding, and BoE Banking Department sterling reserves."
+ )
+ return result
+
+ def get_yield_curves(
+ self,
+ curve_type: str = "gilt_nominal",
+ start: Optional[str] = None,
+ end: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch yield curve data from the IADB.
+
+ Parameters
+ ----------
+ curve_type : str
+ One of: 'gilt_nominal', 'gilt_inflation', 'ois'.
+ Note: The full term-structure yield curve data (per-maturity) is published
+ as ZIP downloads on the statistics/yield-curves page, not via IADB series
+ codes. The IADB series returned here are key-maturity spot/par yields.
+ """
+ group_map = {
+ "gilt_nominal": "gilt_yields",
+ "gilt_inflation": "gilt_yields", # IUDSIZC, IUDMIZC
+ "ois": "ois_yields",
+ }
+ if curve_type not in group_map:
+ return {
+ "success": False,
+ "error": f"Unknown curve_type '{curve_type}'. "
+ f"Choose from: {list(group_map.keys())}",
+ }
+
+ if curve_type == "gilt_inflation":
+ codes = ["IUDSIZC", "IUDMIZC"]
+ result = self.get_series(codes, start=start, end=end)
+ else:
+ result = self.get_series_group(group_map[curve_type], start=start, end=end)
+
+ result["description"] = (
+ f"UK yield curve data – {curve_type}. "
+ "Continuously compounded, quoted on annual basis. "
+ "Full term-structure ZIP downloads available at "
+ "https://www.bankofengland.co.uk/statistics/yield-curves"
+ )
+ result["yield_curve_zip_downloads"] = {
+ "nominal_government": "https://www.bankofengland.co.uk/statistics/yield-curves",
+ "real_government": "https://www.bankofengland.co.uk/statistics/yield-curves",
+ "inflation_government": "https://www.bankofengland.co.uk/statistics/yield-curves",
+ "ois": "https://www.bankofengland.co.uk/statistics/yield-curves",
+ }
+ return result
+
+ def get_overview(self) -> Dict[str, Any]:
+ """
+ Fetch a concise snapshot of the most important BoE series for a
+ quick dashboard view (last 3 months of data).
+ """
+ # Use a short recent window to keep the response fast
+ end = "now"
+ start = "01/Jan/2024"
+
+ snapshot_codes = [
+ "IUDBEDR", # Bank Rate
+ "IUDSOIA", # SONIA
+ "XUDLUSS", # GBP/USD
+ "XUDLERS", # GBP/EUR
+ "XUDLJYS", # GBP/JPY
+ "XUMAERS", # Sterling ERI
+ "IUDMNPY", # 10Y Gilt yield
+ "IUDZLS6", # OIS 10Y
+ ]
+
+ result = self.get_series(snapshot_codes, start=start, end=end)
+ result["description"] = (
+ "Bank of England IADB overview snapshot – key rates and exchange rates."
+ )
+ result["available_groups"] = list(SERIES_GROUPS.keys())
+ result["total_documented_series"] = len(SERIES_CATALOGUE)
+ return result
+
+ # ------------------------------------------------------------------
+ # Discovery helpers
+ # ------------------------------------------------------------------
+
+ def get_available_categories(self) -> Dict[str, Any]:
+ """Return the full series catalogue and group listings."""
+ categories: Dict[str, List[Dict]] = {}
+ for code, meta in SERIES_CATALOGUE.items():
+ cat = meta.get("category", "other")
+ if cat not in categories:
+ categories[cat] = []
+ categories[cat].append({"code": code, **meta})
+
+ return {
+ "success": True,
+ "data": {
+ "categories": categories,
+ "series_groups": {
+ name: {
+ "codes": codes,
+ "count": len(codes),
+ }
+ for name, codes in SERIES_GROUPS.items()
+ },
+ "total_series": len(SERIES_CATALOGUE),
+ },
+ "api_details": {
+ "base_url": BOE_BASE_URL,
+ "authentication": "None required",
+ "response_formats": ["CSV", "XML", "HTML", "Excel"],
+ "primary_format": "CSV",
+ "date_format": "DD/Mon/YYYY (e.g. 01/Jan/2000)",
+ "special_date_values": {"end_date": "Use 'now' for latest available data"},
+ "max_codes_per_request": {
+ "CSV": 300,
+ "HTML": 300,
+ "XML": 300,
+ "Excel": 250,
+ },
+ "csvf_options": {
+ "TT": "Tabular layout with column header titles",
+ "TN": "Tabular layout without titles",
+ "CT": "Columnar layout with titles",
+ "CN": "Columnar layout without titles",
+ },
+ "parameters": {
+ "csv.x": "yes (activates CSV mode)",
+ "Datefrom": "Start date DD/Mon/YYYY",
+ "Dateto": "End date DD/Mon/YYYY or 'now'",
+ "SeriesCodes": "Comma-separated IADB series codes",
+ "CSVF": "CSV format (TT/TN/CT/CN)",
+ "UsingCodes": "Y (mandatory when using SeriesCodes)",
+ "VPD": "Y/N – include provisional data",
+ "VFD": "Y/N – include observation footnotes",
+ },
+ "xml_only_parameters": {
+ "CodeVer": "new (required for XML mode)",
+ "xml.x": "yes",
+ "VUD": "A=all observations, B=updated only",
+ "VUDdate": "DD/Mon/YYYY or 'latest' – filter updates since date",
+ },
+ "missing_value_codes": {
+ "..": "Data not available for this period",
+ "N/a": "Not applicable",
+ },
+ "data_update_schedule": "Aim: by 10am on publication day; daily rates 1-2 working days after reporting date",
+ "historical_depth": "Some daily series back to 1975; M4 monthly from June 1982",
+ "contact": "[email protected]",
+ "database_home": "https://www.bankofengland.co.uk/boeapps/database/",
+ "help_page": "https://www.bankofengland.co.uk/boeapps/database/help.asp",
+ "statistics_home": "https://www.bankofengland.co.uk/statistics",
+ },
+ "source": "Bank of England IADB",
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI entry point
+# ---------------------------------------------------------------------------
+
+def _parse_cli_args(argv: List[str]) -> Dict[str, Any]:
+ """Very simple key=value / --key value argument parser."""
+ parsed: Dict[str, Any] = {}
+ i = 0
+ while i < len(argv):
+ tok = argv[i]
+ if tok.startswith("--"):
+ key = tok[2:]
+ if "=" in key:
+ k, v = key.split("=", 1)
+ parsed[k] = v
+ elif i + 1 < len(argv) and not argv[i + 1].startswith("--"):
+ parsed[key] = argv[i + 1]
+ i += 1
+ else:
+ parsed[key] = True
+ i += 1
+ return parsed
+
+
+def main(args: Optional[List[str]] = None) -> None:
+ if args is None:
+ args = sys.argv[1:]
+
+ if not args:
+ print(json.dumps({
+ "success": False,
+ "error": "No command supplied.",
+ "usage": "python boe_data.py <command> [options]",
+ "commands": [
+ "available_categories",
+ "overview",
+ "bank_rate [--start DD/Mon/YYYY] [--end DD/Mon/YYYY|now]",
+ "sonia [--start ...] [--end ...] [--compounded Y]",
+ "exchange_rates [--currencies USD,EUR,JPY,...] [--start ...] [--end ...]",
+ "exchange_rate_index [--broad Y] [--start ...] [--end ...]",
+ "quoted_rates [--start ...] [--end ...]",
+ "effective_rates [--start ...] [--end ...]",
+ "monetary_aggregates [--start ...] [--end ...]",
+ "yield_curves [--type gilt_nominal|gilt_inflation|ois] [--start ...] [--end ...]",
+ "group --name <group_name> [--start ...] [--end ...]",
+ "series --codes CODE1,CODE2,... [--start ...] [--end ...]",
+ ],
+ }, indent=2))
+ sys.exit(1)
+
+ command = args[0]
+ kwargs = _parse_cli_args(args[1:])
+ wrapper = BankOfEnglandWrapper()
+
+ try:
+ start = kwargs.get("start")
+ end = kwargs.get("end")
+
+ if command == "available_categories":
+ result = wrapper.get_available_categories()
+
+ elif command == "overview":
+ result = wrapper.get_overview()
+
+ elif command == "bank_rate":
+ result = wrapper.get_bank_rate(start=start, end=end)
+
+ elif command == "sonia":
+ compounded = str(kwargs.get("compounded", "N")).upper() == "Y"
+ result = wrapper.get_sonia(
+ start=start, end=end, include_compounded_index=compounded
+ )
+
+ elif command == "exchange_rates":
+ raw_currencies = kwargs.get("currencies")
+ currencies = (
+ [c.strip().upper() for c in raw_currencies.split(",")]
+ if raw_currencies else None
+ )
+ result = wrapper.get_exchange_rates(
+ currencies=currencies, start=start, end=end
+ )
+
+ elif command == "exchange_rate_index":
+ broad = str(kwargs.get("broad", "N")).upper() == "Y"
+ result = wrapper.get_exchange_rate_index(start=start, end=end, broad=broad)
+
+ elif command == "quoted_rates":
+ result = wrapper.get_quoted_rates(start=start, end=end)
+
+ elif command == "effective_rates":
+ result = wrapper.get_effective_rates(start=start, end=end)
+
+ elif command == "monetary_aggregates":
+ result = wrapper.get_monetary_aggregates(start=start, end=end)
+
+ elif command == "yield_curves":
+ curve_type = kwargs.get("type", "gilt_nominal")
+ result = wrapper.get_yield_curves(
+ curve_type=curve_type, start=start, end=end
+ )
+
+ elif command == "group":
+ name = kwargs.get("name")
+ if not name:
+ result = {
+ "success": False,
+ "error": "Provide --name <group_name>. "
+ f"Available: {list(SERIES_GROUPS.keys())}",
+ }
+ else:
+ result = wrapper.get_series_group(name, start=start, end=end)
+
+ elif command == "series":
+ raw_codes = kwargs.get("codes", "")
+ if not raw_codes:
+ result = {
+ "success": False,
+ "error": "Provide --codes CODE1,CODE2,... (e.g. --codes IUDBEDR,IUDSOIA)",
+ }
+ else:
+ codes = [c.strip() for c in raw_codes.split(",") if c.strip()]
+ result = wrapper.get_series(codes, start=start, end=end)
+
+ else:
+ result = {
+ "success": False,
+ "error": f"Unknown command: '{command}'. Run without arguments for usage.",
+ }
+
+ print(json.dumps(result, indent=2, default=str))
+
+ except KeyboardInterrupt:
+ sys.exit(0)
+ except Exception as exc:
+ print(json.dumps({"success": False, "error": str(exc)}, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/boi_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/boi_data.py
new file mode 100644
index 000000000..18c65e8af
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/boi_data.py
@@ -0,0 +1,378 @@
+"""
+Bank of Israel (BOI) Data Wrapper
+Fetches data from the Bank of Israel public APIs.
+
+API References:
+ SDMX REST API:
+ Base URL: https://edge.boi.gov.il/FusionEdgeServer/sdmx/v2
+ Format: CSV (csvdata) or XML
+ Auth: None required — fully public
+ Docs: https://edge.boi.gov.il/FusionEdgeServer/sdmx/v2/swagger-ui/
+
+ Public JSON API:
+ Base URL: https://www.boi.org.il/PublicApi
+ Auth: None required
+
+Dataflows (SDMX):
+ EXR — Exchange rates (ILS per foreign currency)
+ Series pattern: RER_{CCY}_ILS (e.g. RER_USD_ILS, RER_EUR_ILS)
+ Special: NER_ILS_BSK_IDX — effective exchange rate index
+ NER_ILS_BSK_PCT — percent change in effective rate
+ Unit multiplier in column UNIT_MULT:
+ 0 → rate as-is (e.g. USD/ILS = 3.12)
+ 1 → rate ÷ 10 (e.g. LBP)
+ 2 → rate ÷ 100 (e.g. JPY/ILS reported per 100 JPY)
+
+ Public JSON /GetExchangeRates — latest spot rates with daily change
+
+Key exchange rate series:
+ RER_USD_ILS, RER_EUR_ILS, RER_GBP_ILS, RER_JPY_ILS,
+ RER_CHF_ILS, RER_AUD_ILS, RER_CAD_ILS, RER_SEK_ILS,
+ RER_NOK_ILS, RER_DKK_ILS, RER_ZAR_ILS, RER_JOD_ILS
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import csv
+import io
+import json
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime, date, timedelta, timezone
+
+
+SDMX_URL = "https://edge.boi.gov.il/FusionEdgeServer/sdmx/v2"
+PUBLIC_URL = "https://www.boi.org.il/PublicApi"
+DEFAULT_TIMEOUT = 30
+
+# All known EXR series codes with their base currency and unit multiplier
+EXR_SERIES: Dict[str, Dict[str, Any]] = {
+ "RER_USD_ILS": {"base": "USD", "label": "USD/ILS", "multiplier": 1},
+ "RER_EUR_ILS": {"base": "EUR", "label": "EUR/ILS", "multiplier": 1},
+ "RER_GBP_ILS": {"base": "GBP", "label": "GBP/ILS", "multiplier": 1},
+ "RER_JPY_ILS": {"base": "JPY", "label": "JPY/ILS (per 100)", "multiplier": 100},
+ "RER_CHF_ILS": {"base": "CHF", "label": "CHF/ILS", "multiplier": 1},
+ "RER_AUD_ILS": {"base": "AUD", "label": "AUD/ILS", "multiplier": 1},
+ "RER_CAD_ILS": {"base": "CAD", "label": "CAD/ILS", "multiplier": 1},
+ "RER_SEK_ILS": {"base": "SEK", "label": "SEK/ILS", "multiplier": 1},
+ "RER_NOK_ILS": {"base": "NOK", "label": "NOK/ILS", "multiplier": 1},
+ "RER_DKK_ILS": {"base": "DKK", "label": "DKK/ILS", "multiplier": 1},
+ "RER_ZAR_ILS": {"base": "ZAR", "label": "ZAR/ILS", "multiplier": 1},
+ "RER_JOD_ILS": {"base": "JOD", "label": "JOD/ILS", "multiplier": 1},
+ "RER_EGP_ILS": {"base": "EGP", "label": "EGP/ILS", "multiplier": 1},
+ "NER_ILS_BSK_IDX": {"base": "BASKET", "label": "Nominal effective exchange rate index", "multiplier": 1},
+ "NER_ILS_BSK_PCT": {"base": "BASKET", "label": "Nominal effective exchange rate % change", "multiplier": 1},
+}
+
+MAJOR_SERIES = ["RER_USD_ILS", "RER_EUR_ILS", "RER_GBP_ILS", "RER_JPY_ILS",
+ "RER_CHF_ILS", "RER_AUD_ILS", "RER_CAD_ILS"]
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class BOIError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "BOIError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class BOIWrapper:
+ """
+ Wrapper for the Bank of Israel public data APIs.
+
+ Exchange rates are ILS (New Israeli Shekel) per 1 unit of foreign currency,
+ except JPY which is per 100 JPY (multiplier=100).
+ Data is published on Israeli business days (Sun–Thu).
+ """
+
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Accept": "text/csv, application/json, */*",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _sdmx_csv(self, dataflow: str, series_key: str = "",
+ start: Optional[str] = None,
+ end: Optional[str] = None) -> str:
+ """Fetch SDMX CSV data from the BOI FusionEdge server."""
+ path = f"{SDMX_URL}/data/dataflow/BOI.STATISTICS/{dataflow}/1.0"
+ if series_key:
+ path = f"{path}/{series_key}"
+ params: Dict[str, str] = {"format": "csvdata"}
+ if start:
+ params["startperiod"] = start
+ if end:
+ params["endperiod"] = end
+ resp = self.session.get(path, params=params, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.text
+
+ def _parse_exr_csv(self, text: str) -> List[Dict[str, Any]]:
+ """
+ Parse BOI EXR CSV into wide-format rows keyed by date.
+ Handles UNIT_MULT: obs value is already in ILS per currency unit,
+ but for series with multiplier>1 (e.g. JPY), we note it in label.
+ """
+ reader = csv.DictReader(io.StringIO(text))
+ wide: Dict[str, Dict[str, Any]] = {}
+ for row in reader:
+ series = row.get("SERIES_CODE", "").strip()
+ d = row.get("TIME_PERIOD", "").strip()
+ val = row.get("OBS_VALUE", "").strip()
+ if not d or not series:
+ continue
+ if d not in wide:
+ wide[d] = {"date": d}
+ if val not in ("", "..", "N/A"):
+ try:
+ wide[d][series] = float(val)
+ except ValueError:
+ wide[d][series] = val
+ return sorted(wide.values(), key=lambda r: r["date"])
+
+ def _public_json(self, path: str, params: Optional[Dict] = None) -> Any:
+ """Fetch from the BOI PublicApi JSON endpoint."""
+ url = f"{PUBLIC_URL}/{path}"
+ resp = self.session.get(url, params=params or {}, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.json()
+
+ # ------------------------------------------------------------------
+ # Public methods
+ # ------------------------------------------------------------------
+
+ def get_exchange_rates_today(self) -> Dict[str, Any]:
+ """Latest ILS exchange rates from the PublicApi (with daily change %)."""
+ try:
+ data = self._public_json("GetExchangeRates")
+ rates = data.get("exchangeRates", [])
+ result_rows = []
+ for r in rates:
+ result_rows.append({
+ "currency": r.get("key"),
+ "rate": r.get("currentExchangeRate"),
+ "change_pct": round(r.get("currentChange", 0), 6),
+ "unit": r.get("unit", 1),
+ "last_update": r.get("lastUpdate"),
+ })
+ return {
+ "success": True,
+ "data": result_rows,
+ "count": len(result_rows),
+ "note": "ILS per 1 unit of foreign currency (unit=1) or per unit quantity",
+ "source": "Bank of Israel",
+ "url": f"{PUBLIC_URL}/GetExchangeRates",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BOIError("GetExchangeRates", str(e), sc).to_dict()
+ except Exception as e:
+ return BOIError("GetExchangeRates", str(e)).to_dict()
+
+ def get_exchange_rate_history(self, currencies: Optional[List[str]] = None,
+ start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """Historical ILS exchange rates via SDMX (wide format by date)."""
+ if currencies is None:
+ currencies = ["USD", "EUR", "GBP", "JPY", "CHF", "AUD", "CAD"]
+ if start is None:
+ start = (date.today() - timedelta(days=90)).isoformat()
+ series_codes = "+".join(f"RER_{c}_ILS" for c in currencies)
+ try:
+ text = self._sdmx_csv("EXR", series_codes, start, end)
+ rows = self._parse_exr_csv(text)
+ return {
+ "success": True,
+ "currencies": currencies,
+ "start": start,
+ "end": end or date.today().isoformat(),
+ "data": rows,
+ "count": len(rows),
+ "note": "ILS per foreign currency unit; JPY series is per 100 JPY",
+ "source": "Bank of Israel",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BOIError("EXR history", str(e), sc).to_dict()
+ except Exception as e:
+ return BOIError("EXR history", str(e)).to_dict()
+
+ def get_usd_ils(self, start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """USD/ILS exchange rate history."""
+ return self.get_exchange_rate_history(["USD"], start, end)
+
+ def get_eur_ils(self, start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """EUR/ILS exchange rate history."""
+ return self.get_exchange_rate_history(["EUR"], start, end)
+
+ def get_effective_rate(self, start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """Nominal effective exchange rate index (basket) and % change."""
+ if start is None:
+ start = (date.today() - timedelta(days=365)).isoformat()
+ try:
+ text = self._sdmx_csv("EXR", "NER_ILS_BSK_IDX+NER_ILS_BSK_PCT", start, end)
+ rows = self._parse_exr_csv(text)
+ return {
+ "success": True,
+ "series": ["NER_ILS_BSK_IDX", "NER_ILS_BSK_PCT"],
+ "start": start,
+ "data": rows,
+ "count": len(rows),
+ "note": "Nominal effective exchange rate index (higher = stronger ILS)",
+ "source": "Bank of Israel",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BOIError("NER", str(e), sc).to_dict()
+ except Exception as e:
+ return BOIError("NER", str(e)).to_dict()
+
+ def get_all_rates_history(self, start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """All EXR series in wide format (all currencies vs ILS)."""
+ if start is None:
+ start = (date.today() - timedelta(days=30)).isoformat()
+ try:
+ text = self._sdmx_csv("EXR", start=start, end=end)
+ rows = self._parse_exr_csv(text)
+ return {
+ "success": True,
+ "start": start,
+ "data": rows,
+ "count": len(rows),
+ "series": list(EXR_SERIES.keys()),
+ "note": "ILS per foreign currency unit",
+ "source": "Bank of Israel",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return BOIError("EXR all", str(e), sc).to_dict()
+ except Exception as e:
+ return BOIError("EXR all", str(e)).to_dict()
+
+ def get_overview(self) -> Dict[str, Any]:
+ """Snapshot: latest rates (PublicApi) + USD & EUR history."""
+ today = self.get_exchange_rates_today()
+ usd_hist = self.get_usd_ils(
+ start=(date.today() - timedelta(days=7)).isoformat()
+ )
+ return {
+ "success": True,
+ "data": {
+ "latest_rates": today,
+ "usd_week": usd_hist.get("data", [])[-5:],
+ },
+ "source": "Bank of Israel",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def available_series(self) -> Dict[str, Any]:
+ """Built-in EXR series catalogue."""
+ return {
+ "success": True,
+ "data": EXR_SERIES,
+ "note": "All rates expressed as ILS per 1 unit of foreign currency",
+ "source": "Bank of Israel",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "today": " — Latest ILS rates (all currencies) with daily change",
+ "history": "[currencies] [start] [end] — Historical rates (wide format)",
+ "usd": "[start] [end] — USD/ILS history",
+ "eur": "[start] [end] — EUR/ILS history",
+ "effective": "[start] [end] — Nominal effective exchange rate index",
+ "all": "[start] [end] — All series history (wide format)",
+ "overview": " — Snapshot: latest + USD week",
+ "available": " — Series catalogue",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python boi_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = BOIWrapper()
+
+ try:
+ if cmd == "today":
+ result = wrapper.get_exchange_rates_today()
+ elif cmd in ("history", "fx"):
+ raw = _a(2, "USD,EUR,GBP,JPY,CHF,AUD,CAD")
+ ccys = [c.strip().upper() for c in raw.split(",")]
+ result = wrapper.get_exchange_rate_history(ccys, _a(3), _a(4))
+ elif cmd == "usd":
+ result = wrapper.get_usd_ils(_a(2), _a(3))
+ elif cmd == "eur":
+ result = wrapper.get_eur_ils(_a(2), _a(3))
+ elif cmd in ("effective", "ner"):
+ result = wrapper.get_effective_rate(_a(2), _a(3))
+ elif cmd == "all":
+ result = wrapper.get_all_rates_history(_a(2), _a(3))
+ elif cmd == "overview":
+ result = wrapper.get_overview()
+ elif cmd in ("available", "series"):
+ result = wrapper.available_series()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=True))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/cnb_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/cnb_data.py
new file mode 100644
index 000000000..83c4478e6
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/cnb_data.py
@@ -0,0 +1,477 @@
+"""
+Czech National Bank (CNB) Data Wrapper
+Fetches data from the CNB public REST API.
+
+API Reference:
+ Base URL: https://api.cnb.cz/cnbapi
+ Format: JSON
+ Auth: None required — fully public
+ Docs: https://api.cnb.cz/cnbapi/swagger-ui.html
+
+Verified Endpoints:
+ GET /exrates/daily?[date=YYYY-MM-DD]&lang=EN
+ Daily CZK exchange rate fixing (33 currencies)
+ GET /exrates/daily-year?year=YYYY&lang=EN
+ All daily fixings for a year
+ GET /exrates/daily-currency-month?year=YYYY&month=MM&currencyCode=USD&lang=EN
+ Single currency by month
+ GET /exrates/monthly-averages-year?year=YYYY&lang=EN
+ Monthly average rates for a year
+ GET /czeonia/daily?[date=YYYY-MM-DD]&lang=EN
+ CZEONIA overnight rate (Czech equivalent of EONIA)
+ GET /czeonia/daily-year?year=YYYY&lang=EN
+ CZEONIA for a full year
+ GET /pribor/daily?[date=YYYY-MM-DD]&lang=EN
+ PRIBOR fixing (1D, 1W, 2W, 1M, 2M, 3M, 6M, 9M, 12M)
+ GET /pribor/daily-year?year=YYYY&lang=EN
+ PRIBOR for a full year
+ GET /pribor/daily-year-term?year=YYYY&term=THREE_MONTH&lang=EN
+ PRIBOR for a term and year
+ GET /omo/daily?[date=YYYY-MM-DD]&lang=EN
+ Open market operations (repo, deposit facility)
+ GET /forward/daily?[date=YYYY-MM-DD]&lang=EN
+ Forward exchange rates (EUR/CZK, USD/CZK)
+ GET /fxrates/daily-year?year=YYYY&lang=EN
+ FX rates for currencies not in fixing table
+ GET /skd/daily?[date=YYYY-MM-DD]&lang=EN
+ Short-term government debt (SKD) rates
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime, date, timedelta, timezone
+
+
+BASE_URL = "https://api.cnb.cz/cnbapi"
+DEFAULT_TIMEOUT = 30
+DEFAULT_LANG = "EN"
+
+# PRIBOR tenor codes
+PRIBOR_TERMS = ["ONE_DAY", "ONE_WEEK", "TWO_WEEKS", "ONE_MONTH",
+ "TWO_MONTHS", "THREE_MONTHS", "SIX_MONTHS", "NINE_MONTHS", "TWELVE_MONTHS"]
+
+# Main fixing currencies (Table A equivalent)
+FIXING_CURRENCIES = [
+ "AUD", "BGN", "BRL", "CAD", "CHF", "CNY", "DKK", "EUR", "GBP",
+ "HKD", "HRK", "HUF", "IDR", "ILS", "INR", "ISK", "JPY", "KRW",
+ "MXN", "MYR", "NOK", "NZD", "PHP", "PLN", "RON", "RSD", "RUB",
+ "SEK", "SGD", "THB", "TRY", "USD", "ZAR",
+]
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class CNBError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "CNBError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class CNBWrapper:
+ """
+ Wrapper for the Czech National Bank (CNB) public REST API.
+
+ Provides exchange rates, PRIBOR, CZEONIA, OMO, and forward rates.
+ All rates are expressed as CZK per foreign currency (or per amount).
+ No authentication required.
+ """
+
+ def __init__(self, lang: str = DEFAULT_LANG):
+ self.lang = lang
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Accept": "application/json",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _get(self, path: str, params: Optional[Dict] = None) -> Any:
+ url = f"{BASE_URL}/{path.lstrip('/')}"
+ p = {"lang": self.lang, **(params or {})}
+ resp = self.session.get(url, params=p, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.json()
+
+ def _safe(self, path: str, label: str,
+ params: Optional[Dict] = None) -> Dict[str, Any]:
+ try:
+ data = self._get(path, params)
+ return {
+ "success": True,
+ "data": data,
+ "source": "Czech National Bank",
+ "url": f"{BASE_URL}/{path}",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return CNBError(label, str(e), sc).to_dict()
+ except Exception as e:
+ return CNBError(label, str(e)).to_dict()
+
+ def _flatten_rates(self, raw_rates: List[Dict],
+ amount_key: str = "amount") -> List[Dict]:
+ """Normalize a rates list to {date, currencyCode: rate_per_unit}."""
+ by_date: Dict[str, Dict] = {}
+ for r in raw_rates:
+ d = r.get("validFor", "")
+ code = r.get("currencyCode", "")
+ rate = r.get("rate")
+ amt = r.get(amount_key, 1)
+ if not d or not code:
+ continue
+ by_date.setdefault(d, {"date": d})
+ if rate is not None and amt:
+ by_date[d][code] = round(rate / amt, 6) if amt != 1 else rate
+ return sorted(by_date.values(), key=lambda x: x["date"])
+
+ # ------------------------------------------------------------------
+ # Public methods
+ # ------------------------------------------------------------------
+
+ def get_exchange_rates(self, rate_date: Optional[str] = None) -> Dict[str, Any]:
+ """Daily CZK exchange rate fixing. rate_date: YYYY-MM-DD (default=latest)."""
+ params = {}
+ if rate_date:
+ params["date"] = rate_date
+ try:
+ raw = self._get("exrates/daily", params)
+ rates = raw.get("rates", [])
+ rows = self._flatten_rates(rates)
+ return {
+ "success": True,
+ "date": rates[0].get("validFor", rate_date) if rates else rate_date,
+ "data": rows[0] if rows else {},
+ "all_rates": rates,
+ "count": len(rates),
+ "note": "CZK per 1 unit of foreign currency (adjusted for amount)",
+ "source": "Czech National Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return CNBError("exrates/daily", str(e), sc).to_dict()
+ except Exception as e:
+ return CNBError("exrates/daily", str(e)).to_dict()
+
+ def get_exchange_rates_year(self, year: Optional[int] = None) -> Dict[str, Any]:
+ """All daily CZK fixings for a year."""
+ y = year or datetime.now(timezone.utc).year
+ try:
+ raw = self._get("exrates/daily-year", {"year": y})
+ rates = raw.get("rates", [])
+ rows = self._flatten_rates(rates)
+ return {
+ "success": True,
+ "year": y,
+ "data": rows,
+ "count": len(rates),
+ "source": "Czech National Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return CNBError("exrates/daily-year", str(e), sc).to_dict()
+ except Exception as e:
+ return CNBError("exrates/daily-year", str(e)).to_dict()
+
+ def get_exchange_rates_monthly_avg(self, year: Optional[int] = None) -> Dict[str, Any]:
+ """Monthly average CZK rates for a year."""
+ y = year or datetime.now(timezone.utc).year
+ try:
+ raw = self._get("exrates/monthly-averages-year", {"year": y})
+ avgs = raw.get("averages", [])
+ # Pivot by month
+ by_month: Dict[str, Dict] = {}
+ for r in avgs:
+ month = r.get("month", "")
+ code = r.get("currencyCode", "")
+ val = r.get("average")
+ amt = r.get("amount", 1)
+ if not month or not code:
+ continue
+ key = f"{y}-{month}"
+ by_month.setdefault(key, {"date": key})
+ if val is not None and amt:
+ by_month[key][code] = round(val / amt, 6) if amt != 1 else val
+ rows = sorted(by_month.values(), key=lambda x: x["date"])
+ return {
+ "success": True,
+ "year": y,
+ "data": rows,
+ "count": len(rows),
+ "source": "Czech National Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return CNBError("exrates/monthly-averages-year", str(e), sc).to_dict()
+ except Exception as e:
+ return CNBError("exrates/monthly-averages-year", str(e)).to_dict()
+
+ def get_czeonia(self, rate_date: Optional[str] = None) -> Dict[str, Any]:
+ """CZEONIA overnight rate (latest or specific date)."""
+ params = {}
+ if rate_date:
+ params["date"] = rate_date
+ return self._safe("czeonia/daily", "czeonia/daily", params)
+
+ def get_czeonia_year(self, year: Optional[int] = None) -> Dict[str, Any]:
+ """CZEONIA for full year."""
+ y = year or datetime.now(timezone.utc).year
+ return self._safe("czeonia/daily-year", "czeonia/daily-year", {"year": y})
+
+ def get_pribor(self, rate_date: Optional[str] = None) -> Dict[str, Any]:
+ """PRIBOR fixing — all tenors (1D to 12M)."""
+ params = {}
+ if rate_date:
+ params["date"] = rate_date
+ try:
+ raw = self._get("pribor/daily", params)
+ pribs = raw.get("pribs", [])
+ # Build wide row by period
+ if not pribs:
+ return {"success": True, "data": {}, "source": "Czech National Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp())}
+ entry: Dict[str, Any] = {"date": pribs[0].get("validFor", "")}
+ for p in pribs:
+ period = p.get("period", "")
+ val = p.get("pribor")
+ if period and val is not None:
+ entry[period] = val
+ return {
+ "success": True,
+ "data": entry,
+ "source": "Czech National Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return CNBError("pribor/daily", str(e), sc).to_dict()
+ except Exception as e:
+ return CNBError("pribor/daily", str(e)).to_dict()
+
+ def get_pribor_year(self, year: Optional[int] = None,
+ term: str = "THREE_MONTHS") -> Dict[str, Any]:
+ """PRIBOR for a specific term and year. term: ONE_DAY, THREE_MONTHS, etc."""
+ y = year or datetime.now(timezone.utc).year
+ params = {"year": y, "term": term}
+ try:
+ raw = self._get("pribor/daily-year-term", params)
+ pribs = raw.get("pribs", [])
+ rows = [{"date": p.get("validFor", ""), "pribor": p.get("pribor"),
+ "pribid": p.get("pribid")} for p in pribs]
+ return {
+ "success": True,
+ "year": y,
+ "term": term,
+ "data": rows,
+ "count": len(rows),
+ "source": "Czech National Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return CNBError("pribor/daily-year-term", str(e), sc).to_dict()
+ except Exception as e:
+ return CNBError("pribor/daily-year-term", str(e)).to_dict()
+
+ def get_omo(self, trade_date: Optional[str] = None) -> Dict[str, Any]:
+ """Open market operations (repo, deposit facility)."""
+ params = {}
+ if trade_date:
+ params["date"] = trade_date
+ return self._safe("omo/daily", "omo/daily", params)
+
+ def get_forward_rates(self, rate_date: Optional[str] = None) -> Dict[str, Any]:
+ """Forward exchange rates (EUR/CZK, USD/CZK)."""
+ params = {}
+ if rate_date:
+ params["date"] = rate_date
+ return self._safe("forward/daily", "forward/daily", params)
+
+ def get_skd(self, trade_date: Optional[str] = None) -> Dict[str, Any]:
+ """Short-term government debt (SKD) rates."""
+ params = {}
+ if trade_date:
+ params["date"] = trade_date
+ return self._safe("skd/daily", "skd/daily", params)
+
+ def get_overview(self) -> Dict[str, Any]:
+ """Snapshot: today's FX rates, PRIBOR, CZEONIA, OMO."""
+ results: Dict[str, Any] = {}
+ for name, call in [
+ ("exchange_rates", self.get_exchange_rates),
+ ("pribor", self.get_pribor),
+ ("czeonia", self.get_czeonia),
+ ("omo", self.get_omo),
+ ("forward_rates", self.get_forward_rates),
+ ]:
+ r = call()
+ results[name] = {
+ "success": r.get("success"),
+ "data": r.get("data"),
+ }
+ return {
+ "success": True,
+ "data": results,
+ "source": "Czech National Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_pribor_history(self, years: int = 2,
+ term: str = "THREE_MONTHS") -> Dict[str, Any]:
+ """PRIBOR for multiple years merged into one series."""
+ current_year = datetime.now(timezone.utc).year
+ all_rows: List[Dict] = []
+ for y in range(current_year - years + 1, current_year + 1):
+ r = self.get_pribor_year(y, term)
+ all_rows.extend(r.get("data", []))
+ return {
+ "success": True,
+ "term": term,
+ "years": years,
+ "data": sorted(all_rows, key=lambda x: x["date"]),
+ "count": len(all_rows),
+ "source": "Czech National Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def available_endpoints(self) -> Dict[str, Any]:
+ """List all available endpoints."""
+ return {
+ "success": True,
+ "data": {
+ "exchange_rates": {
+ "today": "/exrates/daily",
+ "year": "/exrates/daily-year?year=YYYY",
+ "monthly_avg": "/exrates/monthly-averages-year?year=YYYY",
+ "currency_month":"/exrates/daily-currency-month?year=YYYY&month=MM&currencyCode=USD",
+ },
+ "interest_rates": {
+ "pribor_today": "/pribor/daily",
+ "pribor_year": "/pribor/daily-year?year=YYYY",
+ "pribor_term": "/pribor/daily-year-term?year=YYYY&term=THREE_MONTHS",
+ "czeonia_today": "/czeonia/daily",
+ "czeonia_year": "/czeonia/daily-year?year=YYYY",
+ },
+ "market_operations": {
+ "omo": "/omo/daily",
+ "forward": "/forward/daily",
+ "skd": "/skd/daily",
+ },
+ },
+ "pribor_terms": PRIBOR_TERMS,
+ "fixing_currencies": FIXING_CURRENCIES,
+ "source": "Czech National Bank",
+ "swagger": f"{BASE_URL}/swagger-ui.html",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "exchange_rates": "[date YYYY-MM-DD] — Daily CZK fixing (latest or date)",
+ "exchange_rates_y": "[year] — All daily fixings for a year",
+ "monthly_avg": "[year] — Monthly average rates",
+ "pribor": "[date] — PRIBOR all tenors (1D–12M)",
+ "pribor_year": "[year] [term=THREE_MONTHS] — PRIBOR for a term + year",
+ "pribor_history": "[years=2] [term=THREE_MONTHS] — PRIBOR multi-year history",
+ "czeonia": "[date] — CZEONIA overnight rate",
+ "czeonia_year": "[year] — CZEONIA for full year",
+ "omo": "[date] — Open market operations",
+ "forward": "[date] — Forward exchange rates",
+ "skd": "[date] — Short-term govt debt rates",
+ "overview": " — Today's snapshot",
+ "available": " — List all endpoints",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python cnb_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = CNBWrapper()
+
+ try:
+ if cmd == "exchange_rates":
+ result = wrapper.get_exchange_rates(_a(2))
+ elif cmd == "exchange_rates_y":
+ result = wrapper.get_exchange_rates_year(int(_a(2, datetime.now().year)))
+ elif cmd == "monthly_avg":
+ result = wrapper.get_exchange_rates_monthly_avg(int(_a(2, datetime.now().year)))
+ elif cmd == "pribor":
+ result = wrapper.get_pribor(_a(2))
+ elif cmd == "pribor_year":
+ result = wrapper.get_pribor_year(int(_a(2, datetime.now().year)), _a(3, "THREE_MONTHS"))
+ elif cmd == "pribor_history":
+ result = wrapper.get_pribor_history(int(_a(2, 2)), _a(3, "THREE_MONTHS"))
+ elif cmd == "czeonia":
+ result = wrapper.get_czeonia(_a(2))
+ elif cmd == "czeonia_year":
+ result = wrapper.get_czeonia_year(int(_a(2, datetime.now().year)))
+ elif cmd == "omo":
+ result = wrapper.get_omo(_a(2))
+ elif cmd == "forward":
+ result = wrapper.get_forward_rates(_a(2))
+ elif cmd == "skd":
+ result = wrapper.get_skd(_a(2))
+ elif cmd == "overview":
+ result = wrapper.get_overview()
+ elif cmd in ("available", "endpoints"):
+ result = wrapper.available_endpoints()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/faostat_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/faostat_data.py
new file mode 100644
index 000000000..82af6c41f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/faostat_data.py
@@ -0,0 +1,384 @@
+"""
+FAOSTAT API Data Fetcher
+Wrapper for the UN Food and Agriculture Organization (FAO) FAOSTAT database.
+Covers crop production, trade, food security, emissions, prices, land use, and more.
+
+Base URL: https://fenixservices.fao.org/faostat/api/v1/en/
+Auth: None required - fully public API
+Bulk CDN: https://bulks-faostat.fao.org/production/datasets_E.json
+
+Key domain codes:
+ QCL - Crops and Livestock Products
+ TCL - Trade: Crops and Livestock
+ TM - Bilateral Trade Matrix
+ FBS - Food Balances (2010+)
+ FS - Food Security Indicators
+ RL - Land Use
+ RFN - Fertilizers by Nutrient
+ GLE - GHG Emissions: Land Use
+ GV - GHG Emissions: Livestock
+ PP - Producer Prices
+ CP - Consumer Price Indices
+ OA - Population
+ OEA - Employment in Agriculture
+ FO - Forestry
+ SDGB - SDG Indicators
+"""
+
+import sys
+import json
+import requests
+from datetime import datetime, timezone
+from typing import Dict, Any, Optional, List
+
+BASE_URL = "https://fenixservices.fao.org/faostat/api/v1/en"
+BULK_URL = "https://bulks-faostat.fao.org/production/datasets_E.json"
+
+DOMAIN_CODES = {
+ "QCL": "Crops and Livestock Products",
+ "QI": "Production Indices",
+ "QV": "Value of Agricultural Production",
+ "TCL": "Trade: Crops and Livestock",
+ "TM": "Bilateral Trade Matrix",
+ "FBS": "Food Balances (2010+)",
+ "FBSH":"Food Balances (historical)",
+ "SCL": "Supply Utilization Accounts",
+ "FS": "Food Security Indicators",
+ "CAHD":"Cost and Affordability of Healthy Diets",
+ "RL": "Land Use",
+ "RFN": "Fertilizers by Nutrient",
+ "EP": "Pesticides Use",
+ "GLE": "GHG Emissions: Land Use",
+ "GV": "GHG Emissions: Livestock",
+ "GCE": "GHG Emissions: Crop Residues",
+ "GN": "GHG Emissions: Synthetic Fertilizers",
+ "EI": "Emissions Intensities",
+ "FO": "Forestry Production and Trade",
+ "PP": "Producer Prices",
+ "PA": "Producer Prices (archive)",
+ "CP": "Consumer Price Indices",
+ "OA": "Population",
+ "OEA": "Employment in Agriculture",
+ "FA": "Food Aid Shipments (WFP)",
+ "MK": "Macro-Statistics (GDP)",
+ "CS": "Credit to Agriculture",
+ "IG": "Government Investment in Agriculture",
+ "SDGB":"SDG Indicators",
+ "WCAD":"World Census of Agriculture",
+}
+
+
+class FAOSTATWrapper:
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({"User-Agent": "Fincept-Terminal/1.0", "Accept": "application/json"})
+
+ def _get(self, path: str, params: Optional[Dict] = None) -> Dict[str, Any]:
+ try:
+ p = {k: v for k, v in (params or {}).items() if v is not None}
+ p.setdefault("output_type", "objects")
+ r = self.session.get(f"{BASE_URL}/{path}", params=p, timeout=45)
+ r.raise_for_status()
+ data = r.json()
+ records = data.get("data", data) if isinstance(data, dict) else data
+ return {
+ "success": True, "endpoint": path, "data": records,
+ "count": len(records) if isinstance(records, list) else None,
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ return {"success": False, "error": f"HTTP {e.response.status_code}: {e.response.text[:200]}", "endpoint": path, "status_code": e.response.status_code}
+ except Exception as e:
+ return {"success": False, "error": str(e), "endpoint": path}
+
+ def _fmt(self, v) -> Optional[str]:
+ if v is None:
+ return None
+ return ",".join(str(x) for x in v) if isinstance(v, list) else str(v)
+
+ def get_data(self, domain: str, areas=None, items=None, elements=None, years=None,
+ area_cs: str = "ISO3", limit: int = 10000, show_codes: bool = True) -> Dict[str, Any]:
+ """Generic data query for any FAOSTAT domain."""
+ result = self._get(f"data/{domain}", {
+ "area": self._fmt(areas), "item": self._fmt(items),
+ "element": self._fmt(elements), "year": self._fmt(years),
+ "area_cs": area_cs, "limit": limit,
+ "show_codes": 1 if show_codes else 0,
+ "show_unit": 1, "null_values": 0,
+ })
+ if result.get("success"):
+ result["domain"] = domain
+ result["domain_name"] = DOMAIN_CODES.get(domain, domain)
+ return result
+
+ # --- Metadata ---
+ def list_domains(self):
+ r = self._get("groupsanddomains")
+ r["domain_reference"] = DOMAIN_CODES
+ return r
+
+ def list_areas(self, domain: str):
+ return self._get(f"area/{domain}")
+
+ def list_items(self, domain: str):
+ return self._get(f"item/{domain}")
+
+ def list_elements(self, domain: str):
+ return self._get(f"element/{domain}")
+
+ def list_years(self, domain: str):
+ return self._get(f"year/{domain}")
+
+ def list_all_datasets(self):
+ try:
+ r = self.session.get(BULK_URL, timeout=30)
+ r.raise_for_status()
+ d = r.json()
+ return {"success": True, "data": d, "count": len(d) if isinstance(d, list) else None,
+ "timestamp": int(datetime.now(timezone.utc).timestamp())}
+ except Exception as e:
+ return {"success": False, "error": str(e)}
+
+ # --- Production ---
+ def get_crop_production(self, countries=None, items=None, years=None, elements=None, limit=5000):
+ """Crop and livestock production (QCL): Production(t), Area harvested(ha), Yield(hg/ha)."""
+ return self.get_data("QCL", areas=countries, items=items,
+ elements=elements or [5510, 5312, 5419], years=years, limit=limit)
+
+ def get_production_indices(self, countries=None, years=None):
+ """Production indices base 2014-2016=100."""
+ return self.get_data("QI", areas=countries, years=years)
+
+ def get_production_value(self, countries=None, years=None):
+ """Gross production value in USD."""
+ return self.get_data("QV", areas=countries, years=years)
+
+ # --- Trade ---
+ def get_trade_data(self, countries=None, items=None, years=None, elements=None, limit=5000):
+ """Export/import quantity and value (TCL)."""
+ return self.get_data("TCL", areas=countries, items=items,
+ elements=elements or [5610, 5622, 5910, 5922], years=years, limit=limit)
+
+ def get_bilateral_trade(self, reporter=None, years=None, items=None, limit=5000):
+ """Bilateral trade matrix (TM) - reporter to all partners."""
+ return self.get_data("TM", areas=[reporter] if reporter else None,
+ items=items, years=years, limit=limit)
+
+ # --- Food Supply & Security ---
+ def get_food_balances(self, countries=None, items=None, years=None, limit=5000):
+ """Food Balance Sheets (FBS) - supply, utilization, per-capita availability."""
+ return self.get_data("FBS", areas=countries, items=items, years=years, limit=limit)
+
+ def get_food_security_indicators(self, countries=None, years=None):
+ """Suite of Food Security Indicators (FS) - undernourishment, food insecurity."""
+ return self.get_data("FS", areas=countries, years=years)
+
+ def get_diet_cost_affordability(self, countries=None, years=None):
+ """Cost and Affordability of a Healthy Diet (CAHD)."""
+ return self.get_data("CAHD", areas=countries, years=years)
+
+ def get_supply_utilization(self, countries=None, items=None, years=None, limit=5000):
+ """Supply Utilization Accounts (SCL)."""
+ return self.get_data("SCL", areas=countries, items=items, years=years, limit=limit)
+
+ # --- Land & Inputs ---
+ def get_land_use(self, countries=None, years=None):
+ """Land use (RL) - agricultural area, arable land, permanent crops."""
+ return self.get_data("RL", areas=countries, years=years)
+
+ def get_fertilizer_data(self, countries=None, years=None):
+ """Fertilizers by Nutrient (RFN) - N, P2O5, K2O use."""
+ return self.get_data("RFN", areas=countries, years=years)
+
+ def get_pesticide_data(self, countries=None, years=None):
+ """Pesticides use (EP)."""
+ return self.get_data("EP", areas=countries, years=years)
+
+ # --- Emissions ---
+ def get_emissions_land_use(self, countries=None, years=None, items=None, limit=5000):
+ """GHG Emissions from land use change (GLE) - CO2, N2O, CH4."""
+ return self.get_data("GLE", areas=countries, items=items, years=years, limit=limit)
+
+ def get_emissions_livestock(self, countries=None, years=None):
+ """GHG Emissions from livestock (GV) - enteric fermentation, manure."""
+ return self.get_data("GV", areas=countries, years=years)
+
+ def get_emissions_crops(self, countries=None, years=None):
+ """GHG Emissions from crop residues (GCE)."""
+ return self.get_data("GCE", areas=countries, years=years)
+
+ def get_emission_intensities(self, countries=None, years=None):
+ """Emissions intensities (EI) - GHG per tonne of product."""
+ return self.get_data("EI", areas=countries, years=years)
+
+ # --- Forestry, Prices, Population ---
+ def get_forestry_data(self, countries=None, years=None, limit=5000):
+ """Forestry production and trade (FO) - roundwood, sawnwood, paper."""
+ return self.get_data("FO", areas=countries, years=years, limit=limit)
+
+ def get_producer_prices(self, countries=None, items=None, years=None, limit=5000):
+ """Annual producer prices (PP) - local currency and USD per tonne."""
+ return self.get_data("PP", areas=countries, items=items, years=years, limit=limit)
+
+ def get_consumer_price_index(self, countries=None, years=None):
+ """Consumer Price Indices (CP) - food CPI, general CPI."""
+ return self.get_data("CP", areas=countries, years=years)
+
+ def get_population(self, countries=None, years=None):
+ """Population (OA) - total, rural, urban, agricultural."""
+ return self.get_data("OA", areas=countries, years=years)
+
+ def get_employment_in_agriculture(self, countries=None, years=None):
+ """Employment in agriculture (OEA) - by sex, share of total."""
+ return self.get_data("OEA", areas=countries, years=years)
+
+ # --- Macro / Aid / SDG ---
+ def get_macro_statistics(self, countries=None, years=None):
+ return self.get_data("MK", areas=countries, years=years)
+
+ def get_credit_to_agriculture(self, countries=None, years=None):
+ return self.get_data("CS", areas=countries, years=years)
+
+ def get_government_investment(self, countries=None, years=None):
+ return self.get_data("IG", areas=countries, years=years)
+
+ def get_food_aid_shipments(self, countries=None, years=None):
+ return self.get_data("FA", areas=countries, years=years)
+
+ def get_sdg_indicators(self, countries=None, years=None, items=None, limit=5000):
+ return self.get_data("SDGB", areas=countries, items=items, years=years, limit=limit)
+
+ # --- Convenience ---
+ def get_global_crop_summary(self, year: int, item_code: int = 56):
+ """Global production for one crop. Default 56=Maize. Others: 15=Wheat,27=Rice,236=Soybeans."""
+ return self.get_data("QCL", items=[item_code], elements=[5510], years=[year], limit=5000)
+
+ def get_country_agri_profile(self, country_iso3: str, year: int):
+ """Full agricultural profile combining production, trade, food balance, land use."""
+ c, y = [country_iso3], [year]
+ return {
+ "success": True, "country": country_iso3, "year": year,
+ "production": self.get_crop_production(countries=c, years=y, limit=2000).get("data", []),
+ "trade": self.get_trade_data(countries=c, years=y, limit=2000).get("data", []),
+ "food_balance": self.get_food_balances(countries=c, years=y, limit=1000).get("data", []),
+ "land_use": self.get_land_use(countries=c, years=y).get("data", []),
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_agri_emissions_summary(self, countries=None, years=None):
+ """Combined agricultural GHG emissions across land use, livestock, and crops."""
+ return {
+ "success": True,
+ "data": {
+ "land_use": self.get_emissions_land_use(countries=countries, years=years, limit=2000).get("data", []),
+ "livestock": self.get_emissions_livestock(countries=countries, years=years).get("data", []),
+ "crops": self.get_emissions_crops(countries=countries, years=years).get("data", []),
+ },
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+def _a(n, d=None):
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+def _ls(n):
+ v = _a(n)
+ return v.split(",") if v else None
+
+def _li(n):
+ v = _a(n)
+ return [int(x) for x in v.split(",")] if v else None
+
+
+def main():
+ w = FAOSTATWrapper()
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "success": False, "error": "No command",
+ "available_commands": [
+ "list_domains", "list_datasets",
+ "list_areas <domain>", "list_items <domain>",
+ "list_elements <domain>", "list_years <domain>",
+ "get_data <domain> [areas_csv] [years_csv] [items_csv] [elements_csv] [limit]",
+ "crop_production [countries_csv] [years_csv] [items_csv]",
+ "production_indices [countries_csv] [years_csv]",
+ "production_value [countries_csv] [years_csv]",
+ "trade_data [countries_csv] [years_csv] [items_csv]",
+ "bilateral_trade [reporter_iso3] [years_csv]",
+ "food_balances [countries_csv] [years_csv]",
+ "food_security [countries_csv] [years_csv]",
+ "diet_cost [countries_csv] [years_csv]",
+ "land_use [countries_csv] [years_csv]",
+ "fertilizers [countries_csv] [years_csv]",
+ "pesticides [countries_csv] [years_csv]",
+ "emissions_land [countries_csv] [years_csv]",
+ "emissions_livestock [countries_csv] [years_csv]",
+ "emissions_crops [countries_csv] [years_csv]",
+ "emission_intensities [countries_csv] [years_csv]",
+ "forestry [countries_csv] [years_csv]",
+ "producer_prices [countries_csv] [years_csv] [items_csv]",
+ "consumer_prices [countries_csv] [years_csv]",
+ "population [countries_csv] [years_csv]",
+ "employment_agri [countries_csv] [years_csv]",
+ "macro_stats [countries_csv] [years_csv]",
+ "food_aid [countries_csv] [years_csv]",
+ "sdg_indicators [countries_csv] [years_csv]",
+ "global_crop <year> [item_code]",
+ "country_profile <iso3> <year>",
+ "agri_emissions [countries_csv] [years_csv]",
+ ],
+ "domain_codes": DOMAIN_CODES,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1]
+ try:
+ dispatch = {
+ "list_domains": lambda: w.list_domains(),
+ "list_datasets": lambda: w.list_all_datasets(),
+ "list_areas": lambda: w.list_areas(_a(2, "QCL")),
+ "list_items": lambda: w.list_items(_a(2, "QCL")),
+ "list_elements": lambda: w.list_elements(_a(2, "QCL")),
+ "list_years": lambda: w.list_years(_a(2, "QCL")),
+ "get_data": lambda: w.get_data(_a(2), _ls(3), _ls(4), _ls(5), _ls(6), limit=int(_a(7, 10000))),
+ "crop_production": lambda: w.get_crop_production(_ls(2), _ls(3), _li(4)),
+ "production_indices": lambda: w.get_production_indices(_ls(2), _li(3)),
+ "production_value": lambda: w.get_production_value(_ls(2), _li(3)),
+ "trade_data": lambda: w.get_trade_data(_ls(2), _ls(3), _li(4)),
+ "bilateral_trade": lambda: w.get_bilateral_trade(_a(2), _li(3), _ls(4)),
+ "food_balances": lambda: w.get_food_balances(_ls(2), _ls(3), _li(4)),
+ "food_security": lambda: w.get_food_security_indicators(_ls(2), _li(3)),
+ "diet_cost": lambda: w.get_diet_cost_affordability(_ls(2), _li(3)),
+ "land_use": lambda: w.get_land_use(_ls(2), _li(3)),
+ "fertilizers": lambda: w.get_fertilizer_data(_ls(2), _li(3)),
+ "pesticides": lambda: w.get_pesticide_data(_ls(2), _li(3)),
+ "emissions_land": lambda: w.get_emissions_land_use(_ls(2), _li(3)),
+ "emissions_livestock": lambda: w.get_emissions_livestock(_ls(2), _li(3)),
+ "emissions_crops": lambda: w.get_emissions_crops(_ls(2), _li(3)),
+ "emission_intensities": lambda: w.get_emission_intensities(_ls(2), _li(3)),
+ "forestry": lambda: w.get_forestry_data(_ls(2), _li(3)),
+ "producer_prices": lambda: w.get_producer_prices(_ls(2), _ls(3), _li(4)),
+ "consumer_prices": lambda: w.get_consumer_price_index(_ls(2), _li(3)),
+ "population": lambda: w.get_population(_ls(2), _li(3)),
+ "employment_agri": lambda: w.get_employment_in_agriculture(_ls(2), _li(3)),
+ "macro_stats": lambda: w.get_macro_statistics(_ls(2), _li(3)),
+ "food_aid": lambda: w.get_food_aid_shipments(_ls(2), _li(3)),
+ "sdg_indicators": lambda: w.get_sdg_indicators(_ls(2), _li(3)),
+ "global_crop": lambda: w.get_global_crop_summary(int(_a(2, 2022)), int(_a(3, 56))),
+ "country_profile": lambda: w.get_country_agri_profile(_a(2), int(_a(3, 2022))),
+ "agri_emissions": lambda: w.get_agri_emissions_summary(_ls(2), _li(3)),
+ }
+ if cmd not in dispatch:
+ print(json.dumps({"success": False, "error": f"Unknown command: {cmd}"}))
+ sys.exit(1)
+ print(json.dumps(dispatch[cmd](), indent=2))
+ except KeyboardInterrupt:
+ print(json.dumps({"success": False, "error": "Cancelled"}))
+ sys.exit(1)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e)}))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/govinfo_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/govinfo_data.py
new file mode 100644
index 000000000..bb8406fa7
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/govinfo_data.py
@@ -0,0 +1,1170 @@
+"""
+GovInfo API Data Fetcher
+Comprehensive wrapper for the U.S. Government Publishing Office (GPO) GovInfo API.
+Provides access to official Federal Government publications across all three branches.
+
+API Documentation: https://api.govinfo.gov/docs/
+GitHub: https://github.com/usgpo/api
+Developer Hub: https://www.govinfo.gov/developers
+
+Base URL: https://api.govinfo.gov
+Authentication: API key via api.data.gov (free registration)
+ - Pass as query param: ?api_key=YOUR_KEY
+ - Or header: X-Api-Key: YOUR_KEY
+Rate Limits: 36,000/hour, 1,200/minute, 40/second
+
+Main Service Groups:
+- Collections Service: List/browse all GPO collections
+- Packages Service: Package-level summaries, content, and metadata
+- Granules Service: Sub-document components within packages
+- Published Service: Browse packages by publication date
+- Search Service: Full-text search across GovInfo content
+- Related Service: Find related documents (bills, laws, reports, etc.)
+"""
+
+import sys
+import json
+import os
+import requests
+import time
+from datetime import datetime, timedelta, timezone
+from typing import Dict, Any, Optional, List, Union
+
+
+BASE_URL = "https://api.govinfo.gov"
+
+# Common collection codes for reference
+COLLECTION_CODES = {
+ "BILLS": "Congressional Bills",
+ "BILLSTATUS": "Congressional Bill Status",
+ "BILLSUM": "Congressional Bill Summaries",
+ "BUDGET": "United States Budget",
+ "CDIR": "Congressional Directory",
+ "CFR": "Code of Federal Regulations",
+ "CHRG": "Congressional Hearings",
+ "CMR": "Congresssional Member Record",
+ "COMPS": "Statute Compilations",
+ "CPD": "Compilation of Presidential Documents",
+ "CREC": "Congressional Record",
+ "CRECB": "Congressional Record Bound",
+ "CRI": "Congressional Record Index",
+ "CZIC": "Coastal Zone Information Center",
+ "ECONI": "Economic Indicators",
+ "ERP": "Economic Report of the President",
+ "ES": "Economic Statement",
+ "FR": "Federal Register",
+ "GAOREPORTS": "GAO Reports and Testimonies",
+ "GOVMAN": "United States Government Manual",
+ "GOVPUB": "Government Publications",
+ "GPO": "GPO Publications",
+ "HJOURNAL": "Journal of the House of Representatives",
+ "HOB": "History of Bills",
+ "HMAN": "House Rules and Manual",
+ "HMEMO": "House Committee Memoranda",
+ "HPRT": "House Committee Prints",
+ "JJOURNAL": "Joint Session Journal",
+ "LSA": "List of CFR Sections Affected",
+ "PAI": "Privacy Act Issuances",
+ "PLAW": "Public and Private Laws",
+ "PPP": "Public Papers of the Presidents",
+ "USCOURTS": "United States Courts Opinions",
+ "USCODE": "United States Code",
+ "SERIALSET": "Congressional Serial Set",
+ "SJOURNAL": "Journal of the Senate",
+ "SMAN": "Senate Manual",
+ "SPRT": "Senate Committee Prints",
+ "SRES": "Senate Resolutions",
+ "STATUTE": "Statutes at Large",
+ "WCPD": "Weekly Compilation of Presidential Documents",
+}
+
+
+class GovInfoError:
+ """Error handling wrapper for GovInfo API responses"""
+
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now().timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "error": self.error,
+ "endpoint": self.endpoint,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ }
+
+
+class GovInfoWrapper:
+ """Comprehensive GovInfo API wrapper with fault tolerance"""
+
+ def __init__(self, api_key: Optional[str] = None):
+ self.api_key = api_key or os.environ.get("GOVINFO_API_KEY", "DEMO_KEY")
+ self.base_url = BASE_URL
+ self.session = requests.Session()
+ self.session.headers.update(
+ {
+ "User-Agent": "Fincept-Terminal/1.0",
+ "Accept": "application/json",
+ }
+ )
+
+ # ==================== INTERNAL HELPERS ====================
+
+ def _make_request(
+ self,
+ path: str,
+ params: Optional[Dict[str, Any]] = None,
+ method: str = "GET",
+ json_body: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, Any]:
+ """Centralized request handler with comprehensive error handling"""
+ try:
+ params = params or {}
+ params["api_key"] = self.api_key
+
+ url = f"{self.base_url}{path}"
+
+ if method == "GET":
+ response = self.session.get(url, params=params, timeout=30)
+ elif method == "POST":
+ response = self.session.post(
+ url, params=params, json=json_body, timeout=30
+ )
+ else:
+ return GovInfoError(path, f"Unsupported HTTP method: {method}").to_dict()
+
+ # Handle rate limiting
+ if response.status_code == 429:
+ retry_after = int(response.headers.get("Retry-After", 5))
+ return GovInfoError(
+ path,
+ f"Rate limit exceeded. Retry after {retry_after} seconds.",
+ status_code=429,
+ ).to_dict()
+
+ # Handle file generation in progress
+ if response.status_code == 503:
+ retry_after = int(response.headers.get("Retry-After", 10))
+ return GovInfoError(
+ path,
+ f"File generation in progress. Retry after {retry_after} seconds.",
+ status_code=503,
+ ).to_dict()
+
+ response.raise_for_status()
+
+ data = response.json()
+ return {"success": True, "endpoint": path, "data": data, "timestamp": int(datetime.now().timestamp())}
+
+ except requests.exceptions.HTTPError as e:
+ return GovInfoError(path, f"HTTP error: {str(e)}", status_code=e.response.status_code if e.response else None).to_dict()
+ except requests.exceptions.ConnectionError as e:
+ return GovInfoError(path, f"Connection error: {str(e)}").to_dict()
+ except requests.exceptions.Timeout:
+ return GovInfoError(path, "Request timed out after 30 seconds.").to_dict()
+ except requests.exceptions.RequestException as e:
+ return GovInfoError(path, f"Network error: {str(e)}").to_dict()
+ except json.JSONDecodeError as e:
+ return GovInfoError(path, f"JSON decode error: {str(e)}").to_dict()
+ except Exception as e:
+ return GovInfoError(path, f"Unexpected error: {str(e)}").to_dict()
+
+ def _extract_list(self, result: Dict[str, Any], list_key: str) -> Dict[str, Any]:
+ """Helper to pull a named list out of a successful API response"""
+ if not result.get("success"):
+ return result
+ data = result.get("data", {})
+ return {
+ "success": True,
+ "endpoint": result.get("endpoint"),
+ "data": data.get(list_key, []),
+ "count": data.get("count", None),
+ "total_count": data.get("totalCount", None),
+ "next_page": data.get("nextPage", None),
+ "previous_page": data.get("previousPage", None),
+ "timestamp": result.get("timestamp"),
+ }
+
+ # ==================== COLLECTIONS SERVICE ====================
+
+ def get_collections(self) -> Dict[str, Any]:
+ """
+ GET /collections
+ Returns a list of all collections available in GovInfo, including
+ collectionCode, collectionName, packageCount, and granuleCount.
+ """
+ result = self._make_request("/collections")
+ if not result.get("success"):
+ return result
+ data = result.get("data", {})
+ return {
+ "success": True,
+ "endpoint": "/collections",
+ "data": data.get("collections", data),
+ "timestamp": result.get("timestamp"),
+ }
+
+ def get_collection_packages(
+ self,
+ collection_code: str,
+ start_date: str,
+ end_date: Optional[str] = None,
+ page_size: int = 100,
+ offset_mark: str = "*",
+ doc_class: Optional[str] = None,
+ congress: Optional[str] = None,
+ court_code: Optional[str] = None,
+ court_type: Optional[str] = None,
+ nature_suit_code: Optional[str] = None,
+ nature_suit: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ GET /collections/{collectionCode}/{lastModifiedStartDate}[/{lastModifiedEndDate}]
+ List packages in a collection updated after a given date.
+
+ Args:
+ collection_code: e.g. 'BILLS', 'FR', 'CFR', 'CREC', 'USCOURTS'
+ start_date: ISO 8601 datetime string e.g. '2025-01-01T00:00:00Z'
+ end_date: Optional ISO 8601 end date
+ page_size: Number of results per page (max 1000)
+ offset_mark: Pagination cursor, use '*' for first page
+ doc_class: Filter by document class (collection-specific)
+ congress: Filter by congress number e.g. '119'
+ court_code: Filter by court code (USCOURTS only)
+ court_type: Filter by court type (USCOURTS only)
+ nature_suit_code: Filter by nature of suit code (USCOURTS only)
+ nature_suit: Filter by nature of suit description (USCOURTS only)
+ """
+ path = f"/collections/{collection_code}/{start_date}"
+ if end_date:
+ path += f"/{end_date}"
+
+ params: Dict[str, Any] = {
+ "pageSize": page_size,
+ "offsetMark": offset_mark,
+ }
+ if doc_class:
+ params["docClass"] = doc_class
+ if congress:
+ params["congress"] = congress
+ if court_code:
+ params["courtCode"] = court_code
+ if court_type:
+ params["courtType"] = court_type
+ if nature_suit_code:
+ params["natureSuitCode"] = nature_suit_code
+ if nature_suit:
+ params["natureSuit"] = nature_suit
+
+ result = self._make_request(path, params=params)
+ return self._extract_list(result, "packages")
+
+ # ==================== PUBLISHED SERVICE ====================
+
+ def get_published_packages(
+ self,
+ start_date: str,
+ end_date: Optional[str] = None,
+ collection: Optional[str] = None,
+ page_size: int = 100,
+ offset_mark: str = "*",
+ doc_class: Optional[str] = None,
+ congress: Optional[str] = None,
+ court_code: Optional[str] = None,
+ court_type: Optional[str] = None,
+ modified_since: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ GET /published/{dateIssuedStartDate}[/{dateIssuedEndDate}]
+ List packages by their official publication (dateIssued) date.
+ This differs from collection updates — it reflects when content was published.
+
+ Args:
+ start_date: Publication start date 'YYYY-MM-DD'
+ end_date: Optional publication end date 'YYYY-MM-DD'
+ collection: Comma-separated collection codes e.g. 'BILLS,FR'
+ page_size: Results per page (max 1000)
+ offset_mark: Pagination cursor
+ doc_class: Document class filter
+ congress: Congress number filter
+ court_code: Court code filter (USCOURTS)
+ court_type: Court type filter (USCOURTS)
+ modified_since: Only include packages modified since this date
+ """
+ path = f"/published/{start_date}"
+ if end_date:
+ path += f"/{end_date}"
+
+ params: Dict[str, Any] = {
+ "pageSize": page_size,
+ "offsetMark": offset_mark,
+ }
+ if collection:
+ params["collection"] = collection
+ if doc_class:
+ params["docClass"] = doc_class
+ if congress:
+ params["congress"] = congress
+ if court_code:
+ params["courtCode"] = court_code
+ if court_type:
+ params["courtType"] = court_type
+ if modified_since:
+ params["modifiedSince"] = modified_since
+
+ result = self._make_request(path, params=params)
+ return self._extract_list(result, "packages")
+
+ # ==================== PACKAGES SERVICE ====================
+
+ def get_package_summary(self, package_id: str) -> Dict[str, Any]:
+ """
+ GET /packages/{packageId}/summary
+ Retrieve summary metadata and available download links for a package.
+ Returns: title, dateIssued, congress, publisher, download links (pdf, htm, xml, mods, premis, zip)
+
+ Args:
+ package_id: e.g. 'BILLS-119hr1enr', 'CREC-2025-01-06', 'FR-2025-01-20'
+ """
+ result = self._make_request(f"/packages/{package_id}/summary")
+ if not result.get("success"):
+ return result
+ return {
+ "success": True,
+ "endpoint": f"/packages/{package_id}/summary",
+ "package_id": package_id,
+ "data": result.get("data", {}),
+ "timestamp": result.get("timestamp"),
+ }
+
+ def get_package_content_detail(self, package_id: str) -> Dict[str, Any]:
+ """
+ GET /packages/{packageId}/contentdetail
+ Returns content detail for a package including links to individual files.
+
+ Args:
+ package_id: e.g. 'BILLS-119hr1enr'
+ """
+ result = self._make_request(f"/packages/{package_id}/contentdetail")
+ if not result.get("success"):
+ return result
+ return {
+ "success": True,
+ "endpoint": f"/packages/{package_id}/contentdetail",
+ "package_id": package_id,
+ "data": result.get("data", {}),
+ "timestamp": result.get("timestamp"),
+ }
+
+ # ==================== GRANULES SERVICE ====================
+
+ def get_package_granules(
+ self,
+ package_id: str,
+ page_size: int = 100,
+ offset_mark: str = "*",
+ granule_class: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ GET /packages/{packageId}/granules
+ List individual granule (sub-document) components within a package.
+ Useful for packages like Congressional Record (CREC) with many sections.
+
+ Args:
+ package_id: e.g. 'CREC-2025-01-06'
+ page_size: Results per page (max 1000)
+ offset_mark: Pagination cursor
+ granule_class: Filter by granule class
+ """
+ params: Dict[str, Any] = {
+ "pageSize": page_size,
+ "offsetMark": offset_mark,
+ }
+ if granule_class:
+ params["granuleClass"] = granule_class
+
+ result = self._make_request(f"/packages/{package_id}/granules", params=params)
+ return self._extract_list(result, "granules")
+
+ def get_granule_summary(self, package_id: str, granule_id: str) -> Dict[str, Any]:
+ """
+ GET /packages/{packageId}/granules/{granuleId}/summary
+ Retrieve summary metadata for a specific granule within a package.
+
+ Args:
+ package_id: Parent package ID e.g. 'CREC-2025-01-06'
+ granule_id: Granule ID e.g. 'CREC-2025-01-06-pt1-PgS1'
+ """
+ result = self._make_request(
+ f"/packages/{package_id}/granules/{granule_id}/summary"
+ )
+ if not result.get("success"):
+ return result
+ return {
+ "success": True,
+ "endpoint": f"/packages/{package_id}/granules/{granule_id}/summary",
+ "package_id": package_id,
+ "granule_id": granule_id,
+ "data": result.get("data", {}),
+ "timestamp": result.get("timestamp"),
+ }
+
+ # ==================== SEARCH SERVICE ====================
+
+ def search(
+ self,
+ query: str,
+ page_size: int = 10,
+ offset_mark: str = "*",
+ sorts: Optional[List[Dict[str, str]]] = None,
+ historical: Optional[bool] = None,
+ result_level: Optional[str] = None,
+ date_issued_start: Optional[str] = None,
+ date_issued_end: Optional[str] = None,
+ congress: Optional[List[str]] = None,
+ doc_class: Optional[List[str]] = None,
+ category: Optional[List[str]] = None,
+ collection: Optional[List[str]] = None,
+ modified_start: Optional[str] = None,
+ modified_end: Optional[str] = None,
+ publishdate_start: Optional[str] = None,
+ publishdate_end: Optional[str] = None,
+ government_author1: Optional[List[str]] = None,
+ government_author2: Optional[List[str]] = None,
+ subject: Optional[List[str]] = None,
+ court_code: Optional[List[str]] = None,
+ court_type: Optional[List[str]] = None,
+ nature_suit_code: Optional[List[str]] = None,
+ nature_suit: Optional[List[str]] = None,
+ ) -> Dict[str, Any]:
+ """
+ POST /search
+ Full-text search across GovInfo content. Returns results similar to
+ govinfo.gov search UI.
+
+ Args:
+ query: Search terms e.g. 'infrastructure bill', 'federal reserve'
+ page_size: Results per page
+ offset_mark: Pagination cursor (start with '*')
+ sorts: List of sort dicts e.g. [{'field': 'score', 'sortOrder': 'DESC'}]
+ Supported fields: score, publishdate, lastModified, title
+ historical: Include historical content
+ result_level: 'default' or 'granule'
+ date_issued_start: Filter by publication start date 'YYYY-MM-DD'
+ date_issued_end: Filter by publication end date 'YYYY-MM-DD'
+ congress: Filter by congress numbers e.g. ['119', '118']
+ doc_class: Filter by document classes
+ category: Filter by categories
+ collection: Filter by collection codes e.g. ['BILLS', 'FR']
+ modified_start: Filter by modification start date
+ modified_end: Filter by modification end date
+ publishdate_start: Filter by publish date start
+ publishdate_end: Filter by publish date end
+ government_author1: Filter by primary government author
+ government_author2: Filter by secondary government author
+ subject: Filter by subject terms
+ court_code: Filter by court code (USCOURTS)
+ court_type: Filter by court type
+ nature_suit_code: Filter by nature of suit code
+ nature_suit: Filter by nature of suit
+ """
+ body: Dict[str, Any] = {
+ "query": query,
+ "pageSize": page_size,
+ "offsetMark": offset_mark,
+ }
+
+ if sorts:
+ body["sorts"] = sorts
+ if historical is not None:
+ body["historical"] = historical
+ if result_level:
+ body["resultLevel"] = result_level
+
+ # Build facet/filter fields
+ fields: Dict[str, Any] = {}
+ if date_issued_start:
+ fields["dateIssued"] = {"from": date_issued_start}
+ if date_issued_end:
+ if "dateIssued" not in fields:
+ fields["dateIssued"] = {}
+ fields["dateIssued"]["to"] = date_issued_end
+ if congress:
+ fields["congress"] = congress
+ if doc_class:
+ fields["docClass"] = doc_class
+ if category:
+ fields["category"] = category
+ if collection:
+ fields["collection"] = collection
+ if modified_start:
+ fields["lastModified"] = {"from": modified_start}
+ if modified_end:
+ if "lastModified" not in fields:
+ fields["lastModified"] = {}
+ fields["lastModified"]["to"] = modified_end
+ if publishdate_start:
+ fields["publishdate"] = {"from": publishdate_start}
+ if publishdate_end:
+ if "publishdate" not in fields:
+ fields["publishdate"] = {}
+ fields["publishdate"]["to"] = publishdate_end
+ if government_author1:
+ fields["governmentAuthor1"] = government_author1
+ if government_author2:
+ fields["governmentAuthor2"] = government_author2
+ if subject:
+ fields["subject"] = subject
+ if court_code:
+ fields["courtCode"] = court_code
+ if court_type:
+ fields["courtType"] = court_type
+ if nature_suit_code:
+ fields["natureSuitCode"] = nature_suit_code
+ if nature_suit:
+ fields["natureSuit"] = nature_suit
+
+ if fields:
+ body["fields"] = fields
+
+ result = self._make_request("/search", method="POST", json_body=body)
+ if not result.get("success"):
+ return result
+
+ data = result.get("data", {})
+ return {
+ "success": True,
+ "endpoint": "/search",
+ "query": query,
+ "data": data.get("results", []),
+ "count": data.get("count", 0),
+ "total_count": data.get("totalCount", 0),
+ "next_page": data.get("nextPage", None),
+ "previous_page": data.get("previousPage", None),
+ "timestamp": result.get("timestamp"),
+ }
+
+ # ==================== RELATED SERVICE ====================
+
+ def get_related_documents(
+ self,
+ access_id: str,
+ collection: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ GET /related/{accessId}[/{collection}]
+ Find documents related to a given access ID (BILLS or BILLSTATUS packages).
+ Returns related bill versions, bill history, signing statements, laws,
+ Congressional reports, U.S. Code sections, Statutes at Large, etc.
+
+ Args:
+ access_id: Package or granule access ID e.g. 'BILLS-119hr1enr'
+ collection: Optional collection to filter relationships
+ e.g. 'PLAW', 'STATUTE', 'USCODE', 'HPRT', 'SPRT'
+ """
+ path = f"/related/{access_id}"
+ if collection:
+ path += f"/{collection}"
+
+ result = self._make_request(path)
+ if not result.get("success"):
+ return result
+
+ data = result.get("data", {})
+ return {
+ "success": True,
+ "endpoint": path,
+ "access_id": access_id,
+ "data": data.get("relatedPackages", data.get("packages", data)),
+ "timestamp": result.get("timestamp"),
+ }
+
+ # ==================== HIGH-LEVEL CONVENIENCE METHODS ====================
+
+ def get_recent_bills(
+ self,
+ days_back: int = 7,
+ page_size: int = 50,
+ congress: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Fetch recently updated Congressional Bills from the BILLS collection.
+
+ Args:
+ days_back: How many days back to look for updates
+ page_size: Results per page
+ congress: Filter by congress e.g. '119'
+ """
+ start = (datetime.now(timezone.utc) - timedelta(days=days_back)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+ return self.get_collection_packages(
+ collection_code="BILLS",
+ start_date=start,
+ page_size=page_size,
+ congress=congress,
+ )
+
+ def get_federal_register_entries(
+ self,
+ start_date: str,
+ end_date: Optional[str] = None,
+ page_size: int = 50,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Fetch Federal Register entries by publication date.
+
+ Args:
+ start_date: Start date 'YYYY-MM-DD'
+ end_date: End date 'YYYY-MM-DD' (defaults to today)
+ page_size: Results per page
+ """
+ if not end_date:
+ end_date = datetime.now(timezone.utc).strftime("%Y-%m-%d")
+ return self.get_published_packages(
+ start_date=start_date,
+ end_date=end_date,
+ collection="FR",
+ page_size=page_size,
+ )
+
+ def get_recent_court_opinions(
+ self,
+ days_back: int = 30,
+ court_code: Optional[str] = None,
+ page_size: int = 50,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Fetch recent U.S. Court opinions from USCOURTS collection.
+
+ Args:
+ days_back: Days back to look for new opinions
+ court_code: Specific court code e.g. 'ca9', 'ca4', 'dc'
+ page_size: Results per page
+ """
+ start = (datetime.now(timezone.utc) - timedelta(days=days_back)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+ return self.get_collection_packages(
+ collection_code="USCOURTS",
+ start_date=start,
+ page_size=page_size,
+ court_code=court_code,
+ )
+
+ def get_congressional_record_by_date(
+ self,
+ date: str,
+ page_size: int = 100,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Fetch Congressional Record (CREC) for a specific date.
+ Returns granule listing for the day's record.
+
+ Args:
+ date: Date in format 'YYYY-MM-DD'
+ page_size: Results per page
+ """
+ package_id = f"CREC-{date}"
+ return self.get_package_granules(package_id=package_id, page_size=page_size)
+
+ def get_cfr_titles(
+ self,
+ page_size: int = 50,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get recent Code of Federal Regulations packages.
+
+ Args:
+ page_size: Results per page
+ """
+ start = (datetime.now(timezone.utc) - timedelta(days=365)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+ return self.get_collection_packages(
+ collection_code="CFR",
+ start_date=start,
+ page_size=page_size,
+ )
+
+ def get_public_laws(
+ self,
+ congress: Optional[str] = None,
+ start_date: Optional[str] = None,
+ page_size: int = 50,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get Public and Private Laws (PLAW collection).
+
+ Args:
+ congress: Congress number e.g. '119'
+ start_date: Start date 'YYYY-MM-DD' (defaults to 2 years ago)
+ page_size: Results per page
+ """
+ if not start_date:
+ start_date = (datetime.now(timezone.utc) - timedelta(days=730)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+ return self.get_collection_packages(
+ collection_code="PLAW",
+ start_date=start_date,
+ page_size=page_size,
+ congress=congress,
+ )
+
+ def get_economic_indicators(
+ self,
+ start_date: Optional[str] = None,
+ page_size: int = 50,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get Economic Indicators (ECONI collection).
+
+ Args:
+ start_date: Start date 'YYYY-MM-DD' (defaults to 1 year ago)
+ page_size: Results per page
+ """
+ if not start_date:
+ start_date = (datetime.now(timezone.utc) - timedelta(days=365)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+ return self.get_collection_packages(
+ collection_code="ECONI",
+ start_date=start_date,
+ page_size=page_size,
+ )
+
+ def get_gao_reports(
+ self,
+ start_date: Optional[str] = None,
+ page_size: int = 50,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get GAO Reports and Testimonies (GAOREPORTS collection).
+
+ Args:
+ start_date: Start date (defaults to 90 days ago)
+ page_size: Results per page
+ """
+ if not start_date:
+ start_date = (datetime.now(timezone.utc) - timedelta(days=90)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+ return self.get_collection_packages(
+ collection_code="GAOREPORTS",
+ start_date=start_date,
+ page_size=page_size,
+ )
+
+ def get_presidential_documents(
+ self,
+ start_date: Optional[str] = None,
+ page_size: int = 50,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get Compilation of Presidential Documents (CPD collection).
+
+ Args:
+ start_date: Start date (defaults to 90 days ago)
+ page_size: Results per page
+ """
+ if not start_date:
+ start_date = (datetime.now(timezone.utc) - timedelta(days=90)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+ return self.get_collection_packages(
+ collection_code="CPD",
+ start_date=start_date,
+ page_size=page_size,
+ )
+
+ def search_legislation(
+ self,
+ query: str,
+ congress: Optional[str] = None,
+ page_size: int = 20,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Search for legislation (bills, laws, resolutions).
+
+ Args:
+ query: Search terms
+ congress: Congress number e.g. '119'
+ page_size: Results per page
+ """
+ return self.search(
+ query=query,
+ page_size=page_size,
+ collection=["BILLS", "PLAW", "BILLSTATUS"],
+ congress=[congress] if congress else None,
+ sorts=[{"field": "score", "sortOrder": "DESC"}],
+ )
+
+ def search_federal_regulations(
+ self,
+ query: str,
+ page_size: int = 20,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Search across CFR and Federal Register.
+
+ Args:
+ query: Search terms e.g. 'bank capital requirements'
+ page_size: Results per page
+ """
+ return self.search(
+ query=query,
+ page_size=page_size,
+ collection=["CFR", "FR"],
+ sorts=[{"field": "publishdate", "sortOrder": "DESC"}],
+ )
+
+ def search_court_opinions(
+ self,
+ query: str,
+ court_type: Optional[str] = None,
+ page_size: int = 20,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Search U.S. court opinions.
+
+ Args:
+ query: Search terms
+ court_type: e.g. 'United States Courts of Appeals'
+ page_size: Results per page
+ """
+ return self.search(
+ query=query,
+ page_size=page_size,
+ collection=["USCOURTS"],
+ court_type=[court_type] if court_type else None,
+ sorts=[{"field": "publishdate", "sortOrder": "DESC"}],
+ )
+
+ def get_bill_with_related(self, package_id: str) -> Dict[str, Any]:
+ """
+ Convenience: Get a bill's summary plus all related documents in one call.
+
+ Args:
+ package_id: Bill package ID e.g. 'BILLS-119hr1enr'
+ """
+ summary = self.get_package_summary(package_id)
+ related = self.get_related_documents(package_id)
+
+ return {
+ "success": True,
+ "package_id": package_id,
+ "summary": summary.get("data", {}),
+ "related_documents": related.get("data", []),
+ "timestamp": int(datetime.now().timestamp()),
+ }
+
+ def get_collections_overview(self) -> Dict[str, Any]:
+ """
+ Convenience: Get all collections with their descriptions from the local
+ COLLECTION_CODES reference, merged with live package/granule counts.
+ """
+ result = self.get_collections()
+ if not result.get("success"):
+ return result
+
+ collections = result.get("data", [])
+ enriched = []
+ for col in collections:
+ code = col.get("collectionCode", "")
+ col["collectionDescription"] = COLLECTION_CODES.get(code, "")
+ enriched.append(col)
+
+ return {
+ "success": True,
+ "endpoint": "/collections",
+ "data": enriched,
+ "count": len(enriched),
+ "timestamp": result.get("timestamp"),
+ }
+
+
+# ==================== MAIN CLI ENTRYPOINT ====================
+
+def main():
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "success": False,
+ "error": "No command provided",
+ "available_commands": [
+ "collections",
+ "collections_overview",
+ "collection_packages <collection_code> <start_date> [end_date] [page_size] [congress]",
+ "published <start_date> [end_date] [collection] [page_size] [congress]",
+ "package_summary <package_id>",
+ "package_granules <package_id> [page_size]",
+ "granule_summary <package_id> <granule_id>",
+ "search <query> [page_size] [collection] [congress]",
+ "related <access_id> [collection]",
+ "recent_bills [days_back] [page_size] [congress]",
+ "federal_register <start_date> [end_date] [page_size]",
+ "court_opinions [days_back] [court_code] [page_size]",
+ "congressional_record <date>",
+ "cfr [page_size]",
+ "public_laws [congress] [start_date] [page_size]",
+ "economic_indicators [start_date] [page_size]",
+ "gao_reports [start_date] [page_size]",
+ "presidential_documents [start_date] [page_size]",
+ "search_legislation <query> [congress] [page_size]",
+ "search_regulations <query> [page_size]",
+ "search_court_opinions <query> [court_type] [page_size]",
+ "bill_with_related <package_id>",
+ ],
+ "note": "Requires GOVINFO_API_KEY environment variable (free at https://api.data.gov/signup/)",
+ "rate_limits": "36,000/hour, 1,200/minute, 40/second",
+ }))
+ sys.exit(1)
+
+ command = sys.argv[1]
+ wrapper = GovInfoWrapper()
+
+ try:
+ # ---- Collections ----
+ if command == "collections":
+ result = wrapper.get_collections()
+ print(json.dumps(result, indent=2))
+
+ elif command == "collections_overview":
+ result = wrapper.get_collections_overview()
+ print(json.dumps(result, indent=2))
+
+ elif command == "collection_packages":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py collection_packages <collection_code> <start_date> [end_date] [page_size] [congress]"}))
+ sys.exit(1)
+ collection_code = sys.argv[2]
+ start_date = sys.argv[3]
+ end_date = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else None
+ page_size = int(sys.argv[5]) if len(sys.argv) > 5 and sys.argv[5] else 100
+ congress = sys.argv[6] if len(sys.argv) > 6 and sys.argv[6] else None
+ result = wrapper.get_collection_packages(
+ collection_code=collection_code,
+ start_date=start_date,
+ end_date=end_date,
+ page_size=page_size,
+ congress=congress,
+ )
+ print(json.dumps(result, indent=2))
+
+ # ---- Published ----
+ elif command == "published":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py published <start_date> [end_date] [collection] [page_size] [congress]"}))
+ sys.exit(1)
+ start_date = sys.argv[2]
+ end_date = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else None
+ collection = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else None
+ page_size = int(sys.argv[5]) if len(sys.argv) > 5 and sys.argv[5] else 100
+ congress = sys.argv[6] if len(sys.argv) > 6 and sys.argv[6] else None
+ result = wrapper.get_published_packages(
+ start_date=start_date,
+ end_date=end_date,
+ collection=collection,
+ page_size=page_size,
+ congress=congress,
+ )
+ print(json.dumps(result, indent=2))
+
+ # ---- Packages ----
+ elif command == "package_summary":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py package_summary <package_id>"}))
+ sys.exit(1)
+ package_id = sys.argv[2]
+ result = wrapper.get_package_summary(package_id)
+ print(json.dumps(result, indent=2))
+
+ elif command == "package_granules":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py package_granules <package_id> [page_size]"}))
+ sys.exit(1)
+ package_id = sys.argv[2]
+ page_size = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] else 100
+ result = wrapper.get_package_granules(package_id=package_id, page_size=page_size)
+ print(json.dumps(result, indent=2))
+
+ elif command == "granule_summary":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py granule_summary <package_id> <granule_id>"}))
+ sys.exit(1)
+ package_id = sys.argv[2]
+ granule_id = sys.argv[3]
+ result = wrapper.get_granule_summary(package_id=package_id, granule_id=granule_id)
+ print(json.dumps(result, indent=2))
+
+ # ---- Search ----
+ elif command == "search":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py search <query> [page_size] [collection] [congress]"}))
+ sys.exit(1)
+ query = sys.argv[2]
+ page_size = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] else 10
+ collection_filter = sys.argv[4].split(",") if len(sys.argv) > 4 and sys.argv[4] else None
+ congress_filter = [sys.argv[5]] if len(sys.argv) > 5 and sys.argv[5] else None
+ result = wrapper.search(
+ query=query,
+ page_size=page_size,
+ collection=collection_filter,
+ congress=congress_filter,
+ )
+ print(json.dumps(result, indent=2))
+
+ # ---- Related ----
+ elif command == "related":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py related <access_id> [collection]"}))
+ sys.exit(1)
+ access_id = sys.argv[2]
+ collection = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else None
+ result = wrapper.get_related_documents(access_id=access_id, collection=collection)
+ print(json.dumps(result, indent=2))
+
+ # ---- Convenience methods ----
+ elif command == "recent_bills":
+ days_back = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2] else 7
+ page_size = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] else 50
+ congress = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else None
+ result = wrapper.get_recent_bills(days_back=days_back, page_size=page_size, congress=congress)
+ print(json.dumps(result, indent=2))
+
+ elif command == "federal_register":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py federal_register <start_date> [end_date] [page_size]"}))
+ sys.exit(1)
+ start_date = sys.argv[2]
+ end_date = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else None
+ page_size = int(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4] else 50
+ result = wrapper.get_federal_register_entries(start_date=start_date, end_date=end_date, page_size=page_size)
+ print(json.dumps(result, indent=2))
+
+ elif command == "court_opinions":
+ days_back = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2] else 30
+ court_code = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else None
+ page_size = int(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4] else 50
+ result = wrapper.get_recent_court_opinions(days_back=days_back, court_code=court_code, page_size=page_size)
+ print(json.dumps(result, indent=2))
+
+ elif command == "congressional_record":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py congressional_record <date> (YYYY-MM-DD)"}))
+ sys.exit(1)
+ date = sys.argv[2]
+ result = wrapper.get_congressional_record_by_date(date=date)
+ print(json.dumps(result, indent=2))
+
+ elif command == "cfr":
+ page_size = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2] else 50
+ result = wrapper.get_cfr_titles(page_size=page_size)
+ print(json.dumps(result, indent=2))
+
+ elif command == "public_laws":
+ congress = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] else None
+ start_date = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else None
+ page_size = int(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4] else 50
+ result = wrapper.get_public_laws(congress=congress, start_date=start_date, page_size=page_size)
+ print(json.dumps(result, indent=2))
+
+ elif command == "economic_indicators":
+ start_date = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] else None
+ page_size = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] else 50
+ result = wrapper.get_economic_indicators(start_date=start_date, page_size=page_size)
+ print(json.dumps(result, indent=2))
+
+ elif command == "gao_reports":
+ start_date = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] else None
+ page_size = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] else 50
+ result = wrapper.get_gao_reports(start_date=start_date, page_size=page_size)
+ print(json.dumps(result, indent=2))
+
+ elif command == "presidential_documents":
+ start_date = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] else None
+ page_size = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] else 50
+ result = wrapper.get_presidential_documents(start_date=start_date, page_size=page_size)
+ print(json.dumps(result, indent=2))
+
+ elif command == "search_legislation":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py search_legislation <query> [congress] [page_size]"}))
+ sys.exit(1)
+ query = sys.argv[2]
+ congress = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else None
+ page_size = int(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4] else 20
+ result = wrapper.search_legislation(query=query, congress=congress, page_size=page_size)
+ print(json.dumps(result, indent=2))
+
+ elif command == "search_regulations":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py search_regulations <query> [page_size]"}))
+ sys.exit(1)
+ query = sys.argv[2]
+ page_size = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] else 20
+ result = wrapper.search_federal_regulations(query=query, page_size=page_size)
+ print(json.dumps(result, indent=2))
+
+ elif command == "search_court_opinions":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py search_court_opinions <query> [court_type] [page_size]"}))
+ sys.exit(1)
+ query = sys.argv[2]
+ court_type = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else None
+ page_size = int(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4] else 20
+ result = wrapper.search_court_opinions(query=query, court_type=court_type, page_size=page_size)
+ print(json.dumps(result, indent=2))
+
+ elif command == "bill_with_related":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: govinfo_data.py bill_with_related <package_id>"}))
+ sys.exit(1)
+ package_id = sys.argv[2]
+ result = wrapper.get_bill_with_related(package_id)
+ print(json.dumps(result, indent=2))
+
+ else:
+ print(json.dumps({
+ "success": False,
+ "error": f"Unknown command: {command}",
+ "available_commands": [
+ "collections", "collections_overview",
+ "collection_packages <collection_code> <start_date> [end_date] [page_size] [congress]",
+ "published <start_date> [end_date] [collection] [page_size] [congress]",
+ "package_summary <package_id>",
+ "package_granules <package_id> [page_size]",
+ "granule_summary <package_id> <granule_id>",
+ "search <query> [page_size] [collection] [congress]",
+ "related <access_id> [collection]",
+ "recent_bills [days_back] [page_size] [congress]",
+ "federal_register <start_date> [end_date] [page_size]",
+ "court_opinions [days_back] [court_code] [page_size]",
+ "congressional_record <date>",
+ "cfr [page_size]",
+ "public_laws [congress] [start_date] [page_size]",
+ "economic_indicators [start_date] [page_size]",
+ "gao_reports [start_date] [page_size]",
+ "presidential_documents [start_date] [page_size]",
+ "search_legislation <query> [congress] [page_size]",
+ "search_regulations <query> [page_size]",
+ "search_court_opinions <query> [court_type] [page_size]",
+ "bill_with_related <package_id>",
+ ],
+ }))
+ sys.exit(1)
+
+ except KeyboardInterrupt:
+ print(json.dumps({"success": False, "error": "Operation cancelled by user"}))
+ sys.exit(1)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": f"Unexpected error: {str(e)}"}))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/hnb_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/hnb_data.py
new file mode 100644
index 000000000..9ca91bf44
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/hnb_data.py
@@ -0,0 +1,349 @@
+"""
+Hrvatska Narodna Banka (HNB) — Croatian National Bank Data Wrapper
+Fetches exchange rate data from the HNB public REST API.
+
+API Reference:
+ Base URL: https://api.hnb.hr
+ Format: JSON (UTF-8)
+ Auth: None required — fully public
+ Docs: https://api.hnb.hr/
+
+Endpoints:
+ GET /tecajn-eur/v3 — Latest EUR-based exchange rate list
+ ?broj_tecajnice=N — Specific bulletin number
+ ?broj_tecajnice_od=N&broj_tecajnice_do=M — Range of bulletins
+ ?valuta=XXX — Filter by currency code (ISO 4217)
+ ?datum_primjene=YYYY-MM-DD — Rates valid on date
+
+Notes:
+ - Croatia joined the Eurozone on 1 Jan 2023; EUR is the base currency.
+ - HRK (Kuna) rates available via /tecajn/v2 (legacy endpoint, EUR fixed at 7.5345).
+ - "tecajnica" = rate bulletin; numbered sequentially per year starting from 1.
+ - Rates are EUR per foreign currency unit.
+ - Published every business day; 13 currencies:
+ AUD, CAD, CZK, DKK, HUF, JPY, NOK, SEK, CHF, GBP, USD, BAM, PLN
+
+Fields per item:
+ broj_tecajnice — bulletin number
+ datum_primjene — date rates apply (YYYY-MM-DD)
+ drzava — country name (Croatian)
+ drzava_iso — ISO 3166-1 alpha-3 country code
+ sifra_valute — ISO 4217 numeric currency code
+ valuta — ISO 4217 alpha currency code
+ kupovni_tecaj — buying rate (comma decimal)
+ prodajni_tecaj — selling rate
+ srednji_tecaj — middle/reference rate
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime, date, timedelta, timezone
+
+
+BASE_URL = "https://api.hnb.hr"
+DEFAULT_TIMEOUT = 30
+
+ALL_CURRENCIES = ["AUD", "CAD", "CZK", "DKK", "HUF", "JPY", "NOK",
+ "SEK", "CHF", "GBP", "USD", "BAM", "PLN"]
+MAJOR_CURRENCIES = ["USD", "GBP", "CHF", "JPY", "CAD", "AUD", "NOK",
+ "SEK", "DKK", "CZK", "PLN", "HUF"]
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class HNBError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "HNBError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class HNBWrapper:
+ """
+ Wrapper for the Hrvatska Narodna Banka (HNB) public REST API.
+
+ All exchange rates are EUR per 1 unit of foreign currency
+ (e.g. USD = 1.1767 means 1 USD = 1.1767 EUR, or equivalently
+ 1 EUR ≈ 0.8498 USD).
+ Decimal separator in raw JSON is a comma; wrapper converts to float.
+ Data is published every Croatian business day.
+ """
+
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Accept": "application/json",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _get(self, path: str, params: Optional[Dict] = None) -> Any:
+ url = f"{BASE_URL}/{path.lstrip('/')}"
+ resp = self.session.get(url, params=params or {}, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.json()
+
+ def _parse_rate(self, text: str) -> Optional[float]:
+ """Convert comma-decimal rate string to float."""
+ if not text or text.strip() in ("", "N/A"):
+ return None
+ try:
+ return float(text.strip().replace(",", "."))
+ except ValueError:
+ return None
+
+ def _normalise(self, items: List[Dict]) -> List[Dict[str, Any]]:
+ """
+ Convert raw HNB list to clean list with float rates.
+ Groups by date into wide-format rows when multiple currencies returned.
+ """
+ wide: Dict[str, Dict[str, Any]] = {}
+ for item in items:
+ d = item.get("datum_primjene", "")
+ code = item.get("valuta", "")
+ if d not in wide:
+ wide[d] = {
+ "date": d,
+ "broj_tecajnice": item.get("broj_tecajnice", ""),
+ }
+ if code:
+ wide[d][f"{code}_buy"] = self._parse_rate(item.get("kupovni_tecaj", ""))
+ wide[d][f"{code}_sell"] = self._parse_rate(item.get("prodajni_tecaj", ""))
+ wide[d][f"{code}_mid"] = self._parse_rate(item.get("srednji_tecaj", ""))
+ return sorted(wide.values(), key=lambda r: r["date"])
+
+ def _normalise_single(self, items: List[Dict]) -> List[Dict[str, Any]]:
+ """For single-currency queries: return [{date, buy, sell, mid}, ...]."""
+ rows = []
+ for item in items:
+ rows.append({
+ "date": item.get("datum_primjene", ""),
+ "broj_tecajnice": item.get("broj_tecajnice", ""),
+ "currency": item.get("valuta", ""),
+ "buy": self._parse_rate(item.get("kupovni_tecaj", "")),
+ "sell": self._parse_rate(item.get("prodajni_tecaj", "")),
+ "mid": self._parse_rate(item.get("srednji_tecaj", "")),
+ })
+ return sorted(rows, key=lambda r: r["date"])
+
+ # ------------------------------------------------------------------
+ # Public methods
+ # ------------------------------------------------------------------
+
+ def get_today(self) -> Dict[str, Any]:
+ """Latest exchange rate bulletin — all 13 currencies vs EUR."""
+ try:
+ items = self._get("tecajn-eur/v3", {"broj_tecajnice": 1})
+ rows = self._normalise(items)
+ latest = rows[-1] if rows else {}
+ # Also build a simple flat dict: {USD: mid, EUR: 1, GBP: mid, ...}
+ flat: Dict[str, Any] = {}
+ for item in items:
+ code = item.get("valuta", "")
+ mid = self._parse_rate(item.get("srednji_tecaj", ""))
+ if code and mid is not None:
+ flat[code] = mid
+ return {
+ "success": True,
+ "date": latest.get("date", ""),
+ "broj_tecajnice": latest.get("broj_tecajnice", ""),
+ "data": flat,
+ "full_data": latest,
+ "note": "EUR per 1 unit of foreign currency",
+ "source": "Hrvatska Narodna Banka",
+ "url": f"{BASE_URL}/tecajn-eur/v3",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return HNBError("tecajn-eur/v3", str(e), sc).to_dict()
+ except Exception as e:
+ return HNBError("tecajn-eur/v3", str(e)).to_dict()
+
+ def get_currency(self, currency: str,
+ start_bulletin: Optional[int] = None,
+ end_bulletin: Optional[int] = None,
+ date_from: Optional[str] = None) -> Dict[str, Any]:
+ """
+ Historical rates for a single currency.
+ Use bulletin numbers (1 = most recent, higher = older within year)
+ or date_from for approximate date filtering.
+ Default: last 30 bulletins.
+ """
+ currency = currency.upper()
+ try:
+ params: Dict[str, Any] = {"valuta": currency}
+ if start_bulletin and end_bulletin:
+ params["broj_tecajnice_od"] = start_bulletin
+ params["broj_tecajnice_do"] = end_bulletin
+ elif start_bulletin:
+ params["broj_tecajnice"] = start_bulletin
+ # date_from not natively supported — fetch all and filter
+ items = self._get("tecajn-eur/v3", params)
+ rows = self._normalise_single(items)
+ if date_from:
+ rows = [r for r in rows if r["date"] >= date_from]
+ return {
+ "success": True,
+ "currency": currency,
+ "data": rows,
+ "count": len(rows),
+ "note": f"EUR per 1 {currency}",
+ "source": "Hrvatska Narodna Banka",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return HNBError(f"currency/{currency}", str(e), sc).to_dict()
+ except Exception as e:
+ return HNBError(f"currency/{currency}", str(e)).to_dict()
+
+ def get_bulletin_range(self, from_num: int, to_num: int) -> Dict[str, Any]:
+ """
+ All currencies for a range of bulletin numbers.
+ Returns wide-format rows keyed by date.
+ Each bulletin covers one business day.
+ """
+ try:
+ params = {
+ "broj_tecajnice_od": from_num,
+ "broj_tecajnice_do": to_num,
+ }
+ items = self._get("tecajn-eur/v3", params)
+ rows = self._normalise(items)
+ return {
+ "success": True,
+ "from_num": from_num,
+ "to_num": to_num,
+ "data": rows,
+ "count": len(rows),
+ "note": "EUR per 1 unit of foreign currency",
+ "source": "Hrvatska Narodna Banka",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return HNBError("bulletin_range", str(e), sc).to_dict()
+ except Exception as e:
+ return HNBError("bulletin_range", str(e)).to_dict()
+
+ def get_usd_eur(self, bulletins: int = 20) -> Dict[str, Any]:
+ """USD/EUR rate history — last N bulletins."""
+ return self.get_currency("USD", end_bulletin=bulletins)
+
+ def get_gbp_eur(self, bulletins: int = 20) -> Dict[str, Any]:
+ """GBP/EUR rate history — last N bulletins."""
+ return self.get_currency("GBP", end_bulletin=bulletins)
+
+ def get_overview(self) -> Dict[str, Any]:
+ """Snapshot: today's middle rates for all currencies vs EUR."""
+ return self.get_today()
+
+ def available_currencies(self) -> Dict[str, Any]:
+ """List of currencies published by HNB."""
+ return {
+ "success": True,
+ "currencies": ALL_CURRENCIES,
+ "major_currencies": MAJOR_CURRENCIES,
+ "base_currency": "EUR",
+ "note": "Rates expressed as EUR per 1 unit of foreign currency",
+ "source": "Hrvatska Narodna Banka",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "today": " — Latest bulletin (all currencies vs EUR)",
+ "currency": "<CCY> [from_bulletin] [to_bul] [date_from] — Single currency history",
+ "range": "<from_bulletin> <to_bulletin> — Bulletin range (wide format)",
+ "usd": "[bulletins=20] — USD/EUR last N bulletins",
+ "gbp": "[bulletins=20] — GBP/EUR last N bulletins",
+ "overview": " — Today's rates snapshot",
+ "available":" — List available currencies",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python hnb_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = HNBWrapper()
+
+ try:
+ if cmd == "today":
+ result = wrapper.get_today()
+ elif cmd == "currency":
+ if len(sys.argv) < 3:
+ result = {"error": "currency requires <CCY>"}
+ else:
+ from_b = int(_a(3)) if _a(3) else None
+ to_b = int(_a(4)) if _a(4) else None
+ result = wrapper.get_currency(sys.argv[2], from_b, to_b, _a(5))
+ elif cmd == "range":
+ if len(sys.argv) < 4:
+ result = {"error": "range requires <from_bulletin> <to_bulletin>"}
+ else:
+ result = wrapper.get_bulletin_range(int(sys.argv[2]), int(sys.argv[3]))
+ elif cmd == "usd":
+ result = wrapper.get_usd_eur(int(_a(2, 20)))
+ elif cmd == "gbp":
+ result = wrapper.get_gbp_eur(int(_a(2, 20)))
+ elif cmd == "overview":
+ result = wrapper.get_overview()
+ elif cmd in ("available", "currencies"):
+ result = wrapper.available_currencies()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=True))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/ilostat_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/ilostat_data.py
new file mode 100644
index 000000000..e7b8cb24a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/ilostat_data.py
@@ -0,0 +1,1875 @@
+"""
+ILOSTAT Data Wrapper
+Fetches international labour statistics from the ILO ILOSTAT SDMX REST API
+and the ILOSTAT Bulk Download Facility.
+
+API Reference:
+ Base URL (SDMX): https://sdmx.ilo.org/rest
+ TOC (indicators): https://rplumber.ilo.org/metadata/toc/indicator
+ TOC (ref area): https://rplumber.ilo.org/metadata/toc/ref_area
+ Bulk Download CSV: SDMX REST API preferred; bulk .rds files at rplumber.ilo.org/files/indicator/
+ User Guide: https://webapps.ilo.org/ilostat-files/Documents/SDMX_User_Guide.pdf
+
+Authentication: None required — ILOSTAT is open data, no API key needed.
+
+Rate Limits: Not formally documented; HTTP 413 is returned when the query
+ result set exceeds the server payload limit (~300,000 records).
+ Use the bulk download facility or add dimension filters to reduce payload size.
+
+Response Formats: SDMX-JSON (jsondata), SDMX-CSV (csv / csvfilewithlabels), SDMX-ML (XML)
+Default format used here: CSV with labels for easy parsing.
+
+SDMX Key dimension order (dot-separated):
+ FREQ . REF_AREA . MEASURE . SEX . CLASSIF1 [. CLASSIF2]
+ e.g. "CAN.A.UNE_DEAP_RT.SEX_T.AGE_YTHADULT_YGE15"
+
+ Wildcarding: omit a dimension to wildcard it (use just the dots).
+ OR logic: use + between values, e.g. "CAN+USA+GBR"
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import io
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime
+
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+SDMX_BASE_URL = "https://sdmx.ilo.org/rest"
+
+# Bulk download: the old www.ilo.org URLs redirect to webapps.ilo.org but both
+# return 404 for CSV/GZ files as of 2025. The Rilostat R package uses
+# rplumber.ilo.org which serves .rds (R binary) files. For Python use the
+# SDMX REST API for data; rplumber.ilo.org only for the TOC CSV endpoint.
+BULK_BASE_URL = "https://www.ilo.org/ilostat-files/WEB_bulk_download"
+
+# Table of Contents: discovered working endpoint on rplumber.ilo.org
+TOC_BASE_URL = "https://rplumber.ilo.org/metadata/toc"
+TOC_BY_INDICATOR_URL = f"{TOC_BASE_URL}/indicator"
+TOC_BY_REF_AREA_URL = f"{TOC_BASE_URL}/ref_area"
+
+DEFAULT_TIMEOUT = 60 # seconds
+
+# ---------------------------------------------------------------------------
+# Key indicator codes (measure codes without the DF_ prefix)
+# These are the 'flow' identifiers used in the SDMX key.
+# The full dataflow ID used in the URL is: ILO,DF_<INDICATOR_CODE>
+# ---------------------------------------------------------------------------
+
+# Employment
+INDICATOR_EMP_TOTAL_SEX_AGE = "EMP_TEMP_SEX_AGE_NB" # Employment by sex & age (number)
+INDICATOR_EMP_TOTAL_SEX_STE = "EMP_TEMP_SEX_STE_NB" # Employment by sex & status in employment
+INDICATOR_EMP_TO_POP_RATIO = "EMP_DWAP_SEX_AGE_RT" # Employment-to-population ratio
+INDICATOR_EMP_MODELLED = "EMP_2EMP_SEX_AGE_NB" # ILO modelled estimates — employment
+
+# Unemployment
+INDICATOR_UNE_RATE_SEX_AGE = "UNE_DEAP_SEX_AGE_RT" # Unemployment rate by sex & age (used in SDMX key)
+INDICATOR_UNE_TOTAL_SEX_AGE_NB = "UNE_2UNE_SEX_AGE_NB" # Unemployment count (annual)
+INDICATOR_UNE_MODELLED_RATE = "UNE_DEAP_SEX_AGE_RT" # ILO modelled unemployment rate
+
+# Labour Force / Working-Age Population
+INDICATOR_EAP_TOTAL_SEX_AGE = "EAP_TEAP_SEX_AGE_NB" # Labour force by sex & age
+INDICATOR_EAP_PARTICIPATION_RATE = "EAP_DWAP_SEX_AGE_RT" # Labour force participation rate
+INDICATOR_WAP_TOTAL_SEX_AGE = "WAP_WAPF_SEX_AGE_NB" # Working-age population by sex & age
+
+# Wages & Earnings (verified dataflow IDs from /dataflow/ILO 2025-02)
+INDICATOR_EAR_HOURLY_SEX = "EAR_4HRL_SEX_CUR_NB" # Mean hourly earnings by sex & currency (DSD dims: REF_AREA.FREQ.MEASURE.SEX.CUR)
+INDICATOR_EAR_MONTHLY_SEX = "EAR_4MTH_SEX_CUR_NB" # Mean monthly earnings by sex & currency
+INDICATOR_EAR_MIN_WAGE = "EAR_4MMN_CUR_NB" # Statutory minimum wage (DSD dims: REF_AREA.FREQ.MEASURE.CUR — no SEX)
+INDICATOR_EAR_GENDER_GAP_OCC = "EAR_GGAP_OCU_RT" # Gender wage gap by occupation (verified existing)
+INDICATOR_EAR_LOW_PAY = "EAR_XTLP_SEX_RT" # Low pay incidence by sex (verified existing)
+INDICATOR_EAR_SDG_HOURLY = "SDG_0851_SEX_OCU_NB" # SDG 8.5.1 average hourly earnings
+
+# Labour Income / Productivity
+INDICATOR_LAP_INCOME_SHARE = "LAP_2GDP_NOC_RT" # Labour income share (% of GDP, modelled)
+INDICATOR_LAP_INCOME_DIST = "LAP_2LID_QTL_RT" # Income distribution by decile
+INDICATOR_LAP_GENDER_INCOME_GAP = "LAP_2FTM_NOC_RT" # Gender income gap (women-to-men ratio)
+
+# Hours of Work
+INDICATOR_HOW_MEAN_WEEKLY_SEX = "HOW_TEMP_SEX_ECO_NB" # Mean weekly hours by sex & economic activity
+INDICATOR_HOW_EXCESSIVE_48H = "HOW_XEES_SEX_ECO_RT" # Share working > 48h/week
+
+# SDG Labour Market Indicators
+INDICATOR_SDG_WORKING_POVERTY = "SDG_0111_SEX_AGE_RT" # SDG 1.1.1 working poverty rate (%)
+INDICATOR_SDG_SOCIAL_PROTECTION = "SDG_0131_SEX_SOC_RT" # SDG 1.3.1 social protection coverage
+INDICATOR_SDG_LABOUR_INCOME_SHARE = "SDG_1041_NOC_RT" # SDG 10.4.1 labour income share
+
+# Exchange rates (for currency conversion context)
+INDICATOR_CCF_EXCHANGE_RATES = "CCF_XOXR_CUR_RT" # Official exchange rates (LCU per USD)
+INDICATOR_CCF_PPP = "CCF_XPPP_CUR_RT" # PPP conversion factors
+
+# ---------------------------------------------------------------------------
+# Frequency codes
+# ---------------------------------------------------------------------------
+FREQ_ANNUAL = "A"
+FREQ_QUARTERLY = "Q"
+FREQ_MONTHLY = "M"
+
+# ---------------------------------------------------------------------------
+# Common ISO-2 country code groups
+# ---------------------------------------------------------------------------
+G7_COUNTRIES = "CAN+USA+GBR+DEU+FRA+ITA+JPN"
+G20_COUNTRIES = "CAN+USA+GBR+DEU+FRA+ITA+JPN+AUS+BRA+CHN+IND+IDN+MEX+RUS+SAU+ZAF+KOR+TUR+ARG+EUN"
+EU_COUNTRIES = "AUT+BEL+BGR+HRV+CYP+CZE+DNK+EST+FIN+FRA+DEU+GRC+HUN+IRL+ITA+LVA+LTU+LUX+MLT+NLD+POL+PRT+ROU+SVK+SVN+ESP+SWE"
+
+
+# ---------------------------------------------------------------------------
+# Helper utilities
+# ---------------------------------------------------------------------------
+
+def _build_dataflow_id(indicator_code: str) -> str:
+ """Build the SDMX dataflow ID from a plain indicator code."""
+ if indicator_code.startswith("DF_"):
+ return indicator_code
+ return f"DF_{indicator_code}"
+
+
+def _session() -> requests.Session:
+ """Return a pre-configured requests Session."""
+ s = requests.Session()
+ s.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1 (ILOSTAT-wrapper)",
+ "Accept-Language": "en",
+ })
+ return s
+
+
+def _parse_csv_response(text: str) -> List[Dict[str, Any]]:
+ """
+ Parse a CSV text body into a list of dicts.
+ Uses the stdlib csv module to avoid requiring pandas.
+ """
+ import csv
+ reader = csv.DictReader(io.StringIO(text))
+ rows = []
+ for row in reader:
+ cleaned = {}
+ for k, v in row.items():
+ k = k.strip().strip('"')
+ v = v.strip()
+ # Try numeric conversion
+ try:
+ cleaned[k] = float(v) if "." in v else int(v)
+ except (ValueError, TypeError):
+ cleaned[k] = v if v != "" else None
+ rows.append(cleaned)
+ return rows
+
+
+def _safe_float(val: Any) -> Optional[float]:
+ try:
+ return float(val)
+ except (TypeError, ValueError):
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Core SDMX REST query builder
+# ---------------------------------------------------------------------------
+
+class ILOStatError:
+ """Structured error container for Rust JSON consumption."""
+
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now().timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "ILOStatError",
+ }
+
+
+class ILOStatWrapper:
+ """
+ Complete Python wrapper for the ILOSTAT SDMX REST API and Bulk Download Facility.
+
+ SDMX REST API base URL: https://sdmx.ilo.org/rest
+ Agency ID: ILO (always)
+ Dataflow pattern: ILO,DF_<DSD_ID>[,<version>]
+
+ Supported resource types:
+ data — actual observations
+ dataflow — list / describe dataflows (indicators)
+ datastructure — DSD (dimensions, attributes, measures)
+ codelist — code lists (e.g. CL_AREA, CL_SEX)
+ conceptscheme — concept schemes
+ categoryscheme — category schemes
+ categorisation — categorisations
+
+ Data URL format:
+ {base}/data/{agency},{flow}[,{version}]/{key}
+ ?startPeriod=YYYY[-MM[-DD]]
+ &endPeriod=YYYY[-MM[-DD]]
+ &detail=dataonly|serieskeysonly|full
+ &updatedAfter=YYYY-MM-DDThh:mm:ss
+ &firstNObservations=N
+ &lastNObservations=N
+ &dimensionAtObservation=AllDimensions|TIME_PERIOD
+ Accept: text/csv → returns SDMX-CSV
+ Accept: application/json → returns SDMX-JSON (complex nested structure)
+
+ Key format (dot-separated dimension values, in DSD-defined order):
+ FREQ.REF_AREA.MEASURE.SEX.CLASSIF1[.CLASSIF2]
+ Omit a dimension to wildcard (consecutive dots mean wildcard).
+ Use + for OR: CAN+USA+GBR
+ Use ALL to wildcard every dimension.
+
+ Example calls:
+ # Canada monthly unemployment rate, all sexes, adults 15+
+ GET https://sdmx.ilo.org/rest/data/ILO,DF_UNE_DEAP_SEX_AGE_RT,1.0/CAN.M.UNE_DEAP_RT.SEX_T.AGE_YTHADULT_YGE15
+ ?startPeriod=2010&format=csv
+
+ # All countries, annual employment by sex & age
+ GET https://sdmx.ilo.org/rest/data/ILO,DF_EMP_TEMP_SEX_AGE_NB/ALL
+ ?startPeriod=2000&endPeriod=2023&format=csv
+
+ Bulk Download:
+ Indicator CSV: https://www.ilo.org/ilostat-files/WEB_bulk_download/indicator/{INDICATOR_CODE}.csv.gz
+ TOC: https://www.ilo.org/ilostat-files/WEB_bulk_download/indicator/table_of_contents_en.csv
+ """
+
+ def __init__(self):
+ self.sdmx_base = SDMX_BASE_URL
+ self.bulk_base = BULK_BASE_URL
+ self.session = _session()
+
+ # ------------------------------------------------------------------
+ # Internal request helpers
+ # ------------------------------------------------------------------
+
+ def _get_csv(self, url: str, params: Optional[Dict] = None) -> str:
+ """Perform a GET request expecting CSV; return raw text."""
+ headers = {"Accept": "text/csv"}
+ resp = self.session.get(url, params=params, headers=headers, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.text
+
+ def _get_json(self, url: str, params: Optional[Dict] = None) -> Dict[str, Any]:
+ """Perform a GET request expecting JSON."""
+ headers = {"Accept": "application/json"}
+ resp = self.session.get(url, params=params, headers=headers, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.json()
+
+ def _get_xml(self, url: str, params: Optional[Dict] = None) -> str:
+ """Perform a GET request expecting XML text."""
+ headers = {"Accept": "application/xml"}
+ resp = self.session.get(url, params=params, headers=headers, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.text
+
+ # ------------------------------------------------------------------
+ # Structural / metadata endpoints
+ # ------------------------------------------------------------------
+
+ def list_dataflows(self, topic_prefix: Optional[str] = None) -> Dict[str, Any]:
+ """
+ Retrieve all available ILOSTAT dataflows (indicators).
+
+ Calls: GET {base}/dataflow/ILO
+ Returns a list of dataflow objects parsed from the XML response.
+
+ Args:
+ topic_prefix: Optional filter, e.g. "EMP", "UNE", "EAR", "HOW", "WAP", "LAP"
+ If supplied only matching dataflows are returned.
+
+ Returns dict:
+ {
+ "success": True,
+ "data": [{"id": "DF_EMP_TEMP_SEX_AGE_NB", "name": "...", "agency": "ILO"}, ...],
+ "count": N,
+ "parameters": {"topic_prefix": ...}
+ }
+ """
+ try:
+ url = f"{self.sdmx_base}/dataflow/ILO"
+ # Fetch as XML because the JSON format for structure queries is unreliable
+ xml_text = self._get_xml(url)
+
+ # Parse minimal dataflow information from the XML without lxml dependency
+ import re
+ # Match Dataflow elements and extract id and name attributes / child Name elements
+ dataflows = []
+ # Pattern to extract dataflow blocks
+ df_blocks = re.findall(
+ r'<(?:str:|structure:)?Dataflow\b([^>]*)>(.*?)</(?:str:|structure:)?Dataflow>',
+ xml_text,
+ re.DOTALL | re.IGNORECASE,
+ )
+
+ if not df_blocks:
+ # Simpler attribute-only match (self-closing or with children)
+ id_matches = re.findall(
+ r'<(?:str:|structure:)?Dataflow\b[^>]*\bid=["\']([^"\']+)["\'][^>]*>',
+ xml_text,
+ re.IGNORECASE,
+ )
+ for df_id in id_matches:
+ dataflows.append({"id": df_id, "agency": "ILO"})
+ else:
+ for attrs_str, body in df_blocks:
+ df_id_m = re.search(r'\bid=["\']([^"\']+)["\']', attrs_str)
+ name_m = re.search(r'<(?:com:|common:)?Name[^>]*>([^<]+)</(?:com:|common:)?Name>', body, re.IGNORECASE)
+ df_id = df_id_m.group(1) if df_id_m else "unknown"
+ df_name = name_m.group(1).strip() if name_m else df_id
+ dataflows.append({"id": df_id, "name": df_name, "agency": "ILO"})
+
+ # Apply topic prefix filter
+ if topic_prefix:
+ prefix_upper = topic_prefix.upper()
+ dataflows = [d for d in dataflows if prefix_upper in d.get("id", "")]
+
+ return {
+ "success": True,
+ "data": dataflows,
+ "count": len(dataflows),
+ "parameters": {"topic_prefix": topic_prefix},
+ }
+
+ except requests.exceptions.HTTPError as e:
+ return {"error": ILOStatError("list_dataflows", str(e), e.response.status_code).to_dict()}
+ except Exception as e:
+ return {"error": ILOStatError("list_dataflows", str(e)).to_dict()}
+
+ def get_codelist(self, codelist_id: str, agency: str = "ILO") -> Dict[str, Any]:
+ """
+ Retrieve a specific codelist by ID.
+
+ Calls: GET {base}/codelist/{agency}/{codelist_id}
+
+ Common codelist IDs:
+ CL_AREA — ISO country / region codes used by ILO
+ CL_SEX — Sex disaggregation codes (SEX_T, SEX_M, SEX_F)
+ CL_FREQ — Frequency codes (A, Q, M)
+ CL_ECO — Economic activity classification (ISIC)
+ CL_AGE — Age group classification
+ CL_OCU — Occupation classification (ISCO)
+
+ Returns dict with list of code entries.
+ """
+ try:
+ url = f"{self.sdmx_base}/codelist/{agency}/{codelist_id}"
+ xml_text = self._get_xml(url)
+
+ import re
+ # Extract Code elements
+ codes = []
+ code_blocks = re.findall(
+ r'<(?:str:|structure:)?Code\b([^>]*)>(.*?)</(?:str:|structure:)?Code>',
+ xml_text,
+ re.DOTALL | re.IGNORECASE,
+ )
+ for attrs_str, body in code_blocks:
+ code_id_m = re.search(r'\bid=["\']([^"\']+)["\']', attrs_str)
+ name_m = re.search(r'<(?:com:|common:)?Name[^>]*>([^<]+)</(?:com:|common:)?Name>', body, re.IGNORECASE)
+ code_id = code_id_m.group(1) if code_id_m else "unknown"
+ code_name = name_m.group(1).strip() if name_m else code_id
+ codes.append({"id": code_id, "label": code_name})
+
+ return {
+ "success": True,
+ "codelist_id": codelist_id,
+ "agency": agency,
+ "data": codes,
+ "count": len(codes),
+ }
+
+ except requests.exceptions.HTTPError as e:
+ return {"error": ILOStatError("get_codelist", str(e), e.response.status_code).to_dict()}
+ except Exception as e:
+ return {"error": ILOStatError("get_codelist", str(e)).to_dict()}
+
+ def get_data_structure(self, dsd_id: str) -> Dict[str, Any]:
+ """
+ Retrieve the Data Structure Definition (DSD) for a given indicator.
+
+ Calls: GET {base}/datastructure/ILO/{dsd_id}
+
+ The DSD describes all dimensions, their order, and the codelists they reference.
+ The dsd_id is the same as the indicator code (without the DF_ prefix).
+
+ Example: dsd_id = "EMP_TEMP_SEX_AGE_NB"
+ """
+ try:
+ url = f"{self.sdmx_base}/datastructure/ILO/{dsd_id}"
+ xml_text = self._get_xml(url)
+ return {
+ "success": True,
+ "dsd_id": dsd_id,
+ "raw_xml": xml_text,
+ }
+ except requests.exceptions.HTTPError as e:
+ return {"error": ILOStatError("get_data_structure", str(e), e.response.status_code).to_dict()}
+ except Exception as e:
+ return {"error": ILOStatError("get_data_structure", str(e)).to_dict()}
+
+ # ------------------------------------------------------------------
+ # Table of Contents (bulk download)
+ # ------------------------------------------------------------------
+
+ def get_table_of_contents(
+ self,
+ segment: str = "indicator",
+ language: str = "en",
+ search: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Download and parse the ILOSTAT Table of Contents CSV.
+
+ This is the definitive catalogue of ~500 indicator datasets. Each row
+ contains the dataset id, frequency, time range, last update, and file size.
+
+ Args:
+ segment: "indicator" (default) or "ref_area"
+ language: "en" (default), "fr", or "es"
+ search: Optional case-insensitive substring to filter indicator rows.
+
+ TOC URL: https://rplumber.ilo.org/metadata/toc/{segment}
+ (CSV response; the old www.ilo.org bulk-download CSV URLs are no longer publicly accessible)
+
+ Returns dict:
+ {
+ "success": True,
+ "data": [{"id": "EMP_TEMP_SEX_AGE_NB_A", "indicator": "...", ...}, ...],
+ "count": N
+ }
+ """
+ try:
+ # rplumber.ilo.org returns CSV directly for both segments
+ # The language parameter is not supported by this endpoint (English only)
+ url = f"{TOC_BASE_URL}/{segment}"
+ text = self._get_csv(url)
+ rows = _parse_csv_response(text)
+
+ if search:
+ search_lower = search.lower()
+ rows = [
+ r for r in rows
+ if any(search_lower in str(v).lower() for v in r.values())
+ ]
+
+ return {
+ "success": True,
+ "data": rows,
+ "count": len(rows),
+ "parameters": {"segment": segment, "language": language, "search": search},
+ }
+
+ except requests.exceptions.HTTPError as e:
+ return {"error": ILOStatError("get_table_of_contents", str(e), e.response.status_code).to_dict()}
+ except Exception as e:
+ return {"error": ILOStatError("get_table_of_contents", str(e)).to_dict()}
+
+ # ------------------------------------------------------------------
+ # Data retrieval — SDMX REST API
+ # ------------------------------------------------------------------
+
+ def get_data(
+ self,
+ indicator_code: str,
+ key: str = "ALL",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ detail: str = "dataonly",
+ last_n_obs: Optional[int] = None,
+ first_n_obs: Optional[int] = None,
+ version: str = "1.0",
+ ) -> Dict[str, Any]:
+ """
+ Core data query against the ILOSTAT SDMX REST API.
+
+ Calls:
+ GET {base}/data/ILO,DF_{indicator_code},{version}/{key}
+ ?startPeriod=...&endPeriod=...&detail=...
+
+ Args:
+ indicator_code: The indicator/DSD code without the DF_ prefix.
+ E.g. "UNE_DEAP_SEX_AGE_RT" or "EMP_TEMP_SEX_AGE_NB"
+ key: Dot-separated dimension key. "ALL" wildcards everything.
+ Format: FREQ.REF_AREA.MEASURE.SEX.CLASSIF1[.CLASSIF2]
+ Example: "A.DEU.UNE_DEAP_RT.SEX_T.AGE_YTHADULT_YGE15"
+ Use + for OR: "CAN+USA+GBR.A..."
+ start_period: Start year/date in ISO format (e.g. "2010" or "2010-01").
+ end_period: End year/date in ISO format.
+ detail: Level of detail:
+ "dataonly" — observations only (fastest)
+ "full" — observations + all attributes
+ "serieskeysonly" — no observations, just dimension keys
+ "nodata" — structure only, no obs values
+ last_n_obs: Return only the last N observations per series.
+ first_n_obs: Return only the first N observations per series.
+ version: Dataflow version (default "1.0").
+
+ Returns:
+ {
+ "success": True,
+ "indicator": "UNE_DEAP_SEX_AGE_RT",
+ "dataflow": "ILO,DF_UNE_DEAP_SEX_AGE_RT,1.0",
+ "key": "ALL",
+ "data": [
+ {
+ "FREQ": "A", "REF_AREA": "USA", "MEASURE": "UNE_DEAP_RT",
+ "SEX": "SEX_T", "AGE": "AGE_YTHADULT_YGE15",
+ "TIME_PERIOD": "2022", "OBS_VALUE": 3.6
+ }, ...
+ ],
+ "count": N,
+ "parameters": {...}
+ }
+ """
+ try:
+ # Build the dataflow reference
+ df_id = _build_dataflow_id(indicator_code)
+ flow_ref = f"ILO,{df_id},{version}"
+ url = f"{self.sdmx_base}/data/{flow_ref}/{key}"
+
+ params: Dict[str, Any] = {"detail": detail}
+ if start_period:
+ params["startPeriod"] = start_period
+ if end_period:
+ params["endPeriod"] = end_period
+ if last_n_obs is not None:
+ params["lastNObservations"] = last_n_obs
+ if first_n_obs is not None:
+ params["firstNObservations"] = first_n_obs
+
+ csv_text = self._get_csv(url, params=params)
+ rows = _parse_csv_response(csv_text)
+
+ # Coerce OBS_VALUE to float where possible
+ for row in rows:
+ if "OBS_VALUE" in row and row["OBS_VALUE"] is not None:
+ row["OBS_VALUE"] = _safe_float(row["OBS_VALUE"])
+
+ return {
+ "success": True,
+ "indicator": indicator_code,
+ "dataflow": flow_ref,
+ "key": key,
+ "data": rows,
+ "count": len(rows),
+ "parameters": {
+ "start_period": start_period,
+ "end_period": end_period,
+ "detail": detail,
+ "last_n_obs": last_n_obs,
+ "first_n_obs": first_n_obs,
+ },
+ }
+
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ msg = str(e)
+ if sc == 413:
+ msg = (
+ "HTTP 413 Payload Too Large: query returned too many results. "
+ "Narrow the key (add country, frequency, or classification filters) "
+ "or use get_bulk_data() for full datasets."
+ )
+ return {"error": ILOStatError("get_data", msg, sc).to_dict()}
+ except Exception as e:
+ return {"error": ILOStatError("get_data", str(e)).to_dict()}
+
+ # ------------------------------------------------------------------
+ # High-level, domain-specific convenience methods
+ # ------------------------------------------------------------------
+
+ def get_unemployment(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ sex: str = "SEX_T",
+ age_group: str = "AGE_YTHADULT_YGE15",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch unemployment rate data.
+
+ Indicator: DF_UNE_DEAP_SEX_AGE_RT (ILO modelled estimates — unemployment rate)
+ Dataflow: https://sdmx.ilo.org/rest/data/ILO,DF_UNE_DEAP_SEX_AGE_RT,1.0/{key}
+
+ Dimension key order: REF_AREA . FREQ . MEASURE . SEX . AGE
+
+ Args:
+ countries: ISO-2 country code(s). Use + for multiple: "USA+DEU+FRA"
+ Use "ALL" to get all countries (may be slow / 413).
+ frequency: "A" (annual), "Q" (quarterly), "M" (monthly)
+ sex: "SEX_T" (total), "SEX_M" (male), "SEX_F" (female)
+ age_group: Common values:
+ "AGE_YTHADULT_YGE15" — 15 and over (standard)
+ "AGE_YTHADULT_Y15-24" — youth 15-24
+ "AGE_YTHADULT_YGE25" — adult 25 and over
+ start_period: e.g. "2000"
+ end_period: e.g. "2023"
+
+ Example URL:
+ https://sdmx.ilo.org/rest/data/ILO,DF_UNE_DEAP_SEX_AGE_RT,1.0/
+ USA.A.UNE_DEAP_RT.SEX_T.AGE_YTHADULT_YGE15?startPeriod=2010
+
+ Returns standard data dict.
+ """
+ # Key: REF_AREA.FREQ.MEASURE.SEX.AGE
+ measure = "UNE_DEAP_RT"
+ key = f"{countries}.{frequency}.{measure}.{sex}.{age_group}"
+
+ result = self.get_data(
+ indicator_code = "UNE_DEAP_SEX_AGE_RT",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "unemployment_rate"
+ return result
+
+ def get_employment(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ sex: str = "SEX_T",
+ age_group: str = "_T",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch total employment data by sex and age.
+
+ Indicator: DF_EMP_TEMP_SEX_AGE_NB (employment by sex and age, number)
+ Dataflow: https://sdmx.ilo.org/rest/data/ILO,DF_EMP_TEMP_SEX_AGE_NB,1.0/{key}
+
+ Dimension key order: REF_AREA.FREQ.MEASURE.SEX.AGE
+
+ Common age group codes:
+ "_T" — Total (all ages)
+ "AGE_YTHADULT_YGE15" — 15 and over
+ "AGE_YTHADULT_Y15-24" — Youth 15-24
+ "AGE_5YRBANDS_YGE65" — 65 and over
+ """
+ measure = "EMP_TEMP_NB"
+ key = f"{countries}.{frequency}.{measure}.{sex}.{age_group}"
+ result = self.get_data(
+ indicator_code = "EMP_TEMP_SEX_AGE_NB",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "employment_total"
+ return result
+
+ def get_employment_to_population_ratio(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ sex: str = "SEX_T",
+ age_group: str = "AGE_YTHADULT_YGE15",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch employment-to-population ratio.
+
+ Indicator: DF_EMP_DWAP_SEX_AGE_RT
+ """
+ measure = "EMP_DWAP_RT"
+ key = f"{countries}.{frequency}.{measure}.{sex}.{age_group}"
+ result = self.get_data(
+ indicator_code = "EMP_DWAP_SEX_AGE_RT",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "employment_to_population_ratio"
+ return result
+
+ def get_labour_force_participation(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ sex: str = "SEX_T",
+ age_group: str = "AGE_YTHADULT_YGE15",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch labour force participation rate.
+
+ Indicator: DF_EAP_DWAP_SEX_AGE_RT (labour force participation rate)
+ """
+ measure = "EAP_DWAP_RT"
+ key = f"{countries}.{frequency}.{measure}.{sex}.{age_group}"
+ result = self.get_data(
+ indicator_code = "EAP_DWAP_SEX_AGE_RT",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "labour_force_participation_rate"
+ return result
+
+ def get_wages(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ wage_type: str = "monthly",
+ sex: str = "SEX_T",
+ currency: str = "CUR_TYPE_LCU",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch mean earnings data (hourly or monthly).
+
+ Verified dataflow IDs (from the live SDMX /dataflow/ILO endpoint):
+ hourly → DF_EAR_4HRL_SEX_CUR_NB
+ DSD dims: REF_AREA.FREQ.MEASURE.SEX.CUR
+ Measure: EAR_4HRL_NB
+ monthly → DF_EAR_4MTH_SEX_CUR_NB
+ DSD dims: REF_AREA.FREQ.MEASURE.SEX.CUR
+ Measure: EAR_4MTH_NB
+ minimum → DF_EAR_4MMN_CUR_NB (statutory minimum wage, no sex dimension)
+ DSD dims: REF_AREA.FREQ.MEASURE.CUR
+ Measure: EAR_4MMN_NB
+
+ Args:
+ wage_type: "hourly" | "monthly" (default) | "minimum"
+ currency: CL_CUR codelist value:
+ "CUR_TYPE_LCU" — Local currency units [default]
+ "CUR_TYPE_USD" — US Dollars
+ "CUR_TYPE_EUR" — Euros (where applicable)
+ "CUR_TYPE_PPP" — PPP-adjusted international dollars
+
+ Example (Germany monthly wages in LCU):
+ https://sdmx.ilo.org/rest/data/ILO,DF_EAR_4MTH_SEX_CUR_NB,1.0/
+ DEU.A.EAR_4MTH_NB.SEX_T.CUR_TYPE_LCU?startPeriod=2010
+ """
+ if wage_type == "hourly":
+ indicator_code = "EAR_4HRL_SEX_CUR_NB"
+ measure = "EAR_4HRL_NB"
+ key = f"{countries}.{frequency}.{measure}.{sex}.{currency}"
+ elif wage_type == "minimum":
+ indicator_code = "EAR_4MMN_CUR_NB"
+ measure = "EAR_4MMN_NB"
+ # Minimum wage DSD has no SEX dimension: REF_AREA.FREQ.MEASURE.CUR
+ key = f"{countries}.{frequency}.{measure}.{currency}"
+ else: # monthly (default)
+ indicator_code = "EAR_4MTH_SEX_CUR_NB"
+ measure = "EAR_4MTH_NB"
+ key = f"{countries}.{frequency}.{measure}.{sex}.{currency}"
+
+ result = self.get_data(
+ indicator_code = indicator_code,
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = f"wages_{wage_type}"
+ return result
+
+ def get_gender_wage_gap(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ occupation: str = "OCU_ISCO08_TOTAL",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch gender wage gap by occupation.
+
+ Indicator: DF_EAR_GGAP_OCU_RT
+ DSD dimension order (verified): REF_AREA . FREQ . MEASURE . OCU
+ Note: This dataflow has NO SEX dimension — it is inherently a gender gap measure.
+
+ Args:
+ occupation: OCU codelist code (same CL_OCU as employment by occupation).
+ "OCU_ISCO08_TOTAL" — Total all occupations [default]
+ "" (empty string) — wildcard to get all occupation breakdowns
+
+ Example:
+ https://sdmx.ilo.org/rest/data/ILO,DF_EAR_GGAP_OCU_RT,1.0/
+ GBR.A.EAR_GGAP_RT.OCU_ISCO08_TOTAL?startPeriod=2015
+ """
+ measure = "EAR_GGAP_RT"
+ if occupation:
+ key = f"{countries}.{frequency}.{measure}.{occupation}"
+ else:
+ key = f"{countries}.{frequency}.{measure}."
+ result = self.get_data(
+ indicator_code = "EAR_GGAP_OCU_RT",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "gender_wage_gap"
+ return result
+
+ def get_hours_of_work(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ sex: str = "SEX_T",
+ economic_act: str = "ECO_ISIC4_TOTAL",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch mean weekly hours of work.
+
+ Indicator: DF_HOW_TEMP_SEX_ECO_NB (mean weekly hours by sex & economic activity)
+ DSD dimension order: REF_AREA . FREQ . MEASURE . SEX . ECO
+
+ Common ECO codes (same CL_ECO codelist as employment by sector):
+ "ECO_ISIC4_TOTAL" — Total (all sectors) [default]
+ "ECO_ISIC4_A" — Agriculture, forestry and fishing
+ "ECO_ISIC4_C" — Manufacturing
+ "ECO_ISIC4_F" — Construction
+ "ECO_ISIC4_G" — Wholesale and retail trade
+ "ECO_ISIC4_K" — Financial and insurance activities
+ "ECO_ISIC4_O" — Public administration and defence
+ "ECO_ISIC4_P" — Education
+ "ECO_ISIC4_Q" — Human health and social work
+
+ Pass economic_act="" to wildcard (all sector breakdowns).
+ """
+ measure = "HOW_TEMP_NB"
+ if economic_act:
+ key = f"{countries}.{frequency}.{measure}.{sex}.{economic_act}"
+ else:
+ key = f"{countries}.{frequency}.{measure}.{sex}."
+ result = self.get_data(
+ indicator_code = "HOW_TEMP_SEX_ECO_NB",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "hours_of_work_mean_weekly"
+ return result
+
+ def get_labour_income_share(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch labour income share as % of GDP (ILO modelled estimates).
+
+ Indicator: DF_LAP_2GDP_NOC_RT
+ SDG 10.4.1 proxy indicator.
+ """
+ measure = "LAP_2GDP_RT"
+ key = f"{countries}.{frequency}.{measure}"
+ result = self.get_data(
+ indicator_code = "LAP_2GDP_NOC_RT",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "labour_income_share"
+ return result
+
+ def get_working_poverty(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ sex: str = "SEX_T",
+ age_group: str = "AGE_YTHADULT_YGE15",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch working poverty rate (SDG 1.1.1).
+
+ Indicator: DF_SDG_0111_SEX_AGE_RT
+ DSD dimension order (verified): REF_AREA . FREQ . MEASURE . SEX . AGE
+ Working poverty: employed persons living below US$3.65/day (2017 PPP).
+
+ Args:
+ age_group: AGE codelist code.
+ "AGE_YTHADULT_YGE15" — 15 and over [default]
+ "" (empty string) — wildcard all age groups
+
+ Example:
+ https://sdmx.ilo.org/rest/data/ILO,DF_SDG_0111_SEX_AGE_RT,1.0/
+ IND.A.SDG_0111_RT.SEX_T.AGE_YTHADULT_YGE15?startPeriod=2010
+ """
+ measure = "SDG_0111_RT"
+ if age_group:
+ key = f"{countries}.{frequency}.{measure}.{sex}.{age_group}"
+ else:
+ key = f"{countries}.{frequency}.{measure}.{sex}."
+ result = self.get_data(
+ indicator_code = "SDG_0111_SEX_AGE_RT",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "working_poverty_rate"
+ return result
+
+ def get_employment_by_sector(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ sex: str = "SEX_T",
+ sector: str = "ECO_ISIC4_TOTAL",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch employment broken down by economic sector (ISIC Rev.4).
+
+ Indicator: DF_EMP_TEMP_SEX_ECO_NB (employment by sex and economic activity)
+ DSD dimension order (verified): REF_AREA . FREQ . MEASURE . SEX . ECO
+
+ Common ECO sector codes (ILO CL_ECO codelist, ISIC Rev.4):
+ "ECO_ISIC4_TOTAL" — Total (all sectors) [default]
+ "ECO_ISIC4_A" — Agriculture, forestry and fishing
+ "ECO_ISIC4_B" — Mining and quarrying
+ "ECO_ISIC4_C" — Manufacturing
+ "ECO_ISIC4_D" — Electricity, gas, steam and air conditioning supply
+ "ECO_ISIC4_E" — Water supply, sewerage, waste management
+ "ECO_ISIC4_F" — Construction
+ "ECO_ISIC4_G" — Wholesale and retail trade; repair of motor vehicles
+ "ECO_ISIC4_H" — Transportation and storage
+ "ECO_ISIC4_I" — Accommodation and food service activities
+ "ECO_ISIC4_J" — Information and communication
+ "ECO_ISIC4_K" — Financial and insurance activities
+ "ECO_ISIC4_L" — Real estate activities
+ "ECO_ISIC4_M" — Professional, scientific and technical activities
+ "ECO_ISIC4_N" — Administrative and support service activities
+ "ECO_ISIC4_O" — Public administration and defence
+ "ECO_ISIC4_P" — Education
+ "ECO_ISIC4_Q" — Human health and social work activities
+ "ECO_ISIC4_R" — Arts, entertainment and recreation
+ "ECO_ISIC4_S" — Other service activities
+ "ECO_ISIC4_T" — Activities of households as employers
+ "ECO_ISIC4_U" — Activities of extraterritorial organizations
+
+ Trailing dot wildcard (all sectors): pass sector="" to get all sector breakdowns.
+ """
+ measure = "EMP_TEMP_NB"
+ # Allow trailing wildcard: if sector is empty, omit it (trailing dot wildcards last dim)
+ if sector:
+ key = f"{countries}.{frequency}.{measure}.{sex}.{sector}"
+ else:
+ key = f"{countries}.{frequency}.{measure}.{sex}."
+ result = self.get_data(
+ indicator_code = "EMP_TEMP_SEX_ECO_NB",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "employment_by_sector"
+ return result
+
+ def get_employment_by_occupation(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ sex: str = "SEX_T",
+ occupation: str = "OCU_ISCO08_TOTAL",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch employment by occupation (ISCO-08 1-digit).
+
+ Indicator: DF_EMP_TEMP_SEX_OCU_NB
+ DSD dimension order: REF_AREA . FREQ . MEASURE . SEX . OCU
+
+ Common occupation codes (ILO CL_OCU codelist, ISCO-08):
+ "OCU_ISCO08_TOTAL" — Total all occupations [default]
+ "OCU_ISCO08_1" — Managers
+ "OCU_ISCO08_2" — Professionals
+ "OCU_ISCO08_3" — Technicians and associate professionals
+ "OCU_ISCO08_4" — Clerical support workers
+ "OCU_ISCO08_5" — Service and sales workers
+ "OCU_ISCO08_6" — Skilled agricultural, forestry and fishery workers
+ "OCU_ISCO08_7" — Craft and related trades workers
+ "OCU_ISCO08_8" — Plant and machine operators, and assemblers
+ "OCU_ISCO08_9" — Elementary occupations
+ "OCU_ISCO08_0" — Armed forces occupations
+
+ Pass occupation="" to wildcard (all occupation breakdowns).
+ """
+ measure = "EMP_TEMP_NB"
+ if occupation:
+ key = f"{countries}.{frequency}.{measure}.{sex}.{occupation}"
+ else:
+ key = f"{countries}.{frequency}.{measure}.{sex}."
+ result = self.get_data(
+ indicator_code = "EMP_TEMP_SEX_OCU_NB",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "employment_by_occupation"
+ return result
+
+ def get_employment_by_status(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ sex: str = "SEX_T",
+ status: str = "STE_ICSE93_TOTAL",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch employment by status in employment (ICSE-93 / ICSE-18).
+
+ Indicator: DF_EMP_TEMP_SEX_STE_NB
+ DSD dimension order: REF_AREA . FREQ . MEASURE . SEX . STE
+
+ Common status codes (ILO CL_STE codelist, ICSE-93):
+ "STE_ICSE93_TOTAL" — Total [default]
+ "STE_ICSE93_1" — Employees
+ "STE_ICSE93_2" — Employers
+ "STE_ICSE93_3" — Own-account workers
+ "STE_ICSE93_4" — Members of producers cooperatives
+ "STE_ICSE93_5" — Contributing family workers
+ "STE_ICSE93_6" — Workers not classifiable by status
+
+ Pass status="" to wildcard (all status breakdowns).
+ """
+ measure = "EMP_TEMP_NB"
+ if status:
+ key = f"{countries}.{frequency}.{measure}.{sex}.{status}"
+ else:
+ key = f"{countries}.{frequency}.{measure}.{sex}."
+ result = self.get_data(
+ indicator_code = "EMP_TEMP_SEX_STE_NB",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "employment_by_status_in_employment"
+ return result
+
+ def get_informal_employment(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ sex: str = "SEX_T",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch informal employment rate.
+
+ Indicator: DF_EMP_2EMP_SEX_STE_RT (share of informal employment by sex and status)
+ """
+ measure = "EMP_2EMP_RT"
+ key = f"{countries}.{frequency}.{measure}.{sex}._T"
+ result = self.get_data(
+ indicator_code = "EMP_2EMP_SEX_STE_RT",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "informal_employment"
+ return result
+
+ def get_social_protection_coverage(
+ self,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ sex: str = "SEX_T",
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch social protection coverage (SDG 1.3.1).
+
+ Indicator: DF_SDG_0131_SEX_SOC_RT
+ """
+ measure = "SDG_0131_RT"
+ key = f"{countries}.{frequency}.{measure}.{sex}._T"
+ result = self.get_data(
+ indicator_code = "SDG_0131_SEX_SOC_RT",
+ key = key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = "social_protection_coverage"
+ return result
+
+ def get_country_profile(
+ self,
+ country: str,
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch a comprehensive labour market profile for a single country.
+
+ Runs multiple queries and bundles results into one response.
+ Each sub-query falls back gracefully on failure.
+
+ Args:
+ country: ISO-2 country code, e.g. "DEU", "IND", "BRA"
+ start_period: e.g. "2010"
+ end_period: e.g. "2023"
+
+ Returns:
+ {
+ "success": True,
+ "country": "DEU",
+ "data": {
+ "unemployment_rate": {...},
+ "employment_to_pop": {...},
+ "labour_force_participation": {...},
+ "hours_of_work": {...},
+ "wages_monthly": {...},
+ "labour_income_share": {...},
+ },
+ "parameters": {...}
+ }
+ """
+ try:
+ profile: Dict[str, Any] = {}
+
+ # Unemployment rate
+ try:
+ profile["unemployment_rate"] = self.get_unemployment(
+ countries=country, start_period=start_period, end_period=end_period
+ )
+ except Exception as exc:
+ profile["unemployment_rate"] = {"error": str(exc)}
+
+ # Employment-to-population ratio
+ try:
+ profile["employment_to_pop"] = self.get_employment_to_population_ratio(
+ countries=country, start_period=start_period, end_period=end_period
+ )
+ except Exception as exc:
+ profile["employment_to_pop"] = {"error": str(exc)}
+
+ # Labour force participation rate
+ try:
+ profile["labour_force_participation"] = self.get_labour_force_participation(
+ countries=country, start_period=start_period, end_period=end_period
+ )
+ except Exception as exc:
+ profile["labour_force_participation"] = {"error": str(exc)}
+
+ # Mean weekly hours of work
+ try:
+ profile["hours_of_work"] = self.get_hours_of_work(
+ countries=country, start_period=start_period, end_period=end_period
+ )
+ except Exception as exc:
+ profile["hours_of_work"] = {"error": str(exc)}
+
+ # Monthly wages
+ try:
+ profile["wages_monthly"] = self.get_wages(
+ countries=country, wage_type="monthly",
+ start_period=start_period, end_period=end_period
+ )
+ except Exception as exc:
+ profile["wages_monthly"] = {"error": str(exc)}
+
+ # Labour income share
+ try:
+ profile["labour_income_share"] = self.get_labour_income_share(
+ countries=country, start_period=start_period, end_period=end_period
+ )
+ except Exception as exc:
+ profile["labour_income_share"] = {"error": str(exc)}
+
+ return {
+ "success": True,
+ "country": country,
+ "data": profile,
+ "parameters": {
+ "country": country,
+ "start_period": start_period,
+ "end_period": end_period,
+ },
+ }
+
+ except Exception as e:
+ return {"error": ILOStatError("get_country_profile", str(e)).to_dict()}
+
+ def get_sdg_indicator(
+ self,
+ sdg_code: str,
+ countries: str = "ALL",
+ frequency: str = FREQ_ANNUAL,
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Fetch a specific SDG labour market indicator.
+
+ Common SDG codes available in ILOSTAT:
+ "SDG_0111_SEX_AGE_RT" — 1.1.1 Working poverty rate
+ "SDG_0131_SEX_SOC_RT" — 1.3.1 Social protection coverage
+ "SDG_0551_NOC_RT" — 5.5.1 Women in managerial positions
+ "SDG_0552_NOC_RT" — 5.5.2 Women in senior and middle management
+ "SDG_0811_SEX_AGE_RT" — 8.1.1 Annual growth rate of GDP per employed person
+ "SDG_0851_SEX_OCU_NB" — 8.5.1 Average hourly earnings
+ "SDG_0852_SEX_AGE_RT" — 8.5.2 Unemployment rate
+ "SDG_0861_SEX_AGE_NB" — 8.6.1 Youth not in education, employment or training (NEET)
+ "SDG_0871_SEX_AGE_RT" — 8.7.1 Child labour
+ "SDG_0881_NOC_RT" — 8.8.1 Fatal occupational injuries
+ "SDG_0882_NOC_RT" — 8.8.2 Non-fatal occupational injuries
+ "SDG_1041_NOC_RT" — 10.4.1 Labour income share (% of GDP)
+
+ Args:
+ sdg_code: The full indicator code, e.g. "SDG_0852_SEX_AGE_RT"
+ countries: ISO-2 country code(s) or "ALL"
+ frequency: "A", "Q", or "M"
+
+ Returns standard data dict.
+ """
+ # Build a minimal key — the exact key dimensions depend on the specific DSD.
+ # Using ALL key is safest for discovery; narrow down as needed.
+ result = self.get_data(
+ indicator_code = sdg_code,
+ key = countries if countries == "ALL" else f"{countries}.{frequency}",
+ start_period = start_period,
+ end_period = end_period,
+ )
+ result["topic"] = f"sdg_{sdg_code}"
+ return result
+
+ # ------------------------------------------------------------------
+ # Bulk download method (for large datasets)
+ # ------------------------------------------------------------------
+
+ def get_bulk_data(
+ self,
+ indicator_id: str,
+ ref_area: Optional[str] = None,
+ start_period: Optional[str] = None,
+ end_period: Optional[str] = None,
+ max_rows: Optional[int] = None,
+ ) -> Dict[str, Any]:
+ """
+ Download a full dataset for a given indicator via the SDMX REST API
+ using an ALL key (wildcards every dimension).
+
+ Note on bulk download facility:
+ The classic CSV.GZ files at www.ilo.org/ilostat-files/WEB_bulk_download/
+ were migrated to webapps.ilo.org but appear to no longer be publicly
+ accessible as of 2025. The Rilostat R package uses .rds binary files
+ at rplumber.ilo.org which are not parseable from Python without R.
+ This method therefore uses the SDMX REST API with an ALL key, which
+ is functionally equivalent but subject to the 300,000-record payload
+ limit (HTTP 413). For datasets larger than this, filter by ref_area
+ or use the SDMX key to narrow the query before calling this function.
+
+ Args:
+ indicator_id: The indicator DSD code without the _A/_Q/_M frequency suffix
+ AND without the DF_ prefix, e.g. "EMP_TEMP_SEX_AGE_NB".
+ The frequency suffix present in the TOC id (e.g. _A) should
+ be omitted here — frequency is handled via the SDMX key.
+ ref_area: Optional ISO-2 country code to filter the SDMX key,
+ e.g. "DEU". If omitted, ALL countries are requested.
+ start_period: Start year/date, e.g. "2010".
+ end_period: End year/date, e.g. "2023".
+ max_rows: Cap on rows returned in the response (applied after fetch).
+
+ Returns standard data dict.
+ """
+ try:
+ # Strip _A/_Q/_M frequency suffix that appears in the TOC id
+ clean_id = indicator_id
+ for suffix in ("_A", "_Q", "_M"):
+ if clean_id.endswith(suffix):
+ clean_id = clean_id[:-len(suffix)]
+ break
+
+ sdmx_key = ref_area if ref_area else "ALL"
+
+ result = self.get_data(
+ indicator_code = clean_id,
+ key = sdmx_key,
+ start_period = start_period,
+ end_period = end_period,
+ )
+
+ if result.get("success") and max_rows:
+ result["data"] = result["data"][:max_rows]
+ result["count"] = len(result["data"])
+
+ result["indicator_id"] = indicator_id
+ result["source"] = "sdmx_all_key"
+ return result
+
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return {"error": ILOStatError("get_bulk_data", str(e), sc).to_dict()}
+ except Exception as e:
+ return {"error": ILOStatError("get_bulk_data", str(e)).to_dict()}
+
+ # ------------------------------------------------------------------
+ # Search / discovery helpers
+ # ------------------------------------------------------------------
+
+ def search_indicators(self, query: str, language: str = "en") -> Dict[str, Any]:
+ """
+ Search the ILOSTAT table of contents for matching indicators.
+
+ Wraps get_table_of_contents() with a search filter.
+
+ Args:
+ query: Free-text search string (case-insensitive substring match).
+ language: "en", "fr", or "es"
+
+ Returns standard data dict with matching TOC rows.
+ """
+ return self.get_table_of_contents(segment="indicator", language=language, search=query)
+
+ def list_countries(self) -> Dict[str, Any]:
+ """
+ Return the ILO area code list (ISO-2 + ILO region aggregates).
+
+ Calls: GET {base}/codelist/ILO/CL_AREA
+ """
+ return self.get_codelist("CL_AREA")
+
+ def list_sex_codes(self) -> Dict[str, Any]:
+ """Return sex disaggregation codes (SEX_T, SEX_M, SEX_F)."""
+ return self.get_codelist("CL_SEX")
+
+ def list_age_codes(self) -> Dict[str, Any]:
+ """Return age group codes used in ILOSTAT."""
+ return self.get_codelist("CL_AGE")
+
+ def list_economic_activity_codes(self) -> Dict[str, Any]:
+ """Return ISIC-based economic activity codes (CL_ECO)."""
+ return self.get_codelist("CL_ECO")
+
+ def list_occupation_codes(self) -> Dict[str, Any]:
+ """Return ISCO-based occupation codes (CL_OCU)."""
+ return self.get_codelist("CL_OCU")
+
+ def get_available_indicators_summary(self) -> Dict[str, Any]:
+ """
+ Return a curated static reference of the most commonly used
+ ILOSTAT indicator codes, grouped by topic.
+
+ This is a fast local reference — use get_table_of_contents() or
+ list_dataflows() for the live, complete catalogue.
+ """
+ indicators = {
+ "employment": [
+ {"code": "EMP_TEMP_SEX_AGE_NB", "freq": ["A", "Q", "M"], "description": "Employment by sex and age (number)"},
+ {"code": "EMP_TEMP_SEX_ECO_NB", "freq": ["A"], "description": "Employment by sex and economic activity (ISIC)"},
+ {"code": "EMP_TEMP_SEX_OCU_NB", "freq": ["A"], "description": "Employment by sex and occupation (ISCO)"},
+ {"code": "EMP_TEMP_SEX_STE_NB", "freq": ["A"], "description": "Employment by sex and status in employment"},
+ {"code": "EMP_DWAP_SEX_AGE_RT", "freq": ["A", "Q"], "description": "Employment-to-population ratio by sex and age"},
+ {"code": "EMP_2EMP_SEX_AGE_NB", "freq": ["A"], "description": "ILO modelled estimates — employment"},
+ {"code": "EMP_2EMP_SEX_STE_RT", "freq": ["A"], "description": "Informal employment share by sex and status"},
+ ],
+ "unemployment": [
+ {"code": "UNE_DEAP_SEX_AGE_RT", "freq": ["A", "Q", "M"], "description": "Unemployment rate by sex and age (ILO modelled)"},
+ {"code": "UNE_2UNE_SEX_AGE_NB", "freq": ["A"], "description": "Unemployment count by sex and age (annual)"},
+ {"code": "UNE_TUNE_SEX_AGE_NB", "freq": ["Q"], "description": "Unemployment by sex and age (quarterly)"},
+ ],
+ "labour_force": [
+ {"code": "EAP_DWAP_SEX_AGE_RT", "freq": ["A", "Q", "M"], "description": "Labour force participation rate by sex and age"},
+ {"code": "EAP_TEAP_SEX_AGE_NB", "freq": ["A", "Q"], "description": "Labour force (economically active population) by sex and age"},
+ {"code": "WAP_WAPF_SEX_AGE_NB", "freq": ["A"], "description": "Working-age population by sex and age"},
+ ],
+ "wages_earnings": [
+ {"code": "EAR_4HRL_SEX_CUR_NB", "freq": ["A"], "description": "Mean hourly earnings by sex and currency (CUR dim: CUR_TYPE_LCU/USD/EUR/PPP)"},
+ {"code": "EAR_4MTH_SEX_CUR_NB", "freq": ["A"], "description": "Mean monthly earnings by sex and currency"},
+ {"code": "EAR_4MMN_CUR_NB", "freq": ["A"], "description": "Statutory minimum wage (nominal; no sex dimension)"},
+ {"code": "EAR_GGAP_OCU_RT", "freq": ["A"], "description": "Gender wage gap by occupation"},
+ {"code": "EAR_XTLP_SEX_RT", "freq": ["A"], "description": "Low pay incidence by sex"},
+ {"code": "SDG_0851_SEX_OCU_NB", "freq": ["A"], "description": "SDG 8.5.1 average hourly earnings"},
+ ],
+ "currency_codes_cur": {
+ "CUR_TYPE_LCU": "Local currency units",
+ "CUR_TYPE_USD": "US Dollars",
+ "CUR_TYPE_EUR": "Euros",
+ "CUR_TYPE_PPP": "PPP-adjusted international dollars",
+ },
+ "hours_of_work": [
+ {"code": "HOW_TEMP_SEX_ECO_NB", "freq": ["A"], "description": "Mean weekly hours by sex and economic activity"},
+ {"code": "HOW_XEES_SEX_ECO_RT", "freq": ["A"], "description": "Share of employed working > 48h/week"},
+ ],
+ "labour_income_productivity": [
+ {"code": "LAP_2GDP_NOC_RT", "freq": ["A"], "description": "Labour income share (% of GDP, ILO modelled)"},
+ {"code": "LAP_2LID_QTL_RT", "freq": ["A"], "description": "Labour income distribution by decile"},
+ {"code": "LAP_2FTM_NOC_RT", "freq": ["A"], "description": "Gender income gap (women-to-men ratio)"},
+ {"code": "SDG_1041_NOC_RT", "freq": ["A"], "description": "SDG 10.4.1 labour income share"},
+ ],
+ "social_protection_poverty": [
+ {"code": "SDG_0111_SEX_AGE_RT", "freq": ["A"], "description": "SDG 1.1.1 working poverty rate (%)"},
+ {"code": "SDG_0131_SEX_SOC_RT", "freq": ["A"], "description": "SDG 1.3.1 social protection coverage"},
+ ],
+ "sdg_indicators": [
+ {"code": "SDG_0551_NOC_RT", "freq": ["A"], "description": "SDG 5.5.1 women in managerial positions"},
+ {"code": "SDG_0552_NOC_RT", "freq": ["A"], "description": "SDG 5.5.2 women in senior/middle management"},
+ {"code": "SDG_0811_SEX_AGE_RT", "freq": ["A"], "description": "SDG 8.1.1 GDP per employed person growth rate"},
+ {"code": "SDG_0852_SEX_AGE_RT", "freq": ["A", "Q"], "description": "SDG 8.5.2 unemployment rate"},
+ {"code": "SDG_0861_SEX_AGE_NB", "freq": ["A"], "description": "SDG 8.6.1 youth NEET rate"},
+ {"code": "SDG_0871_SEX_AGE_RT", "freq": ["A"], "description": "SDG 8.7.1 child labour rate"},
+ {"code": "SDG_0881_NOC_RT", "freq": ["A"], "description": "SDG 8.8.1 fatal occupational injuries"},
+ {"code": "SDG_0882_NOC_RT", "freq": ["A"], "description": "SDG 8.8.2 non-fatal occupational injuries"},
+ ],
+ "country_groups": {
+ "G7": G7_COUNTRIES,
+ "G20": G20_COUNTRIES,
+ "EU": EU_COUNTRIES,
+ },
+ "dimension_notes": {
+ "key_order": "REF_AREA.FREQ.MEASURE.SEX.CLASSIF1[.CLASSIF2]",
+ "wildcard": "Omit a dimension or use ALL to wildcard all dimensions",
+ "or_operator": "Use + between values, e.g. CAN+USA+GBR",
+ "freq_codes": {"A": "Annual", "Q": "Quarterly", "M": "Monthly"},
+ "sex_codes": {"SEX_T": "Total", "SEX_M": "Male", "SEX_F": "Female"},
+ "common_age_codes": {
+ "AGE_YTHADULT_YGE15": "15 and over",
+ "AGE_YTHADULT_Y15-24": "Youth 15-24",
+ "AGE_YTHADULT_YGE25": "Adults 25+",
+ "_T": "Total (no age breakdown)",
+ },
+ },
+ }
+
+ return {
+ "success": True,
+ "data": indicators,
+ "sector_codes_eco": {
+ "ECO_ISIC4_TOTAL": "Total (all sectors)",
+ "ECO_ISIC4_A": "Agriculture, forestry and fishing",
+ "ECO_ISIC4_B": "Mining and quarrying",
+ "ECO_ISIC4_C": "Manufacturing",
+ "ECO_ISIC4_D": "Electricity, gas, steam supply",
+ "ECO_ISIC4_E": "Water supply, sewerage, waste",
+ "ECO_ISIC4_F": "Construction",
+ "ECO_ISIC4_G": "Wholesale and retail trade",
+ "ECO_ISIC4_H": "Transportation and storage",
+ "ECO_ISIC4_I": "Accommodation and food service",
+ "ECO_ISIC4_J": "Information and communication",
+ "ECO_ISIC4_K": "Financial and insurance activities",
+ "ECO_ISIC4_L": "Real estate activities",
+ "ECO_ISIC4_M": "Professional, scientific and technical",
+ "ECO_ISIC4_N": "Administrative and support services",
+ "ECO_ISIC4_O": "Public administration and defence",
+ "ECO_ISIC4_P": "Education",
+ "ECO_ISIC4_Q": "Human health and social work",
+ "ECO_ISIC4_R": "Arts, entertainment and recreation",
+ "ECO_ISIC4_S": "Other service activities",
+ },
+ "occupation_codes_ocu": {
+ "OCU_ISCO08_TOTAL": "Total all occupations",
+ "OCU_ISCO08_1": "Managers",
+ "OCU_ISCO08_2": "Professionals",
+ "OCU_ISCO08_3": "Technicians and associate professionals",
+ "OCU_ISCO08_4": "Clerical support workers",
+ "OCU_ISCO08_5": "Service and sales workers",
+ "OCU_ISCO08_6": "Skilled agricultural workers",
+ "OCU_ISCO08_7": "Craft and related trades workers",
+ "OCU_ISCO08_8": "Plant and machine operators",
+ "OCU_ISCO08_9": "Elementary occupations",
+ "OCU_ISCO08_0": "Armed forces occupations",
+ },
+ "status_codes_ste": {
+ "STE_ICSE93_TOTAL": "Total",
+ "STE_ICSE93_1": "Employees",
+ "STE_ICSE93_2": "Employers",
+ "STE_ICSE93_3": "Own-account workers",
+ "STE_ICSE93_4": "Members of producers cooperatives",
+ "STE_ICSE93_5": "Contributing family workers",
+ "STE_ICSE93_6": "Workers not classifiable by status",
+ },
+ "api_info": {
+ "sdmx_base_url": SDMX_BASE_URL,
+ "toc_url": TOC_BY_INDICATOR_URL,
+ "toc_ref_area_url": TOC_BY_REF_AREA_URL,
+ "authentication": "None required — open data",
+ "rate_limits": "HTTP 413 returned when result set exceeds ~300,000 records; narrow the key",
+ "formats": ["csv (text/csv Accept header)", "jsondata", "genericdata (XML)"],
+ "user_guide": "https://webapps.ilo.org/ilostat-files/Documents/SDMX_User_Guide.pdf",
+ "sdmx_user_guide_notice": "April 2024: base URL migrated from www.ilo.org/sdmx/rest to sdmx.ilo.org/rest",
+ },
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI entry point (invoked by Tauri Rust bridge)
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ # Short aliases (preferred)
+ "unemployment": "[countries] [frequency] [sex] [age_group] [start] [end]",
+ "employment": "[countries] [frequency] [sex] [age_group] [start] [end]",
+ "emp_to_pop": "[countries] [frequency] [sex] [age_group] [start] [end]",
+ "lfpr": "[countries] [frequency] [sex] [age_group] [start] [end]",
+ "wages": "[countries] [frequency] [wage_type] [sex] [currency] [start] [end]",
+ "gender_wage_gap": "[countries] [frequency] [occupation] [start] [end]",
+ "hours_of_work": "[countries] [frequency] [sex] [economic_act] [start] [end]",
+ "labour_income_share": "[countries] [frequency] [start] [end]",
+ "working_poverty": "[countries] [frequency] [sex] [age_group] [start] [end]",
+ "emp_by_sector": "[countries] [frequency] [sex] [sector] [start] [end]",
+ "emp_by_occupation": "[countries] [frequency] [sex] [occupation] [start] [end]",
+ "emp_by_status": "[countries] [frequency] [sex] [status] [start] [end]",
+ "informal_employment": "[countries] [frequency] [sex] [start] [end]",
+ "social_protection": "[countries] [frequency] [sex] [start] [end]",
+ "country_profile": "<country> [start] [end]",
+ "sdg_indicator": "<sdg_code> [countries] [frequency] [start] [end]",
+ "bulk_data": "<indicator_id> [ref_area] [start] [end] [max_rows]",
+ "search": "<query> [language]",
+ "dataflows": "(topic_prefix?)",
+ "codelist": "<codelist_id> [agency]",
+ "toc": "[segment] [language] [search]",
+ "data": "<indicator_code> [key] [start] [end] [detail]",
+ "countries": "(no args)",
+ "available": "(no args)",
+ # Verbose aliases (also supported)
+ "list_dataflows": "(topic_prefix?)",
+ "get_codelist": "<codelist_id> [agency]",
+ "get_table_of_contents": "[segment] [language] [search]",
+ "get_data": "<indicator_code> [key] [start] [end] [detail]",
+ "get_unemployment": "[countries] [frequency] [sex] [age_group] [start] [end]",
+ "get_employment": "[countries] [frequency] [sex] [age_group] [start] [end]",
+ "get_employment_to_population": "[countries] [frequency] [sex] [age_group] [start] [end]",
+ "get_labour_force_participation": "[countries] [frequency] [sex] [age_group] [start] [end]",
+ "get_wages": "[countries] [frequency] [wage_type] [sex] [currency] [start] [end]",
+ "get_gender_wage_gap": "[countries] [frequency] [occupation] [start] [end]",
+ "get_hours_of_work": "[countries] [frequency] [sex] [economic_act] [start] [end]",
+ "get_labour_income_share": "[countries] [frequency] [start] [end]",
+ "get_working_poverty": "[countries] [frequency] [sex] [age_group] [start] [end]",
+ "get_employment_by_sector": "[countries] [frequency] [sex] [sector] [start] [end]",
+ "get_employment_by_occupation": "[countries] [frequency] [sex] [occupation] [start] [end]",
+ "get_employment_by_status": "[countries] [frequency] [sex] [status] [start] [end]",
+ "get_informal_employment": "[countries] [frequency] [sex] [start] [end]",
+ "get_social_protection": "[countries] [frequency] [sex] [start] [end]",
+ "get_country_profile": "<country> [start] [end]",
+ "get_sdg_indicator": "<sdg_code> [countries] [frequency] [start] [end]",
+ "get_bulk_data": "<indicator_id> [ref_area] [start] [end] [max_rows]",
+ "search_indicators": "<query> [language]",
+ "list_countries": "(no args)",
+ "list_sex_codes": "(no args)",
+ "list_age_codes": "(no args)",
+ "list_economic_activity_codes": "(no args)",
+ "list_occupation_codes": "(no args)",
+ "available_indicators": "(no args)",
+}
+
+
+def _arg(args: List[str], index: int, default: Any = None) -> Any:
+ """Safe list index access with default."""
+ try:
+ val = args[index]
+ return val if val else default
+ except IndexError:
+ return default
+
+
+def main(args: Optional[List[str]] = None) -> None:
+ if args is None:
+ args = sys.argv[1:]
+
+ if not args:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python ilostat_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ command = args[0]
+ rest = args[1:]
+ wrapper = ILOStatWrapper()
+
+ # Normalize short aliases to canonical names
+ _ALIASES = {
+ "unemployment": "get_unemployment",
+ "employment": "get_employment",
+ "emp_to_pop": "get_employment_to_population",
+ "lfpr": "get_labour_force_participation",
+ "wages": "get_wages",
+ "gender_wage_gap": "get_gender_wage_gap",
+ "hours_of_work": "get_hours_of_work",
+ "labour_income_share": "get_labour_income_share",
+ "working_poverty": "get_working_poverty",
+ "emp_by_sector": "get_employment_by_sector",
+ "emp_by_occupation": "get_employment_by_occupation",
+ "emp_by_status": "get_employment_by_status",
+ "informal_employment": "get_informal_employment",
+ "social_protection": "get_social_protection",
+ "country_profile": "get_country_profile",
+ "sdg_indicator": "get_sdg_indicator",
+ "bulk_data": "get_bulk_data",
+ "search": "search_indicators",
+ "dataflows": "list_dataflows",
+ "codelist": "get_codelist",
+ "toc": "get_table_of_contents",
+ "data": "get_data",
+ "countries": "list_countries",
+ "available": "available_indicators",
+ }
+ command = _ALIASES.get(command, command)
+
+ try:
+ if command == "list_dataflows":
+ result = wrapper.list_dataflows(topic_prefix=_arg(rest, 0))
+
+ elif command == "get_codelist":
+ if not rest:
+ result = {"error": "get_codelist requires <codelist_id>"}
+ else:
+ result = wrapper.get_codelist(
+ codelist_id = rest[0],
+ agency = _arg(rest, 1, "ILO"),
+ )
+
+ elif command == "get_table_of_contents":
+ result = wrapper.get_table_of_contents(
+ segment = _arg(rest, 0, "indicator"),
+ language = _arg(rest, 1, "en"),
+ search = _arg(rest, 2),
+ )
+
+ elif command == "get_data":
+ if not rest:
+ result = {"error": "get_data requires <indicator_code>"}
+ else:
+ result = wrapper.get_data(
+ indicator_code = rest[0],
+ key = _arg(rest, 1, "ALL"),
+ start_period = _arg(rest, 2),
+ end_period = _arg(rest, 3),
+ detail = _arg(rest, 4, "dataonly"),
+ )
+
+ elif command == "get_unemployment":
+ result = wrapper.get_unemployment(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ sex = _arg(rest, 2, "SEX_T"),
+ age_group = _arg(rest, 3, "AGE_YTHADULT_YGE15"),
+ start_period = _arg(rest, 4),
+ end_period = _arg(rest, 5),
+ )
+
+ elif command == "get_employment":
+ result = wrapper.get_employment(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ sex = _arg(rest, 2, "SEX_T"),
+ age_group = _arg(rest, 3, "_T"),
+ start_period = _arg(rest, 4),
+ end_period = _arg(rest, 5),
+ )
+
+ elif command == "get_employment_to_population":
+ result = wrapper.get_employment_to_population_ratio(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ sex = _arg(rest, 2, "SEX_T"),
+ age_group = _arg(rest, 3, "AGE_YTHADULT_YGE15"),
+ start_period = _arg(rest, 4),
+ end_period = _arg(rest, 5),
+ )
+
+ elif command == "get_labour_force_participation":
+ result = wrapper.get_labour_force_participation(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ sex = _arg(rest, 2, "SEX_T"),
+ age_group = _arg(rest, 3, "AGE_YTHADULT_YGE15"),
+ start_period = _arg(rest, 4),
+ end_period = _arg(rest, 5),
+ )
+
+ elif command == "get_wages":
+ result = wrapper.get_wages(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ wage_type = _arg(rest, 2, "monthly"),
+ sex = _arg(rest, 3, "SEX_T"),
+ currency = _arg(rest, 4, "CUR_TYPE_LCU"),
+ start_period = _arg(rest, 5),
+ end_period = _arg(rest, 6),
+ )
+
+ elif command == "get_gender_wage_gap":
+ result = wrapper.get_gender_wage_gap(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ occupation = _arg(rest, 2, "OCU_ISCO08_TOTAL"),
+ start_period = _arg(rest, 3),
+ end_period = _arg(rest, 4),
+ )
+
+ elif command == "get_hours_of_work":
+ result = wrapper.get_hours_of_work(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ sex = _arg(rest, 2, "SEX_T"),
+ economic_act = _arg(rest, 3, "ECO_ISIC4_TOTAL"),
+ start_period = _arg(rest, 4),
+ end_period = _arg(rest, 5),
+ )
+
+ elif command == "get_labour_income_share":
+ result = wrapper.get_labour_income_share(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ start_period = _arg(rest, 2),
+ end_period = _arg(rest, 3),
+ )
+
+ elif command == "get_working_poverty":
+ result = wrapper.get_working_poverty(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ sex = _arg(rest, 2, "SEX_T"),
+ age_group = _arg(rest, 3, "AGE_YTHADULT_YGE15"),
+ start_period = _arg(rest, 4),
+ end_period = _arg(rest, 5),
+ )
+
+ elif command == "get_employment_by_sector":
+ result = wrapper.get_employment_by_sector(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ sex = _arg(rest, 2, "SEX_T"),
+ sector = _arg(rest, 3, "_T"),
+ start_period = _arg(rest, 4),
+ end_period = _arg(rest, 5),
+ )
+
+ elif command == "get_employment_by_occupation":
+ result = wrapper.get_employment_by_occupation(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ sex = _arg(rest, 2, "SEX_T"),
+ occupation = _arg(rest, 3, "_T"),
+ start_period = _arg(rest, 4),
+ end_period = _arg(rest, 5),
+ )
+
+ elif command == "get_employment_by_status":
+ result = wrapper.get_employment_by_status(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ sex = _arg(rest, 2, "SEX_T"),
+ status = _arg(rest, 3, "_T"),
+ start_period = _arg(rest, 4),
+ end_period = _arg(rest, 5),
+ )
+
+ elif command == "get_informal_employment":
+ result = wrapper.get_informal_employment(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ sex = _arg(rest, 2, "SEX_T"),
+ start_period = _arg(rest, 3),
+ end_period = _arg(rest, 4),
+ )
+
+ elif command == "get_social_protection":
+ result = wrapper.get_social_protection_coverage(
+ countries = _arg(rest, 0, "ALL"),
+ frequency = _arg(rest, 1, FREQ_ANNUAL),
+ sex = _arg(rest, 2, "SEX_T"),
+ start_period = _arg(rest, 3),
+ end_period = _arg(rest, 4),
+ )
+
+ elif command == "get_country_profile":
+ if not rest:
+ result = {"error": "get_country_profile requires <country>"}
+ else:
+ result = wrapper.get_country_profile(
+ country = rest[0],
+ start_period = _arg(rest, 1),
+ end_period = _arg(rest, 2),
+ )
+
+ elif command == "get_sdg_indicator":
+ if not rest:
+ result = {"error": "get_sdg_indicator requires <sdg_code>"}
+ else:
+ result = wrapper.get_sdg_indicator(
+ sdg_code = rest[0],
+ countries = _arg(rest, 1, "ALL"),
+ frequency = _arg(rest, 2, FREQ_ANNUAL),
+ start_period = _arg(rest, 3),
+ end_period = _arg(rest, 4),
+ )
+
+ elif command == "get_bulk_data":
+ if not rest:
+ result = {"error": "get_bulk_data requires <indicator_id>"}
+ else:
+ max_rows = _arg(rest, 4)
+ result = wrapper.get_bulk_data(
+ indicator_id = rest[0],
+ ref_area = _arg(rest, 1),
+ start_period = _arg(rest, 2),
+ end_period = _arg(rest, 3),
+ max_rows = int(max_rows) if max_rows else None,
+ )
+
+ elif command == "search_indicators":
+ if not rest:
+ result = {"error": "search_indicators requires <query>"}
+ else:
+ result = wrapper.search_indicators(
+ query = rest[0],
+ language = _arg(rest, 1, "en"),
+ )
+
+ elif command == "list_countries":
+ result = wrapper.list_countries()
+
+ elif command == "list_sex_codes":
+ result = wrapper.list_sex_codes()
+
+ elif command == "list_age_codes":
+ result = wrapper.list_age_codes()
+
+ elif command == "list_economic_activity_codes":
+ result = wrapper.list_economic_activity_codes()
+
+ elif command == "list_occupation_codes":
+ result = wrapper.list_occupation_codes()
+
+ elif command == "available_indicators":
+ result = wrapper.get_available_indicators_summary()
+
+ else:
+ result = {
+ "error": f"Unknown command: {command}",
+ "commands": COMMANDS,
+ }
+
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+
+ except Exception as exc:
+ print(json.dumps({
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/mnb_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/mnb_data.py
new file mode 100644
index 000000000..bc1bc190e
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/mnb_data.py
@@ -0,0 +1,358 @@
+"""
+Magyar Nemzeti Bank (MNB) — National Bank of Hungary Data Wrapper
+Fetches exchange rate data from the MNB SOAP web service.
+
+API Reference:
+ Endpoint: http://www.mnb.hu/arfolyamok.asmx
+ Protocol: SOAP 1.1
+ Format: XML (UTF-8) — inner result is HTML-entity-encoded XML
+ Auth: None required — fully public
+ WSDL: http://www.mnb.hu/arfolyamok.asmx?WSDL
+
+SOAP Operations:
+ GetCurrentExchangeRates()
+ → Today's rates for all currencies
+
+ GetExchangeRates(startDate, endDate, currencyNames)
+ → Date-range rates for selected currencies (comma-separated codes)
+
+ GetCurrencies()
+ → List of available currency codes
+
+Exchange rates expressed as HUF per foreign currency unit.
+Comma is used as decimal separator in the raw XML (e.g. "379,08000").
+Some currencies use a multiplier (unit): JPY=100, KRW=100, IDR=100.
+The wrapper normalises all to HUF per 1 unit.
+
+Published currencies (31):
+ AUD, BRL, CAD, CHF, CNY, CZK, DKK, EUR, GBP, HKD, IDR (×100),
+ ILS, INR, ISK, JPY (×100), KRW (×100), MXN, MYR, NOK, NZD, PHP,
+ PLN, RON, RSD, RUB, SEK, SGD, THB, TRY, UAH, USD, ZAR
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import html
+import json
+import requests
+import traceback
+import xml.etree.ElementTree as ET
+from typing import Dict, Any, List, Optional
+from datetime import datetime, date, timedelta, timezone
+
+
+SOAP_URL = "http://www.mnb.hu/arfolyamok.asmx"
+SOAP_NS = "http://www.mnb.hu/webservices/"
+DEFAULT_TIMEOUT = 30
+
+MAJOR_CURRENCIES = ["USD", "EUR", "GBP", "JPY", "CHF", "CAD", "AUD",
+ "SEK", "NOK", "DKK", "CNY", "PLN", "CZK", "RON"]
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class MNBError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "MNBError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class MNBWrapper:
+ """
+ Wrapper for the Magyar Nemzeti Bank (MNB) SOAP exchange rate service.
+
+ Rates are HUF (Hungarian Forint) per 1 unit of foreign currency.
+ JPY, KRW, IDR are quoted per 100 units; the wrapper normalises them.
+ Data is published on Hungarian business days (Mon–Fri).
+ """
+
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Content-Type": "text/xml; charset=utf-8",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal SOAP helpers
+ # ------------------------------------------------------------------
+
+ def _soap_call(self, operation: str, body_inner: str) -> str:
+ """
+ Execute a SOAP 1.1 request and return the inner result XML string.
+ The MNB service wraps its XML result in HTML-entity encoding.
+ """
+ soap_action = f"{SOAP_NS}MNBArfolyamServiceSoap/{operation}"
+ envelope = (
+ '<?xml version="1.0" encoding="utf-8"?>'
+ '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
+ f'<soap:Body><{operation} xmlns="{SOAP_NS}">'
+ f'{body_inner}'
+ f'</{operation}></soap:Body></soap:Envelope>'
+ )
+ resp = self.session.post(
+ SOAP_URL,
+ data=envelope.encode("utf-8"),
+ headers={"SOAPAction": soap_action},
+ timeout=DEFAULT_TIMEOUT,
+ )
+ resp.raise_for_status()
+
+ root = ET.fromstring(resp.content)
+ result_tag = f"{{{SOAP_NS}}}{operation}Result"
+ result_el = root.find(f".//{result_tag}")
+ if result_el is None or result_el.text is None:
+ raise ValueError(f"Empty SOAP result for {operation}")
+ return html.unescape(result_el.text)
+
+ def _parse_rate_value(self, text: str, unit: int) -> Optional[float]:
+ """Convert MNB rate string ('379,08000') to float, normalised by unit."""
+ if not text or text.strip() in ("", "N/A"):
+ return None
+ try:
+ return round(float(text.strip().replace(",", ".")), 6) / unit
+ except ValueError:
+ return None
+
+ def _parse_rates_xml(self, xml_str: str) -> List[Dict[str, Any]]:
+ """
+ Parse MNBExchangeRates or MNBCurrentExchangeRates XML into
+ wide-format rows: [{date, USD: rate, EUR: rate, ...}, ...]
+ """
+ root = ET.fromstring(xml_str)
+ rows: List[Dict[str, Any]] = []
+ for day_el in root.findall("Day"):
+ d = day_el.get("date", "")
+ row: Dict[str, Any] = {"date": d}
+ for rate_el in day_el.findall("Rate"):
+ code = rate_el.get("curr", "")
+ unit = int(rate_el.get("unit", "1") or "1")
+ val = self._parse_rate_value(rate_el.text or "", unit)
+ if code and val is not None:
+ row[code] = val
+ rows.append(row)
+ return sorted(rows, key=lambda r: r["date"])
+
+ # ------------------------------------------------------------------
+ # Public methods
+ # ------------------------------------------------------------------
+
+ def get_today(self) -> Dict[str, Any]:
+ """Current exchange rates for all available currencies."""
+ try:
+ xml_str = self._soap_call("GetCurrentExchangeRates", "")
+ rows = self._parse_rates_xml(xml_str)
+ latest = rows[-1] if rows else {}
+ return {
+ "success": True,
+ "date": latest.get("date", ""),
+ "data": {k: v for k, v in latest.items() if k != "date"},
+ "note": "HUF per 1 unit of foreign currency (JPY/KRW/IDR normalised from per-100)",
+ "source": "Magyar Nemzeti Bank",
+ "url": SOAP_URL,
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return MNBError("GetCurrentExchangeRates", str(e), sc).to_dict()
+ except Exception as e:
+ return MNBError("GetCurrentExchangeRates", str(e)).to_dict()
+
+ def get_range(self, start_date: str, end_date: Optional[str] = None,
+ currencies: Optional[List[str]] = None) -> Dict[str, Any]:
+ """
+ Exchange rates for a date range and selected currencies.
+ If currencies is None, fetches all available currencies.
+ """
+ if end_date is None:
+ end_date = date.today().isoformat()
+ if currencies is None:
+ # MNB requires explicit list; use known full set
+ currencies = [
+ "AUD", "BRL", "CAD", "CHF", "CNY", "CZK", "DKK", "EUR",
+ "GBP", "HKD", "IDR", "ILS", "INR", "ISK", "JPY", "KRW",
+ "MXN", "MYR", "NOK", "NZD", "PHP", "PLN", "RON", "RSD",
+ "RUB", "SEK", "SGD", "THB", "TRY", "UAH", "USD", "ZAR",
+ ]
+ ccy_str = ",".join(currencies)
+ body = (
+ f"<startDate>{start_date}</startDate>"
+ f"<endDate>{end_date}</endDate>"
+ f"<currencyNames>{ccy_str}</currencyNames>"
+ )
+ try:
+ xml_str = self._soap_call("GetExchangeRates", body)
+ rows = self._parse_rates_xml(xml_str)
+ return {
+ "success": True,
+ "start_date": start_date,
+ "end_date": end_date,
+ "currencies": currencies,
+ "data": rows,
+ "count": len(rows),
+ "note": "HUF per 1 unit of foreign currency",
+ "source": "Magyar Nemzeti Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return MNBError("GetExchangeRates", str(e), sc).to_dict()
+ except Exception as e:
+ return MNBError("GetExchangeRates", str(e)).to_dict()
+
+ def get_currency(self, currency: str,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Historical rates for a single currency vs HUF."""
+ if start_date is None:
+ start_date = (date.today() - timedelta(days=90)).isoformat()
+ result = self.get_range(start_date, end_date, [currency.upper()])
+ if result.get("success"):
+ result["currency"] = currency.upper()
+ result["note"] = f"HUF per 1 {currency.upper()}"
+ return result
+
+ def get_usd_huf(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """USD/HUF exchange rate history."""
+ return self.get_currency("USD", start_date, end_date)
+
+ def get_eur_huf(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """EUR/HUF exchange rate history."""
+ return self.get_currency("EUR", start_date, end_date)
+
+ def get_major_currencies(self, start_date: Optional[str] = None) -> Dict[str, Any]:
+ """Major currencies vs HUF — last 30 days if no start given."""
+ if start_date is None:
+ start_date = (date.today() - timedelta(days=30)).isoformat()
+ return self.get_range(start_date, currencies=MAJOR_CURRENCIES)
+
+ def get_available_currencies(self) -> Dict[str, Any]:
+ """List all currency codes available from MNB."""
+ try:
+ xml_str = self._soap_call("GetCurrencies", "")
+ root = ET.fromstring(xml_str)
+ codes = [c.text.strip() for c in root.findall("Curr") if c.text]
+ return {
+ "success": True,
+ "currencies": codes,
+ "count": len(codes),
+ "source": "Magyar Nemzeti Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return MNBError("GetCurrencies", str(e), sc).to_dict()
+ except Exception as e:
+ return MNBError("GetCurrencies", str(e)).to_dict()
+
+ def get_overview(self) -> Dict[str, Any]:
+ """Snapshot: today's major currency rates vs HUF."""
+ today = self.get_today()
+ if not today.get("success"):
+ return today
+ all_rates = today.get("data", {})
+ snapshot = {c: all_rates[c] for c in MAJOR_CURRENCIES if c in all_rates}
+ return {
+ "success": True,
+ "date": today.get("date"),
+ "data": snapshot,
+ "all_rates": all_rates,
+ "note": "HUF per 1 unit of foreign currency",
+ "source": "Magyar Nemzeti Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "today": " — Today's rates (all currencies)",
+ "range": "<start> [end] [currencies] — Date range (comma-separated currencies)",
+ "currency": "<CCY> [start] [end] — Single currency vs HUF history",
+ "usd": "[start] [end] — USD/HUF history",
+ "eur": "[start] [end] — EUR/HUF history",
+ "major": "[start] — Major currencies last 30 days",
+ "overview": " — Today's major currency snapshot",
+ "available":" — List available currencies from MNB",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python mnb_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = MNBWrapper()
+
+ try:
+ if cmd == "today":
+ result = wrapper.get_today()
+ elif cmd == "range":
+ if len(sys.argv) < 3:
+ result = {"error": "range requires <start_date>"}
+ else:
+ ccys = [c.strip().upper() for c in _a(4, "").split(",")] if _a(4) else None
+ result = wrapper.get_range(sys.argv[2], _a(3), ccys)
+ elif cmd == "currency":
+ if len(sys.argv) < 3:
+ result = {"error": "currency requires <CCY>"}
+ else:
+ result = wrapper.get_currency(sys.argv[2], _a(3), _a(4))
+ elif cmd == "usd":
+ result = wrapper.get_usd_huf(_a(2), _a(3))
+ elif cmd == "eur":
+ result = wrapper.get_eur_huf(_a(2), _a(3))
+ elif cmd == "major":
+ result = wrapper.get_major_currencies(_a(2))
+ elif cmd == "overview":
+ result = wrapper.get_overview()
+ elif cmd in ("available", "currencies"):
+ result = wrapper.get_available_currencies()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=True))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/nbp_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/nbp_data.py
new file mode 100644
index 000000000..a896c77b3
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/nbp_data.py
@@ -0,0 +1,412 @@
+"""
+National Bank of Poland (NBP) Data Wrapper
+Fetches data from the NBP Public Web API.
+
+API Reference:
+ Base URL: https://api.nbp.pl/api
+ Format: JSON
+ Auth: None required — fully public
+ Docs: https://api.nbp.pl/
+
+Exchange rate tables:
+ Table A — 32 currencies, daily fixing (Mon–Fri)
+ Table B — ~120 exotic currencies, weekly
+ Table C — bid/ask rates for 8 major currencies (Forex)
+
+Endpoints:
+ GET /exchangerates/tables/{table}/ — latest table
+ GET /exchangerates/tables/{table}/{date}/ — single date
+ GET /exchangerates/tables/{table}/{from}/{to}/ — date range
+ GET /exchangerates/rates/{table}/{code}/ — single currency history
+ GET /exchangerates/rates/{table}/{code}/{date}/
+ GET /exchangerates/rates/{table}/{code}/{from}/{to}/
+ GET /exchangerates/rates/{table}/{code}/last/{n}/
+
+All endpoints accept ?format=json
+
+NBP interest rates are published at:
+ https://api.nbp.pl/api/rates/reference/ (no REST; scraped from HTML)
+ We use the NBP SDMX data alternatively.
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime, date, timedelta, timezone
+
+
+BASE_URL = "https://api.nbp.pl/api"
+DEFAULT_TIMEOUT = 30
+
+# Currency codes available in Table A (32 major currencies)
+TABLE_A_CODES = [
+ "THB", "USD", "AUD", "HKD", "CAD", "NZD", "SGD", "EUR", "HUF", "CHF",
+ "GBP", "UAH", "JPY", "CZK", "DKK", "ISK", "NOK", "SEK", "RON", "BGN",
+ "TRY", "ILS", "CLP", "PHP", "MXN", "ZAR", "BRL", "MYR", "IDR", "INR",
+ "KRW", "CNY",
+]
+
+# Key currency groups
+MAJOR_CURRENCIES = ["USD", "EUR", "GBP", "JPY", "CHF", "CAD", "AUD", "NOK", "SEK", "DKK"]
+EM_CURRENCIES = ["CNY", "INR", "BRL", "KRW", "TRY", "MXN", "ZAR", "IDR", "MYR", "PHP"]
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class NBPError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "NBPError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class NBPWrapper:
+ """
+ Wrapper for the National Bank of Poland (NBP) Public Web API.
+
+ Exchange rates published Mon–Fri (Table A/C) or weekly (Table B).
+ All data is in JSON format, no authentication required.
+ Rates are expressed as PLN per foreign currency unit.
+ """
+
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Accept": "application/json",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _get(self, path: str, params: Optional[Dict] = None) -> Any:
+ url = f"{BASE_URL}/{path.lstrip('/')}"
+ resp = self.session.get(url, params={"format": "json", **(params or {})},
+ timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.json()
+
+ def _safe(self, path: str, label: str,
+ extra_fields: Optional[Dict] = None) -> Dict[str, Any]:
+ try:
+ data = self._get(path)
+ result = {
+ "success": True,
+ "data": data,
+ "source": "National Bank of Poland",
+ "url": f"{BASE_URL}/{path}",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ if extra_fields:
+ result.update(extra_fields)
+ return result
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return NBPError(label, str(e), sc).to_dict()
+ except Exception as e:
+ return NBPError(label, str(e)).to_dict()
+
+ def _flatten_table(self, raw: Any) -> Dict[str, Any]:
+ """Flatten NBP table response to list of {date, code: rate} rows."""
+ if isinstance(raw, dict):
+ raw = [raw]
+ # raw = [{table, no, effectiveDate, rates: [{currency, code, mid}]}]
+ rows = []
+ for entry in raw:
+ d = entry.get("effectiveDate") or entry.get("tradingDate", "")
+ row: Dict[str, Any] = {"date": d}
+ for r in entry.get("rates", []):
+ code = r.get("code", "")
+ mid = r.get("mid")
+ bid = r.get("bid")
+ ask = r.get("ask")
+ if code:
+ if mid is not None:
+ row[code] = mid
+ elif bid is not None and ask is not None:
+ row[f"{code}_bid"] = bid
+ row[f"{code}_ask"] = ask
+ rows.append(row)
+ return rows
+
+ def _flatten_rates(self, raw: Any) -> Dict[str, Any]:
+ """Flatten single-currency rate series to list of {date, mid/bid/ask} rows."""
+ if isinstance(raw, dict):
+ raw_rates = raw.get("rates", [])
+ code = raw.get("code", "")
+ else:
+ raw_rates = []
+ code = ""
+ rows = []
+ for r in raw_rates:
+ d = r.get("effectiveDate", r.get("tradingDate", ""))
+ row = {"date": d}
+ if "mid" in r:
+ row["mid"] = r["mid"]
+ if "bid" in r and "ask" in r:
+ row["bid"] = r["bid"]
+ row["ask"] = r["ask"]
+ rows.append(row)
+ return rows, code
+
+ # ------------------------------------------------------------------
+ # Public methods
+ # ------------------------------------------------------------------
+
+ def get_exchange_rates_today(self, table: str = "A") -> Dict[str, Any]:
+ """Latest exchange rate table (A=mid, B=exotic, C=bid/ask)."""
+ try:
+ raw = self._get(f"exchangerates/tables/{table}/")
+ rows = self._flatten_table(raw)
+ return {
+ "success": True,
+ "table": table,
+ "data": rows,
+ "count": len(rows),
+ "source": "National Bank of Poland",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return NBPError(f"tables/{table}", str(e), sc).to_dict()
+ except Exception as e:
+ return NBPError(f"tables/{table}", str(e)).to_dict()
+
+ def get_exchange_rates_range(self, start_date: str, end_date: str,
+ table: str = "A") -> Dict[str, Any]:
+ """Exchange rate table for a date range (max ~93 days per request)."""
+ try:
+ raw = self._get(f"exchangerates/tables/{table}/{start_date}/{end_date}/")
+ rows = self._flatten_table(raw)
+ return {
+ "success": True,
+ "table": table,
+ "start_date": start_date,
+ "end_date": end_date,
+ "data": rows,
+ "count": len(rows),
+ "source": "National Bank of Poland",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return NBPError(f"tables/{table}/{start_date}/{end_date}", str(e), sc).to_dict()
+ except Exception as e:
+ return NBPError(f"tables/{table}/{start_date}/{end_date}", str(e)).to_dict()
+
+ def get_currency_rate(self, code: str, start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ last_n: Optional[int] = None,
+ table: str = "A") -> Dict[str, Any]:
+ """Historical rates for a single currency vs PLN."""
+ try:
+ if last_n:
+ path = f"exchangerates/rates/{table}/{code}/last/{last_n}/"
+ elif start_date and end_date:
+ path = f"exchangerates/rates/{table}/{code}/{start_date}/{end_date}/"
+ elif start_date:
+ # single date
+ path = f"exchangerates/rates/{table}/{code}/{start_date}/"
+ else:
+ path = f"exchangerates/rates/{table}/{code}/"
+ raw = self._get(path)
+ rows, c = self._flatten_rates(raw)
+ return {
+ "success": True,
+ "currency": raw.get("currency", "") if isinstance(raw, dict) else "",
+ "code": code.upper(),
+ "table": table,
+ "data": rows,
+ "count": len(rows),
+ "note": "Rates expressed as PLN per 1 unit of foreign currency",
+ "source": "National Bank of Poland",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return NBPError(f"rates/{table}/{code}", str(e), sc).to_dict()
+ except Exception as e:
+ return NBPError(f"rates/{table}/{code}", str(e)).to_dict()
+
+ def get_usd_pln(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ last_n: int = 30) -> Dict[str, Any]:
+ """USD/PLN exchange rate history."""
+ return self.get_currency_rate("USD", start_date, end_date, last_n if not start_date else None)
+
+ def get_eur_pln(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ last_n: int = 30) -> Dict[str, Any]:
+ """EUR/PLN exchange rate history."""
+ return self.get_currency_rate("EUR", start_date, end_date, last_n if not start_date else None)
+
+ def get_major_currencies(self, last_n: int = 30) -> Dict[str, Any]:
+ """Last N observations for major currencies vs PLN."""
+ try:
+ end = date.today().isoformat()
+ start = (date.today() - timedelta(days=last_n * 2)).isoformat() # buffer for weekends
+ raw = self._get(f"exchangerates/tables/A/{start}/{end}/")
+ rows = self._flatten_table(raw)
+ # Filter to major currencies only
+ filtered = []
+ for row in rows:
+ entry = {"date": row["date"]}
+ for c in MAJOR_CURRENCIES:
+ if c in row:
+ entry[c] = row[c]
+ filtered.append(entry)
+ return {
+ "success": True,
+ "currencies": MAJOR_CURRENCIES,
+ "data": filtered[-last_n:],
+ "count": len(filtered),
+ "note": "PLN per 1 unit of foreign currency",
+ "source": "National Bank of Poland",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return NBPError("major_currencies", str(e), sc).to_dict()
+ except Exception as e:
+ return NBPError("major_currencies", str(e)).to_dict()
+
+ def get_bid_ask(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Table C — bid/ask rates for major currencies (forex)."""
+ if start_date and end_date:
+ return self.get_exchange_rates_range(start_date, end_date, "C")
+ return self.get_exchange_rates_today("C")
+
+ def get_overview(self) -> Dict[str, Any]:
+ """Latest rates snapshot — today's Table A + C."""
+ results: Dict[str, Any] = {}
+ for name, call in [
+ ("table_a_today", lambda: self.get_exchange_rates_today("A")),
+ ("table_c_today", lambda: self.get_exchange_rates_today("C")),
+ ]:
+ r = call()
+ latest = r.get("data", [{}])[-1] if r.get("data") else None
+ results[name] = {"success": r.get("success"), "count": r.get("count"), "latest": latest}
+ return {
+ "success": True,
+ "data": results,
+ "source": "National Bank of Poland",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_all_currencies(self) -> Dict[str, Any]:
+ """All currencies available in Table A + B."""
+ return {
+ "success": True,
+ "table_a_codes": TABLE_A_CODES,
+ "major_currencies": MAJOR_CURRENCIES,
+ "em_currencies": EM_CURRENCIES,
+ "tables": {
+ "A": "32 major currencies, daily mid rate (Mon-Fri)",
+ "B": "~120 exotic currencies, weekly mid rate",
+ "C": "8 major currencies, daily bid/ask (Mon-Fri)",
+ },
+ "note": "Rates expressed as PLN per foreign currency unit",
+ "source": "National Bank of Poland",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "today": "[table=A] — Latest exchange rate table",
+ "range": "<start YYYY-MM-DD> <end> [table=A] — Table for date range",
+ "currency": "<code> [start] [end] [last_n] [table=A] — Single currency history",
+ "usd": "[start] [end] — USD/PLN history",
+ "eur": "[start] [end] — EUR/PLN history",
+ "major": "[last_n=30] — Major currencies vs PLN",
+ "bid_ask": "[start] [end] — Table C bid/ask rates",
+ "overview": " — Today's Table A + C snapshot",
+ "available": " — List available currencies",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python nbp_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = NBPWrapper()
+
+ try:
+ if cmd == "today":
+ result = wrapper.get_exchange_rates_today(_a(2, "A"))
+ elif cmd == "range":
+ if len(sys.argv) < 4:
+ result = {"error": "range requires <start> <end>"}
+ else:
+ result = wrapper.get_exchange_rates_range(sys.argv[2], sys.argv[3], _a(4, "A"))
+ elif cmd == "currency":
+ if len(sys.argv) < 3:
+ result = {"error": "currency requires <code>"}
+ else:
+ ln = int(_a(5)) if _a(5) else None
+ result = wrapper.get_currency_rate(sys.argv[2], _a(3), _a(4), ln, _a(6, "A"))
+ elif cmd == "usd":
+ result = wrapper.get_usd_pln(_a(2), _a(3))
+ elif cmd == "eur":
+ result = wrapper.get_eur_pln(_a(2), _a(3))
+ elif cmd == "major":
+ n = int(_a(2, 30))
+ result = wrapper.get_major_currencies(n)
+ elif cmd == "bid_ask":
+ result = wrapper.get_bid_ask(_a(2), _a(3))
+ elif cmd == "overview":
+ result = wrapper.get_overview()
+ elif cmd in ("available", "currencies"):
+ result = wrapper.get_all_currencies()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=True))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/norges_bank_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/norges_bank_data.py
new file mode 100644
index 000000000..611f2f4f4
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/norges_bank_data.py
@@ -0,0 +1,400 @@
+"""
+Norges Bank (Bank of Norway) Data Wrapper
+Fetches data from the Norges Bank open data SDMX API.
+
+API Reference:
+ Base URL: https://data.norges-bank.no/api
+ Format: Semicolon-delimited CSV (SDMX)
+ Auth: None required — open data
+ Docs: https://www.norges-bank.no/en/topics/Statistics/open-data/
+
+Data URL pattern:
+ GET https://data.norges-bank.no/api/data/{flow}/{key}
+ flow: Dataflow ID (e.g. EXR, IR, ANN_KPRA)
+ key: Dot-separated dimension filter (e.g. B.USD+EUR.NOK.SP)
+ format: csv
+ startPeriod: YYYY-MM-DD or YYYY-MM or YYYY
+ endPeriod: YYYY-MM-DD or YYYY-MM or YYYY
+ locale: en | no
+
+Verified dataflows:
+ ANN_KPRA — Policy rate announcements (key rate, overnight lending, reserve)
+ IR — Interest rates (NIBOR, NOWA historical, deposit rates)
+ SHORT_RATES — NOWA overnight rate + compounded averages
+ EXR — Exchange rates (NOK per foreign currency, business day)
+ FINANCIAL_INDICATORS— Financial Conditions Index and indicators
+ GOVT_GENERIC_RATES — Government bond yields by tenor (3M–10Y)
+ MONEY_MARKET — Interbank money market transactions
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import csv
+import io
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime, timezone
+
+
+BASE_URL = "https://data.norges-bank.no/api"
+DEFAULT_TIMEOUT = 30
+
+# ---------------------------------------------------------------------------
+# Dataflow catalogue
+# ---------------------------------------------------------------------------
+
+DATAFLOWS = {
+ "ANN_KPRA": {"name": "Policy Rate Announcements", "category": "monetary_policy", "freq": "per decision"},
+ "IR": {"name": "Interest Rates (NIBOR, deposit rates)", "category": "interest_rates", "freq": "daily/monthly"},
+ "SHORT_RATES": {"name": "NOWA Overnight Rate", "category": "interest_rates", "freq": "daily"},
+ "EXR": {"name": "Exchange Rates (NOK per foreign CCY)", "category": "exchange_rates", "freq": "daily/monthly"},
+ "FINANCIAL_INDICATORS":{"name": "Financial Conditions Index", "category": "financial", "freq": "daily"},
+ "GOVT_GENERIC_RATES": {"name": "Government Bond Yields", "category": "govt_bonds", "freq": "daily/monthly"},
+ "MONEY_MARKET": {"name": "Money Market Transactions", "category": "money_market", "freq": "daily"},
+ "FAUCTION": {"name": "F-Auction (liquidity)", "category": "liquidity", "freq": "per auction"},
+}
+
+# Key series keys per flow
+SERIES = {
+ "EXR_MAJOR": "B.USD+EUR+GBP+JPY+SEK+DKK+CHF+CNY.NOK.SP",
+ "EXR_ALL": "B..NOK.SP",
+ "IR_NIBOR": "M.NIBOR_1W+NIBOR_1M+NIBOR_3M+NIBOR_6M...",
+ "GOVT_BONDS": "M.3Y+5Y+10Y.GBON.",
+}
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class NorgesBankError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "NorgesBankError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class NorgesBankWrapper:
+ """
+ Wrapper for the Norges Bank open data SDMX/REST API.
+
+ Exchange rates and interest rates are free, no auth required.
+ CSV responses use semicolons; first row is the header with dimension names.
+ The wrapper returns wide-format JSON rows.
+ """
+
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Accept": "text/csv,text/plain,*/*",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _fetch(self, flow: str, key: str = "", start: Optional[str] = None,
+ end: Optional[str] = None, locale: str = "en") -> str:
+ path = f"{BASE_URL}/data/{flow}"
+ if key:
+ path = f"{path}/{key}"
+ params: Dict[str, str] = {"format": "csv", "locale": locale}
+ if start:
+ params["startPeriod"] = start
+ if end:
+ params["endPeriod"] = end
+ resp = self.session.get(path, params=params, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.text
+
+ def _parse(self, text: str) -> Dict[str, Any]:
+ """
+ Parse Norges Bank SDMX CSV.
+
+ Header row: FREQ;..label..;TENOR;...;TIME_PERIOD;OBS_VALUE
+ Even-indexed cols are codes, odd-indexed are labels.
+ TIME_PERIOD and OBS_VALUE are always the last two.
+ Returns wide-format keyed on TIME_PERIOD.
+ """
+ reader = list(csv.reader(io.StringIO(text), delimiter=";"))
+ if not reader:
+ return {"data": [], "count": 0, "series": []}
+
+ header = reader[0]
+
+ # Find TIME_PERIOD and OBS_VALUE column indices
+ try:
+ tp_idx = header.index("TIME_PERIOD")
+ obs_idx = header.index("OBS_VALUE")
+ except ValueError:
+ return {"error": "Missing TIME_PERIOD/OBS_VALUE columns",
+ "raw_preview": text[:300]}
+
+ # Dimension columns = everything before TIME_PERIOD (skip label cols)
+ dim_cols = [i for i in range(0, tp_idx, 2)] # code cols only
+ dim_names = [header[i] for i in dim_cols]
+
+ # Build rows — pivot by TIME_PERIOD + dimension combo
+ wide: Dict[str, Dict[str, Any]] = {}
+ series_set: List[str] = []
+
+ for row in reader[1:]:
+ if len(row) <= obs_idx:
+ continue
+ date_str = row[tp_idx].strip()
+ if not date_str:
+ continue
+ raw_val = row[obs_idx].strip()
+
+ # Build dimension key
+ dim_vals = [row[i].strip() for i in dim_cols]
+ dim_key = "_".join(v for v in dim_vals if v)
+
+ if dim_key not in series_set:
+ series_set.append(dim_key)
+
+ if date_str not in wide:
+ wide[date_str] = {"date": date_str}
+
+ if raw_val in ("", "..", "N/A", "na"):
+ wide[date_str][dim_key] = None
+ else:
+ try:
+ wide[date_str][dim_key] = float(raw_val.replace(",", ""))
+ except ValueError:
+ wide[date_str][dim_key] = raw_val
+
+ rows = sorted(wide.values(), key=lambda r: r["date"])
+ return {"data": rows, "count": len(rows), "series": series_set,
+ "dimensions": dim_names}
+
+ def _get(self, flow: str, key: str = "", start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ try:
+ text = self._fetch(flow, key, start, end)
+ parsed = self._parse(text)
+ if "error" in parsed:
+ return {"success": False, **parsed}
+ info = DATAFLOWS.get(flow, {})
+ return {
+ "success": True,
+ "flow": flow,
+ "flow_name": info.get("name", flow),
+ "category": info.get("category", ""),
+ "frequency": info.get("freq", ""),
+ "series": parsed["series"],
+ "dimensions": parsed.get("dimensions", []),
+ "data": parsed["data"],
+ "count": parsed["count"],
+ "source": "Norges Bank",
+ "url": f"{BASE_URL}/data/{flow}/{key}",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return NorgesBankError(flow, str(e), sc).to_dict()
+ except Exception as e:
+ return NorgesBankError(flow, str(e)).to_dict()
+
+ # ------------------------------------------------------------------
+ # Public convenience methods
+ # ------------------------------------------------------------------
+
+ def get_policy_rate(self, start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """Policy rate announcements: key rate, overnight lending, reserve rate."""
+ return self._get("ANN_KPRA", start=start, end=end)
+
+ def get_exchange_rates(self, currencies: str = "USD+EUR+GBP+JPY+SEK+DKK+CHF+CNY",
+ start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """Daily NOK exchange rates vs selected currencies."""
+ key = f"B.{currencies}.NOK.SP"
+ return self._get("EXR", key, start, end)
+
+ def get_exchange_rates_monthly(self, currencies: str = "USD+EUR+GBP+JPY+SEK+DKK+CHF",
+ start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """Monthly average NOK exchange rates."""
+ key = f"M.{currencies}.NOK.SP"
+ return self._get("EXR", key, start, end)
+
+ def get_interest_rates(self, start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """NIBOR rates and other interest rates (flow: IR)."""
+ return self._get("IR", start=start, end=end)
+
+ def get_nowa(self, start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """NOWA overnight rate and compounded averages (flow: SHORT_RATES)."""
+ return self._get("SHORT_RATES", start=start, end=end)
+
+ def get_govt_bond_yields(self, tenors: str = "3Y+5Y+10Y",
+ start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """Norwegian government bond yields (3Y, 5Y, 10Y)."""
+ key = f"M.{tenors}.GBON."
+ return self._get("GOVT_GENERIC_RATES", key, start, end)
+
+ def get_govt_bond_yields_daily(self, tenors: str = "3Y+5Y+10Y",
+ start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """Norwegian government bond yields — daily."""
+ key = f"B.{tenors}.GBON."
+ return self._get("GOVT_GENERIC_RATES", key, start, end)
+
+ def get_financial_conditions(self, start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """Financial Conditions Index and related indicators."""
+ return self._get("FINANCIAL_INDICATORS", start=start, end=end)
+
+ def get_money_market(self, start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """Interbank money market transaction volumes and rates."""
+ return self._get("MONEY_MARKET", start=start, end=end)
+
+ def get_overview(self, start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """Snapshot: policy rate, NOK/USD, government bonds."""
+ results: Dict[str, Any] = {}
+ for name, flow, key in [
+ ("policy_rate", "ANN_KPRA", ""),
+ ("nok_usd", "EXR", "B.USD.NOK.SP"),
+ ("nok_eur", "EXR", "B.EUR.NOK.SP"),
+ ("govt_10y", "GOVT_GENERIC_RATES", "B.10Y.GBON."),
+ ]:
+ r = self._get(flow, key, start, end)
+ results[name] = {
+ "success": r.get("success"),
+ "count": r.get("count"),
+ "latest": r.get("data", [{}])[-1] if r.get("data") else None,
+ }
+ return {
+ "success": True,
+ "data": results,
+ "source": "Norges Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_flow(self, flow: str, key: str = "",
+ start: Optional[str] = None,
+ end: Optional[str] = None) -> Dict[str, Any]:
+ """Fetch any dataflow by ID with optional key filter."""
+ return self._get(flow, key, start, end)
+
+ def available_flows(self) -> Dict[str, Any]:
+ """List all available dataflows."""
+ by_cat: Dict[str, List] = {}
+ for fid, info in DATAFLOWS.items():
+ cat = info["category"]
+ by_cat.setdefault(cat, []).append({
+ "flow": fid, "name": info["name"], "frequency": info["freq"],
+ })
+ return {
+ "success": True,
+ "data": by_cat,
+ "base_url": BASE_URL,
+ "source": "Norges Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "policy_rate": "[start] [end] — Policy rate announcements",
+ "exchange_rates": "[currencies] [start] [end] — Daily NOK FX rates",
+ "fx_monthly": "[currencies] [start] [end] — Monthly avg NOK FX rates",
+ "interest_rates": "[start] [end] — NIBOR & interest rates",
+ "nowa": "[start] [end] — NOWA overnight rate",
+ "bond_yields": "[tenors] [start] [end] — Govt bond yields (monthly)",
+ "bond_yields_d": "[tenors] [start] [end] — Govt bond yields (daily)",
+ "financial": "[start] [end] — Financial Conditions Index",
+ "money_market": "[start] [end] — Money market transactions",
+ "overview": "[start] [end] — Key indicators snapshot",
+ "flow": "<flow_id> [key] [start] [end] — Any dataflow by ID",
+ "available": " — List all dataflows",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python norges_bank_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = NorgesBankWrapper()
+
+ try:
+ if cmd == "policy_rate":
+ result = wrapper.get_policy_rate(_a(2), _a(3))
+ elif cmd in ("exchange_rates", "fx"):
+ result = wrapper.get_exchange_rates(_a(2, "USD+EUR+GBP+JPY+SEK+DKK+CHF+CNY"), _a(3), _a(4))
+ elif cmd in ("fx_monthly", "exchange_rates_m"):
+ result = wrapper.get_exchange_rates_monthly(_a(2, "USD+EUR+GBP+JPY+SEK+DKK+CHF"), _a(3), _a(4))
+ elif cmd == "interest_rates":
+ result = wrapper.get_interest_rates(_a(2), _a(3))
+ elif cmd == "nowa":
+ result = wrapper.get_nowa(_a(2), _a(3))
+ elif cmd == "bond_yields":
+ result = wrapper.get_govt_bond_yields(_a(2, "3Y+5Y+10Y"), _a(3), _a(4))
+ elif cmd == "bond_yields_d":
+ result = wrapper.get_govt_bond_yields_daily(_a(2, "3Y+5Y+10Y"), _a(3), _a(4))
+ elif cmd == "financial":
+ result = wrapper.get_financial_conditions(_a(2), _a(3))
+ elif cmd == "money_market":
+ result = wrapper.get_money_market(_a(2), _a(3))
+ elif cmd == "overview":
+ result = wrapper.get_overview(_a(2), _a(3))
+ elif cmd == "flow":
+ if len(sys.argv) < 3:
+ result = {"error": "flow requires <flow_id>"}
+ else:
+ result = wrapper.get_flow(sys.argv[2], _a(3, ""), _a(4), _a(5))
+ elif cmd in ("available", "flows"):
+ result = wrapper.available_flows()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/rba_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/rba_data.py
new file mode 100644
index 000000000..c0f0246a8
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/rba_data.py
@@ -0,0 +1,492 @@
+"""
+Reserve Bank of Australia (RBA) Data Wrapper
+Fetches statistical data from RBA published CSV tables.
+
+API Reference:
+ Base URL: https://www.rba.gov.au/statistics/tables/csv/
+ Format: CSV files, no auth required, no rate limits published
+ Tables: https://www.rba.gov.au/statistics/tables/
+
+Authentication: None required — all data is freely available.
+
+CSV Structure:
+ Row 1: Series IDs (column headers)
+ Row 2: Series descriptions
+ Row 3: Frequency (Monthly / Quarterly / Daily / Annual)
+ Row 4: Data type (Orig / Seasonally Adjusted / Trend)
+ Row 5: Units
+ Row 6: Source
+ Row 7: Publication date
+ Row 8: Blank separator
+ Row 9+: DATE, value1, value2, ... (date format: DD-Mon-YYYY or Mon-YYYY or YYYY)
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import io
+import csv
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime, timezone
+
+
+BASE_URL = "https://www.rba.gov.au/statistics/tables/csv"
+DEFAULT_TIMEOUT = 30
+
+# ---------------------------------------------------------------------------
+# RBA Table catalogue
+# ---------------------------------------------------------------------------
+
+TABLES = {
+ # Interest rates
+ "f1": {"name": "Money Market Interest Rates", "category": "interest_rates"},
+ "f2": {"name": "Capital Market Yields - Government Bonds", "category": "interest_rates"},
+ "f3": {"name": "Capital Market Yields - Non-Government", "category": "interest_rates"},
+ "f4": {"name": "Retail Deposit and Investment Rates", "category": "interest_rates"},
+ "f5": {"name": "Indicator Lending Rates", "category": "interest_rates"},
+ "f6": {"name": "Housing Lending Rates", "category": "interest_rates"},
+ "f7": {"name": "Borrowing and Deposit Rates (Business)", "category": "interest_rates"},
+ # Exchange rates
+ "f11": {"name": "Exchange Rates - Daily", "category": "exchange_rates"},
+ "f12": {"name": "USD Exchange Rates", "category": "exchange_rates"},
+ "f15": {"name": "Real Exchange Rate Measures", "category": "exchange_rates"},
+ # Monetary & credit aggregates
+ "d1": {"name": "Growth in Selected Financial Aggregates", "category": "monetary"},
+ "d2": {"name": "Lending and Credit Aggregates", "category": "monetary"},
+ "d3": {"name": "Monetary Aggregates", "category": "monetary"},
+ # Balance of payments / external
+ "b1": {"name": "RBA Balance Sheet", "category": "balance_sheet"},
+ "b2": {"name": "Banknotes on Issue", "category": "balance_sheet"},
+ # Inflation / prices
+ "g1": {"name": "Consumer Price Inflation", "category": "inflation"},
+ "g2": {"name": "Consumer Price Inflation Expectations", "category": "inflation"},
+ "g3": {"name": "Inflation Expectations Survey", "category": "inflation"},
+ # Housing
+ "f20": {"name": "House Price Growth", "category": "housing"},
+ # Labour / economic activity
+ "h1": {"name": "Labour Market", "category": "labour"},
+ "h3": {"name": "Gross Domestic Product", "category": "gdp"},
+ "h5": {"name": "Business Indicators", "category": "business"},
+ # Payments
+ "c1": {"name": "Credit and Charge Cards", "category": "payments"},
+}
+
+# Pre-built groups for convenience commands
+GROUPS = {
+ "cash_rate": ["f1"],
+ "bond_yields": ["f2"],
+ "exchange_rates": ["f11"],
+ "aud_usd": ["f11"],
+ "lending_rates": ["f5", "f6"],
+ "deposit_rates": ["f4"],
+ "monetary": ["d1", "d3"],
+ "credit": ["d2"],
+ "inflation": ["g1"],
+ "housing": ["f6", "f20"],
+ "labour": ["h1"],
+ "gdp": ["h3"],
+ "balance_sheet": ["b1"],
+ "overview": ["f1", "f2", "f11", "d3", "g1"],
+}
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class RBAError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "RBAError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class RBAWrapper:
+ """
+ Wrapper for Reserve Bank of Australia statistical CSV tables.
+
+ Data is published as CSV files with a 7-row metadata header followed by data rows.
+ No authentication required.
+ """
+
+ def __init__(self):
+ pass # RBA CDN blocks persistent sessions; use plain requests.get()
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _fetch(self, table_code: str) -> str:
+ code = table_code.lower().replace("-", "")
+ url = f"{BASE_URL}/{code}-data.csv"
+ resp = requests.get(url, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.text
+
+ def _parse(self, text: str, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """
+ Parse RBA CSV. Returns dict with series metadata and data rows.
+
+ RBA CSV layout (as of 2026):
+ Row 0: Table title (e.g. "F1 INTEREST RATES AND YIELDS")
+ Row 1: "Title", col1_name, col2_name, ...
+ Row 2: "Description", col1_desc, ...
+ Row 3: "Frequency", Daily, Monthly, ...
+ Row 4: "Type", Original, ...
+ Row 5: "Units", Per cent, ...
+ Row 6: blank
+ Row 7: blank
+ Row 8: "Source", RBA, ...
+ Row 9: "Publication date", ...
+ Row 10: "Series ID", FIRMMCRTD, ...
+ Row 11+: data rows "DD-Mon-YYYY", val, val, ...
+ """
+ reader = list(csv.reader(io.StringIO(text)))
+
+ meta_rows: Dict[str, List[str]] = {}
+ series_ids: List[str] = []
+ data_start = 0
+
+ for i, row in enumerate(reader):
+ if not row:
+ continue
+ label = row[0].strip()
+ if label == "Series ID":
+ series_ids = [c.strip() for c in row]
+ data_start = i + 1
+ break
+ if label in ("Title", "Description", "Frequency", "Type",
+ "Units", "Source", "Publication date"):
+ meta_rows[label] = [c.strip() for c in row]
+
+ if not series_ids:
+ return {"error": "Could not find 'Series ID' row", "raw_preview": text[:300]}
+
+ # Build series metadata
+ titles = meta_rows.get("Title", [""] * len(series_ids))
+ descriptions = meta_rows.get("Description", [""] * len(series_ids))
+ frequencies = meta_rows.get("Frequency", [""] * len(series_ids))
+ data_types = meta_rows.get("Type", [""] * len(series_ids))
+ units = meta_rows.get("Units", [""] * len(series_ids))
+ sources = meta_rows.get("Source", [""] * len(series_ids))
+
+ meta: Dict[str, Any] = {}
+ for i in range(1, len(series_ids)):
+ sid = series_ids[i]
+ if sid:
+ meta[sid] = {
+ "title": titles[i] if i < len(titles) else "",
+ "description": descriptions[i] if i < len(descriptions) else "",
+ "frequency": frequencies[i] if i < len(frequencies) else "",
+ "type": data_types[i] if i < len(data_types) else "",
+ "unit": units[i] if i < len(units) else "",
+ "source": sources[i] if i < len(sources) else "",
+ }
+
+ rows = []
+ for row in reader[data_start:]:
+ if not row or not row[0].strip():
+ continue
+ date_str = row[0].strip()
+ # Skip any remaining metadata rows
+ if date_str in ("Series ID", "Title", "Description", "Frequency",
+ "Type", "Units", "Source", "Publication date"):
+ continue
+ entry = {"date": date_str}
+ for i in range(1, len(series_ids)):
+ if i >= len(row):
+ break
+ sid = series_ids[i]
+ if not sid:
+ continue
+ raw = row[i].strip()
+ if raw in ("", "..", "N/a", "N/A", "na", "NA"):
+ entry[sid] = None
+ else:
+ try:
+ entry[sid] = float(raw.replace(",", ""))
+ except ValueError:
+ entry[sid] = raw
+ rows.append(entry)
+
+ if start_date:
+ rows = [r for r in rows if r["date"] >= start_date]
+ if end_date:
+ rows = [r for r in rows if r["date"] <= end_date]
+
+ return {
+ "series_metadata": meta,
+ "data": rows,
+ "count": len(rows),
+ }
+
+ def _fetch_table(self, table_code: str, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ try:
+ text = self._fetch(table_code)
+ parsed = self._parse(text, start_date, end_date)
+ if "error" in parsed:
+ return {"success": False, **parsed}
+ info = TABLES.get(table_code.lower(), {})
+ return {
+ "success": True,
+ "table": table_code.lower(),
+ "table_name": info.get("name", table_code),
+ "category": info.get("category", ""),
+ "data": parsed["data"],
+ "count": parsed["count"],
+ "series_metadata": parsed["series_metadata"],
+ "source": "Reserve Bank of Australia",
+ "url": f"{BASE_URL}/{table_code.lower()}-data.csv",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ return RBAError(table_code, str(e), e.response.status_code if e.response else None).to_dict()
+ except Exception as e:
+ return RBAError(table_code, str(e)).to_dict()
+
+ def _fetch_group(self, tables: List[str], start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Fetch multiple tables and merge into single response."""
+ all_data = {}
+ all_meta = {}
+ total_count = 0
+ errors = []
+ for tbl in tables:
+ res = self._fetch_table(tbl, start_date, end_date)
+ if res.get("success"):
+ all_meta.update(res.get("series_metadata", {}))
+ for row in res.get("data", []):
+ date = row["date"]
+ if date not in all_data:
+ all_data[date] = {"date": date}
+ all_data[date].update({k: v for k, v in row.items() if k != "date"})
+ total_count = max(total_count, res.get("count", 0))
+ else:
+ errors.append({"table": tbl, "error": res.get("error", "unknown")})
+
+ merged = sorted(all_data.values(), key=lambda r: r["date"])
+ return {
+ "success": len(errors) < len(tables),
+ "tables": tables,
+ "data": merged,
+ "count": len(merged),
+ "series_metadata": all_meta,
+ "errors": errors if errors else None,
+ "source": "Reserve Bank of Australia",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ # ------------------------------------------------------------------
+ # Public convenience methods
+ # ------------------------------------------------------------------
+
+ def get_cash_rate(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Official cash rate target and interbank overnight rate (Table F1)."""
+ return self._fetch_table("f1", start_date, end_date)
+
+ def get_bond_yields(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Australian Government bond yields (Table F2)."""
+ return self._fetch_table("f2", start_date, end_date)
+
+ def get_exchange_rates(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """AUD exchange rates vs 24 currencies + TWI (Table F11)."""
+ return self._fetch_table("f11", start_date, end_date)
+
+ def get_lending_rates(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Indicator lending rates for housing and business (Tables F5 + F6)."""
+ return self._fetch_group(["f5", "f6"], start_date, end_date)
+
+ def get_deposit_rates(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Retail deposit and investment rates (Table F4)."""
+ return self._fetch_table("f4", start_date, end_date)
+
+ def get_monetary_aggregates(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """M1, M3, broad money aggregates (Table D3)."""
+ return self._fetch_table("d3", start_date, end_date)
+
+ def get_credit_aggregates(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Lending and credit aggregates by sector (Table D2)."""
+ return self._fetch_table("d2", start_date, end_date)
+
+ def get_inflation(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Consumer price inflation (Table G1)."""
+ return self._fetch_table("g1", start_date, end_date)
+
+ def get_housing(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Housing lending rates and house price growth (Tables F6 + F20)."""
+ return self._fetch_group(["f6", "f20"], start_date, end_date)
+
+ def get_labour(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Labour market data (Table H1)."""
+ return self._fetch_table("h1", start_date, end_date)
+
+ def get_gdp(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Gross Domestic Product (Table H3)."""
+ return self._fetch_table("h3", start_date, end_date)
+
+ def get_balance_sheet(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """RBA Balance Sheet (Table B1)."""
+ return self._fetch_table("b1", start_date, end_date)
+
+ def get_overview(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Key indicators: cash rate, bond yields, exchange rates, M3, CPI."""
+ return self._fetch_group(GROUPS["overview"], start_date, end_date)
+
+ def get_table(self, table_code: str, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Fetch any RBA table by code (e.g. 'f1', 'd3', 'g1')."""
+ return self._fetch_table(table_code, start_date, end_date)
+
+ def get_group(self, group_name: str, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Fetch a named group of tables."""
+ tables = GROUPS.get(group_name.lower())
+ if not tables:
+ return {"success": False, "error": f"Unknown group '{group_name}'",
+ "available_groups": list(GROUPS.keys())}
+ return self._fetch_group(tables, start_date, end_date)
+
+ def available_tables(self) -> Dict[str, Any]:
+ """Return catalogue of all available RBA tables."""
+ by_category: Dict[str, List] = {}
+ for code, info in TABLES.items():
+ cat = info["category"]
+ by_category.setdefault(cat, []).append({"code": code, "name": info["name"]})
+ return {
+ "success": True,
+ "data": by_category,
+ "groups": {k: v for k, v in GROUPS.items()},
+ "base_url": BASE_URL,
+ "source": "Reserve Bank of Australia",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI entry point
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "cash_rate": "[start_date] [end_date] — Official cash rate (Table F1)",
+ "bond_yields": "[start_date] [end_date] — Govt bond yields (Table F2)",
+ "exchange_rates": "[start_date] [end_date] — AUD exchange rates (Table F11)",
+ "lending_rates": "[start_date] [end_date] — Lending rates (F5+F6)",
+ "deposit_rates": "[start_date] [end_date] — Deposit rates (Table F4)",
+ "monetary": "[start_date] [end_date] — Monetary aggregates (Table D3)",
+ "credit": "[start_date] [end_date] — Credit aggregates (Table D2)",
+ "inflation": "[start_date] [end_date] — CPI inflation (Table G1)",
+ "housing": "[start_date] [end_date] — Housing lending + prices (F6+F20)",
+ "labour": "[start_date] [end_date] — Labour market (Table H1)",
+ "gdp": "[start_date] [end_date] — GDP (Table H3)",
+ "balance_sheet": "[start_date] [end_date] — RBA balance sheet (Table B1)",
+ "overview": "[start_date] [end_date] — Key indicators snapshot",
+ "table": "<code> [start_date] [end_date] — Any table by code",
+ "group": "<group_name> [start_date] [end_date] — Named group of tables",
+ "available": "List all available tables and groups",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python rba_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = RBAWrapper()
+
+ try:
+ if cmd == "cash_rate":
+ result = wrapper.get_cash_rate(_a(2), _a(3))
+ elif cmd == "bond_yields":
+ result = wrapper.get_bond_yields(_a(2), _a(3))
+ elif cmd == "exchange_rates":
+ result = wrapper.get_exchange_rates(_a(2), _a(3))
+ elif cmd == "lending_rates":
+ result = wrapper.get_lending_rates(_a(2), _a(3))
+ elif cmd == "deposit_rates":
+ result = wrapper.get_deposit_rates(_a(2), _a(3))
+ elif cmd in ("monetary", "monetary_aggregates"):
+ result = wrapper.get_monetary_aggregates(_a(2), _a(3))
+ elif cmd in ("credit", "credit_aggregates"):
+ result = wrapper.get_credit_aggregates(_a(2), _a(3))
+ elif cmd == "inflation":
+ result = wrapper.get_inflation(_a(2), _a(3))
+ elif cmd == "housing":
+ result = wrapper.get_housing(_a(2), _a(3))
+ elif cmd == "labour":
+ result = wrapper.get_labour(_a(2), _a(3))
+ elif cmd == "gdp":
+ result = wrapper.get_gdp(_a(2), _a(3))
+ elif cmd == "balance_sheet":
+ result = wrapper.get_balance_sheet(_a(2), _a(3))
+ elif cmd == "overview":
+ result = wrapper.get_overview(_a(2), _a(3))
+ elif cmd == "table":
+ if len(sys.argv) < 3:
+ result = {"error": "table requires <code>", "example": "python rba_data.py table f1"}
+ else:
+ result = wrapper.get_table(sys.argv[2], _a(3), _a(4))
+ elif cmd == "group":
+ if len(sys.argv) < 3:
+ result = {"error": "group requires <group_name>", "available": list(GROUPS.keys())}
+ else:
+ result = wrapper.get_group(sys.argv[2], _a(3), _a(4))
+ elif cmd in ("available", "tables"):
+ result = wrapper.available_tables()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/riksbank_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/riksbank_data.py
new file mode 100644
index 000000000..055fc82a1
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/riksbank_data.py
@@ -0,0 +1,425 @@
+"""
+Sveriges Riksbank (Sweden) Data Wrapper
+Fetches data from the Riksbank SWEA REST API.
+
+API Reference:
+ Base URL: https://api.riksbank.se/swea/v1
+ Format: JSON (array of {date, value})
+ Auth: None required — fully public
+ Docs: https://api.riksbank.se/swea/v1/swagger-ui/index.html
+ Rate limit: ~5 req/s — wrapper includes retry logic
+
+Endpoints:
+ GET /Series — Full series catalogue
+ GET /Observations/{seriesId}/{from} — Observations from date
+ GET /Observations/{seriesId}/{from}/{to} — Observations between dates
+ GET /CrossRates/{from}/{to} — Cross rates on a date
+
+Key series IDs:
+ Policy rates:
+ SECBREPOEFF — Policy rate (repo rate)
+ SECBDEPOEFF — Deposit rate
+ SECBLENDEFF — Lending rate
+ Exchange rates (SEK per 1 foreign currency unit):
+ SEKUSDPMI, SEKEURPMI, SEKGBPPMI, SEKJPYPMI
+ SEKNOKPMI, SEKDKKPMI, SEKCHFPMI
+ STIBOR interbank rates:
+ SEDPT_NSTIBORDELAYC — T/N
+ SEDP1MSTIBORDELAYC — 1 Month
+ SEDP3MSTIBORDELAYC — 3 Months
+ SEDP6MSTIBORDELAYC — 6 Months
+ Government bond yields:
+ SEGVB2YC, SEGVB5YC, SEGVB7YC, SEGVB10YC
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import time
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime, date, timedelta, timezone
+
+
+BASE_URL = "https://api.riksbank.se/swea/v1"
+DEFAULT_TIMEOUT = 30
+RATE_LIMIT_WAIT = 15 # seconds to wait on 429
+
+
+# ---------------------------------------------------------------------------
+# Series catalogue
+# ---------------------------------------------------------------------------
+
+SERIES = {
+ # Policy rates
+ "SECBREPOEFF": {"label": "Policy rate (repo)", "category": "policy_rates"},
+ "SECBDEPOEFF": {"label": "Deposit rate", "category": "policy_rates"},
+ "SECBLENDEFF": {"label": "Lending rate", "category": "policy_rates"},
+ "SECBLIKVEFF": {"label": "Liquidity facility rate", "category": "policy_rates"},
+ "SECBREFEFF": {"label": "Reference rate", "category": "policy_rates"},
+ # Exchange rates (SEK per 1 foreign currency unit)
+ "SEKUSDPMI": {"label": "SEK/USD", "category": "exchange_rates"},
+ "SEKEURPMI": {"label": "SEK/EUR", "category": "exchange_rates"},
+ "SEKGBPPMI": {"label": "SEK/GBP", "category": "exchange_rates"},
+ "SEKJPYPMI": {"label": "SEK/JPY", "category": "exchange_rates"},
+ "SEKNOKPMI": {"label": "SEK/NOK", "category": "exchange_rates"},
+ "SEKDKKPMI": {"label": "SEK/DKK", "category": "exchange_rates"},
+ "SEKCHFPMI": {"label": "SEK/CHF", "category": "exchange_rates"},
+ "SEKCNYPMI": {"label": "SEK/CNY", "category": "exchange_rates"},
+ "SEKCADPMI": {"label": "SEK/CAD", "category": "exchange_rates"},
+ "SEKAUDPMI": {"label": "SEK/AUD", "category": "exchange_rates"},
+ "SEKKIX92": {"label": "KIX index", "category": "exchange_rates"},
+ # Treasury bills
+ "SETB1MBENCHC": {"label": "SE T-bill 1 Month", "category": "treasury_bills"},
+ "SETB3MBENCH": {"label": "SE T-bill 3 Months", "category": "treasury_bills"},
+ "SETB6MBENCH": {"label": "SE T-bill 6 Months", "category": "treasury_bills"},
+ # Government bond yields
+ "SEGVB2YC": {"label": "SE GVB 2 Year", "category": "govt_bonds"},
+ "SEGVB5YC": {"label": "SE GVB 5 Year", "category": "govt_bonds"},
+ "SEGVB7YC": {"label": "SE GVB 7 Year", "category": "govt_bonds"},
+ "SEGVB10YC": {"label": "SE GVB 10 Year", "category": "govt_bonds"},
+ # Mortgage bonds
+ "SEMB2YCACOMB": {"label": "SE Mortgage Bond 2 Year", "category": "mortgage_bonds"},
+ "SEMB5YCACOMB": {"label": "SE Mortgage Bond 5 Year", "category": "mortgage_bonds"},
+}
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class RiksbankError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "RiksbankError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class RiksbankWrapper:
+ """
+ Wrapper for the Sveriges Riksbank SWEA REST API.
+
+ Exchange rates expressed as SEK per 1 unit of foreign currency.
+ Interest rates are in percent per annum.
+ API has rate limits; wrapper retries once on 429.
+ """
+
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Accept": "application/json",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _get(self, path: str, retries: int = 1) -> Any:
+ url = f"{BASE_URL}/{path.lstrip('/')}"
+ resp = self.session.get(url, timeout=DEFAULT_TIMEOUT)
+ if resp.status_code == 429 and retries > 0:
+ retry_after = int(resp.headers.get("Retry-After", RATE_LIMIT_WAIT))
+ time.sleep(retry_after)
+ return self._get(path, retries - 1)
+ resp.raise_for_status()
+ return resp.json()
+
+ def _fetch_series(self, series_id: str,
+ from_date: Optional[str] = None,
+ to_date: Optional[str] = None) -> Dict[str, Any]:
+ """Fetch observations for a single series."""
+ if from_date is None:
+ from_date = (date.today() - timedelta(days=365)).isoformat()
+ if to_date:
+ path = f"Observations/{series_id}/{from_date}/{to_date}"
+ else:
+ path = f"Observations/{series_id}/{from_date}"
+ try:
+ raw = self._get(path)
+ # raw is list of {date, value} or an error dict
+ if isinstance(raw, dict) and raw.get("statusCode"):
+ return RiksbankError(path, raw.get("message", str(raw)),
+ raw.get("statusCode")).to_dict()
+ rows = [{"date": r["date"], "value": r.get("value")} for r in raw]
+ info = SERIES.get(series_id, {})
+ return {
+ "success": True,
+ "series_id": series_id,
+ "label": info.get("label", series_id),
+ "category": info.get("category", ""),
+ "from_date": from_date,
+ "to_date": to_date or rows[-1]["date"] if rows else None,
+ "data": rows,
+ "count": len(rows),
+ "source": "Sveriges Riksbank",
+ "url": f"{BASE_URL}/{path}",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return RiksbankError(series_id, str(e), sc).to_dict()
+ except Exception as e:
+ return RiksbankError(series_id, str(e)).to_dict()
+
+ def _multi(self, series_ids: List[str],
+ from_date: Optional[str] = None,
+ to_date: Optional[str] = None,
+ delay: float = 0.5) -> Dict[str, Any]:
+ """
+ Fetch multiple series and pivot to wide format.
+ Inserts a small delay between requests to respect rate limits.
+ """
+ if from_date is None:
+ from_date = (date.today() - timedelta(days=365)).isoformat()
+
+ wide: Dict[str, Dict[str, Any]] = {}
+ fetched: List[str] = []
+ errors: List[str] = []
+
+ for sid in series_ids:
+ r = self._fetch_series(sid, from_date, to_date)
+ if r.get("success"):
+ fetched.append(sid)
+ for row in r.get("data", []):
+ d = row["date"]
+ if d not in wide:
+ wide[d] = {"date": d}
+ wide[d][sid] = row.get("value")
+ else:
+ errors.append(f"{sid}: {r.get('error','unknown error')}")
+ if delay and sid != series_ids[-1]:
+ time.sleep(delay)
+
+ rows = sorted(wide.values(), key=lambda x: x["date"])
+ return {
+ "success": True,
+ "series": fetched,
+ "errors": errors,
+ "from_date": from_date,
+ "to_date": to_date,
+ "data": rows,
+ "count": len(rows),
+ "source": "Sveriges Riksbank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ # ------------------------------------------------------------------
+ # Public methods
+ # ------------------------------------------------------------------
+
+ def get_policy_rate(self, from_date: Optional[str] = None,
+ to_date: Optional[str] = None) -> Dict[str, Any]:
+ """Policy rate (repo rate) history."""
+ return self._fetch_series("SECBREPOEFF", from_date, to_date)
+
+ def get_policy_rates_all(self, from_date: Optional[str] = None,
+ to_date: Optional[str] = None) -> Dict[str, Any]:
+ """Policy rate, deposit rate, and lending rate (wide format)."""
+ ids = ["SECBREPOEFF", "SECBDEPOEFF", "SECBLENDEFF"]
+ return self._multi(ids, from_date, to_date)
+
+ def get_exchange_rate(self, currency: str = "USD",
+ from_date: Optional[str] = None,
+ to_date: Optional[str] = None) -> Dict[str, Any]:
+ """SEK exchange rate for a single currency (e.g. USD, EUR, GBP)."""
+ sid = f"SEK{currency.upper()}PMI"
+ return self._fetch_series(sid, from_date, to_date)
+
+ def get_exchange_rates(self, currencies: Optional[List[str]] = None,
+ from_date: Optional[str] = None,
+ to_date: Optional[str] = None) -> Dict[str, Any]:
+ """SEK exchange rates for multiple currencies (wide format)."""
+ if currencies is None:
+ currencies = ["USD", "EUR", "GBP", "JPY", "CHF", "NOK", "DKK"]
+ ids = [f"SEK{c.upper()}PMI" for c in currencies]
+ result = self._multi(ids, from_date, to_date)
+ result["currencies"] = currencies
+ result["note"] = "SEK per 1 unit of foreign currency"
+ return result
+
+ def get_tbills(self, from_date: Optional[str] = None,
+ to_date: Optional[str] = None) -> Dict[str, Any]:
+ """Swedish treasury bill benchmark rates: 1M, 3M, 6M (wide format)."""
+ ids = ["SETB1MBENCHC", "SETB3MBENCH", "SETB6MBENCH"]
+ result = self._multi(ids, from_date, to_date)
+ result["tenors"] = ["1M", "3M", "6M"]
+ return result
+
+ def get_mortgage_bonds(self, from_date: Optional[str] = None,
+ to_date: Optional[str] = None) -> Dict[str, Any]:
+ """Swedish mortgage bond yields: 2Y, 5Y (wide format)."""
+ ids = ["SEMB2YCACOMB", "SEMB5YCACOMB"]
+ return self._multi(ids, from_date, to_date)
+
+ def get_govt_bond_yields(self, from_date: Optional[str] = None,
+ to_date: Optional[str] = None) -> Dict[str, Any]:
+ """Swedish government bond yields: 2Y, 5Y, 7Y, 10Y (wide format)."""
+ ids = ["SEGVB2YC", "SEGVB5YC", "SEGVB7YC", "SEGVB10YC"]
+ return self._multi(ids, from_date, to_date)
+
+ def get_series(self, series_id: str,
+ from_date: Optional[str] = None,
+ to_date: Optional[str] = None) -> Dict[str, Any]:
+ """Fetch any series by its Riksbank series ID."""
+ return self._fetch_series(series_id, from_date, to_date)
+
+ def get_series_catalogue(self) -> Dict[str, Any]:
+ """Full list of all series available in the Riksbank SWEA API."""
+ try:
+ data = self._get("Series")
+ return {
+ "success": True,
+ "count": len(data),
+ "data": data,
+ "source": "Sveriges Riksbank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return RiksbankError("Series", str(e), sc).to_dict()
+ except Exception as e:
+ return RiksbankError("Series", str(e)).to_dict()
+
+ def get_overview(self) -> Dict[str, Any]:
+ """Snapshot: latest policy rate, EUR/SEK, USD/SEK, 10Y bond."""
+ results: Dict[str, Any] = {}
+ from_date = (date.today() - timedelta(days=7)).isoformat()
+ for name, sid in [
+ ("policy_rate", "SECBREPOEFF"),
+ ("deposit_rate","SECBDEPOEFF"),
+ ("eur_sek", "SEKEURPMI"),
+ ("usd_sek", "SEKUSDPMI"),
+ ("gbp_sek", "SEKGBPPMI"),
+ ("bond_10y", "SEGVB10YC"),
+ ("tbill_3m", "SETB3MBENCH"),
+ ]:
+ r = self._fetch_series(sid, from_date)
+ results[name] = {
+ "success": r.get("success"),
+ "label": r.get("label", sid),
+ "latest": r.get("data", [{}])[-1] if r.get("data") else None,
+ }
+ time.sleep(0.3) # be gentle with rate limits
+ return {
+ "success": True,
+ "data": results,
+ "source": "Sveriges Riksbank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def available_series(self) -> Dict[str, Any]:
+ """Built-in series catalogue by category."""
+ by_cat: Dict[str, List] = {}
+ for sid, info in SERIES.items():
+ cat = info["category"]
+ by_cat.setdefault(cat, []).append({"series_id": sid, "label": info["label"]})
+ return {
+ "success": True,
+ "data": by_cat,
+ "total": len(SERIES),
+ "note": "Use get_series(series_id) for any Riksbank series",
+ "source": "Sveriges Riksbank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "policy_rate": "[from_date] [to_date] — Policy rate (repo rate) history",
+ "policy_all": "[from_date] [to_date] — Policy/deposit/lending rates",
+ "fx": "[currencies] [from_date] [to_date] — SEK exchange rates (multi)",
+ "fx_single": "<currency> [from_date] [to_date] — SEK rate for one currency",
+ "tbills": "[from_date] [to_date] — T-bill benchmark rates (1M-6M)",
+ "mortgage": "[from_date] [to_date] — Mortgage bond yields (2Y, 5Y)",
+ "bonds": "[from_date] [to_date] — Govt bond yields (2Y-10Y)",
+ "series": "<series_id> [from_date] [to_date] — Any series by ID",
+ "catalogue": " — Full series catalogue from API",
+ "overview": " — Key indicators snapshot",
+ "available": " — Built-in series catalogue",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python riksbank_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = RiksbankWrapper()
+
+ try:
+ if cmd == "policy_rate":
+ result = wrapper.get_policy_rate(_a(2), _a(3))
+ elif cmd in ("policy_all", "policy_rates"):
+ result = wrapper.get_policy_rates_all(_a(2), _a(3))
+ elif cmd in ("fx", "exchange_rates"):
+ raw = _a(2, "USD,EUR,GBP,JPY,CHF,NOK,DKK")
+ ccys = [c.strip().upper() for c in raw.split(",")]
+ result = wrapper.get_exchange_rates(ccys, _a(3), _a(4))
+ elif cmd in ("fx_single", "fx_one"):
+ if len(sys.argv) < 3:
+ result = {"error": "fx_single requires <currency>"}
+ else:
+ result = wrapper.get_exchange_rate(sys.argv[2].upper(), _a(3), _a(4))
+ elif cmd in ("tbills", "tbill"):
+ result = wrapper.get_tbills(_a(2), _a(3))
+ elif cmd in ("mortgage", "mortgage_bonds"):
+ result = wrapper.get_mortgage_bonds(_a(2), _a(3))
+ elif cmd in ("bonds", "bond_yields"):
+ result = wrapper.get_govt_bond_yields(_a(2), _a(3))
+ elif cmd == "series":
+ if len(sys.argv) < 3:
+ result = {"error": "series requires <series_id>"}
+ else:
+ result = wrapper.get_series(sys.argv[2], _a(3), _a(4))
+ elif cmd == "catalogue":
+ result = wrapper.get_series_catalogue()
+ elif cmd == "overview":
+ result = wrapper.get_overview()
+ elif cmd in ("available", "list"):
+ result = wrapper.available_series()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=True))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/snb_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/snb_data.py
new file mode 100644
index 000000000..525780d38
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/snb_data.py
@@ -0,0 +1,482 @@
+"""
+Swiss National Bank (SNB) Data Wrapper
+Fetches data from the SNB Data Portal REST API.
+
+API Reference:
+ Base URL: https://data.snb.ch/api
+ Format: Semicolon-delimited CSV
+ Auth: None required — open data
+ Docs: https://data.snb.ch/en/help_api
+
+Data URL pattern:
+ GET https://data.snb.ch/api/cube/{cube_id}/data/csv/{lang}
+ lang: en | de | fr | it
+ startDate: YYYY-MM (or YYYY for annual)
+ endDate: YYYY-MM
+ dimSel: D0(code1,code2),D1(code3) — filter specific dimension values
+
+Dimensions URL (for discovering series codes):
+ GET https://data.snb.ch/api/cube/{cube_id}/dimensions/{lang}
+ Returns JSON with all dimension IDs and their allowed values.
+
+CSV structure (semicolons):
+ Row 1: "CubeId";"<id>"
+ Row 2: "PublishingDate";"<date>"
+ Row 3: "Date";"D0"[;"D1"];"Value" <- column header
+ Row 4+: "YYYY-MM";"<code>"[;"<code>"];"<value>"
+
+Multi-dimension cubes produce one row per (date × d0 × d1) combination.
+The wrapper pivots these to wide format: date → {d0_d1: value}.
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import io
+import csv
+import requests
+import traceback
+from typing import Dict, Any, List, Optional
+from datetime import datetime, timezone
+
+
+BASE_URL = "https://data.snb.ch/api"
+DEFAULT_LANG = "en"
+DEFAULT_TIMEOUT = 30
+
+# ---------------------------------------------------------------------------
+# Verified SNB Cube catalogue (tested 2026-02)
+# ---------------------------------------------------------------------------
+
+CUBES = {
+ # --- Monetary policy / interest rates ---
+ "snbgwdzid": {"name": "SNB Policy Rate & Money Market Rates (daily)",
+ "category": "monetary_policy", "freq": "daily",
+ "series": "LZ=Policy rate; SARON=SARON rate; ENG=Repo rate; ZIGBL=Sight deposit rate"},
+ "zimoma": {"name": "Money Market Reference Rates — Monthly",
+ "category": "interest_rates", "freq": "monthly",
+ "series": "SARON=SARON; 1TGT=1M target; EG3M=3M Euromarket; EG6M=6M; EG12M=12M"},
+ "rendoblid": {"name": "Confederation Bond Yields — Daily",
+ "category": "interest_rates", "freq": "daily",
+ "series": "1J-30J = 1Y to 30Y maturity"},
+ "rendoblim": {"name": "Confederation Bond Yields — Monthly",
+ "category": "interest_rates", "freq": "monthly",
+ "series": "1J-30J = 1Y to 30Y maturity"},
+ "snbiprogq": {"name": "SNB Conditional Inflation Forecast — Quarterly",
+ "category": "inflation", "freq": "quarterly",
+ "series": "Inflation forecasts from past MPAs"},
+ # --- Exchange rates ---
+ "devkua": {"name": "CHF Exchange Rates — Annual",
+ "category": "exchange_rates", "freq": "annual",
+ "series": "EUR1, USD1, JPY100, GBP1, CNY1, CAD1, AUD1, etc."},
+ "devkum": {"name": "CHF Exchange Rates — Monthly",
+ "category": "exchange_rates", "freq": "monthly",
+ "series": "D0: M0=monthly avg / M1=end-of-month; D1: EUR1,USD1,JPY100,GBP1,CNY1..."},
+ # --- Monetary aggregates ---
+ "snbmonagg": {"name": "Monetary Aggregates M1, M2, M3",
+ "category": "monetary", "freq": "monthly",
+ "series": "D0: B=level/VV=YoY change; D1: GM1,GM2,GM3,ET,S0,S1,S2"},
+ # --- External / reserves ---
+ "snbimfra": {"name": "Foreign Exchange Reserves (IMF template)",
+ "category": "external", "freq": "monthly",
+ "series": "T0=total reserves; T1=foreign currency; T2=gold; T3=SDR"},
+ # --- Bonds / capital market ---
+ "capcollvf": {"name": "Capital Market — Bond Issues",
+ "category": "capital_market", "freq": "quarterly",
+ "series": "Domestic and foreign bond issues by sector"},
+}
+
+# Convenience groups
+GROUPS = {
+ "policy_rate": ["snbgwdzid"],
+ "interest_rates": ["snbgwdzid", "zimoma", "rendoblim"],
+ "exchange_rates": ["devkum"],
+ "monetary": ["snbmonagg"],
+ "fx_reserves": ["snbimfra"],
+ "inflation": ["snbiprogq"],
+ "bond_yields": ["rendoblid"],
+ "overview": ["snbgwdzid", "devkum", "snbmonagg", "snbimfra"],
+}
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class SNBError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "SNBError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class SNBWrapper:
+ """
+ Wrapper for the Swiss National Bank (SNB) Data Portal REST API.
+
+ No authentication required. Data is in semicolon-delimited CSV.
+ Cubes may have 1 or 2 dimension columns (D0, optionally D1).
+ Multi-dimension data is pivoted to wide format: {date: {dim_key: value}}.
+ """
+
+ def __init__(self, lang: str = DEFAULT_LANG):
+ self.lang = lang
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1 (SNB-wrapper)",
+ "Accept": "text/csv,text/plain,*/*",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _fetch_csv(self, cube_id: str, start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ dim_sel: Optional[str] = None) -> str:
+ url = f"{BASE_URL}/cube/{cube_id}/data/csv/{self.lang}"
+ params: Dict[str, str] = {}
+ if start_date:
+ params["startDate"] = start_date
+ if end_date:
+ params["endDate"] = end_date
+ if dim_sel:
+ params["dimSel"] = dim_sel
+ resp = self.session.get(url, params=params, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.text
+
+ def _get_dimensions(self, cube_id: str) -> Dict[str, Any]:
+ """Return dimension metadata JSON for a cube."""
+ url = f"{BASE_URL}/cube/{cube_id}/dimensions/{self.lang}"
+ resp = self.session.get(url, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.json()
+
+ def _parse_csv(self, text: str) -> Dict[str, Any]:
+ """
+ Parse SNB semicolon CSV into wide-format rows.
+
+ Handles 1-dim (Date;D0;Value) and 2-dim (Date;D0;D1;Value) layouts.
+ Pivot: key = D0 for 1-dim, or D0__D1 for 2-dim.
+ """
+ lines = text.strip().splitlines()
+ cube_id = ""
+ pub_date = ""
+ data_start = 0
+ num_dims = 1 # default
+
+ for i, line in enumerate(lines):
+ stripped = line.strip().strip('"')
+ if line.startswith('"CubeId"') or line.startswith('CubeId'):
+ parts = line.split(";")
+ cube_id = parts[1].strip().strip('"') if len(parts) > 1 else ""
+ elif line.startswith('"PublishingDate"') or line.startswith('PublishingDate'):
+ parts = line.split(";")
+ pub_date = parts[1].strip().strip('"') if len(parts) > 1 else ""
+ elif line.startswith('"Date"') or line.startswith('Date'):
+ # Count dimension columns
+ header_parts = line.split(";")
+ num_dims = len(header_parts) - 2 # subtract Date and Value
+ data_start = i + 1
+ break
+
+ reader = csv.reader(lines[data_start:], delimiter=";")
+ wide: Dict[str, Dict[str, Any]] = {}
+ series_set: List[str] = []
+
+ for row in reader:
+ if len(row) < 3:
+ continue
+ date_str = row[0].strip().strip('"')
+ if not date_str:
+ continue
+
+ raw_val = row[-1].strip().strip('"') # last column always Value
+
+ # Build pivot key from dimension columns
+ if num_dims == 1:
+ d0 = row[1].strip().strip('"')
+ dim_key = d0
+ else:
+ dims = [row[j].strip().strip('"') for j in range(1, num_dims + 1)]
+ dim_key = "__".join(dims)
+
+ if dim_key and dim_key not in series_set:
+ series_set.append(dim_key)
+
+ if date_str not in wide:
+ wide[date_str] = {"date": date_str}
+
+ if raw_val in ("", "..", "N/a", "N/A", "na", "NA", "-"):
+ wide[date_str][dim_key] = None
+ else:
+ try:
+ wide[date_str][dim_key] = float(raw_val.replace(",", ""))
+ except ValueError:
+ wide[date_str][dim_key] = raw_val
+
+ rows = sorted(wide.values(), key=lambda r: r["date"])
+ return {
+ "cube_id": cube_id,
+ "publishing_date": pub_date,
+ "series": series_set,
+ "data": rows,
+ "count": len(rows),
+ }
+
+ def _fetch_cube(self, cube_id: str, start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ dim_sel: Optional[str] = None) -> Dict[str, Any]:
+ try:
+ text = self._fetch_csv(cube_id, start_date, end_date, dim_sel)
+ parsed = self._parse_csv(text)
+ info = CUBES.get(cube_id, {})
+ return {
+ "success": True,
+ "cube": cube_id,
+ "cube_name": info.get("name", cube_id),
+ "category": info.get("category", ""),
+ "frequency": info.get("freq", ""),
+ "publishing_date": parsed["publishing_date"],
+ "series": parsed["series"],
+ "series_notes": info.get("series", ""),
+ "data": parsed["data"],
+ "count": parsed["count"],
+ "source": "Swiss National Bank",
+ "url": f"{BASE_URL}/cube/{cube_id}/data/csv/{self.lang}",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return SNBError(cube_id, str(e), sc).to_dict()
+ except Exception as e:
+ return SNBError(cube_id, str(e)).to_dict()
+
+ # ------------------------------------------------------------------
+ # Public convenience methods
+ # ------------------------------------------------------------------
+
+ def get_policy_rate(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """SNB policy rate, SARON, and sight deposit rate (cube: snbgwdzid)."""
+ return self._fetch_cube("snbgwdzid", start_date, end_date,
+ dim_sel="D0(LZ,SARON,ENG,ZIGBL)")
+
+ def get_money_market_rates(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """SARON and money market reference rates — monthly (cube: zimoma)."""
+ return self._fetch_cube("zimoma", start_date, end_date,
+ dim_sel="D0(SARON,EG3M,EG6M,EG12M,1TGT)")
+
+ def get_bond_yields_daily(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Swiss Confederation bond yields — daily (cube: rendoblid)."""
+ return self._fetch_cube("rendoblid", start_date, end_date,
+ dim_sel="D0(2J,5J,10J,20J,30J)")
+
+ def get_bond_yields_monthly(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Swiss Confederation bond yields — monthly (cube: rendoblim)."""
+ return self._fetch_cube("rendoblim", start_date, end_date,
+ dim_sel="D0(2J,5J,10J,20J,30J)")
+
+ def get_exchange_rates_monthly(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """CHF exchange rates vs major currencies — monthly averages (cube: devkum)."""
+ return self._fetch_cube("devkum", start_date, end_date,
+ dim_sel="D0(M0),D1(EUR1,USD1,JPY100,GBP1,CNY1,CAD1,AUD1,SEK1,NOK1)")
+
+ def get_exchange_rates_annual(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """CHF exchange rates vs major currencies — annual (cube: devkua)."""
+ return self._fetch_cube("devkua", start_date, end_date)
+
+ def get_monetary_aggregates(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """M1, M2, M3 monetary aggregates — levels (cube: snbmonagg)."""
+ return self._fetch_cube("snbmonagg", start_date, end_date,
+ dim_sel="D0(B),D1(GM1,GM2,GM3)")
+
+ def get_monetary_aggregates_full(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Full monetary aggregates with all sub-components (cube: snbmonagg)."""
+ return self._fetch_cube("snbmonagg", start_date, end_date)
+
+ def get_fx_reserves(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Foreign exchange reserves — IMF template (cube: snbimfra)."""
+ return self._fetch_cube("snbimfra", start_date, end_date)
+
+ def get_inflation_forecast(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """SNB conditional inflation forecast (cube: snbiprogq)."""
+ return self._fetch_cube("snbiprogq", start_date, end_date)
+
+ def get_overview(self, start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """Key snapshot: policy rate, FX, M3, reserves."""
+ results: Dict[str, Any] = {}
+ for name, cube, ds in [
+ ("policy_rate", "snbgwdzid", "D0(LZ,SARON)"),
+ ("exchange_rates","devkum", "D0(M0),D1(EUR1,USD1,GBP1,JPY100)"),
+ ("monetary_m3", "snbmonagg", "D0(B),D1(GM3)"),
+ ("fx_reserves", "snbimfra", None),
+ ]:
+ r = self._fetch_cube(cube, start_date, end_date, dim_sel=ds)
+ results[name] = {
+ "success": r.get("success"),
+ "count": r.get("count"),
+ "latest": r.get("data", [{}])[-1] if r.get("data") else None,
+ }
+ return {
+ "success": True,
+ "data": results,
+ "source": "Swiss National Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_cube(self, cube_id: str, start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ dim_sel: Optional[str] = None) -> Dict[str, Any]:
+ """Fetch any SNB cube by ID with optional dimSel filter."""
+ return self._fetch_cube(cube_id, start_date, end_date, dim_sel)
+
+ def get_dimensions(self, cube_id: str) -> Dict[str, Any]:
+ """Return all dimension codes for a cube (use to discover series codes)."""
+ try:
+ data = self._get_dimensions(cube_id)
+ return {"success": True, "cube": cube_id, "data": data,
+ "source": "Swiss National Bank"}
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return SNBError(cube_id, str(e), sc).to_dict()
+ except Exception as e:
+ return SNBError(cube_id, str(e)).to_dict()
+
+ def available_cubes(self) -> Dict[str, Any]:
+ """Return catalogue of all known SNB cubes."""
+ by_category: Dict[str, List] = {}
+ for cid, info in CUBES.items():
+ cat = info["category"]
+ by_category.setdefault(cat, []).append({
+ "cube": cid,
+ "name": info["name"],
+ "frequency": info["freq"],
+ "series": info.get("series", ""),
+ })
+ return {
+ "success": True,
+ "data": by_category,
+ "groups": GROUPS,
+ "base_url": BASE_URL,
+ "source": "Swiss National Bank",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI entry point
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "policy_rate": "[start] [end] — SNB policy rate + SARON",
+ "saron": "[start] [end] — Money market reference rates",
+ "bond_yields": "[start] [end] — Confederation bond yields (monthly)",
+ "bond_yields_d": "[start] [end] — Confederation bond yields (daily)",
+ "exchange_rates": "[start] [end] — CHF monthly FX rates",
+ "exchange_rates_a": "[start] [end] — CHF annual FX rates",
+ "monetary": "[start] [end] — M1/M2/M3 aggregates",
+ "monetary_full": "[start] [end] — All monetary aggregate components",
+ "fx_reserves": "[start] [end] — Foreign exchange reserves",
+ "inflation": "[start] [end] — SNB inflation forecast",
+ "overview": "[start] [end] — Key indicators snapshot",
+ "cube": "<cube_id> [start] [end] [dimSel] — Any cube by ID",
+ "dimensions": "<cube_id> — Show dimension codes for a cube",
+ "available": " — List all cubes and groups",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python snb_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = SNBWrapper()
+
+ try:
+ if cmd == "policy_rate":
+ result = wrapper.get_policy_rate(_a(2), _a(3))
+ elif cmd in ("saron", "money_market"):
+ result = wrapper.get_money_market_rates(_a(2), _a(3))
+ elif cmd == "bond_yields":
+ result = wrapper.get_bond_yields_monthly(_a(2), _a(3))
+ elif cmd == "bond_yields_d":
+ result = wrapper.get_bond_yields_daily(_a(2), _a(3))
+ elif cmd in ("exchange_rates", "fx"):
+ result = wrapper.get_exchange_rates_monthly(_a(2), _a(3))
+ elif cmd in ("exchange_rates_a", "fx_annual"):
+ result = wrapper.get_exchange_rates_annual(_a(2), _a(3))
+ elif cmd in ("monetary", "monetary_aggregates"):
+ result = wrapper.get_monetary_aggregates(_a(2), _a(3))
+ elif cmd == "monetary_full":
+ result = wrapper.get_monetary_aggregates_full(_a(2), _a(3))
+ elif cmd == "fx_reserves":
+ result = wrapper.get_fx_reserves(_a(2), _a(3))
+ elif cmd == "inflation":
+ result = wrapper.get_inflation_forecast(_a(2), _a(3))
+ elif cmd == "overview":
+ result = wrapper.get_overview(_a(2), _a(3))
+ elif cmd == "cube":
+ if len(sys.argv) < 3:
+ result = {"error": "cube requires <cube_id>"}
+ else:
+ result = wrapper.get_cube(sys.argv[2], _a(3), _a(4), _a(5))
+ elif cmd == "dimensions":
+ if len(sys.argv) < 3:
+ result = {"error": "dimensions requires <cube_id>"}
+ else:
+ result = wrapper.get_dimensions(sys.argv[2])
+ elif cmd in ("available", "cubes"):
+ result = wrapper.available_cubes()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/tcmb_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/tcmb_data.py
new file mode 100644
index 000000000..21593ec6b
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/tcmb_data.py
@@ -0,0 +1,435 @@
+"""
+Central Bank of the Republic of Turkey (TCMB / CBRT) Data Wrapper
+Fetches exchange rate data from the TCMB public XML bulletin service.
+
+API Reference:
+ Base URL: https://www.tcmb.gov.tr/kurlar
+ Format: XML (UTF-8)
+ Auth: None required — fully public
+ Docs: https://www.tcmb.gov.tr/wps/wcm/connect/EN/TCMB+EN/Main+Menu/Statistics/Exchange+Rates/
+
+URL patterns:
+ Today: GET /kurlar/today.xml
+ By date: GET /kurlar/{YYYYMM}/{DDMMYYYY}.xml (business days only)
+
+Exchange rates published on Turkish business days (Mon–Fri, excluding holidays).
+Rates are TRY per foreign currency unit.
+Each currency entry includes:
+ ForexBuying — wholesale foreign exchange buying
+ ForexSelling — wholesale foreign exchange selling
+ BanknoteBuying — banknote buying
+ BanknoteSelling — banknote selling
+ CrossRateUSD — cross rate in USD (if applicable)
+
+Currencies available (22):
+ USD, AUD, DKK, EUR, GBP, CHF, SEK, CAD, KWD, NOK, SAR,
+ JPY (per 100), RON, RUB, CNY, PKR, QAR, KRW, AZN, AED, KZT, XDR
+
+Returns JSON output for Rust/Tauri integration.
+"""
+
+import sys
+import json
+import requests
+import traceback
+import xml.etree.ElementTree as ET
+from typing import Dict, Any, List, Optional
+from datetime import datetime, date, timedelta, timezone
+
+
+BASE_URL = "https://www.tcmb.gov.tr/kurlar"
+DEFAULT_TIMEOUT = 30
+
+MAJOR_CURRENCIES = ["USD", "EUR", "GBP", "JPY", "CHF", "CAD", "AUD",
+ "SEK", "NOK", "DKK", "CNY", "SAR", "AED"]
+
+
+# ---------------------------------------------------------------------------
+# Error container
+# ---------------------------------------------------------------------------
+
+class TCMBError:
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "endpoint": self.endpoint,
+ "error": self.error,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ "type": "TCMBError",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Main wrapper
+# ---------------------------------------------------------------------------
+
+class TCMBWrapper:
+ """
+ Wrapper for the TCMB (Central Bank of Turkey) XML exchange rate bulletin.
+
+ Rates are TRY (Turkish Lira) per 1 unit of foreign currency.
+ JPY is quoted per 100 JPY; the wrapper normalises to per 1 JPY.
+ Data is published on Turkish business days only.
+ """
+
+ def __init__(self):
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/3.3.1",
+ "Accept": "application/xml, text/xml, */*",
+ })
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _fetch(self, url: str) -> bytes:
+ resp = self.session.get(url, timeout=DEFAULT_TIMEOUT)
+ resp.raise_for_status()
+ return resp.content
+
+ def _parse_bulletin(self, content: bytes) -> Dict[str, Any]:
+ """
+ Parse a single TCMB XML bulletin into a dict of currency data.
+ Returns {date, USD: {buy, sell, banknote_buy, banknote_sell}, ...}
+ JPY values are normalised (÷100).
+ """
+ root = ET.fromstring(content)
+ date_str = root.get("Date", "") # MM/DD/YYYY
+ bulten_no = root.get("Bulten_No", "")
+
+ # Normalise date to ISO format
+ try:
+ parsed_date = datetime.strptime(date_str, "%m/%d/%Y").date().isoformat()
+ except ValueError:
+ parsed_date = date_str
+
+ rates: Dict[str, Any] = {}
+ for cur in root.findall("Currency"):
+ code = cur.get("CurrencyCode", "")
+ unit = int(cur.findtext("Unit", "1") or "1")
+
+ def _val(tag: str) -> Optional[float]:
+ txt = cur.findtext(tag, "")
+ if not txt or txt.strip() == "":
+ return None
+ try:
+ return round(float(txt.replace(",", ".")), 6) / unit
+ except ValueError:
+ return None
+
+ rates[code] = {
+ "forex_buying": _val("ForexBuying"),
+ "forex_selling": _val("ForexSelling"),
+ "banknote_buying": _val("BanknoteBuying"),
+ "banknote_selling": _val("BanknoteSelling"),
+ "unit": unit,
+ }
+ cross = cur.findtext("CrossRateUSD", "").strip()
+ if cross:
+ try:
+ rates[code]["cross_rate_usd"] = float(cross.replace(",", "."))
+ except ValueError:
+ pass
+
+ return {
+ "date": parsed_date,
+ "bulten_no": bulten_no,
+ "rates": rates,
+ }
+
+ def _date_url(self, d: date) -> str:
+ return f"{BASE_URL}/{d.strftime('%Y%m')}/{d.strftime('%d%m%Y')}.xml"
+
+ def _find_latest_business_day(self, max_lookback: int = 7) -> Optional[date]:
+ """Walk back from today to find the most recent published bulletin."""
+ today = date.today()
+ for i in range(max_lookback):
+ d = today - timedelta(days=i)
+ try:
+ content = self._fetch(self._date_url(d))
+ ET.fromstring(content) # verify it's valid XML
+ return d
+ except Exception:
+ continue
+ return None
+
+ def _flatten_rates(self, bulletin: Dict[str, Any],
+ fields: Optional[List[str]] = None) -> Dict[str, Any]:
+ """Flatten bulletin to {date, USD_buy, USD_sell, EUR_buy, ...} row."""
+ if fields is None:
+ fields = ["forex_buying", "forex_selling"]
+ row: Dict[str, Any] = {"date": bulletin["date"]}
+ for code, data in bulletin["rates"].items():
+ for f in fields:
+ val = data.get(f)
+ if val is not None:
+ key = f"{code}_{f}" if len(fields) > 1 else code
+ row[key] = val
+ return row
+
+ # ------------------------------------------------------------------
+ # Public methods
+ # ------------------------------------------------------------------
+
+ def get_today(self) -> Dict[str, Any]:
+ """Latest exchange rate bulletin (most recent business day)."""
+ try:
+ content = self._fetch(f"{BASE_URL}/today.xml")
+ bulletin = self._parse_bulletin(content)
+ return {
+ "success": True,
+ "date": bulletin["date"],
+ "bulten_no": bulletin["bulten_no"],
+ "data": bulletin["rates"],
+ "note": "TRY per 1 unit of foreign currency (JPY normalised from per-100)",
+ "source": "Central Bank of the Republic of Turkey",
+ "url": f"{BASE_URL}/today.xml",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return TCMBError("today", str(e), sc).to_dict()
+ except Exception as e:
+ return TCMBError("today", str(e)).to_dict()
+
+ def get_date(self, rate_date: str) -> Dict[str, Any]:
+ """Exchange rates for a specific date (YYYY-MM-DD). Must be a business day."""
+ try:
+ d = datetime.strptime(rate_date, "%Y-%m-%d").date()
+ url = self._date_url(d)
+ content = self._fetch(url)
+ bulletin = self._parse_bulletin(content)
+ return {
+ "success": True,
+ "date": bulletin["date"],
+ "bulten_no": bulletin["bulten_no"],
+ "data": bulletin["rates"],
+ "note": "TRY per 1 unit of foreign currency",
+ "source": "Central Bank of the Republic of Turkey",
+ "url": url,
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except requests.exceptions.HTTPError as e:
+ sc = e.response.status_code if e.response is not None else None
+ return TCMBError(f"date/{rate_date}", str(e), sc).to_dict()
+ except Exception as e:
+ return TCMBError(f"date/{rate_date}", str(e)).to_dict()
+
+ def get_range(self, start_date: str, end_date: Optional[str] = None,
+ currencies: Optional[List[str]] = None) -> Dict[str, Any]:
+ """
+ Exchange rates for a date range — fetches each business day individually.
+ Returns wide-format rows with forex_buying rates.
+ """
+ try:
+ start = datetime.strptime(start_date, "%Y-%m-%d").date()
+ end = datetime.strptime(end_date, "%Y-%m-%d").date() if end_date else date.today()
+
+ rows: List[Dict[str, Any]] = []
+ errors: List[str] = []
+ d = start
+ while d <= end:
+ if d.weekday() < 5: # Mon–Fri only
+ try:
+ content = self._fetch(self._date_url(d))
+ bulletin = self._parse_bulletin(content)
+ row = {"date": bulletin["date"]}
+ for code, data in bulletin["rates"].items():
+ if currencies is None or code in currencies:
+ buy = data.get("forex_buying")
+ if buy is not None:
+ row[code] = buy
+ rows.append(row)
+ except Exception:
+ pass # holiday / no data for this day
+ d += timedelta(days=1)
+
+ return {
+ "success": True,
+ "start_date": start_date,
+ "end_date": end.isoformat(),
+ "currencies": currencies or "all",
+ "data": rows,
+ "count": len(rows),
+ "note": "TRY per 1 unit (forex buying rate)",
+ "source": "Central Bank of the Republic of Turkey",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except Exception as e:
+ return TCMBError("range", str(e)).to_dict()
+
+ def get_currency(self, currency: str,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None) -> Dict[str, Any]:
+ """
+ Buying and selling rates for a single currency over a date range.
+ Defaults to the last 30 calendar days.
+ """
+ currency = currency.upper()
+ if start_date is None:
+ start_date = (date.today() - timedelta(days=30)).isoformat()
+ try:
+ result = self.get_range(start_date, end_date, [currency])
+ # Enrich each row with both buy and sell
+ start = datetime.strptime(start_date, "%Y-%m-%d").date()
+ end_d = datetime.strptime(end_date, "%Y-%m-%d").date() if end_date else date.today()
+ rows: List[Dict[str, Any]] = []
+ d = start
+ while d <= end_d:
+ if d.weekday() < 5:
+ try:
+ content = self._fetch(self._date_url(d))
+ bulletin = self._parse_bulletin(content)
+ cdata = bulletin["rates"].get(currency, {})
+ if cdata.get("forex_buying") is not None:
+ rows.append({
+ "date": bulletin["date"],
+ "forex_buying": cdata.get("forex_buying"),
+ "forex_selling": cdata.get("forex_selling"),
+ "banknote_buying": cdata.get("banknote_buying"),
+ "banknote_selling": cdata.get("banknote_selling"),
+ })
+ except Exception:
+ pass
+ d += timedelta(days=1)
+
+ return {
+ "success": True,
+ "currency": currency,
+ "start_date": start_date,
+ "end_date": end_d.isoformat(),
+ "data": rows,
+ "count": len(rows),
+ "note": f"TRY per 1 {currency}",
+ "source": "Central Bank of the Republic of Turkey",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+ except Exception as e:
+ return TCMBError(f"currency/{currency}", str(e)).to_dict()
+
+ def get_major_currencies(self, start_date: Optional[str] = None) -> Dict[str, Any]:
+ """Major currencies vs TRY — last 30 days if no start given."""
+ if start_date is None:
+ start_date = (date.today() - timedelta(days=30)).isoformat()
+ return self.get_range(start_date, currencies=MAJOR_CURRENCIES)
+
+ def get_overview(self) -> Dict[str, Any]:
+ """Snapshot: today's rates for major currencies (buying & selling)."""
+ today = self.get_today()
+ if not today.get("success"):
+ return today
+ all_rates = today.get("data", {})
+ snapshot = {}
+ for c in MAJOR_CURRENCIES:
+ if c in all_rates:
+ snapshot[c] = {
+ "buy": all_rates[c].get("forex_buying"),
+ "sell": all_rates[c].get("forex_selling"),
+ }
+ return {
+ "success": True,
+ "date": today.get("date"),
+ "bulten_no": today.get("bulten_no"),
+ "data": snapshot,
+ "all_rates": all_rates,
+ "note": "TRY per 1 unit of foreign currency",
+ "source": "Central Bank of the Republic of Turkey",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def available_currencies(self) -> Dict[str, Any]:
+ """List of currencies published in TCMB bulletins."""
+ return {
+ "success": True,
+ "major_currencies": MAJOR_CURRENCIES,
+ "all_currencies": [
+ "USD", "AUD", "DKK", "EUR", "GBP", "CHF", "SEK", "CAD",
+ "KWD", "NOK", "SAR", "JPY", "RON", "RUB", "CNY", "PKR",
+ "QAR", "KRW", "AZN", "AED", "KZT", "XDR",
+ ],
+ "note": "TRY per 1 unit; JPY is per 100 in raw XML but normalised here",
+ "source": "Central Bank of the Republic of Turkey",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+COMMANDS = {
+ "today": " — Latest bulletin (most recent business day)",
+ "date": "<YYYY-MM-DD> — Bulletin for a specific date",
+ "range": "<start> [end] [currencies] — Date range, wide format (forex buying)",
+ "currency": "<CCY> [start] [end] — Single currency buy/sell history",
+ "major": "[start] — Major currencies last 30 days",
+ "overview": " — Today's major currency snapshot",
+ "available":" — List available currencies",
+}
+
+
+def _a(n: int, d: Any = None) -> Any:
+ return sys.argv[n] if len(sys.argv) > n and sys.argv[n] else d
+
+
+def main() -> None:
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "No command provided.",
+ "usage": "python tcmb_data.py <command> [args...]",
+ "commands": COMMANDS,
+ }, indent=2))
+ sys.exit(1)
+
+ cmd = sys.argv[1].lower()
+ wrapper = TCMBWrapper()
+
+ try:
+ if cmd == "today":
+ result = wrapper.get_today()
+ elif cmd == "date":
+ if len(sys.argv) < 3:
+ result = {"error": "date requires <YYYY-MM-DD>"}
+ else:
+ result = wrapper.get_date(sys.argv[2])
+ elif cmd == "range":
+ if len(sys.argv) < 3:
+ result = {"error": "range requires <start_date>"}
+ else:
+ ccys = [c.strip().upper() for c in _a(4, "").split(",")] if _a(4) else None
+ result = wrapper.get_range(sys.argv[2], _a(3), ccys)
+ elif cmd == "currency":
+ if len(sys.argv) < 3:
+ result = {"error": "currency requires <CCY>"}
+ else:
+ result = wrapper.get_currency(sys.argv[2], _a(3), _a(4))
+ elif cmd == "major":
+ result = wrapper.get_major_currencies(_a(2))
+ elif cmd == "overview":
+ result = wrapper.get_overview()
+ elif cmd in ("available", "currencies"):
+ result = wrapper.available_currencies()
+ else:
+ result = {"error": f"Unknown command: {cmd}", "commands": COMMANDS}
+
+ print(json.dumps(result, indent=2, ensure_ascii=True))
+
+ except Exception as exc:
+ print(json.dumps({
+ "success": False,
+ "error": str(exc),
+ "traceback": traceback.format_exc(),
+ }, indent=2))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/un_comtrade_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/un_comtrade_data.py
new file mode 100644
index 000000000..1c16065c0
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/un_comtrade_data.py
@@ -0,0 +1,1239 @@
+"""
+UN Comtrade API Data Fetcher
+Comprehensive wrapper for the United Nations Comtrade Database API.
+Provides access to global bilateral trade flows for 200+ countries at
+HS product code level — the most comprehensive global trade dataset.
+
+API Documentation: https://comtradedeveloper.un.org/
+Official Python lib: https://github.com/uncomtrade/comtradeapicall
+Base URL (public): https://comtradeapi.un.org/public/v1/
+Base URL (auth): https://comtradeapi.un.org/data/v1/
+Metadata URL: https://comtradeapi.un.org/files/v1/app/
+
+Authentication:
+ - Without key: unlimited calls/day, max 500 records per call (preview endpoints)
+ - With subscription key: 500 calls/day, max 100,000 records per call
+ - Register free at: https://comtradedeveloper.un.org/
+
+Key Concepts:
+ - typeCode: 'C' = Goods/Commodities, 'S' = Services
+ - freqCode: 'A' = Annual, 'M' = Monthly
+ - clCode: Classification scheme — 'HS' (Harmonized System), 'S1'/'S2'/'S3'/'S4' (SITC revisions), 'B4'/'B5' (BEC)
+ - flowCode: 'X' = Export, 'M' = Import, 'RX' = Re-export, 'RM' = Re-import
+ - period: 'YYYY' for annual, 'YYYYMM' for monthly
+ - cmdCode: HS commodity code e.g. '0101' (horses), 'TOTAL' for all
+ - reporterCode / partnerCode: UN numeric country codes (e.g. 842=USA, 156=China, 356=India)
+"""
+
+import sys
+import json
+import os
+import requests
+from datetime import datetime, timezone, timedelta
+from typing import Dict, Any, Optional, List, Union
+
+
+BASE_URL_PUBLIC = "https://comtradeapi.un.org/public/v1"
+BASE_URL_DATA = "https://comtradeapi.un.org/data/v1"
+BASE_URL_TOOLS = "https://comtradeapi.un.org/tools/v1"
+BASE_URL_BULK = "https://comtradeapi.un.org/bulk/v1"
+BASE_URL_FILES = "https://comtradeapi.un.org/files/v1/app/reference"
+
+# Static reference JSON files
+REF_LIST_URL = f"{BASE_URL_FILES}/../ListofReferences.json"
+REF_REPORTERS = f"{BASE_URL_FILES}/Reporters.json"
+REF_PARTNERS = f"{BASE_URL_FILES}/partnerAreas.json"
+REF_FLOWS = f"{BASE_URL_FILES}/tradeRegimes.json"
+REF_MOT = f"{BASE_URL_FILES}/ModeOfTransportCodes.json"
+REF_CUSTOMS = f"{BASE_URL_FILES}/CustomsCodes.json"
+REF_ISO_CODES = f"{BASE_URL_FILES}/country_area_code_iso.json"
+
+# Reference category → URL map (populated after imports)
+REFERENCE_URLS = {
+ "reporter": f"{BASE_URL_FILES}/Reporters.json",
+ "partner": f"{BASE_URL_FILES}/partnerAreas.json",
+ "flow": f"{BASE_URL_FILES}/tradeRegimes.json",
+ "mot": f"{BASE_URL_FILES}/ModeOfTransportCodes.json",
+ "customs": f"{BASE_URL_FILES}/CustomsCodes.json",
+ "freq": f"{BASE_URL_FILES}/Frequency.json",
+ "qtyunit": f"{BASE_URL_FILES}/QuantityUnits.json",
+ "mos": f"{BASE_URL_FILES}/ModeOfSupply.json",
+ "dataitem": f"{BASE_URL_FILES}/TradeDataItems.json",
+ "HS": f"{BASE_URL_FILES}/HS.json",
+ "H0": f"{BASE_URL_FILES}/H0.json",
+ "H1": f"{BASE_URL_FILES}/H1.json",
+ "H2": f"{BASE_URL_FILES}/H2.json",
+ "H3": f"{BASE_URL_FILES}/H3.json",
+ "H4": f"{BASE_URL_FILES}/H4.json",
+ "H5": f"{BASE_URL_FILES}/H5.json",
+ "H6": f"{BASE_URL_FILES}/H6.json",
+ "S1": f"{BASE_URL_FILES}/S1.json",
+ "S2": f"{BASE_URL_FILES}/S2.json",
+ "S3": f"{BASE_URL_FILES}/S3.json",
+ "S4": f"{BASE_URL_FILES}/S4.json",
+ "B4": f"{BASE_URL_FILES}/B4.json",
+ "B5": f"{BASE_URL_FILES}/B5.json",
+ "EB02": f"{BASE_URL_FILES}/EB02.json",
+ "EB10": f"{BASE_URL_FILES}/EB10.json",
+}
+
+# Common UN country codes for convenience
+COUNTRY_CODES = {
+ "USA": 842, "CHN": 156, "DEU": 276, "JPN": 392, "GBR": 826,
+ "FRA": 251, "IND": 356, "ITA": 381, "CAN": 124, "KOR": 410,
+ "RUS": 643, "AUS": 36, "BRA": 76, "ESP": 724, "MEX": 484,
+ "IDN": 360, "NLD": 528, "SAU": 682, "TUR": 792, "CHE": 757,
+ "POL": 616, "BEL": 56, "SWE": 752, "ARG": 32, "NOR": 578,
+ "ARE": 784, "THA": 764, "ZAF": 710, "MYS": 458, "SGP": 702,
+ "DNK": 208, "EGY": 818, "PHL": 608, "CHL": 152, "VNM": 704,
+ "BGD": 50, "NGA": 566, "PAK": 586, "IRN": 364, "ISR": 376,
+ "AUT": 40, "PRT": 620, "GRC": 300, "CZE": 203, "ROU": 642,
+ "HUN": 348, "FIN": 246, "NZL": 554, "PER": 604, "COL": 170,
+}
+
+# Common HS chapter codes
+HS_CHAPTERS = {
+ "01": "Live animals",
+ "02": "Meat and edible meat offal",
+ "03": "Fish and crustaceans",
+ "04": "Dairy produce; eggs; honey",
+ "10": "Cereals",
+ "15": "Animal/vegetable fats and oils",
+ "22": "Beverages, spirits and vinegar",
+ "27": "Mineral fuels and oils",
+ "28": "Inorganic chemicals",
+ "29": "Organic chemicals",
+ "30": "Pharmaceutical products",
+ "39": "Plastics",
+ "40": "Rubber",
+ "44": "Wood and articles of wood",
+ "52": "Cotton",
+ "61": "Knitted/crocheted clothing",
+ "72": "Iron and steel",
+ "84": "Nuclear reactors, boilers, machinery",
+ "85": "Electrical machinery and equipment",
+ "87": "Vehicles",
+ "88": "Aircraft and spacecraft",
+ "90": "Optical, photographic, medical instruments",
+ "TOTAL": "All commodities",
+}
+
+
+class ComtradeError:
+ """Error handling wrapper for UN Comtrade API responses"""
+
+ def __init__(self, endpoint: str, error: str, status_code: Optional[int] = None):
+ self.endpoint = endpoint
+ self.error = error
+ self.status_code = status_code
+ self.timestamp = int(datetime.now(timezone.utc).timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "error": self.error,
+ "endpoint": self.endpoint,
+ "status_code": self.status_code,
+ "timestamp": self.timestamp,
+ }
+
+
+class UNComtradeWrapper:
+ """
+ Comprehensive UN Comtrade API wrapper.
+ Uses public (no-key) preview endpoints by default.
+ Pass a subscription_key for full data access (500 calls/day, 100k records/call).
+ """
+
+ def __init__(self, subscription_key: Optional[str] = None):
+ self.subscription_key = subscription_key or os.environ.get("UN_COMTRADE_API_KEY", None)
+ self.session = requests.Session()
+ self.session.headers.update({
+ "User-Agent": "Fincept-Terminal/1.0",
+ "Accept": "application/json",
+ })
+
+ # ==================== INTERNAL HELPERS ====================
+
+ def _make_request(self, url: str, params: Dict[str, Any]) -> Dict[str, Any]:
+ """Centralized GET request with error handling"""
+ try:
+ # Strip None values
+ clean_params = {k: v for k, v in params.items() if v is not None}
+
+ # Inject subscription key if available
+ if self.subscription_key:
+ clean_params["subscription-key"] = self.subscription_key
+
+ response = self.session.get(url, params=clean_params, timeout=60)
+
+ if response.status_code == 401:
+ return ComtradeError(url, "Unauthorized — invalid or missing subscription key.", 401).to_dict()
+ if response.status_code == 429:
+ return ComtradeError(url, "Rate limit exceeded. 500 calls/day limit reached.", 429).to_dict()
+ if response.status_code == 403:
+ return ComtradeError(url, "Forbidden — subscription key may be expired or insufficient.", 403).to_dict()
+
+ response.raise_for_status()
+ data = response.json()
+
+ # Comtrade wraps results in {"data": [...], "count": N, "error": null}
+ if isinstance(data, dict) and data.get("error"):
+ return ComtradeError(url, str(data["error"])).to_dict()
+
+ records = data.get("data", data) if isinstance(data, dict) else data
+ count = data.get("count", len(records) if isinstance(records, list) else 0)
+
+ return {
+ "success": True,
+ "endpoint": url,
+ "data": records,
+ "count": count,
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ except requests.exceptions.HTTPError as e:
+ return ComtradeError(url, f"HTTP error: {str(e)}", getattr(e.response, "status_code", None)).to_dict()
+ except requests.exceptions.Timeout:
+ return ComtradeError(url, "Request timed out after 60 seconds.").to_dict()
+ except requests.exceptions.RequestException as e:
+ return ComtradeError(url, f"Network error: {str(e)}").to_dict()
+ except json.JSONDecodeError as e:
+ return ComtradeError(url, f"JSON decode error: {str(e)}").to_dict()
+ except Exception as e:
+ return ComtradeError(url, f"Unexpected error: {str(e)}").to_dict()
+
+ def _trade_url(self, endpoint: str, type_code: str, freq_code: str, cl_code: str) -> str:
+ """Build the correct base URL depending on whether we have a subscription key"""
+ if self.subscription_key:
+ return f"{BASE_URL_DATA}/{endpoint}/{type_code}/{freq_code}/{cl_code}"
+ else:
+ preview_ep = "preview" if endpoint == "get" else "previewTariffline"
+ return f"{BASE_URL_PUBLIC}/{preview_ep}/{type_code}/{freq_code}/{cl_code}"
+
+ # ==================== TRADE DATA ENDPOINTS ====================
+
+ def get_trade_data(
+ self,
+ reporter_code: Union[str, int],
+ period: str,
+ type_code: str = "C",
+ freq_code: str = "A",
+ cl_code: str = "HS",
+ cmd_code: str = "TOTAL",
+ flow_code: str = "X,M",
+ partner_code: Optional[Union[str, int]] = None,
+ partner2_code: Optional[Union[str, int]] = None,
+ customs_code: Optional[str] = None,
+ mot_code: Optional[str] = None,
+ max_records: int = 500,
+ include_desc: bool = True,
+ aggregate_by: Optional[str] = None,
+ breakdown_mode: str = "classic",
+ count_only: bool = False,
+ ) -> Dict[str, Any]:
+ """
+ Retrieve trade data (final aggregated).
+ Without subscription key: limited to 500 records (preview).
+ With subscription key: up to 100,000 records.
+
+ Args:
+ reporter_code: UN country code of the reporting country (e.g. 842 = USA)
+ Use 'all' for all reporters.
+ period: 'YYYY' for annual or 'YYYYMM' for monthly. Comma-separate multiple.
+ E.g. '2023', '202301,202302', '2020,2021,2022'
+ type_code: 'C' = Goods, 'S' = Services
+ freq_code: 'A' = Annual, 'M' = Monthly
+ cl_code: 'HS' = Harmonized System, 'S1'/'S2'/'S3'/'S4' = SITC revisions, 'B4'/'B5' = BEC
+ cmd_code: Commodity code(s). 'TOTAL' = all. Comma-separate multiples.
+ E.g. '27' (mineral fuels), '84,85' (machinery+electronics)
+ flow_code: 'X' = exports, 'M' = imports, 'RX' = re-exports, 'RM' = re-imports
+ Comma-separate e.g. 'X,M'
+ partner_code: Trading partner country code. None = all partners. '0' = world total.
+ partner2_code: Second partner code (for re-export/re-import flows)
+ customs_code: Customs procedure code. None = all.
+ mot_code: Mode of transport code. None = all.
+ max_records: Max records to return (500 for preview, up to 100000 with key)
+ include_desc: Include human-readable descriptions for codes
+ aggregate_by: Aggregation field
+ breakdown_mode: 'classic' or 'plus'
+ count_only: If True, return only record count
+ """
+ url = self._trade_url("get", type_code, freq_code, cl_code)
+ params = {
+ "reporterCode": reporter_code,
+ "period": period,
+ "cmdCode": cmd_code,
+ "flowCode": flow_code,
+ "partnerCode": partner_code,
+ "partner2Code": partner2_code,
+ "customsCode": customs_code,
+ "motCode": mot_code,
+ "maxRecords": max_records,
+ "includeDesc": str(include_desc).lower(),
+ "aggregateBy": aggregate_by,
+ "breakdownMode": breakdown_mode,
+ "countOnly": str(count_only).lower() if count_only else None,
+ }
+ result = self._make_request(url, params)
+ if result.get("success"):
+ result["reporter_code"] = reporter_code
+ result["period"] = period
+ result["cmd_code"] = cmd_code
+ result["flow_code"] = flow_code
+ return result
+
+ def get_tariffline_data(
+ self,
+ reporter_code: Union[str, int],
+ period: str,
+ type_code: str = "C",
+ freq_code: str = "A",
+ cl_code: str = "HS",
+ cmd_code: str = "TOTAL",
+ flow_code: str = "X,M",
+ partner_code: Optional[Union[str, int]] = None,
+ max_records: int = 500,
+ include_desc: bool = True,
+ ) -> Dict[str, Any]:
+ """
+ Retrieve tariff-line level trade data (most granular).
+ Requires subscription key for more than 500 records.
+
+ Args:
+ reporter_code: Reporting country UN code
+ period: 'YYYY' or 'YYYYMM'
+ type_code: 'C' or 'S'
+ freq_code: 'A' or 'M'
+ cl_code: Classification scheme
+ cmd_code: Commodity code(s)
+ flow_code: Trade flow direction(s)
+ partner_code: Partner country code
+ max_records: Maximum records
+ include_desc: Include descriptions
+ """
+ if self.subscription_key:
+ url = f"{BASE_URL_DATA}/getTariffline/{type_code}/{freq_code}/{cl_code}"
+ else:
+ url = f"{BASE_URL_PUBLIC}/previewTariffline/{type_code}/{freq_code}/{cl_code}"
+
+ params = {
+ "reporterCode": reporter_code,
+ "period": period,
+ "cmdCode": cmd_code,
+ "flowCode": flow_code,
+ "partnerCode": partner_code,
+ "maxRecords": max_records,
+ "includeDesc": str(include_desc).lower(),
+ }
+ return self._make_request(url, params)
+
+ def get_trade_balance(
+ self,
+ reporter_code: Union[str, int],
+ period: str,
+ type_code: str = "C",
+ freq_code: str = "A",
+ cl_code: str = "HS",
+ cmd_code: str = "TOTAL",
+ partner_code: Optional[Union[str, int]] = None,
+ include_desc: bool = True,
+ ) -> Dict[str, Any]:
+ """
+ Get trade balance — exports and imports side by side for a reporter.
+ Requires subscription key.
+
+ Args:
+ reporter_code: Reporting country UN code
+ period: Period(s) e.g. '2023' or '2020,2021,2022,2023'
+ type_code: 'C' or 'S'
+ freq_code: 'A' or 'M'
+ cl_code: Classification
+ cmd_code: Commodity code
+ partner_code: Partner country (None = world)
+ include_desc: Include descriptions
+ """
+ if not self.subscription_key:
+ return ComtradeError(
+ "/tools/v1/getTradeBalance",
+ "Trade balance endpoint requires a subscription key. Register free at https://comtradedeveloper.un.org/"
+ ).to_dict()
+
+ url = f"{BASE_URL_TOOLS}/getTradeBalance/{type_code}/{freq_code}/{cl_code}"
+ params = {
+ "reporterCode": reporter_code,
+ "period": period,
+ "cmdCode": cmd_code,
+ "partnerCode": partner_code,
+ "includeDesc": str(include_desc).lower(),
+ }
+ result = self._make_request(url, params)
+ if result.get("success"):
+ result["reporter_code"] = reporter_code
+ result["period"] = period
+ return result
+
+ def get_bilateral_data(
+ self,
+ reporter_code: Union[str, int],
+ partner_code: Union[str, int],
+ period: str,
+ type_code: str = "C",
+ freq_code: str = "A",
+ cl_code: str = "HS",
+ cmd_code: str = "TOTAL",
+ include_desc: bool = True,
+ ) -> Dict[str, Any]:
+ """
+ Get bilateral trade data — both reporter's and partner's reported figures side by side.
+ Useful for reconciling mirror statistics. Requires subscription key.
+
+ Args:
+ reporter_code: Primary reporting country UN code
+ partner_code: Partner country UN code
+ period: Period(s) e.g. '2023'
+ type_code: 'C' or 'S'
+ freq_code: 'A' or 'M'
+ cl_code: Classification
+ cmd_code: Commodity code
+ include_desc: Include descriptions
+ """
+ if not self.subscription_key:
+ return ComtradeError(
+ "/tools/v1/getBilateralData",
+ "Bilateral data endpoint requires a subscription key. Register free at https://comtradedeveloper.un.org/"
+ ).to_dict()
+
+ url = f"{BASE_URL_TOOLS}/getBilateralData/{type_code}/{freq_code}/{cl_code}"
+ params = {
+ "reporterCode": reporter_code,
+ "partnerCode": partner_code,
+ "period": period,
+ "cmdCode": cmd_code,
+ "includeDesc": str(include_desc).lower(),
+ }
+ result = self._make_request(url, params)
+ if result.get("success"):
+ result["reporter_code"] = reporter_code
+ result["partner_code"] = partner_code
+ result["period"] = period
+ return result
+
+ def get_trade_matrix(
+ self,
+ reporter_code: Union[str, int],
+ period: str,
+ type_code: str = "C",
+ freq_code: str = "A",
+ ) -> Dict[str, Any]:
+ """
+ Get the world trade matrix with estimates for missing data.
+ Useful for constructing a complete bilateral trade network.
+ Requires subscription key.
+
+ Args:
+ reporter_code: Country UN code
+ period: 'YYYY' or 'YYYYMM'
+ type_code: 'C' or 'S'
+ freq_code: 'A' or 'M'
+ """
+ if not self.subscription_key:
+ return ComtradeError(
+ "/data/v1/getTradeMatrix",
+ "Trade matrix endpoint requires a subscription key."
+ ).to_dict()
+
+ url = f"{BASE_URL_DATA}/getTradeMatrix/{type_code}/{freq_code}/TM"
+ params = {
+ "reporterCode": reporter_code,
+ "period": period,
+ }
+ return self._make_request(url, params)
+
+ # ==================== DATA AVAILABILITY ====================
+
+ def get_data_availability(
+ self,
+ reporter_code: Optional[Union[str, int]] = None,
+ type_code: str = "C",
+ freq_code: str = "A",
+ cl_code: str = "HS",
+ published_date_from: Optional[str] = None,
+ published_date_to: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Check which reporter/period combinations have data available.
+
+ Args:
+ reporter_code: Country code to check (None = all countries)
+ type_code: 'C' or 'S'
+ freq_code: 'A' or 'M'
+ cl_code: Classification scheme
+ published_date_from: Filter by publish date start 'YYYY-MM-DD'
+ published_date_to: Filter by publish date end 'YYYY-MM-DD'
+ """
+ base = BASE_URL_DATA if self.subscription_key else BASE_URL_PUBLIC
+ url = f"{base}/getDa/{type_code}/{freq_code}/{cl_code}"
+ params = {
+ "reporterCode": reporter_code,
+ "publishedDateFrom": published_date_from,
+ "publishedDateTo": published_date_to,
+ }
+ result = self._make_request(url, params)
+ if result.get("success"):
+ result["type_code"] = type_code
+ result["freq_code"] = freq_code
+ result["cl_code"] = cl_code
+ return result
+
+ def get_live_updates(self) -> Dict[str, Any]:
+ """
+ Get information about recent data releases and updates.
+ Shows which countries and periods were recently published.
+ """
+ url = f"{BASE_URL_PUBLIC}/getLiveUpdate"
+ return self._make_request(url, {})
+
+ # ==================== REFERENCE / METADATA ====================
+
+ def list_references(self) -> Dict[str, Any]:
+ """
+ List all available reference/lookup tables.
+ Returns names of datasets like 'reporter', 'partner', 'cmd', 'flow', etc.
+ """
+ url = "https://comtradeapi.un.org/files/v1/app/reference/ListofReferences.json"
+ return self._make_request(url, {})
+
+ def get_reference(self, category: str) -> Dict[str, Any]:
+ """
+ Get a specific reference/lookup table.
+
+ Args:
+ category: Reference table name. Common values:
+ 'reporter' — All reporting countries with UN codes
+ 'partner' — All partner countries with UN codes
+ 'HS' — Harmonized System commodity codes (latest)
+ 'H0'...'H6' — HS revisions 1992–2022
+ 'S1','S2','S3','S4'— SITC revision commodity codes
+ 'B4','B5' — BEC commodity codes
+ 'flow' — Trade flow types (X, M, RX, RM)
+ 'mot' — Modes of transport
+ 'customs' — Customs procedure codes
+ 'freq' — Frequency codes
+ 'qtyunit' — Quantity unit codes
+ """
+ url = REFERENCE_URLS.get(category)
+ if not url:
+ return ComtradeError(
+ "get_reference",
+ f"Unknown category '{category}'. Valid: {list(REFERENCE_URLS.keys())}"
+ ).to_dict()
+ result = self._make_request(url, {})
+ if result.get("success"):
+ result["category"] = category
+ return result
+
+ def get_metadata(
+ self,
+ reporter_code: Optional[Union[str, int]] = None,
+ type_code: str = "C",
+ freq_code: str = "A",
+ cl_code: str = "HS",
+ ) -> Dict[str, Any]:
+ """
+ Get metadata and publication notes for a dataset.
+
+ Args:
+ reporter_code: Country code (None = all)
+ type_code: 'C' or 'S'
+ freq_code: 'A' or 'M'
+ cl_code: Classification
+ """
+ base = BASE_URL_DATA if self.subscription_key else BASE_URL_PUBLIC
+ url = f"{base}/getMetadata/{type_code}/{freq_code}/{cl_code}"
+ params = {"reporterCode": reporter_code}
+ return self._make_request(url, params)
+
+ # ==================== HIGH-LEVEL CONVENIENCE METHODS ====================
+
+ def get_country_exports(
+ self,
+ country_iso3: str,
+ year: Union[str, int],
+ top_n: int = 500,
+ cl_code: str = "HS",
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get all exports for a country in a given year.
+
+ Args:
+ country_iso3: ISO3 country code e.g. 'USA', 'CHN', 'DEU'
+ year: Year e.g. 2023
+ top_n: Max records (500 for free tier)
+ cl_code: 'HS' or SITC revision
+ """
+ code = COUNTRY_CODES.get(country_iso3.upper())
+ if code is None:
+ return ComtradeError("get_country_exports", f"Unknown ISO3 code: {country_iso3}. Use get_reference('reporter') for valid codes.").to_dict()
+
+ result = self.get_trade_data(
+ reporter_code=code,
+ period=str(year),
+ cmd_code="TOTAL",
+ flow_code="X",
+ max_records=top_n,
+ cl_code=cl_code,
+ )
+ if result.get("success"):
+ result["country"] = country_iso3
+ result["year"] = str(year)
+ result["flow"] = "exports"
+ return result
+
+ def get_country_imports(
+ self,
+ country_iso3: str,
+ year: Union[str, int],
+ top_n: int = 500,
+ cl_code: str = "HS",
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get all imports for a country in a given year.
+
+ Args:
+ country_iso3: ISO3 country code e.g. 'USA', 'CHN', 'DEU'
+ year: Year e.g. 2023
+ top_n: Max records
+ cl_code: Classification
+ """
+ code = COUNTRY_CODES.get(country_iso3.upper())
+ if code is None:
+ return ComtradeError("get_country_imports", f"Unknown ISO3 code: {country_iso3}. Use get_reference('reporter') for valid codes.").to_dict()
+
+ result = self.get_trade_data(
+ reporter_code=code,
+ period=str(year),
+ cmd_code="TOTAL",
+ flow_code="M",
+ max_records=top_n,
+ cl_code=cl_code,
+ )
+ if result.get("success"):
+ result["country"] = country_iso3
+ result["year"] = str(year)
+ result["flow"] = "imports"
+ return result
+
+ def get_bilateral_trade(
+ self,
+ reporter_iso3: str,
+ partner_iso3: str,
+ year: Union[str, int],
+ cl_code: str = "HS",
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get trade between two countries in a given year (both imports and exports).
+
+ Args:
+ reporter_iso3: Reporting country ISO3 e.g. 'USA'
+ partner_iso3: Partner country ISO3 e.g. 'CHN'
+ year: Year e.g. 2023
+ cl_code: Classification
+ """
+ r_code = COUNTRY_CODES.get(reporter_iso3.upper())
+ p_code = COUNTRY_CODES.get(partner_iso3.upper())
+
+ if r_code is None:
+ return ComtradeError("get_bilateral_trade", f"Unknown ISO3 code: {reporter_iso3}").to_dict()
+ if p_code is None:
+ return ComtradeError("get_bilateral_trade", f"Unknown ISO3 code: {partner_iso3}").to_dict()
+
+ result = self.get_trade_data(
+ reporter_code=r_code,
+ partner_code=p_code,
+ period=str(year),
+ cmd_code="TOTAL",
+ flow_code="X,M",
+ )
+ if result.get("success"):
+ result["reporter"] = reporter_iso3
+ result["partner"] = partner_iso3
+ result["year"] = str(year)
+ return result
+
+ def get_commodity_trade(
+ self,
+ commodity_code: str,
+ year: Union[str, int],
+ reporter_code: Union[str, int] = "all",
+ flow_code: str = "X,M",
+ cl_code: str = "HS",
+ max_records: int = 500,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get trade data for a specific commodity across all/selected reporters.
+
+ Args:
+ commodity_code: HS code e.g. '27' (mineral fuels), '8703' (cars), '0101' (horses)
+ year: Year e.g. 2023
+ reporter_code: Country code or 'all'
+ flow_code: 'X', 'M', or 'X,M'
+ cl_code: Classification
+ max_records: Max results
+ """
+ result = self.get_trade_data(
+ reporter_code=reporter_code,
+ period=str(year),
+ cmd_code=commodity_code,
+ flow_code=flow_code,
+ cl_code=cl_code,
+ max_records=max_records,
+ )
+ if result.get("success"):
+ result["commodity_code"] = commodity_code
+ result["commodity_desc"] = HS_CHAPTERS.get(commodity_code, "")
+ result["year"] = str(year)
+ return result
+
+ def get_trade_trend(
+ self,
+ reporter_iso3: str,
+ partner_iso3: Optional[str] = None,
+ start_year: int = 2018,
+ end_year: Optional[int] = None,
+ cmd_code: str = "TOTAL",
+ flow_code: str = "X,M",
+ cl_code: str = "HS",
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get multi-year trade trend for a country/pair.
+ Note: Free tier returns max 500 records across all years combined.
+
+ Args:
+ reporter_iso3: Reporting country ISO3 e.g. 'USA'
+ partner_iso3: Optional partner ISO3 (None = all partners)
+ start_year: Start year e.g. 2018
+ end_year: End year (defaults to last year)
+ cmd_code: Commodity code
+ flow_code: Trade flow
+ cl_code: Classification
+ """
+ if end_year is None:
+ end_year = datetime.now(timezone.utc).year - 1
+
+ r_code = COUNTRY_CODES.get(reporter_iso3.upper())
+ if r_code is None:
+ return ComtradeError("get_trade_trend", f"Unknown ISO3 code: {reporter_iso3}").to_dict()
+
+ p_code = None
+ if partner_iso3:
+ p_code = COUNTRY_CODES.get(partner_iso3.upper())
+ if p_code is None:
+ return ComtradeError("get_trade_trend", f"Unknown ISO3 code: {partner_iso3}").to_dict()
+
+ # Build comma-separated period string
+ periods = ",".join(str(y) for y in range(start_year, end_year + 1))
+
+ # Public preview endpoint does not support multi-year comma-separated periods.
+ # Without a subscription key, fetch year by year and merge.
+ if not self.subscription_key:
+ all_records = []
+ errors = []
+ for year in range(start_year, end_year + 1):
+ r = self.get_trade_data(
+ reporter_code=r_code,
+ period=str(year),
+ cmd_code=cmd_code,
+ flow_code=flow_code,
+ partner_code=p_code,
+ cl_code=cl_code,
+ max_records=500,
+ )
+ if r.get("success"):
+ all_records.extend(r.get("data", []))
+ else:
+ errors.append({"year": year, "error": r.get("error")})
+ return {
+ "success": True,
+ "reporter": reporter_iso3,
+ "partner": partner_iso3,
+ "start_year": start_year,
+ "end_year": end_year,
+ "data": all_records,
+ "count": len(all_records),
+ "errors": errors,
+ "note": "Multi-year trend fetched year-by-year (no subscription key). Each year capped at 500 records.",
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ result = self.get_trade_data(
+ reporter_code=r_code,
+ period=periods,
+ cmd_code=cmd_code,
+ flow_code=flow_code,
+ partner_code=p_code,
+ cl_code=cl_code,
+ max_records=500,
+ )
+ if result.get("success"):
+ result["reporter"] = reporter_iso3
+ result["partner"] = partner_iso3
+ result["start_year"] = start_year
+ result["end_year"] = end_year
+ return result
+
+ def get_top_trading_partners(
+ self,
+ reporter_iso3: str,
+ year: Union[str, int],
+ flow_code: str = "X",
+ max_records: int = 500,
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get a country's top trading partners for exports or imports.
+
+ Args:
+ reporter_iso3: Reporting country ISO3 e.g. 'USA'
+ year: Year e.g. 2023
+ flow_code: 'X' = exports, 'M' = imports
+ max_records: Max records (caps at 500 without key)
+ """
+ code = COUNTRY_CODES.get(reporter_iso3.upper())
+ if code is None:
+ return ComtradeError("get_top_trading_partners", f"Unknown ISO3 code: {reporter_iso3}").to_dict()
+
+ result = self.get_trade_data(
+ reporter_code=code,
+ period=str(year),
+ cmd_code="TOTAL",
+ flow_code=flow_code,
+ max_records=max_records,
+ include_desc=True,
+ )
+ if result.get("success"):
+ result["reporter"] = reporter_iso3
+ result["year"] = str(year)
+ result["flow"] = "exports" if flow_code == "X" else "imports"
+ return result
+
+ def get_energy_trade(
+ self,
+ reporter_iso3: str,
+ year: Union[str, int],
+ flow_code: str = "X,M",
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get energy commodity trade (HS Chapter 27 — mineral fuels, oil, gas, coal).
+
+ Args:
+ reporter_iso3: Country ISO3
+ year: Year
+ flow_code: 'X', 'M', or 'X,M'
+ """
+ return self.get_commodity_trade(
+ commodity_code="27",
+ year=year,
+ reporter_code=COUNTRY_CODES.get(reporter_iso3.upper(), reporter_iso3),
+ flow_code=flow_code,
+ )
+
+ def get_technology_trade(
+ self,
+ reporter_iso3: str,
+ year: Union[str, int],
+ flow_code: str = "X,M",
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get technology trade (HS 84 = machinery/nuclear reactors, HS 85 = electronics).
+ Fetches chapters 84 and 85 separately (public API doesn't support comma-separated cmdCode)
+ and merges results.
+
+ Args:
+ reporter_iso3: Country ISO3
+ year: Year
+ flow_code: 'X', 'M', or 'X,M'
+ """
+ code = COUNTRY_CODES.get(reporter_iso3.upper(), reporter_iso3)
+ all_records = []
+ errors = []
+ for ch in ["84", "85"]:
+ r = self.get_trade_data(
+ reporter_code=code,
+ period=str(year),
+ cmd_code=ch,
+ flow_code=flow_code,
+ )
+ if r.get("success"):
+ all_records.extend(r.get("data", []))
+ else:
+ errors.append({"chapter": ch, "error": r.get("error")})
+
+ return {
+ "success": True,
+ "reporter": reporter_iso3,
+ "year": str(year),
+ "sector": "technology",
+ "hs_chapters": ["84 - Machinery & Nuclear Reactors", "85 - Electrical Machinery & Electronics"],
+ "data": all_records,
+ "count": len(all_records),
+ "errors": errors,
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_agricultural_trade(
+ self,
+ reporter_iso3: str,
+ year: Union[str, int],
+ flow_code: str = "X,M",
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get agricultural commodity trade (HS 01–24 = food and agriculture).
+ Uses HS chapter 01 (aggregated level covers food/agriculture in TOTAL),
+ or fetches chapter by chapter if subscription key available.
+
+ Args:
+ reporter_iso3: Country ISO3
+ year: Year
+ flow_code: 'X', 'M', or 'X,M'
+ """
+ code = COUNTRY_CODES.get(reporter_iso3.upper(), reporter_iso3)
+ agri_chapters = [f"{i:02d}" for i in range(1, 25)] # HS 01-24
+
+ # With key: pass comma-separated. Without key: fetch per-chapter (expensive).
+ # As a practical default, fetch 3 most important chapters individually.
+ if self.subscription_key:
+ cmd_code = ",".join(agri_chapters)
+ result = self.get_trade_data(
+ reporter_code=code, period=str(year),
+ cmd_code=cmd_code, flow_code=flow_code, max_records=10000,
+ )
+ if result.get("success"):
+ result["reporter"] = reporter_iso3
+ result["sector"] = "agriculture"
+ return result
+ else:
+ # Without key: fetch key agri chapters (cereals=10, oilseeds=12, meat=02, dairy=04)
+ key_chapters = ["02", "04", "10", "12", "15", "17", "22", "23"]
+ all_records = []
+ errors = []
+ for ch in key_chapters:
+ r = self.get_trade_data(
+ reporter_code=code, period=str(year),
+ cmd_code=ch, flow_code=flow_code,
+ )
+ if r.get("success"):
+ all_records.extend(r.get("data", []))
+ else:
+ errors.append({"chapter": ch, "error": r.get("error")})
+ return {
+ "success": True,
+ "reporter": reporter_iso3,
+ "year": str(year),
+ "sector": "agriculture",
+ "hs_chapters_fetched": key_chapters,
+ "note": "Without subscription key, only key agri chapters fetched (02, 04, 10, 12, 15, 17, 22, 23). Subscribe for all 24 chapters.",
+ "data": all_records,
+ "count": len(all_records),
+ "errors": errors,
+ "timestamp": int(datetime.now(timezone.utc).timestamp()),
+ }
+
+ def get_pharmaceutical_trade(
+ self,
+ reporter_iso3: str,
+ year: Union[str, int],
+ flow_code: str = "X,M",
+ ) -> Dict[str, Any]:
+ """
+ Convenience: Get pharmaceutical trade (HS Chapter 30).
+
+ Args:
+ reporter_iso3: Country ISO3
+ year: Year
+ flow_code: 'X', 'M', or 'X,M'
+ """
+ return self.get_commodity_trade(
+ commodity_code="30",
+ year=year,
+ reporter_code=COUNTRY_CODES.get(reporter_iso3.upper(), reporter_iso3),
+ flow_code=flow_code,
+ )
+
+ def get_country_codes(self) -> Dict[str, Any]:
+ """
+ Convenience: Get UN numeric country codes for all reporters.
+ Returns the full reporter reference table including ISO3 codes.
+ Also includes the built-in quick-reference dict for common countries.
+ """
+ result = self.get_reference("reporter")
+ if result.get("success"):
+ result["note"] = "Use the 'id' field as reporterCode in API calls"
+ result["quick_reference"] = COUNTRY_CODES
+ return result
+
+ def get_iso_to_code_map(self) -> Dict[str, Any]:
+ """
+ Convenience: Get ISO3 → UN numeric code mapping for all countries.
+ """
+ url = f"{BASE_URL_FILES}/country_area_code_iso.json"
+ result = self._make_request(url, {})
+ if result.get("success"):
+ result["note"] = "Maps ISO3 alpha codes to UN numeric reporterCode values"
+ return result
+
+ def get_hs_codes(self, level: str = "HS") -> Dict[str, Any]:
+ """
+ Convenience: Get Harmonized System commodity codes reference table.
+
+ Args:
+ level: 'HS' for full HS, or specific revision e.g. 'H0','H1','H2','H3','H4','H5','H6'
+ """
+ return self.get_reference(level)
+
+
+# ==================== MAIN CLI ENTRYPOINT ====================
+
+def main():
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "success": False,
+ "error": "No command provided",
+ "available_commands": [
+ "trade_data <reporter_code> <period> [flow_code] [cmd_code] [freq_code] [cl_code] [max_records]",
+ "tariffline <reporter_code> <period> [flow_code] [cmd_code]",
+ "trade_balance <reporter_code> <period> [cmd_code]",
+ "bilateral <reporter_code> <partner_code> <period> [cmd_code]",
+ "data_availability [reporter_code] [type_code] [freq_code] [cl_code]",
+ "live_updates",
+ "list_references",
+ "get_reference <category>",
+ "metadata [reporter_code] [type_code] [freq_code] [cl_code]",
+ "country_exports <iso3> <year>",
+ "country_imports <iso3> <year>",
+ "bilateral_trade <reporter_iso3> <partner_iso3> <year>",
+ "commodity_trade <hs_code> <year> [reporter_code] [flow_code]",
+ "trade_trend <reporter_iso3> <start_year> [end_year] [partner_iso3] [cmd_code]",
+ "top_partners <reporter_iso3> <year> [flow_code]",
+ "energy_trade <reporter_iso3> <year> [flow_code]",
+ "tech_trade <reporter_iso3> <year> [flow_code]",
+ "agri_trade <reporter_iso3> <year> [flow_code]",
+ "pharma_trade <reporter_iso3> <year> [flow_code]",
+ "country_codes",
+ "hs_codes [classification]",
+ ],
+ "notes": [
+ "Without UN_COMTRADE_API_KEY: max 500 records per call (preview endpoints)",
+ "With UN_COMTRADE_API_KEY: 500 calls/day, up to 100,000 records per call",
+ "Register free at: https://comtradedeveloper.un.org/",
+ "flow_code: X=exports, M=imports, RX=re-exports, RM=re-imports",
+ "freq_code: A=annual, M=monthly",
+ "cl_code: HS, S1, S2, S3, S4, B4, B5",
+ "period: YYYY for annual, YYYYMM for monthly",
+ ],
+ "common_country_codes": COUNTRY_CODES,
+ "hs_chapter_reference": HS_CHAPTERS,
+ }, indent=2))
+ sys.exit(1)
+
+ command = sys.argv[1]
+ wrapper = UNComtradeWrapper()
+
+ try:
+ if command == "trade_data":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py trade_data <reporter_code> <period> [flow_code] [cmd_code] [freq_code] [cl_code] [max_records]"}))
+ sys.exit(1)
+ reporter_code = sys.argv[2]
+ period = sys.argv[3]
+ flow_code = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else "X,M"
+ cmd_code = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else "TOTAL"
+ freq_code = sys.argv[6] if len(sys.argv) > 6 and sys.argv[6] else "A"
+ cl_code = sys.argv[7] if len(sys.argv) > 7 and sys.argv[7] else "HS"
+ max_records = int(sys.argv[8]) if len(sys.argv) > 8 and sys.argv[8] else 500
+ result = wrapper.get_trade_data(
+ reporter_code=reporter_code, period=period, flow_code=flow_code,
+ cmd_code=cmd_code, freq_code=freq_code, cl_code=cl_code, max_records=max_records,
+ )
+ print(json.dumps(result, indent=2))
+
+ elif command == "tariffline":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py tariffline <reporter_code> <period> [flow_code] [cmd_code]"}))
+ sys.exit(1)
+ reporter_code = sys.argv[2]
+ period = sys.argv[3]
+ flow_code = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else "X,M"
+ cmd_code = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else "TOTAL"
+ result = wrapper.get_tariffline_data(reporter_code=reporter_code, period=period, flow_code=flow_code, cmd_code=cmd_code)
+ print(json.dumps(result, indent=2))
+
+ elif command == "trade_balance":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py trade_balance <reporter_code> <period> [cmd_code]"}))
+ sys.exit(1)
+ reporter_code = sys.argv[2]
+ period = sys.argv[3]
+ cmd_code = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else "TOTAL"
+ result = wrapper.get_trade_balance(reporter_code=reporter_code, period=period, cmd_code=cmd_code)
+ print(json.dumps(result, indent=2))
+
+ elif command == "bilateral":
+ if len(sys.argv) < 5:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py bilateral <reporter_code> <partner_code> <period> [cmd_code]"}))
+ sys.exit(1)
+ reporter_code = sys.argv[2]
+ partner_code = sys.argv[3]
+ period = sys.argv[4]
+ cmd_code = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else "TOTAL"
+ result = wrapper.get_bilateral_data(reporter_code=reporter_code, partner_code=partner_code, period=period, cmd_code=cmd_code)
+ print(json.dumps(result, indent=2))
+
+ elif command == "data_availability":
+ reporter_code = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] else None
+ type_code = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else "C"
+ freq_code = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else "A"
+ cl_code = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else "HS"
+ result = wrapper.get_data_availability(reporter_code=reporter_code, type_code=type_code, freq_code=freq_code, cl_code=cl_code)
+ print(json.dumps(result, indent=2))
+
+ elif command == "live_updates":
+ result = wrapper.get_live_updates()
+ print(json.dumps(result, indent=2))
+
+ elif command == "list_references":
+ result = wrapper.list_references()
+ print(json.dumps(result, indent=2))
+
+ elif command == "get_reference":
+ if len(sys.argv) < 3:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py get_reference <category> (e.g. reporter, partner, HS, flow)"}))
+ sys.exit(1)
+ result = wrapper.get_reference(sys.argv[2])
+ print(json.dumps(result, indent=2))
+
+ elif command == "metadata":
+ reporter_code = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] else None
+ type_code = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else "C"
+ freq_code = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else "A"
+ cl_code = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else "HS"
+ result = wrapper.get_metadata(reporter_code=reporter_code, type_code=type_code, freq_code=freq_code, cl_code=cl_code)
+ print(json.dumps(result, indent=2))
+
+ elif command == "country_exports":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py country_exports <iso3> <year> e.g. USA 2023"}))
+ sys.exit(1)
+ result = wrapper.get_country_exports(country_iso3=sys.argv[2], year=sys.argv[3])
+ print(json.dumps(result, indent=2))
+
+ elif command == "country_imports":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py country_imports <iso3> <year> e.g. CHN 2023"}))
+ sys.exit(1)
+ result = wrapper.get_country_imports(country_iso3=sys.argv[2], year=sys.argv[3])
+ print(json.dumps(result, indent=2))
+
+ elif command == "bilateral_trade":
+ if len(sys.argv) < 5:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py bilateral_trade <reporter_iso3> <partner_iso3> <year> e.g. USA CHN 2023"}))
+ sys.exit(1)
+ result = wrapper.get_bilateral_trade(reporter_iso3=sys.argv[2], partner_iso3=sys.argv[3], year=sys.argv[4])
+ print(json.dumps(result, indent=2))
+
+ elif command == "commodity_trade":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py commodity_trade <hs_code> <year> [reporter_code] [flow_code] e.g. 27 2023 842 X"}))
+ sys.exit(1)
+ hs_code = sys.argv[2]
+ year = sys.argv[3]
+ reporter_code = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else "all"
+ flow_code = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else "X,M"
+ result = wrapper.get_commodity_trade(commodity_code=hs_code, year=year, reporter_code=reporter_code, flow_code=flow_code)
+ print(json.dumps(result, indent=2))
+
+ elif command == "trade_trend":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py trade_trend <reporter_iso3> <start_year> [end_year] [partner_iso3] [cmd_code] e.g. USA 2018 2023 CHN TOTAL"}))
+ sys.exit(1)
+ reporter_iso3 = sys.argv[2]
+ start_year = int(sys.argv[3])
+ end_year = int(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4] else None
+ partner_iso3 = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else None
+ cmd_code = sys.argv[6] if len(sys.argv) > 6 and sys.argv[6] else "TOTAL"
+ result = wrapper.get_trade_trend(
+ reporter_iso3=reporter_iso3, start_year=start_year, end_year=end_year,
+ partner_iso3=partner_iso3, cmd_code=cmd_code,
+ )
+ print(json.dumps(result, indent=2))
+
+ elif command == "top_partners":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py top_partners <reporter_iso3> <year> [flow_code] e.g. USA 2023 X"}))
+ sys.exit(1)
+ flow_code = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else "X"
+ result = wrapper.get_top_trading_partners(reporter_iso3=sys.argv[2], year=sys.argv[3], flow_code=flow_code)
+ print(json.dumps(result, indent=2))
+
+ elif command == "energy_trade":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py energy_trade <reporter_iso3> <year> [flow_code] e.g. DEU 2023 M"}))
+ sys.exit(1)
+ flow_code = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else "X,M"
+ result = wrapper.get_energy_trade(reporter_iso3=sys.argv[2], year=sys.argv[3], flow_code=flow_code)
+ print(json.dumps(result, indent=2))
+
+ elif command == "tech_trade":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py tech_trade <reporter_iso3> <year> [flow_code] e.g. USA 2023 X"}))
+ sys.exit(1)
+ flow_code = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else "X,M"
+ result = wrapper.get_technology_trade(reporter_iso3=sys.argv[2], year=sys.argv[3], flow_code=flow_code)
+ print(json.dumps(result, indent=2))
+
+ elif command == "agri_trade":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py agri_trade <reporter_iso3> <year> [flow_code] e.g. BRA 2023 X"}))
+ sys.exit(1)
+ flow_code = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else "X,M"
+ result = wrapper.get_agricultural_trade(reporter_iso3=sys.argv[2], year=sys.argv[3], flow_code=flow_code)
+ print(json.dumps(result, indent=2))
+
+ elif command == "pharma_trade":
+ if len(sys.argv) < 4:
+ print(json.dumps({"success": False, "error": "Usage: un_comtrade_data.py pharma_trade <reporter_iso3> <year> [flow_code] e.g. DEU 2023 X"}))
+ sys.exit(1)
+ flow_code = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else "X,M"
+ result = wrapper.get_pharmaceutical_trade(reporter_iso3=sys.argv[2], year=sys.argv[3], flow_code=flow_code)
+ print(json.dumps(result, indent=2))
+
+ elif command == "country_codes":
+ result = wrapper.get_country_codes()
+ print(json.dumps(result, indent=2))
+
+ elif command == "iso_to_code_map":
+ result = wrapper.get_iso_to_code_map()
+ print(json.dumps(result, indent=2))
+
+ elif command == "hs_codes":
+ classification = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] else "HS"
+ result = wrapper.get_hs_codes(level=classification)
+ print(json.dumps(result, indent=2))
+
+ else:
+ print(json.dumps({
+ "success": False,
+ "error": f"Unknown command: {command}",
+ "tip": "Run without arguments to see all available commands",
+ }))
+ sys.exit(1)
+
+ except KeyboardInterrupt:
+ print(json.dumps({"success": False, "error": "Operation cancelled by user"}))
+ sys.exit(1)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": f"Unexpected error: {str(e)}"}))
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/__init__.py
new file mode 100644
index 000000000..737b7720b
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/__init__.py
@@ -0,0 +1 @@
+# VisionQuant Pattern Intelligence - Fincept Terminal Integration
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/backtester.py b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/backtester.py
new file mode 100644
index 000000000..22f8b1043
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/backtester.py
@@ -0,0 +1,264 @@
+"""
+VisionQuant Backtester
+Adaptive strategy backtest using pattern intelligence signals.
+
+CLI Protocol:
+ python backtester.py backtest '{"symbol":"AAPL","start":"20230101","end":"20250101","capital":100000}'
+"""
+
+import sys
+import json
+import os
+import numpy as np
+import pandas as pd
+from datetime import datetime
+
+SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
+if SCRIPT_DIR not in sys.path:
+ sys.path.insert(0, SCRIPT_DIR)
+
+from utils import fetch_ohlcv, json_response, output_json, parse_args
+
+
+def compute_rsi(close, period=14):
+ """Compute RSI for a close price series."""
+ deltas = np.diff(close)
+ gains = np.where(deltas > 0, deltas, 0)
+ losses = np.where(deltas < 0, -deltas, 0)
+
+ avg_gain = pd.Series(gains).rolling(period).mean().values
+ avg_loss = pd.Series(losses).rolling(period).mean().values
+
+ rs = avg_gain / (avg_loss + 1e-8)
+ rsi = 100 - (100 / (1 + rs))
+ # Pad to match original length
+ return np.concatenate([[50.0], rsi])
+
+
+def compute_macd_hist(close, fast=12, slow=26, signal=9):
+ """Compute MACD histogram."""
+ s = pd.Series(close)
+ ema_fast = s.ewm(span=fast).mean().values
+ ema_slow = s.ewm(span=slow).mean().values
+ macd = ema_fast - ema_slow
+ sig = pd.Series(macd).ewm(span=signal).mean().values
+ return macd - sig
+
+
+def run_backtest(symbol, start_date, end_date, initial_capital=100000.0,
+ stop_loss_pct=0.03, take_profit_pct=0.05, max_hold=20,
+ entry_rsi=40, exit_rsi=70, ma_period=60,
+ macd_fast=12, macd_slow=26, macd_signal=9):
+ """
+ Run a strategy backtest using MA + RSI + MACD signals.
+
+ The strategy:
+ - BUY when: price > MA AND RSI < entry_rsi AND MACD histogram turning positive
+ - SELL when: stop-loss hit, take-profit hit, max holding period, or RSI > exit_rsi
+
+ Returns dict with metrics and equity curve.
+ """
+ # Fetch data
+ df = fetch_ohlcv(symbol, start=start_date, end=end_date)
+ min_bars = ma_period + 1
+ if df is None or len(df) < min_bars:
+ return json_response("error", error=f"Insufficient data for {symbol} in date range")
+
+ close = df["Close"].values
+ dates = df.index.tolist()
+ n = len(close)
+
+ # Compute indicators
+ ma = pd.Series(close).rolling(ma_period).mean().values
+ rsi = compute_rsi(close)
+ macd_hist = compute_macd_hist(close, fast=macd_fast, slow=macd_slow, signal=macd_signal)
+
+ # Backtest state
+ capital = initial_capital
+ position = 0 # shares held
+ entry_price = 0.0
+ entry_idx = 0
+ trades = []
+ equity_curve = []
+
+ for i in range(ma_period, n):
+ current_price = close[i]
+ current_equity = capital + position * current_price
+
+ equity_curve.append({
+ "date": dates[i].strftime("%Y-%m-%d") if hasattr(dates[i], "strftime") else str(dates[i]),
+ "equity": round(current_equity, 2),
+ })
+
+ if position > 0:
+ # Check exit conditions
+ pnl_pct = (current_price - entry_price) / entry_price
+ hold_days = i - entry_idx
+
+ exit_signal = False
+ exit_reason = ""
+
+ if pnl_pct <= -stop_loss_pct:
+ exit_signal = True
+ exit_reason = "stop_loss"
+ elif pnl_pct >= take_profit_pct:
+ exit_signal = True
+ exit_reason = "take_profit"
+ elif hold_days >= max_hold:
+ exit_signal = True
+ exit_reason = "max_hold"
+ # Also exit if RSI > exit_rsi (overbought)
+ elif i < len(rsi) and rsi[i] > exit_rsi:
+ exit_signal = True
+ exit_reason = "rsi_overbought"
+
+ if exit_signal:
+ proceeds = position * current_price
+ profit = proceeds - (position * entry_price)
+ capital += proceeds
+ trades.append({
+ "entry_date": dates[entry_idx].strftime("%Y-%m-%d") if hasattr(dates[entry_idx], "strftime") else str(dates[entry_idx]),
+ "exit_date": dates[i].strftime("%Y-%m-%d") if hasattr(dates[i], "strftime") else str(dates[i]),
+ "entry_price": round(entry_price, 2),
+ "exit_price": round(current_price, 2),
+ "shares": position,
+ "profit": round(profit, 2),
+ "return_pct": round(pnl_pct * 100, 2),
+ "hold_days": hold_days,
+ "exit_reason": exit_reason,
+ })
+ position = 0
+ entry_price = 0.0
+
+ else:
+ # Check entry conditions
+ if i >= len(rsi) or i >= len(macd_hist):
+ continue
+ if np.isnan(ma[i]):
+ continue
+
+ price_above_ma = current_price > ma[i]
+ rsi_oversold = rsi[i] < entry_rsi
+ macd_positive = macd_hist[i] > 0 and (i > 0 and macd_hist[i] > macd_hist[i - 1])
+
+ if price_above_ma and rsi_oversold and macd_positive:
+ # Buy with full capital
+ shares = int(capital // current_price)
+ if shares > 0:
+ cost = shares * current_price
+ capital -= cost
+ position = shares
+ entry_price = current_price
+ entry_idx = i
+
+ # Close any remaining position
+ if position > 0:
+ final_price = close[-1]
+ proceeds = position * final_price
+ profit = proceeds - (position * entry_price)
+ capital += proceeds
+ trades.append({
+ "entry_date": dates[entry_idx].strftime("%Y-%m-%d") if hasattr(dates[entry_idx], "strftime") else str(dates[entry_idx]),
+ "exit_date": dates[-1].strftime("%Y-%m-%d") if hasattr(dates[-1], "strftime") else str(dates[-1]),
+ "entry_price": round(entry_price, 2),
+ "exit_price": round(final_price, 2),
+ "shares": position,
+ "profit": round(profit, 2),
+ "return_pct": round((final_price - entry_price) / entry_price * 100, 2),
+ "hold_days": n - 1 - entry_idx,
+ "exit_reason": "end_of_period",
+ })
+ position = 0
+
+ final_equity = capital
+ total_return_pct = (final_equity - initial_capital) / initial_capital * 100
+
+ # Compute metrics
+ wins = [t for t in trades if t["profit"] > 0]
+ losses = [t for t in trades if t["profit"] <= 0]
+ win_rate = len(wins) / len(trades) * 100 if trades else 0
+
+ # Sharpe ratio (annualized, from equity curve)
+ if len(equity_curve) >= 2:
+ equities = [e["equity"] for e in equity_curve]
+ daily_returns = np.diff(equities) / equities[:-1]
+ sharpe = float(np.mean(daily_returns) / (np.std(daily_returns) + 1e-8) * np.sqrt(252))
+ else:
+ sharpe = 0.0
+
+ # Max drawdown
+ if equity_curve:
+ equities = np.array([e["equity"] for e in equity_curve])
+ peak = np.maximum.accumulate(equities)
+ dd = (equities - peak) / peak
+ max_dd = float(dd.min()) * 100
+ else:
+ max_dd = 0.0
+
+ # Buy & hold comparison
+ bh_return = (close[-1] - close[ma_period]) / close[ma_period] * 100
+
+ return json_response("success", data={
+ "symbol": symbol,
+ "start_date": start_date,
+ "end_date": end_date,
+ "initial_capital": initial_capital,
+ "final_equity": round(final_equity, 2),
+ "return_pct": round(total_return_pct, 2),
+ "buy_hold_return_pct": round(bh_return, 2),
+ "sharpe_ratio": round(sharpe, 3),
+ "max_drawdown_pct": round(max_dd, 2),
+ "total_trades": len(trades),
+ "win_rate": round(win_rate, 1),
+ "wins": len(wins),
+ "losses": len(losses),
+ "avg_profit": round(np.mean([t["profit"] for t in wins]), 2) if wins else 0,
+ "avg_loss": round(np.mean([t["profit"] for t in losses]), 2) if losses else 0,
+ "avg_hold_days": round(np.mean([t["hold_days"] for t in trades]), 1) if trades else 0,
+ "trades": trades,
+ "equity_curve": equity_curve,
+ })
+
+
+def main():
+ command, params = parse_args()
+
+ if command == "backtest":
+ symbol = params.get("symbol", "")
+ start = params.get("start", params.get("start_date", ""))
+ end = params.get("end", params.get("end_date", ""))
+ capital = float(params.get("capital", params.get("initial_capital", 100000)))
+ stop_loss = float(params.get("stop_loss", 0.03))
+ take_profit = float(params.get("take_profit", 0.05))
+ max_hold = int(params.get("max_hold", 20))
+ entry_rsi = float(params.get("entry_rsi", 40))
+ exit_rsi = float(params.get("exit_rsi", 70))
+ ma_period = int(params.get("ma_period", 60))
+ macd_fast = int(params.get("macd_fast", 12))
+ macd_slow = int(params.get("macd_slow", 26))
+ macd_signal = int(params.get("macd_signal", 9))
+
+ if not symbol:
+ output_json(json_response("error", error="symbol is required"))
+ return
+ if not start or not end:
+ output_json(json_response("error", error="start and end dates are required"))
+ return
+
+ # Normalize dates
+ start = start.replace("-", "")
+ end = end.replace("-", "")
+ start_fmt = f"{start[:4]}-{start[4:6]}-{start[6:8]}"
+ end_fmt = f"{end[:4]}-{end[4:6]}-{end[6:8]}"
+
+ result = run_backtest(symbol, start_fmt, end_fmt, capital, stop_loss, take_profit,
+ max_hold, entry_rsi, exit_rsi, ma_period,
+ macd_fast, macd_slow, macd_signal)
+ output_json(result)
+
+ else:
+ output_json(json_response("error", error=f"Unknown command: {command}"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/engine.py b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/engine.py
new file mode 100644
index 000000000..ed619dd31
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/engine.py
@@ -0,0 +1,563 @@
+"""
+VisionQuant Pattern Search Engine
+Core pattern recognition engine adapted from VisionQuant-Pro for Fincept Terminal.
+
+CLI Protocol:
+ python engine.py search '{"symbol":"AAPL","date":"20250115","top_k":10}'
+ python engine.py status '{}'
+ python engine.py encode '{"image_path":"/path/to/img.png"}'
+"""
+
+import os
+import sys
+import json
+import bisect
+import numpy as np
+import pandas as pd
+from datetime import datetime
+
+os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
+os.environ["OMP_NUM_THREADS"] = "1"
+
+# Add parent for relative imports
+SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
+if SCRIPT_DIR not in sys.path:
+ sys.path.insert(0, SCRIPT_DIR)
+
+from utils import (
+ get_data_dir, get_model_path, get_index_path, get_meta_path,
+ fetch_ohlcv, generate_kline_image, ensure_dirs,
+ json_response, output_json, parse_args,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helper functions for DTW and shape features
+# ---------------------------------------------------------------------------
+
+def _dtw_distance(s1, s2, window=5):
+ """Fast DTW with Sakoe-Chiba band constraint. Returns normalized distance in [0, inf)."""
+ try:
+ n, m = len(s1), len(s2)
+ if n == 0 or m == 0:
+ return float("inf")
+ s1 = np.asarray(s1, dtype=float)
+ s2 = np.asarray(s2, dtype=float)
+ s1 = (s1 - s1.min()) / (s1.max() - s1.min() + 1e-8)
+ s2 = (s2 - s2.min()) / (s2.max() - s2.min() + 1e-8)
+
+ dtw = np.full((n + 1, m + 1), float("inf"))
+ dtw[0, 0] = 0
+ for i in range(1, n + 1):
+ j_start = max(1, i - window)
+ j_end = min(m + 1, i + window + 1)
+ for j in range(j_start, j_end):
+ cost = abs(s1[i - 1] - s2[j - 1])
+ dtw[i, j] = cost + min(dtw[i - 1, j], dtw[i, j - 1], dtw[i - 1, j - 1])
+ return dtw[n, m] / max(n, m)
+ except Exception:
+ return float("inf")
+
+
+def _extract_kline_features(prices):
+ """
+ Extract 8-dim shape feature vector:
+ [trend, change, volatility, high_pos, low_pos, head_trend, mid_trend, tail_trend]
+ """
+ try:
+ if len(prices) < 6:
+ return None
+ prices = np.asarray(prices, dtype=float)
+ n = len(prices)
+
+ trend = 1.0 if prices[-1] > prices[0] else -1.0
+ change = (prices[-1] - prices[0]) / (prices[0] + 1e-8)
+ change_norm = float(np.tanh(change * 10))
+
+ returns = np.diff(prices) / (prices[:-1] + 1e-8)
+ vol = float(np.std(returns) * np.sqrt(252))
+ vol_norm = min(vol / 0.5, 1.0)
+
+ high_pos = float(np.argmax(prices) / (n - 1))
+ low_pos = float(np.argmin(prices) / (n - 1))
+
+ seg = n // 3
+ head = (prices[seg] - prices[0]) / (prices[0] + 1e-8)
+ mid = (prices[2 * seg] - prices[seg]) / (prices[seg] + 1e-8)
+ tail = (prices[-1] - prices[2 * seg]) / (prices[2 * seg] + 1e-8)
+
+ return np.array([
+ trend, change_norm, vol_norm,
+ high_pos, low_pos,
+ float(np.tanh(head * 10)),
+ float(np.tanh(mid * 10)),
+ float(np.tanh(tail * 10)),
+ ])
+ except Exception:
+ return None
+
+
+# ---------------------------------------------------------------------------
+# VisionEngine - adapted for global markets via yfinance
+# ---------------------------------------------------------------------------
+
+class VisionEngine:
+ def __init__(self):
+ import torch
+ from torchvision import transforms
+
+ self.device = torch.device("cpu")
+ self.model = None
+ self.model_loaded = False
+
+ self.preprocess = transforms.Compose([
+ transforms.Resize((224, 224)),
+ transforms.ToTensor(),
+ ])
+
+ self.index = None
+ self.meta_data = []
+ self._path_map = {}
+ self._symbol_dates = {}
+
+ self._try_load_model()
+
+ def _try_load_model(self):
+ import torch
+ model_path = get_model_path()
+ if not os.path.exists(model_path):
+ return False
+ try:
+ from models.attention_cae import AttentionCAE
+ self.model = AttentionCAE(latent_dim=1024, num_attention_heads=8).to(self.device)
+ state_dict = torch.load(model_path, map_location=self.device, weights_only=True)
+ self.model.load_state_dict(state_dict)
+ self.model.eval()
+ self.model_loaded = True
+ return True
+ except Exception as e:
+ self.model_loaded = False
+ return False
+
+ def reload_index(self):
+ import faiss
+ index_file = get_index_path()
+ meta_file = get_meta_path()
+
+ if not os.path.exists(index_file):
+ return False
+ try:
+ self.index = faiss.read_index(index_file)
+ except Exception:
+ return False
+
+ if os.path.exists(meta_file):
+ df = pd.read_csv(meta_file, dtype=str, engine="c", low_memory=False)
+ self.meta_data = df.to_dict("records")
+ else:
+ return False
+
+ self._build_path_index()
+ return True
+
+ def _build_path_index(self):
+ self._path_map = {}
+ self._symbol_dates = {}
+ for info in self.meta_data:
+ sym = str(info.get("symbol", ""))
+ date_str = str(info.get("date", "")).replace("-", "")
+ path = info.get("path")
+ if not sym or not date_str or not path:
+ continue
+ self._path_map[(sym, date_str)] = path
+ try:
+ self._symbol_dates.setdefault(sym, []).append(int(date_str))
+ except Exception:
+ continue
+ for dates in self._symbol_dates.values():
+ dates.sort()
+
+ def find_image_path(self, symbol, date_str, allow_nearest=True):
+ date_n = str(date_str).replace("-", "")
+ path = self._path_map.get((symbol, date_n))
+ if path and os.path.exists(path):
+ return path
+ if allow_nearest:
+ dates = self._symbol_dates.get(symbol)
+ try:
+ target = int(date_n)
+ except Exception:
+ return None
+ if dates:
+ idx = bisect.bisect_right(dates, target) - 1
+ if idx >= 0:
+ nearest = f"{dates[idx]:08d}"
+ path = self._path_map.get((symbol, nearest))
+ if path and os.path.exists(path):
+ return path
+ return None
+
+ def _image_to_vector(self, img_path):
+ import torch
+ from PIL import Image
+ try:
+ with Image.open(img_path) as img:
+ img = img.convert("RGB")
+ tensor = self.preprocess(img).unsqueeze(0).to(self.device)
+ with torch.no_grad():
+ feature = self.model.encode(tensor)
+ return feature.cpu().numpy().flatten()
+ except Exception:
+ return None
+
+ def _vector_score_to_similarity(self, score):
+ import faiss as _faiss
+ try:
+ if self.index is not None and self.index.metric_type == _faiss.METRIC_INNER_PRODUCT:
+ sim = (float(score) + 1.0) / 2.0
+ else:
+ sim = 1.0 / (1.0 + max(float(score), 0.0))
+ return float(np.clip(sim, 0.0, 1.0))
+ except Exception:
+ return 0.0
+
+ def _parse_date(self, date_str):
+ for fmt in ("%Y%m%d", "%Y-%m-%d"):
+ try:
+ return datetime.strptime(str(date_str), fmt)
+ except Exception:
+ continue
+ return None
+
+ # ------------------------------------------------------------------
+ # Core search
+ # ------------------------------------------------------------------
+
+ def search_similar_patterns(self, symbol, date_str=None, top_k=10, lookback=60, config=None):
+ """
+ Search for similar K-line patterns.
+
+ 1. Fetch OHLCV via yfinance
+ 2. Generate candlestick image
+ 3. Encode to 1024-dim vector
+ 4. FAISS coarse search -> 2000 candidates
+ 5. DTW + correlation + shape feature re-ranking
+ 6. Triple Barrier labeling of each match
+ 7. Return top-K results with win-rate stats
+
+ Args:
+ config: dict with optional keys: isolation_days, dtw_window,
+ w_dtw, w_corr, w_shape, w_visual, trend_bonus,
+ faiss_multiplier, hq_dtw_threshold,
+ tb_upper, tb_lower, tb_max_hold
+
+ Returns dict ready for JSON serialization.
+ """
+ import faiss as _faiss
+ cfg = config or {}
+
+ # Extract configurable constants
+ isolation_days = int(cfg.get("isolation_days", 20))
+ dtw_window = int(cfg.get("dtw_window", 5))
+ w_dtw = float(cfg.get("w_dtw", 0.50))
+ w_corr = float(cfg.get("w_corr", 0.30))
+ w_shape = float(cfg.get("w_shape", 0.15))
+ w_visual = float(cfg.get("w_visual", 0.05))
+ trend_bonus = float(cfg.get("trend_bonus", 0.08))
+ faiss_multiplier = int(cfg.get("faiss_multiplier", 200))
+ hq_dtw_threshold = float(cfg.get("hq_dtw_threshold", 0.8))
+ tb_upper = float(cfg.get("tb_upper", 0.05))
+ tb_lower = float(cfg.get("tb_lower", 0.03))
+ tb_max_hold = int(cfg.get("tb_max_hold", 20))
+
+ if self.index is None:
+ if not self.reload_index():
+ return json_response("error", error="FAISS index not loaded. Run setup first.")
+
+ if not self.model_loaded:
+ if not self._try_load_model():
+ return json_response("error", error="Model not loaded. Run setup first.")
+
+ # 1. Fetch price data
+ df = fetch_ohlcv(symbol, period="1y")
+ if df is None or len(df) < lookback + 1:
+ return json_response("error", error=f"Insufficient data for {symbol}")
+
+ # Determine target date slice
+ if date_str:
+ target_dt = pd.to_datetime(date_str)
+ mask = df.index <= target_dt
+ df_slice = df[mask]
+ else:
+ df_slice = df
+
+ if len(df_slice) < lookback:
+ return json_response("error", error="Not enough historical bars before target date")
+
+ query_df = df_slice.tail(lookback)
+ query_prices = query_df["Close"].values
+
+ # 2. Generate query image
+ data_dir = ensure_dirs()
+ img_dir = os.path.join(data_dir, "images", "query")
+ os.makedirs(img_dir, exist_ok=True)
+ img_path = os.path.join(img_dir, f"{symbol}_{date_str or 'latest'}.png")
+ generate_kline_image(query_df, img_path, window=lookback)
+
+ # 3. Encode to vector
+ vec = self._image_to_vector(img_path)
+ if vec is None:
+ return json_response("error", error="Failed to encode query image")
+
+ vec = vec.astype("float32").reshape(1, -1)
+ _faiss.normalize_L2(vec)
+
+ # 4. FAISS coarse search
+ search_k = max(top_k * faiss_multiplier, 2000)
+ D, I = self.index.search(vec, search_k)
+
+ # 5. Re-rank with DTW + correlation + shape features
+ query_20 = query_prices[-20:] if len(query_prices) >= 20 else query_prices
+ query_feat = _extract_kline_features(query_20)
+ query_trend = 1 if query_20[-1] > query_20[0] else -1
+
+ candidates = []
+ seen_dates = {}
+ price_cache = {}
+
+ for vector_score, idx in zip(D[0], I[0]):
+ if idx >= len(self.meta_data):
+ continue
+ info = self.meta_data[idx]
+ sym = str(info.get("symbol", ""))
+ d_str = str(info.get("date", ""))
+ dt = self._parse_date(d_str)
+ if dt is None:
+ continue
+
+ # Time isolation
+ conflict = False
+ if sym in seen_dates:
+ for ed in seen_dates[sym]:
+ if abs((dt - ed).days) < isolation_days:
+ conflict = True
+ break
+ if conflict:
+ continue
+
+ # Compute price-based metrics
+ dtw_sim = None
+ corr_norm = 0.5
+ feature_sim = 0.5
+ trend_match = None
+ match_prices = None
+
+ try:
+ if sym not in price_cache:
+ price_cache[sym] = fetch_ohlcv(sym, period="5y")
+ mdf = price_cache[sym]
+ if mdf is not None and not mdf.empty:
+ mdf_idx = pd.to_datetime(mdf.index)
+ closest = mdf_idx[mdf_idx <= dt]
+ if len(closest) >= 20:
+ loc = len(closest) - 1
+ match_prices = mdf.iloc[loc - 19:loc + 1]["Close"].values
+ if len(match_prices) == 20:
+ # DTW
+ dtw_dist = _dtw_distance(query_20, match_prices, window=dtw_window)
+ dtw_sim = max(0, 1.0 - dtw_dist)
+ # Correlation
+ qn = (query_20 - query_20.mean()) / (query_20.std() + 1e-8)
+ mn = (match_prices - match_prices.mean()) / (match_prices.std() + 1e-8)
+ corr = np.corrcoef(qn, mn)[0, 1]
+ if not np.isnan(corr):
+ corr_norm = (float(corr) + 1.0) / 2.0
+ # Shape features
+ m_feat = _extract_kline_features(match_prices)
+ if query_feat is not None and m_feat is not None:
+ cos = np.dot(query_feat, m_feat) / (
+ np.linalg.norm(query_feat) * np.linalg.norm(m_feat) + 1e-8
+ )
+ feature_sim = (cos + 1.0) / 2.0
+ trend_match = 1 if m_feat[0] == query_trend else 0
+ except Exception:
+ pass
+
+ sim_score = self._vector_score_to_similarity(vector_score)
+
+ # Weighted score using configurable weights
+ if dtw_sim is not None:
+ combined = w_dtw * dtw_sim + w_corr * corr_norm + w_shape * feature_sim + w_visual * sim_score
+ else:
+ combined = sim_score * 0.3
+
+ # Trend bonus/penalty
+ if trend_match == 1:
+ combined += trend_bonus
+ elif trend_match == 0:
+ combined -= trend_bonus
+
+ candidates.append({
+ "symbol": sym,
+ "date": d_str,
+ "score": round(float(combined), 4),
+ "dtw_sim": round(float(dtw_sim), 4) if dtw_sim is not None else None,
+ "correlation": round(float(corr_norm * 2 - 1), 4) if corr_norm != 0.5 else None,
+ "feature_sim": round(float(feature_sim), 4),
+ "visual_sim": round(float(sim_score), 4),
+ "trend_match": trend_match,
+ "path": info.get("path"),
+ })
+
+ seen_dates.setdefault(sym, []).append(dt)
+
+ # Early exit if enough high-quality candidates
+ hq = [c for c in candidates if c.get("dtw_sim") is not None and c["dtw_sim"] > hq_dtw_threshold]
+ if len(hq) >= top_k * 3:
+ break
+
+ candidates.sort(key=lambda x: x["score"], reverse=True)
+ top_matches = candidates[:top_k]
+
+ # 6. Triple Barrier labeling for each match
+ from models.triple_barrier import TripleBarrierLabeler, calculate_win_loss_ratio
+ labeler = TripleBarrierLabeler(upper_barrier=tb_upper, lower_barrier=tb_lower, max_holding_period=tb_max_hold)
+
+ tb_results = []
+ for m in top_matches:
+ try:
+ sym = m["symbol"]
+ if sym not in price_cache:
+ price_cache[sym] = fetch_ohlcv(sym, period="5y")
+ mdf = price_cache[sym]
+ if mdf is None or mdf.empty:
+ continue
+ mdt = self._parse_date(m["date"])
+ if mdt is None:
+ continue
+ mdf_idx = pd.to_datetime(mdf.index)
+ loc_mask = mdf_idx <= mdt
+ if loc_mask.sum() == 0:
+ continue
+ loc = loc_mask.sum() - 1
+ if loc + labeler.max_hold >= len(mdf):
+ continue
+ entry_price = float(mdf.iloc[loc]["Close"])
+ future = mdf.iloc[loc:loc + labeler.max_hold + 1]["Close"]
+ rets = (future.iloc[1:] - entry_price) / entry_price
+ label, hit_day, hit_type = labeler._check_barriers(rets)
+ tb_results.append({
+ "symbol": sym,
+ "date": m["date"],
+ "label": label,
+ "hit_day": hit_day,
+ "hit_type": hit_type,
+ "final_return": round(float(rets.iloc[-1]) * 100, 2) if len(rets) > 0 else 0,
+ })
+ m["tb_label"] = label
+ m["tb_hit_day"] = hit_day
+ m["tb_hit_type"] = hit_type
+ m["final_return_pct"] = round(float(rets.iloc[-1]) * 100, 2) if len(rets) > 0 else 0
+ except Exception:
+ continue
+
+ # 7. Compute win-rate stats
+ total_tb = len(tb_results)
+ bullish = sum(1 for r in tb_results if r["label"] == 1)
+ bearish = sum(1 for r in tb_results if r["label"] == -1)
+ neutral = sum(1 for r in tb_results if r["label"] == 0)
+ win_rate, wl_ratio = calculate_win_loss_ratio(tb_results)
+
+ avg_return = np.mean([r["final_return"] for r in tb_results]) if tb_results else 0
+ avg_hit_day = np.mean([r["hit_day"] for r in tb_results]) if tb_results else 0
+
+ return json_response("success", data={
+ "matches": top_matches,
+ "query_info": {
+ "symbol": symbol,
+ "date": date_str or "latest",
+ "bars": lookback,
+ },
+ "win_rate_stats": {
+ "total": total_tb,
+ "bullish": bullish,
+ "neutral": neutral,
+ "bearish": bearish,
+ "win_rate": round(win_rate * 100, 1),
+ "win_loss_ratio": round(wl_ratio, 2),
+ "avg_return_pct": round(float(avg_return), 2),
+ "avg_holding_days": round(float(avg_hit_day), 1),
+ },
+ })
+
+ def get_status(self):
+ index_exists = os.path.exists(get_index_path())
+ model_exists = os.path.exists(get_model_path())
+ meta_exists = os.path.exists(get_meta_path())
+ n_records = len(self.meta_data) if self.meta_data else 0
+ if not n_records and meta_exists:
+ try:
+ n_records = sum(1 for _ in open(get_meta_path())) - 1
+ except Exception:
+ pass
+
+ return json_response("success", data={
+ "index_ready": index_exists and model_exists and meta_exists,
+ "model_exists": model_exists,
+ "index_exists": index_exists,
+ "meta_exists": meta_exists,
+ "n_records": n_records,
+ "model_loaded": self.model_loaded,
+ "data_dir": get_data_dir(),
+ })
+
+ def encode_image(self, image_path):
+ if not self.model_loaded:
+ if not self._try_load_model():
+ return json_response("error", error="Model not loaded")
+ vec = self._image_to_vector(image_path)
+ if vec is None:
+ return json_response("error", error="Failed to encode image")
+ return json_response("success", data={
+ "vector": vec.tolist(),
+ "dim": len(vec),
+ })
+
+
+# ---------------------------------------------------------------------------
+# CLI entry point
+# ---------------------------------------------------------------------------
+
+def main():
+ command, params = parse_args()
+
+ if command == "status":
+ engine = VisionEngine()
+ output_json(engine.get_status())
+
+ elif command == "search":
+ engine = VisionEngine()
+ symbol = params.get("symbol", "")
+ date = params.get("date")
+ top_k = int(params.get("top_k", 10))
+ lookback = int(params.get("lookback", 60))
+ if not symbol:
+ output_json(json_response("error", error="symbol is required"))
+ return
+ result = engine.search_similar_patterns(symbol, date_str=date, top_k=top_k, lookback=lookback, config=params)
+ output_json(result)
+
+ elif command == "encode":
+ engine = VisionEngine()
+ image_path = params.get("image_path", "")
+ if not image_path or not os.path.exists(image_path):
+ output_json(json_response("error", error="Valid image_path is required"))
+ return
+ output_json(engine.encode_image(image_path))
+
+ else:
+ output_json(json_response("error", error=f"Unknown command: {command}"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/models/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/models/__init__.py
new file mode 100644
index 000000000..90629c0da
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/models/__init__.py
@@ -0,0 +1 @@
+# VisionQuant Models
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/models/attention_cae.py b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/models/attention_cae.py
new file mode 100644
index 000000000..f198c93ed
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/models/attention_cae.py
@@ -0,0 +1,241 @@
+"""
+AttentionCAE: Self-Attention Enhanced Convolutional Autoencoder
+Adapted from VisionQuant-Pro for Fincept Terminal integration.
+
+Architecture:
+ Input: 224x224x3 (K-line chart image)
+ -> CNN Encoder (4 layers): 224->112->56->28->14, channels: 32->64->128->256
+ -> Multi-Head Self-Attention (8 heads) on 14x14x256 feature map
+ -> Adaptive Pooling + Linear -> 1024-dim L2-normalized latent vector
+ -> CNN Decoder (4 layers): 14->28->56->112->224
+ Output: 224x224x3 (reconstructed image)
+
+Training objective: minimize MSE(input, output)
+The 1024-dim latent vector is used for FAISS similarity search.
+"""
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+from typing import Tuple, Optional
+
+
+class MultiHeadSelfAttention(nn.Module):
+ """
+ Multi-head self-attention module for capturing global dependencies
+ in K-line chart feature maps (e.g. symmetry in head-and-shoulders patterns).
+ """
+
+ def __init__(self, in_channels: int, num_heads: int = 8, dropout: float = 0.1):
+ super().__init__()
+ assert in_channels % num_heads == 0
+ self.num_heads = num_heads
+ self.head_dim = in_channels // num_heads
+ self.scale = self.head_dim ** -0.5
+
+ self.query = nn.Conv2d(in_channels, in_channels, kernel_size=1)
+ self.key = nn.Conv2d(in_channels, in_channels, kernel_size=1)
+ self.value = nn.Conv2d(in_channels, in_channels, kernel_size=1)
+ self.out_proj = nn.Conv2d(in_channels, in_channels, kernel_size=1)
+ self.norm = nn.LayerNorm(in_channels)
+ self.dropout = nn.Dropout(dropout)
+
+ def forward(self, x: torch.Tensor, attn_bias: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
+ B, C, H, W = x.shape
+
+ q = self.query(x).view(B, self.num_heads, self.head_dim, H * W)
+ k = self.key(x).view(B, self.num_heads, self.head_dim, H * W)
+ v = self.value(x).view(B, self.num_heads, self.head_dim, H * W)
+
+ attn = torch.matmul(q.transpose(-2, -1), k) * self.scale
+
+ if attn_bias is not None:
+ if attn_bias.dim() == 2:
+ attn_bias = attn_bias.unsqueeze(1).unsqueeze(2)
+ elif attn_bias.dim() == 3:
+ attn_bias = attn_bias.unsqueeze(2)
+ attn = attn + attn_bias
+
+ attn_weights = F.softmax(attn, dim=-1)
+ attn_weights = self.dropout(attn_weights)
+
+ out = torch.matmul(v, attn_weights.transpose(-2, -1))
+ out = out.view(B, C, H, W)
+ out = self.out_proj(out)
+
+ # Residual + LayerNorm
+ out = out + x
+ out = out.permute(0, 2, 3, 1)
+ out = self.norm(out)
+ out = out.permute(0, 3, 1, 2)
+
+ return out, attn_weights
+
+
+class AttentionCAE(nn.Module):
+ """
+ Convolutional Autoencoder with Self-Attention for K-line pattern recognition.
+ Produces 1024-dim L2-normalized vectors for FAISS similarity search.
+ """
+
+ def __init__(
+ self,
+ latent_dim: int = 1024,
+ num_attention_heads: int = 8,
+ dropout: float = 0.1,
+ use_attention: bool = True,
+ feature_dim: int = 256,
+ ):
+ super().__init__()
+ self.latent_dim = latent_dim
+ self.use_attention = use_attention
+ self.feature_dim = feature_dim
+
+ # Encoder: 224->112->56->28->14
+ self.encoder = nn.Sequential(
+ nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1),
+ nn.BatchNorm2d(32),
+ nn.LeakyReLU(0.2, inplace=True),
+ nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1),
+ nn.BatchNorm2d(64),
+ nn.LeakyReLU(0.2, inplace=True),
+ nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1),
+ nn.BatchNorm2d(128),
+ nn.LeakyReLU(0.2, inplace=True),
+ nn.Conv2d(128, feature_dim, kernel_size=3, stride=2, padding=1),
+ nn.BatchNorm2d(feature_dim),
+ nn.LeakyReLU(0.2, inplace=True),
+ )
+
+ # Self-Attention
+ if use_attention:
+ self.attention = MultiHeadSelfAttention(
+ in_channels=feature_dim,
+ num_heads=num_attention_heads,
+ dropout=dropout,
+ )
+
+ # Latent projection: feature_dim -> latent_dim
+ self.to_latent = nn.Sequential(
+ nn.AdaptiveAvgPool2d((1, 1)),
+ nn.Flatten(),
+ nn.Linear(feature_dim, latent_dim),
+ nn.LayerNorm(latent_dim),
+ )
+
+ # Decoder
+ self.from_latent = nn.Sequential(
+ nn.Linear(latent_dim, feature_dim * 14 * 14),
+ nn.LeakyReLU(0.2, inplace=True),
+ )
+
+ self.decoder = nn.Sequential(
+ nn.ConvTranspose2d(feature_dim, 128, kernel_size=3, stride=2, padding=1, output_padding=1),
+ nn.BatchNorm2d(128),
+ nn.LeakyReLU(0.2, inplace=True),
+ nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, output_padding=1),
+ nn.BatchNorm2d(64),
+ nn.LeakyReLU(0.2, inplace=True),
+ nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, output_padding=1),
+ nn.BatchNorm2d(32),
+ nn.LeakyReLU(0.2, inplace=True),
+ nn.ConvTranspose2d(32, 3, kernel_size=3, stride=2, padding=1, output_padding=1),
+ nn.Sigmoid(),
+ )
+
+ self._last_attention_weights = None
+
+ def encode(self, x: torch.Tensor, event_bias: Optional[torch.Tensor] = None) -> torch.Tensor:
+ """Encode image to L2-normalized latent vector [B, latent_dim]."""
+ features = self.encoder(x)
+ if self.use_attention:
+ features, attn_weights = self.attention(features, attn_bias=event_bias)
+ self._last_attention_weights = attn_weights
+ latent = self.to_latent(features)
+ latent = F.normalize(latent, p=2, dim=1)
+ return latent
+
+ def decode(self, z: torch.Tensor) -> torch.Tensor:
+ """Decode latent vector to reconstructed image [B, 3, 224, 224]."""
+ x = self.from_latent(z)
+ x = x.view(-1, self.feature_dim, 14, 14)
+ return self.decoder(x)
+
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ latent = self.encode(x)
+ recon = self.decode(latent)
+ return recon, latent
+
+ def get_attention_weights(self, x: torch.Tensor) -> torch.Tensor:
+ if not self.use_attention:
+ raise ValueError("Attention is disabled")
+ self.eval()
+ with torch.no_grad():
+ features = self.encoder(x)
+ _, attn_weights = self.attention(features)
+ return attn_weights
+
+ def get_attention_map(self, x: torch.Tensor, head_idx: int = 0) -> np.ndarray:
+ if x.dim() == 3:
+ x = x.unsqueeze(0)
+ attn = self.get_attention_weights(x)
+ center_idx = 98 # 14*14/2
+ attn_map = attn[0, head_idx, center_idx, :].cpu().numpy().reshape(14, 14)
+ return np.kron(attn_map, np.ones((16, 16)))
+
+
+class AttentionCAETrainer:
+ """Trainer for AttentionCAE model."""
+
+ def __init__(self, model: AttentionCAE, device: str = None, lr: float = 1e-3, weight_decay: float = 1e-5):
+ if device is None:
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+ self.device = device
+ self.model = model.to(device)
+ self.optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=weight_decay)
+ self.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(self.optimizer, T_max=100, eta_min=1e-6)
+ self.criterion = nn.MSELoss()
+
+ def train_epoch(self, dataloader) -> float:
+ self.model.train()
+ total_loss = 0
+ for images, _ in dataloader:
+ images = images.to(self.device)
+ recon, latent = self.model(images)
+ loss = self.criterion(recon, images)
+ self.optimizer.zero_grad()
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=1.0)
+ self.optimizer.step()
+ total_loss += loss.item()
+ self.scheduler.step()
+ return total_loss / max(len(dataloader), 1)
+
+ @torch.no_grad()
+ def validate(self, dataloader) -> float:
+ self.model.eval()
+ total_loss = 0
+ for images, _ in dataloader:
+ images = images.to(self.device)
+ recon, _ = self.model(images)
+ total_loss += self.criterion(recon, images).item()
+ return total_loss / max(len(dataloader), 1)
+
+ def save_checkpoint(self, path: str, epoch: int, loss: float):
+ torch.save({
+ "epoch": epoch,
+ "model_state_dict": self.model.state_dict(),
+ "optimizer_state_dict": self.optimizer.state_dict(),
+ "loss": loss,
+ }, path)
+
+ def load_checkpoint(self, path: str):
+ checkpoint = torch.load(path, map_location=self.device)
+ self.model.load_state_dict(checkpoint["model_state_dict"])
+ self.optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
+ return checkpoint["epoch"], checkpoint["loss"]
+
+
+# Compatibility alias
+QuantCAE = AttentionCAE
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/models/triple_barrier.py b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/models/triple_barrier.py
new file mode 100644
index 000000000..3d1348f22
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/models/triple_barrier.py
@@ -0,0 +1,207 @@
+"""
+Triple Barrier Method - Industry-standard financial labeling
+Based on: Lopez de Prado, M. (2018). Advances in Financial Machine Learning.
+
+Labels:
+ +1: Price hit upper barrier (take-profit) first -> Bullish
+ 0: Timed out without hitting either barrier -> Neutral
+ -1: Price hit lower barrier (stop-loss) first -> Bearish
+"""
+
+import pandas as pd
+import numpy as np
+from typing import Tuple, Dict, List
+
+
+class TripleBarrierLabeler:
+ """
+ Generate triple-barrier labels for a price series.
+
+ Usage:
+ labeler = TripleBarrierLabeler(upper=0.05, lower=0.03, max_hold=20)
+ labels = labeler.generate_labels(price_series)
+ """
+
+ def __init__(self, upper_barrier: float = 0.05, lower_barrier: float = 0.03, max_holding_period: int = 20):
+ self.upper = upper_barrier
+ self.lower = lower_barrier # stored positive, negated when checking
+ self.max_hold = max_holding_period
+
+ def generate_labels(self, prices: pd.Series, return_details: bool = False):
+ if len(prices) < self.max_hold + 1:
+ raise ValueError(f"Price series too short ({len(prices)}), need at least {self.max_hold + 1}")
+
+ labels = pd.Series(index=prices.index, dtype=float)
+ labels[:] = np.nan
+ details = [] if return_details else None
+
+ for i in range(len(prices) - self.max_hold):
+ entry_price = prices.iloc[i]
+ entry_date = prices.index[i]
+ future_prices = prices.iloc[i + 1:i + 1 + self.max_hold]
+ future_returns = (future_prices - entry_price) / entry_price
+ label, hit_day, hit_type = self._check_barriers(future_returns)
+ labels.iloc[i] = label
+
+ if return_details:
+ details.append({
+ "date": entry_date,
+ "entry_price": entry_price,
+ "label": label,
+ "hit_day": hit_day,
+ "hit_type": hit_type,
+ "max_return": future_returns.max(),
+ "min_return": future_returns.min(),
+ "final_return": future_returns.iloc[-1] if len(future_returns) > 0 else 0,
+ })
+
+ if return_details:
+ return labels, pd.DataFrame(details)
+ return labels
+
+ def _check_barriers(self, returns: pd.Series) -> Tuple[int, int, str]:
+ upper_touch = returns >= self.upper
+ lower_touch = returns <= -self.lower
+
+ upper_idx = np.where(upper_touch)[0]
+ first_upper = upper_idx[0] if len(upper_idx) > 0 else np.inf
+
+ lower_idx = np.where(lower_touch)[0]
+ first_lower = lower_idx[0] if len(lower_idx) > 0 else np.inf
+
+ if first_upper == np.inf and first_lower == np.inf:
+ return 0, self.max_hold, "timeout"
+ elif first_upper <= first_lower:
+ return 1, int(first_upper) + 1, "upper"
+ else:
+ return -1, int(first_lower) + 1, "lower"
+
+ def get_statistics(self, labels: pd.Series) -> Dict:
+ valid = labels.dropna()
+ total = len(valid)
+ if total == 0:
+ return {"total": 0, "bullish": 0, "neutral": 0, "bearish": 0}
+
+ bullish = int((valid == 1).sum())
+ neutral = int((valid == 0).sum())
+ bearish = int((valid == -1).sum())
+
+ return {
+ "total": total,
+ "bullish": bullish,
+ "bullish_pct": round(bullish / total * 100, 2),
+ "neutral": neutral,
+ "neutral_pct": round(neutral / total * 100, 2),
+ "bearish": bearish,
+ "bearish_pct": round(bearish / total * 100, 2),
+ "bull_bear_ratio": round(bullish / bearish, 2) if bearish > 0 else float("inf"),
+ }
+
+
+class TripleBarrierPredictor:
+ """Predict triple-barrier outcomes from historical pattern matches."""
+
+ def __init__(self, labeler: TripleBarrierLabeler = None):
+ self.labeler = labeler or TripleBarrierLabeler()
+
+ def predict_from_matches(self, matches: List[Dict], min_matches: int = 5) -> Dict:
+ """
+ Predict outcome from Top-K similar pattern matches.
+ Each match dict must have: symbol, date, score, future_prices (pd.Series of Close).
+ """
+ results = []
+
+ for match in matches:
+ try:
+ entry_price = match["entry_price"]
+ future_prices = match["future_prices"]
+ score = match.get("score", 0.5)
+
+ if future_prices is None or len(future_prices) < 2:
+ continue
+
+ returns = (future_prices - entry_price) / entry_price
+ label, hit_day, hit_type = self.labeler._check_barriers(returns)
+
+ results.append({
+ "symbol": match.get("symbol", ""),
+ "date": match.get("date", ""),
+ "score": score,
+ "label": label,
+ "hit_day": hit_day,
+ "hit_type": hit_type,
+ "max_return": float(returns.max()) * 100,
+ "min_return": float(returns.min()) * 100,
+ "final_return": float(returns.iloc[-1]) * 100 if len(returns) > 0 else 0,
+ })
+ except Exception:
+ continue
+
+ if len(results) < min_matches:
+ return {
+ "valid": False,
+ "message": f"Insufficient matches ({len(results)}/{min_matches})",
+ "matches_count": len(results),
+ }
+
+ df_r = pd.DataFrame(results)
+ total = len(df_r)
+ bullish = int((df_r["label"] == 1).sum())
+ neutral = int((df_r["label"] == 0).sum())
+ bearish = int((df_r["label"] == -1).sum())
+
+ weights = df_r["score"].values
+ weights = weights / (weights.sum() + 1e-8)
+
+ weighted_label = float((df_r["label"] * weights).sum())
+ expected_return = float((df_r["final_return"] * weights).sum())
+
+ if bullish > bearish and bullish >= total * 0.4:
+ prediction = "BULLISH"
+ confidence = bullish / total
+ elif bearish > bullish and bearish >= total * 0.4:
+ prediction = "BEARISH"
+ confidence = bearish / total
+ else:
+ prediction = "NEUTRAL"
+ confidence = neutral / total
+
+ return {
+ "valid": True,
+ "prediction": prediction,
+ "confidence": round(confidence * 100, 1),
+ "weighted_label": round(weighted_label, 3),
+ "bullish_count": bullish,
+ "bullish_pct": round(bullish / total * 100, 1),
+ "neutral_count": neutral,
+ "neutral_pct": round(neutral / total * 100, 1),
+ "bearish_count": bearish,
+ "bearish_pct": round(bearish / total * 100, 1),
+ "avg_max_return": round(df_r["max_return"].mean(), 2),
+ "avg_min_return": round(df_r["min_return"].mean(), 2),
+ "avg_final_return": round(df_r["final_return"].mean(), 2),
+ "expected_return": round(expected_return, 2),
+ "avg_hit_day": round(df_r["hit_day"].mean(), 1),
+ "matches_count": total,
+ "details": results,
+ }
+
+
+def calculate_win_loss_ratio(matches_results: List[Dict]) -> Tuple[float, float]:
+ """Calculate win rate and win/loss ratio (for Kelly criterion)."""
+ if not matches_results:
+ return 0.5, 1.0
+
+ wins = [r["final_return"] for r in matches_results if r.get("final_return", 0) > 0]
+ losses = [abs(r["final_return"]) for r in matches_results if r.get("final_return", 0) < 0]
+
+ total = len(wins) + len(losses)
+ if total == 0:
+ return 0.5, 1.0
+
+ win_rate = len(wins) / total
+ avg_win = np.mean(wins) if wins else 0
+ avg_loss = np.mean(losses) if losses else 1
+ win_loss_ratio = avg_win / avg_loss if avg_loss > 0 else 1.0
+
+ return win_rate, win_loss_ratio
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/scorer.py b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/scorer.py
new file mode 100644
index 000000000..717a380ad
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/scorer.py
@@ -0,0 +1,332 @@
+"""
+VisionQuant Multi-Factor Scorer
+Combines Vision (V), Fundamental (F), and Technical (Q) scores.
+
+CLI Protocol:
+ python scorer.py score '{"symbol":"AAPL","win_rate":72.5,"date":"20250115"}'
+
+Score breakdown:
+ V (Vision): 0-3 points — from pattern search win rate
+ F (Fundamental): 0-4 points — P/E and ROE from yfinance
+ Q (Technical): 0-3 points — MA60 + RSI + MACD histogram
+
+Total: 0-10 -> BUY (>=7) / WAIT (>=5) / SELL (<5)
+"""
+
+import sys
+import json
+import numpy as np
+import pandas as pd
+
+import os
+SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
+if SCRIPT_DIR not in sys.path:
+ sys.path.insert(0, SCRIPT_DIR)
+
+from utils import fetch_ohlcv, json_response, output_json, parse_args
+
+
+# ---------------------------------------------------------------------------
+# Vision Score (V): 0 - 3
+# ---------------------------------------------------------------------------
+
+def compute_vision_score(win_rate: float, config: dict = None) -> dict:
+ """
+ Convert pattern match win rate to a 0-3 vision score.
+ win_rate: percentage 0-100
+
+ Config keys: vision_breakpoints (default [70, 55, 40])
+ """
+ cfg = config or {}
+ bp = cfg.get("vision_breakpoints", [70, 55, 40])
+ if len(bp) < 3:
+ bp = [70, 55, 40]
+
+ if win_rate >= bp[0]:
+ score = 3.0
+ elif win_rate >= bp[1]:
+ score = 2.0 + (win_rate - bp[1]) / max(bp[0] - bp[1], 1)
+ elif win_rate >= bp[2]:
+ score = 1.0 + (win_rate - bp[2]) / max(bp[1] - bp[2], 1)
+ else:
+ score = max(0, win_rate / max(bp[2], 1))
+
+ return {
+ "score": round(score, 2),
+ "max": 3,
+ "win_rate": round(win_rate, 1),
+ "label": "Strong" if score >= 2.5 else ("Moderate" if score >= 1.5 else "Weak"),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Fundamental Score (F): 0 - 4
+# ---------------------------------------------------------------------------
+
+def compute_fundamental_score(symbol: str, config: dict = None) -> dict:
+ """
+ Score fundamentals using yfinance Ticker.info.
+ P/E: 0-2, ROE: 0-2.
+
+ Config keys: pe_thresholds (default [15,25,40,60]),
+ roe_thresholds (default [20,15,10,5])
+ """
+ cfg = config or {}
+ pe_t = cfg.get("pe_thresholds", [15, 25, 40, 60])
+ roe_t = cfg.get("roe_thresholds", [20, 15, 10, 5])
+
+ try:
+ import yfinance as yf
+ ticker = yf.Ticker(symbol)
+ info = ticker.info or {}
+ except Exception as e:
+ return {
+ "score": 2.0, # neutral default
+ "max": 4,
+ "pe": None,
+ "roe": None,
+ "pe_score": 1.0,
+ "roe_score": 1.0,
+ "label": "N/A",
+ "error": str(e),
+ }
+
+ # P/E ratio scoring (lower is better for value)
+ pe = info.get("trailingPE") or info.get("forwardPE")
+ if pe is not None and pe > 0:
+ if pe < pe_t[0]:
+ pe_score = 2.0
+ elif pe < pe_t[1]:
+ pe_score = 1.5
+ elif pe < pe_t[2]:
+ pe_score = 1.0
+ elif pe < pe_t[3]:
+ pe_score = 0.5
+ else:
+ pe_score = 0.0
+ else:
+ pe_score = 1.0 # neutral
+
+ # ROE scoring (higher is better)
+ roe = info.get("returnOnEquity")
+ if roe is not None:
+ roe_pct = roe * 100 # yfinance returns decimal
+ if roe_pct >= roe_t[0]:
+ roe_score = 2.0
+ elif roe_pct >= roe_t[1]:
+ roe_score = 1.5
+ elif roe_pct >= roe_t[2]:
+ roe_score = 1.0
+ elif roe_pct >= roe_t[3]:
+ roe_score = 0.5
+ else:
+ roe_score = 0.0
+ else:
+ roe_score = 1.0
+
+ total = pe_score + roe_score
+
+ return {
+ "score": round(total, 2),
+ "max": 4,
+ "pe": round(pe, 2) if pe else None,
+ "roe": round(roe * 100, 2) if roe else None,
+ "pe_score": round(pe_score, 2),
+ "roe_score": round(roe_score, 2),
+ "label": "Strong" if total >= 3 else ("Moderate" if total >= 2 else "Weak"),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Technical Score (Q): 0 - 3
+# ---------------------------------------------------------------------------
+
+def compute_technical_score(symbol: str, date_str: str = None, config: dict = None) -> dict:
+ """
+ Score technicals: MA signal (0-1), RSI (0-1), MACD histogram (0-1).
+
+ Config keys: ma_period (60), rsi_ranges ([30,40,60,70]),
+ macd_fast (12), macd_slow (26), macd_signal (9),
+ ma_thresholds ([1.02, 1.00, 0.98])
+ """
+ cfg = config or {}
+ ma_period = int(cfg.get("ma_period", 60))
+ rsi_ranges = cfg.get("rsi_ranges", [30, 40, 60, 70])
+ if len(rsi_ranges) < 4:
+ rsi_ranges = [30, 40, 60, 70]
+ macd_fast = int(cfg.get("macd_fast", 12))
+ macd_slow = int(cfg.get("macd_slow", 26))
+ macd_signal_span = int(cfg.get("macd_signal", 9))
+ ma_thresh = cfg.get("ma_thresholds", [1.02, 1.00, 0.98])
+ if len(ma_thresh) < 3:
+ ma_thresh = [1.02, 1.00, 0.98]
+
+ df = fetch_ohlcv(symbol, period="1y")
+ if df is None or len(df) < ma_period:
+ return {
+ "score": 1.5,
+ "max": 3,
+ "ma60_signal": None,
+ "rsi": None,
+ "macd_hist": None,
+ "label": "N/A",
+ "error": "Insufficient data",
+ }
+
+ close = df["Close"].values
+
+ # If date specified, truncate
+ if date_str:
+ try:
+ target = pd.to_datetime(date_str)
+ df_trunc = df[df.index <= target]
+ if len(df_trunc) >= ma_period:
+ close = df_trunc["Close"].values
+ except Exception:
+ pass
+
+ # 1. MA signal: price above MA = bullish
+ ma = np.mean(close[-ma_period:])
+ current = close[-1]
+ if current > ma * ma_thresh[0]:
+ ma_score = 1.0
+ elif current > ma * ma_thresh[1]:
+ ma_score = 0.7
+ elif current > ma * ma_thresh[2]:
+ ma_score = 0.3
+ else:
+ ma_score = 0.0
+
+ # 2. RSI (14-period)
+ deltas = np.diff(close[-15:])
+ gains = np.where(deltas > 0, deltas, 0)
+ losses = np.where(deltas < 0, -deltas, 0)
+ avg_gain = np.mean(gains) if len(gains) > 0 else 0
+ avg_loss = np.mean(losses) if len(losses) > 0 else 1e-8
+ rs = avg_gain / (avg_loss + 1e-8)
+ rsi = 100 - (100 / (1 + rs))
+
+ if rsi_ranges[1] <= rsi <= rsi_ranges[2]:
+ rsi_score = 0.5 # neutral
+ elif rsi_ranges[0] <= rsi < rsi_ranges[1]:
+ rsi_score = 0.7 # slightly oversold = opportunity
+ elif rsi < rsi_ranges[0]:
+ rsi_score = 1.0 # oversold = strong buy signal
+ elif rsi_ranges[2] < rsi <= rsi_ranges[3]:
+ rsi_score = 0.3
+ else:
+ rsi_score = 0.0 # overbought
+
+ # 3. MACD histogram
+ ema_fast = pd.Series(close).ewm(span=macd_fast).mean().values
+ ema_slow = pd.Series(close).ewm(span=macd_slow).mean().values
+ macd_line = ema_fast - ema_slow
+ signal_line = pd.Series(macd_line).ewm(span=macd_signal_span).mean().values
+ hist = macd_line - signal_line
+
+ if len(hist) >= 2:
+ if hist[-1] > 0 and hist[-1] > hist[-2]:
+ macd_score = 1.0 # positive and rising
+ elif hist[-1] > 0:
+ macd_score = 0.7
+ elif hist[-1] < 0 and hist[-1] > hist[-2]:
+ macd_score = 0.3 # negative but improving
+ else:
+ macd_score = 0.0
+ else:
+ macd_score = 0.5
+
+ total = ma_score + rsi_score + macd_score
+
+ return {
+ "score": round(total, 2),
+ "max": 3,
+ "ma60_signal": round(ma_score, 2),
+ "rsi": round(rsi, 1),
+ "rsi_score": round(rsi_score, 2),
+ "macd_hist": round(float(hist[-1]), 4) if len(hist) > 0 else None,
+ "macd_score": round(macd_score, 2),
+ "label": "Strong" if total >= 2.5 else ("Moderate" if total >= 1.5 else "Weak"),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Combined Scorecard
+# ---------------------------------------------------------------------------
+
+def compute_scorecard(symbol: str, win_rate: float, date_str: str = None, config: dict = None) -> dict:
+ """Compute the full V+F+Q scorecard.
+
+ Config keys: buy_threshold (7), wait_threshold (5), plus all sub-function keys.
+ """
+ cfg = config or {}
+ buy_threshold = float(cfg.get("buy_threshold", 7))
+ wait_threshold = float(cfg.get("wait_threshold", 5))
+
+ v = compute_vision_score(win_rate, config=cfg)
+ f = compute_fundamental_score(symbol, config=cfg)
+ q = compute_technical_score(symbol, date_str, config=cfg)
+
+ total = v["score"] + f["score"] + q["score"]
+
+ if total >= buy_threshold:
+ action = "BUY"
+ elif total >= wait_threshold:
+ action = "WAIT"
+ else:
+ action = "SELL"
+
+ return {
+ "total_score": round(total, 2),
+ "max_score": 10,
+ "action": action,
+ "vision": v,
+ "fundamental": f,
+ "technical": q,
+ "symbol": symbol,
+ "date": date_str or "latest",
+ }
+
+
+# ---------------------------------------------------------------------------
+# CLI entry point
+# ---------------------------------------------------------------------------
+
+def main():
+ command, params = parse_args()
+
+ if command == "score":
+ symbol = params.get("symbol", "")
+ win_rate = float(params.get("win_rate", 50))
+ date = params.get("date")
+ if not symbol:
+ output_json(json_response("error", error="symbol is required"))
+ return
+ result = compute_scorecard(symbol, win_rate, date, config=params)
+ output_json(json_response("success", data=result))
+
+ elif command == "vision_score":
+ win_rate = float(params.get("win_rate", 50))
+ output_json(json_response("success", data=compute_vision_score(win_rate, config=params)))
+
+ elif command == "fundamental_score":
+ symbol = params.get("symbol", "")
+ if not symbol:
+ output_json(json_response("error", error="symbol is required"))
+ return
+ output_json(json_response("success", data=compute_fundamental_score(symbol, config=params)))
+
+ elif command == "technical_score":
+ symbol = params.get("symbol", "")
+ date = params.get("date")
+ if not symbol:
+ output_json(json_response("error", error="symbol is required"))
+ return
+ output_json(json_response("success", data=compute_technical_score(symbol, date, config=params)))
+
+ else:
+ output_json(json_response("error", error=f"Unknown command: {command}"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/setup_index.py b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/setup_index.py
new file mode 100644
index 000000000..535eedc0e
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/setup_index.py
@@ -0,0 +1,293 @@
+"""
+VisionQuant Index Builder - First-run setup
+Downloads data, generates candlestick images, trains model, builds FAISS index.
+
+CLI Protocol:
+ python setup_index.py build '{"symbols":["AAPL","MSFT"],"start":"20200101","stride":5}'
+ python setup_index.py status '{}'
+
+Progress is streamed as JSON lines to stdout.
+"""
+
+import sys
+import json
+import os
+import time
+import numpy as np
+import pandas as pd
+from datetime import datetime
+
+SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
+if SCRIPT_DIR not in sys.path:
+ sys.path.insert(0, SCRIPT_DIR)
+
+from utils import (
+ get_data_dir, get_model_path, get_index_path, get_meta_path,
+ fetch_ohlcv, generate_kline_image, ensure_dirs,
+ json_response, output_json, output_progress, parse_args,
+)
+
+# Default US market symbols (S&P 500 top 50)
+DEFAULT_SYMBOLS = [
+ "AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA", "BRK-B", "JPM", "V",
+ "UNH", "JNJ", "XOM", "PG", "MA", "HD", "CVX", "MRK", "ABBV", "PEP",
+ "KO", "COST", "AVGO", "LLY", "WMT", "MCD", "CSCO", "TMO", "ACN", "ABT",
+ "DHR", "NEE", "LIN", "TXN", "PM", "UNP", "LOW", "INTC", "COP", "AMGN",
+ "RTX", "HON", "NKE", "BA", "CAT", "GS", "IBM", "MMM", "DIS", "AXP",
+]
+
+
+def build_index(symbols=None, start_date="2020-01-01", stride=5, window=60, epochs=30,
+ batch_size=32, chart_style="international", learning_rate=1e-3):
+ """
+ Full pipeline: download -> generate images -> train model -> build FAISS index.
+
+ Args:
+ symbols: List of ticker symbols
+ start_date: Start date for historical data
+ stride: Step size between consecutive images (days)
+ window: Bars per image
+ epochs: Training epochs for the CAE model
+ """
+ if symbols is None or len(symbols) == 0:
+ symbols = DEFAULT_SYMBOLS
+
+ base_dir = ensure_dirs()
+ img_dir = os.path.join(base_dir, "images")
+ data_dir = os.path.join(base_dir, "data")
+ model_path = get_model_path()
+ index_path = get_index_path()
+ meta_path = get_meta_path()
+
+ total_steps = 4
+ current_step = 0
+
+ # =====================================================================
+ # Step 1: Download OHLCV data
+ # =====================================================================
+ current_step += 1
+ output_progress(f"Step {current_step}/{total_steps}: Downloading market data...", pct=0)
+
+ all_data = {}
+ for i, sym in enumerate(symbols):
+ pct = int(i / len(symbols) * 25)
+ output_progress(f"Downloading {sym} ({i+1}/{len(symbols)})", pct=pct)
+ try:
+ df = fetch_ohlcv(sym, start=start_date)
+ if df is not None and len(df) >= window + 1:
+ # Cache to CSV
+ csv_path = os.path.join(data_dir, f"{sym}.csv")
+ df.to_csv(csv_path)
+ all_data[sym] = df
+ except Exception as e:
+ output_progress(f"Warning: Failed to download {sym}: {e}")
+ continue
+
+ if len(all_data) == 0:
+ output_json(json_response("error", error="No data downloaded for any symbol"))
+ return
+
+ output_progress(f"Downloaded data for {len(all_data)} symbols", pct=25)
+
+ # =====================================================================
+ # Step 2: Generate candlestick images
+ # =====================================================================
+ current_step += 1
+ output_progress(f"Step {current_step}/{total_steps}: Generating K-line images...", pct=25)
+
+ metadata = [] # (symbol, date, image_path)
+ total_images = 0
+
+ for sym_idx, (sym, df) in enumerate(all_data.items()):
+ sym_dir = os.path.join(img_dir, sym)
+ os.makedirs(sym_dir, exist_ok=True)
+
+ n_bars = len(df)
+ for i in range(0, n_bars - window, stride):
+ slice_df = df.iloc[i:i + window]
+ date_str = slice_df.index[-1].strftime("%Y%m%d")
+ img_path = os.path.join(sym_dir, f"{sym}_{date_str}.png")
+
+ result = generate_kline_image(slice_df, img_path, window=window, style=chart_style)
+ if result:
+ metadata.append({
+ "symbol": sym,
+ "date": date_str,
+ "path": img_path,
+ })
+ total_images += 1
+
+ pct = 25 + int(sym_idx / len(all_data) * 25)
+ output_progress(f"Images for {sym}: {total_images} total so far", pct=pct)
+
+ output_progress(f"Generated {total_images} images", pct=50)
+
+ if total_images < 10:
+ output_json(json_response("error", error=f"Too few images generated ({total_images})"))
+ return
+
+ # =====================================================================
+ # Step 3: Train AttentionCAE model
+ # =====================================================================
+ current_step += 1
+ output_progress(f"Step {current_step}/{total_steps}: Training AttentionCAE model...", pct=50)
+
+ import torch
+ from torchvision import transforms
+ from torch.utils.data import DataLoader, Dataset
+ from PIL import Image
+ from models.attention_cae import AttentionCAE, AttentionCAETrainer
+
+ class KlineImageDataset(Dataset):
+ def __init__(self, image_paths, transform):
+ self.paths = [p for p in image_paths if os.path.exists(p)]
+ self.transform = transform
+
+ def __len__(self):
+ return len(self.paths)
+
+ def __getitem__(self, idx):
+ img = Image.open(self.paths[idx]).convert("RGB")
+ tensor = self.transform(img)
+ return tensor, 0 # label unused for autoencoder
+
+ transform = transforms.Compose([
+ transforms.Resize((224, 224)),
+ transforms.ToTensor(),
+ ])
+
+ image_paths = [m["path"] for m in metadata]
+ dataset = KlineImageDataset(image_paths, transform)
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=0)
+
+ model = AttentionCAE(latent_dim=1024, num_attention_heads=8)
+ trainer = AttentionCAETrainer(model, lr=learning_rate)
+
+ best_loss = float("inf")
+ for epoch in range(epochs):
+ loss = trainer.train_epoch(dataloader)
+ pct = 50 + int(epoch / epochs * 25)
+ output_progress(f"Epoch {epoch+1}/{epochs}, Loss: {loss:.6f}", pct=pct)
+
+ if loss < best_loss:
+ best_loss = loss
+ os.makedirs(os.path.dirname(model_path), exist_ok=True)
+ torch.save(model.state_dict(), model_path)
+
+ output_progress(f"Model trained. Best loss: {best_loss:.6f}", pct=75)
+
+ # =====================================================================
+ # Step 4: Encode all images and build FAISS index
+ # =====================================================================
+ current_step += 1
+ output_progress(f"Step {current_step}/{total_steps}: Building FAISS index...", pct=75)
+
+ import faiss
+
+ # Load best model
+ model.load_state_dict(torch.load(model_path, map_location="cpu", weights_only=True))
+ model.eval()
+ device = torch.device("cpu")
+
+ vectors = []
+ valid_meta = []
+
+ for i, meta in enumerate(metadata):
+ img_path = meta["path"]
+ if not os.path.exists(img_path):
+ continue
+ try:
+ img = Image.open(img_path).convert("RGB")
+ tensor = transform(img).unsqueeze(0).to(device)
+ with torch.no_grad():
+ vec = model.encode(tensor).cpu().numpy().flatten()
+ vectors.append(vec)
+ valid_meta.append(meta)
+ except Exception:
+ continue
+
+ if (i + 1) % 100 == 0:
+ pct = 75 + int(i / len(metadata) * 25)
+ output_progress(f"Encoded {i+1}/{len(metadata)} images", pct=pct)
+
+ if len(vectors) < 10:
+ output_json(json_response("error", error=f"Too few vectors encoded ({len(vectors)})"))
+ return
+
+ # Build FAISS index (Inner Product for cosine similarity on L2-normalized vectors)
+ dim = len(vectors[0])
+ matrix = np.array(vectors, dtype="float32")
+ faiss.normalize_L2(matrix)
+
+ index = faiss.IndexFlatIP(dim)
+ index.add(matrix)
+
+ os.makedirs(os.path.dirname(index_path), exist_ok=True)
+ faiss.write_index(index, index_path)
+
+ # Save metadata CSV
+ meta_df = pd.DataFrame(valid_meta)
+ meta_df.to_csv(meta_path, index=False)
+
+ output_progress("Index built successfully!", pct=100)
+
+ output_json(json_response("success", data={
+ "symbols_count": len(all_data),
+ "images_count": total_images,
+ "vectors_count": len(vectors),
+ "index_dim": dim,
+ "model_path": model_path,
+ "index_path": index_path,
+ "meta_path": meta_path,
+ "best_loss": round(best_loss, 6),
+ }))
+
+
+def check_status():
+ """Check if the index is already built."""
+ model_exists = os.path.exists(get_model_path())
+ index_exists = os.path.exists(get_index_path())
+ meta_exists = os.path.exists(get_meta_path())
+
+ n_records = 0
+ if meta_exists:
+ try:
+ n_records = sum(1 for _ in open(get_meta_path())) - 1
+ except Exception:
+ pass
+
+ return json_response("success", data={
+ "index_ready": model_exists and index_exists and meta_exists,
+ "model_exists": model_exists,
+ "index_exists": index_exists,
+ "meta_exists": meta_exists,
+ "n_records": n_records,
+ "data_dir": get_data_dir(),
+ })
+
+
+def main():
+ command, params = parse_args()
+
+ if command == "build":
+ symbols = params.get("symbols", DEFAULT_SYMBOLS)
+ start = params.get("start", params.get("start_date", "2020-01-01"))
+ if len(start) == 8 and "-" not in start:
+ start = f"{start[:4]}-{start[4:6]}-{start[6:8]}"
+ stride = int(params.get("stride", 5))
+ window = int(params.get("window", 60))
+ epochs = int(params.get("epochs", 30))
+ batch_size = int(params.get("batch_size", 32))
+ chart_style = params.get("chart_style", "international")
+ learning_rate = float(params.get("learning_rate", 1e-3))
+ build_index(symbols, start, stride, window, epochs, batch_size, chart_style, learning_rate)
+
+ elif command == "status":
+ output_json(check_status())
+
+ else:
+ output_json(json_response("error", error=f"Unknown command: {command}"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/utils.py b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/utils.py
new file mode 100644
index 000000000..5ff00fe0a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/vision_quant/utils.py
@@ -0,0 +1,221 @@
+"""
+VisionQuant Utilities - Shared helpers for Pattern Intelligence
+"""
+
+import os
+import sys
+import json
+import numpy as np
+import pandas as pd
+from datetime import datetime
+
+
+def get_data_dir():
+ """Resolve the VisionQuant data directory."""
+ fincept_dir = os.environ.get("FINCEPT_DATA_DIR", "")
+ if fincept_dir:
+ return os.path.join(fincept_dir, "vision_quant")
+ # Fallback: ~/.fincept/vision_quant
+ home = os.path.expanduser("~")
+ return os.path.join(home, ".fincept", "vision_quant")
+
+
+def ensure_dirs():
+ """Create the full directory structure for VisionQuant data."""
+ base = get_data_dir()
+ dirs = [
+ base,
+ os.path.join(base, "models"),
+ os.path.join(base, "indices"),
+ os.path.join(base, "images"),
+ os.path.join(base, "data"),
+ ]
+ for d in dirs:
+ os.makedirs(d, exist_ok=True)
+ return base
+
+
+def get_model_path():
+ return os.path.join(get_data_dir(), "models", "attention_cae_best.pth")
+
+
+def get_index_path():
+ return os.path.join(get_data_dir(), "indices", "cae_faiss_attention.bin")
+
+
+def get_meta_path():
+ return os.path.join(get_data_dir(), "indices", "meta_data_attention.csv")
+
+
+def normalize_ohlcv(df):
+ """
+ Normalize OHLCV DataFrame to standard column names.
+ yfinance returns: Open, High, Low, Close, Volume (already standard).
+ Handles various common formats.
+ """
+ if df is None or df.empty:
+ return df
+
+ col_map = {}
+ for c in df.columns:
+ cl = c.lower().strip()
+ if cl in ("open", "opening"):
+ col_map[c] = "Open"
+ elif cl in ("high", "highest"):
+ col_map[c] = "High"
+ elif cl in ("low", "lowest"):
+ col_map[c] = "Low"
+ elif cl in ("close", "closing", "adj close"):
+ col_map[c] = "Close"
+ elif cl in ("volume", "vol"):
+ col_map[c] = "Volume"
+
+ if col_map:
+ df = df.rename(columns=col_map)
+
+ # Ensure datetime index
+ if not isinstance(df.index, pd.DatetimeIndex):
+ try:
+ df.index = pd.to_datetime(df.index)
+ except Exception:
+ pass
+
+ return df
+
+
+def fetch_ohlcv(symbol, start=None, end=None, period="5y"):
+ """
+ Fetch OHLCV data via yfinance.
+
+ Args:
+ symbol: Ticker string (e.g. 'AAPL', '600519.SS')
+ start: Start date string 'YYYY-MM-DD'
+ end: End date string 'YYYY-MM-DD'
+ period: yfinance period if start/end not given
+
+ Returns:
+ DataFrame with Open, High, Low, Close, Volume columns
+ """
+ import yfinance as yf
+
+ ticker = yf.Ticker(symbol)
+ if start and end:
+ df = ticker.history(start=start, end=end, auto_adjust=True)
+ else:
+ df = ticker.history(period=period, auto_adjust=True)
+
+ if df is None or df.empty:
+ return None
+
+ df = normalize_ohlcv(df)
+
+ # Keep only OHLCV columns
+ keep = [c for c in ["Open", "High", "Low", "Close", "Volume"] if c in df.columns]
+ df = df[keep].copy()
+ df.dropna(inplace=True)
+
+ return df
+
+
+def generate_kline_image(ohlcv_df, save_path, window=60, style="international",
+ dpi=75, figsize=(3, 3)):
+ """
+ Render a candlestick chart to PNG using mplfinance.
+
+ Args:
+ ohlcv_df: DataFrame with OHLCV columns and DatetimeIndex
+ save_path: Output PNG path
+ window: Number of bars to render (default 60)
+ style: 'international' (green=up) or 'chinese' (red=up)
+ dpi: Image DPI (default 75)
+ figsize: Figure size tuple (default (3, 3))
+
+ Returns:
+ save_path on success, None on failure
+ """
+ import mplfinance as mpf
+ import matplotlib
+ matplotlib.use("Agg")
+
+ if ohlcv_df is None or len(ohlcv_df) < 10:
+ return None
+
+ # Take the last `window` bars
+ df = ohlcv_df.tail(window).copy()
+
+ # Ensure required columns
+ required = ["Open", "High", "Low", "Close"]
+ for c in required:
+ if c not in df.columns:
+ return None
+
+ # Style: green=up, red=down (international standard)
+ if style == "chinese":
+ mc = mpf.make_marketcolors(up="red", down="green", edge="inherit",
+ wick="inherit", volume="in")
+ else:
+ mc = mpf.make_marketcolors(up="green", down="red", edge="inherit",
+ wick="inherit", volume="in")
+
+ s = mpf.make_mpf_style(marketcolors=mc, gridstyle="", y_on_right=False,
+ rc={"axes.edgecolor": "black"})
+
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
+
+ has_volume = "Volume" in df.columns and df["Volume"].sum() > 0
+
+ mpf.plot(
+ df,
+ type="candle",
+ style=s,
+ volume=has_volume,
+ figsize=figsize,
+ tight_layout=True,
+ savefig=dict(fname=save_path, dpi=dpi, bbox_inches="tight", pad_inches=0),
+ axisoff=True,
+ )
+
+ # Resize to 224x224 for model input
+ try:
+ from PIL import Image
+ img = Image.open(save_path).convert("RGB").resize((224, 224), Image.LANCZOS)
+ img.save(save_path)
+ except Exception:
+ pass
+
+ return save_path
+
+
+def json_response(status, data=None, error=None):
+ """Build a standard JSON response for the Fincept protocol."""
+ resp = {"status": status}
+ if data is not None:
+ resp["data"] = data
+ if error is not None:
+ resp["error"] = str(error)
+ return resp
+
+
+def output_json(obj):
+ """Print JSON to stdout (Fincept protocol)."""
+ print(json.dumps(obj, default=str, ensure_ascii=False))
+
+
+def output_progress(message, pct=None):
+ """Print a progress line to stdout."""
+ line = {"type": "progress", "message": message}
+ if pct is not None:
+ line["percent"] = pct
+ print(json.dumps(line, ensure_ascii=False), flush=True)
+
+
+def parse_args():
+ """Parse command + JSON params from sys.argv (Fincept protocol)."""
+ command = sys.argv[1] if len(sys.argv) > 1 else ""
+ params = {}
+ if len(sys.argv) > 2:
+ try:
+ params = json.loads(sys.argv[2])
+ except json.JSONDecodeError:
+ params = {}
+ return command, params
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 e9de031c4..0ad28375f 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs
@@ -338,8 +338,19 @@ where
continue;
}
- // Determine chunk type based on content prefix
- let (chunk_type, content) = if trimmed.starts_with("THINKING:") {
+ // Determine chunk type based on content prefix.
+ // Python escapes \n as \\n so newlines survive line-by-line reading;
+ // unescape them back here before forwarding to the callback.
+ let unescape = |s: &str| -> String {
+ s.replace("\\\\", "\x00BS\x00")
+ .replace("\\n", "\n")
+ .replace("\\r", "\r")
+ .replace("\x00BS\x00", "\\")
+ };
+
+ let (chunk_type, raw_content) = if trimmed.starts_with("TOKEN:") {
+ ("token", trimmed.strip_prefix("TOKEN:").unwrap_or(trimmed))
+ } else 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())
@@ -355,6 +366,9 @@ where
("token", trimmed)
};
+ let content_owned = unescape(raw_content);
+ let content = content_owned.as_str();
+
full_output.push_str(content);
full_output.push('\n');
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
index 7c9d9a43f..82ff5651a 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
@@ -13,12 +13,12 @@ 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;
-/// Shorter timeout for discovery/listing operations (15 seconds)
-const DISCOVERY_TIMEOUT_SECS: u64 = 15;
-/// Timeout for routing-only operations (no LLM call, just keyword matching)
-const ROUTING_TIMEOUT_SECS: u64 = 10;
+/// Default timeout for agent operations (300 seconds - Fincept endpoint can take up to 70s+)
+const AGENT_TIMEOUT_SECS: u64 = 300;
+/// Timeout for discovery/listing operations (60 seconds)
+const DISCOVERY_TIMEOUT_SECS: u64 = 60;
+/// Timeout for routing operations (includes Python startup + rate limiter + LLM call)
+const ROUTING_TIMEOUT_SECS: u64 = 300;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentParameter {
@@ -47,15 +47,6 @@ pub struct AgentMetadata {
pub color: String,
}
-#[derive(Debug, Serialize, Deserialize)]
-pub struct AgentExecutionResult {
- pub success: bool,
- pub data: Option<serde_json::Value>,
- pub error: Option<String>,
- pub execution_time_ms: u64,
- pub agent_type: String,
-}
-
/// Execute CoreAgent with single JSON payload (unified entry point)
///
/// Payload format:
@@ -183,47 +174,6 @@ 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
-}
-
/// Deliver a tool execution result from TypeScript back to the waiting Python agent.
/// TypeScript calls this after executing a terminal MCP tool triggered by the Python agent.
///
@@ -308,6 +258,21 @@ pub async fn create_stock_analysis_plan(
execute_core_agent(app, payload).await
}
+/// Generate a dynamic execution plan using LLM based on a natural-language query
+#[tauri::command]
+pub async fn generate_dynamic_plan(
+ app: tauri::AppHandle,
+ query: String,
+ api_keys: Option<std::collections::HashMap<String, String>>,
+) -> Result<String, String> {
+ let payload = serde_json::json!({
+ "action": "generate_dynamic_plan",
+ "api_keys": api_keys.unwrap_or_default(),
+ "params": { "query": query }
+ });
+ execute_core_agent(app, payload).await
+}
+
/// Execute an execution plan
#[tauri::command]
pub async fn execute_plan(
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/backtest.rs b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/backtest.rs
index 8d9118701..e32c767b8 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/backtest.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/backtest.rs
@@ -101,7 +101,7 @@ pub async fn run_algo_backtest(
debug_log.push("[backtest] Launching Python backtest_engine.py...".to_string());
- let output = Command::new("python")
+ let child = match Command::new("python")
.arg(&backtest_path)
.arg("--symbol")
.arg(&symbol)
@@ -123,10 +123,10 @@ pub async fn run_algo_backtest(
.arg(&data_provider)
.arg("--db")
.arg(&db_path)
- .output();
-
- let output = match output {
- Ok(out) => out,
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn() {
+ Ok(c) => c,
Err(e) => {
debug_log.push(format!("[backtest] ERROR: Failed to spawn Python process: {}", e));
return Ok(json!({
@@ -137,6 +137,36 @@ pub async fn run_algo_backtest(
}
};
+ // Wait for output with a 120-second timeout to prevent hanging
+ let timeout_duration = std::time::Duration::from_secs(120);
+ let output = match tokio::time::timeout(timeout_duration, tokio::task::spawn_blocking(move || child.wait_with_output())).await {
+ Ok(Ok(Ok(out))) => out,
+ Ok(Ok(Err(e))) => {
+ debug_log.push(format!("[backtest] ERROR: Failed to read process output: {}", e));
+ return Ok(json!({
+ "success": false,
+ "error": format!("Failed to run backtest: {}", e),
+ "debug": debug_log
+ }).to_string());
+ }
+ Ok(Err(e)) => {
+ debug_log.push(format!("[backtest] ERROR: Spawn blocking error: {}", e));
+ return Ok(json!({
+ "success": false,
+ "error": format!("Failed to run backtest: {}", e),
+ "debug": debug_log
+ }).to_string());
+ }
+ Err(_) => {
+ debug_log.push("[backtest] ERROR: Backtest timed out after 120 seconds".to_string());
+ return Ok(json!({
+ "success": false,
+ "error": "Backtest timed out after 120 seconds. Try a shorter period or simpler conditions.",
+ "debug": debug_log
+ }).to_string());
+ }
+ };
+
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/candles.rs b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/candles.rs
index 4a61f952a..f6c578ec5 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/candles.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/candles.rs
@@ -275,7 +275,7 @@ pub async fn evaluate_conditions_once(
}).to_string());
}
- let output = Command::new("python")
+ let child = Command::new("python")
.arg(&evaluator_path)
.arg("--mode")
.arg("once")
@@ -287,9 +287,26 @@ pub async fn evaluate_conditions_once(
.arg(&tf)
.arg("--db")
.arg(&db_path)
- .output()
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()
.map_err(|e| format!("Failed to evaluate conditions: {}", e))?;
+ // Wait with a 30-second timeout to prevent hanging
+ let timeout_duration = std::time::Duration::from_secs(30);
+ let output = match tokio::time::timeout(timeout_duration, tokio::task::spawn_blocking(move || child.wait_with_output())).await {
+ Ok(Ok(Ok(out))) => out,
+ Ok(Ok(Err(e))) => {
+ return Ok(json!({ "success": false, "error": format!("Process error: {}", e) }).to_string());
+ }
+ Ok(Err(e)) => {
+ return Ok(json!({ "success": false, "error": format!("Spawn error: {}", e) }).to_string());
+ }
+ Err(_) => {
+ return Ok(json!({ "success": false, "error": "Condition evaluation timed out after 30 seconds" }).to_string());
+ }
+ };
+
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&stdout) {
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/deployment.rs b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/deployment.rs
index dcd335edd..d97d8cb1a 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/deployment.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/deployment.rs
@@ -1,6 +1,7 @@
//! Deployment lifecycle management
//!
//! Handles algo strategy deployment, monitoring, and termination.
+//! Includes process reaping, PID verification, and candle aggregation cleanup.
use crate::database::pool::get_db;
use serde_json::json;
@@ -8,6 +9,71 @@ use serde_json::json;
use super::helpers::{get_algo_scripts_dir, get_main_db_path_str};
use super::candles::prefetch_historical_candles;
+/// Maximum number of concurrent deployments allowed (rate limiting)
+const MAX_CONCURRENT_DEPLOYMENTS: i64 = 10;
+
+/// Verify that a PID belongs to a Python algo runner process (not a recycled PID).
+/// Returns true if the process appears to be our algo runner, false otherwise.
+fn verify_pid_is_algo_runner(pid: i64) -> bool {
+ #[cfg(target_os = "windows")]
+ {
+ let output = std::process::Command::new("tasklist")
+ .args(["/FI", &format!("PID eq {}", pid), "/FO", "CSV", "/NH"])
+ .output();
+ match output {
+ Ok(o) => {
+ let stdout = String::from_utf8_lossy(&o.stdout).to_lowercase();
+ stdout.contains("python")
+ }
+ Err(_) => false,
+ }
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ let cmdline_path = format!("/proc/{}/cmdline", pid);
+ match std::fs::read_to_string(&cmdline_path) {
+ Ok(cmdline) => cmdline.contains("algo_live_runner"),
+ Err(_) => false,
+ }
+ }
+}
+
+/// Safely kill a process after verifying it is our algo runner.
+/// Returns true if the process was killed, false if verification failed or kill failed.
+fn safe_kill_algo_process(pid: i64) -> bool {
+ if !verify_pid_is_algo_runner(pid) {
+ eprintln!("[AlgoDeploy] PID {} is not a Python algo runner, skipping kill", pid);
+ return false;
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ let result = std::process::Command::new("taskkill")
+ .args(["/F", "/PID", &pid.to_string()])
+ .output();
+ match result {
+ Ok(o) => o.status.success(),
+ Err(e) => {
+ eprintln!("[AlgoDeploy] Failed to kill PID {}: {}", pid, e);
+ false
+ }
+ }
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ let result = std::process::Command::new("kill")
+ .arg(pid.to_string())
+ .output();
+ match result {
+ Ok(o) => o.status.success(),
+ Err(e) => {
+ eprintln!("[AlgoDeploy] Failed to kill PID {}: {}", pid, e);
+ false
+ }
+ }
+ }
+}
+
/// Deploy an algo strategy (spawn Python algo_live_runner.py as background process)
#[tauri::command]
pub async fn deploy_algo_strategy(
@@ -41,12 +107,23 @@ pub async fn deploy_algo_strategy(
println!("[AlgoDeploy] Strategy: {}, Symbol: {}, Mode: {}, TF: {}, Qty: {}", strategy_id, symbol, deploy_mode, deploy_timeframe, deploy_qty);
println!("[AlgoDeploy] Provider: '{}', Params: {}", deploy_provider, deploy_params);
+ // Rate limit: max concurrent deployments
+ let conn = get_db().map_err(|e| e.to_string())?;
+ let running_count: i64 = conn.query_row(
+ "SELECT COUNT(*) FROM algo_deployments WHERE status IN ('running', 'starting')",
+ [],
+ |r| r.get(0),
+ ).unwrap_or(0);
+ if running_count >= MAX_CONCURRENT_DEPLOYMENTS {
+ return Ok(json!({
+ "success": false,
+ "error": format!("Maximum {} concurrent deployments allowed. Stop an existing deployment first.", MAX_CONCURRENT_DEPLOYMENTS)
+ }).to_string());
+ }
+
// Generate deployment ID
let deploy_id = format!("algo-{}", uuid::Uuid::new_v4());
println!("[AlgoDeploy] Deploy ID: {}", deploy_id);
-
- // 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)",
@@ -68,10 +145,12 @@ pub async fn deploy_algo_strategy(
if !runner_path.exists() {
// Update deployment status to error
- let _ = conn.execute(
+ if let Err(e) = conn.execute(
"UPDATE algo_deployments SET status = 'error', error_message = 'Runner script not found' WHERE id = ?1",
rusqlite::params![deploy_id],
- );
+ ) {
+ eprintln!("[AlgoDeploy] DB update failed: {}", e);
+ }
return Ok(json!({
"success": false,
"error": "algo_live_runner.py not found"
@@ -118,15 +197,50 @@ pub async fn deploy_algo_strategy(
.spawn();
match child {
- Ok(child) => {
+ Ok(mut child) => {
let pid = child.id();
println!("[AlgoDeploy] Python runner spawned OK, PID={}", pid);
// Update deployment with PID and running status
- let _ = conn.execute(
+ if let Err(e) = conn.execute(
"UPDATE algo_deployments SET status = 'running', pid = ?1, updated_at = CURRENT_TIMESTAMP WHERE id = ?2",
rusqlite::params![pid as i64, deploy_id],
- );
+ ) {
+ eprintln!("[AlgoDeploy] DB update failed: {}", e);
+ }
+
+ // Spawn a background reaper task to wait for the child process.
+ // This prevents zombie processes and auto-updates DB status if the runner crashes.
+ let reaper_deploy_id = deploy_id.clone();
+ tokio::spawn(async move {
+ let exit_status = tokio::task::spawn_blocking(move || child.wait()).await;
+ match exit_status {
+ Ok(Ok(status)) => {
+ let new_status = if status.success() { "stopped" } else { "error" };
+ let error_msg = if status.success() {
+ None
+ } else {
+ Some(format!("Runner exited with code: {:?}", status.code()))
+ };
+ println!("[AlgoReaper] Deployment {} runner exited: {:?}", reaper_deploy_id, status);
+ if let Ok(conn) = get_db() {
+ // Only update if still marked as 'running' (avoid overwriting manual stop)
+ if let Err(e) = conn.execute(
+ "UPDATE algo_deployments SET status = ?1, error_message = COALESCE(?2, error_message), updated_at = CURRENT_TIMESTAMP WHERE id = ?3 AND status = 'running'",
+ rusqlite::params![new_status, error_msg, reaper_deploy_id],
+ ) {
+ eprintln!("[AlgoReaper] DB update failed for {}: {}", reaper_deploy_id, e);
+ }
+ }
+ }
+ Ok(Err(e)) => {
+ eprintln!("[AlgoReaper] Failed to wait for deployment {}: {}", reaper_deploy_id, e);
+ }
+ Err(e) => {
+ eprintln!("[AlgoReaper] Spawn blocking error for {}: {}", reaper_deploy_id, e);
+ }
+ }
+ });
// Auto-start candle aggregation for this symbol+timeframe
// IMPORTANT: For Indian brokers, normalize symbol format to match WebSocket ticks
@@ -209,10 +323,12 @@ pub async fn deploy_algo_strategy(
}).to_string())
}
Err(e) => {
- let _ = conn.execute(
+ if let Err(db_err) = conn.execute(
"UPDATE algo_deployments SET status = 'error', error_message = ?1 WHERE id = ?2",
rusqlite::params![format!("Failed to spawn: {}", e), deploy_id],
- );
+ ) {
+ eprintln!("[AlgoDeploy] DB update failed: {}", db_err);
+ }
Ok(json!({
"success": false,
"error": format!("Failed to spawn runner: {}", e)
@@ -221,34 +337,35 @@ pub async fn deploy_algo_strategy(
}
}
-/// Stop a running algo deployment (kill process, update DB)
+/// Stop a running algo deployment (kill process, cleanup candle subscriptions, update DB)
#[tauri::command]
-pub async fn stop_algo_deployment(deploy_id: String) -> Result<String, String> {
+pub async fn stop_algo_deployment(
+ state: tauri::State<'_, crate::WebSocketState>,
+ 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'",
+ // Get PID, symbol, and timeframe from deployment record
+ let deploy_info: Result<(Option<i64>, String, String), _> = conn.query_row(
+ "SELECT pid, symbol, timeframe FROM algo_deployments WHERE id = ?1 AND status = 'running'",
rusqlite::params![deploy_id],
- |row| row.get(0),
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
);
- 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();
+ match deploy_info {
+ Ok((pid, symbol, timeframe)) => {
+ if let Some(pid) = pid {
+ // Verify PID is our runner before killing (prevents killing recycled PIDs)
+ safe_kill_algo_process(pid);
}
+ // Cleanup candle aggregation subscriptions
+ let services = state.services.read().await;
+ services.candle_aggregator.remove_subscription(symbol.clone(), timeframe.clone()).await;
+ // Also remove exchange-prefixed variant
+ let prefixed = format!("NSE:{}", symbol);
+ services.candle_aggregator.remove_subscription(prefixed, timeframe).await;
+
// Update status
conn.execute(
"UPDATE algo_deployments SET status = 'stopped', stopped_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE id = ?1",
@@ -258,14 +375,6 @@ pub async fn stop_algo_deployment(deploy_id: String) -> Result<String, String> {
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())
}
@@ -295,23 +404,14 @@ pub async fn stop_all_algo_deployments() -> Result<String, String> {
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();
- }
+ safe_kill_algo_process(*pid);
- let _ = conn.execute(
+ if let Err(e) = conn.execute(
"UPDATE algo_deployments SET status = 'stopped', stopped_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE id = ?1",
rusqlite::params![id],
- );
+ ) {
+ eprintln!("[AlgoStopAll] DB update failed for {}: {}", id, e);
+ }
stopped += 1;
}
@@ -335,37 +435,32 @@ pub async fn delete_algo_deployment(deploy_id: String) -> Result<String, String>
match status_result {
Ok((status, pid)) => {
- // Kill process if still running
+ // Kill process if still running (with PID verification)
if status == "running" {
if let Some(pid) = pid {
- #[cfg(target_os = "windows")]
- {
- let _ = std::process::Command::new("taskkill")
- .args(["/F", "/PID", &pid.to_string()])
- .output();
- }
- #[cfg(not(target_os = "windows"))]
- {
- let _ = std::process::Command::new("kill")
- .arg(pid.to_string())
- .output();
- }
+ safe_kill_algo_process(pid);
}
}
// Delete associated records (trades, metrics, order signals)
- let _ = conn.execute(
+ if let Err(e) = conn.execute(
"DELETE FROM algo_trades WHERE deployment_id = ?1",
rusqlite::params![deploy_id],
- );
- let _ = conn.execute(
+ ) {
+ eprintln!("[AlgoDelete] Failed to delete trades for {}: {}", deploy_id, e);
+ }
+ if let Err(e) = conn.execute(
"DELETE FROM algo_metrics WHERE deployment_id = ?1",
rusqlite::params![deploy_id],
- );
- let _ = conn.execute(
+ ) {
+ eprintln!("[AlgoDelete] Failed to delete metrics for {}: {}", deploy_id, e);
+ }
+ if let Err(e) = conn.execute(
"DELETE FROM algo_order_signals WHERE deployment_id = ?1",
rusqlite::params![deploy_id],
- );
+ ) {
+ eprintln!("[AlgoDelete] Failed to delete signals for {}: {}", deploy_id, e);
+ }
// Delete the deployment itself
conn.execute(
@@ -440,7 +535,15 @@ pub async fn list_algo_deployments() -> Result<String, String> {
})
.map_err(|e| format!("Failed to query deployments: {}", e))?;
- let deployments: Vec<serde_json::Value> = rows.filter_map(|r| r.ok()).collect();
+ let deployments: Vec<serde_json::Value> = rows
+ .filter_map(|r| match r {
+ Ok(v) => Some(v),
+ Err(e) => {
+ eprintln!("[AlgoList] Failed to parse deployment row: {}", e);
+ None
+ }
+ })
+ .collect();
// Log deployment list summary to console (only when there are running deployments)
let running_count = deployments.iter().filter(|d| d.get("status").and_then(|s| s.as_str()) == Some("running")).count();
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/order_bridge.rs b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/order_bridge.rs
index 51bcdcf47..609ea5ffe 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/order_bridge.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/order_bridge.rs
@@ -68,27 +68,32 @@ pub async fn stop_order_signal_bridge() -> Result<String, String> {
}).to_string())
}
-/// Poll `algo_order_signals` for pending signals and execute them
-/// Only processes signals from deployments that are still running
+/// Poll `algo_order_signals` for pending signals and execute them.
+/// Uses an atomic SELECT+UPDATE in a transaction to prevent double-processing.
+/// Only processes signals from deployments that are still running.
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 - only for running deployments
- // This prevents executing signals from stopped/deleted deployments
- let signals = tokio::task::spawn_blocking(|| -> Result<Vec<(String, String, String, String, f64, String, Option<f64>)>, String> {
+ // Atomically read pending signals and mark them as 'processing' in a single transaction.
+ // This prevents race conditions if multiple bridge instances run.
+ let signals = tokio::task::spawn_blocking(|| -> Result<Vec<(String, String, String, String, f64, String, Option<f64>, String)>, String> {
let conn = get_db().map_err(|e| e.to_string())?;
+
+ // Use BEGIN IMMEDIATE to acquire a write lock upfront
+ conn.execute_batch("BEGIN IMMEDIATE").map_err(|e| format!("Failed to begin transaction: {}", e))?;
+
let mut stmt = conn
.prepare(
- "SELECT s.id, s.deployment_id, s.symbol, s.side, s.quantity, s.order_type, s.price
+ "SELECT s.id, s.deployment_id, s.symbol, s.side, s.quantity, s.order_type, s.price, COALESCE(d.params, '{}')
FROM algo_order_signals s
INNER JOIN algo_deployments d ON s.deployment_id = d.id
WHERE s.status = 'pending' AND d.status = 'running'
ORDER BY s.created_at ASC
LIMIT 10",
)
- .map_err(|e| format!("Failed to query signals: {}", e))?;
+ .map_err(|e| { let _ = conn.execute_batch("ROLLBACK"); format!("Failed to query signals: {}", e) })?;
let rows = stmt
.query_map([], |row| {
@@ -100,9 +105,10 @@ async fn poll_and_execute_signals(
row.get::<_, f64>(4)?, // quantity
row.get::<_, String>(5)?, // order_type
row.get::<_, Option<f64>>(6)?, // price
+ row.get::<_, String>(7)?, // deploy params (for product_type)
))
})
- .map_err(|e| format!("Failed to read signals: {}", e))?;
+ .map_err(|e| { let _ = conn.execute_batch("ROLLBACK"); format!("Failed to read signals: {}", e) })?;
let mut result = Vec::new();
for row in rows {
@@ -110,6 +116,19 @@ async fn poll_and_execute_signals(
result.push(r);
}
}
+
+ // Mark all selected signals as 'processing' atomically
+ for (ref signal_id, ..) in &result {
+ if let Err(e) = conn.execute(
+ "UPDATE algo_order_signals SET status = 'processing' WHERE id = ?1",
+ rusqlite::params![signal_id],
+ ) {
+ eprintln!("[AlgoOrderBridge] Failed to mark signal {} as processing: {}", signal_id, e);
+ }
+ }
+
+ conn.execute_batch("COMMIT").map_err(|e| format!("Failed to commit transaction: {}", e))?;
+
Ok(result)
})
.await
@@ -119,15 +138,38 @@ async fn poll_and_execute_signals(
return Ok(0);
}
+ // Track which symbols currently have a signal being processed to prevent conflicting orders
+ let mut processing_symbols = std::collections::HashSet::new();
let mut executed = 0;
- for (signal_id, deployment_id, symbol, side, quantity, order_type, price) in &signals {
+ for (signal_id, deployment_id, symbol, side, quantity, order_type, price, deploy_params) in &signals {
// Validate quantity before processing
if *quantity <= 0.0 {
eprintln!("[AlgoOrderBridge] Invalid quantity {} for signal {}, skipping", quantity, signal_id);
continue;
}
+ // Concurrency check: skip if another signal for same symbol is already being processed
+ let clean_sym_for_check = if symbol.contains(':') {
+ symbol.splitn(2, ':').last().unwrap_or(symbol).to_string()
+ } else {
+ symbol.clone()
+ };
+ if !processing_symbols.insert(clean_sym_for_check.clone()) {
+ eprintln!("[AlgoOrderBridge] Skipping signal {} — conflicting signal already processing for {}", signal_id, clean_sym_for_check);
+ // Mark it back to pending so it gets picked up next cycle
+ 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 = 'pending' WHERE id = ?1",
+ rusqlite::params![sid],
+ );
+ }
+ }).await;
+ continue;
+ }
+
// Emit algo_signal event to notify frontend that a condition matched
let _ = app_handle.emit(
"algo_signal",
@@ -141,18 +183,6 @@ async fn poll_and_execute_signals(
}),
);
- // 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(':') {
@@ -162,6 +192,13 @@ async fn poll_and_execute_signals(
("NSE".to_string(), symbol.clone())
};
+ // Read product_type from deployment params instead of hardcoding
+ let params_json: serde_json::Value = serde_json::from_str(deploy_params).unwrap_or_default();
+ let product_type = params_json.get("product_type")
+ .and_then(|v| v.as_str())
+ .unwrap_or("MIS")
+ .to_string();
+
let order = UnifiedOrder {
symbol: clean_symbol,
exchange,
@@ -170,7 +207,7 @@ async fn poll_and_execute_signals(
quantity: *quantity,
price: *price,
stop_price: None,
- product_type: Some("MIS".to_string()),
+ product_type: Some(product_type),
};
// Execute via unified trading system
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/python_strategies.rs b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/python_strategies.rs
index 844953867..e2163a80e 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/python_strategies.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/python_strategies.rs
@@ -15,7 +15,7 @@ fn parse_strategy_registry(registry_path: &PathBuf) -> Result<Vec<serde_json::Va
// Find the STRATEGY_REGISTRY dict content
let start_marker = "STRATEGY_REGISTRY = {";
- let end_marker = "}";
+ let _end_marker = "}";
if let Some(start_idx) = content.find(start_marker) {
let dict_content = &content[start_idx + start_marker.len()..];
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/strategy.rs b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/strategy.rs
index 083601c33..38292c701 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/strategy.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading/strategy.rs
@@ -3,6 +3,38 @@
use crate::database::pool::get_db;
use serde_json::json;
+/// Validate that a conditions JSON string has the correct structure.
+/// Each non-string element must have at minimum `indicator`, `operator`, `field` keys.
+fn validate_conditions_json(conditions: &str, label: &str) -> Result<(), String> {
+ let parsed: Vec<serde_json::Value> = serde_json::from_str(conditions)
+ .map_err(|e| format!("Invalid {} JSON: {}", label, e))?;
+
+ for (i, item) in parsed.iter().enumerate() {
+ if item.is_string() {
+ // Logic operators like "AND" / "OR" are fine
+ let s = item.as_str().unwrap_or("");
+ if s != "AND" && s != "OR" {
+ return Err(format!("{} item {} is an invalid string '{}' (expected 'AND' or 'OR')", label, i, s));
+ }
+ continue;
+ }
+ if item.is_object() {
+ if item.get("indicator").is_none() {
+ return Err(format!("{} item {} is missing required 'indicator' field", label, i));
+ }
+ if item.get("operator").is_none() {
+ return Err(format!("{} item {} is missing required 'operator' field", label, i));
+ }
+ if item.get("field").is_none() {
+ return Err(format!("{} item {} is missing required 'field' field", label, i));
+ }
+ } else {
+ return Err(format!("{} item {} has unexpected type (expected object or string)", label, i));
+ }
+ }
+ Ok(())
+}
+
/// Save or update an algo strategy (condition-based)
#[tauri::command]
pub async fn save_algo_strategy(
@@ -20,6 +52,14 @@ pub async fn save_algo_strategy(
timeframe: Option<String>,
symbols: Option<String>,
) -> Result<String, String> {
+ // Validate condition JSON structure before saving
+ if let Err(e) = validate_conditions_json(&entry_conditions, "entry_conditions") {
+ return Ok(json!({ "success": false, "error": e }).to_string());
+ }
+ if let Err(e) = validate_conditions_json(&exit_conditions, "exit_conditions") {
+ return Ok(json!({ "success": false, "error": e }).to_string());
+ }
+
let conn = get_db().map_err(|e| e.to_string())?;
conn.execute(
@@ -102,7 +142,15 @@ pub async fn list_algo_strategies() -> Result<String, String> {
})
.map_err(|e| format!("Failed to query strategies: {}", e))?;
- let strategies: Vec<serde_json::Value> = rows.filter_map(|r| r.ok()).collect();
+ let strategies: Vec<serde_json::Value> = rows
+ .filter_map(|r| match r {
+ Ok(v) => Some(v),
+ Err(e) => {
+ eprintln!("[AlgoStrategy] Failed to parse strategy row: {}", e);
+ None
+ }
+ })
+ .collect();
Ok(json!({
"success": true,
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
index 7f9ec54c4..31cfb027e 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/angelone.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/angelone.rs
@@ -239,7 +239,7 @@ fn build_unified_symbol(
expiry: &Option<String>,
strike: f64,
instrument_type: &str,
- exchange: &str,
+ _exchange: &str,
) -> String {
let normalized_name = normalize_index_symbol(name);
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
index 0c3623793..365ac7b01 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/dhan.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/dhan.rs
@@ -165,7 +165,7 @@ fn parse_dhan_csv(csv_text: &str, segment: &str) -> Result<Vec<SymbolRecord>> {
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 _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();
@@ -175,7 +175,7 @@ fn parse_dhan_row(fields: &[&str], segment: &str) -> Option<SymbolRecord> {
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();
+ let _custom_symbol = fields.get(COL_CUSTOM_SYMBOL)?.trim();
// Determine unified exchange
let unified_exchange = match segment {
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
index 10fe59b26..9fb075f2f 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/fyers.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/fyers.rs
@@ -251,7 +251,7 @@ fn build_unified_symbol(
symbol_details: &str,
expiry_raw: &str,
strike: f64,
- option_type: &str,
+ _option_type: &str,
instrument_type: &str,
) -> String {
let normalized_underlying = normalize_index_symbol(underlying);
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
index b0d4f56ea..d626e64ae 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/broker_downloads/mod.rs
@@ -10,10 +10,3 @@ 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/brokers/common.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/common.rs
index 91ab52d49..94932c95e 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/common.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/common.rs
@@ -1,7 +1,5 @@
-#![allow(dead_code)]
// Common types and utilities for Indian broker integrations
-use reqwest::header::{HeaderMap, HeaderValue};
use serde::{Deserialize, Serialize};
// ============================================================================
@@ -31,16 +29,3 @@ pub struct OrderPlaceResponse {
pub error: Option<String>,
}
-// ============================================================================
-// Helper Functions
-// ============================================================================
-
-/// Create common HTTP headers for API requests
-pub fn create_common_headers() -> HeaderMap {
- let mut headers = HeaderMap::new();
- headers.insert(
- "Content-Type",
- HeaderValue::from_static("application/json"),
- );
- headers
-}
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 6c12f3080..a4a1b8cc5 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/shoonya.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/shoonya.rs
@@ -928,17 +928,8 @@ pub async fn shoonya_get_history(
// Shoonya Master Contract Commands
// ============================================================================
-use crate::database::shoonya_symbols::{self, ShoonyaSymbol};
-
-/// Master contract URLs for each exchange
-const SHOONYA_MASTER_URLS: &[(&str, &str)] = &[
- ("NSE", "https://api.shoonya.com/NSE_symbols.txt.zip"),
- ("NFO", "https://api.shoonya.com/NFO_symbols.txt.zip"),
- ("CDS", "https://api.shoonya.com/CDS_symbols.txt.zip"),
- ("MCX", "https://api.shoonya.com/MCX_symbols.txt.zip"),
- ("BSE", "https://api.shoonya.com/BSE_symbols.txt.zip"),
- ("BFO", "https://api.shoonya.com/BFO_symbols.txt.zip"),
-];
+use crate::database::shoonya_symbols;
+
/// Download and cache Shoonya master contract
#[tauri::command]
@@ -970,188 +961,6 @@ pub async fn shoonya_download_master_contract() -> Result<ApiResponse<Value>, St
}
}
-/// Parse Shoonya ZIP file containing symbol CSV
-fn parse_shoonya_zip(zip_bytes: &[u8], exchange: &str) -> Result<Vec<ShoonyaSymbol>, String> {
- use std::io::{Cursor, Read};
- use zip::ZipArchive;
-
- let cursor = Cursor::new(zip_bytes);
- let mut archive = ZipArchive::new(cursor).map_err(|e| format!("Failed to open ZIP: {}", e))?;
-
- let mut symbols = Vec::new();
-
- for i in 0..archive.len() {
- let mut file = archive.by_index(i).map_err(|e| format!("Failed to read ZIP entry: {}", e))?;
-
- if file.name().ends_with(".txt") {
- let mut contents = String::new();
- file.read_to_string(&mut contents).map_err(|e| format!("Failed to read file: {}", e))?;
-
- // Parse CSV based on exchange
- let parsed = parse_shoonya_csv(&contents, exchange)?;
- symbols.extend(parsed);
- }
- }
-
- Ok(symbols)
-}
-
-/// Parse Shoonya CSV content
-fn parse_shoonya_csv(csv_content: &str, exchange: &str) -> Result<Vec<ShoonyaSymbol>, String> {
- let mut symbols = Vec::new();
- let mut lines = csv_content.lines();
-
- // Skip header
- lines.next();
-
- for line in lines {
- if line.trim().is_empty() {
- continue;
- }
-
- let fields: Vec<&str> = line.split(',').collect();
-
- // Minimum fields check
- if fields.len() < 6 {
- continue;
- }
-
- // Parse based on exchange type
- let symbol = match exchange {
- "NSE" | "BSE" => parse_equity_symbol(&fields, exchange),
- "NFO" | "BFO" => parse_fo_symbol(&fields, exchange),
- "MCX" => parse_mcx_symbol(&fields),
- "CDS" => parse_cds_symbol(&fields),
- _ => continue,
- };
-
- if let Some(sym) = symbol {
- symbols.push(sym);
- }
- }
-
- Ok(symbols)
-}
-
-fn parse_equity_symbol(fields: &[&str], exchange: &str) -> Option<ShoonyaSymbol> {
- // Columns: Exchange, Token, LotSize, Symbol, TradingSymbol, Instrument, TickSize
- let token = fields.get(1)?.trim().to_string();
- let lot_size = fields.get(2)?.trim().parse::<i32>().unwrap_or(1);
- let name = fields.get(3)?.trim().to_string();
- let br_symbol = fields.get(4)?.trim().to_string();
- let instrument_type = fields.get(5)?.trim().to_string();
- let tick_size = fields.get(6)?.trim().parse::<f64>().unwrap_or(0.05);
-
- // Generate OpenAlgo-style symbol
- let symbol = if br_symbol.ends_with("-EQ") {
- br_symbol.replace("-EQ", "")
- } else if br_symbol.ends_with("-BE") {
- br_symbol.replace("-BE", "")
- } else {
- br_symbol.clone()
- };
-
- // Determine actual exchange (handle INDEX)
- let actual_exchange = if instrument_type == "INDEX" {
- format!("{}_INDEX", exchange)
- } else {
- exchange.to_string()
- };
-
- Some(ShoonyaSymbol {
- symbol,
- br_symbol,
- name,
- exchange: actual_exchange.clone(),
- br_exchange: actual_exchange,
- token,
- expiry: None,
- strike: None,
- lot_size,
- instrument_type: if instrument_type == "EQ" || instrument_type == "BE" { "EQ".to_string() } else { instrument_type },
- tick_size,
- })
-}
-
-fn parse_fo_symbol(fields: &[&str], exchange: &str) -> Option<ShoonyaSymbol> {
- // Columns: Exchange, Token, LotSize, Symbol, TradingSymbol, Expiry, Instrument, OptionType, StrikePrice, TickSize
- if fields.len() < 10 {
- return None;
- }
-
- let token = fields.get(1)?.trim().to_string();
- let lot_size = fields.get(2)?.trim().parse::<i32>().unwrap_or(1);
- let name = fields.get(3)?.trim().to_string();
- let br_symbol = fields.get(4)?.trim().to_string();
- let expiry_str = fields.get(5)?.trim();
- let _instrument = fields.get(6)?.trim();
- let option_type = fields.get(7)?.trim();
- let strike_str = fields.get(8)?.trim();
- let tick_size = fields.get(9)?.trim().parse::<f64>().unwrap_or(0.05);
-
- // Parse expiry (DD-MMM-YYYY to DD-MMM-YY)
- let expiry = chrono::NaiveDate::parse_from_str(expiry_str, "%d-%b-%Y")
- .ok()
- .map(|d| d.format("%d-%b-%y").to_string().to_uppercase());
-
- // Determine instrument type
- let instrument_type = if option_type == "XX" {
- "FUT".to_string()
- } else {
- option_type.to_string()
- };
-
- // Parse strike price
- let strike: Option<f64> = strike_str.parse().ok();
-
- // Generate OpenAlgo symbol
- let compact_expiry = expiry.as_ref().map(|e| e.replace("-", "")).unwrap_or_default();
- let symbol = if instrument_type == "FUT" {
- format!("{}{}FUT", name, compact_expiry)
- } else {
- let strike_fmt = if let Some(s) = strike {
- if s.fract() == 0.0 { format!("{}", s as i64) } else { format!("{}", s) }
- } else {
- "0".to_string()
- };
- format!("{}{}{}{}", name, compact_expiry, strike_fmt, instrument_type)
- };
-
- Some(ShoonyaSymbol {
- symbol,
- br_symbol,
- name,
- exchange: exchange.to_string(),
- br_exchange: exchange.to_string(),
- token,
- expiry,
- strike,
- lot_size,
- instrument_type,
- tick_size,
- })
-}
-
-fn parse_mcx_symbol(fields: &[&str]) -> Option<ShoonyaSymbol> {
- // Similar to NFO but for commodities
- parse_fo_symbol(fields, "MCX")
-}
-
-fn parse_cds_symbol(fields: &[&str]) -> Option<ShoonyaSymbol> {
- // Currency derivatives
- if fields.len() < 10 {
- return None;
- }
-
- // Filter out dummy entries
- let token: i32 = fields.get(1)?.trim().parse().ok()?;
- if token < 100 {
- return None;
- }
-
- parse_fo_symbol(fields, "CDS")
-}
-
/// Search for symbols in master contract database
#[tauri::command]
pub async fn shoonya_search_symbol(
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 ba9a6ff26..a010ac266 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/upstox.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/upstox.rs
@@ -10,9 +10,6 @@
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
-use std::collections::HashMap;
-use flate2::read::GzDecoder;
-use std::io::Read;
use super::common::{ApiResponse, TokenExchangeResponse, OrderPlaceResponse};
use crate::database::pool::get_db;
@@ -20,7 +17,6 @@ use crate::database::pool::get_db;
// Upstox API Configuration
const UPSTOX_API_BASE_V2: &str = "https://api.upstox.com/v2";
const UPSTOX_API_BASE_V3: &str = "https://api.upstox.com/v3";
-const UPSTOX_MASTER_CONTRACT_URL: &str = "https://assets.upstox.com/market-quote/instruments/exchange/complete.json.gz";
fn create_upstox_headers(access_token: &str) -> HeaderMap {
let mut headers = HeaderMap::new();
@@ -742,109 +738,6 @@ fn init_upstox_symbols_table() -> Result<(), String> {
Ok(())
}
-/// Download and store Upstox master contract (async version)
-async fn download_and_store_upstox_symbols() -> Result<(i64, HashMap<String, i64>), String> {
- eprintln!("[upstox_symbols] Downloading master contract...");
-
- // Download gzipped JSON
- let client = reqwest::Client::new();
- let response = client
- .get(UPSTOX_MASTER_CONTRACT_URL)
- .send()
- .await
- .map_err(|e| format!("Download failed: {}", e))?;
-
- let bytes = response.bytes().await.map_err(|e| format!("Failed to read response: {}", e))?;
-
- // Decompress
- let mut decoder = GzDecoder::new(&bytes[..]);
- let mut json_str = String::new();
- decoder.read_to_string(&mut json_str).map_err(|e| format!("Decompression failed: {}", e))?;
-
- // Parse JSON
- let instruments: Vec<Value> = serde_json::from_str(&json_str)
- .map_err(|e| format!("JSON parse failed: {}", e))?;
-
- eprintln!("[upstox_symbols] Parsed {} instruments", instruments.len());
-
- // Initialize table
- init_upstox_symbols_table()?;
-
- let db = get_db().map_err(|e| e.to_string())?;
-
- // Clear existing data
- db.execute("DELETE FROM upstox_symbols", []).map_err(|e| e.to_string())?;
-
- let mut segment_counts: HashMap<String, i64> = HashMap::new();
- let mut total = 0i64;
-
- // Exchange mapping (Upstox segment → standard exchange)
- let exchange_map: HashMap<&str, &str> = [
- ("NSE_EQ", "NSE"),
- ("BSE_EQ", "BSE"),
- ("NSE_FO", "NFO"),
- ("BSE_FO", "BFO"),
- ("MCX_FO", "MCX"),
- ("NCD_FO", "CDS"),
- ("NSE_INDEX", "NSE_INDEX"),
- ("BSE_INDEX", "BSE_INDEX"),
- ].iter().cloned().collect();
-
- for inst in instruments {
- let segment = inst.get("segment").and_then(|s| s.as_str()).unwrap_or("");
-
- // Skip NSE_COM
- if segment == "NSE_COM" {
- continue;
- }
-
- let exchange = exchange_map.get(segment).copied().unwrap_or(segment);
-
- let instrument_key = inst.get("instrument_key").and_then(|v| v.as_str()).unwrap_or("");
- let trading_symbol = inst.get("trading_symbol").and_then(|v| v.as_str()).unwrap_or("");
- let name = inst.get("name").and_then(|v| v.as_str()).unwrap_or("");
- let instrument_type = inst.get("instrument_type").and_then(|v| v.as_str()).unwrap_or("");
- let lot_size = inst.get("lot_size").and_then(|v| v.as_i64()).unwrap_or(1) as i32;
- let tick_size = inst.get("tick_size").and_then(|v| v.as_f64()).unwrap_or(0.05);
- let strike = inst.get("strike_price").and_then(|v| v.as_f64());
-
- // Convert expiry from milliseconds to date string
- let expiry: Option<String> = inst.get("expiry")
- .and_then(|v| v.as_i64())
- .and_then(|ms| {
- let secs = ms / 1000;
- chrono::DateTime::from_timestamp(secs, 0)
- .map(|dt| dt.format("%d-%b-%y").to_string().to_uppercase())
- });
-
- if db.execute(
- "INSERT OR REPLACE INTO upstox_symbols
- (instrument_key, trading_symbol, name, exchange, segment, instrument_type, lot_size, tick_size, expiry, strike)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
- rusqlite::params![instrument_key, trading_symbol, name, exchange, segment, instrument_type, lot_size, tick_size, expiry, strike],
- ).is_ok() {
- total += 1;
- *segment_counts.entry(segment.to_string()).or_insert(0) += 1;
- }
- }
-
- // Update metadata
- let now = chrono::Utc::now().timestamp();
- db.execute(
- "INSERT OR REPLACE INTO upstox_metadata (key, value) VALUES ('last_updated', ?1)",
- rusqlite::params![now.to_string()],
- ).map_err(|e| e.to_string())?;
-
- db.execute(
- "INSERT OR REPLACE INTO upstox_metadata (key, value) VALUES ('symbol_count', ?1)",
- rusqlite::params![total.to_string()],
- ).map_err(|e| e.to_string())?;
-
- eprintln!("[upstox_symbols] Stored {} symbols", total);
-
- Ok((total, segment_counts))
-}
-
fn search_upstox_symbols(keyword: &str, exchange: Option<&str>, limit: i32) -> Result<Vec<UpstoxSymbol>, String> {
init_upstox_symbols_table()?;
let db = get_db().map_err(|e| e.to_string())?;
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/websocket_commands.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/websocket_commands.rs
index 14760390c..cac1069d7 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/websocket_commands.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/websocket_commands.rs
@@ -397,11 +397,6 @@ pub async fn angelone_ws_unsubscribe(symbol: String, mode: String) -> Result<Api
// ANGEL ONE AUTO-CONNECT HELPER (called from algo_trading deploy)
// ============================================================================
-/// Check if Angel One WebSocket is connected
-pub async fn is_angelone_ws_connected() -> bool {
- ANGELONE_WS.read().await.is_some()
-}
-
/// Connect Angel One WebSocket using stored credentials (no frontend needed).
/// Called from deploy_algo_strategy when provider is "angelone".
/// Returns Ok(true) if connected (or already connected), Err on failure.
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/database.rs b/fincept-terminal-desktop/src-tauri/src/commands/database.rs
index f500e5dc5..3e6d8b118 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/database.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/database.rs
@@ -785,6 +785,13 @@ pub async fn db_admin_get_table_data(
limit: i64,
offset: i64,
) -> Result<Vec<TableRow>, String> {
+ validate_sql_identifier(&table_name, "Table name")?;
+ if limit < 0 || limit > 10000 {
+ return Err("Limit must be between 0 and 10000".to_string());
+ }
+ if offset < 0 {
+ return Err("Offset must be non-negative".to_string());
+ }
let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
let query = format!(
@@ -837,14 +844,30 @@ pub async fn db_admin_execute_query(
db_path: String,
query: String,
) -> Result<Vec<TableRow>, String> {
- // Security: Only allow SELECT queries
- let query_upper = query.trim().to_uppercase();
+ // Security: Only allow SELECT queries — reject anything that could modify data
+ let query_trimmed = query.trim();
+ let query_upper = query_trimmed.to_uppercase();
if !query_upper.starts_with("SELECT") {
return Err("Only SELECT queries are allowed".to_string());
}
+ // Reject queries containing multiple statements or dangerous keywords after SELECT
+ let dangerous_keywords = ["INSERT", "UPDATE", "DELETE", "DROP", "ALTER", "CREATE", "ATTACH", "DETACH", "PRAGMA"];
+ // Check for semicolons (multi-statement) — only allow the trailing one
+ let without_trailing = query_trimmed.trim_end_matches(';').trim();
+ if without_trailing.contains(';') {
+ return Err("Multiple SQL statements are not allowed".to_string());
+ }
+ // Check for dangerous keywords in the rest of the query (skip the leading SELECT)
+ let rest_upper = query_upper.get(6..).unwrap_or("");
+ for kw in &dangerous_keywords {
+ // Match whole word boundaries to avoid false positives (e.g. column named "updated")
+ if rest_upper.split_whitespace().any(|word| word == *kw) {
+ return Err(format!("Query contains disallowed keyword: {}", kw));
+ }
+ }
let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
- let mut stmt = conn.prepare(&query).map_err(|e| e.to_string())?;
+ let mut stmt = conn.prepare(query_trimmed).map_err(|e| e.to_string())?;
let column_count = stmt.column_count();
let column_names: Vec<String> = (0..column_count)
@@ -893,6 +916,11 @@ pub async fn db_admin_update_row(
primary_key_column: String,
primary_key_value: serde_json::Value,
) -> Result<String, String> {
+ validate_sql_identifier(&table_name, "Table name")?;
+ validate_sql_identifier(&primary_key_column, "Primary key column")?;
+ for col in row_data.keys() {
+ validate_sql_identifier(col, "Column name")?;
+ }
let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
let mut set_clauses = Vec::new();
@@ -932,6 +960,10 @@ pub async fn db_admin_insert_row(
table_name: String,
row_data: HashMap<String, serde_json::Value>,
) -> Result<String, String> {
+ validate_sql_identifier(&table_name, "Table name")?;
+ for col in row_data.keys() {
+ validate_sql_identifier(col, "Column name")?;
+ }
let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
let columns: Vec<String> = row_data.keys().map(|k| format!("\"{}\"", k)).collect();
@@ -961,6 +993,8 @@ pub async fn db_admin_delete_row(
primary_key_column: String,
primary_key_value: serde_json::Value,
) -> Result<String, String> {
+ validate_sql_identifier(&table_name, "Table name")?;
+ validate_sql_identifier(&primary_key_column, "Primary key column")?;
let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
let query = format!(
@@ -982,6 +1016,8 @@ pub async fn db_admin_rename_table(
old_name: String,
new_name: String,
) -> Result<String, String> {
+ validate_sql_identifier(&old_name, "Old table name")?;
+ validate_sql_identifier(&new_name, "New table name")?;
let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
let query = format!("ALTER TABLE \"{}\" RENAME TO \"{}\"", old_name, new_name);
@@ -990,6 +1026,25 @@ pub async fn db_admin_rename_table(
Ok("Table renamed successfully".to_string())
}
+/// Validates a SQL identifier (table name, column name) to prevent injection.
+/// Only allows alphanumeric characters, underscores, and spaces (for quoted identifiers).
+/// Rejects empty strings and strings containing quotes, semicolons, or other dangerous chars.
+fn validate_sql_identifier(name: &str, kind: &str) -> Result<(), String> {
+ if name.is_empty() {
+ return Err(format!("{} cannot be empty", kind));
+ }
+ if name.len() > 128 {
+ return Err(format!("{} too long (max 128 chars)", kind));
+ }
+ // Reject characters that could break out of double-quoted identifiers
+ if name.contains('"') || name.contains(';') || name.contains('\\')
+ || name.contains('\0') || name.contains('\'')
+ {
+ return Err(format!("{} contains invalid characters: {}", kind, name));
+ }
+ Ok(())
+}
+
// Helper function to convert JSON value to SQL value
fn json_to_sql_value(val: &serde_json::Value) -> rusqlite::types::Value {
match val {
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/finscript_cmd.rs b/fincept-terminal-desktop/src-tauri/src/commands/finscript_cmd.rs
index 7a65c2b96..55a1ed5d5 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/finscript_cmd.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/finscript_cmd.rs
@@ -1,149 +1,163 @@
+use finscript::{FinScriptResult, OhlcvSeries};
+use crate::data_sources::yfinance::{YFinanceProvider, HistoricalData};
use serde::{Deserialize, Serialize};
-use std::path::PathBuf;
-use tokio::process::Command;
+use std::collections::HashMap;
+/// Configuration for live data fetch
#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct FinScriptResult {
- pub success: bool,
- pub output: String,
- pub signals: Vec<Signal>,
- pub plots: Vec<PlotData>,
- pub errors: Vec<String>,
- pub alerts: Vec<AlertInfo>,
- pub drawings: Vec<DrawingInfo>,
- pub execution_time_ms: u64,
+pub struct DataConfig {
+ pub start_date: String,
+ pub end_date: String,
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Signal {
- pub signal_type: String,
- pub message: String,
- pub timestamp: String,
- pub price: Option<f64>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct PlotData {
- pub plot_type: String,
- pub label: String,
- pub data: Vec<PlotPoint>,
- pub color: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct PlotPoint {
- pub timestamp: i64,
- pub value: Option<f64>,
- pub open: Option<f64>,
- pub high: Option<f64>,
- pub low: Option<f64>,
- pub close: Option<f64>,
- pub volume: Option<f64>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct AlertInfo {
- pub message: String,
- pub alert_type: String,
- pub timestamp: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct DrawingInfo {
- pub drawing_type: String,
- pub x1: i64,
- pub y1: f64,
- pub x2: i64,
- pub y2: f64,
- pub color: String,
- pub text: String,
- pub style: String,
- pub width: f64,
+/// Execute FinScript with synthetic demo data (backward compatible)
+#[tauri::command]
+pub async fn execute_finscript(
+ _app: tauri::AppHandle,
+ code: String,
+) -> Result<FinScriptResult, String> {
+ tokio::task::spawn_blocking(move || finscript::execute(&code))
+ .await
+ .map_err(|e| format!("FinScript execution error: {}", e))
}
-/// Find the finscript binary path.
-/// In development: looks in src-tauri/finscript/target/release/
-/// In production: looks next to the main executable.
-fn find_finscript_binary() -> Result<PathBuf, String> {
- // Try development path first (relative to src-tauri/)
- let dev_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
- .join("finscript")
- .join("target")
- .join("release")
- .join(if cfg!(windows) { "finscript.exe" } else { "finscript" });
-
- if dev_path.exists() {
- return Ok(dev_path);
- }
-
- // Try debug build path
- let debug_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
- .join("finscript")
- .join("target")
- .join("debug")
- .join(if cfg!(windows) { "finscript.exe" } else { "finscript" });
-
- if debug_path.exists() {
- return Ok(debug_path);
+/// Execute FinScript with real market data from yfinance
+#[tauri::command]
+pub async fn execute_finscript_live(
+ app: tauri::AppHandle,
+ code: String,
+ data_config: DataConfig,
+) -> Result<FinScriptResult, String> {
+ // Step 1: Extract symbols from code
+ let symbols = finscript::extract_symbols(&code)
+ .map_err(|e| format!("Symbol extraction failed: {}", e))?;
+
+ if symbols.is_empty() {
+ // No symbols referenced; run with empty data
+ return tokio::task::spawn_blocking(move || {
+ finscript::execute_with_data(&code, HashMap::new())
+ })
+ .await
+ .map_err(|e| format!("FinScript execution error: {}", e));
}
- // Try next to the current executable (production bundle)
- if let Ok(exe_path) = std::env::current_exe() {
- if let Some(exe_dir) = exe_path.parent() {
- let bundled_path = exe_dir.join(if cfg!(windows) { "finscript.exe" } else { "finscript" });
- if bundled_path.exists() {
- return Ok(bundled_path);
+ // Step 2: Fetch real OHLCV data for each symbol
+ let provider = YFinanceProvider::new(&app).map_err(|e| e.to_string())?;
+ let mut symbol_data: HashMap<String, OhlcvSeries> = HashMap::new();
+
+ for symbol in &symbols {
+ match provider
+ .get_historical(symbol, &data_config.start_date, &data_config.end_date)
+ .await
+ {
+ Some(hist) => {
+ symbol_data.insert(symbol.clone(), historical_to_ohlcv(symbol, hist));
+ }
+ None => {
+ return Err(format!(
+ "Failed to fetch market data for '{}'. Check symbol name and date range.",
+ symbol
+ ));
}
}
}
- Err(format!(
- "FinScript binary not found. Expected at: {}. Run 'cargo build --release' in src-tauri/finscript/ first.",
- dev_path.display()
- ))
+ // Step 3: Execute with real data on a blocking thread
+ tokio::task::spawn_blocking(move || finscript::execute_with_data(&code, symbol_data))
+ .await
+ .map_err(|e| format!("FinScript execution error: {}", e))
}
+/// Result for a single symbol in batch mode
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BatchResult {
+ pub symbol: String,
+ pub result: FinScriptResult,
+}
+
+/// Execute FinScript against multiple symbols (screener/batch mode).
+/// Runs the script once per symbol with that symbol's data loaded.
#[tauri::command]
-pub async fn execute_finscript(
- _app: tauri::AppHandle,
+pub async fn execute_finscript_batch(
+ app: tauri::AppHandle,
code: String,
-) -> Result<FinScriptResult, String> {
- let binary_path = find_finscript_binary()?;
-
- // Spawn the standalone finscript binary, piping code via stdin
- let mut cmd = Command::new(&binary_path);
- cmd.stdin(std::process::Stdio::piped())
- .stdout(std::process::Stdio::piped())
- .stderr(std::process::Stdio::piped());
-
- // Hide console window on Windows
- #[cfg(windows)]
- {
- cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
- }
-
- let mut child = cmd.spawn()
- .map_err(|e| format!("Failed to start finscript: {}", e))?;
+ symbols: Vec<String>,
+ data_config: DataConfig,
+) -> Result<Vec<BatchResult>, String> {
+ let provider = YFinanceProvider::new(&app).map_err(|e| e.to_string())?;
+ let mut results = Vec::new();
+
+ for symbol in &symbols {
+ let mut symbol_data: HashMap<String, OhlcvSeries> = HashMap::new();
+
+ match provider
+ .get_historical(symbol, &data_config.start_date, &data_config.end_date)
+ .await
+ {
+ Some(hist) => {
+ symbol_data.insert(symbol.clone(), historical_to_ohlcv(symbol, hist));
+ }
+ None => {
+ results.push(BatchResult {
+ symbol: symbol.clone(),
+ result: FinScriptResult {
+ success: false,
+ output: String::new(),
+ signals: vec![],
+ plots: vec![],
+ errors: vec![format!("Failed to fetch data for {}", symbol)],
+ alerts: vec![],
+ drawings: vec![],
+ integration_actions: vec![],
+ execution_time_ms: 0,
+ },
+ });
+ continue;
+ }
+ }
- // Write code to stdin
- if let Some(mut stdin) = child.stdin.take() {
- use tokio::io::AsyncWriteExt;
- stdin.write_all(code.as_bytes()).await
- .map_err(|e| format!("Failed to write to finscript stdin: {}", e))?;
- drop(stdin); // Close stdin to signal EOF
+ let code_clone = code.clone();
+ let res = tokio::task::spawn_blocking(move || {
+ finscript::execute_with_data(&code_clone, symbol_data)
+ })
+ .await
+ .map_err(|e| format!("Execution error: {}", e))?;
+
+ results.push(BatchResult {
+ symbol: symbol.clone(),
+ result: res,
+ });
}
- let output = child.wait_with_output().await
- .map_err(|e| format!("Failed to read finscript output: {}", e))?;
+ Ok(results)
+}
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- return Err(format!("FinScript process failed: {}", stderr));
+/// Convert Vec<HistoricalData> (from yfinance) to OhlcvSeries (for finscript)
+fn historical_to_ohlcv(symbol: &str, data: Vec<HistoricalData>) -> OhlcvSeries {
+ let len = data.len();
+ let mut timestamps = Vec::with_capacity(len);
+ let mut open = Vec::with_capacity(len);
+ let mut high = Vec::with_capacity(len);
+ let mut low = Vec::with_capacity(len);
+ let mut close = Vec::with_capacity(len);
+ let mut volume = Vec::with_capacity(len);
+
+ for d in data {
+ timestamps.push(d.timestamp);
+ open.push(d.open);
+ high.push(d.high);
+ low.push(d.low);
+ close.push(d.close);
+ volume.push(d.volume as f64);
}
- let stdout = String::from_utf8_lossy(&output.stdout);
-
- // Parse the JSON output from the binary
- serde_json::from_str::<FinScriptResult>(&stdout)
- .map_err(|e| format!("Failed to parse finscript output: {}. Raw: {}", e, &stdout[..stdout.len().min(200)]))
+ OhlcvSeries {
+ symbol: symbol.to_string(),
+ timestamps,
+ open,
+ high,
+ low,
+ close,
+ volume,
+ }
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/market_data.rs b/fincept-terminal-desktop/src-tauri/src/commands/market_data.rs
index 87cab1710..e6cbfe984 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/market_data.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/market_data.rs
@@ -5,6 +5,23 @@ use crate::data_sources::yfinance::{YFinanceProvider, QuoteData, HistoricalData}
use serde::{Deserialize, Serialize};
use serde_json::Value;
+const MAX_SYMBOL_LEN: usize = 20;
+const MAX_SYMBOLS_BATCH: usize = 100;
+
+fn validate_symbol(symbol: &str) -> Result<(), String> {
+ let trimmed = symbol.trim();
+ if trimmed.is_empty() {
+ return Err("Symbol cannot be empty".to_string());
+ }
+ if trimmed.len() > MAX_SYMBOL_LEN {
+ return Err(format!("Symbol too long (max {} chars)", MAX_SYMBOL_LEN));
+ }
+ if !trimmed.chars().all(|c| c.is_alphanumeric() || c == '.' || c == '-' || c == '^' || c == '=' || c == '/') {
+ return Err(format!("Symbol contains invalid characters: {}", trimmed));
+ }
+ Ok(())
+}
+
#[derive(Debug, Serialize, Deserialize)]
pub struct QuoteResponse {
pub success: bool,
@@ -36,7 +53,7 @@ pub struct PeriodReturnsResponse {
/// Fetch a single quote
#[tauri::command]
pub async fn get_market_quote(app: tauri::AppHandle, symbol: String) -> Result<QuoteResponse, String> {
-
+ validate_symbol(&symbol)?;
let provider = YFinanceProvider::new(&app).map_err(|e| e.to_string())?;
match provider.get_quote(&symbol).await {
@@ -56,7 +73,12 @@ pub async fn get_market_quote(app: tauri::AppHandle, symbol: String) -> Result<Q
/// Fetch multiple quotes (batch)
#[tauri::command]
pub async fn get_market_quotes(app: tauri::AppHandle, symbols: Vec<String>) -> Result<QuotesResponse, String> {
-
+ if symbols.len() > MAX_SYMBOLS_BATCH {
+ return Err(format!("Too many symbols (max {})", MAX_SYMBOLS_BATCH));
+ }
+ for s in &symbols {
+ validate_symbol(s)?;
+ }
let provider = YFinanceProvider::new(&app).map_err(|e| e.to_string())?;
let quotes = provider.get_quotes(symbols).await;
@@ -70,7 +92,7 @@ pub async fn get_market_quotes(app: tauri::AppHandle, symbols: Vec<String>) -> R
/// Fetch period returns (7D, 30D)
#[tauri::command]
pub async fn get_period_returns(app: tauri::AppHandle, symbol: String) -> Result<PeriodReturnsResponse, String> {
-
+ validate_symbol(&symbol)?;
let provider = YFinanceProvider::new(&app).map_err(|e| e.to_string())?;
match provider.get_period_returns(&symbol).await {
@@ -113,6 +135,7 @@ pub async fn get_historical_data(
start_date: String,
end_date: String,
) -> Result<HistoricalResponse, String> {
+ validate_symbol(&symbol)?;
let provider = YFinanceProvider::new(&app).map_err(|e| e.to_string())?;
match provider.get_historical(&symbol, &start_date, &end_date).await {
@@ -139,6 +162,7 @@ pub struct StockInfoResponse {
/// Fetch stock info (company data, metrics, etc.)
#[tauri::command]
pub async fn get_stock_info(app: tauri::AppHandle, symbol: String) -> Result<StockInfoResponse, String> {
+ validate_symbol(&symbol)?;
let provider = YFinanceProvider::new(&app).map_err(|e| e.to_string())?;
match provider.get_info(&symbol).await {
@@ -165,6 +189,7 @@ pub struct FinancialsResponse {
/// Fetch financial statements (income, balance sheet, cash flow)
#[tauri::command]
pub async fn get_financials(app: tauri::AppHandle, symbol: String) -> Result<FinancialsResponse, String> {
+ validate_symbol(&symbol)?;
let provider = YFinanceProvider::new(&app).map_err(|e| e.to_string())?;
match provider.get_financials(&symbol).await {
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
index 8e8e6553e..a3594fa64 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
@@ -197,3 +197,6 @@ pub mod gs_quant;
// Polymarket - Prediction markets data
pub mod polymarket;
+
+// VisionQuant - AI K-line Pattern Intelligence
+pub mod vision_quant;
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/orderbook.rs b/fincept-terminal-desktop/src-tauri/src/commands/orderbook.rs
index afcba04a3..f48542450 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/orderbook.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/orderbook.rs
@@ -41,6 +41,8 @@ pub struct OrderBookUpdate {
/// - Pre-allocated capacity to avoid reallocation
///
/// Benchmark: ~2-5μs per update (vs 50-100μs in TypeScript)
+const MAX_ORDERBOOK_DEPTH: usize = 1000;
+
#[tauri::command]
pub fn merge_orderbook(
existing_bids: Vec<OrderBookLevel>,
@@ -49,6 +51,7 @@ pub fn merge_orderbook(
update_asks: Option<Vec<OrderBookLevel>>,
max_depth: usize,
) -> Result<(Vec<OrderBookLevel>, Vec<OrderBookLevel>), String> {
+ let max_depth = max_depth.min(MAX_ORDERBOOK_DEPTH);
// Process bids
let merged_bids = if let Some(updates) = update_bids {
merge_levels(existing_bids, updates, max_depth, false)
@@ -140,6 +143,7 @@ pub fn update_orderbook_snapshot(
mut asks: Vec<OrderBookLevel>,
max_depth: usize,
) -> Result<(Vec<OrderBookLevel>, Vec<OrderBookLevel>), String> {
+ let max_depth = max_depth.min(MAX_ORDERBOOK_DEPTH);
// Sort bids descending
bids.sort_unstable_by(|a, b| {
b.price.partial_cmp(&a.price).unwrap_or(Ordering::Equal)
@@ -208,6 +212,7 @@ pub fn batch_merge_orderbook(
updates: Vec<OrderBookUpdate>,
max_depth: usize,
) -> Result<(Vec<OrderBookLevel>, Vec<OrderBookLevel>), String> {
+ let max_depth = max_depth.min(MAX_ORDERBOOK_DEPTH);
for update in updates {
if let Some(bid_updates) = update.bids {
current_bids = merge_levels(current_bids, bid_updates, max_depth, false);
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/quantstats.rs b/fincept-terminal-desktop/src-tauri/src/commands/quantstats.rs
index 1632096db..b85380036 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/quantstats.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/quantstats.rs
@@ -11,11 +11,13 @@ pub async fn run_quantstats_analysis(
benchmark: Option<String>,
period: Option<String>,
risk_free_rate: Option<f64>,
+ num_sims: Option<u32>,
) -> Result<String, String> {
let action = action.unwrap_or_else(|| "full_report".to_string());
let benchmark = benchmark.unwrap_or_else(|| "SPY".to_string());
let period = period.unwrap_or_else(|| "1y".to_string());
let rf = risk_free_rate.unwrap_or(0.02);
+ let sims = num_sims.unwrap_or(1000);
let args = vec![
action,
@@ -23,6 +25,7 @@ pub async fn run_quantstats_analysis(
benchmark,
period,
rf.to_string(),
+ sims.to_string(),
];
python::execute(&app, "Analytics/quantstats_analytics.py", args).await
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rs b/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rs
index dd95f168d..07f22007d 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rs
@@ -274,7 +274,7 @@ pub async fn skfolio_generate_report(
#[command]
pub async fn skfolio_export_weights(
- app: tauri::AppHandle,
+ _app: tauri::AppHandle,
weights: String,
asset_names: String,
filename: Option<String>,
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/strategies.rs b/fincept-terminal-desktop/src-tauri/src/commands/strategies.rs
index 6b2c3f133..9768e57fc 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/strategies.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/strategies.rs
@@ -279,7 +279,7 @@ pub async fn deploy_strategy(
let strategy_id = parsed["strategy_id"].as_str().unwrap_or("").to_string();
let symbol = parsed["symbol"].as_str().unwrap_or("").to_string();
- let asset_type = parsed["asset_type"].as_str().unwrap_or("equity").to_string();
+ let _asset_type = parsed["asset_type"].as_str().unwrap_or("equity").to_string();
if strategy_id.is_empty() || symbol.is_empty() {
return Ok(json!({
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/symbol_master.rs b/fincept-terminal-desktop/src-tauri/src/commands/symbol_master.rs
index 7cb832c98..d900abef0 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/symbol_master.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/symbol_master.rs
@@ -28,13 +28,6 @@ pub struct StatusResponse {
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,
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 cb8eb4a93..d70109d57 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs
@@ -262,7 +262,7 @@ async fn place_zerodha_order(order: &UnifiedOrder) -> Result<UnifiedOrderRespons
return Err("Zerodha credentials not found. Please authenticate first.".to_string());
}
- let cred_data = creds.data.unwrap();
+ let cred_data = creds.data.ok_or("Zerodha credentials data missing")?;
let api_key = cred_data.get("apiKey")
.and_then(|v| v.as_str())
.ok_or("API key not found")?
@@ -294,7 +294,12 @@ async fn place_zerodha_order(order: &UnifiedOrder) -> Result<UnifiedOrderRespons
params.insert("transaction_type".to_string(), Value::String(transaction_type));
params.insert("order_type".to_string(), Value::String(zerodha_order_type.to_string()));
params.insert("product".to_string(), Value::String(product.to_string()));
- params.insert("quantity".to_string(), Value::Number(serde_json::Number::from(order.quantity as i64)));
+ let qty_i64 = if order.quantity < 0.0 || order.quantity > i64::MAX as f64 || !order.quantity.is_finite() {
+ return Err("Invalid order quantity".to_string());
+ } else {
+ order.quantity as i64
+ };
+ params.insert("quantity".to_string(), Value::Number(serde_json::Number::from(qty_i64)));
if let Some(price) = order.price {
params.insert("price".to_string(), Value::Number(serde_json::Number::from_f64(price).unwrap_or(serde_json::Number::from(0))));
@@ -335,7 +340,7 @@ async fn place_fyers_order(order: &UnifiedOrder) -> Result<UnifiedOrderResponse,
return Err("Fyers credentials not found. Please authenticate first.".to_string());
}
- let cred_data = creds.data.unwrap();
+ let cred_data = creds.data.ok_or("Fyers credentials data missing")?;
let api_key = cred_data.get("apiKey")
.and_then(|v| v.as_str())
.ok_or("Fyers API key not found")?
@@ -377,7 +382,12 @@ async fn place_fyers_order(order: &UnifiedOrder) -> Result<UnifiedOrderResponse,
api_key,
access_token,
fyers_symbol,
- order.quantity as i32,
+ {
+ if order.quantity < 0.0 || order.quantity > i32::MAX as f64 || !order.quantity.is_finite() {
+ return Err("Invalid order quantity for Fyers".to_string());
+ }
+ order.quantity as i32
+ },
fyers_order_type,
fyers_side,
product_type,
@@ -532,7 +542,7 @@ async fn get_live_positions(session: &TradingSession) -> Result<Vec<UnifiedPosit
return Err("Credentials not found".to_string());
}
- let cred_data = creds.data.unwrap();
+ let cred_data = creds.data.ok_or("Zerodha credentials data missing")?;
let api_key = cred_data.get("apiKey")
.and_then(|v| v.as_str())
.ok_or("API key not found")?
@@ -587,7 +597,7 @@ async fn get_live_positions(session: &TradingSession) -> Result<Vec<UnifiedPosit
return Err("Fyers credentials not found".to_string());
}
- let cred_data = creds.data.unwrap();
+ let cred_data = creds.data.ok_or("Fyers credentials data missing")?;
let api_key = cred_data.get("apiKey")
.and_then(|v| v.as_str())
.ok_or("API key not found")?
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/vision_quant.rs b/fincept-terminal-desktop/src-tauri/src/commands/vision_quant.rs
new file mode 100644
index 000000000..02571ae38
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/vision_quant.rs
@@ -0,0 +1,114 @@
+// VisionQuant Pattern Intelligence Commands
+// AI K-line pattern recognition using AttentionCAE + FAISS + DTW
+use crate::python;
+
+/// Merge an optional JSON config string into a serde_json::Value object.
+/// This lets the frontend pass advanced settings without bloating every function signature.
+fn merge_config(base: &mut serde_json::Value, config: Option<String>) {
+ if let Some(cfg_str) = config {
+ if let Ok(cfg_val) = serde_json::from_str::<serde_json::Value>(&cfg_str) {
+ if let Some(obj) = cfg_val.as_object() {
+ if let Some(base_obj) = base.as_object_mut() {
+ for (k, v) in obj {
+ base_obj.insert(k.clone(), v.clone());
+ }
+ }
+ }
+ }
+ }
+}
+
+/// Search for similar K-line patterns using the VisionQuant engine
+#[tauri::command]
+pub async fn vision_quant_search_patterns(
+ app: tauri::AppHandle,
+ symbol: String,
+ date: Option<String>,
+ top_k: Option<u32>,
+ lookback: Option<u32>,
+ config: Option<String>,
+) -> Result<String, String> {
+ let mut params = serde_json::json!({
+ "symbol": symbol,
+ "date": date,
+ "top_k": top_k.unwrap_or(10),
+ "lookback": lookback.unwrap_or(60)
+ });
+ merge_config(&mut params, config);
+
+ let args = vec!["search".to_string(), params.to_string()];
+ python::execute_sync(&app, "vision_quant/engine.py", args)
+}
+
+/// Get multi-factor scorecard (Vision + Fundamental + Technical)
+#[tauri::command]
+pub async fn vision_quant_score(
+ app: tauri::AppHandle,
+ symbol: String,
+ win_rate: f64,
+ date: Option<String>,
+ config: Option<String>,
+) -> Result<String, String> {
+ let mut params = serde_json::json!({
+ "symbol": symbol,
+ "win_rate": win_rate,
+ "date": date
+ });
+ merge_config(&mut params, config);
+
+ let args = vec!["score".to_string(), params.to_string()];
+ python::execute_sync(&app, "vision_quant/scorer.py", args)
+}
+
+/// Run adaptive strategy backtest
+#[tauri::command]
+pub async fn vision_quant_backtest(
+ app: tauri::AppHandle,
+ symbol: String,
+ start_date: String,
+ end_date: String,
+ initial_capital: Option<f64>,
+ config: Option<String>,
+) -> Result<String, String> {
+ let mut params = serde_json::json!({
+ "symbol": symbol,
+ "start": start_date,
+ "end": end_date,
+ "capital": initial_capital.unwrap_or(100000.0)
+ });
+ merge_config(&mut params, config);
+
+ let args = vec!["backtest".to_string(), params.to_string()];
+ python::execute_sync(&app, "vision_quant/backtester.py", args)
+}
+
+/// Build FAISS index (first-run setup)
+#[tauri::command]
+pub async fn vision_quant_setup_index(
+ app: tauri::AppHandle,
+ symbols: Option<Vec<String>>,
+ start_date: Option<String>,
+ stride: Option<u32>,
+ epochs: Option<u32>,
+ config: Option<String>,
+) -> Result<String, String> {
+ let mut params = serde_json::json!({
+ "symbols": symbols,
+ "start": start_date.unwrap_or_else(|| "2020-01-01".to_string()),
+ "stride": stride.unwrap_or(5),
+ "epochs": epochs.unwrap_or(30)
+ });
+ merge_config(&mut params, config);
+
+ let args = vec!["build".to_string(), params.to_string()];
+ python::execute_sync(&app, "vision_quant/setup_index.py", args)
+}
+
+/// Check VisionQuant index status (model, index, metadata)
+#[tauri::command]
+pub async fn vision_quant_status(
+ app: tauri::AppHandle,
+) -> Result<String, String> {
+ let args = vec!["status".to_string()];
+ python::execute_sync(&app, "vision_quant/engine.py", args)
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/database/schema.rs b/fincept-terminal-desktop/src-tauri/src/database/schema.rs
index 337bcbd63..542b96f57 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/schema.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/schema.rs
@@ -69,7 +69,7 @@ pub fn create_schema(conn: &Connection) -> Result<()> {
-- Insert default Fincept LLM config if not exists
INSERT OR IGNORE INTO llm_configs (provider, api_key, base_url, model, is_active)
- VALUES ('fincept', '', 'https://finceptbackend.share.zrok.io/research/llm', 'fincept-llm', 1);
+ VALUES ('fincept', '', 'https://api.fincept.in/research/llm', 'fincept-llm', 1);
-- Chat sessions table
CREATE TABLE IF NOT EXISTS chat_sessions (
diff --git a/fincept-terminal-desktop/src-tauri/src/database/symbol_master.rs b/fincept-terminal-desktop/src-tauri/src/database/symbol_master.rs
index 38ba98a20..f632bfaf6 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/symbol_master.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/symbol_master.rs
@@ -254,20 +254,6 @@ pub fn get_status(broker_id: &str) -> Result<MasterContractStatus> {
}))
}
-/// 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
@@ -727,14 +713,6 @@ pub fn build_options_symbol(underlying: &str, expiry: &str, strike: f64, option_
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
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index 765655b0f..bf674350a 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -37,6 +37,7 @@ struct MCPState {
}
// Global state for WebSocket manager
+#[allow(private_interfaces)]
pub struct WebSocketState {
pub manager: Arc<tokio::sync::RwLock<websocket::WebSocketManager>>,
pub router: Arc<tokio::sync::RwLock<websocket::MessageRouter>>,
@@ -44,7 +45,7 @@ pub struct WebSocketState {
}
#[allow(dead_code)]
-struct WebSocketServices {
+pub(crate) struct WebSocketServices {
paper_trading: websocket::services::PaperTradingService,
arbitrage: websocket::services::ArbitrageService,
portfolio: websocket::services::PortfolioService,
@@ -196,7 +197,8 @@ fn spawn_mcp_server(
response_rx,
};
- let mut processes = state.processes.lock().unwrap();
+ let mut processes = state.processes.lock()
+ .map_err(|e| format!("Failed to lock MCP state: {}", e))?;
processes.insert(server_id.clone(), mcp_process);
Ok(SpawnResult {
@@ -227,12 +229,14 @@ fn send_mcp_request(
let timeout = timeout_secs.unwrap_or(30);
println!("[Tauri] Sending request to server {} (timeout: {}s): {}", server_id, timeout, request);
- let mut processes = state.processes.lock().unwrap();
+ let mut processes = state.processes.lock()
+ .map_err(|e| format!("Failed to lock MCP state: {}", e))?;
if let Some(mcp_process) = processes.get_mut(&server_id) {
// Write request to stdin
{
- let mut stdin = mcp_process.stdin.lock().unwrap();
+ let mut stdin = mcp_process.stdin.lock()
+ .map_err(|e| format!("Failed to lock stdin: {}", e))?;
writeln!(stdin, "{}", request)
.map_err(|e| format!("Failed to write to stdin: {}", e))?;
stdin.flush()
@@ -263,10 +267,12 @@ fn send_mcp_notification(
server_id: String,
notification: String,
) -> Result<(), String> {
- let mut processes = state.processes.lock().unwrap();
+ let mut processes = state.processes.lock()
+ .map_err(|e| format!("Failed to lock MCP state: {}", e))?;
if let Some(mcp_process) = processes.get_mut(&server_id) {
- let mut stdin = mcp_process.stdin.lock().unwrap();
+ let mut stdin = mcp_process.stdin.lock()
+ .map_err(|e| format!("Failed to lock stdin: {}", e))?;
writeln!(stdin, "{}", notification)
.map_err(|e| format!("Failed to write notification: {}", e))?;
stdin.flush()
@@ -283,7 +289,8 @@ fn ping_mcp_server(
state: tauri::State<MCPState>,
server_id: String,
) -> Result<bool, String> {
- let mut processes = state.processes.lock().unwrap();
+ let mut processes = state.processes.lock()
+ .map_err(|e| format!("Failed to lock MCP state: {}", e))?;
if let Some(mcp_process) = processes.get_mut(&server_id) {
// Check if process is still running
@@ -303,11 +310,14 @@ fn kill_mcp_server(
state: tauri::State<MCPState>,
server_id: String,
) -> Result<(), String> {
- let mut processes = state.processes.lock().unwrap();
+ let mut processes = state.processes.lock()
+ .map_err(|e| format!("Failed to lock MCP state: {}", e))?;
if let Some(mut mcp_process) = processes.remove(&server_id) {
match mcp_process.child.kill() {
Ok(_) => {
+ // Reap the child process to avoid zombies
+ let _ = mcp_process.child.wait();
Ok(())
}
Err(e) => Err(format!("Failed to kill server: {}", e)),
@@ -738,6 +748,7 @@ pub fn run() {
close: payload.get("close").and_then(|v| v.as_f64()),
change: payload.get("change").and_then(|v| v.as_f64()),
change_percent: payload.get("change_percent").and_then(|v| v.as_f64()),
+ quote_volume: payload.get("quote_volume").and_then(|v| v.as_f64()),
timestamp: payload.get("timestamp").and_then(|v| v.as_u64()).unwrap_or(0),
};
@@ -1400,6 +1411,8 @@ pub fn run() {
commands::jupyter::install_python_package,
commands::jupyter::list_python_packages,
commands::finscript_cmd::execute_finscript,
+ commands::finscript_cmd::execute_finscript_live,
+ commands::finscript_cmd::execute_finscript_batch,
// Python Agent Commands
commands::agents::list_available_agents,
commands::agents::get_agent_metadata,
@@ -1412,6 +1425,7 @@ pub fn run() {
commands::agents::execute_routed_query,
commands::agents::discover_agents,
commands::agents::create_stock_analysis_plan,
+ commands::agents::generate_dynamic_plan,
commands::agents::execute_plan,
commands::agents::save_trade_decision,
commands::agents::get_trade_decisions,
@@ -2614,7 +2628,13 @@ pub fn run() {
// Python Strategy Backtest & Deployment
commands::algo_trading::run_python_backtest,
commands::algo_trading::extract_strategy_parameters,
- commands::algo_trading::deploy_python_strategy
+ commands::algo_trading::deploy_python_strategy,
+ // VisionQuant Pattern Intelligence
+ commands::vision_quant::vision_quant_search_patterns,
+ commands::vision_quant::vision_quant_score,
+ commands::vision_quant::vision_quant_backtest,
+ commands::vision_quant::vision_quant_setup_index,
+ commands::vision_quant::vision_quant_status
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
diff --git a/fincept-terminal-desktop/src-tauri/src/market_sim/mod.rs b/fincept-terminal-desktop/src-tauri/src/market_sim/mod.rs
index 1c48311f5..12905906b 100644
--- a/fincept-terminal-desktop/src-tauri/src/market_sim/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/market_sim/mod.rs
@@ -1,13 +1,25 @@
+#[allow(dead_code, unused_assignments)]
pub mod types;
+#[allow(dead_code, unused_assignments)]
pub mod orderbook;
+#[allow(dead_code, unused_assignments)]
pub mod matching_engine;
+#[allow(dead_code, unused_assignments)]
pub mod risk_engine;
+#[allow(dead_code, unused_assignments)]
pub mod clearing;
+#[allow(dead_code, unused_assignments)]
pub mod market_data;
+#[allow(dead_code, unused_assignments)]
pub mod agents;
+#[allow(dead_code)]
pub mod exchange;
+#[allow(dead_code)]
pub mod auction;
+#[allow(dead_code)]
pub mod latency;
+#[allow(dead_code)]
pub mod analytics;
+#[allow(dead_code)]
pub mod events;
pub mod commands;
diff --git a/fincept-terminal-desktop/src-tauri/src/mcp_bridge.rs b/fincept-terminal-desktop/src-tauri/src/mcp_bridge.rs
index d14b93f15..bf36ee5f3 100644
--- a/fincept-terminal-desktop/src-tauri/src/mcp_bridge.rs
+++ b/fincept-terminal-desktop/src-tauri/src/mcp_bridge.rs
@@ -37,8 +37,20 @@ pub fn get_or_start_bridge(app: AppHandle) -> u16 {
/// Safe to call multiple times — only starts once.
fn start_bridge(app: AppHandle) -> u16 {
// Bind to random available port on loopback only
- let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind MCP bridge");
- let port = listener.local_addr().expect("No local addr").port();
+ let listener = match TcpListener::bind("127.0.0.1:0") {
+ Ok(l) => l,
+ Err(e) => {
+ eprintln!("[MCPBridge] Failed to bind: {}. MCP bridge disabled.", e);
+ return 0;
+ }
+ };
+ let port = match listener.local_addr() {
+ Ok(addr) => addr.port(),
+ Err(e) => {
+ eprintln!("[MCPBridge] Failed to get local addr: {}. MCP bridge disabled.", e);
+ return 0;
+ }
+ };
// Store port globally
BRIDGE_PORT.store(port, Ordering::Relaxed);
@@ -75,7 +87,14 @@ fn handle_connection(
app: AppHandle,
) {
// Read HTTP request line + headers
- let mut reader = BufReader::new(stream.try_clone().expect("clone stream"));
+ let cloned = match stream.try_clone() {
+ Ok(s) => s,
+ Err(e) => {
+ eprintln!("[MCPBridge] Failed to clone stream: {}", e);
+ return;
+ }
+ };
+ let mut reader = BufReader::new(cloned);
let mut request_line = String::new();
if reader.read_line(&mut request_line).is_err() {
return;
@@ -110,7 +129,12 @@ fn handle_connection(
let method = parts[0];
let path = parts[1];
- // Read body
+ // Read body (limit to 10 MB to prevent OOM from malicious Content-Length)
+ const MAX_BODY_SIZE: usize = 10 * 1024 * 1024;
+ if content_length > MAX_BODY_SIZE {
+ write_response(stream, 413, "Payload Too Large", b"{\"error\":\"body exceeds 10MB limit\"}");
+ return;
+ }
let mut body = vec![0u8; content_length];
if content_length > 0 {
use std::io::Read;
@@ -186,10 +210,18 @@ fn handle_tool_call(
// Economics tools (CEIC, central bank rates) can take 15-30s each.
// We're on a std thread (not a tokio task), so we create a minimal runtime.
let result = {
- let rt = tokio::runtime::Builder::new_current_thread()
+ let rt = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
- .expect("mini runtime for MCP bridge");
+ {
+ Ok(rt) => rt,
+ Err(e) => {
+ eprintln!("[MCPBridge] Failed to create runtime: {}", e);
+ pending.remove(&id);
+ write_response(stream, 500, "Internal Server Error", b"{\"error\":\"runtime creation failed\"}");
+ return;
+ }
+ };
rt.block_on(async {
tokio::time::timeout(std::time::Duration::from_secs(90), rx).await
})
diff --git a/fincept-terminal-desktop/src-tauri/src/paper_trading.rs b/fincept-terminal-desktop/src-tauri/src/paper_trading.rs
index d19b90e8c..ad37843dd 100644
--- a/fincept-terminal-desktop/src-tauri/src/paper_trading.rs
+++ b/fincept-terminal-desktop/src-tauri/src/paper_trading.rs
@@ -236,14 +236,34 @@ pub fn reset_portfolio(id: &str) -> Result<Portfolio> {
pub fn place_order(portfolio_id: &str, symbol: &str, side: &str, order_type: &str, quantity: f64, price: Option<f64>, stop_price: Option<f64>, reduce_only: bool) -> Result<Order> {
let portfolio = get_portfolio(portfolio_id)?;
- // Validate
- if quantity <= 0.0 { bail!("Invalid quantity"); }
+ // Validate order_type
+ let valid_order_types = ["market", "limit", "stop", "stop_limit"];
+ if !valid_order_types.contains(&order_type) {
+ bail!("Invalid order type: {}. Must be one of: market, limit, stop, stop_limit", order_type);
+ }
+
+ // Validate side
+ if side != "buy" && side != "sell" {
+ bail!("Invalid side: {}. Must be 'buy' or 'sell'", side);
+ }
+
+ // Validate quantity
+ if !quantity.is_finite() || quantity <= 0.0 { bail!("Invalid quantity"); }
+
+ // Validate price fields
+ if let Some(p) = price { if !p.is_finite() || p <= 0.0 { bail!("Invalid price"); } }
+ if let Some(sp) = stop_price { if !sp.is_finite() || sp <= 0.0 { bail!("Invalid stop price"); } }
+
if order_type == "limit" && price.is_none() { bail!("Limit order requires price"); }
if (order_type == "stop" || order_type == "stop_limit") && stop_price.is_none() { bail!("Stop order requires stop_price"); }
// Check margin for new positions
if !reduce_only {
- let required_margin = quantity * price.unwrap_or(stop_price.unwrap_or(0.0)) / portfolio.leverage;
+ let reference_price = price.or(stop_price).unwrap_or(0.0);
+ if reference_price <= 0.0 {
+ bail!("Market orders require a reference price for margin calculation");
+ }
+ let required_margin = quantity * reference_price / portfolio.leverage;
if required_margin > portfolio.balance { bail!("Insufficient margin"); }
}
@@ -273,13 +293,20 @@ pub fn get_orders(portfolio_id: &str, status: Option<&str>) -> Result<Vec<Order>
let pool = get_pool()?;
let conn = pool.get()?;
- let sql = match status {
- Some(s) => format!("SELECT id, portfolio_id, symbol, side, order_type, quantity, price, stop_price, filled_qty, avg_price, status, reduce_only, created_at, filled_at FROM pt_orders WHERE portfolio_id = ?1 AND status = '{}'", s),
- None => "SELECT id, portfolio_id, symbol, side, order_type, quantity, price, stop_price, filled_qty, avg_price, status, reduce_only, created_at, filled_at FROM pt_orders WHERE portfolio_id = ?1".to_string(),
+ let (sql, query_params): (String, Vec<Box<dyn rusqlite::types::ToSql>>) = match status {
+ Some(s) => (
+ "SELECT id, portfolio_id, symbol, side, order_type, quantity, price, stop_price, filled_qty, avg_price, status, reduce_only, created_at, filled_at FROM pt_orders WHERE portfolio_id = ?1 AND status = ?2".to_string(),
+ vec![Box::new(portfolio_id.to_string()) as Box<dyn rusqlite::types::ToSql>, Box::new(s.to_string())],
+ ),
+ None => (
+ "SELECT id, portfolio_id, symbol, side, order_type, quantity, price, stop_price, filled_qty, avg_price, status, reduce_only, created_at, filled_at FROM pt_orders WHERE portfolio_id = ?1".to_string(),
+ vec![Box::new(portfolio_id.to_string()) as Box<dyn rusqlite::types::ToSql>],
+ ),
};
let mut stmt = conn.prepare(&sql)?;
- let rows = stmt.query_map(params![portfolio_id], |row| Ok(Order {
+ let params_refs: Vec<&dyn rusqlite::types::ToSql> = query_params.iter().map(|p| p.as_ref()).collect();
+ let rows = stmt.query_map(params_refs.as_slice(), |row| Ok(Order {
id: row.get(0)?, portfolio_id: row.get(1)?, symbol: row.get(2)?, side: row.get(3)?, order_type: row.get(4)?,
quantity: row.get(5)?, price: row.get(6)?, stop_price: row.get(7)?, filled_qty: row.get(8)?, avg_price: row.get(9)?,
status: row.get(10)?, reduce_only: row.get(11)?, created_at: row.get(12)?, filled_at: row.get(13)?
@@ -292,11 +319,21 @@ pub fn get_orders(portfolio_id: &str, status: Option<&str>) -> Result<Vec<Order>
// ============================================================================
pub fn fill_order(order_id: &str, fill_price: f64, fill_qty: Option<f64>) -> Result<Trade> {
+ if !fill_price.is_finite() || fill_price <= 0.0 {
+ bail!("Invalid fill price");
+ }
+ if let Some(fq) = fill_qty {
+ if !fq.is_finite() || fq <= 0.0 {
+ bail!("Invalid fill quantity");
+ }
+ }
+
let pool = get_pool()?;
- let conn = pool.get()?;
+ let mut conn = pool.get()?;
+ let tx = conn.transaction()?;
// Get order
- let order: Order = conn.query_row(
+ let order: Order = tx.query_row(
"SELECT id, portfolio_id, symbol, side, order_type, quantity, price, stop_price, filled_qty, avg_price, status, reduce_only, created_at, filled_at FROM pt_orders WHERE id = ?1",
params![order_id],
|row| Ok(Order { id: row.get(0)?, portfolio_id: row.get(1)?, symbol: row.get(2)?, side: row.get(3)?, order_type: row.get(4)?, quantity: row.get(5)?, price: row.get(6)?, stop_price: row.get(7)?, filled_qty: row.get(8)?, avg_price: row.get(9)?, status: row.get(10)?, reduce_only: row.get(11)?, created_at: row.get(12)?, filled_at: row.get(13)? })
@@ -315,7 +352,7 @@ pub fn fill_order(order_id: &str, fill_price: f64, fill_qty: Option<f64>) -> Res
let mut pnl = 0.0;
// Check if closing opposite position
- let existing: Option<Position> = conn.query_row(
+ let existing: Option<Position> = tx.query_row(
"SELECT id, portfolio_id, symbol, side, quantity, entry_price, current_price, unrealized_pnl, realized_pnl, leverage, liquidation_price, opened_at FROM pt_positions WHERE portfolio_id = ?1 AND symbol = ?2 AND side = ?3",
params![order.portfolio_id, order.symbol, opposite_side],
|row| Ok(Position { id: row.get(0)?, portfolio_id: row.get(1)?, symbol: row.get(2)?, side: row.get(3)?, quantity: row.get(4)?, entry_price: row.get(5)?, current_price: row.get(6)?, unrealized_pnl: row.get(7)?, realized_pnl: row.get(8)?, leverage: row.get(9)?, liquidation_price: row.get(10)?, opened_at: row.get(11)? })
@@ -327,23 +364,23 @@ pub fn fill_order(order_id: &str, fill_price: f64, fill_qty: Option<f64>) -> Res
pnl = if pos.side == "long" { (fill_price - pos.entry_price) * close_qty } else { (pos.entry_price - fill_price) * close_qty };
if close_qty >= pos.quantity {
- conn.execute("DELETE FROM pt_positions WHERE id = ?1", params![pos.id])?;
+ tx.execute("DELETE FROM pt_positions WHERE id = ?1", params![pos.id])?;
} else {
- conn.execute("UPDATE pt_positions SET quantity = quantity - ?1, realized_pnl = realized_pnl + ?2 WHERE id = ?3", params![close_qty, pnl, pos.id])?;
+ tx.execute("UPDATE pt_positions SET quantity = quantity - ?1, realized_pnl = realized_pnl + ?2 WHERE id = ?3", params![close_qty, pnl, pos.id])?;
}
// Open remaining as new position if qty > close_qty (flip position)
if qty > close_qty {
let new_qty = qty - close_qty;
let pos_id = Uuid::new_v4().to_string();
- conn.execute(
+ tx.execute(
"INSERT INTO pt_positions (id, portfolio_id, symbol, side, quantity, entry_price, current_price, leverage, opened_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
params![pos_id, order.portfolio_id, order.symbol, position_side, new_qty, fill_price, fill_price, portfolio.leverage, now]
)?;
}
} else {
// Check for same-side position to add to
- let same_pos: Option<Position> = conn.query_row(
+ let same_pos: Option<Position> = tx.query_row(
"SELECT id, portfolio_id, symbol, side, quantity, entry_price, current_price, unrealized_pnl, realized_pnl, leverage, liquidation_price, opened_at FROM pt_positions WHERE portfolio_id = ?1 AND symbol = ?2 AND side = ?3",
params![order.portfolio_id, order.symbol, position_side],
|row| Ok(Position { id: row.get(0)?, portfolio_id: row.get(1)?, symbol: row.get(2)?, side: row.get(3)?, quantity: row.get(4)?, entry_price: row.get(5)?, current_price: row.get(6)?, unrealized_pnl: row.get(7)?, realized_pnl: row.get(8)?, leverage: row.get(9)?, liquidation_price: row.get(10)?, opened_at: row.get(11)? })
@@ -353,11 +390,11 @@ pub fn fill_order(order_id: &str, fill_price: f64, fill_qty: Option<f64>) -> Res
// Average into existing position
let new_qty = pos.quantity + qty;
let new_entry = (pos.entry_price * pos.quantity + fill_price * qty) / new_qty;
- conn.execute("UPDATE pt_positions SET quantity = ?1, entry_price = ?2, current_price = ?3 WHERE id = ?4", params![new_qty, new_entry, fill_price, pos.id])?;
+ tx.execute("UPDATE pt_positions SET quantity = ?1, entry_price = ?2, current_price = ?3 WHERE id = ?4", params![new_qty, new_entry, fill_price, pos.id])?;
} else {
// Brand new position
let pos_id = Uuid::new_v4().to_string();
- conn.execute(
+ tx.execute(
"INSERT INTO pt_positions (id, portfolio_id, symbol, side, quantity, entry_price, current_price, leverage, opened_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
params![pos_id, order.portfolio_id, order.symbol, position_side, qty, fill_price, fill_price, portfolio.leverage, now]
)?;
@@ -369,22 +406,24 @@ pub fn fill_order(order_id: &str, fill_price: f64, fill_qty: Option<f64>) -> Res
// Opening positions does NOT affect wallet balance (margin is reserved from available balance)
// Closing positions adds/subtracts realized P&L minus fees
let balance_change = pnl - fee;
- conn.execute("UPDATE pt_portfolios SET balance = balance + ?1 WHERE id = ?2", params![balance_change, order.portfolio_id])?;
+ tx.execute("UPDATE pt_portfolios SET balance = balance + ?1 WHERE id = ?2", params![balance_change, order.portfolio_id])?;
// Update order
let new_filled = order.filled_qty + qty;
let new_status = if new_filled >= order.quantity { "filled" } else { "partial" };
let new_avg = Some((order.avg_price.unwrap_or(0.0) * order.filled_qty + fill_price * qty) / new_filled);
- conn.execute("UPDATE pt_orders SET filled_qty = ?1, avg_price = ?2, status = ?3, filled_at = ?4 WHERE id = ?5", params![new_filled, new_avg, new_status, now, order_id])?;
+ tx.execute("UPDATE pt_orders SET filled_qty = ?1, avg_price = ?2, status = ?3, filled_at = ?4 WHERE id = ?5", params![new_filled, new_avg, new_status, now, order_id])?;
// Create trade
let trade_id = Uuid::new_v4().to_string();
- conn.execute(
+ tx.execute(
"INSERT INTO pt_trades (id, portfolio_id, order_id, symbol, side, price, quantity, fee, pnl, timestamp) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
params![trade_id, order.portfolio_id, order_id, order.symbol, order.side, fill_price, qty, fee, pnl, now]
)?;
- Ok(Trade { id: trade_id, portfolio_id: order.portfolio_id, order_id: order_id.to_string(), symbol: order.symbol, side: order.side, price: fill_price, quantity: qty, fee, pnl, timestamp: now })
+ let trade = Trade { id: trade_id, portfolio_id: order.portfolio_id, order_id: order_id.to_string(), symbol: order.symbol, side: order.side, price: fill_price, quantity: qty, fee, pnl, timestamp: now };
+ tx.commit()?;
+ Ok(trade)
}
// ============================================================================
diff --git a/fincept-terminal-desktop/src-tauri/src/setup.rs b/fincept-terminal-desktop/src-tauri/src/setup.rs
index a50c9537d..1fcdb38df 100644
--- a/fincept-terminal-desktop/src-tauri/src/setup.rs
+++ b/fincept-terminal-desktop/src-tauri/src/setup.rs
@@ -714,10 +714,12 @@ async fn create_venv(app: &AppHandle, install_dir: &PathBuf, venv_name: &str) ->
cmd
};
+ let venv_path_str = venv_path.to_str().ok_or_else(|| format!("Invalid venv path encoding: {:?}", venv_path))?;
+ let python_exe_str = python_exe.to_str().ok_or_else(|| format!("Invalid python path encoding: {:?}", python_exe))?;
cmd.args(&[
"venv",
- venv_path.to_str().unwrap(),
- "--python", python_exe.to_str().unwrap()
+ venv_path_str,
+ "--python", python_exe_str
]);
#[cfg(target_os = "windows")]
@@ -787,10 +789,12 @@ async fn install_packages_in_venv(
cmd
};
+ let venv_python_str = venv_python.to_str().ok_or_else(|| format!("Invalid venv python path encoding: {:?}", venv_python))?;
+ let requirements_path_str = requirements_path.to_str().ok_or_else(|| format!("Invalid requirements path encoding: {:?}", requirements_path))?;
cmd.args(&[
"pip", "install",
- "--python", venv_python.to_str().unwrap(),
- "-r", requirements_path.to_str().unwrap()
+ "--python", venv_python_str,
+ "-r", requirements_path_str
]);
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/angelone.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/angelone.rs
index 5d6ec9aba..39d969648 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/angelone.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/angelone.rs
@@ -377,6 +377,7 @@ impl AngelOneAdapter {
close: if tick.close > 0.0 { Some(tick.close) } else { None },
change: if change != 0.0 { Some(change) } else { None },
change_percent: if change_pct != 0.0 { Some(change_pct) } else { None },
+ quote_volume: None,
timestamp: now_ms,
}));
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/binance.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/binance.rs
index 09da40d08..3273a8b0d 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/binance.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/binance.rs
@@ -36,7 +36,7 @@ impl BinanceAdapter {
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
- .unwrap()
+ .unwrap_or_else(|_| std::time::Duration::from_secs(0))
.as_millis() as u64
}
@@ -64,7 +64,7 @@ impl BinanceAdapter {
let high = data.get("h")?.as_str()?.parse::<f64>().ok();
let low = data.get("l")?.as_str()?.parse::<f64>().ok();
let volume = data.get("v")?.as_str()?.parse::<f64>().ok();
- let _quote_volume = data.get("q")?.as_str()?.parse::<f64>().ok();
+ let quote_volume = data.get("q")?.as_str()?.parse::<f64>().ok();
// Calculate change percent
let change_percent = if let Some(open_price) = open {
@@ -92,6 +92,7 @@ impl BinanceAdapter {
close: Some(close),
change: None,
change_percent,
+ quote_volume,
timestamp: Self::now(),
})
}
@@ -121,6 +122,7 @@ impl BinanceAdapter {
close: Some(price),
change: None,
change_percent: None,
+ quote_volume: None,
timestamp: Self::now(),
})
}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/bitfinex.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/bitfinex.rs
new file mode 100644
index 000000000..f4c3bd44d
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/bitfinex.rs
@@ -0,0 +1,393 @@
+#![allow(dead_code)]
+// Bitfinex WebSocket Adapter
+//
+// Implements Bitfinex WebSocket API v2
+// Supports: ticker, book, trades channels
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+const BITFINEX_WS_URL: &str = "wss://api-pub.bitfinex.com/ws/2";
+
+pub struct BitfinexAdapter {
+ config: ProviderConfig,
+ ws: Option<Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>>,
+ message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
+ connected: Arc<RwLock<bool>>,
+ // Map channel ID to (symbol, channel_type)
+ channel_map: Arc<RwLock<HashMap<u64, (String, String)>>>,
+}
+
+impl BitfinexAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ ws: None,
+ message_callback: None,
+ connected: Arc::new(RwLock::new(false)),
+ channel_map: Arc::new(RwLock::new(HashMap::new())),
+ }
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| std::time::Duration::from_secs(0))
+ .as_millis() as u64
+ }
+
+ /// Normalize Bitfinex symbol (tBTCUSD -> BTC/USD)
+ fn normalize_bitfinex_symbol(symbol: &str) -> String {
+ let s = symbol.strip_prefix('t').unwrap_or(symbol);
+ // Handle pairs like BTCUSD, ETHBTC, etc.
+ if s.len() >= 6 {
+ // Check for 3-char quote currencies
+ for quote in ["USD", "UST", "BTC", "ETH", "EUR", "GBP", "JPY"] {
+ if s.ends_with(quote) {
+ let base = &s[..s.len() - quote.len()];
+ return format!("{}/{}", base, quote);
+ }
+ }
+ }
+ s.to_string()
+ }
+
+ /// Convert symbol to Bitfinex format (BTC/USD -> tBTCUSD)
+ fn to_bitfinex_symbol(symbol: &str) -> String {
+ format!("t{}", symbol.replace('/', ""))
+ }
+
+ /// Parse Bitfinex ticker (from array format)
+ fn parse_ticker(&self, data: &Value, symbol: &str) -> Option<TickerData> {
+ let arr = data.as_array()?;
+ if arr.len() < 10 {
+ return None;
+ }
+
+ let bid = arr.get(0)?.as_f64()?;
+ let bid_size = arr.get(1)?.as_f64();
+ let ask = arr.get(2)?.as_f64()?;
+ let ask_size = arr.get(3)?.as_f64();
+ let daily_change = arr.get(4)?.as_f64();
+ let daily_change_perc = arr.get(5)?.as_f64().map(|p| p * 100.0);
+ let last_price = arr.get(6)?.as_f64()?;
+ let volume = arr.get(7)?.as_f64();
+ let high = arr.get(8)?.as_f64();
+ let low = arr.get(9)?.as_f64();
+
+ Some(TickerData {
+ provider: "bitfinex".to_string(),
+ symbol: Self::normalize_bitfinex_symbol(symbol),
+ price: last_price,
+ bid: Some(bid),
+ ask: Some(ask),
+ bid_size,
+ ask_size,
+ volume,
+ high,
+ low,
+ open: None,
+ close: Some(last_price),
+ change: daily_change,
+ change_percent: daily_change_perc,
+ quote_volume: None,
+ timestamp: Self::now(),
+ })
+ }
+
+ /// Parse Bitfinex order book (snapshot or update)
+ fn parse_orderbook(&self, data: &Value, symbol: &str, is_snapshot: bool) -> Option<OrderBookData> {
+ let mut bids = Vec::new();
+ let mut asks = Vec::new();
+
+ if is_snapshot {
+ // Snapshot: array of [price, count, amount]
+ if let Some(arr) = data.as_array() {
+ for entry in arr {
+ if let Some(entry_arr) = entry.as_array() {
+ if entry_arr.len() >= 3 {
+ let price = entry_arr.get(0)?.as_f64()?;
+ let count = entry_arr.get(1)?.as_i64()? as u32;
+ let amount = entry_arr.get(2)?.as_f64()?;
+
+ let level = OrderBookLevel {
+ price,
+ quantity: amount.abs(),
+ count: Some(count),
+ };
+
+ if amount > 0.0 {
+ bids.push(level);
+ } else {
+ asks.push(level);
+ }
+ }
+ }
+ }
+ }
+ } else {
+ // Update: single [price, count, amount]
+ if let Some(arr) = data.as_array() {
+ if arr.len() >= 3 {
+ let price = arr.get(0)?.as_f64()?;
+ let count = arr.get(1)?.as_i64()? as u32;
+ let amount = arr.get(2)?.as_f64()?;
+
+ let level = OrderBookLevel {
+ price,
+ quantity: amount.abs(),
+ count: Some(count),
+ };
+
+ if amount > 0.0 {
+ bids.push(level);
+ } else {
+ asks.push(level);
+ }
+ }
+ }
+ }
+
+ Some(OrderBookData {
+ provider: "bitfinex".to_string(),
+ symbol: Self::normalize_bitfinex_symbol(symbol),
+ bids,
+ asks,
+ timestamp: Self::now(),
+ is_snapshot,
+ })
+ }
+
+ /// Parse Bitfinex trade
+ fn parse_trade(&self, data: &Value, symbol: &str) -> Option<TradeData> {
+ let arr = data.as_array()?;
+ if arr.len() < 4 {
+ return None;
+ }
+
+ // Format: [ID, MTS, AMOUNT, PRICE] or [ID, MTS, AMOUNT, PRICE] in tu
+ let trade_id = arr.get(0)?.as_u64().map(|i| i.to_string());
+ let timestamp = arr.get(1)?.as_u64().unwrap_or_else(Self::now);
+ let amount = arr.get(2)?.as_f64()?;
+ let price = arr.get(3)?.as_f64()?;
+
+ Some(TradeData {
+ provider: "bitfinex".to_string(),
+ symbol: Self::normalize_bitfinex_symbol(symbol),
+ trade_id,
+ price,
+ quantity: amount.abs(),
+ side: if amount > 0.0 { TradeSide::Buy } else { TradeSide::Sell },
+ timestamp,
+ })
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for BitfinexAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ let url = if self.config.url.is_empty() {
+ BITFINEX_WS_URL
+ } else {
+ &self.config.url
+ };
+
+ let (ws_stream, _) = connect_async(url).await?;
+ let ws = Arc::new(RwLock::new(ws_stream));
+ self.ws = Some(ws.clone());
+ *self.connected.write().await = true;
+
+ let callback = self.message_callback.clone();
+ let connected = self.connected.clone();
+ let channel_map = self.channel_map.clone();
+
+ tokio::spawn(async move {
+ let mut ws_lock = ws.write().await;
+
+ while let Some(msg) = ws_lock.next().await {
+ match msg {
+ Ok(Message::Text(text)) => {
+ if let Ok(data) = serde_json::from_str::<Value>(&text) {
+ // Handle info/subscribed events
+ if let Some(event) = data.get("event").and_then(|e| e.as_str()) {
+ if event == "subscribed" {
+ let chan_id = data.get("chanId").and_then(|c| c.as_u64()).unwrap_or(0);
+ let symbol = data.get("symbol").or_else(|| data.get("pair"))
+ .and_then(|s| s.as_str()).unwrap_or("").to_string();
+ let channel = data.get("channel").and_then(|c| c.as_str()).unwrap_or("").to_string();
+
+ let mut map = channel_map.write().await;
+ map.insert(chan_id, (symbol, channel));
+ }
+ continue;
+ }
+
+ // Handle data messages (array format)
+ if let Some(arr) = data.as_array() {
+ if arr.len() >= 2 {
+ let chan_id = arr.get(0).and_then(|c| c.as_u64()).unwrap_or(0);
+
+ // Skip heartbeat
+ if arr.get(1).and_then(|h| h.as_str()) == Some("hb") {
+ continue;
+ }
+
+ if let Some(ref cb) = callback {
+ let map = channel_map.read().await;
+ if let Some((symbol, channel)) = map.get(&chan_id) {
+ let adapter = BitfinexAdapter::new(ProviderConfig::default());
+ let payload = &arr[1];
+
+ let message = match channel.as_str() {
+ "ticker" => adapter.parse_ticker(payload, symbol).map(MarketMessage::Ticker),
+ "book" => {
+ let is_snapshot = payload.as_array()
+ .map(|a| a.first().and_then(|f| f.as_array()).is_some())
+ .unwrap_or(false);
+ adapter.parse_orderbook(payload, symbol, is_snapshot).map(MarketMessage::OrderBook)
+ }
+ "trades" => {
+ // Handle both snapshot and updates
+ if let Some(trade_data) = payload.as_array() {
+ // Check if it's a snapshot (array of trades) or single trade
+ if trade_data.first().and_then(|f| f.as_array()).is_some() {
+ // Snapshot - emit each trade
+ for trade in trade_data {
+ if let Some(t) = adapter.parse_trade(trade, symbol) {
+ cb(MarketMessage::Trade(t));
+ }
+ }
+ None
+ } else {
+ adapter.parse_trade(payload, symbol).map(MarketMessage::Trade)
+ }
+ } else {
+ None
+ }
+ }
+ _ => None,
+ };
+
+ if let Some(msg) = message {
+ cb(msg);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ Ok(Message::Close(_)) => {
+ *connected.write().await = false;
+ break;
+ }
+ Err(_) => {
+ *connected.write().await = false;
+ break;
+ }
+ _ => {}
+ }
+ }
+ });
+
+ Ok(())
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ if let Some(ws) = &self.ws {
+ let mut ws_lock = ws.write().await;
+ ws_lock.close(None).await?;
+ }
+ *self.connected.write().await = false;
+ self.ws = None;
+ self.channel_map.write().await.clear();
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ _params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let bitfinex_symbol = Self::to_bitfinex_symbol(symbol);
+
+ let bitfinex_channel = match channel {
+ "ticker" => "ticker",
+ "book" | "depth" => "book",
+ "trade" => "trades",
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let mut subscribe_msg = json!({
+ "event": "subscribe",
+ "channel": bitfinex_channel,
+ "symbol": bitfinex_symbol
+ });
+
+ // Add precision for orderbook
+ if bitfinex_channel == "book" {
+ subscribe_msg["prec"] = json!("P0");
+ subscribe_msg["len"] = json!("25");
+ }
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(subscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let bitfinex_symbol = Self::to_bitfinex_symbol(symbol);
+
+ // Find channel ID
+ let map = self.channel_map.read().await;
+ let chan_id = map.iter()
+ .find(|(_, (s, c))| {
+ s == &bitfinex_symbol && match channel {
+ "ticker" => c == "ticker",
+ "book" | "depth" => c == "book",
+ "trade" => c == "trades",
+ _ => false,
+ }
+ })
+ .map(|(id, _)| *id);
+ drop(map);
+
+ if let Some(id) = chan_id {
+ let unsubscribe_msg = json!({
+ "event": "unsubscribe",
+ "chanId": id
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(unsubscribe_msg.to_string())).await?;
+
+ self.channel_map.write().await.remove(&id);
+ }
+
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(Arc::new(callback));
+ }
+
+ fn provider_name(&self) -> &str {
+ "bitfinex"
+ }
+
+ fn is_connected(&self) -> bool {
+ *self.connected.blocking_read()
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/bitget.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/bitget.rs
new file mode 100644
index 000000000..cc201294e
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/bitget.rs
@@ -0,0 +1,301 @@
+#![allow(dead_code)]
+// Bitget WebSocket Adapter
+//
+// Implements Bitget WebSocket API v2
+// Supports: ticker, books, trades channels
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+const BITGET_WS_URL: &str = "wss://ws.bitget.com/v2/ws/public";
+
+pub struct BitgetAdapter {
+ config: ProviderConfig,
+ ws: Option<Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>>,
+ message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
+ connected: Arc<RwLock<bool>>,
+}
+
+impl BitgetAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ ws: None,
+ message_callback: None,
+ connected: Arc::new(RwLock::new(false)),
+ }
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| std::time::Duration::from_secs(0))
+ .as_millis() as u64
+ }
+
+ /// Normalize Bitget symbol (BTCUSDT -> BTC/USDT)
+ fn normalize_bitget_symbol(symbol: &str) -> String {
+ for quote in ["USDT", "USDC", "USD", "BTC", "ETH"] {
+ if let Some(base) = symbol.strip_suffix(quote) {
+ return format!("{}/{}", base, quote);
+ }
+ }
+ symbol.to_string()
+ }
+
+ /// Convert symbol to Bitget format (BTC/USDT -> BTCUSDT)
+ fn to_bitget_symbol(symbol: &str) -> String {
+ symbol.replace('/', "").to_uppercase()
+ }
+
+ /// Parse Bitget ticker
+ fn parse_ticker(&self, data: &Value) -> Option<TickerData> {
+ let inst_id = data.get("instId")?.as_str()?;
+ let last = data.get("lastPr")?.as_str()?.parse::<f64>().ok()?;
+ let bid = data.get("bidPr")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let ask = data.get("askPr")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let bid_sz = data.get("bidSz")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let ask_sz = data.get("askSz")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let volume = data.get("baseVolume")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let high = data.get("high24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let low = data.get("low24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let open = data.get("open24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let change_percent = data.get("change24h")?.as_str().and_then(|s| s.parse::<f64>().ok())
+ .map(|c| c * 100.0);
+
+ Some(TickerData {
+ provider: "bitget".to_string(),
+ symbol: Self::normalize_bitget_symbol(inst_id),
+ price: last,
+ bid,
+ ask,
+ bid_size: bid_sz,
+ ask_size: ask_sz,
+ volume,
+ high,
+ low,
+ open,
+ close: Some(last),
+ change: None,
+ change_percent,
+ quote_volume: data.get("quoteVolume")?.as_str().and_then(|s| s.parse::<f64>().ok()),
+ timestamp: data.get("ts")?.as_str()?.parse::<u64>().ok().unwrap_or_else(Self::now),
+ })
+ }
+
+ /// Parse Bitget order book
+ fn parse_orderbook(&self, data: &Value, inst_id: &str) -> Option<OrderBookData> {
+ let bids = data.get("bids")?.as_array()?;
+ let asks = data.get("asks")?.as_array()?;
+
+ let parse_levels = |levels: &Vec<Value>| -> Vec<OrderBookLevel> {
+ levels
+ .iter()
+ .filter_map(|level| {
+ let arr = level.as_array()?;
+ Some(OrderBookLevel {
+ price: arr.get(0)?.as_str()?.parse::<f64>().ok()?,
+ quantity: arr.get(1)?.as_str()?.parse::<f64>().ok()?,
+ count: None,
+ })
+ })
+ .collect()
+ };
+
+ Some(OrderBookData {
+ provider: "bitget".to_string(),
+ symbol: Self::normalize_bitget_symbol(inst_id),
+ bids: parse_levels(bids),
+ asks: parse_levels(asks),
+ timestamp: data.get("ts")?.as_str()?.parse::<u64>().ok().unwrap_or_else(Self::now),
+ is_snapshot: true,
+ })
+ }
+
+ /// Parse Bitget trade
+ fn parse_trade(&self, data: &Value) -> Option<TradeData> {
+ let inst_id = data.get("instId")?.as_str()?;
+ let price = data.get("price")?.as_str()?.parse::<f64>().ok()?;
+ let size = data.get("size")?.as_str()?.parse::<f64>().ok()?;
+ let side = data.get("side")?.as_str()?;
+ let trade_id = data.get("tradeId")?.as_str().map(|s| s.to_string());
+ let ts = data.get("ts")?.as_str()?.parse::<u64>().ok().unwrap_or_else(Self::now);
+
+ Some(TradeData {
+ provider: "bitget".to_string(),
+ symbol: Self::normalize_bitget_symbol(inst_id),
+ trade_id,
+ price,
+ quantity: size,
+ side: match side {
+ "buy" => TradeSide::Buy,
+ "sell" => TradeSide::Sell,
+ _ => TradeSide::Unknown,
+ },
+ timestamp: ts,
+ })
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for BitgetAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ let url = if self.config.url.is_empty() {
+ BITGET_WS_URL
+ } else {
+ &self.config.url
+ };
+
+ let (ws_stream, _) = connect_async(url).await?;
+ let ws = Arc::new(RwLock::new(ws_stream));
+ self.ws = Some(ws.clone());
+ *self.connected.write().await = true;
+
+ let callback = self.message_callback.clone();
+ let connected = self.connected.clone();
+
+ tokio::spawn(async move {
+ let mut ws_lock = ws.write().await;
+
+ while let Some(msg) = ws_lock.next().await {
+ match msg {
+ Ok(Message::Text(text)) => {
+ if let Ok(data) = serde_json::from_str::<Value>(&text) {
+ // Handle ping
+ if text == "ping" {
+ let _ = ws_lock.send(Message::Text("pong".to_string())).await;
+ continue;
+ }
+
+ if let Some(ref cb) = callback {
+ if let Some(arg) = data.get("arg") {
+ let channel = arg.get("channel").and_then(|c| c.as_str()).unwrap_or("");
+ let inst_id = arg.get("instId").and_then(|i| i.as_str()).unwrap_or("");
+
+ if let Some(data_arr) = data.get("data").and_then(|d| d.as_array()) {
+ for item in data_arr {
+ let adapter = BitgetAdapter::new(ProviderConfig::default());
+
+ let message = match channel {
+ "ticker" => adapter.parse_ticker(item).map(MarketMessage::Ticker),
+ "books5" | "books15" => {
+ adapter.parse_orderbook(item, inst_id).map(MarketMessage::OrderBook)
+ }
+ "trade" => adapter.parse_trade(item).map(MarketMessage::Trade),
+ _ => None,
+ };
+
+ if let Some(msg) = message {
+ cb(msg);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ Ok(Message::Ping(data)) => {
+ let _ = ws_lock.send(Message::Pong(data)).await;
+ }
+ Ok(Message::Close(_)) => {
+ *connected.write().await = false;
+ break;
+ }
+ Err(_) => {
+ *connected.write().await = false;
+ break;
+ }
+ _ => {}
+ }
+ }
+ });
+
+ Ok(())
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ if let Some(ws) = &self.ws {
+ let mut ws_lock = ws.write().await;
+ ws_lock.close(None).await?;
+ }
+ *self.connected.write().await = false;
+ self.ws = None;
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ _params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let bitget_symbol = Self::to_bitget_symbol(symbol);
+
+ let bitget_channel = match channel {
+ "ticker" => "ticker",
+ "book" | "depth" => "books5",
+ "trade" => "trade",
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let subscribe_msg = json!({
+ "op": "subscribe",
+ "args": [{
+ "instType": "SPOT",
+ "channel": bitget_channel,
+ "instId": bitget_symbol
+ }]
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(subscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let bitget_symbol = Self::to_bitget_symbol(symbol);
+
+ let bitget_channel = match channel {
+ "ticker" => "ticker",
+ "book" | "depth" => "books5",
+ "trade" => "trade",
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let unsubscribe_msg = json!({
+ "op": "unsubscribe",
+ "args": [{
+ "instType": "SPOT",
+ "channel": bitget_channel,
+ "instId": bitget_symbol
+ }]
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(unsubscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(Arc::new(callback));
+ }
+
+ fn provider_name(&self) -> &str {
+ "bitget"
+ }
+
+ fn is_connected(&self) -> bool {
+ *self.connected.blocking_read()
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/bybit.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/bybit.rs
new file mode 100644
index 000000000..56f69e032
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/bybit.rs
@@ -0,0 +1,332 @@
+#![allow(dead_code)]
+// Bybit WebSocket Adapter
+//
+// Implements Bybit WebSocket API v5
+// Supports: ticker, orderbook, trade, kline channels
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+const BYBIT_WS_URL: &str = "wss://stream.bybit.com/v5/public/spot";
+
+pub struct BybitAdapter {
+ config: ProviderConfig,
+ ws: Option<Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>>,
+ message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
+ connected: Arc<RwLock<bool>>,
+}
+
+impl BybitAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ ws: None,
+ message_callback: None,
+ connected: Arc::new(RwLock::new(false)),
+ }
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| std::time::Duration::from_secs(0))
+ .as_millis() as u64
+ }
+
+ /// Normalize Bybit symbol (BTCUSDT -> BTC/USDT)
+ fn normalize_bybit_symbol(symbol: &str) -> String {
+ for quote in ["USDT", "USDC", "USD", "BTC", "ETH"] {
+ if let Some(base) = symbol.strip_suffix(quote) {
+ return format!("{}/{}", base, quote);
+ }
+ }
+ symbol.to_string()
+ }
+
+ /// Convert symbol to Bybit format (BTC/USDT -> BTCUSDT)
+ fn to_bybit_symbol(symbol: &str) -> String {
+ symbol.replace('/', "").to_uppercase()
+ }
+
+ /// Parse Bybit ticker
+ fn parse_ticker(&self, data: &Value) -> Option<TickerData> {
+ let symbol = data.get("symbol")?.as_str()?;
+ let last_price = data.get("lastPrice")?.as_str()?.parse::<f64>().ok()?;
+ let bid = data.get("bid1Price")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let ask = data.get("ask1Price")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let bid_sz = data.get("bid1Size")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let ask_sz = data.get("ask1Size")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let volume = data.get("volume24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let high = data.get("highPrice24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let low = data.get("lowPrice24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let change_percent = data.get("price24hPcnt")?.as_str().and_then(|s| s.parse::<f64>().ok())
+ .map(|p| p * 100.0);
+
+ Some(TickerData {
+ provider: "bybit".to_string(),
+ symbol: Self::normalize_bybit_symbol(symbol),
+ price: last_price,
+ bid,
+ ask,
+ bid_size: bid_sz,
+ ask_size: ask_sz,
+ volume,
+ high,
+ low,
+ open: None,
+ close: Some(last_price),
+ change: None,
+ change_percent,
+ quote_volume: data.get("turnover24h")?.as_str().and_then(|s| s.parse::<f64>().ok()),
+ timestamp: Self::now(),
+ })
+ }
+
+ /// Parse Bybit order book
+ fn parse_orderbook(&self, data: &Value, symbol: &str) -> Option<OrderBookData> {
+ let bids = data.get("b")?.as_array()?;
+ let asks = data.get("a")?.as_array()?;
+
+ let parse_levels = |levels: &Vec<Value>| -> Vec<OrderBookLevel> {
+ levels
+ .iter()
+ .filter_map(|level| {
+ let arr = level.as_array()?;
+ Some(OrderBookLevel {
+ price: arr.get(0)?.as_str()?.parse::<f64>().ok()?,
+ quantity: arr.get(1)?.as_str()?.parse::<f64>().ok()?,
+ count: None,
+ })
+ })
+ .collect()
+ };
+
+ Some(OrderBookData {
+ provider: "bybit".to_string(),
+ symbol: Self::normalize_bybit_symbol(symbol),
+ bids: parse_levels(bids),
+ asks: parse_levels(asks),
+ timestamp: data.get("ts")?.as_u64().unwrap_or_else(Self::now),
+ is_snapshot: data.get("type")?.as_str() == Some("snapshot"),
+ })
+ }
+
+ /// Parse Bybit trade
+ fn parse_trade(&self, data: &Value) -> Option<TradeData> {
+ let symbol = data.get("s")?.as_str()?;
+ let price = data.get("p")?.as_str()?.parse::<f64>().ok()?;
+ let quantity = data.get("v")?.as_str()?.parse::<f64>().ok()?;
+ let side = data.get("S")?.as_str()?;
+ let trade_id = data.get("i")?.as_str().map(|s| s.to_string());
+ let ts = data.get("T")?.as_u64().unwrap_or_else(Self::now);
+
+ Some(TradeData {
+ provider: "bybit".to_string(),
+ symbol: Self::normalize_bybit_symbol(symbol),
+ trade_id,
+ price,
+ quantity,
+ side: match side {
+ "Buy" => TradeSide::Buy,
+ "Sell" => TradeSide::Sell,
+ _ => TradeSide::Unknown,
+ },
+ timestamp: ts,
+ })
+ }
+
+ /// Parse Bybit kline/candle
+ fn parse_candle(&self, data: &Value) -> Option<CandleData> {
+ let symbol = data.get("symbol")?.as_str()?;
+ let interval = data.get("interval")?.as_str()?;
+
+ // Bybit sends candles as arrays
+ let candle = data.get("list")?.as_array()?.first()?;
+ let arr = candle.as_array()?;
+
+ Some(CandleData {
+ provider: "bybit".to_string(),
+ symbol: Self::normalize_bybit_symbol(symbol),
+ interval: interval.to_string(),
+ open: arr.get(1)?.as_str()?.parse::<f64>().ok()?,
+ high: arr.get(2)?.as_str()?.parse::<f64>().ok()?,
+ low: arr.get(3)?.as_str()?.parse::<f64>().ok()?,
+ close: arr.get(4)?.as_str()?.parse::<f64>().ok()?,
+ volume: arr.get(5)?.as_str()?.parse::<f64>().ok()?,
+ timestamp: arr.get(0)?.as_str()?.parse::<u64>().ok()?,
+ })
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for BybitAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ let url = if self.config.url.is_empty() {
+ BYBIT_WS_URL
+ } else {
+ &self.config.url
+ };
+
+ let (ws_stream, _) = connect_async(url).await?;
+ let ws = Arc::new(RwLock::new(ws_stream));
+ self.ws = Some(ws.clone());
+ *self.connected.write().await = true;
+
+ let callback = self.message_callback.clone();
+ let connected = self.connected.clone();
+
+ tokio::spawn(async move {
+ let mut ws_lock = ws.write().await;
+
+ while let Some(msg) = ws_lock.next().await {
+ match msg {
+ Ok(Message::Text(text)) => {
+ if let Ok(data) = serde_json::from_str::<Value>(&text) {
+ if let Some(ref cb) = callback {
+ // Check topic for message type
+ if let Some(topic) = data.get("topic").and_then(|t| t.as_str()) {
+ if let Some(msg_data) = data.get("data") {
+ let adapter = BybitAdapter::new(ProviderConfig::default());
+
+ let message = if topic.starts_with("tickers.") {
+ adapter.parse_ticker(msg_data).map(MarketMessage::Ticker)
+ } else if topic.starts_with("orderbook.") {
+ let symbol = topic.split('.').last().unwrap_or("");
+ adapter.parse_orderbook(msg_data, symbol).map(MarketMessage::OrderBook)
+ } else if topic.starts_with("publicTrade.") {
+ // Trades come as an array
+ if let Some(trades) = msg_data.as_array() {
+ for trade in trades {
+ if let Some(t) = adapter.parse_trade(trade) {
+ cb(MarketMessage::Trade(t));
+ }
+ }
+ }
+ None
+ } else if topic.starts_with("kline.") {
+ adapter.parse_candle(msg_data).map(MarketMessage::Candle)
+ } else {
+ None
+ };
+
+ if let Some(msg) = message {
+ cb(msg);
+ }
+ }
+ }
+ }
+ }
+ }
+ Ok(Message::Ping(data)) => {
+ // Respond to ping
+ let mut ws_lock_inner = ws.write().await;
+ let _ = ws_lock_inner.send(Message::Pong(data)).await;
+ }
+ Ok(Message::Close(_)) => {
+ *connected.write().await = false;
+ break;
+ }
+ Err(_) => {
+ *connected.write().await = false;
+ break;
+ }
+ _ => {}
+ }
+ }
+ });
+
+ Ok(())
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ if let Some(ws) = &self.ws {
+ let mut ws_lock = ws.write().await;
+ ws_lock.close(None).await?;
+ }
+ *self.connected.write().await = false;
+ self.ws = None;
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let bybit_symbol = Self::to_bybit_symbol(symbol);
+
+ let topic = match channel {
+ "ticker" => format!("tickers.{}", bybit_symbol),
+ "book" | "depth" => {
+ let depth = params.as_ref()
+ .and_then(|p| p.get("depth"))
+ .and_then(|d| d.as_u64())
+ .unwrap_or(25);
+ format!("orderbook.{}.{}", depth, bybit_symbol)
+ }
+ "trade" => format!("publicTrade.{}", bybit_symbol),
+ "candle" | "ohlc" => {
+ let interval = params.as_ref()
+ .and_then(|p| p.get("interval"))
+ .and_then(|i| i.as_str())
+ .unwrap_or("1");
+ format!("kline.{}.{}", interval, bybit_symbol)
+ }
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let subscribe_msg = json!({
+ "op": "subscribe",
+ "args": [topic]
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(subscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let bybit_symbol = Self::to_bybit_symbol(symbol);
+
+ let topic = match channel {
+ "ticker" => format!("tickers.{}", bybit_symbol),
+ "book" | "depth" => format!("orderbook.25.{}", bybit_symbol),
+ "trade" => format!("publicTrade.{}", bybit_symbol),
+ "candle" | "ohlc" => format!("kline.1.{}", bybit_symbol),
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let unsubscribe_msg = json!({
+ "op": "unsubscribe",
+ "args": [topic]
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(unsubscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(Arc::new(callback));
+ }
+
+ fn provider_name(&self) -> &str {
+ "bybit"
+ }
+
+ fn is_connected(&self) -> bool {
+ *self.connected.blocking_read()
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/coinbase.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/coinbase.rs
new file mode 100644
index 000000000..8512cffdf
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/coinbase.rs
@@ -0,0 +1,279 @@
+#![allow(dead_code)]
+// Coinbase WebSocket Adapter
+//
+// Implements Coinbase Exchange WebSocket API
+// Supports: ticker, level2 (orderbook), matches (trades) channels
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+const COINBASE_WS_URL: &str = "wss://ws-feed.exchange.coinbase.com";
+
+pub struct CoinbaseAdapter {
+ config: ProviderConfig,
+ ws: Option<Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>>,
+ message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
+ connected: Arc<RwLock<bool>>,
+}
+
+impl CoinbaseAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ ws: None,
+ message_callback: None,
+ connected: Arc::new(RwLock::new(false)),
+ }
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| std::time::Duration::from_secs(0))
+ .as_millis() as u64
+ }
+
+ /// Normalize Coinbase symbol (BTC-USD -> BTC/USD)
+ fn normalize_coinbase_symbol(symbol: &str) -> String {
+ symbol.replace('-', "/")
+ }
+
+ /// Convert symbol to Coinbase format (BTC/USD -> BTC-USD)
+ fn to_coinbase_symbol(symbol: &str) -> String {
+ symbol.replace('/', "-")
+ }
+
+ /// Parse Coinbase ticker
+ fn parse_ticker(&self, data: &Value) -> Option<TickerData> {
+ let product_id = data.get("product_id")?.as_str()?;
+ let price = data.get("price")?.as_str()?.parse::<f64>().ok()?;
+ let bid = data.get("best_bid")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let ask = data.get("best_ask")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let bid_sz = data.get("best_bid_size")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let ask_sz = data.get("best_ask_size")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let volume = data.get("volume_24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let high = data.get("high_24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let low = data.get("low_24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let open = data.get("open_24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+
+ let change_percent = if let (Some(o), Some(p)) = (open, Some(price)) {
+ if o > 0.0 {
+ Some((p - o) / o * 100.0)
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ Some(TickerData {
+ provider: "coinbase".to_string(),
+ symbol: Self::normalize_coinbase_symbol(product_id),
+ price,
+ bid,
+ ask,
+ bid_size: bid_sz,
+ ask_size: ask_sz,
+ volume,
+ high,
+ low,
+ open,
+ close: Some(price),
+ change: None,
+ change_percent,
+ quote_volume: None,
+ timestamp: Self::now(),
+ })
+ }
+
+ /// Parse Coinbase level2 snapshot (orderbook)
+ fn parse_orderbook_snapshot(&self, data: &Value) -> Option<OrderBookData> {
+ let product_id = data.get("product_id")?.as_str()?;
+ let bids = data.get("bids")?.as_array()?;
+ let asks = data.get("asks")?.as_array()?;
+
+ let parse_levels = |levels: &Vec<Value>| -> Vec<OrderBookLevel> {
+ levels
+ .iter()
+ .filter_map(|level| {
+ let arr = level.as_array()?;
+ Some(OrderBookLevel {
+ price: arr.get(0)?.as_str()?.parse::<f64>().ok()?,
+ quantity: arr.get(1)?.as_str()?.parse::<f64>().ok()?,
+ count: None,
+ })
+ })
+ .collect()
+ };
+
+ Some(OrderBookData {
+ provider: "coinbase".to_string(),
+ symbol: Self::normalize_coinbase_symbol(product_id),
+ bids: parse_levels(bids),
+ asks: parse_levels(asks),
+ timestamp: Self::now(),
+ is_snapshot: true,
+ })
+ }
+
+ /// Parse Coinbase match (trade)
+ fn parse_trade(&self, data: &Value) -> Option<TradeData> {
+ let product_id = data.get("product_id")?.as_str()?;
+ let price = data.get("price")?.as_str()?.parse::<f64>().ok()?;
+ let size = data.get("size")?.as_str()?.parse::<f64>().ok()?;
+ let side = data.get("side")?.as_str()?;
+ let trade_id = data.get("trade_id")?.as_u64().map(|t| t.to_string());
+
+ Some(TradeData {
+ provider: "coinbase".to_string(),
+ symbol: Self::normalize_coinbase_symbol(product_id),
+ trade_id,
+ price,
+ quantity: size,
+ side: match side {
+ "buy" => TradeSide::Buy,
+ "sell" => TradeSide::Sell,
+ _ => TradeSide::Unknown,
+ },
+ timestamp: Self::now(),
+ })
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for CoinbaseAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ let url = if self.config.url.is_empty() {
+ COINBASE_WS_URL
+ } else {
+ &self.config.url
+ };
+
+ let (ws_stream, _) = connect_async(url).await?;
+ let ws = Arc::new(RwLock::new(ws_stream));
+ self.ws = Some(ws.clone());
+ *self.connected.write().await = true;
+
+ let callback = self.message_callback.clone();
+ let connected = self.connected.clone();
+
+ tokio::spawn(async move {
+ let mut ws_lock = ws.write().await;
+
+ while let Some(msg) = ws_lock.next().await {
+ match msg {
+ Ok(Message::Text(text)) => {
+ if let Ok(data) = serde_json::from_str::<Value>(&text) {
+ if let Some(ref cb) = callback {
+ let msg_type = data.get("type").and_then(|t| t.as_str()).unwrap_or("");
+ let adapter = CoinbaseAdapter::new(ProviderConfig::default());
+
+ let message = match msg_type {
+ "ticker" => adapter.parse_ticker(&data).map(MarketMessage::Ticker),
+ "snapshot" => adapter.parse_orderbook_snapshot(&data).map(MarketMessage::OrderBook),
+ "match" | "last_match" => adapter.parse_trade(&data).map(MarketMessage::Trade),
+ _ => None,
+ };
+
+ if let Some(msg) = message {
+ cb(msg);
+ }
+ }
+ }
+ }
+ Ok(Message::Close(_)) => {
+ *connected.write().await = false;
+ break;
+ }
+ Err(_) => {
+ *connected.write().await = false;
+ break;
+ }
+ _ => {}
+ }
+ }
+ });
+
+ Ok(())
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ if let Some(ws) = &self.ws {
+ let mut ws_lock = ws.write().await;
+ ws_lock.close(None).await?;
+ }
+ *self.connected.write().await = false;
+ self.ws = None;
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ _params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let coinbase_symbol = Self::to_coinbase_symbol(symbol);
+
+ let coinbase_channel = match channel {
+ "ticker" => "ticker",
+ "book" | "depth" => "level2",
+ "trade" => "matches",
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let subscribe_msg = json!({
+ "type": "subscribe",
+ "product_ids": [coinbase_symbol],
+ "channels": [coinbase_channel]
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(subscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let coinbase_symbol = Self::to_coinbase_symbol(symbol);
+
+ let coinbase_channel = match channel {
+ "ticker" => "ticker",
+ "book" | "depth" => "level2",
+ "trade" => "matches",
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let unsubscribe_msg = json!({
+ "type": "unsubscribe",
+ "product_ids": [coinbase_symbol],
+ "channels": [coinbase_channel]
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(unsubscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(Arc::new(callback));
+ }
+
+ fn provider_name(&self) -> &str {
+ "coinbase"
+ }
+
+ fn is_connected(&self) -> bool {
+ *self.connected.blocking_read()
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/dhan.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/dhan.rs
index dba3fb759..330735792 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/dhan.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/dhan.rs
@@ -409,6 +409,7 @@ impl DhanAdapter {
close: Some(tick.close as f64),
change: None,
change_percent: None,
+ quote_volume: None,
timestamp: tick.ltt as u64,
})
}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs
index 7d26bf33d..4c7cd3735 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs
@@ -61,22 +61,6 @@ const DEPTH_FIELDS: &[&str] = &[
"type", "symbol"
];
-/// Exchange segment mapping (fytoken prefix -> segment name)
-#[allow(dead_code)]
-fn get_exchange_segment(segment_code: &str) -> &'static str {
- match segment_code {
- "1010" => "nse_cm", // NSE Cash
- "1011" => "nse_fo", // NSE F&O
- "1120" => "mcx_fo", // MCX F&O
- "1210" => "bse_cm", // BSE Cash
- "1211" => "bse_fo", // BSE F&O
- "1212" => "bcs_fo", // BSE Currency
- "1012" => "cde_fo", // CDE F&O
- "1020" => "nse_com", // NSE Commodity
- _ => "unknown",
- }
-}
-
// ============================================================================
// FYERS DATA TYPES
// ============================================================================
@@ -655,6 +639,7 @@ impl FyersAdapter {
close: scrip_data.get("prev_close_price").map(|v| *v as f64 / divisor),
change: None, // Calculate from ltp - prev_close
change_percent: None,
+ quote_volume: None,
timestamp: scrip_data.get("exch_feed_time").map(|v| *v as u64).unwrap_or_else(|| chrono::Utc::now().timestamp() as u64),
};
@@ -735,6 +720,7 @@ impl FyersAdapter {
close: index_data.get("prev_close_price").map(|v| *v as f64 / divisor),
change: None,
change_percent: None,
+ quote_volume: None,
timestamp: index_data.get("exch_feed_time").map(|v| *v as u64).unwrap_or_else(|| chrono::Utc::now().timestamp() as u64),
};
@@ -981,6 +967,7 @@ impl FyersAdapter {
close: cache_entry.get("prev_close_price").map(|v| *v as f64 / divisor),
change: None,
change_percent: None,
+ quote_volume: None,
timestamp: cache_entry.get("exch_feed_time").map(|v| *v as u64).unwrap_or_else(|| chrono::Utc::now().timestamp() as u64),
};
@@ -1173,7 +1160,8 @@ impl WebSocketAdapter for FyersAdapter {
}
// Send authentication message
- let hsm_key = self.hsm_key.as_ref().unwrap();
+ let hsm_key = self.hsm_key.as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Fyers HSM key not set — call set_config with hsm_key before connecting"))?;
let auth_msg = Self::create_auth_message(hsm_key);
{
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/gateio.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/gateio.rs
new file mode 100644
index 000000000..51d957368
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/gateio.rs
@@ -0,0 +1,279 @@
+#![allow(dead_code)]
+// Gate.io WebSocket Adapter
+//
+// Implements Gate.io WebSocket API v4
+// Supports: ticker, orderbook, trades channels
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+const GATEIO_WS_URL: &str = "wss://api.gateio.ws/ws/v4/";
+
+pub struct GateioAdapter {
+ config: ProviderConfig,
+ ws: Option<Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>>,
+ message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
+ connected: Arc<RwLock<bool>>,
+}
+
+impl GateioAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ ws: None,
+ message_callback: None,
+ connected: Arc::new(RwLock::new(false)),
+ }
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| std::time::Duration::from_secs(0))
+ .as_millis() as u64
+ }
+
+ /// Normalize Gate.io symbol (BTC_USDT -> BTC/USDT)
+ fn normalize_gateio_symbol(symbol: &str) -> String {
+ symbol.replace('_', "/")
+ }
+
+ /// Convert symbol to Gate.io format (BTC/USDT -> BTC_USDT)
+ fn to_gateio_symbol(symbol: &str) -> String {
+ symbol.replace('/', "_")
+ }
+
+ /// Parse Gate.io ticker
+ fn parse_ticker(&self, data: &Value) -> Option<TickerData> {
+ let result = data.get("result")?;
+ let currency_pair = result.get("currency_pair")?.as_str()?;
+ let last = result.get("last")?.as_str()?.parse::<f64>().ok()?;
+ let high = result.get("high_24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let low = result.get("low_24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let volume = result.get("base_volume")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let quote_volume = result.get("quote_volume")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let change_percent = result.get("change_percentage")?.as_str().and_then(|s| s.parse::<f64>().ok());
+
+ Some(TickerData {
+ provider: "gateio".to_string(),
+ symbol: Self::normalize_gateio_symbol(currency_pair),
+ price: last,
+ bid: None,
+ ask: None,
+ bid_size: None,
+ ask_size: None,
+ volume,
+ high,
+ low,
+ open: None,
+ close: Some(last),
+ change: None,
+ change_percent,
+ quote_volume,
+ timestamp: Self::now(),
+ })
+ }
+
+ /// Parse Gate.io order book
+ fn parse_orderbook(&self, data: &Value) -> Option<OrderBookData> {
+ let result = data.get("result")?;
+ let symbol = result.get("s")?.as_str()?;
+ let bids = result.get("bids")?.as_array()?;
+ let asks = result.get("asks")?.as_array()?;
+
+ let parse_levels = |levels: &Vec<Value>| -> Vec<OrderBookLevel> {
+ levels
+ .iter()
+ .filter_map(|level| {
+ let arr = level.as_array()?;
+ Some(OrderBookLevel {
+ price: arr.get(0)?.as_str()?.parse::<f64>().ok()?,
+ quantity: arr.get(1)?.as_str()?.parse::<f64>().ok()?,
+ count: None,
+ })
+ })
+ .collect()
+ };
+
+ Some(OrderBookData {
+ provider: "gateio".to_string(),
+ symbol: Self::normalize_gateio_symbol(symbol),
+ bids: parse_levels(bids),
+ asks: parse_levels(asks),
+ timestamp: result.get("t")?.as_u64().unwrap_or_else(Self::now),
+ is_snapshot: true,
+ })
+ }
+
+ /// Parse Gate.io trade
+ fn parse_trade(&self, data: &Value) -> Option<TradeData> {
+ let result = data.get("result")?;
+ let currency_pair = result.get("currency_pair")?.as_str()?;
+ let price = result.get("price")?.as_str()?.parse::<f64>().ok()?;
+ let amount = result.get("amount")?.as_str()?.parse::<f64>().ok()?;
+ let side = result.get("side")?.as_str()?;
+ let id = result.get("id")?.as_u64().map(|i| i.to_string());
+ let ts = result.get("create_time_ms")?.as_str()?.parse::<u64>().ok().unwrap_or_else(Self::now);
+
+ Some(TradeData {
+ provider: "gateio".to_string(),
+ symbol: Self::normalize_gateio_symbol(currency_pair),
+ trade_id: id,
+ price,
+ quantity: amount,
+ side: match side {
+ "buy" => TradeSide::Buy,
+ "sell" => TradeSide::Sell,
+ _ => TradeSide::Unknown,
+ },
+ timestamp: ts,
+ })
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for GateioAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ let url = if self.config.url.is_empty() {
+ GATEIO_WS_URL
+ } else {
+ &self.config.url
+ };
+
+ let (ws_stream, _) = connect_async(url).await?;
+ let ws = Arc::new(RwLock::new(ws_stream));
+ self.ws = Some(ws.clone());
+ *self.connected.write().await = true;
+
+ let callback = self.message_callback.clone();
+ let connected = self.connected.clone();
+
+ tokio::spawn(async move {
+ let mut ws_lock = ws.write().await;
+
+ while let Some(msg) = ws_lock.next().await {
+ match msg {
+ Ok(Message::Text(text)) => {
+ if let Ok(data) = serde_json::from_str::<Value>(&text) {
+ if let Some(ref cb) = callback {
+ let channel = data.get("channel").and_then(|c| c.as_str()).unwrap_or("");
+ let event = data.get("event").and_then(|e| e.as_str()).unwrap_or("");
+
+ if event == "update" {
+ let adapter = GateioAdapter::new(ProviderConfig::default());
+
+ let message = match channel {
+ "spot.tickers" => adapter.parse_ticker(&data).map(MarketMessage::Ticker),
+ "spot.order_book" => adapter.parse_orderbook(&data).map(MarketMessage::OrderBook),
+ "spot.trades" => adapter.parse_trade(&data).map(MarketMessage::Trade),
+ _ => None,
+ };
+
+ if let Some(msg) = message {
+ cb(msg);
+ }
+ }
+ }
+ }
+ }
+ Ok(Message::Ping(data)) => {
+ let _ = ws_lock.send(Message::Pong(data)).await;
+ }
+ Ok(Message::Close(_)) => {
+ *connected.write().await = false;
+ break;
+ }
+ Err(_) => {
+ *connected.write().await = false;
+ break;
+ }
+ _ => {}
+ }
+ }
+ });
+
+ Ok(())
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ if let Some(ws) = &self.ws {
+ let mut ws_lock = ws.write().await;
+ ws_lock.close(None).await?;
+ }
+ *self.connected.write().await = false;
+ self.ws = None;
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ _params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let gateio_symbol = Self::to_gateio_symbol(symbol);
+
+ let (gateio_channel, payload) = match channel {
+ "ticker" => ("spot.tickers", json!([gateio_symbol])),
+ "book" | "depth" => ("spot.order_book", json!([gateio_symbol, "20", "100ms"])),
+ "trade" => ("spot.trades", json!([gateio_symbol])),
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let subscribe_msg = json!({
+ "time": Self::now() / 1000,
+ "channel": gateio_channel,
+ "event": "subscribe",
+ "payload": payload
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(subscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let gateio_symbol = Self::to_gateio_symbol(symbol);
+
+ let (gateio_channel, payload) = match channel {
+ "ticker" => ("spot.tickers", json!([gateio_symbol])),
+ "book" | "depth" => ("spot.order_book", json!([gateio_symbol, "20", "100ms"])),
+ "trade" => ("spot.trades", json!([gateio_symbol])),
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let unsubscribe_msg = json!({
+ "time": Self::now() / 1000,
+ "channel": gateio_channel,
+ "event": "unsubscribe",
+ "payload": payload
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(unsubscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(Arc::new(callback));
+ }
+
+ fn provider_name(&self) -> &str {
+ "gateio"
+ }
+
+ fn is_connected(&self) -> bool {
+ *self.connected.blocking_read()
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/huobi.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/huobi.rs
new file mode 100644
index 000000000..0dc6d3204
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/huobi.rs
@@ -0,0 +1,312 @@
+#![allow(dead_code)]
+// Huobi WebSocket Adapter
+//
+// Implements Huobi WebSocket API
+// Supports: ticker, depth, trade channels
+// Note: Huobi uses gzip compression for messages
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use std::io::Read;
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+const HUOBI_WS_URL: &str = "wss://api.huobi.pro/ws";
+
+pub struct HuobiAdapter {
+ config: ProviderConfig,
+ ws: Option<Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>>,
+ message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
+ connected: Arc<RwLock<bool>>,
+}
+
+impl HuobiAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ ws: None,
+ message_callback: None,
+ connected: Arc::new(RwLock::new(false)),
+ }
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| std::time::Duration::from_secs(0))
+ .as_millis() as u64
+ }
+
+ /// Decompress gzip data
+ fn decompress_gzip(data: &[u8]) -> Option<String> {
+ let mut decoder = flate2::read::GzDecoder::new(data);
+ let mut decompressed = String::new();
+ decoder.read_to_string(&mut decompressed).ok()?;
+ Some(decompressed)
+ }
+
+ /// Normalize Huobi symbol (btcusdt -> BTC/USDT)
+ fn normalize_huobi_symbol(symbol: &str) -> String {
+ let symbol_upper = symbol.to_uppercase();
+ for quote in ["USDT", "USDC", "USD", "BTC", "ETH", "HUSD"] {
+ if let Some(base) = symbol_upper.strip_suffix(quote) {
+ return format!("{}/{}", base, quote);
+ }
+ }
+ symbol_upper
+ }
+
+ /// Convert symbol to Huobi format (BTC/USDT -> btcusdt)
+ fn to_huobi_symbol(symbol: &str) -> String {
+ symbol.replace('/', "").to_lowercase()
+ }
+
+ /// Parse Huobi ticker
+ fn parse_ticker(&self, data: &Value, symbol: &str) -> Option<TickerData> {
+ let tick = data.get("tick")?;
+ let close = tick.get("close")?.as_f64()?;
+ let open = tick.get("open")?.as_f64();
+ let high = tick.get("high")?.as_f64();
+ let low = tick.get("low")?.as_f64();
+ let volume = tick.get("vol")?.as_f64();
+ let bid = tick.get("bid")?.as_array().and_then(|a| a.first()?.as_f64());
+ let ask = tick.get("ask")?.as_array().and_then(|a| a.first()?.as_f64());
+ let bid_sz = tick.get("bid")?.as_array().and_then(|a| a.get(1)?.as_f64());
+ let ask_sz = tick.get("ask")?.as_array().and_then(|a| a.get(1)?.as_f64());
+
+ let change_percent = if let Some(o) = open {
+ if o > 0.0 {
+ Some((close - o) / o * 100.0)
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ Some(TickerData {
+ provider: "huobi".to_string(),
+ symbol: Self::normalize_huobi_symbol(symbol),
+ price: close,
+ bid,
+ ask,
+ bid_size: bid_sz,
+ ask_size: ask_sz,
+ volume,
+ high,
+ low,
+ open,
+ close: Some(close),
+ change: None,
+ change_percent,
+ quote_volume: None,
+ timestamp: data.get("ts")?.as_u64().unwrap_or_else(Self::now),
+ })
+ }
+
+ /// Parse Huobi order book
+ fn parse_orderbook(&self, data: &Value, symbol: &str) -> Option<OrderBookData> {
+ let tick = data.get("tick")?;
+ let bids = tick.get("bids")?.as_array()?;
+ let asks = tick.get("asks")?.as_array()?;
+
+ let parse_levels = |levels: &Vec<Value>| -> Vec<OrderBookLevel> {
+ levels
+ .iter()
+ .filter_map(|level| {
+ let arr = level.as_array()?;
+ Some(OrderBookLevel {
+ price: arr.get(0)?.as_f64()?,
+ quantity: arr.get(1)?.as_f64()?,
+ count: None,
+ })
+ })
+ .collect()
+ };
+
+ Some(OrderBookData {
+ provider: "huobi".to_string(),
+ symbol: Self::normalize_huobi_symbol(symbol),
+ bids: parse_levels(bids),
+ asks: parse_levels(asks),
+ timestamp: data.get("ts")?.as_u64().unwrap_or_else(Self::now),
+ is_snapshot: true,
+ })
+ }
+
+ /// Parse Huobi trade
+ fn parse_trade(&self, data: &Value, symbol: &str) -> Option<TradeData> {
+ let tick = data.get("tick")?;
+ let trade_data = tick.get("data")?.as_array()?.first()?;
+
+ let price = trade_data.get("price")?.as_f64()?;
+ let amount = trade_data.get("amount")?.as_f64()?;
+ let direction = trade_data.get("direction")?.as_str()?;
+ let id = trade_data.get("tradeId")?.as_u64().map(|i| i.to_string());
+ let ts = trade_data.get("ts")?.as_u64().unwrap_or_else(Self::now);
+
+ Some(TradeData {
+ provider: "huobi".to_string(),
+ symbol: Self::normalize_huobi_symbol(symbol),
+ trade_id: id,
+ price,
+ quantity: amount,
+ side: match direction {
+ "buy" => TradeSide::Buy,
+ "sell" => TradeSide::Sell,
+ _ => TradeSide::Unknown,
+ },
+ timestamp: ts,
+ })
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for HuobiAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ let url = if self.config.url.is_empty() {
+ HUOBI_WS_URL
+ } else {
+ &self.config.url
+ };
+
+ let (ws_stream, _) = connect_async(url).await?;
+ let ws = Arc::new(RwLock::new(ws_stream));
+ self.ws = Some(ws.clone());
+ *self.connected.write().await = true;
+
+ let callback = self.message_callback.clone();
+ let connected = self.connected.clone();
+
+ tokio::spawn(async move {
+ let mut ws_lock = ws.write().await;
+
+ while let Some(msg) = ws_lock.next().await {
+ match msg {
+ Ok(Message::Binary(data)) => {
+ // Huobi sends gzip compressed messages
+ if let Some(text) = Self::decompress_gzip(&data) {
+ if let Ok(json_data) = serde_json::from_str::<Value>(&text) {
+ // Handle ping
+ if let Some(ping) = json_data.get("ping") {
+ let pong = json!({ "pong": ping });
+ let _ = ws_lock.send(Message::Text(pong.to_string())).await;
+ continue;
+ }
+
+ if let Some(ref cb) = callback {
+ if let Some(ch) = json_data.get("ch").and_then(|c| c.as_str()) {
+ let parts: Vec<&str> = ch.split('.').collect();
+ if parts.len() >= 3 {
+ let symbol = parts[1];
+ let channel = parts[2];
+ let adapter = HuobiAdapter::new(ProviderConfig::default());
+
+ let message = match channel {
+ "ticker" => adapter.parse_ticker(&json_data, symbol).map(MarketMessage::Ticker),
+ "depth" => adapter.parse_orderbook(&json_data, symbol).map(MarketMessage::OrderBook),
+ "trade" => adapter.parse_trade(&json_data, symbol).map(MarketMessage::Trade),
+ _ => None,
+ };
+
+ if let Some(msg) = message {
+ cb(msg);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ Ok(Message::Close(_)) => {
+ *connected.write().await = false;
+ break;
+ }
+ Err(_) => {
+ *connected.write().await = false;
+ break;
+ }
+ _ => {}
+ }
+ }
+ });
+
+ Ok(())
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ if let Some(ws) = &self.ws {
+ let mut ws_lock = ws.write().await;
+ ws_lock.close(None).await?;
+ }
+ *self.connected.write().await = false;
+ self.ws = None;
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ _params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let huobi_symbol = Self::to_huobi_symbol(symbol);
+
+ let sub_channel = match channel {
+ "ticker" => format!("market.{}.ticker", huobi_symbol),
+ "book" | "depth" => format!("market.{}.depth.step0", huobi_symbol),
+ "trade" => format!("market.{}.trade.detail", huobi_symbol),
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let subscribe_msg = json!({
+ "sub": sub_channel,
+ "id": format!("id{}", Self::now())
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(subscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let huobi_symbol = Self::to_huobi_symbol(symbol);
+
+ let unsub_channel = match channel {
+ "ticker" => format!("market.{}.ticker", huobi_symbol),
+ "book" | "depth" => format!("market.{}.depth.step0", huobi_symbol),
+ "trade" => format!("market.{}.trade.detail", huobi_symbol),
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let unsubscribe_msg = json!({
+ "unsub": unsub_channel,
+ "id": format!("id{}", Self::now())
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(unsubscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(Arc::new(callback));
+ }
+
+ fn provider_name(&self) -> &str {
+ "huobi"
+ }
+
+ fn is_connected(&self) -> bool {
+ *self.connected.blocking_read()
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/hyperliquid.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/hyperliquid.rs
index b3543cdb4..4e8f0b766 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/hyperliquid.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/hyperliquid.rs
@@ -234,6 +234,7 @@ impl HyperLiquidAdapter {
close: None,
change: None,
change_percent: None,
+ quote_volume: None,
timestamp: chrono::Utc::now().timestamp_millis() as u64,
}));
}
@@ -325,6 +326,7 @@ impl WebSocketAdapter for HyperLiquidAdapter {
close: None,
change: None,
change_percent: None,
+ quote_volume: None,
timestamp: chrono::Utc::now().timestamp_millis() as u64,
}));
}
@@ -403,6 +405,7 @@ impl WebSocketAdapter for HyperLiquidAdapter {
close: None,
change: None,
change_percent: None,
+ quote_volume: None,
timestamp: bbo.time,
});
drop(states); // Release lock
@@ -455,6 +458,7 @@ impl WebSocketAdapter for HyperLiquidAdapter {
close: Some(close),
change: Some(change),
change_percent: Some(change_percent),
+ quote_volume: None,
timestamp: candle.end_time,
});
drop(states); // Release lock
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kraken.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kraken.rs
index 11b0cb9f1..7d34b7ead 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kraken.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kraken.rs
@@ -1,7 +1,8 @@
#![allow(dead_code)]
-// Kraken WebSocket Adapter
+// Kraken WebSocket Adapter v2
//
-// Implements Kraken WebSocket API v2
+// Implements Kraken WebSocket API v2 with proper real-time price streaming
+// Reference: https://docs.kraken.com/api/docs/websocket-v2/ticker
// Supports: ticker, book, trade, ohlc channels
use super::WebSocketAdapter;
@@ -10,20 +11,25 @@ use async_trait::async_trait;
use futures_util::stream::SplitSink;
use futures_util::{SinkExt, StreamExt};
use serde_json::Value;
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
-use tokio::sync::{Mutex, RwLock};
+use tokio::sync::Mutex;
use tokio_tungstenite::{connect_async, tungstenite::Message};
+// Kraken WebSocket v2 public endpoint
const KRAKEN_WS_URL: &str = "wss://ws.kraken.com/v2";
+// Heartbeat interval (30 seconds - Kraken sends heartbeats)
+const HEARTBEAT_TIMEOUT_MS: u64 = 45_000;
+
type WsStream = tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
type WsSink = SplitSink<WsStream, Message>;
/// Callback type for connection errors (used to trigger reconnection)
type ErrorCallback = Box<dyn Fn(String) + Send + Sync>;
+/// Kraken WebSocket Adapter - implements proper v2 API
pub struct KrakenAdapter {
config: ProviderConfig,
// Write half of the split stream — used by subscribe/unsubscribe/disconnect
@@ -31,7 +37,9 @@ pub struct KrakenAdapter {
message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
error_callback: Option<Arc<ErrorCallback>>,
connected: Arc<AtomicBool>,
- last_message_time: Arc<RwLock<u64>>,
+ last_message_time: Arc<AtomicU64>,
+ // Shutdown signal for background tasks
+ shutdown: Arc<AtomicBool>,
}
impl KrakenAdapter {
@@ -42,7 +50,8 @@ impl KrakenAdapter {
message_callback: None,
error_callback: None,
connected: Arc::new(AtomicBool::new(false)),
- last_message_time: Arc::new(RwLock::new(0)),
+ last_message_time: Arc::new(AtomicU64::new(0)),
+ shutdown: Arc::new(AtomicBool::new(false)),
}
}
@@ -58,9 +67,34 @@ impl KrakenAdapter {
self.error_callback = Some(Arc::new(callback));
}
- /// Normalize Kraken symbol (XBT -> BTC)
- fn normalize_kraken_symbol(symbol: &str) -> String {
- symbol.replace("XBT", "BTC").replace('/', "")
+ /// Normalize Kraken symbol to standard format
+ /// Kraken API v2 uses standard format like "BTC/USD"
+ /// We normalize XBT -> BTC and remove slashes for internal matching
+ fn normalize_symbol(symbol: &str) -> String {
+ symbol
+ .replace("XBT", "BTC")
+ .replace("XDG", "DOGE")
+ .replace('/', "")
+ }
+
+ /// Convert standard symbol to Kraken format for subscription
+ /// Input: "BTC/USD" or "BTCUSD" -> Output: "BTC/USD" (Kraken v2 format)
+ fn to_kraken_symbol(symbol: &str) -> String {
+ // If already has slash, use as-is
+ if symbol.contains('/') {
+ return symbol.to_string();
+ }
+
+ // Otherwise try to detect the quote currency and add slash
+ let upper = symbol.to_uppercase();
+ for quote in ["USD", "USDT", "EUR", "GBP", "JPY", "CAD", "AUD", "CHF", "BTC", "ETH"] {
+ if let Some(base) = upper.strip_suffix(quote) {
+ return format!("{}/{}", base, quote);
+ }
+ }
+
+ // Fallback: return as-is
+ symbol.to_string()
}
/// Message receiver loop — only holds the read half, never blocks writes
@@ -70,27 +104,31 @@ impl KrakenAdapter {
callback: Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>,
error_callback: Option<Arc<ErrorCallback>>,
connected: Arc<AtomicBool>,
- last_message_time: Arc<RwLock<u64>>,
+ last_message_time: Arc<AtomicU64>,
+ shutdown: Arc<AtomicBool>,
) {
+ eprintln!("[Kraken] Receive loop started");
+
loop {
+ // Check shutdown signal
+ if shutdown.load(Ordering::SeqCst) {
+ eprintln!("[Kraken] Shutdown signal received, exiting receive loop");
+ break;
+ }
+
let msg_result = read_stream.next().await;
match msg_result {
Some(Ok(msg)) => {
// Update last message time
- *last_message_time.write().await = Self::now();
+ last_message_time.store(Self::now(), Ordering::SeqCst);
match &msg {
Message::Text(text) => {
- let cb = callback.clone();
- let text_clone = text.clone();
- tokio::spawn(async move {
- if let Ok(data) = serde_json::from_str::<Value>(&text_clone) {
- Self::process_message(&data, &cb);
- }
- });
+ Self::handle_text_message(text, &callback);
}
Message::Ping(data) => {
+ // Respond to ping with pong
let sink = write_sink.clone();
let pong_data = data.clone();
tokio::spawn(async move {
@@ -101,12 +139,12 @@ impl KrakenAdapter {
// Pong received - heartbeat acknowledged
}
Message::Close(frame) => {
- eprintln!("[Kraken WS] Close frame received: {:?}", frame);
+ eprintln!("[Kraken] Close frame received: {:?}", frame);
connected.store(false, Ordering::SeqCst);
callback(MarketMessage::Status(StatusData {
provider: "kraken".to_string(),
status: ConnectionStatus::Disconnected,
- message: Some(format!("Server closed connection: {:?}", frame)),
+ message: Some(format!("Server closed: {:?}", frame)),
timestamp: Self::now(),
}));
break;
@@ -116,6 +154,7 @@ impl KrakenAdapter {
}
Some(Err(e)) => {
let error_msg = format!("WebSocket error: {}", e);
+ eprintln!("[Kraken] {}", error_msg);
connected.store(false, Ordering::SeqCst);
callback(MarketMessage::Status(StatusData {
@@ -131,7 +170,8 @@ impl KrakenAdapter {
break;
}
None => {
- let error_msg = "WebSocket connection closed unexpectedly".to_string();
+ let error_msg = "WebSocket connection closed".to_string();
+ eprintln!("[Kraken] {}", error_msg);
connected.store(false, Ordering::SeqCst);
callback(MarketMessage::Status(StatusData {
@@ -148,75 +188,156 @@ impl KrakenAdapter {
}
}
}
+
+ eprintln!("[Kraken] Receive loop ended");
+ }
+
+ /// Handle incoming text message
+ fn handle_text_message(text: &str, callback: &Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>) {
+ // Debug: log first few raw messages
+ static RAW_MSG_COUNT: AtomicU64 = AtomicU64::new(0);
+ let count = RAW_MSG_COUNT.fetch_add(1, Ordering::Relaxed);
+ if count < 10 {
+ let preview = &text[..std::cmp::min(300, text.len())];
+ eprintln!("[Kraken] Raw msg #{}: {}", count, preview);
+ }
+
+ let cb = callback.clone();
+ let text_clone = text.to_string();
+
+ // Parse JSON and process
+ if let Ok(data) = serde_json::from_str::<Value>(&text_clone) {
+ Self::process_message(&data, &cb);
+ }
}
/// Process a parsed message and route to callback
fn process_message(data: &Value, callback: &Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>) {
- if let Some(channel) = data.get("channel").and_then(|c| c.as_str()) {
- match channel {
- "ticker" => {
- if let Some(ticker) = Self::parse_ticker_static(data) {
- callback(MarketMessage::Ticker(ticker));
+ // Get channel type
+ let channel = match data.get("channel").and_then(|c| c.as_str()) {
+ Some(c) => c,
+ None => return, // Not a data message
+ };
+
+ // Get message type (snapshot, update, etc.)
+ let msg_type = data.get("type").and_then(|t| t.as_str()).unwrap_or("");
+
+ match channel {
+ "ticker" => {
+ if let Some(ticker) = Self::parse_ticker(data) {
+ // Debug log
+ static TICKER_COUNT: AtomicU64 = AtomicU64::new(0);
+ let count = TICKER_COUNT.fetch_add(1, Ordering::Relaxed);
+ if count < 5 || count % 50 == 0 {
+ eprintln!("[Kraken] Ticker #{}: {} @ {:.2}", count, ticker.symbol, ticker.price);
}
+ callback(MarketMessage::Ticker(ticker));
}
- "book" => {
- let is_snapshot = data.get("type")
- .and_then(|t| t.as_str())
- .map(|t| t == "snapshot")
- .unwrap_or(false);
-
- if let Some(book) = Self::parse_orderbook_static(data, is_snapshot) {
- callback(MarketMessage::OrderBook(book));
- }
+ }
+ "book" => {
+ let is_snapshot = msg_type == "snapshot";
+ if let Some(book) = Self::parse_orderbook(data, is_snapshot) {
+ callback(MarketMessage::OrderBook(book));
}
- "trade" => {
- if let Some(trades) = Self::parse_trade_static(data) {
- for trade in trades {
- callback(MarketMessage::Trade(trade));
- }
+ }
+ "trade" => {
+ if let Some(trades) = Self::parse_trades(data) {
+ for trade in trades {
+ callback(MarketMessage::Trade(trade));
}
}
- "ohlc" => {
- if let Some(candle) = Self::parse_candle_static(data) {
- callback(MarketMessage::Candle(candle));
- }
+ }
+ "ohlc" => {
+ if let Some(candle) = Self::parse_candle(data) {
+ callback(MarketMessage::Candle(candle));
}
- "heartbeat" | "status" => {
- // Heartbeat and status messages - ignore silently
+ }
+ "heartbeat" => {
+ // Heartbeat received - connection is alive
+ // eprintln!("[Kraken] Heartbeat received");
+ }
+ "status" => {
+ // System status message
+ if let Some(status) = data.get("data").and_then(|d| d.as_array()).and_then(|a| a.first()) {
+ let system = status.get("system").and_then(|s| s.as_str()).unwrap_or("unknown");
+ let version = status.get("version").and_then(|v| v.as_str()).unwrap_or("unknown");
+ eprintln!("[Kraken] System status: {} v{}", system, version);
+ }
+ }
+ _ => {
+ // Unknown channel - log for debugging
+ static UNKNOWN_COUNT: AtomicU64 = AtomicU64::new(0);
+ let count = UNKNOWN_COUNT.fetch_add(1, Ordering::Relaxed);
+ if count < 5 {
+ eprintln!("[Kraken] Unknown channel: {}", channel);
}
- _ => {}
}
}
}
- // Static parsing methods (don't need &self)
- fn parse_ticker_static(data: &Value) -> Option<TickerData> {
- let ticker_data = data.get("data")?.as_array()?.get(0)?;
- let symbol = ticker_data.get("symbol")?.as_str()?;
- let last = ticker_data.get("last")?.as_f64()?;
+ /// Parse ticker data from Kraken v2 format
+ /// Example response:
+ /// {
+ /// "channel": "ticker",
+ /// "type": "snapshot",
+ /// "data": [{
+ /// "symbol": "BTC/USD",
+ /// "bid": 42000.0,
+ /// "bid_qty": 0.5,
+ /// "ask": 42010.0,
+ /// "ask_qty": 0.3,
+ /// "last": 42005.0,
+ /// "volume": 1234.5,
+ /// "vwap": 41950.0,
+ /// "low": 41000.0,
+ /// "high": 43000.0,
+ /// "change": 500.0,
+ /// "change_pct": 1.2
+ /// }]
+ /// }
+ fn parse_ticker(data: &Value) -> Option<TickerData> {
+ let ticker_arr = data.get("data")?.as_array()?;
+ let ticker = ticker_arr.first()?;
+
+ let symbol = ticker.get("symbol")?.as_str()?;
+ let last = ticker.get("last")?.as_f64()?;
Some(TickerData {
provider: "kraken".to_string(),
- symbol: Self::normalize_kraken_symbol(symbol),
+ symbol: Self::normalize_symbol(symbol),
price: last,
- bid: ticker_data.get("bid").and_then(|v| v.as_f64()),
- ask: ticker_data.get("ask").and_then(|v| v.as_f64()),
- bid_size: ticker_data.get("bid_qty").and_then(|v| v.as_f64()),
- ask_size: ticker_data.get("ask_qty").and_then(|v| v.as_f64()),
- volume: ticker_data.get("volume").and_then(|v| v.as_f64()),
- high: ticker_data.get("high").and_then(|v| v.as_f64()),
- low: ticker_data.get("low").and_then(|v| v.as_f64()),
- open: ticker_data.get("open").and_then(|v| v.as_f64()),
+ bid: ticker.get("bid").and_then(|v| v.as_f64()),
+ ask: ticker.get("ask").and_then(|v| v.as_f64()),
+ bid_size: ticker.get("bid_qty").and_then(|v| v.as_f64()),
+ ask_size: ticker.get("ask_qty").and_then(|v| v.as_f64()),
+ volume: ticker.get("volume").and_then(|v| v.as_f64()),
+ high: ticker.get("high").and_then(|v| v.as_f64()),
+ low: ticker.get("low").and_then(|v| v.as_f64()),
+ open: None, // Kraken v2 doesn't provide open in ticker
close: Some(last),
- change: ticker_data.get("change").and_then(|v| v.as_f64()),
- change_percent: ticker_data.get("change_pct").and_then(|v| v.as_f64()),
+ change: ticker.get("change").and_then(|v| v.as_f64()),
+ change_percent: ticker.get("change_pct").and_then(|v| v.as_f64()),
+ quote_volume: None,
timestamp: Self::now(),
})
}
- fn parse_orderbook_static(data: &Value, is_snapshot: bool) -> Option<OrderBookData> {
- let book_data = data.get("data")?.as_array()?.get(0)?;
- let symbol = book_data.get("symbol")?.as_str()?;
+ /// Parse order book data
+ /// Example response:
+ /// {
+ /// "channel": "book",
+ /// "type": "snapshot",
+ /// "data": [{
+ /// "symbol": "BTC/USD",
+ /// "bids": [{"price": 42000.0, "qty": 0.5}, ...],
+ /// "asks": [{"price": 42010.0, "qty": 0.3}, ...]
+ /// }]
+ /// }
+ fn parse_orderbook(data: &Value, is_snapshot: bool) -> Option<OrderBookData> {
+ let book_arr = data.get("data")?.as_array()?;
+ let book = book_arr.first()?;
+
+ let symbol = book.get("symbol")?.as_str()?;
let parse_levels = |levels: &Value| -> Vec<OrderBookLevel> {
levels.as_array()
@@ -236,21 +357,33 @@ impl KrakenAdapter {
Some(OrderBookData {
provider: "kraken".to_string(),
- symbol: Self::normalize_kraken_symbol(symbol),
- bids: book_data.get("bids").map(parse_levels).unwrap_or_default(),
- asks: book_data.get("asks").map(parse_levels).unwrap_or_default(),
+ symbol: Self::normalize_symbol(symbol),
+ bids: book.get("bids").map(parse_levels).unwrap_or_default(),
+ asks: book.get("asks").map(parse_levels).unwrap_or_default(),
timestamp: Self::now(),
is_snapshot,
})
}
- fn parse_trade_static(data: &Value) -> Option<Vec<TradeData>> {
- let trades_array = data.get("data")?.as_array()?;
- if trades_array.is_empty() {
- return None;
- }
-
- let trades: Vec<TradeData> = trades_array.iter()
+ /// Parse trade data
+ /// Example response:
+ /// {
+ /// "channel": "trade",
+ /// "type": "update",
+ /// "data": [{
+ /// "symbol": "BTC/USD",
+ /// "side": "buy",
+ /// "price": 42005.0,
+ /// "qty": 0.1,
+ /// "ord_type": "limit",
+ /// "trade_id": 12345,
+ /// "timestamp": "2024-01-01T00:00:00.000Z"
+ /// }]
+ /// }
+ fn parse_trades(data: &Value) -> Option<Vec<TradeData>> {
+ let trades_arr = data.get("data")?.as_array()?;
+
+ let trades: Vec<TradeData> = trades_arr.iter()
.filter_map(|trade| {
let symbol = trade.get("symbol")?.as_str()?;
let price = trade.get("price")?.as_f64()?;
@@ -263,10 +396,23 @@ impl KrakenAdapter {
_ => TradeSide::Unknown,
};
+ // Parse trade_id (can be number or string)
+ let trade_id = trade.get("trade_id")
+ .map(|v| {
+ if let Some(n) = v.as_u64() {
+ n.to_string()
+ } else if let Some(s) = v.as_str() {
+ s.to_string()
+ } else {
+ String::new()
+ }
+ })
+ .filter(|s| !s.is_empty());
+
Some(TradeData {
provider: "kraken".to_string(),
- symbol: Self::normalize_kraken_symbol(symbol),
- trade_id: trade.get("trade_id").and_then(|v| v.as_str()).map(String::from),
+ symbol: Self::normalize_symbol(symbol),
+ trade_id,
price,
quantity: qty,
side,
@@ -278,24 +424,26 @@ impl KrakenAdapter {
if trades.is_empty() { None } else { Some(trades) }
}
- fn parse_candle_static(data: &Value) -> Option<CandleData> {
- let candle_array = data.get("data")?.as_array()?;
- let candle_data = candle_array.get(0)?;
- let symbol = candle_data.get("symbol")?.as_str()?;
+ /// Parse OHLC/candle data
+ fn parse_candle(data: &Value) -> Option<CandleData> {
+ let candle_arr = data.get("data")?.as_array()?;
+ let candle = candle_arr.first()?;
+
+ let symbol = candle.get("symbol")?.as_str()?;
Some(CandleData {
provider: "kraken".to_string(),
- symbol: Self::normalize_kraken_symbol(symbol),
- open: candle_data.get("open")?.as_f64()?,
- high: candle_data.get("high")?.as_f64()?,
- low: candle_data.get("low")?.as_f64()?,
- close: candle_data.get("close")?.as_f64()?,
- volume: candle_data.get("volume")?.as_f64().unwrap_or(0.0),
+ symbol: Self::normalize_symbol(symbol),
+ open: candle.get("open")?.as_f64()?,
+ high: candle.get("high")?.as_f64()?,
+ low: candle.get("low")?.as_f64()?,
+ close: candle.get("close")?.as_f64()?,
+ volume: candle.get("volume").and_then(|v| v.as_f64()).unwrap_or(0.0),
timestamp: Self::now(),
- interval: candle_data.get("interval")
- .and_then(|v| v.as_str())
- .unwrap_or("1m")
- .to_string(),
+ interval: candle.get("interval")
+ .and_then(|v| v.as_i64())
+ .map(|i| format!("{}m", i))
+ .unwrap_or_else(|| "1m".to_string()),
})
}
}
@@ -303,50 +451,81 @@ impl KrakenAdapter {
#[async_trait]
impl WebSocketAdapter for KrakenAdapter {
async fn connect(&mut self) -> anyhow::Result<()> {
- let url = self.config.url.clone();
- let connect_url = if url.is_empty() { KRAKEN_WS_URL } else { &url };
+ // Reset shutdown flag
+ self.shutdown.store(false, Ordering::SeqCst);
- eprintln!("[Kraken] Connecting to WebSocket: {}", connect_url);
+ let url = if self.config.url.is_empty() {
+ KRAKEN_WS_URL
+ } else {
+ &self.config.url
+ };
- let (ws_stream, _) = connect_async(connect_url).await
+ eprintln!("[Kraken] Connecting to {}", url);
+
+ let (ws_stream, response) = connect_async(url).await
.map_err(|e| {
- eprintln!("[Kraken] ✗ Failed to connect: {}", e);
+ eprintln!("[Kraken] Connection failed: {}", e);
e
})?;
- eprintln!("[Kraken] ✓ WebSocket connected successfully");
+ eprintln!("[Kraken] Connected! Response: {:?}", response.status());
// Split into independent read/write halves
let (write_half, read_half) = ws_stream.split();
let sink = Arc::new(Mutex::new(write_half));
self.ws_sink = Some(sink.clone());
self.connected.store(true, Ordering::SeqCst);
+ self.last_message_time.store(Self::now(), Ordering::SeqCst);
- // Start receive loop with only the read half — subscribe/unsubscribe won't block
+ // Start receive loop
if let Some(callback) = self.message_callback.clone() {
let connected = self.connected.clone();
let error_callback = self.error_callback.clone();
let last_message_time = self.last_message_time.clone();
- eprintln!("[Kraken] Starting receive loop");
+ let shutdown = self.shutdown.clone();
+
tokio::spawn(async move {
- Self::receive_loop(read_half, sink, callback, error_callback, connected, last_message_time).await;
- eprintln!("[Kraken] Receive loop ended");
+ Self::receive_loop(
+ read_half,
+ sink,
+ callback,
+ error_callback,
+ connected,
+ last_message_time,
+ shutdown,
+ ).await;
});
} else {
eprintln!("[Kraken] Warning: No message callback set");
}
+ // Emit connected status
+ if let Some(ref cb) = self.message_callback {
+ cb(MarketMessage::Status(StatusData {
+ provider: "kraken".to_string(),
+ status: ConnectionStatus::Connected,
+ message: Some("Connected to Kraken WebSocket v2".to_string()),
+ timestamp: Self::now(),
+ }));
+ }
+
Ok(())
}
async fn disconnect(&mut self) -> anyhow::Result<()> {
+ eprintln!("[Kraken] Disconnecting...");
+
+ // Signal shutdown
+ self.shutdown.store(true, Ordering::SeqCst);
self.connected.store(false, Ordering::SeqCst);
+ // Close WebSocket
if let Some(sink) = &self.ws_sink {
let _ = sink.lock().await.close().await;
}
self.ws_sink = None;
+ eprintln!("[Kraken] Disconnected");
Ok(())
}
@@ -356,53 +535,57 @@ impl WebSocketAdapter for KrakenAdapter {
channel: &str,
params: Option<Value>,
) -> anyhow::Result<()> {
- eprintln!("[Kraken] subscribe called: symbol={}, channel={}, connected={}",
- symbol, channel, self.connected.load(Ordering::SeqCst));
-
if !self.connected.load(Ordering::SeqCst) {
- return Err(anyhow::anyhow!("WebSocket not connected"));
+ return Err(anyhow::anyhow!("Not connected"));
}
let sink = self.ws_sink.as_ref()
- .ok_or_else(|| {
- eprintln!("[Kraken] subscribe failed: ws_sink is None");
- anyhow::anyhow!("Not connected")
- })?;
+ .ok_or_else(|| anyhow::anyhow!("WebSocket sink not available"))?;
- // Build subscription message
+ // Convert symbol to Kraken format
+ let kraken_symbol = Self::to_kraken_symbol(symbol);
+
+ // Build Kraken v2 subscription message
let mut sub_msg = serde_json::json!({
"method": "subscribe",
"params": {
"channel": channel,
- "symbol": [symbol],
+ "symbol": [kraken_symbol],
}
});
- // Add optional params (depth, snapshot, etc.)
+ // Add optional params (depth for book, interval for ohlc)
if let Some(p) = params {
- if let Some(obj) = sub_msg.get_mut("params") {
- if let Some(params_obj) = obj.as_object_mut() {
- if let Some(p_obj) = p.as_object() {
- for (k, v) in p_obj {
- params_obj.insert(k.clone(), v.clone());
- }
+ if let Some(params_obj) = sub_msg.get_mut("params").and_then(|p| p.as_object_mut()) {
+ if let Some(p_obj) = p.as_object() {
+ for (k, v) in p_obj {
+ params_obj.insert(k.clone(), v.clone());
}
}
}
}
+ // Add default depth for book channel
+ if channel == "book" {
+ if let Some(params_obj) = sub_msg.get_mut("params").and_then(|p| p.as_object_mut()) {
+ if !params_obj.contains_key("depth") {
+ params_obj.insert("depth".to_string(), serde_json::json!(25));
+ }
+ }
+ }
+
let msg_str = serde_json::to_string(&sub_msg)?;
- eprintln!("[Kraken] Sending subscription: {}", msg_str);
+ eprintln!("[Kraken] Subscribing: {}", msg_str);
match sink.lock().await.send(Message::Text(msg_str)).await {
Ok(_) => {
- eprintln!("[Kraken] ✓ Subscription sent successfully for {} {}", symbol, channel);
+ eprintln!("[Kraken] Subscription sent for {} {}", kraken_symbol, channel);
Ok(())
}
Err(e) => {
- eprintln!("[Kraken] ✗ Failed to send subscription: {}", e);
+ eprintln!("[Kraken] Subscription failed: {}", e);
self.connected.store(false, Ordering::SeqCst);
- Err(anyhow::anyhow!("Failed to send subscription: {}", e))
+ Err(anyhow::anyhow!("Failed to subscribe: {}", e))
}
}
}
@@ -411,17 +594,20 @@ impl WebSocketAdapter for KrakenAdapter {
let sink = self.ws_sink.as_ref()
.ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let kraken_symbol = Self::to_kraken_symbol(symbol);
+
let unsub_msg = serde_json::json!({
"method": "unsubscribe",
"params": {
"channel": channel,
- "symbol": [symbol],
+ "symbol": [kraken_symbol],
}
});
let msg_str = serde_json::to_string(&unsub_msg)?;
- sink.lock().await.send(Message::Text(msg_str)).await?;
+ eprintln!("[Kraken] Unsubscribing: {}", msg_str);
+ sink.lock().await.send(Message::Text(msg_str)).await?;
Ok(())
}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kucoin.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kucoin.rs
new file mode 100644
index 000000000..7558b56b7
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kucoin.rs
@@ -0,0 +1,316 @@
+#![allow(dead_code)]
+// KuCoin WebSocket Adapter
+//
+// Implements KuCoin WebSocket API
+// Note: KuCoin requires a token from REST API before connecting
+// Supports: ticker, level2 (orderbook), match (trades) channels
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+const KUCOIN_WS_URL: &str = "wss://ws-api-spot.kucoin.com";
+
+static MSG_ID: AtomicU64 = AtomicU64::new(1);
+
+pub struct KucoinAdapter {
+ config: ProviderConfig,
+ ws: Option<Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>>,
+ message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
+ connected: Arc<RwLock<bool>>,
+}
+
+impl KucoinAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ ws: None,
+ message_callback: None,
+ connected: Arc::new(RwLock::new(false)),
+ }
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| std::time::Duration::from_secs(0))
+ .as_millis() as u64
+ }
+
+ fn next_id() -> u64 {
+ MSG_ID.fetch_add(1, Ordering::SeqCst)
+ }
+
+ /// Normalize KuCoin symbol (BTC-USDT -> BTC/USDT)
+ fn normalize_kucoin_symbol(symbol: &str) -> String {
+ symbol.replace('-', "/")
+ }
+
+ /// Convert symbol to KuCoin format (BTC/USDT -> BTC-USDT)
+ fn to_kucoin_symbol(symbol: &str) -> String {
+ symbol.replace('/', "-")
+ }
+
+ /// Parse KuCoin ticker
+ fn parse_ticker(&self, data: &Value) -> Option<TickerData> {
+ let symbol = data.get("symbol")?.as_str()?;
+ let price = data.get("price")?.as_str()?.parse::<f64>().ok()?;
+ let bid = data.get("bestBid")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let ask = data.get("bestAsk")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let bid_sz = data.get("bestBidSize")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let ask_sz = data.get("bestAskSize")?.as_str().and_then(|s| s.parse::<f64>().ok());
+
+ Some(TickerData {
+ provider: "kucoin".to_string(),
+ symbol: Self::normalize_kucoin_symbol(symbol),
+ price,
+ bid,
+ ask,
+ bid_size: bid_sz,
+ ask_size: ask_sz,
+ volume: None,
+ high: None,
+ low: None,
+ open: None,
+ close: Some(price),
+ change: None,
+ change_percent: None,
+ quote_volume: None,
+ timestamp: Self::now(),
+ })
+ }
+
+ /// Parse KuCoin order book
+ fn parse_orderbook(&self, data: &Value, symbol: &str) -> Option<OrderBookData> {
+ let changes = data.get("changes")?;
+ let bids = changes.get("bids")?.as_array()?;
+ let asks = changes.get("asks")?.as_array()?;
+
+ let parse_levels = |levels: &Vec<Value>| -> Vec<OrderBookLevel> {
+ levels
+ .iter()
+ .filter_map(|level| {
+ let arr = level.as_array()?;
+ Some(OrderBookLevel {
+ price: arr.get(0)?.as_str()?.parse::<f64>().ok()?,
+ quantity: arr.get(1)?.as_str()?.parse::<f64>().ok()?,
+ count: None,
+ })
+ })
+ .collect()
+ };
+
+ Some(OrderBookData {
+ provider: "kucoin".to_string(),
+ symbol: Self::normalize_kucoin_symbol(symbol),
+ bids: parse_levels(bids),
+ asks: parse_levels(asks),
+ timestamp: Self::now(),
+ is_snapshot: false,
+ })
+ }
+
+ /// Parse KuCoin trade
+ fn parse_trade(&self, data: &Value) -> Option<TradeData> {
+ let symbol = data.get("symbol")?.as_str()?;
+ let price = data.get("price")?.as_str()?.parse::<f64>().ok()?;
+ let size = data.get("size")?.as_str()?.parse::<f64>().ok()?;
+ let side = data.get("side")?.as_str()?;
+ let trade_id = data.get("tradeId")?.as_str().map(|s| s.to_string());
+ let ts = data.get("time")?.as_str()?.parse::<u64>().ok().unwrap_or_else(Self::now);
+
+ Some(TradeData {
+ provider: "kucoin".to_string(),
+ symbol: Self::normalize_kucoin_symbol(symbol),
+ trade_id,
+ price,
+ quantity: size,
+ side: match side {
+ "buy" => TradeSide::Buy,
+ "sell" => TradeSide::Sell,
+ _ => TradeSide::Unknown,
+ },
+ timestamp: ts,
+ })
+ }
+
+ /// Parse KuCoin candle
+ fn parse_candle(&self, data: &Value, symbol: &str) -> Option<CandleData> {
+ let candles = data.get("candles")?.as_array()?;
+
+ Some(CandleData {
+ provider: "kucoin".to_string(),
+ symbol: Self::normalize_kucoin_symbol(symbol),
+ interval: "1min".to_string(),
+ open: candles.get(1)?.as_str()?.parse::<f64>().ok()?,
+ high: candles.get(3)?.as_str()?.parse::<f64>().ok()?,
+ low: candles.get(4)?.as_str()?.parse::<f64>().ok()?,
+ close: candles.get(2)?.as_str()?.parse::<f64>().ok()?,
+ volume: candles.get(5)?.as_str()?.parse::<f64>().ok()?,
+ timestamp: candles.get(0)?.as_str()?.parse::<u64>().ok()?,
+ })
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for KucoinAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ let url = if self.config.url.is_empty() {
+ KUCOIN_WS_URL
+ } else {
+ &self.config.url
+ };
+
+ let (ws_stream, _) = connect_async(url).await?;
+ let ws = Arc::new(RwLock::new(ws_stream));
+ self.ws = Some(ws.clone());
+ *self.connected.write().await = true;
+
+ let callback = self.message_callback.clone();
+ let connected = self.connected.clone();
+
+ tokio::spawn(async move {
+ let mut ws_lock = ws.write().await;
+
+ while let Some(msg) = ws_lock.next().await {
+ match msg {
+ Ok(Message::Text(text)) => {
+ if let Ok(data) = serde_json::from_str::<Value>(&text) {
+ // Handle ping/pong
+ if data.get("type").and_then(|t| t.as_str()) == Some("ping") {
+ let pong = json!({
+ "id": Self::next_id().to_string(),
+ "type": "pong"
+ });
+ let _ = ws_lock.send(Message::Text(pong.to_string())).await;
+ continue;
+ }
+
+ if let Some(ref cb) = callback {
+ if let Some(topic) = data.get("topic").and_then(|t| t.as_str()) {
+ if let Some(msg_data) = data.get("data") {
+ let adapter = KucoinAdapter::new(ProviderConfig::default());
+ let symbol = data.get("subject").and_then(|s| s.as_str()).unwrap_or("");
+
+ let message = if topic.starts_with("/market/ticker:") {
+ adapter.parse_ticker(msg_data).map(MarketMessage::Ticker)
+ } else if topic.starts_with("/market/level2:") {
+ adapter.parse_orderbook(msg_data, symbol).map(MarketMessage::OrderBook)
+ } else if topic.starts_with("/market/match:") {
+ adapter.parse_trade(msg_data).map(MarketMessage::Trade)
+ } else if topic.starts_with("/market/candles:") {
+ adapter.parse_candle(msg_data, symbol).map(MarketMessage::Candle)
+ } else {
+ None
+ };
+
+ if let Some(msg) = message {
+ cb(msg);
+ }
+ }
+ }
+ }
+ }
+ }
+ Ok(Message::Close(_)) => {
+ *connected.write().await = false;
+ break;
+ }
+ Err(_) => {
+ *connected.write().await = false;
+ break;
+ }
+ _ => {}
+ }
+ }
+ });
+
+ Ok(())
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ if let Some(ws) = &self.ws {
+ let mut ws_lock = ws.write().await;
+ ws_lock.close(None).await?;
+ }
+ *self.connected.write().await = false;
+ self.ws = None;
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ _params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let kucoin_symbol = Self::to_kucoin_symbol(symbol);
+
+ let topic = match channel {
+ "ticker" => format!("/market/ticker:{}", kucoin_symbol),
+ "book" | "depth" => format!("/market/level2:{}", kucoin_symbol),
+ "trade" => format!("/market/match:{}", kucoin_symbol),
+ "candle" | "ohlc" => format!("/market/candles:{}_1min", kucoin_symbol),
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let subscribe_msg = json!({
+ "id": Self::next_id().to_string(),
+ "type": "subscribe",
+ "topic": topic,
+ "privateChannel": false,
+ "response": true
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(subscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let kucoin_symbol = Self::to_kucoin_symbol(symbol);
+
+ let topic = match channel {
+ "ticker" => format!("/market/ticker:{}", kucoin_symbol),
+ "book" | "depth" => format!("/market/level2:{}", kucoin_symbol),
+ "trade" => format!("/market/match:{}", kucoin_symbol),
+ "candle" | "ohlc" => format!("/market/candles:{}_1min", kucoin_symbol),
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let unsubscribe_msg = json!({
+ "id": Self::next_id().to_string(),
+ "type": "unsubscribe",
+ "topic": topic,
+ "privateChannel": false,
+ "response": true
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(unsubscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(Arc::new(callback));
+ }
+
+ fn provider_name(&self) -> &str {
+ "kucoin"
+ }
+
+ fn is_connected(&self) -> bool {
+ *self.connected.blocking_read()
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mexc.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mexc.rs
new file mode 100644
index 000000000..5751b9051
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mexc.rs
@@ -0,0 +1,285 @@
+#![allow(dead_code)]
+// MEXC WebSocket Adapter
+//
+// Implements MEXC WebSocket API
+// Supports: ticker, depth, trades channels
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+const MEXC_WS_URL: &str = "wss://wbs.mexc.com/ws";
+
+pub struct MexcAdapter {
+ config: ProviderConfig,
+ ws: Option<Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>>,
+ message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
+ connected: Arc<RwLock<bool>>,
+}
+
+impl MexcAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ ws: None,
+ message_callback: None,
+ connected: Arc::new(RwLock::new(false)),
+ }
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| std::time::Duration::from_secs(0))
+ .as_millis() as u64
+ }
+
+ /// Normalize MEXC symbol (BTCUSDT -> BTC/USDT)
+ fn normalize_mexc_symbol(symbol: &str) -> String {
+ for quote in ["USDT", "USDC", "USD", "BTC", "ETH"] {
+ if let Some(base) = symbol.strip_suffix(quote) {
+ return format!("{}/{}", base, quote);
+ }
+ }
+ symbol.to_string()
+ }
+
+ /// Convert symbol to MEXC format (BTC/USDT -> BTCUSDT)
+ fn to_mexc_symbol(symbol: &str) -> String {
+ symbol.replace('/', "").to_uppercase()
+ }
+
+ /// Parse MEXC ticker
+ fn parse_ticker(&self, data: &Value) -> Option<TickerData> {
+ let d = data.get("d")?;
+ let symbol = data.get("s")?.as_str()?;
+ let last = d.get("p")?.as_str()?.parse::<f64>().ok()?;
+ let volume = d.get("v")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let high = d.get("h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let low = d.get("l")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let open = d.get("o")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let change_percent = d.get("r")?.as_str().and_then(|s| s.parse::<f64>().ok())
+ .map(|r| r * 100.0);
+
+ Some(TickerData {
+ provider: "mexc".to_string(),
+ symbol: Self::normalize_mexc_symbol(symbol),
+ price: last,
+ bid: None,
+ ask: None,
+ bid_size: None,
+ ask_size: None,
+ volume,
+ high,
+ low,
+ open,
+ close: Some(last),
+ change: None,
+ change_percent,
+ quote_volume: None,
+ timestamp: Self::now(),
+ })
+ }
+
+ /// Parse MEXC order book
+ fn parse_orderbook(&self, data: &Value) -> Option<OrderBookData> {
+ let d = data.get("d")?;
+ let symbol = data.get("s")?.as_str()?;
+ let bids = d.get("bids")?.as_array()?;
+ let asks = d.get("asks")?.as_array()?;
+
+ let parse_levels = |levels: &Vec<Value>| -> Vec<OrderBookLevel> {
+ levels
+ .iter()
+ .filter_map(|level| {
+ let price = level.get("p")?.as_str()?.parse::<f64>().ok()?;
+ let quantity = level.get("v")?.as_str()?.parse::<f64>().ok()?;
+ Some(OrderBookLevel {
+ price,
+ quantity,
+ count: None,
+ })
+ })
+ .collect()
+ };
+
+ Some(OrderBookData {
+ provider: "mexc".to_string(),
+ symbol: Self::normalize_mexc_symbol(symbol),
+ bids: parse_levels(bids),
+ asks: parse_levels(asks),
+ timestamp: Self::now(),
+ is_snapshot: true,
+ })
+ }
+
+ /// Parse MEXC trade
+ fn parse_trade(&self, data: &Value) -> Option<TradeData> {
+ let d = data.get("d")?;
+ let deals = d.get("deals")?.as_array()?.first()?;
+ let symbol = data.get("s")?.as_str()?;
+ let price = deals.get("p")?.as_str()?.parse::<f64>().ok()?;
+ let quantity = deals.get("v")?.as_str()?.parse::<f64>().ok()?;
+ let side = deals.get("S")?.as_i64()?;
+ let ts = deals.get("t")?.as_u64().unwrap_or_else(Self::now);
+
+ Some(TradeData {
+ provider: "mexc".to_string(),
+ symbol: Self::normalize_mexc_symbol(symbol),
+ trade_id: None,
+ price,
+ quantity,
+ side: if side == 1 { TradeSide::Buy } else { TradeSide::Sell },
+ timestamp: ts,
+ })
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for MexcAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ let url = if self.config.url.is_empty() {
+ MEXC_WS_URL
+ } else {
+ &self.config.url
+ };
+
+ let (ws_stream, _) = connect_async(url).await?;
+ let ws = Arc::new(RwLock::new(ws_stream));
+ self.ws = Some(ws.clone());
+ *self.connected.write().await = true;
+
+ let callback = self.message_callback.clone();
+ let connected = self.connected.clone();
+
+ tokio::spawn(async move {
+ let mut ws_lock = ws.write().await;
+
+ while let Some(msg) = ws_lock.next().await {
+ match msg {
+ Ok(Message::Text(text)) => {
+ if let Ok(data) = serde_json::from_str::<Value>(&text) {
+ // Handle ping
+ if data.get("ping").is_some() {
+ let pong = json!({ "pong": Self::now() });
+ let _ = ws_lock.send(Message::Text(pong.to_string())).await;
+ continue;
+ }
+
+ if let Some(ref cb) = callback {
+ if let Some(channel) = data.get("c").and_then(|c| c.as_str()) {
+ let adapter = MexcAdapter::new(ProviderConfig::default());
+
+ let message = if channel.contains("ticker") {
+ adapter.parse_ticker(&data).map(MarketMessage::Ticker)
+ } else if channel.contains("depth") {
+ adapter.parse_orderbook(&data).map(MarketMessage::OrderBook)
+ } else if channel.contains("deals") {
+ adapter.parse_trade(&data).map(MarketMessage::Trade)
+ } else {
+ None
+ };
+
+ if let Some(msg) = message {
+ cb(msg);
+ }
+ }
+ }
+ }
+ }
+ Ok(Message::Ping(data)) => {
+ let _ = ws_lock.send(Message::Pong(data)).await;
+ }
+ Ok(Message::Close(_)) => {
+ *connected.write().await = false;
+ break;
+ }
+ Err(_) => {
+ *connected.write().await = false;
+ break;
+ }
+ _ => {}
+ }
+ }
+ });
+
+ Ok(())
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ if let Some(ws) = &self.ws {
+ let mut ws_lock = ws.write().await;
+ ws_lock.close(None).await?;
+ }
+ *self.connected.write().await = false;
+ self.ws = None;
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ _params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let mexc_symbol = Self::to_mexc_symbol(symbol);
+
+ let param = match channel {
+ "ticker" => format!("[email protected]@{}", mexc_symbol),
+ "book" | "depth" => format!("[email protected]@{}@20", mexc_symbol),
+ "trade" => format!("[email protected]@{}", mexc_symbol),
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let subscribe_msg = json!({
+ "method": "SUBSCRIPTION",
+ "params": [param]
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(subscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let mexc_symbol = Self::to_mexc_symbol(symbol);
+
+ let param = match channel {
+ "ticker" => format!("[email protected]@{}", mexc_symbol),
+ "book" | "depth" => format!("[email protected]@{}@20", mexc_symbol),
+ "trade" => format!("[email protected]@{}", mexc_symbol),
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let unsubscribe_msg = json!({
+ "method": "UNSUBSCRIPTION",
+ "params": [param]
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(unsubscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(Arc::new(callback));
+ }
+
+ fn provider_name(&self) -> &str {
+ "mexc"
+ }
+
+ fn is_connected(&self) -> bool {
+ *self.connected.blocking_read()
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs
index 5d3cad4f5..5e0748867 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs
@@ -8,6 +8,15 @@ use async_trait::async_trait;
pub mod kraken;
pub mod hyperliquid;
pub mod binance;
+pub mod okx;
+pub mod bybit;
+pub mod coinbase;
+pub mod kucoin;
+pub mod gateio;
+pub mod huobi;
+pub mod mexc;
+pub mod bitget;
+pub mod bitfinex;
// Indian stock broker adapters
pub mod fyers;
@@ -27,6 +36,15 @@ pub mod shoonya;
pub use kraken::KrakenAdapter;
pub use hyperliquid::HyperLiquidAdapter;
pub use binance::BinanceAdapter;
+pub use okx::OkxAdapter;
+pub use bybit::BybitAdapter;
+pub use coinbase::CoinbaseAdapter;
+pub use kucoin::KucoinAdapter;
+pub use gateio::GateioAdapter;
+pub use huobi::HuobiAdapter;
+pub use mexc::MexcAdapter;
+pub use bitget::BitgetAdapter;
+pub use bitfinex::BitfinexAdapter;
// Indian broker exports
pub use fyers::FyersAdapter;
@@ -89,7 +107,16 @@ pub fn create_adapter(
// Crypto exchanges
"kraken" => Ok(Box::new(KrakenAdapter::new(config))),
"hyperliquid" => Ok(Box::new(HyperLiquidAdapter::new(config))),
- "binance" => Ok(Box::new(BinanceAdapter::new(config))),
+ "binance" | "binanceus" => Ok(Box::new(BinanceAdapter::new(config))),
+ "okx" => Ok(Box::new(OkxAdapter::new(config))),
+ "bybit" => Ok(Box::new(BybitAdapter::new(config))),
+ "coinbase" | "coinbasepro" => Ok(Box::new(CoinbaseAdapter::new(config))),
+ "kucoin" => Ok(Box::new(KucoinAdapter::new(config))),
+ "gateio" | "gate" => Ok(Box::new(GateioAdapter::new(config))),
+ "huobi" | "htx" => Ok(Box::new(HuobiAdapter::new(config))),
+ "mexc" => Ok(Box::new(MexcAdapter::new(config))),
+ "bitget" => Ok(Box::new(BitgetAdapter::new(config))),
+ "bitfinex" => Ok(Box::new(BitfinexAdapter::new(config))),
// Indian stock brokers
"fyers" => Ok(Box::new(FyersAdapter::new(config))),
"zerodha" | "kite" => Ok(Box::new(ZerodhaAdapter::new(config))),
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/okx.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/okx.rs
new file mode 100644
index 000000000..35d34b59a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/okx.rs
@@ -0,0 +1,328 @@
+#![allow(dead_code)]
+// OKX WebSocket Adapter
+//
+// Implements OKX WebSocket API v5
+// Supports: ticker, book (depth), trade, candle channels
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+const OKX_WS_URL: &str = "wss://ws.okx.com:8443/ws/v5/public";
+
+pub struct OkxAdapter {
+ config: ProviderConfig,
+ ws: Option<Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>>,
+ message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
+ connected: Arc<RwLock<bool>>,
+}
+
+impl OkxAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ ws: None,
+ message_callback: None,
+ connected: Arc::new(RwLock::new(false)),
+ }
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| std::time::Duration::from_secs(0))
+ .as_millis() as u64
+ }
+
+ /// Normalize OKX symbol (BTC-USDT -> BTC/USDT)
+ fn normalize_okx_symbol(symbol: &str) -> String {
+ symbol.replace('-', "/")
+ }
+
+ /// Convert symbol to OKX format (BTC/USDT -> BTC-USDT)
+ fn to_okx_symbol(symbol: &str) -> String {
+ symbol.replace('/', "-")
+ }
+
+ /// Parse OKX ticker
+ fn parse_ticker(&self, data: &Value) -> Option<TickerData> {
+ let inst_id = data.get("instId")?.as_str()?;
+ let last = data.get("last")?.as_str()?.parse::<f64>().ok()?;
+ let bid = data.get("bidPx")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let ask = data.get("askPx")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let bid_sz = data.get("bidSz")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let ask_sz = data.get("askSz")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let vol24h = data.get("vol24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let high24h = data.get("high24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let low24h = data.get("low24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+ let open24h = data.get("open24h")?.as_str().and_then(|s| s.parse::<f64>().ok());
+
+ let change_percent = if let Some(open) = open24h {
+ if open > 0.0 {
+ Some((last - open) / open * 100.0)
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ Some(TickerData {
+ provider: "okx".to_string(),
+ symbol: Self::normalize_okx_symbol(inst_id),
+ price: last,
+ bid,
+ ask,
+ bid_size: bid_sz,
+ ask_size: ask_sz,
+ volume: vol24h,
+ high: high24h,
+ low: low24h,
+ open: open24h,
+ close: Some(last),
+ change: None,
+ change_percent,
+ quote_volume: None,
+ timestamp: Self::now(),
+ })
+ }
+
+ /// Parse OKX order book
+ fn parse_orderbook(&self, data: &Value, inst_id: &str) -> Option<OrderBookData> {
+ let bids = data.get("bids")?.as_array()?;
+ let asks = data.get("asks")?.as_array()?;
+
+ let parse_levels = |levels: &Vec<Value>| -> Vec<OrderBookLevel> {
+ levels
+ .iter()
+ .filter_map(|level| {
+ let arr = level.as_array()?;
+ Some(OrderBookLevel {
+ price: arr.get(0)?.as_str()?.parse::<f64>().ok()?,
+ quantity: arr.get(1)?.as_str()?.parse::<f64>().ok()?,
+ count: arr.get(3)?.as_str().and_then(|s| s.parse::<u32>().ok()),
+ })
+ })
+ .collect()
+ };
+
+ Some(OrderBookData {
+ provider: "okx".to_string(),
+ symbol: Self::normalize_okx_symbol(inst_id),
+ bids: parse_levels(bids),
+ asks: parse_levels(asks),
+ timestamp: Self::now(),
+ is_snapshot: true,
+ })
+ }
+
+ /// Parse OKX trade
+ fn parse_trade(&self, data: &Value) -> Option<TradeData> {
+ let inst_id = data.get("instId")?.as_str()?;
+ let price = data.get("px")?.as_str()?.parse::<f64>().ok()?;
+ let quantity = data.get("sz")?.as_str()?.parse::<f64>().ok()?;
+ let side = data.get("side")?.as_str()?;
+ let trade_id = data.get("tradeId")?.as_str().map(|s| s.to_string());
+ let ts = data.get("ts")?.as_str().and_then(|s| s.parse::<u64>().ok()).unwrap_or_else(Self::now);
+
+ Some(TradeData {
+ provider: "okx".to_string(),
+ symbol: Self::normalize_okx_symbol(inst_id),
+ trade_id,
+ price,
+ quantity,
+ side: match side {
+ "buy" => TradeSide::Buy,
+ "sell" => TradeSide::Sell,
+ _ => TradeSide::Unknown,
+ },
+ timestamp: ts,
+ })
+ }
+
+ /// Parse OKX candle
+ fn parse_candle(&self, data: &Value, inst_id: &str, interval: &str) -> Option<CandleData> {
+ let arr = data.as_array()?;
+
+ Some(CandleData {
+ provider: "okx".to_string(),
+ symbol: Self::normalize_okx_symbol(inst_id),
+ interval: interval.to_string(),
+ open: arr.get(1)?.as_str()?.parse::<f64>().ok()?,
+ high: arr.get(2)?.as_str()?.parse::<f64>().ok()?,
+ low: arr.get(3)?.as_str()?.parse::<f64>().ok()?,
+ close: arr.get(4)?.as_str()?.parse::<f64>().ok()?,
+ volume: arr.get(5)?.as_str()?.parse::<f64>().ok()?,
+ timestamp: arr.get(0)?.as_str()?.parse::<u64>().ok()?,
+ })
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for OkxAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ let url = if self.config.url.is_empty() {
+ OKX_WS_URL
+ } else {
+ &self.config.url
+ };
+
+ let (ws_stream, _) = connect_async(url).await?;
+ let ws = Arc::new(RwLock::new(ws_stream));
+ self.ws = Some(ws.clone());
+ *self.connected.write().await = true;
+
+ let callback = self.message_callback.clone();
+ let connected = self.connected.clone();
+
+ tokio::spawn(async move {
+ let mut ws_lock = ws.write().await;
+
+ while let Some(msg) = ws_lock.next().await {
+ match msg {
+ Ok(Message::Text(text)) => {
+ if let Ok(data) = serde_json::from_str::<Value>(&text) {
+ if let Some(ref cb) = callback {
+ // Check if it's a data message
+ if let Some(arg) = data.get("arg") {
+ let channel = arg.get("channel").and_then(|c| c.as_str()).unwrap_or("");
+ let inst_id = arg.get("instId").and_then(|i| i.as_str()).unwrap_or("");
+
+ if let Some(data_arr) = data.get("data").and_then(|d| d.as_array()) {
+ for item in data_arr {
+ let adapter = OkxAdapter::new(ProviderConfig::default());
+ let message = match channel {
+ "tickers" => adapter.parse_ticker(item).map(MarketMessage::Ticker),
+ "books5" | "books" | "books50-l2-tbt" => {
+ adapter.parse_orderbook(item, inst_id).map(MarketMessage::OrderBook)
+ }
+ "trades" => adapter.parse_trade(item).map(MarketMessage::Trade),
+ c if c.starts_with("candle") => {
+ let interval = c.strip_prefix("candle").unwrap_or("1m");
+ adapter.parse_candle(item, inst_id, interval).map(MarketMessage::Candle)
+ }
+ _ => None,
+ };
+
+ if let Some(msg) = message {
+ cb(msg);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ Ok(Message::Close(_)) => {
+ *connected.write().await = false;
+ break;
+ }
+ Err(_) => {
+ *connected.write().await = false;
+ break;
+ }
+ _ => {}
+ }
+ }
+ });
+
+ Ok(())
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ if let Some(ws) = &self.ws {
+ let mut ws_lock = ws.write().await;
+ ws_lock.close(None).await?;
+ }
+ *self.connected.write().await = false;
+ self.ws = None;
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let okx_symbol = Self::to_okx_symbol(symbol);
+
+ let okx_channel = match channel {
+ "ticker" => "tickers",
+ "book" | "depth" => {
+ let depth = params.as_ref()
+ .and_then(|p| p.get("depth"))
+ .and_then(|d| d.as_u64())
+ .unwrap_or(5);
+ if depth <= 5 { "books5" } else { "books" }
+ }
+ "trade" => "trades",
+ "candle" | "ohlc" => {
+ let interval = params.as_ref()
+ .and_then(|p| p.get("interval"))
+ .and_then(|i| i.as_str())
+ .unwrap_or("1m");
+ &format!("candle{}", interval)
+ }
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let subscribe_msg = json!({
+ "op": "subscribe",
+ "args": [{
+ "channel": okx_channel,
+ "instId": okx_symbol
+ }]
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(subscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+ let okx_symbol = Self::to_okx_symbol(symbol);
+
+ let okx_channel = match channel {
+ "ticker" => "tickers",
+ "book" | "depth" => "books5",
+ "trade" => "trades",
+ "candle" | "ohlc" => "candle1m",
+ _ => return Err(anyhow::anyhow!("Unsupported channel: {}", channel)),
+ };
+
+ let unsubscribe_msg = json!({
+ "op": "unsubscribe",
+ "args": [{
+ "channel": okx_channel,
+ "instId": okx_symbol
+ }]
+ });
+
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(unsubscribe_msg.to_string())).await?;
+
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(Arc::new(callback));
+ }
+
+ fn provider_name(&self) -> &str {
+ "okx"
+ }
+
+ fn is_connected(&self) -> bool {
+ *self.connected.blocking_read()
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/upstox.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/upstox.rs
index 344294543..ffde35ceb 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/upstox.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/upstox.rs
@@ -188,6 +188,7 @@ impl UpstoxAdapter {
close: Some(tick.close),
change: Some(tick.change),
change_percent: None,
+ quote_volume: None,
timestamp: tick.timestamp,
})
}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/zerodha.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/zerodha.rs
index e91a7e4f5..bfb70097b 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/zerodha.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/zerodha.rs
@@ -400,6 +400,7 @@ impl ZerodhaAdapter {
close: None,
change: None,
change_percent: None,
+ quote_volume: None,
timestamp: Self::now(),
};
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/router.rs b/fincept-terminal-desktop/src-tauri/src/websocket/router.rs
index f789b41ec..bf8f26d4d 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/router.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/router.rs
@@ -81,6 +81,8 @@ impl MessageRouter {
#[inline]
fn normalize_symbol(symbol: &str) -> String {
symbol
+ .replace("XBT", "BTC") // Kraken uses XBT; normalize to BTC for matching
+ .replace("XDG", "DOGE") // Kraken uses XDG for DOGE
.replace('/', "")
.replace('-', "")
.replace('_', "")
@@ -95,12 +97,14 @@ impl MessageRouter {
// Topic format: "provider.channel.symbol"
let parts: Vec<&str> = topic.splitn(3, '.').collect();
if parts.len() == 3 {
- let provider = parts[0];
+ // Normalize provider to lowercase for consistent matching with Rust adapters
+ let provider = parts[0].to_lowercase();
let channel = parts[1];
let symbol = parts[2];
let normalized = Self::normalize_symbol(symbol);
let key = format!("{}.{}", provider, channel);
+ eprintln!("[Router] subscribe_frontend: topic='{}' => key='{}' normalized='{}'", topic, key, normalized);
self.normalized_subscriptions
.entry(key)
.or_insert_with(HashSet::new)
@@ -115,7 +119,8 @@ impl MessageRouter {
// Remove from normalized cache
let parts: Vec<&str> = topic.splitn(3, '.').collect();
if parts.len() == 3 {
- let provider = parts[0];
+ // Normalize provider to lowercase for consistent matching
+ let provider = parts[0].to_lowercase();
let channel = parts[1];
let symbol = parts[2];
let normalized = Self::normalize_symbol(symbol);
@@ -136,7 +141,25 @@ impl MessageRouter {
// Fast lookup using pre-computed normalized subscriptions
let key = format!("{}.{}", provider, channel);
if let Some(symbols) = self.normalized_subscriptions.get(&key) {
- return symbols.contains(&normalized_symbol);
+ let found = symbols.contains(&normalized_symbol);
+ if !found {
+ // Debug: log mismatch (only first few to avoid spam)
+ static DEBUG_COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+ let count = DEBUG_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ if count < 20 {
+ eprintln!("[Router] Symbol mismatch: incoming='{}' normalized='{}' | subscribed={:?}",
+ symbol, normalized_symbol, symbols.iter().take(5).collect::<Vec<_>>());
+ }
+ }
+ return found;
+ }
+
+ // Debug: no subscriptions at all for this provider.channel
+ static NO_SUB_COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+ let count = NO_SUB_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ if count < 10 {
+ eprintln!("[Router] No subscriptions for key='{}' (symbol='{}' normalized='{}')",
+ key, symbol, normalized_symbol);
}
false
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/services/monitoring.rs b/fincept-terminal-desktop/src-tauri/src/websocket/services/monitoring.rs
index f604681e1..a91973ea7 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/services/monitoring.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/services/monitoring.rs
@@ -178,9 +178,9 @@ impl MonitoringService {
"[MonitoringService] {} alert(s) triggered — provider={} symbol={} price={}",
alerts.len(), ticker.provider, ticker.symbol, ticker.price
);
- if app_handle.is_some() {
+ if let Some(handle) = app_handle.as_ref() {
for alert in alerts {
- let _ = app_handle.as_ref().unwrap().emit("monitor_alert", &alert);
+ let _ = handle.emit("monitor_alert", &alert);
}
}
}
@@ -213,12 +213,26 @@ impl MonitoringService {
let conditions = stmt
.query_map([], |row| {
+ let field_str: String = row.get(3)?;
+ let operator_str: String = row.get(4)?;
+ let field = MonitorField::from_str(&field_str).ok_or_else(|| {
+ rusqlite::Error::FromSqlConversionFailure(
+ 3, rusqlite::types::Type::Text,
+ Box::from(format!("invalid monitor field: {}", field_str)),
+ )
+ })?;
+ let operator = MonitorOperator::from_str(&operator_str).ok_or_else(|| {
+ rusqlite::Error::FromSqlConversionFailure(
+ 4, rusqlite::types::Type::Text,
+ Box::from(format!("invalid monitor operator: {}", operator_str)),
+ )
+ })?;
Ok(MonitorCondition {
id: Some(row.get(0)?),
provider: row.get(1)?,
symbol: row.get(2)?,
- field: MonitorField::from_str(&row.get::<_, String>(3)?).unwrap(),
- operator: MonitorOperator::from_str(&row.get::<_, String>(4)?).unwrap(),
+ field,
+ operator,
value: row.get(5)?,
value2: row.get(6)?,
enabled: row.get::<_, i32>(7)? == 1,
@@ -406,7 +420,7 @@ impl MonitoringService {
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
- .unwrap()
+ .unwrap_or_else(|_| std::time::Duration::from_secs(0))
.as_millis() as u64
}
}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/types.rs b/fincept-terminal-desktop/src-tauri/src/websocket/types.rs
index ea85f618d..57506c5f7 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/types.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/types.rs
@@ -37,6 +37,8 @@ pub struct TickerData {
pub close: Option<f64>,
pub change: Option<f64>,
pub change_percent: Option<f64>,
+ #[serde(default)]
+ pub quote_volume: Option<f64>,
pub timestamp: u64,
}
diff --git a/fincept-terminal-desktop/src-tauri/tauri.conf.json b/fincept-terminal-desktop/src-tauri/tauri.conf.json
index f236d7a53..bdcd660c4 100644
--- a/fincept-terminal-desktop/src-tauri/tauri.conf.json
+++ b/fincept-terminal-desktop/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "FinceptTerminal",
- "version": "3.3.1",
+ "version": "3.3.3",
"identifier": "com.fincept.terminal",
"build": {
"beforeDevCommand": "bun run dev",
diff --git a/fincept-terminal-desktop/src/brokers/crypto/base/CoreAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/base/CoreAdapter.ts
index 6d2257478..29a3e33ba 100644
--- a/fincept-terminal-desktop/src/brokers/crypto/base/CoreAdapter.ts
+++ b/fincept-terminal-desktop/src/brokers/crypto/base/CoreAdapter.ts
@@ -147,6 +147,41 @@ export abstract class CoreExchangeAdapter {
}
}
+ /**
+ * Returns two maps built from the already-loaded CCXT markets:
+ * wsIdToUnified: wsId (what the exchange sends on WS wire) → unified symbol (e.g. "XBT/USD" → "BTC/USD")
+ * unifiedToWsId: unified symbol → wsId (e.g. "BTC/USD" → "XBT/USD")
+ *
+ * Falls back to the unified symbol itself when wsId is not present (most exchanges use the
+ * unified symbol on their WS feed directly).
+ * Only includes active spot USD markets to keep the list relevant.
+ */
+ getMarketSymbolMap(): {
+ wsIdToUnified: Map<string, string>;
+ unifiedToWsId: Map<string, string>;
+ activeUsdSymbols: string[];
+ } {
+ const wsIdToUnified = new Map<string, string>();
+ const unifiedToWsId = new Map<string, string>();
+ const activeUsdSymbols: string[] = [];
+
+ const markets = this.exchange.markets;
+ if (!markets) return { wsIdToUnified, unifiedToWsId, activeUsdSymbols };
+
+ for (const [unified, market] of Object.entries(markets)) {
+ if (!market.active) continue;
+ if (!market.spot) continue;
+ if (market.quote !== 'USD' && market.quote !== 'USDT') continue;
+
+ const wsId: string = (market as any).wsId ?? unified;
+ wsIdToUnified.set(wsId, unified);
+ unifiedToWsId.set(unified, wsId);
+ activeUsdSymbols.push(unified);
+ }
+
+ return { wsIdToUnified, unifiedToWsId, activeUsdSymbols };
+ }
+
async fetchStatus(): Promise<any> {
try {
await this.ensureConnected();
diff --git a/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts b/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts
index 540fec62f..ec478e852 100644
--- a/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts
+++ b/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts
@@ -300,6 +300,15 @@ export const COMMANDS: Command[] = [
action: 'code',
keywords: ['code', 'editor', 'development', 'programming']
},
+ {
+ id: 'datamap',
+ name: 'Data Mapping',
+ description: 'API integration & schema transformation',
+ aliases: ['datamap', 'data-mapping', 'mapping', 'schema', 'transform'],
+ category: 'tool',
+ action: 'data-mapping',
+ keywords: ['data', 'mapping', 'schema', 'transform', 'api', 'integration', 'field', 'parser']
+ },
{
id: 'datasrc',
name: 'Data Sources',
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 048bdb9de..93ff798cd 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -67,6 +67,7 @@ const AlternativeInvestmentsTab = React.lazy(() => import('@/components/tabs/alt
const MarketSimTab = React.lazy(() => import('@/components/tabs/market-sim').then(m => ({ default: m.MarketSimTab })));
const AlgoTradingTab = React.lazy(() => import('@/components/tabs/algo-trading'));
const QuantLibCoreTab = React.lazy(() => import('@/components/tabs/quantlib-core'));
+const DataMappingTab = React.lazy(() => import('@/components/tabs/data-mapping'));
// Loading fallback component for lazy-loaded tabs
const TabLoadingFallback = () => (
@@ -585,6 +586,7 @@ function FinxeptTerminalContent() {
{ label: 'Algo Trading', action: () => setActiveTab('algo-trading') },
{ label: 'Agent Config', action: () => setActiveTab('agents') },
{ label: 'MCP Servers', action: () => setActiveTab('mcp') },
+ { label: 'Data Mapping', action: () => setActiveTab('data-mapping') },
{ label: 'QuantLib', action: () => setActiveTab('quantlib-core') },
{ label: 'Data Sources', action: () => setActiveTab('datasources') },
{ label: 'Report Builder', action: () => setActiveTab('reportbuilder') },
@@ -1191,6 +1193,11 @@ function FinxeptTerminalContent() {
<QuantLibCoreTab />
</React.Suspense>
</TabsContent>
+ <TabsContent value="data-mapping" className="h-full m-0 p-0">
+ <React.Suspense fallback={<TabLoadingFallback />}>
+ <DataMappingTab />
+ </React.Suspense>
+ </TabsContent>
</Tabs>
)}
</div>
diff --git a/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsx b/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsx
index 5d1895f23..6efa59430 100644
--- a/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsx
+++ b/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsx
@@ -22,7 +22,7 @@ import {
Link as LinkIcon
} from 'lucide-react';
import polymarketServiceEnhanced from '@/services/polymarket/polymarketServiceEnhanced';
-import { getSetting, saveSetting } from '@/services/core/sqliteService';
+import { saveCredential, getCredentialByService, deleteCredential } from '@/services/core/sqliteService';
import { showConfirm } from '@/utils/notifications';
// Fincept Professional Color Palette
@@ -82,14 +82,23 @@ export const PolymarketCredentialsPanel: React.FC = () => {
const loadSavedCredentials = async () => {
try {
- const saved = await getSetting('polymarket_credentials');
- if (saved) {
- const parsed = JSON.parse(saved);
+ const cred = await getCredentialByService('polymarket');
+ if (cred && cred.api_key) {
+ const additional = cred.additional_data ? JSON.parse(cred.additional_data) : {};
+ const parsed: PolymarketCredentials = {
+ apiKey: cred.api_key,
+ apiSecret: cred.api_secret ?? '',
+ apiPassphrase: cred.password ?? '',
+ walletAddress: cred.username ?? undefined,
+ createdAt: additional.createdAt,
+ method: additional.method ?? 'manual',
+ };
setCredentials(parsed);
polymarketServiceEnhanced.setCredentials({
apiKey: parsed.apiKey,
apiSecret: parsed.apiSecret,
- apiPassphrase: parsed.apiPassphrase
+ apiPassphrase: parsed.apiPassphrase,
+ walletAddress: parsed.walletAddress,
});
if (parsed.walletAddress) {
setWalletAddress(parsed.walletAddress);
@@ -103,12 +112,20 @@ export const PolymarketCredentialsPanel: React.FC = () => {
const saveCredentials = async (creds: PolymarketCredentials) => {
try {
- await saveSetting('polymarket_credentials', JSON.stringify(creds), 'polymarket');
+ await saveCredential({
+ service_name: 'polymarket',
+ username: creds.walletAddress,
+ api_key: creds.apiKey,
+ api_secret: creds.apiSecret,
+ password: creds.apiPassphrase,
+ additional_data: JSON.stringify({ method: creds.method, createdAt: creds.createdAt ?? Date.now() }),
+ });
setCredentials(creds);
polymarketServiceEnhanced.setCredentials({
apiKey: creds.apiKey,
apiSecret: creds.apiSecret,
- apiPassphrase: creds.apiPassphrase
+ apiPassphrase: creds.apiPassphrase,
+ walletAddress: creds.walletAddress,
});
} catch (error) {
console.error('[PolymarketCredentials] Failed to save credentials:', error);
@@ -175,6 +192,7 @@ export const PolymarketCredentialsPanel: React.FC = () => {
const provider = new BrowserProvider(window.ethereum as any);
const signer = await provider.getSigner();
+ // L1 authentication: EIP-712 typed data signing as required by Polymarket CLOB API
const domain = {
name: 'ClobAuthDomain',
version: '1',
@@ -192,13 +210,21 @@ export const PolymarketCredentialsPanel: React.FC = () => {
setTestResult({ success: true, message: 'Please sign the message in MetaMask...' });
const signature = await signer.signTypedData(domain, types, value);
+ const timestamp = Math.floor(Date.now() / 1000).toString();
+ const nonce = '0';
setTestResult({ success: true, message: 'Generating API credentials...' });
+ // Polymarket /auth/api-key requires L1 headers, NOT a JSON body
const response = await fetch('https://clob.polymarket.com/auth/api-key', {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ address, signature, nonce: 0 })
+ headers: {
+ 'Content-Type': 'application/json',
+ 'POLY_ADDRESS': address,
+ 'POLY_SIGNATURE': signature,
+ 'POLY_TIMESTAMP': timestamp,
+ 'POLY_NONCE': nonce,
+ },
});
if (!response.ok) {
@@ -209,7 +235,7 @@ export const PolymarketCredentialsPanel: React.FC = () => {
const apiCredentials = await response.json();
const newCredentials: PolymarketCredentials = {
- apiKey: apiCredentials.apiKey,
+ apiKey: apiCredentials.apiKey ?? apiCredentials.key,
apiSecret: apiCredentials.secret,
apiPassphrase: apiCredentials.passphrase,
walletAddress: address,
@@ -217,7 +243,7 @@ export const PolymarketCredentialsPanel: React.FC = () => {
method: 'wallet'
};
- saveCredentials(newCredentials);
+ await saveCredentials(newCredentials);
setTestResult({ success: true, message: 'API credentials generated and saved!' });
} catch (error: any) {
@@ -236,14 +262,17 @@ export const PolymarketCredentialsPanel: React.FC = () => {
setTestResult(null);
try {
- const markets = await polymarketServiceEnhanced.getCLOBMarkets();
- if (markets && (markets.length > 0 || Array.isArray(markets))) {
- setTestResult({ success: true, message: 'Connection successful! Credentials valid.' });
+ // Test against an authenticated endpoint — getOpenOrders requires valid L2 auth headers
+ const orders = await polymarketServiceEnhanced.getOpenOrders();
+ setTestResult({ success: true, message: `Connection successful! Credentials valid. (${orders.length} open orders)` });
+ } catch (error: any) {
+ // Distinguish auth failure from network error
+ const msg = error.message ?? '';
+ if (msg.includes('401') || msg.includes('403') || msg.includes('Unauthorized')) {
+ setTestResult({ success: false, message: 'Authentication failed — check your API key, secret, and passphrase.' });
} else {
- setTestResult({ success: false, message: 'Invalid response from API' });
+ setTestResult({ success: false, message: `Test failed: ${msg}` });
}
- } catch (error: any) {
- setTestResult({ success: false, message: `Test failed: ${error.message}` });
} finally {
setIsTesting(false);
}
@@ -259,7 +288,14 @@ export const PolymarketCredentialsPanel: React.FC = () => {
);
if (!confirmed) return;
- await saveSetting('polymarket_credentials', '', 'polymarket');
+ try {
+ const cred = await getCredentialByService('polymarket');
+ if (cred?.id) {
+ await deleteCredential(cred.id);
+ }
+ } catch (error) {
+ console.error('[PolymarketCredentials] Failed to delete credentials:', error);
+ }
setCredentials(null);
setWalletConnected(false);
setWalletAddress('');
diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/hooks/useAgentConfig.ts b/fincept-terminal-desktop/src/components/tabs/agent-config/hooks/useAgentConfig.ts
index f7873d2db..105e7b3ff 100644
--- a/fincept-terminal-desktop/src/components/tabs/agent-config/hooks/useAgentConfig.ts
+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/hooks/useAgentConfig.ts
@@ -116,6 +116,9 @@ export function useAgentConfig() {
}, [updateTabSession]);
const [showMembersResponses, setShowMembersResponses] = useState(false);
const [teamLeaderIndex, setTeamLeaderIndex] = useState<number>(-1);
+ // Team-level LLM override — set by the Agent Configuration panel in TeamsView
+ const [teamProvider, setTeamProvider] = useState<string>('');
+ const [teamModelId, setTeamModelId] = useState<string>('');
// ─── Chat ─────────────────────────────────────────────────────────────────
const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
@@ -132,10 +135,8 @@ export function useAgentConfig() {
const [selectedPortfolioCtx, setSelectedPortfolioCtx] = useState<Portfolio | null>(null);
const [showPortfolioDropdown, setShowPortfolioDropdown] = useState(false);
- // ─── Streaming ────────────────────────────────────────────────────────────
- const [streamingContent, setStreamingContent] = useState<string>('');
- const [isStreaming, setIsStreaming] = useState(false);
- const [activeStreamHandle, setActiveStreamHandle] = useState<any>(null);
+ // ─── Team Execution Log ───────────────────────────────────────────────────
+ const [teamLog, setTeamLog] = useState<{ label: string; text: string }[]>([]);
// ─── Workflow / Planner ───────────────────────────────────────────────────
const [workflowSymbol, setWorkflowSymbolInternal] = useState(tabSession.workflowSymbol);
@@ -145,6 +146,7 @@ export function useAgentConfig() {
}, [updateTabSession]);
const [currentPlan, setCurrentPlan] = useState<ExecutionPlan | null>(null);
const [planExecuting, setPlanExecuting] = useState(false);
+ const [planGeneratedBy, setPlanGeneratedBy] = useState<'llm' | 'fallback' | 'template' | null>(null);
// ─── Cleanup Refs ─────────────────────────────────────────────────────────
const mountedRef = useRef(true);
@@ -303,7 +305,7 @@ export function useAgentConfig() {
try {
const timeoutPromise = new Promise<AgentCard[]>((_, reject) =>
- setTimeout(() => reject(new Error('Agent discovery timeout')), 5000)
+ setTimeout(() => reject(new Error('Agent discovery timeout')), 20000)
);
const agents = await Promise.race([agentService.discoverAgents(), timeoutPromise]);
if (Array.isArray(agents) && agents.length > 0) {
@@ -389,9 +391,10 @@ export function useAgentConfig() {
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 : {};
+ const fallback = getActiveFallback();
setEditedConfig({
- provider: model.provider || 'openai',
- model_id: model.model_id || 'gpt-4-turbo',
+ provider: model.provider || fallback.provider,
+ model_id: model.model_id || fallback.model_id,
temperature: model.temperature ?? 0.7,
max_tokens: model.max_tokens ?? 4096,
tools: config.tools || [],
@@ -409,7 +412,7 @@ export function useAgentConfig() {
knowledge_type: knowledgeCfg?.type || 'url',
knowledge_urls: (knowledgeCfg?.urls || []).join('\n'),
knowledge_vector_db: knowledgeCfg?.vector_db || 'lancedb',
- knowledge_embedder: knowledgeCfg?.embedder || 'openai',
+ knowledge_embedder: knowledgeCfg?.embedder || fallback.provider,
guardrails_pii: guardrailsCfg?.pii_detection ?? true,
guardrails_injection: guardrailsCfg?.injection_check ?? true,
guardrails_compliance: guardrailsCfg?.financial_compliance ?? false,
@@ -425,6 +428,16 @@ export function useAgentConfig() {
setJsonText(JSON.stringify(agent, null, 2));
};
+ // ─── Active LLM fallback (derived from already-loaded configuredLLMs state) ─
+ // All panels in this hook use this — no repeated DB calls needed.
+ const getActiveFallback = (): { provider: string; model_id: string } => {
+ const active = configuredLLMs.find(c => c.is_active) ?? configuredLLMs[0] ?? null;
+ return {
+ provider: active?.provider ?? 'fincept',
+ model_id: active?.model ?? 'fincept-llm',
+ };
+ };
+
// ─── API Keys ─────────────────────────────────────────────────────────────
const getApiKeys = async (): Promise<Record<string, string>> => {
@@ -541,7 +554,7 @@ export function useAgentConfig() {
if (useAutoRouting) {
const routingResult = await withTimeout(
agentService.routeQuery(testQuery, apiKeys),
- 15000,
+ 310000,
'Query routing timed out'
);
setLastRoutingResult(routingResult);
@@ -557,7 +570,7 @@ export function useAgentConfig() {
);
const result = await withTimeout(
agentService.executeRoutedQuery(testQuery, apiKeys, undefined, userConfig),
- 60000,
+ 310000,
'Agent execution timed out'
);
setTestResult(result);
@@ -578,12 +591,12 @@ export function useAgentConfig() {
if (selectedOutputModel) {
result = await withTimeout(
agentService.runAgentStructured(testQuery, config, selectedOutputModel, apiKeys),
- 60000, 'Agent execution timed out'
+ 310000, 'Agent execution timed out'
);
} else {
result = await withTimeout(
agentService.runAgent(testQuery, config, apiKeys),
- 60000, 'Agent execution timed out'
+ 310000, 'Agent execution timed out'
);
}
setTestResult(result);
@@ -618,24 +631,25 @@ export function useAgentConfig() {
const currentFetchId = ++fetchIdRef.current;
setExecuting(true);
- setIsStreaming(true);
- setStreamingContent('');
setError(null);
-
- setChatMessages(prev => [...prev, { role: 'user', content: testQuery, timestamp: new Date() }]);
+ setTeamLog([]);
try {
const apiKeys = await getApiKeys();
if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;
+ const fallback = getActiveFallback();
+ const resolvedProvider = teamProvider || fallback.provider;
+ const resolvedModelId = teamModelId || fallback.model_id;
+
const teamConfig = agentService.buildTeamConfig(
'Custom Team',
teamMode,
teamMembers.map(agent => ({
name: agent.name,
role: agent.description,
- provider: agent.config?.model?.provider || 'openai',
- modelId: agent.config?.model?.model_id || 'gpt-4-turbo',
+ provider: agent.config?.model?.provider || resolvedProvider,
+ modelId: agent.config?.model?.model_id || resolvedModelId,
tools: agent.config?.tools || [],
instructions: agent.config?.instructions || '',
})),
@@ -645,57 +659,45 @@ export function useAgentConfig() {
}
);
- let accumulatedContent = '';
- const streamHandle = await agentService.runTeamStreaming(testQuery, teamConfig, apiKeys, (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') {
- setIsStreaming(false);
- } else if (chunk.chunk_type === 'error') {
- setError(chunk.content);
- setIsStreaming(false);
- }
+ // Log each member being called
+ const logs: { label: string; text: string }[] = [];
+ teamMembers.forEach((m, i) => {
+ logs.push({ label: `AGENT ${i + 1} — ${m.name}`, text: `Role: ${m.description || 'General'}` });
});
+ logs.push({ label: 'STATUS', text: `Running ${teamMode} team with ${teamMembers.length} agents...` });
+ setTeamLog(logs);
- setActiveStreamHandle(streamHandle);
+ const result = await withTimeout(
+ agentService.runTeam(testQuery, teamConfig, apiKeys),
+ 600000,
+ 'Team execution timed out'
+ );
+ if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;
- 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);
+ const finalContent = extractAgentResponseText(result.response || result.error || JSON.stringify(result, null, 2));
+
+ setTeamLog(prev => [...prev, { label: 'DONE', text: 'Team execution completed' }]);
+ setTestResult({ success: true, response: finalContent });
+ setChatMessages(prev => [...prev,
+ { role: 'user', content: testQuery, timestamp: new Date() },
+ {
+ role: 'assistant',
+ content: finalContent,
+ timestamp: new Date(),
+ agentName: `Team (${teamMembers.length} agents)`,
+ },
+ ]);
+ setSuccess('Team executed successfully');
+ setTimeout(() => setSuccess(null), 3000);
} catch (err: any) {
+ if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;
+ setTeamLog(prev => [...prev, { label: 'ERROR', text: err.toString() }]);
setError(err.toString());
- setExecuting(false);
- setIsStreaming(false);
+ } finally {
+ if (mountedRef.current && currentFetchId === fetchIdRef.current) setExecuting(false);
}
};
- const cancelStream = async () => {
- if (activeStreamHandle) {
- await activeStreamHandle.cancel();
- setActiveStreamHandle(null);
- setIsStreaming(false);
- setExecuting(false);
- setStreamingContent('');
- }
- };
const runWorkflow = async (workflowType: string, extraParams?: Record<string, any>) => {
if (workflowType === 'stock_analysis') {
@@ -782,18 +784,25 @@ export function useAgentConfig() {
// ─── Planner ──────────────────────────────────────────────────────────────
- const createPlan = async () => {
+ const createPlan = async (planQuery?: string) => {
if (!workflowSymbol.trim()) return;
setExecuting(true);
setError(null);
+ setPlanGeneratedBy(null);
try {
- const plan = await agentService.createStockAnalysisPlan(workflowSymbol);
- if (plan) {
- setCurrentPlan(plan);
- setSuccess('Execution plan created');
+ const apiKeys = await getApiKeys();
+ const query = planQuery
+ ? `${planQuery} for ${workflowSymbol}`
+ : `Perform a comprehensive financial analysis of ${workflowSymbol} including price data, fundamentals, news sentiment, technical analysis, and an overall investment recommendation.`;
+
+ const result = await agentService.generateDynamicPlan(query, apiKeys);
+ if (result?.plan) {
+ setCurrentPlan(result.plan);
+ setPlanGeneratedBy(result.generated_by === 'fallback' ? 'fallback' : 'llm');
+ setSuccess(result.generated_by === 'llm' ? 'AI-generated plan ready' : 'Plan created (template fallback)');
setTimeout(() => setSuccess(null), 3000);
} else {
- setError('Failed to create plan');
+ setError('Failed to generate plan');
}
} catch (err: any) {
setError(err.toString());
@@ -802,13 +811,14 @@ export function useAgentConfig() {
}
};
- const executePlan = async () => {
- if (!currentPlan) return;
+ const executePlan = async (planOverride?: ExecutionPlan) => {
+ const planToExecute = planOverride ?? currentPlan;
+ if (!planToExecute) return;
setPlanExecuting(true);
setError(null);
try {
const apiKeys = await getApiKeys();
- const result = await agentService.executePlan(currentPlan, apiKeys);
+ const result = await agentService.executePlan(planToExecute, apiKeys);
if (result) {
setCurrentPlan(result);
if (result.is_complete) {
@@ -931,6 +941,8 @@ export function useAgentConfig() {
teamMembers, teamMode, setTeamMode,
showMembersResponses, setShowMembersResponses,
teamLeaderIndex, setTeamLeaderIndex,
+ teamProvider, setTeamProvider,
+ teamModelId, setTeamModelId,
// Chat
chatMessages, chatInput, setChatInput, chatEndRef,
// Tools — selectedTools is derived from editedConfig.tools (single source of truth)
@@ -941,15 +953,15 @@ export function useAgentConfig() {
// Portfolio
portfolios, selectedPortfolioCtx, setSelectedPortfolioCtx,
showPortfolioDropdown, setShowPortfolioDropdown,
- // Streaming
- streamingContent, isStreaming, activeStreamHandle,
+ // Team log
+ teamLog,
// Workflow / Planner
- workflowSymbol, setWorkflowSymbol, currentPlan, planExecuting,
+ workflowSymbol, setWorkflowSymbol, currentPlan, planExecuting, planGeneratedBy,
// Actions
loadDiscoveredAgents,
loadCustomAgentsFromDb,
updateEditedConfigFromAgent,
- runAgent, runTeam, runWorkflow, cancelStream,
+ runAgent, runTeam, runWorkflow,
createPlan, executePlan,
addToTeam, removeFromTeam,
toggleToolCategory, copyTool, toggleToolSelection,
diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/types.ts b/fincept-terminal-desktop/src/components/tabs/agent-config/types.ts
index a68ed4248..d17c0f983 100644
--- a/fincept-terminal-desktop/src/components/tabs/agent-config/types.ts
+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/types.ts
@@ -160,7 +160,7 @@ export const DEFAULT_EDITED_CONFIG: EditedConfig = {
knowledge_type: 'url',
knowledge_urls: '',
knowledge_vector_db: 'lancedb',
- knowledge_embedder: 'openai',
+ knowledge_embedder: 'fincept',
guardrails_pii: true,
guardrails_injection: true,
guardrails_compliance: false,
diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/views/PlannerView.tsx b/fincept-terminal-desktop/src/components/tabs/agent-config/views/PlannerView.tsx
index d2e94a861..2eacdc58d 100644
--- a/fincept-terminal-desktop/src/components/tabs/agent-config/views/PlannerView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/views/PlannerView.tsx
@@ -1,11 +1,585 @@
/**
- * PlannerView - Execution plan builder and step visualization
+ * PlannerView - Interactive execution plan builder, visualizer and results viewer
+ * Supports: step editing (name/type/config), add/remove/reorder steps, plan history,
+ * resizable results panel, markdown rendering, copy/export.
*/
-import React from 'react';
-import { ListTree, Target, Play, Loader2 } from 'lucide-react';
+import React, { useState, useCallback, useRef, useEffect } from 'react';
+import {
+ ListTree, Target, Play, Loader2, ChevronDown, ChevronRight,
+ Copy, Check, Trash2, RotateCcw, Download, Clock, AlertCircle,
+ CheckCircle, XCircle, BarChart2, TrendingUp, Shield, Layers,
+ Search, PanelRightClose, PanelRightOpen, Maximize2, Minimize2,
+ FileText, Plus, ArrowUp, ArrowDown, Edit2, Save, X, Settings,
+ GripVertical,
+} from 'lucide-react';
import { FINCEPT } from '../types';
import type { AgentConfigState } from '../hooks/useAgentConfig';
+import type { ExecutionPlan, PlanStep } from '@/services/agentService';
+import MarkdownRenderer from '@/components/common/MarkdownRenderer';
+
+// ─── Types ────────────────────────────────────────────────────────────────────
+
+interface PlanHistoryEntry {
+ id: string;
+ symbol: string;
+ planType: string;
+ timestamp: Date;
+ plan: ExecutionPlan;
+ label: string;
+}
+
+type PlanTemplate = {
+ id: string;
+ name: string;
+ desc: string;
+ icon: React.ReactNode;
+ defaultSymbol: string;
+ color: string;
+};
+
+// Editable config row: {key, value} pairs that map to step.config
+interface ConfigRow {
+ key: string;
+ value: string;
+}
+
+// ─── Content Extraction ───────────────────────────────────────────────────────
+
+function extractContextContent(value: unknown): string {
+ if (typeof value === 'string') return value;
+ if (typeof value !== 'object' || value === null) return String(value ?? '');
+
+ const obj = value as Record<string, unknown>;
+
+ for (const field of ['result', 'output', 'content', 'text', 'analysis', 'summary', 'response']) {
+ if (typeof obj[field] === 'string' && (obj[field] as string).length > 0) {
+ return obj[field] as string;
+ }
+ }
+
+ const entries = Object.entries(obj);
+ const stringEntries = entries.filter(([, v]) => typeof v === 'string' && (v as string).trim().length > 0);
+
+ if (stringEntries.length > 0 && stringEntries.length >= Math.ceil(entries.length * 0.6)) {
+ return stringEntries
+ .map(([key, val]) => {
+ const heading = key.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
+ return `## ${heading}\n\n${val as string}`;
+ })
+ .join('\n\n---\n\n');
+ }
+
+ return '```json\n' + JSON.stringify(value, null, 2) + '\n```';
+}
+
+// ─── Helpers ──────────────────────────────────────────────────────────────────
+
+function deepClonePlan(plan: ExecutionPlan): ExecutionPlan {
+ return JSON.parse(JSON.stringify(plan));
+}
+
+function makeNewStep(index: number): PlanStep {
+ return {
+ id: `custom_step_${Date.now()}_${index}`,
+ name: `Custom Step ${index + 1}`,
+ step_type: 'analysis',
+ config: {},
+ dependencies: [],
+ status: 'pending',
+ };
+}
+
+function configToRows(config: Record<string, any>): ConfigRow[] {
+ return Object.entries(config).map(([key, value]) => ({
+ key,
+ value: typeof value === 'string' ? value : JSON.stringify(value),
+ }));
+}
+
+function rowsToConfig(rows: ConfigRow[]): Record<string, any> {
+ const result: Record<string, any> = {};
+ for (const row of rows) {
+ if (!row.key.trim()) continue;
+ try {
+ result[row.key.trim()] = JSON.parse(row.value);
+ } catch {
+ result[row.key.trim()] = row.value;
+ }
+ }
+ return result;
+}
+
+// ─── Constants ────────────────────────────────────────────────────────────────
+
+const PLAN_TEMPLATES: PlanTemplate[] = [
+ {
+ id: 'stock_analysis',
+ name: 'Stock Analysis',
+ desc: 'Fundamental + technical deep-dive',
+ icon: <TrendingUp size={12} />,
+ defaultSymbol: 'AAPL',
+ color: FINCEPT.ORANGE,
+ },
+ {
+ id: 'portfolio_rebalance',
+ name: 'Portfolio Rebalance',
+ desc: 'Optimize asset allocation',
+ icon: <BarChart2 size={12} />,
+ defaultSymbol: 'PORTFOLIO',
+ color: FINCEPT.CYAN,
+ },
+ {
+ id: 'risk_audit',
+ name: 'Risk Audit',
+ desc: 'VaR, drawdown & stress test',
+ icon: <Shield size={12} />,
+ defaultSymbol: 'PORTFOLIO',
+ color: FINCEPT.RED,
+ },
+ {
+ id: 'sector_rotation',
+ name: 'Sector Rotation',
+ desc: 'Identify rotation opportunities',
+ icon: <Layers size={12} />,
+ defaultSymbol: 'SPY',
+ color: FINCEPT.GREEN,
+ },
+];
+
+const STEP_TYPES = [
+ 'fetch', 'analysis', 'research', 'synthesis',
+ 'technical', 'fundamental', 'news', 'sentiment',
+ 'risk', 'portfolio', 'report', 'custom',
+];
+
+const STATUS_COLOR: Record<string, string> = {
+ completed: FINCEPT.GREEN,
+ failed: FINCEPT.RED,
+ running: FINCEPT.ORANGE,
+ pending: FINCEPT.GRAY,
+ skipped: FINCEPT.MUTED,
+};
+
+const STATUS_ICON: Record<string, React.ReactNode> = {
+ completed: <CheckCircle size={12} />,
+ failed: <XCircle size={12} />,
+ running: <Loader2 size={12} className="animate-spin" />,
+ pending: <Clock size={12} />,
+ skipped: <AlertCircle size={12} />,
+};
+
+// ─── Inline field style helpers ───────────────────────────────────────────────
+
+const inputStyle = (focused?: boolean): React.CSSProperties => ({
+ width: '100%',
+ padding: '5px 8px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${focused ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ outline: 'none',
+ boxSizing: 'border-box' as const,
+});
+
+// ─── StepEditor component ─────────────────────────────────────────────────────
+
+interface StepEditorProps {
+ step: PlanStep;
+ onSave: (updated: PlanStep) => void;
+ onCancel: () => void;
+}
+
+const StepEditor: React.FC<StepEditorProps> = ({ step, onSave, onCancel }) => {
+ const [name, setName] = useState(step.name);
+ const [stepType, setStepType] = useState(step.step_type);
+ const [configRows, setConfigRows] = useState<ConfigRow[]>(() =>
+ configToRows(step.config || {}).length > 0
+ ? configToRows(step.config || {})
+ : [{ key: '', value: '' }]
+ );
+ const [depsText, setDepsText] = useState(step.dependencies.join(', '));
+ const [nameFocused, setNameFocused] = useState(false);
+ const [depsFocused, setDepsFocused] = useState(false);
+
+ const addConfigRow = () => setConfigRows(prev => [...prev, { key: '', value: '' }]);
+
+ const removeConfigRow = (i: number) =>
+ setConfigRows(prev => prev.filter((_, idx) => idx !== i));
+
+ const updateConfigRow = (i: number, field: 'key' | 'value', val: string) =>
+ setConfigRows(prev => prev.map((row, idx) => idx === i ? { ...row, [field]: val } : row));
+
+ const handleSave = () => {
+ onSave({
+ ...step,
+ name: name.trim() || step.name,
+ step_type: stepType,
+ config: rowsToConfig(configRows),
+ dependencies: depsText.split(',').map(s => s.trim()).filter(Boolean),
+ });
+ };
+
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
+ {/* Name */}
+ <div>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '4px' }}>STEP NAME</div>
+ <input
+ value={name}
+ onChange={e => setName(e.target.value)}
+ style={inputStyle(nameFocused)}
+ onFocus={() => setNameFocused(true)}
+ onBlur={() => setNameFocused(false)}
+ />
+ </div>
+
+ {/* Step type */}
+ <div>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '4px' }}>STEP TYPE</div>
+ <select
+ value={stepType}
+ onChange={e => setStepType(e.target.value)}
+ style={{
+ ...inputStyle(),
+ backgroundColor: FINCEPT.DARK_BG,
+ cursor: 'pointer',
+ appearance: 'none' as const,
+ }}
+ >
+ {STEP_TYPES.map(t => (
+ <option key={t} value={t} style={{ backgroundColor: FINCEPT.DARK_BG }}>{t}</option>
+ ))}
+ {!STEP_TYPES.includes(stepType) && (
+ <option value={stepType} style={{ backgroundColor: FINCEPT.DARK_BG }}>{stepType}</option>
+ )}
+ </select>
+ </div>
+
+ {/* Dependencies */}
+ <div>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '4px' }}>DEPENDENCIES <span style={{ color: FINCEPT.MUTED, fontWeight: 400 }}>(comma separated step IDs)</span></div>
+ <input
+ value={depsText}
+ onChange={e => setDepsText(e.target.value)}
+ placeholder="step_id_1, step_id_2"
+ style={inputStyle(depsFocused)}
+ onFocus={() => setDepsFocused(true)}
+ onBlur={() => setDepsFocused(false)}
+ />
+ </div>
+
+ {/* Config key-value pairs */}
+ <div>
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>CONFIG</div>
+ <button
+ onClick={addConfigRow}
+ style={{ background: 'none', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', cursor: 'pointer', color: FINCEPT.ORANGE, padding: '2px 6px', fontSize: '8px', display: 'flex', alignItems: 'center', gap: '3px' }}
+ >
+ <Plus size={9} /> ADD KEY
+ </button>
+ </div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ {configRows.map((row, i) => (
+ <div key={i} style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
+ <input
+ value={row.key}
+ onChange={e => updateConfigRow(i, 'key', e.target.value)}
+ placeholder="key"
+ style={{ ...inputStyle(), flex: '0 0 36%' }}
+ />
+ <input
+ value={row.value}
+ onChange={e => updateConfigRow(i, 'value', e.target.value)}
+ placeholder="value"
+ style={{ ...inputStyle(), flex: 1 }}
+ />
+ <button
+ onClick={() => removeConfigRow(i)}
+ style={{ background: 'none', border: 'none', cursor: 'pointer', color: FINCEPT.MUTED, padding: '4px', flexShrink: 0, display: 'flex', alignItems: 'center' }}
+ >
+ <X size={10} />
+ </button>
+ </div>
+ ))}
+ {configRows.length === 0 && (
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED, fontStyle: 'italic' }}>No config — click ADD KEY to add parameters</div>
+ )}
+ </div>
+ </div>
+
+ {/* Save / Cancel */}
+ <div style={{ display: 'flex', gap: '6px', paddingTop: '4px', borderTop: `1px solid ${FINCEPT.BORDER}` }}>
+ <button
+ onClick={handleSave}
+ style={{ flex: 1, padding: '6px', backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG, border: 'none', borderRadius: '2px', cursor: 'pointer', fontSize: '8px', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}
+ >
+ <Save size={10} /> SAVE STEP
+ </button>
+ <button
+ onClick={onCancel}
+ style={{ flex: 1, padding: '6px', background: 'none', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', cursor: 'pointer', fontSize: '8px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}
+ >
+ <X size={10} /> CANCEL
+ </button>
+ </div>
+ </div>
+ );
+};
+
+// ─── StepCard ─────────────────────────────────────────────────────────────────
+
+interface StepCardProps {
+ step: PlanStep;
+ index: number;
+ total: number;
+ isExpanded: boolean;
+ isEditing: boolean;
+ canEdit: boolean;
+ onToggle: () => void;
+ onJumpToResult: () => void;
+ onEdit: () => void;
+ onSave: (updated: PlanStep) => void;
+ onCancelEdit: () => void;
+ onDelete: () => void;
+ onMoveUp: () => void;
+ onMoveDown: () => void;
+}
+
+const StepCard: React.FC<StepCardProps> = ({
+ step, index, total, isExpanded, isEditing, canEdit,
+ onToggle, onJumpToResult, onEdit, onSave, onCancelEdit, onDelete, onMoveUp, onMoveDown,
+}) => {
+ const color = STATUS_COLOR[step.status] ?? FINCEPT.GRAY;
+ const icon = STATUS_ICON[step.status] ?? <Clock size={12} />;
+ const resultPreview = step.result ? extractContextContent(step.result).slice(0, 160) : null;
+
+ return (
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${isEditing ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ borderLeft: `3px solid ${isEditing ? FINCEPT.ORANGE : color}`,
+ borderRadius: '2px',
+ overflow: 'hidden',
+ transition: 'border-color 0.15s',
+ }}>
+ {/* ── Header row ───────────────────────────────────────────────── */}
+ <div style={{ padding: '9px 12px', display: 'flex', alignItems: 'center', gap: '8px' }}>
+
+ {/* Drag handle / index */}
+ <span style={{
+ width: '22px', height: '22px', minWidth: '22px',
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
+ backgroundColor: FINCEPT.DARK_BG, color: isEditing ? FINCEPT.ORANGE : color,
+ fontSize: '9px', fontWeight: 700, borderRadius: '2px',
+ border: `1px solid ${isEditing ? FINCEPT.ORANGE : color}30`,
+ flexShrink: 0,
+ }}>
+ {index + 1}
+ </span>
+
+ {/* Name + type — clicking toggles expand */}
+ <div style={{ flex: 1, minWidth: 0, cursor: 'pointer', userSelect: 'none' }} onClick={onToggle}>
+ <div style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
+ {step.name}
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED, marginTop: '1px' }}>
+ <span style={{ color: FINCEPT.CYAN }}>{step.step_type}</span>
+ {step.dependencies.length > 0 && (
+ <span style={{ color: FINCEPT.GRAY }}> • deps: {step.dependencies.join(', ')}</span>
+ )}
+ </div>
+ </div>
+
+ {/* Action buttons (only visible for pending steps) */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', flexShrink: 0 }}>
+ {canEdit && (
+ <>
+ {/* Move up */}
+ <button
+ onClick={onMoveUp}
+ disabled={index === 0}
+ title="Move step up"
+ style={{ background: 'none', border: 'none', cursor: index === 0 ? 'not-allowed' : 'pointer', color: index === 0 ? FINCEPT.BORDER : FINCEPT.GRAY, padding: '3px', display: 'flex', alignItems: 'center' }}
+ >
+ <ArrowUp size={10} />
+ </button>
+ {/* Move down */}
+ <button
+ onClick={onMoveDown}
+ disabled={index === total - 1}
+ title="Move step down"
+ style={{ background: 'none', border: 'none', cursor: index === total - 1 ? 'not-allowed' : 'pointer', color: index === total - 1 ? FINCEPT.BORDER : FINCEPT.GRAY, padding: '3px', display: 'flex', alignItems: 'center' }}
+ >
+ <ArrowDown size={10} />
+ </button>
+ {/* Edit */}
+ <button
+ onClick={e => { e.stopPropagation(); onEdit(); }}
+ title="Edit step"
+ style={{ background: 'none', border: `1px solid ${isEditing ? FINCEPT.ORANGE : FINCEPT.BORDER}`, borderRadius: '2px', cursor: 'pointer', color: isEditing ? FINCEPT.ORANGE : FINCEPT.GRAY, padding: '3px 5px', display: 'flex', alignItems: 'center' }}
+ >
+ <Edit2 size={10} />
+ </button>
+ {/* Delete */}
+ <button
+ onClick={e => { e.stopPropagation(); onDelete(); }}
+ title="Remove step"
+ style={{ background: 'none', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', cursor: 'pointer', color: FINCEPT.RED, padding: '3px 5px', display: 'flex', alignItems: 'center' }}
+ >
+ <Trash2 size={10} />
+ </button>
+ </>
+ )}
+
+ {/* Jump to result */}
+ {step.status === 'completed' && (
+ <button
+ onClick={e => { e.stopPropagation(); onJumpToResult(); }}
+ title="View result"
+ style={{ background: 'none', border: 'none', cursor: 'pointer', color: FINCEPT.CYAN, display: 'flex', alignItems: 'center', padding: '3px' }}
+ >
+ <FileText size={11} />
+ </button>
+ )}
+
+ {/* Status badge */}
+ <span style={{
+ display: 'flex', alignItems: 'center', gap: '4px',
+ padding: '3px 7px',
+ backgroundColor: `${color}15`,
+ color,
+ fontSize: '8px', fontWeight: 700, borderRadius: '2px',
+ }}>
+ {icon}
+ {step.status.toUpperCase()}
+ </span>
+
+ {/* Expand toggle */}
+ <span style={{ cursor: 'pointer', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center' }} onClick={onToggle}>
+ {isExpanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
+ </span>
+ </div>
+ </div>
+
+ {/* ── Expanded body ─────────────────────────────────────────────── */}
+ {isExpanded && (
+ <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}`, padding: '12px', backgroundColor: `${FINCEPT.DARK_BG}80` }}>
+
+ {/* Editor mode */}
+ {isEditing ? (
+ <StepEditor
+ step={step}
+ onSave={onSave}
+ onCancel={onCancelEdit}
+ />
+ ) : (
+ <>
+ {/* Error */}
+ {step.error && (
+ <div style={{ padding: '8px', backgroundColor: `${FINCEPT.RED}10`, border: `1px solid ${FINCEPT.RED}30`, borderRadius: '2px', marginBottom: '8px' }}>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.RED, marginBottom: '4px' }}>ERROR</div>
+ <div style={{ fontSize: '9px', color: FINCEPT.WHITE, fontFamily: '"IBM Plex Mono", monospace', whiteSpace: 'pre-wrap' }}>{step.error}</div>
+ </div>
+ )}
+
+ {/* Result preview */}
+ {resultPreview && (
+ <div style={{ marginBottom: '8px' }}>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '4px', letterSpacing: '0.5px' }}>RESULT PREVIEW</div>
+ <div style={{ fontSize: '9px', color: FINCEPT.WHITE, fontFamily: '"IBM Plex Mono", monospace', whiteSpace: 'pre-wrap', wordBreak: 'break-word', lineHeight: '1.4', opacity: 0.85 }}>
+ {resultPreview}{resultPreview.length >= 160 ? '…' : ''}
+ </div>
+ </div>
+ )}
+
+ {/* Config viewer */}
+ {Object.keys(step.config || {}).length > 0 && (
+ <div style={{ marginBottom: '8px' }}>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>CONFIG</div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}>
+ {Object.entries(step.config).map(([k, v]) => (
+ <div key={k} style={{ display: 'flex', gap: '8px', alignItems: 'flex-start' }}>
+ <span style={{ fontSize: '8px', color: FINCEPT.CYAN, fontFamily: '"IBM Plex Mono", monospace', flexShrink: 0, paddingTop: '1px' }}>{k}:</span>
+ <span style={{ fontSize: '8px', color: FINCEPT.WHITE, fontFamily: '"IBM Plex Mono", monospace', wordBreak: 'break-word' }}>
+ {typeof v === 'string' ? v : JSON.stringify(v)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* No content state */}
+ {!step.error && !resultPreview && Object.keys(step.config || {}).length === 0 && (
+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, fontStyle: 'italic' }}>
+ {step.status === 'pending'
+ ? canEdit
+ ? 'Click the edit icon above to configure this step.'
+ : 'Waiting to execute…'
+ : 'No output yet'}
+ </div>
+ )}
+
+ {/* Edit prompt for pending steps with no config */}
+ {canEdit && step.status === 'pending' && Object.keys(step.config || {}).length === 0 && !step.error && (
+ <button
+ onClick={onEdit}
+ style={{ marginTop: '4px', padding: '5px 10px', background: 'none', border: `1px dashed ${FINCEPT.ORANGE}60`, borderRadius: '2px', cursor: 'pointer', fontSize: '8px', color: FINCEPT.ORANGE, display: 'flex', alignItems: 'center', gap: '4px' }}
+ >
+ <Settings size={9} /> CONFIGURE STEP
+ </button>
+ )}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
+// ─── Progress Bar ─────────────────────────────────────────────────────────────
+
+const PlanProgressBar: React.FC<{ steps: PlanStep[] }> = ({ steps }) => {
+ if (!steps.length) return null;
+ const completed = steps.filter(s => s.status === 'completed').length;
+ const failed = steps.filter(s => s.status === 'failed').length;
+ const running = steps.filter(s => s.status === 'running').length;
+ const pct = Math.round((completed / steps.length) * 100);
+
+ return (
+ <div style={{ padding: '7px 16px', borderBottom: `1px solid ${FINCEPT.BORDER}`, backgroundColor: FINCEPT.DARK_BG }}>
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '4px' }}>
+ <div style={{ display: 'flex', gap: '12px' }}>
+ {[
+ { label: 'DONE', val: completed, color: FINCEPT.GREEN },
+ { label: 'FAIL', val: failed, color: FINCEPT.RED },
+ { label: 'RUN', val: running, color: FINCEPT.ORANGE },
+ { label: 'WAIT', val: steps.length - completed - failed - running, color: FINCEPT.GRAY },
+ ].map(item => (
+ <span key={item.label} style={{ fontSize: '8px', color: item.color, fontWeight: 700 }}>
+ {item.val} {item.label}
+ </span>
+ ))}
+ </div>
+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY, fontWeight: 700 }}>{pct}%</span>
+ </div>
+ <div style={{ height: '3px', backgroundColor: FINCEPT.BORDER, borderRadius: '2px', overflow: 'hidden' }}>
+ <div style={{
+ height: '100%', width: `${pct}%`,
+ backgroundColor: failed > 0 ? FINCEPT.RED : running > 0 ? FINCEPT.ORANGE : FINCEPT.GREEN,
+ transition: 'width 0.4s ease, background-color 0.3s',
+ borderRadius: '2px',
+ }} />
+ </div>
+ </div>
+ );
+};
+
+// ─── Main Component ───────────────────────────────────────────────────────────
interface PlannerViewProps {
state: AgentConfigState;
@@ -15,142 +589,715 @@ export const PlannerView: React.FC<PlannerViewProps> = ({ state }) => {
const {
workflowSymbol, setWorkflowSymbol,
currentPlan, planExecuting, executing,
+ planGeneratedBy,
createPlan, executePlan,
} = state;
+ // ─── Left sidebar UI state ──────────────────────────────────────────
+ const [selectedTemplate, setSelectedTemplate] = useState<string>('stock_analysis');
+ const [useCustomQuery, setUseCustomQuery] = useState(false);
+ const [customQuery, setCustomQuery] = useState('');
+ const [showHistory, setShowHistory] = useState(false);
+ const [historySearch, setHistorySearch] = useState('');
+ const [planHistory, setPlanHistory] = useState<PlanHistoryEntry[]>([]);
+ const [activeHistoryId, setActiveHistoryId] = useState<string | null>(null);
+
+ // ─── Center panel UI state ──────────────────────────────────────────
+ const [expandedSteps, setExpandedSteps] = useState<Set<string>>(new Set());
+ const [editingStepId, setEditingStepId] = useState<string | null>(null);
+ const [searchQuery, setSearchQuery] = useState('');
+
+ // ─── LOCAL editable plan (deep clone of currentPlan, fully mutable) ─
+ const [editablePlan, setEditablePlan] = useState<ExecutionPlan | null>(null);
+
+ // ─── Results panel state ────────────────────────────────────────────
+ const [copiedResult, setCopiedResult] = useState(false);
+ const [activeResultStep, setActiveResultStep] = useState<string | null>(null);
+ const [resultsCollapsed, setResultsCollapsed] = useState(false);
+ const [resultsWidth, setResultsWidth] = useState(420);
+ const [isDraggingResults, setIsDraggingResults] = useState(false);
+
+ const dragStartX = useRef(0);
+ const dragStartWidth = useRef(0);
+ const resultStepRefs = useRef<Record<string, HTMLDivElement | null>>({});
+
+ // ─── Sync editablePlan from currentPlan ─────────────────────────────
+ // When backend returns a new/updated plan, deep-clone it into local state.
+ // We only reset editablePlan when the plan ID changes (new plan created),
+ // so mid-execution updates merge step statuses without blowing away edits.
+ useEffect(() => {
+ if (!currentPlan) { setEditablePlan(null); return; }
+
+ setEditablePlan(prev => {
+ if (!prev || prev.id !== currentPlan.id) {
+ // Brand new plan — full reset
+ setEditingStepId(null);
+ setExpandedSteps(new Set());
+ setActiveResultStep(null);
+ return deepClonePlan(currentPlan);
+ }
+ // Same plan — merge status/result/error from backend without losing local config edits
+ return {
+ ...prev,
+ status: currentPlan.status,
+ is_complete: currentPlan.is_complete,
+ has_failed: currentPlan.has_failed,
+ context: currentPlan.context,
+ steps: prev.steps.map(localStep => {
+ const serverStep = currentPlan.steps.find(s => s.id === localStep.id);
+ if (!serverStep) return localStep;
+ return {
+ ...localStep, // keep local name/type/config edits
+ status: serverStep.status, // take live status from server
+ result: serverStep.result,
+ error: serverStep.error,
+ };
+ }),
+ };
+ });
+ }, [currentPlan]);
+
+ // ─── Auto-save completed plan to history ────────────────────────────
+ useEffect(() => {
+ if (!currentPlan || (!currentPlan.is_complete && !currentPlan.has_failed)) return;
+ setPlanHistory(prev => {
+ if (prev.find(h => h.id === currentPlan.id)) return prev;
+ const entry: PlanHistoryEntry = {
+ id: currentPlan.id,
+ symbol: workflowSymbol,
+ planType: selectedTemplate,
+ timestamp: new Date(),
+ plan: deepClonePlan(currentPlan),
+ label: `${workflowSymbol} · ${PLAN_TEMPLATES.find(t => t.id === selectedTemplate)?.name ?? selectedTemplate}`,
+ };
+ return [entry, ...prev.slice(0, 19)];
+ });
+ }, [currentPlan?.is_complete, currentPlan?.has_failed]);
+
+ // ─── Auto-expand running step ────────────────────────────────────────
+ useEffect(() => {
+ if (!editablePlan) return;
+ const running = editablePlan.steps.find(s => s.status === 'running');
+ if (running) setExpandedSteps(prev => new Set([...prev, running.id]));
+ }, [editablePlan]);
+
+ // ─── Derived display plan (history view OR live editable) ────────────
+ const displayPlan = activeHistoryId
+ ? planHistory.find(h => h.id === activeHistoryId)?.plan ?? editablePlan
+ : editablePlan;
+
+ const isHistoryView = !!activeHistoryId;
+ // Steps can be edited only when looking at the live editable plan and it hasn't started
+ const canEditSteps = !isHistoryView && !!editablePlan && !editablePlan.is_complete && !planExecuting;
+
+ // ─── Resize handler ──────────────────────────────────────────────────
+ const onResizeMouseDown = useCallback((e: React.MouseEvent) => {
+ e.preventDefault();
+ dragStartX.current = e.clientX;
+ dragStartWidth.current = resultsWidth;
+ setIsDraggingResults(true);
+ const onMouseMove = (ev: MouseEvent) => {
+ const delta = dragStartX.current - ev.clientX;
+ setResultsWidth(Math.max(280, Math.min(700, dragStartWidth.current + delta)));
+ };
+ const onMouseUp = () => {
+ setIsDraggingResults(false);
+ window.removeEventListener('mousemove', onMouseMove);
+ window.removeEventListener('mouseup', onMouseUp);
+ };
+ window.addEventListener('mousemove', onMouseMove);
+ window.addEventListener('mouseup', onMouseUp);
+ }, [resultsWidth]);
+
+ // ─── Step mutation helpers ───────────────────────────────────────────
+ const updateStep = useCallback((stepId: string, updated: PlanStep) => {
+ setEditablePlan(prev => {
+ if (!prev) return prev;
+ return { ...prev, steps: prev.steps.map(s => s.id === stepId ? updated : s) };
+ });
+ setEditingStepId(null);
+ }, []);
+
+ const deleteStep = useCallback((stepId: string) => {
+ setEditablePlan(prev => {
+ if (!prev) return prev;
+ return { ...prev, steps: prev.steps.filter(s => s.id !== stepId) };
+ });
+ setEditingStepId(null);
+ }, []);
+
+ const moveStep = useCallback((stepId: string, direction: 'up' | 'down') => {
+ setEditablePlan(prev => {
+ if (!prev) return prev;
+ const steps = [...prev.steps];
+ const idx = steps.findIndex(s => s.id === stepId);
+ if (idx < 0) return prev;
+ const targetIdx = direction === 'up' ? idx - 1 : idx + 1;
+ if (targetIdx < 0 || targetIdx >= steps.length) return prev;
+ [steps[idx], steps[targetIdx]] = [steps[targetIdx], steps[idx]];
+ return { ...prev, steps };
+ });
+ }, []);
+
+ const addStep = useCallback((afterIndex: number) => {
+ setEditablePlan(prev => {
+ if (!prev) return prev;
+ const newStep = makeNewStep(afterIndex + 1);
+ const steps = [...prev.steps];
+ steps.splice(afterIndex + 1, 0, newStep);
+ return { ...prev, steps };
+ });
+ // Auto-expand and open editor for the new step
+ setTimeout(() => {
+ setEditablePlan(prev => {
+ if (!prev) return prev;
+ const newStep = prev.steps[afterIndex + 1];
+ if (newStep) {
+ setExpandedSteps(s => new Set([...s, newStep.id]));
+ setEditingStepId(newStep.id);
+ }
+ return prev;
+ });
+ }, 50);
+ }, []);
+
+ // ─── Plan action handlers ────────────────────────────────────────────
+ const handleCreatePlan = useCallback(() => {
+ setActiveHistoryId(null);
+ setEditingStepId(null);
+ setExpandedSteps(new Set());
+ setActiveResultStep(null);
+ // Build query: custom text takes priority, otherwise derive from template
+ let query: string | undefined;
+ if (useCustomQuery && customQuery.trim()) {
+ query = customQuery.trim();
+ } else {
+ const templateQueryMap: Record<string, string> = {
+ stock_analysis: 'Perform a comprehensive stock analysis including price data, fundamentals, news sentiment, technical analysis, and investment recommendation',
+ portfolio_rebalance: 'Analyze and rebalance the portfolio: fetch current positions, evaluate risk metrics, generate rebalancing recommendations, and calculate required trades',
+ risk_audit: 'Conduct a risk audit: assess volatility, drawdown, correlation, concentration risk, and provide risk-adjusted recommendations',
+ sector_rotation: 'Analyze sector rotation opportunities: evaluate sector performance, macroeconomic trends, relative strength, and recommend sector allocation adjustments',
+ };
+ query = templateQueryMap[selectedTemplate];
+ }
+ createPlan(query);
+ }, [createPlan, useCustomQuery, customQuery, selectedTemplate]);
+
+ const handleExecutePlan = useCallback(() => {
+ if (!editablePlan) return;
+ setActiveHistoryId(null);
+ setEditingStepId(null);
+ executePlan(editablePlan);
+ }, [executePlan, editablePlan]);
+
+ const handleTemplateSelect = (template: PlanTemplate) => {
+ setSelectedTemplate(template.id);
+ if (template.defaultSymbol !== 'PORTFOLIO') setWorkflowSymbol(template.defaultSymbol);
+ };
+
+ // ─── Results helpers ─────────────────────────────────────────────────
+ const jumpToResult = (stepKey: string) => {
+ setActiveResultStep(stepKey);
+ setResultsCollapsed(false);
+ setTimeout(() => {
+ resultStepRefs.current[stepKey]?.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ }, 80);
+ };
+
+ const handleCopyResults = useCallback(() => {
+ if (!displayPlan?.context) return;
+ const text = Object.entries(displayPlan.context)
+ .map(([key, val]) => `## ${key.replace(/_/g, ' ').toUpperCase()}\n\n${extractContextContent(val)}`)
+ .join('\n\n---\n\n');
+ navigator.clipboard.writeText(text).then(() => {
+ setCopiedResult(true);
+ setTimeout(() => setCopiedResult(false), 2000);
+ });
+ }, [displayPlan]);
+
+ const handleExportMarkdown = useCallback(() => {
+ if (!displayPlan) return;
+ const lines: string[] = [
+ `# ${displayPlan.name}`,
+ `> ${displayPlan.description}`,
+ '',
+ `**Status:** ${displayPlan.status} | **Steps:** ${displayPlan.steps.length}`,
+ '',
+ '---',
+ '',
+ ];
+ Object.entries(displayPlan.context || {}).forEach(([key, val]) => {
+ lines.push(`## ${key.replace(/_/g, ' ')}`);
+ lines.push('');
+ lines.push(extractContextContent(val));
+ lines.push('');
+ lines.push('---');
+ lines.push('');
+ });
+ const blob = new Blob([lines.join('\n')], { type: 'text/markdown' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `${workflowSymbol}-plan-${Date.now()}.md`;
+ a.click();
+ URL.revokeObjectURL(url);
+ }, [displayPlan, workflowSymbol]);
+
+ // ─── Filtered steps ──────────────────────────────────────────────────
+ const filteredSteps = (displayPlan?.steps ?? []).filter(s =>
+ !searchQuery ||
+ s.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ s.step_type.toLowerCase().includes(searchQuery.toLowerCase())
+ );
+
+ const filteredHistory = planHistory.filter(h =>
+ !historySearch || h.label.toLowerCase().includes(historySearch.toLowerCase())
+ );
+
+ const contextEntries = Object.entries(displayPlan?.context ?? {});
+ const currentTemplate = PLAN_TEMPLATES.find(t => t.id === selectedTemplate);
+
+ // ─── Render ──────────────────────────────────────────────────────────
return (
- <div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>
- {/* Left - Plan Creation */}
- <div style={{ width: '320px', minWidth: '320px', backgroundColor: FINCEPT.PANEL_BG, borderRight: `1px solid ${FINCEPT.BORDER}`, display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
- <div style={{ padding: '12px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}`, display: 'flex', alignItems: 'center', gap: '8px' }}>
- <ListTree size={14} style={{ color: FINCEPT.ORANGE }} />
- <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>EXECUTION PLANNER</span>
- </div>
+ <div style={{
+ display: 'flex', height: '100%', overflow: 'hidden',
+ fontFamily: '"IBM Plex Mono", monospace',
+ userSelect: isDraggingResults ? 'none' : 'auto',
+ }}>
- <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
- <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '8px' }}>CREATE PLAN</label>
- <input
- type="text"
- value={workflowSymbol}
- onChange={e => setWorkflowSymbol(e.target.value.toUpperCase())}
- placeholder="Symbol (e.g., AAPL)"
- style={{ width: '100%', padding: '8px 10px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '10px', marginBottom: '8px', fontFamily: '"IBM Plex Mono", monospace' }}
- />
+ {/* ══ LEFT SIDEBAR ════════════════════════════════════════════════ */}
+ <div style={{
+ width: '280px', minWidth: '280px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex', flexDirection: 'column', flexShrink: 0, overflow: 'hidden',
+ }}>
+
+ {/* Header */}
+ <div style={{ padding: '10px 12px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <ListTree size={13} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>EXECUTION PLANNER</span>
+ </div>
<button
- onClick={createPlan}
- disabled={executing}
- style={{ width: '100%', padding: '8px', backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG, border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: executing ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', opacity: executing ? 0.7 : 1 }}
+ onClick={() => setShowHistory(v => !v)}
+ title="Plan history"
+ style={{ background: 'none', border: 'none', cursor: 'pointer', color: showHistory ? FINCEPT.ORANGE : FINCEPT.GRAY, display: 'flex', alignItems: 'center', gap: '3px', padding: '2px' }}
>
- {executing ? <Loader2 size={10} className="animate-spin" /> : <Target size={10} />}
- CREATE PLAN
+ <Clock size={13} />
+ {planHistory.length > 0 && (
+ <span style={{ fontSize: '8px', color: FINCEPT.ORANGE, fontWeight: 700 }}>{planHistory.length}</span>
+ )}
</button>
</div>
- {/* Templates */}
- <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
- <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '8px' }}>TEMPLATES</label>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
- {[
- { id: 'stock_analysis', name: 'Stock Analysis', desc: 'Fundamental + technical' },
- { id: 'portfolio_rebalance', name: 'Portfolio Rebalance', desc: 'Optimize allocation' },
- { id: 'sector_rotation', name: 'Sector Rotation', desc: 'Identify opportunities' },
- { id: 'risk_audit', name: 'Risk Audit', desc: 'Risk assessment' },
- ].map(template => (
+ {/* ── History mode ── */}
+ {showHistory ? (
+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
+ <div style={{ padding: '8px 12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{ position: 'relative' }}>
+ <Search size={10} style={{ position: 'absolute', left: '8px', top: '50%', transform: 'translateY(-50%)', color: FINCEPT.MUTED }} />
+ <input
+ value={historySearch}
+ onChange={e => setHistorySearch(e.target.value)}
+ placeholder="Search history…"
+ style={{ width: '100%', padding: '6px 8px 6px 24px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', boxSizing: 'border-box', outline: 'none' }}
+ />
+ </div>
+ </div>
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ {filteredHistory.length === 0 ? (
+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.MUTED, fontSize: '9px' }}>No plan history yet</div>
+ ) : filteredHistory.map(entry => (
+ <button
+ key={entry.id}
+ onClick={() => { setActiveHistoryId(entry.id); setShowHistory(false); setExpandedSteps(new Set()); setActiveResultStep(null); }}
+ style={{
+ width: '100%', padding: '9px 10px', marginBottom: '4px',
+ backgroundColor: activeHistoryId === entry.id ? `${FINCEPT.ORANGE}15` : FINCEPT.DARK_BG,
+ border: `1px solid ${activeHistoryId === entry.id ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ borderRadius: '2px', cursor: 'pointer', textAlign: 'left',
+ }}
+ >
+ <div style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.WHITE, marginBottom: '3px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
+ {entry.label}
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ fontSize: '8px', color: entry.plan.is_complete ? FINCEPT.GREEN : entry.plan.has_failed ? FINCEPT.RED : FINCEPT.GRAY }}>
+ {entry.plan.is_complete ? '✓ Complete' : entry.plan.has_failed ? '✗ Failed' : entry.plan.status}
+ </span>
+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>
+ {entry.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
+ </span>
+ </div>
+ </button>
+ ))}
+ </div>
+ {planHistory.length > 0 && (
+ <div style={{ padding: '8px', borderTop: `1px solid ${FINCEPT.BORDER}` }}>
+ <button
+ onClick={() => { setPlanHistory([]); setShowHistory(false); setActiveHistoryId(null); }}
+ style={{ width: '100%', padding: '6px', background: 'none', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', cursor: 'pointer', fontSize: '8px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}
+ >
+ <Trash2 size={9} /> CLEAR HISTORY
+ </button>
+ </div>
+ )}
+ </div>
+ ) : (
+ /* ── Normal sidebar mode ── */
+ <div style={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
+
+ {/* Plan type grid */}
+ <div style={{ padding: '10px 12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '8px' }}>PLAN TYPE</div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '5px' }}>
+ {PLAN_TEMPLATES.map(template => (
+ <button
+ key={template.id}
+ onClick={() => handleTemplateSelect(template)}
+ style={{
+ padding: '8px 6px',
+ backgroundColor: selectedTemplate === template.id ? `${template.color}15` : FINCEPT.DARK_BG,
+ border: `1px solid ${selectedTemplate === template.id ? template.color : FINCEPT.BORDER}`,
+ borderRadius: '2px', cursor: 'pointer', textAlign: 'left', transition: 'all 0.15s',
+ }}
+ onMouseEnter={e => { if (selectedTemplate !== template.id) e.currentTarget.style.borderColor = template.color + '60'; }}
+ onMouseLeave={e => { if (selectedTemplate !== template.id) e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ >
+ <div style={{ color: template.color, marginBottom: '3px', display: 'flex', alignItems: 'center', gap: '4px' }}>
+ {template.icon}
+ <span style={{ fontSize: '9px', fontWeight: 700 }}>{template.name.split(' ')[0]}</span>
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED, lineHeight: 1.3 }}>{template.desc}</div>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Target input */}
+ <div style={{ padding: '10px 12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '6px' }}>TARGET</div>
+ <input
+ type="text"
+ value={workflowSymbol}
+ onChange={e => setWorkflowSymbol(e.target.value.toUpperCase())}
+ placeholder="Symbol (e.g., AAPL)"
+ style={{ width: '100%', padding: '7px 10px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '10px', boxSizing: 'border-box', fontFamily: '"IBM Plex Mono", monospace', outline: 'none' }}
+ onFocus={e => { e.currentTarget.style.borderColor = currentTemplate?.color ?? FINCEPT.ORANGE; }}
+ onBlur={e => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ />
+ <div style={{ marginTop: '8px' }}>
+ <label style={{ display: 'flex', alignItems: 'center', gap: '6px', cursor: 'pointer' }}>
+ <input type="checkbox" checked={useCustomQuery} onChange={e => setUseCustomQuery(e.target.checked)} style={{ accentColor: FINCEPT.ORANGE, cursor: 'pointer' }} />
+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY, fontWeight: 600 }}>CUSTOM QUERY</span>
+ </label>
+ {useCustomQuery && (
+ <textarea
+ value={customQuery}
+ onChange={e => setCustomQuery(e.target.value)}
+ placeholder="Describe your analysis request…"
+ rows={3}
+ style={{ marginTop: '6px', width: '100%', padding: '7px 10px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', resize: 'vertical', boxSizing: 'border-box', fontFamily: '"IBM Plex Mono", monospace', lineHeight: 1.5, outline: 'none' }}
+ onFocus={e => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}
+ onBlur={e => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ />
+ )}
+ </div>
+ </div>
+
+ {/* Action buttons */}
+ <div style={{ padding: '10px 12px', borderBottom: `1px solid ${FINCEPT.BORDER}`, display: 'flex', flexDirection: 'column', gap: '6px' }}>
<button
- key={template.id}
- onClick={() => { setWorkflowSymbol('AAPL'); createPlan(); }}
- style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', cursor: 'pointer', textAlign: 'left', transition: 'all 0.2s' }}
- onMouseEnter={e => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}
- onMouseLeave={e => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ onClick={handleCreatePlan}
+ disabled={executing || !workflowSymbol.trim()}
+ style={{ width: '100%', padding: '9px', backgroundColor: executing ? `${FINCEPT.ORANGE}50` : currentTemplate?.color ?? FINCEPT.ORANGE, color: FINCEPT.DARK_BG, border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: executing || !workflowSymbol.trim() ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', opacity: !workflowSymbol.trim() ? 0.5 : 1 }}
>
- <div style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.WHITE, marginBottom: '2px' }}>{template.name}</div>
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{template.desc}</div>
+ {executing ? <Loader2 size={11} className="animate-spin" /> : <Target size={11} />}
+ {executing ? 'AI GENERATING…' : 'CREATE PLAN'}
</button>
- ))}
+ {!executing && (
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED, textAlign: 'center', letterSpacing: '0.3px' }}>
+ LLM generates a custom plan for your query
+ </div>
+ )}
+
+ {editablePlan && !editablePlan.is_complete && !isHistoryView && (
+ <button
+ onClick={handleExecutePlan}
+ disabled={planExecuting}
+ style={{ width: '100%', padding: '9px', backgroundColor: planExecuting ? `${FINCEPT.GREEN}40` : FINCEPT.GREEN, color: FINCEPT.DARK_BG, border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: planExecuting ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px' }}
+ >
+ {planExecuting ? <Loader2 size={11} className="animate-spin" /> : <Play size={11} />}
+ {planExecuting ? 'EXECUTING…' : 'EXECUTE PLAN'}
+ </button>
+ )}
+
+ {displayPlan && (
+ <div style={{ display: 'flex', gap: '5px' }}>
+ {displayPlan.is_complete && (
+ <>
+ <button
+ onClick={handleCopyResults}
+ style={{ flex: 1, padding: '7px', background: 'none', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', cursor: 'pointer', fontSize: '8px', color: copiedResult ? FINCEPT.GREEN : FINCEPT.GRAY, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px', transition: 'color 0.2s' }}
+ >
+ {copiedResult ? <Check size={10} /> : <Copy size={10} />}
+ {copiedResult ? 'COPIED' : 'COPY'}
+ </button>
+ <button
+ onClick={handleExportMarkdown}
+ style={{ flex: 1, padding: '7px', background: 'none', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', cursor: 'pointer', fontSize: '8px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}
+ >
+ <Download size={10} /> EXPORT
+ </button>
+ </>
+ )}
+ {isHistoryView && (
+ <button
+ onClick={() => { setActiveHistoryId(null); setExpandedSteps(new Set()); }}
+ style={{ flex: 1, padding: '7px', background: 'none', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', cursor: 'pointer', fontSize: '8px', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}
+ >
+ <RotateCcw size={10} /> BACK TO LIVE
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Plan info */}
+ {displayPlan && (
+ <div style={{ padding: '10px 12px', flex: 1, overflow: 'auto' }}>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '6px' }}>PLAN INFO</div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
+ {[
+ { label: 'NAME', value: displayPlan.name },
+ { label: 'STATUS', value: displayPlan.status.toUpperCase(), color: displayPlan.is_complete ? FINCEPT.GREEN : displayPlan.has_failed ? FINCEPT.RED : FINCEPT.ORANGE },
+ { label: 'STEPS', value: `${displayPlan.steps.length} total` },
+ { label: 'DONE', value: `${displayPlan.steps.filter(s => s.status === 'completed').length} / ${displayPlan.steps.length}` },
+ ].map(row => (
+ <div key={row.label} style={{ display: 'flex', justifyContent: 'space-between', gap: '8px' }}>
+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED, flexShrink: 0 }}>{row.label}</span>
+ <span style={{ fontSize: '8px', color: (row as any).color ?? FINCEPT.WHITE, textAlign: 'right', wordBreak: 'break-word' }}>{row.value}</span>
+ </div>
+ ))}
+ {displayPlan.description && (
+ <div style={{ marginTop: '4px', padding: '6px 8px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '2px', border: `1px solid ${FINCEPT.BORDER}` }}>
+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY, lineHeight: 1.4 }}>{displayPlan.description}</span>
+ </div>
+ )}
+ {canEditSteps && (
+ <div style={{ marginTop: '4px', padding: '5px 8px', backgroundColor: `${FINCEPT.ORANGE}08`, borderRadius: '2px', border: `1px dashed ${FINCEPT.ORANGE}40` }}>
+ <span style={{ fontSize: '8px', color: FINCEPT.ORANGE }}>✎ Plan is editable — use step controls to modify before executing.</span>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
</div>
- </div>
+ )}
</div>
- {/* Center - Plan Visualization */}
+ {/* ══ CENTER — Steps ══════════════════════════════════════════════ */}
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minWidth: 0 }}>
- {currentPlan ? (
+ {displayPlan ? (
<>
- <div style={{ padding: '12px 16px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
- <div>
- <div style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>{currentPlan.name}</div>
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{currentPlan.description}</div>
- </div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <span style={{ padding: '4px 8px', backgroundColor: currentPlan.is_complete ? `${FINCEPT.GREEN}20` : currentPlan.has_failed ? `${FINCEPT.RED}20` : `${FINCEPT.ORANGE}20`, color: currentPlan.is_complete ? FINCEPT.GREEN : currentPlan.has_failed ? FINCEPT.RED : FINCEPT.ORANGE, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
- {currentPlan.status}
+ {/* Toolbar */}
+ <div style={{ padding: '8px 12px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}`, display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE, flex: 1, display: 'flex', alignItems: 'center', gap: '6px', minWidth: 0 }}>
+ <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
+ {isHistoryView ? '📂 ' : ''}{displayPlan.name}
</span>
+ {!isHistoryView && planGeneratedBy === 'llm' && (
+ <span style={{ flexShrink: 0, fontSize: '8px', fontWeight: 700, padding: '2px 5px', backgroundColor: '#6366f120', color: '#818cf8', border: '1px solid #6366f140', borderRadius: '2px', letterSpacing: '0.4px' }}>
+ AI
+ </span>
+ )}
+ {!isHistoryView && planGeneratedBy === 'fallback' && (
+ <span style={{ flexShrink: 0, fontSize: '8px', fontWeight: 700, padding: '2px 5px', backgroundColor: `${FINCEPT.ORANGE}20`, color: FINCEPT.ORANGE, border: `1px solid ${FINCEPT.ORANGE}40`, borderRadius: '2px', letterSpacing: '0.4px' }}>
+ TPL
+ </span>
+ )}
+ </div>
+
+ {/* Step search */}
+ <div style={{ position: 'relative', flexShrink: 0 }}>
+ <Search size={9} style={{ position: 'absolute', left: '7px', top: '50%', transform: 'translateY(-50%)', color: FINCEPT.MUTED }} />
+ <input
+ value={searchQuery}
+ onChange={e => setSearchQuery(e.target.value)}
+ placeholder="Filter steps…"
+ style={{ width: '120px', padding: '5px 8px 5px 22px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace', outline: 'none' }}
+ />
+ </div>
+
+ {/* Expand/Collapse all */}
+ <button
+ onClick={() => setExpandedSteps(prev => prev.size > 0 ? new Set() : new Set(displayPlan.steps.map(s => s.id)))}
+ style={{ background: 'none', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', cursor: 'pointer', color: FINCEPT.GRAY, padding: '4px 6px', display: 'flex', alignItems: 'center', gap: '3px', fontSize: '8px', flexShrink: 0 }}
+ >
+ {expandedSteps.size > 0 ? <Minimize2 size={10} /> : <Maximize2 size={10} />}
+ {expandedSteps.size > 0 ? 'COLLAPSE' : 'EXPAND'}
+ </button>
+
+ {/* Add step at end (only when editable) */}
+ {canEditSteps && (
<button
- onClick={executePlan}
- disabled={planExecuting || currentPlan.is_complete}
- style={{ padding: '6px 12px', backgroundColor: currentPlan.is_complete ? FINCEPT.GREEN : FINCEPT.ORANGE, color: FINCEPT.DARK_BG, border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: (planExecuting || currentPlan.is_complete) ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', gap: '4px', opacity: planExecuting ? 0.7 : 1 }}
+ onClick={() => addStep(displayPlan.steps.length - 1)}
+ title="Add new step at end"
+ style={{ background: 'none', border: `1px solid ${FINCEPT.ORANGE}60`, borderRadius: '2px', cursor: 'pointer', color: FINCEPT.ORANGE, padding: '4px 7px', display: 'flex', alignItems: 'center', gap: '3px', fontSize: '8px', flexShrink: 0 }}
>
- {planExecuting ? <Loader2 size={10} className="animate-spin" /> : <Play size={10} />}
- {currentPlan.is_complete ? 'DONE' : 'EXECUTE'}
+ <Plus size={10} /> ADD STEP
</button>
- </div>
+ )}
</div>
- <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
- {currentPlan.steps.map((step, idx) => (
- <div
- key={step.id}
- style={{
- padding: '12px', backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `3px solid ${step.status === 'completed' ? FINCEPT.GREEN : step.status === 'failed' ? FINCEPT.RED : step.status === 'running' ? FINCEPT.ORANGE : FINCEPT.GRAY}`,
- borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '12px',
+ {/* Progress bar */}
+ <PlanProgressBar steps={displayPlan.steps} />
+
+ {/* Steps list */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: '5px' }}>
+ {filteredSteps.length === 0 ? (
+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.MUTED, fontSize: '10px' }}>
+ {searchQuery ? 'No steps match your filter' : 'No steps in this plan'}
+ </div>
+ ) : filteredSteps.map((step, idx) => (
+ <React.Fragment key={step.id}>
+ <StepCard
+ step={step}
+ index={displayPlan.steps.indexOf(step)}
+ total={displayPlan.steps.length}
+ isExpanded={expandedSteps.has(step.id)}
+ isEditing={editingStepId === step.id}
+ canEdit={canEditSteps && step.status === 'pending'}
+ onToggle={() => setExpandedSteps(prev => {
+ const next = new Set(prev);
+ next.has(step.id) ? next.delete(step.id) : next.add(step.id);
+ return next;
+ })}
+ onJumpToResult={() => {
+ const ctxKey =
+ Object.keys(displayPlan.context ?? {}).find(k =>
+ k === step.id ||
+ k === step.name ||
+ k.toLowerCase().includes(step.name.toLowerCase().replace(/\s+/g, '_')) ||
+ k.toLowerCase().replace(/_/g, ' ').includes(step.name.toLowerCase())
+ ) ?? Object.keys(displayPlan.context ?? {})[idx] ?? null;
+ if (ctxKey) jumpToResult(ctxKey);
}}
- >
- <span style={{ width: '24px', height: '24px', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.GRAY, fontSize: '10px', fontWeight: 700, borderRadius: '2px' }}>
- {idx + 1}
- </span>
- <div style={{ flex: 1 }}>
- <div style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE }}>{step.name}</div>
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
- {step.step_type}{step.dependencies.length > 0 && ` • Deps: ${step.dependencies.join(', ')}`}
- </div>
+ onEdit={() => {
+ setExpandedSteps(prev => new Set([...prev, step.id]));
+ setEditingStepId(prev => prev === step.id ? null : step.id);
+ }}
+ onSave={updated => updateStep(step.id, updated)}
+ onCancelEdit={() => setEditingStepId(null)}
+ onDelete={() => deleteStep(step.id)}
+ onMoveUp={() => moveStep(step.id, 'up')}
+ onMoveDown={() => moveStep(step.id, 'down')}
+ />
+
+ {/* Insert-step-here button between steps */}
+ {canEditSteps && idx < filteredSteps.length - 1 && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', padding: '0 4px' }}>
+ <div style={{ flex: 1, height: '1px', backgroundColor: FINCEPT.BORDER }} />
+ <button
+ onClick={() => addStep(displayPlan.steps.indexOf(step))}
+ title="Insert step here"
+ style={{ background: 'none', border: `1px dashed ${FINCEPT.BORDER}`, borderRadius: '2px', cursor: 'pointer', color: FINCEPT.MUTED, padding: '1px 8px', fontSize: '8px', display: 'flex', alignItems: 'center', gap: '3px', flexShrink: 0, transition: 'color 0.15s, border-color 0.15s' }}
+ onMouseEnter={e => { e.currentTarget.style.color = FINCEPT.ORANGE; e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}
+ onMouseLeave={e => { e.currentTarget.style.color = FINCEPT.MUTED; e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ >
+ <Plus size={8} /> INSERT
+ </button>
+ <div style={{ flex: 1, height: '1px', backgroundColor: FINCEPT.BORDER }} />
</div>
- <span style={{
- padding: '4px 8px',
- backgroundColor: step.status === 'completed' ? `${FINCEPT.GREEN}20` : step.status === 'failed' ? `${FINCEPT.RED}20` : step.status === 'running' ? `${FINCEPT.ORANGE}20` : FINCEPT.BORDER,
- color: step.status === 'completed' ? FINCEPT.GREEN : step.status === 'failed' ? FINCEPT.RED : step.status === 'running' ? FINCEPT.ORANGE : FINCEPT.GRAY,
- fontSize: '8px', fontWeight: 700, borderRadius: '2px', textTransform: 'uppercase',
- }}>
- {step.status}
- </span>
- </div>
- ))}
- </div>
+ )}
+ </React.Fragment>
+ ))}
</div>
</>
) : (
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: FINCEPT.PANEL_BG }}>
- <div style={{ textAlign: 'center', color: FINCEPT.MUTED }}>
- <ListTree size={40} style={{ marginBottom: '12px', opacity: 0.5 }} />
- <div style={{ fontSize: '11px' }}>Create a plan to visualize steps</div>
+ <div style={{ textAlign: 'center', color: FINCEPT.MUTED, maxWidth: '260px' }}>
+ <ListTree size={36} style={{ marginBottom: '12px', opacity: 0.3, color: FINCEPT.ORANGE }} />
+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE, marginBottom: '6px' }}>NO ACTIVE PLAN</div>
+ <div style={{ fontSize: '9px', lineHeight: 1.6 }}>
+ Select a plan type and target symbol on the left, then click{' '}
+ <strong style={{ color: FINCEPT.ORANGE }}>CREATE PLAN</strong> to generate an execution roadmap.
+ </div>
</div>
</div>
)}
</div>
- {/* Right - Results (only when plan is complete) */}
- {currentPlan?.is_complete && currentPlan.context && (
- <div style={{ width: '300px', minWidth: '300px', backgroundColor: FINCEPT.PANEL_BG, borderLeft: `1px solid ${FINCEPT.BORDER}`, display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
- <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' }}>PLAN RESULTS</span>
- </div>
- <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
- <pre style={{ fontSize: '9px', color: FINCEPT.WHITE, whiteSpace: 'pre-wrap', wordBreak: 'break-word', margin: 0, fontFamily: '"IBM Plex Mono", monospace' }}>
- {JSON.stringify(currentPlan.context, null, 2)}
- </pre>
+ {/* ══ RESULTS PANEL ═══════════════════════════════════════════════ */}
+ {contextEntries.length > 0 && (
+ <>
+ {!resultsCollapsed && (
+ <div
+ onMouseDown={onResizeMouseDown}
+ style={{ width: '4px', cursor: 'col-resize', backgroundColor: isDraggingResults ? FINCEPT.ORANGE : 'transparent', transition: 'background-color 0.2s', flexShrink: 0 }}
+ onMouseEnter={e => { e.currentTarget.style.backgroundColor = `${FINCEPT.ORANGE}60`; }}
+ onMouseLeave={e => { if (!isDraggingResults) e.currentTarget.style.backgroundColor = 'transparent'; }}
+ />
+ )}
+
+ <div style={{
+ width: resultsCollapsed ? '36px' : `${resultsWidth}px`,
+ minWidth: resultsCollapsed ? '36px' : '280px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderLeft: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex', flexDirection: 'column', flexShrink: 0,
+ overflow: 'hidden', transition: resultsCollapsed ? 'width 0.2s' : 'none',
+ }}>
+ {/* Header */}
+ <div style={{ padding: '8px 10px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}`, display: 'flex', alignItems: 'center', gap: '6px', flexShrink: 0 }}>
+ <button
+ onClick={() => setResultsCollapsed(v => !v)}
+ style={{ background: 'none', border: 'none', cursor: 'pointer', color: FINCEPT.GRAY, display: 'flex', alignItems: 'center', padding: '2px', flexShrink: 0 }}
+ >
+ {resultsCollapsed ? <PanelRightOpen size={13} /> : <PanelRightClose size={13} />}
+ </button>
+ {!resultsCollapsed && (
+ <>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', flex: 1 }}>PLAN RESULTS</span>
+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>{contextEntries.length} step{contextEntries.length !== 1 ? 's' : ''}</span>
+ </>
+ )}
+ </div>
+
+ {/* Scroll area */}
+ {!resultsCollapsed && (
+ <div style={{ flex: 1, overflow: 'auto', padding: '12px', display: 'flex', flexDirection: 'column', gap: '14px' }}>
+ {contextEntries.map(([stepKey, stepValue]) => {
+ const content = extractContextContent(stepValue);
+ const isActive = activeResultStep === stepKey;
+
+ return (
+ <div
+ key={stepKey}
+ ref={el => { resultStepRefs.current[stepKey] = el; }}
+ style={{ borderLeft: `2px solid ${isActive ? FINCEPT.CYAN : FINCEPT.ORANGE}`, paddingLeft: '10px', transition: 'border-color 0.3s', scrollMarginTop: '8px' }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: isActive ? FINCEPT.CYAN : FINCEPT.ORANGE, letterSpacing: '0.5px', textTransform: 'uppercase' }}>
+ {stepKey.replace(/_/g, ' ')}
+ </div>
+ <button
+ onClick={() => navigator.clipboard.writeText(content)}
+ title="Copy section"
+ style={{ background: 'none', border: 'none', cursor: 'pointer', color: FINCEPT.MUTED, padding: '2px', display: 'flex', alignItems: 'center' }}
+ >
+ <Copy size={9} />
+ </button>
+ </div>
+ <MarkdownRenderer content={content} style={{ fontSize: '10px', lineHeight: '1.5' }} />
+ </div>
+ );
+ })}
+ </div>
+ )}
</div>
- </div>
+ </>
)}
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/views/TeamsView.tsx b/fincept-terminal-desktop/src/components/tabs/agent-config/views/TeamsView.tsx
index 7d7770c30..d76a7ae5a 100644
--- a/fincept-terminal-desktop/src/components/tabs/agent-config/views/TeamsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/views/TeamsView.tsx
@@ -3,7 +3,7 @@
*/
import React from 'react';
-import { Users, Trash2, Plus, Loader2, Play, Eye } from 'lucide-react';
+import { Users, Trash2, Plus, Loader2, Play, Eye, Sliders, CheckCircle, AlertCircle } from 'lucide-react';
import MarkdownRenderer from '@/components/common/MarkdownRenderer';
import { FINCEPT, extractAgentResponseText } from '../types';
import type { AgentConfigState } from '../hooks/useAgentConfig';
@@ -18,10 +18,15 @@ export const TeamsView: React.FC<TeamsViewProps> = ({ state }) => {
showMembersResponses, setShowMembersResponses,
teamLeaderIndex, setTeamLeaderIndex,
testQuery, setTestQuery, testResult,
- executing, isStreaming, streamingContent,
- addToTeam, removeFromTeam, runTeam, cancelStream,
+ executing, teamLog,
+ addToTeam, removeFromTeam, runTeam,
+ configuredLLMs,
+ teamProvider, setTeamProvider,
+ teamModelId, setTeamModelId,
} = state;
+ const activeLLM = configuredLLMs.find((l: any) => l.is_active) ?? configuredLLMs[0];
+
return (
<div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>
{/* Left - Team Members */}
@@ -55,7 +60,7 @@ export const TeamsView: React.FC<TeamsViewProps> = ({ state }) => {
{teamMembers.map((m, i) => <option key={i} value={i}>{m.name.toUpperCase()}</option>)}
</select>
<button
- onClick={() => setShowMembersResponses(prev => !prev)}
+ onClick={() => setShowMembersResponses((prev: boolean) => !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' }}
>
@@ -108,13 +113,13 @@ export const TeamsView: React.FC<TeamsViewProps> = ({ state }) => {
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minWidth: 0 }}>
<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' }}>
- AVAILABLE AGENTS ({discoveredAgents.filter(a => !teamMembers.find(m => m.id === a.id)).length})
+ AVAILABLE AGENTS ({discoveredAgents.filter((a: any) => !teamMembers.find((m: any) => m.id === a.id)).length})
</span>
</div>
<div style={{ flex: 1, overflow: 'auto', padding: '16px', display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '8px', alignContent: 'start' }}>
{discoveredAgents
- .filter(a => !teamMembers.find(m => m.id === a.id))
- .map(agent => (
+ .filter((a: any) => !teamMembers.find((m: any) => m.id === a.id))
+ .map((agent: any) => (
<div
key={agent.id}
onClick={() => addToTeam(agent)}
@@ -132,54 +137,131 @@ export const TeamsView: React.FC<TeamsViewProps> = ({ state }) => {
</div>
</div>
- {/* Right - Query Panel */}
- <div style={{ width: '300px', minWidth: '300px', backgroundColor: FINCEPT.PANEL_BG, borderLeft: `1px solid ${FINCEPT.BORDER}`, display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
- <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' }}>TEAM QUERY</span>
+ {/* Right - Config + Query + Log + Result */}
+ <div style={{ width: '380px', minWidth: '380px', backgroundColor: FINCEPT.PANEL_BG, borderLeft: `1px solid ${FINCEPT.BORDER}`, display: 'flex', flexDirection: 'column', flexShrink: 0, overflow: 'hidden' }}>
+
+ {/* Agent Configuration */}
+ <div style={{ borderBottom: `1px solid ${FINCEPT.BORDER}`, flexShrink: 0 }}>
+ <div style={{ padding: '10px 12px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}`, display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Sliders size={13} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>AGENT CONFIGURATION</span>
+ </div>
+ <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
+ {configuredLLMs.length > 0 ? (
+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.GREEN}40`, borderRadius: '2px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '8px' }}>
+ <CheckCircle size={10} style={{ color: FINCEPT.GREEN }} />
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GREEN }}>SELECT LLM PROVIDER</span>
+ </div>
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '5px' }}>
+ {configuredLLMs.map((llm: any, idx: number) => {
+ const hasKey = !!llm.api_key && llm.api_key.length > 0;
+ const isSelected = teamProvider === llm.provider && teamModelId === llm.model;
+ return (
+ <button key={idx}
+ onClick={() => { setTeamProvider(llm.provider); setTeamModelId(llm.model); }}
+ style={{ padding: '5px 9px', backgroundColor: isSelected ? FINCEPT.ORANGE : FINCEPT.BORDER, color: isSelected ? FINCEPT.DARK_BG : FINCEPT.WHITE, border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 600, cursor: 'pointer', opacity: hasKey ? 1 : 0.5, display: 'flex', alignItems: 'center', gap: '5px' }}
+ >
+ {llm.is_active && <span style={{ color: isSelected ? FINCEPT.DARK_BG : FINCEPT.GREEN }}>&#9679;</span>}
+ <span>{llm.provider.toUpperCase()}</span>
+ <span style={{ color: isSelected ? FINCEPT.DARK_BG : FINCEPT.GRAY }}>/ {llm.model}</span>
+ {!hasKey && <AlertCircle size={9} style={{ color: FINCEPT.RED }} />}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ ) : (
+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.RED}40`, borderRadius: '2px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' }}>
+ <AlertCircle size={10} style={{ color: FINCEPT.RED }} />
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.RED }}>NO LLM CONFIGURED</span>
+ </div>
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Go to Settings &#x2192; LLM Configuration to add API keys.</span>
+ </div>
+ )}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
+ <div>
+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '4px' }}>PROVIDER</label>
+ <div style={{ padding: '6px 8px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '10px', color: FINCEPT.CYAN }}>
+ {teamProvider || activeLLM?.provider || 'fincept'}
+ </div>
+ </div>
+ <div>
+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '4px' }}>MODEL</label>
+ <div style={{ padding: '6px 8px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '10px', color: FINCEPT.CYAN, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ {teamModelId || activeLLM?.model || 'fincept-llm'}
+ </div>
+ </div>
+ </div>
+ </div>
</div>
- <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
+
+ {/* Team Query */}
+ <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}`, flexShrink: 0 }}>
+ <span style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '8px' }}>TEAM QUERY</span>
<textarea
value={testQuery}
onChange={e => setTestQuery(e.target.value)}
- rows={6}
+ rows={3}
placeholder="Enter your query for the team..."
- style={{ width: '100%', padding: '10px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '11px', fontFamily: '"IBM Plex Mono", monospace', resize: 'none' }}
+ style={{ width: '100%', padding: '10px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '11px', fontFamily: '"IBM Plex Mono", monospace', resize: 'none', boxSizing: 'border-box' }}
/>
<button
onClick={runTeam}
disabled={executing || teamMembers.length === 0}
- style={{ width: '100%', padding: '10px', backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG, border: 'none', borderRadius: '2px', fontSize: '10px', fontWeight: 700, cursor: (executing || teamMembers.length === 0) ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', opacity: (executing || teamMembers.length === 0) ? 0.7 : 1 }}
+ style={{ width: '100%', marginTop: '8px', padding: '10px', backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG, border: 'none', borderRadius: '2px', fontSize: '10px', fontWeight: 700, cursor: (executing || teamMembers.length === 0) ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', opacity: (executing || teamMembers.length === 0) ? 0.7 : 1 }}
>
{executing ? <Loader2 size={12} className="animate-spin" /> : <Play size={12} />}
- RUN TEAM
+ {executing ? 'RUNNING TEAM...' : 'RUN TEAM'}
</button>
</div>
- <div style={{ flex: 1, borderTop: `1px solid ${FINCEPT.BORDER}`, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
- <div style={{ padding: '12px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ {/* Execution Log + Final Result */}
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+
+ {/* Log cards */}
+ {teamLog.length > 0 && (
+ <div style={{ flexShrink: 0, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div style={{ padding: '8px 12px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>EXECUTION LOG</span>
+ </div>
+ <div style={{ padding: '8px', display: 'flex', flexDirection: 'column', gap: '4px', maxHeight: '140px', overflowY: 'auto' }}>
+ {(teamLog as { label: string; text: string }[]).map((entry, i) => {
+ const isDone = entry.label === 'DONE';
+ const isError = entry.label === 'ERROR';
+ const isStatus = entry.label === 'STATUS';
+ const color = isDone ? FINCEPT.GREEN : isError ? FINCEPT.RED : isStatus ? FINCEPT.ORANGE : FINCEPT.CYAN;
+ return (
+ <div key={i} style={{ display: 'flex', gap: '8px', padding: '6px 8px', backgroundColor: FINCEPT.DARK_BG, borderLeft: `2px solid ${color}`, borderRadius: '2px', alignItems: 'flex-start' }}>
+ <span style={{ fontSize: '8px', fontWeight: 700, color, letterSpacing: '0.5px', whiteSpace: 'nowrap', paddingTop: '1px' }}>{entry.label}</span>
+ <span style={{ fontSize: '9px', color: FINCEPT.WHITE, opacity: 0.85, wordBreak: 'break-word' }}>{entry.text}</span>
+ {executing && i === teamLog.length - 1 && !isDone && !isError && (
+ <Loader2 size={10} className="animate-spin" style={{ color: FINCEPT.ORANGE, marginLeft: 'auto', flexShrink: 0 }} />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
+ {/* Final Result */}
+ <div style={{ padding: '8px 12px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}`, flexShrink: 0 }}>
<span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>RESULT</span>
</div>
<div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
- {isStreaming && streamingContent ? (
- <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 ? (
+ {testResult ? (
<MarkdownRenderer
content={extractAgentResponseText(
typeof testResult === 'string' ? testResult : (testResult.response || JSON.stringify(testResult, null, 2))
)}
/>
+ ) : executing ? (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '12px', color: FINCEPT.GRAY, fontSize: '10px' }}>
+ <Loader2 size={14} className="animate-spin" style={{ color: FINCEPT.ORANGE }} />
+ <span>Waiting for team response...</span>
+ </div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', color: FINCEPT.MUTED, fontSize: '10px', textAlign: 'center' }}>
<Users size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />
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 6adeccada..16ab2b906 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
@@ -32,7 +32,8 @@ import {
Layers,
AlertCircle,
Cpu,
- Server
+ Server,
+ Eye
} from 'lucide-react';
import { TabFooter } from '@/components/common/TabFooter';
import { useTerminalTheme } from '@/contexts/ThemeContext';
@@ -55,9 +56,10 @@ import { RollingRetrainingPanel } from './RollingRetrainingPanel';
import { AdvancedModelsPanel } from './AdvancedModelsPanel';
import { GluonTSPanel } from './GluonTSPanel';
import { GsQuantPanel } from './GsQuantPanel';
+import { PatternIntelligencePanel } from './PatternIntelligencePanel';
-type ViewMode = 'factor_discovery' | 'model_library' | 'backtesting' | 'live_signals' | 'functime' | 'fortitudo' | 'statsmodels' | 'cfa_quant' | 'deep_agent' | 'rl_trading' | 'online_learning' | 'hft' | 'meta_learning' | 'rolling_retraining' | 'advanced_models' | 'gluonts' | 'gs_quant';
+type ViewMode = 'factor_discovery' | 'model_library' | 'backtesting' | 'live_signals' | 'functime' | 'fortitudo' | 'statsmodels' | 'cfa_quant' | 'deep_agent' | 'rl_trading' | 'online_learning' | 'hft' | 'meta_learning' | 'rolling_retraining' | 'advanced_models' | 'gluonts' | 'gs_quant' | 'pattern_intelligence';
interface ModuleItem {
id: ViewMode;
@@ -214,7 +216,10 @@ export default function AIQuantLabTab() {
{ 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 },
{ id: 'gluonts', label: 'GluonTS', shortLabel: 'GLUON', icon: Brain, category: 'Analytics', color: moduleColors.magenta },
- { id: 'gs_quant', label: 'GS Quant', shortLabel: 'GS-Q', icon: Sigma, category: 'Analytics', color: moduleColors.purple }
+ { id: 'gs_quant', label: 'GS Quant', shortLabel: 'GS-Q', icon: Sigma, category: 'Analytics', color: moduleColors.purple },
+
+ // AI/ML
+ { id: 'pattern_intelligence', label: 'Pattern Intelligence', shortLabel: 'PATTERN', icon: Eye, category: 'AI/ML', color: moduleColors.cyan }
];
const activeModule = modules.find(m => m.id === state.activeView) || modules[0];
@@ -523,6 +528,7 @@ export default function AIQuantLabTab() {
{state.activeView === 'cfa_quant' && <CFAQuantPanel />}
{state.activeView === 'gluonts' && <GluonTSPanel />}
{state.activeView === 'gs_quant' && <GsQuantPanel />}
+ {state.activeView === 'pattern_intelligence' && <PatternIntelligencePanel />}
</div>
</div>
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 572ccfec0..fee131758 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
@@ -25,6 +25,7 @@ import {
RefreshCw
} from 'lucide-react';
import { rdAgentService, type DiscoveredFactor } from '@/services/aiQuantLab/rdAgentService';
+import { buildApiKeysMap } from '@/services/core/sqliteService';
import { showError, showWarning, showSuccess } from '@/utils/notifications';
import { useTerminalTheme } from '@/contexts/ThemeContext';
@@ -70,9 +71,15 @@ export function FactorDiscoveryPanel() {
setTaskStatus(null);
try {
+ const apiKeys = await buildApiKeysMap();
+ // Allow manual override from the input field for backward compat
+ if (apiKey.trim()) {
+ apiKeys['OPENAI_API_KEY'] = apiKey.trim();
+ apiKeys['openai'] = apiKey.trim();
+ }
const response = await rdAgentService.startFactorMining({
task_description: taskDescription,
- api_keys: { openai: apiKey },
+ api_keys: apiKeys,
target_market: targetMarket,
budget: budget
});
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/PatternIntelligencePanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/PatternIntelligencePanel.tsx
new file mode 100644
index 000000000..44760c4d6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/PatternIntelligencePanel.tsx
@@ -0,0 +1,1077 @@
+/**
+ * Pattern Intelligence Panel
+ * AI K-line pattern recognition powered by VisionQuant.
+ * Sub-panel within the AI Quant Lab tab.
+ */
+
+import React, { useState, useEffect, useCallback } from 'react';
+import {
+ Search, Eye, TrendingUp, TrendingDown, Minus, BarChart3,
+ AlertCircle, Loader2, Play, Settings2, Database,
+ Target, Zap, Shield,
+ ChevronDown, ChevronUp, RefreshCw, RotateCcw, Sliders
+} from 'lucide-react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
+import {
+ visionQuantService,
+ type SearchResult,
+ type Scorecard,
+ type BacktestResult,
+ type IndexStatus,
+ type PatternMatch,
+ type SearchConfig,
+ type ScoringConfig,
+ type BacktestConfig,
+ type SetupConfig,
+} from '@/services/visionQuantService';
+
+// ─── Default Configs ────────────────────────────────────────────────────────
+
+const DEFAULT_SEARCH_CONFIG: Required<SearchConfig> = {
+ isolation_days: 20,
+ dtw_window: 5,
+ w_dtw: 0.50,
+ w_corr: 0.30,
+ w_shape: 0.15,
+ w_visual: 0.05,
+ trend_bonus: 0.08,
+ faiss_multiplier: 200,
+ hq_dtw_threshold: 0.80,
+ tb_upper: 0.05,
+ tb_lower: 0.03,
+ tb_max_hold: 20,
+};
+
+const DEFAULT_SCORING_CONFIG: Required<ScoringConfig> = {
+ vision_breakpoints: [70, 55, 40],
+ pe_thresholds: [15, 25, 40, 60],
+ roe_thresholds: [20, 15, 10, 5],
+ ma_period: 60,
+ rsi_ranges: [30, 40, 60, 70],
+ macd_fast: 12,
+ macd_slow: 26,
+ macd_signal: 9,
+ ma_thresholds: [1.02, 1.00, 0.98],
+ buy_threshold: 7,
+ wait_threshold: 5,
+};
+
+const DEFAULT_BACKTEST_CONFIG: Required<BacktestConfig> = {
+ stop_loss: 0.03,
+ take_profit: 0.05,
+ max_hold: 20,
+ entry_rsi: 40,
+ exit_rsi: 70,
+ ma_period: 60,
+ macd_fast: 12,
+ macd_slow: 26,
+ macd_signal: 9,
+};
+
+const DEFAULT_SETUP_CONFIG: Required<SetupConfig> = {
+ batch_size: 32,
+ chart_style: 'international',
+ learning_rate: 0.001,
+};
+
+// ─── State ───────────────────────────────────────────────────────────────────
+
+interface PanelState {
+ symbol: string;
+ searchDate: string;
+ topK: number;
+ lookback: number;
+
+ isSearching: boolean;
+ isScoring: boolean;
+ isBacktesting: boolean;
+ isSettingUp: boolean;
+ indexStatus: IndexStatus | null;
+
+ searchResult: SearchResult | null;
+ scorecard: Scorecard | null;
+ backtestResult: BacktestResult | null;
+ error: string | null;
+
+ btSymbol: string;
+ btStart: string;
+ btEnd: string;
+ btCapital: string;
+
+ showSetup: boolean;
+ showBacktest: boolean;
+
+ // Setup index params
+ setupSymbols: string;
+ setupStart: string;
+ setupStride: number;
+ setupWindow: number;
+ setupEpochs: number;
+}
+
+const DEFAULT_STATE: PanelState = {
+ symbol: 'AAPL',
+ searchDate: '',
+ topK: 10,
+ lookback: 60,
+ isSearching: false,
+ isScoring: false,
+ isBacktesting: false,
+ isSettingUp: false,
+ indexStatus: null,
+ searchResult: null,
+ scorecard: null,
+ backtestResult: null,
+ error: null,
+ btSymbol: 'AAPL',
+ btStart: '2023-01-01',
+ btEnd: '2025-01-01',
+ btCapital: '100000',
+ showSetup: false,
+ showBacktest: false,
+ setupSymbols: '',
+ setupStart: '2020-01-01',
+ setupStride: 5,
+ setupWindow: 60,
+ setupEpochs: 30,
+};
+
+// ─── Helpers ─────────────────────────────────────────────────────────────────
+
+function ActionBadge({ action }: { action: string }) {
+ const bg = action === 'BUY' ? '#16a34a' : action === 'SELL' ? '#dc2626' : '#ca8a04';
+ return (
+ <span
+ className="px-2 py-0.5 rounded text-xs font-bold tracking-wider"
+ style={{ backgroundColor: bg, color: '#fff' }}
+ >
+ {action}
+ </span>
+ );
+}
+
+function ScoreBar({ label, score, max, color }: { label: string; score: number; max: number; color: string }) {
+ const pct = Math.min((score / max) * 100, 100);
+ return (
+ <div className="flex items-center gap-2 text-xs">
+ <span className="w-28 text-right opacity-70">{label}</span>
+ <div className="flex-1 h-2 rounded-full overflow-hidden" style={{ backgroundColor: 'rgba(255,255,255,0.1)' }}>
+ <div className="h-full rounded-full transition-all" style={{ width: `${pct}%`, backgroundColor: color }} />
+ </div>
+ <span className="w-12 text-right font-mono">{score.toFixed(1)}/{max}</span>
+ </div>
+ );
+}
+
+function TBLabelIcon({ label }: { label?: number }) {
+ if (label === 1) return <TrendingUp size={14} className="text-green-400" />;
+ if (label === -1) return <TrendingDown size={14} className="text-red-400" />;
+ return <Minus size={14} className="text-yellow-400" />;
+}
+
+function SectionHeader({
+ icon,
+ title,
+ expanded,
+ onToggle,
+ primaryColor,
+}: {
+ icon: React.ReactNode;
+ title: string;
+ expanded: boolean;
+ onToggle: () => void;
+ primaryColor: string;
+}) {
+ return (
+ <button
+ onClick={onToggle}
+ className="flex items-center gap-2 w-full text-left py-1"
+ style={{ color: primaryColor }}
+ >
+ {icon}
+ <span className="text-xs font-bold tracking-wider uppercase" style={{ letterSpacing: '0.08em' }}>{title}</span>
+ {expanded ? <ChevronUp size={14} className="ml-auto opacity-50" /> : <ChevronDown size={14} className="ml-auto opacity-50" />}
+ </button>
+ );
+}
+
+function ParamRow({ children }: { children: React.ReactNode }) {
+ return <div className="flex items-center gap-3 flex-wrap">{children}</div>;
+}
+
+function ParamLabel({ text }: { text: string }) {
+ return (
+ <span className="text-xs opacity-60 w-28 text-right flex-shrink-0" style={{ letterSpacing: '0.04em' }}>
+ {text}
+ </span>
+ );
+}
+
+function NumInput({
+ value,
+ onChange,
+ min,
+ max,
+ step,
+ width = 'w-20',
+ inputStyle,
+}: {
+ value: number;
+ onChange: (v: number) => void;
+ min?: number;
+ max?: number;
+ step?: number;
+ width?: string;
+ inputStyle: React.CSSProperties;
+}) {
+ return (
+ <input
+ type="number"
+ value={value}
+ onChange={e => onChange(parseFloat(e.target.value) || 0)}
+ min={min}
+ max={max}
+ step={step}
+ className={`px-2 py-1 rounded text-xs font-mono ${width}`}
+ style={inputStyle}
+ />
+ );
+}
+
+function SliderInput({
+ value,
+ onChange,
+ min,
+ max,
+ step,
+ label,
+ format,
+ primaryColor,
+}: {
+ value: number;
+ onChange: (v: number) => void;
+ min: number;
+ max: number;
+ step: number;
+ label: string;
+ format?: (v: number) => string;
+ primaryColor: string;
+}) {
+ return (
+ <div className="flex items-center gap-2 text-xs">
+ <span className="w-16 text-right opacity-60">{label}</span>
+ <input
+ type="range"
+ min={min}
+ max={max}
+ step={step}
+ value={value}
+ onChange={e => onChange(parseFloat(e.target.value))}
+ className="flex-1 h-1"
+ style={{ accentColor: primaryColor }}
+ />
+ <span className="w-14 text-right font-mono">{format ? format(value) : value}</span>
+ </div>
+ );
+}
+
+// ─── Main Component ──────────────────────────────────────────────────────────
+
+export function PatternIntelligencePanel() {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+ const [s, setS] = useState<PanelState>(DEFAULT_STATE);
+ const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set());
+ const [searchConfig, setSearchConfig] = useState<Required<SearchConfig>>({ ...DEFAULT_SEARCH_CONFIG });
+ const [scoringConfig, setScoringConfig] = useState<Required<ScoringConfig>>({ ...DEFAULT_SCORING_CONFIG });
+ const [backtestConfig, setBacktestConfig] = useState<Required<BacktestConfig>>({ ...DEFAULT_BACKTEST_CONFIG });
+ const [setupConfig, setSetupConfig] = useState<Required<SetupConfig>>({ ...DEFAULT_SETUP_CONFIG });
+
+ const update = useCallback((patch: Partial<PanelState>) => {
+ setS(prev => ({ ...prev, ...patch }));
+ }, []);
+
+ const toggleSection = useCallback((id: string) => {
+ setExpandedSections(prev => {
+ const next = new Set(prev);
+ next.has(id) ? next.delete(id) : next.add(id);
+ return next;
+ });
+ }, []);
+
+ // Check index status on mount
+ useEffect(() => {
+ checkStatus();
+ }, []);
+
+ async function checkStatus() {
+ try {
+ const status = await visionQuantService.getStatus();
+ update({ indexStatus: status, error: null });
+ if (!status.index_ready) {
+ update({ showSetup: true });
+ }
+ } catch (err: any) {
+ update({ error: `Status check failed: ${err.message}` });
+ }
+ }
+
+ async function handleSearch() {
+ if (!s.symbol.trim()) return;
+ update({ isSearching: true, error: null, searchResult: null, scorecard: null });
+ try {
+ const result = await visionQuantService.searchPatterns(
+ s.symbol.trim().toUpperCase(),
+ s.searchDate || undefined,
+ s.topK,
+ s.lookback,
+ searchConfig,
+ );
+ update({ searchResult: result, isSearching: false });
+
+ // Auto-score
+ if (result.win_rate_stats?.win_rate != null) {
+ update({ isScoring: true });
+ try {
+ const sc = await visionQuantService.getScore(
+ s.symbol.trim().toUpperCase(),
+ result.win_rate_stats.win_rate,
+ s.searchDate || undefined,
+ scoringConfig,
+ );
+ update({ scorecard: sc, isScoring: false });
+ } catch {
+ update({ isScoring: false });
+ }
+ }
+ } catch (err: any) {
+ update({ isSearching: false, error: err.message });
+ }
+ }
+
+ async function handleBacktest() {
+ if (!s.btSymbol.trim()) return;
+ update({ isBacktesting: true, backtestResult: null, error: null });
+ try {
+ const result = await visionQuantService.runBacktest(
+ s.btSymbol.trim().toUpperCase(),
+ s.btStart.replace(/-/g, ''),
+ s.btEnd.replace(/-/g, ''),
+ parseFloat(s.btCapital) || 100000,
+ backtestConfig,
+ );
+ update({ backtestResult: result, isBacktesting: false });
+ } catch (err: any) {
+ update({ isBacktesting: false, error: err.message });
+ }
+ }
+
+ async function handleSetupIndex() {
+ update({ isSettingUp: true, error: null });
+ try {
+ const symbols = s.setupSymbols.trim()
+ ? s.setupSymbols.split(',').map(t => t.trim()).filter(Boolean)
+ : undefined;
+ await visionQuantService.setupIndex(
+ symbols,
+ s.setupStart || undefined,
+ s.setupStride || undefined,
+ s.setupEpochs || undefined,
+ setupConfig,
+ );
+ await checkStatus();
+ update({ isSettingUp: false, showSetup: false });
+ } catch (err: any) {
+ update({ isSettingUp: false, error: `Setup failed: ${err.message}` });
+ }
+ }
+
+ function handleResetAll() {
+ setSearchConfig({ ...DEFAULT_SEARCH_CONFIG });
+ setScoringConfig({ ...DEFAULT_SCORING_CONFIG });
+ setBacktestConfig({ ...DEFAULT_BACKTEST_CONFIG });
+ setSetupConfig({ ...DEFAULT_SETUP_CONFIG });
+ update({
+ topK: 10,
+ lookback: 60,
+ setupStart: '2020-01-01',
+ setupStride: 5,
+ setupWindow: 60,
+ setupEpochs: 30,
+ setupSymbols: '',
+ });
+ }
+
+ // Re-ranking weight normalization
+ function handleWeightChange(key: keyof Pick<SearchConfig, 'w_dtw' | 'w_corr' | 'w_shape' | 'w_visual'>, value: number) {
+ const clamped = Math.max(0, Math.min(1, value));
+ const keys: Array<keyof Pick<SearchConfig, 'w_dtw' | 'w_corr' | 'w_shape' | 'w_visual'>> = ['w_dtw', 'w_corr', 'w_shape', 'w_visual'];
+ const others = keys.filter(k => k !== key);
+ const remaining = 1.0 - clamped;
+ const otherSum = others.reduce((sum, k) => sum + searchConfig[k], 0);
+
+ const updated = { ...searchConfig, [key]: clamped };
+ if (otherSum > 0) {
+ const scale = remaining / otherSum;
+ for (const k of others) {
+ updated[k] = Math.round(searchConfig[k] * scale * 1000) / 1000;
+ }
+ } else {
+ const each = remaining / others.length;
+ for (const k of others) {
+ updated[k] = Math.round(each * 1000) / 1000;
+ }
+ }
+ setSearchConfig(updated);
+ }
+
+ const borderColor = (colors as any).border || '#333';
+ const primaryColor = colors.primary || '#FF8800';
+
+ const inputStyle: React.CSSProperties = {
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${borderColor}`,
+ fontSize: fontSize.small,
+ fontFamily,
+ };
+
+ const cardStyle: React.CSSProperties = {
+ backgroundColor: colors.panel,
+ border: `1px solid ${borderColor}`,
+ };
+
+ const sectionBg: React.CSSProperties = {
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ border: `1px solid ${borderColor}`,
+ };
+
+ const weightSum = searchConfig.w_dtw + searchConfig.w_corr + searchConfig.w_shape + searchConfig.w_visual;
+
+ return (
+ <div className="flex flex-col h-full overflow-auto p-3 gap-3" style={{ color: colors.text, fontFamily }}>
+ {/* Error banner */}
+ {s.error && (
+ <div className="flex items-center gap-2 px-3 py-2 rounded text-xs" style={{ backgroundColor: 'rgba(220,38,38,0.15)', border: '1px solid rgba(220,38,38,0.3)' }}>
+ <AlertCircle size={14} className="text-red-400 flex-shrink-0" />
+ <span className="text-red-300">{s.error}</span>
+ <button onClick={() => update({ error: null })} className="ml-auto text-red-400 hover:text-red-300">&times;</button>
+ </div>
+ )}
+
+ {/* Setup banner */}
+ {s.showSetup && s.indexStatus && !s.indexStatus.index_ready && (
+ <div className="rounded p-3" style={cardStyle}>
+ <div className="flex items-center gap-2 mb-2">
+ <Database size={16} style={{ color: primaryColor }} />
+ <span className="text-sm font-semibold">First-Run Setup Required</span>
+ </div>
+ <p className="text-xs opacity-70 mb-3">
+ The pattern intelligence engine needs to build its knowledge base. This will download historical data
+ for 50 major US stocks, generate candlestick images, train the AI model, and build the search index.
+ This is a one-time operation.
+ </p>
+ <button
+ onClick={handleSetupIndex}
+ disabled={s.isSettingUp}
+ className="flex items-center gap-2 px-4 py-2 rounded text-xs font-semibold transition-all"
+ style={{
+ backgroundColor: s.isSettingUp ? 'rgba(255,255,255,0.1)' : primaryColor,
+ color: s.isSettingUp ? colors.text : colors.background,
+ opacity: s.isSettingUp ? 0.6 : 1,
+ }}
+ >
+ {s.isSettingUp ? <Loader2 size={14} className="animate-spin" /> : <Zap size={14} />}
+ {s.isSettingUp ? 'Building Index... (this may take 10-30 min)' : 'Build Index Now'}
+ </button>
+ </div>
+ )}
+
+ {/* ─── Search Section ─── */}
+ <div className="rounded p-3" style={cardStyle}>
+ <div className="flex items-center gap-2 mb-3">
+ <Eye size={16} style={{ color: primaryColor }} />
+ <span className="text-sm font-semibold">Pattern Search</span>
+ {s.indexStatus && (
+ <span className="ml-auto text-xs opacity-50">
+ {s.indexStatus.n_records.toLocaleString()} patterns indexed
+ </span>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2">
+ <input
+ type="text"
+ value={s.symbol}
+ onChange={e => update({ symbol: e.target.value.toUpperCase() })}
+ onKeyDown={e => e.key === 'Enter' && handleSearch()}
+ placeholder="Symbol (e.g. AAPL)"
+ className="px-2 py-1.5 rounded text-xs w-32"
+ style={inputStyle}
+ />
+ <input
+ type="text"
+ value={s.searchDate}
+ onChange={e => update({ searchDate: e.target.value })}
+ onKeyDown={e => e.key === 'Enter' && handleSearch()}
+ placeholder="Date (optional, YYYYMMDD)"
+ className="px-2 py-1.5 rounded text-xs w-48"
+ style={inputStyle}
+ />
+ <NumInput value={s.topK} onChange={v => update({ topK: Math.max(1, Math.round(v)) })} min={1} max={50} step={1} width="w-16" inputStyle={inputStyle} />
+ <span className="text-xs opacity-40">Top K</span>
+ <NumInput value={s.lookback} onChange={v => update({ lookback: Math.max(10, Math.round(v)) })} min={10} max={200} step={5} width="w-16" inputStyle={inputStyle} />
+ <span className="text-xs opacity-40">Bars</span>
+ <button
+ onClick={handleSearch}
+ disabled={s.isSearching || !s.symbol.trim()}
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-semibold transition-all"
+ style={{
+ backgroundColor: s.isSearching ? 'rgba(255,255,255,0.1)' : primaryColor,
+ color: s.isSearching ? colors.text : colors.background,
+ }}
+ >
+ {s.isSearching ? <Loader2 size={12} className="animate-spin" /> : <Search size={12} />}
+ {s.isSearching ? 'Searching...' : 'Search'}
+ </button>
+ <button
+ onClick={checkStatus}
+ className="p-1.5 rounded opacity-50 hover:opacity-100 transition-opacity"
+ title="Refresh status"
+ >
+ <RefreshCw size={12} />
+ </button>
+ </div>
+ </div>
+
+ {/* ═══════════════════════════════════════════════════════════════════ */}
+ {/* ADVANCED SETTINGS SECTIONS */}
+ {/* ═══════════════════════════════════════════════════════════════════ */}
+
+ {/* ─── Search Parameters ─── */}
+ <div className="rounded p-3" style={sectionBg}>
+ <SectionHeader
+ icon={<Settings2 size={14} />}
+ title="Search Parameters"
+ expanded={expandedSections.has('search')}
+ onToggle={() => toggleSection('search')}
+ primaryColor={primaryColor}
+ />
+ {expandedSections.has('search') && (
+ <div className="mt-3 flex flex-col gap-3">
+ <ParamRow>
+ <ParamLabel text="Isolation Days" />
+ <NumInput value={searchConfig.isolation_days} onChange={v => setSearchConfig(p => ({ ...p, isolation_days: Math.max(1, Math.round(v)) }))} min={1} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="DTW Window" />
+ <NumInput value={searchConfig.dtw_window} onChange={v => setSearchConfig(p => ({ ...p, dtw_window: Math.max(1, Math.round(v)) }))} min={1} max={50} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="FAISS Mult" />
+ <NumInput value={searchConfig.faiss_multiplier} onChange={v => setSearchConfig(p => ({ ...p, faiss_multiplier: Math.max(10, Math.round(v)) }))} min={10} max={1000} step={10} inputStyle={inputStyle} />
+ </ParamRow>
+ <ParamRow>
+ <ParamLabel text="HQ Threshold" />
+ <NumInput value={searchConfig.hq_dtw_threshold} onChange={v => setSearchConfig(p => ({ ...p, hq_dtw_threshold: Math.max(0, Math.min(1, v)) }))} min={0} max={1} step={0.05} inputStyle={inputStyle} />
+ <ParamLabel text="Trend Bonus" />
+ <NumInput value={searchConfig.trend_bonus} onChange={v => setSearchConfig(p => ({ ...p, trend_bonus: Math.max(0, Math.min(0.5, v)) }))} min={0} max={0.5} step={0.01} inputStyle={inputStyle} />
+ </ParamRow>
+
+ <div className="border-t pt-2 mt-1" style={{ borderColor }}>
+ <div className="flex items-center gap-2 mb-2">
+ <span className="text-xs font-semibold opacity-70 uppercase tracking-wider">Re-Ranking Weights</span>
+ <span className={`text-xs font-mono ml-auto ${Math.abs(weightSum - 1.0) < 0.01 ? 'text-green-400' : 'text-red-400'}`}>
+ Sum: {weightSum.toFixed(3)}
+ </span>
+ </div>
+ <div className="flex flex-col gap-1">
+ <SliderInput label="DTW" value={searchConfig.w_dtw} onChange={v => handleWeightChange('w_dtw', v)} min={0} max={1} step={0.01} format={v => v.toFixed(2)} primaryColor={primaryColor} />
+ <SliderInput label="Corr" value={searchConfig.w_corr} onChange={v => handleWeightChange('w_corr', v)} min={0} max={1} step={0.01} format={v => v.toFixed(2)} primaryColor={primaryColor} />
+ <SliderInput label="Shape" value={searchConfig.w_shape} onChange={v => handleWeightChange('w_shape', v)} min={0} max={1} step={0.01} format={v => v.toFixed(2)} primaryColor={primaryColor} />
+ <SliderInput label="Visual" value={searchConfig.w_visual} onChange={v => handleWeightChange('w_visual', v)} min={0} max={1} step={0.01} format={v => v.toFixed(2)} primaryColor={primaryColor} />
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* ─── Triple Barrier ─── */}
+ <div className="rounded p-3" style={sectionBg}>
+ <SectionHeader
+ icon={<Target size={14} />}
+ title="Triple Barrier"
+ expanded={expandedSections.has('barrier')}
+ onToggle={() => toggleSection('barrier')}
+ primaryColor={primaryColor}
+ />
+ {expandedSections.has('barrier') && (
+ <div className="mt-3 flex flex-col gap-2">
+ <SliderInput label="Take Profit" value={searchConfig.tb_upper} onChange={v => setSearchConfig(p => ({ ...p, tb_upper: v }))} min={0.01} max={0.20} step={0.005} format={v => `${(v * 100).toFixed(1)}%`} primaryColor="#16a34a" />
+ <SliderInput label="Stop Loss" value={searchConfig.tb_lower} onChange={v => setSearchConfig(p => ({ ...p, tb_lower: v }))} min={0.01} max={0.15} step={0.005} format={v => `${(v * 100).toFixed(1)}%`} primaryColor="#dc2626" />
+ <ParamRow>
+ <ParamLabel text="Max Hold Days" />
+ <NumInput value={searchConfig.tb_max_hold} onChange={v => setSearchConfig(p => ({ ...p, tb_max_hold: Math.max(1, Math.round(v)) }))} min={1} max={60} step={1} inputStyle={inputStyle} />
+ </ParamRow>
+ </div>
+ )}
+ </div>
+
+ {/* ─── Scoring Thresholds ─── */}
+ <div className="rounded p-3" style={sectionBg}>
+ <SectionHeader
+ icon={<Shield size={14} />}
+ title="Scoring Thresholds"
+ expanded={expandedSections.has('scoring')}
+ onToggle={() => toggleSection('scoring')}
+ primaryColor={primaryColor}
+ />
+ {expandedSections.has('scoring') && (
+ <div className="mt-3 flex flex-col gap-3">
+ {/* Vision Score */}
+ <div>
+ <span className="text-xs font-semibold opacity-70 mb-1 block">VISION SCORE (0-3)</span>
+ <ParamRow>
+ <ParamLabel text="Strong >=" />
+ <NumInput value={scoringConfig.vision_breakpoints[0]} onChange={v => setScoringConfig(p => ({ ...p, vision_breakpoints: [Math.round(v), p.vision_breakpoints[1], p.vision_breakpoints[2]] }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Moderate >=" />
+ <NumInput value={scoringConfig.vision_breakpoints[1]} onChange={v => setScoringConfig(p => ({ ...p, vision_breakpoints: [p.vision_breakpoints[0], Math.round(v), p.vision_breakpoints[2]] }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Weak >=" />
+ <NumInput value={scoringConfig.vision_breakpoints[2]} onChange={v => setScoringConfig(p => ({ ...p, vision_breakpoints: [p.vision_breakpoints[0], p.vision_breakpoints[1], Math.round(v)] }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ </ParamRow>
+ </div>
+
+ {/* Fundamental */}
+ <div className="border-t pt-2" style={{ borderColor }}>
+ <span className="text-xs font-semibold opacity-70 mb-1 block">FUNDAMENTAL (0-4) - P/E Thresholds</span>
+ <ParamRow>
+ <ParamLabel text="Excellent <" />
+ <NumInput value={scoringConfig.pe_thresholds[0]} onChange={v => setScoringConfig(p => ({ ...p, pe_thresholds: [Math.round(v), p.pe_thresholds[1], p.pe_thresholds[2], p.pe_thresholds[3]] }))} min={1} max={200} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Good <" />
+ <NumInput value={scoringConfig.pe_thresholds[1]} onChange={v => setScoringConfig(p => ({ ...p, pe_thresholds: [p.pe_thresholds[0], Math.round(v), p.pe_thresholds[2], p.pe_thresholds[3]] }))} min={1} max={200} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Fair <" />
+ <NumInput value={scoringConfig.pe_thresholds[2]} onChange={v => setScoringConfig(p => ({ ...p, pe_thresholds: [p.pe_thresholds[0], p.pe_thresholds[1], Math.round(v), p.pe_thresholds[3]] }))} min={1} max={200} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Poor <" />
+ <NumInput value={scoringConfig.pe_thresholds[3]} onChange={v => setScoringConfig(p => ({ ...p, pe_thresholds: [p.pe_thresholds[0], p.pe_thresholds[1], p.pe_thresholds[2], Math.round(v)] }))} min={1} max={200} step={1} inputStyle={inputStyle} />
+ </ParamRow>
+ </div>
+
+ <div>
+ <span className="text-xs font-semibold opacity-70 mb-1 block">ROE Thresholds (%)</span>
+ <ParamRow>
+ <ParamLabel text="Excellent >=" />
+ <NumInput value={scoringConfig.roe_thresholds[0]} onChange={v => setScoringConfig(p => ({ ...p, roe_thresholds: [Math.round(v), p.roe_thresholds[1], p.roe_thresholds[2], p.roe_thresholds[3]] }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Good >=" />
+ <NumInput value={scoringConfig.roe_thresholds[1]} onChange={v => setScoringConfig(p => ({ ...p, roe_thresholds: [p.roe_thresholds[0], Math.round(v), p.roe_thresholds[2], p.roe_thresholds[3]] }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Fair >=" />
+ <NumInput value={scoringConfig.roe_thresholds[2]} onChange={v => setScoringConfig(p => ({ ...p, roe_thresholds: [p.roe_thresholds[0], p.roe_thresholds[1], Math.round(v), p.roe_thresholds[3]] }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Weak >=" />
+ <NumInput value={scoringConfig.roe_thresholds[3]} onChange={v => setScoringConfig(p => ({ ...p, roe_thresholds: [p.roe_thresholds[0], p.roe_thresholds[1], p.roe_thresholds[2], Math.round(v)] }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ </ParamRow>
+ </div>
+
+ {/* Technical */}
+ <div className="border-t pt-2" style={{ borderColor }}>
+ <span className="text-xs font-semibold opacity-70 mb-1 block">TECHNICAL (0-3)</span>
+ <ParamRow>
+ <ParamLabel text="MA Period" />
+ <NumInput value={scoringConfig.ma_period} onChange={v => setScoringConfig(p => ({ ...p, ma_period: Math.max(5, Math.round(v)) }))} min={5} max={200} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="MACD Fast" />
+ <NumInput value={scoringConfig.macd_fast} onChange={v => setScoringConfig(p => ({ ...p, macd_fast: Math.max(2, Math.round(v)) }))} min={2} max={50} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Slow" />
+ <NumInput value={scoringConfig.macd_slow} onChange={v => setScoringConfig(p => ({ ...p, macd_slow: Math.max(2, Math.round(v)) }))} min={2} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Signal" />
+ <NumInput value={scoringConfig.macd_signal} onChange={v => setScoringConfig(p => ({ ...p, macd_signal: Math.max(2, Math.round(v)) }))} min={2} max={50} step={1} inputStyle={inputStyle} />
+ </ParamRow>
+ <div className="mt-2">
+ <span className="text-xs opacity-50 block mb-1">RSI Ranges</span>
+ <ParamRow>
+ <ParamLabel text="Oversold <" />
+ <NumInput value={scoringConfig.rsi_ranges[0]} onChange={v => setScoringConfig(p => ({ ...p, rsi_ranges: [Math.round(v), p.rsi_ranges[1], p.rsi_ranges[2], p.rsi_ranges[3]] }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Low <" />
+ <NumInput value={scoringConfig.rsi_ranges[1]} onChange={v => setScoringConfig(p => ({ ...p, rsi_ranges: [p.rsi_ranges[0], Math.round(v), p.rsi_ranges[2], p.rsi_ranges[3]] }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="High >" />
+ <NumInput value={scoringConfig.rsi_ranges[2]} onChange={v => setScoringConfig(p => ({ ...p, rsi_ranges: [p.rsi_ranges[0], p.rsi_ranges[1], Math.round(v), p.rsi_ranges[3]] }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Overbought >" />
+ <NumInput value={scoringConfig.rsi_ranges[3]} onChange={v => setScoringConfig(p => ({ ...p, rsi_ranges: [p.rsi_ranges[0], p.rsi_ranges[1], p.rsi_ranges[2], Math.round(v)] }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ </ParamRow>
+ </div>
+ <div className="mt-2">
+ <span className="text-xs opacity-50 block mb-1">MA Thresholds (price/MA ratio)</span>
+ <ParamRow>
+ <ParamLabel text="Bullish >" />
+ <NumInput value={scoringConfig.ma_thresholds[0]} onChange={v => setScoringConfig(p => ({ ...p, ma_thresholds: [v, p.ma_thresholds[1], p.ma_thresholds[2]] }))} min={0.9} max={1.2} step={0.005} inputStyle={inputStyle} />
+ <ParamLabel text="Neutral >" />
+ <NumInput value={scoringConfig.ma_thresholds[1]} onChange={v => setScoringConfig(p => ({ ...p, ma_thresholds: [p.ma_thresholds[0], v, p.ma_thresholds[2]] }))} min={0.9} max={1.1} step={0.005} inputStyle={inputStyle} />
+ <ParamLabel text="Bearish >" />
+ <NumInput value={scoringConfig.ma_thresholds[2]} onChange={v => setScoringConfig(p => ({ ...p, ma_thresholds: [p.ma_thresholds[0], p.ma_thresholds[1], v] }))} min={0.8} max={1.1} step={0.005} inputStyle={inputStyle} />
+ </ParamRow>
+ </div>
+ </div>
+
+ {/* Action thresholds */}
+ <div className="border-t pt-2" style={{ borderColor }}>
+ <span className="text-xs font-semibold opacity-70 mb-1 block">ACTION THRESHOLDS</span>
+ <ParamRow>
+ <ParamLabel text="BUY >=" />
+ <NumInput value={scoringConfig.buy_threshold} onChange={v => setScoringConfig(p => ({ ...p, buy_threshold: Math.max(0, Math.min(10, v)) }))} min={0} max={10} step={0.5} inputStyle={inputStyle} />
+ <ParamLabel text="WAIT >=" />
+ <NumInput value={scoringConfig.wait_threshold} onChange={v => setScoringConfig(p => ({ ...p, wait_threshold: Math.max(0, Math.min(10, v)) }))} min={0} max={10} step={0.5} inputStyle={inputStyle} />
+ <span className="text-xs opacity-40">SELL &lt; {scoringConfig.wait_threshold}</span>
+ </ParamRow>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* ─── Backtest Strategy ─── */}
+ <div className="rounded p-3" style={sectionBg}>
+ <SectionHeader
+ icon={<Sliders size={14} />}
+ title="Backtest Strategy"
+ expanded={expandedSections.has('btstrategy')}
+ onToggle={() => toggleSection('btstrategy')}
+ primaryColor={primaryColor}
+ />
+ {expandedSections.has('btstrategy') && (
+ <div className="mt-3 flex flex-col gap-2">
+ <SliderInput label="Stop Loss" value={backtestConfig.stop_loss} onChange={v => setBacktestConfig(p => ({ ...p, stop_loss: v }))} min={0.005} max={0.15} step={0.005} format={v => `${(v * 100).toFixed(1)}%`} primaryColor="#dc2626" />
+ <SliderInput label="Take Profit" value={backtestConfig.take_profit} onChange={v => setBacktestConfig(p => ({ ...p, take_profit: v }))} min={0.01} max={0.30} step={0.005} format={v => `${(v * 100).toFixed(1)}%`} primaryColor="#16a34a" />
+ <ParamRow>
+ <ParamLabel text="Max Hold" />
+ <NumInput value={backtestConfig.max_hold} onChange={v => setBacktestConfig(p => ({ ...p, max_hold: Math.max(1, Math.round(v)) }))} min={1} max={120} step={1} inputStyle={inputStyle} />
+ <span className="text-xs opacity-40">days</span>
+ <ParamLabel text="Entry RSI <" />
+ <NumInput value={backtestConfig.entry_rsi} onChange={v => setBacktestConfig(p => ({ ...p, entry_rsi: Math.max(0, Math.min(100, v)) }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Exit RSI >" />
+ <NumInput value={backtestConfig.exit_rsi} onChange={v => setBacktestConfig(p => ({ ...p, exit_rsi: Math.max(0, Math.min(100, v)) }))} min={0} max={100} step={1} inputStyle={inputStyle} />
+ </ParamRow>
+ <ParamRow>
+ <ParamLabel text="MA Period" />
+ <NumInput value={backtestConfig.ma_period} onChange={v => setBacktestConfig(p => ({ ...p, ma_period: Math.max(5, Math.round(v)) }))} min={5} max={200} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="MACD Fast" />
+ <NumInput value={backtestConfig.macd_fast} onChange={v => setBacktestConfig(p => ({ ...p, macd_fast: Math.max(2, Math.round(v)) }))} min={2} max={50} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Slow" />
+ <NumInput value={backtestConfig.macd_slow} onChange={v => setBacktestConfig(p => ({ ...p, macd_slow: Math.max(2, Math.round(v)) }))} min={2} max={100} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Signal" />
+ <NumInput value={backtestConfig.macd_signal} onChange={v => setBacktestConfig(p => ({ ...p, macd_signal: Math.max(2, Math.round(v)) }))} min={2} max={50} step={1} inputStyle={inputStyle} />
+ </ParamRow>
+ </div>
+ )}
+ </div>
+
+ {/* ─── Index Setup ─── */}
+ <div className="rounded p-3" style={sectionBg}>
+ <SectionHeader
+ icon={<Database size={14} />}
+ title="Index Setup"
+ expanded={expandedSections.has('setup')}
+ onToggle={() => toggleSection('setup')}
+ primaryColor={primaryColor}
+ />
+ {expandedSections.has('setup') && (
+ <div className="mt-3 flex flex-col gap-2">
+ <ParamRow>
+ <ParamLabel text="Start Date" />
+ <input type="text" value={s.setupStart} onChange={e => update({ setupStart: e.target.value })} placeholder="YYYY-MM-DD" className="px-2 py-1 rounded text-xs w-28" style={inputStyle} />
+ <ParamLabel text="Stride" />
+ <NumInput value={s.setupStride} onChange={v => update({ setupStride: Math.max(1, Math.round(v)) })} min={1} max={30} step={1} inputStyle={inputStyle} />
+ <span className="text-xs opacity-40">days</span>
+ <ParamLabel text="Window" />
+ <NumInput value={s.setupWindow} onChange={v => update({ setupWindow: Math.max(10, Math.round(v)) })} min={10} max={200} step={5} inputStyle={inputStyle} />
+ <span className="text-xs opacity-40">bars</span>
+ </ParamRow>
+ <ParamRow>
+ <ParamLabel text="Epochs" />
+ <NumInput value={s.setupEpochs} onChange={v => update({ setupEpochs: Math.max(1, Math.round(v)) })} min={1} max={200} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Batch Size" />
+ <NumInput value={setupConfig.batch_size} onChange={v => setSetupConfig(p => ({ ...p, batch_size: Math.max(1, Math.round(v)) }))} min={1} max={256} step={1} inputStyle={inputStyle} />
+ <ParamLabel text="Learn Rate" />
+ <NumInput value={setupConfig.learning_rate} onChange={v => setSetupConfig(p => ({ ...p, learning_rate: Math.max(0.00001, v) }))} min={0.00001} max={0.1} step={0.0001} width="w-24" inputStyle={inputStyle} />
+ </ParamRow>
+ <ParamRow>
+ <ParamLabel text="Chart Style" />
+ <select
+ value={setupConfig.chart_style}
+ onChange={e => setSetupConfig(p => ({ ...p, chart_style: e.target.value as 'international' | 'chinese' }))}
+ className="px-2 py-1 rounded text-xs"
+ style={inputStyle}
+ >
+ <option value="international">International (Green=Up)</option>
+ <option value="chinese">Chinese (Red=Up)</option>
+ </select>
+ </ParamRow>
+ <div className="mt-1">
+ <ParamLabel text="Symbols" />
+ <textarea
+ value={s.setupSymbols}
+ onChange={e => update({ setupSymbols: e.target.value })}
+ placeholder="Leave empty for default 50 S&P 500 stocks. Or enter comma-separated: AAPL,MSFT,GOOGL"
+ className="w-full mt-1 px-2 py-1.5 rounded text-xs font-mono"
+ style={{ ...inputStyle, minHeight: '40px', resize: 'vertical' }}
+ rows={2}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* ─── Model Info (read-only) ─── */}
+ <div className="rounded p-3" style={sectionBg}>
+ <SectionHeader
+ icon={<Eye size={14} />}
+ title="Model Info"
+ expanded={expandedSections.has('model')}
+ onToggle={() => toggleSection('model')}
+ primaryColor={primaryColor}
+ />
+ {expandedSections.has('model') && (
+ <div className="mt-3 grid grid-cols-4 gap-2 text-xs opacity-60">
+ <span>Latent Dim: <span className="font-mono">1024</span></span>
+ <span>Attention Heads: <span className="font-mono">8</span></span>
+ <span>Image Size: <span className="font-mono">224x224</span></span>
+ <span>Feature Dim: <span className="font-mono">256</span></span>
+ </div>
+ )}
+ </div>
+
+ {/* ─── Reset All ─── */}
+ <button
+ onClick={handleResetAll}
+ className="flex items-center gap-2 px-3 py-1.5 rounded text-xs opacity-50 hover:opacity-100 transition-opacity self-start"
+ style={{ border: `1px solid ${borderColor}` }}
+ >
+ <RotateCcw size={12} />
+ Reset All to Defaults
+ </button>
+
+ {/* ═══════════════════════════════════════════════════════════════════ */}
+ {/* RESULTS */}
+ {/* ═══════════════════════════════════════════════════════════════════ */}
+
+ {/* ─── Results ─── */}
+ {s.searchResult && (
+ <>
+ {/* Win Rate Stats */}
+ <div className="rounded p-3" style={cardStyle}>
+ <div className="flex items-center gap-2 mb-2">
+ <Target size={16} style={{ color: primaryColor }} />
+ <span className="text-sm font-semibold">Win Rate Statistics</span>
+ <span className="ml-auto text-xs opacity-50">
+ Triple Barrier: +{(searchConfig.tb_upper * 100).toFixed(1)}% / -{(searchConfig.tb_lower * 100).toFixed(1)}% / {searchConfig.tb_max_hold}d
+ </span>
+ </div>
+ <div className="grid grid-cols-4 gap-3 text-center">
+ <StatBox
+ label="Win Rate"
+ value={`${s.searchResult.win_rate_stats.win_rate}%`}
+ color={s.searchResult.win_rate_stats.win_rate >= 55 ? '#16a34a' : s.searchResult.win_rate_stats.win_rate >= 45 ? '#ca8a04' : '#dc2626'}
+ />
+ <StatBox label="Avg Return" value={`${s.searchResult.win_rate_stats.avg_return_pct > 0 ? '+' : ''}${s.searchResult.win_rate_stats.avg_return_pct}%`}
+ color={s.searchResult.win_rate_stats.avg_return_pct >= 0 ? '#16a34a' : '#dc2626'} />
+ <StatBox label="Avg Hold" value={`${s.searchResult.win_rate_stats.avg_holding_days}d`} color={primaryColor} />
+ <StatBox label="W/L Ratio" value={`${s.searchResult.win_rate_stats.win_loss_ratio}`} color={primaryColor} />
+ </div>
+ <div className="flex items-center gap-4 mt-2 text-xs opacity-70 justify-center">
+ <span className="flex items-center gap-1"><TrendingUp size={12} className="text-green-400" /> Bullish: {s.searchResult.win_rate_stats.bullish}</span>
+ <span className="flex items-center gap-1"><Minus size={12} className="text-yellow-400" /> Neutral: {s.searchResult.win_rate_stats.neutral}</span>
+ <span className="flex items-center gap-1"><TrendingDown size={12} className="text-red-400" /> Bearish: {s.searchResult.win_rate_stats.bearish}</span>
+ </div>
+ </div>
+
+ {/* Scorecard */}
+ {s.isScoring && (
+ <div className="rounded p-3 flex items-center gap-2 text-xs" style={cardStyle}>
+ <Loader2 size={14} className="animate-spin" style={{ color: primaryColor }} />
+ <span>Computing multi-factor score...</span>
+ </div>
+ )}
+ {s.scorecard && (
+ <div className="rounded p-3" style={cardStyle}>
+ <div className="flex items-center gap-2 mb-3">
+ <Shield size={16} style={{ color: primaryColor }} />
+ <span className="text-sm font-semibold">Scorecard</span>
+ <ActionBadge action={s.scorecard.action} />
+ <span className="ml-auto text-lg font-bold font-mono" style={{ color: primaryColor }}>
+ {s.scorecard.total_score.toFixed(1)}<span className="text-xs opacity-50">/10</span>
+ </span>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <ScoreBar label="Vision (V)" score={s.scorecard.vision.score} max={3} color="#a78bfa" />
+ <ScoreBar label="Fundamental (F)" score={s.scorecard.fundamental.score} max={4} color="#60a5fa" />
+ <ScoreBar label="Technical (Q)" score={s.scorecard.technical.score} max={3} color="#34d399" />
+ </div>
+ <div className="flex gap-4 mt-2 text-xs opacity-60">
+ {s.scorecard.fundamental.pe != null && <span>P/E: {s.scorecard.fundamental.pe}</span>}
+ {s.scorecard.fundamental.roe != null && <span>ROE: {s.scorecard.fundamental.roe}%</span>}
+ {s.scorecard.technical.rsi != null && <span>RSI: {s.scorecard.technical.rsi}</span>}
+ </div>
+ </div>
+ )}
+
+ {/* Match Gallery */}
+ <div className="rounded p-3" style={cardStyle}>
+ <div className="flex items-center gap-2 mb-2">
+ <Eye size={16} style={{ color: primaryColor }} />
+ <span className="text-sm font-semibold">Top Pattern Matches</span>
+ <span className="ml-auto text-xs opacity-50">{s.searchResult.matches.length} matches</span>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-2">
+ {s.searchResult.matches.map((m, i) => (
+ <MatchCard key={`${m.symbol}-${m.date}-${i}`} match={m} rank={i + 1} colors={colors} />
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* ─── Backtest Section ─── */}
+ <div className="rounded p-3" style={cardStyle}>
+ <button
+ onClick={() => update({ showBacktest: !s.showBacktest })}
+ className="flex items-center gap-2 w-full text-left"
+ >
+ <BarChart3 size={16} style={{ color: primaryColor }} />
+ <span className="text-sm font-semibold">Strategy Backtest</span>
+ {s.showBacktest ? <ChevronUp size={14} className="ml-auto opacity-50" /> : <ChevronDown size={14} className="ml-auto opacity-50" />}
+ </button>
+
+ {s.showBacktest && (
+ <div className="mt-3">
+ <div className="flex items-center gap-2 flex-wrap">
+ <input type="text" value={s.btSymbol} onChange={e => update({ btSymbol: e.target.value.toUpperCase() })} placeholder="Symbol" className="px-2 py-1.5 rounded text-xs w-24" style={inputStyle} />
+ <input type="text" value={s.btStart} onChange={e => update({ btStart: e.target.value })} placeholder="Start (YYYY-MM-DD)" className="px-2 py-1.5 rounded text-xs w-32" style={inputStyle} />
+ <input type="text" value={s.btEnd} onChange={e => update({ btEnd: e.target.value })} placeholder="End (YYYY-MM-DD)" className="px-2 py-1.5 rounded text-xs w-32" style={inputStyle} />
+ <input type="text" value={s.btCapital} onChange={e => update({ btCapital: e.target.value })} placeholder="Capital" className="px-2 py-1.5 rounded text-xs w-24" style={inputStyle} />
+ <button
+ onClick={handleBacktest}
+ disabled={s.isBacktesting}
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-semibold transition-all"
+ style={{
+ backgroundColor: s.isBacktesting ? 'rgba(255,255,255,0.1)' : primaryColor,
+ color: s.isBacktesting ? colors.text : colors.background,
+ }}
+ >
+ {s.isBacktesting ? <Loader2 size={12} className="animate-spin" /> : <Play size={12} />}
+ {s.isBacktesting ? 'Running...' : 'Run Backtest'}
+ </button>
+ </div>
+
+ {s.backtestResult && (
+ <div className="mt-3">
+ <div className="grid grid-cols-4 gap-2 text-center mb-3">
+ <StatBox
+ label="Strategy Return"
+ value={`${s.backtestResult.return_pct > 0 ? '+' : ''}${s.backtestResult.return_pct}%`}
+ color={s.backtestResult.return_pct >= 0 ? '#16a34a' : '#dc2626'}
+ />
+ <StatBox
+ label="Buy & Hold"
+ value={`${s.backtestResult.buy_hold_return_pct > 0 ? '+' : ''}${s.backtestResult.buy_hold_return_pct}%`}
+ color={s.backtestResult.buy_hold_return_pct >= 0 ? '#16a34a' : '#dc2626'}
+ />
+ <StatBox label="Sharpe" value={`${s.backtestResult.sharpe_ratio}`} color={primaryColor} />
+ <StatBox label="Max DD" value={`${s.backtestResult.max_drawdown_pct}%`} color="#dc2626" />
+ </div>
+ <div className="flex gap-4 text-xs opacity-60 justify-center">
+ <span>Trades: {s.backtestResult.total_trades}</span>
+ <span>Win Rate: {s.backtestResult.win_rate}%</span>
+ <span>Avg Hold: {s.backtestResult.avg_hold_days}d</span>
+ </div>
+
+ {/* Trade list */}
+ {s.backtestResult.trades.length > 0 && (
+ <div className="mt-3 max-h-40 overflow-auto">
+ <table className="w-full text-xs">
+ <thead>
+ <tr className="opacity-50 border-b" style={{ borderColor }}>
+ <th className="text-left py-1">Entry</th>
+ <th className="text-left py-1">Exit</th>
+ <th className="text-right py-1">Return</th>
+ <th className="text-right py-1">Days</th>
+ <th className="text-left py-1">Reason</th>
+ </tr>
+ </thead>
+ <tbody>
+ {s.backtestResult.trades.map((t, i) => (
+ <tr key={i} className="border-b" style={{ borderColor: 'rgba(255,255,255,0.05)' }}>
+ <td className="py-1">{t.entry_date}</td>
+ <td className="py-1">{t.exit_date}</td>
+ <td className="py-1 text-right font-mono" style={{ color: t.return_pct >= 0 ? '#16a34a' : '#dc2626' }}>
+ {t.return_pct > 0 ? '+' : ''}{t.return_pct}%
+ </td>
+ <td className="py-1 text-right">{t.hold_days}</td>
+ <td className="py-1 opacity-50">{t.exit_reason}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// ─── Sub-components ──────────────────────────────────────────────────────────
+
+function StatBox({ label, value, color }: { label: string; value: string; color: string }) {
+ return (
+ <div className="flex flex-col items-center gap-0.5 py-1.5 px-2 rounded" style={{ backgroundColor: 'rgba(255,255,255,0.03)' }}>
+ <span className="text-lg font-bold font-mono" style={{ color }}>{value}</span>
+ <span className="text-xs opacity-50">{label}</span>
+ </div>
+ );
+}
+
+function MatchCard({ match, rank, colors }: { match: PatternMatch; rank: number; colors: any }) {
+ const scorePct = Math.round(match.score * 100);
+ const scoreColor = scorePct >= 70 ? '#16a34a' : scorePct >= 50 ? '#ca8a04' : '#dc2626';
+
+ return (
+ <div
+ className="rounded p-2 flex flex-col gap-1"
+ style={{
+ backgroundColor: 'rgba(255,255,255,0.03)',
+ border: '1px solid rgba(255,255,255,0.06)',
+ }}
+ >
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-1.5">
+ <span className="text-xs opacity-30">#{rank}</span>
+ <span className="text-xs font-semibold">{match.symbol}</span>
+ <span className="text-xs opacity-40">{match.date}</span>
+ </div>
+ <span className="text-xs font-bold font-mono" style={{ color: scoreColor }}>
+ {scorePct}%
+ </span>
+ </div>
+ <div className="flex items-center gap-3 text-xs opacity-60">
+ {match.dtw_sim != null && <span>DTW: {(match.dtw_sim * 100).toFixed(0)}%</span>}
+ {match.correlation != null && <span>Corr: {(match.correlation * 100).toFixed(0)}%</span>}
+ {match.trend_match != null && (
+ <span className={match.trend_match === 1 ? 'text-green-400' : 'text-red-400'}>
+ {match.trend_match === 1 ? 'Trend OK' : 'Trend X'}
+ </span>
+ )}
+ </div>
+ {match.tb_label !== undefined && (
+ <div className="flex items-center gap-2 text-xs">
+ <TBLabelIcon label={match.tb_label} />
+ <span className={
+ match.tb_label === 1 ? 'text-green-400' :
+ match.tb_label === -1 ? 'text-red-400' : 'text-yellow-400'
+ }>
+ {match.tb_hit_type === 'upper' ? 'Take Profit' :
+ match.tb_hit_type === 'lower' ? 'Stop Loss' : 'Timeout'}
+ {match.tb_hit_day ? ` (${match.tb_hit_day}d)` : ''}
+ </span>
+ {match.final_return_pct != null && (
+ <span className="ml-auto font-mono" style={{ color: match.final_return_pct >= 0 ? '#16a34a' : '#dc2626' }}>
+ {match.final_return_pct > 0 ? '+' : ''}{match.final_return_pct}%
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/AlgoTradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/AlgoTradingTab.tsx
index 9043a08f8..af6818fc9 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/AlgoTradingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/AlgoTradingTab.tsx
@@ -1,8 +1,9 @@
-import React, { useState } from 'react';
+import React, { useState, useEffect } from 'react';
import {
Bot, Wrench, Search, BarChart3, Layout, Activity, Library,
Plus, Zap, ChevronRight,
} from 'lucide-react';
+import { listAlgoDeployments } from './services/algoTradingService';
import type { AlgoSubView, PythonStrategy } from './types';
import StrategyEditor from './components/StrategyEditor';
import StrategyManager from './components/StrategyManager';
@@ -12,24 +13,7 @@ import StrategyLibraryTab from './components/StrategyLibraryTab';
import PythonBacktestPanel from './components/PythonBacktestPanel';
import PythonStrategyEditor from './components/PythonStrategyEditor';
import PythonDeployPanel from './components/PythonDeployPanel';
-
-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',
-};
+import { F } from './constants/theme';
const NAV_ITEMS: { key: AlgoSubView; label: string; icon: React.ElementType; description: string }[] = [
{ key: 'builder', label: 'STRATEGY BUILDER', icon: Wrench, description: 'Create & edit strategies' },
@@ -45,6 +29,20 @@ const AlgoTradingTab: React.FC = () => {
const [clonePythonStrategy, setClonePythonStrategy] = useState<PythonStrategy | null>(null);
const [backtestPythonStrategy, setBacktestPythonStrategy] = useState<PythonStrategy | null>(null);
const [deployPythonStrategy, setDeployPythonStrategy] = useState<PythonStrategy | null>(null);
+ const [runningCount, setRunningCount] = useState(0);
+
+ // Lightweight poll just for the sidebar status indicator (30s interval, not 5s)
+ useEffect(() => {
+ const checkStatus = async () => {
+ const result = await listAlgoDeployments();
+ if (result.success && result.data) {
+ setRunningCount(result.data.filter(d => d.status === 'running').length);
+ }
+ };
+ checkStatus();
+ const interval = setInterval(checkStatus, 30000);
+ return () => clearInterval(interval);
+ }, []);
const handleEditStrategy = (id: string) => {
setEditStrategyId(id);
@@ -72,8 +70,7 @@ const AlgoTradingTab: React.FC = () => {
setClonePythonStrategy(null);
};
- const handlePythonEditorSave = (customId: string) => {
- console.log('Python strategy saved with ID:', customId);
+ const handlePythonEditorSave = (_customId: string) => {
setClonePythonStrategy(null);
setActiveView('strategies');
};
@@ -214,15 +211,19 @@ const AlgoTradingTab: React.FC = () => {
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '8px' }}>
<Zap size={10} style={{ color: F.YELLOW }} />
- <span style={{ fontSize: '8px', color: F.GRAY, letterSpacing: '0.5px' }}>SYSTEM STATUS</span>
+ <span style={{ fontSize: '8px', color: F.GRAY, letterSpacing: '0.5px' }}>DEPLOYMENTS</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- <span style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: F.GREEN, display: 'inline-block' }} />
- <span style={{ fontSize: '8px', color: F.GREEN }}>ONLINE</span>
+ <span style={{
+ width: '6px', height: '6px', borderRadius: '50%',
+ backgroundColor: runningCount > 0 ? F.GREEN : F.MUTED,
+ display: 'inline-block',
+ }} />
+ <span style={{ fontSize: '8px', color: runningCount > 0 ? F.GREEN : F.MUTED }}>
+ {runningCount > 0 ? `${runningCount} RUNNING` : 'IDLE'}
+ </span>
</div>
- <span style={{ fontSize: '8px', color: F.MUTED }}>|</span>
- <span style={{ fontSize: '8px', color: F.MUTED }}>ENGINE READY</span>
</div>
</div>
</div>
@@ -253,10 +254,12 @@ const AlgoTradingTab: React.FC = () => {
{NAV_ITEMS.find(n => n.key === activeView)?.label}
</span>
</div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <Activity size={10} style={{ color: F.GREEN }} />
- <span style={{ fontSize: '8px', color: F.GREEN }}>LIVE</span>
- </div>
+ {runningCount > 0 && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Activity size={10} style={{ color: F.GREEN }} />
+ <span style={{ fontSize: '8px', color: F.GREEN }}>{runningCount} LIVE</span>
+ </div>
+ )}
</div>
{/* View Content */}
@@ -305,11 +308,11 @@ const AlgoTradingTab: React.FC = () => {
}}>
<div style={{ display: 'flex', gap: '16px' }}>
<span><span style={{ color: F.MUTED }}>ENGINE:</span> v1.0</span>
- <span><span style={{ color: F.MUTED }}>MODE:</span> <span style={{ color: F.CYAN }}>PRODUCTION</span></span>
+ <span><span style={{ color: F.MUTED }}>DEPLOYMENTS:</span> <span style={{ color: runningCount > 0 ? F.GREEN : F.MUTED }}>{runningCount} active</span></span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
- <span style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: F.GREEN }} />
- <span style={{ color: F.GREEN }}>READY</span>
+ <span style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: runningCount > 0 ? F.GREEN : F.MUTED }} />
+ <span style={{ color: runningCount > 0 ? F.GREEN : F.MUTED }}>{runningCount > 0 ? 'ACTIVE' : 'IDLE'}</span>
</div>
</div>
</div>
@@ -336,8 +339,7 @@ const AlgoTradingTab: React.FC = () => {
<PythonDeployPanel
strategy={deployPythonStrategy}
onClose={() => setDeployPythonStrategy(null)}
- onDeployed={(deployId) => {
- console.log('Strategy deployed:', deployId);
+ onDeployed={() => {
setDeployPythonStrategy(null);
setActiveView('dashboard');
}}
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
index fce214ec2..14a03806a 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionBuilder.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionBuilder.tsx
@@ -3,13 +3,7 @@ import { Plus, ChevronDown, ChevronRight, Zap, Layers, Sparkles } from 'lucide-r
import type { ConditionItem } from '../types';
import { getIndicatorDef } from '../constants/indicators';
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', MUTED: '#4A4A4A',
- GREEN: '#00D66F', RED: '#FF3B3B', YELLOW: '#FFD700', PURPLE: '#9D4EDD',
-};
+import { F } from '../constants/theme';
interface ConditionBuilderProps {
label: string;
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
index 61e3950c8..6408bf091 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionRow.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionRow.tsx
@@ -2,13 +2,7 @@ import React from 'react';
import { Clock, ArrowRight, AlertTriangle } 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', GREEN: '#00D66F', YELLOW: '#FFD600',
- PURPLE: '#9D4EDD', BLUE: '#0088FF', HEADER_BG: '#1A1A1A',
-};
+import { F } from '../constants/theme';
// Operator labels for readable display
const OPERATOR_LABELS: Record<string, string> = {
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
index 608fa59ba..cfaaf4f36 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeployPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeployPanel.tsx
@@ -9,14 +9,9 @@ import { SymbolSearch } from '@/components/tabs/equity-trading/components/Symbol
import type { SymbolSearchResult, SupportedBroker } from '@/services/trading/masterContractService';
import type { StockExchange } from '@/brokers/stocks/types';
-type AssetType = 'crypto' | 'stock';
+import { F } from '../constants/theme';
-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', HOVER: '#1F1F1F',
-};
+type AssetType = 'crypto' | 'stock';
const inputStyle: React.CSSProperties = {
width: '100%', padding: '8px 10px', backgroundColor: F.DARK_BG,
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
index 000245020..36b52aa6f 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeploymentCard.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/DeploymentCard.tsx
@@ -7,13 +7,7 @@ import { listen } from '@tauri-apps/api/event';
import type { AlgoDeployment } from '../types';
import { stopAlgoDeployment, deleteAlgoDeployment } from '../services/algoTradingService';
import TradeHistoryTable from './TradeHistoryTable';
-
-const F = {
- ORANGE: '#FF8800', WHITE: '#FFFFFF', RED: '#FF3B3B', GREEN: '#00D66F',
- GRAY: '#787878', DARK_BG: '#000000', PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A', BORDER: '#2A2A2A', MUTED: '#4A4A4A',
- CYAN: '#00E5FF', YELLOW: '#FFD700', BLUE: '#0088FF', PURPLE: '#9D4EDD',
-};
+import { F } from '../constants/theme';
const statusConfig: Record<string, { color: string; bg: string; label: string }> = {
running: { color: F.GREEN, bg: `${F.GREEN}15`, label: 'RUNNING' },
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
index c6d534ae9..2a24daa7e 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/MonitorDashboard.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/MonitorDashboard.tsx
@@ -7,13 +7,7 @@ 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', BLUE: '#0088FF', HOVER: '#1F1F1F',
-};
+import { F } from '../constants/theme';
const MonitorDashboard: React.FC = () => {
const [deployments, setDeployments] = useState<AlgoDeployment[]>([]);
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ParameterEditor.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ParameterEditor.tsx
index 4dc827e1a..0bab77a4b 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ParameterEditor.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ParameterEditor.tsx
@@ -2,13 +2,7 @@ import React, { useState, useEffect } from 'react';
import { Settings, Loader2, AlertCircle, RefreshCw, Code, Hash, ToggleLeft, Type } from 'lucide-react';
import type { StrategyParameter } from '../types';
import { extractStrategyParameters } from '../services/algoTradingService';
-
-const F = {
- ORANGE: '#FF8800', WHITE: '#FFFFFF', RED: '#FF3B3B', GREEN: '#00D66F',
- GRAY: '#787878', DARK_BG: '#000000', PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A', BORDER: '#2A2A2A', HOVER: '#1F1F1F',
- MUTED: '#4A4A4A', CYAN: '#00E5FF', YELLOW: '#FFD700', BLUE: '#0088FF',
-};
+import { F } from '../constants/theme';
const inputBaseStyle: React.CSSProperties = {
width: '100%', padding: '8px 10px', backgroundColor: F.DARK_BG,
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonBacktestPanel.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonBacktestPanel.tsx
index 434324233..eaeeba6b3 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonBacktestPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonBacktestPanel.tsx
@@ -20,24 +20,7 @@ import {
import type { PythonStrategy, PythonBacktestResult, BacktestMetrics, EquityPoint, BacktestTrade } from '../types';
import { runPythonBacktest, getPythonStrategyCode } from '../services/algoTradingService';
import ParameterEditor from './ParameterEditor';
-
-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',
-};
+import { F } from '../constants/theme';
interface PythonBacktestPanelProps {
strategy: PythonStrategy;
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonDeployPanel.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonDeployPanel.tsx
index 7f8f7c972..7175a52eb 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonDeployPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonDeployPanel.tsx
@@ -11,24 +11,7 @@ import {
import { invoke } from '@tauri-apps/api/core';
import { useStockBrokerContextOptional } from '@/contexts/StockBrokerContext';
import ParameterEditor from './ParameterEditor';
-
-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',
-};
+import { F } from '../constants/theme';
interface PythonDeployPanelProps {
strategy: PythonStrategy;
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonStrategyEditor.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonStrategyEditor.tsx
index 91db5b0f3..fd61d748d 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonStrategyEditor.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/PythonStrategyEditor.tsx
@@ -12,24 +12,7 @@ import {
extractStrategyParameters,
} from '../services/algoTradingService';
import ParameterEditor from './ParameterEditor';
-
-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',
-};
+import { F } from '../constants/theme';
// Python syntax keywords for basic highlighting
const PYTHON_KEYWORDS = [
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
index a4a183dc6..ee5b98cec 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx
@@ -6,13 +6,7 @@ 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',
- YELLOW: '#FFD600', PURPLE: '#9D4EDD', BLUE: '#0088FF',
-};
+import { F } from '../constants/theme';
const inputStyle: React.CSSProperties = {
width: '100%', padding: '8px 10px', backgroundColor: F.DARK_BG,
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
index 8c140aad6..0f20a104b 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyEditor.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyEditor.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect, useCallback } from 'react';
import {
Save, Play, Loader, ArrowLeft, Shield, AlertTriangle, ChevronDown, ChevronRight,
Target, TrendingUp, TrendingDown, BarChart3, Clock, Percent, Activity,
@@ -8,14 +8,7 @@ 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',
- BLUE: '#0088FF',
-};
+import { F } from '../constants/theme';
interface StrategyEditorProps {
editStrategyId: string | null;
@@ -89,11 +82,7 @@ const StrategyEditor: React.FC<StrategyEditorProps> = ({ editStrategyId, onSaved
const [showDebug, setShowDebug] = useState(false);
const [showBacktest, setShowBacktest] = useState(true);
- useEffect(() => {
- if (editStrategyId) loadStrategy(editStrategyId);
- }, [editStrategyId]);
-
- const loadStrategy = async (id: string) => {
+ const loadStrategy = useCallback(async (id: string) => {
const result = await getAlgoStrategy(id);
if (result.success && result.data) {
const s = result.data;
@@ -107,7 +96,11 @@ const StrategyEditor: React.FC<StrategyEditorProps> = ({ editStrategyId, onSaved
setExitConditions(JSON.parse(s.exit_conditions).filter((c: unknown) => typeof c === 'object'));
} catch { /* keep defaults */ }
}
- };
+ }, []);
+
+ useEffect(() => {
+ if (editStrategyId) loadStrategy(editStrategyId);
+ }, [editStrategyId, loadStrategy]);
const buildConditionsJson = (conditions: ConditionItem[], logic: string): string => {
if (conditions.length === 0) return '[]';
@@ -120,7 +113,7 @@ const StrategyEditor: React.FC<StrategyEditorProps> = ({ editStrategyId, onSaved
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 id = editStrategyId || `algo-${crypto.randomUUID()}`;
const result = await saveAlgoStrategy({
id, name: name.trim(), description: description.trim(),
entry_conditions: buildConditionsJson(entryConditions, entryLogic),
@@ -408,7 +401,7 @@ const StrategyEditor: React.FC<StrategyEditorProps> = ({ editStrategyId, onSaved
<div>
<label style={labelStyle}>TRAILING STOP (%)</label>
<input type="number" value={trailingStop} onChange={e => setTrailingStop(e.target.value)} placeholder="e.g. 1.5" step="0.1" min="0" style={inputStyle} />
- <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>Not yet implemented</div>
+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>Exit if pullback from peak &ge; this %</div>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyLibraryTab.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyLibraryTab.tsx
index ab2b2d1cb..acf7fb1dd 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyLibraryTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyLibraryTab.tsx
@@ -9,24 +9,7 @@ import {
getStrategyCategories,
getPythonStrategyCode,
} from '../services/algoTradingService';
-
-const F = {
- ORANGE: '#FF8800',
- WHITE: '#FFFFFF',
- RED: '#FF3B3B',
- GREEN: '#00D66F',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0F0F0F',
- HEADER_BG: '#1A1A1A',
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F',
- MUTED: '#4A4A4A',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- BLUE: '#0088FF',
- PURPLE: '#9D4EDD',
-};
+import { F } from '../constants/theme';
interface StrategyLibraryTabProps {
onViewCode?: (strategy: PythonStrategy, code: string) => void;
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
index 812d60ad0..385dd46aa 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyManager.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/StrategyManager.tsx
@@ -13,24 +13,7 @@ import {
} from '../services/algoTradingService';
import DeployPanel from './DeployPanel';
import PythonStrategyEditor from './PythonStrategyEditor';
-
-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',
- PURPLE: '#9D4EDD',
- YELLOW: '#FFD700',
- BLUE: '#0088FF',
-};
+import { F } from '../constants/theme';
type StrategyType = 'all' | 'json' | 'python';
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
index b096d1170..9ddd64605 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/TradeHistoryTable.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/TradeHistoryTable.tsx
@@ -1,12 +1,7 @@
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',
-};
+import { F } from '../constants/theme';
const thStyle: React.CSSProperties = {
padding: '6px 12px', fontSize: '8px', fontWeight: 700, color: F.GRAY,
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/theme.ts b/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/theme.ts
new file mode 100644
index 000000000..0f78f63a1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/theme.ts
@@ -0,0 +1,21 @@
+// Algo Trading Theme Constants
+// Raw hex values required here (not CSS variables) because components
+// use hex alpha concatenation like `${F.ORANGE}20`
+
+export const F = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ YELLOW: '#FFD700',
+ CYAN: '#00E5FF',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
+ GRAY: '#787878',
+ MUTED: '#4A4A4A',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ HOVER: '#1F1F1F',
+ BORDER: '#2A2A2A',
+} as const;
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
index cdc7f6b6c..5fda8bce4 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useCandleData.ts
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/hooks/useCandleData.ts
@@ -1,8 +1,9 @@
import { useState, useCallback } from 'react';
import { getCandleCache } from '../services/algoTradingService';
+import type { CandleData } from '../types';
export function useCandleData() {
- const [candles, setCandles] = useState<unknown[]>([]);
+ const [candles, setCandles] = useState<CandleData[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
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
index ccc3ab89e..10666c91f 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/services/algoTradingService.ts
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/services/algoTradingService.ts
@@ -4,6 +4,7 @@ import type {
AlgoDeployment,
AlgoTrade,
ScanResult,
+ CandleData,
PythonStrategy,
CustomPythonStrategy,
PythonBacktestRequest,
@@ -137,33 +138,34 @@ export async function runAlgoScan(
lookbackDays?: number
): Promise<ApiResult<ScanResponse>> {
const raw = await invoke<string>('run_algo_scan', { conditions, symbols, timeframe, provider, lookbackDays });
- const result = parseResult<ScanResponse>(raw);
- // The Rust backend puts debug/prefetch_warning at root level (same as success/error),
- // and the Python scanner puts matches/scanned/errors in the same JSON object.
- // Normalize: merge top-level fields into data when success=true.
- if (result.success && !result.data) {
- // Scanner output is flat JSON — parse again to extract fields
- try {
- const parsed = JSON.parse(raw);
- result.data = {
- matches: parsed.matches || [],
- scanned: parsed.scanned || 0,
- errors: parsed.errors,
- debug: parsed.debug,
- prefetch_warning: parsed.prefetch_warning,
- };
- result.debug = parsed.debug;
- result.prefetch_warning = parsed.prefetch_warning;
- } catch { /* already handled */ }
+
+ // Parse once and normalize the flat scanner JSON into ApiResult<ScanResponse>
+ let parsed: Record<string, unknown>;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ return { success: false, error: 'Failed to parse scan response' };
}
- // Also carry debug from root level
- if (!result.debug) {
- try {
- const parsed = JSON.parse(raw);
- if (parsed.debug) result.debug = parsed.debug;
- if (parsed.prefetch_warning) result.prefetch_warning = parsed.prefetch_warning;
- } catch { /* ignore */ }
+
+ const result: ApiResult<ScanResponse> = {
+ success: (parsed.success as boolean) ?? false,
+ error: parsed.error as string | undefined,
+ debug: parsed.debug as string[] | undefined,
+ prefetch_warning: parsed.prefetch_warning as string | undefined,
+ };
+
+ // The scanner output is flat JSON with matches/scanned at root level.
+ // Normalize into the data property.
+ if (result.success) {
+ result.data = {
+ matches: (parsed.matches || parsed.data && (parsed.data as Record<string, unknown>).matches || []) as ScanResult[],
+ scanned: (parsed.scanned || parsed.data && (parsed.data as Record<string, unknown>).scanned || 0) as number,
+ errors: (parsed.errors || parsed.data && (parsed.data as Record<string, unknown>).errors) as Array<{ symbol: string; error: string }> | undefined,
+ debug: result.debug,
+ prefetch_warning: result.prefetch_warning,
+ };
}
+
return result;
}
@@ -172,7 +174,7 @@ export async function getCandleCache(
symbol: string,
timeframe?: string,
limit?: number
-): Promise<ApiResult<unknown[]>> {
+): Promise<ApiResult<CandleData[]>> {
const raw = await invoke<string>('get_candle_cache', { symbol, timeframe, limit });
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
index 54ff1619d..9a2e49d5f 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/types/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/types/index.ts
@@ -1,3 +1,16 @@
+export interface CandleData {
+ symbol: string;
+ provider: string;
+ timeframe: string;
+ open_time: number;
+ o: number;
+ h: number;
+ l: number;
+ c: number;
+ volume: number;
+ is_closed: number;
+}
+
export interface ConditionItem {
indicator: string;
params: Record<string, number>;
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaRightPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaRightPanel.tsx
index 3ae99a1a1..a0f2711a7 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaRightPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaRightPanel.tsx
@@ -183,10 +183,32 @@ const AlphaArenaRightPanel: React.FC<AlphaArenaRightPanelProps> = ({
);
};
+// Get action color for Polymarket or crypto decisions
+const getActionColor = (action: string): string => {
+ switch (action?.toLowerCase()) {
+ case 'buy': case 'buy_yes': return '#00D66F';
+ case 'sell': case 'sell_yes': return '#FF3B3B';
+ case 'buy_no': return '#FF3B3B';
+ case 'sell_no': return '#00D66F';
+ case 'short': return '#9D4EDD';
+ default: return '#787878';
+ }
+};
+
+const getActionBg = (action: string): string => {
+ const color = getActionColor(action);
+ return `${color}20`;
+};
+
// Decisions sub-content - Terminal style
const DecisionsContent: React.FC<{ decisions: ModelDecision[] }> = ({ decisions }) => {
const safeDecisions = Array.isArray(decisions) ? decisions : [];
+ // Check if decisions are Polymarket-style (action contains buy_yes, buy_no, etc.)
+ const isPolymarket = safeDecisions.some(d =>
+ ['buy_yes', 'buy_no', 'sell_yes', 'sell_no'].includes(d.action)
+ );
+
return (
<div style={{ display: 'flex', flexDirection: 'column', backgroundColor: FINCEPT.CARD_BG }}>
{/* Header */}
@@ -200,7 +222,9 @@ const DecisionsContent: React.FC<{ decisions: ModelDecision[] }> = ({ decisions
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
<Brain size={14} style={{ color: FINCEPT.PURPLE }} />
- <span style={{ fontWeight: 700, fontSize: '11px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>AI DECISIONS</span>
+ <span style={{ fontWeight: 700, fontSize: '11px', color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>
+ {isPolymarket ? 'PM DECISIONS' : 'AI DECISIONS'}
+ </span>
</div>
<span style={{
fontSize: '9px',
@@ -223,71 +247,110 @@ const DecisionsContent: React.FC<{ decisions: ModelDecision[] }> = ({ decisions
</div>
) : (
<div>
- {safeDecisions.slice(0, 50).map((decision, idx) => (
- <div
- key={`${decision.model_name}-${decision.cycle_number}-${idx}`}
- style={{
- padding: '8px 10px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- transition: 'background-color 0.15s',
- cursor: 'default',
- }}
- onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = FINCEPT.PANEL_BG; }}
- onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent'; }}
- >
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.WHITE }}>
- {decision.model_name}
- </span>
- <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
- Cycle {decision.cycle_number}
- </span>
- </div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
- <span style={{
- fontSize: '9px',
- padding: '1px 6px',
- fontWeight: 700,
- letterSpacing: '0.5px',
- backgroundColor: decision.action === 'buy' ? `${FINCEPT.GREEN}20` :
- decision.action === 'sell' ? `${FINCEPT.RED}20` :
- decision.action === 'short' ? `${FINCEPT.PURPLE}20` :
- `${FINCEPT.GRAY}20`,
- color: decision.action === 'buy' ? FINCEPT.GREEN :
- decision.action === 'sell' ? FINCEPT.RED :
- decision.action === 'short' ? FINCEPT.PURPLE :
- FINCEPT.GRAY,
- }}>
- {(decision.action || 'hold').toUpperCase()}
- </span>
- <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
- {decision.symbol}
- </span>
- <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
- Qty: {(decision.quantity ?? 0).toFixed(4)}
- </span>
- </div>
- {decision.reasoning && (
- <p style={{
- fontSize: '9px',
- marginTop: '4px',
- color: FINCEPT.MUTED,
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- display: '-webkit-box',
- WebkitLineClamp: 2,
- WebkitBoxOrient: 'vertical',
- }}>
- {decision.reasoning}
- </p>
- )}
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: '4px' }}>
- <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
- Confidence: {((decision.confidence ?? 0) * 100).toFixed(0)}%
- </span>
+ {safeDecisions.slice(0, 50).map((decision, idx) => {
+ const confidence = decision.confidence ?? 0;
+ const actionColor = getActionColor(decision.action);
+ const isHighConfidence = confidence >= 0.7;
+
+ return (
+ <div
+ key={`${decision.model_name}-${decision.cycle_number}-${idx}`}
+ style={{
+ padding: '8px 10px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderLeft: `3px solid ${actionColor}`,
+ transition: 'background-color 0.15s',
+ cursor: 'default',
+ }}
+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = FINCEPT.PANEL_BG; }}
+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent'; }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '4px' }}>
+ <span style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.WHITE }}>
+ {decision.model_name}
+ </span>
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
+ Cycle {decision.cycle_number}
+ </span>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap' }}>
+ <span style={{
+ fontSize: '9px',
+ padding: '1px 6px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ backgroundColor: getActionBg(decision.action),
+ color: actionColor,
+ }}>
+ {(decision.action || 'hold').toUpperCase().replace('_', ' ')}
+ </span>
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, maxWidth: '180px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ {decision.symbol}
+ </span>
+ {decision.quantity > 0 && (
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
+ {isPolymarket ? `$${(decision.quantity ?? 0).toFixed(2)}` : `Qty: ${(decision.quantity ?? 0).toFixed(4)}`}
+ </span>
+ )}
+ {isHighConfidence && decision.action !== 'hold' && (
+ <span style={{
+ fontSize: '8px',
+ padding: '0 4px',
+ fontWeight: 700,
+ backgroundColor: `${FINCEPT.ORANGE}20`,
+ color: FINCEPT.ORANGE,
+ }}>
+ HIGH EDGE
+ </span>
+ )}
+ </div>
+
+ {/* Confidence bar */}
+ <div style={{ marginTop: '5px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <div style={{
+ flex: 1,
+ height: '3px',
+ backgroundColor: FINCEPT.BORDER,
+ overflow: 'hidden',
+ }}>
+ <div style={{
+ width: `${confidence * 100}%`,
+ height: '100%',
+ backgroundColor: confidence >= 0.7 ? FINCEPT.GREEN : confidence >= 0.4 ? FINCEPT.ORANGE : FINCEPT.RED,
+ transition: 'width 0.3s',
+ }} />
+ </div>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 600,
+ color: confidence >= 0.7 ? FINCEPT.GREEN : confidence >= 0.4 ? FINCEPT.ORANGE : FINCEPT.RED,
+ minWidth: '30px',
+ textAlign: 'right',
+ }}>
+ {(confidence * 100).toFixed(0)}%
+ </span>
+ </div>
+ </div>
+
+ {decision.reasoning && (
+ <p style={{
+ fontSize: '9px',
+ marginTop: '4px',
+ color: FINCEPT.MUTED,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ display: '-webkit-box',
+ WebkitLineClamp: 2,
+ WebkitBoxOrient: 'vertical',
+ }}>
+ {decision.reasoning}
+ </p>
+ )}
</div>
- </div>
- ))}
+ );
+ })}
</div>
)}
</div>
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 0a1393a7a..e8428ebd5 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx
@@ -800,52 +800,343 @@ const AlphaArenaTab: React.FC = () => {
/>
</div>
- {/* Symbol & Mode */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '10px' }}>
- <div>
- <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>TRADING SYMBOL</label>
- <select
- value={arena.symbol}
- onChange={e => arena.setSymbol(e.target.value)}
+ {/* Competition Type Toggle */}
+ <div style={{ marginBottom: '10px' }}>
+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>COMPETITION TYPE</label>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <button
+ type="button"
+ onClick={() => arena.setCompetitionType('crypto')}
style={{
- width: '100%',
- padding: '8px 10px',
- backgroundColor: FINCEPT.HEADER_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
- fontSize: '12px',
+ flex: 1,
+ padding: '10px 12px',
+ backgroundColor: arena.competitionType === 'crypto' ? FINCEPT.ORANGE : FINCEPT.CARD_BG,
+ color: arena.competitionType === 'crypto' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ border: `1px solid ${arena.competitionType === 'crypto' ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ fontWeight: 700,
+ fontSize: '11px',
fontFamily: TERMINAL_FONT,
- outline: 'none',
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ letterSpacing: '0.5px',
}}
>
- {TRADING_SYMBOLS.map(s => (
- <option key={s.value} value={s.value} style={{ backgroundColor: FINCEPT.HEADER_BG }}>{s.label}</option>
- ))}
- </select>
- </div>
- <div>
- <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>COMPETITION MODE</label>
- <select
- value={arena.mode}
- onChange={e => arena.setMode(e.target.value as CompetitionMode)}
+ <TrendingUp size={12} style={{ marginRight: '6px', verticalAlign: 'middle' }} />
+ CRYPTO TRADING
+ </button>
+ <button
+ type="button"
+ onClick={() => arena.setCompetitionType('polymarket')}
style={{
- width: '100%',
- padding: '8px 10px',
- backgroundColor: FINCEPT.HEADER_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
- fontSize: '12px',
+ flex: 1,
+ padding: '10px 12px',
+ backgroundColor: arena.competitionType === 'polymarket' ? FINCEPT.PURPLE : FINCEPT.CARD_BG,
+ color: arena.competitionType === 'polymarket' ? FINCEPT.WHITE : FINCEPT.GRAY,
+ border: `1px solid ${arena.competitionType === 'polymarket' ? FINCEPT.PURPLE : FINCEPT.BORDER}`,
+ fontWeight: 700,
+ fontSize: '11px',
fontFamily: TERMINAL_FONT,
- outline: 'none',
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ letterSpacing: '0.5px',
}}
>
- {COMPETITION_MODES.map(m => (
- <option key={m.value} value={m.value} style={{ backgroundColor: FINCEPT.HEADER_BG }}>{m.label}</option>
- ))}
- </select>
+ <BarChart3 size={12} style={{ marginRight: '6px', verticalAlign: 'middle' }} />
+ PREDICTION MARKETS
+ </button>
</div>
</div>
+ {/* Symbol & Mode (Crypto only) */}
+ {arena.competitionType === 'crypto' && (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '10px' }}>
+ <div>
+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>TRADING SYMBOL</label>
+ <select
+ value={arena.symbol}
+ onChange={e => arena.setSymbol(e.target.value)}
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '12px',
+ fontFamily: TERMINAL_FONT,
+ outline: 'none',
+ }}
+ >
+ {TRADING_SYMBOLS.map(s => (
+ <option key={s.value} value={s.value} style={{ backgroundColor: FINCEPT.HEADER_BG }}>{s.label}</option>
+ ))}
+ </select>
+ </div>
+ <div>
+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>COMPETITION MODE</label>
+ <select
+ value={arena.mode}
+ onChange={e => arena.setMode(e.target.value as CompetitionMode)}
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '12px',
+ fontFamily: TERMINAL_FONT,
+ outline: 'none',
+ }}
+ >
+ {COMPETITION_MODES.map(m => (
+ <option key={m.value} value={m.value} style={{ backgroundColor: FINCEPT.HEADER_BG }}>{m.label}</option>
+ ))}
+ </select>
+ </div>
+ </div>
+ )}
+
+ {/* Polymarket Market Selection (Polymarket only) */}
+ {arena.competitionType === 'polymarket' && (
+ <div style={{ marginBottom: '10px' }}>
+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>
+ SELECT PREDICTION MARKETS (min 1 required)
+ </label>
+
+ {/* Filters Row */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', marginBottom: '8px' }}>
+ <div>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '2px', fontWeight: 600 }}>CATEGORY</label>
+ <select
+ value={arena.polymarketCategory}
+ onChange={e => arena.setPolymarketCategory(e.target.value)}
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '10px',
+ fontFamily: TERMINAL_FONT,
+ outline: 'none',
+ }}
+ >
+ <option value="" style={{ backgroundColor: FINCEPT.HEADER_BG }}>All Categories</option>
+ <option value="politics" style={{ backgroundColor: FINCEPT.HEADER_BG }}>Politics</option>
+ <option value="sports" style={{ backgroundColor: FINCEPT.HEADER_BG }}>Sports</option>
+ <option value="crypto" style={{ backgroundColor: FINCEPT.HEADER_BG }}>Crypto</option>
+ <option value="science" style={{ backgroundColor: FINCEPT.HEADER_BG }}>Science</option>
+ <option value="entertainment" style={{ backgroundColor: FINCEPT.HEADER_BG }}>Entertainment</option>
+ <option value="pop-culture" style={{ backgroundColor: FINCEPT.HEADER_BG }}>Pop Culture</option>
+ <option value="business" style={{ backgroundColor: FINCEPT.HEADER_BG }}>Business</option>
+ </select>
+ </div>
+ <div>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '2px', fontWeight: 600 }}>SORT BY</label>
+ <select
+ value={arena.polymarketSortBy}
+ onChange={e => arena.setPolymarketSortBy(e.target.value as 'volume' | 'liquidity' | 'end_date' | 'spread')}
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '10px',
+ fontFamily: TERMINAL_FONT,
+ outline: 'none',
+ }}
+ >
+ <option value="volume" style={{ backgroundColor: FINCEPT.HEADER_BG }}>Volume (High→Low)</option>
+ <option value="liquidity" style={{ backgroundColor: FINCEPT.HEADER_BG }}>Liquidity (High→Low)</option>
+ <option value="end_date" style={{ backgroundColor: FINCEPT.HEADER_BG }}>End Date (Soonest)</option>
+ <option value="spread" style={{ backgroundColor: FINCEPT.HEADER_BG }}>Spread (Highest)</option>
+ </select>
+ </div>
+ </div>
+
+ {/* Min thresholds */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '6px', marginBottom: '8px' }}>
+ <div>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '2px', fontWeight: 600 }}>MIN VOLUME ($)</label>
+ <input
+ type="number"
+ value={arena.polymarketMinVolume}
+ onChange={e => arena.setPolymarketMinVolume(Number(e.target.value) || 0)}
+ placeholder="0"
+ style={{
+ width: '100%',
+ padding: '5px 6px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '10px',
+ fontFamily: TERMINAL_FONT,
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ display: 'block', fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '2px', fontWeight: 600 }}>MIN LIQUIDITY ($)</label>
+ <input
+ type="number"
+ value={arena.polymarketMinLiquidity}
+ onChange={e => arena.setPolymarketMinLiquidity(Number(e.target.value) || 0)}
+ placeholder="0"
+ style={{
+ width: '100%',
+ padding: '5px 6px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '10px',
+ fontFamily: TERMINAL_FONT,
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ </div>
+ <div style={{ display: 'flex', alignItems: 'flex-end' }}>
+ <button
+ onClick={() => arena.loadPolymarkets()}
+ style={{
+ width: '100%',
+ padding: '5px 6px',
+ backgroundColor: FINCEPT.PURPLE,
+ color: FINCEPT.WHITE,
+ border: 'none',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ }}
+ >
+ <RefreshCw size={9} />
+ REFRESH
+ </button>
+ </div>
+ </div>
+
+ {/* Market list */}
+ <div style={{
+ maxHeight: '200px',
+ overflowY: 'auto',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.CARD_BG,
+ }}>
+ {arena.loadingPolymarkets ? (
+ <div style={{ padding: '20px', textAlign: 'center' }}>
+ <Loader2 size={20} style={{ color: FINCEPT.PURPLE, animation: 'alpha-spin 1s linear infinite' }} />
+ <p style={{ fontSize: '10px', color: FINCEPT.GRAY, marginTop: '8px' }}>Loading markets...</p>
+ </div>
+ ) : arena.availablePolymarkets.length === 0 ? (
+ <div style={{ padding: '20px', textAlign: 'center' }}>
+ <p style={{ fontSize: '10px', color: FINCEPT.GRAY }}>No active markets found</p>
+ </div>
+ ) : (
+ arena.availablePolymarkets.map(market => {
+ const isSelected = arena.selectedPolymarkets.some(m => m.id === market.id);
+ const yesPrice = market.outcome_prices[0] ?? 0;
+ const noPrice = market.outcome_prices[1] ?? (1 - yesPrice);
+ const spread = Math.abs(yesPrice - noPrice);
+ const edgeFromFair = Math.abs(0.5 - yesPrice);
+ return (
+ <div
+ key={market.id}
+ onClick={() => arena.togglePolymarketSelection(market)}
+ style={{
+ padding: '10px 12px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ cursor: 'pointer',
+ backgroundColor: isSelected ? `${FINCEPT.PURPLE}15` : 'transparent',
+ transition: 'background-color 0.1s',
+ }}
+ onMouseEnter={e => { if (!isSelected) e.currentTarget.style.backgroundColor = FINCEPT.HOVER; }}
+ onMouseLeave={e => { if (!isSelected) e.currentTarget.style.backgroundColor = 'transparent'; }}
+ >
+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '10px' }}>
+ <div style={{
+ width: '16px',
+ height: '16px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: isSelected ? FINCEPT.PURPLE : FINCEPT.BORDER,
+ flexShrink: 0,
+ marginTop: '2px',
+ }}>
+ {isSelected && <Check size={10} style={{ color: FINCEPT.WHITE }} />}
+ </div>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div style={{
+ fontSize: '11px',
+ fontWeight: 600,
+ color: FINCEPT.WHITE,
+ marginBottom: '4px',
+ lineHeight: 1.3,
+ }}>
+ {market.question}
+ </div>
+ {/* Price bar visualization */}
+ <div style={{ display: 'flex', height: '4px', marginBottom: '5px', overflow: 'hidden' }}>
+ <div style={{ width: `${yesPrice * 100}%`, backgroundColor: FINCEPT.GREEN, transition: 'width 0.3s' }} />
+ <div style={{ width: `${noPrice * 100}%`, backgroundColor: FINCEPT.RED, transition: 'width 0.3s' }} />
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '9px', flexWrap: 'wrap' }}>
+ <span style={{ color: FINCEPT.GREEN, fontWeight: 600 }}>
+ YES {(yesPrice * 100).toFixed(1)}¢
+ </span>
+ <span style={{ color: FINCEPT.RED, fontWeight: 600 }}>
+ NO {(noPrice * 100).toFixed(1)}¢
+ </span>
+ <span style={{ color: FINCEPT.GRAY }}>
+ VOL ${market.volume >= 1000000 ? (market.volume / 1000000).toFixed(1) + 'M' : (market.volume / 1000).toFixed(1) + 'K'}
+ </span>
+ <span style={{ color: FINCEPT.GRAY }}>
+ LIQ ${market.liquidity >= 1000 ? (market.liquidity / 1000).toFixed(1) + 'K' : market.liquidity.toFixed(0)}
+ </span>
+ {edgeFromFair > 0.15 && (
+ <span style={{
+ color: FINCEPT.YELLOW,
+ fontWeight: 700,
+ padding: '0 3px',
+ backgroundColor: `${FINCEPT.YELLOW}15`,
+ }}>
+ DECISIVE
+ </span>
+ )}
+ {market.end_date && (
+ <span style={{ color: FINCEPT.CYAN, fontSize: '8px' }}>
+ Ends: {new Date(market.end_date).toLocaleDateString()}
+ </span>
+ )}
+ {market.category && (
+ <span style={{
+ color: FINCEPT.PURPLE,
+ fontSize: '8px',
+ padding: '0 4px',
+ backgroundColor: `${FINCEPT.PURPLE}15`,
+ }}>
+ {market.category}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+ })
+ )}
+ </div>
+ <p style={{ fontSize: '9px', marginTop: '6px', color: FINCEPT.GRAY }}>
+ Selected: {arena.selectedPolymarkets.length} market(s)
+ </p>
+ </div>
+ )}
+
{/* Capital & Interval */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '10px' }}>
<div>
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
deleted file mode 100644
index 7cb495aab..000000000
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ApiKeysModal.tsx
+++ /dev/null
@@ -1,264 +0,0 @@
-/**
- * API Keys Modal Component
- *
- * @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';
-
-interface ApiKeysModalProps {
- isOpen: boolean;
- onClose: () => void;
-}
-
-interface ApiKeyConfig {
- provider: string;
- label: string;
- envVar: string;
- value: string;
- placeholder: string;
-}
-
-const DEFAULT_PROVIDERS: Omit<ApiKeyConfig, 'value'>[] = [
- {
- provider: 'openai',
- label: 'OpenAI',
- envVar: 'OPENAI_API_KEY',
- placeholder: 'sk-...',
- },
- {
- provider: 'anthropic',
- label: 'Anthropic',
- envVar: 'ANTHROPIC_API_KEY',
- placeholder: 'sk-ant-...',
- },
- {
- provider: 'google',
- label: 'Google AI',
- envVar: 'GOOGLE_API_KEY',
- placeholder: 'AIza...',
- },
- {
- provider: 'deepseek',
- label: 'DeepSeek',
- envVar: 'DEEPSEEK_API_KEY',
- placeholder: 'sk-...',
- },
- {
- provider: 'groq',
- label: 'Groq',
- envVar: 'GROQ_API_KEY',
- placeholder: 'gsk_...',
- },
-];
-
-// State machine for load/save operations
-type LoadState =
- | { status: 'idle' }
- | { status: 'loading' }
- | { status: 'success' }
- | { status: 'error'; error: string };
-
-type SaveState =
- | { status: 'idle' }
- | { status: 'saving' }
- | { status: 'saved' }
- | { status: 'error'; error: string };
-
-type LoadAction =
- | { type: 'LOAD_START' }
- | { type: 'LOAD_SUCCESS' }
- | { type: 'LOAD_ERROR'; error: string };
-
-type SaveAction =
- | { type: 'SAVE_START' }
- | { type: 'SAVE_SUCCESS' }
- | { type: 'SAVE_ERROR'; error: string }
- | { type: 'SAVE_RESET' };
-
-function loadReducer(_state: LoadState, action: LoadAction): LoadState {
- switch (action.type) {
- case 'LOAD_START': return { status: 'loading' };
- case 'LOAD_SUCCESS': return { status: 'success' };
- case 'LOAD_ERROR': return { status: 'error', error: action.error };
- default: return _state;
- }
-}
-
-function saveReducer(_state: SaveState, action: SaveAction): SaveState {
- switch (action.type) {
- case 'SAVE_START': return { status: 'saving' };
- case 'SAVE_SUCCESS': return { status: 'saved' };
- case 'SAVE_ERROR': return { status: 'error', error: action.error };
- case 'SAVE_RESET': return { status: 'idle' };
- default: return _state;
- }
-}
-
-const ApiKeysModal: React.FC<ApiKeysModalProps> = ({ isOpen, onClose }) => {
- const [apiKeys, setApiKeys] = useState<ApiKeyConfig[]>(
- DEFAULT_PROVIDERS.map((p) => ({ ...p, value: '' }))
- );
- const [visibleKeys, setVisibleKeys] = useState<Record<string, boolean>>({});
- const [loadState, dispatchLoad] = useReducer(loadReducer, { status: 'loading' });
- const [saveState, dispatchSave] = useReducer(saveReducer, { status: 'idle' });
- const mountedRef = useRef(true);
-
- useEffect(() => {
- mountedRef.current = true;
- return () => { mountedRef.current = false; };
- }, []);
-
- // Load existing keys on mount
- useEffect(() => {
- if (isOpen) {
- loadApiKeys();
- }
- }, [isOpen]);
-
- const loadApiKeys = async () => {
- dispatchLoad({ type: 'LOAD_START' });
- // API keys are now managed in Settings > LLM Config
- dispatchLoad({ type: 'LOAD_SUCCESS' });
- };
-
- const handleKeyChange = (provider: string, value: string) => {
- setApiKeys((prev) =>
- prev.map((key) => (key.provider === provider ? { ...key, value } : key))
- );
- if (saveState.status === 'saved') {
- dispatchSave({ type: 'SAVE_RESET' });
- }
- };
-
- const toggleVisibility = (provider: string) => {
- setVisibleKeys((prev) => ({
- ...prev,
- [provider]: !prev[provider],
- }));
- };
-
- const handleSave = async () => {
- // 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';
- const isSaving = saveState.status === 'saving';
- const error = loadState.status === 'error' ? loadState.error : saveState.status === 'error' ? saveState.error : null;
- const success = saveState.status === 'saved';
-
- if (!isOpen) return null;
-
- return (
- <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50">
- <div className="bg-[#0F0F0F] rounded-lg border border-[#2A2A2A] w-full max-w-lg">
- {/* Header */}
- <div className="flex items-center justify-between px-6 py-4 border-b border-[#2A2A2A]">
- <div className="flex items-center gap-2">
- <Key className="w-5 h-5 text-[#FF8800]" />
- <h2 className="text-lg font-semibold text-white">API Keys</h2>
- </div>
- <button
- onClick={onClose}
- className="p-1 rounded hover:bg-[#2A2A2A] text-[#787878] hover:text-white"
- >
- <X className="w-5 h-5" />
- </button>
- </div>
-
- {/* Content */}
- <div className="p-6 space-y-4">
- {error && (
- <div className="flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm">
- <AlertCircle className="w-4 h-4 flex-shrink-0" />
- {error}
- </div>
- )}
-
- {success && (
- <div className="p-3 bg-green-500/10 border border-green-500/30 rounded-lg text-green-400 text-sm">
- API keys saved successfully
- </div>
- )}
-
- <p className="text-sm text-[#787878]">
- Configure API keys for LLM providers. Keys are stored securely and
- used for AI trading agents.
- </p>
-
- {isLoading ? (
- <div className="flex items-center justify-center py-8">
- <Loader2 className="w-6 h-6 animate-spin text-[#FF8800]" />
- </div>
- ) : (
- <div className="space-y-3">
- {apiKeys.map((key) => (
- <div key={key.provider}>
- <label className="block text-sm font-medium text-white mb-1">
- {key.label}
- </label>
- <div className="relative">
- <input
- type={visibleKeys[key.provider] ? 'text' : 'password'}
- value={key.value}
- onChange={(e) =>
- handleKeyChange(key.provider, e.target.value)
- }
- placeholder={key.placeholder}
- className="w-full px-3 py-2 pr-10 bg-[#1A1A1A] border border-[#2A2A2A] rounded-lg text-white placeholder-[#505050] focus:border-[#FF8800] focus:outline-none font-mono text-sm"
- />
- <button
- type="button"
- onClick={() => toggleVisibility(key.provider)}
- className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[#787878] hover:text-white"
- >
- {visibleKeys[key.provider] ? (
- <EyeOff className="w-4 h-4" />
- ) : (
- <Eye className="w-4 h-4" />
- )}
- </button>
- </div>
- <p className="text-xs text-[#505050] mt-1">{key.envVar}</p>
- </div>
- ))}
- </div>
- )}
- </div>
-
- {/* Footer */}
- <div className="flex justify-end gap-3 px-6 py-4 border-t border-[#2A2A2A]">
- <button
- onClick={onClose}
- className="px-4 py-2 rounded-lg border border-[#2A2A2A] text-[#787878] hover:bg-[#1A1A1A]"
- >
- Cancel
- </button>
- <button
- onClick={handleSave}
- disabled={isSaving}
- className="px-4 py-2 rounded-lg bg-[#FF8800] text-black font-medium hover:bg-[#FF9900] disabled:opacity-50 flex items-center gap-2"
- >
- {isSaving ? (
- <>
- <Loader2 className="w-4 h-4 animate-spin" />
- Saving...
- </>
- ) : (
- <>
- <Save className="w-4 h-4" />
- Save Keys
- </>
- )}
- </button>
- </div>
- </div>
- </div>
- );
-};
-
-export default withErrorBoundary(ApiKeysModal, { name: 'AlphaArena.ApiKeysModal' });
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 be1d7ae33..ae2fc65f3 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
@@ -21,6 +21,8 @@ import type {
SnapshotsResponse,
ListAgentsResponse,
ModelDecision,
+ CompetitionType,
+ PolymarketMarketInfo,
} from '../types';
// =============================================================================
@@ -519,6 +521,8 @@ export interface StoredCompetition {
mode: string;
cycle_interval_seconds: number;
exchange_id: string;
+ competition_type?: CompetitionType;
+ polymarket_markets?: PolymarketMarketInfo[];
};
status: string;
cycle_count: number;
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 743706ef6..ca3d73275 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
@@ -10,6 +10,12 @@ export type CompetitionStatus = 'created' | 'running' | 'paused' | 'completed' |
export type TradeAction = 'buy' | 'sell' | 'hold' | 'short';
export type ModelProvider = 'openai' | 'anthropic' | 'google' | 'deepseek' | 'groq' | 'openrouter' | 'ollama' | 'fincept';
+// Competition Type - crypto or prediction markets
+export type CompetitionType = 'crypto' | 'polymarket';
+
+// Polymarket-specific action types
+export type PolymarketAction = 'buy_yes' | 'buy_no' | 'sell_yes' | 'sell_no' | 'hold';
+
// Response Events
export type StreamResponseEvent =
| 'message_chunk'
@@ -157,6 +163,72 @@ export interface MarketData {
timestamp: string;
}
+// Polymarket-specific types
+export interface PolymarketMarketInfo {
+ id: string;
+ question: string;
+ description?: string;
+ outcomes: string[]; // e.g., ["Yes", "No"]
+ outcome_prices: number[]; // e.g., [0.65, 0.35]
+ token_ids: string[]; // CLOB token IDs for each outcome
+ volume: number;
+ liquidity: number;
+ end_date?: string;
+ image?: string;
+ category?: string;
+}
+
+export interface PolymarketPosition {
+ market_id: string;
+ market_question: string;
+ outcome: string; // "YES" or "NO"
+ shares: number;
+ avg_price: number;
+ current_price: number;
+ unrealized_pnl: number;
+ realized_pnl: number;
+ resolved: boolean;
+}
+
+export interface PolymarketPortfolioState {
+ model_name: string;
+ cash: number;
+ portfolio_value: number;
+ positions: Record<string, PolymarketPosition>; // keyed by market_id
+ total_pnl: number;
+ unrealized_pnl: number;
+ trades_count: number;
+}
+
+export interface PolymarketDecision {
+ competition_id: string;
+ model_name: string;
+ cycle_number: number;
+ market_id: string;
+ market_question: string;
+ action: PolymarketAction;
+ amount_usd: number;
+ confidence: number;
+ estimated_probability: number; // Agent's estimate of true probability
+ reasoning: string;
+ trade_executed?: PolymarketTradeResult;
+ timestamp: string;
+}
+
+export interface PolymarketTradeResult {
+ status: 'executed' | 'rejected' | 'partial';
+ action: PolymarketAction;
+ market_id: string;
+ outcome: string; // "YES" or "NO"
+ shares: number;
+ price: number;
+ cost?: number;
+ proceeds?: number;
+ pnl?: number;
+ reason?: string;
+ timestamp: string;
+}
+
export interface TradeResult {
status: 'executed' | 'rejected' | 'partial';
action: TradeAction;
@@ -211,6 +283,11 @@ export interface CompetitionConfig {
exchange_id: string;
max_cycles?: number;
custom_prompt?: string;
+ // Competition type - crypto or polymarket
+ competition_type?: CompetitionType;
+ // Polymarket-specific config
+ polymarket_markets?: PolymarketMarketInfo[];
+ polymarket_category?: string;
}
export interface Competition {
@@ -304,6 +381,11 @@ export interface CreateCompetitionRequest {
max_tokens: number;
system_prompt: string;
};
+ // Competition type - crypto or polymarket
+ competition_type?: CompetitionType;
+ // Polymarket-specific params
+ polymarket_market_ids?: string[];
+ polymarket_category?: string;
}
export interface CreateCompetitionResponse {
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/useAlphaArena.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/useAlphaArena.ts
index a3670e63e..0c3955358 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/useAlphaArena.ts
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/useAlphaArena.ts
@@ -8,7 +8,7 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { listen, UnlistenFn } from '@tauri-apps/api/event';
import { showConfirm } from '@/utils/notifications';
-import { sqliteService, type LLMGlobalSettings } from '@/services/core/sqliteService';
+import { sqliteService, buildApiKeysMap, type LLMGlobalSettings } from '@/services/core/sqliteService';
import { withTimeout } from '@/services/core/apiUtils';
import { validateString } from '@/services/core/validators';
import { useCache, cacheKey } from '@/hooks/useCache';
@@ -22,8 +22,11 @@ import type {
PerformanceSnapshot,
CompetitionMode,
AgentAdvancedConfig,
+ CompetitionType,
+ PolymarketMarketInfo,
} from './types';
import { DEFAULT_ADVANCED_CONFIG } from './types';
+import polymarketService from '@/services/polymarket/polymarketService';
// Extended model type for Alpha Arena with API key and advanced config
export interface AlphaArenaModel {
@@ -99,6 +102,19 @@ export function useAlphaArena() {
const [cycleInterval, setCycleInterval] = useState(150);
const [exchangeId, setExchangeId] = useState('kraken');
+ // Competition type state (crypto vs polymarket)
+ const [competitionType, setCompetitionType] = useState<CompetitionType>('crypto');
+
+ // Polymarket-specific state
+ const [availablePolymarkets, setAvailablePolymarkets] = useState<PolymarketMarketInfo[]>([]);
+ const [selectedPolymarkets, setSelectedPolymarkets] = useState<PolymarketMarketInfo[]>([]);
+ const [polymarketCategory, setPolymarketCategory] = useState<string>('');
+ const [polymarketPrices, setPolymarketPrices] = useState<Record<string, number>>({});
+ const [loadingPolymarkets, setLoadingPolymarkets] = useState(false);
+ const [polymarketSortBy, setPolymarketSortBy] = useState<'volume' | 'liquidity' | 'end_date' | 'spread'>('volume');
+ const [polymarketMinVolume, setPolymarketMinVolume] = useState(0);
+ const [polymarketMinLiquidity, setPolymarketMinLiquidity] = useState(0);
+
// Component mounted ref for async safety
const mountedRef = useRef(true);
@@ -248,6 +264,105 @@ export function useAlphaArena() {
return () => { window.removeEventListener('llm-config-changed', handler); };
}, [loadLLMConfigs]);
+ // ===========================================================================
+ // Polymarket Markets Loading
+ // ===========================================================================
+
+ const loadPolymarkets = useCallback(async () => {
+ if (competitionType !== 'polymarket') return;
+ setLoadingPolymarkets(true);
+ try {
+ const result = await withTimeout(
+ polymarketService.getMarkets({
+ active: true,
+ limit: 50,
+ tag_id: polymarketCategory || undefined,
+ }),
+ 15000
+ );
+ if (!mountedRef.current) return;
+
+ // Transform to PolymarketMarketInfo
+ let markets: PolymarketMarketInfo[] = (result || []).map((m: any) => {
+ let outcomes: string[] = [];
+ let outcomePrices: number[] = [];
+ let tokenIds: string[] = [];
+ try {
+ if (typeof m.outcomes === 'string') outcomes = JSON.parse(m.outcomes);
+ else if (Array.isArray(m.outcomes)) outcomes = m.outcomes;
+ } catch { /* ignore */ }
+ try {
+ if (typeof m.outcomePrices === 'string') outcomePrices = JSON.parse(m.outcomePrices).map(Number);
+ else if (Array.isArray(m.outcomePrices)) outcomePrices = m.outcomePrices.map(Number);
+ } catch { /* ignore */ }
+ try {
+ if (typeof m.clobTokenIds === 'string') tokenIds = JSON.parse(m.clobTokenIds);
+ else if (Array.isArray(m.clobTokenIds)) tokenIds = m.clobTokenIds;
+ } catch { /* ignore */ }
+
+ return {
+ id: m.id,
+ question: m.question,
+ description: m.description,
+ outcomes,
+ outcome_prices: outcomePrices,
+ token_ids: tokenIds,
+ volume: m.volumeNum ?? m.volume ?? 0,
+ liquidity: m.liquidityNum ?? m.liquidity ?? 0,
+ end_date: m.endDate,
+ image: m.image,
+ category: m.tags?.[0]?.label,
+ };
+ });
+
+ // Apply volume/liquidity filters
+ if (polymarketMinVolume > 0) {
+ markets = markets.filter(m => m.volume >= polymarketMinVolume);
+ }
+ if (polymarketMinLiquidity > 0) {
+ markets = markets.filter(m => m.liquidity >= polymarketMinLiquidity);
+ }
+
+ // Sort
+ markets.sort((a, b) => {
+ switch (polymarketSortBy) {
+ case 'volume': return b.volume - a.volume;
+ case 'liquidity': return b.liquidity - a.liquidity;
+ case 'end_date': {
+ if (!a.end_date) return 1;
+ if (!b.end_date) return -1;
+ return new Date(a.end_date).getTime() - new Date(b.end_date).getTime();
+ }
+ case 'spread': {
+ const spreadA = Math.abs(0.5 - (a.outcome_prices[0] || 0.5));
+ const spreadB = Math.abs(0.5 - (b.outcome_prices[0] || 0.5));
+ return spreadB - spreadA; // Highest spread first (most decisive markets)
+ }
+ default: return 0;
+ }
+ });
+
+ setAvailablePolymarkets(markets);
+ } catch (err) {
+ console.error('[AlphaArena] Failed to load Polymarket markets:', err);
+ if (mountedRef.current) setAvailablePolymarkets([]);
+ } finally {
+ if (mountedRef.current) setLoadingPolymarkets(false);
+ }
+ }, [competitionType, polymarketCategory, polymarketSortBy, polymarketMinVolume, polymarketMinLiquidity]);
+
+ useEffect(() => {
+ loadPolymarkets();
+ }, [loadPolymarkets]);
+
+ const togglePolymarketSelection = useCallback((market: PolymarketMarketInfo) => {
+ setSelectedPolymarkets(prev => {
+ const exists = prev.some(m => m.id === market.id);
+ if (exists) return prev.filter(m => m.id !== market.id);
+ return [...prev, market];
+ });
+ }, []);
+
// ===========================================================================
// Past Competitions (useCache)
// ===========================================================================
@@ -306,6 +421,14 @@ export function useAlphaArena() {
setExchangeId(comp.config.exchange_id);
}
+ // Restore competition type and polymarket markets if applicable
+ if (comp.config.competition_type) {
+ setCompetitionType(comp.config.competition_type);
+ }
+ if (comp.config.polymarket_markets && comp.config.polymarket_markets.length > 0) {
+ setSelectedPolymarkets(comp.config.polymarket_markets);
+ }
+
showSuccess(`Loaded competition: ${comp.config.competition_name}`);
} catch (err) {
if (!mountedRef.current) return;
@@ -451,6 +574,11 @@ export function useAlphaArena() {
setError('Cycle interval must be at least 10 seconds');
return;
}
+ // Polymarket validation
+ if (competitionType === 'polymarket' && selectedPolymarkets.length < 1) {
+ setError('Select at least 1 prediction market for Polymarket competition');
+ return;
+ }
setIsLoading(true);
setError(null);
@@ -469,16 +597,24 @@ export function useAlphaArena() {
trading_style: m.advancedConfig.trading_style || undefined,
advanced_config: m.advancedConfig,
})),
- symbols: [symbol],
+ symbols: competitionType === 'crypto' ? [symbol] : undefined,
initial_capital: initialCapital,
mode,
cycle_interval_seconds: cycleInterval,
- exchange_id: exchangeId,
+ exchange_id: competitionType === 'crypto' ? exchangeId : undefined,
llm_settings: {
temperature: llmGlobalSettings.temperature,
max_tokens: llmGlobalSettings.max_tokens,
system_prompt: llmGlobalSettings.system_prompt,
},
+ // Polymarket-specific params
+ competition_type: competitionType,
+ polymarket_market_ids: competitionType === 'polymarket'
+ ? selectedPolymarkets.map(m => m.id)
+ : undefined,
+ polymarket_category: competitionType === 'polymarket'
+ ? polymarketCategory || undefined
+ : undefined,
});
if (!mountedRef.current) return;
@@ -511,18 +647,7 @@ export function useAlphaArena() {
try {
const currentCompetitionId = competitionId;
- const currentModels = [...selectedModels];
- // Collect API keys — use model-specific key, keyed by "provider:model_id" to support
- // multiple models from the same provider with different keys
- const apiKeys: Record<string, string> = {};
- for (const model of currentModels) {
- if (model.api_key) {
- // Provider-level key (first one wins per provider for backend compatibility)
- if (!apiKeys[model.provider]) {
- apiKeys[model.provider] = model.api_key;
- }
- }
- }
+ const apiKeys = await buildApiKeysMap();
const result = await alphaArenaService.runCycle(currentCompetitionId, Object.keys(apiKeys).length > 0 ? apiKeys : undefined);
// If cancelled or unmounted while awaiting, discard results
@@ -643,14 +768,18 @@ export function useAlphaArena() {
};
}, []);
- // Real-time price streaming via Rust WebSocket — uses competition's configured exchange
- const tickerHook = useRustTicker(exchangeId, symbol, !!competitionId);
+ // Real-time price streaming via Rust WebSocket — uses competition's configured exchange (crypto only)
+ const tickerHook = useRustTicker(
+ exchangeId,
+ symbol,
+ !!competitionId && competitionType === 'crypto'
+ );
useEffect(() => {
- if (tickerHook.data && mountedRef.current) {
+ if (tickerHook.data && mountedRef.current && competitionType === 'crypto') {
setLatestPrice(tickerHook.data.price);
}
- }, [tickerHook.data]);
+ }, [tickerHook.data, competitionType]);
const toggleModelSelection = (model: AlphaArenaModel) => {
setSelectedModels(prev => {
@@ -720,6 +849,27 @@ export function useAlphaArena() {
exchangeId,
setExchangeId,
+ // Competition type (crypto vs polymarket)
+ competitionType,
+ setCompetitionType,
+
+ // Polymarket state
+ availablePolymarkets,
+ selectedPolymarkets,
+ setSelectedPolymarkets,
+ polymarketCategory,
+ setPolymarketCategory,
+ polymarketPrices,
+ loadingPolymarkets,
+ loadPolymarkets,
+ togglePolymarketSelection,
+ polymarketSortBy,
+ setPolymarketSortBy,
+ polymarketMinVolume,
+ setPolymarketMinVolume,
+ polymarketMinLiquidity,
+ setPolymarketMinLiquidity,
+
// Past competitions
pastCompetitions,
loadingPastCompetitions,
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 0103611eb..2bf979d27 100644
--- a/fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsx
@@ -60,7 +60,8 @@ interface SearchState {
// ─── Language Config (moved inside component to access theme colors) ────────────────
const DEFAULT_FINSCRIPT = `// FinScript - EMA/RSI Crossover Strategy
-// Data is generated synthetically for instant execution
+// Toggle LIVE DATA in toolbar to use real Yahoo Finance market data
+// In DEMO mode, synthetic data is generated for instant execution
// Calculate indicators on AAPL
ema_fast = ema(AAPL, 12)
@@ -125,6 +126,16 @@ export default function CodeEditorTab() {
const [activeFileId, setActiveFileId] = useState('1');
const [isRunning, setIsRunning] = useState(false);
const [finscriptResult, setFinscriptResult] = useState<FinScriptExecutionResult | null>(null);
+ const [useLiveData, setUseLiveData] = useState(false);
+ const [dateRange, setDateRange] = useState(() => {
+ const end = new Date();
+ const start = new Date();
+ start.setFullYear(start.getFullYear() - 1);
+ return {
+ startDate: start.toISOString().split('T')[0],
+ endDate: end.toISOString().split('T')[0],
+ };
+ });
const [showExplorer, setShowExplorer] = useState(true);
const [outputHeight, setOutputHeight] = useState(280);
const [isOutputMaximized, setIsOutputMaximized] = useState(false);
@@ -412,10 +423,29 @@ export default function CodeEditorTab() {
setShowOutput(true);
try {
- const result = await invoke<FinScriptExecutionResult>('execute_finscript', {
- code: activeFile.content
- });
+ let result: FinScriptExecutionResult;
+ if (useLiveData) {
+ result = await invoke<FinScriptExecutionResult>('execute_finscript_live', {
+ code: activeFile.content,
+ dataConfig: {
+ start_date: dateRange.startDate,
+ end_date: dateRange.endDate,
+ },
+ });
+ } else {
+ result = await invoke<FinScriptExecutionResult>('execute_finscript', {
+ code: activeFile.content,
+ });
+ }
setFinscriptResult(result);
+
+ // Process integration actions from FinScript
+ if (result.integration_actions && result.integration_actions.length > 0) {
+ for (const action of result.integration_actions) {
+ console.log(`[FinScript Integration] ${action.action_type}:`, action.payload);
+ }
+ }
+
setExecutionHistory(prev => [...prev.slice(-9), {
time: new Date().toLocaleTimeString(),
status: result.success ? 'success' : 'error',
@@ -428,6 +458,9 @@ export default function CodeEditorTab() {
signals: [],
plots: [],
errors: [String(error)],
+ alerts: [],
+ drawings: [],
+ integration_actions: [],
execution_time_ms: 0,
};
setFinscriptResult(errorResult);
@@ -638,8 +671,60 @@ export default function CodeEditorTab() {
}}
>
<Play size={11} fill={F.DARK_BG} />
- {isRunning ? t('toolbar.running') : t('toolbar.run')}
+ {isRunning ? (useLiveData ? 'FETCHING...' : t('toolbar.running')) : t('toolbar.run')}
</button>
+
+ <div style={{ width: '1px', height: '18px', backgroundColor: F.BORDER, margin: '0 4px' }} />
+
+ {/* Live Data Toggle */}
+ <button
+ onClick={() => setUseLiveData(!useLiveData)}
+ style={{
+ padding: '4px 10px', display: 'flex', alignItems: 'center', gap: '5px',
+ backgroundColor: useLiveData ? `${F.GREEN}18` : 'transparent',
+ border: `1px solid ${useLiveData ? F.GREEN : F.BORDER}`,
+ borderRadius: '2px',
+ color: useLiveData ? F.GREEN : F.GRAY,
+ fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px',
+ cursor: 'pointer', fontFamily: FONT, transition: 'all 0.2s',
+ }}
+ title={useLiveData ? 'Using real Yahoo Finance data' : 'Using synthetic demo data'}
+ >
+ <div style={{
+ width: 6, height: 6, borderRadius: '50%',
+ backgroundColor: useLiveData ? F.GREEN : F.GRAY,
+ }} />
+ {useLiveData ? 'LIVE' : 'DEMO'}
+ </button>
+
+ {/* Date Range (visible only in live mode) */}
+ {useLiveData && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <input
+ type="date"
+ value={dateRange.startDate}
+ onChange={(e) => setDateRange(d => ({ ...d, startDate: e.target.value }))}
+ style={{
+ padding: '3px 5px', backgroundColor: F.PANEL_BG,
+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',
+ color: F.GRAY, fontSize: '9px', fontFamily: FONT,
+ outline: 'none', colorScheme: 'dark',
+ }}
+ />
+ <span style={{ color: F.MUTED, fontSize: '9px', fontFamily: FONT }}>to</span>
+ <input
+ type="date"
+ value={dateRange.endDate}
+ onChange={(e) => setDateRange(d => ({ ...d, endDate: e.target.value }))}
+ style={{
+ padding: '3px 5px', backgroundColor: F.PANEL_BG,
+ border: `1px solid ${F.BORDER}`, borderRadius: '2px',
+ color: F.GRAY, fontSize: '9px', fontFamily: FONT,
+ outline: 'none', colorScheme: 'dark',
+ }}
+ />
+ </div>
+ )}
</div>
)}
</div>
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 2d8171728..141d06ff5 100644
--- a/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptOutputPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptOutputPanel.tsx
@@ -15,6 +15,11 @@ interface PlotPoint {
volume?: number;
}
+export interface IntegrationAction {
+ action_type: 'watchlist_add' | 'paper_trade' | 'alert_create' | 'screener_run' | string;
+ payload: Record<string, unknown>;
+}
+
export interface FinScriptExecutionResult {
success: boolean;
output: string;
@@ -31,6 +36,19 @@ export interface FinScriptExecutionResult {
color?: string;
}>;
errors: string[];
+ alerts?: Array<{
+ message: string;
+ alert_type: string;
+ timestamp: string;
+ }>;
+ drawings?: Array<{
+ drawing_type: string;
+ x1: number; y1: number;
+ x2: number; y2: number;
+ color: string; text: string;
+ style: string; width: number;
+ }>;
+ integration_actions?: IntegrationAction[];
execution_time_ms: number;
}
diff --git a/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptTooltip.tsx b/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptTooltip.tsx
index 68b516f69..fd14be43f 100644
--- a/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptTooltip.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptTooltip.tsx
@@ -268,6 +268,80 @@ export const FINSCRIPT_FUNCTIONS: Record<string, {
description: 'Print values to output console',
example: 'print "Price:", round(last(close(AAPL)), 2)'
},
+
+ // Risk & Portfolio Analytics
+ 'sharpe': {
+ signature: 'sharpe(series, rf_rate?)',
+ description: 'Annualized Sharpe ratio — measures risk-adjusted return',
+ params: ['series: Price or returns series', 'rf_rate: Risk-free rate (default 0.0)'],
+ returns: 'Number',
+ example: 'sr = sharpe(close(AAPL))\nprint "Sharpe:", round(sr, 3)'
+ },
+ 'sortino': {
+ signature: 'sortino(series, rf_rate?)',
+ description: 'Sortino ratio — like Sharpe but penalizes only downside volatility',
+ params: ['series: Price or returns series', 'rf_rate: Risk-free rate (default 0.0)'],
+ returns: 'Number',
+ example: 'so = sortino(close(AAPL))\nprint "Sortino:", round(so, 3)'
+ },
+ 'max_drawdown': {
+ signature: 'max_drawdown(series)',
+ description: 'Maximum drawdown — largest peak-to-trough decline (0 to 1)',
+ params: ['series: Price or equity series'],
+ returns: 'Number',
+ example: 'dd = max_drawdown(close(AAPL))\nprint "Max DD:", round(dd * 100, 2), "%"'
+ },
+ 'correlation': {
+ signature: 'correlation(series_a, series_b)',
+ description: 'Pearson correlation coefficient between two return series (-1 to 1)',
+ params: ['series_a: First price series', 'series_b: Second price series'],
+ returns: 'Number',
+ example: 'corr = correlation(close(AAPL), close(MSFT))\nprint "Correlation:", round(corr, 3)'
+ },
+ 'beta': {
+ signature: 'beta(asset, benchmark)',
+ description: 'Beta coefficient — sensitivity of asset returns to benchmark',
+ params: ['asset: Asset price series', 'benchmark: Benchmark price series (e.g., SPY)'],
+ returns: 'Number',
+ example: 'b = beta(close(AAPL), close(SPY))\nprint "Beta:", round(b, 3)'
+ },
+ 'returns': {
+ signature: 'returns(series)',
+ description: 'Daily returns series — percentage change between consecutive values',
+ params: ['series: Price series'],
+ returns: 'Series',
+ example: 'rets = returns(close(AAPL))\nprint "Last return:", round(last(rets) * 100, 2), "%"'
+ },
+
+ // Terminal Integration Functions
+ 'watchlist_add': {
+ signature: 'watchlist_add(symbol, name?)',
+ description: 'Add a symbol to the terminal watchlist',
+ params: ['symbol: Ticker symbol to add', 'name: Watchlist name (default "default")'],
+ returns: 'Bool',
+ example: 'if rsi_now < 30 {\n watchlist_add(AAPL, "Oversold")\n}'
+ },
+ 'paper_trade': {
+ signature: 'paper_trade(symbol, side, quantity, price?)',
+ description: 'Submit a paper trade order to the terminal',
+ params: ['symbol: Ticker symbol', 'side: "buy" or "sell"', 'quantity: Number of shares', 'price: Limit price (optional, uses market if omitted)'],
+ returns: 'Bool',
+ example: 'if crossover(ema(AAPL, 12), ema(AAPL, 26)) {\n paper_trade(AAPL, "buy", 100)\n}'
+ },
+ 'alert_create': {
+ signature: 'alert_create(message, type?)',
+ description: 'Create a persistent alert in the terminal notification system',
+ params: ['message: Alert message text', 'type: "info", "warning", or "critical" (default "info")'],
+ returns: 'Bool',
+ example: 'if rsi_now > 80 {\n alert_create("AAPL extremely overbought!", "warning")\n}'
+ },
+ 'screener_scan': {
+ signature: 'screener_scan(symbols)',
+ description: 'Queue a batch screener scan across multiple symbols',
+ params: ['symbols: Array of ticker symbols to scan'],
+ returns: 'Bool',
+ example: 'tickers = ["AAPL", "MSFT", "GOOGL", "TSLA"]\nscreener_scan(tickers)'
+ },
};
interface FinScriptTooltipProps {
diff --git a/fincept-terminal-desktop/src/components/tabs/code-editor/finscriptExamples.ts b/fincept-terminal-desktop/src/components/tabs/code-editor/finscriptExamples.ts
index 812fc322d..673f36b54 100644
--- a/fincept-terminal-desktop/src/components/tabs/code-editor/finscriptExamples.ts
+++ b/fincept-terminal-desktop/src/components/tabs/code-editor/finscriptExamples.ts
@@ -1103,6 +1103,304 @@ line_new(200, stop_loss, 250, stop_loss, "red", "dashed", 1)
line_new(200, take_profit, 250, take_profit, "green", "dashed", 1)
label_new(250, stop_loss, "SL", "red")
label_new(250, take_profit, "TP", "green")
+`,
+ },
+ {
+ id: 'ex_live_data',
+ name: '13_live_data.fincept',
+ category: 'Live Data',
+ description: 'Real market data analysis with Yahoo Finance',
+ content: `// ═══════════════════════════════════════════════════════════════
+// Live Data Analysis
+// Toggle LIVE mode in toolbar to use real Yahoo Finance data
+// ═══════════════════════════════════════════════════════════════
+
+// ─── Instructions ───────────────────────────────────────────
+// 1. Click "DEMO" button in toolbar to switch to "LIVE"
+// 2. Set date range (e.g., 2024-01-01 to 2025-01-01)
+// 3. Run script — real data will be fetched automatically
+
+// ─── Fetch Real OHLCV Data ─────────────────────────────────
+close_prices = close(AAPL)
+open_prices = open(AAPL)
+high_prices = high(AAPL)
+low_prices = low(AAPL)
+vol = volume(AAPL)
+
+print "=== AAPL Market Data ==="
+print "Data points:", len(close_prices)
+print "Latest close:", round(last(close_prices), 2)
+print "Latest open:", round(last(open_prices), 2)
+print "Latest high:", round(last(high_prices), 2)
+print "Latest low:", round(last(low_prices), 2)
+print "Latest volume:", last(vol)
+
+// ─── Technical Analysis on Real Data ────────────────────────
+sma_50 = sma(AAPL, 50)
+ema_20 = ema(AAPL, 20)
+rsi_14 = rsi(AAPL, 14)
+atr_14 = atr(AAPL, 14)
+bb_up = bollinger(AAPL, 20, 2)
+bb_low = bollinger_lower(AAPL, 20, 2)
+
+price = last(close_prices)
+rsi_now = last(rsi_14)
+
+print "\\n=== Technical Indicators ==="
+print "SMA(50):", round(last(sma_50), 2)
+print "EMA(20):", round(last(ema_20), 2)
+print "RSI(14):", round(rsi_now, 1)
+print "ATR(14):", round(last(atr_14), 2)
+print "BB Width:", round(last(bb_up) - last(bb_low), 2)
+
+// ─── Trend Assessment ──────────────────────────────────────
+above_sma = price > last(sma_50)
+ema_trend = last(ema(AAPL, 12)) > last(ema(AAPL, 26))
+
+print "\\n=== Trend Status ==="
+print "Price vs SMA(50):", above_sma ? "ABOVE" : "BELOW"
+print "EMA Trend:", ema_trend ? "BULLISH" : "BEARISH"
+print "RSI Zone:", rsi_now > 70 ? "OVERBOUGHT" : (rsi_now < 30 ? "OVERSOLD" : "NEUTRAL")
+
+// ─── Signal Generation ─────────────────────────────────────
+if ema_trend and rsi_now < 65 and above_sma {
+ buy "Bullish: EMA uptrend + RSI neutral + Above SMA50"
+}
+if not ema_trend and rsi_now > 35 and not above_sma {
+ sell "Bearish: EMA downtrend + Below SMA50"
+}
+
+// ─── Multi-Symbol Comparison ────────────────────────────────
+print "\\n=== Tech Sector RSI ==="
+print "AAPL:", round(last(rsi(AAPL, 14)), 1)
+print "MSFT:", round(last(rsi(MSFT, 14)), 1)
+print "GOOGL:", round(last(rsi(GOOGL, 14)), 1)
+
+// ─── Visualization ─────────────────────────────────────────
+plot_candlestick AAPL, "AAPL (Live Data)"
+plot_line sma_50, "SMA 50", "blue"
+plot_line ema_20, "EMA 20", "orange"
+plot_line bb_up, "BB Upper", "gray"
+plot_line bb_low, "BB Lower", "gray"
+plot rsi_14, "RSI (14)"
+hline 70, "Overbought", "red"
+hline 30, "Oversold", "green"
+`,
+ },
+ {
+ id: 'ex_risk_dashboard',
+ name: '14_risk_dashboard.fincept',
+ category: 'Risk Analytics',
+ description: 'Portfolio risk metrics: Sharpe, Sortino, drawdown, correlation',
+ content: `// ═══════════════════════════════════════════════════════════════
+// Risk Analytics Dashboard
+// Built-in functions: sharpe, sortino, max_drawdown, correlation, beta
+// ═══════════════════════════════════════════════════════════════
+
+// ─── Single Stock Risk Profile ─────────────────────────────
+print "=== AAPL Risk Profile ==="
+aapl = close(AAPL)
+
+sr = sharpe(aapl)
+so = sortino(aapl)
+dd = max_drawdown(aapl)
+
+print "Sharpe Ratio:", round(sr, 3)
+print "Sortino Ratio:", round(so, 3)
+print "Max Drawdown:", round(dd * 100, 2), "%"
+
+// Sharpe interpretation
+if sr > 2.0 {
+ print "Risk-Adjusted Return: EXCELLENT"
+} else if sr > 1.0 {
+ print "Risk-Adjusted Return: GOOD"
+} else if sr > 0.0 {
+ print "Risk-Adjusted Return: POSITIVE"
+} else {
+ print "Risk-Adjusted Return: NEGATIVE"
+}
+
+// ─── Multi-Asset Comparison ────────────────────────────────
+print "\\n=== Multi-Asset Risk Comparison ==="
+print "Ticker | Sharpe | Sortino | Max DD"
+print "─────────────────────────────────────"
+
+fn risk_report(ticker, name) {
+ prices = close(ticker)
+ s = sharpe(prices)
+ so_val = sortino(prices)
+ d = max_drawdown(prices)
+ print name, " |", round(s, 2), "|", round(so_val, 2), "|", round(d * 100, 1), "%"
+}
+
+risk_report(AAPL, "AAPL ")
+risk_report(MSFT, "MSFT ")
+risk_report(GOOGL, "GOOGL")
+
+// ─── Correlation Matrix ────────────────────────────────────
+print "\\n=== Correlation Matrix ==="
+corr_am = correlation(close(AAPL), close(MSFT))
+corr_ag = correlation(close(AAPL), close(GOOGL))
+corr_mg = correlation(close(MSFT), close(GOOGL))
+
+print "AAPL-MSFT:", round(corr_am, 3)
+print "AAPL-GOOGL:", round(corr_ag, 3)
+print "MSFT-GOOGL:", round(corr_mg, 3)
+
+// ─── Beta Analysis ─────────────────────────────────────────
+print "\\n=== Beta (vs SPY) ==="
+aapl_beta = beta(close(AAPL), close(SPY))
+msft_beta = beta(close(MSFT), close(SPY))
+googl_beta = beta(close(GOOGL), close(SPY))
+
+print "AAPL Beta:", round(aapl_beta, 3)
+print "MSFT Beta:", round(msft_beta, 3)
+print "GOOGL Beta:", round(googl_beta, 3)
+
+// Beta interpretation
+if aapl_beta > 1.0 {
+ print "AAPL is MORE volatile than the market"
+} else {
+ print "AAPL is LESS volatile than the market"
+}
+
+// ─── Daily Returns Analysis ────────────────────────────────
+print "\\n=== Returns Distribution ==="
+rets = returns(close(AAPL))
+print "Observations:", len(rets)
+print "Avg Daily Return:", round(avg(rets) * 100, 4), "%"
+print "Last Return:", round(last(rets) * 100, 4), "%"
+
+// ─── Custom Sharpe with Risk-Free Rate ─────────────────────
+print "\\n=== Sharpe with Risk-Free Rate ==="
+sr_0 = sharpe(close(AAPL), 0.0)
+sr_5 = sharpe(close(AAPL), 0.05)
+print "Sharpe (rf=0%):", round(sr_0, 3)
+print "Sharpe (rf=5%):", round(sr_5, 3)
+
+// ─── Visualization ─────────────────────────────────────────
+plot_candlestick AAPL, "AAPL Risk Dashboard"
+plot_line sma(AAPL, 50), "SMA 50", "blue"
+plot rsi(AAPL, 14), "RSI"
+hline 70, "OB", "red"
+hline 30, "OS", "green"
+`,
+ },
+ {
+ id: 'ex_terminal_integration',
+ name: '15_terminal_integration.fincept',
+ category: 'Terminal Integration',
+ description: 'Watchlist, paper trading, alerts, and screener',
+ content: `// ═══════════════════════════════════════════════════════════════
+// Terminal Integration
+// Connect FinScript outputs to terminal features:
+// watchlist_add, paper_trade, alert_create, screener_scan
+// ═══════════════════════════════════════════════════════════════
+
+// ─── Setup ─────────────────────────────────────────────────
+rsi_val = rsi(AAPL, 14)
+ema_12 = ema(AAPL, 12)
+ema_26 = ema(AAPL, 26)
+atr_val = atr(AAPL, 14)
+
+rsi_now = last(rsi_val)
+ema_f = last(ema_12)
+ema_s = last(ema_26)
+price = last(close(AAPL))
+atr_now = last(atr_val)
+
+print "=== AAPL Analysis ==="
+print "Price:", round(price, 2)
+print "RSI:", round(rsi_now, 1)
+print "EMA Trend:", ema_f > ema_s ? "BULLISH" : "BEARISH"
+print "ATR:", round(atr_now, 2)
+
+// ─── Watchlist Management ──────────────────────────────────
+// Add stocks to watchlists based on conditions
+if rsi_now < 35 {
+ watchlist_add(AAPL, "Oversold Picks")
+ print ">> Added AAPL to 'Oversold Picks' watchlist"
+}
+
+if rsi_now > 65 {
+ watchlist_add(AAPL, "Overbought Watch")
+ print ">> Added AAPL to 'Overbought Watch' watchlist"
+}
+
+if ema_f > ema_s {
+ watchlist_add(AAPL, "Uptrend Stocks")
+ print ">> Added AAPL to 'Uptrend Stocks' watchlist"
+}
+
+// ─── Paper Trading ─────────────────────────────────────────
+// Execute paper trades on strong signals
+// Position sizing based on ATR
+stop_distance = atr_now * 1.5
+position_size = round(2000 / stop_distance, 0) // Risk $2000 per trade
+
+print "\\n=== Trade Setup ==="
+print "Stop Distance:", round(stop_distance, 2)
+print "Position Size:", position_size, "shares"
+
+// Long entry conditions
+long_signal = ema_f > ema_s and rsi_now > 30 and rsi_now < 60
+// Short entry conditions
+short_signal = ema_f < ema_s and rsi_now < 70 and rsi_now > 40
+
+if long_signal {
+ paper_trade(AAPL, "buy", position_size)
+ print ">> Paper BUY", position_size, "shares of AAPL at", round(price, 2)
+ buy "EMA bullish + RSI neutral"
+}
+
+if short_signal {
+ paper_trade(AAPL, "sell", position_size)
+ print ">> Paper SELL", position_size, "shares of AAPL at", round(price, 2)
+ sell "EMA bearish + RSI neutral"
+}
+
+// ─── Alert System ──────────────────────────────────────────
+// Create persistent alerts for important conditions
+print "\\n=== Alert Checks ==="
+
+if rsi_now > 80 {
+ alert_create("AAPL RSI at " + str(round(rsi_now, 1)) + " - Extremely Overbought!", "critical")
+ print ">> CRITICAL alert created: Extreme overbought"
+}
+
+if rsi_now < 20 {
+ alert_create("AAPL RSI at " + str(round(rsi_now, 1)) + " - Extremely Oversold!", "critical")
+ print ">> CRITICAL alert created: Extreme oversold"
+}
+
+if crossover(ema_12, ema_26) {
+ alert_create("AAPL Golden Cross: EMA 12 crossed above EMA 26", "warning")
+ print ">> WARNING alert: Golden Cross detected"
+}
+
+if crossunder(ema_12, ema_26) {
+ alert_create("AAPL Death Cross: EMA 12 crossed below EMA 26", "warning")
+ print ">> WARNING alert: Death Cross detected"
+}
+
+// Informational alerts
+alert_create("AAPL daily scan complete. RSI: " + str(round(rsi_now, 1)), "info")
+
+// ─── Screener ──────────────────────────────────────────────
+// Scan multiple symbols with this script's logic
+print "\\n=== Screener ==="
+universe = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA", "META", "NVDA", "JPM"]
+screener_scan(universe)
+print "Queued screener scan for", len(universe), "symbols"
+
+// ─── Visualization ─────────────────────────────────────────
+plot_candlestick AAPL, "Terminal Integration Demo"
+plot_line ema_12, "EMA 12", "cyan"
+plot_line ema_26, "EMA 26", "orange"
+plot rsi_val, "RSI (14)"
+hline 70, "Overbought", "red"
+hline 30, "Oversold", "green"
+hline 50, "Midline", "gray"
`,
},
];
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 606149a5a..b09ef36bf 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
@@ -4,10 +4,12 @@ import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';
import { useTranslation } from 'react-i18next';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
-import { fetch as tauriFetch } from '@tauri-apps/plugin-http';
+import { websocketBridge } from '@/services/trading/websocketBridge';
import { useBrokerContext } from '@/contexts/BrokerContext';
import { useRustTicker, useRustOrderBook, useRustTrades } from '@/hooks/useRustWebSocket';
+import { useExchangeMarkets } from '@/hooks/useExchangeMarkets';
+import { useMemo } from 'react';
import { getMarketDataService } from '@/services/trading/UnifiedMarketDataService';
import { withTimeout } from '@/services/core/apiUtils';
import { sanitizeInput } from '@/services/core/validators';
@@ -43,7 +45,6 @@ import type { OrderRequest } from '@/types/trading';
// Constants
const API_TIMEOUT_MS = 30000;
-const WATCHLIST_REFRESH_MS = 30000;
const PAPER_TRADING_REFRESH_MS = 30000; // 30 second fallback sync (WebSocket handles real-time)
// State machine types
@@ -73,6 +74,7 @@ type CryptoAction =
| { type: 'SET_ORDERBOOK'; data: OrderBook; timestamp: number }
| { type: 'SET_TRADES'; data: TradeData[] }
| { type: 'SET_WATCHLIST_PRICES'; prices: Record<string, WatchlistPrice> }
+ | { type: 'UPDATE_WATCHLIST_PRICE'; symbol: string; price: number; change: number }
| { type: 'SET_PAPER_DATA'; positions: Position[]; orders: Order[]; trades: any[]; balance: number; equity: number; stats: any }
| { type: 'SET_SYMBOLS'; symbols: string[]; isLoading: boolean }
| { type: 'RESET_DATA' }
@@ -108,7 +110,15 @@ function cryptoReducer(state: CryptoState, action: CryptoAction): CryptoState {
case 'SET_TRADES':
return { ...state, tradesData: action.data };
case 'SET_WATCHLIST_PRICES':
- return { ...state, watchlistPrices: action.prices };
+ return { ...state, watchlistPrices: { ...state.watchlistPrices, ...action.prices } };
+ case 'UPDATE_WATCHLIST_PRICE':
+ return {
+ ...state,
+ watchlistPrices: {
+ ...state.watchlistPrices,
+ [action.symbol]: { price: action.price, change: action.change },
+ },
+ };
case 'SET_PAPER_DATA':
return {
...state,
@@ -191,7 +201,6 @@ export function CryptoTradingTab() {
// Refs for cleanup and race condition prevention
const mountedRef = useRef(true);
const fetchIdRef = useRef(0);
- const watchlistFetchIdRef = useRef(0);
const paperDataFetchIdRef = useRef(0);
// Main state reducer
@@ -227,8 +236,31 @@ export function CryptoTradingTab() {
const [makerFee, setMakerFee] = useState(0.0002);
const [takerFee, setTakerFee] = useState(0.0005);
- // Watchlist
- const [watchlist, setWatchlist] = useState<string[]>(DEFAULT_CRYPTO_WATCHLIST);
+ // Watchlist — derived dynamically from exchange markets via CCXT
+ const {
+ wsIdToUnified,
+ unifiedToWsId,
+ watchlistSymbols,
+ ready: marketsReady,
+ } = useExchangeMarkets(realAdapter);
+
+ // Fall back to hardcoded list until markets are loaded from exchange
+ const watchlist = marketsReady ? watchlistSymbols : DEFAULT_CRYPTO_WATCHLIST;
+
+ // Market precision/limits from CCXT for order validation
+ const marketLimits = useMemo(() => {
+ if (!realAdapter || !marketsReady) return null;
+ const markets = (realAdapter as any).getMarkets?.();
+ const market = markets?.[selectedSymbol];
+ if (!market) return null;
+ return {
+ amountPrecision: market.precision?.amount ?? 6,
+ pricePrecision: market.precision?.price ?? 2,
+ minAmount: market.limits?.amount?.min ?? 0,
+ maxAmount: market.limits?.amount?.max ?? null,
+ minCost: market.limits?.cost?.min ?? 0,
+ };
+ }, [realAdapter, selectedSymbol, marketsReady]);
// WebSocket provider initialization state
const [wsProvidersReady, setWsProvidersReady] = useState(false);
@@ -241,17 +273,42 @@ export function CryptoTradingTab() {
};
}, []);
- // Initialize WebSocket providers (Kraken & HyperLiquid)
+ // WebSocket URL mapping for all supported crypto exchanges
+ const WS_CONFIGS: Record<string, { url: string }> = {
+ kraken: { url: 'wss://ws.kraken.com/v2' },
+ hyperliquid: { url: 'wss://api.hyperliquid.xyz/ws' },
+ binance: { url: 'wss://stream.binance.com:9443/ws' },
+ binanceus: { url: 'wss://stream.binance.us:9443/ws' },
+ coinbase: { url: 'wss://ws-feed.exchange.coinbase.com' },
+ coinbasepro: { url: 'wss://ws-feed.exchange.coinbase.com' },
+ bitfinex: { url: 'wss://api-pub.bitfinex.com/ws/2' },
+ okx: { url: 'wss://ws.okx.com:8443/ws/v5/public' },
+ bybit: { url: 'wss://stream.bybit.com/v5/public/spot' },
+ kucoin: { url: 'wss://ws-api-spot.kucoin.com' },
+ gateio: { url: 'wss://api.gateio.ws/ws/v4/' },
+ huobi: { url: 'wss://api.huobi.pro/ws' },
+ mexc: { url: 'wss://wbs.mexc.com/ws' },
+ bitget: { url: 'wss://ws.bitget.com/v2/ws/public' },
+ };
+
+ // Initialize WebSocket config for the active broker
useEffect(() => {
- const initializeProviders = async () => {
- if (!mountedRef.current) return;
+ const initializeProvider = async () => {
+ if (!mountedRef.current || !activeBroker) return;
+
+ const wsConfig = WS_CONFIGS[activeBroker.toLowerCase()];
+ if (!wsConfig) {
+ console.warn(`[CryptoTrading] No WebSocket config for broker: ${activeBroker}`);
+ setWsProvidersReady(true); // Allow fallback behavior
+ return;
+ }
try {
await withTimeout(
invoke('ws_set_config', {
config: {
- name: 'kraken',
- url: 'wss://ws.kraken.com/v2',
+ name: activeBroker.toLowerCase(),
+ url: wsConfig.url,
enabled: true,
reconnect_delay_ms: 5000,
max_reconnect_attempts: 10,
@@ -259,41 +316,24 @@ export function CryptoTradingTab() {
}
}),
API_TIMEOUT_MS,
- 'Kraken WebSocket config timeout'
+ `${activeBroker} WebSocket config timeout`
);
- if (!mountedRef.current) return;
-
- await withTimeout(
- invoke('ws_set_config', {
- config: {
- name: 'hyperliquid',
- url: 'wss://api.hyperliquid.xyz/ws',
- enabled: true,
- reconnect_delay_ms: 5000,
- max_reconnect_attempts: 10,
- heartbeat_interval_ms: 30000,
- }
- }),
- API_TIMEOUT_MS,
- 'HyperLiquid WebSocket config timeout'
- );
- // Mark providers as ready after config is set
if (mountedRef.current) {
setWsProvidersReady(true);
}
} catch (err) {
- // WebSocket config errors are non-fatal, log for debugging
+ console.warn(`[CryptoTrading] WebSocket config warning for ${activeBroker}:`, err);
if (mountedRef.current) {
- console.warn('[CryptoTrading] WebSocket provider init warning:', err);
- // Still mark as ready to allow fallback behavior
- setWsProvidersReady(true);
+ setWsProvidersReady(true); // Still allow fallback
}
}
};
- initializeProviders();
- }, []);
+ // Reset ready state when broker changes, then reinitialize
+ setWsProvidersReady(false);
+ initializeProvider();
+ }, [activeBroker]);
// Update time
useEffect(() => {
@@ -303,75 +343,98 @@ export function CryptoTradingTab() {
return () => clearInterval(timer);
}, []);
- // Fetch watchlist prices via CoinGecko (fast, reliable, US-accessible)
- const fetchWatchlistPrices = useCallback(async () => {
- const currentFetchId = ++watchlistFetchIdRef.current;
-
- try {
- const symbolToCoinGeckoId: Record<string, string> = {
- 'BTC/USD': 'bitcoin', 'ETH/USD': 'ethereum', 'BNB/USD': 'binancecoin',
- 'SOL/USD': 'solana', 'XRP/USD': 'ripple', 'ADA/USD': 'cardano',
- 'DOGE/USD': 'dogecoin', 'AVAX/USD': 'avalanche-2', 'DOT/USD': 'polkadot',
- 'POL/USD': 'matic-network', 'LTC/USD': 'litecoin', 'SHIB/USD': 'shiba-inu',
- 'TRX/USD': 'tron', 'LINK/USD': 'chainlink', 'UNI/USD': 'uniswap',
- 'ATOM/USD': 'cosmos', 'XLM/USD': 'stellar', 'ETC/USD': 'ethereum-classic',
- 'BCH/USD': 'bitcoin-cash', 'NEAR/USD': 'near', 'APT/USD': 'aptos',
- 'ARB/USD': 'arbitrum', 'OP/USD': 'optimism', 'LDO/USD': 'lido-dao',
- 'FIL/USD': 'filecoin', 'ICP/USD': 'internet-computer', 'INJ/USD': 'injective-protocol',
- 'STX/USD': 'blockstack', 'MKR/USD': 'maker', 'AAVE/USD': 'aave',
- };
+ // Subscribe to all watchlist symbols on the active exchange via WebSocket.
+ // Uses CCXT wsId for subscription (exchange wire format) and wsIdToUnified for
+ // reverse-mapping incoming ticks back to the unified symbol (e.g. XBT/USD → BTC/USD).
+ useEffect(() => {
+ if (!activeBroker || !wsProvidersReady) return;
- const coinIds = watchlist
- .map(s => symbolToCoinGeckoId[s])
- .filter(Boolean)
- .join(',');
+ let mounted = true;
+ let unlistenTicker: (() => void) | null = null;
+
+ // Build a normalised-wsId → unified lookup for fast O(1) matching in the hot path.
+ // When markets aren't loaded yet (marketsReady=false), fall back to normalised
+ // unified-symbol matching (works for exchanges that use unified symbols on WS).
+ // Normalize helper: strips separators + maps exchange aliases (XBT→BTC, XDG→DOGE)
+ const normSym = (s: string) => s.replace(/XBT/g, 'BTC').replace(/XDG/g, 'DOGE').replace(/[/\-_]/g, '').toUpperCase();
+
+ const normWsIdToUnified = new Map<string, string>();
+ if (marketsReady && wsIdToUnified.size > 0) {
+ for (const [wsId, unified] of wsIdToUnified) {
+ normWsIdToUnified.set(normSym(wsId), unified);
+ }
+ } else {
+ // Fallback: normalised unified symbol maps to itself
+ for (const sym of watchlist) {
+ normWsIdToUnified.set(normSym(sym), sym);
+ }
+ }
- try {
- const response = await tauriFetch(
- `https://api.coingecko.com/api/v3/simple/price?ids=${coinIds}&vs_currencies=usd&include_24hr_change=true`
- );
+ // Normalize broker name to lowercase for consistent matching with Rust backend
+ const normalizedBroker = activeBroker.toLowerCase();
- if (!mountedRef.current || currentFetchId !== watchlistFetchIdRef.current) return;
+ const setup = async () => {
+ // Register listener FIRST so no ticks are missed while subscribing
+ unlistenTicker = await websocketBridge.onTicker((tickerData) => {
+ if (!mounted || tickerData.provider !== normalizedBroker) return;
+ if (tickerData.price <= 0) return;
- if (!response.ok) {
- throw new Error(`CoinGecko API returned ${response.status}`);
- }
+ const normalizedIncoming = normSym(tickerData.symbol);
+ const unified = normWsIdToUnified.get(normalizedIncoming);
+ if (!unified) return;
- const data = await response.json();
- const prices: Record<string, WatchlistPrice> = {};
- let hasValidData = false;
+ dispatch({
+ type: 'UPDATE_WATCHLIST_PRICE',
+ symbol: unified,
+ price: tickerData.price,
+ change: tickerData.change_percent ?? 0,
+ });
+ });
- watchlist.forEach(symbol => {
- const coinId = symbolToCoinGeckoId[symbol];
- const coinData = coinId && data[coinId];
+ // Subscribe using wsId (exchange wire format) when available, else unified symbol
+ await Promise.allSettled(
+ watchlist.map(unified => {
+ const wsId = unifiedToWsId.get(unified) ?? unified;
+ return websocketBridge.subscribe(normalizedBroker, wsId, 'ticker');
+ })
+ );
- if (coinData && coinData.usd > 0) {
- prices[symbol] = {
- price: coinData.usd,
- change: coinData.usd_24h_change || 0,
- };
- hasValidData = true;
+ // Seed watchlist prices immediately with REST snapshot (before WS ticks arrive)
+ if (realAdapter && marketsReady && typeof (realAdapter as any).fetchTickers === 'function') {
+ try {
+ const tickers = await withTimeout(
+ (realAdapter as any).fetchTickers(watchlist),
+ API_TIMEOUT_MS,
+ 'fetchTickers timeout'
+ );
+ if (!mounted) return;
+ // Batch all seed prices into a single dispatch to avoid N re-renders
+ const seedPrices: Record<string, { price: number; change: number }> = {};
+ for (const [sym, ticker] of Object.entries(tickers as Record<string, any>)) {
+ if (ticker?.last && ticker.last > 0) {
+ seedPrices[sym] = { price: ticker.last, change: ticker.percentage ?? 0 };
+ }
}
- });
-
- if (hasValidData && mountedRef.current && currentFetchId === watchlistFetchIdRef.current) {
- dispatch({ type: 'SET_WATCHLIST_PRICES', prices });
+ if (Object.keys(seedPrices).length > 0) {
+ dispatch({ type: 'SET_WATCHLIST_PRICES', prices: seedPrices });
+ }
+ } catch {
+ // fetchTickers seed is best-effort — WS will fill in shortly
}
- } catch (fetchErr) {
- if (!mountedRef.current || currentFetchId !== watchlistFetchIdRef.current) return;
- console.warn('[CryptoTrading] CoinGecko API fetch failed:', fetchErr);
}
- } catch (error) {
- if (!mountedRef.current || currentFetchId !== watchlistFetchIdRef.current) return;
- console.error('[CryptoTrading] Failed to fetch prices:', error);
- }
- }, [watchlist]);
+ };
- useEffect(() => {
- fetchWatchlistPrices();
- const interval = setInterval(fetchWatchlistPrices, WATCHLIST_REFRESH_MS);
- return () => clearInterval(interval);
- }, [fetchWatchlistPrices]);
+ setup();
+
+ return () => {
+ mounted = false;
+ if (unlistenTicker) unlistenTicker();
+ for (const unified of watchlist) {
+ const wsId = unifiedToWsId.get(unified) ?? unified;
+ websocketBridge.unsubscribe(normalizedBroker, wsId, 'ticker').catch((e) => console.warn('[CryptoTradingTab] watchlist unsubscribe error:', e));
+ }
+ };
+ }, [activeBroker, wsProvidersReady, watchlist, marketsReady, wsIdToUnified, unifiedToWsId]);
// Clear data when symbol changes
useEffect(() => {
@@ -390,22 +453,25 @@ export function CryptoTradingTab() {
// Subscribe to Rust WebSocket feeds (only after providers are configured)
const shouldConnectWs = !!activeBroker && wsProvidersReady;
+ // Convert unified symbol to exchange wire format (e.g. BTC/USD → XBT/USD on Kraken)
+ const selectedWsSymbol = (marketsReady ? unifiedToWsId.get(selectedSymbol) : undefined) ?? selectedSymbol;
+
const { data: tickerData, error: tickerError } = useRustTicker(
activeBroker || '',
- selectedSymbol,
+ selectedWsSymbol,
shouldConnectWs
);
const { data: orderbookData, error: orderbookError } = useRustOrderBook(
activeBroker || '',
- selectedSymbol,
+ selectedWsSymbol,
25,
shouldConnectWs
);
const { trades: tradesData, error: tradesError } = useRustTrades(
activeBroker || '',
- selectedSymbol,
+ selectedWsSymbol,
50,
shouldConnectWs
);
@@ -428,6 +494,7 @@ export function CryptoTradingTab() {
change: tickerData.change,
changePercent: tickerData.change_percent,
open: tickerData.open,
+ quoteVolume: tickerData.quote_volume,
}
});
@@ -593,6 +660,35 @@ export function CryptoTradingTab() {
}
}, [tradingMode, paperAdapter, activeBroker]);
+ // Live data loader — fetches balance, positions, open orders, and trade history from realAdapter
+ const loadLiveBalance = useCallback(async () => {
+ if (tradingMode !== 'live' || !realAdapter || !realAdapter.isConnected() || !mountedRef.current) return;
+ try {
+ const [balanceData, myTrades] = await Promise.allSettled([
+ withTimeout((realAdapter as any).fetchBalance(), API_TIMEOUT_MS, 'Fetch live balance timeout'),
+ withTimeout((realAdapter as any).fetchMyTrades(undefined, undefined, 50), API_TIMEOUT_MS, 'Fetch live trades timeout'),
+ ]);
+
+ if (!mountedRef.current) return;
+
+ const balance = balanceData.status === 'fulfilled' ? (balanceData.value as any) : null;
+ const usdBalance = balance ? (balance.free?.USD || balance.free?.USDT || 0) : state.balance;
+ const totalEquity = balance ? (balance.total?.USD || balance.total?.USDT || 0) : state.equity;
+ const trades = myTrades.status === 'fulfilled' ? (myTrades.value as any[]) : state.trades;
+
+ dispatch({ type: 'SET_PAPER_DATA', positions: state.positions, orders: state.orders, trades, balance: usdBalance, equity: totalEquity, stats: state.stats });
+ } catch {
+ // Silently fail — live data is best-effort
+ }
+ }, [tradingMode, realAdapter, state.positions, state.orders, state.trades, state.balance, state.equity, state.stats]);
+
+ useEffect(() => {
+ if (tradingMode !== 'live') return;
+ loadLiveBalance();
+ const interval = setInterval(loadLiveBalance, 30000);
+ return () => clearInterval(interval);
+ }, [tradingMode, loadLiveBalance]);
+
// Normalize symbol for comparison (removes slashes, dashes, converts to uppercase)
const normalizeSymbol = (symbol: string): string => {
return symbol.replace(/[/\-_]/g, '').toUpperCase();
@@ -659,6 +755,29 @@ export function CryptoTradingTab() {
}
}, [slippage, makerFee, takerFee, paperAdapter]);
+ // Load real trading fees from exchange when in live authenticated mode
+ useEffect(() => {
+ if (tradingMode !== 'live' || !realAdapter || !realAdapter.isAuthenticated?.() || !selectedSymbol) return;
+ let active = true;
+ const loadFees = async () => {
+ try {
+ const fee = await withTimeout(
+ (realAdapter as any).fetchTradingFee(selectedSymbol),
+ API_TIMEOUT_MS,
+ 'fetchTradingFee timeout'
+ );
+ if (!active || !fee) return;
+ const feeData = fee as any;
+ if (feeData.maker != null) setMakerFee(feeData.maker);
+ if (feeData.taker != null) setTakerFee(feeData.taker);
+ } catch {
+ // Best-effort — keep defaults on failure
+ }
+ };
+ loadFees();
+ return () => { active = false; };
+ }, [tradingMode, realAdapter, selectedSymbol]);
+
// Fetch markets with timeout
useEffect(() => {
const fetchMarkets = async () => {
@@ -880,6 +999,9 @@ export function CryptoTradingTab() {
isConnecting={isConnecting}
paperAdapter={paperAdapter}
realAdapter={realAdapter}
+ makerFee={makerFee}
+ takerFee={takerFee}
+ marketLimits={marketLimits}
onTradingModeChange={setTradingMode}
onOrderPlaced={loadPaperTradingData}
/>
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 7eec3339b..2784e71e0 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
@@ -11,6 +11,14 @@ interface Position {
currentPrice: number;
}
+interface MarketLimits {
+ amountPrecision: number; // decimal places for quantity
+ pricePrecision: number; // decimal places for price
+ minAmount: number; // minimum order quantity
+ maxAmount: number | null;
+ minCost: number; // minimum notional value
+}
+
interface CryptoOrderEntryProps {
selectedSymbol: string;
currentPrice: number;
@@ -22,6 +30,9 @@ interface CryptoOrderEntryProps {
isConnecting: boolean;
paperAdapter: any;
realAdapter: any;
+ makerFee?: number;
+ takerFee?: number;
+ marketLimits?: MarketLimits | null;
onTradingModeChange: (mode: 'paper' | 'live') => void;
onRetryConnection?: () => void;
onOrderPlaced?: () => void;
@@ -41,10 +52,18 @@ export function CryptoOrderEntry({
isConnecting,
paperAdapter,
realAdapter,
+ makerFee = 0.001,
+ takerFee = 0.001,
+ marketLimits = null,
onTradingModeChange,
onRetryConnection,
onOrderPlaced,
}: CryptoOrderEntryProps) {
+ // Precision helpers — use CCXT market data when available, sensible defaults otherwise
+ const amountDecimals = marketLimits?.amountPrecision ?? 6;
+ const priceDecimals = marketLimits?.pricePrecision ?? 2;
+ const minAmount = marketLimits?.minAmount ?? 0;
+ const minCost = marketLimits?.minCost ?? 0;
// Order state
const [side, setSide] = useState<OrderSide>('buy');
const [orderType, setOrderType] = useState<OrderType>('limit');
@@ -119,17 +138,27 @@ export function CryptoOrderEntry({
return num.toFixed(6);
};
- // Validation
+ // Effective fee: limit orders use makerFee, market/stop-limit use takerFee
+ const effectiveFee = orderType === 'limit' ? makerFee : takerFee;
+
+ // Validation — includes exchange-enforced limits from CCXT market data
const validation = useMemo(() => {
const errors: string[] = [];
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');
- // Include estimated fee (0.1%) in balance check
- const totalWithFees = total + (total * 0.001);
+ // Exchange minimum order size
+ if (quantityNum > 0 && minAmount > 0 && quantityNum < minAmount) {
+ errors.push(`Min order: ${minAmount} ${selectedSymbol.split('/')[0]}`);
+ }
+ // Exchange minimum notional value
+ if (total > 0 && minCost > 0 && total < minCost) {
+ errors.push(`Min order value: $${minCost}`);
+ }
+ const totalWithFees = total + (total * effectiveFee);
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]);
+ }, [quantityNum, priceNum, orderType, stopPrice, side, total, balance, effectiveFee, minAmount, minCost, selectedSymbol]);
// Handle percentage buttons
const handlePercentage = useCallback((percent: number) => {
@@ -140,18 +169,16 @@ export function CryptoOrderEntry({
if (effectivePrice <= 0 || balance <= 0) return;
const maxQty = balance / effectivePrice;
const qty = maxQty * percent;
- setQuantity(qty > 0 ? qty.toFixed(6) : '');
+ setQuantity(qty > 0 ? qty.toFixed(amountDecimals) : '');
} else {
// Sell/Short: percentage of current position holdings OR percentage of balance for new shorts
if (positionQuantity > 0 && positionSide === 'long') {
- // If we have a long position, sell percentage of that position
const qty = positionQuantity * percent;
- setQuantity(qty > 0 ? qty.toFixed(6) : '');
+ setQuantity(qty > 0 ? qty.toFixed(amountDecimals) : '');
} else if (effectivePrice > 0 && balance > 0) {
- // No position or short position - calculate short size based on available margin
const maxQty = balance / effectivePrice;
const qty = maxQty * percent;
- setQuantity(qty > 0 ? qty.toFixed(6) : '');
+ setQuantity(qty > 0 ? qty.toFixed(amountDecimals) : '');
}
}
}, [balance, currentPrice, priceNum, side, positionQuantity, positionSide]);
@@ -174,12 +201,16 @@ export function CryptoOrderEntry({
if (orderType === 'stop-limit' && parsedStopPrice) params.stopPrice = parsedStopPrice;
if (typeof adapter.createOrder === 'function') {
+ // Apply exchange precision before submitting — prevents exchange rejections
+ const preciseAmount = parseFloat(quantityNum.toFixed(amountDecimals));
+ const precisePrice = priceNum > 0 ? parseFloat(priceNum.toFixed(priceDecimals)) : undefined;
+
await adapter.createOrder(
selectedSymbol,
orderType,
side,
- quantityNum,
- orderType !== 'market' ? priceNum : undefined,
+ preciseAmount,
+ orderType !== 'market' ? precisePrice : undefined,
Object.keys(params).length > 0 ? params : undefined
);
}
@@ -539,6 +570,16 @@ export function CryptoOrderEntry({
border: `1px solid ${FINCEPT.BORDER}`,
marginBottom: '12px',
}}>
+ {/* Market limits info row */}
+ {marketLimits && (
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
+ <span style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>Min order</span>
+ <span style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>
+ {minAmount > 0 ? `${minAmount} ${selectedSymbol.split('/')[0]}` : '—'}
+ {minCost > 0 ? ` / $${minCost}` : ''}
+ </span>
+ </div>
+ )}
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
<span style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>Order Value</span>
<span style={{ color: FINCEPT.WHITE, fontSize: '12px', fontWeight: 600 }}>
@@ -546,16 +587,16 @@ export function CryptoOrderEntry({
</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
- <span style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>Est. Fee (0.1%)</span>
+ <span style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>Est. Fee ({(effectiveFee * 100).toFixed(2)}%)</span>
<span style={{ color: FINCEPT.GRAY, fontSize: '11px' }}>
- ${formatNum(total * 0.001)}
+ ${formatNum(total * effectiveFee)}
</span>
</div>
<div style={{ height: '1px', background: FINCEPT.BORDER, margin: '8px 0' }} />
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>Total</span>
<span style={{ color: FINCEPT.YELLOW, fontSize: '14px', fontWeight: 700, fontFamily: '"IBM Plex Mono", monospace' }}>
- ${formatNum(total + (total * 0.001))}
+ ${formatNum(total + (total * effectiveFee))}
</span>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoSettingsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoSettingsPanel.tsx
index 11375370a..8d9af1370 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoSettingsPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoSettingsPanel.tsx
@@ -39,20 +39,6 @@ export function CryptoSettingsPanel({
}
};
- const handleMakerFeeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const value = parseFloat(e.target.value);
- if (!isNaN(value) && value >= 0 && value <= 1) {
- onMakerFeeChange(value);
- }
- };
-
- const handleTakerFeeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const value = parseFloat(e.target.value);
- if (!isNaN(value) && value >= 0 && value <= 1) {
- onTakerFeeChange(value);
- }
- };
-
const handleResetPortfolio = () => {
if (onResetPortfolio && window.confirm('Are you sure you want to reset your paper trading portfolio? This will clear all positions, orders, and trade history.')) {
onResetPortfolio();
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 5be68bc3a..33670e4f6 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
@@ -65,7 +65,8 @@ export function CryptoTickerBar({
if (changeRef.current && tickerData) {
const arrow = priceChange >= 0 ? '▲' : '▼';
const sign = priceChange >= 0 ? '+' : '';
- changeRef.current.innerHTML = `<span style="color: ${priceChange >= 0 ? FINCEPT.GREEN : FINCEPT.RED}">${arrow} ${sign}${priceChange.toFixed(2)} (${sign}${priceChangePercent.toFixed(2)}%)</span>`;
+ changeRef.current.textContent = `${arrow} ${sign}${priceChange.toFixed(2)} (${sign}${priceChangePercent.toFixed(2)}%)`;
+ changeRef.current.style.color = priceChange >= 0 ? FINCEPT.GREEN : FINCEPT.RED;
}
// Update bid/ask
@@ -178,7 +179,9 @@ export function CryptoTickerBar({
fontSize: '11px',
backgroundColor: symbol === selectedSymbol ? `${FINCEPT.ORANGE}20` : 'transparent',
color: symbol === selectedSymbol ? FINCEPT.ORANGE : FINCEPT.WHITE,
- borderLeft: symbol === selectedSymbol ? `3px solid ${FINCEPT.ORANGE}` : 'none'
+ borderLeftWidth: '3px',
+ borderLeftStyle: 'solid',
+ borderLeftColor: symbol === selectedSymbol ? FINCEPT.ORANGE : 'transparent'
}}
onMouseEnter={(e) => {
if (symbol !== selectedSymbol) {
@@ -252,7 +255,7 @@ export function CryptoTickerBar({
</div>
<div>
<div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>EQUITY</div>
- <div style={{ color: FINCEPT.YELLOW, fontWeight: 600 }}>${equity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
+ <div style={{ color: FINCEPT.YELLOW, fontWeight: 600 }}>{equity > 0 ? `$${equity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : '--'}</div>
</div>
</div>
</>
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx
index b9389c6e4..62e579b03 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx
@@ -267,7 +267,9 @@ export function CryptoTopNav({
cursor: 'pointer',
fontSize: '11px',
backgroundColor: activeBroker === broker.id ? `${FINCEPT.ORANGE}15` : 'transparent',
- borderLeft: activeBroker === broker.id ? `3px solid ${FINCEPT.ORANGE}` : '3px solid transparent',
+ borderLeftWidth: '3px',
+ borderLeftStyle: 'solid',
+ borderLeftColor: activeBroker === broker.id ? FINCEPT.ORANGE : 'transparent',
transition: 'all 0.15s',
}}
onMouseEnter={(e) => {
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 651535b93..c1bd9efd0 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
@@ -85,7 +85,9 @@ export function CryptoWatchlist({
padding: '8px 10px',
cursor: 'pointer',
borderBottom: `1px solid ${FINCEPT.BORDER}20`,
- borderLeft: isSelected ? `3px solid ${FINCEPT.ORANGE}` : '3px solid transparent',
+ borderLeftWidth: '3px',
+ borderLeftStyle: 'solid',
+ borderLeftColor: isSelected ? FINCEPT.ORANGE : 'transparent',
backgroundColor: isSelected ? `${FINCEPT.ORANGE}10` : 'transparent',
transition: 'all 0.15s',
}}
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/constants.ts b/fincept-terminal-desktop/src/components/tabs/crypto-trading/constants.ts
index 2df0dc727..15a36cf3f 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/constants.ts
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/constants.ts
@@ -17,14 +17,15 @@ export const FINCEPT = {
MUTED: '#4A4A4A'
} as const;
-// Top 30 most traded crypto pairs
+// Top crypto pairs available on Kraken
+// Removed: BNB, POL, SHIB, TRX, APT, ARB, OP, LDO, STX (not listed on Kraken)
export const DEFAULT_CRYPTO_WATCHLIST = [
- 'BTC/USD', 'ETH/USD', 'BNB/USD', 'SOL/USD', 'XRP/USD',
- 'ADA/USD', 'DOGE/USD', 'AVAX/USD', 'DOT/USD', 'POL/USD',
- 'LTC/USD', 'SHIB/USD', 'TRX/USD', 'LINK/USD', 'UNI/USD',
- 'ATOM/USD', 'XLM/USD', 'ETC/USD', 'BCH/USD', 'NEAR/USD',
- 'APT/USD', 'ARB/USD', 'OP/USD', 'LDO/USD', 'FIL/USD',
- 'ICP/USD', 'INJ/USD', 'STX/USD', 'MKR/USD', 'AAVE/USD'
+ 'BTC/USD', 'ETH/USD', 'SOL/USD', 'XRP/USD', 'ADA/USD',
+ 'DOGE/USD', 'AVAX/USD', 'DOT/USD', 'LTC/USD', 'LINK/USD',
+ 'UNI/USD', 'ATOM/USD', 'XLM/USD', 'ETC/USD', 'BCH/USD',
+ 'NEAR/USD', 'FIL/USD', 'ICP/USD', 'INJ/USD', 'MKR/USD',
+ 'AAVE/USD', 'PEPE/USD', 'WIF/USD', 'BONK/USD', 'JUP/USD',
+ 'SUI/USD', 'TIA/USD', 'SEI/USD', 'RENDER/USD', 'TAO/USD'
];
// CSS styles for the crypto trading terminal
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 70846c2f0..d6482c02a 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/types.ts
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/types.ts
@@ -46,7 +46,7 @@ export interface TickerData {
change?: number;
changePercent?: number;
open?: number;
- quoteVolume?: number;
+ quoteVolume?: number; // USD-denominated 24h volume (e.g. Binance "q" field)
}
export interface TradeData {
diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/EconomicCalendarWidget.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/EconomicCalendarWidget.tsx
index 0e4efea6c..7a2bd9d20 100644
--- a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/EconomicCalendarWidget.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/EconomicCalendarWidget.tsx
@@ -81,7 +81,7 @@ export const EconomicCalendarWidget: React.FC<EconomicCalendarWidgetProps> = ({
// Call backend API via Tauri with API key
const response = await fetch(
- `https://finceptbackend.share.zrok.io/macro/economic-calendar?country=${country}&limit=${limit}`,
+ `https://api.fincept.in/macro/economic-calendar?country=${country}&limit=${limit}`,
{
method: 'GET',
headers: {
diff --git a/fincept-terminal-desktop/src/components/tabs/docs/content/finscriptLanguage.ts b/fincept-terminal-desktop/src/components/tabs/docs/content/finscriptLanguage.ts
index fe56032fc..22afb6c5d 100644
--- a/fincept-terminal-desktop/src/components/tabs/docs/content/finscriptLanguage.ts
+++ b/fincept-terminal-desktop/src/components/tabs/docs/content/finscriptLanguage.ts
@@ -14,21 +14,25 @@ export const finscriptLanguageDoc: DocSection = {
**Key Features:**
• Pine Script-inspired syntax — familiar to traders
• 30+ built-in technical indicators (EMA, SMA, RSI, MACD, Bollinger, ATR, etc.)
-• Deterministic OHLCV data generation for instant backtesting
+• Live market data from Yahoo Finance or demo mode with synthetic data
+• Risk analytics: Sharpe, Sortino, max drawdown, correlation, beta
+• Terminal integration: watchlist, paper trading, alerts, screener
• Candlestick and line chart visualization
• Buy/Sell signal generation with strategy mode
• User-defined functions, structs, maps, and matrices
• For/while loops, if/else, switch, ternary operator
• Alerts and alert conditions
+• Batch execution for multi-symbol screening
• Print debugging with formatted output
-• Zero external dependencies — pure Rust execution
+• Zero external dependencies — compiled Rust library
**Architecture:**
• Lexer tokenizes source code into tokens
• Recursive descent parser produces an AST
• Tree-walking interpreter evaluates the program
-• Results returned as JSON (signals, plots, output, alerts)
-• Standalone CLI binary — no Python or network required
+• Results returned as JSON (signals, plots, output, alerts, integration actions)
+• Linked as a Rust library into the Tauri app for native performance
+• Live mode fetches real OHLCV data via Yahoo Finance
**File Extension:** \`.fincept\``,
codeExample: `// Your first FinScript program
@@ -695,8 +699,8 @@ print "AAPL-MSFT corr:", matrix_get(corr, 0, 1)`
**Ticker Symbols:**
• Any ALL-UPPERCASE identifier is treated as a ticker symbol
• Examples: \`AAPL\`, \`MSFT\`, \`GOOGL\`, \`TSLA\`, \`SPY\`
-• Data is automatically generated (deterministic random walk)
-• 180 days of daily OHLCV data per symbol
+• Demo mode: synthetic data (deterministic random walk, 180 days)
+• Live mode: real historical data from Yahoo Finance (configurable date range)
**request.security():**
• \`request.security(SYMBOL)\` — Fetch close data for another symbol
@@ -805,6 +809,206 @@ label_new(200, 170.0, "Resistance", "red")
// Box for price zone
box_new(50, 148.0, 200, 152.0, "blue", "rgba(0,0,255,0.1)", 1)`
+ },
+ {
+ id: 'fs-live-data',
+ title: 'Live Market Data',
+ content: `FinScript supports both demo mode (synthetic data) and live mode (real market data from Yahoo Finance). Toggle between modes using the LIVE/DEMO button in the toolbar.
+
+**Demo Mode (Default):**
+• Uses deterministic synthetic OHLCV data
+• Instant execution — no network required
+• 180 days of generated daily data per symbol
+• Great for learning and prototyping strategies
+
+**Live Mode:**
+• Fetches real historical OHLCV data from Yahoo Finance
+• Configure date range with start and end date pickers
+• Symbols are auto-detected from your code
+• Slightly slower due to data fetching
+• Requires internet connection
+
+**How to Use:**
+1. Click the "DEMO" button in the toolbar to switch to "LIVE"
+2. Set your desired date range (defaults to last 1 year)
+3. Run your script — real data will be fetched for all referenced symbols
+4. The green dot indicator shows when live mode is active
+
+**Batch / Screener Mode:**
+• Use \`screener_scan(symbols)\` to run your script across multiple symbols
+• Each symbol is executed independently with its own data
+• Results are collected and displayed together
+
+**Notes:**
+• Symbol names must be valid Yahoo Finance tickers (e.g., AAPL, MSFT, BTC-USD)
+• Date format: YYYY-MM-DD
+• If a symbol fails to fetch, an error is returned for that symbol only`,
+ codeExample: `// This script works in both DEMO and LIVE mode
+// In LIVE mode, real Yahoo Finance data is used
+// Toggle the LIVE/DEMO button in the toolbar
+
+close_prices = close(AAPL)
+sma_20 = sma(AAPL, 20)
+ema_12 = ema(AAPL, 12)
+rsi_14 = rsi(AAPL, 14)
+
+print "Data points:", len(close_prices)
+print "Latest close:", round(last(close_prices), 2)
+print "SMA(20):", round(last(sma_20), 2)
+print "RSI(14):", round(last(rsi_14), 1)
+
+// Multi-symbol analysis (each symbol's data is fetched)
+aapl_rsi = last(rsi(AAPL, 14))
+msft_rsi = last(rsi(MSFT, 14))
+spy_rsi = last(rsi(SPY, 14))
+
+print "AAPL RSI:", round(aapl_rsi, 1)
+print "MSFT RSI:", round(msft_rsi, 1)
+print "SPY RSI:", round(spy_rsi, 1)
+
+plot_candlestick AAPL, "AAPL (Live Data)"
+plot_line sma_20, "SMA 20", "blue"
+plot_line ema_12, "EMA 12", "orange"`
+ },
+ {
+ id: 'fs-risk-analytics',
+ title: 'Risk & Portfolio Analytics',
+ content: `FinScript includes built-in risk analytics functions for portfolio analysis. These operate on price or return series and produce key performance metrics.
+
+**Risk Metrics:**
+• \`sharpe(series, rf_rate?)\` — Annualized Sharpe ratio (risk-adjusted return)
+• \`sortino(series, rf_rate?)\` — Sortino ratio (penalizes only downside volatility)
+• \`max_drawdown(series)\` — Maximum peak-to-trough decline (0 to 1)
+
+**Correlation & Beta:**
+• \`correlation(series_a, series_b)\` — Pearson correlation of daily returns (-1 to 1)
+• \`beta(asset, benchmark)\` — Beta coefficient (sensitivity to benchmark)
+
+**Returns:**
+• \`returns(series)\` — Computes daily returns series (percentage changes)
+
+**Parameters:**
+• \`rf_rate\` — Annual risk-free rate (default 0.0). Use 0.05 for 5%.
+• All functions accept price Series (close prices). Returns are computed internally.
+
+**Interpretation:**
+• Sharpe > 1.0 = good, > 2.0 = very good, > 3.0 = excellent
+• Sortino is preferred when returns are asymmetric
+• Max drawdown of 0.20 means the asset dropped 20% from peak
+• Beta > 1 = more volatile than benchmark, < 1 = less volatile
+• Correlation near 1 = assets move together, near -1 = inversely`,
+ codeExample: `// Risk analytics for a single stock
+prices = close(AAPL)
+sr = sharpe(prices)
+so = sortino(prices)
+dd = max_drawdown(prices)
+
+print "=== AAPL Risk Profile ==="
+print "Sharpe Ratio:", round(sr, 3)
+print "Sortino Ratio:", round(so, 3)
+print "Max Drawdown:", round(dd * 100, 2), "%"
+
+// Compare two assets
+corr = correlation(close(AAPL), close(MSFT))
+b = beta(close(AAPL), close(SPY))
+
+print "\\n=== Relative Metrics ==="
+print "AAPL-MSFT Correlation:", round(corr, 3)
+print "AAPL Beta (vs SPY):", round(b, 3)
+
+// Analyze daily returns
+rets = returns(close(AAPL))
+print "\\n=== Returns ==="
+print "Return observations:", len(rets)
+print "Last daily return:", round(last(rets) * 100, 4), "%"
+print "Avg daily return:", round(avg(rets) * 100, 4), "%"
+
+// Risk-adjusted comparison
+print "\\n=== Comparison ==="
+print "AAPL Sharpe:", round(sharpe(close(AAPL)), 3)
+print "MSFT Sharpe:", round(sharpe(close(MSFT)), 3)
+print "GOOGL Sharpe:", round(sharpe(close(GOOGL)), 3)
+
+plot_candlestick AAPL, "AAPL Risk Analysis"`
+ },
+ {
+ id: 'fs-terminal-integration',
+ title: 'Terminal Integration',
+ content: `FinScript can interact with the Fincept Terminal through integration functions. These queue actions that are processed by the terminal after script execution.
+
+**Watchlist:**
+• \`watchlist_add(symbol, name?)\` — Add a symbol to a terminal watchlist
+• \`name\` is optional (defaults to "default")
+• Returns \`true\` on success
+
+**Paper Trading:**
+• \`paper_trade(symbol, side, quantity, price?)\` — Submit a paper trade order
+• \`side\`: "buy" or "sell"
+• \`price\` is optional (market order if omitted)
+• Returns \`true\` on success
+
+**Alerts:**
+• \`alert_create(message, type?)\` — Create a persistent terminal alert
+• Types: "info" (default), "warning", "critical"
+• Different from \`alert()\` — these persist in the notification panel
+
+**Screener:**
+• \`screener_scan(symbols)\` — Run the current script across multiple symbols
+• Accepts an array of ticker symbol strings
+• Results collected per-symbol
+
+**How It Works:**
+1. Integration functions queue actions during script execution
+2. After the script finishes, the terminal processes all queued actions
+3. Actions are dispatched to the appropriate terminal subsystem
+4. The output panel shows a summary of actions taken
+
+**Use Cases:**
+• Auto-add oversold stocks to a watchlist for monitoring
+• Execute paper trades when strategy conditions are met
+• Create alerts for important market conditions
+• Screen a universe of stocks with custom criteria`,
+ codeExample: `// Terminal integration workflow
+// This script analyzes AAPL and takes actions
+
+rsi_now = last(rsi(AAPL, 14))
+ema_f = last(ema(AAPL, 12))
+ema_s = last(ema(AAPL, 26))
+price = last(close(AAPL))
+
+print "=== Signal Analysis ==="
+print "Price:", round(price, 2)
+print "RSI:", round(rsi_now, 1)
+print "Trend:", ema_f > ema_s ? "UP" : "DOWN"
+
+// Add to watchlist if interesting
+if rsi_now < 35 {
+ watchlist_add(AAPL, "Oversold")
+ print "Added AAPL to Oversold watchlist"
+}
+
+// Paper trade on strong signal
+if ema_f > ema_s and rsi_now < 65 {
+ paper_trade(AAPL, "buy", 50)
+ print "Paper buy 50 shares of AAPL"
+}
+
+// Create alert for extreme conditions
+if rsi_now > 80 {
+ alert_create("AAPL RSI extremely overbought!", "warning")
+}
+if rsi_now < 20 {
+ alert_create("AAPL RSI extremely oversold!", "critical")
+}
+
+// Screen multiple symbols
+tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"]
+screener_scan(tickers)
+
+plot_candlestick AAPL, "Terminal Integration Demo"
+plot rsi(AAPL, 14), "RSI"
+hline 70, "OB", "red"
+hline 30, "OS", "green"`
},
{
id: 'fs-imports',
@@ -845,7 +1049,7 @@ fn calculate_sharpe(returns, risk_free) {
return (avg_ret - risk_free) / std_ret
}
-fn max_drawdown(equity_curve) {
+fn calc_max_drawdown(equity_curve) {
peak = first(equity_curve)
max_dd = 0
for val in equity_curve {
@@ -861,7 +1065,7 @@ fn max_drawdown(equity_curve) {
}
export calculate_sharpe
-export max_drawdown
+export calc_max_drawdown
// Use the functions
returns = [0.02, -0.01, 0.03, 0.01, -0.02, 0.04]
@@ -869,8 +1073,11 @@ sharpe = calculate_sharpe(returns, 0.005)
print "Sharpe:", round(sharpe, 3)
equity = [100000, 102000, 101500, 104000, 103000, 106000]
-dd = max_drawdown(equity)
-print "Max Drawdown:", round(dd * 100, 2), "%"`
+dd = calc_max_drawdown(equity)
+print "Max Drawdown:", round(dd * 100, 2), "%"
+
+// Note: FinScript also has a built-in max_drawdown(series)
+// that works directly on price Series data`
},
{
id: 'fs-complete-example',
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/hooks/useEconomicsData.ts b/fincept-terminal-desktop/src/components/tabs/economics/hooks/useEconomicsData.ts
index c206f7537..d9c9a3d90 100644
--- a/fincept-terminal-desktop/src/components/tabs/economics/hooks/useEconomicsData.ts
+++ b/fincept-terminal-desktop/src/components/tabs/economics/hooks/useEconomicsData.ts
@@ -163,7 +163,7 @@ export function useEconomicsData(): UseEconomicsDataReturn {
setFinceptCeicIndicator('');
try {
const res = await fetch(
- `https://finceptbackend.share.zrok.io/macro/ceic/series/indicators?country=${encodeURIComponent(countrySlug)}`,
+ `https://api.fincept.in/macro/ceic/series/indicators?country=${encodeURIComponent(countrySlug)}`,
{ headers: { 'X-API-Key': 'fk_user_vU20qwUxKtPmg0fWpriNBhcAnBVGgOtJxsKiiwfD9Qo' } }
);
const parsed = await res.json();
@@ -439,7 +439,7 @@ export function useEconomicsData(): UseEconomicsDataReturn {
break;
case 'fincept': {
- const BASE_URL = 'https://finceptbackend.share.zrok.io';
+ const BASE_URL = 'https://api.fincept.in';
const FINCEPT_API_KEY = 'fk_user_vU20qwUxKtPmg0fWpriNBhcAnBVGgOtJxsKiiwfD9Qo';
let url = '';
switch (selectedIndicator) {
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useSymbolSearch.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useSymbolSearch.ts
index e88aeeafe..8b1939418 100644
--- a/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useSymbolSearch.ts
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useSymbolSearch.ts
@@ -25,7 +25,7 @@ export function useSymbolSearch(): UseSymbolSearchReturn {
// HTTP Symbol Search function
const searchSymbolsHttp = async (query: string) => {
try {
- const response = await fetch(`https://finceptbackend.share.zrok.io/search/symbols?query=${encodeURIComponent(query)}&limit=50`);
+ const response = await fetch(`https://api.fincept.in/search/symbols?query=${encodeURIComponent(query)}&limit=50`);
if (response.ok) {
const data = await response.json();
console.log('[Search] HTTP results:', data);
diff --git a/fincept-terminal-desktop/src/components/tabs/login-audit/LoginAuditDashboard.tsx b/fincept-terminal-desktop/src/components/tabs/login-audit/LoginAuditDashboard.tsx
deleted file mode 100644
index 29b14d67f..000000000
--- a/fincept-terminal-desktop/src/components/tabs/login-audit/LoginAuditDashboard.tsx
+++ /dev/null
@@ -1,604 +0,0 @@
-/**
- * Login Audit Dashboard
- * ======================
- * Admin dashboard for monitoring user login activity and security events.
- *
- * Features:
- * - Real-time login activity feed
- * - Security alerts (brute force, suspicious IPs)
- * - DAU/MAU metrics
- * - Geographic distribution
- * - Failed login analysis
- */
-
-import React, { useState, useEffect } from 'react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { useAuth } from '@/contexts/AuthContext';
-import { useTranslation } from 'react-i18next';
-import { APP_VERSION } from '@/constants/version';
-import { useTimezone } from '@/contexts/TimezoneContext';
-
-// Types
-interface LoginEvent {
- logId: string;
- userId: string | null;
- email?: string;
- eventType: 'LOGIN_SUCCESS' | 'LOGIN_FAILURE' | 'LOGOUT' | 'SUSPICIOUS_BLOCK';
- timestamp: string;
- ipAddress: string;
- geoCountry?: string;
- geoCity?: string;
- deviceId?: string;
- userAgent?: string;
- clientVersion?: string;
- metadata?: Record<string, unknown>;
-}
-
-interface SecurityAlert {
- id: string;
- type: 'brute_force' | 'impossible_travel' | 'credential_stuffing' | 'suspicious_device';
- severity: 'low' | 'medium' | 'high' | 'critical';
- description: string;
- ipAddress?: string;
- userId?: string;
- timestamp: string;
- details: Record<string, unknown>;
-}
-
-interface MetricsSummary {
- dauToday: number;
- dauYesterday: number;
- mauCurrent: number;
- loginSuccessRate: number;
- failedAttemptsLast24h: number;
- activeSessionsCount: number;
- uniqueIpsToday: number;
-}
-
-// Mock data for demo (replace with API calls)
-const mockLoginEvents: LoginEvent[] = [
- {
- logId: '1',
- userId: 'user-123',
- email: '[email protected]',
- eventType: 'LOGIN_SUCCESS',
- timestamp: new Date().toISOString(),
- ipAddress: '192.168.1.1',
- geoCountry: 'US',
- geoCity: 'New York',
- clientVersion: APP_VERSION,
- },
- {
- logId: '2',
- userId: null,
- email: '[email protected]',
- eventType: 'LOGIN_FAILURE',
- timestamp: new Date(Date.now() - 5 * 60000).toISOString(),
- ipAddress: '10.0.0.5',
- geoCountry: 'CN',
- metadata: { failure_reason: 'bad_password' },
- },
-];
-
-const mockAlerts: SecurityAlert[] = [
- {
- id: 'alert-1',
- type: 'brute_force',
- severity: 'high',
- description: '12 failed attempts from IP 10.0.0.5 in 10 minutes',
- ipAddress: '10.0.0.5',
- timestamp: new Date(Date.now() - 2 * 60000).toISOString(),
- details: { attempts: 12, duration_minutes: 10 },
- },
-];
-
-const mockMetrics: MetricsSummary = {
- dauToday: 1247,
- dauYesterday: 1189,
- mauCurrent: 8432,
- loginSuccessRate: 94.7,
- failedAttemptsLast24h: 342,
- activeSessionsCount: 567,
- uniqueIpsToday: 892,
-};
-
-type DashboardView = 'overview' | 'events' | 'alerts' | 'analytics';
-
-const LoginAuditDashboard: React.FC = () => {
- const { t } = useTranslation('loginAudit');
- const { colors } = useTerminalTheme();
- const { session } = useAuth();
- const { timezone, formatTime } = useTimezone();
- const [currentView, setCurrentView] = useState<DashboardView>('overview');
- const [loginEvents, setLoginEvents] = useState<LoginEvent[]>(mockLoginEvents);
- const [alerts, setAlerts] = useState<SecurityAlert[]>(mockAlerts);
- const [metrics, setMetrics] = useState<MetricsSummary>(mockMetrics);
- const [loading, setLoading] = useState(false);
- const [autoRefresh, setAutoRefresh] = useState(true);
- const [currentTime, setCurrentTime] = useState(new Date());
-
- // Auto-refresh timer
- useEffect(() => {
- const timer = setInterval(() => setCurrentTime(new Date()), 1000);
- return () => clearInterval(timer);
- }, []);
-
- // Auto-refresh data
- useEffect(() => {
- if (!autoRefresh) return;
- const interval = setInterval(() => {
- // In production, fetch from API
- console.log('Auto-refreshing dashboard data...');
- }, 30000);
- return () => clearInterval(interval);
- }, [autoRefresh]);
-
- const formatTimestamp = (ts: string) => {
- const date = new Date(ts);
- return date.toLocaleTimeString('en-US', { hour12: false });
- };
-
- const formatDate = (ts: string) => {
- return new Date(ts).toLocaleDateString('en-US', {
- month: 'short',
- day: 'numeric',
- hour: '2-digit',
- minute: '2-digit',
- });
- };
-
- const getEventColor = (eventType: string) => {
- switch (eventType) {
- case 'LOGIN_SUCCESS': return colors.secondary;
- case 'LOGIN_FAILURE': return colors.alert;
- case 'LOGOUT': return colors.textMuted;
- case 'SUSPICIOUS_BLOCK': return colors.warning;
- default: return colors.text;
- }
- };
-
- const getSeverityColor = (severity: string) => {
- switch (severity) {
- case 'critical': return '#FF0000';
- case 'high': return colors.alert;
- case 'medium': return colors.warning;
- case 'low': return colors.info;
- default: return colors.textMuted;
- }
- };
-
- const renderMetricCard = (label: string, value: string | number, change?: number, color?: string) => (
- <div style={{
- backgroundColor: colors.panel,
- border: `1px solid ${colors.textMuted}`,
- padding: '8px',
- flex: 1,
- minWidth: '120px',
- }}>
- <div style={{ color: colors.textMuted, fontSize: '11px', marginBottom: '4px' }}>{label}</div>
- <div style={{ color: color || colors.text, fontSize: '18px', fontWeight: 'bold' }}>{value}</div>
- {change !== undefined && (
- <div style={{
- color: change >= 0 ? colors.secondary : colors.alert,
- fontSize: '11px',
- marginTop: '2px'
- }}>
- {change >= 0 ? '↑' : '↓'} {Math.abs(change).toFixed(1)}%
- </div>
- )}
- </div>
- );
-
- const renderOverview = () => {
- const dauChange = ((metrics.dauToday - metrics.dauYesterday) / metrics.dauYesterday) * 100;
-
- return (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', height: '100%' }}>
- {/* Metrics Row */}
- <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
- {renderMetricCard(t('metrics.dauToday'), metrics.dauToday.toLocaleString(), dauChange, colors.accent)}
- {renderMetricCard(t('metrics.mau'), metrics.mauCurrent.toLocaleString())}
- {renderMetricCard(t('metrics.successRate'), `${metrics.loginSuccessRate}%`, undefined, colors.secondary)}
- {renderMetricCard(t('metrics.failed24h'), metrics.failedAttemptsLast24h.toLocaleString(), undefined, colors.alert)}
- {renderMetricCard(t('metrics.activeSessions'), metrics.activeSessionsCount.toLocaleString())}
- {renderMetricCard(t('metrics.uniqueIps'), metrics.uniqueIpsToday.toLocaleString())}
- </div>
-
- <div style={{ display: 'flex', gap: '4px', flex: 1 }}>
- {/* Recent Activity */}
- <div style={{ flex: 2, backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '8px', overflow: 'auto' }}>
- <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
- {t('activity.recentLoginActivity')}
- </div>
- {loginEvents.slice(0, 10).map((event, idx) => (
- <div key={event.logId} style={{
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- padding: '4px',
- backgroundColor: idx % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- borderLeft: `2px solid ${getEventColor(event.eventType)}`,
- marginBottom: '2px',
- fontSize: '11px',
- }}>
- <span style={{ color: colors.textMuted, width: '60px' }}>{formatTimestamp(event.timestamp)}</span>
- <span style={{
- color: getEventColor(event.eventType),
- width: '80px',
- fontWeight: 'bold'
- }}>
- {event.eventType.replace('LOGIN_', '')}
- </span>
- <span style={{ color: colors.text, flex: 1 }}>{event.email || 'Unknown'}</span>
- <span style={{ color: colors.textMuted }}>{event.ipAddress}</span>
- <span style={{ color: colors.info, width: '30px' }}>{event.geoCountry || '??'}</span>
- </div>
- ))}
- </div>
-
- {/* Alerts Panel */}
- <div style={{ flex: 1, backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '8px', overflow: 'auto' }}>
- <div style={{ color: colors.alert, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
- [WARN]️ {t('activity.securityAlerts')} ({alerts.length})
- </div>
- {alerts.length === 0 ? (
- <div style={{ color: colors.secondary, fontSize: '11px' }}>[OK] {t('activity.noActiveAlerts')}</div>
- ) : (
- alerts.map((alert) => (
- <div key={alert.id} style={{
- backgroundColor: 'rgba(255,0,0,0.05)',
- border: `1px solid ${getSeverityColor(alert.severity)}`,
- padding: '6px',
- marginBottom: '4px',
- fontSize: '11px',
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
- <span style={{ color: getSeverityColor(alert.severity), fontWeight: 'bold', textTransform: 'uppercase' }}>
- {alert.severity}
- </span>
- <span style={{ color: colors.textMuted }}>{formatTimestamp(alert.timestamp)}</span>
- </div>
- <div style={{ color: colors.text, marginBottom: '2px' }}>{alert.description}</div>
- {alert.ipAddress && (
- <div style={{ color: colors.textMuted }}>IP: {alert.ipAddress}</div>
- )}
- </div>
- ))
- )}
- </div>
- </div>
- </div>
- );
- };
-
- const renderEvents = () => (
- <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '8px', height: '100%', overflow: 'auto' }}>
- <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
- {t('activity.loginEventLog')}
- </div>
- <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '11px' }}>
- <thead>
- <tr style={{ borderBottom: `1px solid ${colors.textMuted}` }}>
- <th style={{ textAlign: 'left', padding: '4px', color: colors.textMuted }}>Time</th>
- <th style={{ textAlign: 'left', padding: '4px', color: colors.textMuted }}>Event</th>
- <th style={{ textAlign: 'left', padding: '4px', color: colors.textMuted }}>User</th>
- <th style={{ textAlign: 'left', padding: '4px', color: colors.textMuted }}>IP Address</th>
- <th style={{ textAlign: 'left', padding: '4px', color: colors.textMuted }}>Location</th>
- <th style={{ textAlign: 'left', padding: '4px', color: colors.textMuted }}>Device</th>
- <th style={{ textAlign: 'left', padding: '4px', color: colors.textMuted }}>Details</th>
- </tr>
- </thead>
- <tbody>
- {loginEvents.map((event, idx) => (
- <tr key={event.logId} style={{
- backgroundColor: idx % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- borderLeft: `2px solid ${getEventColor(event.eventType)}`,
- }}>
- <td style={{ padding: '4px', color: colors.textMuted }}>{formatDate(event.timestamp)}</td>
- <td style={{ padding: '4px', color: getEventColor(event.eventType), fontWeight: 'bold' }}>
- {event.eventType}
- </td>
- <td style={{ padding: '4px', color: colors.text }}>{event.email || event.userId || '-'}</td>
- <td style={{ padding: '4px', color: colors.accent }}>{event.ipAddress}</td>
- <td style={{ padding: '4px', color: colors.info }}>
- {event.geoCity ? `${event.geoCity}, ${event.geoCountry}` : event.geoCountry || '-'}
- </td>
- <td style={{ padding: '4px', color: colors.textMuted }}>{event.deviceId?.substring(0, 12) || '-'}</td>
- <td style={{ padding: '4px', color: colors.textMuted }}>
- {event.metadata?.failure_reason as string || '-'}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- );
-
- const renderAlerts = () => (
- <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '8px', height: '100%', overflow: 'auto' }}>
- <div style={{ color: colors.alert, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
- SECURITY ALERTS & INCIDENTS
- </div>
- {alerts.length === 0 ? (
- <div style={{
- textAlign: 'center',
- padding: '40px',
- color: colors.secondary
- }}>
- <div style={{ fontSize: '24px', marginBottom: '8px' }}>[OK]</div>
- <div>No security alerts at this time</div>
- </div>
- ) : (
- alerts.map((alert) => (
- <div key={alert.id} style={{
- backgroundColor: 'rgba(255,0,0,0.05)',
- border: `1px solid ${getSeverityColor(alert.severity)}`,
- padding: '12px',
- marginBottom: '8px',
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
- <span style={{
- color: getSeverityColor(alert.severity),
- fontWeight: 'bold',
- textTransform: 'uppercase',
- fontSize: '12px'
- }}>
- [{alert.severity}] {alert.type.replace('_', ' ')}
- </span>
- <span style={{ color: colors.textMuted, fontSize: '11px' }}>{formatDate(alert.timestamp)}</span>
- </div>
- <div style={{ color: colors.text, fontSize: '12px', marginBottom: '8px' }}>{alert.description}</div>
- <div style={{ display: 'flex', gap: '16px', fontSize: '11px' }}>
- {alert.ipAddress && (
- <div><span style={{ color: colors.textMuted }}>IP:</span> <span style={{ color: colors.accent }}>{alert.ipAddress}</span></div>
- )}
- {alert.userId && (
- <div><span style={{ color: colors.textMuted }}>User:</span> <span style={{ color: colors.text }}>{alert.userId}</span></div>
- )}
- </div>
- <div style={{ marginTop: '8px', display: 'flex', gap: '4px' }}>
- <button style={{
- padding: '4px 8px',
- backgroundColor: colors.secondary,
- border: 'none',
- color: colors.background,
- fontSize: '10px',
- cursor: 'pointer',
- }}>
- DISMISS
- </button>
- <button style={{
- padding: '4px 8px',
- backgroundColor: colors.alert,
- border: 'none',
- color: '#fff',
- fontSize: '10px',
- cursor: 'pointer',
- }}>
- BLOCK IP
- </button>
- <button style={{
- padding: '4px 8px',
- backgroundColor: colors.background,
- border: `1px solid ${colors.textMuted}`,
- color: colors.text,
- fontSize: '10px',
- cursor: 'pointer',
- }}>
- INVESTIGATE
- </button>
- </div>
- </div>
- ))
- )}
- </div>
- );
-
- const renderAnalytics = () => (
- <div style={{ display: 'flex', gap: '8px', height: '100%' }}>
- {/* Country breakdown */}
- <div style={{ flex: 1, backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '8px', overflow: 'auto' }}>
- <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
- LOGINS BY COUNTRY (30 days)
- </div>
- {[
- { country: 'US', count: 4521, pct: 35.2 },
- { country: 'IN', count: 2103, pct: 16.4 },
- { country: 'GB', count: 1842, pct: 14.3 },
- { country: 'DE', count: 1205, pct: 9.4 },
- { country: 'JP', count: 987, pct: 7.7 },
- ].map((item, idx) => (
- <div key={idx} style={{ marginBottom: '8px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '2px' }}>
- <span style={{ color: colors.text }}>{item.country}</span>
- <span style={{ color: colors.textMuted }}>{item.count.toLocaleString()} ({item.pct}%)</span>
- </div>
- <div style={{ backgroundColor: colors.background, height: '8px' }}>
- <div style={{
- width: `${item.pct}%`,
- height: '100%',
- backgroundColor: colors.primary,
- }} />
- </div>
- </div>
- ))}
- </div>
-
- {/* Failure reasons */}
- <div style={{ flex: 1, backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '8px', overflow: 'auto' }}>
- <div style={{ color: colors.alert, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
- FAILURE REASONS (24h)
- </div>
- {[
- { reason: 'bad_password', count: 187, pct: 54.7 },
- { reason: 'user_not_found', count: 78, pct: 22.8 },
- { reason: 'account_locked', count: 45, pct: 13.2 },
- { reason: 'mfa_failed', count: 32, pct: 9.3 },
- ].map((item, idx) => (
- <div key={idx} style={{
- display: 'flex',
- justifyContent: 'space-between',
- padding: '4px',
- backgroundColor: idx % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- fontSize: '11px',
- }}>
- <span style={{ color: colors.text }}>{item.reason}</span>
- <span style={{ color: colors.alert }}>{item.count} ({item.pct}%)</span>
- </div>
- ))}
- </div>
-
- {/* Hourly distribution */}
- <div style={{ flex: 1, backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '8px', overflow: 'auto' }}>
- <div style={{ color: colors.info, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
- PEAK HOURS ({timezone.shortLabel})
- </div>
- {[
- { hour: '09:00', logins: 342 },
- { hour: '14:00', logins: 298 },
- { hour: '10:00', logins: 276 },
- { hour: '15:00', logins: 254 },
- { hour: '08:00', logins: 231 },
- ].map((item, idx) => (
- <div key={idx} style={{
- display: 'flex',
- justifyContent: 'space-between',
- padding: '4px',
- backgroundColor: idx % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- fontSize: '11px',
- }}>
- <span style={{ color: colors.textMuted }}>{item.hour}</span>
- <span style={{ color: colors.info }}>{item.logins} logins</span>
- </div>
- ))}
- </div>
- </div>
- );
-
- // Check admin access
- const isAdmin = session?.user_info?.account_type === 'admin' ||
- (session?.user_info as any)?.role === 'admin';
-
- if (!isAdmin) {
- return (
- <div style={{
- height: '100%',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- backgroundColor: colors.background,
- color: colors.alert,
- }}>
- <div style={{ textAlign: 'center' }}>
- <div style={{ fontSize: '24px', marginBottom: '8px' }}>🔒</div>
- <div>Admin access required to view Login Audit Dashboard</div>
- </div>
- </div>
- );
- }
-
- return (
- <div style={{ height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: colors.background, overflow: 'hidden' }}>
- {/* Header */}
- <div style={{ backgroundColor: colors.panel, borderBottom: `1px solid ${colors.textMuted}`, padding: '4px 8px', flexShrink: 0 }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px' }}>
- <span style={{ color: colors.primary, fontWeight: 'bold' }}>🔐 {t('title')}</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.text }}>
- {formatTime(currentTime, {
- year: 'numeric', month: '2-digit', day: '2-digit',
- hour: '2-digit', minute: '2-digit', second: '2-digit'
- })} {timezone.shortLabel}
- </span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.textMuted }}>Alerts:</span>
- <span style={{ color: alerts.length > 0 ? colors.alert : colors.secondary, fontWeight: 'bold' }}>
- {alerts.length}
- </span>
- <div style={{ marginLeft: 'auto', display: 'flex', gap: '8px', alignItems: 'center' }}>
- <label style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '11px', color: colors.textMuted }}>
- <input
- type="checkbox"
- checked={autoRefresh}
- onChange={(e) => setAutoRefresh(e.target.checked)}
- />
- {t('controls.autoRefresh')}
- </label>
- <button
- onClick={() => setLoading(true)}
- disabled={loading}
- style={{
- padding: '2px 8px',
- backgroundColor: colors.primary,
- color: colors.background,
- border: 'none',
- fontSize: '11px',
- cursor: loading ? 'not-allowed' : 'pointer',
- fontWeight: 'bold',
- }}
- >
- {loading ? t('controls.loading') : '↻ ' + t('controls.refresh')}
- </button>
- </div>
- </div>
- </div>
-
- {/* Navigation */}
- <div style={{ backgroundColor: colors.panel, borderBottom: `1px solid ${colors.textMuted}`, padding: '2px 4px', flexShrink: 0 }}>
- <div style={{ display: 'flex', gap: '2px' }}>
- {[
- { key: 'overview', label: t('views.overview') },
- { key: 'events', label: t('views.eventLog') },
- { key: 'alerts', label: t('views.alerts') },
- { key: 'analytics', label: t('views.analytics') },
- ].map((item) => (
- <button
- key={item.key}
- onClick={() => setCurrentView(item.key as DashboardView)}
- style={{
- backgroundColor: currentView === item.key ? colors.primary : colors.background,
- border: `1px solid ${colors.textMuted}`,
- color: currentView === item.key ? colors.background : colors.text,
- padding: '4px 12px',
- fontSize: '11px',
- fontWeight: currentView === item.key ? 'bold' : 'normal',
- cursor: 'pointer',
- }}
- >
- {item.label}
- </button>
- ))}
- </div>
- </div>
-
- {/* Main Content */}
- <div style={{ flex: 1, overflow: 'auto', padding: '8px', backgroundColor: '#050505' }}>
- {currentView === 'overview' && renderOverview()}
- {currentView === 'events' && renderEvents()}
- {currentView === 'alerts' && renderAlerts()}
- {currentView === 'analytics' && renderAnalytics()}
- </div>
-
- {/* Status Bar */}
- <div style={{
- borderTop: `1px solid ${colors.textMuted}`,
- backgroundColor: colors.panel,
- padding: '2px 8px',
- fontSize: '11px',
- color: colors.textMuted,
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span>Admin: {session?.user_info?.email || 'Unknown'}</span>
- <span>
- DAU: {metrics.dauToday} |
- Active Sessions: {metrics.activeSessionsCount} |
- Status: {loading ? 'UPDATING' : 'READY'}
- </span>
- </div>
- </div>
- </div>
- );
-};
-
-export default LoginAuditDashboard;
diff --git a/fincept-terminal-desktop/src/components/tabs/login-audit/index.ts b/fincept-terminal-desktop/src/components/tabs/login-audit/index.ts
deleted file mode 100644
index 22a584f67..000000000
--- a/fincept-terminal-desktop/src/components/tabs/login-audit/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { default } from "./LoginAuditDashboard";
-export { default as LoginAuditDashboard } from "./LoginAuditDashboard";
diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/DealDatabase.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/DealDatabase.tsx
index 3467729ae..135aa3dc2 100644
--- a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/DealDatabase.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/DealDatabase.tsx
@@ -6,7 +6,7 @@
*/
import React, { useState, useEffect, useMemo } from 'react';
-import { Database, Search, FileText, TrendingUp, RefreshCw, Scan, AlertCircle, ExternalLink, BarChart3, Clock } from 'lucide-react';
+import { Database, Search, FileText, TrendingUp, RefreshCw, Scan, AlertCircle, ExternalLink, BarChart3, Clock, ChevronRight, Activity } from 'lucide-react';
import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';
import { MA_COLORS, CHART_STYLE, CHART_PALETTE } from '../constants';
import { MAMetricCard, MAChartPanel, MASectionHeader, MAEmptyState, MADataTable, MAExportButton } from '../components';
@@ -27,6 +27,9 @@ interface SECFiling {
deal_indicators?: string;
}
+type PanelView = 'deal' | 'filing' | 'summary' | 'empty';
+type LeftTab = 'deals' | 'filings';
+
const ACCENT = MA_COLORS.dealDb;
const STATUS_COLORS: Record<string, string> = {
@@ -41,106 +44,41 @@ const STATUS_COLORS: Record<string, string> = {
'unknown': FINCEPT.GRAY,
};
-// SEC Filings table column definitions
-const filingsColumns = [
- {
- key: 'company_name',
- label: 'Company',
- sortable: true,
- format: (val: any) => (
- <span style={{ color: FINCEPT.WHITE, fontWeight: TYPOGRAPHY.BOLD as any }}>{val}</span>
- ),
- },
- {
- key: 'filing_type',
- label: 'Type',
- width: '80px',
- sortable: true,
- format: (val: any) => (
- <span style={{
- padding: '2px 6px',
- borderRadius: '2px',
- backgroundColor: `${ACCENT}20`,
- color: ACCENT,
- fontSize: TYPOGRAPHY.TINY,
- }}>
- {val}
- </span>
- ),
- },
- {
- key: 'filing_date',
- label: 'Date',
- width: '90px',
- sortable: true,
- format: (val: any) => <span style={{ color: FINCEPT.GRAY }}>{val}</span>,
- },
- {
- key: 'confidence_score',
- label: 'Confidence',
- width: '90px',
- align: 'center' as const,
- sortable: true,
- format: (val: any) => {
- const color = val >= 0.9 ? FINCEPT.GREEN : val >= 0.75 ? '#FFC400' : FINCEPT.GRAY;
- return <span style={{ color, fontWeight: TYPOGRAPHY.BOLD as any }}>{(val * 100).toFixed(0)}%</span>;
- },
- },
- {
- key: 'deal_indicators',
- label: 'Indicators',
- format: (val: any) => (
- <span style={{
- color: FINCEPT.MUTED,
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap' as const,
- maxWidth: '180px',
- display: 'inline-block',
- }}>
- {val || '-'}
- </span>
- ),
- },
- {
- key: 'filing_url',
- label: 'Link',
- width: '50px',
- align: 'center' as const,
- sortable: false,
- format: (val: any) => (
- <a
- href={val}
- target="_blank"
- rel="noopener noreferrer"
- style={{ color: ACCENT, textDecoration: 'none' }}
- onClick={(e) => e.stopPropagation()}
- >
- <ExternalLink size={12} />
- </a>
- ),
- },
-];
+const CONFIDENCE_COLOR = (score: number) =>
+ score >= 0.9 ? FINCEPT.GREEN : score >= 0.75 ? '#FFC400' : score >= 0.5 ? ACCENT : FINCEPT.GRAY;
+
+const FORM_TYPE_LABELS: Record<string, string> = {
+ 'DEFM14A': 'Definitive Merger Proxy',
+ 'PREM14A': 'Preliminary Merger Proxy',
+ 'S-4': 'Registration (Merger)',
+ 'SC TO-T': 'Tender Offer (3rd Party)',
+ 'SC TO-I': 'Tender Offer (Issuer)',
+ 'SC 13E-3': 'Going Private',
+ '8-K': 'Material Event',
+ '425': 'Merger Communication',
+};
export const DealDatabase: React.FC = () => {
const [deals, setDeals] = useState<MADeal[]>([]);
const [selectedDeal, setSelectedDeal] = useState<MADeal | null>(null);
const [recentFilings, setRecentFilings] = useState<SECFiling[]>([]);
- const [showFilings, setShowFilings] = useState(false);
+ const [selectedFiling, setSelectedFiling] = useState<SECFiling | null>(null);
+ const [leftTab, setLeftTab] = useState<LeftTab>('filings');
const [searchQuery, setSearchQuery] = useState('');
const [loading, setLoading] = useState(false);
const [scanning, setScanning] = useState(false);
const [scanDays, setScanDays] = useState(30);
+ const [hideSelfTenders, setHideSelfTenders] = useState(true);
const [statusMessage, setStatusMessage] = useState<{ type: 'success' | 'error' | 'info'; text: string } | null>(null);
useEffect(() => {
loadDeals();
}, []);
- // Clear status message after 5 seconds
+ // Clear status message after 6 seconds
useEffect(() => {
if (statusMessage) {
- const timer = setTimeout(() => setStatusMessage(null), 5000);
+ const timer = setTimeout(() => setStatusMessage(null), 6000);
return () => clearTimeout(timer);
}
}, [statusMessage]);
@@ -150,7 +88,10 @@ export const DealDatabase: React.FC = () => {
try {
const result = await MAAnalyticsService.DealDatabase.getAllDeals();
setDeals(result);
- setStatusMessage({ type: 'info', text: `Loaded ${result.length} deals from database` });
+ if (result.length > 0) {
+ setStatusMessage({ type: 'info', text: `Loaded ${result.length} deal${result.length !== 1 ? 's' : ''} from database` });
+ setLeftTab('deals');
+ }
} catch (error) {
console.error('Failed to load deals:', error);
setStatusMessage({ type: 'error', text: 'Failed to load deals from database' });
@@ -161,7 +102,7 @@ export const DealDatabase: React.FC = () => {
const scanFilings = async () => {
setScanning(true);
- setStatusMessage({ type: 'info', text: `Scanning SEC filings from the last ${scanDays} days...` });
+ setStatusMessage({ type: 'info', text: `Scanning SEC EDGAR for last ${scanDays} days...` });
try {
const result = await MAAnalyticsService.DealDatabase.scanFilings(scanDays);
const filingsFound = result.filings_found || 0;
@@ -169,15 +110,20 @@ export const DealDatabase: React.FC = () => {
const dealsCreated = result.deals_created || 0;
const totalDeals = dealsParsed + dealsCreated;
- // Store filings for display
- if (result.filings && result.filings.length > 0) {
- setRecentFilings(result.filings);
- setShowFilings(true);
+ // Store filings for display — always show them after a scan
+ const filings: SECFiling[] = result.filings || [];
+ if (filings.length > 0) {
+ setRecentFilings(filings);
+ setLeftTab('filings');
+ // Auto-select first high-confidence filing
+ const topFiling = [...filings].sort((a, b) => b.confidence_score - a.confidence_score)[0];
+ setSelectedFiling(topFiling);
+ setSelectedDeal(null);
}
setStatusMessage({
type: 'success',
- text: `Found ${filingsFound} filings, ${totalDeals} deal${totalDeals !== 1 ? 's' : ''} added to database`,
+ text: `Found ${filingsFound} filing${filingsFound !== 1 ? 's' : ''}${totalDeals > 0 ? `, ${totalDeals} deal${totalDeals !== 1 ? 's' : ''} added` : ''}`,
});
// Reload deals from database
@@ -191,18 +137,34 @@ export const DealDatabase: React.FC = () => {
};
const formatCurrency = (value: number) => {
+ if (!value || isNaN(value)) return '—';
if (value >= 1e9) return `$${(value / 1e9).toFixed(2)}B`;
if (value >= 1e6) return `$${(value / 1e6).toFixed(2)}M`;
return `$${value.toLocaleString()}`;
};
- const filteredDeals = deals.filter(deal =>
- deal.target_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
- deal.acquirer_name.toLowerCase().includes(searchQuery.toLowerCase())
- );
+ const filteredDeals = useMemo(() =>
+ deals.filter(deal => {
+ // Optionally hide self-tenders (acquirer === target, e.g. fund share repurchases)
+ if (hideSelfTenders && deal.acquirer_name && deal.target_name &&
+ deal.acquirer_name.trim().toLowerCase() === deal.target_name.trim().toLowerCase()) {
+ return false;
+ }
+ if (!searchQuery) return true;
+ const q = searchQuery.toLowerCase();
+ return deal.target_name?.toLowerCase().includes(q) ||
+ deal.acquirer_name?.toLowerCase().includes(q) ||
+ deal.deal_type?.toLowerCase().includes(q) ||
+ deal.industry?.toLowerCase().includes(q);
+ }), [deals, searchQuery, hideSelfTenders]);
- // --- Derived chart data ---
+ const filteredFilings = useMemo(() =>
+ recentFilings.filter(f =>
+ f.company_name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ f.filing_type?.toLowerCase().includes(searchQuery.toLowerCase())
+ ), [recentFilings, searchQuery]);
+ // --- Derived chart data ---
const statusCounts = useMemo(() => {
return deals.reduce((acc, d) => {
const status = d.status || 'unknown';
@@ -211,15 +173,12 @@ export const DealDatabase: React.FC = () => {
}, {} as Record<string, number>);
}, [deals]);
- const pipelineData = useMemo(() => {
- return Object.entries(statusCounts).map(([status, count]) => ({
- name: status,
- value: count,
- }));
- }, [statusCounts]);
+ const pipelineData = useMemo(() =>
+ Object.entries(statusCounts).map(([status, count]) => ({ name: status, value: count })),
+ [statusCounts]);
- const timelineData = useMemo(() => {
- return deals
+ const timelineData = useMemo(() =>
+ deals
.filter(d => d.announced_date && d.deal_value)
.map(d => ({
date: new Date(d.announced_date).getTime(),
@@ -227,8 +186,23 @@ export const DealDatabase: React.FC = () => {
name: d.target_name,
premium: d.premium_1day,
}))
- .filter(d => !isNaN(d.date));
- }, [deals]);
+ .filter(d => !isNaN(d.date)),
+ [deals]);
+
+ // Filing type distribution for chart
+ const filingTypeData = useMemo(() => {
+ const counts: Record<string, number> = {};
+ recentFilings.forEach(f => {
+ counts[f.filing_type] = (counts[f.filing_type] || 0) + 1;
+ });
+ return Object.entries(counts)
+ .sort((a, b) => b[1] - a[1])
+ .map(([name, value]) => ({ name, value }));
+ }, [recentFilings]);
+
+ // Confidence distribution
+ const highConfidenceFilings = useMemo(() =>
+ recentFilings.filter(f => f.confidence_score >= 0.85), [recentFilings]);
// Summary metrics
const totalDealValue = useMemo(() => deals.reduce((sum, d) => sum + (d.deal_value || 0), 0), [deals]);
@@ -236,15 +210,29 @@ export const DealDatabase: React.FC = () => {
if (!deals.length) return 0;
return deals.reduce((sum, d) => sum + (d.premium_1day || 0), 0) / deals.length;
}, [deals]);
- const completedCount = useMemo(() => deals.filter(d => (d.status || '').toLowerCase() === 'completed').length, [deals]);
+ const completedCount = useMemo(() =>
+ deals.filter(d => (d.status || '').toLowerCase() === 'completed').length, [deals]);
- // Find the selected deal index in filteredDeals for MADataTable highlight
const selectedDealIndex = useMemo(() => {
if (!selectedDeal) return undefined;
return filteredDeals.findIndex(d => d.deal_id === selectedDeal.deal_id);
}, [filteredDeals, selectedDeal]);
- // Deal list column definitions for left panel
+ const selectedFilingIndex = useMemo(() => {
+ if (!selectedFiling) return undefined;
+ return filteredFilings.findIndex(f => f.accession_number === selectedFiling.accession_number);
+ }, [filteredFilings, selectedFiling]);
+
+ // Determine right panel view
+ const panelView: PanelView = selectedDeal
+ ? 'deal'
+ : selectedFiling
+ ? 'filing'
+ : (deals.length > 0 || recentFilings.length > 0)
+ ? 'summary'
+ : 'empty';
+
+ // Deal list columns
const dealListColumns = useMemo(() => [
{
key: 'target_name',
@@ -260,9 +248,9 @@ export const DealDatabase: React.FC = () => {
width: '80px',
align: 'right' as const,
sortable: true,
- format: (val: any) => (
- <span style={{ color: ACCENT }}>{formatCurrency(val || 0)}</span>
- ),
+ format: (val: any) => val
+ ? <span style={{ color: ACCENT }}>{formatCurrency(val)}</span>
+ : <span style={{ color: FINCEPT.MUTED }}>–</span>,
},
{
key: 'premium_1day',
@@ -270,9 +258,58 @@ export const DealDatabase: React.FC = () => {
width: '55px',
align: 'right' as const,
sortable: true,
+ format: (val: any) => {
+ if (!val || val === 0) return <span style={{ color: FINCEPT.MUTED }}>–</span>;
+ return (
+ <span style={{ color: val > 0 ? FINCEPT.GREEN : FINCEPT.RED }}>
+ {val > 0 ? '+' : ''}{val.toFixed(1)}%
+ </span>
+ );
+ },
+ },
+ ], []);
+
+ // Filing list columns (compact)
+ const filingListColumns = useMemo(() => [
+ {
+ key: 'company_name',
+ label: 'Company',
+ sortable: true,
format: (val: any) => (
- <span style={{ color: val > 0 ? FINCEPT.GREEN : FINCEPT.RED }}>
- {val > 0 ? '+' : ''}{(val || 0).toFixed(1)}%
+ <span style={{ color: FINCEPT.WHITE, fontWeight: TYPOGRAPHY.BOLD as any,
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' as const,
+ display: 'block', maxWidth: '140px' }}>
+ {val}
+ </span>
+ ),
+ },
+ {
+ key: 'filing_type',
+ label: 'Type',
+ width: '72px',
+ sortable: true,
+ format: (val: any) => (
+ <span style={{
+ padding: '2px 5px',
+ borderRadius: '2px',
+ backgroundColor: `${ACCENT}20`,
+ color: ACCENT,
+ fontSize: TYPOGRAPHY.TINY,
+ whiteSpace: 'nowrap' as const,
+ }}>
+ {val}
+ </span>
+ ),
+ },
+ {
+ key: 'confidence_score',
+ label: 'Conf',
+ width: '42px',
+ align: 'right' as const,
+ sortable: true,
+ format: (val: any) => (
+ <span style={{ color: CONFIDENCE_COLOR(val), fontWeight: TYPOGRAPHY.BOLD as any }}>
+ {((val || 0) * 100).toFixed(0)}%
</span>
),
},
@@ -280,7 +317,7 @@ export const DealDatabase: React.FC = () => {
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
- {/* TOP HEADER BAR */}
+ {/* ── TOP HEADER BAR ── */}
<div style={{
...COMMON_STYLES.header,
borderBottom: `2px solid ${ACCENT}`,
@@ -300,14 +337,32 @@ export const DealDatabase: React.FC = () => {
}}>
DEAL DATABASE
</span>
- <span style={{
- fontSize: TYPOGRAPHY.TINY,
- fontFamily: TYPOGRAPHY.MONO,
- color: FINCEPT.MUTED,
- marginLeft: SPACING.SMALL,
- }}>
- {deals.length} deal{deals.length !== 1 ? 's' : ''} tracked
- </span>
+ {/* Counters */}
+ <div style={{ display: 'flex', gap: SPACING.SMALL }}>
+ {deals.length > 0 && (
+ <span style={{
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.GREEN, padding: '1px 6px',
+ backgroundColor: `${FINCEPT.GREEN}15`, borderRadius: '2px',
+ }}>
+ {deals.length} deal{deals.length !== 1 ? 's' : ''}
+ </span>
+ )}
+ {recentFilings.length > 0 && (
+ <span style={{
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: ACCENT, padding: '1px 6px',
+ backgroundColor: `${ACCENT}15`, borderRadius: '2px',
+ }}>
+ {recentFilings.length} filing{recentFilings.length !== 1 ? 's' : ''}
+ {highConfidenceFilings.length > 0 && (
+ <span style={{ color: FINCEPT.GREEN, marginLeft: '4px' }}>
+ ({highConfidenceFilings.length} high conf.)
+ </span>
+ )}
+ </span>
+ )}
+ </div>
</div>
<div style={{ flex: 1 }} />
@@ -320,14 +375,12 @@ export const DealDatabase: React.FC = () => {
fontSize: TYPOGRAPHY.TINY,
fontFamily: TYPOGRAPHY.MONO,
backgroundColor: statusMessage.type === 'error' ? `${FINCEPT.RED}20` :
- statusMessage.type === 'success' ? `${FINCEPT.GREEN}20` :
- `${ACCENT}20`,
+ statusMessage.type === 'success' ? `${FINCEPT.GREEN}20` :
+ `${ACCENT}20`,
color: statusMessage.type === 'error' ? FINCEPT.RED :
- statusMessage.type === 'success' ? FINCEPT.GREEN :
- ACCENT,
- display: 'flex',
- alignItems: 'center',
- gap: SPACING.SMALL,
+ statusMessage.type === 'success' ? FINCEPT.GREEN : ACCENT,
+ display: 'flex', alignItems: 'center', gap: SPACING.SMALL,
+ maxWidth: '360px',
}}>
<AlertCircle size={10} />
{statusMessage.text}
@@ -366,9 +419,7 @@ export const DealDatabase: React.FC = () => {
fontFamily: TYPOGRAPHY.MONO,
fontWeight: TYPOGRAPHY.BOLD,
letterSpacing: TYPOGRAPHY.WIDE,
- display: 'flex',
- alignItems: 'center',
- gap: SPACING.SMALL,
+ display: 'flex', alignItems: 'center', gap: SPACING.SMALL,
textTransform: 'uppercase' as const,
}}
>
@@ -377,14 +428,14 @@ export const DealDatabase: React.FC = () => {
</button>
</div>
- <MAExportButton data={deals} filename="deal_database" accentColor={ACCENT} />
+ <MAExportButton data={[...deals, ...recentFilings]} filename="deal_database" accentColor={ACCENT} />
</div>
- {/* MAIN CONTENT: LEFT PANEL + RIGHT PANEL */}
+ {/* ── MAIN CONTENT ── */}
<div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
- {/* LEFT - Deal List Panel (300px) */}
+ {/* ── LEFT PANEL (320px) ── */}
<div style={{
- width: '300px',
+ width: '320px',
backgroundColor: FINCEPT.PANEL_BG,
borderRight: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
@@ -392,28 +443,56 @@ export const DealDatabase: React.FC = () => {
overflow: 'hidden',
flexShrink: 0,
}}>
- {/* Search Bar */}
+ {/* Tab switcher */}
<div style={{
- padding: SPACING.DEFAULT,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
- gap: SPACING.SMALL,
- alignItems: 'center',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ flexShrink: 0,
}}>
- <div style={{ position: 'relative', flex: 1 }}>
- <Search
- size={11}
+ {(['filings', 'deals'] as LeftTab[]).map(tab => (
+ <button
+ key={tab}
+ onClick={() => setLeftTab(tab)}
style={{
- position: 'absolute',
- left: '8px',
- top: '50%',
- transform: 'translateY(-50%)',
- color: FINCEPT.MUTED,
+ flex: 1,
+ padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,
+ backgroundColor: 'transparent',
+ border: 'none',
+ borderBottom: leftTab === tab ? `2px solid ${ACCENT}` : '2px solid transparent',
+ color: leftTab === tab ? ACCENT : FINCEPT.MUTED,
+ fontSize: TYPOGRAPHY.TINY,
+ fontFamily: TYPOGRAPHY.MONO,
+ fontWeight: leftTab === tab ? TYPOGRAPHY.BOLD : TYPOGRAPHY.REGULAR,
+ letterSpacing: TYPOGRAPHY.WIDE,
+ cursor: 'pointer',
+ textTransform: 'uppercase' as const,
+ transition: 'all 0.15s',
+ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px',
}}
- />
+ >
+ {tab === 'filings' ? <FileText size={10} /> : <Database size={10} />}
+ {tab === 'filings'
+ ? `Filings${recentFilings.length > 0 ? ` (${recentFilings.length})` : ''}`
+ : `Deals${deals.length > 0 ? ` (${deals.length})` : ''}`}
+ </button>
+ ))}
+ </div>
+
+ {/* Search */}
+ <div style={{
+ padding: SPACING.DEFAULT,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL,
+ }}>
+ <div style={{ display: 'flex', gap: SPACING.SMALL, alignItems: 'center' }}>
+ <div style={{ position: 'relative', flex: 1 }}>
+ <Search size={11} style={{
+ position: 'absolute', left: '8px', top: '50%',
+ transform: 'translateY(-50%)', color: FINCEPT.MUTED,
+ }} />
<input
type="text"
- placeholder="Search deals..."
+ placeholder={leftTab === 'filings' ? 'Search filings...' : 'Search deals...'}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
style={{
@@ -427,7 +506,7 @@ export const DealDatabase: React.FC = () => {
<button
onClick={loadDeals}
disabled={loading}
- title="Refresh deals"
+ title="Refresh"
style={{
padding: SPACING.SMALL,
backgroundColor: 'transparent',
@@ -435,80 +514,113 @@ export const DealDatabase: React.FC = () => {
borderRadius: '2px',
color: FINCEPT.GRAY,
cursor: loading ? 'not-allowed' : 'pointer',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
transition: 'all 0.15s',
}}
- onMouseEnter={(e) => {
- e.currentTarget.style.borderColor = ACCENT;
- e.currentTarget.style.color = ACCENT;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
- e.currentTarget.style.color = FINCEPT.GRAY;
- }}
+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = ACCENT; e.currentTarget.style.color = ACCENT; }}
+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; e.currentTarget.style.color = FINCEPT.GRAY; }}
>
<RefreshCw size={12} className={loading ? 'animate-spin' : ''} />
</button>
+ </div>
+ {leftTab === 'deals' && (
+ <label style={{
+ display: 'flex', alignItems: 'center', gap: SPACING.SMALL,
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO, color: FINCEPT.GRAY,
+ cursor: 'pointer', userSelect: 'none' as const,
+ }}>
+ <input
+ type="checkbox"
+ checked={hideSelfTenders}
+ onChange={(e) => setHideSelfTenders(e.target.checked)}
+ style={{ accentColor: ACCENT, cursor: 'pointer' }}
+ />
+ Hide self-tenders / fund filings
+ </label>
+ )}
</div>
- {/* Deal List */}
+ {/* List body */}
<div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
{loading ? (
<div style={{ ...COMMON_STYLES.emptyState, padding: SPACING.XLARGE }}>
- <div
- className="animate-spin"
- style={{
- width: '20px',
- height: '20px',
- border: `2px solid ${FINCEPT.BORDER}`,
- borderTop: `2px solid ${ACCENT}`,
- borderRadius: '50%',
- marginBottom: SPACING.SMALL,
- }}
- />
- <span style={{ fontFamily: TYPOGRAPHY.MONO, fontSize: TYPOGRAPHY.TINY }}>Loading deals...</span>
+ <div className="animate-spin" style={{
+ width: '20px', height: '20px',
+ border: `2px solid ${FINCEPT.BORDER}`,
+ borderTop: `2px solid ${ACCENT}`,
+ borderRadius: '50%', marginBottom: SPACING.SMALL,
+ }} />
+ <span style={{ fontFamily: TYPOGRAPHY.MONO, fontSize: TYPOGRAPHY.TINY }}>Loading...</span>
</div>
- ) : filteredDeals.length === 0 ? (
- <div style={{ ...COMMON_STYLES.emptyState, padding: SPACING.XLARGE }}>
- <Database size={28} style={{ marginBottom: SPACING.SMALL, opacity: 0.3, color: ACCENT }} />
- <span style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.GRAY, fontFamily: TYPOGRAPHY.MONO }}>
- {searchQuery ? 'No matching deals' : 'No deals tracked yet'}
- </span>
- <div style={{
- fontSize: TYPOGRAPHY.TINY,
- fontFamily: TYPOGRAPHY.MONO,
- color: FINCEPT.MUTED,
- marginTop: SPACING.SMALL,
- textAlign: 'center',
- maxWidth: '220px',
- }}>
- {searchQuery ? (
- 'Try a different search term'
- ) : (
- <>
- Click <strong style={{ color: ACCENT }}>SCAN SEC</strong> above to discover M&A deals from SEC EDGAR
- </>
+ ) : leftTab === 'filings' ? (
+ filteredFilings.length === 0 ? (
+ <div style={{ ...COMMON_STYLES.emptyState, padding: SPACING.XLARGE }}>
+ <FileText size={28} style={{ marginBottom: SPACING.SMALL, opacity: 0.3, color: ACCENT }} />
+ <span style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.GRAY, fontFamily: TYPOGRAPHY.MONO }}>
+ {searchQuery ? 'No matching filings' : 'No filings scanned yet'}
+ </span>
+ {!searchQuery && (
+ <div style={{
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.MUTED, marginTop: SPACING.SMALL,
+ textAlign: 'center', maxWidth: '220px',
+ }}>
+ Click <strong style={{ color: ACCENT }}>SCAN SEC</strong> to fetch real M&A filings from SEC EDGAR
+ </div>
)}
</div>
- </div>
+ ) : (
+ <MADataTable
+ columns={filingListColumns}
+ data={filteredFilings as any}
+ accentColor={ACCENT}
+ compact
+ maxHeight="100%"
+ onRowClick={(row: any) => {
+ setSelectedFiling(row as SECFiling);
+ setSelectedDeal(null);
+ }}
+ selectedIndex={selectedFilingIndex}
+ emptyMessage="No filings found"
+ />
+ )
) : (
- <MADataTable
- columns={dealListColumns}
- data={filteredDeals as any}
- accentColor={ACCENT}
- compact
- maxHeight="100%"
- onRowClick={(row) => setSelectedDeal(row as MADeal)}
- selectedIndex={selectedDealIndex}
- emptyMessage="No deals found"
- />
+ filteredDeals.length === 0 ? (
+ <div style={{ ...COMMON_STYLES.emptyState, padding: SPACING.XLARGE }}>
+ <Database size={28} style={{ marginBottom: SPACING.SMALL, opacity: 0.3, color: ACCENT }} />
+ <span style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.GRAY, fontFamily: TYPOGRAPHY.MONO }}>
+ {searchQuery ? 'No matching deals' : 'No deals in database'}
+ </span>
+ {!searchQuery && (
+ <div style={{
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.MUTED, marginTop: SPACING.SMALL,
+ textAlign: 'center', maxWidth: '220px',
+ }}>
+ Deals are parsed from high-confidence SEC filings
+ </div>
+ )}
+ </div>
+ ) : (
+ <MADataTable
+ columns={dealListColumns}
+ data={filteredDeals as any}
+ accentColor={ACCENT}
+ compact
+ maxHeight="100%"
+ onRowClick={(row: any) => {
+ setSelectedDeal(row as MADeal);
+ setSelectedFiling(null);
+ }}
+ selectedIndex={selectedDealIndex}
+ emptyMessage="No deals found"
+ />
+ )
)}
</div>
</div>
- {/* RIGHT - Deal Details & Charts */}
+ {/* ── RIGHT PANEL ── */}
<div style={{
flex: 1,
backgroundColor: FINCEPT.DARK_BG,
@@ -516,7 +628,8 @@ export const DealDatabase: React.FC = () => {
flexDirection: 'column',
overflow: 'hidden',
}}>
- {selectedDeal ? (
+ {/* ── DEAL DETAIL VIEW ── */}
+ {panelView === 'deal' && selectedDeal && (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
{/* Deal Header */}
<div style={{
@@ -525,28 +638,18 @@ export const DealDatabase: React.FC = () => {
borderBottom: `1px solid ${ACCENT}40`,
flexShrink: 0,
}}>
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'flex-start',
- }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
<div>
<div style={{
- fontSize: TYPOGRAPHY.HEADING,
- fontFamily: TYPOGRAPHY.MONO,
- fontWeight: TYPOGRAPHY.BOLD,
- color: FINCEPT.WHITE,
+ fontSize: TYPOGRAPHY.HEADING, fontFamily: TYPOGRAPHY.MONO,
+ fontWeight: TYPOGRAPHY.BOLD, color: FINCEPT.WHITE,
}}>
{selectedDeal.target_name}
</div>
<div style={{
- fontSize: TYPOGRAPHY.SMALL,
- fontFamily: TYPOGRAPHY.MONO,
- color: FINCEPT.GRAY,
- marginTop: SPACING.TINY,
- display: 'flex',
- alignItems: 'center',
- gap: SPACING.SMALL,
+ fontSize: TYPOGRAPHY.SMALL, fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.GRAY, marginTop: SPACING.TINY,
+ display: 'flex', alignItems: 'center', gap: SPACING.SMALL,
}}>
<TrendingUp size={11} style={{ color: ACCENT }} />
<span>Acquired by <span style={{ color: FINCEPT.WHITE }}>{selectedDeal.acquirer_name}</span></span>
@@ -554,83 +657,85 @@ export const DealDatabase: React.FC = () => {
</div>
<div style={{ textAlign: 'right' }}>
<div style={{
- fontSize: TYPOGRAPHY.HEADING,
- fontFamily: TYPOGRAPHY.MONO,
- fontWeight: TYPOGRAPHY.BOLD,
- color: ACCENT,
+ fontSize: TYPOGRAPHY.HEADING, fontFamily: TYPOGRAPHY.MONO,
+ fontWeight: TYPOGRAPHY.BOLD, color: ACCENT,
}}>
{formatCurrency(selectedDeal.deal_value)}
</div>
<div style={{
- fontSize: TYPOGRAPHY.TINY,
- fontFamily: TYPOGRAPHY.MONO,
- color: FINCEPT.MUTED,
- marginTop: SPACING.TINY,
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.MUTED, marginTop: SPACING.TINY,
letterSpacing: TYPOGRAPHY.WIDE,
}}>
DEAL VALUE
</div>
</div>
</div>
-
- {/* Status Badges */}
- <div style={{ marginTop: SPACING.DEFAULT, display: 'flex', gap: SPACING.SMALL }}>
+ <div style={{ marginTop: SPACING.DEFAULT, display: 'flex', gap: SPACING.SMALL, flexWrap: 'wrap' as const }}>
<span style={{
...COMMON_STYLES.badgeInfo,
- backgroundColor: selectedDeal.status === 'Completed' ? `${FINCEPT.GREEN}20` :
- selectedDeal.status === 'Pending' || selectedDeal.status === 'pending' ? `${'#FFC400'}20` :
- `${ACCENT}20`,
- color: selectedDeal.status === 'Completed' ? FINCEPT.GREEN :
- selectedDeal.status === 'Pending' || selectedDeal.status === 'pending' ? '#FFC400' :
- ACCENT,
- fontFamily: TYPOGRAPHY.MONO,
- letterSpacing: TYPOGRAPHY.WIDE,
+ backgroundColor: `${STATUS_COLORS[selectedDeal.status] || ACCENT}20`,
+ color: STATUS_COLORS[selectedDeal.status] || ACCENT,
+ fontFamily: TYPOGRAPHY.MONO, letterSpacing: TYPOGRAPHY.WIDE,
}}>
{selectedDeal.status.toUpperCase()}
</span>
+ {selectedDeal.deal_type && (
+ <span style={{
+ ...COMMON_STYLES.badgeInfo,
+ backgroundColor: `${FINCEPT.CYAN}20`, color: FINCEPT.CYAN,
+ fontFamily: TYPOGRAPHY.MONO, letterSpacing: TYPOGRAPHY.WIDE,
+ }}>
+ {selectedDeal.deal_type.toUpperCase()}
+ </span>
+ )}
<span style={{
...COMMON_STYLES.badgeInfo,
- backgroundColor: `${ACCENT}20`,
- color: ACCENT,
- fontFamily: TYPOGRAPHY.MONO,
- letterSpacing: TYPOGRAPHY.WIDE,
+ backgroundColor: `${ACCENT}20`, color: ACCENT,
+ fontFamily: TYPOGRAPHY.MONO, letterSpacing: TYPOGRAPHY.WIDE,
}}>
{selectedDeal.industry.toUpperCase()}
</span>
- <span style={{
- ...COMMON_STYLES.badgeInfo,
- fontFamily: TYPOGRAPHY.MONO,
- }}>
+ {selectedDeal.hostile_flag === 1 && (
+ <span style={{ ...COMMON_STYLES.badgeInfo, backgroundColor: `${FINCEPT.RED}20`, color: FINCEPT.RED, fontFamily: TYPOGRAPHY.MONO }}>
+ HOSTILE
+ </span>
+ )}
+ {selectedDeal.tender_offer_flag === 1 && (
+ <span style={{ ...COMMON_STYLES.badgeInfo, backgroundColor: `${FINCEPT.CYAN}15`, color: FINCEPT.CYAN, fontFamily: TYPOGRAPHY.MONO }}>
+ TENDER OFFER
+ </span>
+ )}
+ {selectedDeal.cross_border_flag === 1 && (
+ <span style={{ ...COMMON_STYLES.badgeInfo, backgroundColor: `${FINCEPT.GREEN}15`, color: FINCEPT.GREEN, fontFamily: TYPOGRAPHY.MONO }}>
+ CROSS-BORDER
+ </span>
+ )}
+ <span style={{ ...COMMON_STYLES.badgeInfo, fontFamily: TYPOGRAPHY.MONO }}>
{selectedDeal.announced_date}
</span>
</div>
</div>
- {/* Scrollable content */}
<div style={{ flex: 1, overflow: 'auto', padding: SPACING.LARGE }}>
- {/* Key Metrics */}
- <MASectionHeader
- title="Key Metrics"
- icon={<BarChart3 size={13} />}
- accentColor={ACCENT}
- />
+ <MASectionHeader title="Key Metrics" icon={<BarChart3 size={13} />} accentColor={ACCENT} />
<div style={{
- display: 'grid',
- gridTemplateColumns: 'repeat(3, 1fr)',
- gap: SPACING.DEFAULT,
- marginBottom: SPACING.LARGE,
+ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
+ gap: SPACING.DEFAULT, marginBottom: SPACING.LARGE,
}}>
<MAMetricCard
label="Premium (1-Day)"
- value={`${selectedDeal.premium_1day > 0 ? '+' : ''}${selectedDeal.premium_1day.toFixed(1)}%`}
- accentColor={selectedDeal.premium_1day > 0 ? FINCEPT.GREEN : FINCEPT.RED}
+ value={selectedDeal.premium_1day
+ ? `${selectedDeal.premium_1day > 0 ? '+' : ''}${selectedDeal.premium_1day.toFixed(1)}%`
+ : 'N/A'}
+ accentColor={selectedDeal.premium_1day > 0 ? FINCEPT.GREEN : selectedDeal.premium_1day < 0 ? FINCEPT.RED : FINCEPT.GRAY}
trend={selectedDeal.premium_1day > 0 ? 'up' : selectedDeal.premium_1day < 0 ? 'down' : 'neutral'}
/>
<MAMetricCard
label="Cash Component"
value={`${selectedDeal.payment_cash_pct}%`}
accentColor={ACCENT}
- subtitle={`Stock: ${selectedDeal.payment_stock_pct}%`}
+ subtitle={`Stock: ${selectedDeal.payment_stock_pct}% · ${selectedDeal.payment_method || 'Cash'}`}
/>
<MAMetricCard
label="Announced"
@@ -638,71 +743,45 @@ export const DealDatabase: React.FC = () => {
accentColor={FINCEPT.GRAY}
format="text"
/>
+ {selectedDeal.offer_price_per_share != null && (
+ <MAMetricCard label="Offer Price / Share" value={`$${selectedDeal.offer_price_per_share.toFixed(2)}`} accentColor={FINCEPT.GREEN} />
+ )}
+ {selectedDeal.expected_close_date && (
+ <MAMetricCard label="Expected Close" value={selectedDeal.expected_close_date} accentColor={FINCEPT.GRAY} format="text" />
+ )}
+ {selectedDeal.breakup_fee != null && (
+ <MAMetricCard label="Breakup Fee" value={formatCurrency(selectedDeal.breakup_fee)} accentColor={FINCEPT.RED} />
+ )}
{selectedDeal.ev_revenue != null && (
- <MAMetricCard
- label="EV / Revenue"
- value={`${selectedDeal.ev_revenue.toFixed(2)}x`}
- accentColor={FINCEPT.CYAN}
- />
+ <MAMetricCard label="EV / Revenue" value={`${selectedDeal.ev_revenue.toFixed(2)}x`} accentColor={FINCEPT.CYAN} />
)}
{selectedDeal.ev_ebitda != null && (
- <MAMetricCard
- label="EV / EBITDA"
- value={`${selectedDeal.ev_ebitda.toFixed(2)}x`}
- accentColor={FINCEPT.CYAN}
- />
+ <MAMetricCard label="EV / EBITDA" value={`${selectedDeal.ev_ebitda.toFixed(2)}x`} accentColor={FINCEPT.CYAN} />
)}
{selectedDeal.synergies != null && (
- <MAMetricCard
- label="Est. Synergies"
- value={formatCurrency(selectedDeal.synergies)}
- accentColor={FINCEPT.GREEN}
- />
+ <MAMetricCard label="Est. Synergies" value={formatCurrency(selectedDeal.synergies)} accentColor={FINCEPT.GREEN} />
)}
</div>
- {/* Payment Structure Detail */}
- <MASectionHeader
- title="Payment Structure"
- accentColor={ACCENT}
- />
+ <MASectionHeader title="Payment Structure" accentColor={ACCENT} />
<div style={{
- display: 'flex',
- gap: SPACING.SMALL,
- marginBottom: SPACING.LARGE,
- height: '6px',
- borderRadius: '2px',
- overflow: 'hidden',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
+ height: '6px', borderRadius: '2px', overflow: 'hidden',
+ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex', marginBottom: SPACING.SMALL,
}}>
{selectedDeal.payment_cash_pct > 0 && (
- <div
- style={{
- width: `${selectedDeal.payment_cash_pct}%`,
- backgroundColor: ACCENT,
- borderRadius: '1px',
- }}
- title={`Cash: ${selectedDeal.payment_cash_pct}%`}
- />
+ <div style={{ width: `${selectedDeal.payment_cash_pct}%`, backgroundColor: ACCENT }} title={`Cash: ${selectedDeal.payment_cash_pct}%`} />
)}
{selectedDeal.payment_stock_pct > 0 && (
- <div
- style={{
- width: `${selectedDeal.payment_stock_pct}%`,
- backgroundColor: FINCEPT.CYAN,
- borderRadius: '1px',
- }}
- title={`Stock: ${selectedDeal.payment_stock_pct}%`}
- />
+ <div style={{ width: `${selectedDeal.payment_stock_pct}%`, backgroundColor: FINCEPT.CYAN }} title={`Stock: ${selectedDeal.payment_stock_pct}%`} />
+ )}
+ {selectedDeal.payment_cash_pct === 0 && selectedDeal.payment_stock_pct === 0 && (
+ <div style={{ width: '100%', backgroundColor: FINCEPT.BORDER }} title="Payment structure unknown" />
)}
</div>
<div style={{
- display: 'flex',
- gap: SPACING.LARGE,
- marginBottom: SPACING.LARGE,
- fontSize: TYPOGRAPHY.TINY,
- fontFamily: TYPOGRAPHY.MONO,
+ display: 'flex', gap: SPACING.LARGE, marginBottom: SPACING.LARGE,
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
}}>
<span style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>
<span style={{ width: '8px', height: '8px', backgroundColor: ACCENT, borderRadius: '1px', display: 'inline-block' }} />
@@ -712,94 +791,52 @@ export const DealDatabase: React.FC = () => {
<span style={{ width: '8px', height: '8px', backgroundColor: FINCEPT.CYAN, borderRadius: '1px', display: 'inline-block' }} />
<span style={{ color: FINCEPT.GRAY }}>Stock {selectedDeal.payment_stock_pct}%</span>
</span>
+ {selectedDeal.payment_method && (
+ <span style={{ color: FINCEPT.MUTED, marginLeft: 'auto' }}>
+ Method: <span style={{ color: FINCEPT.WHITE }}>{selectedDeal.payment_method}</span>
+ </span>
+ )}
</div>
- {/* Pipeline & Timeline Charts (if deals exist) */}
- {deals.length > 0 && (
+ {deals.length > 1 && (
<>
- <MASectionHeader
- title="Pipeline Analytics"
- icon={<BarChart3 size={13} />}
- accentColor={ACCENT}
- />
- <div style={{
- display: 'grid',
- gridTemplateColumns: '1fr 1fr',
- gap: SPACING.DEFAULT,
- marginBottom: SPACING.LARGE,
- }}>
- {/* Deal Pipeline Status Pie */}
+ <MASectionHeader title="Pipeline Analytics" icon={<Activity size={13} />} accentColor={ACCENT} />
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.DEFAULT, marginBottom: SPACING.LARGE }}>
{pipelineData.length > 0 && (
- <MAChartPanel
- title="Deal Pipeline Status"
- icon={<BarChart3 size={12} />}
- accentColor={ACCENT}
- height={200}
- >
+ <MAChartPanel title="Deal Pipeline Status" icon={<BarChart3 size={12} />} accentColor={ACCENT} height={200}>
<PieChart>
- <Pie
- data={pipelineData}
- dataKey="value"
- nameKey="name"
- cx="50%"
- cy="50%"
- outerRadius={70}
+ <Pie data={pipelineData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={70}
label={({ name, value }) => `${name} (${value})`}
labelLine={{ stroke: FINCEPT.MUTED }}
- style={{ fontSize: '9px', fontFamily: 'var(--ft-font-family, monospace)' }}
- >
+ style={{ fontSize: '9px', fontFamily: 'var(--ft-font-family, monospace)' }}>
{pipelineData.map((entry, i) => (
<Cell key={i} fill={STATUS_COLORS[entry.name] || CHART_PALETTE[i % CHART_PALETTE.length]} />
))}
</Pie>
- <Legend
- wrapperStyle={{ fontSize: '9px', fontFamily: 'var(--ft-font-family, monospace)' }}
- />
+ <Legend wrapperStyle={{ fontSize: '9px', fontFamily: 'var(--ft-font-family, monospace)' }} />
<Tooltip contentStyle={CHART_STYLE.tooltip} />
</PieChart>
</MAChartPanel>
)}
-
- {/* Deal Value Timeline Scatter */}
{timelineData.length > 0 && (
- <MAChartPanel
- title="Deal Value Timeline"
- icon={<Clock size={12} />}
- accentColor={ACCENT}
- height={200}
- >
+ <MAChartPanel title="Deal Value Timeline" icon={<Clock size={12} />} accentColor={ACCENT} height={200}>
<ScatterChart margin={{ top: 10, right: 10, bottom: 10, left: 10 }}>
<CartesianGrid stroke={CHART_STYLE.grid.stroke} strokeDasharray={CHART_STYLE.grid.strokeDasharray} />
- <XAxis
- type="number"
- dataKey="date"
- domain={['auto', 'auto']}
+ <XAxis type="number" dataKey="date" domain={['auto', 'auto']}
tickFormatter={(val) => new Date(val).toLocaleDateString()}
- tick={CHART_STYLE.axis}
- stroke={FINCEPT.BORDER}
- />
- <YAxis
- dataKey="value"
- tick={CHART_STYLE.axis}
- stroke={FINCEPT.BORDER}
- tickFormatter={(val) => {
- if (val >= 1e9) return `$${(val / 1e9).toFixed(0)}B`;
- if (val >= 1e6) return `$${(val / 1e6).toFixed(0)}M`;
- return `$${val}`;
- }}
- />
+ tick={CHART_STYLE.axis} stroke={FINCEPT.BORDER} />
+ <YAxis dataKey="value" tick={CHART_STYLE.axis} stroke={FINCEPT.BORDER}
+ tickFormatter={(val) => val >= 1e9 ? `$${(val / 1e9).toFixed(0)}B` : `$${(val / 1e6).toFixed(0)}M`} />
<ZAxis dataKey="premium" range={[20, 200]} />
<Scatter data={timelineData} fill={ACCENT} />
- <Tooltip
- contentStyle={CHART_STYLE.tooltip}
+ <Tooltip contentStyle={CHART_STYLE.tooltip}
formatter={(value: any, name: string) => {
if (name === 'date') return [new Date(value).toLocaleDateString(), 'Date'];
if (name === 'value') return [formatCurrency(value), 'Deal Value'];
- if (name === 'premium') return [`${value > 0 ? '+' : ''}${value.toFixed(1)}%`, 'Premium'];
+ if (name === 'premium') return [`${value > 0 ? '+' : ''}${(value).toFixed(1)}%`, 'Premium'];
return [value, name];
}}
- labelFormatter={() => ''}
- />
+ labelFormatter={() => ''} />
</ScatterChart>
</MAChartPanel>
)}
@@ -808,34 +845,353 @@ export const DealDatabase: React.FC = () => {
)}
</div>
</div>
- ) : (
- /* No deal selected -- show charts, filings, or empty state */
+ )}
+
+ {/* ── FILING DETAIL VIEW ── */}
+ {panelView === 'filing' && selectedFiling && (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
- {deals.length > 0 ? (
- <div style={{ flex: 1, overflow: 'auto', padding: SPACING.LARGE }}>
- {/* Summary Metrics */}
+ {/* Filing Header */}
+ <div style={{
+ padding: SPACING.LARGE,
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${ACCENT}40`,
+ flexShrink: 0,
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div style={{
+ fontSize: TYPOGRAPHY.HEADING, fontFamily: TYPOGRAPHY.MONO,
+ fontWeight: TYPOGRAPHY.BOLD, color: FINCEPT.WHITE,
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' as const,
+ }}>
+ {selectedFiling.company_name}
+ </div>
+ <div style={{
+ fontSize: TYPOGRAPHY.SMALL, fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.GRAY, marginTop: SPACING.TINY,
+ display: 'flex', alignItems: 'center', gap: SPACING.SMALL,
+ }}>
+ <FileText size={11} style={{ color: ACCENT }} />
+ <span>{FORM_TYPE_LABELS[selectedFiling.filing_type] || selectedFiling.filing_type}</span>
+ </div>
+ </div>
+ <div style={{ textAlign: 'right', flexShrink: 0, marginLeft: SPACING.DEFAULT }}>
+ <div style={{
+ fontSize: '22px', fontFamily: TYPOGRAPHY.MONO,
+ fontWeight: TYPOGRAPHY.BOLD,
+ color: CONFIDENCE_COLOR(selectedFiling.confidence_score),
+ }}>
+ {(selectedFiling.confidence_score * 100).toFixed(0)}%
+ </div>
+ <div style={{
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.MUTED, marginTop: SPACING.TINY,
+ letterSpacing: TYPOGRAPHY.WIDE,
+ }}>
+ M&A CONFIDENCE
+ </div>
+ </div>
+ </div>
+
+ <div style={{ marginTop: SPACING.DEFAULT, display: 'flex', gap: SPACING.SMALL, flexWrap: 'wrap' as const, alignItems: 'center' }}>
+ <span style={{
+ padding: '3px 8px', borderRadius: '2px',
+ backgroundColor: `${ACCENT}20`, color: ACCENT,
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ letterSpacing: TYPOGRAPHY.WIDE,
+ }}>
+ {selectedFiling.filing_type}
+ </span>
+ <span style={{ ...COMMON_STYLES.badgeInfo, fontFamily: TYPOGRAPHY.MONO }}>
+ {selectedFiling.filing_date}
+ </span>
+ {selectedFiling.cik && (
+ <span style={{ ...COMMON_STYLES.badgeInfo, fontFamily: TYPOGRAPHY.MONO, color: FINCEPT.MUTED }}>
+ CIK: {selectedFiling.cik}
+ </span>
+ )}
+ <a
+ href={selectedFiling.filing_url}
+ target="_blank"
+ rel="noopener noreferrer"
+ style={{
+ display: 'flex', alignItems: 'center', gap: '4px',
+ padding: '3px 8px', borderRadius: '2px',
+ backgroundColor: `${ACCENT}15`, color: ACCENT,
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ textDecoration: 'none', letterSpacing: TYPOGRAPHY.WIDE,
+ border: `1px solid ${ACCENT}30`,
+ }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <ExternalLink size={10} />
+ VIEW ON EDGAR
+ </a>
+ </div>
+ </div>
+
+ <div style={{ flex: 1, overflow: 'auto', padding: SPACING.LARGE }}>
+ {/* Filing Metrics */}
+ <MASectionHeader title="Filing Details" icon={<FileText size={13} />} accentColor={ACCENT} />
+ <div style={{
+ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
+ gap: SPACING.DEFAULT, marginBottom: SPACING.LARGE,
+ }}>
+ <MAMetricCard
+ label="Form Type"
+ value={selectedFiling.filing_type}
+ accentColor={ACCENT}
+ format="text"
+ />
+ <MAMetricCard
+ label="Filing Date"
+ value={selectedFiling.filing_date}
+ accentColor={FINCEPT.GRAY}
+ format="text"
+ />
+ <MAMetricCard
+ label="M&A Confidence"
+ value={`${(selectedFiling.confidence_score * 100).toFixed(0)}%`}
+ accentColor={CONFIDENCE_COLOR(selectedFiling.confidence_score)}
+ trend={selectedFiling.confidence_score >= 0.75 ? 'up' : 'neutral'}
+ />
+ </div>
+
+ {/* Confidence bar */}
+ <MASectionHeader title="Signal Strength" accentColor={ACCENT} />
+ <div style={{
+ marginBottom: SPACING.LARGE,
+ padding: SPACING.DEFAULT,
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: SPACING.SMALL, fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO, color: FINCEPT.GRAY }}>
+ <span>0%</span>
+ <span style={{ color: CONFIDENCE_COLOR(selectedFiling.confidence_score) }}>
+ {(selectedFiling.confidence_score * 100).toFixed(0)}% — {
+ selectedFiling.confidence_score >= 0.9 ? 'Very High' :
+ selectedFiling.confidence_score >= 0.75 ? 'High' :
+ selectedFiling.confidence_score >= 0.5 ? 'Medium' : 'Low'
+ }
+ </span>
+ <span>100%</span>
+ </div>
+ <div style={{ height: '6px', backgroundColor: FINCEPT.BORDER, borderRadius: '2px', overflow: 'hidden' }}>
+ <div style={{
+ width: `${selectedFiling.confidence_score * 100}%`,
+ height: '100%',
+ backgroundColor: CONFIDENCE_COLOR(selectedFiling.confidence_score),
+ borderRadius: '2px',
+ transition: 'width 0.3s ease',
+ }} />
+ </div>
+ </div>
+
+ {/* Deal Indicators */}
+ {selectedFiling.deal_indicators && (
+ <>
+ <MASectionHeader title="M&A Indicators Detected" icon={<Activity size={13} />} accentColor={ACCENT} />
+ <div style={{
+ marginBottom: SPACING.LARGE,
+ display: 'flex', flexWrap: 'wrap' as const, gap: SPACING.SMALL,
+ }}>
+ {selectedFiling.deal_indicators.split(',').map((indicator, i) => (
+ <span key={i} style={{
+ padding: '3px 8px', borderRadius: '2px',
+ backgroundColor: `${FINCEPT.GREEN}15`,
+ border: `1px solid ${FINCEPT.GREEN}30`,
+ color: FINCEPT.GREEN,
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ }}>
+ {indicator.trim()}
+ </span>
+ ))}
+ </div>
+ </>
+ )}
+
+ {/* Form type explanation */}
+ <MASectionHeader title="Form Type Reference" accentColor={ACCENT} />
+ <div style={{
+ padding: SPACING.DEFAULT,
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ marginBottom: SPACING.LARGE,
+ }}>
+ {Object.entries(FORM_TYPE_LABELS).map(([form, desc]) => (
+ <div key={form} style={{
+ display: 'flex', gap: SPACING.DEFAULT,
+ padding: `${SPACING.TINY} 0`,
+ borderBottom: `1px solid ${FINCEPT.BORDER}20`,
+ alignItems: 'center',
+ }}>
+ <span style={{
+ width: '80px', flexShrink: 0,
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: form === selectedFiling.filing_type ? ACCENT : FINCEPT.MUTED,
+ fontWeight: form === selectedFiling.filing_type ? TYPOGRAPHY.BOLD : TYPOGRAPHY.REGULAR,
+ }}>
+ {form}
+ </span>
+ {form === selectedFiling.filing_type && (
+ <ChevronRight size={10} style={{ color: ACCENT, flexShrink: 0 }} />
+ )}
+ <span style={{
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: form === selectedFiling.filing_type ? FINCEPT.WHITE : FINCEPT.MUTED,
+ }}>
+ {desc}
+ </span>
+ </div>
+ ))}
+ </div>
+
+ {/* Accession number */}
+ <div style={{
+ padding: SPACING.DEFAULT,
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.MUTED,
+ }}>
+ <span style={{ color: FINCEPT.GRAY }}>Accession Number: </span>
+ <span style={{ color: ACCENT }}>{selectedFiling.accession_number}</span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* ── SUMMARY VIEW (deals or filings exist, nothing selected) ── */}
+ {panelView === 'summary' && (
+ <div style={{ flex: 1, overflow: 'auto', padding: SPACING.LARGE }}>
+ {/* Filings Summary */}
+ {recentFilings.length > 0 && (
+ <>
<MASectionHeader
- title="Portfolio Summary"
- subtitle={`${deals.length} deals`}
- icon={<BarChart3 size={13} />}
+ title="SEC Filings Summary"
+ subtitle={`${recentFilings.length} filings from last ${scanDays} days`}
+ icon={<FileText size={13} />}
accentColor={ACCENT}
/>
<div style={{
- display: 'grid',
- gridTemplateColumns: 'repeat(4, 1fr)',
- gap: SPACING.DEFAULT,
- marginBottom: SPACING.LARGE,
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: SPACING.DEFAULT, marginBottom: SPACING.LARGE,
}}>
+ <MAMetricCard label="Total Filings" value={String(recentFilings.length)} accentColor={ACCENT} />
<MAMetricCard
- label="Total Deals"
- value={String(deals.length)}
- accentColor={ACCENT}
+ label="High Confidence"
+ value={String(highConfidenceFilings.length)}
+ accentColor={FINCEPT.GREEN}
+ subtitle={`${recentFilings.length > 0 ? ((highConfidenceFilings.length / recentFilings.length) * 100).toFixed(0) : 0}% of total`}
+ />
+ <MAMetricCard
+ label="Form Types"
+ value={String(new Set(recentFilings.map(f => f.filing_type)).size)}
+ accentColor={FINCEPT.CYAN}
/>
<MAMetricCard
- label="Total Value"
- value={formatCurrency(totalDealValue)}
+ label="Avg Confidence"
+ value={`${recentFilings.length > 0 ? ((recentFilings.reduce((s, f) => s + f.confidence_score, 0) / recentFilings.length) * 100).toFixed(0) : 0}%`}
accentColor={ACCENT}
/>
+ </div>
+
+ {/* Form type distribution chart */}
+ {filingTypeData.length > 0 && (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.DEFAULT, marginBottom: SPACING.LARGE }}>
+ <MAChartPanel title="Filing Type Distribution" icon={<FileText size={12} />} accentColor={ACCENT} height={200}>
+ <PieChart>
+ <Pie data={filingTypeData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={65}
+ label={({ name, value }) => `${name} (${value})`}
+ labelLine={{ stroke: FINCEPT.MUTED }}
+ style={{ fontSize: '9px', fontFamily: 'var(--ft-font-family, monospace)' }}>
+ {filingTypeData.map((_, i) => (
+ <Cell key={i} fill={CHART_PALETTE[i % CHART_PALETTE.length]} />
+ ))}
+ </Pie>
+ <Legend wrapperStyle={{ fontSize: '9px', fontFamily: 'var(--ft-font-family, monospace)' }} />
+ <Tooltip contentStyle={CHART_STYLE.tooltip} />
+ </PieChart>
+ </MAChartPanel>
+
+ {/* High confidence filings quick list */}
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ padding: SPACING.DEFAULT,
+ height: '200px',
+ overflow: 'auto',
+ }}>
+ <div style={{
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.GREEN, letterSpacing: TYPOGRAPHY.WIDE,
+ marginBottom: SPACING.SMALL, fontWeight: TYPOGRAPHY.BOLD,
+ }}>
+ HIGH CONFIDENCE FILINGS
+ </div>
+ {highConfidenceFilings.slice(0, 8).map((f, i) => (
+ <div
+ key={i}
+ onClick={() => { setSelectedFiling(f); setLeftTab('filings'); }}
+ style={{
+ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
+ padding: `${SPACING.TINY} 0`,
+ borderBottom: `1px solid ${FINCEPT.BORDER}20`,
+ cursor: 'pointer',
+ }}
+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = `${ACCENT}10`; }}
+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent'; }}
+ >
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div style={{
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.WHITE,
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' as const,
+ }}>
+ {f.company_name}
+ </div>
+ <div style={{
+ fontSize: '9px', fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.MUTED,
+ }}>
+ {f.filing_type} · {f.filing_date}
+ </div>
+ </div>
+ <span style={{
+ fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO,
+ color: CONFIDENCE_COLOR(f.confidence_score),
+ fontWeight: TYPOGRAPHY.BOLD, marginLeft: SPACING.SMALL,
+ flexShrink: 0,
+ }}>
+ {(f.confidence_score * 100).toFixed(0)}%
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </>
+ )}
+
+ {/* Deals Summary (if deals exist) */}
+ {deals.length > 0 && (
+ <>
+ <MASectionHeader
+ title="Deal Portfolio Summary"
+ subtitle={`${deals.length} deals`}
+ icon={<Database size={13} />}
+ accentColor={ACCENT}
+ />
+ <div style={{
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: SPACING.DEFAULT, marginBottom: SPACING.LARGE,
+ }}>
+ <MAMetricCard label="Total Deals" value={String(deals.length)} accentColor={ACCENT} />
+ <MAMetricCard label="Total Value" value={formatCurrency(totalDealValue)} accentColor={ACCENT} />
<MAMetricCard
label="Avg Premium"
value={`${avgPremium > 0 ? '+' : ''}${avgPremium.toFixed(1)}%`}
@@ -849,164 +1205,77 @@ export const DealDatabase: React.FC = () => {
subtitle={`${deals.length > 0 ? ((completedCount / deals.length) * 100).toFixed(0) : 0}% completion`}
/>
</div>
-
- {/* Charts Row */}
- <div style={{
- display: 'grid',
- gridTemplateColumns: '1fr 1fr',
- gap: SPACING.DEFAULT,
- marginBottom: SPACING.LARGE,
- }}>
- {/* Pipeline Pie Chart */}
- {pipelineData.length > 0 && (
- <MAChartPanel
- title="Deal Pipeline Status"
- icon={<BarChart3 size={12} />}
- accentColor={ACCENT}
- height={220}
- >
+ {pipelineData.length > 0 && timelineData.length > 0 && (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.DEFAULT, marginBottom: SPACING.LARGE }}>
+ <MAChartPanel title="Deal Pipeline Status" icon={<BarChart3 size={12} />} accentColor={ACCENT} height={220}>
<PieChart>
- <Pie
- data={pipelineData}
- dataKey="value"
- nameKey="name"
- cx="50%"
- cy="50%"
- outerRadius={70}
+ <Pie data={pipelineData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={70}
label={({ name, value }) => `${name} (${value})`}
labelLine={{ stroke: FINCEPT.MUTED }}
- style={{ fontSize: '9px', fontFamily: 'var(--ft-font-family, monospace)' }}
- >
+ style={{ fontSize: '9px', fontFamily: 'var(--ft-font-family, monospace)' }}>
{pipelineData.map((entry, i) => (
<Cell key={i} fill={STATUS_COLORS[entry.name] || CHART_PALETTE[i % CHART_PALETTE.length]} />
))}
</Pie>
- <Legend
- wrapperStyle={{ fontSize: '9px', fontFamily: 'var(--ft-font-family, monospace)' }}
- />
+ <Legend wrapperStyle={{ fontSize: '9px', fontFamily: 'var(--ft-font-family, monospace)' }} />
<Tooltip contentStyle={CHART_STYLE.tooltip} />
</PieChart>
</MAChartPanel>
- )}
-
- {/* Timeline Scatter Chart */}
- {timelineData.length > 0 && (
- <MAChartPanel
- title="Deal Value Timeline"
- icon={<Clock size={12} />}
- accentColor={ACCENT}
- height={220}
- >
+ <MAChartPanel title="Deal Value Timeline" icon={<Clock size={12} />} accentColor={ACCENT} height={220}>
<ScatterChart margin={{ top: 10, right: 10, bottom: 10, left: 10 }}>
<CartesianGrid stroke={CHART_STYLE.grid.stroke} strokeDasharray={CHART_STYLE.grid.strokeDasharray} />
- <XAxis
- type="number"
- dataKey="date"
- domain={['auto', 'auto']}
+ <XAxis type="number" dataKey="date" domain={['auto', 'auto']}
tickFormatter={(val) => new Date(val).toLocaleDateString()}
- tick={CHART_STYLE.axis}
- stroke={FINCEPT.BORDER}
- />
- <YAxis
- dataKey="value"
- tick={CHART_STYLE.axis}
- stroke={FINCEPT.BORDER}
- tickFormatter={(val) => {
- if (val >= 1e9) return `$${(val / 1e9).toFixed(0)}B`;
- if (val >= 1e6) return `$${(val / 1e6).toFixed(0)}M`;
- return `$${val}`;
- }}
- />
+ tick={CHART_STYLE.axis} stroke={FINCEPT.BORDER} />
+ <YAxis dataKey="value" tick={CHART_STYLE.axis} stroke={FINCEPT.BORDER}
+ tickFormatter={(val) => val >= 1e9 ? `$${(val / 1e9).toFixed(0)}B` : `$${(val / 1e6).toFixed(0)}M`} />
<ZAxis dataKey="premium" range={[20, 200]} />
<Scatter data={timelineData} fill={ACCENT} />
- <Tooltip
- contentStyle={CHART_STYLE.tooltip}
+ <Tooltip contentStyle={CHART_STYLE.tooltip}
formatter={(value: any, name: string) => {
if (name === 'date') return [new Date(value).toLocaleDateString(), 'Date'];
if (name === 'value') return [formatCurrency(value), 'Deal Value'];
- if (name === 'premium') return [`${value > 0 ? '+' : ''}${value.toFixed(1)}%`, 'Premium'];
+ if (name === 'premium') return [`${value > 0 ? '+' : ''}${(value).toFixed(1)}%`, 'Premium'];
return [value, name];
}}
- labelFormatter={() => ''}
- />
+ labelFormatter={() => ''} />
</ScatterChart>
</MAChartPanel>
- )}
- </div>
-
- {/* Recent SEC Filings */}
- {showFilings && recentFilings.length > 0 && (
- <>
- <MASectionHeader
- title="Recent SEC Filings"
- icon={<FileText size={13} />}
- accentColor={ACCENT}
- action={
- <button
- onClick={() => setShowFilings(false)}
- style={{
- ...COMMON_STYLES.buttonSecondary,
- padding: '3px 8px',
- fontSize: TYPOGRAPHY.TINY,
- }}
- >
- HIDE
- </button>
- }
- />
- <MADataTable
- columns={filingsColumns}
- data={recentFilings as any}
- accentColor={ACCENT}
- compact
- maxHeight="300px"
- emptyMessage="No filings found"
- />
- </>
+ </div>
)}
+ </>
+ )}
+
+ {/* Prompt to select a filing */}
+ {recentFilings.length > 0 && !deals.length && (
+ <div style={{
+ padding: SPACING.LARGE,
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${ACCENT}30`,
+ borderRadius: '2px',
+ textAlign: 'center',
+ fontSize: TYPOGRAPHY.SMALL,
+ fontFamily: TYPOGRAPHY.MONO,
+ color: FINCEPT.GRAY,
+ }}>
+ <FileText size={20} style={{ color: ACCENT, marginBottom: SPACING.SMALL, display: 'block', margin: '0 auto 8px' }} />
+ Select a filing from the list to view details
</div>
- ) : showFilings && recentFilings.length > 0 ? (
- /* No deals but filings scanned */
- <div style={{ flex: 1, overflow: 'auto', padding: SPACING.LARGE }}>
- <MASectionHeader
- title="Recent SEC Filings"
- icon={<FileText size={13} />}
- accentColor={ACCENT}
- action={
- <button
- onClick={() => setShowFilings(false)}
- style={{
- ...COMMON_STYLES.buttonSecondary,
- padding: '3px 8px',
- fontSize: TYPOGRAPHY.TINY,
- }}
- >
- HIDE
- </button>
- }
- />
- <MADataTable
- columns={filingsColumns}
- data={recentFilings as any}
- accentColor={ACCENT}
- compact
- maxHeight="600px"
- emptyMessage="No filings found"
- />
- </div>
- ) : (
- /* Full empty state */
- <MAEmptyState
- icon={<Database size={48} />}
- title="Deal Database"
- description="Scan SEC filings or select a deal to view details"
- accentColor={ACCENT}
- actionLabel="Scan SEC Filings"
- onAction={scanFilings}
- />
)}
</div>
)}
+
+ {/* ── EMPTY STATE ── */}
+ {panelView === 'empty' && (
+ <MAEmptyState
+ icon={<Database size={48} />}
+ title="Deal Database"
+ description="Scan SEC EDGAR to discover real M&A filings — no demo data, live signals only"
+ accentColor={ACCENT}
+ actionLabel="Scan SEC Filings"
+ onAction={scanFilings}
+ />
+ )}
</div>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/MergerAnalysis.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/MergerAnalysis.tsx
index a18b6dad7..104b4f161 100644
--- a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/MergerAnalysis.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/MergerAnalysis.tsx
@@ -798,8 +798,10 @@ export const MergerAnalysis: React.FC = () => {
];
const dealOverview = result.deal_overview || {};
- const goodwill = result.goodwill || {};
- const breakeven = result.breakeven_synergies || {};
+ // goodwill from Python is a raw float, not an object
+ const goodwillAmount = typeof result.goodwill === 'number' ? result.goodwill : (result.goodwill?.goodwill_amount || result.goodwill?.goodwill || 0);
+ // breakeven_synergies from Python is a raw float, not an object
+ const breakevenAmount = typeof result.breakeven_synergies === 'number' ? result.breakeven_synergies : (result.breakeven_synergies?.required_synergies || result.breakeven_synergies?.breakeven_amount || 0);
const contribAnalysis = result.contribution_analysis || {};
// Pro forma comparison chart
@@ -904,13 +906,12 @@ export const MergerAnalysis: React.FC = () => {
/>
<MAMetricCard
label="Goodwill Created"
- value={formatCurrency(goodwill.goodwill_amount || goodwill.goodwill || 0)}
+ value={formatCurrency(goodwillAmount)}
accentColor={CHART_PALETTE[2]}
/>
<MAMetricCard
label="Breakeven Synergies"
- value={formatCurrency(breakeven.required_synergies || breakeven.breakeven_amount || 0)}
- subtitle={breakeven.as_pct_of_target_revenue ? `${breakeven.as_pct_of_target_revenue.toFixed(1)}% of target rev` : undefined}
+ value={formatCurrency(breakevenAmount)}
accentColor={FINCEPT.CYAN}
/>
<MAMetricCard
diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/ValuationToolkit.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/ValuationToolkit.tsx
index 82d710549..47bf48997 100644
--- a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/ValuationToolkit.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/ValuationToolkit.tsx
@@ -33,6 +33,13 @@ export const ValuationToolkit: React.FC = () => {
beta: 1.2,
terminalGrowth: 0.025,
shares: 100,
+ marketCapM: 5000,
+ debtM: 1000,
+ costOfDebt: 0.05,
+ cash: 500,
+ depreciation: 100,
+ capex: 150,
+ changeInNwc: 20,
});
// LBO Returns Inputs (simple)
@@ -120,23 +127,23 @@ export const ValuationToolkit: React.FC = () => {
risk_free_rate: dcfInputs.riskFreeRate,
market_risk_premium: 0.06,
beta: dcfInputs.beta,
- cost_of_debt: 0.05,
+ cost_of_debt: dcfInputs.costOfDebt,
tax_rate: dcfInputs.taxRate,
- market_value_equity: 5000000000,
- market_value_debt: 1000000000,
+ market_value_equity: dcfInputs.marketCapM * 1000000,
+ market_value_debt: dcfInputs.debtM * 1000000,
},
fcf_inputs: {
ebit: dcfInputs.ebit * 1000000,
tax_rate: dcfInputs.taxRate,
- depreciation: 100000000,
- capex: 150000000,
- change_in_nwc: 20000000,
+ depreciation: dcfInputs.depreciation * 1000000,
+ capex: dcfInputs.capex * 1000000,
+ change_in_nwc: dcfInputs.changeInNwc * 1000000,
},
growth_rates: [0.15, 0.12, 0.10, 0.08, 0.06],
terminal_growth: dcfInputs.terminalGrowth,
balance_sheet: {
- cash: 500000000,
- debt: 1000000000,
+ cash: dcfInputs.cash * 1000000,
+ debt: dcfInputs.debtM * 1000000,
minority_interest: 0,
preferred_stock: 0,
},
@@ -599,6 +606,13 @@ export const ValuationToolkit: React.FC = () => {
{method === 'dcf' && (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px' }}>
{renderInputField('EBIT ($M)', dcfInputs.ebit, (v) => setDcfInputs({ ...dcfInputs, ebit: parseFloat(v) || 0 }))}
+ {renderInputField('DEPRECIATION ($M)', dcfInputs.depreciation, (v) => setDcfInputs({ ...dcfInputs, depreciation: parseFloat(v) || 0 }))}
+ {renderInputField('CAPEX ($M)', dcfInputs.capex, (v) => setDcfInputs({ ...dcfInputs, capex: parseFloat(v) || 0 }))}
+ {renderInputField('CHANGE IN NWC ($M)', dcfInputs.changeInNwc, (v) => setDcfInputs({ ...dcfInputs, changeInNwc: parseFloat(v) || 0 }))}
+ {renderInputField('MARKET CAP ($M)', dcfInputs.marketCapM, (v) => setDcfInputs({ ...dcfInputs, marketCapM: parseFloat(v) || 0 }))}
+ {renderInputField('TOTAL DEBT ($M)', dcfInputs.debtM, (v) => setDcfInputs({ ...dcfInputs, debtM: parseFloat(v) || 0 }))}
+ {renderInputField('CASH ($M)', dcfInputs.cash, (v) => setDcfInputs({ ...dcfInputs, cash: parseFloat(v) || 0 }))}
+ {renderInputField('COST OF DEBT', dcfInputs.costOfDebt, (v) => setDcfInputs({ ...dcfInputs, costOfDebt: parseFloat(v) || 0 }))}
{renderInputField('TAX RATE', dcfInputs.taxRate, (v) => setDcfInputs({ ...dcfInputs, taxRate: parseFloat(v) || 0 }))}
{renderInputField('RISK-FREE RATE', dcfInputs.riskFreeRate, (v) => setDcfInputs({ ...dcfInputs, riskFreeRate: parseFloat(v) || 0 }))}
{renderInputField('BETA', dcfInputs.beta, (v) => setDcfInputs({ ...dcfInputs, beta: parseFloat(v) || 0 }))}
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/NodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/NodeEditorTab.tsx
index 69d68a8c0..6d5359a97 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/NodeEditorTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/NodeEditorTab.tsx
@@ -7,6 +7,7 @@
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';
+import { useTimezone } from '@/contexts/TimezoneContext';
import ReactFlow, {
Node,
Edge,
@@ -44,7 +45,8 @@ import {
} from './components';
// Local hooks
-import { useWorkflowManagement } from './hooks';
+import { useWorkflowManagement, useUndoRedo } from './hooks';
+import { stripCallbacks } from './utils';
// Node components
import {
@@ -78,10 +80,14 @@ import { TabFooter } from '@/components/common/TabFooter';
export default function NodeEditorTab() {
const { t } = useTranslation('nodeEditor');
+ const { timezone } = useTimezone();
// MCP configurations
const [mcpNodeConfigs, setMcpNodeConfigs] = useState<MCPNodeConfig[]>([]);
+ // Shared ref for undo/redo <-> auto-save coordination
+ const isUndoRedoActionRef = useRef<boolean>(false);
+
// Workflow management hook
const {
nodes,
@@ -114,7 +120,7 @@ export default function NodeEditorTab() {
deleteSelectedNodes,
deleteSelectedEdges,
onSelectionChange,
- } = useWorkflowManagement();
+ } = useWorkflowManagement(isUndoRedoActionRef);
// UI state
const [showNodeMenu, setShowNodeMenu] = useState(false);
@@ -128,6 +134,9 @@ export default function NodeEditorTab() {
const reactFlowWrapper = useRef<HTMLDivElement>(null);
+ // Clipboard for copy/paste
+ const clipboardRef = useRef<{ nodes: Node[]; edges: Edge[] } | null>(null);
+
// Workspace tab state
const getWorkspaceState = useCallback(() => ({
activeView,
@@ -188,9 +197,14 @@ export default function NodeEditorTab() {
[]
);
+ // Refs to hold undo/redo snapshot functions (breaks circular dependency)
+ const takeSnapshotRef = useRef<() => void>(() => {});
+ const takeDebouncedSnapshotRef = useRef<() => void>(() => {});
+
// Handle label change
const handleLabelChange = useCallback(
(nodeId: string, newLabel: string) => {
+ takeDebouncedSnapshotRef.current();
setNodes((nds) =>
nds.map((node) => {
if (node.id === nodeId) {
@@ -209,9 +223,36 @@ export default function NodeEditorTab() {
[setNodes]
);
+ // Re-attach function callbacks to nodes after undo/redo restore
+ const reattachCallbacks = useCallback(
+ (restoredNodes: Node[]): Node[] =>
+ restoredNodes.map((node) => {
+ if (node.type === 'custom') {
+ return { ...node, data: { ...node.data, onLabelChange: handleLabelChange } };
+ }
+ return node;
+ }),
+ [handleLabelChange]
+ );
+
+ // Undo/Redo hook
+ const { takeSnapshot, takeDebouncedSnapshot, undo, redo, canUndo, canRedo } = useUndoRedo({
+ nodes,
+ edges,
+ setNodes,
+ setEdges,
+ isUndoRedoActionRef,
+ restoreCallbacks: reattachCallbacks,
+ });
+
+ // Keep refs in sync with latest hook values
+ takeSnapshotRef.current = takeSnapshot;
+ takeDebouncedSnapshotRef.current = takeDebouncedSnapshot;
+
// Handle connection
const onConnect = useCallback(
(params: Connection) => {
+ takeSnapshot();
const newEdge = {
...params,
animated: true,
@@ -220,19 +261,20 @@ export default function NodeEditorTab() {
};
setEdges((eds) => addEdge(newEdge, eds));
},
- [setEdges]
+ [setEdges, takeSnapshot]
);
// Add new node
const addNode = useCallback(
(config: any) => {
+ takeSnapshot();
const isMCPNode = config.type === 'mcp-tool';
const isResultsDisplay = config.type === 'results-display';
const isAgentMediator = config.type === 'agent-mediator';
const isDataSource = config.type === 'data-source';
const isTechnicalIndicator = config.type === 'technical-indicator';
- const nodeId = `node_${Date.now()}`;
+ const nodeId = `node_${crypto.randomUUID()}`;
const newNode: Node = {
id: nodeId,
@@ -350,7 +392,7 @@ export default function NodeEditorTab() {
setNodes((nds) => [...nds, newNode]);
setShowNodeMenu(false);
},
- [setNodes, handleLabelChange]
+ [setNodes, handleLabelChange, takeSnapshot]
);
// Handle node from palette
@@ -363,9 +405,10 @@ export default function NodeEditorTab() {
} else if (nodeData.source === 'agent') {
addNode({ ...nodeData.data, type: 'python-agent' });
} else if (nodeData.source === 'registry') {
+ takeSnapshot();
const registryNode = nodeData.data as INodeTypeDescription;
const newNode: Node = {
- id: `node_${Date.now()}`,
+ id: `node_${crypto.randomUUID()}`,
type: 'custom',
position: { x: Math.random() * 400 + 100, y: Math.random() * 300 + 100 },
data: {
@@ -386,7 +429,7 @@ export default function NodeEditorTab() {
setShowNodeMenu(false);
},
- [addNode, setNodes, handleLabelChange]
+ [addNode, setNodes, handleLabelChange, takeSnapshot]
);
// Handle drop from palette
@@ -407,9 +450,10 @@ export default function NodeEditorTab() {
};
if (nodeData.source === 'registry') {
+ takeSnapshot();
const registryNode = nodeData.data as INodeTypeDescription;
const newNode: Node = {
- id: `node_${Date.now()}`,
+ id: `node_${crypto.randomUUID()}`,
type: 'custom',
position,
data: {
@@ -430,7 +474,7 @@ export default function NodeEditorTab() {
handlePaletteNodeAdd(nodeData.type, nodeData);
}
},
- [setNodes, handlePaletteNodeAdd, handleLabelChange]
+ [setNodes, handlePaletteNodeAdd, handleLabelChange, takeSnapshot]
);
const onDragOver = useCallback((event: React.DragEvent) => {
@@ -438,6 +482,28 @@ export default function NodeEditorTab() {
event.dataTransfer.dropEffect = 'move';
}, []);
+ // Connection validation
+ const isValidConnection = useCallback(
+ (connection: Connection) => {
+ // Prevent self-loops
+ if (connection.source === connection.target) return false;
+ // Prevent duplicate connections
+ const exists = edges.some(
+ (e) => e.source === connection.source && e.target === connection.target
+ );
+ if (exists) return false;
+ // Check hasInput/hasOutput from BUILTIN_NODE_CONFIGS
+ const sourceNode = nodes.find((n) => n.id === connection.source);
+ const targetNode = nodes.find((n) => n.id === connection.target);
+ const sourceConfig = BUILTIN_NODE_CONFIGS.find((c) => c.type === sourceNode?.type);
+ const targetConfig = BUILTIN_NODE_CONFIGS.find((c) => c.type === targetNode?.type);
+ if (sourceConfig && !sourceConfig.hasOutput) return false;
+ if (targetConfig && !targetConfig.hasInput) return false;
+ return true;
+ },
+ [edges, nodes]
+ );
+
// Execute workflow
const handleExecute = useCallback(async () => {
if (isExecuting) {
@@ -445,6 +511,11 @@ export default function NodeEditorTab() {
return;
}
+ if (nodes.length === 0) {
+ showWarning('No nodes in the workflow. Add nodes before executing.');
+ return;
+ }
+
try {
setIsExecuting(true);
await nodeExecutionManager.executeWorkflow(nodes, edges, (nodeId, status, result) => {
@@ -474,32 +545,14 @@ export default function NodeEditorTab() {
return node;
})
);
- });
+ }, timezone.zone);
} catch (error: any) {
console.error('[NodeEditor] Workflow execution failed:', error);
+ showError('Execution failed', [{ label: 'Error', value: error.message }]);
} finally {
setIsExecuting(false);
}
- }, [isExecuting, nodes, edges, setNodes, setIsExecuting]);
-
- // Handle keyboard shortcuts
- useEffect(() => {
- const handleKeyDown = (event: KeyboardEvent) => {
- // Don't trigger if user is typing in an input field
- const target = event.target as HTMLElement;
- if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
- return;
- }
-
- if (event.key === 'Delete' || event.key === 'Backspace') {
- deleteSelectedNodes();
- deleteSelectedEdges();
- }
- };
-
- window.addEventListener('keydown', handleKeyDown);
- return () => window.removeEventListener('keydown', handleKeyDown);
- }, [deleteSelectedNodes, deleteSelectedEdges]);
+ }, [isExecuting, nodes, edges, setNodes, setIsExecuting, timezone.zone]);
// Quick save draft handler
const handleQuickSaveDraft = useCallback(async () => {
@@ -638,6 +691,7 @@ export default function NodeEditorTab() {
// Handle parameter change for config panel
const handleParameterChange = useCallback(
(paramName: string, value: NodeParameterValue) => {
+ takeDebouncedSnapshot();
if (selectedNodes.length === 1) {
setNodes((nds) =>
nds.map((node) => {
@@ -658,7 +712,29 @@ export default function NodeEditorTab() {
);
}
},
- [selectedNodes, setNodes]
+ [selectedNodes, setNodes, takeDebouncedSnapshot]
+ );
+
+ // Handle timeout change for per-node execution timeout
+ const handleTimeoutChange = useCallback(
+ (nodeId: string, timeoutMs: number | undefined) => {
+ takeDebouncedSnapshot();
+ setNodes((nds) =>
+ nds.map((node) => {
+ if (node.id === nodeId) {
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ timeoutMs,
+ },
+ };
+ }
+ return node;
+ })
+ );
+ },
+ [setNodes, takeDebouncedSnapshot]
);
// Handle duplicate node
@@ -666,19 +742,132 @@ export default function NodeEditorTab() {
if (selectedNodes.length === 1) {
const selectedNode = nodes.find((n) => n.id === selectedNodes[0]);
if (selectedNode) {
+ takeSnapshot();
+ const newNodeId = `node_${crypto.randomUUID()}`;
+ // Deep clone data to avoid shared references between original and duplicate
+ const clonedData = JSON.parse(JSON.stringify(selectedNode.data));
+ // Re-attach callback for custom nodes
+ if (selectedNode.type === 'custom') {
+ clonedData.onLabelChange = handleLabelChange;
+ }
const newNode = {
...selectedNode,
- id: `node_${Date.now()}`,
+ id: newNodeId,
position: {
x: selectedNode.position.x + 50,
y: selectedNode.position.y + 50,
},
- data: { ...selectedNode.data },
+ data: clonedData,
};
setNodes((nds) => [...nds, newNode]);
}
}
- }, [selectedNodes, nodes, setNodes]);
+ }, [selectedNodes, nodes, setNodes, handleLabelChange, takeSnapshot]);
+
+ // Copy selected nodes and their interconnecting edges
+ const handleCopy = useCallback(() => {
+ if (selectedNodes.length === 0) return;
+ const selectedSet = new Set(selectedNodes);
+ const copiedNodes = nodes
+ .filter((n) => selectedSet.has(n.id))
+ .map((n) => ({
+ ...n,
+ data: stripCallbacks(n.data),
+ }));
+ const copiedEdges = edges.filter(
+ (e) => selectedSet.has(e.source) && selectedSet.has(e.target)
+ );
+ clipboardRef.current = { nodes: copiedNodes, edges: copiedEdges };
+ }, [selectedNodes, nodes, edges]);
+
+ // Paste copied nodes with new IDs and offset positions
+ const handlePaste = useCallback(() => {
+ if (!clipboardRef.current || clipboardRef.current.nodes.length === 0) return;
+ takeSnapshot();
+
+ const { nodes: copiedNodes, edges: copiedEdges } = clipboardRef.current;
+ // Build old→new ID map
+ const idMap = new Map<string, string>();
+ copiedNodes.forEach((n) => {
+ idMap.set(n.id, `node_${crypto.randomUUID()}`);
+ });
+
+ const pastedNodes: Node[] = copiedNodes.map((n) => {
+ const clonedData = JSON.parse(JSON.stringify(n.data));
+ // Re-attach callbacks based on node type
+ if (n.type === 'custom') {
+ clonedData.onLabelChange = handleLabelChange;
+ }
+ return {
+ ...n,
+ id: idMap.get(n.id)!,
+ position: { x: n.position.x + 50, y: n.position.y + 50 },
+ selected: true,
+ data: clonedData,
+ };
+ });
+
+ const pastedEdges: Edge[] = copiedEdges.map((e) => ({
+ ...e,
+ id: `edge_${crypto.randomUUID()}`,
+ source: idMap.get(e.source) || e.source,
+ target: idMap.get(e.target) || e.target,
+ }));
+
+ // Deselect existing nodes, add pasted ones (selected)
+ setNodes((nds) => [
+ ...nds.map((n) => ({ ...n, selected: false })),
+ ...pastedNodes,
+ ]);
+ setEdges((eds) => [...eds, ...pastedEdges]);
+
+ // Update selectedNodes to the newly pasted ones
+ setSelectedNodes(pastedNodes.map((n) => n.id));
+ }, [takeSnapshot, handleLabelChange, setNodes, setEdges, setSelectedNodes]);
+
+ // Handle keyboard shortcuts
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ // Don't trigger if user is typing in an input field
+ const target = event.target as HTMLElement;
+ if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
+ return;
+ }
+
+ if (event.key === 'Delete' || event.key === 'Backspace') {
+ takeSnapshot();
+ deleteSelectedNodes();
+ deleteSelectedEdges();
+ }
+
+ // Copy: Ctrl+C
+ if ((event.ctrlKey || event.metaKey) && event.key === 'c') {
+ event.preventDefault();
+ handleCopy();
+ }
+
+ // Paste: Ctrl+V
+ if ((event.ctrlKey || event.metaKey) && event.key === 'v') {
+ event.preventDefault();
+ handlePaste();
+ }
+
+ // Undo: Ctrl+Z
+ if ((event.ctrlKey || event.metaKey) && event.key === 'z' && !event.shiftKey) {
+ event.preventDefault();
+ undo();
+ }
+
+ // Redo: Ctrl+Shift+Z or Ctrl+Y
+ if ((event.ctrlKey || event.metaKey) && (event.key === 'y' || (event.key === 'z' && event.shiftKey) || (event.key === 'Z' && event.shiftKey))) {
+ event.preventDefault();
+ redo();
+ }
+ };
+
+ window.addEventListener('keydown', handleKeyDown);
+ return () => window.removeEventListener('keydown', handleKeyDown);
+ }, [deleteSelectedNodes, deleteSelectedEdges, takeSnapshot, undo, redo, handleCopy, handlePaste]);
// Import workflow template
const handleImportTemplate = useCallback(
@@ -788,6 +977,10 @@ export default function NodeEditorTab() {
onShowDeployDialog={() => setShowDeployDialog(true)}
onQuickSaveDraft={handleQuickSaveDraft}
onShowTemplates={() => setShowTemplateGallery(true)}
+ canUndo={canUndo}
+ canRedo={canRedo}
+ onUndo={undo}
+ onRedo={redo}
/>
{/* Node Menu */}
@@ -971,6 +1164,8 @@ export default function NodeEditorTab() {
onEdgesChange={onEdgesChange}
onConnect={onConnect}
onSelectionChange={onSelectionChange}
+ onNodeDragStart={takeSnapshot}
+ isValidConnection={isValidConnection}
nodeTypes={nodeTypes}
fitView
style={{ background: '#0a0a0a' }}
@@ -1023,6 +1218,7 @@ export default function NodeEditorTab() {
selectedNode={selectedNode}
onLabelChange={handleLabelChange}
onParameterChange={handleParameterChange}
+ onTimeoutChange={handleTimeoutChange}
onClose={() => setSelectedNodes([])}
onDelete={deleteSelectedNodes}
onDuplicate={handleDuplicateNode}
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 0c75eb87a..cafae38b6 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
@@ -20,6 +20,7 @@ import {
Play,
BarChart3,
Zap,
+ Clock,
} from 'lucide-react';
import { NodeParameterInput } from '../nodes/NodeParameterInput';
import type { INodeProperties, NodeParameterValue } from '@/services/nodeSystem';
@@ -36,6 +37,7 @@ interface NodeConfigPanelProps {
selectedNode: Node;
onLabelChange: (nodeId: string, newLabel: string) => void;
onParameterChange: (paramName: string, value: NodeParameterValue) => void;
+ onTimeoutChange: (nodeId: string, timeoutMs: number | undefined) => void;
onClose: () => void;
onDelete: () => void;
onDuplicate: () => void;
@@ -125,6 +127,7 @@ const NodeConfigPanel: React.FC<NodeConfigPanelProps> = ({
selectedNode,
onLabelChange,
onParameterChange,
+ onTimeoutChange,
onClose,
onDelete,
onDuplicate,
@@ -150,7 +153,8 @@ const NodeConfigPanel: React.FC<NodeConfigPanelProps> = ({
const [amProvider, setAmProvider] = useState(selectedNode.data.selectedProvider || '');
const [amPrompt, setAmPrompt] = useState(selectedNode.data.customPrompt || '');
- // Sync local state when node changes
+ // Sync local state when node changes or when node data is updated externally
+ // (e.g., after execution, loading from storage, or another component updating the node)
useEffect(() => {
setLocalConnection(selectedNode.data.selectedConnectionId || '');
setLocalQuery(selectedNode.data.query || '');
@@ -160,7 +164,17 @@ const NodeConfigPanel: React.FC<NodeConfigPanelProps> = ({
setTiCategories(selectedNode.data.categories || ['momentum', 'volume', 'volatility', 'trend', 'others']);
setAmProvider(selectedNode.data.selectedProvider || '');
setAmPrompt(selectedNode.data.customPrompt || '');
- }, [selectedNode.id]);
+ }, [
+ selectedNode.id,
+ selectedNode.data.selectedConnectionId,
+ selectedNode.data.query,
+ selectedNode.data.dataSource,
+ selectedNode.data.symbol,
+ selectedNode.data.period,
+ selectedNode.data.categories,
+ selectedNode.data.selectedProvider,
+ selectedNode.data.customPrompt,
+ ]);
// Check if this is a custom node type that needs special handling
const isDataSourceNode = selectedNode.type === 'data-source';
@@ -968,6 +982,69 @@ const NodeConfigPanel: React.FC<NodeConfigPanelProps> = ({
</div>
</div>
+ {/* Execution Timeout */}
+ <div style={{ padding: SPACING.LG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: SPACING.MD,
+ marginBottom: SPACING.MD,
+ }}
+ >
+ <Clock size={12} color={FINCEPT.GRAY} />
+ <span
+ style={{
+ color: FINCEPT.ORANGE,
+ fontSize: FONT_SIZE.SM,
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}
+ >
+ EXECUTION TIMEOUT
+ </span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.MD }}>
+ <input
+ type="number"
+ min={1}
+ max={600}
+ placeholder="30"
+ value={selectedNode.data.timeoutMs != null ? selectedNode.data.timeoutMs / 1000 : ''}
+ onChange={(e) => {
+ const val = e.target.value;
+ if (val === '' || val === '0') {
+ onTimeoutChange(selectedNode.id, undefined);
+ } else {
+ const seconds = parseInt(val, 10);
+ if (!isNaN(seconds) && seconds > 0) {
+ onTimeoutChange(selectedNode.id, seconds * 1000);
+ }
+ }
+ }}
+ style={{
+ ...textInputStyle,
+ width: '80px',
+ flex: 'none',
+ }}
+ />
+ <span style={{ color: FINCEPT.GRAY, fontSize: FONT_SIZE.SM }}>
+ seconds
+ </span>
+ </div>
+ <div
+ style={{
+ marginTop: SPACING.XS,
+ fontSize: FONT_SIZE.XS,
+ color: FINCEPT.GRAY,
+ opacity: 0.6,
+ }}
+ >
+ Default: 30s. Leave blank to use default.
+ </div>
+ </div>
+
{/* Description (for registry nodes) */}
{registryData?.description && (
<div style={{ padding: SPACING.LG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodeEditorToolbar.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodeEditorToolbar.tsx
index e6577c99e..ef0061ebd 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodeEditorToolbar.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodeEditorToolbar.tsx
@@ -14,6 +14,8 @@ import {
Trash2,
Rocket,
LayoutTemplate,
+ Undo2,
+ Redo2,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type { NodeEditorToolbarProps } from '../types';
@@ -39,6 +41,10 @@ const NodeEditorToolbar: React.FC<NodeEditorToolbarProps> = ({
onShowDeployDialog,
onQuickSaveDraft,
onShowTemplates,
+ canUndo,
+ canRedo,
+ onUndo,
+ onRedo,
}) => {
const { t } = useTranslation('nodeEditor');
@@ -190,6 +196,77 @@ const NodeEditorToolbar: React.FC<NodeEditorToolbarProps> = ({
<div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }} />
+ {/* Undo / Redo */}
+ <button
+ onClick={onUndo}
+ disabled={!canUndo}
+ style={{
+ backgroundColor: 'transparent',
+ color: canUndo ? '#a3a3a3' : '#525252',
+ border: `1px solid ${canUndo ? '#404040' : '#333333'}`,
+ padding: '6px 10px',
+ fontSize: '11px',
+ cursor: canUndo ? 'pointer' : 'not-allowed',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '5px',
+ opacity: canUndo ? 1 : 0.4,
+ }}
+ onMouseEnter={(e) => {
+ if (canUndo) {
+ e.currentTarget.style.backgroundColor = '#2d2d2d';
+ e.currentTarget.style.color = 'white';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (canUndo) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#a3a3a3';
+ }
+ }}
+ title="Undo (Ctrl+Z)"
+ >
+ <Undo2 size={14} />
+ UNDO
+ </button>
+
+ <button
+ onClick={onRedo}
+ disabled={!canRedo}
+ style={{
+ backgroundColor: 'transparent',
+ color: canRedo ? '#a3a3a3' : '#525252',
+ border: `1px solid ${canRedo ? '#404040' : '#333333'}`,
+ padding: '6px 10px',
+ fontSize: '11px',
+ cursor: canRedo ? 'pointer' : 'not-allowed',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '5px',
+ opacity: canRedo ? 1 : 0.4,
+ }}
+ onMouseEnter={(e) => {
+ if (canRedo) {
+ e.currentTarget.style.backgroundColor = '#2d2d2d';
+ e.currentTarget.style.color = 'white';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (canRedo) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#a3a3a3';
+ }
+ }}
+ title="Redo (Ctrl+Shift+Z)"
+ >
+ <Redo2 size={14} />
+ REDO
+ </button>
+
+ <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }} />
+
{/* New Workflow Button */}
<button
onClick={async () => {
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodePalette.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodePalette.tsx
index b9d86a029..9a7b699d0 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodePalette.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodePalette.tsx
@@ -11,6 +11,19 @@ import { NodeRegistry, INodeTypeDescription } from '@/services/nodeSystem';
import { BUILTIN_NODE_CONFIGS, CATEGORY_CONFIG } from '../constants';
import type { NodePaletteProps, PaletteNodeItem } from '../types';
+// Non-functional nodes to hide from the palette.
+// These nodes have stub implementations (credentials not wired, binary pipeline missing,
+// trigger infrastructure absent, or call non-existent helpers).
+// The code is kept for future implementation — we just hide them from the UI.
+const HIDDEN_NODES = new Set([
+ // Notifications — credential retrieval not implemented
+ 'Discord', 'Email', 'Slack', 'SMS', 'Telegram', 'Webhook',
+ // Files — no binary pipeline in the executor
+ 'BinaryFile', 'Compress', 'ConvertToFile', 'FileOperations', 'SpreadsheetFile',
+ // Control flow — calls non-existent ExecuteWorkflow helper
+ 'ExecuteWorkflow',
+]);
+
const NodePalette: React.FC<NodePaletteProps> = ({
onNodeAdd,
isCollapsed,
@@ -23,6 +36,7 @@ const NodePalette: React.FC<NodePaletteProps> = ({
);
// Get all registered nodes from NodeRegistry
+ // Re-evaluated when mcpNodeConfigs changes (which happens after NodeLoader.loadAll() completes)
const registryNodes = useMemo(() => {
try {
return NodeRegistry.getAllNodes();
@@ -30,7 +44,8 @@ const NodePalette: React.FC<NodePaletteProps> = ({
console.warn('[NodePalette] NodeRegistry not initialized yet');
return [];
}
- }, []);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [mcpNodeConfigs]);
// Combine builtin nodes with registry nodes
const allNodes = useMemo(() => {
@@ -50,6 +65,9 @@ const NodePalette: React.FC<NodePaletteProps> = ({
});
registryNodes.forEach((node: INodeTypeDescription) => {
+ // Skip non-functional nodes
+ if (HIDDEN_NODES.has(node.name)) return;
+
const category = node.group?.[0] || 'Core';
const categoryConfig = CATEGORY_CONFIG[category] || CATEGORY_CONFIG['Core'];
nodes.push({
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/node-editor/hooks/index.ts
index 22276d546..92ccc319d 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/hooks/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/hooks/index.ts
@@ -3,3 +3,4 @@
*/
export { useWorkflowManagement } from './useWorkflowManagement';
+export { useUndoRedo } from './useUndoRedo';
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/hooks/useUndoRedo.ts b/fincept-terminal-desktop/src/components/tabs/node-editor/hooks/useUndoRedo.ts
new file mode 100644
index 000000000..8df07c360
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/hooks/useUndoRedo.ts
@@ -0,0 +1,167 @@
+/**
+ * useUndoRedo Hook
+ *
+ * Snapshot-based undo/redo for the Node Editor.
+ * Uses useRef for history stacks to avoid re-renders on every snapshot,
+ * with useState only for canUndo/canRedo (toolbar button state).
+ */
+
+import { useState, useRef, useCallback } from 'react';
+import { Node, Edge } from 'reactflow';
+import { stripCallbacks } from '../utils';
+
+interface Snapshot {
+ nodes: Node[];
+ edges: Edge[];
+}
+
+export interface UseUndoRedoParams {
+ nodes: Node[];
+ edges: Edge[];
+ setNodes: React.Dispatch<React.SetStateAction<Node[]>>;
+ setEdges: React.Dispatch<React.SetStateAction<Edge[]>>;
+ isUndoRedoActionRef: React.MutableRefObject<boolean>;
+ restoreCallbacks?: (nodes: Node[]) => Node[];
+ maxHistory?: number;
+ debounceMs?: number;
+}
+
+export interface UseUndoRedoReturn {
+ takeSnapshot: () => void;
+ takeDebouncedSnapshot: () => void;
+ undo: () => void;
+ redo: () => void;
+ canUndo: boolean;
+ canRedo: boolean;
+}
+
+export function useUndoRedo({
+ nodes,
+ edges,
+ setNodes,
+ setEdges,
+ isUndoRedoActionRef,
+ restoreCallbacks,
+ maxHistory = 50,
+ debounceMs = 300,
+}: UseUndoRedoParams): UseUndoRedoReturn {
+ const pastRef = useRef<Snapshot[]>([]);
+ const futureRef = useRef<Snapshot[]>([]);
+ const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const pendingSnapshotRef = useRef<boolean>(false);
+
+ const [canUndo, setCanUndo] = useState(false);
+ const [canRedo, setCanRedo] = useState(false);
+
+ /** Update the boolean state for toolbar buttons */
+ const syncButtonState = useCallback(() => {
+ setCanUndo(pastRef.current.length > 0);
+ setCanRedo(futureRef.current.length > 0);
+ }, []);
+
+ /** Create a serializable snapshot of current state */
+ const createSnapshot = useCallback((): Snapshot => {
+ return {
+ nodes: nodes.map((n) => ({
+ ...n,
+ data: stripCallbacks(n.data),
+ })),
+ edges: edges.map((e) => ({ ...e })),
+ };
+ }, [nodes, edges]);
+
+ /** Push current state to the past stack, clear future */
+ const takeSnapshot = useCallback(() => {
+ const snapshot = createSnapshot();
+ pastRef.current = [...pastRef.current.slice(-(maxHistory - 1)), snapshot];
+ futureRef.current = [];
+ syncButtonState();
+ }, [createSnapshot, maxHistory, syncButtonState]);
+
+ /** Flush any pending debounced snapshot immediately */
+ const flushDebouncedSnapshot = useCallback(() => {
+ if (debounceTimerRef.current) {
+ clearTimeout(debounceTimerRef.current);
+ debounceTimerRef.current = null;
+ }
+ if (pendingSnapshotRef.current) {
+ pendingSnapshotRef.current = false;
+ // The snapshot was already captured when the debounce started;
+ // we just need to ensure it's flushed. Since takeSnapshot captures
+ // current state, and the state may have changed, we take a fresh one.
+ takeSnapshot();
+ }
+ }, [takeSnapshot]);
+
+ /** Debounced snapshot for rapid changes (label typing, parameter tweaks) */
+ const takeDebouncedSnapshot = useCallback(() => {
+ // On first call in a burst, take an immediate snapshot of the pre-change state
+ if (!pendingSnapshotRef.current) {
+ pendingSnapshotRef.current = true;
+ takeSnapshot();
+ }
+
+ // Reset the debounce timer
+ if (debounceTimerRef.current) {
+ clearTimeout(debounceTimerRef.current);
+ }
+ debounceTimerRef.current = setTimeout(() => {
+ pendingSnapshotRef.current = false;
+ debounceTimerRef.current = null;
+ }, debounceMs);
+ }, [takeSnapshot, debounceMs]);
+
+ /** Restore a snapshot */
+ const restoreSnapshot = useCallback(
+ (snapshot: Snapshot) => {
+ isUndoRedoActionRef.current = true;
+ const restoredNodes = restoreCallbacks
+ ? restoreCallbacks(snapshot.nodes)
+ : snapshot.nodes;
+ setNodes(restoredNodes);
+ setEdges(snapshot.edges);
+ },
+ [setNodes, setEdges, isUndoRedoActionRef, restoreCallbacks]
+ );
+
+ /** Undo: pop from past, push current to future */
+ const undo = useCallback(() => {
+ flushDebouncedSnapshot();
+
+ if (pastRef.current.length === 0) return;
+
+ const currentSnapshot = createSnapshot();
+ const previous = pastRef.current[pastRef.current.length - 1];
+
+ pastRef.current = pastRef.current.slice(0, -1);
+ futureRef.current = [...futureRef.current, currentSnapshot];
+
+ restoreSnapshot(previous);
+ syncButtonState();
+ }, [createSnapshot, restoreSnapshot, flushDebouncedSnapshot, syncButtonState]);
+
+ /** Redo: pop from future, push current to past */
+ const redo = useCallback(() => {
+ flushDebouncedSnapshot();
+
+ if (futureRef.current.length === 0) return;
+
+ const currentSnapshot = createSnapshot();
+ const next = futureRef.current[futureRef.current.length - 1];
+
+ futureRef.current = futureRef.current.slice(0, -1);
+ pastRef.current = [...pastRef.current, currentSnapshot];
+
+ restoreSnapshot(next);
+ syncButtonState();
+ }, [createSnapshot, restoreSnapshot, flushDebouncedSnapshot, syncButtonState]);
+
+ return {
+ takeSnapshot,
+ takeDebouncedSnapshot,
+ undo,
+ redo,
+ canUndo,
+ canRedo,
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/hooks/useWorkflowManagement.ts b/fincept-terminal-desktop/src/components/tabs/node-editor/hooks/useWorkflowManagement.ts
index 3367e8527..228a84f37 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/hooks/useWorkflowManagement.ts
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/hooks/useWorkflowManagement.ts
@@ -8,8 +8,9 @@ import { useState, useCallback, useEffect } from 'react';
import { Node, Edge, useNodesState, useEdgesState } from 'reactflow';
import { saveSetting, getSetting } from '@/services/core/sqliteService';
import { workflowService, Workflow as WorkflowType } from '@/services/core/workflowService';
-import { workflowExecutor } from '../nodes/WorkflowExecutor';
-import { showWarning, showError, showConfirm } from '@/utils/notifications';
+import { nodeExecutionManager } from '@/services/core/nodeExecutionManager';
+import { showWarning, showError, showSuccess, showConfirm } from '@/utils/notifications';
+import { stripCallbacks } from '../utils';
export interface UseWorkflowManagementReturn {
// Node and edge state
@@ -55,7 +56,9 @@ export interface UseWorkflowManagementReturn {
onSelectionChange: (params: any) => void;
}
-export function useWorkflowManagement(): UseWorkflowManagementReturn {
+export function useWorkflowManagement(
+ isUndoRedoActionRef?: React.MutableRefObject<boolean>
+): UseWorkflowManagementReturn {
// Node and edge state
const [nodes, setNodes, onNodesChange] = useNodesState([]);
const [edges, setEdges, onEdgesChange] = useEdgesState([]);
@@ -99,24 +102,38 @@ export function useWorkflowManagement(): UseWorkflowManagementReturn {
// Auto-save workflow to storage whenever nodes or edges change
useEffect(() => {
+ // If this state change came from undo/redo, use a longer delay
+ // to avoid rapid saves during undo/redo sequences
+ const delay = isUndoRedoActionRef?.current ? 2000 : 500;
+ if (isUndoRedoActionRef?.current) {
+ isUndoRedoActionRef.current = false;
+ }
+
const saveWorkflowAuto = async () => {
try {
- const workflow = { nodes, edges };
+ const serializableNodes = nodes.map((n) => ({
+ ...n,
+ data: stripCallbacks(n.data),
+ }));
+ const workflow = { nodes: serializableNodes, edges };
await saveSetting('nodeEditorWorkflow', JSON.stringify(workflow), 'node_editor');
} catch (error) {
console.error('[useWorkflowManagement] Failed to auto-save workflow:', error);
}
};
- // Debounce saves
- const timeoutId = setTimeout(saveWorkflowAuto, 500);
+ const timeoutId = setTimeout(saveWorkflowAuto, delay);
return () => clearTimeout(timeoutId);
}, [nodes, edges]);
// Save workflow manually
const saveWorkflow = useCallback(async () => {
try {
- const workflow = { nodes, edges };
+ const serializableNodes = nodes.map((n) => ({
+ ...n,
+ data: stripCallbacks(n.data),
+ }));
+ const workflow = { nodes: serializableNodes, edges };
await saveSetting('nodeEditorWorkflow', JSON.stringify(workflow), 'node_editor');
} catch (error) {
console.error('[useWorkflowManagement] Failed to save workflow:', error);
@@ -125,8 +142,12 @@ export function useWorkflowManagement(): UseWorkflowManagementReturn {
// Export workflow to JSON file
const exportWorkflow = useCallback(() => {
+ const serializableNodes = nodes.map((n) => ({
+ ...n,
+ data: stripCallbacks(n.data),
+ }));
const workflow = {
- nodes: nodes,
+ nodes: serializableNodes,
edges: edges,
};
const dataStr = JSON.stringify(workflow, null, 2);
@@ -175,7 +196,7 @@ export function useWorkflowManagement(): UseWorkflowManagementReturn {
setWorkflowDescription('');
}, [setNodes, setEdges]);
- // Deploy workflow
+ // Deploy workflow — uses nodeExecutionManager for execution, then saves results
const deployWorkflow = useCallback(
async (statusCallback: (nodeId: string, status: string, result?: any) => void) => {
if (!workflowName.trim()) {
@@ -188,38 +209,38 @@ export function useWorkflowManagement(): UseWorkflowManagementReturn {
return;
}
- const name = workflowName;
- const description = workflowDescription;
- const currentNodes = nodes;
- const currentEdges = edges;
+ if (nodes.length === 0) {
+ showWarning('No nodes in the workflow. Add nodes before deploying.');
+ return;
+ }
setIsExecuting(true);
try {
- const result = await workflowExecutor.executeAndSave(
- currentNodes,
- currentEdges,
- {
- name: name,
- description: description,
- saveAsDraft: false,
- },
- statusCallback
- );
+ // Execute through the centralized nodeExecutionManager
+ const results = await nodeExecutionManager.executeWorkflow(nodes, edges, statusCallback);
+
+ // Save the deployed workflow with results
+ const serializableNodes = nodes.map((n) => ({
+ ...n,
+ data: stripCallbacks(n.data),
+ }));
+
+ const deployedWorkflow: WorkflowType = {
+ id: `workflow_${Date.now()}`,
+ name: workflowName,
+ description: workflowDescription,
+ nodes: serializableNodes,
+ edges,
+ status: 'completed',
+ results: Object.fromEntries(results),
+ };
- if (result.success) {
- setNodes([]);
- setEdges([]);
- await saveSetting('nodeEditorWorkflow', '', 'node_editor');
- setCurrentWorkflowId(null);
- setWorkflowMode('new');
- setEditingDraftId(null);
- } else {
- console.error('[useWorkflowManagement] Deployment failed:', result.error);
- showError('Deployment failed', [
- { label: 'ERROR', value: result.error || 'Unknown error' }
- ]);
- }
+ await workflowService.saveWorkflow(deployedWorkflow);
+
+ showSuccess('Workflow deployed successfully');
+ setWorkflowMode('deployed');
+ setEditingDraftId(null);
} catch (error: any) {
console.error('[useWorkflowManagement] Deploy failed:', error);
showError('Deployment failed', [
@@ -229,7 +250,7 @@ export function useWorkflowManagement(): UseWorkflowManagementReturn {
setIsExecuting(false);
}
},
- [nodes, edges, workflowName, workflowDescription, isExecuting, setNodes, setEdges]
+ [nodes, edges, workflowName, workflowDescription, isExecuting]
);
// Save as draft
@@ -240,22 +261,33 @@ export function useWorkflowManagement(): UseWorkflowManagementReturn {
}
try {
+ const serializableNodes = nodes.map((n) => ({
+ ...n,
+ data: stripCallbacks(n.data),
+ }));
+
let workflowId: string;
if (editingDraftId) {
await workflowService.updateDraft(
editingDraftId,
workflowName,
workflowDescription,
- nodes,
+ serializableNodes,
edges
);
workflowId = editingDraftId;
setEditingDraftId(null);
} else {
- workflowId = await workflowExecutor.saveDraft(workflowName, workflowDescription, nodes, edges);
+ workflowId = await workflowService.saveDraft(
+ workflowName,
+ workflowDescription,
+ serializableNodes,
+ edges
+ );
}
setCurrentWorkflowId(workflowId);
setWorkflowMode('draft');
+ showSuccess('Draft saved successfully');
} catch (error: any) {
console.error('[useWorkflowManagement] Save draft failed:', error);
showError('Save failed', [
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/types.ts b/fincept-terminal-desktop/src/components/tabs/node-editor/types.ts
index 893d64775..ae8b2427a 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/types.ts
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/types.ts
@@ -63,6 +63,10 @@ export interface NodeEditorToolbarProps {
onShowDeployDialog: () => void;
onQuickSaveDraft: () => Promise<void>;
onShowTemplates: () => void;
+ canUndo: boolean;
+ canRedo: boolean;
+ onUndo: () => void;
+ onRedo: () => void;
}
// Deploy dialog props
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/utils.ts b/fincept-terminal-desktop/src/components/tabs/node-editor/utils.ts
new file mode 100644
index 000000000..2d37cdaba
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/utils.ts
@@ -0,0 +1,14 @@
+/**
+ * Node Editor - Shared Utilities
+ */
+
+/** Strip callback functions from node data before serialization */
+export function stripCallbacks<T extends Record<string, any>>(nodeData: T): T {
+ const cleaned = {} as any;
+ for (const [key, value] of Object.entries(nodeData)) {
+ if (typeof value !== 'function') {
+ cleaned[key] = value;
+ }
+ }
+ return cleaned as T;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/polymarket/PolymarketTabEnhanced.tsx b/fincept-terminal-desktop/src/components/tabs/polymarket/PolymarketTabEnhanced.tsx
index d31ab9340..4fae491a9 100644
--- a/fincept-terminal-desktop/src/components/tabs/polymarket/PolymarketTabEnhanced.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/polymarket/PolymarketTabEnhanced.tsx
@@ -1,7 +1,7 @@
// File: src/components/tabs/PolymarketTab.tsx
// Polymarket prediction markets integration - Fincept Terminal Style
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
TrendingUp,
TrendingDown,
@@ -34,8 +34,22 @@ import polymarketService, {
} from '@/services/polymarket/polymarketService';
import polymarketServiceEnhanced, {
HistoricalPrice,
- PricePoint
+ PricePoint,
+ WSMarketUpdate,
+ PolymarketOrderBookEnriched,
+ PolymarketTopHolders,
+ PolymarketOpenInterest,
} from '@/services/polymarket/polymarketServiceEnhanced';
+import {
+ LineChart,
+ Line,
+ XAxis,
+ YAxis,
+ CartesianGrid,
+ Tooltip,
+ ResponsiveContainer,
+ Legend
+} from 'recharts';
const PolymarketTabEnhanced: React.FC = () => {
// State management
@@ -49,6 +63,30 @@ const PolymarketTabEnhanced: React.FC = () => {
const [selectedSport, setSelectedSport] = useState<PolymarketSport | null>(null);
const [recentTrades, setRecentTrades] = useState<PolymarketTrade[]>([]);
const [priceHistory, setPriceHistory] = useState<PricePoint[]>([]);
+ const [noPriceHistory, setNoPriceHistory] = useState<PricePoint[]>([]);
+ const [chartInterval, setChartInterval] = useState<string>('1d');
+ const [priceChartLoading, setPriceChartLoading] = useState(false);
+ const [priceChartError, setPriceChartError] = useState<string | null>(null);
+ // Trade calculator state
+ const [tradeAmount, setTradeAmount] = useState<string>('');
+ const [selectedOutcomeIndex, setSelectedOutcomeIndex] = useState<number>(0);
+ // Order book state (YES + NO token books)
+ const [yesOrderBook, setYesOrderBook] = useState<PolymarketOrderBookEnriched | null>(null);
+ const [noOrderBook, setNoOrderBook] = useState<PolymarketOrderBookEnriched | null>(null);
+ const [orderBookLoading, setOrderBookLoading] = useState(false);
+ const [orderBookError, setOrderBookError] = useState<string | null>(null);
+ const [activeOrderBookSide, setActiveOrderBookSide] = useState<'yes' | 'no'>('yes');
+ // Top holders state
+ const [topHolders, setTopHolders] = useState<PolymarketTopHolders | null>(null);
+ const [holdersLoading, setHoldersLoading] = useState(false);
+ const [holdersError, setHoldersError] = useState<string | null>(null);
+ // Open interest
+ const [openInterest, setOpenInterest] = useState<PolymarketOpenInterest | null>(null);
+ // Live outcome prices from WebSocket — keyed by tokenId
+ const [livePrices, setLivePrices] = useState<Record<string, number>>({});
+ const [wsConnected, setWsConnected] = useState(false);
+ // Ref to active market WebSocket so we can close it on unmount / market change
+ const marketWsRef = useRef<WebSocket | null>(null);
// Filters and search
const [searchQuery, setSearchQuery] = useState('');
@@ -87,6 +125,139 @@ const PolymarketTabEnhanced: React.FC = () => {
}
}, [selectedSport, showClosed, currentPage, sortBy]);
+ // Connect market WebSocket when a market is selected; disconnect on close
+ useEffect(() => {
+ // Close any existing WebSocket first
+ if (marketWsRef.current) {
+ marketWsRef.current.close();
+ marketWsRef.current = null;
+ setWsConnected(false);
+ }
+
+ if (!selectedMarket) return;
+
+ // Parse token IDs from the selected market
+ let tokenIds: string[] = [];
+ try {
+ const raw = selectedMarket.clobTokenIds;
+ if (typeof raw === 'string') {
+ tokenIds = JSON.parse(raw);
+ } else if (Array.isArray(raw)) {
+ tokenIds = raw as string[];
+ }
+ } catch { /* ignore parse errors */ }
+
+ if (tokenIds.length === 0) return;
+
+ const yesTokenId = tokenIds[0];
+ const noTokenId = tokenIds[1];
+
+ try {
+ const ws = polymarketServiceEnhanced.connectMarketWebSocket(
+ tokenIds,
+ (update: WSMarketUpdate) => {
+ const assetId: string | undefined = update.asset_id;
+ const eventType = update.event_type;
+
+ // --- Live order book snapshot (flat fields: bids, asks, tick_size, last_trade_price) ---
+ if (eventType === 'book') {
+ const bids: Array<{ price: string; size: string }> = Array.isArray(update.bids) ? update.bids : [];
+ const asks: Array<{ price: string; size: string }> = Array.isArray(update.asks) ? update.asks : [];
+ // Sort bids descending by price, asks ascending
+ bids.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
+ asks.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
+ const bookSnapshot = {
+ market: update.market,
+ asset_id: assetId ?? '',
+ bids,
+ asks,
+ timestamp: Number(update.timestamp),
+ tick_size: update.tick_size,
+ last_trade_price: update.last_trade_price,
+ };
+ if (assetId === yesTokenId) {
+ setYesOrderBook(prev => ({ ...prev, ...bookSnapshot }));
+ } else if (assetId === noTokenId) {
+ setNoOrderBook(prev => ({ ...prev, ...bookSnapshot }));
+ }
+ return;
+ }
+
+ // --- price_change: flat price + side fields ---
+ if (eventType === 'price_change') {
+ const p = parseFloat(update.price ?? '');
+ if (assetId && !isNaN(p)) {
+ setLivePrices(prev => ({ ...prev, [assetId]: p }));
+ }
+ return;
+ }
+
+ // --- last_trade_price: flat price field ---
+ if (eventType === 'last_trade_price') {
+ const ltp = parseFloat(update.last_trade_price ?? update.price ?? '');
+ if (!isNaN(ltp) && assetId) {
+ setLivePrices(prev => ({ ...prev, [assetId]: ltp }));
+ const ltpStr = ltp.toFixed(4);
+ if (assetId === yesTokenId) {
+ setYesOrderBook(prev => prev ? { ...prev, last_trade_price: ltpStr } : prev);
+ } else if (assetId === noTokenId) {
+ setNoOrderBook(prev => prev ? { ...prev, last_trade_price: ltpStr } : prev);
+ }
+ }
+ return;
+ }
+
+ // --- best_bid_ask: flat best_bid, best_ask fields ---
+ if (eventType === 'best_bid_ask') {
+ const bid = parseFloat(update.best_bid ?? '');
+ const ask = parseFloat(update.best_ask ?? '');
+ if (!isNaN(bid) && !isNaN(ask) && assetId) {
+ const mid = (bid + ask) / 2;
+ setLivePrices(prev => ({ ...prev, [assetId]: mid }));
+ const midStr = mid.toFixed(4);
+ if (assetId === yesTokenId) {
+ setYesOrderBook(prev => prev ? { ...prev, last_trade_price: midStr } : prev);
+ } else if (assetId === noTokenId) {
+ setNoOrderBook(prev => prev ? { ...prev, last_trade_price: midStr } : prev);
+ }
+ }
+ return;
+ }
+ }
+ );
+ marketWsRef.current = ws;
+
+ // Track connected state using onopen/onclose on the returned ws
+ const origOnOpen = ws.onopen;
+ ws.onopen = (e) => {
+ setWsConnected(true);
+ if (origOnOpen) (origOnOpen as any).call(ws, e);
+ };
+ const origOnClose = ws.onclose;
+ ws.onclose = (e) => {
+ setWsConnected(false);
+ if (origOnClose) (origOnClose as any).call(ws, e);
+ };
+ } catch (err) {
+ console.warn('Market WebSocket failed to connect:', err);
+ }
+
+ return () => {
+ if (marketWsRef.current) {
+ marketWsRef.current.close();
+ marketWsRef.current = null;
+ setWsConnected(false);
+ }
+ };
+ }, [selectedMarket?.id]);
+
+ // Cleanup WebSocket on component unmount
+ useEffect(() => {
+ return () => {
+ polymarketServiceEnhanced.disconnectWebSocket('market');
+ };
+ }, []);
+
const loadInitialData = async () => {
try {
setLoading(true);
@@ -171,12 +342,32 @@ const PolymarketTabEnhanced: React.FC = () => {
}
};
- const loadMarketDetails = async (market: PolymarketMarket) => {
+ const loadMarketDetails = async (market: PolymarketMarket, interval: string = chartInterval) => {
+ const isNewMarket = market.id !== selectedMarket?.id;
+
setSelectedMarket(market);
- setPriceHistory([]); // Reset price history
- setRecentTrades([]); // Reset trades
+ setPriceHistory([]);
+ setNoPriceHistory([]);
+ setPriceChartLoading(true);
+ setPriceChartError(null);
+ setTradeAmount('');
+ setSelectedOutcomeIndex(0);
+
+ // Reset secondary panels only when switching to a different market
+ if (isNewMarket) {
+ setRecentTrades([]);
+ setYesOrderBook(null);
+ setNoOrderBook(null);
+ setOrderBookLoading(true);
+ setOrderBookError(null);
+ setActiveOrderBookSide('yes');
+ setTopHolders(null);
+ setHoldersLoading(true);
+ setHoldersError(null);
+ setOpenInterest(null);
+ }
- // Parse token IDs - they might be a JSON string
+ // Parse token IDs — Gamma API returns clobTokenIds as a JSON string
let tokenIds: string[] = [];
try {
if (market.clobTokenIds) {
@@ -186,45 +377,101 @@ const PolymarketTabEnhanced: React.FC = () => {
tokenIds = market.clobTokenIds;
}
}
- } catch (error) {
- console.error('Error parsing clobTokenIds:', error);
+ } catch (err) {
+ console.error('Error parsing clobTokenIds:', err);
}
- // Load data if we have token IDs
- if (tokenIds.length > 0) {
- const tokenId = tokenIds[0]; // Use first token (YES outcome)
+ const yesTokenId = tokenIds[0];
+ const noTokenId = tokenIds[1]; // binary markets always have YES[0] and NO[1]
+
+ // Fire non-blocking parallel fetches for order book, top holders, open interest
+ // Only on market change (not on interval change)
+ if (isNewMarket) {
+ // Order book — both YES and NO tokens
+ if (yesTokenId || noTokenId) {
+ Promise.all([
+ yesTokenId ? polymarketServiceEnhanced.getOrderBookEnriched(yesTokenId).catch(() => null) : Promise.resolve(null),
+ noTokenId ? polymarketServiceEnhanced.getOrderBookEnriched(noTokenId).catch(() => null) : Promise.resolve(null),
+ ]).then(([yesBook, noBook]) => {
+ setYesOrderBook(yesBook);
+ setNoOrderBook(noBook);
+ if (!yesBook && !noBook) setOrderBookError('Order book unavailable');
+ }).finally(() => setOrderBookLoading(false));
+ } else {
+ setOrderBookLoading(false);
+ setOrderBookError('No token IDs available');
+ }
- console.log('Loading data for token:', tokenId);
+ // Top holders + open interest require conditionId
+ const condId = market.conditionId ?? '';
+ if (condId) {
+ polymarketServiceEnhanced.getTopHolders(condId, 20)
+ .then(data => setTopHolders(data))
+ .catch(() => setHoldersError('Failed to load holders'))
+ .finally(() => setHoldersLoading(false));
+
+ polymarketServiceEnhanced.getOpenInterest([condId])
+ .then(data => setOpenInterest(data.find(d => d.market === condId) ?? data[0] ?? null))
+ .catch((e) => console.warn('[Polymarket] Failed to load open interest:', e));
+ } else {
+ setHoldersLoading(false);
+ setHoldersError('conditionId not available for this market');
+ }
+ }
- // Load recent trades
+ // Load trades for YES token
+ if (yesTokenId) {
try {
- const trades = await polymarketService.getTrades({
- token_id: tokenId,
- limit: 50
- });
- setRecentTrades(trades || []);
+ const result = await polymarketService.getTrades({ token_id: yesTokenId, limit: 50 });
+ const trades = Array.isArray(result) ? result : ((result as any).data ?? []);
+ setRecentTrades(trades);
} catch (err) {
console.error('Error loading trades:', err);
}
+ }
- // Load price history - use 'max' interval to get all available data
+ // Load YES + NO price histories in parallel
+ if (yesTokenId) {
try {
- console.log('Fetching price history for token:', tokenId);
+ // Fidelity = candle size in minutes. Coarser fidelity for longer intervals
+ // so we get a reasonable number of data points (not too few, not thousands)
+ const fidelityMap: Record<string, number> = {
+ '1h': 1, // 1-min candles → ~60 pts
+ '6h': 5, // 5-min candles → ~72 pts
+ '1d': 60, // 1-hour candles → ~24 pts
+ '1w': 360, // 6-hour candles → ~28 pts
+ '1m': 1440, // 1-day candles → ~30 pts
+ 'max': 1440,
+ 'all': 1440,
+ };
+ const fidelity = fidelityMap[interval] ?? 60;
+
+ const fetches: Promise<any>[] = [
+ polymarketServiceEnhanced.getPriceHistory({ token_id: yesTokenId, interval, fidelity }),
+ ];
+ if (noTokenId) {
+ fetches.push(polymarketServiceEnhanced.getPriceHistory({ token_id: noTokenId, interval, fidelity }));
+ }
- const history = await polymarketServiceEnhanced.getPriceHistory({
- token_id: tokenId,
- interval: 'max', // Get all available history
- fidelity: 60 // 1 hour resolution
- });
+ const [yesHistory, noHistory] = await Promise.all(fetches);
+ const yesPrices = yesHistory?.prices ?? [];
+ const noPrices = noHistory?.prices ?? [];
- console.log('Price history received:', history?.prices?.length || 0, 'data points');
- setPriceHistory(history?.prices || []);
- } catch (err) {
+ if (yesPrices.length === 0) {
+ setPriceChartError('No price history available for this market');
+ } else {
+ setPriceHistory(yesPrices);
+ if (noPrices.length > 0) setNoPriceHistory(noPrices);
+ }
+ } catch (err: any) {
console.error('Error loading price history:', err);
+ setPriceChartError('Failed to load price history');
}
} else {
- console.warn('No token IDs available for this market');
+ setPriceChartError('No token ID available for this market');
}
+
+ setPriceChartLoading(false);
};
const loadSportMarkets = async (sport: PolymarketSport) => {
@@ -290,31 +537,48 @@ const PolymarketTabEnhanced: React.FC = () => {
}
};
+ // Outcome color palette — indexed by position; first/leading outcome is green, rest red/orange
+ const OUTCOME_COLORS = ['#00D66F', '#FF3B3B', '#FF8800', '#4F8EF7', '#A855F7'];
+
+ // Format dollar volume: 1234567 → "$1.23M", 12345 → "$12.35K"
+ const formatDollarVolume = (val: any): string => {
+ const n = typeof val === 'number' ? val : parseFloat(val) || 0;
+ if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(2)}M`;
+ if (n >= 1_000) return `$${(n / 1_000).toFixed(2)}K`;
+ return `$${n.toFixed(2)}`;
+ };
+
// Render helpers
const renderMarketCard = (market: PolymarketMarket) => {
const status = polymarketService.getMarketStatus(market);
const isTradeable = polymarketService.isMarketTradeable(market);
- // Parse prices - outcomePrices might be a JSON string or an array
- let yesPrice = 0;
- let noPrice = 0;
+ // Parse outcome names — Gamma returns JSON string e.g. '["Yes","No"]'
+ let outcomeNames: string[] = [];
+ try {
+ let raw: any = market.outcomes;
+ if (typeof raw === 'string') raw = JSON.parse(raw);
+ if (Array.isArray(raw)) outcomeNames = raw.map(String);
+ } catch { /* ignore */ }
+ // Parse outcome prices — Gamma returns JSON string e.g. '["0.97","0.03"]'
+ let outcomePrices: number[] = [];
try {
- let prices = market.outcomePrices;
+ let raw: any = market.outcomePrices;
+ if (typeof raw === 'string') raw = JSON.parse(raw);
+ if (Array.isArray(raw)) outcomePrices = raw.map((p: any) => parseFloat(p) || 0);
+ } catch { /* ignore */ }
- // If it's a string, parse it as JSON
- if (typeof prices === 'string') {
- prices = JSON.parse(prices);
- }
+ // Parse token IDs so we can check live prices
+ let tokenIds: string[] = [];
+ try {
+ const raw = market.clobTokenIds;
+ if (typeof raw === 'string') tokenIds = JSON.parse(raw);
+ else if (Array.isArray(raw)) tokenIds = raw as string[];
+ } catch { /* ignore */ }
- // Now extract the prices from the array
- if (Array.isArray(prices) && prices.length >= 2) {
- yesPrice = parseFloat(prices[0]) || 0;
- noPrice = parseFloat(prices[1]) || 0;
- }
- } catch (error) {
- console.error('Error parsing outcome prices:', error);
- }
+ // Determine leading outcome index (highest price)
+ const maxPrice = outcomePrices.length > 0 ? Math.max(...outcomePrices) : 0;
return (
<div
@@ -338,6 +602,16 @@ const PolymarketTabEnhanced: React.FC = () => {
<div style={{ color: '#FFFFFF', fontWeight: 'bold', marginBottom: '4px', fontSize: '12px' }}>
{market.question}
</div>
+ {(market.featured || market.new) && (
+ <div style={{ display: 'flex', gap: '4px', marginBottom: '4px' }}>
+ {market.featured && (
+ <span style={{ padding: '1px 5px', backgroundColor: '#FF880020', color: '#FF8800', fontSize: '8px', fontWeight: 'bold', border: '1px solid #FF880066', letterSpacing: '0.05em' }}>FEATURED</span>
+ )}
+ {market.new && (
+ <span style={{ padding: '1px 5px', backgroundColor: '#4F8EF720', color: '#4F8EF7', fontSize: '8px', fontWeight: 'bold', border: '1px solid #4F8EF766', letterSpacing: '0.05em' }}>NEW</span>
+ )}
+ </div>
+ )}
{market.description && (
<div style={{ color: '#787878', fontSize: '10px', marginBottom: '6px' }}>
{market.description.length > 120 ? market.description.substring(0, 120) + '...' : market.description}
@@ -353,57 +627,70 @@ const PolymarketTabEnhanced: React.FC = () => {
)}
</div>
- {/* Outcome prices - Fincept style */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '8px' }}>
+ {/* Outcome prices — dynamic names and colors */}
+ {outcomeNames.length > 0 ? (
<div style={{
- backgroundColor: '#1A1A1A',
- border: '1px solid #333333',
- padding: '8px'
+ display: 'grid',
+ gridTemplateColumns: `repeat(${Math.min(outcomeNames.length, 4)}, 1fr)`,
+ gap: '8px',
+ marginBottom: '8px'
}}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <span style={{ color: '#787878', fontSize: '9px', fontWeight: 'bold' }}>YES</span>
- <span style={{
- color: '#00D66F',
- fontSize: '13px',
- fontWeight: 'bold'
- }}>
- {(yesPrice * 100).toFixed(1)}%
- </span>
- </div>
- <div style={{ color: '#787878', fontSize: '9px', marginTop: '2px' }}>
- ${yesPrice.toFixed(4)}
- </div>
- </div>
- <div style={{
- backgroundColor: '#1A1A1A',
- border: '1px solid #333333',
- padding: '8px'
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <span style={{ color: '#787878', fontSize: '9px', fontWeight: 'bold' }}>NO</span>
- <span style={{
- color: '#FF3B3B',
- fontSize: '13px',
- fontWeight: 'bold'
- }}>
- {(noPrice * 100).toFixed(1)}%
- </span>
- </div>
- <div style={{ color: '#787878', fontSize: '9px', marginTop: '2px' }}>
- ${noPrice.toFixed(4)}
- </div>
+ {outcomeNames.map((name, i) => {
+ // Use live price if available, otherwise REST price
+ const tokenId = tokenIds[i];
+ const livePrice = tokenId ? livePrices[tokenId] : undefined;
+ const price = livePrice ?? outcomePrices[i] ?? 0;
+ const isLeading = price === maxPrice && maxPrice > 0;
+ const color = isLeading ? OUTCOME_COLORS[0] : OUTCOME_COLORS[Math.min(i, OUTCOME_COLORS.length - 1) > 0 ? Math.min(i, OUTCOME_COLORS.length - 1) : 1];
+ return (
+ <div key={i} style={{
+ backgroundColor: '#1A1A1A',
+ border: '1px solid #333333',
+ padding: '8px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <span style={{ color: '#787878', fontSize: '9px', fontWeight: 'bold', textTransform: 'uppercase' }}>{name}</span>
+ <span style={{ color, fontSize: '13px', fontWeight: 'bold' }}>
+ {(price * 100).toFixed(1)}%
+ </span>
+ </div>
+ <div style={{ color: '#787878', fontSize: '9px', marginTop: '2px' }}>
+ ${price.toFixed(4)}{livePrice !== undefined && <span style={{ color: '#FF8800', marginLeft: '4px' }}>●</span>}
+ </div>
+ </div>
+ );
+ })}
</div>
- </div>
+ ) : null}
{/* Market stats */}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: '10px', color: '#787878' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <div>VOL: {polymarketService.formatVolume(market.volume || '0')}</div>
- {market.liquidity && (
- <div>LIQ: {polymarketService.formatVolume(market.liquidity)}</div>
+ <div>
+ <div>VOL: {formatDollarVolume(market.volumeNum ?? market.volume ?? 0)}</div>
+ {(() => {
+ // 24h volume lives on events[0].series[0].volume24hr, not directly on market
+ const v24h: number | null = (market as any).events?.[0]?.series?.[0]?.volume24hr ?? null;
+ return v24h != null ? <div style={{ color: '#555', fontSize: '9px' }}>24H: {formatDollarVolume(v24h)}</div> : null;
+ })()}
+ </div>
+ {(market.liquidityNum ?? market.liquidity) && (
+ <div>LIQ: {formatDollarVolume(market.liquidityNum ?? market.liquidity ?? 0)}</div>
)}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ {market.oneDayPriceChange != null && Math.abs(market.oneDayPriceChange) > 0.001 && (
+ <span style={{
+ padding: '2px 6px',
+ backgroundColor: market.oneDayPriceChange >= 0 ? '#003300' : '#330000',
+ color: market.oneDayPriceChange >= 0 ? '#00D66F' : '#FF3B3B',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ border: `1px solid ${market.oneDayPriceChange >= 0 ? '#00D66F' : '#FF3B3B'}`,
+ }}>
+ {market.oneDayPriceChange >= 0 ? '▲' : '▼'} {Math.abs(market.oneDayPriceChange * 100).toFixed(1)}%
+ </span>
+ )}
{isTradeable && (
<span style={{
padding: '2px 6px',
@@ -515,26 +802,40 @@ const PolymarketTabEnhanced: React.FC = () => {
const renderMarketDetails = () => {
if (!selectedMarket) return null;
- // Parse prices - outcomePrices might be a JSON string or an array
- let yesPrice = 0;
- let noPrice = 0;
-
+ // Parse outcomePrices — Gamma returns a JSON string e.g. '["0.0235","0.9765"]'
+ let parsedPrices: number[] = [];
try {
- let prices = selectedMarket.outcomePrices;
+ let raw: any = selectedMarket.outcomePrices;
+ if (typeof raw === 'string') raw = JSON.parse(raw);
+ if (Array.isArray(raw)) parsedPrices = raw.map((p: any) => parseFloat(p) || 0);
+ } catch { /* ignore */ }
- // If it's a string, parse it as JSON
- if (typeof prices === 'string') {
- prices = JSON.parse(prices);
- }
+ // Parse outcomes — Gamma returns a JSON string e.g. '["Yes","No"]'
+ let outcomeNames: string[] = [];
+ try {
+ let raw: any = selectedMarket.outcomes;
+ if (typeof raw === 'string') raw = JSON.parse(raw);
+ if (Array.isArray(raw)) outcomeNames = raw.map(String);
+ } catch { /* ignore */ }
- // Now extract the prices from the array
- if (Array.isArray(prices) && prices.length >= 2) {
- yesPrice = parseFloat(prices[0]) || 0;
- noPrice = parseFloat(prices[1]) || 0;
- }
- } catch (error) {
- console.error('Error parsing outcome prices in details:', error);
- }
+ // Parse token IDs for live price lookup
+ let detailTokenIds: string[] = [];
+ try {
+ const raw = selectedMarket.clobTokenIds;
+ if (typeof raw === 'string') detailTokenIds = JSON.parse(raw);
+ else if (Array.isArray(raw)) detailTokenIds = raw as string[];
+ } catch { /* ignore */ }
+
+ // Build per-outcome display items, merging live WS prices where available
+ const outcomeItems = outcomeNames.map((name, i) => {
+ const tokenId = detailTokenIds[i];
+ const livePrice = tokenId ? livePrices[tokenId] : undefined;
+ return {
+ name,
+ price: livePrice ?? parsedPrices[i] ?? 0,
+ isLive: livePrice !== undefined,
+ };
+ });
return (
<div style={{
@@ -596,156 +897,709 @@ const PolymarketTabEnhanced: React.FC = () => {
</div>
<div style={{ padding: '16px' }}>
- {/* Price Display */}
- <div style={{ backgroundColor: '#0A0A0A', border: '1px solid #333333', padding: '16px', marginBottom: '16px' }}>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '20px' }}>
- <div style={{
- backgroundColor: '#000000',
- border: '2px solid #333333',
- padding: '16px'
- }}>
- <div style={{ color: '#787878', fontSize: '10px', marginBottom: '8px', fontWeight: 'bold' }}>YES</div>
- <div style={{
- color: '#00D66F',
- fontSize: '32px',
- fontWeight: 'bold',
- marginBottom: '4px'
+ {/* Outcome Price Boxes — one per outcome, dynamic names + colors */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: `repeat(${Math.min(outcomeItems.length, 4)}, 1fr)`,
+ gap: '8px',
+ marginBottom: '12px'
+ }}>
+ {outcomeItems.map((item, i) => {
+ // Leading outcome uses first palette color (green); rest use their indexed color
+ const detailMaxPrice = Math.max(...outcomeItems.map(o => o.price));
+ const isLeading = item.price === detailMaxPrice && detailMaxPrice > 0;
+ const priceColor = isLeading ? OUTCOME_COLORS[0] : OUTCOME_COLORS[Math.min(i, OUTCOME_COLORS.length - 1) > 0 ? Math.min(i, OUTCOME_COLORS.length - 1) : 1];
+ return (
+ <div key={i} style={{
+ backgroundColor: '#0A0A0A',
+ border: `1px solid ${priceColor}33`,
+ padding: '14px 16px',
}}>
- {(yesPrice * 100).toFixed(1)}%
- </div>
- <div style={{ color: '#787878', fontSize: '11px' }}>
- ${yesPrice.toFixed(4)} per share
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
+ <span style={{ color: '#787878', fontSize: '10px', fontWeight: 'bold', textTransform: 'uppercase' }}>
+ {item.name}
+ </span>
+ {item.isLive && (
+ <span style={{ fontSize: '8px', color: '#FF8800', display: 'flex', alignItems: 'center', gap: '2px' }}>
+ <span style={{ display: 'inline-block', width: '5px', height: '5px', borderRadius: '50%', backgroundColor: '#FF8800' }} />
+ LIVE
+ </span>
+ )}
+ </div>
+ <div style={{ color: priceColor, fontSize: '28px', fontWeight: 'bold', marginBottom: '4px', lineHeight: 1 }}>
+ {(item.price * 100).toFixed(1)}%
+ </div>
+ <div style={{ color: '#555', fontSize: '11px' }}>
+ ${item.price.toFixed(4)} per share
+ </div>
</div>
- </div>
- <div style={{
- backgroundColor: '#000000',
- border: '2px solid #333333',
- padding: '16px'
- }}>
- <div style={{ color: '#787878', fontSize: '10px', marginBottom: '8px', fontWeight: 'bold' }}>NO</div>
- <div style={{
- color: '#FF3B3B',
- fontSize: '32px',
- fontWeight: 'bold',
- marginBottom: '4px'
- }}>
- {(noPrice * 100).toFixed(1)}%
+ );
+ })}
+ </div>
+
+ {/* Trade Calculator */}
+ {outcomeItems.length > 0 && (() => {
+ const selectedItem = outcomeItems[selectedOutcomeIndex] ?? outcomeItems[0];
+ const price = selectedItem?.price ?? 0;
+ const amount = parseFloat(tradeAmount) || 0;
+ // Shares = amount / price (each share costs `price` USDC)
+ const shares = price > 0 ? amount / price : 0;
+ // Potential profit if outcome wins: shares pay out $1 each, minus cost
+ const potentialReturn = shares; // gross payout in USDC
+ const potentialProfit = potentialReturn - amount;
+ const maxReturn = price > 0 ? amount / price : 0;
+
+ return (
+ <div style={{ border: '1px solid #333333', backgroundColor: '#000000', marginBottom: '12px' }}>
+ {/* Header */}
+ <div style={{ padding: '8px 12px', borderBottom: '1px solid #1e1e1e', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
+ <span style={{ fontSize: '10px', color: '#787878', fontFamily: 'IBM Plex Mono, monospace' }}>TRADE CALCULATOR</span>
+ <span style={{ fontSize: '9px', color: '#555', fontFamily: 'IBM Plex Mono, monospace' }}>READ-ONLY · CONNECT WALLET ON POLYMARKET TO TRADE</span>
</div>
- <div style={{ color: '#787878', fontSize: '11px' }}>
- ${noPrice.toFixed(4)} per share
+
+ <div style={{ padding: '12px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ {/* Left: outcome selector + amount input */}
+ <div>
+ {/* Outcome buttons */}
+ <div style={{ fontSize: '9px', color: '#555', marginBottom: '6px', fontFamily: 'IBM Plex Mono, monospace' }}>SELECT OUTCOME</div>
+ <div style={{ display: 'flex', gap: '4px', marginBottom: '12px', flexWrap: 'wrap' }}>
+ {outcomeItems.map((item, i) => {
+ const isSelected = selectedOutcomeIndex === i;
+ const detailMaxPrice = Math.max(...outcomeItems.map(o => o.price));
+ const isLeading = item.price === detailMaxPrice && detailMaxPrice > 0;
+ const btnColor = isLeading ? OUTCOME_COLORS[0] : OUTCOME_COLORS[Math.min(i, OUTCOME_COLORS.length - 1) > 0 ? Math.min(i, OUTCOME_COLORS.length - 1) : 1];
+ return (
+ <button
+ key={i}
+ onClick={() => setSelectedOutcomeIndex(i)}
+ style={{
+ padding: '6px 14px',
+ fontSize: '10px',
+ fontFamily: 'IBM Plex Mono, monospace',
+ fontWeight: 'bold',
+ background: isSelected ? btnColor : 'transparent',
+ color: isSelected ? '#000' : btnColor,
+ border: `1px solid ${btnColor}`,
+ cursor: 'pointer',
+ transition: 'all 0.1s',
+ }}
+ >
+ {item.name.toUpperCase()} · {(item.price * 100).toFixed(1)}%
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Amount input */}
+ <div style={{ fontSize: '9px', color: '#555', marginBottom: '6px', fontFamily: 'IBM Plex Mono, monospace' }}>AMOUNT (USDC)</div>
+ <div style={{ display: 'flex', alignItems: 'center', backgroundColor: '#0A0A0A', border: '1px solid #333', marginBottom: '8px' }}>
+ <span style={{ padding: '0 10px', color: '#787878', fontSize: '13px', fontWeight: 'bold' }}>$</span>
+ <input
+ type="number"
+ min="0"
+ step="1"
+ placeholder="0.00"
+ value={tradeAmount}
+ onChange={(e) => setTradeAmount(e.target.value)}
+ style={{
+ flex: 1,
+ padding: '10px 8px',
+ backgroundColor: 'transparent',
+ border: 'none',
+ outline: 'none',
+ color: '#FFFFFF',
+ fontSize: '14px',
+ fontWeight: 'bold',
+ fontFamily: 'IBM Plex Mono, monospace',
+ }}
+ />
+ <span style={{ padding: '0 10px', color: '#555', fontSize: '10px' }}>USDC</span>
+ </div>
+ {/* Quick amount buttons */}
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {[10, 50, 100, 500].map(v => (
+ <button
+ key={v}
+ onClick={() => setTradeAmount(String(v))}
+ style={{
+ flex: 1,
+ padding: '4px 0',
+ fontSize: '9px',
+ fontFamily: 'IBM Plex Mono, monospace',
+ background: 'transparent',
+ color: '#787878',
+ border: '1px solid #333',
+ cursor: 'pointer',
+ }}
+ >
+ ${v}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Right: payout breakdown */}
+ <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
+ <div>
+ <div style={{ fontSize: '9px', color: '#555', marginBottom: '10px', fontFamily: 'IBM Plex Mono, monospace' }}>ORDER SUMMARY</div>
+
+ {[
+ { label: 'OUTCOME', value: selectedItem?.name?.toUpperCase() ?? '—' },
+ { label: 'AVG PRICE', value: price > 0 ? `$${price.toFixed(4)}` : '—' },
+ { label: 'SHARES', value: amount > 0 && price > 0 ? shares.toFixed(2) : amount === 0 ? 'ENTER AMOUNT' : '—' },
+ { label: 'MAX RETURN', value: amount > 0 && price > 0 ? `$${maxReturn.toFixed(2)}` : amount === 0 ? 'ENTER AMOUNT' : '—' },
+ { label: 'POTENTIAL PROFIT', value: amount > 0 && price > 0 ? `$${potentialProfit.toFixed(2)}` : amount === 0 ? 'ENTER AMOUNT' : '—' },
+ { label: 'ROI', value: amount > 0 && price > 0 ? `${((potentialProfit / amount) * 100).toFixed(1)}%` : amount === 0 ? 'ENTER AMOUNT' : '—' },
+ ].map(row => (
+ <div key={row.label} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '5px 0', borderBottom: '1px solid #111' }}>
+ <span style={{ fontSize: '9px', color: '#555', fontFamily: 'IBM Plex Mono, monospace' }}>{row.label}</span>
+ <span style={{
+ fontSize: '11px',
+ fontWeight: 'bold',
+ fontFamily: 'IBM Plex Mono, monospace',
+ color: row.value === 'ENTER AMOUNT' ? '#333'
+ : row.label === 'POTENTIAL PROFIT' ? (potentialProfit > 0 ? '#00D66F' : '#787878')
+ : row.label === 'ROI' ? (potentialProfit > 0 ? '#00D66F' : '#787878')
+ : row.label === 'OUTCOME' ? (OUTCOME_COLORS[selectedOutcomeIndex] ?? '#FFF')
+ : '#FFFFFF'
+ }}>
+ {row.value}
+ </span>
+ </div>
+ ))}
+ </div>
+
+ {/* Total you'll receive box */}
+ {amount > 0 && price > 0 && (
+ <div style={{ marginTop: '10px', padding: '10px 12px', backgroundColor: '#0A0A0A', border: '1px solid #333' }}>
+ <div style={{ fontSize: '9px', color: '#555', marginBottom: '4px', fontFamily: 'IBM Plex Mono, monospace' }}>YOU'LL RECEIVE IF {selectedItem?.name?.toUpperCase()} WINS</div>
+ <div style={{ fontSize: '22px', fontWeight: 'bold', color: '#00D66F', fontFamily: 'IBM Plex Mono, monospace' }}>
+ ${maxReturn.toFixed(2)}
+ </div>
+ <div style={{ fontSize: '9px', color: '#555', marginTop: '2px', fontFamily: 'IBM Plex Mono, monospace' }}>
+ {shares.toFixed(2)} shares × $1.00 payout
+ </div>
+ </div>
+ )}
+ </div>
</div>
</div>
- </div>
+ );
+ })()}
- {/* Price Chart */}
- <div style={{
- height: '200px',
- border: '1px solid #333333',
- backgroundColor: '#000000',
- position: 'relative'
- }}>
- {priceHistory.length > 1 ? (
- <svg width="100%" height="200" viewBox="0 0 800 200" preserveAspectRatio="none" style={{ display: 'block' }}>
- {/* Grid lines */}
- {[0, 0.25, 0.5, 0.75, 1.0].map((priceLevel, i) => (
- <line
- key={i}
- x1="0"
- y1={200 - (priceLevel * 200)}
- x2="800"
- y2={200 - (priceLevel * 200)}
- stroke="#333333"
- strokeWidth="1"
- strokeDasharray="4,4"
- />
- ))}
+ {/* Chart section */}
+ <div style={{ marginBottom: '12px' }}>
- {/* Price line */}
- <polyline
- points={priceHistory.map((point, index) => {
- const x = (index / (priceHistory.length - 1)) * 800;
- const price = typeof point.price === 'number' ? point.price : parseFloat(point.price);
- const y = 200 - (price * 200);
- return `${x},${y}`;
- }).join(' ')}
- fill="none"
- stroke="#00D66F"
- strokeWidth="2"
- vectorEffect="non-scaling-stroke"
- />
-
- {/* Price labels on Y axis */}
- {[0, 0.25, 0.5, 0.75, 1.0].map((price, i) => (
- <text
- key={i}
- x="10"
- y={200 - (price * 200) + 4}
- fill="#787878"
- fontSize="12"
- fontFamily="IBM Plex Mono, monospace"
+ {/* Price Chart */}
+ <div style={{ border: '1px solid #333333', backgroundColor: '#000000' }}>
+ {/* Interval selector */}
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 10px', borderBottom: '1px solid #1e1e1e' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ fontSize: '10px', color: '#787878', fontFamily: 'IBM Plex Mono, monospace' }}>PROBABILITY HISTORY</span>
+ {wsConnected && (
+ <span style={{ fontSize: '9px', color: '#00D66F', fontFamily: 'IBM Plex Mono, monospace', display: 'flex', alignItems: 'center', gap: '3px' }}>
+ <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', backgroundColor: '#00D66F' }} />
+ LIVE
+ </span>
+ )}
+ </div>
+ <div style={{ display: 'flex', gap: '2px' }}>
+ {(['1d', '1w', '1m', '6h', '1h', 'max'] as const).map(iv => (
+ <button
+ key={iv}
+ onClick={() => {
+ setChartInterval(iv);
+ if (selectedMarket) loadMarketDetails(selectedMarket, iv);
+ }}
+ style={{
+ padding: '2px 7px',
+ fontSize: '10px',
+ fontFamily: 'IBM Plex Mono, monospace',
+ background: chartInterval === iv ? '#FF8800' : 'transparent',
+ color: chartInterval === iv ? '#000' : '#787878',
+ border: '1px solid ' + (chartInterval === iv ? '#FF8800' : '#333'),
+ cursor: 'pointer',
+ }}
>
- ${price.toFixed(2)}
- </text>
+ {iv.toUpperCase()}
+ </button>
))}
- </svg>
- ) : (
- <div style={{
- height: '100%',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- color: '#787878'
- }}>
+ </div>
+ </div>
+
+ {priceChartLoading ? (
+ <div style={{ height: '220px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#787878' }}>
+ <div style={{ textAlign: 'center' }}>
+ <BarChart3 size={32} style={{ opacity: 0.3, margin: '0 auto 8px' }} />
+ <div style={{ fontSize: '11px', fontFamily: 'IBM Plex Mono, monospace' }}>LOADING PRICE HISTORY...</div>
+ </div>
+ </div>
+ ) : priceHistory.length > 1 ? (() => {
+ // Build a merged timestamp map so both lines share the same X points
+ const yesMap = new Map(priceHistory.map(pt => [pt.timestamp, pt.price]));
+ const noMap = new Map(noPriceHistory.map(pt => [pt.timestamp, pt.price]));
+
+ // Use YES timestamps as the base (they always exist)
+ const chartData = priceHistory.map(pt => {
+ const ts = typeof pt.timestamp === 'number' ? pt.timestamp : Number(pt.timestamp) || 0;
+ const ms = ts < 1e12 ? ts * 1000 : ts;
+ const d = new Date(ms);
+ // For 1d use time labels, for longer use date labels
+ const label = chartInterval === '1d'
+ ? d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false })
+ : d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
+ return {
+ label,
+ yes: typeof pt.price === 'number' ? pt.price : parseFloat(pt.price as any) || 0,
+ no: noMap.get(pt.timestamp) ?? null,
+ };
+ });
+
+ // Y domain: span actual data range with 5% padding
+ const allPrices = chartData.flatMap(d => [d.yes, d.no ?? d.yes]);
+ const minP = Math.min(...allPrices);
+ const maxP = Math.max(...allPrices);
+ const pad = (maxP - minP) * 0.05 || 0.02;
+ const yMin = Math.max(0, minP - pad);
+ const yMax = Math.min(1, maxP + pad);
+
+ const tickInterval = Math.max(1, Math.floor(chartData.length / 6));
+
+ // Use dynamic outcome labels; fall back to generic names
+ const yesLabel = outcomeNames[0] ?? 'Outcome 1';
+ const noLabel = outcomeNames[1] ?? 'Outcome 2';
+ // Chart line colors from palette (index 0 = leading/yes, index 1 = no)
+ const yesColor = OUTCOME_COLORS[0];
+ const noColor = OUTCOME_COLORS[1];
+
+ return (
+ <ResponsiveContainer width="100%" height={220}>
+ <LineChart data={chartData} margin={{ top: 8, right: 12, left: 4, bottom: 4 }}>
+ <CartesianGrid strokeDasharray="2 4" stroke="#1a1a1a" vertical={false} />
+ <XAxis
+ dataKey="label"
+ tick={{ fill: '#555', fontSize: 9, fontFamily: 'IBM Plex Mono, monospace' }}
+ tickLine={false}
+ axisLine={{ stroke: '#222' }}
+ interval={tickInterval}
+ />
+ <YAxis
+ domain={[yMin, yMax]}
+ tickFormatter={v => `${(v * 100).toFixed(0)}%`}
+ tick={{ fill: '#555', fontSize: 9, fontFamily: 'IBM Plex Mono, monospace' }}
+ tickLine={false}
+ axisLine={false}
+ width={38}
+ tickCount={5}
+ />
+ <Tooltip
+ contentStyle={{ backgroundColor: '#111', border: '1px solid #2a2a2a', borderRadius: 2, fontFamily: 'IBM Plex Mono, monospace', fontSize: 10, padding: '6px 10px' }}
+ labelStyle={{ color: '#555', marginBottom: 4 }}
+ formatter={(val: number, name: string) => [
+ `${(val * 100).toFixed(1)}%`,
+ name === 'yes' ? yesLabel : name === 'no' ? noLabel : name
+ ]}
+ />
+ <Legend
+ wrapperStyle={{ fontSize: '10px', fontFamily: 'IBM Plex Mono, monospace', paddingTop: '2px' }}
+ formatter={(value) => (
+ <span style={{ color: value === 'yes' ? yesColor : noColor }}>
+ {value === 'yes' ? yesLabel : value === 'no' ? noLabel : value}
+ </span>
+ )}
+ />
+ <Line
+ type="monotone"
+ dataKey="yes"
+ name="yes"
+ stroke={yesColor}
+ strokeWidth={1.5}
+ dot={false}
+ activeDot={{ r: 3, fill: yesColor, stroke: '#000', strokeWidth: 1 }}
+ isAnimationActive={false}
+ connectNulls
+ />
+ {noPriceHistory.length > 1 && (
+ <Line
+ type="monotone"
+ dataKey="no"
+ name="no"
+ stroke={noColor}
+ strokeWidth={1.5}
+ dot={false}
+ activeDot={{ r: 3, fill: noColor, stroke: '#000', strokeWidth: 1 }}
+ isAnimationActive={false}
+ connectNulls
+ />
+ )}
+ </LineChart>
+ </ResponsiveContainer>
+ );
+ })() : (
+ <div style={{ height: '220px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#787878' }}>
<div style={{ textAlign: 'center' }}>
- <BarChart3 size={48} style={{ opacity: 0.3, margin: '0 auto 8px' }} />
- <div style={{ fontSize: '11px' }}>Loading price chart...</div>
+ <BarChart3 size={32} style={{ opacity: 0.3, margin: '0 auto 8px' }} />
+ <div style={{ fontSize: '11px', fontFamily: 'IBM Plex Mono, monospace' }}>
+ {priceChartError ?? 'NO PRICE DATA'}
+ </div>
</div>
</div>
)}
</div>
</div>
- {/* Market Stats Grid */}
+ {/* Order Book Panel — YES and NO side by side, proper ladder layout */}
+ <div style={{ border: '1px solid #333333', backgroundColor: '#000000', marginBottom: '12px' }}>
+ {/* Header */}
+ <div style={{ padding: '8px 12px', borderBottom: '1px solid #1e1e1e', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
+ <span style={{ fontSize: '10px', color: '#787878', fontWeight: 'bold', letterSpacing: '0.05em' }}>ORDER BOOK</span>
+ <div style={{ display: 'flex', gap: '16px' }}>
+ {[yesOrderBook, noOrderBook].map((book, i) => {
+ if (!book?.last_trade_price) return null;
+ const ltpNum = parseFloat(book.last_trade_price);
+ if (isNaN(ltpNum)) return null;
+ const name = outcomeNames[i] ?? (i === 0 ? 'YES' : 'NO');
+ const color = OUTCOME_COLORS[i] ?? '#787878';
+ return (
+ <span key={i} style={{ fontSize: '9px', color: '#555' }}>
+ <span style={{ color, fontWeight: 'bold' }}>{name.toUpperCase()}</span>
+ {' LAST: '}
+ <span style={{ color: '#FFFFFF', fontWeight: 'bold' }}>${ltpNum.toFixed(4)}</span>
+ </span>
+ );
+ })}
+ </div>
+ </div>
+
+ {orderBookLoading ? (
+ <div style={{ padding: '20px', textAlign: 'center', color: '#555', fontSize: '10px' }}>LOADING ORDER BOOK...</div>
+ ) : orderBookError && !yesOrderBook && !noOrderBook ? (
+ <div style={{ padding: '20px', textAlign: 'center', color: '#555', fontSize: '10px' }}>{orderBookError}</div>
+ ) : (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1px', backgroundColor: '#1a1a1a' }}>
+ {([
+ { book: yesOrderBook, outcomeIdx: 0 },
+ { book: noOrderBook, outcomeIdx: 1 },
+ ] as const).map(({ book, outcomeIdx }) => {
+ const name = outcomeNames[outcomeIdx] ?? (outcomeIdx === 0 ? 'YES' : 'NO');
+ const labelColor = OUTCOME_COLORS[outcomeIdx] ?? '#787878';
+
+ if (!book) {
+ return (
+ <div key={outcomeIdx} style={{ backgroundColor: '#000000', padding: '20px', textAlign: 'center', color: '#555', fontSize: '9px' }}>
+ <div style={{ color: labelColor, fontWeight: 'bold', marginBottom: '6px' }}>{name.toUpperCase()}</div>
+ NO DATA
+ </div>
+ );
+ }
+
+ // bids sorted descending: best bid (highest price) first
+ const bids = [...(book.bids ?? [])]
+ .sort((a, b) => parseFloat(b.price) - parseFloat(a.price))
+ .slice(0, 8);
+ // asks sorted ascending: best ask (lowest price) last — we display reversed so best ask is nearest spread
+ const asks = [...(book.asks ?? [])]
+ .sort((a, b) => parseFloat(a.price) - parseFloat(b.price))
+ .slice(0, 8);
+
+ // Spread between best bid and best ask
+ const bestBidPrice = bids[0] ? parseFloat(bids[0].price) : null;
+ const bestAskPrice = asks[0] ? parseFloat(asks[0].price) : null;
+ const spread = bestBidPrice != null && bestAskPrice != null ? bestAskPrice - bestBidPrice : null;
+
+ // Shared max size for depth bars across both sides
+ const maxSize = Math.max(
+ ...bids.map(b => parseFloat(b.size) || 0),
+ ...asks.map(a => parseFloat(a.size) || 0),
+ 0.001
+ );
+
+ const fmtSize = (s: number) => s >= 1000 ? `${(s / 1000).toFixed(1)}K` : s.toFixed(0);
+ const fmtPrice = (p: number) => `$${p.toFixed(3)}`;
+
+ // cols: PRICE (fixed) | SIZE (fixed) — depth bar fills behind
+ const ROW_COLS = '80px 1fr';
+
+ const renderLevel = (entry: { price: string; size: string }, side: 'bid' | 'ask') => {
+ const price = parseFloat(entry.price);
+ const size = parseFloat(entry.size) || 0;
+ const pct = Math.min((size / maxSize) * 100, 100);
+ const isBid = side === 'bid';
+ return (
+ <div
+ key={`${side}-${entry.price}`}
+ style={{ position: 'relative', display: 'grid', gridTemplateColumns: ROW_COLS, padding: '3px 8px', borderBottom: '1px solid #080808' }}
+ >
+ {/* depth bar — fills from right edge for asks, right edge for bids (both right-to-left so the bar is behind the qty) */}
+ <div style={{
+ position: 'absolute', top: 0, bottom: 0, right: 0,
+ width: `${pct}%`,
+ backgroundColor: isBid ? '#00D66F0D' : '#FF3B3B0D',
+ }} />
+ <span style={{ position: 'relative', fontSize: '10px', fontWeight: 'bold', color: isBid ? '#00D66F' : '#FF3B3B', fontFamily: 'IBM Plex Mono, monospace' }}>
+ {fmtPrice(price)}
+ </span>
+ <span style={{ position: 'relative', fontSize: '10px', color: '#787878', textAlign: 'right', fontFamily: 'IBM Plex Mono, monospace' }}>
+ {fmtSize(size)}
+ </span>
+ </div>
+ );
+ };
+
+ return (
+ <div key={outcomeIdx} style={{ backgroundColor: '#000000' }}>
+ {/* Outcome header */}
+ <div style={{ padding: '5px 8px', borderBottom: '1px solid #1a1a1a', display: 'flex', alignItems: 'center', justifyContent: 'space-between', backgroundColor: '#050505' }}>
+ <span style={{ fontSize: '10px', color: labelColor, fontWeight: 'bold', letterSpacing: '0.05em' }}>{name.toUpperCase()}</span>
+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
+ {book.last_trade_price && (
+ <span style={{ fontSize: '8px', color: '#555' }}>
+ LAST <span style={{ color: '#FFFFFF' }}>{fmtPrice(parseFloat(book.last_trade_price))}</span>
+ </span>
+ )}
+ {book.tick_size && (
+ <span style={{ fontSize: '8px', color: '#333' }}>TICK {book.tick_size}</span>
+ )}
+ </div>
+ </div>
+
+ {/* Column labels */}
+ <div style={{ display: 'grid', gridTemplateColumns: ROW_COLS, padding: '2px 8px', borderBottom: '1px solid #111' }}>
+ <span style={{ fontSize: '8px', color: '#555', fontWeight: 'bold' }}>PRICE</span>
+ <span style={{ fontSize: '8px', color: '#555', fontWeight: 'bold', textAlign: 'right' }}>QTY ($)</span>
+ </div>
+
+ {/* ASKS — worst (highest) at top, best (lowest) at bottom just above spread */}
+ {asks.length === 0
+ ? <div style={{ padding: '6px 8px', fontSize: '9px', color: '#333', textAlign: 'center' }}>no asks</div>
+ : [...asks].reverse().map(a => renderLevel(a, 'ask'))
+ }
+
+ {/* Spread separator */}
+ <div style={{ display: 'grid', gridTemplateColumns: ROW_COLS, padding: '3px 8px', backgroundColor: '#0C0C0C', borderTop: '1px solid #1a1a1a', borderBottom: '1px solid #1a1a1a' }}>
+ <span style={{ fontSize: '8px', color: '#444', fontWeight: 'bold' }}>SPREAD</span>
+ <span style={{ fontSize: '9px', color: '#555', textAlign: 'right', fontFamily: 'IBM Plex Mono, monospace' }}>
+ {spread != null ? fmtPrice(spread) : '—'}
+ </span>
+ </div>
+
+ {/* BIDS — best (highest) at top just below spread, worst at bottom */}
+ {bids.length === 0
+ ? <div style={{ padding: '6px 8px', fontSize: '9px', color: '#333', textAlign: 'center' }}>no bids</div>
+ : bids.map(b => renderLevel(b, 'bid'))
+ }
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+
+ {/* Market Stats Grid — 8 cells */}
+ {(() => {
+ // Open interest lives on events[0].openInterest (number)
+ const eventOpenInterest: number | null = (selectedMarket as any).events?.[0]?.openInterest ?? null;
+ // 24h volume lives on events[0].series[0].volume24hr
+ const series24h: number | null = (selectedMarket as any).events?.[0]?.series?.[0]?.volume24hr ?? null;
+ // 1wk / 1mo volume — API returns volume1wk / volume1mo directly on market
+ const vol1wk: number | null = selectedMarket.volume1wk ?? null;
+ const vol1mo: number | null = selectedMarket.volume1mo ?? null;
+
+ return (
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: '1px',
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #1a1a1a',
+ marginBottom: '12px'
+ }}>
+ {[
+ {
+ label: 'TOTAL VOLUME',
+ value: formatDollarVolume(selectedMarket.volumeNum ?? selectedMarket.volume ?? 0),
+ },
+ {
+ label: '24H VOLUME',
+ value: series24h != null ? formatDollarVolume(series24h) : 'N/A',
+ },
+ {
+ label: 'LIQUIDITY',
+ value: formatDollarVolume(selectedMarket.liquidityNum ?? selectedMarket.liquidity ?? 0),
+ },
+ {
+ label: 'OPEN INTEREST',
+ value: eventOpenInterest != null ? formatDollarVolume(eventOpenInterest) : 'N/A',
+ },
+ {
+ label: 'END DATE',
+ value: selectedMarket.endDate
+ ? new Date(selectedMarket.endDate).toLocaleDateString('en-US', { month: 'numeric', day: 'numeric', year: 'numeric' })
+ : 'N/A',
+ },
+ {
+ label: 'SPREAD',
+ value: (() => {
+ const s = selectedMarket.spread;
+ if (s !== null && s !== undefined && !isNaN(Number(s))) return `${(Number(s) * 100).toFixed(2)}%`;
+ return 'N/A';
+ })(),
+ },
+ {
+ label: '1WK VOLUME',
+ value: vol1wk != null ? formatDollarVolume(vol1wk) : 'N/A',
+ },
+ {
+ label: '1MO VOLUME',
+ value: vol1mo != null ? formatDollarVolume(vol1mo) : 'N/A',
+ },
+ ].map(stat => (
+ <div key={stat.label} style={{ backgroundColor: '#000000', padding: '12px' }}>
+ <div style={{ color: '#555', fontSize: '9px', marginBottom: '4px', fontWeight: 'bold', letterSpacing: '0.05em' }}>
+ {stat.label}
+ </div>
+ <div style={{ color: '#FFFFFF', fontSize: '13px', fontWeight: 'bold' }}>
+ {stat.value}
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+ })()}
+
+ {/* Price Change Row — only 1D is reliably provided by the API */}
+ {selectedMarket.oneDayPriceChange != null && (
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: '1px',
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #1a1a1a',
+ marginBottom: '12px'
+ }}>
+ {[
+ { label: '1D PRICE CHANGE', val: selectedMarket.oneDayPriceChange },
+ { label: 'LAST TRADE', val: selectedMarket.lastTradePrice != null ? selectedMarket.lastTradePrice : null, isPrice: true },
+ { label: 'BEST BID', val: selectedMarket.bestBid != null ? selectedMarket.bestBid : null, isPrice: true },
+ { label: 'BEST ASK', val: selectedMarket.bestAsk != null ? selectedMarket.bestAsk : null, isPrice: true },
+ ].map(item => {
+ const isPrice = (item as any).isPrice;
+ const color = item.val == null ? '#555'
+ : isPrice ? '#FFFFFF'
+ : item.val >= 0 ? '#00D66F' : '#FF3B3B';
+ const displayVal = item.val == null ? 'N/A'
+ : isPrice ? `$${(item.val as number).toFixed(4)}`
+ : `${item.val >= 0 ? '+' : ''}${(item.val * 100).toFixed(2)}%`;
+ return (
+ <div key={item.label} style={{ backgroundColor: '#000000', padding: '12px' }}>
+ <div style={{ color: '#555', fontSize: '9px', marginBottom: '4px', fontWeight: 'bold', letterSpacing: '0.05em' }}>{item.label}</div>
+ <div style={{ color, fontSize: '13px', fontWeight: 'bold' }}>{displayVal}</div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Market Metadata Row */}
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(4, 1fr)',
gap: '1px',
- backgroundColor: '#333333',
- border: '1px solid #333333',
- marginBottom: '16px'
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #1a1a1a',
+ marginBottom: '12px'
}}>
{[
- { label: 'VOLUME', value: polymarketService.formatVolume(selectedMarket.volume || '0') },
- { label: 'LIQUIDITY', value: polymarketService.formatVolume(selectedMarket.liquidity || '0') },
- { label: 'END DATE', value: selectedMarket.endDate ? new Date(selectedMarket.endDate).toLocaleDateString() : 'N/A' },
{
- label: 'SPREAD',
+ label: 'RESOLUTION SOURCE',
+ value: selectedMarket.resolutionSource || 'N/A',
+ },
+ {
+ label: 'STATUS',
+ value: selectedMarket.acceptingOrders ? 'ACCEPTING ORDERS'
+ : selectedMarket.closed ? 'CLOSED'
+ : 'NOT ACCEPTING',
+ },
+ {
+ label: 'MIN ORDER SIZE',
value: (() => {
- const spread = selectedMarket.spread;
- if (spread !== null && spread !== undefined && !isNaN(spread)) {
- return `${spread.toFixed(2)}%`;
- }
- return 'N/A';
- })()
+ const minSize = yesOrderBook?.min_order_size ?? (selectedMarket.orderMinSize != null ? String(selectedMarket.orderMinSize) : null);
+ return minSize != null ? `$${parseFloat(minSize).toFixed(2)}` : 'N/A';
+ })(),
+ },
+ {
+ label: 'TICK SIZE',
+ value: (() => {
+ const tick = yesOrderBook?.tick_size ?? (selectedMarket.orderPriceMinTickSize != null ? String(selectedMarket.orderPriceMinTickSize) : null);
+ return tick != null ? parseFloat(tick).toFixed(6) : 'N/A';
+ })(),
},
].map(stat => (
- <div key={stat.label} style={{
- backgroundColor: '#000000',
- padding: '12px'
- }}>
- <div style={{ color: '#787878', fontSize: '9px', marginBottom: '4px', fontWeight: 'bold' }}>
+ <div key={stat.label} style={{ backgroundColor: '#000000', padding: '12px' }}>
+ <div style={{ color: '#555', fontSize: '9px', marginBottom: '4px', fontWeight: 'bold', letterSpacing: '0.05em' }}>
{stat.label}
</div>
- <div style={{ color: '#FFFFFF', fontSize: '12px', fontWeight: 'bold' }}>
+ <div style={{
+ color: stat.label === 'STATUS' && stat.value === 'ACCEPTING ORDERS' ? '#00D66F'
+ : stat.label === 'STATUS' ? '#FF3B3B'
+ : '#FFFFFF',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ wordBreak: 'break-all'
+ }}>
{stat.value}
</div>
</div>
))}
</div>
+ {/* Top Holders Table */}
+ <div style={{ border: '1px solid #333333', backgroundColor: '#000000', marginBottom: '12px' }}>
+ <div style={{ padding: '8px 12px', borderBottom: '1px solid #1e1e1e' }}>
+ <span style={{ fontSize: '10px', color: '#787878' }}>TOP HOLDERS</span>
+ </div>
+ {holdersLoading ? (
+ <div style={{ padding: '20px', textAlign: 'center', color: '#555', fontSize: '10px' }}>LOADING HOLDERS...</div>
+ ) : holdersError ? (
+ <div style={{ padding: '20px', textAlign: 'center', color: '#555', fontSize: '10px' }}>{holdersError}</div>
+ ) : !topHolders || topHolders.holders.length === 0 ? (
+ <div style={{ padding: '20px', textAlign: 'center', color: '#555', fontSize: '10px' }}>NO HOLDER DATA</div>
+ ) : (
+ <>
+ {/* Column headers */}
+ <div style={{ display: 'grid', gridTemplateColumns: '24px 1fr 80px 80px', padding: '4px 8px', borderBottom: '1px solid #111', gap: '8px' }}>
+ <span style={{ fontSize: '9px', color: '#555', fontWeight: 'bold' }}>#</span>
+ <span style={{ fontSize: '9px', color: '#555', fontWeight: 'bold' }}>HOLDER</span>
+ <span style={{ fontSize: '9px', color: '#555', fontWeight: 'bold', textAlign: 'center' }}>OUTCOME</span>
+ <span style={{ fontSize: '9px', color: '#555', fontWeight: 'bold', textAlign: 'right' }}>POSITION</span>
+ </div>
+ <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
+ {topHolders.holders.slice(0, 20).map((holder, idx) => {
+ const outcomeName = outcomeNames[holder.outcomeIndex] ?? `Outcome ${holder.outcomeIndex}`;
+ const outcomeColor = OUTCOME_COLORS[holder.outcomeIndex] ?? '#787878';
+ const displayName = holder.name ?? holder.pseudonym ?? `${holder.proxyWallet.slice(0, 6)}...${holder.proxyWallet.slice(-4)}`;
+ return (
+ <div key={idx} style={{ display: 'grid', gridTemplateColumns: '24px 1fr 80px 80px', padding: '5px 8px', borderBottom: '1px solid #0a0a0a', gap: '8px', alignItems: 'center' }}>
+ <span style={{ fontSize: '9px', color: '#555' }}>{idx + 1}</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', overflow: 'hidden' }}>
+ {holder.profileImage && (
+ <img src={holder.profileImage} alt="" style={{ width: '16px', height: '16px', borderRadius: '50%', flexShrink: 0 }} />
+ )}
+ <span style={{ fontSize: '10px', color: '#FFFFFF', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{displayName}</span>
+ </div>
+ <span style={{ fontSize: '9px', color: outcomeColor, fontWeight: 'bold', textAlign: 'center', textTransform: 'uppercase' }}>{outcomeName}</span>
+ <span style={{ fontSize: '10px', color: '#FFFFFF', fontWeight: 'bold', textAlign: 'right' }}>{formatDollarVolume(holder.amount)}</span>
+ </div>
+ );
+ })}
+ </div>
+ </>
+ )}
+ </div>
+
{/* Recent Trades */}
{recentTrades.length > 0 && (
- <div style={{ backgroundColor: '#0A0A0A', border: '1px solid #333333', padding: '16px' }}>
+ <div style={{ backgroundColor: '#0A0A0A', border: '1px solid #333333', padding: '16px', marginBottom: '12px' }}>
<div style={{ color: '#FF8800', fontSize: '11px', fontWeight: 'bold', marginBottom: '12px', borderBottom: '1px solid #333333', paddingBottom: '8px' }}>
RECENT TRADES
</div>
@@ -798,10 +1652,10 @@ const PolymarketTabEnhanced: React.FC = () => {
)}
{/* External Link */}
- {selectedMarket.slug && (
+ {(selectedMarket.slug || selectedMarket.events?.[0]?.slug) && (
<div style={{ marginTop: '16px' }}>
<a
- href={`https://polymarket.com/event/${selectedMarket.slug}`}
+ href={`https://polymarket.com/event/${selectedMarket.events?.[0]?.slug ?? selectedMarket.slug}`}
target="_blank"
rel="noopener noreferrer"
style={{
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-optimization/PortfolioOptimizationTab.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-optimization/PortfolioOptimizationTab.tsx
deleted file mode 100644
index 0c136661f..000000000
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-optimization/PortfolioOptimizationTab.tsx
+++ /dev/null
@@ -1,1110 +0,0 @@
-import React, { useState } from 'react';
-import { invoke } from '@tauri-apps/api/core';
-import { TrendingUp, BarChart3, PieChart, LineChart, Target, Shield, Calculator, Download } from 'lucide-react';
-
-// Library selection
-const LIBRARIES = [
- { value: 'pyportfolioopt', label: 'PyPortfolioOpt', description: 'Classical optimization' },
- { value: 'skfolio', label: 'skfolio', description: 'Modern ML-integrated optimization (2025)' },
-];
-
-// PyPortfolioOpt methods
-const PYPORTFOLIOOPT_METHODS = [
- { value: 'efficient_frontier', label: 'Efficient Frontier', description: 'Mean-variance optimization' },
- { value: 'hrp', label: 'HRP (Hierarchical Risk Parity)', description: 'Machine learning based' },
- { value: 'cla', label: 'CLA (Critical Line Algorithm)', description: 'Analytical solution' },
- { value: 'black_litterman', label: 'Black-Litterman', description: 'Views-based approach' },
- { value: 'efficient_semivariance', label: 'Efficient Semivariance', description: 'Downside risk focus' },
- { value: 'efficient_cvar', label: 'Efficient CVaR', description: 'Conditional Value at Risk' },
- { value: 'efficient_cdar', label: 'Efficient CDaR', description: 'Conditional Drawdown at Risk' },
-];
-
-// skfolio methods
-const SKFOLIO_METHODS = [
- { value: 'mean_risk', label: 'Mean-Risk', description: 'Mean-variance with advanced estimators' },
- { value: 'risk_parity', label: 'Risk Parity', description: 'Equal risk contribution' },
- { value: 'hrp', label: 'Hierarchical Risk Parity', description: 'Clustering-based allocation' },
- { value: 'max_div', label: 'Maximum Diversification', description: 'Maximize portfolio diversification' },
- { value: 'equal_weight', label: 'Equal Weight', description: '1/N allocation' },
- { value: 'inverse_vol', label: 'Inverse Volatility', description: 'Weight by inverse volatility' },
-];
-
-// PyPortfolioOpt objectives
-const PYPORTFOLIOOPT_OBJECTIVES = [
- { value: 'max_sharpe', label: 'Maximize Sharpe Ratio' },
- { value: 'min_volatility', label: 'Minimize Volatility' },
- { value: 'max_quadratic_utility', label: 'Maximize Quadratic Utility' },
- { value: 'efficient_risk', label: 'Target Risk Level' },
- { value: 'efficient_return', label: 'Target Return Level' },
-];
-
-// skfolio objectives
-const SKFOLIO_OBJECTIVES = [
- { value: 'minimize_risk', label: 'Minimize Risk' },
- { value: 'maximize_return', label: 'Maximize Return' },
- { value: 'maximize_ratio', label: 'Maximize Sharpe Ratio' },
- { value: 'maximize_utility', label: 'Maximize Utility' },
-];
-
-// skfolio risk measures
-const SKFOLIO_RISK_MEASURES = [
- { value: 'variance', label: 'Variance' },
- { value: 'semi_variance', label: 'Semi-Variance' },
- { value: 'cvar', label: 'CVaR (Conditional Value at Risk)' },
- { value: 'evar', label: 'EVaR (Entropic Value at Risk)' },
- { value: 'max_drawdown', label: 'Maximum Drawdown' },
- { value: 'cdar', label: 'CDaR (Conditional Drawdown at Risk)' },
- { value: 'ulcer_index', label: 'Ulcer Index' },
-];
-
-const EXPECTED_RETURNS_METHODS = [
- { value: 'mean_historical_return', label: 'Mean Historical Return' },
- { value: 'ema_historical_return', label: 'EMA Historical Return' },
- { value: 'capm_return', label: 'CAPM Return' },
-];
-
-const RISK_MODELS = [
- { value: 'sample_cov', label: 'Sample Covariance' },
- { value: 'semicovariance', label: 'Semicovariance' },
- { value: 'exp_cov', label: 'Exponential Covariance' },
- { value: 'shrunk_covariance', label: 'Shrunk Covariance' },
- { value: 'ledoit_wolf', label: 'Ledoit-Wolf' },
-];
-
-interface OptimizationConfig {
- optimization_method: string;
- objective: string;
- expected_returns_method: string;
- risk_model_method: string;
- risk_free_rate: number;
- weight_bounds_min: number;
- weight_bounds_max: number;
- gamma: number;
- total_portfolio_value: number;
-}
-
-interface OptimizationResults {
- weights?: Record<string, number>;
- performance_metrics?: {
- expected_annual_return: number;
- annual_volatility: number;
- sharpe_ratio: number;
- };
- discrete_allocation?: {
- allocation: Record<string, number>;
- leftover_cash: number;
- total_value: number;
- };
- efficient_frontier?: {
- returns: number[];
- volatility: number[];
- sharpe_ratios: number[];
- };
- backtest_results?: {
- annual_return: number;
- annual_volatility: number;
- sharpe_ratio: number;
- max_drawdown: number;
- calmar_ratio: number;
- };
-}
-
-const PortfolioOptimizationTab: React.FC = () => {
- const [library, setLibrary] = useState<'pyportfolioopt' | 'skfolio'>('skfolio');
- const [config, setConfig] = useState<OptimizationConfig>({
- optimization_method: 'mean_risk',
- objective: 'maximize_ratio',
- expected_returns_method: 'mean_historical_return',
- risk_model_method: 'sample_cov',
- risk_free_rate: 0.02,
- weight_bounds_min: 0,
- weight_bounds_max: 1,
- gamma: 0,
- total_portfolio_value: 10000,
- });
-
- const [skfolioConfig, setSkfolioConfig] = useState({
- risk_measure: 'cvar',
- covariance_estimator: 'ledoit_wolf',
- train_test_split: 0.7,
- l1_coef: 0.0,
- l2_coef: 0.0,
- });
-
- const [assetSymbols, setAssetSymbols] = useState<string>('AAPL,GOOGL,MSFT,AMZN,TSLA');
- const [results, setResults] = useState<OptimizationResults | null>(null);
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [activeTab, setActiveTab] = useState<'optimize' | 'frontier' | 'backtest' | 'allocation' | 'risk'>('optimize');
-
- // Main optimization
- const handleOptimize = async () => {
- setLoading(true);
- setError(null);
-
- try {
- let response: string;
-
- if (library === 'skfolio') {
- // Use skfolio
- const skfolioParams = {
- ...skfolioConfig,
- optimization_method: config.optimization_method,
- objective_function: config.objective,
- };
-
- response = await invoke<string>('skfolio_optimize_portfolio', {
- pricesData: assetSymbols, // Will be fetched by Python script
- optimizationMethod: config.optimization_method,
- objectiveFunction: config.objective,
- riskMeasure: skfolioConfig.risk_measure,
- config: JSON.stringify(skfolioParams),
- });
- } else {
- // Use PyPortfolioOpt with PyO3
- // First, fetch price data (in production, this would come from your data source)
- const pricesJson = JSON.stringify({
- // This is placeholder - in production you'd fetch actual price data
- symbols: assetSymbols.split(',').map(s => s.trim()),
- // You'll need to integrate with your price data fetching service here
- });
-
- const pyportfoliooptConfig = {
- optimization_method: config.optimization_method,
- objective: config.objective,
- expected_returns_method: config.expected_returns_method,
- risk_model_method: config.risk_model_method,
- risk_free_rate: config.risk_free_rate,
- risk_aversion: 1.0,
- market_neutral: false,
- weight_bounds: [config.weight_bounds_min, config.weight_bounds_max] as [number, number],
- gamma: config.gamma,
- span: 500,
- frequency: 252,
- delta: 0.95,
- shrinkage_target: "constant_variance",
- beta: 0.95,
- tau: 0.1,
- linkage_method: "ward",
- distance_metric: "euclidean",
- total_portfolio_value: config.total_portfolio_value,
- };
-
- response = await invoke<string>('pyportfolioopt_optimize', {
- pricesJson,
- config: pyportfoliooptConfig,
- });
- }
-
- const data = JSON.parse(response);
- setResults(data);
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Optimization failed');
- } finally {
- setLoading(false);
- }
- };
-
- // Generate efficient frontier
- const handleGenerateFrontier = async () => {
- setLoading(true);
- setError(null);
-
- try {
- const pricesJson = JSON.stringify({
- symbols: assetSymbols.split(',').map(s => s.trim()),
- });
-
- const pyportfoliooptConfig = {
- optimization_method: config.optimization_method,
- objective: config.objective,
- expected_returns_method: config.expected_returns_method,
- risk_model_method: config.risk_model_method,
- risk_free_rate: config.risk_free_rate,
- risk_aversion: 1.0,
- market_neutral: false,
- weight_bounds: [config.weight_bounds_min, config.weight_bounds_max] as [number, number],
- gamma: config.gamma,
- span: 500,
- frequency: 252,
- delta: 0.95,
- shrinkage_target: "constant_variance",
- beta: 0.95,
- tau: 0.1,
- linkage_method: "ward",
- distance_metric: "euclidean",
- total_portfolio_value: config.total_portfolio_value,
- };
-
- const response = await invoke<string>('pyportfolioopt_efficient_frontier', {
- pricesJson,
- config: pyportfoliooptConfig,
- numPoints: 100,
- });
-
- const data = JSON.parse(response);
- setResults({ ...results, efficient_frontier: data });
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Frontier generation failed');
- } finally {
- setLoading(false);
- }
- };
-
- // Run backtest
- const handleBacktest = async () => {
- setLoading(true);
- setError(null);
-
- try {
- const pricesJson = JSON.stringify({
- symbols: assetSymbols.split(',').map(s => s.trim()),
- });
-
- const pyportfoliooptConfig = {
- optimization_method: config.optimization_method,
- objective: config.objective,
- expected_returns_method: config.expected_returns_method,
- risk_model_method: config.risk_model_method,
- risk_free_rate: config.risk_free_rate,
- risk_aversion: 1.0,
- market_neutral: false,
- weight_bounds: [config.weight_bounds_min, config.weight_bounds_max] as [number, number],
- gamma: config.gamma,
- span: 500,
- frequency: 252,
- delta: 0.95,
- shrinkage_target: "constant_variance",
- beta: 0.95,
- tau: 0.1,
- linkage_method: "ward",
- distance_metric: "euclidean",
- total_portfolio_value: config.total_portfolio_value,
- };
-
- const response = await invoke<string>('pyportfolioopt_backtest', {
- pricesJson,
- config: pyportfoliooptConfig,
- rebalanceFrequency: 21,
- lookbackPeriod: 252,
- });
-
- const data = JSON.parse(response);
- setResults({ ...results, backtest_results: data });
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Backtest failed');
- } finally {
- setLoading(false);
- }
- };
-
- // Discrete allocation
- const handleDiscreteAllocation = async () => {
- if (!results?.weights) {
- setError('Run optimization first');
- return;
- }
-
- setLoading(true);
- setError(null);
-
- try {
- const pricesJson = JSON.stringify({
- symbols: assetSymbols.split(',').map(s => s.trim()),
- });
-
- const response = await invoke<string>('pyportfolioopt_discrete_allocation', {
- pricesJson,
- weights: results.weights,
- totalPortfolioValue: config.total_portfolio_value,
- });
-
- const data = JSON.parse(response);
- setResults({ ...results, discrete_allocation: data });
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Allocation failed');
- } finally {
- setLoading(false);
- }
- };
-
- // Export results
- const handleExport = async (format: 'json' | 'csv') => {
- if (!results) return;
-
- try {
- const pricesJson = JSON.stringify({
- symbols: assetSymbols.split(',').map(s => s.trim()),
- });
-
- const pyportfoliooptConfig = {
- optimization_method: config.optimization_method,
- objective: config.objective,
- expected_returns_method: config.expected_returns_method,
- risk_model_method: config.risk_model_method,
- risk_free_rate: config.risk_free_rate,
- risk_aversion: 1.0,
- market_neutral: false,
- weight_bounds: [config.weight_bounds_min, config.weight_bounds_max] as [number, number],
- gamma: config.gamma,
- span: 500,
- frequency: 252,
- delta: 0.95,
- shrinkage_target: "constant_variance",
- beta: 0.95,
- tau: 0.1,
- linkage_method: "ward",
- distance_metric: "euclidean",
- total_portfolio_value: config.total_portfolio_value,
- };
-
- const reportJson = await invoke<string>('pyportfolioopt_generate_report', {
- pricesJson,
- config: pyportfoliooptConfig,
- });
-
- // Download the report
- const blob = new Blob([reportJson], { type: format === 'json' ? 'application/json' : 'text/csv' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `portfolio_optimization_${Date.now()}.${format}`;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Export failed');
- }
- };
-
- return (
- <div style={{
- height: '100%',
- backgroundColor: '#000000',
- color: '#FFFFFF',
- fontFamily: 'IBM Plex Mono, monospace',
- overflow: 'auto',
- padding: '16px'
- }}>
- {/* Header */}
- <div style={{
- borderBottom: '2px solid #FF8800',
- paddingBottom: '12px',
- marginBottom: '24px'
- }}>
- <h1 style={{
- color: '#FF8800',
- fontSize: '18px',
- fontWeight: 'bold',
- margin: 0,
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}>
- <TrendingUp size={24} />
- PORTFOLIO OPTIMIZATION - {library === 'skfolio' ? 'skfolio (2025)' : 'PyPortfolioOpt'}
- </h1>
- </div>
-
- {/* Navigation Tabs */}
- <div style={{ display: 'flex', gap: '8px', marginBottom: '24px', borderBottom: '1px solid #333' }}>
- {[
- { id: 'optimize', label: 'OPTIMIZE', icon: Calculator },
- { id: 'frontier', label: 'EFFICIENT FRONTIER', icon: LineChart },
- { id: 'backtest', label: 'BACKTEST', icon: BarChart3 },
- { id: 'allocation', label: 'ALLOCATION', icon: PieChart },
- { id: 'risk', label: 'RISK ANALYSIS', icon: Shield },
- ].map(({ id, label, icon: Icon }) => (
- <button
- key={id}
- onClick={() => setActiveTab(id as any)}
- style={{
- padding: '8px 16px',
- backgroundColor: activeTab === id ? '#FF8800' : 'transparent',
- color: activeTab === id ? '#000' : '#FFF',
- border: 'none',
- borderBottom: activeTab === id ? '2px solid #FF8800' : '2px solid transparent',
- cursor: 'pointer',
- fontFamily: 'inherit',
- fontSize: '11px',
- fontWeight: 'bold',
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Icon size={14} />
- {label}
- </button>
- ))}
- </div>
-
- {/* Error Display */}
- {error && (
- <div style={{
- padding: '12px',
- backgroundColor: 'rgba(255,59,59,0.1)',
- border: '1px solid #FF3B3B',
- color: '#FF3B3B',
- marginBottom: '16px',
- fontSize: '11px'
- }}>
- ERROR: {error}
- </div>
- )}
-
- {/* OPTIMIZE TAB */}
- {activeTab === 'optimize' && (
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px' }}>
- {/* Configuration Panel */}
- <div>
- <div style={{
- color: '#FF8800',
- fontSize: '12px',
- fontWeight: 'bold',
- marginBottom: '16px',
- borderBottom: '1px solid #FF8800',
- paddingBottom: '8px'
- }}>
- OPTIMIZATION CONFIGURATION
- </div>
-
- {/* Library Selection */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- OPTIMIZATION LIBRARY
- </label>
- <select
- value={library}
- onChange={(e) => {
- setLibrary(e.target.value as 'pyportfolioopt' | 'skfolio');
- // Reset config based on library
- if (e.target.value === 'skfolio') {
- setConfig(prev => ({ ...prev, optimization_method: 'mean_risk', objective: 'maximize_ratio' }));
- } else {
- setConfig(prev => ({ ...prev, optimization_method: 'efficient_frontier', objective: 'max_sharpe' }));
- }
- }}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- >
- {LIBRARIES.map(lib => (
- <option key={lib.value} value={lib.value}>{lib.label} - {lib.description}</option>
- ))}
- </select>
- </div>
-
- {/* Asset Symbols */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- ASSET SYMBOLS (comma-separated)
- </label>
- <input
- type="text"
- value={assetSymbols}
- onChange={(e) => setAssetSymbols(e.target.value)}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- placeholder="AAPL,GOOGL,MSFT,AMZN,TSLA"
- />
- </div>
-
- {/* Optimization Method */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- OPTIMIZATION METHOD
- </label>
- <select
- value={config.optimization_method}
- onChange={(e) => setConfig({ ...config, optimization_method: e.target.value })}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- >
- {(library === 'skfolio' ? SKFOLIO_METHODS : PYPORTFOLIOOPT_METHODS).map(m => (
- <option key={m.value} value={m.value}>{m.label} - {m.description}</option>
- ))}
- </select>
- </div>
-
- {/* Objective */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- OBJECTIVE FUNCTION
- </label>
- <select
- value={config.objective}
- onChange={(e) => setConfig({ ...config, objective: e.target.value })}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- >
- {(library === 'skfolio' ? SKFOLIO_OBJECTIVES : PYPORTFOLIOOPT_OBJECTIVES).map(o => (
- <option key={o.value} value={o.value}>{o.label}</option>
- ))}
- </select>
- </div>
-
- {/* skfolio-specific: Risk Measure */}
- {library === 'skfolio' && (
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- RISK MEASURE
- </label>
- <select
- value={skfolioConfig.risk_measure}
- onChange={(e) => setSkfolioConfig({ ...skfolioConfig, risk_measure: e.target.value })}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- >
- {SKFOLIO_RISK_MEASURES.map(r => (
- <option key={r.value} value={r.value}>{r.label}</option>
- ))}
- </select>
- </div>
- )}
-
- {/* Expected Returns Method */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- EXPECTED RETURNS METHOD
- </label>
- <select
- value={config.expected_returns_method}
- onChange={(e) => setConfig({ ...config, expected_returns_method: e.target.value })}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- >
- {EXPECTED_RETURNS_METHODS.map(m => (
- <option key={m.value} value={m.value}>{m.label}</option>
- ))}
- </select>
- </div>
-
- {/* Risk Model */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- RISK MODEL
- </label>
- <select
- value={config.risk_model_method}
- onChange={(e) => setConfig({ ...config, risk_model_method: e.target.value })}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- >
- {RISK_MODELS.map(m => (
- <option key={m.value} value={m.value}>{m.label}</option>
- ))}
- </select>
- </div>
-
- {/* Risk-Free Rate */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- RISK-FREE RATE (%)
- </label>
- <input
- type="text"
- inputMode="decimal"
- value={config.risk_free_rate * 100}
- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setConfig({ ...config, risk_free_rate: (parseFloat(v) || 0) / 100 }); }}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- />
- </div>
-
- {/* Weight Bounds */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '16px' }}>
- <div>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- MIN WEIGHT (%)
- </label>
- <input
- type="text"
- inputMode="decimal"
- value={config.weight_bounds_min * 100}
- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setConfig({ ...config, weight_bounds_min: (parseFloat(v) || 0) / 100 }); }}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- />
- </div>
- <div>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- MAX WEIGHT (%)
- </label>
- <input
- type="text"
- inputMode="decimal"
- value={config.weight_bounds_max * 100}
- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setConfig({ ...config, weight_bounds_max: (parseFloat(v) || 0) / 100 }); }}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- />
- </div>
- </div>
-
- {/* L2 Regularization */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- L2 REGULARIZATION (Gamma)
- </label>
- <input
- type="text"
- inputMode="decimal"
- value={config.gamma}
- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setConfig({ ...config, gamma: parseFloat(v) || 0 }); }}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- />
- </div>
-
- {/* Portfolio Value */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- TOTAL PORTFOLIO VALUE ($)
- </label>
- <input
- type="text"
- inputMode="decimal"
- value={config.total_portfolio_value}
- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setConfig({ ...config, total_portfolio_value: parseFloat(v) || 0 }); }}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
- }}
- />
- </div>
-
- {/* Optimize Button */}
- <button
- onClick={handleOptimize}
- disabled={loading}
- style={{
- width: '100%',
- padding: '12px',
- backgroundColor: loading ? '#666' : '#FF8800',
- color: '#000',
- border: 'none',
- fontFamily: 'inherit',
- fontSize: '12px',
- fontWeight: 'bold',
- cursor: loading ? 'not-allowed' : 'pointer',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- gap: '8px'
- }}
- >
- <Target size={16} />
- {loading ? 'OPTIMIZING...' : 'RUN OPTIMIZATION'}
- </button>
- </div>
-
- {/* Results Panel */}
- <div>
- <div style={{
- color: '#FF8800',
- fontSize: '12px',
- fontWeight: 'bold',
- marginBottom: '16px',
- borderBottom: '1px solid #FF8800',
- paddingBottom: '8px'
- }}>
- OPTIMIZATION RESULTS
- </div>
-
- {results?.performance_metrics && (
- <>
- {/* Performance Metrics */}
- <div style={{ marginBottom: '24px' }}>
- <div style={{ color: '#00E5FF', fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
- PERFORMANCE METRICS
- </div>
- <div style={{ backgroundColor: '#0F0F0F', padding: '12px', border: '1px solid #333' }}>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', fontSize: '10px' }}>
- <div>
- <div style={{ color: '#787878' }}>Expected Annual Return</div>
- <div style={{ color: '#00D66F', fontSize: '14px', fontWeight: 'bold' }}>
- {(results.performance_metrics.expected_annual_return * 100).toFixed(2)}%
- </div>
- </div>
- <div>
- <div style={{ color: '#787878' }}>Annual Volatility</div>
- <div style={{ color: '#FFD700', fontSize: '14px', fontWeight: 'bold' }}>
- {(results.performance_metrics.annual_volatility * 100).toFixed(2)}%
- </div>
- </div>
- <div style={{ gridColumn: '1 / -1' }}>
- <div style={{ color: '#787878' }}>Sharpe Ratio</div>
- <div style={{ color: '#FF8800', fontSize: '18px', fontWeight: 'bold' }}>
- {results.performance_metrics.sharpe_ratio.toFixed(3)}
- </div>
- </div>
- </div>
- </div>
- </div>
-
- {/* Portfolio Weights */}
- {results.weights && (
- <div style={{ marginBottom: '24px' }}>
- <div style={{ color: '#00E5FF', fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
- OPTIMAL WEIGHTS
- </div>
- <div style={{ backgroundColor: '#0F0F0F', border: '1px solid #333', maxHeight: '300px', overflow: 'auto' }}>
- {Object.entries(results.weights)
- .sort(([, a], [, b]) => b - a)
- .map(([symbol, weight]) => (
- <div
- key={symbol}
- style={{
- padding: '8px 12px',
- borderBottom: '1px solid #1A1A1A',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- fontSize: '10px'
- }}
- >
- <span style={{ color: '#00E5FF', fontWeight: 'bold' }}>{symbol}</span>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <div
- style={{
- width: '100px',
- height: '6px',
- backgroundColor: '#1A1A1A',
- position: 'relative',
- overflow: 'hidden'
- }}
- >
- <div
- style={{
- position: 'absolute',
- left: 0,
- top: 0,
- height: '100%',
- width: `${weight * 100}%`,
- backgroundColor: '#FF8800'
- }}
- />
- </div>
- <span style={{ color: '#FFF', width: '60px', textAlign: 'right' }}>
- {(weight * 100).toFixed(2)}%
- </span>
- </div>
- </div>
- ))}
- </div>
- </div>
- )}
-
- {/* Export Buttons */}
- <div style={{ display: 'flex', gap: '8px' }}>
- <button
- onClick={() => handleExport('json')}
- style={{
- flex: 1,
- padding: '8px',
- backgroundColor: '#00D66F',
- color: '#000',
- border: 'none',
- fontFamily: 'inherit',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- gap: '4px'
- }}
- >
- <Download size={12} />
- EXPORT JSON
- </button>
- <button
- onClick={() => handleExport('csv')}
- style={{
- flex: 1,
- padding: '8px',
- backgroundColor: '#00E5FF',
- color: '#000',
- border: 'none',
- fontFamily: 'inherit',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- gap: '4px'
- }}
- >
- <Download size={12} />
- EXPORT CSV
- </button>
- </div>
- </>
- )}
-
- {!results && !loading && (
- <div style={{
- padding: '48px',
- textAlign: 'center',
- color: '#787878',
- fontSize: '11px',
- backgroundColor: '#0F0F0F',
- border: '1px solid #333'
- }}>
- Configure parameters and click "RUN OPTIMIZATION" to see results
- </div>
- )}
- </div>
- </div>
- )}
-
- {/* EFFICIENT FRONTIER TAB */}
- {activeTab === 'frontier' && (
- <div>
- <button
- onClick={handleGenerateFrontier}
- disabled={loading}
- style={{
- padding: '12px 24px',
- backgroundColor: loading ? '#666' : '#FF8800',
- color: '#000',
- border: 'none',
- fontFamily: 'inherit',
- fontSize: '12px',
- fontWeight: 'bold',
- cursor: loading ? 'not-allowed' : 'pointer',
- marginBottom: '24px'
- }}
- >
- {loading ? 'GENERATING...' : 'GENERATE EFFICIENT FRONTIER'}
- </button>
-
- {results?.efficient_frontier && (
- <div style={{ backgroundColor: '#0F0F0F', padding: '24px', border: '1px solid #333' }}>
- <div style={{ color: '#00E5FF', fontSize: '12px', fontWeight: 'bold', marginBottom: '16px' }}>
- EFFICIENT FRONTIER ({results.efficient_frontier.returns.length} points)
- </div>
- <div style={{ color: '#787878', fontSize: '10px' }}>
- Chart visualization would be rendered here using Recharts or similar
- </div>
- </div>
- )}
- </div>
- )}
-
- {/* BACKTEST TAB */}
- {activeTab === 'backtest' && (
- <div>
- <button
- onClick={handleBacktest}
- disabled={loading}
- style={{
- padding: '12px 24px',
- backgroundColor: loading ? '#666' : '#FF8800',
- color: '#000',
- border: 'none',
- fontFamily: 'inherit',
- fontSize: '12px',
- fontWeight: 'bold',
- cursor: loading ? 'not-allowed' : 'pointer',
- marginBottom: '24px'
- }}
- >
- {loading ? 'RUNNING BACKTEST...' : 'RUN BACKTEST'}
- </button>
-
- {results?.backtest_results && (
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px' }}>
- {[
- { label: 'Annual Return', value: results.backtest_results.annual_return, color: '#00D66F', format: '%' },
- { label: 'Annual Volatility', value: results.backtest_results.annual_volatility, color: '#FFD700', format: '%' },
- { label: 'Sharpe Ratio', value: results.backtest_results.sharpe_ratio, color: '#FF8800', format: '' },
- { label: 'Max Drawdown', value: results.backtest_results.max_drawdown, color: '#FF3B3B', format: '%' },
- { label: 'Calmar Ratio', value: results.backtest_results.calmar_ratio, color: '#00E5FF', format: '' },
- ].map(metric => (
- <div key={metric.label} style={{ backgroundColor: '#0F0F0F', padding: '16px', border: '1px solid #333' }}>
- <div style={{ color: '#787878', fontSize: '9px', marginBottom: '4px' }}>{metric.label}</div>
- <div style={{ color: metric.color, fontSize: '18px', fontWeight: 'bold' }}>
- {metric.format === '%'
- ? `${(metric.value * 100).toFixed(2)}%`
- : metric.value.toFixed(3)
- }
- </div>
- </div>
- ))}
- </div>
- )}
- </div>
- )}
-
- {/* ALLOCATION TAB */}
- {activeTab === 'allocation' && (
- <div>
- <button
- onClick={handleDiscreteAllocation}
- disabled={loading || !results?.weights}
- style={{
- padding: '12px 24px',
- backgroundColor: (loading || !results?.weights) ? '#666' : '#FF8800',
- color: '#000',
- border: 'none',
- fontFamily: 'inherit',
- fontSize: '12px',
- fontWeight: 'bold',
- cursor: (loading || !results?.weights) ? 'not-allowed' : 'pointer',
- marginBottom: '24px'
- }}
- >
- {loading ? 'CALCULATING...' : 'CALCULATE DISCRETE ALLOCATION'}
- </button>
-
- {results?.discrete_allocation && (
- <div>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', marginBottom: '24px' }}>
- <div style={{ backgroundColor: '#0F0F0F', padding: '16px', border: '1px solid #333' }}>
- <div style={{ color: '#787878', fontSize: '9px' }}>Total Value</div>
- <div style={{ color: '#00E5FF', fontSize: '18px', fontWeight: 'bold' }}>
- ${results.discrete_allocation.total_value.toLocaleString()}
- </div>
- </div>
- <div style={{ backgroundColor: '#0F0F0F', padding: '16px', border: '1px solid #333' }}>
- <div style={{ color: '#787878', fontSize: '9px' }}>Allocated</div>
- <div style={{ color: '#00D66F', fontSize: '18px', fontWeight: 'bold' }}>
- ${(results.discrete_allocation.total_value - results.discrete_allocation.leftover_cash).toLocaleString()}
- </div>
- </div>
- <div style={{ backgroundColor: '#0F0F0F', padding: '16px', border: '1px solid #333' }}>
- <div style={{ color: '#787878', fontSize: '9px' }}>Leftover Cash</div>
- <div style={{ color: '#FFD700', fontSize: '18px', fontWeight: 'bold' }}>
- ${results.discrete_allocation.leftover_cash.toLocaleString()}
- </div>
- </div>
- </div>
-
- <div style={{ backgroundColor: '#0F0F0F', padding: '16px', border: '1px solid #333' }}>
- <div style={{ color: '#00E5FF', fontSize: '11px', fontWeight: 'bold', marginBottom: '12px' }}>
- SHARE ALLOCATION
- </div>
- {Object.entries(results.discrete_allocation.allocation).map(([symbol, shares]) => (
- <div
- key={symbol}
- style={{
- padding: '8px 0',
- borderBottom: '1px solid #1A1A1A',
- display: 'flex',
- justifyContent: 'space-between',
- fontSize: '11px'
- }}
- >
- <span style={{ color: '#00E5FF', fontWeight: 'bold' }}>{symbol}</span>
- <span style={{ color: '#FFF' }}>{shares} shares</span>
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
- )}
-
- {/* RISK ANALYSIS TAB */}
- {activeTab === 'risk' && (
- <div style={{
- padding: '24px',
- textAlign: 'center',
- backgroundColor: '#0F0F0F',
- border: '1px solid #333',
- color: '#787878',
- fontSize: '11px'
- }}>
- Risk decomposition and correlation matrix analysis coming soon...
- </div>
- )}
- </div>
- );
-};
-
-export default PortfolioOptimizationTab;
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 a97baeaa1..064b4a8a9 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx
@@ -10,7 +10,8 @@ import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';
import { useTerminalTheme } from '@/contexts/ThemeContext';
import { Briefcase, RefreshCw, Bot, X, ChevronDown } from 'lucide-react';
import { FINCEPT, COMMON_STYLES } from './finceptStyles';
-import agentService from '@/services/agentService';
+import agentService, { buildAgentConfig } from '@/services/agentService';
+import { withTimeout } from '@/services/core/apiUtils';
import { sqliteService, getSetting, getAgentConfigs } from '@/services/core/sqliteService';
import type { AgentConfig } from '@/services/core/sqliteService';
import MarkdownRenderer from '@/components/common/MarkdownRenderer';
@@ -69,6 +70,18 @@ const PortfolioTab: React.FC = () => {
const agentResultCache = useRef<Record<string, string>>({});
const lastPortfolioId = useRef<string | null>(null);
+ // Clear caches when the selected portfolio changes
+ useEffect(() => {
+ const currentId = selectedPortfolio?.id ?? null;
+ if (lastPortfolioId.current !== currentId) {
+ aiResultCache.current = {};
+ agentResultCache.current = {};
+ lastPortfolioId.current = currentId;
+ setAiResult(null);
+ setAgentResult(null);
+ }
+ }, [selectedPortfolio?.id]);
+
// ── Agent Runner state ──
const [agentRunning, setAgentRunning] = useState(false);
const [agentResult, setAgentResult] = useState<string | null>(null);
@@ -100,9 +113,9 @@ const PortfolioTab: React.FC = () => {
setAgentResult(null);
try {
- const agentCfg = JSON.parse(agentCfgRow.config_json || '{}');
+ const savedCfg = JSON.parse(agentCfgRow.config_json || '{}');
- // Build api keys
+ // Build api keys from LLM configs
const llmConfigs = await sqliteService.getLLMConfigs();
const apiKeys: Record<string, string> = {};
for (const cfg of llmConfigs) {
@@ -121,34 +134,56 @@ const PortfolioTab: React.FC = () => {
if (finceptKey) { apiKeys['fincept'] = finceptKey; apiKeys['FINCEPT_API_KEY'] = finceptKey; }
}
- // Build portfolio context to prepend to the agent query
+ // Resolve provider/model — prefer saved config, fall back to active LLM
+ const activeLLM = llmConfigs.find(c => c.is_active) ?? llmConfigs[0] ?? null;
+ const provider = savedCfg.model?.provider ?? activeLLM?.provider ?? 'fincept';
+ const model_id = savedCfg.model?.model_id ?? activeLLM?.model ?? 'fincept-llm';
+
+ if (!activeLLM && !apiKeys['fincept']) {
+ setAgentResult('No LLM configured. Please add a model in Settings → LLM Configuration.');
+ return;
+ }
+
+ // Build proper agent config using the shared builder
+ const agentConfig = buildAgentConfig(
+ provider,
+ model_id,
+ savedCfg.instructions || 'You are a professional portfolio analyst. Analyze the provided portfolio data and give actionable insights.',
+ {
+ tools: savedCfg.tools ?? [],
+ temperature: savedCfg.model?.temperature ?? 0.3,
+ maxTokens: savedCfg.model?.max_tokens ?? 4096,
+ memory: savedCfg.memory,
+ reasoning: savedCfg.reasoning,
+ guardrails: savedCfg.guardrails,
+ }
+ );
+
+ // Build structured portfolio context query
const portfolioHoldings = portfolioSummary.holdings || [];
const holdingsSummary = portfolioHoldings.map((h: any) =>
- h.symbol + ': ' + h.quantity + ' units @ $' + (h.current_price || 0).toFixed(2) +
- ' | Weight: ' + (h.weight || 0).toFixed(1) + '%'
+ `${h.symbol}: ${h.quantity} units @ $${(h.current_price || 0).toFixed(2)} | PnL: ${(h.unrealized_pnl_percent || 0).toFixed(2)}% | Weight: ${(h.weight || 0).toFixed(1)}%`
).join('\n');
const portfolioContext = [
- '=== PORTFOLIO CONTEXT ===',
- 'Portfolio: ' + (portfolioSummary.portfolio?.name || 'Unknown'),
- 'NAV: ' + currency + ' ' + portfolioSummary.total_market_value.toFixed(2),
- 'Holdings (' + portfolioHoldings.length + '):',
+ `Portfolio: ${portfolioSummary.portfolio?.name || 'Unknown'} | NAV: ${currency} ${portfolioSummary.total_market_value.toFixed(2)}`,
+ `Total P&L: ${portfolioSummary.total_unrealized_pnl_percent?.toFixed(2) ?? 'N/A'}% | Day Change: ${portfolioSummary.total_day_change_percent?.toFixed(2) ?? 'N/A'}%`,
+ `Holdings (${portfolioHoldings.length}):`,
holdingsSummary,
- '========================',
'',
- 'Please analyze the portfolio above and provide actionable insights.',
+ 'Please analyze this portfolio and provide actionable insights with specific recommendations.',
].join('\n');
- const result = await agentService.runAgent(
- portfolioContext,
- { ...agentCfg, markdown: true },
- apiKeys
+ const result = await withTimeout(
+ agentService.runAgent(portfolioContext, agentConfig, apiKeys),
+ 180000,
+ 'Agent timed out. Check your LLM API key and network connection.'
);
const agentText = result.response || result.error || 'No response returned.';
agentResultCache.current[selectedAgentId] = agentText;
setAgentResult(agentText);
} catch (err: any) {
- setAgentResult('Agent run failed: ' + (err?.message || 'Unknown error'));
+ setAgentResult(`Agent run failed: ${err?.message || 'Unknown error'}`);
} finally {
setAgentRunning(false);
}
@@ -354,7 +389,7 @@ const PortfolioTab: React.FC = () => {
</div>
) : detailView ? (
/* ═══ FULL-SCREEN DETAIL VIEW ═══ */
- <div style={{ flex: 1, minWidth: 0, overflow: 'hidden' }}>
+ <div style={{ flex: 1, minWidth: 0, overflow: 'auto' }}>
<DetailViewWrapper
view={detailView}
onBack={() => setDetailView(null)}
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/components/DetailViewWrapper.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/components/DetailViewWrapper.tsx
index 6482675f9..c34af1274 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/components/DetailViewWrapper.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/components/DetailViewWrapper.tsx
@@ -90,7 +90,7 @@ const DetailViewWrapper: React.FC<DetailViewWrapperProps> = ({
</div>
{/* Content — full height remaining */}
- <div style={{ flex: 1, overflow: 'hidden' }}>
+ <div style={{ flex: 1, overflow: 'visible' }}>
{view === 'analytics-sectors' && (
<AnalyticsSectorsPanel portfolioSummary={portfolioSummary} currency={currency} />
)}
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/hooks/usePortfolioOperations.ts b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/hooks/usePortfolioOperations.ts
index 01e3edfa2..1f12ad33c 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/hooks/usePortfolioOperations.ts
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/hooks/usePortfolioOperations.ts
@@ -107,6 +107,11 @@ export const usePortfolioOperations = () => {
setPortfolioSummary(cachedSummary.data);
}
} else {
+ // No cache — clear stale data and show spinner
+ if (loadingPortfolioIdRef.current === portfolioId) {
+ setPortfolioSummary(null);
+ setTransactions([]);
+ }
// Fetch fresh summary
const summary = await portfolioService.getPortfolioSummary(portfolioId);
@@ -329,11 +334,17 @@ export const usePortfolioOperations = () => {
// Initialize service and load portfolios, restoring last selection
useEffect(() => {
+ let cancelled = false;
+
const initService = async () => {
setLoading(true);
try {
await portfolioService.initialize();
+ if (cancelled) return;
+
const result = await portfolioService.getPortfolios();
+ if (cancelled) return;
+
setPortfolios(result);
if (result.length > 0) {
@@ -358,10 +369,16 @@ export const usePortfolioOperations = () => {
} catch (error) {
console.error('[usePortfolioOperations] Initialization error:', error);
} finally {
- setLoading(false);
+ if (!cancelled) {
+ setLoading(false);
+ }
}
};
initService();
+
+ return () => {
+ cancelled = true;
+ };
}, [setSelectedPortfolio]);
// Auto-refresh portfolio data only when tab is visible
@@ -408,14 +425,10 @@ export const usePortfolioOperations = () => {
// Load portfolio summary when selection changes
useEffect(() => {
if (selectedPortfolio) {
- // Clear previous portfolio data immediately when switching
- setPortfolioSummary(null);
- setTransactions([]);
-
// Update the ref to track which portfolio we're loading
loadingPortfolioIdRef.current = selectedPortfolio.id;
- // Load new portfolio data
+ // Load new portfolio data (cache hit = instant, no flicker)
loadPortfolioSummary(selectedPortfolio.id);
} else {
// Clear data when no portfolio is selected
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/QuantStatsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/QuantStatsView.tsx
index 04f7536a0..0ba343646 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/QuantStatsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/QuantStatsView.tsx
@@ -86,6 +86,7 @@ const QuantStatsView: React.FC<QuantStatsViewProps> = ({ portfolioSummary }) =>
const [error, setError] = useState<string | null>(null);
const [benchmark, setBenchmark] = useState('SPY');
const [period, setPeriod] = useState('1y');
+ const [numSims, setNumSims] = useState(1000);
const [activeSection, setActiveSection] = useState<'metrics' | 'returns' | 'drawdown' | 'rolling' | 'montecarlo'>('metrics');
// ── FFN + Fortitudo state ──
@@ -119,8 +120,8 @@ const QuantStatsView: React.FC<QuantStatsViewProps> = ({ portfolioSummary }) =>
const validHoldings = portfolioSummary.holdings.filter(h => h.symbol && h.quantity > 0);
const symbols = validHoldings.map(h => h.symbol).sort().join(',');
const weights = validHoldings.map(h => Math.round(h.weight * 10)).join(',');
- return `quantstats:${symbols}:${weights}:${benchmark}:${period}`;
- }, [portfolioSummary.holdings, benchmark, period]);
+ return `quantstats:${symbols}:${weights}:${benchmark}:${period}:${numSims}`;
+ }, [portfolioSummary.holdings, benchmark, period, numSims]);
const fortitudoCacheKey = useMemo(() => {
const validHoldings = portfolioSummary.holdings.filter(h => h.symbol && h.quantity > 0);
@@ -152,11 +153,11 @@ const QuantStatsView: React.FC<QuantStatsViewProps> = ({ portfolioSummary }) =>
return;
}
- console.log('[QuantStats] Running analysis with tickers:', tickers, 'benchmark:', benchmark, 'period:', period);
+ console.log('[QuantStats] Running analysis with tickers:', tickers, 'benchmark:', benchmark, 'period:', period, 'sims:', numSims);
setLoading(true);
setError(null);
try {
- const data = await quantstatsService.getFullReport(tickers, benchmark, period);
+ const data = await quantstatsService.getFullReport(tickers, benchmark, period, undefined, numSims);
setReport(data);
cacheService.set(cacheKey, data, 'api-response', '1h');
} catch (e) {
@@ -165,7 +166,7 @@ const QuantStatsView: React.FC<QuantStatsViewProps> = ({ portfolioSummary }) =>
} finally {
setLoading(false);
}
- }, [buildTickersWeights, benchmark, period, cacheKey]);
+ }, [buildTickersWeights, benchmark, period, numSims, cacheKey]);
const generateHtmlReport = useCallback(async () => {
const tickers = buildTickersWeights();
@@ -290,10 +291,10 @@ const QuantStatsView: React.FC<QuantStatsViewProps> = ({ portfolioSummary }) =>
return (
<div style={{
- height: '100%',
display: 'flex',
flexDirection: 'column',
backgroundColor: FINCEPT.DARK_BG,
+ minHeight: '100%',
}}>
{/* Terminal-style Header */}
<div style={{
@@ -385,6 +386,30 @@ const QuantStatsView: React.FC<QuantStatsViewProps> = ({ portfolioSummary }) =>
))}
</div>
+ {/* Sims selector */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <span style={{ color: FINCEPT.WHITE, fontSize: '10px', letterSpacing: '0.5px', fontFamily: 'monospace', opacity: 0.7 }}>SIMS:</span>
+ <div style={{ display: 'flex', gap: '2px' }}>
+ {([500, 1000, 2000, 5000] as const).map(s => (
+ <button
+ key={s}
+ onClick={() => setNumSims(s)}
+ style={{
+ padding: '6px 8px',
+ backgroundColor: numSims === s ? FINCEPT.CYAN : FINCEPT.DARK_BG,
+ border: `1px solid ${numSims === s ? FINCEPT.CYAN : FINCEPT.BORDER}`,
+ color: numSims === s ? '#000000' : FINCEPT.WHITE,
+ fontSize: '10px', fontWeight: 700, fontFamily: 'monospace',
+ cursor: 'pointer', letterSpacing: '0.5px',
+ opacity: numSims === s ? 1 : 0.7,
+ }}
+ >
+ {s >= 1000 ? `${s / 1000}K` : s}
+ </button>
+ ))}
+ </div>
+ </div>
+
{/* Run Analysis button */}
<button
onClick={runAnalysis}
@@ -485,8 +510,6 @@ const QuantStatsView: React.FC<QuantStatsViewProps> = ({ portfolioSummary }) =>
{/* Main Content Area */}
<div style={{
- flex: 1,
- overflow: 'auto',
padding: '16px',
}}>
diff --git a/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx b/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
index 6c5bea6ee..b634f9354 100644
--- a/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
@@ -159,6 +159,7 @@ const ProfileTab: React.FC = () => {
const [state, dispatch] = useReducer(profileReducer, initialState);
const mountedRef = useRef(true);
const fetchIdRef = useRef(0);
+ const refreshIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
// Cleanup on unmount
useEffect(() => {
@@ -178,7 +179,7 @@ const ProfileTab: React.FC = () => {
try {
if (state.activeSection === 'usage') {
const result = session.user_type === 'guest'
- ? await withTimeout(UserApiService.getGuestUsage(session.api_key), API_TIMEOUT_MS, 'Usage fetch timeout')
+ ? { success: true, data: { requests_today: session.requests_today || 0, credit_balance: session.credit_balance || 0, expires_at: session.expires_at }, error: undefined, status_code: 200 }
: await withTimeout(UserApiService.getUserUsage(session.api_key), API_TIMEOUT_MS, 'Usage fetch timeout');
if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;
@@ -222,6 +223,28 @@ const ProfileTab: React.FC = () => {
}
}, [state.activeSection, state.status, session]);
+ // Refresh credits/usage from session on mount and every 30 seconds
+ const refreshCreditsAndUsage = useCallback(async () => {
+ if (!mountedRef.current || !session?.api_key) return;
+ await refreshUserData();
+ // If on usage section, also re-fetch usage data
+ if (state.activeSection === 'usage' && state.status !== 'loading') {
+ fetchSectionData();
+ }
+ }, [refreshUserData, session?.api_key, state.activeSection, state.status, fetchSectionData]);
+
+ // On mount: immediate refresh + start 30s interval
+ useEffect(() => {
+ refreshCreditsAndUsage();
+ refreshIntervalRef.current = setInterval(refreshCreditsAndUsage, 30000);
+ return () => {
+ if (refreshIntervalRef.current) {
+ clearInterval(refreshIntervalRef.current);
+ refreshIntervalRef.current = null;
+ }
+ };
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+
useEffect(() => {
fetchSectionData();
}, [state.activeSection]); // Only re-fetch when section changes
@@ -455,7 +478,7 @@ const OverviewSection: React.FC<{ session: any; onLogout: () => void; isLoggingO
<DataRow label="PLAN" value={accountType.toUpperCase()} valueColor={F.ORANGE} />
{session?.user_type === 'guest' && (
<>
- <DataRow label="DAILY LIMIT" value={session?.daily_limit?.toString() || '0'} />
+ <DataRow label="CREDITS" value={session?.credit_balance?.toString() || '0'} />
<DataRow label="REQUESTS TODAY" value={session?.requests_today?.toString() || '0'} />
</>
)}
@@ -475,10 +498,10 @@ const OverviewSection: React.FC<{ session: any; onLogout: () => void; isLoggingO
// ─── Usage Section ────────────────────────────────────────────────────────────
const UsageSection: React.FC<{ usageData: UsageData | null; loading: boolean; session: any }> = ({ usageData, loading, session }) => {
- const credits = session?.user_info?.credit_balance || 0;
- const dailyLimit = session?.daily_limit || 0;
+ const credits = session?.user_type === 'guest'
+ ? (session?.credit_balance || 0)
+ : (session?.user_info?.credit_balance || 0);
const requestsToday = session?.requests_today || 0;
- const usagePercent = dailyLimit > 0 ? (requestsToday / dailyLimit) * 100 : 0;
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
@@ -492,22 +515,11 @@ const UsageSection: React.FC<{ usageData: UsageData | null; loading: boolean; se
</Panel>
{session?.user_type === 'guest' && (
- <Panel title="DAILY USAGE LIMIT" icon={<Activity size={14} />}>
+ <Panel title="GUEST SESSION USAGE" icon={<Activity size={14} />}>
<div style={{ padding: '12px 0' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px', fontSize: '10px' }}>
<span style={{ color: F.GRAY, fontWeight: 700, fontSize: '9px', letterSpacing: '0.5px' }}>REQUESTS TODAY</span>
- <span style={{ color: F.WHITE, fontWeight: 700, fontFamily: FONT }}>
- {requestsToday} / {dailyLimit}
- </span>
- </div>
- <div style={{ height: '6px', backgroundColor: F.HEADER_BG, borderRadius: '2px', position: 'relative' }}>
- <div style={{
- height: '100%',
- width: `${Math.min(usagePercent, 100)}%`,
- backgroundColor: usagePercent >= 90 ? F.RED : usagePercent >= 70 ? F.YELLOW : F.GREEN,
- borderRadius: '2px',
- transition: 'width 0.3s',
- }} />
+ <span style={{ color: F.WHITE, fontWeight: 700, fontFamily: FONT }}>{requestsToday}</span>
</div>
</div>
</Panel>
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-analysis/quantlibAnalysisApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-analysis/quantlibAnalysisApi.ts
index cd79acedc..b4839303b 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-analysis/quantlibAnalysisApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-analysis/quantlibAnalysisApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-analysis/quantlibAnalysisApi.ts
// 122 endpoints — fundamentals(11), ratios(77), valuation(30), industry(4)
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setAnalysisApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-core/quantlibCoreApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-core/quantlibCoreApi.ts
index 1e42471c2..0fd4bebcc 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-core/quantlibCoreApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-core/quantlibCoreApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-core/quantlibCoreApi.ts
// API service for QuantLib Core endpoints
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setQuantLibApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-curves/quantlibCurvesApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-curves/quantlibCurvesApi.ts
index 39395baa2..0e3f0226c 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-curves/quantlibCurvesApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-curves/quantlibCurvesApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-curves/quantlibCurvesApi.ts
// 31 endpoints — yield curves, interpolation, shifts, Nelson-Siegel, inflation, multicurve
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setCurvesApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-economics/quantlibEconomicsApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-economics/quantlibEconomicsApi.ts
index 491697378..f61587901 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-economics/quantlibEconomicsApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-economics/quantlibEconomicsApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-economics/quantlibEconomicsApi.ts
// 25 endpoints — equilibrium, game theory, auctions, utility theory
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setEconomicsApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-instruments/quantlibInstrumentsApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-instruments/quantlibInstrumentsApi.ts
index 19196da7e..ce933fce8 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-instruments/quantlibInstrumentsApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-instruments/quantlibInstrumentsApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-instruments/quantlibInstrumentsApi.ts
// 26 endpoints — bonds, swaps, FRA, money market, OIS, equity, commodity, FX, CDS, futures
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setInstrumentsApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-ml/quantlibMlApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-ml/quantlibMlApi.ts
index c38ec3e5e..7f9bb96a3 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-ml/quantlibMlApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-ml/quantlibMlApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-ml/quantlibMlApi.ts
// API service for QuantLib ML endpoints (48 endpoints)
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setMlApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-models/quantlibModelsApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-models/quantlibModelsApi.ts
index 7f04b1d34..a2c11ac5c 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-models/quantlibModelsApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-models/quantlibModelsApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-models/quantlibModelsApi.ts
// API service for QuantLib Models endpoints
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setModelsApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-numerical/quantlibNumericalApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-numerical/quantlibNumericalApi.ts
index 231874fd2..b6842bafd 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-numerical/quantlibNumericalApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-numerical/quantlibNumericalApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-numerical/quantlibNumericalApi.ts
// 28 endpoints — differentiation, FFT, integration, interpolation, linalg, ODE, roots, optimize, least squares
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setNumericalApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-physics/quantlibPhysicsApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-physics/quantlibPhysicsApi.ts
index eaa928cf8..45a9f6d8e 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-physics/quantlibPhysicsApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-physics/quantlibPhysicsApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-physics/quantlibPhysicsApi.ts
// API service for QuantLib Physics endpoints (24 endpoints)
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setPhysicsApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-portfolio/quantlibPortfolioApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-portfolio/quantlibPortfolioApi.ts
index eaf55da52..42df7e354 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-portfolio/quantlibPortfolioApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-portfolio/quantlibPortfolioApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-portfolio/quantlibPortfolioApi.ts
// API service for QuantLib Portfolio endpoints (15 endpoints)
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setPortfolioApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-pricing/quantlibPricingApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-pricing/quantlibPricingApi.ts
index a25159780..5c6cab1f7 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-pricing/quantlibPricingApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-pricing/quantlibPricingApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-pricing/quantlibPricingApi.ts
// 29 endpoints — Black-Scholes, Black76, Bachelier, Kirk, Binomial, Monte Carlo, PDE
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setPricingApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-regulatory/quantlibRegulatoryApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-regulatory/quantlibRegulatoryApi.ts
index 3f38a8dc0..4acfc75ff 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-regulatory/quantlibRegulatoryApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-regulatory/quantlibRegulatoryApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-regulatory/quantlibRegulatoryApi.ts
// API service for QuantLib Regulatory endpoints
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setRegulatoryApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-risk/quantlibRiskApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-risk/quantlibRiskApi.ts
index 28f268443..e96f882e3 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-risk/quantlibRiskApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-risk/quantlibRiskApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-risk/quantlibRiskApi.ts
// 25 endpoints — VaR, stress testing, EVT, XVA, sensitivities, tail risk, portfolio risk
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setRiskModApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-scheduling/quantlibSchedulingApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-scheduling/quantlibSchedulingApi.ts
index f30629e96..5c67c70f4 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-scheduling/quantlibSchedulingApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-scheduling/quantlibSchedulingApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-scheduling/quantlibSchedulingApi.ts
// API service for QuantLib Scheduling endpoints (14 endpoints)
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setSchedulingApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-solver/quantlibSolverApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-solver/quantlibSolverApi.ts
index d6cd3d020..f29829eb9 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-solver/quantlibSolverApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-solver/quantlibSolverApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-solver/quantlibSolverApi.ts
// 25 endpoints — bond analytics, rates, implied vol, spreads, basis, carry, cashflows
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setSolverApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-statistics/quantlibStatisticsApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-statistics/quantlibStatisticsApi.ts
index 88180d4b5..7c0475f3c 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-statistics/quantlibStatisticsApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-statistics/quantlibStatisticsApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-statistics/quantlibStatisticsApi.ts
// API service for QuantLib Statistics endpoints (52 endpoints)
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setStatisticsApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-stochastic/quantlibStochasticApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-stochastic/quantlibStochasticApi.ts
index 62d4b236f..f036a90bf 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-stochastic/quantlibStochasticApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-stochastic/quantlibStochasticApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-stochastic/quantlibStochasticApi.ts
// API service for QuantLib Stochastic endpoints (36 endpoints)
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setStochasticApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/quantlib-volatility/quantlibVolatilityApi.ts b/fincept-terminal-desktop/src/components/tabs/quantlib-volatility/quantlibVolatilityApi.ts
index 748a42b4e..6a2478471 100644
--- a/fincept-terminal-desktop/src/components/tabs/quantlib-volatility/quantlibVolatilityApi.ts
+++ b/fincept-terminal-desktop/src/components/tabs/quantlib-volatility/quantlibVolatilityApi.ts
@@ -1,7 +1,7 @@
// File: src/components/tabs/quantlib-volatility/quantlibVolatilityApi.ts
// API service for QuantLib Volatility endpoints
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
let _apiKey: string | null = null;
export function setVolatilityApiKey(key: string | null) { _apiKey = key; }
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/hooks/useSettingsData.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/hooks/useSettingsData.ts
index be102414c..fbd08f5c4 100644
--- a/fincept-terminal-desktop/src/components/tabs/settings-tab/hooks/useSettingsData.ts
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/hooks/useSettingsData.ts
@@ -66,7 +66,7 @@ export function useSettingsData() {
const finceptConfig = {
provider: 'fincept',
api_key: userApiKey,
- base_url: 'https://finceptbackend.share.zrok.io/research/llm',
+ base_url: 'https://api.fincept.in/research/llm',
model: 'fincept-llm',
is_active: true,
created_at: now,
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
index 730707f8e..4203e6ae6 100644
--- 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
@@ -156,6 +156,7 @@ export function LLMConfigSection({
newModelConfig={state.newModelConfig}
setNewModelConfig={state.setNewModelConfig}
newModelConfigModels={state.newModelConfigModels}
+ availableProviders={state.availableProviders}
useManualEntry={state.useManualEntryAddModel}
setUseManualEntry={state.setUseManualEntryAddModel}
showApiKeys={state.showApiKeys}
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
index cdfba73a9..a3c1fbbad 100644
--- 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
@@ -2,7 +2,6 @@ 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,
@@ -10,6 +9,7 @@ export function AddModelForm({
newModelConfig,
setNewModelConfig,
newModelConfigModels,
+ availableProviders,
useManualEntry,
setUseManualEntry,
onSubmit,
@@ -54,7 +54,7 @@ export function AddModelForm({
fontSize: '12px'
}}
>
- {PROVIDER_OPTIONS.map(option => (
+ {availableProviders.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
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
index 53eb61744..83dd41dbd 100644
--- 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
@@ -17,6 +17,7 @@ export function ModelLibraryPanel({
newModelConfig,
setNewModelConfig,
newModelConfigModels,
+ availableProviders,
useManualEntry,
setUseManualEntry,
showApiKeys,
@@ -86,10 +87,10 @@ export function ModelLibraryPanel({
newModelConfig={newModelConfig}
setNewModelConfig={setNewModelConfig}
newModelConfigModels={newModelConfigModels}
+ availableProviders={availableProviders}
useManualEntry={useManualEntry}
setUseManualEntry={setUseManualEntry}
onSubmit={handleAddModelConfig}
- onCancel={() => setShowAddModel(false)}
/>
)}
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
index 676886970..ccba2e01f 100644
--- 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
@@ -26,33 +26,6 @@ export const LLM_PROVIDERS = {
// 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,
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
index 05d419b28..9bb5bd217 100644
--- 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
@@ -47,6 +47,16 @@ export function useLLMConfigState({
const [showAddModel, setShowAddModel] = useState(false);
const [newModelConfig, setNewModelConfig] = useState<NewModelConfig>({ ...DEFAULT_NEW_MODEL_CONFIG });
const [newModelConfigModels, setNewModelConfigModels] = useState<ModelInfo[]>([]);
+ const [availableProviders, setAvailableProviders] = useState<Array<{ value: string; label: string }>>([]);
+
+ // Load dynamic providers from LiteLLM data
+ useEffect(() => {
+ LLMModelsService.getProviders().then(providers => {
+ if (providers.length > 0) {
+ setAvailableProviders(providers.map(p => ({ value: p.id, label: LLMModelsService.getProviderDisplayName(p.id) })));
+ }
+ }).catch(() => {});
+ }, []);
// API key visibility state
const [showApiKeys, setShowApiKeys] = useState<Record<string, boolean>>({});
@@ -267,6 +277,7 @@ export function useLLMConfigState({
setNewModelConfig,
newModelConfigModels,
resetNewModelConfig,
+ availableProviders,
// API key visibility
showApiKeys,
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
index a0b657621..cbfbdeffa 100644
--- 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
@@ -78,6 +78,7 @@ export interface ModelLibraryPanelProps {
newModelConfig: NewModelConfig;
setNewModelConfig: React.Dispatch<React.SetStateAction<NewModelConfig>>;
newModelConfigModels: ModelInfo[];
+ availableProviders: Array<{ value: string; label: string }>;
useManualEntry: boolean;
setUseManualEntry: (value: boolean) => void;
showApiKeys: Record<string, boolean>;
@@ -90,10 +91,10 @@ export interface AddModelFormProps {
newModelConfig: NewModelConfig;
setNewModelConfig: React.Dispatch<React.SetStateAction<NewModelConfig>>;
newModelConfigModels: ModelInfo[];
+ availableProviders: Array<{ value: string; label: string }>;
useManualEntry: boolean;
setUseManualEntry: (value: boolean) => void;
onSubmit: () => void;
- onCancel: () => void;
}
export interface ModelListItemProps {
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/AdvancedFeaturesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/AdvancedFeaturesPanel.tsx
deleted file mode 100644
index 7e6c68ef6..000000000
--- a/fincept-terminal-desktop/src/components/tabs/trading/AdvancedFeaturesPanel.tsx
+++ /dev/null
@@ -1,270 +0,0 @@
-// File: src/components/tabs/trading/AdvancedFeaturesPanel.tsx
-// Advanced trading features panel with leverage, margin mode, and broker-specific controls
-
-import React, { useState, useEffect, useCallback } from 'react';
-import { useBrokerContext } from '../../../contexts/BrokerContext';
-import { Sliders, ArrowUpDown, Settings, Zap, Loader } from 'lucide-react';
-
-const COLORS = {
- ORANGE: '#ea580c',
- WHITE: '#ffffff',
- GREEN: '#10b981',
- RED: '#dc2626',
- GRAY: '#525252',
- DARK_BG: '#0d0d0d',
- PANEL_BG: '#1a1a1a',
-};
-
-export function AdvancedFeaturesPanel() {
- const {
- activeBroker,
- activeBrokerMetadata,
- activeAdapter,
- supports,
- tradingMode,
- } = useBrokerContext();
-
- const [leverage, setLeverage] = useState(1);
- const [marginMode, setMarginMode] = useState<'cross' | 'isolated'>('cross');
- const [isLoading, setIsLoading] = useState(false);
- const [isFetching, setIsFetching] = useState(false);
-
- const { ORANGE, WHITE, GREEN, GRAY, PANEL_BG, DARK_BG } = COLORS;
-
- const canSetLeverage = supports?.canSetLeverage() || false;
- const canTransfer = supports?.canTransfer() || false;
- const hasVaults = supports?.hasVaults() || false;
- const hasSubaccounts = supports?.hasSubaccounts() || false;
- const maxLeverage = activeBrokerMetadata?.advancedFeatures?.maxLeverage || 100;
-
- const fetchCurrentSettings = useCallback(async () => {
- if (!activeAdapter || !canSetLeverage) return;
-
- setIsFetching(true);
- try {
- if ('fetchLeverage' in activeAdapter && typeof (activeAdapter as any).fetchLeverage === 'function') {
- const leverageData = await (activeAdapter as any).fetchLeverage();
- if (leverageData?.leverage) {
- setLeverage(leverageData.leverage);
- } else if (leverageData?.longLeverage) {
- setLeverage(leverageData.longLeverage);
- }
- if (leverageData?.marginMode) {
- setMarginMode(leverageData.marginMode);
- }
- }
-
- if ('fetchMarginMode' in activeAdapter && typeof (activeAdapter as any).fetchMarginMode === 'function') {
- const modeData = await (activeAdapter as any).fetchMarginMode();
- if (modeData?.marginMode) {
- setMarginMode(modeData.marginMode);
- }
- }
- } catch (err) {
- console.warn('[AdvancedFeaturesPanel] Failed to fetch current settings:', err);
- } finally {
- setIsFetching(false);
- }
- }, [activeAdapter, canSetLeverage]);
-
- useEffect(() => {
- fetchCurrentSettings();
- }, [fetchCurrentSettings, activeBroker]);
-
- // Handle leverage change
- const handleLeverageChange = async (newLeverage: number) => {
- if (!activeAdapter || !canSetLeverage) return;
-
- setLeverage(newLeverage);
-
- if (tradingMode === 'live') {
- try {
- setIsLoading(true);
- if ('setLeverage' in activeAdapter) {
- await (activeAdapter as any).setLeverage('', newLeverage);
- }
- } catch (error) {
- console.error('Failed to set leverage:', error);
- } finally {
- setIsLoading(false);
- }
- }
- };
-
- // Handle margin mode change
- const handleMarginModeChange = async (mode: 'cross' | 'isolated') => {
- if (!activeAdapter) return;
-
- setMarginMode(mode);
-
- if (tradingMode === 'live') {
- try {
- setIsLoading(true);
- if ('setMarginMode' in activeAdapter) {
- await (activeAdapter as any).setMarginMode('', mode);
- }
- } catch (error) {
- console.error('Failed to set margin mode:', error);
- } finally {
- setIsLoading(false);
- }
- }
- };
-
- // Don't render if no advanced features
- if (!canSetLeverage && !canTransfer && !hasVaults && !hasSubaccounts) {
- return null;
- }
-
- return (
- <div style={{
- backgroundColor: PANEL_BG,
- borderBottom: `1px solid ${GRAY}`,
- padding: '8px 12px',
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flexWrap: 'wrap' }}>
- {/* Header */}
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
- <Settings size={12} style={{ color: ORANGE }} />
- <span style={{ fontSize: '10px', color: GRAY, fontWeight: 'bold', textTransform: 'uppercase' }}>
- Advanced:
- </span>
- </div>
-
- {/* Leverage Control */}
- {canSetLeverage && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Sliders size={12} style={{ color: GRAY }} />
- <span style={{ fontSize: '10px', color: GRAY }}>Leverage:</span>
- {isFetching ? (
- <Loader size={12} style={{ color: ORANGE, animation: 'spin 1s linear infinite' }} />
- ) : (
- <>
- <input
- type="range"
- min="1"
- max={maxLeverage}
- value={leverage}
- onChange={(e) => handleLeverageChange(Number(e.target.value))}
- disabled={isLoading}
- style={{
- width: '100px',
- height: '4px',
- accentColor: ORANGE,
- cursor: isLoading ? 'not-allowed' : 'pointer',
- }}
- />
- <span style={{
- fontSize: '11px',
- fontWeight: 'bold',
- color: leverage > 1 ? ORANGE : WHITE,
- minWidth: '35px',
- textAlign: 'right',
- }}>
- {leverage}x
- </span>
- </>
- )}
- </div>
- )}
-
- {/* Margin Mode */}
- {canSetLeverage && !isFetching && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
- <ArrowUpDown size={12} style={{ color: GRAY }} />
- <span style={{ fontSize: '10px', color: GRAY }}>Margin:</span>
- <div style={{ display: 'flex', gap: '4px', backgroundColor: DARK_BG, padding: '2px', borderRadius: '2px' }}>
- <button
- onClick={() => handleMarginModeChange('cross')}
- disabled={isLoading}
- style={{
- padding: '3px 8px',
- fontSize: '9px',
- fontWeight: 'bold',
- backgroundColor: marginMode === 'cross' ? ORANGE : 'transparent',
- color: marginMode === 'cross' ? '#000' : GRAY,
- border: 'none',
- cursor: isLoading ? 'not-allowed' : 'pointer',
- borderRadius: '2px',
- textTransform: 'uppercase',
- }}
- >
- Cross
- </button>
- <button
- onClick={() => handleMarginModeChange('isolated')}
- disabled={isLoading}
- style={{
- padding: '3px 8px',
- fontSize: '9px',
- fontWeight: 'bold',
- backgroundColor: marginMode === 'isolated' ? ORANGE : 'transparent',
- color: marginMode === 'isolated' ? '#000' : GRAY,
- border: 'none',
- cursor: isLoading ? 'not-allowed' : 'pointer',
- borderRadius: '2px',
- textTransform: 'uppercase',
- }}
- >
- Isolated
- </button>
- </div>
- </div>
- )}
-
- {/* HyperLiquid Specific Features */}
- {activeBroker === 'hyperliquid' && (
- <>
- {hasVaults && (
- <div style={{
- padding: '3px 8px',
- fontSize: '9px',
- fontWeight: 'bold',
- backgroundColor: '#1a1a1a',
- color: ORANGE,
- border: `1px solid ${ORANGE}40`,
- borderRadius: '2px',
- textTransform: 'uppercase',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- }}>
- <Zap size={10} />
- Vaults Available
- </div>
- )}
- {hasSubaccounts && (
- <div style={{
- padding: '3px 8px',
- fontSize: '9px',
- fontWeight: 'bold',
- backgroundColor: '#1a1a1a',
- color: GREEN,
- border: `1px solid ${GREEN}40`,
- borderRadius: '2px',
- textTransform: 'uppercase',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- }}>
- Subaccounts
- </div>
- )}
- </>
- )}
-
- {/* Trading Mode Warning */}
- {tradingMode === 'paper' && canSetLeverage && (
- <span style={{
- fontSize: '9px',
- color: '#666',
- fontStyle: 'italic',
- marginLeft: 'auto',
- }}>
- Paper mode - changes apply to virtual trading only
- </span>
- )}
- </div>
- </div>
- );
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AIAgentsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AIAgentsPanel.tsx
index 9f8ff3cea..827083bdf 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AIAgentsPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AIAgentsPanel.tsx
@@ -60,7 +60,7 @@ export function AIAgentsPanel({ selectedSymbol, portfolioData }: AIAgentsPanelPr
const [error, setError] = useState<string | null>(null);
// Quick Actions State
- const [selectedModel, setSelectedModel] = useState('openai:gpt-4o-mini');
+ const [selectedModel, setSelectedModel] = useState('');
const [analysisType, setAnalysisType] = useState<'quick' | 'comprehensive' | 'deep'>('comprehensive');
const [strategy, setStrategy] = useState<'momentum' | 'breakout' | 'reversal' | 'trend_following'>('momentum');
const [hasConfiguredKeys, setHasConfiguredKeys] = useState(false);
@@ -497,11 +497,7 @@ function QuickActionsView({
onStartCompetition,
onExecuteTrade
}: QuickActionsViewProps) {
- const models = availableModels.length > 0 ? availableModels : [
- { value: 'openai:gpt-4o-mini', label: 'GPT-4o Mini (Configure in Settings)' },
- { value: 'anthropic:claude-sonnet-4', label: 'Claude Sonnet 4 (Configure in Settings)' },
- { value: 'google:gemini-2.0-flash-exp', label: 'Gemini 2.0 Flash (Configure in Settings)' },
- ];
+ const models = availableModels;
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AgentConfigurationUI.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AgentConfigurationUI.tsx
index cef134e13..e6e9c26b3 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AgentConfigurationUI.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AgentConfigurationUI.tsx
@@ -5,7 +5,7 @@
* Includes all Alpha Arena features: auto-trading, TP/SL, confidence, safety limits.
*/
-import React, { useState } from 'react';
+import React, { useState, useEffect } from 'react';
import {
Bot, Brain, Shield, Target, Zap, Settings, AlertTriangle,
Clock, TrendingUp, Activity, BarChart3, Sliders, Play, Pause,
@@ -40,9 +40,37 @@ export function AgentConfigurationUI({ onAgentCreated }: AgentConfigUIProps) {
const [description, setDescription] = useState('');
// LLM Config
- const [provider, setProvider] = useState('openai');
- const [model, setModel] = useState('gpt-4o-mini');
+ const [provider, setProvider] = useState('');
+ const [model, setModel] = useState('');
const [temperature, setTemperature] = useState(0.7);
+ const [availableProviders, setAvailableProviders] = useState<Array<{ value: string; label: string }>>([]);
+
+ useEffect(() => {
+ const loadLLMConfig = async () => {
+ try {
+ const { sqliteService } = await import('../../../../services/core/sqliteService');
+ const [activeConfig, allConfigs] = await Promise.all([
+ sqliteService.getActiveLLMConfig(),
+ sqliteService.getLLMConfigs()
+ ]);
+ const configured = allConfigs.filter(c => c.api_key && c.api_key.trim().length > 0 || c.provider === 'ollama' || c.provider === 'fincept');
+ setAvailableProviders(configured.map(c => ({ value: c.provider, label: c.provider.charAt(0).toUpperCase() + c.provider.slice(1) })));
+ if (activeConfig) {
+ setProvider(activeConfig.provider);
+ setModel(activeConfig.model);
+ setTemperature((activeConfig as any).temperature ?? 0.7);
+ } else if (configured.length > 0) {
+ setProvider(configured[0].provider);
+ setModel(configured[0].model);
+ }
+ } catch (err) {
+ console.error('Failed to load LLM config:', err);
+ }
+ };
+ loadLLMConfig();
+ window.addEventListener('llm-config-changed', loadLLMConfig);
+ return () => window.removeEventListener('llm-config-changed', loadLLMConfig);
+ }, []);
// Trading Config
const [symbols, setSymbols] = useState(['BTC/USD']);
@@ -223,19 +251,20 @@ export function AgentConfigurationUI({ onAgentCreated }: AgentConfigUIProps) {
<SelectField
label="Provider"
value={provider}
- onChange={setProvider}
- options={[
- { value: 'openai', label: 'OpenAI' },
- { value: 'anthropic', label: 'Anthropic' },
- { value: 'google', label: 'Google' },
- { value: 'groq', label: 'Groq (Fast & Free)' },
- { value: 'deepseek', label: 'DeepSeek' },
- { value: 'xai', label: 'xAI (Grok)' },
- { value: 'ollama', label: 'Ollama (Local)' }
- ]}
+ onChange={(val: string) => {
+ setProvider(val);
+ // Update model when provider changes
+ import('../../../../services/core/sqliteService').then(({ sqliteService }) => {
+ sqliteService.getLLMConfigs().then(configs => {
+ const match = configs.find(c => c.provider === val);
+ if (match) setModel(match.model);
+ });
+ });
+ }}
+ options={availableProviders.length > 0 ? availableProviders : [{ value: provider || 'none', label: provider ? provider.charAt(0).toUpperCase() + provider.slice(1) : 'Configure in Settings' }]}
/>
- <InputField label="Model" value={model} onChange={setModel} placeholder="gpt-4o-mini" />
+ <InputField label="Model" value={model} onChange={setModel} placeholder="Configure LLM in Settings" />
</div>
<SliderField
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/DebateArenaPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/DebateArenaPanel.tsx
index d48411f00..0fa03ee76 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/DebateArenaPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/DebateArenaPanel.tsx
@@ -32,9 +32,9 @@ interface DebateArenaPanelProps {
}
export function DebateArenaPanel({ selectedSymbol, currentPrice, marketData }: DebateArenaPanelProps) {
- const [bullModel, setBullModel] = useState('openai:gpt-4o-mini');
- const [bearModel, setBearModel] = useState('anthropic:claude-sonnet-4');
- const [analystModel, setAnalystModel] = useState('google:gemini-2.0-flash-exp');
+ const [bullModel, setBullModel] = useState('');
+ const [bearModel, setBearModel] = useState('');
+ const [analystModel, setAnalystModel] = useState('');
const [isDebating, setIsDebating] = useState(false);
const [error, setError] = useState<string | null>(null);
const [debateResult, setDebateResult] = useState<DebateResult | null>(null);
diff --git a/fincept-terminal-desktop/src/components/tabs/visualization-3d/Visualization3DTab.tsx b/fincept-terminal-desktop/src/components/tabs/visualization-3d/Visualization3DTab.tsx
deleted file mode 100644
index 568fec7bc..000000000
--- a/fincept-terminal-desktop/src/components/tabs/visualization-3d/Visualization3DTab.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-/**
- * Visualization 3D Tab
- * ====================
- * This tab has been deprecated in favor of SurfaceAnalyticsTab
- * which provides real Databento integration for 3D financial visualizations.
- *
- * @deprecated Use SurfaceAnalyticsTab instead
- */
-
-import React from 'react';
-import { AlertTriangle, ArrowRight } from 'lucide-react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-
-// This tab is deprecated - redirect users to SurfaceAnalyticsTab
-const Visualization3DTab: React.FC = () => {
- const { colors, fontFamily } = useTerminalTheme();
-
- return (
- <div
- style={{
- height: '100%',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- justifyContent: 'center',
- backgroundColor: '#000000',
- color: colors.text,
- fontFamily,
- padding: '48px',
- }}
- >
- <div
- style={{
- maxWidth: '480px',
- padding: '32px',
- backgroundColor: '#0F0F0F',
- border: '1px solid #2A2A2A',
- borderRadius: '2px',
- textAlign: 'center',
- }}
- >
- <div
- style={{
- width: '64px',
- height: '64px',
- margin: '0 auto 24px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- backgroundColor: '#FFD70015',
- borderRadius: '50%',
- }}
- >
- <AlertTriangle size={32} style={{ color: '#FFD700' }} />
- </div>
-
- <h2
- style={{
- fontSize: '16px',
- fontWeight: 700,
- color: colors.text,
- marginBottom: '12px',
- letterSpacing: '0.5px',
- }}
- >
- TAB DEPRECATED
- </h2>
-
- <p
- style={{
- fontSize: '11px',
- color: '#787878',
- marginBottom: '24px',
- lineHeight: '1.6',
- }}
- >
- The 3D Visualization tab has been replaced with Surface Analytics,
- which provides real-time market data from Databento for professional
- financial analysis including volatility surfaces, correlation matrices,
- and PCA factor analysis.
- </p>
-
- <div
- style={{
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- gap: '8px',
- padding: '12px 24px',
- backgroundColor: colors.accent,
- color: '#000000',
- borderRadius: '2px',
- fontSize: '10px',
- fontWeight: 700,
- letterSpacing: '0.5px',
- }}
- >
- <span>USE SURFACE ANALYTICS TAB</span>
- <ArrowRight size={14} />
- </div>
-
- <p
- style={{
- marginTop: '16px',
- fontSize: '9px',
- color: '#4A4A4A',
- }}
- >
- Navigate to: Surface Analytics (in the sidebar)
- </p>
- </div>
- </div>
- );
-};
-
-export default Visualization3DTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/visualization-3d/index.ts b/fincept-terminal-desktop/src/components/tabs/visualization-3d/index.ts
deleted file mode 100644
index 00a65a6ed..000000000
--- a/fincept-terminal-desktop/src/components/tabs/visualization-3d/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { default } from "./Visualization3DTab";
-export { default as Visualization3DTab } from "./Visualization3DTab";
diff --git a/fincept-terminal-desktop/src/constants/version.ts b/fincept-terminal-desktop/src/constants/version.ts
index 3bfba7ba0..10c83cc90 100644
--- a/fincept-terminal-desktop/src/constants/version.ts
+++ b/fincept-terminal-desktop/src/constants/version.ts
@@ -6,7 +6,7 @@
// Run `bun run sync-version` to sync from package.json
// Or edit package.json and run build/dev to auto-sync
-export const APP_VERSION = '3.3.1';
+export const APP_VERSION = '3.3.3';
export const APP_NAME = 'Fincept Terminal';
export const APP_BUILD_DATE = new Date().toISOString().split('T')[0];
diff --git a/fincept-terminal-desktop/src/contexts/AuthContext.tsx b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
index 536abcd44..3a8fce95c 100644
--- a/fincept-terminal-desktop/src/contexts/AuthContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
@@ -40,11 +40,11 @@ export interface UserProfileResponse {
export interface DeviceRegisterResponse {
success: boolean;
data?: {
- api_key?: string;
- temp_api_key?: string;
- expires_at?: string;
- daily_limit?: number;
- requests_today?: number;
+ api_key: string;
+ expires_at: string;
+ credit_balance: number;
+ user_type: 'guest';
+ message: string;
};
message?: string;
error?: string;
@@ -128,7 +128,7 @@ export interface SessionData {
mfa_enabled?: boolean;
};
expires_at?: string;
- daily_limit?: number;
+ credit_balance?: number;
requests_today?: number;
subscription?: UserSubscription;
}
@@ -361,7 +361,6 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
mfa_enabled: userProfile.mfa_enabled
} : apiData.user,
expires_at: apiData.user_type === 'guest' ? apiData.guest?.expires_at : undefined,
- daily_limit: apiData.user_type === 'guest' ? apiData.guest?.daily_limit : undefined,
requests_today: apiData.user_type === 'guest' ? apiData.guest?.requests_today : undefined,
subscription: userSubscription || undefined
};
@@ -374,16 +373,21 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
// Initialize session on app load
useEffect(() => {
+ let mounted = true;
+
const initializeSession = async () => {
try {
const isFirstTime = await checkIsFirstTimeUser();
+ if (!mounted) return;
setIsFirstTimeUser(isFirstTime);
const savedSession = await loadSession();
+ if (!mounted) return;
if (savedSession) {
if (savedSession.user_type === 'registered') {
const validatedSession = await validateSession(savedSession);
+ if (!mounted) return;
if (validatedSession) {
setSession(validatedSession);
await saveSession(validatedSession);
@@ -398,11 +402,12 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
} catch (error) {
console.error('Session initialization error:', error);
} finally {
- setIsLoading(false);
+ if (mounted) setIsLoading(false);
}
};
initializeSession();
+ return () => { mounted = false; };
}, []);
// Check API connectivity
@@ -780,38 +785,16 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
// Guest access setup
const setupGuestAccess = async (): Promise<{ success: boolean; error?: string }> => {
try {
- if (import.meta.env.DEV) {
- const mockGuestSession: SessionData = {
- authenticated: true,
- user_type: 'guest',
- api_key: 'mock_guest_api_key_' + Date.now(),
- device_id: generateDeviceId(),
- expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
- daily_limit: 50,
- requests_today: 0
- };
-
- setSession(mockGuestSession);
- await saveSession(mockGuestSession);
- const isFirstTime = await checkIsFirstTimeUser();
- setIsFirstTimeUser(isFirstTime);
-
- return { success: true };
- }
-
const deviceId = generateDeviceId();
- const result = await AuthApiService.registerDevice({
+ const result = await AuthApiService.createGuestSession({
device_id: deviceId,
device_name: `Fincept Terminal - ${navigator.platform}`,
platform: 'desktop',
hardware_info: {
- platform: navigator.platform,
- user_agent: navigator.userAgent,
- language: navigator.language,
- screen_resolution: `${window.screen.width}x${window.screen.height}`,
cpu_cores: navigator.hardwareConcurrency || 4,
- memory_gb: (navigator as any).deviceMemory || 8
+ memory_gb: (navigator as any).deviceMemory || 8,
+ screen_resolution: `${window.screen.width}x${window.screen.height}`
}
}) as DeviceRegisterResponse;
@@ -820,15 +803,14 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
const guestSession: SessionData = {
authenticated: true,
user_type: 'guest',
- api_key: apiData.api_key || apiData.temp_api_key || null,
+ api_key: apiData.api_key,
device_id: deviceId,
expires_at: apiData.expires_at,
- daily_limit: apiData.daily_limit || 50,
- requests_today: apiData.requests_today || 0
+ credit_balance: apiData.credit_balance
};
setSession(guestSession);
- saveSession(guestSession);
+ await saveSession(guestSession);
const isFirstTime = await checkIsFirstTimeUser();
setIsFirstTimeUser(isFirstTime);
diff --git a/fincept-terminal-desktop/src/contexts/BrokerContext.tsx b/fincept-terminal-desktop/src/contexts/BrokerContext.tsx
index fd714c8c2..10d7703fb 100644
--- a/fincept-terminal-desktop/src/contexts/BrokerContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/BrokerContext.tsx
@@ -142,10 +142,14 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
const [paperAdapter, setPaperAdapter] = useState<PaperTradingAdapter | null>(null);
const [paperPortfolio, setPaperPortfolio] = useState<Portfolio | null>(null);
+ // Keep ref in sync with state so initializeAdapters can read latest without being in deps
+ useEffect(() => { realAdapterRef.current = realAdapter; }, [realAdapter]);
+
// Refs for cleanup and abort control
const abortControllerRef = useRef<AbortController | null>(null);
const hasInitializedRef = useRef(false); // Prevent duplicate initialization
const marketDataInitializedRef = useRef(false); // Track market data service init
+ const realAdapterRef = useRef<IExchangeAdapter | null>(null); // Ref to avoid dep loop in initializeAdapters
// Get available brokers (memoized once, doesn't change)
const availableBrokers = useMemo(() => {
@@ -222,11 +226,13 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
}
}
- // Load saved preferences with validation
- const savedBroker = await safeStorageGet('active_trading_broker');
- const savedModeStr = await safeStorageGet('trading_mode');
+ // Load saved preferences in parallel (no inter-dependencies)
+ const [savedBroker, savedModeStr, savedPaperMode] = await Promise.all([
+ safeStorageGet('active_trading_broker'),
+ safeStorageGet('trading_mode'),
+ safeStorageGet('paper_portfolio_mode'),
+ ]);
const savedMode = validateTradingMode(savedModeStr);
- const savedPaperMode = await safeStorageGet('paper_portfolio_mode');
if (savedBroker && BROKER_REGISTRY[savedBroker]) {
setActiveBrokerState(savedBroker);
@@ -286,6 +292,8 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
}, []);
// Initialize adapters function
+ // Strategy: create paper adapter FIRST (fast, DB-only), then connect real adapter in background.
+ // This means the tab is usable immediately in paper mode without waiting for network.
const initializeAdapters = useCallback(async () => {
// Create new abort controller for this initialization
@@ -297,55 +305,27 @@ 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 and wait for completion to prevent race conditions
- await cleanupAdapters(realAdapter);
-
- // Also cleanup old paper adapter if exists to clear pending orders
+ // Clean up old adapters
+ await cleanupAdapters(realAdapterRef.current);
if (paperAdapter) {
- try {
- await paperAdapter.disconnect();
- } catch (err) {
+ try { await paperAdapter.disconnect(); } catch (err) {
console.error('[BrokerContext] Paper adapter disconnect error:', err);
}
}
if (signal.aborted) return;
- // Create real adapter
- newRealAdapter = createBrokerAdapter(activeBroker);
-
- try {
- await retryConnect(() => newRealAdapter!.connect());
- } catch (connectError: any) {
- // Non-fatal: paper trading can still work without real connection
- // This commonly happens with CORS restrictions or slow networks
- const errMsg = connectError?.message || String(connectError);
- console.warn(`[BrokerContext] [WARN] Failed to connect ${activeBroker} real adapter after retries: ${errMsg}`);
- }
-
- if (signal.aborted) {
- await cleanupAdapters(newRealAdapter);
- return;
- }
-
- // Update real adapter state
- setRealAdapter(newRealAdapter);
-
- // Create or get paper portfolio from Rust backend
const portfolioName = paperPortfolioMode === 'unified'
? 'Global Paper Trading Portfolio'
: `${activeBroker.toUpperCase()} Paper Trading`;
-
const fees = getBrokerFees(activeBrokerMetadata);
+ // --- STEP 1: Create paper adapter immediately (DB-only, no network) ---
try {
- // 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();
newPaperAdapter = createPaperTradingAdapter(
{
@@ -366,14 +346,9 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
await newPaperAdapter.connect();
- if (signal.aborted) {
- await newPaperAdapter.disconnect();
- return;
- }
+ if (signal.aborted) { await newPaperAdapter.disconnect(); return; }
setPaperAdapter(newPaperAdapter);
-
- // Also get the portfolio for direct Rust API access
const portfolio = await paperTrading.getPortfolio(newPaperAdapter.portfolioId);
setPaperPortfolio(portfolio);
} catch (error) {
@@ -383,39 +358,54 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
setPaperPortfolio(null);
}
- } catch (error) {
+ // Paper adapter is ready — unblock the UI immediately
+ setIsConnecting(false);
+
if (signal.aborted) return;
- console.error(`[BrokerContext] [FAIL] Failed to initialize ${activeBroker}:`, error);
+ // --- STEP 2: Connect real adapter in background (network, can be slow) ---
+ newRealAdapter = createBrokerAdapter(activeBroker);
+ try {
+ await retryConnect(() => newRealAdapter!.connect());
+ } catch (connectError: any) {
+ const errMsg = connectError?.message || String(connectError);
+ console.warn(`[BrokerContext] [WARN] Failed to connect ${activeBroker} real adapter after retries: ${errMsg}`);
+ }
+
+ if (signal.aborted) { await cleanupAdapters(newRealAdapter); return; }
+
+ setRealAdapter(newRealAdapter);
+
+ } catch (error) {
+ if (signal.aborted) return;
+ console.error(`[BrokerContext] [FAIL] Failed to initialize ${activeBroker}:`, error);
setRealAdapter(null);
newRealAdapter = null;
newPaperAdapter = null;
setPaperAdapter(null);
setPaperPortfolio(null);
brokerMCPBridge.disconnect();
+ setIsConnecting(false);
}
- // Connect BrokerMCPBridge AFTER adapters are created (outside try-catch for proper scoping)
+ // Connect BrokerMCPBridge after both adapters are available
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'})`);
+ console.log(`[BrokerContext] BrokerMCPBridge connected (${tradingMode} mode, realAdapter: ${newRealAdapter ? 'available' : 'none'})`);
} else {
- console.warn(`[BrokerContext] Adapter for ${tradingMode} mode not available or not connected - bridge not connected`);
+ console.warn(`[BrokerContext] Adapter for ${tradingMode} mode not available - bridge not connected`);
brokerMCPBridge.disconnect();
}
}
-
- setIsConnecting(false);
- }, [activeBroker, tradingMode, paperPortfolioMode, activeBrokerMetadata, cleanupAdapters, realAdapter, getBrokerFees]);
+ }, [activeBroker, tradingMode, paperPortfolioMode, activeBrokerMetadata, cleanupAdapters, getBrokerFees]);
// Set active broker
const setActiveBroker = useCallback(async (brokerId: string) => {
@@ -431,7 +421,7 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
setActiveBrokerState(brokerId);
// Save preference
- await safeStorageSet('active_broker', brokerId);
+ await safeStorageSet('active_trading_broker', brokerId);
// Re-initialize adapters
await initializeAdapters();
diff --git a/fincept-terminal-desktop/src/contexts/DataSourceContext.tsx b/fincept-terminal-desktop/src/contexts/DataSourceContext.tsx
index 2f5889538..ff0ca6039 100644
--- a/fincept-terminal-desktop/src/contexts/DataSourceContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/DataSourceContext.tsx
@@ -121,6 +121,8 @@ export const DataSourceProvider: React.FC<{ children: React.ReactNode }> = ({ ch
const [state, dispatch] = useReducer(dataSourceReducer, initialState);
const mountedRef = useRef(true);
const abortControllerRef = useRef<AbortController | null>(null);
+ // Track active test connection IDs to prevent duplicate concurrent tests
+ const activeTestRef = useRef<string | null>(null);
// Load connections from SQLite on mount
const loadConnections = useCallback(async () => {
@@ -242,6 +244,10 @@ export const DataSourceProvider: React.FC<{ children: React.ReactNode }> = ({ ch
const testConnection = useCallback(async (connection: DataSourceConnection) => {
if (!mountedRef.current) return;
+ // Prevent duplicate concurrent tests for the same connection
+ if (activeTestRef.current === connection.id) return;
+ activeTestRef.current = connection.id;
+
dispatch({ type: 'SET_TESTING', payload: connection.id });
try {
@@ -252,7 +258,7 @@ export const DataSourceProvider: React.FC<{ children: React.ReactNode }> = ({ ch
// Use the actual adapter's test method
const result = await adapter.testConnection();
- if (!mountedRef.current) return;
+ if (!mountedRef.current || activeTestRef.current !== connection.id) return;
if (result.success) {
dispatch({ type: 'SET_CONNECTED', payload: connection.id });
@@ -263,15 +269,19 @@ export const DataSourceProvider: React.FC<{ children: React.ReactNode }> = ({ ch
// No adapter available, simulate test
await new Promise((resolve) => setTimeout(resolve, 1500));
- if (!mountedRef.current) return;
+ if (!mountedRef.current || activeTestRef.current !== connection.id) return;
dispatch({ type: 'SET_CONNECTED', payload: connection.id });
}
} catch (error) {
- if (!mountedRef.current) return;
+ if (!mountedRef.current || activeTestRef.current !== connection.id) return;
dispatch({
type: 'SET_ERROR',
payload: { id: connection.id, message: error instanceof Error ? error.message : 'Connection test failed' },
});
+ } finally {
+ if (activeTestRef.current === connection.id) {
+ activeTestRef.current = null;
+ }
}
}, []);
diff --git a/fincept-terminal-desktop/src/contexts/LanguageContext.tsx b/fincept-terminal-desktop/src/contexts/LanguageContext.tsx
index 1795345a3..1a2731b69 100644
--- a/fincept-terminal-desktop/src/contexts/LanguageContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/LanguageContext.tsx
@@ -1,7 +1,7 @@
// File: src/contexts/LanguageContext.tsx
// Language context for managing application language and translations
-import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
+import React, { createContext, useContext, useState, useEffect, useRef, ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { saveSetting, getSetting } from '@/services/core/sqliteService';
@@ -53,12 +53,18 @@ export const LanguageProvider: React.FC<LanguageProviderProps> = ({ children })
const { i18n } = useTranslation();
const [currentLanguage, setCurrentLanguage] = useState(i18n.language || 'en');
const [isRTL, setIsRTL] = useState(false);
+ const mountedRef = useRef(true);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => { mountedRef.current = false; };
+ }, []);
useEffect(() => {
// Load saved language from storage on mount
const loadLanguage = async () => {
const savedLanguage = await getSetting('i18nextLng');
- if (savedLanguage && languages.find(lang => lang.code === savedLanguage)) {
+ if (mountedRef.current && savedLanguage && languages.find(lang => lang.code === savedLanguage)) {
changeLanguage(savedLanguage);
}
};
diff --git a/fincept-terminal-desktop/src/contexts/NavigationContext.tsx b/fincept-terminal-desktop/src/contexts/NavigationContext.tsx
index 1a50e2a92..9f34b55d1 100644
--- a/fincept-terminal-desktop/src/contexts/NavigationContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/NavigationContext.tsx
@@ -1,7 +1,7 @@
// File: src/contexts/NavigationContext.tsx
// Reusable navigation context for sharing navigation functions across components
-import React, { createContext, useContext, ReactNode } from 'react';
+import React, { createContext, useContext, useRef, useEffect, useCallback, ReactNode } from 'react';
import { Screen } from '../App';
interface NavigationContextType {
@@ -36,25 +36,36 @@ export const NavigationProvider: React.FC<NavigationProviderProps> = ({
onSetActiveTab,
activeTab
}) => {
- const navigateToScreen = (screen: Screen) => {
+ const profileTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(() => {
+ return () => {
+ if (profileTimerRef.current) {
+ clearTimeout(profileTimerRef.current);
+ }
+ };
+ }, []);
+
+ const navigateToScreen = useCallback((screen: Screen) => {
onNavigate(screen);
- };
+ }, [onNavigate]);
- const navigateToPricing = () => {
+ const navigateToPricing = useCallback(() => {
onNavigate('pricing');
- };
+ }, [onNavigate]);
- const navigateToDashboard = () => {
+ const navigateToDashboard = useCallback(() => {
onNavigate('dashboard');
- };
+ }, [onNavigate]);
- const navigateToProfile = () => {
+ const navigateToProfile = useCallback(() => {
onNavigate('dashboard');
if (onSetActiveTab) {
// Set active tab to profile after a short delay to ensure dashboard is mounted
- setTimeout(() => onSetActiveTab('profile'), 100);
+ if (profileTimerRef.current) clearTimeout(profileTimerRef.current);
+ profileTimerRef.current = setTimeout(() => onSetActiveTab('profile'), 100);
}
- };
+ }, [onNavigate, onSetActiveTab]);
const value: NavigationContextType = {
navigateToScreen,
diff --git a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx
index 5aab86211..a88b4652b 100644
--- a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx
@@ -314,6 +314,8 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
// Auto-create adapter when broker changes (including on startup)
// adapterInitKey forces re-init when incremented (for re-selecting same broker)
useEffect(() => {
+ let cancelled = false;
+
const initializeAdapter = async () => {
if (!activeBroker) {
// If we're skipping init and isLoading is true, set it to false
@@ -328,6 +330,7 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
try {
const newAdapter = createStockBrokerAdapter(activeBroker);
+ if (cancelled) return;
console.log(`[StockBrokerContext] Created adapter for: ${activeBroker}`);
// Check if this is a paper-only broker that doesn't need credentials (like yfinance)
@@ -339,6 +342,7 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
// Auto-authenticate for paper-only brokers (no real credentials needed)
const authResult = await newAdapter.authenticate({ apiKey: 'paper_trading' });
+ if (cancelled) return;
if (authResult.success) {
console.log(`[StockBrokerContext] ✓ Paper trading auto-authenticated for ${activeBroker}`);
@@ -352,14 +356,17 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
// Initialize unified trading session in paper mode
try {
await initTradingSession(activeBroker, 'paper');
+ if (cancelled) return;
console.log(`[StockBrokerContext] ✓ Paper trading session initialized`);
} catch (sessionErr) {
+ if (cancelled) return;
console.error('[StockBrokerContext] Failed to init paper trading session:', sessionErr);
}
// Auto-download master contract for YFinance (CRITICAL for chart/symbol lookup)
setMasterContractReady(false);
symbolMaster.ensureMasterContract(activeBroker).then((result) => {
+ if (cancelled) return;
if (result.success) {
console.log(`[StockBrokerContext] ✓ Master contract ready (paper trading): ${result.total_symbols} symbols`);
setMasterContractReady(true);
@@ -370,6 +377,7 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
setMasterContractReady(true);
}
}).catch((err) => {
+ if (cancelled) return;
console.warn(`[StockBrokerContext] Master contract download failed:`, err);
// For YFinance, we can still work without master contract (uses direct symbol)
setMasterContractReady(true);
@@ -389,6 +397,7 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
try {
console.log(`[StockBrokerContext] Loading credentials from database (no auto-connect)...`);
const storedCreds = await (newAdapter as any).loadCredentials();
+ if (cancelled) return;
if (storedCreds && storedCreds.apiKey) {
console.log(`[StockBrokerContext] Found stored credentials, loading into adapter memory...`);
@@ -439,16 +448,20 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
// Initialize trading session and fetch data in background
try {
await initTradingSession(activeBroker, tradingMode);
+ if (cancelled) return;
} catch (sessionErr) {
+ if (cancelled) return;
console.error('[StockBrokerContext] Failed to init trading session:', sessionErr);
}
refreshAllData(newAdapter).catch(err => {
+ if (cancelled) return;
console.warn('[StockBrokerContext] Background data refresh failed:', err);
});
// Auto-download master contract if needed (CRITICAL for chart/symbol lookup)
setMasterContractReady(false);
symbolMaster.ensureMasterContract(activeBroker).then((result) => {
+ if (cancelled) return;
if (result.success) {
console.log(`[StockBrokerContext] ✓ Master contract ready (session restore): ${result.total_symbols} symbols`);
setMasterContractReady(true);
@@ -458,6 +471,7 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
setMasterContractReady(result.total_symbols > 0);
}
}).catch((err) => {
+ if (cancelled) return;
console.warn(`[StockBrokerContext] Master contract download failed:`, err);
setMasterContractReady(false);
});
@@ -500,6 +514,7 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
};
initializeAdapter();
+ return () => { cancelled = true; };
}, [activeBroker, tradingMode, adapterInitKey]);
// ============================================================================
diff --git a/fincept-terminal-desktop/src/contexts/TimezoneContext.tsx b/fincept-terminal-desktop/src/contexts/TimezoneContext.tsx
index 54a15a4f3..722871270 100644
--- a/fincept-terminal-desktop/src/contexts/TimezoneContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/TimezoneContext.tsx
@@ -89,12 +89,6 @@ interface TimezoneContextValue {
formatTimeShort: (date: Date) => string;
/** Get the current time formatted in the selected timezone */
getCurrentTimeFormatted: () => string;
-
- // Aliases for backwards compatibility with Settings Tab
- /** @deprecated Use timezone instead */
- defaultTimezone: TimezoneOption;
- /** @deprecated Use setTimezone instead */
- setDefaultTimezone: (timezoneId: string) => void;
}
const TimezoneContext = createContext<TimezoneContextValue | undefined>(undefined);
@@ -194,9 +188,6 @@ export const TimezoneProvider: React.FC<TimezoneProviderProps> = ({ children })
formatTime,
formatTimeShort,
getCurrentTimeFormatted,
- // Backwards compatibility aliases
- defaultTimezone: timezone,
- setDefaultTimezone: setTimezone,
};
return (
@@ -252,7 +243,4 @@ export const useCurrentTime = (refreshInterval: number = 1000) => {
};
};
-// Keep useDefaultTime as alias for backwards compatibility
-export const useDefaultTime = useCurrentTime;
-
export default TimezoneContext;
diff --git a/fincept-terminal-desktop/src/contexts/WorkspaceContext.tsx b/fincept-terminal-desktop/src/contexts/WorkspaceContext.tsx
index 399fea7f5..e7983932a 100644
--- a/fincept-terminal-desktop/src/contexts/WorkspaceContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/WorkspaceContext.tsx
@@ -201,11 +201,13 @@ export const WorkspaceProvider: React.FC<{ children: ReactNode }> = ({ children
const restoredTabStates = useRef<Record<string, unknown>>({});
const mountedRef = useRef(true);
- // Point 3: Cleanup on unmount
+ // Cleanup on unmount — release all registry references to allow GC
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
+ tabStateRegistry.current.clear();
+ restoredTabStates.current = {};
};
}, []);
diff --git a/fincept-terminal-desktop/src/hooks/useAutoUpdater.ts b/fincept-terminal-desktop/src/hooks/useAutoUpdater.ts
index ed30a94a0..f8f90190e 100644
--- a/fincept-terminal-desktop/src/hooks/useAutoUpdater.ts
+++ b/fincept-terminal-desktop/src/hooks/useAutoUpdater.ts
@@ -29,6 +29,7 @@ export function useAutoUpdater(): UseAutoUpdaterReturn {
const checkingRef = useRef<boolean>(false);
const relaunchTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
+ const errorClearTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
const checkForUpdate = useCallback(async (silent = false) => {
// Prevent duplicate checks
@@ -67,7 +68,8 @@ export function useAutoUpdater(): UseAutoUpdaterReturn {
console.log('[AutoUpdater] No updates available');
if (!silent) {
setError('You are running the latest version!');
- setTimeout(() => setError(null), 3000);
+ if (errorClearTimerRef.current) clearTimeout(errorClearTimerRef.current);
+ errorClearTimerRef.current = setTimeout(() => setError(null), 3000);
}
}
} catch (err) {
@@ -187,6 +189,9 @@ export function useAutoUpdater(): UseAutoUpdaterReturn {
if (relaunchTimerRef.current) {
clearTimeout(relaunchTimerRef.current);
}
+ if (errorClearTimerRef.current) {
+ clearTimeout(errorClearTimerRef.current);
+ }
};
}, [checkForUpdate]);
diff --git a/fincept-terminal-desktop/src/hooks/useCache.ts b/fincept-terminal-desktop/src/hooks/useCache.ts
index 7a530e622..b0cb3092e 100644
--- a/fincept-terminal-desktop/src/hooks/useCache.ts
+++ b/fincept-terminal-desktop/src/hooks/useCache.ts
@@ -171,9 +171,13 @@ export function useCache<T>(options: UseCacheOptions<T>): UseCacheResult<T> {
const fetchIdRef = useRef(0); // Track fetch operations to handle race conditions
const previousKeyRef = useRef<string>(key);
- // Memoize fetcher to prevent unnecessary re-renders
+ // Memoize fetcher and callbacks to prevent stale closures in async operations
const stableFetcher = useRef(fetcher);
stableFetcher.current = fetcher;
+ const stableOnSuccess = useRef(onSuccess);
+ stableOnSuccess.current = onSuccess;
+ const stableOnError = useRef(onError);
+ stableOnError.current = onError;
// Reset state when key changes
useEffect(() => {
@@ -225,7 +229,7 @@ export function useCache<T>(options: UseCacheOptions<T>): UseCacheResult<T> {
setData(cached.data);
setIsStale(cached.isStale);
setIsLoading(false);
- onSuccess?.(cached.data);
+ stableOnSuccess.current?.(cached.data);
// If data is stale and staleWhileRevalidate is enabled, fetch fresh in background
if (cached.isStale && staleWhileRevalidate && isOnline) {
@@ -253,7 +257,7 @@ export function useCache<T>(options: UseCacheOptions<T>): UseCacheResult<T> {
await cacheService.set(key, freshData, category, ttl);
setData(freshData);
setIsStale(false);
- onSuccess?.(freshData);
+ stableOnSuccess.current?.(freshData);
} catch (fetchError) {
// Silently fail background refresh, we already have stale data
if (!(fetchError instanceof Error && fetchError.message === 'Request aborted')) {
@@ -270,7 +274,7 @@ export function useCache<T>(options: UseCacheOptions<T>): UseCacheResult<T> {
setData(staleData.data);
setIsStale(true);
setIsLoading(false);
- onSuccess?.(staleData.data);
+ stableOnSuccess.current?.(staleData.data);
return;
}
throw new Error('No cached data available offline');
@@ -300,7 +304,7 @@ export function useCache<T>(options: UseCacheOptions<T>): UseCacheResult<T> {
setData(freshData);
setIsStale(false);
setIsLoading(false);
- onSuccess?.(freshData);
+ stableOnSuccess.current?.(freshData);
}
} catch (err) {
// Check if still valid
@@ -314,7 +318,7 @@ export function useCache<T>(options: UseCacheOptions<T>): UseCacheResult<T> {
if (error.message !== 'Request aborted') {
setError(error);
setIsLoading(false);
- onError?.(error);
+ stableOnError.current?.(error);
}
} finally {
// Check if still valid
@@ -322,7 +326,7 @@ export function useCache<T>(options: UseCacheOptions<T>): UseCacheResult<T> {
setIsFetching(false);
}
}
- }, [key, category, ttl, staleWhileRevalidate, retry, retryDelay, isOnline, onSuccess, onError, data]);
+ }, [key, category, ttl, staleWhileRevalidate, retry, retryDelay, isOnline, data]);
// Force refresh - bypasses cache
const refresh = useCallback(async () => {
@@ -355,7 +359,7 @@ export function useCache<T>(options: UseCacheOptions<T>): UseCacheResult<T> {
await cacheService.set(key, freshData, category, ttl);
setData(freshData);
setIsStale(false);
- onSuccess?.(freshData);
+ stableOnSuccess.current?.(freshData);
} catch (err) {
if (fetchId !== fetchIdRef.current || !mountedRef.current) {
return;
@@ -364,14 +368,14 @@ export function useCache<T>(options: UseCacheOptions<T>): UseCacheResult<T> {
const error = err instanceof Error ? err : new Error(String(err));
if (error.message !== 'Request aborted') {
setError(error);
- onError?.(error);
+ stableOnError.current?.(error);
}
} finally {
if (fetchId === fetchIdRef.current && mountedRef.current) {
setIsFetching(false);
}
}
- }, [key, category, ttl, retry, retryDelay, isOnline, onSuccess, onError]);
+ }, [key, category, ttl, retry, retryDelay, isOnline]);
// Invalidate cache and reset state
const invalidate = useCallback(async () => {
diff --git a/fincept-terminal-desktop/src/hooks/useExchangeMarkets.ts b/fincept-terminal-desktop/src/hooks/useExchangeMarkets.ts
new file mode 100644
index 000000000..98527c3c3
--- /dev/null
+++ b/fincept-terminal-desktop/src/hooks/useExchangeMarkets.ts
@@ -0,0 +1,89 @@
+/**
+ * useExchangeMarkets
+ *
+ * Derives the watchlist symbols and wsId<->unified symbol maps directly from
+ * the CCXT realAdapter that is already connected in BrokerContext.
+ *
+ * - No hardcoded symbol lists
+ * - Works for any broker (Kraken, Binance, HyperLiquid, OKX, …)
+ * - Automatically updates when the broker changes
+ */
+
+import { useState, useEffect } from 'react';
+import type { CoreExchangeAdapter } from '@/brokers/crypto/base/CoreAdapter';
+import { DEFAULT_CRYPTO_WATCHLIST } from '@/components/tabs/crypto-trading/constants';
+
+export interface ExchangeMarkets {
+ /** wsId → unified symbol e.g. "XBT/USD" → "BTC/USD" */
+ wsIdToUnified: Map<string, string>;
+ /** unified symbol → wsId e.g. "BTC/USD" → "XBT/USD" */
+ unifiedToWsId: Map<string, string>;
+ /** Default watchlist: preferred symbols available on this exchange (USD/USDT spot) */
+ watchlistSymbols: string[];
+ /** True once maps are populated from the exchange */
+ ready: boolean;
+}
+
+const PREFERRED_QUOTE = ['USD', 'USDT'];
+
+// Symbols we want to show by preference order (unified format)
+const PREFERRED_SYMBOLS = [
+ 'BTC/USD', 'ETH/USD', 'SOL/USD', 'XRP/USD', 'ADA/USD',
+ 'DOGE/USD', 'AVAX/USD', 'DOT/USD', 'LTC/USD', 'LINK/USD',
+ 'UNI/USD', 'ATOM/USD', 'XLM/USD', 'ETC/USD', 'BCH/USD',
+ 'NEAR/USD', 'FIL/USD', 'ICP/USD', 'INJ/USD', 'MKR/USD',
+ 'AAVE/USD', 'PEPE/USD', 'WIF/USD', 'BONK/USD', 'SUI/USD',
+ 'BNB/USD', 'BNB/USDT', 'ARB/USD', 'OP/USD', 'TRX/USDT',
+];
+
+function buildWatchlist(activeSymbols: Set<string>): string[] {
+ const result: string[] = [];
+
+ // First: include preferred symbols that exist on this exchange
+ for (const sym of PREFERRED_SYMBOLS) {
+ if (activeSymbols.has(sym)) result.push(sym);
+ }
+
+ // Fill up to 30 with other USD spot pairs alphabetically if needed
+ if (result.length < 30) {
+ for (const sym of Array.from(activeSymbols).sort()) {
+ if (result.length >= 30) break;
+ if (!result.includes(sym)) result.push(sym);
+ }
+ }
+
+ return result.slice(0, 30);
+}
+
+export function useExchangeMarkets(realAdapter: any | null): ExchangeMarkets {
+ const [markets, setMarkets] = useState<ExchangeMarkets>({
+ wsIdToUnified: new Map(),
+ unifiedToWsId: new Map(),
+ watchlistSymbols: DEFAULT_CRYPTO_WATCHLIST,
+ ready: false,
+ });
+
+ useEffect(() => {
+ if (!realAdapter || typeof realAdapter.getMarketSymbolMap !== 'function') {
+ // Adapter not ready or doesn't have the method — keep defaults
+ setMarkets(prev => ({ ...prev, ready: false }));
+ return;
+ }
+
+ const { wsIdToUnified, unifiedToWsId, activeUsdSymbols } =
+ (realAdapter as CoreExchangeAdapter).getMarketSymbolMap();
+
+ if (wsIdToUnified.size === 0) {
+ // Markets not loaded yet (connect() hasn't finished)
+ setMarkets(prev => ({ ...prev, ready: false }));
+ return;
+ }
+
+ const activeSet = new Set(activeUsdSymbols);
+ const watchlistSymbols = buildWatchlist(activeSet);
+
+ setMarkets({ wsIdToUnified, unifiedToWsId, watchlistSymbols, ready: true });
+ }, [realAdapter]);
+
+ return markets;
+}
diff --git a/fincept-terminal-desktop/src/hooks/useRustWebSocket.ts b/fincept-terminal-desktop/src/hooks/useRustWebSocket.ts
index 3665af3c9..de63c6281 100644
--- a/fincept-terminal-desktop/src/hooks/useRustWebSocket.ts
+++ b/fincept-terminal-desktop/src/hooks/useRustWebSocket.ts
@@ -13,9 +13,14 @@ import {
/**
* Normalize a symbol for comparison (removes slashes, dashes, underscores, uppercase)
+ * Also maps exchange-specific aliases: XBT→BTC (Kraken), XDG→DOGE (Kraken)
*/
function normalizeSymbol(symbol: string): string {
- return symbol.replace(/[/\-_]/g, '').toUpperCase();
+ return symbol
+ .replace(/XBT/g, 'BTC')
+ .replace(/XDG/g, 'DOGE')
+ .replace(/[/\-_]/g, '')
+ .toUpperCase();
}
// ============================================================================
@@ -29,6 +34,9 @@ export function useRustTicker(provider: string, symbol: string, autoConnect = tr
const subscriptionRef = useRef<{ provider: string; symbol: string } | null>(null);
const listenerRef = useRef<(() => void) | null>(null);
+ // Normalize provider to lowercase for consistent matching
+ const normalizedProvider = provider.toLowerCase();
+
useEffect(() => {
let mounted = true;
const normalizedInputSymbol = normalizeSymbol(symbol);
@@ -43,27 +51,36 @@ export function useRustTicker(provider: string, symbol: string, autoConnect = tr
// Unsubscribe from old subscription if provider/symbol changed
if (subscriptionRef.current &&
- (subscriptionRef.current.provider !== provider ||
+ (subscriptionRef.current.provider !== normalizedProvider ||
subscriptionRef.current.symbol !== symbol)) {
await websocketBridge.unsubscribe(
subscriptionRef.current.provider,
subscriptionRef.current.symbol,
'ticker'
- ).catch(() => {});
+ ).catch((e) => console.warn('[useRustTicker] unsubscribe error:', e));
subscriptionRef.current = null;
}
// Subscribe to ticker channel
if (!subscriptionRef.current) {
- await websocketBridge.subscribe(provider, symbol, 'ticker');
- subscriptionRef.current = { provider, symbol };
+ console.log(`[useRustTicker] Subscribing: provider='${normalizedProvider}' symbol='${symbol}'`);
+ await websocketBridge.subscribe(normalizedProvider, symbol, 'ticker');
+ subscriptionRef.current = { provider: normalizedProvider, symbol };
}
// Listen to ticker events
const unlisten = await websocketBridge.onTicker((tickerData) => {
// Only process if mounted and matches our symbol/provider
if (!mounted) return;
- if (tickerData.provider !== provider) return;
+
+ // Debug: log first few incoming ticks
+ const debugCount = (window as any).__tickerDebugCount || 0;
+ if (debugCount < 5) {
+ console.log(`[useRustTicker] Received: provider='${tickerData.provider}' symbol='${tickerData.symbol}' price=${tickerData.price}`);
+ (window as any).__tickerDebugCount = debugCount + 1;
+ }
+
+ if (tickerData.provider !== normalizedProvider) return;
if (normalizeSymbol(tickerData.symbol) !== normalizedInputSymbol) return;
setData(tickerData);
@@ -92,11 +109,11 @@ export function useRustTicker(provider: string, symbol: string, autoConnect = tr
subscriptionRef.current.provider,
subscriptionRef.current.symbol,
'ticker'
- ).catch(() => {});
+ ).catch((e) => console.warn('[useRustTicker] cleanup unsubscribe error:', e));
subscriptionRef.current = null;
}
};
- }, [provider, symbol, autoConnect]);
+ }, [normalizedProvider, symbol, autoConnect]);
return { data, error };
}
@@ -116,6 +133,9 @@ export function useRustOrderBook(
const subscriptionRef = useRef<{ provider: string; symbol: string } | null>(null);
const listenerRef = useRef<(() => void) | null>(null);
+ // Normalize provider to lowercase for consistent matching
+ const normalizedProvider = provider.toLowerCase();
+
useEffect(() => {
let mounted = true;
const normalizedInputSymbol = normalizeSymbol(symbol);
@@ -130,26 +150,26 @@ export function useRustOrderBook(
// Unsubscribe from old subscription if provider/symbol changed
if (subscriptionRef.current &&
- (subscriptionRef.current.provider !== provider ||
+ (subscriptionRef.current.provider !== normalizedProvider ||
subscriptionRef.current.symbol !== symbol)) {
await websocketBridge.unsubscribe(
subscriptionRef.current.provider,
subscriptionRef.current.symbol,
'book'
- ).catch(() => {});
+ ).catch((e) => console.warn('[useRustOrderBook] unsubscribe error:', e));
subscriptionRef.current = null;
}
// Subscribe to book channel with depth parameter
if (!subscriptionRef.current) {
- await websocketBridge.subscribe(provider, symbol, 'book', { depth });
- subscriptionRef.current = { provider, symbol };
+ await websocketBridge.subscribe(normalizedProvider, symbol, 'book', { depth });
+ subscriptionRef.current = { provider: normalizedProvider, symbol };
}
// Listen to orderbook events
const unlisten = await websocketBridge.onOrderBook((bookData) => {
if (!mounted) return;
- if (bookData.provider !== provider) return;
+ if (bookData.provider !== normalizedProvider) return;
if (normalizeSymbol(bookData.symbol) !== normalizedInputSymbol) return;
setData(bookData);
@@ -178,11 +198,11 @@ export function useRustOrderBook(
subscriptionRef.current.provider,
subscriptionRef.current.symbol,
'book'
- ).catch(() => {});
+ ).catch((e) => console.warn('[useRustOrderBook] cleanup unsubscribe error:', e));
subscriptionRef.current = null;
}
};
- }, [provider, symbol, depth, autoConnect]);
+ }, [normalizedProvider, symbol, depth, autoConnect]);
return { data, error };
}
@@ -197,6 +217,9 @@ export function useRustTrades(provider: string, symbol: string, maxTrades = 50,
const subscriptionRef = useRef<{ provider: string; symbol: string } | null>(null);
const listenerRef = useRef<(() => void) | null>(null);
+ // Normalize provider to lowercase for consistent matching
+ const normalizedProvider = provider.toLowerCase();
+
useEffect(() => {
let mounted = true;
const normalizedInputSymbol = normalizeSymbol(symbol);
@@ -211,13 +234,13 @@ export function useRustTrades(provider: string, symbol: string, maxTrades = 50,
// Unsubscribe from old subscription if provider/symbol changed
if (subscriptionRef.current &&
- (subscriptionRef.current.provider !== provider ||
+ (subscriptionRef.current.provider !== normalizedProvider ||
subscriptionRef.current.symbol !== symbol)) {
await websocketBridge.unsubscribe(
subscriptionRef.current.provider,
subscriptionRef.current.symbol,
'trade'
- ).catch(() => {});
+ ).catch((e) => console.warn('[useRustTrades] unsubscribe error:', e));
subscriptionRef.current = null;
// Clear old trades when symbol changes
setTrades([]);
@@ -225,14 +248,14 @@ export function useRustTrades(provider: string, symbol: string, maxTrades = 50,
// Subscribe to trade channel
if (!subscriptionRef.current) {
- await websocketBridge.subscribe(provider, symbol, 'trade');
- subscriptionRef.current = { provider, symbol };
+ await websocketBridge.subscribe(normalizedProvider, symbol, 'trade');
+ subscriptionRef.current = { provider: normalizedProvider, symbol };
}
// Listen to trade events
const unlisten = await websocketBridge.onTrade((tradeData) => {
if (!mounted) return;
- if (tradeData.provider !== provider) return;
+ if (tradeData.provider !== normalizedProvider) return;
if (normalizeSymbol(tradeData.symbol) !== normalizedInputSymbol) return;
setTrades((prev) => {
@@ -264,11 +287,11 @@ export function useRustTrades(provider: string, symbol: string, maxTrades = 50,
subscriptionRef.current.provider,
subscriptionRef.current.symbol,
'trade'
- ).catch(() => {});
+ ).catch((e) => console.warn('[useRustTrades] cleanup unsubscribe error:', e));
subscriptionRef.current = null;
}
};
- }, [provider, symbol, maxTrades, autoConnect]);
+ }, [normalizedProvider, symbol, maxTrades, autoConnect]);
return { trades, error };
}
@@ -289,6 +312,9 @@ export function useRustCandles(
const subscriptionRef = useRef<{ provider: string; symbol: string; interval: string } | null>(null);
const listenerRef = useRef<(() => void) | null>(null);
+ // Normalize provider to lowercase for consistent matching
+ const normalizedProvider = provider.toLowerCase();
+
useEffect(() => {
let mounted = true;
const normalizedInputSymbol = normalizeSymbol(symbol);
@@ -303,14 +329,14 @@ export function useRustCandles(
// Unsubscribe from old subscription if provider/symbol/interval changed
if (subscriptionRef.current &&
- (subscriptionRef.current.provider !== provider ||
+ (subscriptionRef.current.provider !== normalizedProvider ||
subscriptionRef.current.symbol !== symbol ||
subscriptionRef.current.interval !== interval)) {
await websocketBridge.unsubscribe(
subscriptionRef.current.provider,
subscriptionRef.current.symbol,
'ohlc'
- ).catch(() => {});
+ ).catch((e) => console.warn('[useRustCandles] unsubscribe error:', e));
subscriptionRef.current = null;
// Clear old candles when symbol/interval changes
setCandles([]);
@@ -319,14 +345,14 @@ export function useRustCandles(
// Subscribe to candle channel
if (!subscriptionRef.current) {
- await websocketBridge.subscribe(provider, symbol, 'ohlc', { interval });
- subscriptionRef.current = { provider, symbol, interval };
+ await websocketBridge.subscribe(normalizedProvider, symbol, 'ohlc', { interval });
+ subscriptionRef.current = { provider: normalizedProvider, symbol, interval };
}
// Listen to candle events
const unlisten = await websocketBridge.onCandle((candleData) => {
if (!mounted) return;
- if (candleData.provider !== provider) return;
+ if (candleData.provider !== normalizedProvider) return;
// Use normalized symbol comparison (fixes the inconsistency)
if (normalizeSymbol(candleData.symbol) !== normalizedInputSymbol) return;
if (candleData.interval !== interval) return;
@@ -368,11 +394,11 @@ export function useRustCandles(
subscriptionRef.current.provider,
subscriptionRef.current.symbol,
'ohlc'
- ).catch(() => {});
+ ).catch((e) => console.warn('[useRustCandles] cleanup unsubscribe error:', e));
subscriptionRef.current = null;
}
};
- }, [provider, symbol, interval, autoConnect]);
+ }, [normalizedProvider, symbol, interval, autoConnect]);
return { candles, latestCandle, error };
}
@@ -385,6 +411,9 @@ export function useConnectionStatus(provider: string) {
const [status, setStatus] = useState<StatusData | null>(null);
const [metrics, setMetrics] = useState<ConnectionMetrics | null>(null);
+ // Normalize provider to lowercase for consistent matching
+ const normalizedProvider = provider.toLowerCase();
+
useEffect(() => {
let mounted = true;
let unlisten: (() => void) | null = null;
@@ -393,7 +422,7 @@ export function useConnectionStatus(provider: string) {
const setup = async () => {
// Listen to status events
unlisten = await websocketBridge.onStatus((statusData) => {
- if (mounted && statusData.provider === provider) {
+ if (mounted && statusData.provider === normalizedProvider) {
setStatus(statusData);
}
});
@@ -402,7 +431,7 @@ export function useConnectionStatus(provider: string) {
const fetchMetrics = async () => {
if (mounted) {
try {
- const m = await websocketBridge.getMetrics(provider);
+ const m = await websocketBridge.getMetrics(normalizedProvider);
if (m) {
setMetrics(m);
}
@@ -429,7 +458,7 @@ export function useConnectionStatus(provider: string) {
clearInterval(intervalId);
}
};
- }, [provider]);
+ }, [normalizedProvider]);
return { status, metrics };
}
@@ -445,8 +474,9 @@ export function useMultiProviderTicker(providers: string[], symbol: string) {
const subscriptionsRef = useRef<Map<string, { provider: string; symbol: string }>>(new Map());
const listenerRef = useRef<(() => void) | null>(null);
- // Memoize providers string to prevent unnecessary re-renders
- const providersKey = providers.join(',');
+ // Normalize providers to lowercase
+ const normalizedProviders = providers.map(p => p.toLowerCase());
+ const providersKey = normalizedProviders.join(',');
useEffect(() => {
let mounted = true;
@@ -462,14 +492,14 @@ export function useMultiProviderTicker(providers: string[], symbol: string) {
// Unsubscribe from providers no longer in the list
for (const [key, sub] of subscriptionsRef.current.entries()) {
- if (!providers.includes(sub.provider) || sub.symbol !== symbol) {
- await websocketBridge.unsubscribe(sub.provider, sub.symbol, 'ticker').catch(() => {});
+ if (!normalizedProviders.includes(sub.provider) || sub.symbol !== symbol) {
+ await websocketBridge.unsubscribe(sub.provider, sub.symbol, 'ticker').catch((e) => console.warn('[useMultiProviderTicker] unsubscribe error:', e));
subscriptionsRef.current.delete(key);
}
}
- // Subscribe to new providers
- for (const provider of providers) {
+ // Subscribe to new providers (using normalized names)
+ for (const provider of normalizedProviders) {
const key = `${provider}:${symbol}`;
if (!subscriptionsRef.current.has(key)) {
await websocketBridge.subscribe(provider, symbol, 'ticker');
@@ -480,7 +510,7 @@ export function useMultiProviderTicker(providers: string[], symbol: string) {
// Listen to ticker events from all providers
const unlisten = await websocketBridge.onTicker((tickerData) => {
if (!mounted) return;
- if (!providers.includes(tickerData.provider)) return;
+ if (!normalizedProviders.includes(tickerData.provider)) return;
if (normalizeSymbol(tickerData.symbol) !== normalizedInputSymbol) return;
setPrices((prev) => {
@@ -498,7 +528,7 @@ export function useMultiProviderTicker(providers: string[], symbol: string) {
}
};
- if (providers.length > 0 && symbol) {
+ if (normalizedProviders.length > 0 && symbol) {
subscribe();
}
@@ -510,7 +540,7 @@ export function useMultiProviderTicker(providers: string[], symbol: string) {
}
// Unsubscribe from all on cleanup
for (const sub of subscriptionsRef.current.values()) {
- websocketBridge.unsubscribe(sub.provider, sub.symbol, 'ticker').catch(() => {});
+ websocketBridge.unsubscribe(sub.provider, sub.symbol, 'ticker').catch((e) => console.warn('[useMultiProviderTicker] cleanup unsubscribe error:', e));
}
subscriptionsRef.current.clear();
setPrices(new Map());
diff --git a/fincept-terminal-desktop/src/hooks/useTabSession.ts b/fincept-terminal-desktop/src/hooks/useTabSession.ts
index 7b448f26a..7f063b502 100644
--- a/fincept-terminal-desktop/src/hooks/useTabSession.ts
+++ b/fincept-terminal-desktop/src/hooks/useTabSession.ts
@@ -141,7 +141,9 @@ export function useTabSession<T extends object>(
if (saveTimeoutRef.current) {
clearTimeout(saveTimeoutRef.current);
// Synchronous save on unmount is not ideal but ensures data isn't lost
- cacheService.setTabSession(tabId, tabName, stateRef.current).catch(() => {});
+ cacheService.setTabSession(tabId, tabName, stateRef.current).catch((err) => {
+ console.warn(`[useTabSession] Failed to save on unmount for ${tabId}:`, err);
+ });
}
};
}, [tabId, tabName]);
diff --git a/fincept-terminal-desktop/src/services/agentService.ts b/fincept-terminal-desktop/src/services/agentService.ts
index b5841f3de..f548dcad3 100644
--- a/fincept-terminal-desktop/src/services/agentService.ts
+++ b/fincept-terminal-desktop/src/services/agentService.ts
@@ -12,7 +12,6 @@
*/
import { invoke } from '@tauri-apps/api/core';
-import { listen, UnlistenFn } from '@tauri-apps/api/event';
import { mcpToolService } from '@/services/mcp/mcpToolService';
import { INTERNAL_SERVER_ID } from '@/services/mcp/internal';
@@ -164,22 +163,6 @@ export interface ModelsInfo {
}
// Streaming types
-export interface StreamChunk {
- stream_id: string;
- chunk_type: 'token' | 'thinking' | 'tool_call' | 'tool_result' | 'done' | 'error' | 'agent_token' | 'agent_done';
- content: string;
- metadata?: Record<string, any>;
- sequence: number;
-}
-
-export interface StreamHandle {
- streamId: string;
- eventName: string;
- unlisten: UnlistenFn | null;
- cancel: () => Promise<void>;
-}
-
-export type StreamCallback = (chunk: StreamChunk) => void;
// Parallel execution types
export interface ParallelTask {
@@ -440,105 +423,6 @@ async function executeWithPriority<T = any>(
}
}
-// =============================================================================
-// Streaming Operations
-// =============================================================================
-
-/**
- * Run agent with real-time streaming
- * Returns a handle to control the stream
- */
-export async function runAgentStreaming(
- query: string,
- config: AgentConfig,
- apiKeys: Record<string, string>,
- onChunk: StreamCallback,
- sessionId?: string
-): Promise<StreamHandle> {
- const payload = {
- action: 'run',
- api_keys: apiKeys,
- config,
- params: { query, session_id: sessionId },
- };
-
- // Start streaming
- const result = await invoke<string>('execute_agent_streaming', { payload });
- const parsed = JSON.parse(result);
-
- if (!parsed.success) {
- throw new Error(parsed.error || 'Failed to start stream');
- }
-
- const streamId = parsed.stream_id;
- const eventName = parsed.event_name;
-
- // Subscribe to stream events
- const unlisten = await listen<StreamChunk>(eventName, (event) => {
- onChunk(event.payload);
- });
-
- return {
- streamId,
- eventName,
- unlisten,
- cancel: async () => {
- unlisten();
- await invoke('cancel_agent_stream', { streamId });
- },
- };
-}
-
-/**
- * Run team with streaming updates per agent
- */
-export async function runTeamStreaming(
- query: string,
- teamConfig: TeamConfig,
- apiKeys: Record<string, string>,
- onChunk: StreamCallback,
- sessionId?: string
-): Promise<StreamHandle> {
- const payload = {
- action: 'run_team',
- api_keys: apiKeys,
- params: { query, team_config: teamConfig, session_id: sessionId },
- };
-
- const result = await invoke<string>('execute_agent_streaming', { payload });
- const parsed = JSON.parse(result);
-
- if (!parsed.success) {
- throw new Error(parsed.error || 'Failed to start team stream');
- }
-
- const streamId = parsed.stream_id;
- const eventName = parsed.event_name;
-
- const unlisten = await listen<StreamChunk>(eventName, (event) => {
- onChunk(event.payload);
- });
-
- return {
- streamId,
- eventName,
- unlisten,
- cancel: async () => {
- unlisten();
- await invoke('cancel_agent_stream', { streamId });
- },
- };
-}
-
-/**
- * Get all active streams
- */
-export async function getActiveStreams(): Promise<string[]> {
- const result = await invoke<string>('get_active_agent_streams');
- const parsed = JSON.parse(result);
- return parsed.active_streams || [];
-}
-
// =============================================================================
// Parallel Execution
// =============================================================================
@@ -817,37 +701,6 @@ export async function searchKnowledge(
});
}
-// =============================================================================
-// Guardrails & Evaluation
-// =============================================================================
-
-/**
- * Check input against guardrails
- */
-export async function checkGuardrails(
- text: string,
- context?: Record<string, any>
-): Promise<AgentResponse<{ passed: boolean; violations: string[] }>> {
- return execute({
- action: 'check_guardrails',
- params: { text, context, check_type: 'input' },
- });
-}
-
-/**
- * Evaluate agent response
- */
-export async function evaluateResponse(
- query: string,
- response: string,
- context?: Record<string, any>
-): Promise<AgentResponse<{ passed: boolean; score: number; details: any }>> {
- return execute({
- action: 'evaluate',
- params: { query, response, context, type: 'response' },
- });
-}
-
// =============================================================================
// System Information (Cached)
// =============================================================================
@@ -918,35 +771,6 @@ export async function getModels(forceRefresh = false): Promise<ModelsInfo | null
return null;
}
-/**
- * Get available output models (cached)
- */
-export async function getOutputModels(forceRefresh = false): Promise<string[]> {
- const cacheKey = 'output_models';
-
- if (!forceRefresh) {
- const cached = cache.get<string[]>(cacheKey);
- if (cached) return cached;
- }
-
- 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);
- return response.data.models;
- }
-
- // Default output models if API fails
- return [
- 'trade_signal',
- 'stock_analysis',
- 'portfolio_analysis',
- 'risk_assessment',
- 'market_analysis',
- 'research_report',
- ];
-}
-
// =============================================================================
// Workflow Execution
// =============================================================================
@@ -1274,18 +1098,6 @@ export function getCacheStats(): { cacheSize: number; responseCacheSize: number;
return cache.getStats();
}
-/**
- * Pre-warm the agent system (call on app startup)
- */
-export async function prewarmAgent(): Promise<void> {
- // Fetch and cache static data in parallel
- await Promise.all([
- getSystemInfo(),
- getTools(),
- getModels(),
- ]);
-}
-
/**
* Build agent config from UI state — wires ALL CoreAgent features
*/
@@ -1557,6 +1369,26 @@ export async function createStockAnalysisPlan(symbol: string): Promise<Execution
}
}
+/**
+ * Generate a dynamic execution plan using LLM from a natural-language query.
+ * Returns { plan, generated_by } where generated_by is "llm" or "fallback".
+ */
+export async function generateDynamicPlan(
+ query: string,
+ apiKeys?: Record<string, string>
+): Promise<{ plan: ExecutionPlan; generated_by: string } | null> {
+ try {
+ const result = await invoke<string>('generate_dynamic_plan', { query, apiKeys: apiKeys ?? {} });
+ const parsed = JSON.parse(result);
+ if (parsed.success && parsed.plan) {
+ return { plan: parsed.plan as ExecutionPlan, generated_by: parsed.generated_by ?? 'llm' };
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
/**
* Execute an execution plan
*/
@@ -1631,10 +1463,6 @@ export const agentService = {
runAgentStructured,
runTeam,
- // Streaming
- runAgentStreaming,
- runTeamStreaming,
- getActiveStreams,
// Parallel Execution
runAgentsParallel,
@@ -1657,15 +1485,10 @@ export const agentService = {
recallMemories,
searchKnowledge,
- // Guardrails
- checkGuardrails,
- evaluateResponse,
-
// System (cached)
getSystemInfo,
getTools,
getModels,
- getOutputModels,
// SuperAgent & Routing (v2.1)
routeQuery,
@@ -1674,6 +1497,7 @@ export const agentService = {
// Execution Planner (v2.1)
createStockAnalysisPlan,
+ generateDynamicPlan,
executePlan,
// Trade Decisions (v2.1)
@@ -1711,117 +1535,9 @@ export const agentService = {
clearCache,
clearResponseCache,
getCacheStats,
- prewarmAgent,
buildAgentConfig,
buildTeamConfig,
runPortfolioAnalysis,
};
-// =============================================================================
-// Renaissance Technologies Integration
-// =============================================================================
-
-export interface RenTechSignal {
- ticker: string;
- signal_type: string;
- direction: 'long' | 'short';
- strength: number;
- confidence: number;
- p_value: number;
- information_coefficient: number;
-}
-
-export interface RenTechConfig {
- max_position_size_pct?: number;
- max_leverage?: number;
- max_drawdown_pct?: number;
- max_daily_var_pct?: number;
- min_signal_confidence?: number;
-}
-
-export interface RenTechResult {
- success: boolean;
- signal_id?: string;
- statistical_quality?: string;
- risk_assessment?: string;
- ic_decision?: any;
- execution_plan?: any;
- error?: string;
-}
-
-/**
- * Run Renaissance Technologies signal analysis via finagent_core
- */
-export async function runRenaissanceTechnologies(
- signal: RenTechSignal,
- config?: RenTechConfig
-): Promise<RenTechResult> {
- try {
- const query = JSON.stringify({ command: 'analyze_signal', signal, config: config || {} });
- const payload = {
- action: 'run',
- api_keys: {},
- config: {
- model: { provider: 'openai', model_id: 'gpt-4-turbo' },
- instructions: 'You are a quantitative analyst embodying Renaissance Technologies approach. Apply mathematical pattern recognition, statistical arbitrage, and systematic signal analysis.',
- },
- params: { query },
- };
- const result = await invoke<string>('execute_core_agent', { payload });
- const parsed = JSON.parse(result);
- return parsed.data || parsed;
- } catch (error: any) {
- console.error('[RenTech] Analysis failed:', error);
- return { success: false, error: error.message || 'Renaissance Technologies analysis failed' };
- }
-}
-
-/**
- * Run IC Deliberation on a signal via finagent_core
- */
-export async function runICDeliberation(deliberationData: {
- signal: any;
- signal_evaluation: any;
- risk_assessment: any;
- sizing_recommendation: any;
-}): Promise<RenTechResult> {
- try {
- const query = JSON.stringify({ command: 'run_ic_deliberation', data: deliberationData });
- const payload = {
- action: 'run',
- api_keys: {},
- config: {
- model: { provider: 'openai', model_id: 'gpt-4-turbo' },
- instructions: 'You are an Investment Committee member at a quantitative hedge fund. Deliberate on trade signals and provide IC-level decisions with clear reasoning.',
- },
- params: { query },
- };
- const result = await invoke<string>('execute_core_agent', { payload });
- const parsed = JSON.parse(result);
- return { success: true, ic_decision: parsed.data || parsed.response };
- } catch (error: any) {
- console.error('[RenTech] IC deliberation failed:', error);
- return { success: false, error: error.message || 'IC deliberation failed' };
- }
-}
-
-/**
- * Get Renaissance Technologies agent presets via finagent_core
- */
-export async function getRenTechPresets(): Promise<{ agents: any[]; teams: any[] }> {
- try {
- const payload = {
- action: 'list_agents',
- api_keys: {},
- params: { category: 'hedge-fund' },
- };
- const result = await invoke<string>('execute_core_agent', { payload });
- const parsed = JSON.parse(result);
- return parsed.data || { agents: parsed.agents || [], teams: [] };
- } catch (error) {
- console.error('[RenTech] Failed to get presets:', error);
- return { agents: [], teams: [] };
- }
-}
-
export default agentService;
diff --git a/fincept-terminal-desktop/src/services/auth/authApi.tsx b/fincept-terminal-desktop/src/services/auth/authApi.tsx
index 72f0c8c65..7f9dd5167 100644
--- a/fincept-terminal-desktop/src/services/auth/authApi.tsx
+++ b/fincept-terminal-desktop/src/services/auth/authApi.tsx
@@ -5,7 +5,7 @@ import { fetch } from '@tauri-apps/plugin-http';
// API Configuration
const API_CONFIG = {
- BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',
+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',
API_VERSION: 'v1',
CONNECTION_TIMEOUT: 10000,
REQUEST_TIMEOUT: 30000
@@ -55,16 +55,9 @@ interface ResetPasswordRequest {
interface DeviceRegisterRequest {
device_id: string;
- device_name: string;
+ device_name?: string;
platform: string;
- hardware_info: {
- platform: string;
- user_agent: string;
- language: string;
- screen_resolution?: string;
- cpu_cores?: number;
- memory_gb?: number;
- };
+ hardware_info: Record<string, any>;
}
// Response Types
@@ -112,19 +105,15 @@ interface AuthStatusResponse {
platform: string;
requests_today: number;
expires_at: string;
- daily_limit?: number;
};
}
interface DeviceRegisterResponse {
- api_key?: string;
- temp_api_key?: string;
- guest_id?: number;
- device_id?: string;
- expires_at?: string;
- daily_limit?: number;
- requests_today?: number;
- credit_balance?: number;
+ api_key: string;
+ expires_at: string;
+ credit_balance: number;
+ user_type: 'guest';
+ message: string;
}
// Generic API request function
@@ -142,17 +131,26 @@ const makeApiRequest = async <T = any>(
const url = getApiEndpoint(endpoint);
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), API_CONFIG.REQUEST_TIMEOUT);
+
const config: RequestInit = {
method,
headers: defaultHeaders,
mode: 'cors',
+ signal: controller.signal,
};
if (data && (method === 'POST' || method === 'PUT')) {
config.body = JSON.stringify(data);
}
- const response = await fetch(url, config);
+ let response: Response;
+ try {
+ response = await fetch(url, config);
+ } finally {
+ clearTimeout(timeoutId);
+ }
const responseText = await response.text();
@@ -248,10 +246,6 @@ export class AuthApiService {
// Login user
static async login(request: LoginRequest): Promise<ApiResponse<LoginResponse>> {
- console.log('=== LOGIN REQUEST DEBUG ===');
- console.log('Endpoint: /user/login');
- console.log('Request body:', JSON.stringify(request, null, 2));
- console.log('========================');
return makeApiRequest<LoginResponse>('POST', '/user/login', request);
}
@@ -295,16 +289,9 @@ export class AuthApiService {
return makeApiRequest<AuthStatusResponse>('GET', '/auth/status', undefined, headers);
}
- // Register device for guest access
- static async registerDevice(request: DeviceRegisterRequest): Promise<ApiResponse<DeviceRegisterResponse>> {
- return makeApiRequest<DeviceRegisterResponse>('POST', '/guest/register', request);
- }
-
- // Get guest status
- static async getGuestStatus(apiKey: string): Promise<ApiResponse<any>> {
- return makeApiRequest('GET', '/guest/status', undefined, {
- 'X-API-Key': apiKey
- });
+ // Create or renew guest session (idempotent — same device_id returns existing session)
+ static async createGuestSession(request: DeviceRegisterRequest): Promise<ApiResponse<DeviceRegisterResponse>> {
+ return makeApiRequest<DeviceRegisterResponse>('POST', '/guest/session', request);
}
// Update user profile
diff --git a/fincept-terminal-desktop/src/services/auth/userApi.tsx b/fincept-terminal-desktop/src/services/auth/userApi.tsx
index 9a637f737..6c57f54d5 100644
--- a/fincept-terminal-desktop/src/services/auth/userApi.tsx
+++ b/fincept-terminal-desktop/src/services/auth/userApi.tsx
@@ -5,7 +5,7 @@ import { fetch as tauriFetch } from '@tauri-apps/plugin-http';
// API Configuration - always use full URL for Tauri fetch
const API_CONFIG = {
- BASE_URL: 'https://finceptbackend.share.zrok.io',
+ BASE_URL: 'https://api.fincept.in',
};
const getApiEndpoint = (path: string) => `${API_CONFIG.BASE_URL}${path}`;
@@ -20,6 +20,8 @@ interface ApiResponse<T = any> {
status_code: number;
}
+const REQUEST_TIMEOUT_MS = 30000;
+
// Generic API request handler
async function makeApiRequest<T = any>(
endpoint: string,
@@ -28,19 +30,28 @@ async function makeApiRequest<T = any>(
body?: any
): Promise<ApiResponse<T>> {
try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
+
const options: RequestInit = {
method,
headers: {
'Content-Type': 'application/json',
'X-API-Key': apiKey,
},
+ signal: controller.signal,
};
if (body && (method === 'POST' || method === 'PUT')) {
options.body = JSON.stringify(body);
}
- const response = await safeFetch(getApiEndpoint(endpoint), options);
+ let response: Response;
+ try {
+ response = await safeFetch(getApiEndpoint(endpoint), options);
+ } finally {
+ clearTimeout(timeoutId);
+ }
const data = await response.json();
return {
@@ -125,26 +136,6 @@ export class UserApiService {
return makeApiRequest(`/payment/payments/${paymentUuid}`, 'GET', apiKey);
}
- // ========================
- // GUEST USER ENDPOINTS
- // ========================
-
- static async getGuestStatus(apiKey: string): Promise<ApiResponse> {
- return makeApiRequest('/guest/status', 'GET', apiKey);
- }
-
- static async extendGuestSession(apiKey: string): Promise<ApiResponse> {
- return makeApiRequest('/guest/extend', 'POST', apiKey);
- }
-
- static async getGuestUsage(apiKey: string): Promise<ApiResponse> {
- return makeApiRequest('/guest/usage', 'GET', apiKey);
- }
-
- static async deleteGuestSession(apiKey: string): Promise<ApiResponse> {
- return makeApiRequest('/guest/session', 'DELETE', apiKey);
- }
-
// ========================
// SUPPORT & TICKETS
// ========================
diff --git a/fincept-terminal-desktop/src/services/cache/cacheService.ts b/fincept-terminal-desktop/src/services/cache/cacheService.ts
index 62b5e3abd..f9bf23369 100644
--- a/fincept-terminal-desktop/src/services/cache/cacheService.ts
+++ b/fincept-terminal-desktop/src/services/cache/cacheService.ts
@@ -206,10 +206,16 @@ export class CacheService {
try {
const entry = await invoke<CacheEntry | null>('cache_get', { key });
if (!entry) return null;
- return {
- data: JSON.parse(entry.data) as T,
- isStale: entry.is_expired,
- };
+ try {
+ return {
+ data: JSON.parse(entry.data) as T,
+ isStale: entry.is_expired,
+ };
+ } catch (parseError) {
+ console.warn(`[CacheService] Corrupted cache entry for key "${key}", deleting:`, parseError);
+ await this.delete(key).catch(() => {});
+ return null;
+ }
} catch (error) {
console.error('[CacheService] get error:', error);
return null;
@@ -225,10 +231,16 @@ export class CacheService {
try {
const entry = await invoke<CacheEntry | null>('cache_get_with_stale', { key });
if (!entry) return null;
- return {
- data: JSON.parse(entry.data) as T,
- isStale: entry.is_expired,
- };
+ try {
+ return {
+ data: JSON.parse(entry.data) as T,
+ isStale: entry.is_expired,
+ };
+ } catch (parseError) {
+ console.warn(`[CacheService] Corrupted stale cache entry for key "${key}", deleting:`, parseError);
+ await this.delete(key).catch(() => {});
+ return null;
+ }
} catch (error) {
console.error('[CacheService] getWithStale error:', error);
return null;
@@ -294,7 +306,7 @@ export class CacheService {
try {
result.set(entry.cache_key, JSON.parse(entry.data) as T);
} catch {
- // Skip invalid entries
+ console.warn(`[CacheService] Skipping corrupted entry: ${entry.cache_key}`);
}
}
return result;
@@ -496,7 +508,13 @@ export class CacheService {
try {
const session = await invoke<TabSession | null>('tab_session_get', { tabId });
if (!session) return null;
- return JSON.parse(session.state) as T;
+ try {
+ return JSON.parse(session.state) as T;
+ } catch (parseError) {
+ console.warn(`[CacheService] Corrupted tab session for "${tabId}", deleting:`, parseError);
+ await this.deleteTabSession(tabId).catch(() => {});
+ return null;
+ }
} catch (error) {
console.error('[CacheService] getTabSession error:', error);
return null;
diff --git a/fincept-terminal-desktop/src/services/chat/llmApi.ts b/fincept-terminal-desktop/src/services/chat/llmApi.ts
index 4960d55fc..bfde07be0 100644
--- a/fincept-terminal-desktop/src/services/chat/llmApi.ts
+++ b/fincept-terminal-desktop/src/services/chat/llmApi.ts
@@ -533,7 +533,7 @@ class LLMApiService {
config: LLMConfig,
onStream?: StreamCallback
): Promise<LLMResponse> {
- const url = config.baseUrl || 'https://finceptbackend.share.zrok.io/research/llm';
+ const url = config.baseUrl || 'https://api.fincept.in/research/llm';
try {
// Build full prompt including system message and conversation history
@@ -1028,7 +1028,7 @@ Mention the year-over-year growth percentages when discussing financial performa
onStream?: StreamCallback,
onToolCall?: (toolName: string, args: any, result?: any) => void
): Promise<LLMResponse> {
- const url = config.baseUrl || 'https://finceptbackend.share.zrok.io/research/llm';
+ const url = config.baseUrl || 'https://api.fincept.in/research/llm';
try {
// Build full prompt
diff --git a/fincept-terminal-desktop/src/services/chat/pythonAgentService.ts b/fincept-terminal-desktop/src/services/chat/pythonAgentService.ts
index c56d70821..f946c9258 100644
--- a/fincept-terminal-desktop/src/services/chat/pythonAgentService.ts
+++ b/fincept-terminal-desktop/src/services/chat/pythonAgentService.ts
@@ -1,7 +1,7 @@
// Python Agent Service - Interface to execute Python agents via finagent_core
import { invoke } from '@tauri-apps/api/core';
import { pythonAgentLogger } from '../core/loggerService';
-import { getLLMConfigs } from '../core/sqliteService';
+import { buildApiKeysMap, getLLMConfigs } from '../core/sqliteService';
export interface AgentParameter {
name: string;
label: string;
@@ -53,18 +53,7 @@ const AGENT_INSTRUCTIONS_FALLBACK: Record<string, string> = {
};
async function buildApiKeys(): Promise<Record<string, string>> {
- try {
- const configs = await getLLMConfigs();
- const apiKeys: Record<string, string> = {};
- for (const config of configs) {
- if (config.api_key) {
- apiKeys[config.provider.toUpperCase() + '_API_KEY'] = config.api_key;
- apiKeys[config.provider] = config.api_key;
- }
- if (config.base_url) apiKeys[config.provider.toUpperCase() + '_BASE_URL'] = config.base_url;
- }
- return apiKeys;
- } catch { return {}; }
+ return buildApiKeysMap();
}
function extractQuery(parameters: Record<string, any>, inputs: Record<string, any>): string {
diff --git a/fincept-terminal-desktop/src/services/core/apiUtils.ts b/fincept-terminal-desktop/src/services/core/apiUtils.ts
index 3e1506cc3..698f1cdc2 100644
--- a/fincept-terminal-desktop/src/services/core/apiUtils.ts
+++ b/fincept-terminal-desktop/src/services/core/apiUtils.ts
@@ -219,36 +219,32 @@ interface PendingRequest<T> {
}
const pendingRequests = new Map<string, PendingRequest<unknown>>();
-const DEDUP_WINDOW_MS = 100;
+const DEDUP_WINDOW_MS = 2000;
/**
- * Deduplicate concurrent requests with the same key
+ * Deduplicate identical concurrent requests within a time window.
+ * If a request with the same key is already in-flight, returns the existing promise.
*/
export async function deduplicatedFetch<T>(
key: string,
- fn: () => Promise<T>
+ fn: () => Promise<T>,
): Promise<T> {
const now = Date.now();
-
- // Check for existing request
const existing = pendingRequests.get(key);
+
if (existing && now - existing.timestamp < DEDUP_WINDOW_MS) {
return existing.promise as Promise<T>;
}
- // Create new request
- const promise = fn();
- pendingRequests.set(key, { promise, timestamp: now });
+ const promise = fn().finally(() => {
+ // Clean up after completion
+ const current = pendingRequests.get(key);
+ if (current && current.promise === promise) {
+ pendingRequests.delete(key);
+ }
+ });
- try {
- return await promise;
- } finally {
- // Cleanup after window
- setTimeout(() => {
- const current = pendingRequests.get(key);
- if (current?.promise === promise) {
- pendingRequests.delete(key);
- }
- }, DEDUP_WINDOW_MS);
- }
+ pendingRequests.set(key, { promise, timestamp: now });
+ return promise;
}
+
diff --git a/fincept-terminal-desktop/src/services/core/nodeExecutionManager.ts b/fincept-terminal-desktop/src/services/core/nodeExecutionManager.ts
index 08ad4d8af..49e92e99c 100644
--- a/fincept-terminal-desktop/src/services/core/nodeExecutionManager.ts
+++ b/fincept-terminal-desktop/src/services/core/nodeExecutionManager.ts
@@ -6,6 +6,7 @@ import { mcpToolService } from '../mcp/mcpToolService';
import { agentLLMService } from '../chat/agentLLMService';
import { backtestingService } from '../backtesting/BacktestingService';
import { MarketDataBridge } from '../nodeSystem/adapters/MarketDataBridge';
+import { NodeRegistry } from '../nodeSystem/NodeRegistry';
import { nodeLogger } from './loggerService';
export type NodeStatus = 'idle' | 'running' | 'completed' | 'error';
@@ -19,6 +20,9 @@ export interface ExecutionResult {
}
class NodeExecutionManager {
+ /** Terminal timezone IANA string (e.g. "Asia/Kolkata"), set per workflow execution */
+ private terminalTimezone: string | undefined;
+
/**
* Topological sort of nodes based on edges
*/
@@ -68,7 +72,12 @@ class NodeExecutionManager {
// Check for cycles
if (sorted.length !== nodes.length) {
- throw new Error('Workflow contains cycles - cannot execute');
+ const cycleNodeIds = nodes
+ .filter(n => !sorted.find(s => s.id === n.id))
+ .map(n => n.data?.label || n.id);
+ throw new Error(
+ `Workflow contains cycles involving nodes: ${cycleNodeIds.join(', ')}. Remove circular connections to proceed.`
+ );
}
return sorted;
@@ -509,6 +518,85 @@ class NodeExecutionManager {
}
}
+ /**
+ * Execute a trigger node via its registry execute() method.
+ * Creates a minimal IExecuteFunctions context so the node can read its parameters.
+ */
+ private async executeTriggerNode(
+ node: Node,
+ nodeTypeName: string,
+ parameters: Record<string, any>,
+ startTime: number
+ ): Promise<ExecutionResult> {
+ try {
+ const registryNode = NodeRegistry.getNodeType(nodeTypeName);
+ if (!registryNode.execute) {
+ return {
+ nodeId: node.id,
+ success: true,
+ data: { triggered: true, trigger: nodeTypeName, timestamp: new Date().toISOString(), ...parameters },
+ };
+ }
+
+ // Build a minimal IExecuteFunctions context for the trigger node
+ const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
+ const terminalTz = this.terminalTimezone;
+ const context = {
+ getNodeParameter: (paramName: string, _itemIndex: number, fallbackValue?: any) => {
+ // For timezone parameters, prefer the user's explicit value, then terminal timezone, then node default
+ if (paramName === 'timezone') {
+ if (parameters[paramName] !== undefined) return parameters[paramName];
+ if (terminalTz) return terminalTz;
+ }
+ if (parameters[paramName] !== undefined) return parameters[paramName];
+ // Fall back to the node description's default value
+ const prop = registryNode.description.properties.find((p) => p.name === paramName);
+ if (prop && prop.default !== undefined) return prop.default;
+ return fallbackValue;
+ },
+ getExecutionId: () => executionId,
+ getNode: () => ({ id: node.id, name: node.data?.label || nodeTypeName, type: nodeTypeName, typeVersion: 1, position: [0, 0] as [number, number], parameters }),
+ getWorkflow: () => null,
+ getWorkflowId: () => 'workflow_' + node.id,
+ continueOnFail: () => false,
+ evaluateExpression: (expr: string) => expr,
+ getInputData: () => [],
+ helpers: {} as any,
+ getCredentials: async () => ({}),
+ getExecutionCancelSignal: () => new AbortController().signal,
+ getInputConnectionData: async () => null,
+ addExecutionHints: () => {},
+ };
+
+ const result = await registryNode.execute.call(context as any);
+
+ // The execute() method returns NodeOutput = INodeExecutionData[][]
+ // Extract the JSON data from the first output item
+ const outputData = result?.[0]?.[0]?.json || {};
+
+ // Inject the effective timezone used into the output
+ if (terminalTz && !outputData.terminalTimezone) {
+ outputData.terminalTimezone = terminalTz;
+ }
+
+ return {
+ nodeId: node.id,
+ success: true,
+ data: outputData,
+ execution_time_ms: Math.round(performance.now() - startTime),
+ };
+ } catch (error: any) {
+ nodeLogger.error(`Trigger node ${nodeTypeName} execution failed:`, error);
+ // Fall back to simple trigger metadata if registry execution fails
+ return {
+ nodeId: node.id,
+ success: true,
+ data: { triggered: true, trigger: nodeTypeName, timestamp: new Date().toISOString(), ...parameters, warning: error.message },
+ execution_time_ms: Math.round(performance.now() - startTime),
+ };
+ }
+ }
+
/**
* Execute custom node - handles registry-based nodes (manualTrigger, getQuote, getHistoricalData, filter, sort, etc.)
*/
@@ -522,13 +610,10 @@ class NodeExecutionManager {
nodeLogger.info(`Executing custom node: ${nodeTypeName || 'unknown'}`, { nodeId: node.id });
- // Manual trigger - just emits a signal to start the workflow
- if (nodeTypeName === 'manualTrigger') {
- return {
- nodeId: node.id,
- success: true,
- data: { triggered: true, timestamp: new Date().toISOString(), ...parameters }
- };
+ // Trigger nodes — delegate to the registry node's execute() method
+ const triggerTypes = ['manualTrigger', 'scheduleTrigger', 'priceAlertTrigger', 'marketEventTrigger', 'newsEventTrigger'];
+ if (triggerTypes.includes(nodeTypeName || '')) {
+ return this.executeTriggerNode(node, nodeTypeName!, parameters, startTime);
}
// Get Quote - fetch actual stock quote data via MarketDataBridge
@@ -709,17 +794,16 @@ class NodeExecutionManager {
};
} catch (error: any) {
const executionTime = Math.round(performance.now() - startTime);
- nodeLogger.warn('Technical indicator Python execution failed, returning config:', error);
+ nodeLogger.warn('Technical indicator Python execution failed:', error);
- // Return the config summary so the results display still shows something
return {
nodeId: node.id,
- success: true,
+ success: false,
+ error: `Technical indicator failed: ${error.message || 'Python runtime unavailable'}`,
data: {
symbol: symbol || 'AAPL',
period: period || '1y',
categories: categories || ['momentum', 'trend'],
- note: 'Python runtime unavailable - showing configuration',
...(Object.keys(inputs).length > 0 ? { upstreamData: inputs } : {}),
},
execution_time_ms: executionTime,
@@ -770,16 +854,16 @@ class NodeExecutionManager {
execution_time_ms: Math.round(performance.now() - startTime),
};
} catch (error: any) {
- nodeLogger.warn('Backtest execution failed, returning config summary:', error);
+ nodeLogger.warn('Backtest execution failed:', error);
return {
nodeId: node.id,
- success: true,
+ success: false,
+ error: `Backtest failed: ${error.message || 'Backtesting provider unavailable'}`,
data: {
strategy: parameters.strategy || 'MA_Crossover',
initialCapital: parameters.initialCapital || 100000,
commission: parameters.commission || 0.001,
- note: 'Backtesting provider unavailable - showing configuration summary',
parameters,
inputData: Object.keys(inputs).length > 0 ? inputs : undefined,
},
@@ -835,15 +919,15 @@ class NodeExecutionManager {
execution_time_ms: Math.round(performance.now() - startTime),
};
} catch (error: any) {
- nodeLogger.warn('Optimization execution failed, returning config summary:', error);
+ nodeLogger.warn('Optimization execution failed:', error);
return {
nodeId: node.id,
- success: true,
+ success: false,
+ error: `Optimization failed: ${error.message || 'Optimization provider unavailable'}`,
data: {
method: parameters.method || 'grid',
objective: parameters.objective || 'sharpe_ratio',
- note: 'Optimization provider unavailable - showing configuration summary',
parameters,
inputData: Object.keys(inputs).length > 0 ? inputs : undefined,
},
@@ -895,17 +979,42 @@ class NodeExecutionManager {
};
}
+ /**
+ * Execute a node with a timeout
+ */
+ private executeWithTimeout(
+ node: Node,
+ inputs: Record<string, any>,
+ timeoutMs: number = 30000
+ ): Promise<ExecutionResult> {
+ return Promise.race([
+ this.executeNode(node, inputs),
+ new Promise<ExecutionResult>((_, reject) =>
+ setTimeout(() => reject(new Error(`Node execution timed out after ${timeoutMs / 1000}s`)), timeoutMs)
+ ),
+ ]);
+ }
+
/**
* Execute entire workflow
*/
async executeWorkflow(
nodes: Node[],
edges: Edge[],
- onNodeStatusChange: (nodeId: string, status: NodeStatus, result?: any) => void
+ onNodeStatusChange: (nodeId: string, status: NodeStatus, result?: any) => void,
+ terminalTimezone?: string
): Promise<Map<string, any>> {
- // Topological sort
+ this.terminalTimezone = terminalTimezone;
+
+ if (nodes.length === 0) {
+ nodeLogger.warn('No nodes to execute');
+ return new Map();
+ }
+
+ // Topological sort (throws on cycles with descriptive message)
const sortedNodes = this.topologicalSort(nodes, edges);
const results = new Map<string, any>();
+ let hasErrors = false;
nodeLogger.info('Executing workflow with nodes:', sortedNodes.map(n => n.id));
@@ -919,23 +1028,46 @@ class NodeExecutionManager {
const inputs = this.getNodeInputs(node, edges, results);
nodeLogger.debug(`Node ${node.id} inputs:`, inputs);
- // Execute node
- const result = await this.executeNode(node, inputs);
+ // Execute node with timeout
+ let result: ExecutionResult;
+ try {
+ const nodeTimeout = typeof node.data?.timeoutMs === 'number' ? node.data.timeoutMs : undefined;
+ result = await this.executeWithTimeout(node, inputs, nodeTimeout);
+ } catch (error: any) {
+ result = {
+ nodeId: node.id,
+ success: false,
+ error: error.message || 'Unknown error',
+ };
+ }
nodeLogger.debug(`Node ${node.id} result:`, result);
- // Store result
- results.set(node.id, result.data);
+ // Store result (even on failure, so downstream nodes can see error data)
+ results.set(node.id, result.data ?? { error: result.error });
// Update status
if (result.success) {
onNodeStatusChange(node.id, 'completed', result.data);
} else {
- onNodeStatusChange(node.id, 'error', result.error);
- throw new Error(`Node ${node.id} failed: ${result.error}`);
+ onNodeStatusChange(node.id, 'error', { error: result.error, data: result.data });
+ hasErrors = true;
+
+ // Check continueOnFail
+ const continueOnFail = node.data?.continueOnFail === true;
+ if (!continueOnFail) {
+ nodeLogger.error(`Node ${node.id} failed, stopping workflow: ${result.error}`);
+ // Mark remaining nodes as idle
+ const remainingNodes = sortedNodes.slice(sortedNodes.indexOf(node) + 1);
+ for (const remaining of remainingNodes) {
+ onNodeStatusChange(remaining.id, 'idle');
+ }
+ throw new Error(`Node ${node.data?.label || node.id} failed: ${result.error}`);
+ }
+ nodeLogger.warn(`Node ${node.id} failed but continueOnFail is set, continuing: ${result.error}`);
}
}
- nodeLogger.info('Workflow completed successfully');
+ nodeLogger.info(`Workflow completed${hasErrors ? ' with errors' : ' successfully'}`);
return results;
}
}
diff --git a/fincept-terminal-desktop/src/services/core/sqliteService.ts b/fincept-terminal-desktop/src/services/core/sqliteService.ts
index b5e783ba3..e0d4bd7e4 100644
--- a/fincept-terminal-desktop/src/services/core/sqliteService.ts
+++ b/fincept-terminal-desktop/src/services/core/sqliteService.ts
@@ -63,7 +63,7 @@ export const LLM_PROVIDERS = [
id: 'fincept',
name: 'Fincept LLM',
description: 'Fincept Research API (Default - 5 credits/response)',
- endpoint: 'https://finceptbackend.share.zrok.io/research/llm',
+ endpoint: 'https://api.fincept.in/research/llm',
requiresApiKey: true,
isDefault: true,
models: ['fincept-llm']
@@ -228,6 +228,49 @@ export const getActiveLLMConfig = async (): Promise<LLMConfig | null> => {
return configs.find(c => c.is_active) || null;
};
+/**
+ * Build a complete api_keys map from LLM configs — the canonical implementation.
+ * Matches exactly what useAgentConfig.getApiKeys() does so all panels behave the same.
+ *
+ * Keys emitted per provider:
+ * OPENAI_API_KEY, openai, openai_base_url, OPENAI_BASE_URL, …
+ * Plus fincept fallback from the stored session key.
+ */
+export const buildApiKeysMap = async (): Promise<Record<string, string>> => {
+ try {
+ const llmConfigs = await getLLMConfigs();
+ const apiKeys: Record<string, string> = {};
+
+ for (const config of llmConfigs) {
+ if (config.api_key) {
+ const providerUpper = config.provider.toUpperCase();
+ apiKeys[`${providerUpper}_API_KEY`] = config.api_key;
+ apiKeys[config.provider] = config.api_key;
+ apiKeys[config.provider.toLowerCase()] = config.api_key;
+ }
+ if (config.base_url) {
+ const providerUpper = config.provider.toUpperCase();
+ apiKeys[`${providerUpper}_BASE_URL`] = config.base_url;
+ apiKeys[`${config.provider}_base_url`] = config.base_url;
+ }
+ }
+
+ // Fincept session key — always include so Python agents can use the
+ // fincept provider even if the user hasn't added it in LLM Settings.
+ if (!apiKeys['fincept']) {
+ const finceptKey = await getSetting('fincept_api_key');
+ if (finceptKey) {
+ apiKeys['fincept'] = finceptKey;
+ apiKeys['FINCEPT_API_KEY'] = finceptKey;
+ }
+ }
+
+ return apiKeys;
+ } catch {
+ return {};
+ }
+};
+
export const getLLMGlobalSettings = async (): Promise<LLMGlobalSettings> => {
return await invoke<LLMGlobalSettings>('db_get_llm_global_settings');
};
@@ -1210,6 +1253,7 @@ class SqliteService {
getActiveLLMConfig = getActiveLLMConfig;
getLLMGlobalSettings = getLLMGlobalSettings;
saveLLMGlobalSettings = saveLLMGlobalSettings;
+ buildApiKeysMap = buildApiKeysMap;
async ensureDefaultLLMConfigs() {
// Not needed with Rust backend - schema handles defaults
diff --git a/fincept-terminal-desktop/src/services/core/validators.ts b/fincept-terminal-desktop/src/services/core/validators.ts
index 80cc3bf02..cd8d3955c 100644
--- a/fincept-terminal-desktop/src/services/core/validators.ts
+++ b/fincept-terminal-desktop/src/services/core/validators.ts
@@ -176,27 +176,6 @@ export function validateNumber(
return { valid: true };
}
-/**
- * Validate a price value
- */
-export function validatePrice(value: unknown): ValidationResult {
- return validateNumber(value, { positive: true, allowZero: false });
-}
-
-/**
- * Validate a quantity value
- */
-export function validateQuantity(value: unknown): ValidationResult {
- return validateNumber(value, { positive: true, integer: true, allowZero: false });
-}
-
-/**
- * Validate a percentage value (0-100)
- */
-export function validatePercentage(value: unknown): ValidationResult {
- return validateNumber(value, { min: 0, max: 100 });
-}
-
// ============================================================================
// String Validation & Sanitization
// ============================================================================
@@ -252,15 +231,6 @@ export function sanitizeInput(input: string): string {
.replace(/[\x00-\x1F\x7F]/g, ''); // Remove control characters
}
-/**
- * Sanitize for SQL-like operations (basic protection)
- */
-export function sanitizeForQuery(input: string): string {
- return sanitizeInput(input)
- .replace(/['";\\]/g, '') // Remove quotes and backslashes
- .replace(/--/g, ''); // Remove SQL comments
-}
-
// ============================================================================
// Email Validation
// ============================================================================
@@ -333,33 +303,3 @@ export function validateDateRange(
return { valid: true };
}
-// ============================================================================
-// Composite Validation Helper
-// ============================================================================
-
-type ValidatorFn = (value: unknown) => ValidationResult;
-
-/**
- * Compose multiple validators
- */
-export function composeValidators(...validators: ValidatorFn[]): ValidatorFn {
- return (value: unknown) => {
- for (const validator of validators) {
- const result = validator(value);
- if (!result.valid) return result;
- }
- return { valid: true };
- };
-}
-
-/**
- * Create a required field validator
- */
-export function required(fieldName: string): ValidatorFn {
- return (value: unknown) => {
- if (value === null || value === undefined || value === '') {
- return { valid: false, error: `${fieldName} is required` };
- }
- return { valid: true };
- };
-}
diff --git a/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts b/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts
index 58a12ce2a..4ca9c26af 100644
--- a/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts
+++ b/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts
@@ -37,7 +37,7 @@ class ChatModeApiService {
private apiKey: string | null = null;
constructor() {
- this.baseUrl = import.meta.env.VITE_API_URL || 'https://finceptbackend.share.zrok.io';
+ this.baseUrl = import.meta.env.VITE_API_URL || 'https://api.fincept.in';
}
/**
diff --git a/fincept-terminal-desktop/src/services/forum/forumApi.tsx b/fincept-terminal-desktop/src/services/forum/forumApi.tsx
index 6c10f6af6..8428a4b88 100644
--- a/fincept-terminal-desktop/src/services/forum/forumApi.tsx
+++ b/fincept-terminal-desktop/src/services/forum/forumApi.tsx
@@ -5,7 +5,7 @@ import { fetch } from '@tauri-apps/plugin-http';
// API Configuration - matches your existing auth setup
const API_CONFIG = {
- BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',
+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',
API_VERSION: 'v1',
CONNECTION_TIMEOUT: 10000,
REQUEST_TIMEOUT: 30000
diff --git a/fincept-terminal-desktop/src/services/forum/supportApi.tsx b/fincept-terminal-desktop/src/services/forum/supportApi.tsx
index 6986f38ac..f8be6f09a 100644
--- a/fincept-terminal-desktop/src/services/forum/supportApi.tsx
+++ b/fincept-terminal-desktop/src/services/forum/supportApi.tsx
@@ -5,7 +5,7 @@ import { fetch } from '@tauri-apps/plugin-http';
// API Configuration
const API_CONFIG = {
- BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',
+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',
};
const getApiEndpoint = (path: string) => `${API_CONFIG.BASE_URL}${path}`;
diff --git a/fincept-terminal-desktop/src/services/maAnalyticsService.ts b/fincept-terminal-desktop/src/services/maAnalyticsService.ts
index a54d3915c..a85f416e3 100644
--- a/fincept-terminal-desktop/src/services/maAnalyticsService.ts
+++ b/fincept-terminal-desktop/src/services/maAnalyticsService.ts
@@ -28,14 +28,23 @@ export interface MADeal {
deal_value: number;
offer_price_per_share?: number;
premium_1day: number;
+ payment_method?: string;
payment_cash_pct: number;
payment_stock_pct: number;
ev_revenue?: number;
ev_ebitda?: number;
synergies?: number;
status: string;
+ deal_type?: string;
industry: string;
announced_date: string;
+ expected_close_date?: string;
+ breakup_fee?: number;
+ hostile_flag?: number;
+ tender_offer_flag?: number;
+ cross_border_flag?: number;
+ acquirer_country?: string;
+ target_country?: string;
}
export interface ValuationResult {
@@ -250,22 +259,43 @@ export class DealDatabaseService {
const parsed = JSON.parse(result as string);
if (parsed.success) {
// Map DB column names to MADeal interface
- return (parsed.data || []).map((d: any) => ({
- deal_id: d.deal_id || '',
- target_name: d.target_name || '',
- acquirer_name: d.acquirer_name || '',
- deal_value: d.deal_value || 0,
- offer_price_per_share: d.offer_price_per_share,
- premium_1day: d.premium_1day || 0,
- payment_cash_pct: d.cash_percentage ?? d.payment_cash_pct ?? 0,
- payment_stock_pct: d.stock_percentage ?? d.payment_stock_pct ?? 0,
- ev_revenue: d.ev_revenue,
- ev_ebitda: d.ev_ebitda,
- synergies: d.synergies_disclosed ?? d.synergies,
- status: d.deal_status || d.status || 'Unknown',
- industry: d.industry || 'General',
- announced_date: d.announcement_date || d.announced_date || '',
- }));
+ return (parsed.data || []).map((d: any) => {
+ const paymentMethod: string = d.payment_method || '';
+ // Derive cash/stock percentages from stored columns first, then fall back to payment_method string
+ let cashPct: number = d.cash_percentage ?? d.payment_cash_pct ?? null;
+ let stockPct: number = d.stock_percentage ?? d.payment_stock_pct ?? null;
+ if (cashPct === null && stockPct === null) {
+ if (paymentMethod === 'Cash') { cashPct = 100; stockPct = 0; }
+ else if (paymentMethod === 'Stock') { cashPct = 0; stockPct = 100; }
+ else if (paymentMethod === 'Mixed') { cashPct = 50; stockPct = 50; }
+ else { cashPct = 0; stockPct = 0; }
+ }
+ return {
+ deal_id: d.deal_id || '',
+ target_name: d.target_name || '',
+ acquirer_name: d.acquirer_name || '',
+ deal_value: d.deal_value || 0,
+ offer_price_per_share: d.offer_price_per_share ?? undefined,
+ premium_1day: d.premium_1day || 0,
+ payment_method: paymentMethod,
+ payment_cash_pct: cashPct ?? 0,
+ payment_stock_pct: stockPct ?? 0,
+ ev_revenue: d.ev_revenue ?? undefined,
+ ev_ebitda: d.ev_ebitda ?? undefined,
+ synergies: d.synergies_disclosed ?? d.synergies ?? undefined,
+ status: d.deal_status || d.status || 'Unknown',
+ deal_type: d.deal_type || undefined,
+ industry: d.industry || 'General',
+ announced_date: d.announcement_date || d.announced_date || '',
+ expected_close_date: d.expected_close_date || undefined,
+ breakup_fee: d.breakup_fee ?? undefined,
+ hostile_flag: d.hostile_flag ?? undefined,
+ tender_offer_flag: d.tender_offer_flag ?? undefined,
+ cross_border_flag: d.cross_border_flag ?? undefined,
+ acquirer_country: d.acquirer_country || undefined,
+ target_country: d.target_country || undefined,
+ };
+ });
} else {
throw new Error(parsed.error || 'Failed to get deals');
}
@@ -652,7 +682,9 @@ export class StartupValuationService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Berkus valuation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ // Normalize: Python returns total_valuation, frontend expects valuation
+ return { ...d, valuation: d.total_valuation ?? d.valuation ?? 0 };
}
/**
@@ -670,7 +702,9 @@ export class StartupValuationService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Scorecard valuation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ // Normalize: Python returns final_valuation, frontend expects valuation
+ return { ...d, valuation: d.final_valuation ?? d.valuation ?? 0 };
}
/**
@@ -692,7 +726,12 @@ export class StartupValuationService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'VC method valuation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ // Normalize: Python returns investor_ownership_pct (0-100), frontend expects ownership_percentage (0-1)
+ return {
+ ...d,
+ ownership_percentage: (d.investor_ownership_pct ?? 0) / 100,
+ };
}
/**
@@ -712,7 +751,16 @@ export class StartupValuationService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'First Chicago valuation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ // Normalize: Python returns expected_present_value, frontend checks weighted_valuation
+ // Also extract scenario_values array for display
+ return {
+ ...d,
+ weighted_valuation: d.expected_present_value ?? d.weighted_valuation ?? d.valuation ?? 0,
+ scenario_values: Array.isArray(d.scenarios)
+ ? d.scenarios.map((s: any) => s.present_value ?? s.exit_value ?? 0)
+ : [],
+ };
}
/**
@@ -728,7 +776,13 @@ export class StartupValuationService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Risk factor valuation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ // Normalize: Python returns final_valuation and base_valuation, frontend expects adjusted_valuation
+ return {
+ ...d,
+ adjusted_valuation: d.final_valuation ?? d.adjusted_valuation ?? 0,
+ base_valuation: d.base_valuation ?? 0,
+ };
}
/**
@@ -751,7 +805,13 @@ export class StartupValuationService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Comprehensive startup valuation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ // Normalize: Python returns valuations_by_method, frontend expects methods
+ // Each method entry has {valuation, method, applicability, details}
+ return {
+ ...d,
+ methods: d.valuations_by_method ?? d.methods ?? {},
+ };
}
/**
@@ -961,7 +1021,19 @@ export class FairnessOpinionService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Fairness opinion generation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ const wvr = d.weighted_valuation_range || {};
+ // Normalize: build valuation_summary that the frontend expects
+ return {
+ ...d,
+ valuation_summary: {
+ average: wvr.midpoint ?? 0,
+ median: wvr.midpoint ?? 0,
+ range_low: wvr.low ?? 0,
+ range_high: wvr.high ?? 0,
+ ...(d.valuation_summary || {}),
+ },
+ };
}
/**
@@ -979,7 +1051,21 @@ export class FairnessOpinionService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Premium fairness analysis failed');
- return parsed.data;
+ const d = parsed.data || {};
+ // Python returns premiums_to_unaffected.{1_day,5_day,20_day,60_day}
+ // Frontend checks premium_1day, premium_1week, premium_1month, premium_52week_high
+ const pu = d.premiums_to_unaffected || {};
+ // Also handle calculate_premiums format: premiums.{1_day,1_week,1_month}.premium_pct
+ const cp = d.premiums || {};
+ const getPremium = (puKey: string, cpKey: string) =>
+ pu[puKey] ?? cp[cpKey]?.premium_pct ?? undefined;
+ return {
+ ...d,
+ premium_1day: getPremium('1_day', '1_day'),
+ premium_1week: getPremium('5_day', '1_week'),
+ premium_1month: getPremium('20_day', '1_month'),
+ premium_52week_high: getPremium('60_day', '52_week'),
+ };
}
/**
@@ -993,7 +1079,15 @@ export class FairnessOpinionService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Process quality assessment failed');
- return parsed.data;
+ const d = parsed.data || {};
+ // For flat input mode, overall_score is already 1-5. For nested, we computed it.
+ // For nested without comprehensive (missing data), compute from available component scores.
+ const comprehensiveScore = d.comprehensive?.overall_process_score;
+ return {
+ ...d,
+ overall_score: d.overall_score ?? (comprehensiveScore != null ? comprehensiveScore / 20 : undefined),
+ factor_scores: d.factor_scores ?? {},
+ };
}
}
@@ -1015,7 +1109,14 @@ export class IndustryMetricsService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Tech metrics calculation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ // Ensure standard output fields are always present
+ return {
+ ...d,
+ valuation_metrics: d.valuation_metrics ?? {},
+ benchmarks: d.benchmarks ?? {},
+ insights: Array.isArray(d.insights) ? d.insights : [],
+ };
}
/**
@@ -1031,7 +1132,13 @@ export class IndustryMetricsService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Healthcare metrics calculation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ return {
+ ...d,
+ valuation_metrics: d.valuation_metrics ?? {},
+ benchmarks: d.benchmarks ?? {},
+ insights: Array.isArray(d.insights) ? d.insights : [],
+ };
}
/**
@@ -1047,7 +1154,13 @@ export class IndustryMetricsService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Financial services metrics calculation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ return {
+ ...d,
+ valuation_metrics: d.valuation_metrics ?? {},
+ benchmarks: d.benchmarks ?? {},
+ insights: Array.isArray(d.insights) ? d.insights : [],
+ };
}
}
@@ -1079,7 +1192,18 @@ export class AdvancedAnalyticsService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Monte Carlo valuation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ // Ensure flat top-level fields frontend expects: mean, median, std, p5, p25, p75, p95
+ return {
+ ...d,
+ mean: d.mean ?? d.valuation_statistics?.mean ?? 0,
+ median: d.median ?? d.valuation_statistics?.median ?? 0,
+ std: d.std ?? d.valuation_statistics?.std ?? 0,
+ p5: d.p5 ?? d.valuation_statistics?.percentile_5 ?? 0,
+ p25: d.p25 ?? d.valuation_statistics?.percentile_25 ?? 0,
+ p75: d.p75 ?? d.valuation_statistics?.percentile_75 ?? 0,
+ p95: d.p95 ?? d.valuation_statistics?.percentile_95 ?? 0,
+ };
}
/**
@@ -1097,7 +1221,22 @@ export class AdvancedAnalyticsService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Regression valuation failed');
- return parsed.data;
+ const d = parsed.data || {};
+ // Normalize output to flat fields the frontend expects
+ const rs = (d.regression_statistics || {}) as Record<string, number>;
+ return {
+ ...d,
+ implied_ev: d.implied_ev ?? d.predicted_value ?? 0,
+ r_squared: d.r_squared ?? rs.r_squared ?? 0,
+ adj_r_squared: d.adj_r_squared ?? rs.adjusted_r_squared ?? 0,
+ // coefficients: flatten to {feature: number} if Python returned nested objects
+ coefficients: d.coefficients && typeof Object.values(d.coefficients)[0] === 'object'
+ ? Object.fromEntries(
+ Object.entries(d.coefficients).map(([k, v]: [string, any]) => [k, v?.coefficient ?? v ?? 0])
+ )
+ : (d.coefficients ?? {}),
+ implied_multiples: d.implied_multiples ?? {},
+ };
}
}
@@ -1108,6 +1247,7 @@ export class AdvancedAnalyticsService {
export class DealComparisonService {
/**
* Compare multiple deals side-by-side
+ * Expected: { comparison: {metric: [v1,v2,...]}, summary: {metric: value} }
*/
static async compareDeals(deals: MADeal[]): Promise<any> {
const result = await invoke('compare_deals', {
@@ -1115,11 +1255,18 @@ export class DealComparisonService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Deal comparison failed');
- return parsed.data;
+ const d = parsed.data || {};
+ return {
+ ...d,
+ comparison: d.comparison ?? {},
+ summary: d.summary ?? {},
+ num_deals: d.num_deals ?? deals.length,
+ };
}
/**
* Rank deals by criteria
+ * Expected: { rankings: [{target_name, acquirer_name, premium_1day|deal_value|ev_revenue|ev_ebitda|synergies}] }
*/
static async rankDeals(
deals: MADeal[],
@@ -1131,11 +1278,17 @@ export class DealComparisonService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Deal ranking failed');
- return parsed.data;
+ const d = parsed.data || {};
+ return {
+ ...d,
+ rankings: Array.isArray(d.rankings) ? d.rankings : [],
+ ranking_criteria: d.ranking_criteria ?? criteria,
+ };
}
/**
* Benchmark deal premium against comparables
+ * Expected: { premium_comparison: {target, median, percentile}, insight: string }
*/
static async benchmarkDealPremium(
targetDeal: MADeal,
@@ -1147,11 +1300,18 @@ export class DealComparisonService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Deal premium benchmark failed');
- return parsed.data;
+ const d = parsed.data || {};
+ return {
+ ...d,
+ premium_comparison: d.premium_comparison ?? null,
+ insight: d.insight ?? '',
+ above_median: Boolean(d.above_median),
+ };
}
/**
* Analyze payment structures across deals
+ * Expected: { distribution: {all_cash: count, all_stock: count, mixed: count}, stats_by_type: {...} }
*/
static async analyzePaymentStructures(deals: MADeal[]): Promise<any> {
const result = await invoke('analyze_payment_structures', {
@@ -1159,11 +1319,18 @@ export class DealComparisonService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Payment structure analysis failed');
- return parsed.data;
+ const d = parsed.data || {};
+ return {
+ ...d,
+ distribution: d.distribution ?? {},
+ stats_by_type: d.stats_by_type ?? {},
+ total_deals: d.total_deals ?? deals.length,
+ };
}
/**
* Analyze deals by industry
+ * Expected: { by_industry: {IndustryName: {count, avg_premium, avg_ev_revenue, avg_ev_ebitda, total_value}} }
*/
static async analyzeIndustryDeals(deals: MADeal[]): Promise<any> {
const result = await invoke('analyze_industry_deals', {
@@ -1171,7 +1338,13 @@ export class DealComparisonService {
});
const parsed = JSON.parse(result as string);
if (!parsed.success) throw new Error(parsed.error || 'Industry deal analysis failed');
- return parsed.data;
+ const d = parsed.data || {};
+ return {
+ ...d,
+ by_industry: d.by_industry ?? {},
+ industries: d.industries ?? [],
+ total_deals: d.total_deals ?? deals.length,
+ };
}
}
diff --git a/fincept-terminal-desktop/src/services/maritime/marineApi.ts b/fincept-terminal-desktop/src/services/maritime/marineApi.ts
index a65e4bc84..b1b65e8e6 100644
--- a/fincept-terminal-desktop/src/services/maritime/marineApi.ts
+++ b/fincept-terminal-desktop/src/services/maritime/marineApi.ts
@@ -5,7 +5,7 @@ import { fetch } from '@tauri-apps/plugin-http';
// API Configuration
const API_CONFIG = {
- BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',
+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',
API_VERSION: 'v1',
CONNECTION_TIMEOUT: 10000,
REQUEST_TIMEOUT: 30000
diff --git a/fincept-terminal-desktop/src/services/marketplace/excelMarketplaceService.ts b/fincept-terminal-desktop/src/services/marketplace/excelMarketplaceService.ts
index 905cea69a..d9081d7fd 100644
--- a/fincept-terminal-desktop/src/services/marketplace/excelMarketplaceService.ts
+++ b/fincept-terminal-desktop/src/services/marketplace/excelMarketplaceService.ts
@@ -5,7 +5,7 @@ import { fetch } from '@tauri-apps/plugin-http';
// API Configuration
const API_CONFIG = {
- BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',
+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',
REQUEST_TIMEOUT: 30000
};
diff --git a/fincept-terminal-desktop/src/services/marketplace/marketplaceApi.tsx b/fincept-terminal-desktop/src/services/marketplace/marketplaceApi.tsx
index b3a8c9509..724d773ff 100644
--- a/fincept-terminal-desktop/src/services/marketplace/marketplaceApi.tsx
+++ b/fincept-terminal-desktop/src/services/marketplace/marketplaceApi.tsx
@@ -5,7 +5,7 @@ import { fetch } from '@tauri-apps/plugin-http';
// API Configuration
const API_CONFIG = {
- BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',
+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',
API_VERSION: 'v1',
CONNECTION_TIMEOUT: 10000,
REQUEST_TIMEOUT: 30000
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/BrokerMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/BrokerMCPBridge.ts
index b52d8dc1f..88125a191 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/BrokerMCPBridge.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/BrokerMCPBridge.ts
@@ -46,7 +46,9 @@ export class BrokerMCPBridge {
this.updateMCPContexts();
// Pre-fetch markets in the background so first resolution is fast
- this.getMarkets().catch(() => {});
+ this.getMarkets().catch((err) => {
+ console.warn('[BrokerMCPBridge] Background market pre-fetch failed:', err);
+ });
}
/**
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/EconomicsMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/EconomicsMCPBridge.ts
index 7ce471fc5..037278210 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/EconomicsMCPBridge.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/EconomicsMCPBridge.ts
@@ -3,7 +3,7 @@
import { terminalMCPProvider } from './TerminalMCPProvider';
-const BASE_URL = 'https://finceptbackend.share.zrok.io';
+const BASE_URL = 'https://api.fincept.in';
const FINCEPT_API_KEY = 'fk_user_vU20qwUxKtPmg0fWpriNBhcAnBVGgOtJxsKiiwfD9Qo';
const CONTEXT_KEYS = [
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/QuantLibMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/QuantLibMCPBridge.ts
new file mode 100644
index 000000000..9917a0992
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/QuantLibMCPBridge.ts
@@ -0,0 +1,124 @@
+// QuantLib MCP Bridge - Manages API key and provides shared utilities for QuantLib tools
+
+import { terminalMCPProvider } from './TerminalMCPProvider';
+
+const QUANTLIB_BASE_URL = 'https://api.fincept.in';
+
+/**
+ * Shared API call function for all QuantLib MCP tools
+ */
+export async function quantlibApiCall<T = any>(
+ path: string,
+ body: any,
+ apiKey: string | null,
+ method: 'GET' | 'POST' = 'POST'
+): Promise<T> {
+ let url = `${QUANTLIB_BASE_URL}${path}`;
+
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
+ if (apiKey) headers['X-API-Key'] = apiKey;
+
+ const opts: RequestInit = { method, headers };
+
+ if (method === 'POST' && body) {
+ opts.body = JSON.stringify(body);
+ } else if (method === 'GET' && body) {
+ // For GET requests, append query params
+ const params = new URLSearchParams();
+ for (const [k, v] of Object.entries(body)) {
+ if (v !== undefined && v !== null) params.append(k, String(v));
+ }
+ const qs = params.toString();
+ if (qs) url += `?${qs}`;
+ }
+
+ const res = await fetch(url, opts);
+
+ if (!res.ok) {
+ const text = await res.text();
+ throw new Error(`QuantLib API ${res.status}: ${text}`);
+ }
+
+ return res.json();
+}
+
+/**
+ * Format numeric results for human-readable messages
+ */
+export function formatNumber(value: number | undefined | null, decimals = 4): string {
+ if (value === undefined || value === null) return 'N/A';
+ return value.toFixed(decimals);
+}
+
+/**
+ * Format percentage values
+ */
+export function formatPercent(value: number | undefined | null, decimals = 2): string {
+ if (value === undefined || value === null) return 'N/A';
+ return `${(value * 100).toFixed(decimals)}%`;
+}
+
+/**
+ * QuantLib MCP Bridge Class
+ * Manages API key context and provides connection to terminal MCP provider
+ */
+class QuantLibMCPBridge {
+ private apiKey: string | null = null;
+ private isConnected = false;
+
+ /**
+ * Connect the bridge and register context functions
+ */
+ connect(apiKey?: string): void {
+ if (apiKey) {
+ this.apiKey = apiKey;
+ }
+
+ // Register context functions with the terminal MCP provider
+ terminalMCPProvider.setContexts({
+ getQuantLibApiKey: () => this.apiKey,
+ setQuantLibApiKey: (key: string | null) => {
+ this.apiKey = key;
+ },
+ });
+
+ this.isConnected = true;
+ }
+
+ /**
+ * Disconnect the bridge
+ */
+ disconnect(): void {
+ this.isConnected = false;
+ }
+
+ /**
+ * Set the API key
+ */
+ setApiKey(key: string | null): void {
+ this.apiKey = key;
+ }
+
+ /**
+ * Get the current API key
+ */
+ getApiKey(): string | null {
+ return this.apiKey;
+ }
+
+ /**
+ * Check if the bridge is connected
+ */
+ isActive(): boolean {
+ return this.isConnected;
+ }
+
+ /**
+ * Check if API key is configured
+ */
+ hasApiKey(): boolean {
+ return this.apiKey !== null && this.apiKey.length > 0;
+ }
+}
+
+export const quantLibMCPBridge = new QuantLibMCPBridge();
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/index.ts b/fincept-terminal-desktop/src/services/mcp/internal/index.ts
index 3a87ed0d4..f11d7dc0f 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/index.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/index.ts
@@ -32,6 +32,8 @@ import { notesMCPBridge } from './NotesMCPBridge';
import { nodeEditorMCPBridge } from './NodeEditorMCPBridge';
import { portfolioMCPBridge } from './PortfolioMCPBridge';
import { newsMCPBridge } from './NewsMCPBridge';
+import { allQuantLibTools, QUANTLIB_TOOL_COUNTS } from './tools/quantlib';
+import { quantLibMCPBridge } from './QuantLibMCPBridge';
// Flag to ensure initialization only runs once
let isInitialized = false;
@@ -70,6 +72,9 @@ export function initializeInternalMCP(): void {
terminalMCPProvider.registerTools(economicsTools);
terminalMCPProvider.registerTools(portfolioPanelTools);
+ // Register QuantLib tools (Phase 1: 120 tools)
+ terminalMCPProvider.registerTools(allQuantLibTools);
+
// Initialize global bridge contexts
reportBuilderMCPBridge.initializeGlobalContexts();
@@ -91,6 +96,9 @@ export function initializeInternalMCP(): void {
// Initialize Economics bridge contexts (Fincept Macro API)
economicsMCPBridge.connect();
+ // Initialize QuantLib bridge contexts
+ quantLibMCPBridge.connect();
+
// Mark as initialized
isInitialized = true;
} catch (error) {
@@ -117,6 +125,8 @@ export { newsMCPBridge } from './NewsMCPBridge';
export { dataMappingMCPBridge } from './DataMappingMCPBridge';
export { customIndexMCPBridge } from './CustomIndexMCPBridge';
export { economicsMCPBridge } from './EconomicsMCPBridge';
+export { quantLibMCPBridge } from './QuantLibMCPBridge';
+export { allQuantLibTools, QUANTLIB_TOOL_COUNTS } from './tools/quantlib';
export { INTERNAL_SERVER_ID, INTERNAL_SERVER_NAME } from './types';
export type { TerminalContexts, InternalTool, InternalToolResult } from './types';
export type {
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/core.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/core.ts
new file mode 100644
index 000000000..3623969d7
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/core.ts
@@ -0,0 +1,1381 @@
+// QuantLib Core MCP Tools - 51 endpoints
+// Types, Conventions, AutoDiff, Distributions, Math, Operations, Legs, Periods
+
+import { InternalTool } from '../../types';
+import { quantlibApiCall, formatNumber } from '../../QuantLibMCPBridge';
+
+export const quantlibCoreTools: InternalTool[] = [
+ // ==================== TYPES ====================
+ {
+ name: 'quantlib_types_tenor_add_to_date',
+ description: 'Add a tenor (e.g., "3M", "1Y", "6M") to a date and get the resulting date',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tenor: { type: 'string', description: 'Tenor string (e.g., "3M", "1Y", "6M", "2W")' },
+ start_date: { type: 'string', description: 'Start date in YYYY-MM-DD format' },
+ },
+ required: ['tenor', 'start_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/types/tenor/add-to-date', {
+ tenor: args.tenor,
+ start_date: args.start_date,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `${args.start_date} + ${args.tenor} = ${result.result_date || result.end_date}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_types_rate_convert',
+ description: 'Convert interest rate between different units (decimal, percent, bps)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ value: { type: 'number', description: 'Rate value to convert' },
+ unit: { type: 'string', description: 'Target unit', enum: ['decimal', 'percent', 'bps'] },
+ },
+ required: ['value'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/types/rate/convert', {
+ value: args.value,
+ unit: args.unit,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Rate conversion: ${args.value} → ${JSON.stringify(result)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_types_money_create',
+ description: 'Create a money object with amount and currency',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ amount: { type: 'number', description: 'Monetary amount' },
+ currency: { type: 'string', description: 'Currency code (e.g., USD, EUR, GBP)' },
+ },
+ required: ['amount'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/types/money/create', {
+ amount: args.amount,
+ currency: args.currency || 'USD',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Created: ${args.currency || 'USD'} ${formatNumber(args.amount, 2)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_types_money_convert',
+ description: 'Convert money from one currency to another using a given exchange rate',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ amount: { type: 'number', description: 'Amount to convert' },
+ from_currency: { type: 'string', description: 'Source currency code' },
+ to_currency: { type: 'string', description: 'Target currency code' },
+ rate: { type: 'number', description: 'Exchange rate (from_currency to to_currency)' },
+ },
+ required: ['amount', 'from_currency', 'to_currency', 'rate'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/types/money/convert', args, apiKey);
+ const converted = args.amount * args.rate;
+ return {
+ success: true,
+ data: result,
+ message: `${args.from_currency} ${formatNumber(args.amount, 2)} → ${args.to_currency} ${formatNumber(converted, 2)} @ rate ${args.rate}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_types_spread_from_bps',
+ description: 'Convert basis points to a spread value',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ bps: { type: 'number', description: 'Spread in basis points (e.g., 50 for 50bps)' },
+ },
+ required: ['bps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/types/spread/from-bps', { bps: args.bps }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `${args.bps} bps = ${formatNumber(args.bps / 10000, 6)} decimal`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_types_notional_schedule',
+ description: 'Generate a notional amortization schedule (bullet, linear, custom)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ schedule_type: { type: 'string', description: 'Schedule type', enum: ['bullet', 'linear', 'custom'] },
+ notional: { type: 'number', description: 'Initial notional amount' },
+ periods: { type: 'number', description: 'Number of periods' },
+ rate: { type: 'number', description: 'Amortization rate (for custom type)' },
+ },
+ required: ['schedule_type', 'notional', 'periods'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/types/notional-schedule', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Generated ${args.schedule_type} schedule: ${args.periods} periods, initial notional ${formatNumber(args.notional, 0)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_types_list_currencies',
+ description: 'Get list of all supported currency codes',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/types/currencies', {}, apiKey, 'GET');
+ return {
+ success: true,
+ data: result,
+ message: `Available currencies: ${Array.isArray(result) ? result.length : 'N/A'} codes`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_types_list_frequencies',
+ description: 'Get list of all supported payment frequencies',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/types/frequencies', {}, apiKey, 'GET');
+ return {
+ success: true,
+ data: result,
+ message: `Available frequencies: ${Array.isArray(result) ? result.join(', ') : JSON.stringify(result)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== CONVENTIONS ====================
+ {
+ name: 'quantlib_conventions_format_date',
+ description: 'Format a date string according to a specified format',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ date_str: { type: 'string', description: 'Date string to format' },
+ format: { type: 'string', description: 'Output format (e.g., "YYYY-MM-DD", "DD/MM/YYYY")' },
+ },
+ required: ['date_str'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/conventions/format-date', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Formatted: ${result.formatted || result.result}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_conventions_parse_date',
+ description: 'Parse a date string into a standardized format',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ date_string: { type: 'string', description: 'Date string to parse' },
+ },
+ required: ['date_string'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/conventions/parse-date', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Parsed: ${result.parsed || result.date}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_conventions_days_to_years',
+ description: 'Convert number of days to years using a day count convention',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ value: { type: 'number', description: 'Number of days' },
+ convention: { type: 'string', description: 'Day count convention (e.g., "ACT/360", "ACT/365", "30/360")' },
+ },
+ required: ['value'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/conventions/days-to-years', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `${args.value} days = ${formatNumber(result.years || result.result, 6)} years (${args.convention || 'default'})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_conventions_years_to_days',
+ description: 'Convert years to number of days using a day count convention',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ value: { type: 'number', description: 'Number of years' },
+ convention: { type: 'string', description: 'Day count convention' },
+ },
+ required: ['value'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/conventions/years-to-days', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `${args.value} years = ${formatNumber(result.days || result.result, 0)} days`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_conventions_normalize_rate',
+ description: 'Normalize an interest rate to decimal format',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ value: { type: 'number', description: 'Rate value' },
+ unit: { type: 'string', description: 'Input unit', enum: ['decimal', 'percent', 'bps'] },
+ },
+ required: ['value'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/conventions/normalize-rate', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Normalized rate: ${formatNumber(result.normalized || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_conventions_normalize_volatility',
+ description: 'Normalize volatility to decimal format',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ value: { type: 'number', description: 'Volatility value' },
+ vol_type: { type: 'string', description: 'Volatility type', enum: ['lognormal', 'normal'] },
+ is_percent: { type: 'boolean', description: 'Whether input is in percent' },
+ },
+ required: ['value'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/conventions/normalize-volatility', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Normalized volatility: ${formatNumber(result.normalized || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== AUTODIFF ====================
+ {
+ name: 'quantlib_autodiff_dual_eval',
+ description: 'Evaluate a function and its derivative using automatic differentiation (dual numbers)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ func_name: { type: 'string', description: 'Function name', enum: ['exp', 'log', 'sin', 'cos', 'sqrt', 'power'] },
+ x: { type: 'number', description: 'Point at which to evaluate' },
+ power_n: { type: 'number', description: 'Power exponent (for power function)' },
+ },
+ required: ['func_name', 'x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/autodiff/dual-eval', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `${args.func_name}(${args.x}): value=${formatNumber(result.value, 6)}, derivative=${formatNumber(result.derivative, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_autodiff_gradient',
+ description: 'Compute gradient of a multivariate function using automatic differentiation',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ func_name: { type: 'string', description: 'Function name', enum: ['sum_squares', 'rosenbrock', 'sphere'] },
+ x: { type: 'string', description: 'JSON array of input values (e.g., "[1.0, 2.0, 3.0]")' },
+ },
+ required: ['func_name', 'x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const xValues = JSON.parse(args.x);
+ const result = await quantlibApiCall('/quantlib/core/autodiff/gradient', {
+ func_name: args.func_name,
+ x: xValues,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Gradient of ${args.func_name}: [${result.gradient?.map((v: number) => formatNumber(v, 6)).join(', ') || 'N/A'}]`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_autodiff_taylor_expand',
+ description: 'Compute Taylor series expansion of a function around a point',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ func_name: { type: 'string', description: 'Function name', enum: ['exp', 'log', 'sin', 'cos'] },
+ x0: { type: 'number', description: 'Point of expansion' },
+ order: { type: 'number', description: 'Order of Taylor expansion' },
+ },
+ required: ['func_name', 'x0'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/autodiff/taylor-expand', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Taylor expansion of ${args.func_name} around x=${args.x0} (order ${args.order || 5})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== DISTRIBUTIONS ====================
+ {
+ name: 'quantlib_dist_normal_cdf',
+ description: 'Calculate cumulative distribution function (CDF) of standard normal distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'number', description: 'Value at which to evaluate CDF' },
+ },
+ required: ['x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/normal/cdf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `N(${args.x}) = ${formatNumber(result.cdf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_normal_pdf',
+ description: 'Calculate probability density function (PDF) of standard normal distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'number', description: 'Value at which to evaluate PDF' },
+ },
+ required: ['x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/normal/pdf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `n(${args.x}) = ${formatNumber(result.pdf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_normal_ppf',
+ description: 'Calculate percent point function (inverse CDF) of standard normal distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ p: { type: 'number', description: 'Probability value (0 to 1)' },
+ },
+ required: ['p'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/normal/ppf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `N⁻¹(${args.p}) = ${formatNumber(result.ppf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_t_cdf',
+ description: 'Calculate CDF of Student\'s t-distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'number', description: 'Value at which to evaluate CDF' },
+ df: { type: 'number', description: 'Degrees of freedom' },
+ },
+ required: ['x', 'df'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/t/cdf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `t-CDF(${args.x}, df=${args.df}) = ${formatNumber(result.cdf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_t_pdf',
+ description: 'Calculate PDF of Student\'s t-distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'number', description: 'Value at which to evaluate PDF' },
+ df: { type: 'number', description: 'Degrees of freedom' },
+ },
+ required: ['x', 'df'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/t/pdf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `t-PDF(${args.x}, df=${args.df}) = ${formatNumber(result.pdf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_t_ppf',
+ description: 'Calculate inverse CDF (quantile) of Student\'s t-distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ p: { type: 'number', description: 'Probability value (0 to 1)' },
+ df: { type: 'number', description: 'Degrees of freedom' },
+ },
+ required: ['p', 'df'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/t/ppf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `t⁻¹(${args.p}, df=${args.df}) = ${formatNumber(result.ppf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_chi2_cdf',
+ description: 'Calculate CDF of chi-squared distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'number', description: 'Value at which to evaluate CDF' },
+ df: { type: 'number', description: 'Degrees of freedom' },
+ },
+ required: ['x', 'df'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/chi2/cdf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `χ²-CDF(${args.x}, df=${args.df}) = ${formatNumber(result.cdf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_chi2_pdf',
+ description: 'Calculate PDF of chi-squared distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'number', description: 'Value at which to evaluate PDF' },
+ df: { type: 'number', description: 'Degrees of freedom' },
+ },
+ required: ['x', 'df'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/chi2/pdf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `χ²-PDF(${args.x}, df=${args.df}) = ${formatNumber(result.pdf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_gamma_cdf',
+ description: 'Calculate CDF of gamma distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'number', description: 'Value at which to evaluate CDF' },
+ alpha: { type: 'number', description: 'Shape parameter (alpha)' },
+ beta: { type: 'number', description: 'Rate parameter (beta)' },
+ },
+ required: ['x', 'alpha'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/gamma/cdf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Gamma-CDF(${args.x}, α=${args.alpha}, β=${args.beta || 1}) = ${formatNumber(result.cdf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_gamma_pdf',
+ description: 'Calculate PDF of gamma distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'number', description: 'Value at which to evaluate PDF' },
+ alpha: { type: 'number', description: 'Shape parameter (alpha)' },
+ beta: { type: 'number', description: 'Rate parameter (beta)' },
+ },
+ required: ['x', 'alpha'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/gamma/pdf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Gamma-PDF(${args.x}, α=${args.alpha}, β=${args.beta || 1}) = ${formatNumber(result.pdf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_exp_cdf',
+ description: 'Calculate CDF of exponential distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'number', description: 'Value at which to evaluate CDF' },
+ rate: { type: 'number', description: 'Rate parameter (lambda)' },
+ },
+ required: ['x', 'rate'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/exponential/cdf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Exp-CDF(${args.x}, λ=${args.rate}) = ${formatNumber(result.cdf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_exp_pdf',
+ description: 'Calculate PDF of exponential distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'number', description: 'Value at which to evaluate PDF' },
+ rate: { type: 'number', description: 'Rate parameter (lambda)' },
+ },
+ required: ['x', 'rate'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/exponential/pdf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Exp-PDF(${args.x}, λ=${args.rate}) = ${formatNumber(result.pdf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_exp_ppf',
+ description: 'Calculate inverse CDF of exponential distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ p: { type: 'number', description: 'Probability value (0 to 1)' },
+ rate: { type: 'number', description: 'Rate parameter (lambda)' },
+ },
+ required: ['p', 'rate'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/exponential/ppf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Exp⁻¹(${args.p}, λ=${args.rate}) = ${formatNumber(result.ppf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_dist_bivariate_normal_cdf',
+ description: 'Calculate CDF of bivariate normal distribution',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'number', description: 'First variable value' },
+ y: { type: 'number', description: 'Second variable value' },
+ rho: { type: 'number', description: 'Correlation coefficient (-1 to 1)' },
+ },
+ required: ['x', 'y', 'rho'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/distributions/bivariate-normal/cdf', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `BivarN(${args.x}, ${args.y}, ρ=${args.rho}) = ${formatNumber(result.cdf || result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== MATH ====================
+ {
+ name: 'quantlib_math_eval',
+ description: 'Evaluate a mathematical function at a point',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ func_name: { type: 'string', description: 'Function name', enum: ['exp', 'log', 'sin', 'cos', 'tan', 'sqrt', 'abs', 'floor', 'ceil'] },
+ x: { type: 'number', description: 'Input value' },
+ },
+ required: ['func_name', 'x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/math/eval', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `${args.func_name}(${args.x}) = ${formatNumber(result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_math_two_arg',
+ description: 'Evaluate a two-argument mathematical function',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ func_name: { type: 'string', description: 'Function name', enum: ['pow', 'max', 'min', 'atan2', 'mod'] },
+ x: { type: 'number', description: 'First argument' },
+ y: { type: 'number', description: 'Second argument' },
+ },
+ required: ['func_name', 'x', 'y'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/math/two-arg', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `${args.func_name}(${args.x}, ${args.y}) = ${formatNumber(result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== OPERATIONS ====================
+ {
+ name: 'quantlib_ops_discount_cashflows',
+ description: 'Calculate present value of a series of cashflows using discount factors',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ cashflows: { type: 'string', description: 'JSON array of cashflow amounts (e.g., "[100, 100, 1100]")' },
+ times: { type: 'string', description: 'JSON array of times in years (e.g., "[1, 2, 3]")' },
+ discount_factors: { type: 'string', description: 'JSON array of discount factors (e.g., "[0.95, 0.90, 0.85]")' },
+ },
+ required: ['cashflows', 'times', 'discount_factors'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/ops/discount-cashflows', {
+ cashflows: JSON.parse(args.cashflows),
+ times: JSON.parse(args.times),
+ discount_factors: JSON.parse(args.discount_factors),
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Present Value: ${formatNumber(result.pv || result.present_value, 2)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_ops_black_scholes',
+ description: 'Calculate Black-Scholes option price and Greeks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ time: { type: 'number', description: 'Time to maturity in years' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ },
+ required: ['option_type', 'spot', 'strike', 'rate', 'time', 'volatility'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/ops/black-scholes', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `BS ${args.option_type}: price=${formatNumber(result.price, 4)}, delta=${formatNumber(result.delta, 4)}, gamma=${formatNumber(result.gamma, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_ops_black76',
+ description: 'Calculate Black76 option price for futures/forwards',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time: { type: 'number', description: 'Time to maturity in years' },
+ discount_factor: { type: 'number', description: 'Discount factor' },
+ },
+ required: ['option_type', 'forward', 'strike', 'volatility', 'time', 'discount_factor'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/ops/black76', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Black76 ${args.option_type}: price=${formatNumber(result.price, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_ops_var',
+ description: 'Calculate Value at Risk using various methods',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ method: { type: 'string', description: 'VaR method', enum: ['parametric', 'historical', 'monte_carlo'] },
+ returns: { type: 'string', description: 'JSON array of historical returns (for historical method)' },
+ portfolio_value: { type: 'number', description: 'Portfolio value' },
+ portfolio_std: { type: 'number', description: 'Portfolio standard deviation (for parametric)' },
+ confidence: { type: 'number', description: 'Confidence level (e.g., 0.95, 0.99)' },
+ holding_period: { type: 'number', description: 'Holding period in days' },
+ },
+ required: ['method'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const body: any = { method: args.method };
+ if (args.returns) body.returns = JSON.parse(args.returns);
+ if (args.portfolio_value !== undefined) body.portfolio_value = args.portfolio_value;
+ if (args.portfolio_std !== undefined) body.portfolio_std = args.portfolio_std;
+ if (args.confidence !== undefined) body.confidence = args.confidence;
+ if (args.holding_period !== undefined) body.holding_period = args.holding_period;
+
+ const result = await quantlibApiCall('/quantlib/core/ops/var', body, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `VaR (${args.method}): ${formatNumber(result.var || result.VaR, 2)} at ${(args.confidence || 0.95) * 100}% confidence`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_ops_interpolate',
+ description: 'Interpolate a value from data points using various methods',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ method: { type: 'string', description: 'Interpolation method', enum: ['linear', 'cubic', 'log_linear', 'flat_forward'] },
+ x: { type: 'number', description: 'Point at which to interpolate' },
+ x_data: { type: 'string', description: 'JSON array of x data points' },
+ y_data: { type: 'string', description: 'JSON array of y data points' },
+ },
+ required: ['method', 'x', 'x_data', 'y_data'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/ops/interpolate', {
+ method: args.method,
+ x: args.x,
+ x_data: JSON.parse(args.x_data),
+ y_data: JSON.parse(args.y_data),
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Interpolated value at x=${args.x}: ${formatNumber(result.y || result.result, 6)} (${args.method})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_ops_forward_rate',
+ description: 'Calculate forward rate from two discount factors',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ df1: { type: 'number', description: 'First discount factor' },
+ df2: { type: 'number', description: 'Second discount factor' },
+ t1: { type: 'number', description: 'First time point (years)' },
+ t2: { type: 'number', description: 'Second time point (years)' },
+ },
+ required: ['df1', 'df2', 't1', 't2'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/ops/forward-rate', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Forward rate [${args.t1}, ${args.t2}]: ${formatNumber(result.forward_rate || result.rate, 6)} (${formatNumber((result.forward_rate || result.rate) * 100, 4)}%)`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_ops_zero_rate_convert',
+ description: 'Convert between zero rate and discount factor',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ direction: { type: 'string', description: 'Conversion direction', enum: ['rate_to_df', 'df_to_rate'] },
+ value: { type: 'number', description: 'Input value (rate or discount factor)' },
+ t: { type: 'number', description: 'Time in years' },
+ },
+ required: ['direction', 'value', 't'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/ops/zero-rate-convert', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Conversion (${args.direction}): ${args.value} → ${formatNumber(result.result, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_ops_gbm_paths',
+ description: 'Generate Geometric Brownian Motion simulation paths',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Initial spot price' },
+ drift: { type: 'number', description: 'Drift rate (mu)' },
+ volatility: { type: 'number', description: 'Volatility (sigma)' },
+ time: { type: 'number', description: 'Time horizon in years' },
+ n_paths: { type: 'number', description: 'Number of simulation paths' },
+ n_steps: { type: 'number', description: 'Number of time steps per path' },
+ seed: { type: 'number', description: 'Random seed for reproducibility' },
+ antithetic: { type: 'boolean', description: 'Use antithetic variates' },
+ },
+ required: ['spot', 'drift', 'volatility', 'time'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/ops/gbm-paths', args, apiKey);
+ const nPaths = args.n_paths || 1000;
+ const nSteps = args.n_steps || 100;
+ return {
+ success: true,
+ data: result,
+ message: `Generated ${nPaths} GBM paths with ${nSteps} steps (S0=${args.spot}, μ=${args.drift}, σ=${args.volatility})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_ops_cholesky',
+ description: 'Compute Cholesky decomposition of a positive-definite matrix',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ matrix: { type: 'string', description: 'JSON 2D array representing the matrix (e.g., "[[1,0.5],[0.5,1]]")' },
+ },
+ required: ['matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/ops/cholesky', {
+ matrix: JSON.parse(args.matrix),
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Cholesky decomposition computed successfully`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_ops_covariance_matrix',
+ description: 'Compute covariance matrix from a matrix of returns',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns: { type: 'string', description: 'JSON 2D array of returns (each row is an asset, each column is a time period)' },
+ },
+ required: ['returns'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/ops/covariance-matrix', {
+ returns: JSON.parse(args.returns),
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Covariance matrix computed (${result.covariance_matrix?.length || 'N/A'} x ${result.covariance_matrix?.[0]?.length || 'N/A'})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_ops_statistics',
+ description: 'Compute descriptive statistics for a series of values',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ values: { type: 'string', description: 'JSON array of numeric values' },
+ ddof: { type: 'number', description: 'Delta degrees of freedom for std dev calculation' },
+ },
+ required: ['values'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/ops/statistics', {
+ values: JSON.parse(args.values),
+ ddof: args.ddof,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Statistics: mean=${formatNumber(result.mean, 4)}, std=${formatNumber(result.std, 4)}, min=${formatNumber(result.min, 4)}, max=${formatNumber(result.max, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_ops_percentile',
+ description: 'Calculate percentile of a data series',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ values: { type: 'string', description: 'JSON array of numeric values' },
+ p: { type: 'number', description: 'Percentile to calculate (0 to 100)' },
+ },
+ required: ['values', 'p'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/ops/percentile', {
+ values: JSON.parse(args.values),
+ p: args.p,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `${args.p}th percentile: ${formatNumber(result.percentile || result.result, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== LEGS ====================
+ {
+ name: 'quantlib_legs_fixed',
+ description: 'Generate a fixed-rate leg (series of fixed coupon payments)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ notional: { type: 'number', description: 'Notional amount' },
+ rate: { type: 'number', description: 'Fixed coupon rate (decimal)' },
+ start_date: { type: 'string', description: 'Start date (YYYY-MM-DD)' },
+ end_date: { type: 'string', description: 'End date (YYYY-MM-DD)' },
+ frequency: { type: 'string', description: 'Payment frequency', enum: ['annual', 'semiannual', 'quarterly', 'monthly'] },
+ day_count: { type: 'string', description: 'Day count convention', enum: ['ACT/360', 'ACT/365', '30/360', 'ACT/ACT'] },
+ currency: { type: 'string', description: 'Currency code' },
+ },
+ required: ['notional', 'rate', 'start_date', 'end_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/legs/fixed', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Fixed leg: ${formatNumber(args.notional, 0)} @ ${formatNumber(args.rate * 100, 2)}% (${args.frequency || 'annual'})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_legs_float',
+ description: 'Generate a floating-rate leg (series of floating coupon payments)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ notional: { type: 'number', description: 'Notional amount' },
+ start_date: { type: 'string', description: 'Start date (YYYY-MM-DD)' },
+ end_date: { type: 'string', description: 'End date (YYYY-MM-DD)' },
+ spread: { type: 'number', description: 'Spread over index (decimal)' },
+ frequency: { type: 'string', description: 'Payment frequency' },
+ day_count: { type: 'string', description: 'Day count convention' },
+ index_name: { type: 'string', description: 'Reference index (e.g., "SOFR", "EURIBOR")' },
+ },
+ required: ['notional', 'start_date', 'end_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/legs/float', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Float leg: ${formatNumber(args.notional, 0)} + ${formatNumber((args.spread || 0) * 10000, 0)}bps spread`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_legs_zero_coupon',
+ description: 'Generate a zero-coupon leg (single payment at maturity)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ notional: { type: 'number', description: 'Notional amount' },
+ rate: { type: 'number', description: 'Zero rate (decimal)' },
+ start_date: { type: 'string', description: 'Start date (YYYY-MM-DD)' },
+ end_date: { type: 'string', description: 'End date (YYYY-MM-DD)' },
+ day_count: { type: 'string', description: 'Day count convention' },
+ },
+ required: ['notional', 'rate', 'start_date', 'end_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/legs/zero-coupon', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Zero-coupon leg: ${formatNumber(args.notional, 0)} @ ${formatNumber(args.rate * 100, 2)}%`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== PERIODS ====================
+ {
+ name: 'quantlib_periods_fixed_coupon',
+ description: 'Calculate a single fixed coupon period',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ notional: { type: 'number', description: 'Notional amount' },
+ rate: { type: 'number', description: 'Coupon rate (decimal)' },
+ start_date: { type: 'string', description: 'Period start date (YYYY-MM-DD)' },
+ end_date: { type: 'string', description: 'Period end date (YYYY-MM-DD)' },
+ day_count: { type: 'string', description: 'Day count convention' },
+ },
+ required: ['notional', 'rate', 'start_date', 'end_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/periods/fixed-coupon', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Fixed coupon: ${formatNumber(result.coupon || result.payment, 2)} (${args.start_date} to ${args.end_date})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_periods_float_coupon',
+ description: 'Calculate a single floating coupon period',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ notional: { type: 'number', description: 'Notional amount' },
+ start_date: { type: 'string', description: 'Period start date (YYYY-MM-DD)' },
+ end_date: { type: 'string', description: 'Period end date (YYYY-MM-DD)' },
+ spread: { type: 'number', description: 'Spread over index (decimal)' },
+ day_count: { type: 'string', description: 'Day count convention' },
+ fixing_rate: { type: 'number', description: 'Fixed rate for the period (if known)' },
+ },
+ required: ['notional', 'start_date', 'end_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/periods/float-coupon', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Float coupon: ${formatNumber(result.coupon || result.payment, 2)} (${args.start_date} to ${args.end_date})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_periods_day_count_fraction',
+ description: 'Calculate the day count fraction between two dates',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ start_date: { type: 'string', description: 'Start date (YYYY-MM-DD)' },
+ end_date: { type: 'string', description: 'End date (YYYY-MM-DD)' },
+ convention: { type: 'string', description: 'Day count convention', enum: ['ACT/360', 'ACT/365', '30/360', 'ACT/ACT'] },
+ },
+ required: ['start_date', 'end_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/core/periods/day-count-fraction', args, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Day count fraction (${args.convention || 'ACT/365'}): ${formatNumber(result.fraction || result.dcf, 6)} years`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/curves.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/curves.ts
new file mode 100644
index 000000000..a0392b043
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/curves.ts
@@ -0,0 +1,1056 @@
+// QuantLib Curves MCP Tools
+// 31 tools for yield curves, interpolation, transformations, Nelson-Siegel, inflation, multicurve
+
+import type { InternalTool } from '../../types';
+import { quantlibApiCall, formatNumber, formatPercent } from '../../QuantLibMCPBridge';
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CURVE BUILDING & QUERYING (6 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const curveBuildTool: InternalTool = {
+ name: 'quantlib_curves_build',
+ description: 'Build a yield curve from reference date, tenors, and rates. Supports zero, discount, or forward curve types with various interpolation methods.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of tenors in years, e.g. [0.25, 0.5, 1, 2, 5, 10]' },
+ values: { type: 'string', description: 'JSON array of rate values corresponding to tenors' },
+ curve_type: { type: 'string', description: 'Curve type: zero, discount, or forward (default: zero)' },
+ interpolation: { type: 'string', description: 'Interpolation method: linear, log_linear, cubic, etc. (default: linear)' },
+ },
+ required: ['reference_date', 'tenors', 'values'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const tenors = JSON.parse(args.tenors as string);
+ const values = JSON.parse(args.values as string);
+ const result = await quantlibApiCall('/quantlib/curves/build', {
+ reference_date: args.reference_date,
+ tenors,
+ values,
+ curve_type: args.curve_type || 'zero',
+ interpolation: args.interpolation || 'linear',
+ }, apiKey);
+ return { success: true, data: result, message: `Built ${args.curve_type || 'zero'} curve with ${tenors.length} points` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const curveZeroRateTool: InternalTool = {
+ name: 'quantlib_curves_zero_rate',
+ description: 'Query the zero rate at a specific tenor from a yield curve.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ query_tenor: { type: 'number', description: 'Tenor to query in years' },
+ curve_type: { type: 'string', description: 'Curve type (default: zero)' },
+ interpolation: { type: 'string', description: 'Interpolation method (default: linear)' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'query_tenor'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/zero-rate', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ query_tenor: args.query_tenor,
+ curve_type: args.curve_type || 'zero',
+ interpolation: args.interpolation || 'linear',
+ }, apiKey);
+ return { success: true, data: result, message: `Zero rate at ${args.query_tenor}Y: ${formatPercent(result.zero_rate)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const curveDiscountFactorTool: InternalTool = {
+ name: 'quantlib_curves_discount_factor',
+ description: 'Query the discount factor at a specific tenor from a yield curve.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ query_tenor: { type: 'number', description: 'Tenor to query in years' },
+ curve_type: { type: 'string', description: 'Curve type (default: zero)' },
+ interpolation: { type: 'string', description: 'Interpolation method (default: linear)' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'query_tenor'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/discount-factor', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ query_tenor: args.query_tenor,
+ curve_type: args.curve_type || 'zero',
+ interpolation: args.interpolation || 'linear',
+ }, apiKey);
+ return { success: true, data: result, message: `Discount factor at ${args.query_tenor}Y: ${formatNumber(result.discount_factor)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const curveForwardRateTool: InternalTool = {
+ name: 'quantlib_curves_forward_rate',
+ description: 'Calculate the forward rate between two tenors from a yield curve.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ start_tenor: { type: 'number', description: 'Start tenor in years' },
+ end_tenor: { type: 'number', description: 'End tenor in years' },
+ curve_type: { type: 'string', description: 'Curve type (default: zero)' },
+ interpolation: { type: 'string', description: 'Interpolation method (default: linear)' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'start_tenor', 'end_tenor'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/forward-rate', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ start_tenor: args.start_tenor,
+ end_tenor: args.end_tenor,
+ curve_type: args.curve_type || 'zero',
+ interpolation: args.interpolation || 'linear',
+ }, apiKey);
+ return { success: true, data: result, message: `Forward rate ${args.start_tenor}Y-${args.end_tenor}Y: ${formatPercent(result.forward_rate)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const curveInstantaneousForwardTool: InternalTool = {
+ name: 'quantlib_curves_instantaneous_forward',
+ description: 'Calculate the instantaneous forward rate at a specific tenor.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ query_tenor: { type: 'number', description: 'Tenor to query in years' },
+ curve_type: { type: 'string', description: 'Curve type (default: zero)' },
+ interpolation: { type: 'string', description: 'Interpolation method (default: linear)' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'query_tenor'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/instantaneous-forward', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ query_tenor: args.query_tenor,
+ curve_type: args.curve_type || 'zero',
+ interpolation: args.interpolation || 'linear',
+ }, apiKey);
+ return { success: true, data: result, message: `Instantaneous forward at ${args.query_tenor}Y: ${formatPercent(result.instantaneous_forward)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const curvePointsTool: InternalTool = {
+ name: 'quantlib_curves_points',
+ description: 'Get curve values at multiple query tenors.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ query_tenors: { type: 'string', description: 'JSON array of tenors to query' },
+ curve_type: { type: 'string', description: 'Curve type (default: zero)' },
+ interpolation: { type: 'string', description: 'Interpolation method (default: linear)' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'query_tenors'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const queryTenors = JSON.parse(args.query_tenors as string);
+ const result = await quantlibApiCall('/quantlib/curves/curve-points', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ query_tenors: queryTenors,
+ curve_type: args.curve_type || 'zero',
+ interpolation: args.interpolation || 'linear',
+ }, apiKey);
+ return { success: true, data: result, message: `Retrieved ${queryTenors.length} curve points` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// INTERPOLATION (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const interpolateTool: InternalTool = {
+ name: 'quantlib_curves_interpolate',
+ description: 'Interpolate values at query points using various methods (linear, cubic, log_linear, etc.).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'string', description: 'JSON array of x coordinates' },
+ y: { type: 'string', description: 'JSON array of y coordinates' },
+ query_x: { type: 'string', description: 'JSON array of x values to interpolate' },
+ method: { type: 'string', description: 'Interpolation method (default: linear)' },
+ },
+ required: ['x', 'y', 'query_x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const queryX = JSON.parse(args.query_x as string);
+ const result = await quantlibApiCall('/quantlib/curves/interpolate', {
+ x: JSON.parse(args.x as string),
+ y: JSON.parse(args.y as string),
+ query_x: queryX,
+ method: args.method || 'linear',
+ }, apiKey);
+ return { success: true, data: result, message: `Interpolated ${queryX.length} points using ${args.method || 'linear'} method` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const interpolateDerivativeTool: InternalTool = {
+ name: 'quantlib_curves_interpolate_derivative',
+ description: 'Calculate the derivative of an interpolated function at a query point.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'string', description: 'JSON array of x coordinates' },
+ y: { type: 'string', description: 'JSON array of y coordinates' },
+ query_x: { type: 'number', description: 'X value to calculate derivative at' },
+ method: { type: 'string', description: 'Interpolation method (default: linear)' },
+ },
+ required: ['x', 'y', 'query_x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/interpolate-derivative', {
+ x: JSON.parse(args.x as string),
+ y: JSON.parse(args.y as string),
+ query_x: args.query_x,
+ method: args.method || 'linear',
+ }, apiKey);
+ return { success: true, data: result, message: `Derivative at x=${args.query_x}: ${formatNumber(result.derivative)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const monotonicityCheckTool: InternalTool = {
+ name: 'quantlib_curves_monotonicity_check',
+ description: 'Check if an interpolation preserves monotonicity at query points.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'string', description: 'JSON array of x coordinates' },
+ y: { type: 'string', description: 'JSON array of y coordinates' },
+ query_x: { type: 'string', description: 'JSON array of x values to check' },
+ method: { type: 'string', description: 'Interpolation method (default: linear)' },
+ },
+ required: ['x', 'y', 'query_x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/monotonicity-check', {
+ x: JSON.parse(args.x as string),
+ y: JSON.parse(args.y as string),
+ query_x: JSON.parse(args.query_x as string),
+ method: args.method || 'linear',
+ }, apiKey);
+ return { success: true, data: result, message: `Monotonicity check: ${result.is_monotonic ? 'PASSED' : 'FAILED'}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CURVE TRANSFORMATIONS (6 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const parallelShiftTool: InternalTool = {
+ name: 'quantlib_curves_parallel_shift',
+ description: 'Apply a parallel shift (bump) to a yield curve in basis points.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ shift_bps: { type: 'number', description: 'Shift amount in basis points' },
+ space: { type: 'string', description: 'Transformation space: zero_rate or discount (default: zero_rate)' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'shift_bps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/parallel-shift', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ shift_bps: args.shift_bps,
+ space: args.space || 'zero_rate',
+ }, apiKey);
+ return { success: true, data: result, message: `Applied ${args.shift_bps}bps parallel shift` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const twistTool: InternalTool = {
+ name: 'quantlib_curves_twist',
+ description: 'Apply a twist (steepening/flattening) transformation to a yield curve.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ pivot_years: { type: 'number', description: 'Pivot point in years' },
+ short_shift_bps: { type: 'number', description: 'Shift for short end in bps' },
+ long_shift_bps: { type: 'number', description: 'Shift for long end in bps' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'pivot_years', 'short_shift_bps', 'long_shift_bps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/twist', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ pivot_years: args.pivot_years,
+ short_shift_bps: args.short_shift_bps,
+ long_shift_bps: args.long_shift_bps,
+ }, apiKey);
+ return { success: true, data: result, message: `Applied twist: short ${args.short_shift_bps}bps, long ${args.long_shift_bps}bps, pivot ${args.pivot_years}Y` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const butterflyTool: InternalTool = {
+ name: 'quantlib_curves_butterfly',
+ description: 'Apply a butterfly transformation to a yield curve (wings vs belly).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ belly_years: { type: 'number', description: 'Belly point in years' },
+ wing_shift_bps: { type: 'number', description: 'Shift for wings in bps' },
+ belly_shift_bps: { type: 'number', description: 'Shift for belly in bps' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'belly_years', 'wing_shift_bps', 'belly_shift_bps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/butterfly', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ belly_years: args.belly_years,
+ wing_shift_bps: args.wing_shift_bps,
+ belly_shift_bps: args.belly_shift_bps,
+ }, apiKey);
+ return { success: true, data: result, message: `Applied butterfly: wings ${args.wing_shift_bps}bps, belly ${args.belly_shift_bps}bps` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const keyRateShiftTool: InternalTool = {
+ name: 'quantlib_curves_key_rate_shift',
+ description: 'Apply a key rate shift (localized bump) at a specific tenor.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ tenor_years: { type: 'number', description: 'Target tenor for key rate shift' },
+ shift_bps: { type: 'number', description: 'Shift amount in bps' },
+ width_years: { type: 'number', description: 'Width of the shift region in years (default: 2)' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'tenor_years', 'shift_bps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/key-rate-shift', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ tenor_years: args.tenor_years,
+ shift_bps: args.shift_bps,
+ width_years: args.width_years || 2,
+ }, apiKey);
+ return { success: true, data: result, message: `Applied ${args.shift_bps}bps key rate shift at ${args.tenor_years}Y` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const rollTool: InternalTool = {
+ name: 'quantlib_curves_roll',
+ description: 'Roll a curve forward in time by a specified number of days.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ days: { type: 'number', description: 'Number of days to roll forward' },
+ preserve_shape: { type: 'boolean', description: 'Whether to preserve curve shape (default: true)' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'days'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/roll', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ days: args.days,
+ preserve_shape: args.preserve_shape !== false,
+ }, apiKey);
+ return { success: true, data: result, message: `Rolled curve forward by ${args.days} days` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const scaleTool: InternalTool = {
+ name: 'quantlib_curves_scale',
+ description: 'Scale all curve values by a factor.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ scale_factor: { type: 'number', description: 'Scaling factor to apply' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'scale_factor'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/scale', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ scale_factor: args.scale_factor,
+ }, apiKey);
+ return { success: true, data: result, message: `Scaled curve by factor ${args.scale_factor}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CURVE CONSTRUCTION (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const compositeTool: InternalTool = {
+ name: 'quantlib_curves_composite',
+ description: 'Build a composite curve from base and forecast curves.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ base_tenors: { type: 'string', description: 'JSON array of base curve tenors' },
+ base_values: { type: 'string', description: 'JSON array of base curve values' },
+ forecast_tenors: { type: 'string', description: 'JSON array of forecast curve tenors' },
+ forecast_values: { type: 'string', description: 'JSON array of forecast curve values' },
+ },
+ required: ['reference_date', 'base_tenors', 'base_values', 'forecast_tenors', 'forecast_values'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/composite', {
+ reference_date: args.reference_date,
+ base_tenors: JSON.parse(args.base_tenors as string),
+ base_values: JSON.parse(args.base_values as string),
+ forecast_tenors: JSON.parse(args.forecast_tenors as string),
+ forecast_values: JSON.parse(args.forecast_values as string),
+ }, apiKey);
+ return { success: true, data: result, message: 'Built composite curve from base and forecast curves' };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const proxyTool: InternalTool = {
+ name: 'quantlib_curves_proxy',
+ description: 'Create a proxy curve by adding a spread to a base curve.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ base_tenors: { type: 'string', description: 'JSON array of base curve tenors' },
+ base_values: { type: 'string', description: 'JSON array of base curve values' },
+ spread_bps: { type: 'number', description: 'Spread to add in basis points' },
+ },
+ required: ['reference_date', 'base_tenors', 'base_values', 'spread_bps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/proxy', {
+ reference_date: args.reference_date,
+ base_tenors: JSON.parse(args.base_tenors as string),
+ base_values: JSON.parse(args.base_values as string),
+ spread_bps: args.spread_bps,
+ }, apiKey);
+ return { success: true, data: result, message: `Created proxy curve with ${args.spread_bps}bps spread` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const timeShiftTool: InternalTool = {
+ name: 'quantlib_curves_time_shift',
+ description: 'Shift a curve in time and query at new tenors.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ tenors: { type: 'string', description: 'JSON array of curve tenors in years' },
+ values: { type: 'string', description: 'JSON array of curve values' },
+ shift_days: { type: 'number', description: 'Time shift in days' },
+ query_tenors: { type: 'string', description: 'JSON array of tenors to query after shift' },
+ preserve_shape: { type: 'boolean', description: 'Whether to preserve curve shape (default: true)' },
+ },
+ required: ['reference_date', 'tenors', 'values', 'shift_days', 'query_tenors'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/time-shift', {
+ reference_date: args.reference_date,
+ tenors: JSON.parse(args.tenors as string),
+ values: JSON.parse(args.values as string),
+ shift_days: args.shift_days,
+ query_tenors: JSON.parse(args.query_tenors as string),
+ preserve_shape: args.preserve_shape !== false,
+ }, apiKey);
+ return { success: true, data: result, message: `Time-shifted curve by ${args.shift_days} days` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// SMOOTHNESS (2 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const constrainedFitTool: InternalTool = {
+ name: 'quantlib_curves_constrained_fit',
+ description: 'Fit a smooth curve with constraints (non-negative forwards, etc.).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tenors: { type: 'string', description: 'JSON array of tenors' },
+ rates: { type: 'string', description: 'JSON array of rates' },
+ },
+ required: ['tenors', 'rates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/constrained-fit', {
+ tenors: JSON.parse(args.tenors as string),
+ rates: JSON.parse(args.rates as string),
+ }, apiKey);
+ return { success: true, data: result, message: 'Fitted constrained smooth curve' };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const smoothnessPenaltyTool: InternalTool = {
+ name: 'quantlib_curves_smoothness_penalty',
+ description: 'Calculate smoothness penalty for an interpolated curve.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ x: { type: 'string', description: 'JSON array of x coordinates' },
+ y: { type: 'string', description: 'JSON array of y coordinates' },
+ query_x: { type: 'string', description: 'JSON array of x values to evaluate' },
+ method: { type: 'string', description: 'Interpolation method (default: linear)' },
+ },
+ required: ['x', 'y', 'query_x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/smoothness-penalty', {
+ x: JSON.parse(args.x as string),
+ y: JSON.parse(args.y as string),
+ query_x: JSON.parse(args.query_x as string),
+ method: args.method || 'linear',
+ }, apiKey);
+ return { success: true, data: result, message: `Smoothness penalty: ${formatNumber(result.penalty)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// NELSON-SIEGEL / NSS (4 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const nelsonSiegelFitTool: InternalTool = {
+ name: 'quantlib_curves_nelson_siegel_fit',
+ description: 'Fit Nelson-Siegel model parameters to market data.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tenors: { type: 'string', description: 'JSON array of tenors in years' },
+ rates: { type: 'string', description: 'JSON array of market rates' },
+ },
+ required: ['tenors', 'rates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/nelson-siegel/fit', {
+ tenors: JSON.parse(args.tenors as string),
+ rates: JSON.parse(args.rates as string),
+ }, apiKey);
+ return { success: true, data: result, message: `Fitted NS: β0=${formatNumber(result.beta0)}, β1=${formatNumber(result.beta1)}, β2=${formatNumber(result.beta2)}, τ=${formatNumber(result.tau)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const nelsonSiegelEvaluateTool: InternalTool = {
+ name: 'quantlib_curves_nelson_siegel_evaluate',
+ description: 'Evaluate Nelson-Siegel curve at given tenors using specified parameters.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ beta0: { type: 'number', description: 'Level parameter' },
+ beta1: { type: 'number', description: 'Slope parameter' },
+ beta2: { type: 'number', description: 'Curvature parameter' },
+ tau: { type: 'number', description: 'Decay parameter' },
+ query_tenors: { type: 'string', description: 'JSON array of tenors to evaluate' },
+ },
+ required: ['beta0', 'beta1', 'beta2', 'tau', 'query_tenors'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const queryTenors = JSON.parse(args.query_tenors as string);
+ const result = await quantlibApiCall('/quantlib/curves/nelson-siegel/evaluate', {
+ beta0: args.beta0,
+ beta1: args.beta1,
+ beta2: args.beta2,
+ tau: args.tau,
+ query_tenors: queryTenors,
+ }, apiKey);
+ return { success: true, data: result, message: `Evaluated NS curve at ${queryTenors.length} points` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const nssFitTool: InternalTool = {
+ name: 'quantlib_curves_nss_fit',
+ description: 'Fit Nelson-Siegel-Svensson (NSS) model parameters to market data.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tenors: { type: 'string', description: 'JSON array of tenors in years' },
+ rates: { type: 'string', description: 'JSON array of market rates' },
+ },
+ required: ['tenors', 'rates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/nss/fit', {
+ tenors: JSON.parse(args.tenors as string),
+ rates: JSON.parse(args.rates as string),
+ }, apiKey);
+ return { success: true, data: result, message: 'Fitted NSS model parameters' };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const nssEvaluateTool: InternalTool = {
+ name: 'quantlib_curves_nss_evaluate',
+ description: 'Evaluate Nelson-Siegel-Svensson curve at given tenors.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ beta0: { type: 'number', description: 'Level parameter' },
+ beta1: { type: 'number', description: 'Slope parameter' },
+ beta2: { type: 'number', description: 'First curvature parameter' },
+ beta3: { type: 'number', description: 'Second curvature parameter' },
+ tau1: { type: 'number', description: 'First decay parameter' },
+ tau2: { type: 'number', description: 'Second decay parameter' },
+ query_tenors: { type: 'string', description: 'JSON array of tenors to evaluate' },
+ },
+ required: ['beta0', 'beta1', 'beta2', 'beta3', 'tau1', 'tau2', 'query_tenors'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const queryTenors = JSON.parse(args.query_tenors as string);
+ const result = await quantlibApiCall('/quantlib/curves/nss/evaluate', {
+ beta0: args.beta0,
+ beta1: args.beta1,
+ beta2: args.beta2,
+ beta3: args.beta3,
+ tau1: args.tau1,
+ tau2: args.tau2,
+ query_tenors: queryTenors,
+ }, apiKey);
+ return { success: true, data: result, message: `Evaluated NSS curve at ${queryTenors.length} points` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// INFLATION (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const inflationBuildTool: InternalTool = {
+ name: 'quantlib_curves_inflation_build',
+ description: 'Build an inflation curve from base CPI and inflation rates.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ base_cpi: { type: 'number', description: 'Base CPI index value' },
+ tenors: { type: 'string', description: 'JSON array of tenors in years' },
+ inflation_rates: { type: 'string', description: 'JSON array of inflation rates' },
+ },
+ required: ['reference_date', 'base_cpi', 'tenors', 'inflation_rates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/inflation/build', {
+ reference_date: args.reference_date,
+ base_cpi: args.base_cpi,
+ tenors: JSON.parse(args.tenors as string),
+ inflation_rates: JSON.parse(args.inflation_rates as string),
+ }, apiKey);
+ return { success: true, data: result, message: `Built inflation curve with base CPI ${args.base_cpi}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const inflationBootstrapTool: InternalTool = {
+ name: 'quantlib_curves_inflation_bootstrap',
+ description: 'Bootstrap an inflation curve from inflation swap rates and nominal curve.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ base_cpi: { type: 'number', description: 'Base CPI index value' },
+ swap_tenors: { type: 'string', description: 'JSON array of inflation swap tenors' },
+ swap_rates: { type: 'string', description: 'JSON array of inflation swap rates' },
+ nominal_tenors: { type: 'string', description: 'JSON array of nominal curve tenors' },
+ nominal_rates: { type: 'string', description: 'JSON array of nominal curve rates' },
+ },
+ required: ['reference_date', 'base_cpi', 'swap_tenors', 'swap_rates', 'nominal_tenors', 'nominal_rates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/inflation/bootstrap', {
+ reference_date: args.reference_date,
+ base_cpi: args.base_cpi,
+ swap_tenors: JSON.parse(args.swap_tenors as string),
+ swap_rates: JSON.parse(args.swap_rates as string),
+ nominal_tenors: JSON.parse(args.nominal_tenors as string),
+ nominal_rates: JSON.parse(args.nominal_rates as string),
+ }, apiKey);
+ return { success: true, data: result, message: 'Bootstrapped inflation curve from swap and nominal data' };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const inflationSeasonalityTool: InternalTool = {
+ name: 'quantlib_curves_inflation_seasonality',
+ description: 'Apply seasonality adjustments to inflation data.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ monthly_factors: { type: 'string', description: 'JSON array of 12 monthly seasonality factors' },
+ cpi_values: { type: 'string', description: 'JSON array of CPI values' },
+ months: { type: 'string', description: 'JSON array of month indices (1-12)' },
+ },
+ required: ['monthly_factors', 'cpi_values', 'months'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/inflation/seasonality', {
+ monthly_factors: JSON.parse(args.monthly_factors as string),
+ cpi_values: JSON.parse(args.cpi_values as string),
+ months: JSON.parse(args.months as string),
+ }, apiKey);
+ return { success: true, data: result, message: 'Applied seasonality adjustments to inflation data' };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// MULTICURVE (2 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const multicurveSetupTool: InternalTool = {
+ name: 'quantlib_curves_multicurve_setup',
+ description: 'Set up a dual-curve framework with OIS discounting and IBOR forecasting.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ ois_tenors: { type: 'string', description: 'JSON array of OIS curve tenors' },
+ ois_rates: { type: 'string', description: 'JSON array of OIS rates' },
+ ibor_tenors: { type: 'string', description: 'JSON array of IBOR curve tenors' },
+ ibor_rates: { type: 'string', description: 'JSON array of IBOR rates' },
+ query_tenors: { type: 'string', description: 'JSON array of tenors to query' },
+ },
+ required: ['reference_date', 'ois_tenors', 'ois_rates', 'ibor_tenors', 'ibor_rates', 'query_tenors'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/multicurve/setup', {
+ reference_date: args.reference_date,
+ ois_tenors: JSON.parse(args.ois_tenors as string),
+ ois_rates: JSON.parse(args.ois_rates as string),
+ ibor_tenors: JSON.parse(args.ibor_tenors as string),
+ ibor_rates: JSON.parse(args.ibor_rates as string),
+ query_tenors: JSON.parse(args.query_tenors as string),
+ }, apiKey);
+ return { success: true, data: result, message: 'Set up multicurve framework with OIS/IBOR curves' };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const basisSpreadTool: InternalTool = {
+ name: 'quantlib_curves_multicurve_basis_spread',
+ description: 'Calculate the basis spread between OIS and IBOR curves at a specific tenor.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ ois_tenors: { type: 'string', description: 'JSON array of OIS curve tenors' },
+ ois_rates: { type: 'string', description: 'JSON array of OIS rates' },
+ ibor_tenors: { type: 'string', description: 'JSON array of IBOR curve tenors' },
+ ibor_rates: { type: 'string', description: 'JSON array of IBOR rates' },
+ query_tenor: { type: 'number', description: 'Tenor to query in years' },
+ },
+ required: ['reference_date', 'ois_tenors', 'ois_rates', 'ibor_tenors', 'ibor_rates', 'query_tenor'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/multicurve/basis-spread', {
+ reference_date: args.reference_date,
+ ois_tenors: JSON.parse(args.ois_tenors as string),
+ ois_rates: JSON.parse(args.ois_rates as string),
+ ibor_tenors: JSON.parse(args.ibor_tenors as string),
+ ibor_rates: JSON.parse(args.ibor_rates as string),
+ query_tenor: args.query_tenor,
+ }, apiKey);
+ return { success: true, data: result, message: `Basis spread at ${args.query_tenor}Y: ${formatNumber(result.basis_spread * 10000)}bps` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CROSS-CURRENCY / REAL RATE (2 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const crossCurrencyBasisTool: InternalTool = {
+ name: 'quantlib_curves_cross_currency_basis',
+ description: 'Build a cross-currency basis curve for FX-adjusted discounting.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ domestic_currency: { type: 'string', description: 'Domestic currency code (e.g., USD)' },
+ foreign_currency: { type: 'string', description: 'Foreign currency code (e.g., EUR)' },
+ tenors: { type: 'string', description: 'JSON array of tenors in years' },
+ basis_spreads_bps: { type: 'string', description: 'JSON array of basis spreads in bps' },
+ query_tenors: { type: 'string', description: 'JSON array of tenors to query' },
+ },
+ required: ['reference_date', 'domestic_currency', 'foreign_currency', 'tenors', 'basis_spreads_bps', 'query_tenors'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/curves/cross-currency-basis', {
+ reference_date: args.reference_date,
+ domestic_currency: args.domestic_currency,
+ foreign_currency: args.foreign_currency,
+ tenors: JSON.parse(args.tenors as string),
+ basis_spreads_bps: JSON.parse(args.basis_spreads_bps as string),
+ query_tenors: JSON.parse(args.query_tenors as string),
+ }, apiKey);
+ return { success: true, data: result, message: `Built ${args.domestic_currency}/${args.foreign_currency} cross-currency basis curve` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const realRateTool: InternalTool = {
+ name: 'quantlib_curves_real_rate',
+ description: 'Calculate real interest rates from nominal rates and inflation expectations.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date in YYYY-MM-DD format' },
+ nominal_tenors: { type: 'string', description: 'JSON array of nominal curve tenors' },
+ nominal_rates: { type: 'string', description: 'JSON array of nominal rates' },
+ base_cpi: { type: 'number', description: 'Base CPI index value' },
+ inflation_tenors: { type: 'string', description: 'JSON array of inflation curve tenors' },
+ inflation_rates: { type: 'string', description: 'JSON array of inflation rates' },
+ query_tenors: { type: 'string', description: 'JSON array of tenors to query' },
+ },
+ required: ['reference_date', 'nominal_tenors', 'nominal_rates', 'base_cpi', 'inflation_tenors', 'inflation_rates', 'query_tenors'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const queryTenors = JSON.parse(args.query_tenors as string);
+ const result = await quantlibApiCall('/quantlib/curves/real-rate', {
+ reference_date: args.reference_date,
+ nominal_tenors: JSON.parse(args.nominal_tenors as string),
+ nominal_rates: JSON.parse(args.nominal_rates as string),
+ base_cpi: args.base_cpi,
+ inflation_tenors: JSON.parse(args.inflation_tenors as string),
+ inflation_rates: JSON.parse(args.inflation_rates as string),
+ query_tenors: queryTenors,
+ }, apiKey);
+ return { success: true, data: result, message: `Calculated real rates at ${queryTenors.length} tenors` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// EXPORT ALL TOOLS
+// ══════════════════════════════════════════════════════════════════════════════
+
+export const quantlibCurvesTools: InternalTool[] = [
+ // Curve Building & Querying (6)
+ curveBuildTool,
+ curveZeroRateTool,
+ curveDiscountFactorTool,
+ curveForwardRateTool,
+ curveInstantaneousForwardTool,
+ curvePointsTool,
+ // Interpolation (3)
+ interpolateTool,
+ interpolateDerivativeTool,
+ monotonicityCheckTool,
+ // Curve Transformations (6)
+ parallelShiftTool,
+ twistTool,
+ butterflyTool,
+ keyRateShiftTool,
+ rollTool,
+ scaleTool,
+ // Curve Construction (3)
+ compositeTool,
+ proxyTool,
+ timeShiftTool,
+ // Smoothness (2)
+ constrainedFitTool,
+ smoothnessPenaltyTool,
+ // Nelson-Siegel / NSS (4)
+ nelsonSiegelFitTool,
+ nelsonSiegelEvaluateTool,
+ nssFitTool,
+ nssEvaluateTool,
+ // Inflation (3)
+ inflationBuildTool,
+ inflationBootstrapTool,
+ inflationSeasonalityTool,
+ // Multicurve (2)
+ multicurveSetupTool,
+ basisSpreadTool,
+ // Cross-Currency / Real Rate (2)
+ crossCurrencyBasisTool,
+ realRateTool,
+];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/index.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/index.ts
new file mode 100644
index 000000000..9da3b93aa
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/index.ts
@@ -0,0 +1,77 @@
+// QuantLib MCP Tools - Barrel Export
+// Exports all QuantLib module tools for registration with the MCP provider
+
+// Phase 1 modules
+import { quantlibCoreTools } from './core';
+import { quantlibPricingTools } from './pricing';
+import { quantlibRiskTools } from './risk';
+import { quantlibPortfolioTools } from './portfolio';
+
+// Phase 2 modules
+import { quantlibCurvesTools } from './curves';
+import { quantlibVolatilityTools } from './volatility';
+import { quantlibModelsTools } from './models';
+import { quantlibStatisticsTools } from './statistics';
+import { quantlibInstrumentsTools } from './instruments';
+
+// Re-export individual modules for selective imports
+// Phase 1
+export { quantlibCoreTools } from './core';
+export { quantlibPricingTools } from './pricing';
+export { quantlibRiskTools } from './risk';
+export { quantlibPortfolioTools } from './portfolio';
+
+// Phase 2
+export { quantlibCurvesTools } from './curves';
+export { quantlibVolatilityTools } from './volatility';
+export { quantlibModelsTools } from './models';
+export { quantlibStatisticsTools } from './statistics';
+export { quantlibInstrumentsTools } from './instruments';
+
+// Combined export of all QuantLib tools
+// Phase 1: Core, Pricing, Risk, Portfolio (120 tools)
+// Phase 2: Curves, Volatility, Models, Statistics, Instruments (137 tools)
+// Total: 257 tools
+export const allQuantLibTools = [
+ // Phase 1 (120 tools)
+ ...quantlibCoreTools, // 51 tools
+ ...quantlibPricingTools, // 29 tools
+ ...quantlibRiskTools, // 25 tools
+ ...quantlibPortfolioTools, // 15 tools
+ // Phase 2 (137 tools)
+ ...quantlibCurvesTools, // 31 tools
+ ...quantlibVolatilityTools, // 14 tools
+ ...quantlibModelsTools, // 14 tools
+ ...quantlibStatisticsTools, // 52 tools
+ ...quantlibInstrumentsTools, // 26 tools
+];
+
+// Tool counts for reference
+export const QUANTLIB_TOOL_COUNTS = {
+ // Phase 1
+ core: quantlibCoreTools.length,
+ pricing: quantlibPricingTools.length,
+ risk: quantlibRiskTools.length,
+ portfolio: quantlibPortfolioTools.length,
+ // Phase 2
+ curves: quantlibCurvesTools.length,
+ volatility: quantlibVolatilityTools.length,
+ models: quantlibModelsTools.length,
+ statistics: quantlibStatisticsTools.length,
+ instruments: quantlibInstrumentsTools.length,
+ // Totals
+ phase1Total: quantlibCoreTools.length + quantlibPricingTools.length + quantlibRiskTools.length + quantlibPortfolioTools.length,
+ phase2Total: quantlibCurvesTools.length + quantlibVolatilityTools.length + quantlibModelsTools.length + quantlibStatisticsTools.length + quantlibInstrumentsTools.length,
+ total: allQuantLibTools.length,
+};
+
+// Future modules (to be implemented):
+// - stochastic.ts (36 tools) - GBM, Ornstein-Uhlenbeck, Monte Carlo
+// - ml.ts (48 tools) - Credit scoring, regression, clustering
+// - numerical.ts (28 tools) - Differentiation, FFT, interpolation
+// - analysis.ts (122 tools) - Fundamentals, ratios, valuation
+// - economics.ts (25 tools) - Equilibrium, game theory
+// - solver.ts (25 tools) - Bond yields, implied vol
+// - physics.ts (24 tools) - Entropy, thermodynamics
+// - scheduling.ts (14 tools) - Calendars, day counts
+// - regulatory.ts (11 tools) - Basel III, IFRS 9
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/instruments.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/instruments.ts
new file mode 100644
index 000000000..428684fb1
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/instruments.ts
@@ -0,0 +1,972 @@
+// QuantLib Instruments MCP Tools
+// 26 tools for bonds, swaps, FRA, money market, OIS, equity, commodity, FX, CDS, futures
+
+import type { InternalTool } from '../../types';
+import { quantlibApiCall, formatNumber, formatPercent } from '../../QuantLibMCPBridge';
+
+// ══════════════════════════════════════════════════════════════════════════════
+// FIXED BOND (4 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const fixedBondCashflowsTool: InternalTool = {
+ name: 'quantlib_instruments_bond_fixed_cashflows',
+ description: 'Generate cashflow schedule for a fixed-rate bond.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ issue_date: { type: 'string', description: 'Issue date (YYYY-MM-DD)' },
+ maturity_date: { type: 'string', description: 'Maturity date (YYYY-MM-DD)' },
+ coupon_rate: { type: 'number', description: 'Annual coupon rate (e.g., 0.05 for 5%)' },
+ face_value: { type: 'number', description: 'Face value (default: 100)' },
+ frequency: { type: 'number', description: 'Coupon frequency per year (default: 2)' },
+ day_count: { type: 'string', description: 'Day count convention (default: ACT/365)' },
+ settlement_date: { type: 'string', description: 'Settlement date (optional)' },
+ },
+ required: ['issue_date', 'maturity_date', 'coupon_rate'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/bond/fixed/cashflows', {
+ issue_date: args.issue_date,
+ maturity_date: args.maturity_date,
+ coupon_rate: args.coupon_rate,
+ face_value: args.face_value || 100,
+ frequency: args.frequency || 2,
+ day_count: args.day_count || 'ACT/365',
+ settlement_date: args.settlement_date,
+ }, apiKey);
+ return { success: true, data: result, message: `Generated ${result.cashflows?.length || 0} cashflows for fixed bond` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const fixedBondPriceTool: InternalTool = {
+ name: 'quantlib_instruments_bond_fixed_price',
+ description: 'Calculate price of a fixed-rate bond given yield.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ issue_date: { type: 'string', description: 'Issue date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ coupon_rate: { type: 'number', description: 'Annual coupon rate' },
+ yield_rate: { type: 'number', description: 'Yield to maturity' },
+ face_value: { type: 'number', description: 'Face value (default: 100)' },
+ frequency: { type: 'number', description: 'Coupon frequency (default: 2)' },
+ day_count: { type: 'string', description: 'Day count convention' },
+ settlement_date: { type: 'string', description: 'Settlement date' },
+ },
+ required: ['issue_date', 'maturity_date', 'coupon_rate', 'yield_rate'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/bond/fixed/price', {
+ issue_date: args.issue_date,
+ maturity_date: args.maturity_date,
+ coupon_rate: args.coupon_rate,
+ yield_rate: args.yield_rate,
+ face_value: args.face_value || 100,
+ frequency: args.frequency || 2,
+ day_count: args.day_count || 'ACT/365',
+ settlement_date: args.settlement_date,
+ }, apiKey);
+ return { success: true, data: result, message: `Bond price: ${formatNumber(result.clean_price)} (clean), ${formatNumber(result.dirty_price)} (dirty)` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const fixedBondYieldTool: InternalTool = {
+ name: 'quantlib_instruments_bond_fixed_yield',
+ description: 'Calculate yield to maturity from bond price.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ issue_date: { type: 'string', description: 'Issue date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ coupon_rate: { type: 'number', description: 'Annual coupon rate' },
+ clean_price: { type: 'number', description: 'Clean price' },
+ face_value: { type: 'number', description: 'Face value (default: 100)' },
+ frequency: { type: 'number', description: 'Coupon frequency (default: 2)' },
+ day_count: { type: 'string', description: 'Day count convention' },
+ settlement_date: { type: 'string', description: 'Settlement date' },
+ },
+ required: ['issue_date', 'maturity_date', 'coupon_rate', 'clean_price'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/bond/fixed/yield', {
+ issue_date: args.issue_date,
+ maturity_date: args.maturity_date,
+ coupon_rate: args.coupon_rate,
+ clean_price: args.clean_price,
+ face_value: args.face_value || 100,
+ frequency: args.frequency || 2,
+ day_count: args.day_count || 'ACT/365',
+ settlement_date: args.settlement_date,
+ }, apiKey);
+ return { success: true, data: result, message: `Yield to maturity: ${formatPercent(result.yield)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const fixedBondAnalyticsTool: InternalTool = {
+ name: 'quantlib_instruments_bond_fixed_analytics',
+ description: 'Calculate bond analytics (duration, convexity, etc.).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ issue_date: { type: 'string', description: 'Issue date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ coupon_rate: { type: 'number', description: 'Annual coupon rate' },
+ yield_rate: { type: 'number', description: 'Yield to maturity' },
+ face_value: { type: 'number', description: 'Face value (default: 100)' },
+ frequency: { type: 'number', description: 'Coupon frequency (default: 2)' },
+ day_count: { type: 'string', description: 'Day count convention' },
+ settlement_date: { type: 'string', description: 'Settlement date' },
+ },
+ required: ['issue_date', 'maturity_date', 'coupon_rate', 'yield_rate'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/bond/fixed/analytics', {
+ issue_date: args.issue_date,
+ maturity_date: args.maturity_date,
+ coupon_rate: args.coupon_rate,
+ yield_rate: args.yield_rate,
+ face_value: args.face_value || 100,
+ frequency: args.frequency || 2,
+ day_count: args.day_count || 'ACT/365',
+ settlement_date: args.settlement_date,
+ }, apiKey);
+ return { success: true, data: result, message: `Duration: ${formatNumber(result.duration)}, Convexity: ${formatNumber(result.convexity)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// ZERO COUPON BOND (1 tool)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const zeroBondPriceTool: InternalTool = {
+ name: 'quantlib_instruments_bond_zero_coupon_price',
+ description: 'Price a zero-coupon bond.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ issue_date: { type: 'string', description: 'Issue date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ face_value: { type: 'number', description: 'Face value (default: 100)' },
+ day_count: { type: 'string', description: 'Day count convention' },
+ settlement_date: { type: 'string', description: 'Settlement date' },
+ },
+ required: ['issue_date', 'maturity_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/bond/zero-coupon/price', {
+ issue_date: args.issue_date,
+ maturity_date: args.maturity_date,
+ face_value: args.face_value || 100,
+ day_count: args.day_count || 'ACT/365',
+ settlement_date: args.settlement_date,
+ }, apiKey);
+ return { success: true, data: result, message: `Zero-coupon bond price: ${formatNumber(result.price)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// INFLATION-LINKED BOND (1 tool)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const inflationBondCalcTool: InternalTool = {
+ name: 'quantlib_instruments_bond_inflation_linked',
+ description: 'Calculate inflation-linked bond values.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ issue_date: { type: 'string', description: 'Issue date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ coupon_rate: { type: 'number', description: 'Real coupon rate' },
+ base_cpi: { type: 'number', description: 'Base CPI at issue' },
+ current_cpi: { type: 'number', description: 'Current CPI' },
+ face_value: { type: 'number', description: 'Face value (default: 100)' },
+ frequency: { type: 'number', description: 'Coupon frequency (default: 2)' },
+ },
+ required: ['issue_date', 'maturity_date', 'coupon_rate', 'base_cpi', 'current_cpi'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/bond/inflation-linked', {
+ issue_date: args.issue_date,
+ maturity_date: args.maturity_date,
+ coupon_rate: args.coupon_rate,
+ base_cpi: args.base_cpi,
+ current_cpi: args.current_cpi,
+ face_value: args.face_value || 100,
+ frequency: args.frequency || 2,
+ }, apiKey);
+ return { success: true, data: result, message: `Inflation-adjusted principal: ${formatNumber(result.adjusted_principal)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// INTEREST RATE SWAP (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const irsValueTool: InternalTool = {
+ name: 'quantlib_instruments_swap_irs_value',
+ description: 'Calculate the present value of an interest rate swap.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ effective_date: { type: 'string', description: 'Effective date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ notional: { type: 'number', description: 'Notional amount' },
+ fixed_rate: { type: 'number', description: 'Fixed rate' },
+ curve_tenors: { type: 'string', description: 'JSON array of curve tenors' },
+ curve_rates: { type: 'string', description: 'JSON array of curve rates' },
+ reference_date: { type: 'string', description: 'Valuation date' },
+ frequency: { type: 'number', description: 'Payment frequency (default: 2)' },
+ day_count: { type: 'string', description: 'Day count convention' },
+ swap_type: { type: 'string', description: 'payer or receiver (default: payer)' },
+ },
+ required: ['effective_date', 'maturity_date', 'notional', 'fixed_rate', 'curve_tenors', 'curve_rates', 'reference_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/swap/irs/value', {
+ effective_date: args.effective_date,
+ maturity_date: args.maturity_date,
+ notional: args.notional,
+ fixed_rate: args.fixed_rate,
+ curve_tenors: JSON.parse(args.curve_tenors as string),
+ curve_rates: JSON.parse(args.curve_rates as string),
+ reference_date: args.reference_date,
+ frequency: args.frequency || 2,
+ day_count: args.day_count || 'ACT/365',
+ swap_type: args.swap_type || 'payer',
+ }, apiKey);
+ return { success: true, data: result, message: `IRS NPV: ${formatNumber(result.npv)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const irsParRateTool: InternalTool = {
+ name: 'quantlib_instruments_swap_irs_par_rate',
+ description: 'Calculate the par swap rate.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ effective_date: { type: 'string', description: 'Effective date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ notional: { type: 'number', description: 'Notional amount' },
+ fixed_rate: { type: 'number', description: 'Current fixed rate' },
+ curve_tenors: { type: 'string', description: 'JSON array of curve tenors' },
+ curve_rates: { type: 'string', description: 'JSON array of curve rates' },
+ reference_date: { type: 'string', description: 'Valuation date' },
+ frequency: { type: 'number', description: 'Payment frequency' },
+ day_count: { type: 'string', description: 'Day count convention' },
+ swap_type: { type: 'string', description: 'payer or receiver' },
+ },
+ required: ['effective_date', 'maturity_date', 'notional', 'fixed_rate', 'curve_tenors', 'curve_rates', 'reference_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/swap/irs/par-rate', {
+ effective_date: args.effective_date,
+ maturity_date: args.maturity_date,
+ notional: args.notional,
+ fixed_rate: args.fixed_rate,
+ curve_tenors: JSON.parse(args.curve_tenors as string),
+ curve_rates: JSON.parse(args.curve_rates as string),
+ reference_date: args.reference_date,
+ frequency: args.frequency || 2,
+ day_count: args.day_count || 'ACT/365',
+ swap_type: args.swap_type || 'payer',
+ }, apiKey);
+ return { success: true, data: result, message: `Par swap rate: ${formatPercent(result.par_rate)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const irsDv01Tool: InternalTool = {
+ name: 'quantlib_instruments_swap_irs_dv01',
+ description: 'Calculate DV01 (dollar value of 1bp) for an IRS.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ effective_date: { type: 'string', description: 'Effective date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ notional: { type: 'number', description: 'Notional amount' },
+ fixed_rate: { type: 'number', description: 'Fixed rate' },
+ curve_tenors: { type: 'string', description: 'JSON array of curve tenors' },
+ curve_rates: { type: 'string', description: 'JSON array of curve rates' },
+ reference_date: { type: 'string', description: 'Valuation date' },
+ frequency: { type: 'number', description: 'Payment frequency' },
+ day_count: { type: 'string', description: 'Day count convention' },
+ swap_type: { type: 'string', description: 'payer or receiver' },
+ },
+ required: ['effective_date', 'maturity_date', 'notional', 'fixed_rate', 'curve_tenors', 'curve_rates', 'reference_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/swap/irs/dv01', {
+ effective_date: args.effective_date,
+ maturity_date: args.maturity_date,
+ notional: args.notional,
+ fixed_rate: args.fixed_rate,
+ curve_tenors: JSON.parse(args.curve_tenors as string),
+ curve_rates: JSON.parse(args.curve_rates as string),
+ reference_date: args.reference_date,
+ frequency: args.frequency || 2,
+ day_count: args.day_count || 'ACT/365',
+ swap_type: args.swap_type || 'payer',
+ }, apiKey);
+ return { success: true, data: result, message: `IRS DV01: ${formatNumber(result.dv01)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// FRA (2 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const fraValueTool: InternalTool = {
+ name: 'quantlib_instruments_fra_value',
+ description: 'Calculate the present value of a Forward Rate Agreement.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ trade_date: { type: 'string', description: 'Trade date' },
+ start_months: { type: 'number', description: 'Start period in months' },
+ end_months: { type: 'number', description: 'End period in months' },
+ notional: { type: 'number', description: 'Notional amount' },
+ fixed_rate: { type: 'number', description: 'FRA fixed rate' },
+ curve_tenors: { type: 'string', description: 'JSON array of curve tenors' },
+ curve_rates: { type: 'string', description: 'JSON array of curve rates' },
+ reference_date: { type: 'string', description: 'Valuation date' },
+ },
+ required: ['trade_date', 'start_months', 'end_months', 'notional', 'fixed_rate', 'curve_tenors', 'curve_rates', 'reference_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/fra/value', {
+ trade_date: args.trade_date,
+ start_months: args.start_months,
+ end_months: args.end_months,
+ notional: args.notional,
+ fixed_rate: args.fixed_rate,
+ curve_tenors: JSON.parse(args.curve_tenors as string),
+ curve_rates: JSON.parse(args.curve_rates as string),
+ reference_date: args.reference_date,
+ }, apiKey);
+ return { success: true, data: result, message: `FRA NPV: ${formatNumber(result.npv)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const fraBreakEvenTool: InternalTool = {
+ name: 'quantlib_instruments_fra_break_even',
+ description: 'Calculate the break-even rate for a FRA.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ trade_date: { type: 'string', description: 'Trade date' },
+ start_months: { type: 'number', description: 'Start period in months' },
+ end_months: { type: 'number', description: 'End period in months' },
+ notional: { type: 'number', description: 'Notional amount' },
+ fixed_rate: { type: 'number', description: 'Current FRA rate' },
+ curve_tenors: { type: 'string', description: 'JSON array of curve tenors' },
+ curve_rates: { type: 'string', description: 'JSON array of curve rates' },
+ reference_date: { type: 'string', description: 'Valuation date' },
+ },
+ required: ['trade_date', 'start_months', 'end_months', 'notional', 'fixed_rate', 'curve_tenors', 'curve_rates', 'reference_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/fra/break-even', {
+ trade_date: args.trade_date,
+ start_months: args.start_months,
+ end_months: args.end_months,
+ notional: args.notional,
+ fixed_rate: args.fixed_rate,
+ curve_tenors: JSON.parse(args.curve_tenors as string),
+ curve_rates: JSON.parse(args.curve_rates as string),
+ reference_date: args.reference_date,
+ }, apiKey);
+ return { success: true, data: result, message: `FRA break-even rate: ${formatPercent(result.break_even_rate)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// MONEY MARKET (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const depositTool: InternalTool = {
+ name: 'quantlib_instruments_money_market_deposit',
+ description: 'Calculate money market deposit value and accrued interest.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ start_date: { type: 'string', description: 'Start date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ notional: { type: 'number', description: 'Deposit amount' },
+ rate: { type: 'number', description: 'Interest rate' },
+ day_count: { type: 'string', description: 'Day count convention (default: ACT/360)' },
+ },
+ required: ['start_date', 'maturity_date', 'notional', 'rate'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/money-market/deposit', {
+ start_date: args.start_date,
+ maturity_date: args.maturity_date,
+ notional: args.notional,
+ rate: args.rate,
+ day_count: args.day_count || 'ACT/360',
+ }, apiKey);
+ return { success: true, data: result, message: `Maturity value: ${formatNumber(result.maturity_value)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const tbillTool: InternalTool = {
+ name: 'quantlib_instruments_money_market_tbill',
+ description: 'Calculate T-Bill price/yield conversion.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ settlement_date: { type: 'string', description: 'Settlement date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ face_value: { type: 'number', description: 'Face value (default: 100)' },
+ discount_rate: { type: 'number', description: 'Discount rate (provide either this or price)' },
+ price: { type: 'number', description: 'Price (provide either this or discount_rate)' },
+ },
+ required: ['settlement_date', 'maturity_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/money-market/tbill', {
+ settlement_date: args.settlement_date,
+ maturity_date: args.maturity_date,
+ face_value: args.face_value || 100,
+ discount_rate: args.discount_rate,
+ price: args.price,
+ }, apiKey);
+ return { success: true, data: result, message: `T-Bill: price=${formatNumber(result.price)}, yield=${formatPercent(result.yield)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const repoTool: InternalTool = {
+ name: 'quantlib_instruments_money_market_repo',
+ description: 'Calculate repo transaction values.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ start_date: { type: 'string', description: 'Repo start date' },
+ end_date: { type: 'string', description: 'Repo end date' },
+ collateral_value: { type: 'number', description: 'Collateral market value' },
+ repo_rate: { type: 'number', description: 'Repo rate' },
+ haircut: { type: 'number', description: 'Haircut percentage (default: 0.02)' },
+ },
+ required: ['start_date', 'end_date', 'collateral_value', 'repo_rate'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/money-market/repo', {
+ start_date: args.start_date,
+ end_date: args.end_date,
+ collateral_value: args.collateral_value,
+ repo_rate: args.repo_rate,
+ haircut: args.haircut || 0.02,
+ }, apiKey);
+ return { success: true, data: result, message: `Repo: purchase=${formatNumber(result.purchase_price)}, repurchase=${formatNumber(result.repurchase_price)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// OIS (2 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const oisValueTool: InternalTool = {
+ name: 'quantlib_instruments_ois_value',
+ description: 'Calculate the present value of an OIS swap.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Valuation date' },
+ effective_date: { type: 'string', description: 'Effective date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ notional: { type: 'number', description: 'Notional amount' },
+ fixed_rate: { type: 'number', description: 'Fixed OIS rate' },
+ curve_tenors: { type: 'string', description: 'JSON array of curve tenors' },
+ curve_rates: { type: 'string', description: 'JSON array of curve rates' },
+ index: { type: 'string', description: 'OIS index (default: SOFR)' },
+ },
+ required: ['reference_date', 'effective_date', 'maturity_date', 'notional', 'fixed_rate', 'curve_tenors', 'curve_rates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/ois/value', {
+ reference_date: args.reference_date,
+ effective_date: args.effective_date,
+ maturity_date: args.maturity_date,
+ notional: args.notional,
+ fixed_rate: args.fixed_rate,
+ curve_tenors: JSON.parse(args.curve_tenors as string),
+ curve_rates: JSON.parse(args.curve_rates as string),
+ index: args.index || 'SOFR',
+ }, apiKey);
+ return { success: true, data: result, message: `OIS NPV: ${formatNumber(result.npv)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const oisBuildCurveTool: InternalTool = {
+ name: 'quantlib_instruments_ois_build_curve',
+ description: 'Build OIS discount curve from OIS rates.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Reference date' },
+ ois_rates: { type: 'string', description: 'JSON array of OIS rates' },
+ },
+ required: ['reference_date', 'ois_rates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/ois/build-curve', {
+ reference_date: args.reference_date,
+ ois_rates: JSON.parse(args.ois_rates as string),
+ }, apiKey);
+ return { success: true, data: result, message: 'Built OIS discount curve' };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// EQUITY (2 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const varianceSwapTool: InternalTool = {
+ name: 'quantlib_instruments_equity_variance_swap',
+ description: 'Calculate variance swap P&L.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ strike_variance: { type: 'number', description: 'Strike variance' },
+ realized_returns: { type: 'string', description: 'JSON array of realized returns' },
+ notional: { type: 'number', description: 'Variance notional' },
+ annualization_factor: { type: 'number', description: 'Annualization factor (default: 252)' },
+ },
+ required: ['strike_variance', 'realized_returns', 'notional'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/equity/variance-swap', {
+ strike_variance: args.strike_variance,
+ realized_returns: JSON.parse(args.realized_returns as string),
+ notional: args.notional,
+ annualization_factor: args.annualization_factor || 252,
+ }, apiKey);
+ return { success: true, data: result, message: `Variance swap P&L: ${formatNumber(result.pnl)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const volatilitySwapTool: InternalTool = {
+ name: 'quantlib_instruments_equity_volatility_swap',
+ description: 'Calculate volatility swap P&L.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ strike_vol: { type: 'number', description: 'Strike volatility' },
+ realized_returns: { type: 'string', description: 'JSON array of realized returns' },
+ notional: { type: 'number', description: 'Vega notional' },
+ annualization_factor: { type: 'number', description: 'Annualization factor (default: 252)' },
+ },
+ required: ['strike_vol', 'realized_returns', 'notional'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/equity/volatility-swap', {
+ strike_vol: args.strike_vol,
+ realized_returns: JSON.parse(args.realized_returns as string),
+ notional: args.notional,
+ annualization_factor: args.annualization_factor || 252,
+ }, apiKey);
+ return { success: true, data: result, message: `Volatility swap P&L: ${formatNumber(result.pnl)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// COMMODITY (1 tool)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const commodityFutureTool: InternalTool = {
+ name: 'quantlib_instruments_commodity_future',
+ description: 'Calculate commodity futures analytics.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ commodity_type: { type: 'string', description: 'Commodity type (e.g., CRUDE, GOLD)' },
+ spot_price: { type: 'number', description: 'Current spot price' },
+ delivery_date: { type: 'string', description: 'Delivery date' },
+ trade_date: { type: 'string', description: 'Trade date' },
+ futures_price: { type: 'number', description: 'Futures price' },
+ contract_size: { type: 'number', description: 'Contract size (default: 1)' },
+ },
+ required: ['commodity_type', 'spot_price', 'delivery_date', 'trade_date', 'futures_price'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/commodity/future', {
+ commodity_type: args.commodity_type,
+ spot_price: args.spot_price,
+ delivery_date: args.delivery_date,
+ trade_date: args.trade_date,
+ futures_price: args.futures_price,
+ contract_size: args.contract_size || 1,
+ }, apiKey);
+ return { success: true, data: result, message: `${args.commodity_type} futures: basis=${formatNumber(result.basis)}, carry=${formatPercent(result.implied_carry)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// FX (2 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const fxForwardTool: InternalTool = {
+ name: 'quantlib_instruments_fx_forward',
+ description: 'Calculate FX forward points and value.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot_rate: { type: 'number', description: 'Current spot rate' },
+ base_rate: { type: 'number', description: 'Base currency interest rate' },
+ quote_rate: { type: 'number', description: 'Quote currency interest rate' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ notional: { type: 'number', description: 'Notional amount' },
+ pair: { type: 'string', description: 'Currency pair (default: EURUSD)' },
+ },
+ required: ['spot_rate', 'base_rate', 'quote_rate', 'time_to_maturity', 'notional'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/fx/forward', {
+ spot_rate: args.spot_rate,
+ base_rate: args.base_rate,
+ quote_rate: args.quote_rate,
+ time_to_maturity: args.time_to_maturity,
+ notional: args.notional,
+ pair: args.pair || 'EURUSD',
+ }, apiKey);
+ return { success: true, data: result, message: `FX forward: ${formatNumber(result.forward_rate)}, points=${formatNumber(result.forward_points * 10000)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const garmanKohlhagenTool: InternalTool = {
+ name: 'quantlib_instruments_fx_garman_kohlhagen',
+ description: 'Price FX options using Garman-Kohlhagen model.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Spot FX rate' },
+ strike: { type: 'number', description: 'Strike rate' },
+ domestic_rate: { type: 'number', description: 'Domestic interest rate' },
+ foreign_rate: { type: 'number', description: 'Foreign interest rate' },
+ volatility: { type: 'number', description: 'FX volatility' },
+ time_to_expiry: { type: 'number', description: 'Time to expiry in years' },
+ option_type: { type: 'string', description: 'call or put (default: call)' },
+ },
+ required: ['spot', 'strike', 'domestic_rate', 'foreign_rate', 'volatility', 'time_to_expiry'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/fx/garman-kohlhagen', {
+ spot: args.spot,
+ strike: args.strike,
+ domestic_rate: args.domestic_rate,
+ foreign_rate: args.foreign_rate,
+ volatility: args.volatility,
+ time_to_expiry: args.time_to_expiry,
+ option_type: args.option_type || 'call',
+ }, apiKey);
+ return { success: true, data: result, message: `FX ${args.option_type || 'call'} price: ${formatNumber(result.price)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CDS (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const cdsValueTool: InternalTool = {
+ name: 'quantlib_instruments_cds_value',
+ description: 'Calculate CDS present value.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ reference_date: { type: 'string', description: 'Valuation date' },
+ effective_date: { type: 'string', description: 'Effective date' },
+ maturity_date: { type: 'string', description: 'Maturity date' },
+ notional: { type: 'number', description: 'Notional amount' },
+ spread_bps: { type: 'number', description: 'CDS spread in bps' },
+ curve_tenors: { type: 'string', description: 'JSON array of curve tenors' },
+ curve_rates: { type: 'string', description: 'JSON array of curve rates' },
+ recovery_rate: { type: 'number', description: 'Recovery rate (default: 0.4)' },
+ frequency: { type: 'number', description: 'Premium frequency (default: 4)' },
+ },
+ required: ['reference_date', 'effective_date', 'maturity_date', 'notional', 'spread_bps', 'curve_tenors', 'curve_rates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/cds/value', {
+ reference_date: args.reference_date,
+ effective_date: args.effective_date,
+ maturity_date: args.maturity_date,
+ notional: args.notional,
+ spread_bps: args.spread_bps,
+ curve_tenors: JSON.parse(args.curve_tenors as string),
+ curve_rates: JSON.parse(args.curve_rates as string),
+ recovery_rate: args.recovery_rate || 0.4,
+ frequency: args.frequency || 4,
+ }, apiKey);
+ return { success: true, data: result, message: `CDS NPV: ${formatNumber(result.npv)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const cdsHazardRateTool: InternalTool = {
+ name: 'quantlib_instruments_cds_hazard_rate',
+ description: 'Calculate implied hazard rate from CDS spread.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spread_bps: { type: 'number', description: 'CDS spread in bps' },
+ recovery_rate: { type: 'number', description: 'Recovery rate (default: 0.4)' },
+ },
+ required: ['spread_bps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/cds/hazard-rate', {
+ spread_bps: args.spread_bps,
+ recovery_rate: args.recovery_rate || 0.4,
+ }, apiKey);
+ return { success: true, data: result, message: `Implied hazard rate: ${formatPercent(result.hazard_rate)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const cdsSurvivalProbTool: InternalTool = {
+ name: 'quantlib_instruments_cds_survival_probability',
+ description: 'Calculate survival probabilities from hazard rate.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ hazard_rate: { type: 'number', description: 'Constant hazard rate' },
+ time_horizon: { type: 'number', description: 'Time horizon in years' },
+ time_points: { type: 'string', description: 'Optional JSON array of time points' },
+ },
+ required: ['hazard_rate', 'time_horizon'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/cds/survival-probability', {
+ hazard_rate: args.hazard_rate,
+ time_horizon: args.time_horizon,
+ time_points: args.time_points ? JSON.parse(args.time_points as string) : undefined,
+ }, apiKey);
+ return { success: true, data: result, message: `Survival probability at ${args.time_horizon}Y: ${formatPercent(result.survival_probability)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// FUTURES (2 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const stirFutureTool: InternalTool = {
+ name: 'quantlib_instruments_futures_stir',
+ description: 'Calculate STIR (Short Term Interest Rate) futures analytics.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ price: { type: 'number', description: 'Futures price (e.g., 95.50)' },
+ contract_date: { type: 'string', description: 'Contract expiry date' },
+ reference_date: { type: 'string', description: 'Valuation date' },
+ notional: { type: 'number', description: 'Notional (default: 1000000)' },
+ tick_value: { type: 'number', description: 'Tick value (default: 25)' },
+ },
+ required: ['price', 'contract_date', 'reference_date'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/futures/stir', {
+ price: args.price,
+ contract_date: args.contract_date,
+ reference_date: args.reference_date,
+ notional: args.notional || 1000000,
+ tick_value: args.tick_value || 25,
+ }, apiKey);
+ return { success: true, data: result, message: `STIR implied rate: ${formatPercent(result.implied_rate)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const bondCtdTool: InternalTool = {
+ name: 'quantlib_instruments_futures_bond_ctd',
+ description: 'Find cheapest-to-deliver bond for bond futures.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ futures_price: { type: 'number', description: 'Futures price' },
+ delivery_date: { type: 'string', description: 'Delivery date' },
+ reference_date: { type: 'string', description: 'Valuation date' },
+ deliverables: { type: 'string', description: 'JSON array of deliverable bonds with conversion factors' },
+ },
+ required: ['futures_price', 'delivery_date', 'reference_date', 'deliverables'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/instruments/futures/bond/ctd', {
+ futures_price: args.futures_price,
+ delivery_date: args.delivery_date,
+ reference_date: args.reference_date,
+ deliverables: JSON.parse(args.deliverables as string),
+ }, apiKey);
+ return { success: true, data: result, message: `CTD: ${result.ctd_bond}, basis=${formatNumber(result.basis)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// EXPORT ALL TOOLS
+// ══════════════════════════════════════════════════════════════════════════════
+
+export const quantlibInstrumentsTools: InternalTool[] = [
+ // Fixed Bond (4)
+ fixedBondCashflowsTool,
+ fixedBondPriceTool,
+ fixedBondYieldTool,
+ fixedBondAnalyticsTool,
+ // Zero Coupon (1)
+ zeroBondPriceTool,
+ // Inflation-Linked (1)
+ inflationBondCalcTool,
+ // IRS (3)
+ irsValueTool,
+ irsParRateTool,
+ irsDv01Tool,
+ // FRA (2)
+ fraValueTool,
+ fraBreakEvenTool,
+ // Money Market (3)
+ depositTool,
+ tbillTool,
+ repoTool,
+ // OIS (2)
+ oisValueTool,
+ oisBuildCurveTool,
+ // Equity (2)
+ varianceSwapTool,
+ volatilitySwapTool,
+ // Commodity (1)
+ commodityFutureTool,
+ // FX (2)
+ fxForwardTool,
+ garmanKohlhagenTool,
+ // CDS (3)
+ cdsValueTool,
+ cdsHazardRateTool,
+ cdsSurvivalProbTool,
+ // Futures (2)
+ stirFutureTool,
+ bondCtdTool,
+];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/models.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/models.ts
new file mode 100644
index 000000000..9a8dbd2fa
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/models.ts
@@ -0,0 +1,584 @@
+// QuantLib Models MCP Tools
+// 14 tools for short rate models, Hull-White, Heston, Merton, Kou, Variance Gamma, Dupire, SVI
+
+import type { InternalTool } from '../../types';
+import { quantlibApiCall, formatNumber, formatPercent } from '../../QuantLibMCPBridge';
+
+// ══════════════════════════════════════════════════════════════════════════════
+// SHORT RATE MODELS (4 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const shortRateBondPriceTool: InternalTool = {
+ name: 'quantlib_models_short_rate_bond_price',
+ description: 'Price zero-coupon bonds using short rate models (Vasicek, CIR, Hull-White).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ model: { type: 'string', description: 'Model type: vasicek, cir, or hull_white (default: vasicek)' },
+ kappa: { type: 'number', description: 'Mean reversion speed' },
+ theta: { type: 'number', description: 'Long-term mean rate' },
+ sigma: { type: 'number', description: 'Volatility' },
+ r0: { type: 'number', description: 'Initial short rate' },
+ maturities: { type: 'string', description: 'JSON array of bond maturities in years' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/short-rate/bond-price', {
+ model: args.model,
+ kappa: args.kappa,
+ theta: args.theta,
+ sigma: args.sigma,
+ r0: args.r0,
+ maturities: args.maturities ? JSON.parse(args.maturities as string) : undefined,
+ }, apiKey);
+ return { success: true, data: result, message: `Priced bonds using ${args.model || 'vasicek'} model` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const shortRateYieldCurveTool: InternalTool = {
+ name: 'quantlib_models_short_rate_yield_curve',
+ description: 'Generate yield curve from short rate model parameters.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ model: { type: 'string', description: 'Model type: vasicek, cir, or hull_white' },
+ kappa: { type: 'number', description: 'Mean reversion speed' },
+ theta: { type: 'number', description: 'Long-term mean rate' },
+ sigma: { type: 'number', description: 'Volatility' },
+ r0: { type: 'number', description: 'Initial short rate' },
+ maturities: { type: 'string', description: 'JSON array of maturities in years' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/short-rate/yield-curve', {
+ model: args.model,
+ kappa: args.kappa,
+ theta: args.theta,
+ sigma: args.sigma,
+ r0: args.r0,
+ maturities: args.maturities ? JSON.parse(args.maturities as string) : undefined,
+ }, apiKey);
+ return { success: true, data: result, message: `Generated yield curve from ${args.model || 'vasicek'} model` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const shortRateMonteCarloTool: InternalTool = {
+ name: 'quantlib_models_short_rate_monte_carlo',
+ description: 'Simulate short rate paths using Monte Carlo.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ model: { type: 'string', description: 'Model type: vasicek, cir, or hull_white' },
+ kappa: { type: 'number', description: 'Mean reversion speed' },
+ theta: { type: 'number', description: 'Long-term mean rate' },
+ sigma: { type: 'number', description: 'Volatility' },
+ r0: { type: 'number', description: 'Initial short rate' },
+ T: { type: 'number', description: 'Time horizon in years' },
+ n_steps: { type: 'number', description: 'Number of time steps' },
+ n_paths: { type: 'number', description: 'Number of simulation paths' },
+ seed: { type: 'number', description: 'Random seed for reproducibility' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/short-rate/monte-carlo', {
+ model: args.model,
+ kappa: args.kappa,
+ theta: args.theta,
+ sigma: args.sigma,
+ r0: args.r0,
+ T: args.T,
+ n_steps: args.n_steps,
+ n_paths: args.n_paths,
+ seed: args.seed,
+ }, apiKey);
+ return { success: true, data: result, message: `Simulated ${args.n_paths || 1000} paths over ${args.T || 1}Y` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const shortRateBondOptionTool: InternalTool = {
+ name: 'quantlib_models_short_rate_bond_option',
+ description: 'Price bond options using short rate models.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ model: { type: 'string', description: 'Model type: vasicek, cir, or hull_white' },
+ kappa: { type: 'number', description: 'Mean reversion speed' },
+ theta: { type: 'number', description: 'Long-term mean rate' },
+ sigma: { type: 'number', description: 'Volatility' },
+ r0: { type: 'number', description: 'Initial short rate' },
+ T: { type: 'number', description: 'Option maturity in years' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/short-rate/bond-option', {
+ model: args.model,
+ kappa: args.kappa,
+ theta: args.theta,
+ sigma: args.sigma,
+ r0: args.r0,
+ T: args.T,
+ }, apiKey);
+ return { success: true, data: result, message: `Priced bond option using ${args.model || 'vasicek'} model` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// HULL-WHITE (1 tool)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const hullWhiteCalibrateTool: InternalTool = {
+ name: 'quantlib_models_hull_white_calibrate',
+ description: 'Calibrate Hull-White model parameters to market data.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ kappa: { type: 'number', description: 'Initial guess for mean reversion' },
+ sigma: { type: 'number', description: 'Initial guess for volatility' },
+ r0: { type: 'number', description: 'Initial short rate' },
+ market_tenors: { type: 'string', description: 'JSON array of market tenors' },
+ market_rates: { type: 'string', description: 'JSON array of market rates' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/hull-white/calibrate', {
+ kappa: args.kappa,
+ sigma: args.sigma,
+ r0: args.r0,
+ market_tenors: args.market_tenors ? JSON.parse(args.market_tenors as string) : undefined,
+ market_rates: args.market_rates ? JSON.parse(args.market_rates as string) : undefined,
+ }, apiKey);
+ return { success: true, data: result, message: `Calibrated Hull-White: κ=${formatNumber(result.kappa)}, σ=${formatNumber(result.sigma)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// HESTON MODEL (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const hestonPriceTool: InternalTool = {
+ name: 'quantlib_models_heston_price',
+ description: 'Price European options using the Heston stochastic volatility model.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ S0: { type: 'number', description: 'Initial spot price' },
+ v0: { type: 'number', description: 'Initial variance' },
+ r: { type: 'number', description: 'Risk-free rate' },
+ kappa: { type: 'number', description: 'Mean reversion speed of variance' },
+ theta: { type: 'number', description: 'Long-term variance' },
+ sigma_v: { type: 'number', description: 'Volatility of variance (vol of vol)' },
+ rho: { type: 'number', description: 'Correlation between spot and variance' },
+ strike: { type: 'number', description: 'Option strike' },
+ T: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type: call or put (default: call)' },
+ },
+ required: ['S0', 'v0', 'r', 'kappa', 'theta', 'sigma_v', 'rho', 'strike', 'T'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/heston/price', {
+ S0: args.S0,
+ v0: args.v0,
+ r: args.r,
+ kappa: args.kappa,
+ theta: args.theta,
+ sigma_v: args.sigma_v,
+ rho: args.rho,
+ strike: args.strike,
+ T: args.T,
+ option_type: args.option_type,
+ }, apiKey);
+ return { success: true, data: result, message: `Heston ${args.option_type || 'call'} price: ${formatNumber(result.price)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const hestonImpliedVolTool: InternalTool = {
+ name: 'quantlib_models_heston_implied_vol',
+ description: 'Calculate implied volatility from Heston model price.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ S0: { type: 'number', description: 'Initial spot price' },
+ v0: { type: 'number', description: 'Initial variance' },
+ r: { type: 'number', description: 'Risk-free rate' },
+ kappa: { type: 'number', description: 'Mean reversion speed' },
+ theta: { type: 'number', description: 'Long-term variance' },
+ sigma_v: { type: 'number', description: 'Vol of vol' },
+ rho: { type: 'number', description: 'Correlation' },
+ strike: { type: 'number', description: 'Option strike' },
+ T: { type: 'number', description: 'Time to maturity' },
+ option_type: { type: 'string', description: 'Option type: call or put' },
+ },
+ required: ['S0', 'v0', 'r', 'kappa', 'theta', 'sigma_v', 'rho', 'strike', 'T'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/heston/implied-vol', {
+ S0: args.S0,
+ v0: args.v0,
+ r: args.r,
+ kappa: args.kappa,
+ theta: args.theta,
+ sigma_v: args.sigma_v,
+ rho: args.rho,
+ strike: args.strike,
+ T: args.T,
+ option_type: args.option_type,
+ }, apiKey);
+ return { success: true, data: result, message: `Heston implied vol: ${formatPercent(result.implied_vol)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const hestonMonteCarloTool: InternalTool = {
+ name: 'quantlib_models_heston_monte_carlo',
+ description: 'Price options using Heston Monte Carlo simulation.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ S0: { type: 'number', description: 'Initial spot price' },
+ v0: { type: 'number', description: 'Initial variance' },
+ r: { type: 'number', description: 'Risk-free rate' },
+ kappa: { type: 'number', description: 'Mean reversion speed' },
+ theta: { type: 'number', description: 'Long-term variance' },
+ sigma_v: { type: 'number', description: 'Vol of vol' },
+ rho: { type: 'number', description: 'Correlation' },
+ strike: { type: 'number', description: 'Option strike' },
+ T: { type: 'number', description: 'Time to maturity' },
+ option_type: { type: 'string', description: 'Option type: call or put' },
+ n_paths: { type: 'number', description: 'Number of Monte Carlo paths' },
+ n_steps: { type: 'number', description: 'Number of time steps' },
+ seed: { type: 'number', description: 'Random seed' },
+ },
+ required: ['S0', 'v0', 'r', 'kappa', 'theta', 'sigma_v', 'rho', 'strike', 'T'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/heston/monte-carlo', {
+ S0: args.S0,
+ v0: args.v0,
+ r: args.r,
+ kappa: args.kappa,
+ theta: args.theta,
+ sigma_v: args.sigma_v,
+ rho: args.rho,
+ strike: args.strike,
+ T: args.T,
+ option_type: args.option_type,
+ n_paths: args.n_paths,
+ n_steps: args.n_steps,
+ seed: args.seed,
+ }, apiKey);
+ return { success: true, data: result, message: `Heston MC price: ${formatNumber(result.price)} (SE: ${formatNumber(result.std_error)})` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// MERTON JUMP DIFFUSION (2 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const mertonPriceTool: InternalTool = {
+ name: 'quantlib_models_merton_price',
+ description: 'Price options using Merton jump-diffusion model (analytical).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ S: { type: 'number', description: 'Spot price' },
+ K: { type: 'number', description: 'Strike price' },
+ T: { type: 'number', description: 'Time to maturity in years' },
+ r: { type: 'number', description: 'Risk-free rate' },
+ sigma: { type: 'number', description: 'Diffusion volatility' },
+ lambda_jump: { type: 'number', description: 'Jump intensity (jumps per year)' },
+ mu_jump: { type: 'number', description: 'Mean log jump size' },
+ sigma_jump: { type: 'number', description: 'Jump size volatility' },
+ q: { type: 'number', description: 'Dividend yield (optional)' },
+ },
+ required: ['S', 'K', 'T', 'r', 'sigma', 'lambda_jump', 'mu_jump', 'sigma_jump'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/merton/price', {
+ S: args.S,
+ K: args.K,
+ T: args.T,
+ r: args.r,
+ sigma: args.sigma,
+ lambda_jump: args.lambda_jump,
+ mu_jump: args.mu_jump,
+ sigma_jump: args.sigma_jump,
+ q: args.q,
+ }, apiKey);
+ return { success: true, data: result, message: `Merton price: ${formatNumber(result.price)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const mertonFFTTool: InternalTool = {
+ name: 'quantlib_models_merton_fft',
+ description: 'Price options using Merton model with FFT method.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ S: { type: 'number', description: 'Spot price' },
+ K: { type: 'number', description: 'Strike price' },
+ T: { type: 'number', description: 'Time to maturity' },
+ r: { type: 'number', description: 'Risk-free rate' },
+ sigma: { type: 'number', description: 'Diffusion volatility' },
+ lambda_jump: { type: 'number', description: 'Jump intensity' },
+ mu_jump: { type: 'number', description: 'Mean log jump size' },
+ sigma_jump: { type: 'number', description: 'Jump size volatility' },
+ q: { type: 'number', description: 'Dividend yield (optional)' },
+ },
+ required: ['S', 'K', 'T', 'r', 'sigma', 'lambda_jump', 'mu_jump', 'sigma_jump'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/merton/fft', {
+ S: args.S,
+ K: args.K,
+ T: args.T,
+ r: args.r,
+ sigma: args.sigma,
+ lambda_jump: args.lambda_jump,
+ mu_jump: args.mu_jump,
+ sigma_jump: args.sigma_jump,
+ q: args.q,
+ }, apiKey);
+ return { success: true, data: result, message: `Merton FFT price: ${formatNumber(result.price)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// KOU DOUBLE EXPONENTIAL JUMP (1 tool)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const kouPriceTool: InternalTool = {
+ name: 'quantlib_models_kou_price',
+ description: 'Price options using Kou double-exponential jump-diffusion model.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ S: { type: 'number', description: 'Spot price' },
+ K: { type: 'number', description: 'Strike price' },
+ T: { type: 'number', description: 'Time to maturity' },
+ r: { type: 'number', description: 'Risk-free rate' },
+ sigma: { type: 'number', description: 'Diffusion volatility' },
+ lambda_jump: { type: 'number', description: 'Jump intensity' },
+ p: { type: 'number', description: 'Probability of upward jump (0-1)' },
+ eta1: { type: 'number', description: 'Rate of upward jump (>1)' },
+ eta2: { type: 'number', description: 'Rate of downward jump (>0)' },
+ q: { type: 'number', description: 'Dividend yield (optional)' },
+ },
+ required: ['S', 'K', 'T', 'r', 'sigma', 'lambda_jump', 'p', 'eta1', 'eta2'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/kou/price', {
+ S: args.S,
+ K: args.K,
+ T: args.T,
+ r: args.r,
+ sigma: args.sigma,
+ lambda_jump: args.lambda_jump,
+ p: args.p,
+ eta1: args.eta1,
+ eta2: args.eta2,
+ q: args.q,
+ }, apiKey);
+ return { success: true, data: result, message: `Kou price: ${formatNumber(result.price)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// VARIANCE GAMMA (1 tool)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const varianceGammaPriceTool: InternalTool = {
+ name: 'quantlib_models_variance_gamma_price',
+ description: 'Price options using Variance Gamma model.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ S: { type: 'number', description: 'Spot price' },
+ K: { type: 'number', description: 'Strike price' },
+ T: { type: 'number', description: 'Time to maturity' },
+ r: { type: 'number', description: 'Risk-free rate' },
+ sigma: { type: 'number', description: 'Volatility parameter' },
+ theta_vg: { type: 'number', description: 'Drift/skewness parameter' },
+ nu: { type: 'number', description: 'Variance rate (kurtosis parameter)' },
+ q: { type: 'number', description: 'Dividend yield (optional)' },
+ },
+ required: ['S', 'K', 'T', 'r', 'sigma', 'theta_vg', 'nu'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/variance-gamma/price', {
+ S: args.S,
+ K: args.K,
+ T: args.T,
+ r: args.r,
+ sigma: args.sigma,
+ theta_vg: args.theta_vg,
+ nu: args.nu,
+ q: args.q,
+ }, apiKey);
+ return { success: true, data: result, message: `Variance Gamma price: ${formatNumber(result.price)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// DUPIRE LOCAL VOL (1 tool)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const dupirePriceTool: InternalTool = {
+ name: 'quantlib_models_dupire_price',
+ description: 'Price options using Dupire local volatility model.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Spot price' },
+ r: { type: 'number', description: 'Risk-free rate' },
+ q: { type: 'number', description: 'Dividend yield' },
+ sigma: { type: 'number', description: 'Local volatility' },
+ strike: { type: 'number', description: 'Strike price' },
+ T: { type: 'number', description: 'Time to maturity' },
+ option_type: { type: 'string', description: 'Option type: call or put' },
+ },
+ required: ['spot'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/dupire/price', {
+ spot: args.spot,
+ r: args.r,
+ q: args.q,
+ sigma: args.sigma,
+ strike: args.strike,
+ T: args.T,
+ option_type: args.option_type,
+ }, apiKey);
+ return { success: true, data: result, message: `Dupire ${args.option_type || 'call'} price: ${formatNumber(result.price)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// SVI (STOCHASTIC VOLATILITY INSPIRED) (1 tool)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const sviCalibrateTool: InternalTool = {
+ name: 'quantlib_models_svi_calibrate',
+ description: 'Calibrate SVI (Stochastic Volatility Inspired) parameters to market smile.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ strikes: { type: 'string', description: 'JSON array of strikes' },
+ market_vols: { type: 'string', description: 'JSON array of market implied vols' },
+ forward: { type: 'number', description: 'Forward price' },
+ T: { type: 'number', description: 'Time to expiry' },
+ },
+ required: ['strikes', 'market_vols', 'forward', 'T'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/models/svi/calibrate', {
+ strikes: JSON.parse(args.strikes as string),
+ market_vols: JSON.parse(args.market_vols as string),
+ forward: args.forward,
+ T: args.T,
+ }, apiKey);
+ return { success: true, data: result, message: `Calibrated SVI: a=${formatNumber(result.a)}, b=${formatNumber(result.b)}, ρ=${formatNumber(result.rho)}, m=${formatNumber(result.m)}, σ=${formatNumber(result.sigma)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// EXPORT ALL TOOLS
+// ══════════════════════════════════════════════════════════════════════════════
+
+export const quantlibModelsTools: InternalTool[] = [
+ // Short Rate (4)
+ shortRateBondPriceTool,
+ shortRateYieldCurveTool,
+ shortRateMonteCarloTool,
+ shortRateBondOptionTool,
+ // Hull-White (1)
+ hullWhiteCalibrateTool,
+ // Heston (3)
+ hestonPriceTool,
+ hestonImpliedVolTool,
+ hestonMonteCarloTool,
+ // Merton (2)
+ mertonPriceTool,
+ mertonFFTTool,
+ // Kou (1)
+ kouPriceTool,
+ // Variance Gamma (1)
+ varianceGammaPriceTool,
+ // Dupire (1)
+ dupirePriceTool,
+ // SVI (1)
+ sviCalibrateTool,
+];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/portfolio.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/portfolio.ts
new file mode 100644
index 000000000..7a4a231c8
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/portfolio.ts
@@ -0,0 +1,491 @@
+// QuantLib Portfolio MCP Tools - 15 endpoints
+// Portfolio Optimization, Risk Metrics, Black-Litterman, Risk Parity
+
+import { InternalTool } from '../../types';
+import { quantlibApiCall, formatNumber, formatPercent } from '../../QuantLibMCPBridge';
+
+export const quantlibPortfolioTools: InternalTool[] = [
+ // ==================== OPTIMIZE (4) ====================
+ {
+ name: 'quantlib_portfolio_optimize_min_variance',
+ description: 'Find minimum variance portfolio weights given expected returns and covariance matrix',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ expected_returns: { type: 'string', description: 'JSON array of expected returns for each asset' },
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ rf_rate: { type: 'number', description: 'Risk-free rate (optional)' },
+ },
+ required: ['expected_returns', 'covariance_matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/optimize/min-variance', {
+ expected_returns: JSON.parse(args.expected_returns),
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ rf_rate: args.rf_rate,
+ }, apiKey);
+ const weights = result.weights || result.optimal_weights;
+ return {
+ success: true,
+ data: result,
+ message: `Min Variance: σ=${formatPercent(result.volatility || result.portfolio_volatility)}, E[R]=${formatPercent(result.expected_return || result.portfolio_return)}, weights=[${weights?.map((w: number) => formatPercent(w)).join(', ') || 'N/A'}]`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_portfolio_optimize_max_sharpe',
+ description: 'Find maximum Sharpe ratio portfolio weights (tangency portfolio)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ expected_returns: { type: 'string', description: 'JSON array of expected returns' },
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ rf_rate: { type: 'number', description: 'Risk-free rate' },
+ },
+ required: ['expected_returns', 'covariance_matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/optimize/max-sharpe', {
+ expected_returns: JSON.parse(args.expected_returns),
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ rf_rate: args.rf_rate,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Max Sharpe: SR=${formatNumber(result.sharpe_ratio, 4)}, E[R]=${formatPercent(result.expected_return || result.portfolio_return)}, σ=${formatPercent(result.volatility || result.portfolio_volatility)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_portfolio_optimize_target_return',
+ description: 'Find minimum variance portfolio for a target return',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ expected_returns: { type: 'string', description: 'JSON array of expected returns' },
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ target_return: { type: 'number', description: 'Target portfolio return (decimal)' },
+ },
+ required: ['expected_returns', 'covariance_matrix', 'target_return'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/optimize/target-return', {
+ expected_returns: JSON.parse(args.expected_returns),
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ target_return: args.target_return,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Target Return ${formatPercent(args.target_return)}: achieved σ=${formatPercent(result.volatility || result.portfolio_volatility)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_portfolio_optimize_efficient_frontier',
+ description: 'Generate the efficient frontier - set of optimal portfolios',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ expected_returns: { type: 'string', description: 'JSON array of expected returns' },
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ n_points: { type: 'number', description: 'Number of points on the frontier' },
+ },
+ required: ['expected_returns', 'covariance_matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/optimize/efficient-frontier', {
+ expected_returns: JSON.parse(args.expected_returns),
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ n_points: args.n_points || 20,
+ }, apiKey);
+ const nPoints = result.frontier?.length || args.n_points || 20;
+ return {
+ success: true,
+ data: result,
+ message: `Efficient frontier: ${nPoints} portfolios from σ=${formatPercent(result.min_volatility || 0)} to σ=${formatPercent(result.max_volatility || 0)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== RISK (8) ====================
+ {
+ name: 'quantlib_portfolio_risk_comprehensive',
+ description: 'Comprehensive portfolio risk analysis including multiple metrics',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ weights: { type: 'string', description: 'JSON array of portfolio weights' },
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ returns: { type: 'string', description: 'JSON array of historical returns (optional)' },
+ benchmark_returns: { type: 'string', description: 'JSON array of benchmark returns (optional)' },
+ rf_rate: { type: 'number', description: 'Risk-free rate' },
+ },
+ required: ['weights', 'covariance_matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/risk/comprehensive', {
+ weights: JSON.parse(args.weights),
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ returns: args.returns ? JSON.parse(args.returns) : undefined,
+ benchmark_returns: args.benchmark_returns ? JSON.parse(args.benchmark_returns) : undefined,
+ rf_rate: args.rf_rate,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Portfolio Risk: σ=${formatPercent(result.volatility)}, Sharpe=${formatNumber(result.sharpe_ratio, 4)}, Sortino=${formatNumber(result.sortino_ratio, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_portfolio_risk_var',
+ description: 'Calculate portfolio Value at Risk',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ weights: { type: 'string', description: 'JSON array of portfolio weights' },
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ confidence: { type: 'number', description: 'Confidence level (e.g., 0.95, 0.99)' },
+ horizon: { type: 'number', description: 'Holding period in days' },
+ portfolio_value: { type: 'number', description: 'Portfolio value' },
+ method: { type: 'string', description: 'VaR method', enum: ['parametric', 'historical', 'monte_carlo'] },
+ },
+ required: ['weights', 'covariance_matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/risk/var', {
+ weights: JSON.parse(args.weights),
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ confidence: args.confidence,
+ horizon: args.horizon,
+ portfolio_value: args.portfolio_value,
+ method: args.method,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Portfolio VaR (${(args.confidence || 0.95) * 100}%): ${formatNumber(result.var || result.VaR, 2)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_portfolio_risk_cvar',
+ description: 'Calculate portfolio Conditional VaR (Expected Shortfall)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ weights: { type: 'string', description: 'JSON array of portfolio weights' },
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ confidence: { type: 'number', description: 'Confidence level' },
+ horizon: { type: 'number', description: 'Holding period' },
+ portfolio_value: { type: 'number', description: 'Portfolio value' },
+ method: { type: 'string', description: 'Method', enum: ['parametric', 'historical'] },
+ },
+ required: ['weights', 'covariance_matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/risk/cvar', {
+ weights: JSON.parse(args.weights),
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ confidence: args.confidence,
+ horizon: args.horizon,
+ portfolio_value: args.portfolio_value,
+ method: args.method,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Portfolio CVaR/ES (${(args.confidence || 0.95) * 100}%): ${formatNumber(result.cvar || result.expected_shortfall, 2)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_portfolio_risk_contribution',
+ description: 'Calculate risk contribution of each asset to portfolio variance',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ weights: { type: 'string', description: 'JSON array of portfolio weights' },
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ },
+ required: ['weights', 'covariance_matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/risk/contribution', {
+ weights: JSON.parse(args.weights),
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ }, apiKey);
+ const contributions = result.risk_contributions || result.contributions;
+ return {
+ success: true,
+ data: result,
+ message: `Risk contributions: [${contributions?.map((c: number) => formatPercent(c)).join(', ') || 'N/A'}]`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_portfolio_risk_ratios',
+ description: 'Calculate portfolio performance ratios (Sharpe, Sortino, Calmar, etc.)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns: { type: 'string', description: 'JSON array of portfolio returns' },
+ rf_rate: { type: 'number', description: 'Risk-free rate' },
+ benchmark_returns: { type: 'string', description: 'JSON array of benchmark returns' },
+ target_return: { type: 'number', description: 'Target return for Sortino ratio' },
+ },
+ required: ['returns'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/risk/ratios', {
+ returns: JSON.parse(args.returns),
+ rf_rate: args.rf_rate,
+ benchmark_returns: args.benchmark_returns ? JSON.parse(args.benchmark_returns) : undefined,
+ target_return: args.target_return,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Ratios: Sharpe=${formatNumber(result.sharpe, 4)}, Sortino=${formatNumber(result.sortino, 4)}, Calmar=${formatNumber(result.calmar, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_portfolio_risk_incremental_var',
+ description: 'Calculate incremental VaR from adding/changing a position',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ weights: { type: 'string', description: 'JSON array of current weights' },
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ new_weight: { type: 'number', description: 'New weight for the asset' },
+ asset_index: { type: 'number', description: 'Index of asset being changed' },
+ confidence: { type: 'number', description: 'Confidence level' },
+ },
+ required: ['weights', 'covariance_matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/risk/incremental-var', {
+ weights: JSON.parse(args.weights),
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ new_weight: args.new_weight,
+ asset_index: args.asset_index,
+ confidence: args.confidence,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Incremental VaR: ${formatNumber(result.incremental_var, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_portfolio_risk_inverse_volatility',
+ description: 'Calculate inverse volatility (1/σ) weighted portfolio',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ },
+ required: ['covariance_matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/risk/inverse-volatility', {
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ }, apiKey);
+ const weights = result.weights || result.inverse_vol_weights;
+ return {
+ success: true,
+ data: result,
+ message: `Inverse Vol Weights: [${weights?.map((w: number) => formatPercent(w)).join(', ') || 'N/A'}]`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_portfolio_risk_comprehensive_analysis',
+ description: 'Full portfolio risk analysis with returns data',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns: { type: 'string', description: 'JSON 2D array of asset returns (each row is an asset)' },
+ weights: { type: 'string', description: 'JSON array of portfolio weights' },
+ confidence: { type: 'number', description: 'Confidence level for VaR/ES' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate' },
+ },
+ required: ['returns', 'weights'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/risk/portfolio-comprehensive', {
+ returns: JSON.parse(args.returns),
+ weights: JSON.parse(args.weights),
+ confidence: args.confidence,
+ risk_free_rate: args.risk_free_rate,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Comprehensive Analysis: σ=${formatPercent(result.volatility)}, VaR=${formatNumber(result.var, 4)}, MaxDD=${formatPercent(result.max_drawdown)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== BLACK-LITTERMAN (2) ====================
+ {
+ name: 'quantlib_portfolio_black_litterman_equilibrium',
+ description: 'Calculate Black-Litterman equilibrium (implied) returns from market cap weights',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ market_caps: { type: 'string', description: 'JSON array of market capitalizations' },
+ risk_aversion: { type: 'number', description: 'Risk aversion parameter (default ~2.5)' },
+ },
+ required: ['covariance_matrix', 'market_caps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/black-litterman/equilibrium', {
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ market_caps: JSON.parse(args.market_caps),
+ risk_aversion: args.risk_aversion,
+ }, apiKey);
+ const returns = result.equilibrium_returns || result.implied_returns;
+ return {
+ success: true,
+ data: result,
+ message: `BL Equilibrium Returns: [${returns?.map((r: number) => formatPercent(r)).join(', ') || 'N/A'}]`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_portfolio_black_litterman_posterior',
+ description: 'Calculate Black-Litterman posterior returns and optimal weights',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ market_caps: { type: 'string', description: 'JSON array of market caps' },
+ views: { type: 'string', description: 'JSON array of view objects with P (picking matrix row), Q (view return), confidence' },
+ risk_aversion: { type: 'number', description: 'Risk aversion parameter' },
+ },
+ required: ['covariance_matrix', 'market_caps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const body: any = {
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ market_caps: JSON.parse(args.market_caps),
+ risk_aversion: args.risk_aversion,
+ };
+ if (args.views) body.views = JSON.parse(args.views);
+
+ const result = await quantlibApiCall('/quantlib/portfolio/black-litterman/posterior', body, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `BL Posterior: ${result.posterior_returns?.length || 'N/A'} assets, optimal weights calculated`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== RISK PARITY (1) ====================
+ {
+ name: 'quantlib_portfolio_risk_parity',
+ description: 'Calculate risk parity portfolio - equal risk contribution from each asset',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ covariance_matrix: { type: 'string', description: 'JSON 2D array covariance matrix' },
+ method: { type: 'string', description: 'Optimization method', enum: ['slsqp', 'ccd', 'newton'] },
+ },
+ required: ['covariance_matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/portfolio/risk-parity', {
+ covariance_matrix: JSON.parse(args.covariance_matrix),
+ method: args.method,
+ }, apiKey);
+ const weights = result.weights || result.risk_parity_weights;
+ return {
+ success: true,
+ data: result,
+ message: `Risk Parity Weights: [${weights?.map((w: number) => formatPercent(w)).join(', ') || 'N/A'}], σ=${formatPercent(result.portfolio_volatility)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/pricing.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/pricing.ts
new file mode 100644
index 000000000..570f03dac
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/pricing.ts
@@ -0,0 +1,1134 @@
+// QuantLib Pricing MCP Tools - 29 endpoints
+// Black-Scholes, Black76, Bachelier, Kirk Spread, Binomial, Monte Carlo, PDE
+
+import { InternalTool } from '../../types';
+import { quantlibApiCall, formatNumber, formatPercent } from '../../QuantLibMCPBridge';
+
+export const quantlibPricingTools: InternalTool[] = [
+ // ==================== BLACK-SCHOLES (8) ====================
+ {
+ name: 'quantlib_pricing_bs_price',
+ description: 'Calculate Black-Scholes option price for European options',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price of the underlying' },
+ strike: { type: 'number', description: 'Strike price of the option' },
+ risk_free_rate: { type: 'number', description: 'Risk-free interest rate (decimal, e.g., 0.05 for 5%)' },
+ volatility: { type: 'number', description: 'Annualized volatility (decimal, e.g., 0.2 for 20%)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ dividend_yield: { type: 'number', description: 'Continuous dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bs/price', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `BS ${args.option_type || 'call'} price: ${formatNumber(result.price, 4)} (S=${args.spot}, K=${args.strike}, σ=${formatPercent(args.volatility)}, T=${args.time_to_maturity}y)`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bs_greeks',
+ description: 'Calculate Black-Scholes Greeks (Delta, Gamma, Theta, Vega, Rho)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bs/greeks', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Greeks: Δ=${formatNumber(result.delta, 4)}, Γ=${formatNumber(result.gamma, 6)}, Θ=${formatNumber(result.theta, 4)}, V=${formatNumber(result.vega, 4)}, ρ=${formatNumber(result.rho, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bs_implied_vol',
+ description: 'Calculate implied volatility from market option price using Black-Scholes',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ market_price: { type: 'number', description: 'Observed market price of the option' },
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['market_price', 'spot', 'strike', 'risk_free_rate', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bs/implied-vol', {
+ market_price: args.market_price,
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Implied Volatility: ${formatPercent(result.implied_volatility || result.iv)} (market price: ${args.market_price})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bs_greeks_full',
+ description: 'Calculate all Black-Scholes Greeks including higher-order (Vanna, Volga, Speed, etc.)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bs/greeks-full', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Full Greeks computed: ${Object.keys(result).length} metrics`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bs_digital_call',
+ description: 'Price a digital (binary) call option using Black-Scholes',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bs/digital-call', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Digital Call price: ${formatNumber(result.price, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bs_digital_put',
+ description: 'Price a digital (binary) put option using Black-Scholes',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bs/digital-put', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Digital Put price: ${formatNumber(result.price, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bs_asset_or_nothing_call',
+ description: 'Price an asset-or-nothing call option',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bs/asset-or-nothing-call', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Asset-or-Nothing Call price: ${formatNumber(result.price, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bs_asset_or_nothing_put',
+ description: 'Price an asset-or-nothing put option',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bs/asset-or-nothing-put', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Asset-or-Nothing Put price: ${formatNumber(result.price, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== BLACK76 (7) ====================
+ {
+ name: 'quantlib_pricing_black76_price',
+ description: 'Calculate Black76 option price for futures/forward options',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ },
+ required: ['forward', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/black76/price', {
+ forward: args.forward,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Black76 ${args.option_type || 'call'} price: ${formatNumber(result.price, 4)} (F=${args.forward}, K=${args.strike})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_black76_greeks',
+ description: 'Calculate Black76 Greeks for futures/forward options',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ },
+ required: ['forward', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/black76/greeks', {
+ forward: args.forward,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Black76 Greeks: Δ=${formatNumber(result.delta, 4)}, Γ=${formatNumber(result.gamma, 6)}, V=${formatNumber(result.vega, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_black76_greeks_full',
+ description: 'Calculate all Black76 Greeks including higher-order',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ },
+ required: ['forward', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/black76/greeks-full', {
+ forward: args.forward,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Black76 Full Greeks computed: ${Object.keys(result).length} metrics`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_black76_implied_vol',
+ description: 'Calculate implied volatility from market price using Black76',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ market_price: { type: 'number', description: 'Market price of the option' },
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ },
+ required: ['market_price', 'forward', 'strike', 'risk_free_rate', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/black76/implied-vol', {
+ market_price: args.market_price,
+ forward: args.forward,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Black76 Implied Vol: ${formatPercent(result.implied_volatility || result.iv)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_black76_caplet',
+ description: 'Price a caplet using Black76 model',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward_rate: { type: 'number', description: 'Forward rate' },
+ strike: { type: 'number', description: 'Strike rate' },
+ discount_factor: { type: 'number', description: 'Discount factor to payment date' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ t_start: { type: 'number', description: 'Caplet start time in years' },
+ t_end: { type: 'number', description: 'Caplet end time in years' },
+ notional: { type: 'number', description: 'Notional amount' },
+ },
+ required: ['forward_rate', 'strike', 'discount_factor', 'volatility', 't_start', 't_end'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/black76/caplet', {
+ forward_rate: args.forward_rate,
+ strike: args.strike,
+ discount_factor: args.discount_factor,
+ volatility: args.volatility,
+ t_start: args.t_start,
+ t_end: args.t_end,
+ notional: args.notional || 1,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Caplet price: ${formatNumber(result.price, 4)} (K=${formatPercent(args.strike)}, σ=${formatPercent(args.volatility)})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_black76_floorlet',
+ description: 'Price a floorlet using Black76 model',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward_rate: { type: 'number', description: 'Forward rate' },
+ strike: { type: 'number', description: 'Strike rate' },
+ discount_factor: { type: 'number', description: 'Discount factor to payment date' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ t_start: { type: 'number', description: 'Floorlet start time in years' },
+ t_end: { type: 'number', description: 'Floorlet end time in years' },
+ notional: { type: 'number', description: 'Notional amount' },
+ },
+ required: ['forward_rate', 'strike', 'discount_factor', 'volatility', 't_start', 't_end'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/black76/floorlet', {
+ forward_rate: args.forward_rate,
+ strike: args.strike,
+ discount_factor: args.discount_factor,
+ volatility: args.volatility,
+ t_start: args.t_start,
+ t_end: args.t_end,
+ notional: args.notional || 1,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Floorlet price: ${formatNumber(result.price, 4)} (K=${formatPercent(args.strike)}, σ=${formatPercent(args.volatility)})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_black76_swaption',
+ description: 'Price a swaption using Black76 model',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward_swap_rate: { type: 'number', description: 'Forward swap rate' },
+ strike: { type: 'number', description: 'Strike rate' },
+ annuity: { type: 'number', description: 'Swap annuity (PV01)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ t_expiry: { type: 'number', description: 'Time to expiry in years' },
+ is_payer: { type: 'boolean', description: 'True for payer swaption, false for receiver' },
+ notional: { type: 'number', description: 'Notional amount' },
+ },
+ required: ['forward_swap_rate', 'strike', 'annuity', 'volatility', 't_expiry'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/black76/swaption', {
+ forward_swap_rate: args.forward_swap_rate,
+ strike: args.strike,
+ annuity: args.annuity,
+ volatility: args.volatility,
+ t_expiry: args.t_expiry,
+ is_payer: args.is_payer !== false,
+ notional: args.notional || 1,
+ }, apiKey);
+ const swaptionType = args.is_payer !== false ? 'Payer' : 'Receiver';
+ return {
+ success: true,
+ data: result,
+ message: `${swaptionType} Swaption price: ${formatNumber(result.price, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== BACHELIER (6) ====================
+ {
+ name: 'quantlib_pricing_bachelier_price',
+ description: 'Calculate option price using Bachelier (normal) model',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ normal_volatility: { type: 'number', description: 'Normal volatility (absolute, not percentage)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ },
+ required: ['forward', 'strike', 'risk_free_rate', 'normal_volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bachelier/price', {
+ forward: args.forward,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ normal_volatility: args.normal_volatility,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Bachelier ${args.option_type || 'call'} price: ${formatNumber(result.price, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bachelier_greeks',
+ description: 'Calculate Bachelier model Greeks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ normal_volatility: { type: 'number', description: 'Normal volatility' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ },
+ required: ['forward', 'strike', 'risk_free_rate', 'normal_volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bachelier/greeks', {
+ forward: args.forward,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ normal_volatility: args.normal_volatility,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Bachelier Greeks: Δ=${formatNumber(result.delta, 4)}, Γ=${formatNumber(result.gamma, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bachelier_greeks_full',
+ description: 'Calculate all Bachelier model Greeks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ normal_volatility: { type: 'number', description: 'Normal volatility' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ },
+ required: ['forward', 'strike', 'risk_free_rate', 'normal_volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bachelier/greeks-full', {
+ forward: args.forward,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ normal_volatility: args.normal_volatility,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Bachelier Full Greeks computed`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bachelier_implied_vol',
+ description: 'Calculate implied normal volatility from market price',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ market_price: { type: 'number', description: 'Market price of the option' },
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ },
+ required: ['market_price', 'forward', 'strike', 'risk_free_rate', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bachelier/implied-vol', {
+ market_price: args.market_price,
+ forward: args.forward,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Bachelier Implied Normal Vol: ${formatNumber(result.implied_volatility || result.iv, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bachelier_vol_conversion',
+ description: 'Convert between lognormal and normal volatility',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ volatility: { type: 'number', description: 'Input volatility' },
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ direction: { type: 'string', description: 'Conversion direction', enum: ['lognormal_to_normal', 'normal_to_lognormal'] },
+ },
+ required: ['volatility', 'forward', 'strike', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bachelier/vol-conversion', {
+ volatility: args.volatility,
+ forward: args.forward,
+ strike: args.strike,
+ time_to_maturity: args.time_to_maturity,
+ direction: args.direction || 'lognormal_to_normal',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Vol conversion (${args.direction || 'lognormal_to_normal'}): ${formatNumber(args.volatility, 4)} → ${formatNumber(result.converted_volatility || result.result, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_bachelier_shifted_lognormal',
+ description: 'Price option using shifted lognormal model',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ shift: { type: 'number', description: 'Shift parameter' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ },
+ required: ['forward', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/bachelier/shifted-lognormal', {
+ forward: args.forward,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ shift: args.shift || 0,
+ option_type: args.option_type || 'call',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Shifted Lognormal price: ${formatNumber(result.price, 4)} (shift=${args.shift || 0})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== KIRK SPREAD (1) ====================
+ {
+ name: 'quantlib_pricing_kirk_spread',
+ description: 'Price a spread option using Kirk approximation',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ F1: { type: 'number', description: 'First forward price' },
+ F2: { type: 'number', description: 'Second forward price' },
+ strike: { type: 'number', description: 'Strike (spread level)' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ sigma1: { type: 'number', description: 'Volatility of first asset (decimal)' },
+ sigma2: { type: 'number', description: 'Volatility of second asset (decimal)' },
+ rho: { type: 'number', description: 'Correlation between assets' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ },
+ required: ['F1', 'F2', 'strike', 'risk_free_rate', 'sigma1', 'sigma2', 'rho', 'time_to_maturity'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/kirk/spread-price', {
+ F1: args.F1,
+ F2: args.F2,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ sigma1: args.sigma1,
+ sigma2: args.sigma2,
+ rho: args.rho,
+ time_to_maturity: args.time_to_maturity,
+ option_type: args.option_type || 'call',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Kirk Spread ${args.option_type || 'call'} price: ${formatNumber(result.price, 4)} (F1=${args.F1}, F2=${args.F2}, K=${args.strike}, ρ=${args.rho})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== BINOMIAL (3) ====================
+ {
+ name: 'quantlib_pricing_binomial_price',
+ description: 'Price option using binomial tree (Cox-Ross-Rubinstein) - supports American exercise',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ steps: { type: 'number', description: 'Number of tree steps' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ exercise: { type: 'string', description: 'Exercise style', enum: ['european', 'american'] },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity', 'steps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/binomial/price', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ steps: args.steps,
+ option_type: args.option_type || 'call',
+ exercise: args.exercise || 'european',
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Binomial ${args.exercise || 'european'} ${args.option_type || 'call'} price: ${formatNumber(result.price, 4)} (${args.steps} steps)`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_binomial_greeks',
+ description: 'Calculate Greeks using binomial tree',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ steps: { type: 'number', description: 'Number of tree steps' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ exercise: { type: 'string', description: 'Exercise style', enum: ['european', 'american'] },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity', 'steps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/binomial/greeks', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ steps: args.steps,
+ option_type: args.option_type || 'call',
+ exercise: args.exercise || 'european',
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Binomial Greeks: Δ=${formatNumber(result.delta, 4)}, Γ=${formatNumber(result.gamma, 6)}, Θ=${formatNumber(result.theta, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_binomial_convergence',
+ description: 'Analyze binomial tree convergence as number of steps increases',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ max_steps: { type: 'number', description: 'Maximum number of steps to analyze' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ exercise: { type: 'string', description: 'Exercise style', enum: ['european', 'american'] },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity', 'max_steps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/binomial/convergence', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ max_steps: args.max_steps,
+ option_type: args.option_type || 'call',
+ exercise: args.exercise || 'european',
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Binomial convergence analysis: ${args.max_steps} max steps`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== MONTE CARLO (2) ====================
+ {
+ name: 'quantlib_pricing_monte_carlo_price',
+ description: 'Price option using Monte Carlo simulation',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ n_simulations: { type: 'number', description: 'Number of Monte Carlo simulations' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity', 'n_simulations'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/monte-carlo/price', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ n_simulations: args.n_simulations,
+ option_type: args.option_type || 'call',
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `MC ${args.option_type || 'call'} price: ${formatNumber(result.price, 4)} ± ${formatNumber(result.std_error || result.se, 4)} (${args.n_simulations} sims)`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_monte_carlo_barrier',
+ description: 'Price barrier option using Monte Carlo simulation',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ barrier: { type: 'number', description: 'Barrier level' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ n_simulations: { type: 'number', description: 'Number of Monte Carlo simulations' },
+ n_steps: { type: 'number', description: 'Number of time steps per path' },
+ barrier_type: { type: 'string', description: 'Barrier type', enum: ['down-and-out', 'down-and-in', 'up-and-out', 'up-and-in'] },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'barrier', 'risk_free_rate', 'volatility', 'time_to_maturity', 'n_simulations', 'n_steps'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/monte-carlo/barrier', {
+ spot: args.spot,
+ strike: args.strike,
+ barrier: args.barrier,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ n_simulations: args.n_simulations,
+ n_steps: args.n_steps,
+ barrier_type: args.barrier_type || 'down-and-out',
+ option_type: args.option_type || 'call',
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `MC Barrier (${args.barrier_type || 'down-and-out'}) ${args.option_type || 'call'}: ${formatNumber(result.price, 4)} (B=${args.barrier})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== PDE / FINITE DIFFERENCE (2) ====================
+ {
+ name: 'quantlib_pricing_pde_price',
+ description: 'Price option using PDE/finite difference method - supports American exercise',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ n_spot: { type: 'number', description: 'Number of spot grid points' },
+ n_time: { type: 'number', description: 'Number of time steps' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ exercise: { type: 'string', description: 'Exercise style', enum: ['european', 'american'] },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity', 'n_spot', 'n_time'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/pde/price', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ n_spot: args.n_spot,
+ n_time: args.n_time,
+ option_type: args.option_type || 'call',
+ exercise: args.exercise || 'european',
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `PDE ${args.exercise || 'european'} ${args.option_type || 'call'} price: ${formatNumber(result.price, 4)} (${args.n_spot}x${args.n_time} grid)`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_pricing_pde_greeks',
+ description: 'Calculate Greeks using PDE/finite difference method',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ strike: { type: 'number', description: 'Strike price' },
+ risk_free_rate: { type: 'number', description: 'Risk-free rate (decimal)' },
+ volatility: { type: 'number', description: 'Volatility (decimal)' },
+ time_to_maturity: { type: 'number', description: 'Time to maturity in years' },
+ n_spot: { type: 'number', description: 'Number of spot grid points' },
+ n_time: { type: 'number', description: 'Number of time steps' },
+ option_type: { type: 'string', description: 'Option type', enum: ['call', 'put'] },
+ exercise: { type: 'string', description: 'Exercise style', enum: ['european', 'american'] },
+ dividend_yield: { type: 'number', description: 'Dividend yield (decimal)' },
+ },
+ required: ['spot', 'strike', 'risk_free_rate', 'volatility', 'time_to_maturity', 'n_spot', 'n_time'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/pricing/pde/greeks', {
+ spot: args.spot,
+ strike: args.strike,
+ risk_free_rate: args.risk_free_rate,
+ volatility: args.volatility,
+ time_to_maturity: args.time_to_maturity,
+ n_spot: args.n_spot,
+ n_time: args.n_time,
+ option_type: args.option_type || 'call',
+ exercise: args.exercise || 'european',
+ dividend_yield: args.dividend_yield || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `PDE Greeks: Δ=${formatNumber(result.delta, 4)}, Γ=${formatNumber(result.gamma, 6)}, Θ=${formatNumber(result.theta, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/risk.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/risk.ts
new file mode 100644
index 000000000..7dcab886a
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/risk.ts
@@ -0,0 +1,783 @@
+// QuantLib Risk MCP Tools - 25 endpoints
+// VaR, Stress Testing, EVT, XVA, Sensitivities, Tail Risk, Portfolio Risk
+
+import { InternalTool } from '../../types';
+import { quantlibApiCall, formatNumber, formatPercent } from '../../QuantLibMCPBridge';
+
+export const quantlibRiskTools: InternalTool[] = [
+ // ==================== VaR (6) ====================
+ {
+ name: 'quantlib_risk_var_parametric',
+ description: 'Calculate parametric (variance-covariance) Value at Risk',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_value: { type: 'number', description: 'Total portfolio value' },
+ volatility: { type: 'number', description: 'Portfolio volatility (decimal)' },
+ confidence: { type: 'number', description: 'Confidence level (e.g., 0.95, 0.99)' },
+ horizon: { type: 'number', description: 'Holding period in days' },
+ },
+ required: ['portfolio_value', 'volatility'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/var/parametric', {
+ portfolio_value: args.portfolio_value,
+ volatility: args.volatility,
+ confidence: args.confidence || 0.99,
+ horizon: args.horizon || 1,
+ }, apiKey);
+ const conf = (args.confidence || 0.99) * 100;
+ return {
+ success: true,
+ data: result,
+ message: `Parametric VaR (${conf}%, ${args.horizon || 1}d): ${formatNumber(result.var || result.VaR, 2)} (${formatPercent((result.var || result.VaR) / args.portfolio_value)} of portfolio)`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_var_historical',
+ description: 'Calculate historical simulation Value at Risk',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns: { type: 'string', description: 'JSON array of historical returns' },
+ confidence: { type: 'number', description: 'Confidence level (e.g., 0.95, 0.99)' },
+ portfolio_value: { type: 'number', description: 'Portfolio value' },
+ },
+ required: ['returns'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/var/historical', {
+ returns: JSON.parse(args.returns),
+ confidence: args.confidence || 0.99,
+ portfolio_value: args.portfolio_value || 1000000,
+ }, apiKey);
+ const conf = (args.confidence || 0.99) * 100;
+ return {
+ success: true,
+ data: result,
+ message: `Historical VaR (${conf}%): ${formatNumber(result.var || result.VaR, 2)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_var_component',
+ description: 'Calculate component VaR - contribution of each factor to total VaR',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns_by_factor: { type: 'string', description: 'JSON object with factor names as keys and return arrays as values' },
+ weights: { type: 'string', description: 'JSON object with factor names as keys and weights as values' },
+ confidence: { type: 'number', description: 'Confidence level' },
+ portfolio_value: { type: 'number', description: 'Portfolio value' },
+ },
+ required: ['returns_by_factor', 'weights'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/var/component', {
+ returns_by_factor: JSON.parse(args.returns_by_factor),
+ weights: JSON.parse(args.weights),
+ confidence: args.confidence || 0.99,
+ portfolio_value: args.portfolio_value || 1000000,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Component VaR calculated for ${Object.keys(JSON.parse(args.weights)).length} factors`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_var_incremental',
+ description: 'Calculate incremental VaR - change in VaR from adding a new position',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_returns: { type: 'string', description: 'JSON array of portfolio returns' },
+ new_position_returns: { type: 'string', description: 'JSON array of new position returns' },
+ position_weight: { type: 'number', description: 'Weight of new position (0 to 1)' },
+ confidence: { type: 'number', description: 'Confidence level' },
+ portfolio_value: { type: 'number', description: 'Portfolio value' },
+ },
+ required: ['portfolio_returns', 'new_position_returns', 'position_weight'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/var/incremental', {
+ portfolio_returns: JSON.parse(args.portfolio_returns),
+ new_position_returns: JSON.parse(args.new_position_returns),
+ position_weight: args.position_weight,
+ confidence: args.confidence || 0.99,
+ portfolio_value: args.portfolio_value || 1000000,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Incremental VaR: ${formatNumber(result.incremental_var, 2)} (${formatPercent(args.position_weight)} weight)`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_var_marginal',
+ description: 'Calculate marginal VaR - sensitivity of VaR to position size changes',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_returns: { type: 'string', description: 'JSON array of portfolio returns' },
+ new_position_returns: { type: 'string', description: 'JSON array of position returns' },
+ position_weight: { type: 'number', description: 'Current position weight' },
+ confidence: { type: 'number', description: 'Confidence level' },
+ portfolio_value: { type: 'number', description: 'Portfolio value' },
+ },
+ required: ['portfolio_returns', 'new_position_returns', 'position_weight'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/var/marginal', {
+ portfolio_returns: JSON.parse(args.portfolio_returns),
+ new_position_returns: JSON.parse(args.new_position_returns),
+ position_weight: args.position_weight,
+ confidence: args.confidence || 0.99,
+ portfolio_value: args.portfolio_value || 1000000,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Marginal VaR: ${formatNumber(result.marginal_var, 4)} per unit weight change`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_var_es_optimization',
+ description: 'Optimize portfolio to minimize Expected Shortfall (CVaR)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns: { type: 'string', description: 'JSON 2D array of asset returns (each row is an asset)' },
+ confidence: { type: 'number', description: 'Confidence level for ES' },
+ target_return: { type: 'number', description: 'Target portfolio return (optional)' },
+ },
+ required: ['returns'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/var/es-optimization', {
+ returns: JSON.parse(args.returns),
+ confidence: args.confidence || 0.95,
+ target_return: args.target_return,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `ES-optimized weights: min ES = ${formatNumber(result.min_es || result.expected_shortfall, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== STRESS & BACKTEST (2) ====================
+ {
+ name: 'quantlib_risk_stress_scenario',
+ description: 'Define and calculate impact of a stress scenario',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Scenario name (e.g., "2008 Crisis", "Rate Shock")' },
+ factor_shocks: { type: 'string', description: 'JSON object with risk factors and their shock magnitudes' },
+ description: { type: 'string', description: 'Scenario description' },
+ },
+ required: ['name', 'factor_shocks'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/stress/scenario', {
+ name: args.name,
+ factor_shocks: JSON.parse(args.factor_shocks),
+ description: args.description || '',
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Stress scenario "${args.name}" applied: ${Object.keys(JSON.parse(args.factor_shocks)).length} factors shocked`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_backtest',
+ description: 'Backtest VaR model against actual returns',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ actual_returns: { type: 'string', description: 'JSON array of actual realized returns' },
+ var_estimates: { type: 'string', description: 'JSON array of VaR estimates for same periods' },
+ confidence: { type: 'number', description: 'VaR confidence level used' },
+ },
+ required: ['actual_returns', 'var_estimates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/backtest', {
+ actual_returns: JSON.parse(args.actual_returns),
+ var_estimates: JSON.parse(args.var_estimates),
+ confidence: args.confidence || 0.99,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `VaR Backtest: ${result.exceptions || result.breaches} exceptions in ${JSON.parse(args.actual_returns).length} periods (expected: ${formatNumber((1 - (args.confidence || 0.99)) * JSON.parse(args.actual_returns).length, 1)})`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== EVT (3) ====================
+ {
+ name: 'quantlib_risk_evt_gpd',
+ description: 'Fit Generalized Pareto Distribution (GPD) to tail losses',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ data: { type: 'string', description: 'JSON array of loss data' },
+ threshold: { type: 'number', description: 'Threshold for tail definition (optional)' },
+ quantile: { type: 'number', description: 'Quantile to use for threshold if not specified' },
+ },
+ required: ['data'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/evt/gpd', {
+ data: JSON.parse(args.data),
+ threshold: args.threshold,
+ quantile: args.quantile || 0.95,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `GPD fit: ξ=${formatNumber(result.xi || result.shape, 4)}, β=${formatNumber(result.beta || result.scale, 4)}, threshold=${formatNumber(result.threshold, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_evt_gev',
+ description: 'Fit Generalized Extreme Value (GEV) distribution to block maxima',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ data: { type: 'string', description: 'JSON array of block maxima data' },
+ fit_method: { type: 'string', description: 'Fitting method', enum: ['mle', 'pwm', 'lmom'] },
+ return_periods: { type: 'string', description: 'JSON array of return periods to calculate' },
+ },
+ required: ['data'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/evt/gev', {
+ data: JSON.parse(args.data),
+ fit_method: args.fit_method || 'mle',
+ return_periods: args.return_periods ? JSON.parse(args.return_periods) : undefined,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `GEV fit: μ=${formatNumber(result.mu || result.location, 4)}, σ=${formatNumber(result.sigma || result.scale, 4)}, ξ=${formatNumber(result.xi || result.shape, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_evt_hill',
+ description: 'Estimate tail index using Hill estimator',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ data: { type: 'string', description: 'JSON array of data' },
+ threshold: { type: 'number', description: 'Threshold for tail' },
+ quantile: { type: 'number', description: 'Quantile for threshold selection' },
+ },
+ required: ['data'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/evt/hill', {
+ data: JSON.parse(args.data),
+ threshold: args.threshold,
+ quantile: args.quantile || 0.95,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Hill estimator: α=${formatNumber(result.alpha || result.hill_index, 4)} (tail index)`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== TAIL RISK (2) ====================
+ {
+ name: 'quantlib_risk_tail_comprehensive',
+ description: 'Comprehensive tail risk analysis including VaR, ES, and EVT metrics',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns: { type: 'string', description: 'JSON array of returns' },
+ confidence: { type: 'number', description: 'Confidence level' },
+ portfolio_value: { type: 'number', description: 'Portfolio value' },
+ },
+ required: ['returns'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/tail-risk/comprehensive', {
+ returns: JSON.parse(args.returns),
+ confidence: args.confidence || 0.99,
+ portfolio_value: args.portfolio_value || 1000000,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Tail Risk: VaR=${formatNumber(result.var, 2)}, ES=${formatNumber(result.es || result.expected_shortfall, 2)}, Skew=${formatNumber(result.skewness, 4)}, Kurt=${formatNumber(result.kurtosis, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_tail_dependence',
+ description: 'Calculate tail dependence between assets',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns_x: { type: 'string', description: 'JSON array of first asset returns' },
+ returns_y: { type: 'string', description: 'JSON array of second asset returns' },
+ quantile: { type: 'number', description: 'Tail quantile (e.g., 0.05 for 5% tail)' },
+ },
+ required: ['returns_x', 'returns_y'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/tail-risk/tail-dependence', {
+ returns_x: JSON.parse(args.returns_x),
+ returns_y: JSON.parse(args.returns_y),
+ quantile: args.quantile || 0.05,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Tail dependence: lower=${formatNumber(result.lower_tail, 4)}, upper=${formatNumber(result.upper_tail, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== XVA (2) ====================
+ {
+ name: 'quantlib_risk_xva_cva',
+ description: 'Calculate Credit Valuation Adjustment (CVA) and related XVA metrics',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ exposure_paths: { type: 'string', description: 'JSON 2D array of exposure simulation paths' },
+ counterparty_spread: { type: 'number', description: 'Counterparty credit spread (decimal)' },
+ recovery_rate: { type: 'number', description: 'Expected recovery rate (decimal)' },
+ own_spread: { type: 'number', description: 'Own credit spread for DVA' },
+ funding_spread: { type: 'number', description: 'Funding spread for FVA' },
+ },
+ required: ['exposure_paths', 'counterparty_spread'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/xva/cva', {
+ exposure_paths: JSON.parse(args.exposure_paths),
+ counterparty_spread: args.counterparty_spread,
+ recovery_rate: args.recovery_rate || 0.4,
+ own_spread: args.own_spread,
+ funding_spread: args.funding_spread,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `CVA: ${formatNumber(result.cva, 4)}, DVA: ${formatNumber(result.dva || 0, 4)}, FVA: ${formatNumber(result.fva || 0, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_xva_pfe',
+ description: 'Calculate Potential Future Exposure (PFE) profile',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ exposure_paths: { type: 'string', description: 'JSON 2D array of exposure simulation paths' },
+ counterparty_spread: { type: 'number', description: 'Counterparty credit spread' },
+ recovery_rate: { type: 'number', description: 'Recovery rate' },
+ },
+ required: ['exposure_paths', 'counterparty_spread'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/xva/pfe', {
+ exposure_paths: JSON.parse(args.exposure_paths),
+ counterparty_spread: args.counterparty_spread,
+ recovery_rate: args.recovery_rate || 0.4,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `PFE profile: max PFE = ${formatNumber(result.max_pfe || Math.max(...(result.pfe_profile || [0])), 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== CORRELATION STRESS (1) ====================
+ {
+ name: 'quantlib_risk_correlation_stress',
+ description: 'Apply stress scenarios to correlation matrix',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ correlation_matrix: { type: 'string', description: 'JSON 2D array correlation matrix' },
+ stress_type: { type: 'string', description: 'Stress type', enum: ['crisis', 'decorrelation', 'custom'] },
+ volatilities: { type: 'string', description: 'JSON array of asset volatilities' },
+ weights: { type: 'string', description: 'JSON array of portfolio weights' },
+ },
+ required: ['correlation_matrix'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/correlation-stress', {
+ correlation_matrix: JSON.parse(args.correlation_matrix),
+ stress_type: args.stress_type || 'crisis',
+ volatilities: args.volatilities ? JSON.parse(args.volatilities) : undefined,
+ weights: args.weights ? JSON.parse(args.weights) : undefined,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Correlation stress (${args.stress_type || 'crisis'}): portfolio vol change = ${formatPercent(result.vol_change || 0)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== SENSITIVITIES (6) ====================
+ {
+ name: 'quantlib_risk_sensitivities_greeks',
+ description: 'Calculate option Greeks for risk management',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ S: { type: 'number', description: 'Spot price' },
+ K: { type: 'number', description: 'Strike price' },
+ T: { type: 'number', description: 'Time to maturity (years)' },
+ r: { type: 'number', description: 'Risk-free rate' },
+ sigma: { type: 'number', description: 'Volatility' },
+ q: { type: 'number', description: 'Dividend yield' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/sensitivities/greeks', {
+ S: args.S || 100,
+ K: args.K || 100,
+ T: args.T || 1,
+ r: args.r || 0.05,
+ sigma: args.sigma || 0.2,
+ q: args.q || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Greeks: Δ=${formatNumber(result.delta, 4)}, Γ=${formatNumber(result.gamma, 6)}, V=${formatNumber(result.vega, 4)}, Θ=${formatNumber(result.theta, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_sensitivities_bucket_delta',
+ description: 'Calculate bucket delta sensitivities for rate curve',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ positions: { type: 'string', description: 'JSON array of position objects with tenor and notional' },
+ bump_size: { type: 'number', description: 'Bump size in decimal (e.g., 0.0001 for 1bp)' },
+ },
+ required: ['positions'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/sensitivities/bucket-delta', {
+ positions: JSON.parse(args.positions),
+ bump_size: args.bump_size || 0.0001,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Bucket deltas calculated for ${JSON.parse(args.positions).length} positions`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_sensitivities_cross_gamma',
+ description: 'Calculate cross-gamma (spot-vol correlation risk)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ S: { type: 'number', description: 'Spot price' },
+ K: { type: 'number', description: 'Strike price' },
+ T: { type: 'number', description: 'Time to maturity' },
+ r: { type: 'number', description: 'Risk-free rate' },
+ sigma: { type: 'number', description: 'Volatility' },
+ bump: { type: 'number', description: 'Bump size for finite difference' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/sensitivities/cross-gamma', {
+ S: args.S || 100,
+ K: args.K || 100,
+ T: args.T || 1,
+ r: args.r || 0.05,
+ sigma: args.sigma || 0.2,
+ bump: args.bump || 0.01,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Cross-Gamma (Vanna): ${formatNumber(result.cross_gamma || result.vanna, 6)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_sensitivities_key_rate_duration',
+ description: 'Calculate key rate durations for a cashflow stream',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ cashflows: { type: 'string', description: 'JSON array of cashflow amounts' },
+ times: { type: 'string', description: 'JSON array of cashflow times (years)' },
+ curve_rates: { type: 'string', description: 'JSON array of zero rates at each tenor' },
+ bump_size: { type: 'number', description: 'Rate bump size' },
+ },
+ required: ['cashflows', 'times', 'curve_rates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/sensitivities/key-rate-duration', {
+ cashflows: JSON.parse(args.cashflows),
+ times: JSON.parse(args.times),
+ curve_rates: JSON.parse(args.curve_rates),
+ bump_size: args.bump_size || 0.0001,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Key rate durations calculated for ${JSON.parse(args.times).length} tenors`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_sensitivities_parallel_shift',
+ description: 'Calculate PV01/DV01 - sensitivity to parallel rate shift',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ cashflows: { type: 'string', description: 'JSON array of cashflow amounts' },
+ times: { type: 'string', description: 'JSON array of cashflow times' },
+ curve_rates: { type: 'string', description: 'JSON array of zero rates' },
+ bump_size: { type: 'number', description: 'Parallel shift size' },
+ },
+ required: ['cashflows', 'times', 'curve_rates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/sensitivities/parallel-shift', {
+ cashflows: JSON.parse(args.cashflows),
+ times: JSON.parse(args.times),
+ curve_rates: JSON.parse(args.curve_rates),
+ bump_size: args.bump_size || 0.0001,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `DV01: ${formatNumber(result.dv01 || result.pv01, 4)} per 1bp parallel shift`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_sensitivities_twist',
+ description: 'Calculate sensitivity to curve twist (steepening/flattening)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ cashflows: { type: 'string', description: 'JSON array of cashflow amounts' },
+ times: { type: 'string', description: 'JSON array of cashflow times' },
+ curve_rates: { type: 'string', description: 'JSON array of zero rates' },
+ bump_size: { type: 'number', description: 'Twist magnitude' },
+ },
+ required: ['cashflows', 'times', 'curve_rates'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/sensitivities/twist', {
+ cashflows: JSON.parse(args.cashflows),
+ times: JSON.parse(args.times),
+ curve_rates: JSON.parse(args.curve_rates),
+ bump_size: args.bump_size || 0.0001,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Twist sensitivity: ${formatNumber(result.twist_sensitivity, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+
+ // ==================== PORTFOLIO RISK (2) ====================
+ {
+ name: 'quantlib_risk_portfolio_optimal_hedge',
+ description: 'Calculate optimal hedge ratios to neutralize delta and gamma',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_delta: { type: 'number', description: 'Current portfolio delta' },
+ hedge_delta: { type: 'number', description: 'Hedge instrument delta' },
+ portfolio_gamma: { type: 'number', description: 'Current portfolio gamma' },
+ hedge_gamma: { type: 'number', description: 'Hedge instrument gamma' },
+ target_delta: { type: 'number', description: 'Target portfolio delta' },
+ target_gamma: { type: 'number', description: 'Target portfolio gamma' },
+ },
+ required: ['portfolio_delta', 'hedge_delta'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/portfolio-risk/optimal-hedge', {
+ portfolio_delta: args.portfolio_delta,
+ hedge_delta: args.hedge_delta,
+ portfolio_gamma: args.portfolio_gamma || 0,
+ hedge_gamma: args.hedge_gamma || 0,
+ target_delta: args.target_delta || 0,
+ target_gamma: args.target_gamma || 0,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Optimal hedge ratio: ${formatNumber(result.hedge_ratio || result.ratio, 4)} units`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'quantlib_risk_portfolio_exposure_profile',
+ description: 'Calculate exposure profile from simulation paths',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ paths: { type: 'string', description: 'JSON 2D array of simulation paths' },
+ confidence: { type: 'number', description: 'Confidence level for PFE' },
+ },
+ required: ['paths'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/risk/portfolio-risk/exposure-profile', {
+ paths: JSON.parse(args.paths),
+ confidence: args.confidence || 0.95,
+ }, apiKey);
+ return {
+ success: true,
+ data: result,
+ message: `Exposure profile: EPE=${formatNumber(result.expected_positive_exposure || result.epe, 4)}, max PFE=${formatNumber(result.max_pfe, 4)}`,
+ };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ },
+];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/statistics.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/statistics.ts
new file mode 100644
index 000000000..899a46790
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/statistics.ts
@@ -0,0 +1,1408 @@
+// QuantLib Statistics MCP Tools
+// 52 tools for continuous distributions, discrete distributions, and time series analysis
+
+import type { InternalTool } from '../../types';
+import { quantlibApiCall, formatNumber } from '../../QuantLibMCPBridge';
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CONTINUOUS DISTRIBUTIONS - NORMAL (4 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const normalPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_normal_properties',
+ description: 'Get properties of a normal distribution (mean, variance, skewness, kurtosis).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mu: { type: 'number', description: 'Mean (default: 0)' },
+ sigma: { type: 'number', description: 'Standard deviation (default: 1)' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/normal/properties', {
+ mu: args.mu,
+ sigma: args.sigma,
+ }, apiKey);
+ return { success: true, data: result, message: `Normal(μ=${args.mu || 0}, σ=${args.sigma || 1}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const normalPdfTool: InternalTool = {
+ name: 'quantlib_statistics_normal_pdf',
+ description: 'Calculate normal distribution PDF at point x.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mu: { type: 'number', description: 'Mean' },
+ sigma: { type: 'number', description: 'Standard deviation' },
+ x: { type: 'number', description: 'Point to evaluate' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/normal/pdf', {
+ mu: args.mu, sigma: args.sigma, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `PDF(${args.x}) = ${formatNumber(result.pdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const normalCdfTool: InternalTool = {
+ name: 'quantlib_statistics_normal_cdf',
+ description: 'Calculate normal distribution CDF at point x.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mu: { type: 'number', description: 'Mean' },
+ sigma: { type: 'number', description: 'Standard deviation' },
+ x: { type: 'number', description: 'Point to evaluate' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/normal/cdf', {
+ mu: args.mu, sigma: args.sigma, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `CDF(${args.x}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const normalPpfTool: InternalTool = {
+ name: 'quantlib_statistics_normal_ppf',
+ description: 'Calculate normal distribution quantile (inverse CDF).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mu: { type: 'number', description: 'Mean' },
+ sigma: { type: 'number', description: 'Standard deviation' },
+ p: { type: 'number', description: 'Probability (0-1)' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/normal/ppf', {
+ mu: args.mu, sigma: args.sigma, p: args.p,
+ }, apiKey);
+ return { success: true, data: result, message: `PPF(${args.p}) = ${formatNumber(result.ppf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CONTINUOUS DISTRIBUTIONS - LOGNORMAL (4 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const lognormalPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_lognormal_properties',
+ description: 'Get properties of a lognormal distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mu: { type: 'number', description: 'Mean of log' },
+ sigma: { type: 'number', description: 'Std dev of log' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/lognormal/properties', {
+ mu: args.mu, sigma: args.sigma,
+ }, apiKey);
+ return { success: true, data: result, message: 'Lognormal distribution properties' };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const lognormalPdfTool: InternalTool = {
+ name: 'quantlib_statistics_lognormal_pdf',
+ description: 'Calculate lognormal distribution PDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mu: { type: 'number', description: 'Mean of log' },
+ sigma: { type: 'number', description: 'Std dev of log' },
+ x: { type: 'number', description: 'Point to evaluate (>0)' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/lognormal/pdf', {
+ mu: args.mu, sigma: args.sigma, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Lognormal PDF(${args.x}) = ${formatNumber(result.pdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const lognormalCdfTool: InternalTool = {
+ name: 'quantlib_statistics_lognormal_cdf',
+ description: 'Calculate lognormal distribution CDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mu: { type: 'number', description: 'Mean of log' },
+ sigma: { type: 'number', description: 'Std dev of log' },
+ x: { type: 'number', description: 'Point to evaluate' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/lognormal/cdf', {
+ mu: args.mu, sigma: args.sigma, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Lognormal CDF(${args.x}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const lognormalPpfTool: InternalTool = {
+ name: 'quantlib_statistics_lognormal_ppf',
+ description: 'Calculate lognormal distribution quantile.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mu: { type: 'number', description: 'Mean of log' },
+ sigma: { type: 'number', description: 'Std dev of log' },
+ p: { type: 'number', description: 'Probability (0-1)' },
+ },
+ required: [],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/lognormal/ppf', {
+ mu: args.mu, sigma: args.sigma, p: args.p,
+ }, apiKey);
+ return { success: true, data: result, message: `Lognormal PPF(${args.p}) = ${formatNumber(result.ppf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CONTINUOUS DISTRIBUTIONS - STUDENT-T (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const studentTPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_student_t_properties',
+ description: 'Get properties of Student-t distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ df: { type: 'number', description: 'Degrees of freedom' },
+ mu: { type: 'number', description: 'Location parameter' },
+ sigma: { type: 'number', description: 'Scale parameter' },
+ },
+ required: ['df'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/student-t/properties', {
+ df: args.df, mu: args.mu, sigma: args.sigma,
+ }, apiKey);
+ return { success: true, data: result, message: `Student-t(df=${args.df}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const studentTPdfTool: InternalTool = {
+ name: 'quantlib_statistics_student_t_pdf',
+ description: 'Calculate Student-t distribution PDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ df: { type: 'number', description: 'Degrees of freedom' },
+ mu: { type: 'number', description: 'Location' },
+ sigma: { type: 'number', description: 'Scale' },
+ x: { type: 'number', description: 'Point to evaluate' },
+ },
+ required: ['df'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/student-t/pdf', {
+ df: args.df, mu: args.mu, sigma: args.sigma, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Student-t PDF(${args.x}) = ${formatNumber(result.pdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const studentTCdfTool: InternalTool = {
+ name: 'quantlib_statistics_student_t_cdf',
+ description: 'Calculate Student-t distribution CDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ df: { type: 'number', description: 'Degrees of freedom' },
+ mu: { type: 'number', description: 'Location' },
+ sigma: { type: 'number', description: 'Scale' },
+ x: { type: 'number', description: 'Point to evaluate' },
+ },
+ required: ['df'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/student-t/cdf', {
+ df: args.df, mu: args.mu, sigma: args.sigma, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Student-t CDF(${args.x}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CONTINUOUS DISTRIBUTIONS - CHI-SQUARED (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const chiSquaredPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_chi_squared_properties',
+ description: 'Get properties of chi-squared distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ df: { type: 'number', description: 'Degrees of freedom' },
+ },
+ required: ['df'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/chi-squared/properties', {
+ df: args.df,
+ }, apiKey);
+ return { success: true, data: result, message: `Chi-squared(df=${args.df}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const chiSquaredPdfTool: InternalTool = {
+ name: 'quantlib_statistics_chi_squared_pdf',
+ description: 'Calculate chi-squared distribution PDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ df: { type: 'number', description: 'Degrees of freedom' },
+ x: { type: 'number', description: 'Point to evaluate (>=0)' },
+ },
+ required: ['df', 'x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/chi-squared/pdf', {
+ df: args.df, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Chi-squared PDF(${args.x}) = ${formatNumber(result.pdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const chiSquaredCdfTool: InternalTool = {
+ name: 'quantlib_statistics_chi_squared_cdf',
+ description: 'Calculate chi-squared distribution CDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ df: { type: 'number', description: 'Degrees of freedom' },
+ x: { type: 'number', description: 'Point to evaluate' },
+ },
+ required: ['df', 'x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/chi-squared/cdf', {
+ df: args.df, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Chi-squared CDF(${args.x}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CONTINUOUS DISTRIBUTIONS - GAMMA (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const gammaPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_gamma_properties',
+ description: 'Get properties of gamma distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ alpha: { type: 'number', description: 'Shape parameter (>0)' },
+ beta: { type: 'number', description: 'Rate parameter (>0)' },
+ },
+ required: ['alpha'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/gamma/properties', {
+ alpha: args.alpha, beta: args.beta,
+ }, apiKey);
+ return { success: true, data: result, message: `Gamma(α=${args.alpha}, β=${args.beta || 1}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const gammaPdfTool: InternalTool = {
+ name: 'quantlib_statistics_gamma_pdf',
+ description: 'Calculate gamma distribution PDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ alpha: { type: 'number', description: 'Shape parameter' },
+ beta: { type: 'number', description: 'Rate parameter' },
+ x: { type: 'number', description: 'Point to evaluate (>=0)' },
+ },
+ required: ['alpha'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/gamma/pdf', {
+ alpha: args.alpha, beta: args.beta, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Gamma PDF(${args.x}) = ${formatNumber(result.pdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const gammaCdfTool: InternalTool = {
+ name: 'quantlib_statistics_gamma_cdf',
+ description: 'Calculate gamma distribution CDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ alpha: { type: 'number', description: 'Shape parameter' },
+ beta: { type: 'number', description: 'Rate parameter' },
+ x: { type: 'number', description: 'Point to evaluate' },
+ },
+ required: ['alpha'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/gamma/cdf', {
+ alpha: args.alpha, beta: args.beta, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Gamma CDF(${args.x}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CONTINUOUS DISTRIBUTIONS - BETA (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const betaPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_beta_properties',
+ description: 'Get properties of beta distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ alpha: { type: 'number', description: 'Alpha parameter (>0)' },
+ beta: { type: 'number', description: 'Beta parameter (>0)' },
+ },
+ required: ['alpha', 'beta'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/beta/properties', {
+ alpha: args.alpha, beta: args.beta,
+ }, apiKey);
+ return { success: true, data: result, message: `Beta(α=${args.alpha}, β=${args.beta}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const betaPdfTool: InternalTool = {
+ name: 'quantlib_statistics_beta_pdf',
+ description: 'Calculate beta distribution PDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ alpha: { type: 'number', description: 'Alpha parameter' },
+ beta: { type: 'number', description: 'Beta parameter' },
+ x: { type: 'number', description: 'Point to evaluate (0-1)' },
+ },
+ required: ['alpha', 'beta'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/beta/pdf', {
+ alpha: args.alpha, beta: args.beta, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Beta PDF(${args.x}) = ${formatNumber(result.pdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const betaCdfTool: InternalTool = {
+ name: 'quantlib_statistics_beta_cdf',
+ description: 'Calculate beta distribution CDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ alpha: { type: 'number', description: 'Alpha parameter' },
+ beta: { type: 'number', description: 'Beta parameter' },
+ x: { type: 'number', description: 'Point to evaluate' },
+ },
+ required: ['alpha', 'beta'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/beta/cdf', {
+ alpha: args.alpha, beta: args.beta, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Beta CDF(${args.x}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CONTINUOUS DISTRIBUTIONS - EXPONENTIAL (4 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const exponentialPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_exponential_properties',
+ description: 'Get properties of exponential distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ rate: { type: 'number', description: 'Rate parameter (λ > 0)' },
+ },
+ required: ['rate'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/exponential/properties', {
+ rate: args.rate,
+ }, apiKey);
+ return { success: true, data: result, message: `Exponential(λ=${args.rate}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const exponentialPdfTool: InternalTool = {
+ name: 'quantlib_statistics_exponential_pdf',
+ description: 'Calculate exponential distribution PDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ rate: { type: 'number', description: 'Rate parameter' },
+ x: { type: 'number', description: 'Point to evaluate (>=0)' },
+ },
+ required: ['rate', 'x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/exponential/pdf', {
+ rate: args.rate, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Exponential PDF(${args.x}) = ${formatNumber(result.pdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const exponentialCdfTool: InternalTool = {
+ name: 'quantlib_statistics_exponential_cdf',
+ description: 'Calculate exponential distribution CDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ rate: { type: 'number', description: 'Rate parameter' },
+ x: { type: 'number', description: 'Point to evaluate' },
+ },
+ required: ['rate', 'x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/exponential/cdf', {
+ rate: args.rate, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `Exponential CDF(${args.x}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const exponentialPpfTool: InternalTool = {
+ name: 'quantlib_statistics_exponential_ppf',
+ description: 'Calculate exponential distribution quantile.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ rate: { type: 'number', description: 'Rate parameter' },
+ p: { type: 'number', description: 'Probability (0-1)' },
+ },
+ required: ['rate', 'p'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/exponential/ppf', {
+ rate: args.rate, p: args.p,
+ }, apiKey);
+ return { success: true, data: result, message: `Exponential PPF(${args.p}) = ${formatNumber(result.ppf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// CONTINUOUS DISTRIBUTIONS - F (2 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const fPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_f_properties',
+ description: 'Get properties of F distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ df1: { type: 'number', description: 'Numerator degrees of freedom' },
+ df2: { type: 'number', description: 'Denominator degrees of freedom' },
+ },
+ required: ['df1', 'df2'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/f/properties', {
+ df1: args.df1, df2: args.df2,
+ }, apiKey);
+ return { success: true, data: result, message: `F(${args.df1}, ${args.df2}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const fPdfTool: InternalTool = {
+ name: 'quantlib_statistics_f_pdf',
+ description: 'Calculate F distribution PDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ df1: { type: 'number', description: 'Numerator df' },
+ df2: { type: 'number', description: 'Denominator df' },
+ x: { type: 'number', description: 'Point to evaluate (>=0)' },
+ },
+ required: ['df1', 'df2', 'x'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/f/pdf', {
+ df1: args.df1, df2: args.df2, x: args.x,
+ }, apiKey);
+ return { success: true, data: result, message: `F PDF(${args.x}) = ${formatNumber(result.pdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// DISCRETE DISTRIBUTIONS - BINOMIAL (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const binomialPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_binomial_properties',
+ description: 'Get properties of binomial distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ n: { type: 'number', description: 'Number of trials' },
+ p: { type: 'number', description: 'Probability of success (0-1)' },
+ },
+ required: ['n', 'p'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/binomial/properties', {
+ n: args.n, p: args.p,
+ }, apiKey);
+ return { success: true, data: result, message: `Binomial(n=${args.n}, p=${args.p}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const binomialPmfTool: InternalTool = {
+ name: 'quantlib_statistics_binomial_pmf',
+ description: 'Calculate binomial distribution PMF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ n: { type: 'number', description: 'Number of trials' },
+ p: { type: 'number', description: 'Probability of success' },
+ k: { type: 'number', description: 'Number of successes' },
+ },
+ required: ['n', 'p', 'k'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/binomial/pmf', {
+ n: args.n, p: args.p, k: args.k,
+ }, apiKey);
+ return { success: true, data: result, message: `Binomial PMF(${args.k}) = ${formatNumber(result.pmf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const binomialCdfTool: InternalTool = {
+ name: 'quantlib_statistics_binomial_cdf',
+ description: 'Calculate binomial distribution CDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ n: { type: 'number', description: 'Number of trials' },
+ p: { type: 'number', description: 'Probability of success' },
+ k: { type: 'number', description: 'Number of successes' },
+ },
+ required: ['n', 'p', 'k'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/binomial/cdf', {
+ n: args.n, p: args.p, k: args.k,
+ }, apiKey);
+ return { success: true, data: result, message: `Binomial CDF(${args.k}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// DISCRETE DISTRIBUTIONS - POISSON (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const poissonPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_poisson_properties',
+ description: 'Get properties of Poisson distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ lam: { type: 'number', description: 'Rate parameter (λ > 0)' },
+ },
+ required: ['lam'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/poisson/properties', {
+ lam: args.lam,
+ }, apiKey);
+ return { success: true, data: result, message: `Poisson(λ=${args.lam}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const poissonPmfTool: InternalTool = {
+ name: 'quantlib_statistics_poisson_pmf',
+ description: 'Calculate Poisson distribution PMF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ lam: { type: 'number', description: 'Rate parameter' },
+ k: { type: 'number', description: 'Number of events' },
+ },
+ required: ['lam', 'k'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/poisson/pmf', {
+ lam: args.lam, k: args.k,
+ }, apiKey);
+ return { success: true, data: result, message: `Poisson PMF(${args.k}) = ${formatNumber(result.pmf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const poissonCdfTool: InternalTool = {
+ name: 'quantlib_statistics_poisson_cdf',
+ description: 'Calculate Poisson distribution CDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ lam: { type: 'number', description: 'Rate parameter' },
+ k: { type: 'number', description: 'Number of events' },
+ },
+ required: ['lam', 'k'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/poisson/cdf', {
+ lam: args.lam, k: args.k,
+ }, apiKey);
+ return { success: true, data: result, message: `Poisson CDF(${args.k}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// DISCRETE DISTRIBUTIONS - GEOMETRIC (4 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const geometricPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_geometric_properties',
+ description: 'Get properties of geometric distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ p: { type: 'number', description: 'Probability of success (0-1)' },
+ },
+ required: ['p'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/geometric/properties', {
+ p: args.p,
+ }, apiKey);
+ return { success: true, data: result, message: `Geometric(p=${args.p}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const geometricPmfTool: InternalTool = {
+ name: 'quantlib_statistics_geometric_pmf',
+ description: 'Calculate geometric distribution PMF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ p: { type: 'number', description: 'Probability of success' },
+ k: { type: 'number', description: 'Trial number of first success' },
+ },
+ required: ['p', 'k'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/geometric/pmf', {
+ p: args.p, k: args.k,
+ }, apiKey);
+ return { success: true, data: result, message: `Geometric PMF(${args.k}) = ${formatNumber(result.pmf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const geometricCdfTool: InternalTool = {
+ name: 'quantlib_statistics_geometric_cdf',
+ description: 'Calculate geometric distribution CDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ p: { type: 'number', description: 'Probability of success' },
+ k: { type: 'number', description: 'Trial number' },
+ },
+ required: ['p', 'k'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/geometric/cdf', {
+ p: args.p, k: args.k,
+ }, apiKey);
+ return { success: true, data: result, message: `Geometric CDF(${args.k}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const geometricPpfTool: InternalTool = {
+ name: 'quantlib_statistics_geometric_ppf',
+ description: 'Calculate geometric distribution quantile.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ p: { type: 'number', description: 'Success probability' },
+ q: { type: 'number', description: 'Quantile probability (0-1)' },
+ },
+ required: ['p', 'q'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/geometric/ppf', {
+ p: args.p, q: args.q,
+ }, apiKey);
+ return { success: true, data: result, message: `Geometric PPF(${args.q}) = ${formatNumber(result.ppf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// DISCRETE DISTRIBUTIONS - HYPERGEOMETRIC (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const hypergeometricPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_hypergeometric_properties',
+ description: 'Get properties of hypergeometric distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ N: { type: 'number', description: 'Population size' },
+ K: { type: 'number', description: 'Number of success states in population' },
+ n: { type: 'number', description: 'Number of draws' },
+ },
+ required: ['N', 'K', 'n'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/hypergeometric/properties', {
+ N: args.N, K: args.K, n: args.n,
+ }, apiKey);
+ return { success: true, data: result, message: `Hypergeometric(N=${args.N}, K=${args.K}, n=${args.n}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const hypergeometricPmfTool: InternalTool = {
+ name: 'quantlib_statistics_hypergeometric_pmf',
+ description: 'Calculate hypergeometric distribution PMF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ N: { type: 'number', description: 'Population size' },
+ K: { type: 'number', description: 'Success states in population' },
+ n: { type: 'number', description: 'Number of draws' },
+ k: { type: 'number', description: 'Number of observed successes' },
+ },
+ required: ['N', 'K', 'n', 'k'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/hypergeometric/pmf', {
+ N: args.N, K: args.K, n: args.n, k: args.k,
+ }, apiKey);
+ return { success: true, data: result, message: `Hypergeometric PMF(${args.k}) = ${formatNumber(result.pmf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const hypergeometricCdfTool: InternalTool = {
+ name: 'quantlib_statistics_hypergeometric_cdf',
+ description: 'Calculate hypergeometric distribution CDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ N: { type: 'number', description: 'Population size' },
+ K: { type: 'number', description: 'Success states in population' },
+ n: { type: 'number', description: 'Number of draws' },
+ k: { type: 'number', description: 'Number of observed successes' },
+ },
+ required: ['N', 'K', 'n', 'k'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/hypergeometric/cdf', {
+ N: args.N, K: args.K, n: args.n, k: args.k,
+ }, apiKey);
+ return { success: true, data: result, message: `Hypergeometric CDF(${args.k}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// DISCRETE DISTRIBUTIONS - NEGATIVE BINOMIAL (3 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const negBinomialPropertiesTool: InternalTool = {
+ name: 'quantlib_statistics_negative_binomial_properties',
+ description: 'Get properties of negative binomial distribution.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ r: { type: 'number', description: 'Number of successes required' },
+ p: { type: 'number', description: 'Probability of success (0-1)' },
+ },
+ required: ['r', 'p'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/negative-binomial/properties', {
+ r: args.r, p: args.p,
+ }, apiKey);
+ return { success: true, data: result, message: `NegBinomial(r=${args.r}, p=${args.p}) properties` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const negBinomialPmfTool: InternalTool = {
+ name: 'quantlib_statistics_negative_binomial_pmf',
+ description: 'Calculate negative binomial distribution PMF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ r: { type: 'number', description: 'Successes required' },
+ p: { type: 'number', description: 'Success probability' },
+ k: { type: 'number', description: 'Number of failures' },
+ },
+ required: ['r', 'p', 'k'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/negative-binomial/pmf', {
+ r: args.r, p: args.p, k: args.k,
+ }, apiKey);
+ return { success: true, data: result, message: `NegBinomial PMF(${args.k}) = ${formatNumber(result.pmf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const negBinomialCdfTool: InternalTool = {
+ name: 'quantlib_statistics_negative_binomial_cdf',
+ description: 'Calculate negative binomial distribution CDF.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ r: { type: 'number', description: 'Successes required' },
+ p: { type: 'number', description: 'Success probability' },
+ k: { type: 'number', description: 'Number of failures' },
+ },
+ required: ['r', 'p', 'k'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/negative-binomial/cdf', {
+ r: args.r, p: args.p, k: args.k,
+ }, apiKey);
+ return { success: true, data: result, message: `NegBinomial CDF(${args.k}) = ${formatNumber(result.cdf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// PGF (1 tool)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const pgfEvaluateTool: InternalTool = {
+ name: 'quantlib_statistics_pgf_evaluate',
+ description: 'Evaluate probability generating function for discrete distributions.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ distribution: { type: 'string', description: 'Distribution type: binomial, poisson' },
+ z: { type: 'number', description: 'Point to evaluate PGF' },
+ n: { type: 'number', description: 'n parameter (for binomial)' },
+ p: { type: 'number', description: 'p parameter (for binomial)' },
+ lam: { type: 'number', description: 'lambda parameter (for poisson)' },
+ },
+ required: ['distribution', 'z'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/distributions/pgf', {
+ distribution: args.distribution,
+ z: args.z,
+ n: args.n,
+ p: args.p,
+ lam: args.lam,
+ }, apiKey);
+ return { success: true, data: result, message: `PGF(${args.z}) = ${formatNumber(result.pgf)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// TIME SERIES (9 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const arFitTool: InternalTool = {
+ name: 'quantlib_statistics_timeseries_ar_fit',
+ description: 'Fit an AR(p) model to time series data.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ data: { type: 'string', description: 'JSON array of time series values' },
+ order: { type: 'number', description: 'AR order (p)' },
+ },
+ required: ['data'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/timeseries/ar/fit', {
+ data: JSON.parse(args.data as string),
+ order: args.order,
+ }, apiKey);
+ return { success: true, data: result, message: `Fitted AR(${args.order || 'auto'}) model` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const arForecastTool: InternalTool = {
+ name: 'quantlib_statistics_timeseries_ar_forecast',
+ description: 'Forecast using AR model.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ data: { type: 'string', description: 'JSON array of time series values' },
+ order: { type: 'number', description: 'AR order' },
+ steps: { type: 'number', description: 'Forecast steps ahead' },
+ },
+ required: ['data'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/timeseries/ar/forecast', {
+ data: JSON.parse(args.data as string),
+ order: args.order,
+ steps: args.steps,
+ }, apiKey);
+ return { success: true, data: result, message: `AR forecast: ${args.steps || 1} steps ahead` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const maFitTool: InternalTool = {
+ name: 'quantlib_statistics_timeseries_ma_fit',
+ description: 'Fit an MA(q) model to time series data.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ data: { type: 'string', description: 'JSON array of time series values' },
+ order: { type: 'number', description: 'MA order (q)' },
+ },
+ required: ['data'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/timeseries/ma/fit', {
+ data: JSON.parse(args.data as string),
+ order: args.order,
+ }, apiKey);
+ return { success: true, data: result, message: `Fitted MA(${args.order || 'auto'}) model` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const arimaFitTool: InternalTool = {
+ name: 'quantlib_statistics_timeseries_arima_fit',
+ description: 'Fit an ARIMA(p,d,q) model to time series data.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ data: { type: 'string', description: 'JSON array of time series values' },
+ p: { type: 'number', description: 'AR order' },
+ d: { type: 'number', description: 'Differencing order' },
+ q: { type: 'number', description: 'MA order' },
+ },
+ required: ['data'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/timeseries/arima/fit', {
+ data: JSON.parse(args.data as string),
+ p: args.p,
+ d: args.d,
+ q: args.q,
+ }, apiKey);
+ return { success: true, data: result, message: `Fitted ARIMA(${args.p || 1},${args.d || 0},${args.q || 0}) model` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const arimaForecastTool: InternalTool = {
+ name: 'quantlib_statistics_timeseries_arima_forecast',
+ description: 'Forecast using ARIMA model.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ data: { type: 'string', description: 'JSON array of time series values' },
+ p: { type: 'number', description: 'AR order' },
+ d: { type: 'number', description: 'Differencing order' },
+ q: { type: 'number', description: 'MA order' },
+ steps: { type: 'number', description: 'Forecast steps ahead' },
+ },
+ required: ['data'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/timeseries/arima/forecast', {
+ data: JSON.parse(args.data as string),
+ p: args.p, d: args.d, q: args.q, steps: args.steps,
+ }, apiKey);
+ return { success: true, data: result, message: `ARIMA forecast: ${args.steps || 1} steps ahead` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const garchFitTool: InternalTool = {
+ name: 'quantlib_statistics_timeseries_garch_fit',
+ description: 'Fit a GARCH(p,q) model to return series.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns: { type: 'string', description: 'JSON array of return values' },
+ p: { type: 'number', description: 'GARCH p order' },
+ q: { type: 'number', description: 'GARCH q order' },
+ },
+ required: ['returns'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/timeseries/garch/fit', {
+ returns: JSON.parse(args.returns as string),
+ p: args.p,
+ q: args.q,
+ }, apiKey);
+ return { success: true, data: result, message: `Fitted GARCH(${args.p || 1},${args.q || 1}) model` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const garchForecastTool: InternalTool = {
+ name: 'quantlib_statistics_timeseries_garch_forecast',
+ description: 'Forecast volatility using GARCH model.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns: { type: 'string', description: 'JSON array of return values' },
+ p: { type: 'number', description: 'GARCH p order' },
+ q: { type: 'number', description: 'GARCH q order' },
+ steps: { type: 'number', description: 'Forecast steps ahead' },
+ },
+ required: ['returns'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/timeseries/garch/forecast', {
+ returns: JSON.parse(args.returns as string),
+ p: args.p, q: args.q, steps: args.steps,
+ }, apiKey);
+ return { success: true, data: result, message: `GARCH volatility forecast: ${args.steps || 1} steps ahead` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const egarchFitTool: InternalTool = {
+ name: 'quantlib_statistics_timeseries_egarch_fit',
+ description: 'Fit an EGARCH model (asymmetric volatility).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns: { type: 'string', description: 'JSON array of return values' },
+ p: { type: 'number', description: 'EGARCH p order' },
+ q: { type: 'number', description: 'EGARCH q order' },
+ },
+ required: ['returns'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/timeseries/egarch/fit', {
+ returns: JSON.parse(args.returns as string),
+ p: args.p,
+ q: args.q,
+ }, apiKey);
+ return { success: true, data: result, message: `Fitted EGARCH(${args.p || 1},${args.q || 1}) model` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const gjrGarchFitTool: InternalTool = {
+ name: 'quantlib_statistics_timeseries_gjr_garch_fit',
+ description: 'Fit a GJR-GARCH model (leverage effect).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ returns: { type: 'string', description: 'JSON array of return values' },
+ p: { type: 'number', description: 'GJR-GARCH p order' },
+ q: { type: 'number', description: 'GJR-GARCH q order' },
+ },
+ required: ['returns'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/statistics/timeseries/gjr-garch/fit', {
+ returns: JSON.parse(args.returns as string),
+ p: args.p,
+ q: args.q,
+ }, apiKey);
+ return { success: true, data: result, message: `Fitted GJR-GARCH(${args.p || 1},${args.q || 1}) model` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// EXPORT ALL TOOLS
+// ══════════════════════════════════════════════════════════════════════════════
+
+export const quantlibStatisticsTools: InternalTool[] = [
+ // Normal (4)
+ normalPropertiesTool, normalPdfTool, normalCdfTool, normalPpfTool,
+ // Lognormal (4)
+ lognormalPropertiesTool, lognormalPdfTool, lognormalCdfTool, lognormalPpfTool,
+ // Student-t (3)
+ studentTPropertiesTool, studentTPdfTool, studentTCdfTool,
+ // Chi-squared (3)
+ chiSquaredPropertiesTool, chiSquaredPdfTool, chiSquaredCdfTool,
+ // Gamma (3)
+ gammaPropertiesTool, gammaPdfTool, gammaCdfTool,
+ // Beta (3)
+ betaPropertiesTool, betaPdfTool, betaCdfTool,
+ // Exponential (4)
+ exponentialPropertiesTool, exponentialPdfTool, exponentialCdfTool, exponentialPpfTool,
+ // F (2)
+ fPropertiesTool, fPdfTool,
+ // Binomial (3)
+ binomialPropertiesTool, binomialPmfTool, binomialCdfTool,
+ // Poisson (3)
+ poissonPropertiesTool, poissonPmfTool, poissonCdfTool,
+ // Geometric (4)
+ geometricPropertiesTool, geometricPmfTool, geometricCdfTool, geometricPpfTool,
+ // Hypergeometric (3)
+ hypergeometricPropertiesTool, hypergeometricPmfTool, hypergeometricCdfTool,
+ // Negative Binomial (3)
+ negBinomialPropertiesTool, negBinomialPmfTool, negBinomialCdfTool,
+ // PGF (1)
+ pgfEvaluateTool,
+ // Time Series (9)
+ arFitTool, arForecastTool, maFitTool,
+ arimaFitTool, arimaForecastTool,
+ garchFitTool, garchForecastTool,
+ egarchFitTool, gjrGarchFitTool,
+];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/volatility.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/volatility.ts
new file mode 100644
index 000000000..7258c689b
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/quantlib/volatility.ts
@@ -0,0 +1,498 @@
+// QuantLib Volatility MCP Tools
+// 14 tools for volatility surfaces, SABR model, and local volatility
+
+import type { InternalTool } from '../../types';
+import { quantlibApiCall, formatNumber, formatPercent } from '../../QuantLibMCPBridge';
+
+// ══════════════════════════════════════════════════════════════════════════════
+// SURFACE (6 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const surfaceFlatTool: InternalTool = {
+ name: 'quantlib_volatility_surface_flat',
+ description: 'Create a flat volatility surface with constant vol across all strikes and expiries.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ volatility: { type: 'number', description: 'Flat volatility level (e.g., 0.20 for 20%)' },
+ query_expiry: { type: 'number', description: 'Expiry to query in years' },
+ query_strike: { type: 'number', description: 'Strike to query' },
+ },
+ required: ['volatility', 'query_expiry', 'query_strike'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/volatility/surface/flat', {
+ volatility: args.volatility,
+ query_expiry: args.query_expiry,
+ query_strike: args.query_strike,
+ }, apiKey);
+ return { success: true, data: result, message: `Flat surface vol: ${formatPercent(args.volatility as number)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const surfaceTermStructureTool: InternalTool = {
+ name: 'quantlib_volatility_surface_term_structure',
+ description: 'Create a volatility term structure (vol varies by expiry only).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ expiries: { type: 'string', description: 'JSON array of expiry times in years' },
+ volatilities: { type: 'string', description: 'JSON array of volatilities corresponding to expiries' },
+ query_expiry: { type: 'number', description: 'Expiry to query in years' },
+ },
+ required: ['expiries', 'volatilities', 'query_expiry'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/volatility/surface/term-structure', {
+ expiries: JSON.parse(args.expiries as string),
+ volatilities: JSON.parse(args.volatilities as string),
+ query_expiry: args.query_expiry,
+ }, apiKey);
+ return { success: true, data: result, message: `Vol at ${args.query_expiry}Y: ${formatPercent(result.volatility)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const surfaceGridTool: InternalTool = {
+ name: 'quantlib_volatility_surface_grid',
+ description: 'Create a full volatility surface from a grid of expiries, strikes, and vol matrix.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ expiries: { type: 'string', description: 'JSON array of expiry times in years' },
+ strikes: { type: 'string', description: 'JSON array of strikes' },
+ vol_matrix: { type: 'string', description: 'JSON 2D array of volatilities [expiries x strikes]' },
+ query_expiry: { type: 'number', description: 'Expiry to query in years' },
+ query_strike: { type: 'number', description: 'Strike to query' },
+ },
+ required: ['expiries', 'strikes', 'vol_matrix', 'query_expiry', 'query_strike'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/volatility/surface/grid', {
+ expiries: JSON.parse(args.expiries as string),
+ strikes: JSON.parse(args.strikes as string),
+ vol_matrix: JSON.parse(args.vol_matrix as string),
+ query_expiry: args.query_expiry,
+ query_strike: args.query_strike,
+ }, apiKey);
+ return { success: true, data: result, message: `Surface vol at T=${args.query_expiry}, K=${args.query_strike}: ${formatPercent(result.volatility)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const surfaceSmileTool: InternalTool = {
+ name: 'quantlib_volatility_surface_smile',
+ description: 'Extract the volatility smile at a given expiry across multiple strikes.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ expiries: { type: 'string', description: 'JSON array of expiry times in years' },
+ strikes: { type: 'string', description: 'JSON array of strikes' },
+ vol_matrix: { type: 'string', description: 'JSON 2D array of volatilities' },
+ query_expiry: { type: 'number', description: 'Expiry to extract smile at' },
+ query_strikes: { type: 'string', description: 'JSON array of strikes to query' },
+ },
+ required: ['expiries', 'strikes', 'vol_matrix', 'query_expiry', 'query_strikes'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const queryStrikes = JSON.parse(args.query_strikes as string);
+ const result = await quantlibApiCall('/quantlib/volatility/surface/smile', {
+ expiries: JSON.parse(args.expiries as string),
+ strikes: JSON.parse(args.strikes as string),
+ vol_matrix: JSON.parse(args.vol_matrix as string),
+ query_expiry: args.query_expiry,
+ query_strikes: queryStrikes,
+ }, apiKey);
+ return { success: true, data: result, message: `Extracted smile at T=${args.query_expiry} for ${queryStrikes.length} strikes` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const surfaceTotalVarianceTool: InternalTool = {
+ name: 'quantlib_volatility_surface_total_variance',
+ description: 'Calculate total variance (sigma^2 * T) at a given point on the surface.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ expiries: { type: 'string', description: 'JSON array of expiry times in years' },
+ strikes: { type: 'string', description: 'JSON array of strikes' },
+ vol_matrix: { type: 'string', description: 'JSON 2D array of volatilities' },
+ query_expiry: { type: 'number', description: 'Expiry to query in years' },
+ query_strike: { type: 'number', description: 'Strike to query' },
+ },
+ required: ['expiries', 'strikes', 'vol_matrix', 'query_expiry', 'query_strike'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/volatility/surface/total-variance', {
+ expiries: JSON.parse(args.expiries as string),
+ strikes: JSON.parse(args.strikes as string),
+ vol_matrix: JSON.parse(args.vol_matrix as string),
+ query_expiry: args.query_expiry,
+ query_strike: args.query_strike,
+ }, apiKey);
+ return { success: true, data: result, message: `Total variance: ${formatNumber(result.total_variance)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const surfaceFromPointsTool: InternalTool = {
+ name: 'quantlib_volatility_surface_from_points',
+ description: 'Build a volatility surface from scattered points (tenors, strikes, vols).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tenors: { type: 'string', description: 'JSON array of tenor values' },
+ strikes: { type: 'string', description: 'JSON array of strike values' },
+ vols: { type: 'string', description: 'JSON array of volatility values' },
+ forwards: { type: 'string', description: 'Optional JSON array of forward prices' },
+ expiry_grid: { type: 'string', description: 'Optional JSON array of expiry grid points' },
+ strike_grid: { type: 'string', description: 'Optional JSON array of strike grid points' },
+ },
+ required: ['tenors', 'strikes', 'vols'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/volatility/surface/from-points', {
+ tenors: JSON.parse(args.tenors as string),
+ strikes: JSON.parse(args.strikes as string),
+ vols: JSON.parse(args.vols as string),
+ forwards: args.forwards ? JSON.parse(args.forwards as string) : undefined,
+ expiry_grid: args.expiry_grid ? JSON.parse(args.expiry_grid as string) : undefined,
+ strike_grid: args.strike_grid ? JSON.parse(args.strike_grid as string) : undefined,
+ }, apiKey);
+ return { success: true, data: result, message: 'Built volatility surface from scattered points' };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// SABR MODEL (6 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const sabrImpliedVolTool: InternalTool = {
+ name: 'quantlib_volatility_sabr_implied_vol',
+ description: 'Calculate SABR implied volatility (lognormal) for given parameters and strike.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ expiry: { type: 'number', description: 'Time to expiry in years' },
+ alpha: { type: 'number', description: 'SABR alpha (initial vol)' },
+ beta: { type: 'number', description: 'SABR beta (elasticity, 0-1)' },
+ rho: { type: 'number', description: 'SABR rho (correlation, -1 to 1)' },
+ nu: { type: 'number', description: 'SABR nu (vol of vol)' },
+ },
+ required: ['forward', 'strike', 'expiry', 'alpha', 'beta', 'rho', 'nu'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/volatility/sabr/implied-vol', {
+ forward: args.forward,
+ strike: args.strike,
+ expiry: args.expiry,
+ alpha: args.alpha,
+ beta: args.beta,
+ rho: args.rho,
+ nu: args.nu,
+ }, apiKey);
+ return { success: true, data: result, message: `SABR implied vol: ${formatPercent(result.implied_vol)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const sabrNormalVolTool: InternalTool = {
+ name: 'quantlib_volatility_sabr_normal_vol',
+ description: 'Calculate SABR normal (Bachelier) volatility for given parameters.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ strike: { type: 'number', description: 'Strike price' },
+ expiry: { type: 'number', description: 'Time to expiry in years' },
+ alpha: { type: 'number', description: 'SABR alpha' },
+ beta: { type: 'number', description: 'SABR beta' },
+ rho: { type: 'number', description: 'SABR rho' },
+ nu: { type: 'number', description: 'SABR nu' },
+ },
+ required: ['forward', 'strike', 'expiry', 'alpha', 'beta', 'rho', 'nu'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/volatility/sabr/normal-vol', {
+ forward: args.forward,
+ strike: args.strike,
+ expiry: args.expiry,
+ alpha: args.alpha,
+ beta: args.beta,
+ rho: args.rho,
+ nu: args.nu,
+ }, apiKey);
+ return { success: true, data: result, message: `SABR normal vol: ${formatNumber(result.normal_vol)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const sabrSmileTool: InternalTool = {
+ name: 'quantlib_volatility_sabr_smile',
+ description: 'Generate the full SABR smile across multiple strikes.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ expiry: { type: 'number', description: 'Time to expiry in years' },
+ alpha: { type: 'number', description: 'SABR alpha' },
+ beta: { type: 'number', description: 'SABR beta' },
+ rho: { type: 'number', description: 'SABR rho' },
+ nu: { type: 'number', description: 'SABR nu' },
+ strikes: { type: 'string', description: 'JSON array of strikes to evaluate' },
+ },
+ required: ['forward', 'expiry', 'alpha', 'beta', 'rho', 'nu', 'strikes'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const strikes = JSON.parse(args.strikes as string);
+ const result = await quantlibApiCall('/quantlib/volatility/sabr/smile', {
+ forward: args.forward,
+ expiry: args.expiry,
+ alpha: args.alpha,
+ beta: args.beta,
+ rho: args.rho,
+ nu: args.nu,
+ strikes,
+ }, apiKey);
+ return { success: true, data: result, message: `Generated SABR smile for ${strikes.length} strikes` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const sabrCalibrateTool: InternalTool = {
+ name: 'quantlib_volatility_sabr_calibrate',
+ description: 'Calibrate SABR parameters to market volatility data.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ expiry: { type: 'number', description: 'Time to expiry in years' },
+ strikes: { type: 'string', description: 'JSON array of market strikes' },
+ market_vols: { type: 'string', description: 'JSON array of market implied vols' },
+ beta: { type: 'number', description: 'Optional fixed beta (if not calibrated)' },
+ weights: { type: 'string', description: 'Optional JSON array of calibration weights' },
+ method: { type: 'string', description: 'Calibration method (default: least_squares)' },
+ },
+ required: ['forward', 'expiry', 'strikes', 'market_vols'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/volatility/sabr/calibrate', {
+ forward: args.forward,
+ expiry: args.expiry,
+ strikes: JSON.parse(args.strikes as string),
+ market_vols: JSON.parse(args.market_vols as string),
+ beta: args.beta,
+ weights: args.weights ? JSON.parse(args.weights as string) : undefined,
+ method: args.method,
+ }, apiKey);
+ return { success: true, data: result, message: `Calibrated SABR: α=${formatNumber(result.alpha)}, β=${formatNumber(result.beta)}, ρ=${formatNumber(result.rho)}, ν=${formatNumber(result.nu)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const sabrDensityTool: InternalTool = {
+ name: 'quantlib_volatility_sabr_density',
+ description: 'Calculate the risk-neutral probability density implied by SABR.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Forward price' },
+ expiry: { type: 'number', description: 'Time to expiry in years' },
+ alpha: { type: 'number', description: 'SABR alpha' },
+ beta: { type: 'number', description: 'SABR beta' },
+ rho: { type: 'number', description: 'SABR rho' },
+ nu: { type: 'number', description: 'SABR nu' },
+ strikes: { type: 'string', description: 'JSON array of strikes to evaluate density' },
+ },
+ required: ['forward', 'expiry', 'alpha', 'beta', 'rho', 'nu', 'strikes'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const strikes = JSON.parse(args.strikes as string);
+ const result = await quantlibApiCall('/quantlib/volatility/sabr/density', {
+ forward: args.forward,
+ expiry: args.expiry,
+ alpha: args.alpha,
+ beta: args.beta,
+ rho: args.rho,
+ nu: args.nu,
+ strikes,
+ }, apiKey);
+ return { success: true, data: result, message: `Computed SABR density at ${strikes.length} points` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const sabrDynamicsTool: InternalTool = {
+ name: 'quantlib_volatility_sabr_dynamics',
+ description: 'Analyze SABR smile dynamics (how smile changes with forward movement).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ forward: { type: 'number', description: 'Current forward price' },
+ expiry: { type: 'number', description: 'Time to expiry in years' },
+ alpha: { type: 'number', description: 'SABR alpha' },
+ beta: { type: 'number', description: 'SABR beta' },
+ rho: { type: 'number', description: 'SABR rho' },
+ nu: { type: 'number', description: 'SABR nu' },
+ strike: { type: 'number', description: 'Strike to analyze' },
+ forward_shift: { type: 'number', description: 'Optional forward shift amount (default: 1%)' },
+ },
+ required: ['forward', 'expiry', 'alpha', 'beta', 'rho', 'nu', 'strike'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/volatility/sabr/dynamics', {
+ forward: args.forward,
+ expiry: args.expiry,
+ alpha: args.alpha,
+ beta: args.beta,
+ rho: args.rho,
+ nu: args.nu,
+ strike: args.strike,
+ forward_shift: args.forward_shift,
+ }, apiKey);
+ return { success: true, data: result, message: 'Analyzed SABR smile dynamics' };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// LOCAL VOL (2 tools)
+// ══════════════════════════════════════════════════════════════════════════════
+
+const localVolConstantTool: InternalTool = {
+ name: 'quantlib_volatility_local_vol_constant',
+ description: 'Create a constant local volatility surface.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ volatility: { type: 'number', description: 'Constant local vol level' },
+ spot: { type: 'number', description: 'Spot price to query' },
+ time: { type: 'number', description: 'Time point to query' },
+ },
+ required: ['volatility', 'spot', 'time'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/volatility/local-vol/constant', {
+ volatility: args.volatility,
+ spot: args.spot,
+ time: args.time,
+ }, apiKey);
+ return { success: true, data: result, message: `Constant local vol: ${formatPercent(args.volatility as number)}` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+const impliedToLocalTool: InternalTool = {
+ name: 'quantlib_volatility_local_vol_implied_to_local',
+ description: 'Convert implied volatility to local volatility using Dupire formula.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spot: { type: 'number', description: 'Current spot price' },
+ rate: { type: 'number', description: 'Risk-free rate' },
+ strike: { type: 'number', description: 'Strike price' },
+ expiry: { type: 'number', description: 'Time to expiry in years' },
+ implied_vol: { type: 'number', description: 'Implied volatility' },
+ dk: { type: 'number', description: 'Optional strike bump for numerical derivative' },
+ dt: { type: 'number', description: 'Optional time bump for numerical derivative' },
+ },
+ required: ['spot', 'rate', 'strike', 'expiry', 'implied_vol'],
+ },
+ handler: async (args, contexts) => {
+ try {
+ const apiKey = contexts.getQuantLibApiKey?.() || null;
+ const result = await quantlibApiCall('/quantlib/volatility/local-vol/implied-to-local', {
+ spot: args.spot,
+ rate: args.rate,
+ strike: args.strike,
+ expiry: args.expiry,
+ implied_vol: args.implied_vol,
+ dk: args.dk,
+ dt: args.dt,
+ }, apiKey);
+ return { success: true, data: result, message: `Local vol: ${formatPercent(result.local_vol)} (from implied ${formatPercent(args.implied_vol as number)})` };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+ },
+};
+
+// ══════════════════════════════════════════════════════════════════════════════
+// EXPORT ALL TOOLS
+// ══════════════════════════════════════════════════════════════════════════════
+
+export const quantlibVolatilityTools: InternalTool[] = [
+ // Surface (6)
+ surfaceFlatTool,
+ surfaceTermStructureTool,
+ surfaceGridTool,
+ surfaceSmileTool,
+ surfaceTotalVarianceTool,
+ surfaceFromPointsTool,
+ // SABR (6)
+ sabrImpliedVolTool,
+ sabrNormalVolTool,
+ sabrSmileTool,
+ sabrCalibrateTool,
+ sabrDensityTool,
+ sabrDynamicsTool,
+ // Local Vol (2)
+ localVolConstantTool,
+ impliedToLocalTool,
+];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/types.ts b/fincept-terminal-desktop/src/services/mcp/internal/types.ts
index eb5800789..dcb61a5cf 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/types.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/types.ts
@@ -258,6 +258,12 @@ export interface TerminalContexts {
getAvailableCategories?: () => string[];
getAvailableRegions?: () => string[];
+ // ============================================================================
+ // QuantLib API
+ // ============================================================================
+ getQuantLibApiKey?: () => string | null;
+ setQuantLibApiKey?: (key: string | null) => void;
+
// ============================================================================
// Economics / Fincept Macro API
// ============================================================================
diff --git a/fincept-terminal-desktop/src/services/news/newsAnalysisService.ts b/fincept-terminal-desktop/src/services/news/newsAnalysisService.ts
index c83acaf20..d58ff643b 100644
--- a/fincept-terminal-desktop/src/services/news/newsAnalysisService.ts
+++ b/fincept-terminal-desktop/src/services/news/newsAnalysisService.ts
@@ -3,7 +3,7 @@
* AI-powered news article analysis via Fincept Backend API
*/
-const API_BASE_URL = 'https://finceptbackend.share.zrok.io';
+const API_BASE_URL = 'https://api.fincept.in';
const API_KEY = 'fk_user_uhwLowYhfwEg6H3WCtXK4hqG0DhZfNhK2UmtNpHuLuB';
export interface NewsAnalysisRequest {
diff --git a/fincept-terminal-desktop/src/services/news/newsEventsService.ts b/fincept-terminal-desktop/src/services/news/newsEventsService.ts
index cc18f0b6f..709df7ed2 100644
--- a/fincept-terminal-desktop/src/services/news/newsEventsService.ts
+++ b/fincept-terminal-desktop/src/services/news/newsEventsService.ts
@@ -1,4 +1,4 @@
-const API_BASE = 'https://finceptbackend.share.zrok.io';
+const API_BASE = 'https://api.fincept.in';
export interface NewsEvent {
url?: string;
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/DirectedGraph.ts b/fincept-terminal-desktop/src/services/nodeSystem/DirectedGraph.ts
index c4f60861c..7ca92ab54 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/DirectedGraph.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/DirectedGraph.ts
@@ -466,16 +466,26 @@ export class DirectedGraph {
/**
* Clone the graph
+ *
+ * Remaps connection references to point to the cloned node objects
+ * so that === comparisons work correctly within the cloned graph.
*/
clone(): DirectedGraph {
const cloned = new DirectedGraph();
+ const nodeMap = new Map<string, INode>();
for (const node of this.nodes.values()) {
- cloned.addNode({ ...node });
+ const clonedNode = { ...node };
+ cloned.addNode(clonedNode);
+ nodeMap.set(node.name, clonedNode);
}
for (const connection of this.connections.values()) {
- cloned.addConnection({ ...connection });
+ cloned.addConnection({
+ ...connection,
+ from: nodeMap.get(connection.from.name) || connection.from,
+ to: nodeMap.get(connection.to.name) || connection.to,
+ });
}
return cloned;
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/WorkflowDataProxy.ts b/fincept-terminal-desktop/src/services/nodeSystem/WorkflowDataProxy.ts
index 590b562c3..91a7a9206 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/WorkflowDataProxy.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/WorkflowDataProxy.ts
@@ -85,7 +85,10 @@ export class WorkflowDataProxy implements IWorkflowDataProxy {
}
/**
- * Get nodes connected to a specific node's input
+ * Get nodes connected to a specific node's input (parent/upstream nodes)
+ *
+ * connections[sourceName] maps source -> targets, so to find parents of nodeName
+ * we must search all connection entries for those that point TO nodeName.
*/
getParentNodes(nodeName: string, inputIndex: number = 0): Array<{
node: INode;
@@ -93,23 +96,23 @@ export class WorkflowDataProxy implements IWorkflowDataProxy {
}> {
const parents: Array<{ node: INode; outputIndex: number }> = [];
- // Get connections for this node
- const nodeConnections = this.workflow.connections[nodeName];
- if (!nodeConnections) {
- return parents;
- }
-
- // Look through all connection types
- for (const [connectionType, connections] of Object.entries(nodeConnections)) {
- if (!connections[inputIndex]) continue;
-
- for (const connection of connections[inputIndex]) {
- const parentNode = this.getNode(connection.node);
- if (parentNode) {
- parents.push({
- node: parentNode,
- outputIndex: connection.index,
- });
+ // Search all connections to find sources that connect TO nodeName
+ for (const [sourceNodeName, nodeConnections] of Object.entries(this.workflow.connections)) {
+ for (const connections of Object.values(nodeConnections)) {
+ for (let outputIndex = 0; outputIndex < connections.length; outputIndex++) {
+ const outputConnections = connections[outputIndex];
+
+ for (const connection of outputConnections) {
+ if (connection.node === nodeName && connection.index === inputIndex) {
+ const parentNode = this.getNode(sourceNodeName);
+ if (parentNode) {
+ parents.push({
+ node: parentNode,
+ outputIndex,
+ });
+ }
+ }
+ }
}
}
}
@@ -118,7 +121,10 @@ export class WorkflowDataProxy implements IWorkflowDataProxy {
}
/**
- * Get nodes connected to a specific node's output
+ * Get nodes connected to a specific node's output (child/downstream nodes)
+ *
+ * connections[sourceName] maps source -> targets, so connections[nodeName]
+ * directly gives us the children.
*/
getChildNodes(nodeName: string, outputIndex: number = 0): Array<{
node: INode;
@@ -126,23 +132,23 @@ export class WorkflowDataProxy implements IWorkflowDataProxy {
}> {
const children: Array<{ node: INode; inputIndex: number }> = [];
- // Search through all node connections
- for (const [targetNodeName, nodeConnections] of Object.entries(this.workflow.connections)) {
- for (const connections of Object.values(nodeConnections)) {
- for (let inputIndex = 0; inputIndex < connections.length; inputIndex++) {
- const inputConnections = connections[inputIndex];
-
- for (const connection of inputConnections) {
- if (connection.node === nodeName && connection.index === outputIndex) {
- const childNode = this.getNode(targetNodeName);
- if (childNode) {
- children.push({
- node: childNode,
- inputIndex,
- });
- }
- }
- }
+ // connections[nodeName] gives outgoing connections FROM nodeName
+ const nodeConnections = this.workflow.connections[nodeName];
+ if (!nodeConnections) {
+ return children;
+ }
+
+ // Look through all connection types at the specified output index
+ for (const [connectionType, connections] of Object.entries(nodeConnections)) {
+ if (!connections[outputIndex]) continue;
+
+ for (const connection of connections[outputIndex]) {
+ const childNode = this.getNode(connection.node);
+ if (childNode) {
+ children.push({
+ node: childNode,
+ inputIndex: connection.index,
+ });
}
}
}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/WorkflowExecutor.ts b/fincept-terminal-desktop/src/services/nodeSystem/WorkflowExecutor.ts
index d68ca003e..dcbf3c295 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/WorkflowExecutor.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/WorkflowExecutor.ts
@@ -114,10 +114,13 @@ export class WorkflowExecutor {
startNode: startNodeName,
} as IWorkflowExecuteStartEvent);
- // Detect cycles
+ // Detect cycles — abort if found
const cycleCheck = handleCycles(this.graph);
if (cycleCheck.hasCycles) {
- console.warn('[WorkflowExecutor] Detected cycles in workflow:', cycleCheck.cycleNodes);
+ const cycleNodeNames = cycleCheck.cycleNodes?.join(', ') || 'unknown';
+ throw new Error(
+ `Workflow contains cycles involving nodes: ${cycleNodeNames}. Remove circular connections to proceed.`
+ );
}
// Merge existing run data with new execution
@@ -175,6 +178,8 @@ export class WorkflowExecutor {
// Execute nodes in order
const executedNodes = new Set<string>();
+ const maxRequeue = nodesToExecute.length * 2;
+ let requeueCount = 0;
while (executionState.nodeExecutionStack.length > 0) {
const executeData = executionState.nodeExecutionStack.shift()!;
@@ -206,6 +211,7 @@ export class WorkflowExecutor {
];
executedNodes.add(executeData.node.name);
+ requeueCount = 0;
// Add downstream nodes
await this.addDownstreamNodesOptimized(
@@ -224,11 +230,20 @@ export class WorkflowExecutor {
);
if (!allParentsExecuted) {
+ requeueCount++;
+ if (requeueCount > maxRequeue) {
+ throw new Error(
+ `Execution deadlock: nodes have unsatisfiable dependencies. ` +
+ `Remaining nodes: ${executionState.nodeExecutionStack.map(e => e.node.name).join(', ')}`
+ );
+ }
// Re-add to end of stack and continue
executionState.nodeExecutionStack.push(executeData);
continue;
}
+ requeueCount = 0;
+
// Execute node
console.log(`[WorkflowExecutor] Executing node: ${executeData.node.name}`);
diff --git a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx b/fincept-terminal-desktop/src/services/payment/paymentApi.tsx
index ab3d956ec..6d09aee30 100644
--- a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx
+++ b/fincept-terminal-desktop/src/services/payment/paymentApi.tsx
@@ -5,7 +5,7 @@ import { fetch } from '@tauri-apps/plugin-http';
// API Configuration
const PAYMENT_API_CONFIG = {
- BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',
+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',
CONNECTION_TIMEOUT: 10000,
REQUEST_TIMEOUT: 30000
};
diff --git a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx.backup b/fincept-terminal-desktop/src/services/payment/paymentApi.tsx.backup
index 6778ac937..17f8f6e79 100644
--- a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx.backup
+++ b/fincept-terminal-desktop/src/services/payment/paymentApi.tsx.backup
@@ -5,7 +5,7 @@ import { fetch } from '@tauri-apps/plugin-http';
// API Configuration
const PAYMENT_API_CONFIG = {
- BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',
+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',
CONNECTION_TIMEOUT: 10000,
REQUEST_TIMEOUT: 30000
};
diff --git a/fincept-terminal-desktop/src/services/polymarket/polymarketService.ts b/fincept-terminal-desktop/src/services/polymarket/polymarketService.ts
index 4f5e9984b..d1f095378 100644
--- a/fincept-terminal-desktop/src/services/polymarket/polymarketService.ts
+++ b/fincept-terminal-desktop/src/services/polymarket/polymarketService.ts
@@ -30,6 +30,42 @@ export interface PolymarketMarket {
spread?: number;
volumeNum?: number;
liquidityNum?: number;
+ // Gamma API nests the parent event(s) — used for constructing the correct URL
+ events?: Array<{ id?: string; slug: string; title?: string }>;
+ groupItemTitle?: string;
+ // Volume variants
+ volume24hr?: number;
+ volume1wk?: number;
+ volume1mo?: number;
+ // Price change (raw decimal, multiply ×100 for %)
+ oneDayPriceChange?: number;
+ oneWeekPriceChange?: number;
+ oneMonthPriceChange?: number;
+ oneHourPriceChange?: number;
+ // Live pricing from Gamma/CLOB
+ lastTradePrice?: number;
+ bestBid?: number;
+ bestAsk?: number;
+ // Status flags
+ featured?: boolean;
+ new?: boolean;
+ acceptingOrders?: boolean;
+ negRiskOther?: boolean;
+ // Resolution metadata
+ resolutionSource?: string;
+ umaResolutionStatus?: string;
+ resolvedBy?: string;
+ // Fees & order config
+ makerBaseFee?: number;
+ takerBaseFee?: number;
+ orderMinSize?: number;
+ orderPriceMinTickSize?: number;
+ // Rankings/discovery
+ competitive?: number;
+ score?: number;
+ curationOrder?: number;
+ // Sports
+ gameStartTime?: string;
}
export interface PolymarketEvent {
diff --git a/fincept-terminal-desktop/src/services/polymarket/polymarketServiceEnhanced.ts b/fincept-terminal-desktop/src/services/polymarket/polymarketServiceEnhanced.ts
index 6d3db7bd1..c958d5799 100644
--- a/fincept-terminal-desktop/src/services/polymarket/polymarketServiceEnhanced.ts
+++ b/fincept-terminal-desktop/src/services/polymarket/polymarketServiceEnhanced.ts
@@ -6,7 +6,6 @@ const CLOB_API_BASE = 'https://clob.polymarket.com';
const DATA_API_BASE = 'https://data-api.polymarket.com';
const WS_MARKET_BASE = 'wss://ws-subscriptions-clob.polymarket.com/ws/market';
const WS_USER_BASE = 'wss://ws-subscriptions-clob.polymarket.com/ws/user';
-const WS_REALTIME_BASE = 'wss://ws-live-data.polymarket.com';
// ==================== TYPE DEFINITIONS ====================
@@ -35,6 +34,42 @@ export interface PolymarketMarket {
spread?: number;
volumeNum?: number;
liquidityNum?: number;
+ // Gamma API nests the parent event(s) — used for constructing the correct URL
+ events?: Array<{ id?: string; slug: string; title?: string }>;
+ groupItemTitle?: string;
+ // Volume variants
+ volume24hr?: number;
+ volume1wk?: number;
+ volume1mo?: number;
+ // Price change (raw decimal, multiply ×100 for %)
+ oneDayPriceChange?: number;
+ oneWeekPriceChange?: number;
+ oneMonthPriceChange?: number;
+ oneHourPriceChange?: number;
+ // Live pricing from Gamma/CLOB
+ lastTradePrice?: number;
+ bestBid?: number;
+ bestAsk?: number;
+ // Status flags
+ featured?: boolean;
+ new?: boolean;
+ acceptingOrders?: boolean;
+ negRiskOther?: boolean;
+ // Resolution metadata
+ resolutionSource?: string;
+ umaResolutionStatus?: string;
+ resolvedBy?: string;
+ // Fees & order config
+ makerBaseFee?: number;
+ takerBaseFee?: number;
+ orderMinSize?: number;
+ orderPriceMinTickSize?: number;
+ // Rankings/discovery
+ competitive?: number;
+ score?: number;
+ curationOrder?: number;
+ // Sports
+ gameStartTime?: string;
}
export interface PolymarketEvent {
@@ -64,10 +99,15 @@ export interface PolymarketTag {
}
export interface PolymarketSport {
- id: string;
- label: string;
- slug: string;
- tagId: string;
+ id: number;
+ sport: string;
+ image?: string;
+ resolution?: string;
+ ordering?: string;
+ /** Comma-separated tag IDs associated with this sport */
+ tags?: string;
+ series?: string;
+ createdAt?: string;
}
export interface PolymarketTrade {
@@ -93,6 +133,38 @@ export interface PolymarketOrderBook {
hash?: string;
}
+// Enriched order book from GET /book?token_id= (includes extra fields vs /orderbook/:id)
+export interface PolymarketOrderBookEnriched extends PolymarketOrderBook {
+ min_order_size?: string;
+ tick_size?: string;
+ last_trade_price?: string;
+ neg_risk?: boolean;
+}
+
+// Top holders from Data API GET /holders?market={conditionId}
+export interface PolymarketHolder {
+ proxyWallet: string;
+ pseudonym?: string;
+ name?: string;
+ amount: number;
+ profileImage?: string;
+ profileImageOptimized?: string;
+ outcomeIndex: number;
+ asset?: string;
+ displayUsernamePublic?: boolean;
+}
+
+export interface PolymarketTopHolders {
+ token: string;
+ holders: PolymarketHolder[];
+}
+
+// Open interest from Data API GET /openInterest?market={conditionId}
+export interface PolymarketOpenInterest {
+ market: string;
+ value: number;
+}
+
export interface PolymarketProfile {
wallet_address: string;
username?: string;
@@ -152,8 +224,8 @@ export interface UserTradeHistory {
// Pricing Types
export interface PricePoint {
- price: string;
- timestamp: number;
+ price: number; // normalized 0–1 float
+ timestamp: number; // unix seconds
}
export interface HistoricalPrice {
@@ -215,12 +287,38 @@ export interface CreateOrderResponse {
}
// WebSocket Types
+// Event types available with custom_feature_enabled=true:
+// best_bid_ask, new_market, market_resolved
+// Standard event types (always available):
+// book, price_change, tick_size_change, last_trade_price
+// Actual wire format from Polymarket WebSocket (verified against live data):
+// Fields are FLAT on the message object, not nested under "data".
+// The discriminant field is "event_type", not "type".
export interface WSMarketUpdate {
- type: 'book' | 'price_change' | 'tick_size_change' | 'last_trade_price';
+ event_type: 'book' | 'price_change' | 'tick_size_change' | 'last_trade_price' | 'best_bid_ask' | 'new_market' | 'market_resolved';
market: string;
asset_id?: string;
- data: any;
- timestamp: number;
+ timestamp: number | string;
+ hash?: string;
+ // book event
+ bids?: Array<{ price: string; size: string }>;
+ asks?: Array<{ price: string; size: string }>;
+ tick_size?: string;
+ last_trade_price?: string;
+ // price_change event
+ price?: string;
+ side?: 'BUY' | 'SELL';
+ size?: string;
+ // best_bid_ask event
+ best_bid?: string;
+ best_ask?: string;
+ spread?: string;
+ // new_market / market_resolved
+ question?: string;
+ outcomes?: string[];
+ winner?: string;
+ // keep data for any undocumented fields
+ data?: any;
}
export interface WSUserUpdate {
@@ -261,10 +359,13 @@ export interface EventQueryParams {
export interface PriceHistoryParams {
token_id: string;
- interval?: '1m' | '1w' | '1d' | '6h' | '1h' | 'max';
+ /** Time window. Valid values: 'max' | 'all' | '1m' | '1w' | '1d' | '6h' | '1h'. Default: '1d' */
+ interval?: string;
+ /** Start timestamp in milliseconds (omit to use interval) */
startTs?: number;
+ /** End timestamp in milliseconds (omit to use interval) */
endTs?: number;
- limit?: number;
+ /** Resolution accuracy in MINUTES (e.g. 1 = 1-minute resolution). Default: 1 */
fidelity?: number;
}
@@ -273,6 +374,7 @@ export interface APICredentials {
apiKey: string;
apiSecret: string;
apiPassphrase: string;
+ walletAddress?: string;
}
// ==================== SERVICE CLASS ====================
@@ -283,7 +385,6 @@ class PolymarketServiceEnhanced {
private dataApiBase: string;
private wsMarketBase: string;
private wsUserBase: string;
- private wsRealtimeBase: string;
private credentials?: APICredentials;
private wsConnections: Map<string, WebSocket>;
@@ -293,7 +394,6 @@ class PolymarketServiceEnhanced {
this.dataApiBase = DATA_API_BASE;
this.wsMarketBase = WS_MARKET_BASE;
this.wsUserBase = WS_USER_BASE;
- this.wsRealtimeBase = WS_REALTIME_BASE;
this.wsConnections = new Map();
}
@@ -307,19 +407,39 @@ class PolymarketServiceEnhanced {
this.credentials = undefined;
}
- private generateAuthHeaders(timestamp: number, method: string, path: string, body?: string): HeadersInit {
+ private async generateAuthHeaders(timestamp: number, method: string, path: string, body?: string): Promise<HeadersInit> {
if (!this.credentials) {
throw new Error('API credentials not set');
}
- // HMAC-SHA256 signature generation would go here
- // For now, return basic headers
+ // Build the message to sign: timestamp + method + path + body
+ const message = timestamp.toString() + method.toUpperCase() + path + (body ?? '');
+
+ // HMAC-SHA256 signature using Web Crypto API
+ const encoder = new TextEncoder();
+ const keyData = encoder.encode(this.credentials.apiSecret);
+ const msgData = encoder.encode(message);
+
+ const cryptoKey = await crypto.subtle.importKey(
+ 'raw',
+ keyData,
+ { name: 'HMAC', hash: 'SHA-256' },
+ false,
+ ['sign']
+ );
+
+ const signatureBuffer = await crypto.subtle.sign('HMAC', cryptoKey, msgData);
+ const signatureBytes = new Uint8Array(signatureBuffer);
+ // Base64 encode the signature
+ const signature = btoa(String.fromCharCode(...signatureBytes));
+
return {
'Content-Type': 'application/json',
- 'POLY-API-KEY': this.credentials.apiKey,
- 'POLY-TIMESTAMP': timestamp.toString(),
- 'POLY-PASSPHRASE': this.credentials.apiPassphrase,
- // 'POLY-SIGNATURE': signature // Would compute actual signature
+ 'POLY_ADDRESS': this.credentials.walletAddress ?? '',
+ 'POLY_API_KEY': this.credentials.apiKey,
+ 'POLY_PASSPHRASE': this.credentials.apiPassphrase,
+ 'POLY_SIGNATURE': signature,
+ 'POLY_TIMESTAMP': timestamp.toString(),
};
}
@@ -451,7 +571,8 @@ class PolymarketServiceEnhanced {
async getOrderBook(tokenId: string): Promise<PolymarketOrderBook> {
try {
- const url = `${this.clobApiBase}/book?token_id=${tokenId}`;
+ // Official endpoint: GET /orderbook/:tokenId (path parameter, not query string)
+ const url = `${this.clobApiBase}/orderbook/${tokenId}`;
const response = await fetch(url);
if (!response.ok) throw new Error(`CLOB API error: ${response.status}`);
return await response.json();
@@ -520,14 +641,13 @@ class PolymarketServiceEnhanced {
async getPriceHistory(params: PriceHistoryParams): Promise<HistoricalPrice> {
try {
const queryParams = new URLSearchParams();
- // API uses 'market' parameter, not 'token_id'
+ // API requires: market = numeric tokenId (NOT conditionId — conditionId returns empty)
queryParams.append('market', params.token_id);
- queryParams.append('interval', params.interval || 'max');
-
- // Add fidelity parameter (resolution in minutes)
- if (params.fidelity) {
- queryParams.append('fidelity', params.fidelity.toString());
- }
+ // 'interval' is MANDATORY — omitting it returns an API error
+ // Valid values: 'max' | 'all' | '1m' | '1w' | '1d' | '6h' | '1h'
+ queryParams.append('interval', params.interval ?? '1d');
+ // fidelity = resolution accuracy in MINUTES (default 1 = 1-minute resolution)
+ queryParams.append('fidelity', (params.fidelity ?? 1).toString());
const url = `${this.clobApiBase}/prices-history?${queryParams.toString()}`;
console.log('Price history URL:', url);
@@ -543,18 +663,22 @@ class PolymarketServiceEnhanced {
console.log('Price history response:', data);
console.log('First history item:', data.history?.[0]);
- // API returns {history: [...]} - map to PricePoint format
- const prices = (data.history || []).map((item: any) => ({
- price: item.p || item.price || '0', // 'p' is the price field
- timestamp: item.t || item.timestamp || 0 // 't' is the timestamp field
- }));
-
- console.log('Mapped prices:', prices.slice(0, 3));
+ // API returns { history: [{ p: number, t: number }, ...] }
+ // p = price (0–1 float), t = unix timestamp in seconds
+ const raw: any[] = data.history || data.prices || [];
+ const prices = raw
+ .map((item: any) => {
+ const p = parseFloat(item.p ?? item.price ?? '0');
+ const t = Number(item.t ?? item.timestamp ?? 0);
+ return { price: p, timestamp: t };
+ })
+ .filter(pt => !isNaN(pt.price) && pt.timestamp > 0)
+ .sort((a, b) => a.timestamp - b.timestamp); // ensure chronological order
return {
token_id: params.token_id,
prices,
- interval: params.interval || 'max'
+ interval: params.interval ?? '1d',
};
} catch (error) {
console.error('Error fetching price history:', error);
@@ -608,7 +732,9 @@ class PolymarketServiceEnhanced {
const url = `${this.clobApiBase}/data/trades${queryParams.toString() ? '?' + queryParams.toString() : ''}`;
const response = await fetch(url);
if (!response.ok) throw new Error(`CLOB API error: ${response.status}`);
- return await response.json();
+ const json = await response.json();
+ // CLOB API returns paginated: { data: PolymarketTrade[], count, limit, offset }
+ return Array.isArray(json) ? json : (json.data ?? []);
} catch (error) {
console.error('Error fetching trades:', error);
throw error;
@@ -653,6 +779,67 @@ class PolymarketServiceEnhanced {
}
}
+ // ==================== DATA API - Market Data ====================
+
+ async getTopHolders(conditionId: string, limit: number = 20): Promise<PolymarketTopHolders> {
+ try {
+ const url = `${this.dataApiBase}/holders?market=${encodeURIComponent(conditionId)}&limit=${limit}`;
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`Data API error: ${response.status}`);
+ const data = await response.json();
+ // API returns array of MetaHolder objects: [{token, holders:[...]}, ...]
+ if (Array.isArray(data)) {
+ // Flatten all holders across token entries
+ const allHolders: PolymarketHolder[] = data.flatMap((entry: any) =>
+ (entry.holders ?? []).map((h: any) => ({
+ ...h,
+ outcomeIndex: h.outcomeIndex ?? (entry.token === data[0]?.token ? 0 : 1),
+ }))
+ );
+ return { token: data[0]?.token ?? '', holders: allHolders };
+ }
+ return data as PolymarketTopHolders;
+ } catch (error) {
+ console.error('Error fetching top holders:', error);
+ throw error;
+ }
+ }
+
+ async getOpenInterest(conditionIds: string[]): Promise<PolymarketOpenInterest[]> {
+ try {
+ const marketParam = conditionIds.map(encodeURIComponent).join(',');
+ const url = `${this.dataApiBase}/openInterest?market=${marketParam}`;
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`Data API error: ${response.status}`);
+ const data = await response.json();
+ return Array.isArray(data) ? data : [data];
+ } catch (error) {
+ console.error('Error fetching open interest:', error);
+ throw error;
+ }
+ }
+
+ async getOrderBookEnriched(tokenId: string): Promise<PolymarketOrderBookEnriched> {
+ try {
+ // Use /book?token_id= which returns extra fields: min_order_size, tick_size, last_trade_price, neg_risk
+ const url = `${this.clobApiBase}/book?token_id=${tokenId}`;
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`CLOB API error: ${response.status}`);
+ const data = await response.json();
+ // Ensure bids sorted desc by price, asks sorted asc
+ if (data.bids) {
+ data.bids = data.bids.sort((a: any, b: any) => parseFloat(b.price) - parseFloat(a.price));
+ }
+ if (data.asks) {
+ data.asks = data.asks.sort((a: any, b: any) => parseFloat(a.price) - parseFloat(b.price));
+ }
+ return data as PolymarketOrderBookEnriched;
+ } catch (error) {
+ console.error('Error fetching enriched order book:', error);
+ throw error;
+ }
+ }
+
// ==================== ORDER MANAGEMENT (L2) ====================
// Note: These require authentication and proper signature generation
@@ -662,9 +849,10 @@ class PolymarketServiceEnhanced {
}
try {
- const timestamp = Date.now();
+ const timestamp = Math.floor(Date.now() / 1000);
const url = `${this.clobApiBase}/order`;
- const headers = this.generateAuthHeaders(timestamp, 'POST', '/order', JSON.stringify(orderRequest));
+ const body = JSON.stringify(orderRequest);
+ const headers = await this.generateAuthHeaders(timestamp, 'POST', '/order', body);
const response = await fetch(url, {
method: 'POST',
@@ -686,10 +874,10 @@ class PolymarketServiceEnhanced {
}
try {
- const timestamp = Date.now();
+ const timestamp = Math.floor(Date.now() / 1000);
const path = userAddress ? `/orders?user=${userAddress}` : '/orders';
const url = `${this.clobApiBase}${path}`;
- const headers = this.generateAuthHeaders(timestamp, 'GET', path);
+ const headers = await this.generateAuthHeaders(timestamp, 'GET', path);
const response = await fetch(url, { headers });
if (!response.ok) throw new Error(`CLOB API error: ${response.status}`);
@@ -706,10 +894,10 @@ class PolymarketServiceEnhanced {
}
try {
- const timestamp = Date.now();
+ const timestamp = Math.floor(Date.now() / 1000);
const path = `/order/${orderId}`;
const url = `${this.clobApiBase}${path}`;
- const headers = this.generateAuthHeaders(timestamp, 'DELETE', path);
+ const headers = await this.generateAuthHeaders(timestamp, 'DELETE', path);
const response = await fetch(url, {
method: 'DELETE',
@@ -730,14 +918,17 @@ class PolymarketServiceEnhanced {
}
try {
- const timestamp = Date.now();
- const path = marketId ? `/orders?market=${marketId}` : '/orders';
+ const timestamp = Math.floor(Date.now() / 1000);
+ // Official endpoint: DELETE /cancel-all (optionally with body { market })
+ const path = '/cancel-all';
+ const body = marketId ? JSON.stringify({ market: marketId }) : undefined;
const url = `${this.clobApiBase}${path}`;
- const headers = this.generateAuthHeaders(timestamp, 'DELETE', path);
+ const headers = await this.generateAuthHeaders(timestamp, 'DELETE', path, body);
const response = await fetch(url, {
method: 'DELETE',
- headers
+ headers,
+ ...(body ? { body } : {}),
});
if (!response.ok) throw new Error(`CLOB API error: ${response.status}`);
@@ -751,6 +942,7 @@ class PolymarketServiceEnhanced {
// ==================== WEBSOCKET CONNECTIONS ====================
connectMarketWebSocket(
+ assetIds: string[],
onMessage: (update: WSMarketUpdate) => void,
onError?: (error: Event) => void
): WebSocket {
@@ -758,12 +950,34 @@ class PolymarketServiceEnhanced {
ws.onopen = () => {
console.log('Market WebSocket connected');
+ // Official subscribe format: type="market", assets_ids=[...tokenIds], initial_dump=true
+ // custom_feature_enabled=true enables extra event types: best_bid_ask, new_market, market_resolved
+ ws.send(JSON.stringify({
+ type: 'market',
+ assets_ids: assetIds,
+ initial_dump: true,
+ custom_feature_enabled: true,
+ }));
+ // Keepalive: docs require PING every 10 seconds (server closes after ~10s silence)
+ const pingInterval = setInterval(() => {
+ if (ws.readyState === WebSocket.OPEN) {
+ ws.send('PING');
+ } else {
+ clearInterval(pingInterval);
+ }
+ }, 10_000);
+ (ws as any)._pingInterval = pingInterval;
};
ws.onmessage = (event) => {
try {
+ if (event.data === 'PONG') return;
const data = JSON.parse(event.data);
- onMessage(data);
+ // Polymarket sends messages as arrays of event objects
+ const messages: WSMarketUpdate[] = Array.isArray(data) ? data : [data];
+ for (const msg of messages) {
+ onMessage(msg);
+ }
} catch (error) {
console.error('Error parsing WebSocket message:', error);
}
@@ -776,6 +990,7 @@ class PolymarketServiceEnhanced {
ws.onclose = () => {
console.log('Market WebSocket disconnected');
+ if ((ws as any)._pingInterval) clearInterval((ws as any)._pingInterval);
};
this.wsConnections.set('market', ws);
@@ -783,6 +998,7 @@ class PolymarketServiceEnhanced {
}
connectUserWebSocket(
+ conditionIds: string[],
onMessage: (update: WSUserUpdate) => void,
onError?: (error: Event) => void
): WebSocket {
@@ -791,20 +1007,41 @@ class PolymarketServiceEnhanced {
}
const ws = new WebSocket(this.wsUserBase);
+ const creds = this.credentials;
ws.onopen = () => {
console.log('User WebSocket connected');
- // Send authentication message
+ // Official auth format: auth object + type="user" + markets=[conditionIds]
ws.send(JSON.stringify({
- type: 'auth',
- apiKey: this.credentials!.apiKey
+ auth: {
+ apiKey: creds.apiKey,
+ secret: creds.apiSecret,
+ passphrase: creds.apiPassphrase,
+ },
+ type: 'user',
+ markets: conditionIds,
+ initial_dump: true,
}));
+ // Keepalive PING every 10 seconds (docs requirement)
+ const pingInterval = setInterval(() => {
+ if (ws.readyState === WebSocket.OPEN) {
+ ws.send('PING');
+ } else {
+ clearInterval(pingInterval);
+ }
+ }, 10_000);
+ (ws as any)._pingInterval = pingInterval;
};
ws.onmessage = (event) => {
try {
+ if (event.data === 'PONG') return;
const data = JSON.parse(event.data);
- onMessage(data);
+ // Polymarket sends messages as arrays of event objects
+ const messages: WSUserUpdate[] = Array.isArray(data) ? data : [data];
+ for (const msg of messages) {
+ onMessage(msg);
+ }
} catch (error) {
console.error('Error parsing WebSocket message:', error);
}
@@ -817,30 +1054,28 @@ class PolymarketServiceEnhanced {
ws.onclose = () => {
console.log('User WebSocket disconnected');
+ if ((ws as any)._pingInterval) clearInterval((ws as any)._pingInterval);
};
this.wsConnections.set('user', ws);
return ws;
}
- subscribeToMarket(marketId: string) {
+ subscribeToMarket(assetIds: string[]) {
const ws = this.wsConnections.get('market');
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
- type: 'subscribe',
- market: marketId
+ type: 'market',
+ assets_ids: assetIds,
+ initial_dump: false,
}));
}
}
- unsubscribeFromMarket(marketId: string) {
- const ws = this.wsConnections.get('market');
- if (ws && ws.readyState === WebSocket.OPEN) {
- ws.send(JSON.stringify({
- type: 'unsubscribe',
- market: marketId
- }));
- }
+ unsubscribeFromMarket(_assetIds: string[]) {
+ // Polymarket WS does not have an explicit unsubscribe message;
+ // close and reconnect with a different assets_ids list if needed.
+ console.warn('[Polymarket WS] To unsubscribe, reconnect with updated assets_ids list.');
}
disconnectWebSocket(type: 'market' | 'user' | 'all' = 'all') {
diff --git a/fincept-terminal-desktop/src/services/quantstatsService.ts b/fincept-terminal-desktop/src/services/quantstatsService.ts
index 636f4e3e3..45a0122ac 100644
--- a/fincept-terminal-desktop/src/services/quantstatsService.ts
+++ b/fincept-terminal-desktop/src/services/quantstatsService.ts
@@ -187,7 +187,8 @@ async function runQuantStats<T>(
action: string,
benchmark: string = 'SPY',
period: string = '1y',
- riskFreeRate: number = 0.02
+ riskFreeRate: number = 0.02,
+ numSims: number = 1000
): Promise<T> {
let result: string;
try {
@@ -197,6 +198,7 @@ async function runQuantStats<T>(
benchmark,
period,
riskFreeRate,
+ numSims,
});
} catch (e) {
// Rust command returned Err - extract useful message
@@ -238,11 +240,11 @@ export const quantstatsService = {
getRolling: (tickers: Record<string, number>, benchmark?: string, period?: string, rf?: number) =>
runQuantStats<RollingAnalysis>(tickers, 'rolling', benchmark, period, rf),
- getFullReport: (tickers: Record<string, number>, benchmark?: string, period?: string, rf?: number) =>
- runQuantStats<FullReport>(tickers, 'full_report', benchmark, period, rf),
+ getFullReport: (tickers: Record<string, number>, benchmark?: string, period?: string, rf?: number, numSims?: number) =>
+ runQuantStats<FullReport>(tickers, 'full_report', benchmark, period, rf, numSims),
- getMonteCarlo: (tickers: Record<string, number>, benchmark?: string, period?: string) =>
- runQuantStats<MonteCarloAnalysis>(tickers, 'montecarlo', benchmark, period),
+ getMonteCarlo: (tickers: Record<string, number>, benchmark?: string, period?: string, numSims?: number) =>
+ runQuantStats<MonteCarloAnalysis>(tickers, 'montecarlo', benchmark, period, undefined, numSims),
getHtmlReport: (tickers: Record<string, number>, benchmark?: string, period?: string) =>
runQuantStats<{ html_base64: string }>(tickers, 'html_report', benchmark, period),
diff --git a/fincept-terminal-desktop/src/services/support/supportApi.ts b/fincept-terminal-desktop/src/services/support/supportApi.ts
index 81a04be48..87d601b48 100644
--- a/fincept-terminal-desktop/src/services/support/supportApi.ts
+++ b/fincept-terminal-desktop/src/services/support/supportApi.ts
@@ -1,6 +1,6 @@
// Support API Service - Feedback, Contact, Newsletter endpoints
-const API_BASE_URL = 'https://finceptbackend.share.zrok.io';
+const API_BASE_URL = 'https://api.fincept.in';
// Types
export interface ContactFormData {
diff --git a/fincept-terminal-desktop/src/services/trading/agnoTradingService.ts b/fincept-terminal-desktop/src/services/trading/agnoTradingService.ts
index 4cc5457ab..851997cc9 100644
--- a/fincept-terminal-desktop/src/services/trading/agnoTradingService.ts
+++ b/fincept-terminal-desktop/src/services/trading/agnoTradingService.ts
@@ -295,35 +295,7 @@ class AgnoTradingService {
* Returns a map of API keys in the format: { OPENAI_API_KEY: "sk-...", ... }
*/
private async getApiKeysMap(): Promise<Record<string, string>> {
- try {
- const configs = await sqliteService.getLLMConfigs();
-
- // Build API keys map
- const apiKeys: Record<string, string> = {};
- configs.forEach(config => {
- if (config.api_key) {
- const provider = config.provider.toLowerCase();
-
- // Map provider name to standard env var format
- // Handle aliases: gemini -> google
- let standardProvider = provider;
- if (provider === 'gemini') {
- standardProvider = 'google';
- // Also add GEMINI_API_KEY for backward compatibility
- apiKeys['GEMINI_API_KEY'] = config.api_key;
- }
-
- // Format: OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_API_KEY, etc.
- const keyName = `${standardProvider.toUpperCase()}_API_KEY`;
- apiKeys[keyName] = config.api_key;
- }
- });
-
- return apiKeys;
- } catch (error) {
- console.warn('Failed to load API keys:', error);
- return {};
- }
+ return sqliteService.buildApiKeysMap();
}
/**
diff --git a/fincept-terminal-desktop/src/services/trading/alphaArenaService.ts b/fincept-terminal-desktop/src/services/trading/alphaArenaService.ts
index a894cf819..c270a2787 100644
--- a/fincept-terminal-desktop/src/services/trading/alphaArenaService.ts
+++ b/fincept-terminal-desktop/src/services/trading/alphaArenaService.ts
@@ -99,46 +99,7 @@ export const alphaArenaService = {
* Get API keys map for all configured providers
*/
async getApiKeysMap(): Promise<Record<string, string>> {
- try {
- const apiKeys = await sqliteService.getAllApiKeys();
- const llmConfigs = await sqliteService.getLLMConfigs();
- const modelConfigs = await sqliteService.getLLMModelConfigs();
-
- const result: Record<string, string> = {};
-
- // From predefined API keys
- if (apiKeys['OPENAI_API_KEY']) {
- result['OPENAI_API_KEY'] = apiKeys['OPENAI_API_KEY'];
- }
- if (apiKeys['ANTHROPIC_API_KEY']) {
- result['ANTHROPIC_API_KEY'] = apiKeys['ANTHROPIC_API_KEY'];
- }
-
- // From legacy LLM configs
- for (const config of llmConfigs) {
- if (config.api_key) {
- const keyName = `${config.provider.toUpperCase()}_API_KEY`;
- if (!result[keyName]) {
- result[keyName] = config.api_key;
- }
- }
- }
-
- // From new model configs
- for (const config of modelConfigs) {
- if (config.api_key) {
- const keyName = `${config.provider.toUpperCase()}_API_KEY`;
- if (!result[keyName]) {
- result[keyName] = config.api_key;
- }
- }
- }
-
- return result;
- } catch (error) {
- console.error('[Service] getApiKeysMap error:', error);
- return {};
- }
+ return sqliteService.buildApiKeysMap();
},
/**
diff --git a/fincept-terminal-desktop/src/services/trading/tradeService.ts b/fincept-terminal-desktop/src/services/trading/tradeService.ts
index 560f9d57f..2b08748c4 100644
--- a/fincept-terminal-desktop/src/services/trading/tradeService.ts
+++ b/fincept-terminal-desktop/src/services/trading/tradeService.ts
@@ -4,7 +4,7 @@
// import { loggerService } from './loggerService';
import { getSetting } from '../core/sqliteService';
-const API_BASE = 'https://finceptbackend.share.zrok.io';
+const API_BASE = 'https://api.fincept.in';
export interface TradePartner {
partner_id: string;
diff --git a/fincept-terminal-desktop/src/services/trading/websocketBridge.ts b/fincept-terminal-desktop/src/services/trading/websocketBridge.ts
index a62a02be1..c6c2c16de 100644
--- a/fincept-terminal-desktop/src/services/trading/websocketBridge.ts
+++ b/fincept-terminal-desktop/src/services/trading/websocketBridge.ts
@@ -4,6 +4,20 @@
import { invoke } from '@tauri-apps/api/core';
import { listen, UnlistenFn } from '@tauri-apps/api/event';
+const INVOKE_TIMEOUT_MS = 15000;
+
+function withTimeout<T>(promise: Promise<T>, ms: number = INVOKE_TIMEOUT_MS, label?: string): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ reject(new Error(`[WebSocketBridge] ${label || 'invoke'} timed out after ${ms}ms`));
+ }, ms);
+ promise.then(
+ (val) => { clearTimeout(timer); resolve(val); },
+ (err) => { clearTimeout(timer); reject(err); }
+ );
+ });
+}
+
// ============================================================================
// TYPES (matching Rust types)
// ============================================================================
@@ -34,6 +48,7 @@ export interface TickerData {
close?: number;
change?: number;
change_percent?: number;
+ quote_volume?: number;
timestamp: number;
}
@@ -106,7 +121,7 @@ export class WebSocketBridge {
// ========================================================================
async setConfig(config: ProviderConfig): Promise<void> {
- await invoke('ws_set_config', { config });
+ await withTimeout(invoke('ws_set_config', { config }), INVOKE_TIMEOUT_MS, 'setConfig');
}
// ========================================================================
@@ -114,15 +129,15 @@ export class WebSocketBridge {
// ========================================================================
async connect(provider: string): Promise<void> {
- await invoke('ws_connect', { provider });
+ await withTimeout(invoke('ws_connect', { provider }), INVOKE_TIMEOUT_MS, 'connect');
}
async disconnect(provider: string): Promise<void> {
- await invoke('ws_disconnect', { provider });
+ await withTimeout(invoke('ws_disconnect', { provider }), INVOKE_TIMEOUT_MS, 'disconnect');
}
async reconnect(provider: string): Promise<void> {
- await invoke('ws_reconnect', { provider });
+ await withTimeout(invoke('ws_reconnect', { provider }), INVOKE_TIMEOUT_MS, 'reconnect');
}
// ========================================================================
@@ -135,16 +150,17 @@ export class WebSocketBridge {
channel: string,
params?: Record<string, any>
): Promise<void> {
- await invoke('ws_subscribe', {
+ console.log(`[WebSocketBridge] subscribe: provider='${provider}' symbol='${symbol}' channel='${channel}'`);
+ await withTimeout(invoke('ws_subscribe', {
provider,
symbol,
channel,
params: params ? params : null,
- });
+ }), INVOKE_TIMEOUT_MS, 'subscribe');
}
async unsubscribe(provider: string, symbol: string, channel: string): Promise<void> {
- await invoke('ws_unsubscribe', { provider, symbol, channel });
+ await withTimeout(invoke('ws_unsubscribe', { provider, symbol, channel }), INVOKE_TIMEOUT_MS, 'unsubscribe');
}
// ========================================================================
@@ -203,11 +219,11 @@ export class WebSocketBridge {
// ========================================================================
async getMetrics(provider: string): Promise<ConnectionMetrics | null> {
- return await invoke('ws_get_metrics', { provider });
+ return await withTimeout(invoke('ws_get_metrics', { provider }), INVOKE_TIMEOUT_MS, 'getMetrics');
}
async getAllMetrics(): Promise<ConnectionMetrics[]> {
- return await invoke('ws_get_all_metrics');
+ return await withTimeout(invoke('ws_get_all_metrics'), INVOKE_TIMEOUT_MS, 'getAllMetrics');
}
// ========================================================================
diff --git a/fincept-terminal-desktop/src/services/visionQuantService.ts b/fincept-terminal-desktop/src/services/visionQuantService.ts
new file mode 100644
index 000000000..08a9c95f0
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/visionQuantService.ts
@@ -0,0 +1,332 @@
+/**
+ * VisionQuant Pattern Intelligence Service
+ * Frontend service layer for AI K-line pattern recognition.
+ * Calls Rust commands via Tauri invoke.
+ */
+import { invoke } from '@tauri-apps/api/core';
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+export interface PatternMatch {
+ symbol: string;
+ date: string;
+ score: number;
+ dtw_sim: number | null;
+ correlation: number | null;
+ feature_sim: number;
+ visual_sim: number;
+ trend_match: number | null;
+ path: string | null;
+ tb_label?: number;
+ tb_hit_day?: number;
+ tb_hit_type?: string;
+ final_return_pct?: number;
+}
+
+export interface WinRateStats {
+ total: number;
+ bullish: number;
+ neutral: number;
+ bearish: number;
+ win_rate: number;
+ win_loss_ratio: number;
+ avg_return_pct: number;
+ avg_holding_days: number;
+}
+
+export interface SearchResult {
+ matches: PatternMatch[];
+ query_info: {
+ symbol: string;
+ date: string;
+ bars: number;
+ };
+ win_rate_stats: WinRateStats;
+}
+
+export interface VisionScore {
+ score: number;
+ max: number;
+ win_rate: number;
+ label: string;
+}
+
+export interface FundamentalScore {
+ score: number;
+ max: number;
+ pe: number | null;
+ roe: number | null;
+ pe_score: number;
+ roe_score: number;
+ label: string;
+ error?: string;
+}
+
+export interface TechnicalScore {
+ score: number;
+ max: number;
+ ma60_signal: number | null;
+ rsi: number | null;
+ rsi_score: number;
+ macd_hist: number | null;
+ macd_score: number;
+ label: string;
+ error?: string;
+}
+
+export interface Scorecard {
+ total_score: number;
+ max_score: number;
+ action: 'BUY' | 'WAIT' | 'SELL';
+ vision: VisionScore;
+ fundamental: FundamentalScore;
+ technical: TechnicalScore;
+ symbol: string;
+ date: string;
+}
+
+export interface Trade {
+ entry_date: string;
+ exit_date: string;
+ entry_price: number;
+ exit_price: number;
+ shares: number;
+ profit: number;
+ return_pct: number;
+ hold_days: number;
+ exit_reason: string;
+}
+
+export interface EquityPoint {
+ date: string;
+ equity: number;
+}
+
+export interface BacktestResult {
+ symbol: string;
+ start_date: string;
+ end_date: string;
+ initial_capital: number;
+ final_equity: number;
+ return_pct: number;
+ buy_hold_return_pct: number;
+ sharpe_ratio: number;
+ max_drawdown_pct: number;
+ total_trades: number;
+ win_rate: number;
+ wins: number;
+ losses: number;
+ avg_profit: number;
+ avg_loss: number;
+ avg_hold_days: number;
+ trades: Trade[];
+ equity_curve: EquityPoint[];
+}
+
+export interface IndexStatus {
+ index_ready: boolean;
+ model_exists: boolean;
+ index_exists: boolean;
+ meta_exists: boolean;
+ n_records: number;
+ model_loaded?: boolean;
+ data_dir: string;
+}
+
+// ---------------------------------------------------------------------------
+// Config interfaces — advanced settings passed through to Python
+// ---------------------------------------------------------------------------
+
+export interface SearchConfig {
+ isolation_days?: number;
+ dtw_window?: number;
+ w_dtw?: number;
+ w_corr?: number;
+ w_shape?: number;
+ w_visual?: number;
+ trend_bonus?: number;
+ faiss_multiplier?: number;
+ hq_dtw_threshold?: number;
+ tb_upper?: number;
+ tb_lower?: number;
+ tb_max_hold?: number;
+}
+
+export interface ScoringConfig {
+ vision_breakpoints?: number[];
+ pe_thresholds?: number[];
+ roe_thresholds?: number[];
+ ma_period?: number;
+ rsi_ranges?: number[];
+ macd_fast?: number;
+ macd_slow?: number;
+ macd_signal?: number;
+ ma_thresholds?: number[];
+ buy_threshold?: number;
+ wait_threshold?: number;
+}
+
+export interface BacktestConfig {
+ stop_loss?: number;
+ take_profit?: number;
+ max_hold?: number;
+ entry_rsi?: number;
+ exit_rsi?: number;
+ ma_period?: number;
+ macd_fast?: number;
+ macd_slow?: number;
+ macd_signal?: number;
+}
+
+export interface SetupConfig {
+ batch_size?: number;
+ chart_style?: 'international' | 'chinese';
+ learning_rate?: number;
+}
+
+// ---------------------------------------------------------------------------
+// Response parsing helper
+// ---------------------------------------------------------------------------
+
+interface PythonResponse<T> {
+ status: string;
+ data?: T;
+ error?: string;
+}
+
+function parseResponse<T>(raw: string): T {
+ // Python scripts may output progress lines before final JSON
+ // Find the last valid JSON line
+ const lines = raw.trim().split('\n');
+ let lastJson = '';
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const line = lines[i].trim();
+ if (line.startsWith('{')) {
+ lastJson = line;
+ break;
+ }
+ }
+
+ if (!lastJson) {
+ throw new Error('No JSON response received from backend');
+ }
+
+ const parsed: PythonResponse<T> = JSON.parse(lastJson);
+
+ if (parsed.status === 'error') {
+ throw new Error(parsed.error || 'Unknown backend error');
+ }
+
+ if (parsed.data === undefined) {
+ throw new Error('Response missing data field');
+ }
+
+ return parsed.data;
+}
+
+// ---------------------------------------------------------------------------
+// Helper: strip undefined values from config before serializing
+// ---------------------------------------------------------------------------
+
+function serializeConfig(config?: Record<string, unknown>): string | null {
+ if (!config) return null;
+ const cleaned: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(config)) {
+ if (v !== undefined) cleaned[k] = v;
+ }
+ return Object.keys(cleaned).length > 0 ? JSON.stringify(cleaned) : null;
+}
+
+// ---------------------------------------------------------------------------
+// Service API
+// ---------------------------------------------------------------------------
+
+export const visionQuantService = {
+ /**
+ * Search for similar K-line patterns.
+ */
+ async searchPatterns(
+ symbol: string,
+ date?: string,
+ topK: number = 10,
+ lookback: number = 60,
+ config?: SearchConfig,
+ ): Promise<SearchResult> {
+ const raw = await invoke<string>('vision_quant_search_patterns', {
+ symbol,
+ date: date || null,
+ topK,
+ lookback,
+ config: serializeConfig(config as Record<string, unknown>),
+ });
+ return parseResponse<SearchResult>(raw);
+ },
+
+ /**
+ * Get multi-factor scorecard (Vision + Fundamental + Technical).
+ */
+ async getScore(
+ symbol: string,
+ winRate: number,
+ date?: string,
+ config?: ScoringConfig,
+ ): Promise<Scorecard> {
+ const raw = await invoke<string>('vision_quant_score', {
+ symbol,
+ winRate,
+ date: date || null,
+ config: serializeConfig(config as Record<string, unknown>),
+ });
+ return parseResponse<Scorecard>(raw);
+ },
+
+ /**
+ * Run adaptive strategy backtest.
+ */
+ async runBacktest(
+ symbol: string,
+ startDate: string,
+ endDate: string,
+ initialCapital: number = 100000,
+ config?: BacktestConfig,
+ ): Promise<BacktestResult> {
+ const raw = await invoke<string>('vision_quant_backtest', {
+ symbol,
+ startDate,
+ endDate,
+ initialCapital,
+ config: serializeConfig(config as Record<string, unknown>),
+ });
+ return parseResponse<BacktestResult>(raw);
+ },
+
+ /**
+ * Build FAISS index (first-run setup).
+ */
+ async setupIndex(
+ symbols?: string[],
+ startDate?: string,
+ stride?: number,
+ epochs?: number,
+ config?: SetupConfig,
+ ): Promise<Record<string, unknown>> {
+ const raw = await invoke<string>('vision_quant_setup_index', {
+ symbols: symbols || null,
+ startDate: startDate || null,
+ stride: stride || null,
+ epochs: epochs || null,
+ config: serializeConfig(config as Record<string, unknown>),
+ });
+ return parseResponse<Record<string, unknown>>(raw);
+ },
+
+ /**
+ * Check VisionQuant index/model status.
+ */
+ async getStatus(): Promise<IndexStatus> {
+ const raw = await invoke<string>('vision_quant_status', {});
+ return parseResponse<IndexStatus>(raw);
+ },
+};
diff --git a/fincept-terminal-desktop/vite.config.ts b/fincept-terminal-desktop/vite.config.ts
index 4a17a96f8..442229d77 100644
--- a/fincept-terminal-desktop/vite.config.ts
+++ b/fincept-terminal-desktop/vite.config.ts
@@ -232,7 +232,7 @@ export default defineConfig({
strictPort: true,
proxy: {
'/api': {
- target: 'https://finceptbackend.share.zrok.io',
+ target: 'https://api.fincept.in',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
configure: (proxy, options) => {