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.

tab updates

tilakpatel229b475e178fd3
diff --git a/fincept-terminal-desktop/src/App.tsx b/fincept-terminal-desktop/src/App.tsx
index 15d64e091..27727ce16 100644
--- a/fincept-terminal-desktop/src/App.tsx
+++ b/fincept-terminal-desktop/src/App.tsx
@@ -4,6 +4,7 @@
import React, { useState, useEffect } from 'react';
import { useAuth } from './contexts/AuthContext';
import { NavigationProvider } from './contexts/NavigationContext';
+import { ThemeProvider } from './contexts/ThemeContext';
import { setPaymentWindowManager } from './services/paymentApi';
// Import screens
@@ -200,9 +201,11 @@ const App: React.FC = () => {
if (session?.authenticated && currentScreen === 'dashboard') {
return (
<>
- <NavigationProvider onNavigate={setCurrentScreen} onSetActiveTab={setActiveTab}>
- <DashboardScreen />
- </NavigationProvider>
+ <ThemeProvider>
+ <NavigationProvider onNavigate={setCurrentScreen} onSetActiveTab={setActiveTab}>
+ <DashboardScreen />
+ </NavigationProvider>
+ </ThemeProvider>
{/* In-App Payment Window Overlay */}
<PaymentOverlay paymentWindow={paymentWindow} />
</>
diff --git a/fincept-terminal-desktop/src/components/charts/CandlestickChart.tsx b/fincept-terminal-desktop/src/components/charts/CandlestickChart.tsx
new file mode 100644
index 000000000..05974f7a1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/charts/CandlestickChart.tsx
@@ -0,0 +1,255 @@
+import React, { useEffect, useRef } from 'react';
+
+export interface CandlestickDataPoint {
+ timestamp: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume?: number;
+}
+
+interface CandlestickChartProps {
+ data: CandlestickDataPoint[];
+ width?: number;
+ height?: number;
+ bullishColor?: string;
+ bearishColor?: string;
+ backgroundColor?: string;
+ gridColor?: string;
+ textColor?: string;
+ showGrid?: boolean;
+ showVolume?: boolean;
+ showLabels?: boolean;
+}
+
+const CandlestickChart: React.FC<CandlestickChartProps> = ({
+ data,
+ width = 400,
+ height = 250,
+ bullishColor = '#00ff88',
+ bearishColor = '#ff4444',
+ backgroundColor = '#0a0a0a',
+ gridColor = '#222222',
+ textColor = '#888888',
+ showGrid = true,
+ showVolume = true,
+ showLabels = true,
+}) => {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+
+ useEffect(() => {
+ if (!canvasRef.current || data.length === 0) return;
+
+ const canvas = canvasRef.current;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return;
+
+ // Set canvas size
+ canvas.width = width;
+ canvas.height = height;
+
+ // Clear canvas
+ ctx.fillStyle = backgroundColor;
+ ctx.fillRect(0, 0, width, height);
+
+ // Calculate data range
+ const highs = data.map(d => d.high);
+ const lows = data.map(d => d.low);
+ const maxPrice = Math.max(...highs);
+ const minPrice = Math.min(...lows);
+ const priceRange = maxPrice - minPrice || 1;
+
+ // Padding
+ const padding = { top: 20, right: 50, bottom: showVolume ? 70 : 30, left: 10 };
+ const chartHeight = showVolume ? height * 0.7 : height - padding.top - padding.bottom;
+ const chartWidth = width - padding.left - padding.right;
+ const volumeHeight = showVolume ? height * 0.2 : 0;
+
+ // Calculate candle width
+ const candleWidth = Math.max(2, Math.floor(chartWidth / data.length) - 2);
+ const candleSpacing = Math.floor(chartWidth / data.length);
+
+ // Draw grid
+ if (showGrid) {
+ ctx.strokeStyle = gridColor;
+ ctx.lineWidth = 1;
+
+ // Horizontal grid lines
+ const gridLines = 5;
+ for (let i = 0; i <= gridLines; i++) {
+ const y = padding.top + (chartHeight / gridLines) * i;
+ ctx.beginPath();
+ ctx.moveTo(padding.left, y);
+ ctx.lineTo(width - padding.right, y);
+ ctx.stroke();
+ }
+
+ // Vertical grid lines
+ const verticalLines = Math.min(5, data.length);
+ for (let i = 0; i <= verticalLines; i++) {
+ const x = padding.left + (chartWidth / verticalLines) * i;
+ ctx.beginPath();
+ ctx.moveTo(x, padding.top);
+ ctx.lineTo(x, padding.top + chartHeight);
+ ctx.stroke();
+ }
+ }
+
+ // Draw price labels on right side
+ if (showLabels) {
+ ctx.fillStyle = textColor;
+ ctx.font = '9px Consolas, monospace';
+ ctx.textAlign = 'left';
+
+ const labelCount = 5;
+ for (let i = 0; i <= labelCount; i++) {
+ const price = minPrice + (priceRange / labelCount) * (labelCount - i);
+ const y = padding.top + (chartHeight / labelCount) * i;
+ ctx.fillText(price.toFixed(2), width - padding.right + 5, y + 3);
+ }
+ }
+
+ // Find max volume for scaling
+ const maxVolume = showVolume && data.some(d => d.volume)
+ ? Math.max(...data.map(d => d.volume || 0))
+ : 1;
+
+ // Draw candlesticks
+ data.forEach((candle, index) => {
+ const x = padding.left + index * candleSpacing + candleSpacing / 2;
+
+ // Determine if bullish or bearish
+ const isBullish = candle.close >= candle.open;
+ const color = isBullish ? bullishColor : bearishColor;
+
+ // Calculate y positions
+ const highY = padding.top + ((maxPrice - candle.high) / priceRange) * chartHeight;
+ const lowY = padding.top + ((maxPrice - candle.low) / priceRange) * chartHeight;
+ const openY = padding.top + ((maxPrice - candle.open) / priceRange) * chartHeight;
+ const closeY = padding.top + ((maxPrice - candle.close) / priceRange) * chartHeight;
+
+ // Draw wick (high-low line)
+ ctx.strokeStyle = color;
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ ctx.moveTo(x, highY);
+ ctx.lineTo(x, lowY);
+ ctx.stroke();
+
+ // Draw body (open-close rectangle)
+ const bodyTop = Math.min(openY, closeY);
+ const bodyHeight = Math.abs(closeY - openY) || 1; // Ensure at least 1px for doji
+
+ ctx.fillStyle = color;
+ ctx.fillRect(x - candleWidth / 2, bodyTop, candleWidth, bodyHeight);
+
+ // Draw volume bars if enabled
+ if (showVolume && candle.volume) {
+ const volumeY = padding.top + chartHeight + 10;
+ const volumeBarHeight = (candle.volume / maxVolume) * volumeHeight;
+
+ ctx.fillStyle = isBullish
+ ? `${bullishColor}66` // Semi-transparent
+ : `${bearishColor}66`;
+ ctx.fillRect(
+ x - candleWidth / 2,
+ volumeY + volumeHeight - volumeBarHeight,
+ candleWidth,
+ volumeBarHeight
+ );
+ }
+ });
+
+ // Draw date labels
+ if (showLabels) {
+ ctx.fillStyle = textColor;
+ ctx.font = '9px Consolas, monospace';
+ ctx.textAlign = 'center';
+
+ const labelIndices = [0, Math.floor(data.length / 2), data.length - 1];
+ labelIndices.forEach(idx => {
+ if (idx < data.length) {
+ const x = padding.left + idx * candleSpacing + candleSpacing / 2;
+ const date = new Date(data[idx].timestamp * 1000);
+ const dateStr = `${date.getMonth() + 1}/${date.getDate()}`;
+ const y = showVolume
+ ? padding.top + chartHeight + volumeHeight + 20
+ : height - 10;
+ ctx.fillText(dateStr, x, y);
+ }
+ });
+
+ // Volume label
+ if (showVolume) {
+ ctx.textAlign = 'left';
+ ctx.fillText('VOL', padding.left, padding.top + chartHeight + 25);
+ }
+ }
+
+ // Draw current price indicator (last candle)
+ if (data.length > 0) {
+ const lastCandle = data[data.length - 1];
+ const lastPrice = lastCandle.close;
+ const lastY = padding.top + ((maxPrice - lastPrice) / priceRange) * chartHeight;
+ const isBullish = lastCandle.close >= lastCandle.open;
+ const indicatorColor = isBullish ? bullishColor : bearishColor;
+
+ // Draw horizontal dashed line
+ ctx.strokeStyle = indicatorColor;
+ ctx.lineWidth = 1;
+ ctx.setLineDash([5, 5]);
+ ctx.beginPath();
+ ctx.moveTo(padding.left, lastY);
+ ctx.lineTo(width - padding.right, lastY);
+ ctx.stroke();
+ ctx.setLineDash([]);
+
+ // Draw price box
+ ctx.fillStyle = indicatorColor;
+ const priceText = lastPrice.toFixed(2);
+ const textWidth = ctx.measureText(priceText).width;
+ ctx.fillRect(width - padding.right + 2, lastY - 8, textWidth + 6, 16);
+ ctx.fillStyle = backgroundColor;
+ ctx.font = 'bold 10px Consolas, monospace';
+ ctx.textAlign = 'left';
+ ctx.fillText(priceText, width - padding.right + 5, lastY + 3);
+
+ // Draw percentage change
+ const firstCandle = data[0];
+ const priceChange = lastPrice - firstCandle.open;
+ const percentChange = (priceChange / firstCandle.open) * 100;
+ const changeText = `${percentChange >= 0 ? '+' : ''}${percentChange.toFixed(2)}%`;
+
+ ctx.fillStyle = indicatorColor;
+ ctx.font = 'bold 11px Consolas, monospace';
+ ctx.textAlign = 'left';
+ ctx.fillText(changeText, padding.left + 5, padding.top + 15);
+ }
+
+ }, [data, width, height, bullishColor, bearishColor, backgroundColor, gridColor, textColor, showGrid, showVolume, showLabels]);
+
+ if (data.length === 0) {
+ return (
+ <div
+ style={{
+ width: `${width}px`,
+ height: `${height}px`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor,
+ color: textColor,
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ }}
+ >
+ No chart data available
+ </div>
+ );
+ }
+
+ return <canvas ref={canvasRef} style={{ display: 'block' }} />;
+};
+
+export default CandlestickChart;
diff --git a/fincept-terminal-desktop/src/components/charts/SimpleLineChart.tsx b/fincept-terminal-desktop/src/components/charts/SimpleLineChart.tsx
new file mode 100644
index 000000000..3779007f3
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/charts/SimpleLineChart.tsx
@@ -0,0 +1,207 @@
+import React, { useEffect, useRef } from 'react';
+
+export interface ChartDataPoint {
+ timestamp: number;
+ value: number;
+ label?: string;
+}
+
+interface SimpleLineChartProps {
+ data: ChartDataPoint[];
+ width?: number;
+ height?: number;
+ color?: string;
+ backgroundColor?: string;
+ gridColor?: string;
+ textColor?: string;
+ lineWidth?: number;
+ showGrid?: boolean;
+ showLabels?: boolean;
+}
+
+const SimpleLineChart: React.FC<SimpleLineChartProps> = ({
+ data,
+ width = 400,
+ height = 200,
+ color = '#00ff88',
+ backgroundColor = '#0a0a0a',
+ gridColor = '#222222',
+ textColor = '#888888',
+ lineWidth = 2,
+ showGrid = true,
+ showLabels = true,
+}) => {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+
+ useEffect(() => {
+ if (!canvasRef.current || data.length === 0) return;
+
+ const canvas = canvasRef.current;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return;
+
+ // Set canvas size
+ canvas.width = width;
+ canvas.height = height;
+
+ // Clear canvas
+ ctx.fillStyle = backgroundColor;
+ ctx.fillRect(0, 0, width, height);
+
+ // Calculate data range
+ const values = data.map(d => d.value);
+ const maxValue = Math.max(...values);
+ const minValue = Math.min(...values);
+ const valueRange = maxValue - minValue || 1;
+
+ // Padding
+ const padding = { top: 20, right: 40, bottom: 30, left: 10 };
+ const chartWidth = width - padding.left - padding.right;
+ const chartHeight = height - padding.top - padding.bottom;
+
+ // Draw grid
+ if (showGrid) {
+ ctx.strokeStyle = gridColor;
+ ctx.lineWidth = 1;
+
+ // Horizontal grid lines
+ const gridLines = 5;
+ for (let i = 0; i <= gridLines; i++) {
+ const y = padding.top + (chartHeight / gridLines) * i;
+ ctx.beginPath();
+ ctx.moveTo(padding.left, y);
+ ctx.lineTo(width - padding.right, y);
+ ctx.stroke();
+ }
+
+ // Vertical grid lines
+ const verticalLines = 4;
+ for (let i = 0; i <= verticalLines; i++) {
+ const x = padding.left + (chartWidth / verticalLines) * i;
+ ctx.beginPath();
+ ctx.moveTo(x, padding.top);
+ ctx.lineTo(x, height - padding.bottom);
+ ctx.stroke();
+ }
+ }
+
+ // Draw price labels
+ if (showLabels) {
+ ctx.fillStyle = textColor;
+ ctx.font = '9px Consolas, monospace';
+ ctx.textAlign = 'left';
+
+ const labelCount = 5;
+ for (let i = 0; i <= labelCount; i++) {
+ const value = minValue + (valueRange / labelCount) * (labelCount - i);
+ const y = padding.top + (chartHeight / labelCount) * i;
+ ctx.fillText(value.toFixed(2), width - padding.right + 5, y + 3);
+ }
+
+ // Draw date labels
+ ctx.textAlign = 'center';
+ const dateLabels = [0, Math.floor(data.length / 2), data.length - 1];
+ dateLabels.forEach(idx => {
+ if (idx < data.length) {
+ const x = padding.left + (chartWidth / (data.length - 1)) * idx;
+ const date = new Date(data[idx].timestamp * 1000);
+ const dateStr = `${date.getMonth() + 1}/${date.getDate()}`;
+ ctx.fillText(dateStr, x, height - padding.bottom + 15);
+ }
+ });
+ }
+
+ // Draw line
+ ctx.strokeStyle = color;
+ ctx.lineWidth = lineWidth;
+ ctx.beginPath();
+
+ data.forEach((point, index) => {
+ const x = padding.left + (chartWidth / (data.length - 1)) * index;
+ const normalizedValue = (point.value - minValue) / valueRange;
+ const y = height - padding.bottom - (normalizedValue * chartHeight);
+
+ if (index === 0) {
+ ctx.moveTo(x, y);
+ } else {
+ ctx.lineTo(x, y);
+ }
+ });
+
+ ctx.stroke();
+
+ // Draw glow effect
+ ctx.shadowColor = color;
+ ctx.shadowBlur = 8;
+ ctx.stroke();
+ ctx.shadowBlur = 0;
+
+ // Draw points
+ data.forEach((point, index) => {
+ const x = padding.left + (chartWidth / (data.length - 1)) * index;
+ const normalizedValue = (point.value - minValue) / valueRange;
+ const y = height - padding.bottom - (normalizedValue * chartHeight);
+
+ // Only draw points at start, end, and every 10th point for clarity
+ if (index === 0 || index === data.length - 1 || index % 10 === 0) {
+ ctx.fillStyle = color;
+ ctx.beginPath();
+ ctx.arc(x, y, 2, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ });
+
+ // Draw current price indicator
+ if (data.length > 0) {
+ const lastPoint = data[data.length - 1];
+ const lastX = padding.left + chartWidth;
+ const normalizedValue = (lastPoint.value - minValue) / valueRange;
+ const lastY = height - padding.bottom - (normalizedValue * chartHeight);
+
+ // Draw horizontal line
+ ctx.strokeStyle = color;
+ ctx.lineWidth = 1;
+ ctx.setLineDash([5, 5]);
+ ctx.beginPath();
+ ctx.moveTo(padding.left, lastY);
+ ctx.lineTo(width - padding.right, lastY);
+ ctx.stroke();
+ ctx.setLineDash([]);
+
+ // Draw price box
+ ctx.fillStyle = color;
+ const priceText = lastPoint.value.toFixed(2);
+ const textWidth = ctx.measureText(priceText).width;
+ ctx.fillRect(width - padding.right + 2, lastY - 8, textWidth + 6, 16);
+ ctx.fillStyle = backgroundColor;
+ ctx.font = 'bold 10px Consolas, monospace';
+ ctx.textAlign = 'left';
+ ctx.fillText(priceText, width - padding.right + 5, lastY + 3);
+ }
+
+ }, [data, width, height, color, backgroundColor, gridColor, textColor, lineWidth, showGrid, showLabels]);
+
+ if (data.length === 0) {
+ return (
+ <div
+ style={{
+ width: `${width}px`,
+ height: `${height}px`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor,
+ color: textColor,
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ }}
+ >
+ No chart data available
+ </div>
+ );
+ }
+
+ return <canvas ref={canvasRef} style={{ display: 'block' }} />;
+};
+
+export default SimpleLineChart;
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 23cc09d0c..244901339 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -34,6 +34,7 @@ import MCPTab from '@/components/tabs/mcp';
import FyersTab from '@/components/tabs/fyers';
import SupportTicketTab from '@/components/tabs/SupportTicketTab';
import PolygonEqTab from '@/components/tabs/PolygonEqTab';
+import KrakenTab from '@/components/tabs/KrakenTab';
// Dropdown Menu Component
const DropdownMenu = ({ label, items, onItemClick }: { label: string; items: any[]; onItemClick: (item: any) => void }) => {
@@ -673,6 +674,12 @@ export default function FinxeptTerminal() {
>
Maritime
</TabsTrigger>
+ <TabsTrigger
+ value="kraken"
+ style={activeTab === 'kraken' ? tabStyles.active : tabStyles.default}
+ >
+ Kraken
+ </TabsTrigger>
<TabsTrigger
value="settings"
style={activeTab === 'settings' ? tabStyles.active : tabStyles.default}
@@ -841,6 +848,9 @@ export default function FinxeptTerminal() {
<TabsContent value="maritime" className="h-full m-0 p-0">
<MaritimeTab />
</TabsContent>
+ <TabsContent value="kraken" className="h-full m-0 p-0">
+ <KrakenTab />
+ </TabsContent>
<TabsContent value="settings" className="h-full m-0 p-0">
<SettingsTab />
</TabsContent>
diff --git a/fincept-terminal-desktop/src/components/tabs/AnalyticsTab.tsx b/fincept-terminal-desktop/src/components/tabs/AnalyticsTab.tsx
index 65b99840e..b7dfbb6a5 100644
--- a/fincept-terminal-desktop/src/components/tabs/AnalyticsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/AnalyticsTab.tsx
@@ -1,24 +1,13 @@
import React, { useState, useEffect } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, AreaChart, Area, ScatterChart, Scatter, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, ComposedChart, ReferenceLine, Treemap, FunnelChart, Funnel, LabelList } from 'recharts';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
const AnalyticsTab: React.FC = () => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
const [dataUpdateCount, setDataUpdateCount] = useState(0);
const [alertCount, setAlertCount] = useState(23);
- // Bloomberg color scheme (exact from DearPyGUI)
- const BLOOMBERG_ORANGE = '#FFA500';
- const BLOOMBERG_WHITE = '#FFFFFF';
- const BLOOMBERG_RED = '#FF0000';
- const BLOOMBERG_GREEN = '#00C800';
- const BLOOMBERG_YELLOW = '#FFFF00';
- const BLOOMBERG_GRAY = '#787878';
- const BLOOMBERG_BLUE = '#6496FA';
- const BLOOMBERG_PURPLE = '#C864FF';
- const BLOOMBERG_CYAN = '#00FFFF';
- const BLOOMBERG_DARK_BG = '#000000';
- const BLOOMBERG_PANEL_BG = '#0a0a0a';
-
useEffect(() => {
const timer = setInterval(() => {
setCurrentTime(new Date());
@@ -203,20 +192,20 @@ const AnalyticsTab: React.FC = () => {
height?: string
}) => (
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px',
height,
width,
overflow: 'hidden'
}}>
<div style={{
- color: BLOOMBERG_ORANGE,
+ color: colors.primary,
fontSize: '10px',
fontWeight: 'bold',
marginBottom: '2px',
textAlign: 'center',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ borderBottom: `1px solid ${colors.textMuted}`,
paddingBottom: '2px'
}}>
{title}
@@ -230,8 +219,8 @@ const AnalyticsTab: React.FC = () => {
return (
<div style={{
height: '100%',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
+ backgroundColor: colors.background,
+ color: colors.text,
fontFamily: 'Consolas, monospace',
overflow: 'hidden',
display: 'flex',
@@ -240,46 +229,46 @@ const AnalyticsTab: React.FC = () => {
}}>
{/* Header */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
padding: '4px 8px',
flexShrink: 0
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px' }}>
- <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>FINANCIAL ANALYTICS DASHBOARD</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GREEN, fontWeight: 'bold' }}>PORTFOLIO VALUE: $2.45M</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_BLUE }}>P&L TODAY: +$12,456 (+0.51%)</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_YELLOW }}>ALERTS: {alertCount}</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GREEN }}>● LIVE DATA</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_WHITE }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>FINANCIAL ANALYTICS DASHBOARD</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.secondary, fontWeight: 'bold' }}>PORTFOLIO VALUE: $2.45M</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.info }}>P&L TODAY: +$12,456 (+0.51%)</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.warning }}>ALERTS: {alertCount}</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.secondary }}>● LIVE DATA</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.text }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>ANALYTICS:</span>
- <span style={{ color: BLOOMBERG_GREEN }}>RISK●</span>
- <span style={{ color: BLOOMBERG_GREEN }}>PERFORMANCE●</span>
- <span style={{ color: BLOOMBERG_GREEN }}>ATTRIBUTION●</span>
- <span style={{ color: BLOOMBERG_GREEN }}>TECHNICAL●</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GRAY }}>MODELS:</span>
- <span style={{ color: BLOOMBERG_BLUE }}>VaR: $45K</span>
- <span style={{ color: BLOOMBERG_YELLOW }}>Sharpe: 1.84</span>
- <span style={{ color: BLOOMBERG_PURPLE }}>Beta: 0.97</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GRAY }}>UPDATES:</span>
- <span style={{ color: BLOOMBERG_CYAN }}>{dataUpdateCount}</span>
+ <span style={{ color: colors.textMuted }}>ANALYTICS:</span>
+ <span style={{ color: colors.secondary }}>RISK●</span>
+ <span style={{ color: colors.secondary }}>PERFORMANCE●</span>
+ <span style={{ color: colors.secondary }}>ATTRIBUTION●</span>
+ <span style={{ color: colors.secondary }}>TECHNICAL●</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>MODELS:</span>
+ <span style={{ color: colors.info }}>VaR: $45K</span>
+ <span style={{ color: colors.warning }}>Sharpe: 1.84</span>
+ <span style={{ color: colors.purple }}>Beta: 0.97</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>UPDATES:</span>
+ <span style={{ color: colors.accent }}>{dataUpdateCount}</span>
</div>
</div>
{/* Function Keys Bar */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
padding: '2px 4px',
flexShrink: 0
}}>
@@ -297,9 +286,9 @@ const AnalyticsTab: React.FC = () => {
{ key: "F10", label: "ALERT", status: "●" }
].map(item => (
<button key={item.key} style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: BLOOMBERG_WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.text,
padding: '2px 4px',
fontSize: '9px',
height: '16px',
@@ -307,11 +296,11 @@ const AnalyticsTab: React.FC = () => {
alignItems: 'center',
justifyContent: 'center'
}}>
- <span style={{ color: BLOOMBERG_YELLOW }}>{item.key}:</span>
+ <span style={{ color: colors.warning }}>{item.key}:</span>
<span style={{ marginLeft: '2px' }}>{item.label}</span>
<span style={{
marginLeft: '2px',
- color: item.status === '●' ? BLOOMBERG_GREEN : BLOOMBERG_YELLOW
+ color: item.status === '●' ? colors.secondary : colors.warning
}}>
{item.status}
</span>
@@ -333,12 +322,12 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="PRICE & VOLUME">
<ResponsiveContainer width="100%" height="100%">
<ComposedChart data={priceData.slice(0, 15)}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="time" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Line type="monotone" dataKey="price" stroke={BLOOMBERG_BLUE} strokeWidth={1} dot={false} />
- <Bar dataKey="volume" fill={BLOOMBERG_GRAY} opacity={0.3} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="time" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Line type="monotone" dataKey="price" stroke={colors.info} strokeWidth={1} dot={false} />
+ <Bar dataKey="volume" fill={colors.textMuted} opacity={0.3} />
</ComposedChart>
</ResponsiveContainer>
</ChartBox>
@@ -353,13 +342,13 @@ const AnalyticsTab: React.FC = () => {
cx="50%"
cy="50%"
outerRadius={50}
- fill={BLOOMBERG_BLUE}
+ fill={colors.info}
>
{sectorData.map((entry, index) => (
- <Cell key={`cell-${index}`} fill={[BLOOMBERG_BLUE, BLOOMBERG_GREEN, BLOOMBERG_YELLOW, BLOOMBERG_RED, BLOOMBERG_PURPLE, BLOOMBERG_CYAN][index % 6]} />
+ <Cell key={`cell-${index}`} fill={[colors.info, colors.secondary, colors.warning, colors.alert, colors.purple, colors.accent][index % 6]} />
))}
</Pie>
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
</PieChart>
</ResponsiveContainer>
</ChartBox>
@@ -367,11 +356,11 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="CORRELATION SCATTER">
<ResponsiveContainer width="100%" height="100%">
<ScatterChart data={correlationData}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Scatter dataKey="y" fill={BLOOMBERG_GREEN} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Scatter dataKey="y" fill={colors.secondary} />
</ScatterChart>
</ResponsiveContainer>
</ChartBox>
@@ -379,11 +368,11 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="PORTFOLIO COMPOSITION">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={portfolioData}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="asset" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Bar dataKey="allocation" fill={BLOOMBERG_ORANGE} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="asset" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Bar dataKey="allocation" fill={colors.primary} />
</BarChart>
</ResponsiveContainer>
</ChartBox>
@@ -391,12 +380,12 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="RISK METRICS">
<ResponsiveContainer width="100%" height="100%">
<LineChart data={riskMetrics.slice(0, 20)}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="day" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Line type="monotone" dataKey="var" stroke={BLOOMBERG_RED} strokeWidth={1} dot={false} />
- <Line type="monotone" dataKey="sharpe" stroke={BLOOMBERG_GREEN} strokeWidth={1} dot={false} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="day" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Line type="monotone" dataKey="var" stroke={colors.alert} strokeWidth={1} dot={false} />
+ <Line type="monotone" dataKey="sharpe" stroke={colors.secondary} strokeWidth={1} dot={false} />
</LineChart>
</ResponsiveContainer>
</ChartBox>
@@ -405,11 +394,11 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="MOMENTUM ANALYSIS">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={momentumData.slice(0, 10)}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="stock" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Bar dataKey="momentum" fill={BLOOMBERG_GREEN} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="stock" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Bar dataKey="momentum" fill={colors.secondary} />
</BarChart>
</ResponsiveContainer>
</ChartBox>
@@ -417,11 +406,11 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="INTRADAY LIQUIDITY">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={liquidityData}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="hour" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Area type="monotone" dataKey="volume" stroke={BLOOMBERG_CYAN} fill={BLOOMBERG_CYAN} fillOpacity={0.3} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="hour" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Area type="monotone" dataKey="volume" stroke={colors.accent} fill={colors.accent} fillOpacity={0.3} />
</AreaChart>
</ResponsiveContainer>
</ChartBox>
@@ -429,13 +418,13 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="TECHNICAL INDICATORS">
<ResponsiveContainer width="100%" height="100%">
<LineChart data={technicalData}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="period" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Line type="monotone" dataKey="price" stroke={BLOOMBERG_WHITE} strokeWidth={2} dot={false} />
- <Line type="monotone" dataKey="sma20" stroke={BLOOMBERG_YELLOW} strokeWidth={1} dot={false} />
- <Line type="monotone" dataKey="ema12" stroke={BLOOMBERG_GREEN} strokeWidth={1} dot={false} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="period" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Line type="monotone" dataKey="price" stroke={colors.text} strokeWidth={2} dot={false} />
+ <Line type="monotone" dataKey="sma20" stroke={colors.warning} strokeWidth={1} dot={false} />
+ <Line type="monotone" dataKey="ema12" stroke={colors.secondary} strokeWidth={1} dot={false} />
</LineChart>
</ResponsiveContainer>
</ChartBox>
@@ -443,12 +432,12 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="FUNDAMENTAL RATIOS">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={fundamentalData} layout="horizontal">
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis type="number" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis type="category" dataKey="metric" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Bar dataKey="value" fill={BLOOMBERG_BLUE} />
- <Bar dataKey="benchmark" fill={BLOOMBERG_GRAY} opacity={0.5} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis type="number" stroke={colors.text} fontSize={8} />
+ <YAxis type="category" dataKey="metric" stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Bar dataKey="value" fill={colors.info} />
+ <Bar dataKey="benchmark" fill={colors.textMuted} opacity={0.5} />
</BarChart>
</ResponsiveContainer>
</ChartBox>
@@ -456,13 +445,13 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="OPTIONS FLOW">
<ResponsiveContainer width="100%" height="100%">
<ComposedChart data={optionsData}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="strike" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Bar dataKey="calls" fill={BLOOMBERG_GREEN} />
- <Bar dataKey="puts" fill={BLOOMBERG_RED} />
- <Line type="monotone" dataKey="iv" stroke={BLOOMBERG_YELLOW} strokeWidth={1} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="strike" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Bar dataKey="calls" fill={colors.secondary} />
+ <Bar dataKey="puts" fill={colors.alert} />
+ <Line type="monotone" dataKey="iv" stroke={colors.warning} strokeWidth={1} />
</ComposedChart>
</ResponsiveContainer>
</ChartBox>
@@ -471,12 +460,12 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="VOLATILITY SURFACE">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={volatilityData.slice(0, 30)}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="day" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Area type="monotone" dataKey="realized" stackId="1" stroke={BLOOMBERG_GREEN} fill={BLOOMBERG_GREEN} fillOpacity={0.6} />
- <Area type="monotone" dataKey="implied" stackId="1" stroke={BLOOMBERG_YELLOW} fill={BLOOMBERG_YELLOW} fillOpacity={0.6} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="day" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Area type="monotone" dataKey="realized" stackId="1" stroke={colors.secondary} fill={colors.secondary} fillOpacity={0.6} />
+ <Area type="monotone" dataKey="implied" stackId="1" stroke={colors.warning} fill={colors.warning} fillOpacity={0.6} />
</AreaChart>
</ResponsiveContainer>
</ChartBox>
@@ -484,12 +473,12 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="ECONOMIC INDICATORS">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={economicData}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="indicator" stroke={BLOOMBERG_WHITE} fontSize={7} angle={-45} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Bar dataKey="current" fill={BLOOMBERG_BLUE} />
- <Bar dataKey="forecast" fill={BLOOMBERG_ORANGE} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="indicator" stroke={colors.text} fontSize={7} angle={-45} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Bar dataKey="current" fill={colors.info} />
+ <Bar dataKey="forecast" fill={colors.primary} />
</BarChart>
</ResponsiveContainer>
</ChartBox>
@@ -497,12 +486,12 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="MARKET SENTIMENT">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={sentimentData.slice(0, 15)}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="date" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Area type="monotone" dataKey="bullish" stackId="1" stroke={BLOOMBERG_GREEN} fill={BLOOMBERG_GREEN} fillOpacity={0.4} />
- <Area type="monotone" dataKey="bearish" stackId="1" stroke={BLOOMBERG_RED} fill={BLOOMBERG_RED} fillOpacity={0.4} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="date" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Area type="monotone" dataKey="bullish" stackId="1" stroke={colors.secondary} fill={colors.secondary} fillOpacity={0.4} />
+ <Area type="monotone" dataKey="bearish" stackId="1" stroke={colors.alert} fill={colors.alert} fillOpacity={0.4} />
</AreaChart>
</ResponsiveContainer>
</ChartBox>
@@ -510,13 +499,13 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="FUND FLOWS">
<ResponsiveContainer width="100%" height="100%">
<ComposedChart data={flowsData}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="date" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Bar dataKey="inflows" fill={BLOOMBERG_GREEN} />
- <Bar dataKey="outflows" fill={BLOOMBERG_RED} />
- <Line type="monotone" dataKey="net" stroke={BLOOMBERG_YELLOW} strokeWidth={2} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="date" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Bar dataKey="inflows" fill={colors.secondary} />
+ <Bar dataKey="outflows" fill={colors.alert} />
+ <Line type="monotone" dataKey="net" stroke={colors.warning} strokeWidth={2} />
</ComposedChart>
</ResponsiveContainer>
</ChartBox>
@@ -524,12 +513,12 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="PERFORMANCE ATTRIBUTION">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={performanceData}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="period" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Bar dataKey="return" fill={BLOOMBERG_GREEN} />
- <Bar dataKey="benchmark" fill={BLOOMBERG_GRAY} opacity={0.5} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="period" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Bar dataKey="return" fill={colors.secondary} />
+ <Bar dataKey="benchmark" fill={colors.textMuted} opacity={0.5} />
</BarChart>
</ResponsiveContainer>
</ChartBox>
@@ -538,11 +527,11 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="FACTOR ATTRIBUTION">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={attribution} layout="horizontal">
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis type="number" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis type="category" dataKey="factor" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Bar dataKey="contribution" fill={BLOOMBERG_GREEN} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis type="number" stroke={colors.text} fontSize={8} />
+ <YAxis type="category" dataKey="factor" stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Bar dataKey="contribution" fill={colors.secondary} />
</BarChart>
</ResponsiveContainer>
</ChartBox>
@@ -550,13 +539,13 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="MONEY FLOW INDEX">
<ResponsiveContainer width="100%" height="100%">
<LineChart data={moneyFlowData}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="day" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Line type="monotone" dataKey="mfi" stroke={BLOOMBERG_PURPLE} strokeWidth={1} dot={false} />
- <ReferenceLine y={20} stroke={BLOOMBERG_RED} strokeDasharray="2 2" />
- <ReferenceLine y={80} stroke={BLOOMBERG_RED} strokeDasharray="2 2" />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="day" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Line type="monotone" dataKey="mfi" stroke={colors.purple} strokeWidth={1} dot={false} />
+ <ReferenceLine y={20} stroke={colors.alert} strokeDasharray="2 2" />
+ <ReferenceLine y={80} stroke={colors.alert} strokeDasharray="2 2" />
</LineChart>
</ResponsiveContainer>
</ChartBox>
@@ -564,24 +553,24 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="GLOBAL MARKETS">
<ResponsiveContainer width="100%" height="100%">
<RadarChart data={marketData}>
- <PolarGrid stroke={BLOOMBERG_GRAY} />
- <PolarAngleAxis dataKey="market" tick={{ fontSize: 9, fill: BLOOMBERG_WHITE }} />
- <PolarRadiusAxis tick={{ fontSize: 8, fill: BLOOMBERG_GRAY }} />
+ <PolarGrid stroke={colors.textMuted} />
+ <PolarAngleAxis dataKey="market" tick={{ fontSize: 9, fill: colors.text }} />
+ <PolarRadiusAxis tick={{ fontSize: 8, fill: colors.textMuted }} />
<Radar
name="Return"
dataKey="return"
- stroke={BLOOMBERG_GREEN}
- fill={BLOOMBERG_GREEN}
+ stroke={colors.secondary}
+ fill={colors.secondary}
fillOpacity={0.3}
/>
<Radar
name="Volatility"
dataKey="volatility"
- stroke={BLOOMBERG_RED}
- fill={BLOOMBERG_RED}
+ stroke={colors.alert}
+ fill={colors.alert}
fillOpacity={0.2}
/>
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
</RadarChart>
</ResponsiveContainer>
</ChartBox>
@@ -589,11 +578,11 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="YIELD CURVE">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={bondData}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="maturity" stroke={BLOOMBERG_WHITE} fontSize={8} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Area type="monotone" dataKey="yield" stroke={BLOOMBERG_YELLOW} fill={BLOOMBERG_YELLOW} fillOpacity={0.3} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="maturity" stroke={colors.text} fontSize={8} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Area type="monotone" dataKey="yield" stroke={colors.warning} fill={colors.warning} fillOpacity={0.3} />
</AreaChart>
</ResponsiveContainer>
</ChartBox>
@@ -601,12 +590,12 @@ const AnalyticsTab: React.FC = () => {
<ChartBox title="STRESS SCENARIOS">
<ResponsiveContainer width="100%" height="100%">
<ComposedChart data={stressData}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="scenario" stroke={BLOOMBERG_WHITE} fontSize={7} angle={-45} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: BLOOMBERG_DARK_BG, border: `1px solid ${BLOOMBERG_GRAY}`, fontSize: '9px' }} />
- <Bar dataKey="probability" fill={BLOOMBERG_BLUE} />
- <Line type="monotone" dataKey="impact" stroke={BLOOMBERG_RED} strokeWidth={2} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="scenario" stroke={colors.text} fontSize={7} angle={-45} />
+ <YAxis stroke={colors.text} fontSize={8} />
+ <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
+ <Bar dataKey="probability" fill={colors.info} />
+ <Line type="monotone" dataKey="impact" stroke={colors.alert} strokeWidth={2} />
</ComposedChart>
</ResponsiveContainer>
</ChartBox>
@@ -615,11 +604,11 @@ const AnalyticsTab: React.FC = () => {
{/* Status Bar */}
<div style={{
- borderTop: `1px solid ${BLOOMBERG_GRAY}`,
- backgroundColor: BLOOMBERG_PANEL_BG,
+ borderTop: `1px solid ${colors.textMuted}`,
+ backgroundColor: colors.panel,
padding: '2px 8px',
fontSize: '10px',
- color: BLOOMBERG_GRAY,
+ color: colors.textMuted,
flexShrink: 0
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
@@ -630,7 +619,7 @@ const AnalyticsTab: React.FC = () => {
<div style={{ display: 'flex', gap: '16px' }}>
<span>Risk: VaR $45K | Sharpe: 1.84 | Beta: 0.97</span>
<span>Session: {currentTime.toTimeString().substring(0, 8)}</span>
- <span style={{ color: BLOOMBERG_GREEN }}>SYSTEM: ACTIVE</span>
+ <span style={{ color: colors.secondary }}>SYSTEM: ACTIVE</span>
</div>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
index 1d94f0616..d14c736d3 100644
--- a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
@@ -1,6 +1,7 @@
import React, { useState, useEffect, useRef } from 'react';
import { flushSync } from 'react-dom';
import { Settings, Trash2, Bot, User, Clock, Send, Plus, Search, Edit2, Check, X } from 'lucide-react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { llmApiService, ChatMessage as APIMessage } from '../../services/llmApi';
import { sqliteService, ChatSession, ChatMessage } from '../../services/sqliteService';
import { llmConfigService } from '../../services/llmConfig';
@@ -12,6 +13,7 @@ interface ChatTabProps {
}
const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
const [currentSessionUuid, setCurrentSessionUuid] = useState<string | null>(null);
const [messages, setMessages] = useState<ChatMessage[]>([]);
@@ -33,16 +35,6 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
const messagesEndRef = useRef<HTMLDivElement>(null);
const sessionsListRef = useRef<HTMLDivElement>(null);
- // Bloomberg color scheme
- const BLOOMBERG_ORANGE = '#FFA500';
- const BLOOMBERG_WHITE = '#FFFFFF';
- const BLOOMBERG_RED = '#FF0000';
- const BLOOMBERG_GREEN = '#00C800';
- const BLOOMBERG_YELLOW = '#FFFF00';
- const BLOOMBERG_GRAY = '#787878';
- const BLOOMBERG_DARK_BG = '#000000';
- const BLOOMBERG_PANEL_BG = '#0a0a0a';
-
// Initialize database on mount
useEffect(() => {
const initDatabase = async () => {
@@ -452,23 +444,23 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
alignItems: 'center',
justifyContent: 'center',
height: '100%',
- backgroundColor: BLOOMBERG_PANEL_BG
+ backgroundColor: colors.panel
}}>
<div style={{ textAlign: 'center', padding: '24px' }}>
- <Bot size={48} color={BLOOMBERG_ORANGE} style={{ marginBottom: '16px' }} />
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '20px', fontWeight: 'bold', marginBottom: '8px' }}>
+ <Bot size={48} color={colors.primary} style={{ marginBottom: '16px' }} />
+ <div style={{ color: colors.primary, fontSize: '20px', fontWeight: 'bold', marginBottom: '8px' }}>
FINCEPT AI ASSISTANT
</div>
- <div style={{ color: BLOOMBERG_WHITE, fontSize: '14px', marginBottom: '16px' }}>
+ <div style={{ color: colors.text, fontSize: '14px', marginBottom: '16px' }}>
Financial Intelligence System
</div>
- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '12px', marginBottom: '16px' }}>
+ <div style={{ color: colors.warning, fontSize: '12px', marginBottom: '16px' }}>
Provider: {currentProvider.toUpperCase()} | Model: {llmConfigService.getActiveConfig().model}
</div>
<button
onClick={createNewSession}
style={{
- backgroundColor: BLOOMBERG_ORANGE,
+ backgroundColor: colors.primary,
color: 'black',
border: 'none',
padding: '10px 20px',
@@ -494,30 +486,30 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
<div style={{
maxWidth: '85%',
minWidth: '120px',
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${message.role === 'user' ? BLOOMBERG_YELLOW : BLOOMBERG_ORANGE}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${message.role === 'user' ? colors.warning : colors.primary}`,
borderRadius: '4px',
padding: '10px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
{message.role === 'user' ? (
- <User size={12} color={BLOOMBERG_YELLOW} />
+ <User size={12} color={colors.warning} />
) : (
- <Bot size={12} color={BLOOMBERG_ORANGE} />
+ <Bot size={12} color={colors.primary} />
)}
<span style={{
- color: message.role === 'user' ? BLOOMBERG_YELLOW : BLOOMBERG_ORANGE,
+ color: message.role === 'user' ? colors.warning : colors.primary,
fontSize: '11px',
fontWeight: 'bold'
}}>
{message.role === 'user' ? 'YOU' : 'AI'}
</span>
- <Clock size={10} color={BLOOMBERG_GRAY} />
- <span style={{ color: BLOOMBERG_GRAY, fontSize: '10px' }}>
+ <Clock size={10} color={colors.textMuted} />
+ <span style={{ color: colors.textMuted, fontSize: '10px' }}>
{formatTime(message.timestamp)}
</span>
{message.provider && (
- <span style={{ color: BLOOMBERG_GRAY, fontSize: '10px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '10px' }}>
| {message.provider}
</span>
)}
@@ -525,7 +517,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
{message.role === 'assistant' ? (
<MarkdownRenderer content={message.content} />
) : (
- <div style={{ color: BLOOMBERG_WHITE, fontSize: '13px', lineHeight: '1.5', whiteSpace: 'pre-wrap' }}>
+ <div style={{ color: colors.text, fontSize: '13px', lineHeight: '1.5', whiteSpace: 'pre-wrap' }}>
{message.content}
</div>
)}
@@ -541,25 +533,25 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
<div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'flex-start' }}>
<div style={{
maxWidth: '85%',
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `2px solid ${BLOOMBERG_ORANGE}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.primary}`,
borderRadius: '4px',
padding: '10px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
- <Bot size={12} color={BLOOMBERG_ORANGE} />
- <span style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
+ <Bot size={12} color={colors.primary} />
+ <span style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold' }}>
AI TYPING...
</span>
</div>
<div style={{
- color: BLOOMBERG_WHITE,
+ color: colors.text,
fontSize: '13px',
lineHeight: '1.5',
whiteSpace: 'pre-wrap'
}}>
{streamingContent}
- <span style={{ color: BLOOMBERG_ORANGE }}>▊</span>
+ <span style={{ color: colors.primary }}>▊</span>
</div>
</div>
</div>
@@ -569,12 +561,14 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
return (
<div style={{
height: '100%',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
- fontFamily: 'Consolas, monospace',
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontFamily: fontFamily,
+ fontWeight: fontWeight,
+ fontStyle: fontStyle,
display: 'flex',
flexDirection: 'column',
- fontSize: '11px'
+ fontSize: fontSize.body
}}>
<style>{`
/* Transparent/hidden scrollbar styling */
@@ -600,8 +594,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
`}</style>
{/* Compact Header */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
padding: '6px 10px',
display: 'flex',
justifyContent: 'space-between',
@@ -609,13 +603,13 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
flexShrink: 0
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
- <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold', fontSize: '12px' }}>FINCEPT AI</span>
- <span style={{ color: BLOOMBERG_GRAY }}>|</span>
- <span style={{ color: BLOOMBERG_YELLOW, fontSize: '10px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '12px' }}>FINCEPT AI</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.warning, fontSize: '10px' }}>
{currentProvider.toUpperCase()}
</span>
- <span style={{ color: BLOOMBERG_GRAY }}>|</span>
- <span style={{ color: BLOOMBERG_WHITE, fontSize: '10px' }}>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.text, fontSize: '10px' }}>
{currentTime.toLocaleTimeString('en-US', { hour12: false })}
</span>
</div>
@@ -623,9 +617,9 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
<button
onClick={() => setIsSettingsOpen(true)}
style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: BLOOMBERG_WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.text,
padding: '4px 8px',
fontSize: '10px',
cursor: 'pointer',
@@ -640,7 +634,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
<button
onClick={createNewSession}
style={{
- backgroundColor: BLOOMBERG_ORANGE,
+ backgroundColor: colors.primary,
border: 'none',
color: 'black',
padding: '4px 8px',
@@ -663,23 +657,23 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
{/* Left Panel - Sessions */}
<div style={{
width: '250px',
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderRight: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ borderRight: `1px solid ${colors.textMuted}`,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden'
}}>
<div style={{ padding: '8px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '11px', fontWeight: 'bold' }}>
+ <div style={{ color: colors.warning, fontSize: '11px', fontWeight: 'bold' }}>
SESSIONS ({statistics.totalSessions})
</div>
{sessions.length > 0 && (
<button
onClick={deleteAllSessions}
style={{
- backgroundColor: BLOOMBERG_RED,
- color: BLOOMBERG_WHITE,
+ backgroundColor: colors.alert,
+ color: colors.text,
border: 'none',
padding: '2px 6px',
fontSize: '8px',
@@ -695,7 +689,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
{/* Search */}
<div style={{ position: 'relative', marginBottom: '8px' }}>
- <Search size={12} color={BLOOMBERG_GRAY} style={{ position: 'absolute', left: '6px', top: '6px' }} />
+ <Search size={12} color={colors.textMuted} style={{ position: 'absolute', left: '6px', top: '6px' }} />
<input
id="session-search"
type="text"
@@ -704,9 +698,9 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
onChange={(e) => setSearchQuery(e.target.value)}
style={{
width: '100%',
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: BLOOMBERG_WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.text,
padding: '4px 4px 4px 24px',
fontSize: '10px'
}}
@@ -714,7 +708,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
</div>
{/* Stats */}
- <div style={{ fontSize: '9px', color: BLOOMBERG_GRAY, marginBottom: '6px' }}>
+ <div style={{ fontSize: '9px', color: colors.textMuted, marginBottom: '6px' }}>
Messages: {statistics.totalMessages} | Tokens: {statistics.totalTokens.toLocaleString()}
</div>
</div>
@@ -732,8 +726,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
<div
key={session.session_uuid}
style={{
- backgroundColor: currentSessionUuid === session.session_uuid ? BLOOMBERG_ORANGE + '30' : BLOOMBERG_DARK_BG,
- border: `1px solid ${currentSessionUuid === session.session_uuid ? BLOOMBERG_ORANGE : BLOOMBERG_GRAY}`,
+ backgroundColor: currentSessionUuid === session.session_uuid ? colors.primary + '30' : colors.background,
+ border: `1px solid ${currentSessionUuid === session.session_uuid ? colors.primary : colors.textMuted}`,
padding: '6px',
marginBottom: '4px',
cursor: renamingSessionId === session.session_uuid ? 'default' : 'pointer'
@@ -754,9 +748,9 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
autoFocus
style={{
flex: 1,
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_ORANGE}`,
- color: BLOOMBERG_WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
fontSize: '11px',
padding: '2px 4px',
fontFamily: 'Consolas, monospace'
@@ -769,7 +763,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
}}
style={{
backgroundColor: 'transparent',
- color: BLOOMBERG_GREEN,
+ color: colors.secondary,
border: 'none',
cursor: 'pointer',
padding: '0',
@@ -785,7 +779,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
}}
style={{
backgroundColor: 'transparent',
- color: BLOOMBERG_RED,
+ color: colors.alert,
border: 'none',
cursor: 'pointer',
padding: '0',
@@ -796,14 +790,14 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
</button>
</div>
) : (
- <div style={{ color: BLOOMBERG_WHITE, fontSize: '11px', marginBottom: '3px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ <div style={{ color: colors.text, fontSize: '11px', marginBottom: '3px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{session.title}
</div>
)}
{/* Actions Row */}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <span style={{ color: BLOOMBERG_GRAY, fontSize: '9px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '9px' }}>
{session.message_count} msgs • {formatSessionTime(session.updated_at)}
</span>
<div style={{ display: 'flex', gap: '6px' }}>
@@ -814,7 +808,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
}}
style={{
backgroundColor: 'transparent',
- color: BLOOMBERG_YELLOW,
+ color: colors.warning,
border: 'none',
fontSize: '9px',
cursor: 'pointer',
@@ -832,7 +826,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
}}
style={{
backgroundColor: 'transparent',
- color: BLOOMBERG_RED,
+ color: colors.alert,
border: 'none',
fontSize: '9px',
cursor: 'pointer',
@@ -853,7 +847,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
{/* Center Panel - Chat */}
<div style={{
flex: 1,
- backgroundColor: BLOOMBERG_PANEL_BG,
+ backgroundColor: colors.panel,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden'
@@ -861,20 +855,20 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
{/* Chat Header */}
<div style={{
padding: '6px 10px',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ borderBottom: `1px solid ${colors.textMuted}`,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}>
- <span style={{ color: BLOOMBERG_WHITE, fontSize: '11px' }}>
+ <span style={{ color: colors.text, fontSize: '11px' }}>
{currentSessionUuid ? sessions.find(s => s.session_uuid === currentSessionUuid)?.title || 'Chat' : 'No Active Session'}
</span>
{currentSessionUuid && (
<button
onClick={clearCurrentChat}
style={{
- backgroundColor: BLOOMBERG_RED,
- color: BLOOMBERG_WHITE,
+ backgroundColor: colors.alert,
+ color: colors.text,
border: 'none',
padding: '3px 8px',
fontSize: '9px',
@@ -891,14 +885,14 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
flex: 1,
padding: '10px',
overflow: 'auto',
- backgroundColor: BLOOMBERG_DARK_BG
+ backgroundColor: colors.background
}}>
{messages.length === 0 && !streamingContent ? renderWelcomeScreen() : (
<div>
{messages.map(renderMessage)}
{streamingContent && renderStreamingMessage()}
{isTyping && !streamingContent && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', color: BLOOMBERG_GRAY, fontSize: '11px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', color: colors.textMuted, fontSize: '11px' }}>
<Bot size={12} />
<span>AI is thinking...</span>
</div>
@@ -909,7 +903,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
</div>
{/* Input Area */}
- <div style={{ padding: '8px', borderTop: `1px solid ${BLOOMBERG_GRAY}` }}>
+ <div style={{ padding: '8px', borderTop: `1px solid ${colors.textMuted}` }}>
<div style={{ display: 'flex', gap: '6px' }}>
<textarea
value={messageInput}
@@ -923,9 +917,9 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
placeholder="Type your message... (Shift+Enter for new line)"
style={{
flex: 1,
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: BLOOMBERG_WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.text,
padding: '6px',
fontSize: '11px',
resize: 'none',
@@ -937,7 +931,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
onClick={handleSendMessage}
disabled={!messageInput.trim() || isTyping}
style={{
- backgroundColor: messageInput.trim() && !isTyping ? BLOOMBERG_ORANGE : BLOOMBERG_GRAY,
+ backgroundColor: messageInput.trim() && !isTyping ? colors.primary : colors.textMuted,
color: 'black',
border: 'none',
padding: '6px 12px',
@@ -953,7 +947,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
SEND
</button>
</div>
- <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px', marginTop: '4px' }}>
+ <div style={{ color: colors.textMuted, fontSize: '9px', marginTop: '4px' }}>
{messageInput.length > 0 ? `${messageInput.length} chars` : systemStatus}
</div>
</div>
@@ -962,12 +956,12 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
{/* Right Panel - Quick Actions */}
<div style={{
width: '200px',
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderLeft: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ borderLeft: `1px solid ${colors.textMuted}`,
padding: '8px',
overflow: 'auto'
}}>
- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
+ <div style={{ color: colors.warning, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
QUICK PROMPTS
</div>
{[
@@ -981,9 +975,9 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
onClick={() => setMessageInput(item.prompt)}
style={{
width: '100%',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ border: `1px solid ${colors.textMuted}`,
padding: '5px',
fontSize: '9px',
textAlign: 'left',
@@ -995,19 +989,19 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
</button>
))}
- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '11px', fontWeight: 'bold', marginTop: '12px', marginBottom: '6px' }}>
+ <div style={{ color: colors.warning, fontSize: '11px', fontWeight: 'bold', marginTop: '12px', marginBottom: '6px' }}>
SYSTEM INFO
</div>
- <div style={{ color: BLOOMBERG_WHITE, fontSize: '9px', marginBottom: '2px' }}>
+ <div style={{ color: colors.text, fontSize: '9px', marginBottom: '2px' }}>
Provider: {currentProvider.toUpperCase()}
</div>
- <div style={{ color: BLOOMBERG_WHITE, fontSize: '9px', marginBottom: '2px' }}>
+ <div style={{ color: colors.text, fontSize: '9px', marginBottom: '2px' }}>
Model: {llmConfigService.getActiveConfig().model}
</div>
- <div style={{ color: BLOOMBERG_WHITE, fontSize: '9px', marginBottom: '2px' }}>
+ <div style={{ color: colors.text, fontSize: '9px', marginBottom: '2px' }}>
Temp: {llmConfigService.getActiveConfig().temperature}
</div>
- <div style={{ color: BLOOMBERG_GREEN, fontSize: '9px' }}>
+ <div style={{ color: colors.secondary, fontSize: '9px' }}>
Streaming: Enabled
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/CodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/CodeEditorTab.tsx
index 44bd5860e..97b054ca7 100644
--- a/fincept-terminal-desktop/src/components/tabs/CodeEditorTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/CodeEditorTab.tsx
@@ -3,6 +3,7 @@ import { Play, Save, FileText, Plus, X, RefreshCw, Terminal as TerminalIcon, Dow
import { invoke } from '@tauri-apps/api/core';
import { open, save } from '@tauri-apps/plugin-dialog';
import { notebookService } from '@/services/notebookService';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface EditorFile {
id: string;
@@ -68,6 +69,7 @@ interface NotebookHistory {
}
export default function CodeEditorTab() {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [editorMode, setEditorMode] = useState<'code' | 'notebook'>('code');
const [files, setFiles] = useState<EditorFile[]>([
{
@@ -113,19 +115,19 @@ plot_candlestick AAPL, "Apple Stock Chart"`,
const textareaRef = useRef<HTMLTextAreaElement>(null);
- // Colors
+ // Use theme colors with legacy variable name for minimal changes
const C = {
- ORANGE: '#FF8C00',
- WHITE: '#FFFFFF',
- GREEN: '#00FF00',
- RED: '#FF0000',
- YELLOW: '#FFFF00',
- BLUE: '#4169E1',
- CYAN: '#00FFFF',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0a0a0a',
- EDITOR_BG: '#1a1a1a'
+ ORANGE: colors.primary,
+ WHITE: colors.text,
+ GREEN: colors.secondary,
+ RED: colors.alert,
+ YELLOW: colors.warning,
+ BLUE: colors.info,
+ CYAN: colors.accent,
+ GRAY: colors.textMuted,
+ DARK_BG: colors.background,
+ PANEL_BG: colors.panel,
+ EDITOR_BG: colors.panel
};
const activeFile = files.find(f => f.id === activeFileId) || files[0];
diff --git a/fincept-terminal-desktop/src/components/tabs/DBnomicsTab.tsx b/fincept-terminal-desktop/src/components/tabs/DBnomicsTab.tsx
index 8ac836a63..ad7694b9c 100644
--- a/fincept-terminal-desktop/src/components/tabs/DBnomicsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/DBnomicsTab.tsx
@@ -1,5 +1,6 @@
import React, { useState } from 'react';
import { RefreshCw, Download, Plus, Minus, Trash2 } from 'lucide-react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface Provider {
code: string;
@@ -32,8 +33,9 @@ interface DataPoint {
type ChartType = 'line' | 'bar' | 'area' | 'scatter' | 'candlestick';
export default function DBnomicsTab() {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const BASE_URL = 'https://api.db.nomics.world/v22';
- const COLORS = ['#ea580c', '#3b82f6', '#10b981', '#f59e0b', '#ec4899', '#8b5cf6', '#14b8a6', '#f97316'];
+ const COLORS = [colors.primary, colors.info, colors.secondary, colors.warning, colors.purple, colors.purple, colors.accent, colors.primary];
const [providers, setProviders] = useState<Provider[]>([]);
const [datasets, setDatasets] = useState<Dataset[]>([]);
@@ -319,10 +321,10 @@ export default function DBnomicsTab() {
const yRange = yMax - yMin;
return (
- <svg width={w} height={h} viewBox={`0 0 ${actualWidth} ${h}`} preserveAspectRatio="xMidYMid meet" style={{ backgroundColor: '#0a0a0a', width: '100%', height: 'auto', maxHeight: compact ? '240px' : '400px' }}>
+ <svg width={w} height={h} viewBox={`0 0 ${actualWidth} ${h}`} preserveAspectRatio="xMidYMid meet" style={{ backgroundColor: colors.panel, width: '100%', height: 'auto', maxHeight: compact ? '240px' : '400px' }}>
{/* Axes */}
- <line x1={ml} y1={mt} x2={ml} y2={h - mb} stroke="#404040" strokeWidth="1" />
- <line x1={ml} y1={h - mb} x2={actualWidth - mr} y2={h - mb} stroke="#404040" strokeWidth="1" />
+ <line x1={ml} y1={mt} x2={ml} y2={h - mb} stroke={colors.textMuted} strokeWidth="1" />
+ <line x1={ml} y1={h - mb} x2={actualWidth - mr} y2={h - mb} stroke={colors.textMuted} strokeWidth="1" />
{/* Y-axis grid and labels */}
{[0, 1, 2, 3, 4].map(i => {
@@ -331,7 +333,7 @@ export default function DBnomicsTab() {
return (
<g key={i}>
<line x1={ml} y1={y} x2={actualWidth - mr} y2={y} stroke="#1a1a1a" strokeDasharray="2,2" />
- <text x={ml - 8} y={y + 3} textAnchor="end" fill="#737373" fontSize="9" fontFamily="monospace">
+ <text x={ml - 8} y={y + 3} textAnchor="end" fill={colors.textMuted} fontSize="9" fontFamily="monospace">
{val.toFixed(1)}
</text>
</g>
@@ -413,7 +415,7 @@ export default function DBnomicsTab() {
y={Math.min(yOpen, yClose)}
width={6}
height={Math.abs(yClose - yOpen) || 1}
- fill={close >= open ? '#10b981' : '#ef4444'}
+ fill={close >= open ? colors.secondary : colors.alert}
/>
</g>
);
@@ -429,7 +431,7 @@ export default function DBnomicsTab() {
if (idx % Math.max(1, Math.floor(arr.length / 6)) !== 0 && idx !== arr.length - 1) return null;
const x = ml + (pw * idx) / (arr.length - 1 || 1);
return (
- <text key={idx} x={x} y={h - mb + 15} textAnchor="middle" fill="#737373" fontSize="8" fontFamily="monospace">
+ <text key={idx} x={x} y={h - mb + 15} textAnchor="middle" fill={colors.textMuted} fontSize="8" fontFamily="monospace">
{obs.period.substring(0, 7)}
</text>
);
@@ -439,7 +441,7 @@ export default function DBnomicsTab() {
{seriesArray.map((series, idx) => (
<g key={idx}>
<rect x={ml + idx * 120} y={5} width={10} height={10} fill={series.color} />
- <text x={ml + idx * 120 + 15} y={13} fill="#d4d4d4" fontSize="9" fontFamily="monospace">
+ <text x={ml + idx * 120 + 15} y={13} fill={colors.text} fontSize="9" fontFamily="monospace">
{series.series_name.substring(0, 12)}
</text>
</g>
@@ -449,7 +451,7 @@ export default function DBnomicsTab() {
};
return (
- <div style={{ width: '100%', height: '100%', backgroundColor: '#000', color: '#d4d4d4', fontFamily: 'Consolas, monospace', fontSize: '11px', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
+ <div style={{ width: '100%', height: '100%', backgroundColor: colors.background, color: colors.text, fontFamily: 'Consolas, monospace', fontSize: '11px', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
<style>{`
/* Custom scrollbar styles */
*::-webkit-scrollbar {
@@ -460,7 +462,7 @@ export default function DBnomicsTab() {
background: #1a1a1a;
}
*::-webkit-scrollbar-thumb {
- background: #404040;
+ background: colors.textMuted;
border-radius: 4px;
}
*::-webkit-scrollbar-thumb:hover {
@@ -468,18 +470,18 @@ export default function DBnomicsTab() {
}
`}</style>
{/* Header */}
- <div style={{ padding: '8px 12px', borderBottom: '1px solid #404040', display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
- <span style={{ color: '#ea580c', fontWeight: 'bold' }}>DBNOMICS TERMINAL</span>
- <span style={{ color: '#0f0', fontSize: '10px' }}>● {status}</span>
- <span style={{ color: '#fbbf24', fontSize: '10px' }}>Providers: {providers.length}</span>
+ <div style={{ padding: '8px 12px', borderBottom: '1px solid colors.textMuted', display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>DBNOMICS TERMINAL</span>
+ <span style={{ color: colors.secondary, fontSize: '10px' }}>● {status}</span>
+ <span style={{ color: colors.warning, fontSize: '10px' }}>Providers: {providers.length}</span>
<div style={{ flex: 1 }}></div>
- <button onClick={loadProviders} disabled={loading} style={{ padding: '3px 10px', backgroundColor: '#2d2d2d', color: '#d4d4d4', border: '1px solid #404040', cursor: loading ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
+ <button onClick={loadProviders} disabled={loading} style={{ padding: '3px 10px', backgroundColor: '#2a2a2a', color: colors.text, border: '1px solid colors.textMuted', cursor: loading ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
LOAD
</button>
- <button onClick={() => currentData && loadSeriesData(currentData.series_id, currentData.series_name)} disabled={!currentData} style={{ padding: '3px 10px', backgroundColor: '#2d2d2d', color: '#d4d4d4', border: '1px solid #404040', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
+ <button onClick={() => currentData && loadSeriesData(currentData.series_id, currentData.series_name)} disabled={!currentData} style={{ padding: '3px 10px', backgroundColor: '#2a2a2a', color: colors.text, border: '1px solid colors.textMuted', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
<RefreshCw size={10} style={{ display: 'inline', marginRight: '4px' }} />REFRESH
</button>
- <button onClick={exportData} disabled={!currentData} style={{ padding: '3px 10px', backgroundColor: '#2d2d2d', color: '#d4d4d4', border: '1px solid #404040', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
+ <button onClick={exportData} disabled={!currentData} style={{ padding: '3px 10px', backgroundColor: '#2a2a2a', color: colors.text, border: '1px solid colors.textMuted', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
<Download size={10} style={{ display: 'inline', marginRight: '4px' }} />EXPORT
</button>
</div>
@@ -487,20 +489,20 @@ export default function DBnomicsTab() {
{/* Main Content */}
<div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
{/* Left Panel */}
- <div style={{ width: '320px', borderRight: '1px solid #404040', display: 'flex', flexDirection: 'column', backgroundColor: '#0a0a0a' }}>
+ <div style={{ width: '320px', borderRight: '1px solid colors.textMuted', display: 'flex', flexDirection: 'column', backgroundColor: colors.panel }}>
<div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '8px' }}>
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '4px' }}>1. PROVIDER</div>
+ <div style={{ color: colors.primary, fontSize: '10px', marginBottom: '4px' }}>1. PROVIDER</div>
<div
style={{
width: '100%',
height: '140px',
backgroundColor: '#1a1a1a',
- border: '1px solid #404040',
+ border: '1px solid colors.textMuted',
marginBottom: '12px',
overflowY: 'auto',
overflowX: 'hidden',
scrollbarWidth: 'thin',
- scrollbarColor: '#404040 #1a1a1a'
+ scrollbarColor: 'colors.textMuted #1a1a1a'
}}
>
{providers.map(p => (
@@ -510,18 +512,18 @@ export default function DBnomicsTab() {
style={{
padding: '6px 8px',
fontSize: '10px',
- color: selectedProvider === p.code ? '#fff' : '#d4d4d4',
- backgroundColor: selectedProvider === p.code ? '#ea580c' : 'transparent',
+ color: selectedProvider === p.code ? '#fff' : colors.text,
+ backgroundColor: selectedProvider === p.code ? colors.primary : 'transparent',
cursor: 'pointer',
fontFamily: 'Consolas, monospace',
lineHeight: '1.4',
wordWrap: 'break-word',
whiteSpace: 'normal',
- borderBottom: '1px solid #0a0a0a'
+ borderBottom: '1px solid colors.panel'
}}
onMouseEnter={(e) => {
if (selectedProvider !== p.code) {
- e.currentTarget.style.backgroundColor = '#2d2d2d';
+ e.currentTarget.style.backgroundColor = '#2a2a2a';
}
}}
onMouseLeave={(e) => {
@@ -535,18 +537,18 @@ export default function DBnomicsTab() {
))}
</div>
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '4px' }}>2. DATASET</div>
+ <div style={{ color: colors.primary, fontSize: '10px', marginBottom: '4px' }}>2. DATASET</div>
<div
style={{
width: '100%',
height: '140px',
backgroundColor: '#1a1a1a',
- border: '1px solid #404040',
+ border: '1px solid colors.textMuted',
marginBottom: '12px',
overflowY: 'auto',
overflowX: 'hidden',
scrollbarWidth: 'thin',
- scrollbarColor: '#404040 #1a1a1a'
+ scrollbarColor: 'colors.textMuted #1a1a1a'
}}
>
{datasets.map(d => (
@@ -556,18 +558,18 @@ export default function DBnomicsTab() {
style={{
padding: '6px 8px',
fontSize: '10px',
- color: selectedDataset === d.code ? '#fff' : '#d4d4d4',
- backgroundColor: selectedDataset === d.code ? '#ea580c' : 'transparent',
+ color: selectedDataset === d.code ? '#fff' : colors.text,
+ backgroundColor: selectedDataset === d.code ? colors.primary : 'transparent',
cursor: 'pointer',
fontFamily: 'Consolas, monospace',
lineHeight: '1.4',
wordWrap: 'break-word',
whiteSpace: 'normal',
- borderBottom: '1px solid #0a0a0a'
+ borderBottom: '1px solid colors.panel'
}}
onMouseEnter={(e) => {
if (selectedDataset !== d.code) {
- e.currentTarget.style.backgroundColor = '#2d2d2d';
+ e.currentTarget.style.backgroundColor = '#2a2a2a';
}
}}
onMouseLeave={(e) => {
@@ -581,18 +583,18 @@ export default function DBnomicsTab() {
))}
</div>
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '4px' }}>3. SERIES</div>
+ <div style={{ color: colors.primary, fontSize: '10px', marginBottom: '4px' }}>3. SERIES</div>
<div
style={{
width: '100%',
height: '140px',
backgroundColor: '#1a1a1a',
- border: '1px solid #404040',
+ border: '1px solid colors.textMuted',
marginBottom: '12px',
overflowY: 'auto',
overflowX: 'hidden',
scrollbarWidth: 'thin',
- scrollbarColor: '#404040 #1a1a1a'
+ scrollbarColor: 'colors.textMuted #1a1a1a'
}}
>
{seriesList.map(s => (
@@ -602,18 +604,18 @@ export default function DBnomicsTab() {
style={{
padding: '6px 8px',
fontSize: '10px',
- color: selectedSeries === s.full_id ? '#fff' : '#d4d4d4',
- backgroundColor: selectedSeries === s.full_id ? '#ea580c' : 'transparent',
+ color: selectedSeries === s.full_id ? '#fff' : colors.text,
+ backgroundColor: selectedSeries === s.full_id ? colors.primary : 'transparent',
cursor: 'pointer',
fontFamily: 'Consolas, monospace',
lineHeight: '1.4',
wordWrap: 'break-word',
whiteSpace: 'normal',
- borderBottom: '1px solid #0a0a0a'
+ borderBottom: '1px solid colors.panel'
}}
onMouseEnter={(e) => {
if (selectedSeries !== s.full_id) {
- e.currentTarget.style.backgroundColor = '#2d2d2d';
+ e.currentTarget.style.backgroundColor = '#2a2a2a';
}
}}
onMouseLeave={(e) => {
@@ -627,50 +629,50 @@ export default function DBnomicsTab() {
))}
</div>
- <div style={{ height: '1px', backgroundColor: '#404040', margin: '8px 0' }}></div>
+ <div style={{ height: '1px', backgroundColor: colors.textMuted, margin: '8px 0' }}></div>
{/* Actions */}
<div style={{ display: 'flex', gap: '4px', marginBottom: '8px' }}>
- <button onClick={addToSingleView} disabled={!currentData} style={{ flex: 1, padding: '4px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
+ <button onClick={addToSingleView} disabled={!currentData} style={{ flex: 1, padding: '4px', backgroundColor: '#1a1a1a', color: colors.text, border: '1px solid colors.textMuted', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
ADD TO SINGLE
</button>
- <button onClick={clearAllSlots} style={{ padding: '4px 8px', backgroundColor: '#1a1a1a', color: '#ef4444', border: '1px solid #404040', cursor: 'pointer', fontSize: '9px' }}>
+ <button onClick={clearAllSlots} style={{ padding: '4px 8px', backgroundColor: '#1a1a1a', color: colors.alert, border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '9px' }}>
<Trash2 size={10} />
</button>
</div>
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '6px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div style={{ color: colors.primary, fontSize: '10px', marginBottom: '6px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span>COMPARISON SLOTS</span>
- <button onClick={addSlot} style={{ padding: '2px 6px', backgroundColor: '#1a1a1a', color: '#10b981', border: '1px solid #404040', cursor: 'pointer', fontSize: '9px' }}>
+ <button onClick={addSlot} style={{ padding: '2px 6px', backgroundColor: '#1a1a1a', color: colors.secondary, border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '9px' }}>
<Plus size={10} />
</button>
</div>
<div style={{ maxHeight: '300px', overflowY: 'auto' }}>
{slots.map((slot, idx) => (
- <div key={idx} style={{ marginBottom: '6px', padding: '6px', backgroundColor: '#1a1a1a', border: '1px solid #404040', borderRadius: '2px' }}>
+ <div key={idx} style={{ marginBottom: '6px', padding: '6px', backgroundColor: '#1a1a1a', border: '1px solid colors.textMuted', borderRadius: '2px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
- <span style={{ color: '#fbbf24', fontSize: '9px' }}>SLOT {idx + 1} ({slot.length})</span>
+ <span style={{ color: colors.warning, fontSize: '9px' }}>SLOT {idx + 1} ({slot.length})</span>
<div style={{ display: 'flex', gap: '2px' }}>
- <button onClick={() => addToSlot(idx)} disabled={!currentData} style={{ padding: '2px 4px', backgroundColor: '#0a0a0a', color: '#10b981', border: '1px solid #404040', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '8px' }}>
+ <button onClick={() => addToSlot(idx)} disabled={!currentData} style={{ padding: '2px 4px', backgroundColor: colors.panel, color: colors.secondary, border: '1px solid colors.textMuted', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '8px' }}>
<Plus size={8} />
</button>
{slots.length > 1 && (
- <button onClick={() => removeSlot(idx)} style={{ padding: '2px 4px', backgroundColor: '#0a0a0a', color: '#ef4444', border: '1px solid #404040', cursor: 'pointer', fontSize: '8px' }}>
+ <button onClick={() => removeSlot(idx)} style={{ padding: '2px 4px', backgroundColor: colors.panel, color: colors.alert, border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '8px' }}>
<Minus size={8} />
</button>
)}
</div>
</div>
{slot.map((s, sIdx) => (
- <div key={sIdx} style={{ fontSize: '8px', color: '#737373', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2px' }}>
+ <div key={sIdx} style={{ fontSize: '8px', color: colors.textMuted, display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2px' }}>
<span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={s.series_name}>{s.series_name}</span>
- <button onClick={() => removeFromSlot(idx, sIdx)} style={{ padding: '1px 3px', backgroundColor: 'transparent', color: '#ef4444', border: 'none', cursor: 'pointer', fontSize: '8px' }}>
+ <button onClick={() => removeFromSlot(idx, sIdx)} style={{ padding: '1px 3px', backgroundColor: 'transparent', color: colors.alert, border: 'none', cursor: 'pointer', fontSize: '8px' }}>
×
</button>
</div>
))}
- {slot.length === 0 && <div style={{ fontSize: '8px', color: '#404040', textAlign: 'center' }}>Empty</div>}
+ {slot.length === 0 && <div style={{ fontSize: '8px', color: colors.textMuted, textAlign: 'center' }}>Empty</div>}
</div>
))}
</div>
@@ -680,19 +682,19 @@ export default function DBnomicsTab() {
{/* Right Panel */}
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
{/* View Toggle */}
- <div style={{ padding: '8px 12px', borderBottom: '1px solid #404040', display: 'flex', gap: '8px', alignItems: 'center' }}>
- <button onClick={() => setActiveView('single')} style={{ padding: '4px 12px', backgroundColor: activeView === 'single' ? '#ea580c' : '#2d2d2d', color: '#fff', border: '1px solid #404040', cursor: 'pointer', fontSize: '10px' }}>
+ <div style={{ padding: '8px 12px', borderBottom: '1px solid colors.textMuted', display: 'flex', gap: '8px', alignItems: 'center' }}>
+ <button onClick={() => setActiveView('single')} style={{ padding: '4px 12px', backgroundColor: activeView === 'single' ? colors.primary : '#2a2a2a', color: '#fff', border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '10px' }}>
SINGLE
</button>
- <button onClick={() => setActiveView('comparison')} style={{ padding: '4px 12px', backgroundColor: activeView === 'comparison' ? '#ea580c' : '#2d2d2d', color: '#fff', border: '1px solid #404040', cursor: 'pointer', fontSize: '10px' }}>
+ <button onClick={() => setActiveView('comparison')} style={{ padding: '4px 12px', backgroundColor: activeView === 'comparison' ? colors.primary : '#2a2a2a', color: '#fff', border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '10px' }}>
COMPARE
</button>
{activeView === 'single' ? (
<>
- <div style={{ color: '#737373', fontSize: '9px', marginLeft: '8px' }}>Chart Type:</div>
+ <div style={{ color: colors.textMuted, fontSize: '9px', marginLeft: '8px' }}>Chart Type:</div>
{(['line', 'bar', 'area', 'scatter', 'candlestick'] as ChartType[]).map(type => (
- <button key={type} onClick={() => setSingleChartType(type)} style={{ padding: '3px 8px', backgroundColor: singleChartType === type ? '#3b82f6' : '#2d2d2d', color: '#fff', border: '1px solid #404040', cursor: 'pointer', fontSize: '9px', textTransform: 'uppercase' }}>
+ <button key={type} onClick={() => setSingleChartType(type)} style={{ padding: '3px 8px', backgroundColor: singleChartType === type ? colors.info : '#2a2a2a', color: '#fff', border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '9px', textTransform: 'uppercase' }}>
{type}
</button>
))}
@@ -705,12 +707,12 @@ export default function DBnomicsTab() {
{activeView === 'single' ? (
<div>
<div style={{ marginBottom: '12px' }}>
- <div style={{ color: '#ea580c', fontSize: '11px', marginBottom: '6px' }}>SINGLE VIEW ({singleViewSeries.length} series)</div>
+ <div style={{ color: colors.primary, fontSize: '11px', marginBottom: '6px' }}>SINGLE VIEW ({singleViewSeries.length} series)</div>
{singleViewSeries.map((s, idx) => (
- <div key={idx} style={{ display: 'inline-flex', alignItems: 'center', gap: '4px', padding: '3px 6px', backgroundColor: '#1a1a1a', border: '1px solid #404040', borderRadius: '2px', marginRight: '4px', marginBottom: '4px', fontSize: '9px' }}>
+ <div key={idx} style={{ display: 'inline-flex', alignItems: 'center', gap: '4px', padding: '3px 6px', backgroundColor: '#1a1a1a', border: '1px solid colors.textMuted', borderRadius: '2px', marginRight: '4px', marginBottom: '4px', fontSize: '9px' }}>
<div style={{ width: '8px', height: '8px', backgroundColor: s.color, borderRadius: '50%' }}></div>
<span>{s.series_name.substring(0, 20)}</span>
- <button onClick={() => removeFromSingleView(idx)} style={{ padding: '0 4px', backgroundColor: 'transparent', color: '#ef4444', border: 'none', cursor: 'pointer', fontSize: '10px' }}>×</button>
+ <button onClick={() => removeFromSingleView(idx)} style={{ padding: '0 4px', backgroundColor: 'transparent', color: colors.alert, border: 'none', cursor: 'pointer', fontSize: '10px' }}>×</button>
</div>
))}
</div>
@@ -721,12 +723,12 @@ export default function DBnomicsTab() {
{/* Data Table */}
<div style={{ marginTop: '24px' }}>
- <div style={{ color: '#ea580c', fontSize: '11px', marginBottom: '8px' }}>DATA TABLE</div>
- <div style={{ overflowX: 'auto', overflowY: 'auto', maxHeight: '300px', border: '1px solid #404040', backgroundColor: '#0a0a0a' }}>
+ <div style={{ color: colors.primary, fontSize: '11px', marginBottom: '8px' }}>DATA TABLE</div>
+ <div style={{ overflowX: 'auto', overflowY: 'auto', maxHeight: '300px', border: '1px solid colors.textMuted', backgroundColor: colors.panel }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>
<thead style={{ position: 'sticky', top: 0, backgroundColor: '#1a1a1a', zIndex: 1 }}>
- <tr style={{ borderBottom: '2px solid #404040' }}>
- <th style={{ padding: '8px 12px', textAlign: 'left', color: '#ea580c', fontWeight: 'bold', whiteSpace: 'nowrap' }}>Period</th>
+ <tr style={{ borderBottom: '2px solid colors.textMuted' }}>
+ <th style={{ padding: '8px 12px', textAlign: 'left', color: colors.primary, fontWeight: 'bold', whiteSpace: 'nowrap' }}>Period</th>
{singleViewSeries.map((series, idx) => (
<th key={idx} style={{ padding: '8px 12px', textAlign: 'right', fontWeight: 'bold', whiteSpace: 'nowrap' }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '6px' }}>
@@ -746,12 +748,12 @@ export default function DBnomicsTab() {
return allPeriods.slice(0, 50).map((period, idx) => (
<tr key={idx} style={{ borderBottom: '1px solid #1a1a1a' }}>
- <td style={{ padding: '6px 12px', color: '#d4d4d4', whiteSpace: 'nowrap', fontWeight: 'bold' }}>{period}</td>
+ <td style={{ padding: '6px 12px', color: colors.text, whiteSpace: 'nowrap', fontWeight: 'bold' }}>{period}</td>
{singleViewSeries.map((series, sIdx) => {
const obs = series.observations.find(o => o.period === period);
const value = obs ? (typeof obs.value === 'number' ? obs.value : Number(obs.value)) : null;
return (
- <td key={sIdx} style={{ padding: '6px 12px', textAlign: 'right', color: value !== null ? '#a3a3a3' : '#404040', whiteSpace: 'nowrap' }}>
+ <td key={sIdx} style={{ padding: '6px 12px', textAlign: 'right', color: value !== null ? '#a3a3a3' : colors.textMuted, whiteSpace: 'nowrap' }}>
{value !== null && !isNaN(value) ? value.toFixed(4) : '—'}
</td>
);
@@ -762,24 +764,24 @@ export default function DBnomicsTab() {
</tbody>
</table>
</div>
- <div style={{ color: '#737373', fontSize: '9px', marginTop: '6px', textAlign: 'right' }}>
+ <div style={{ color: colors.textMuted, fontSize: '9px', marginTop: '6px', textAlign: 'right' }}>
Showing latest 50 periods
</div>
</div>
</>
) : (
- <div style={{ color: '#737373', textAlign: 'center', paddingTop: '40px' }}>Add series to view</div>
+ <div style={{ color: colors.textMuted, textAlign: 'center', paddingTop: '40px' }}>Add series to view</div>
)}
</div>
) : (
<div>
- <div style={{ color: '#ea580c', marginBottom: '12px', fontSize: '11px' }}>COMPARISON DASHBOARD</div>
+ <div style={{ color: colors.primary, marginBottom: '12px', fontSize: '11px' }}>COMPARISON DASHBOARD</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(380px, 1fr))', gap: '16px' }}>
{slots.map((slot, idx) => (
- <div key={idx} style={{ border: '1px solid #404040', padding: '12px', backgroundColor: '#0a0a0a', minHeight: '280px', display: 'flex', flexDirection: 'column' }}>
+ <div key={idx} style={{ border: '1px solid colors.textMuted', padding: '12px', backgroundColor: colors.panel, minHeight: '280px', display: 'flex', flexDirection: 'column' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
- <div style={{ color: '#fbbf24', fontSize: '10px' }}>SLOT {idx + 1}</div>
- <select value={slotChartTypes[idx]} onChange={(e) => { const newTypes = [...slotChartTypes]; newTypes[idx] = e.target.value as ChartType; setSlotChartTypes(newTypes); }} style={{ padding: '2px 4px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', fontSize: '8px', fontFamily: 'Consolas, monospace' }}>
+ <div style={{ color: colors.warning, fontSize: '10px' }}>SLOT {idx + 1}</div>
+ <select value={slotChartTypes[idx]} onChange={(e) => { const newTypes = [...slotChartTypes]; newTypes[idx] = e.target.value as ChartType; setSlotChartTypes(newTypes); }} style={{ padding: '2px 4px', backgroundColor: '#1a1a1a', color: colors.text, border: '1px solid colors.textMuted', fontSize: '8px', fontFamily: 'Consolas, monospace' }}>
<option value="line">LINE</option>
<option value="bar">BAR</option>
<option value="area">AREA</option>
@@ -788,7 +790,7 @@ export default function DBnomicsTab() {
</select>
</div>
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '240px' }}>
- {slot.length > 0 ? renderChart(slot, slotChartTypes[idx], true) : <div style={{ color: '#404040', textAlign: 'center', fontSize: '10px' }}>Empty Slot</div>}
+ {slot.length > 0 ? renderChart(slot, slotChartTypes[idx], true) : <div style={{ color: colors.textMuted, textAlign: 'center', fontSize: '10px' }}>Empty Slot</div>}
</div>
</div>
))}
diff --git a/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx b/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx
index 2eb3810db..7a8c3f6dd 100644
--- a/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx
@@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react';
import GridLayout, { Layout } from 'react-grid-layout';
import { Plus, RotateCcw, Save } from 'lucide-react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import {
NewsWidget,
MarketDataWidget,
@@ -18,14 +19,6 @@ import { AddWidgetModal } from './dashboard/AddWidgetModal';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
-const BLOOMBERG_ORANGE = '#FFA500';
-const BLOOMBERG_WHITE = '#FFFFFF';
-const BLOOMBERG_GREEN = '#00C800';
-const BLOOMBERG_YELLOW = '#FFFF00';
-const BLOOMBERG_GRAY = '#787878';
-const BLOOMBERG_DARK_BG = '#000000';
-const BLOOMBERG_PANEL_BG = '#0a0a0a';
-
interface WidgetInstance extends WidgetConfig {
layout: Layout;
}
@@ -113,6 +106,7 @@ interface DashboardTabProps {
}
const DashboardTab: React.FC<DashboardTabProps> = ({ onNavigateToTab }) => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [widgets, setWidgets] = useState<WidgetInstance[]>([]);
const [showAddModal, setShowAddModal] = useState(false);
const [currentTime, setCurrentTime] = useState(new Date());
@@ -313,9 +307,11 @@ const DashboardTab: React.FC<DashboardTabProps> = ({ onNavigateToTab }) => {
return (
<div style={{
height: '100%',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
- fontFamily: 'Consolas, monospace',
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontFamily: fontFamily,
+ fontWeight: fontWeight,
+ fontStyle: fontStyle,
overflow: 'hidden',
display: 'flex',
flexDirection: 'column'
@@ -339,7 +335,7 @@ const DashboardTab: React.FC<DashboardTabProps> = ({ onNavigateToTab }) => {
/* Grid layout drag handle styling */
.react-grid-item.react-grid-placeholder {
- background: ${BLOOMBERG_ORANGE} !important;
+ background: ${colors.primary} !important;
opacity: 0.3;
border-radius: 4px;
}
@@ -374,33 +370,33 @@ const DashboardTab: React.FC<DashboardTabProps> = ({ onNavigateToTab }) => {
}
.react-resizable-handle::after {
- border-right: 2px solid ${BLOOMBERG_ORANGE};
- border-bottom: 2px solid ${BLOOMBERG_ORANGE};
+ border-right: 2px solid ${colors.primary};
+ border-bottom: 2px solid ${colors.primary};
}
`}</style>
{/* Header Bar */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
padding: '8px 12px',
flexShrink: 0
}}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold', fontSize: '14px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: fontSize.subheading }}>
CUSTOMIZABLE DASHBOARD
</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GREEN, fontSize: '10px' }}>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.secondary, fontSize: fontSize.small }}>
● LIVE
</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_YELLOW, fontSize: '11px' }}>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.warning, fontSize: fontSize.body }}>
{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC
</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GRAY, fontSize: '10px' }}>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted, fontSize: fontSize.small }}>
WIDGETS: {widgets.length}
</span>
</div>
@@ -409,11 +405,11 @@ const DashboardTab: React.FC<DashboardTabProps> = ({ onNavigateToTab }) => {
<button
onClick={() => setShowAddModal(true)}
style={{
- background: BLOOMBERG_GREEN,
+ background: colors.secondary,
color: 'black',
border: 'none',
padding: '6px 12px',
- fontSize: '10px',
+ fontSize: fontSize.small,
fontWeight: 'bold',
cursor: 'pointer',
display: 'flex',
@@ -428,11 +424,11 @@ const DashboardTab: React.FC<DashboardTabProps> = ({ onNavigateToTab }) => {
<button
onClick={saveLayout}
style={{
- background: BLOOMBERG_ORANGE,
+ background: colors.primary,
color: 'black',
border: 'none',
padding: '6px 12px',
- fontSize: '10px',
+ fontSize: fontSize.small,
fontWeight: 'bold',
cursor: 'pointer',
display: 'flex',
@@ -447,11 +443,11 @@ const DashboardTab: React.FC<DashboardTabProps> = ({ onNavigateToTab }) => {
<button
onClick={resetLayout}
style={{
- background: BLOOMBERG_GRAY,
+ background: colors.textMuted,
color: 'black',
border: 'none',
padding: '6px 12px',
- fontSize: '10px',
+ fontSize: fontSize.small,
fontWeight: 'bold',
cursor: 'pointer',
display: 'flex',
@@ -469,18 +465,18 @@ const DashboardTab: React.FC<DashboardTabProps> = ({ onNavigateToTab }) => {
{/* Info Bar */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
padding: '4px 12px',
- fontSize: '10px',
- color: BLOOMBERG_GRAY,
+ fontSize: fontSize.small,
+ color: colors.textMuted,
flexShrink: 0
}}>
<div style={{ display: 'flex', gap: '16px' }}>
- <span>💡 <span style={{ color: BLOOMBERG_WHITE }}>Drag widgets to rearrange</span></span>
- <span>🔧 <span style={{ color: BLOOMBERG_WHITE }}>Resize from bottom-right corner</span></span>
- <span>✖️ <span style={{ color: BLOOMBERG_WHITE }}>Remove widgets with X button</span></span>
- <span>📐 <span style={{ color: BLOOMBERG_WHITE }}>Responsive layout - uses full width</span></span>
+ <span>💡 <span style={{ color: colors.text }}>Drag widgets to rearrange</span></span>
+ <span>🔧 <span style={{ color: colors.text }}>Resize from bottom-right corner</span></span>
+ <span>✖️ <span style={{ color: colors.text }}>Remove widgets with X button</span></span>
+ <span>📐 <span style={{ color: colors.text }}>Responsive layout - uses full width</span></span>
</div>
</div>
@@ -503,17 +499,17 @@ const DashboardTab: React.FC<DashboardTabProps> = ({ onNavigateToTab }) => {
height: '100%',
gap: '16px'
}}>
- <div style={{ color: BLOOMBERG_GRAY, fontSize: '14px' }}>
+ <div style={{ color: colors.textMuted, fontSize: fontSize.subheading }}>
No widgets on dashboard
</div>
<button
onClick={() => setShowAddModal(true)}
style={{
- background: BLOOMBERG_ORANGE,
+ background: colors.primary,
color: 'black',
border: 'none',
padding: '12px 24px',
- fontSize: '12px',
+ fontSize: fontSize.body,
fontWeight: 'bold',
cursor: 'pointer',
borderRadius: '4px'
@@ -547,18 +543,18 @@ const DashboardTab: React.FC<DashboardTabProps> = ({ onNavigateToTab }) => {
{/* Status Bar */}
<div style={{
- borderTop: `1px solid ${BLOOMBERG_GRAY}`,
- backgroundColor: BLOOMBERG_PANEL_BG,
+ borderTop: `1px solid ${colors.textMuted}`,
+ backgroundColor: colors.panel,
padding: '4px 12px',
- fontSize: '9px',
- color: BLOOMBERG_GRAY,
+ fontSize: fontSize.tiny,
+ color: colors.textMuted,
flexShrink: 0
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span>Fincept Customizable Dashboard v2.0.0 | Drag & drop workspace</span>
<span>
Widgets: {widgets.length} | Layout: {widgets.length > 0 ? 'Custom' : 'Empty'} |
- Status: <span style={{ color: BLOOMBERG_GREEN }}>ACTIVE</span>
+ Status: <span style={{ color: colors.secondary }}>ACTIVE</span>
</span>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/EconomicCalendarTab.tsx b/fincept-terminal-desktop/src/components/tabs/EconomicCalendarTab.tsx
index a6cef282e..b2d77f66d 100644
--- a/fincept-terminal-desktop/src/components/tabs/EconomicCalendarTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/EconomicCalendarTab.tsx
@@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface EconomicEvent {
time: string;
@@ -14,23 +15,12 @@ interface EconomicEvent {
}
const EconomicCalendarTab: React.FC = () => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
const [selectedDate, setSelectedDate] = useState('2025-03-15');
const [selectedImportance, setSelectedImportance] = useState('ALL');
const [selectedCountry, setSelectedCountry] = useState('ALL');
- const COLOR_ORANGE = '#FFA500';
- const COLOR_WHITE = '#FFFFFF';
- const COLOR_RED = '#FF0000';
- const COLOR_GREEN = '#00C800';
- const COLOR_YELLOW = '#FFFF00';
- const COLOR_GRAY = '#787878';
- const COLOR_BLUE = '#6496FA';
- const COLOR_PURPLE = '#C864FF';
- const COLOR_CYAN = '#00FFFF';
- const COLOR_DARK_BG = '#000000';
- const COLOR_PANEL_BG = '#0a0a0a';
-
useEffect(() => {
const timer = setInterval(() => setCurrentTime(new Date()), 1000);
return () => clearInterval(timer);
@@ -206,27 +196,27 @@ const EconomicCalendarTab: React.FC = () => {
const getImportanceColor = (importance: string) => {
switch(importance) {
- case 'HIGH': return COLOR_RED;
- case 'MEDIUM': return COLOR_ORANGE;
- case 'LOW': return COLOR_YELLOW;
- default: return COLOR_GRAY;
+ case 'HIGH': return colors.alert;
+ case 'MEDIUM': return colors.primary;
+ case 'LOW': return colors.warning;
+ default: return colors.textMuted;
}
};
const getImpactColor = (impact: string) => {
switch(impact) {
- case 'POSITIVE': return COLOR_GREEN;
- case 'NEGATIVE': return COLOR_RED;
- case 'NEUTRAL': return COLOR_GRAY;
- default: return COLOR_WHITE;
+ case 'POSITIVE': return colors.secondary;
+ case 'NEGATIVE': return colors.alert;
+ case 'NEUTRAL': return colors.textMuted;
+ default: return colors.text;
}
};
return (
<div style={{
height: '100%',
- backgroundColor: COLOR_DARK_BG,
- color: COLOR_WHITE,
+ backgroundColor: colors.background,
+ color: colors.text,
fontFamily: 'Consolas, monospace',
overflow: 'hidden',
display: 'flex',
@@ -235,18 +225,18 @@ const EconomicCalendarTab: React.FC = () => {
}}>
{/* Header */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- borderBottom: `2px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `2px solid ${colors.textMuted}`,
padding: '8px 16px',
flexShrink: 0
}}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '16px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '16px' }}>
ECONOMIC CALENDAR
</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_CYAN }}>GLOBAL EVENTS • INDICATORS • CENTRAL BANKS</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.accent }}>GLOBAL EVENTS • INDICATORS • CENTRAL BANKS</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<input
@@ -254,15 +244,15 @@ const EconomicCalendarTab: React.FC = () => {
value={selectedDate}
onChange={(e) => setSelectedDate(e.target.value)}
style={{
- backgroundColor: COLOR_DARK_BG,
- color: COLOR_CYAN,
- border: `2px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.background,
+ color: colors.accent,
+ border: `2px solid ${colors.textMuted}`,
padding: '4px 8px',
fontSize: '11px',
fontFamily: 'Consolas, monospace'
}}
/>
- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>
{currentTime.toLocaleTimeString()}
</span>
</div>
@@ -275,12 +265,12 @@ const EconomicCalendarTab: React.FC = () => {
<div style={{ width: '340px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
{/* Economic Indicators */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
- borderLeft: `6px solid ${COLOR_CYAN}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
+ borderLeft: `6px solid ${colors.accent}`,
padding: '12px'
}}>
- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
KEY INDICATORS
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
@@ -288,24 +278,24 @@ const EconomicCalendarTab: React.FC = () => {
<div key={index} style={{
padding: '10px',
backgroundColor: 'rgba(255,255,255,0.02)',
- border: `1px solid ${COLOR_GRAY}`
+ border: `1px solid ${colors.textMuted}`
}}>
- <div style={{ color: COLOR_GRAY, fontSize: '10px', marginBottom: '4px' }}>
+ <div style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '4px' }}>
{indicator.name}
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <span style={{ color: COLOR_CYAN, fontSize: '16px', fontWeight: 'bold' }}>
+ <span style={{ color: colors.accent, fontSize: '16px', fontWeight: 'bold' }}>
{indicator.value}
</span>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<span style={{
- color: indicator.trend === 'up' ? COLOR_GREEN : indicator.trend === 'down' ? COLOR_RED : COLOR_GRAY,
+ color: indicator.trend === 'up' ? colors.secondary : indicator.trend === 'down' ? colors.alert : colors.textMuted,
fontSize: '12px'
}}>
{indicator.trend === 'up' ? '▲' : indicator.trend === 'down' ? '▼' : '●'}
</span>
<span style={{
- color: indicator.change > 0 ? COLOR_GREEN : indicator.change < 0 ? COLOR_RED : COLOR_GRAY,
+ color: indicator.change > 0 ? colors.secondary : indicator.change < 0 ? colors.alert : colors.textMuted,
fontSize: '11px'
}}>
{indicator.change > 0 ? '+' : ''}{indicator.change.toFixed(1)}%
@@ -319,12 +309,12 @@ const EconomicCalendarTab: React.FC = () => {
{/* Central Bank Meetings */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
- borderLeft: `6px solid ${COLOR_PURPLE}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
+ borderLeft: `6px solid ${colors.purple}`,
padding: '12px'
}}>
- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
UPCOMING CB MEETINGS
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
@@ -332,20 +322,20 @@ const EconomicCalendarTab: React.FC = () => {
<div key={index} style={{
padding: '10px',
backgroundColor: 'rgba(200,100,255,0.05)',
- border: `1px solid ${COLOR_PURPLE}`
+ border: `1px solid ${colors.purple}`
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
- <span style={{ color: COLOR_PURPLE, fontWeight: 'bold', fontSize: '12px' }}>
+ <span style={{ color: colors.purple, fontWeight: 'bold', fontSize: '12px' }}>
{meeting.bank}
</span>
- <span style={{ color: COLOR_GRAY, fontSize: '10px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '10px' }}>
{meeting.date}
</span>
</div>
- <div style={{ color: COLOR_WHITE, fontSize: '11px', marginBottom: '4px' }}>
+ <div style={{ color: colors.text, fontSize: '11px', marginBottom: '4px' }}>
{meeting.decision}
</div>
- <div style={{ color: COLOR_CYAN, fontSize: '10px' }}>
+ <div style={{ color: colors.accent, fontSize: '10px' }}>
Expected: {meeting.expected}
</div>
</div>
@@ -355,41 +345,41 @@ const EconomicCalendarTab: React.FC = () => {
{/* Impact Summary */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
- borderLeft: `6px solid ${COLOR_GREEN}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
+ borderLeft: `6px solid ${colors.secondary}`,
padding: '12px'
}}>
- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
TODAY'S IMPACT
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<div style={{
padding: '10px',
backgroundColor: 'rgba(255,0,0,0.05)',
- border: `1px solid ${COLOR_RED}`
+ border: `1px solid ${colors.alert}`
}}>
- <div style={{ color: COLOR_GRAY, fontSize: '10px', marginBottom: '4px' }}>HIGH IMPACT</div>
- <div style={{ color: COLOR_RED, fontSize: '20px', fontWeight: 'bold' }}>7</div>
- <div style={{ color: COLOR_GRAY, fontSize: '9px' }}>events scheduled</div>
+ <div style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '4px' }}>HIGH IMPACT</div>
+ <div style={{ color: colors.alert, fontSize: '20px', fontWeight: 'bold' }}>7</div>
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>events scheduled</div>
</div>
<div style={{
padding: '10px',
backgroundColor: 'rgba(255,165,0,0.05)',
- border: `1px solid ${COLOR_ORANGE}`
+ border: `1px solid ${colors.primary}`
}}>
- <div style={{ color: COLOR_GRAY, fontSize: '10px', marginBottom: '4px' }}>MEDIUM IMPACT</div>
- <div style={{ color: COLOR_ORANGE, fontSize: '20px', fontWeight: 'bold' }}>3</div>
- <div style={{ color: COLOR_GRAY, fontSize: '9px' }}>events scheduled</div>
+ <div style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '4px' }}>MEDIUM IMPACT</div>
+ <div style={{ color: colors.primary, fontSize: '20px', fontWeight: 'bold' }}>3</div>
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>events scheduled</div>
</div>
<div style={{
padding: '10px',
backgroundColor: 'rgba(255,255,0,0.05)',
- border: `1px solid ${COLOR_YELLOW}`
+ border: `1px solid ${colors.warning}`
}}>
- <div style={{ color: COLOR_GRAY, fontSize: '10px', marginBottom: '4px' }}>LOW IMPACT</div>
- <div style={{ color: COLOR_YELLOW, fontSize: '20px', fontWeight: 'bold' }}>2</div>
- <div style={{ color: COLOR_GRAY, fontSize: '9px' }}>events scheduled</div>
+ <div style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '4px' }}>LOW IMPACT</div>
+ <div style={{ color: colors.warning, fontSize: '20px', fontWeight: 'bold' }}>2</div>
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>events scheduled</div>
</div>
</div>
</div>
@@ -399,21 +389,21 @@ const EconomicCalendarTab: React.FC = () => {
<div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
{/* Filters */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
padding: '12px',
marginBottom: '12px'
}}>
<div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>IMPORTANCE:</span>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>IMPORTANCE:</span>
{['ALL', 'HIGH', 'MEDIUM', 'LOW'].map((importance) => (
<button key={importance}
onClick={() => setSelectedImportance(importance)}
style={{
padding: '6px 12px',
- backgroundColor: selectedImportance === importance ? getImportanceColor(importance) : COLOR_DARK_BG,
- border: `2px solid ${selectedImportance === importance ? getImportanceColor(importance) : COLOR_GRAY}`,
- color: selectedImportance === importance ? COLOR_DARK_BG : COLOR_WHITE,
+ backgroundColor: selectedImportance === importance ? getImportanceColor(importance) : colors.background,
+ border: `2px solid ${selectedImportance === importance ? getImportanceColor(importance) : colors.textMuted}`,
+ color: selectedImportance === importance ? colors.background : colors.text,
fontSize: '10px',
fontWeight: 'bold',
cursor: 'pointer',
@@ -422,16 +412,16 @@ const EconomicCalendarTab: React.FC = () => {
{importance}
</button>
))}
- <span style={{ color: COLOR_GRAY, marginLeft: '16px' }}>|</span>
- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>COUNTRY:</span>
+ <span style={{ color: colors.textMuted, marginLeft: '16px' }}>|</span>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>COUNTRY:</span>
{['ALL', 'US', 'EU', 'GB', 'JP', 'CN'].map((country) => (
<button key={country}
onClick={() => setSelectedCountry(country)}
style={{
padding: '6px 12px',
- backgroundColor: selectedCountry === country ? COLOR_CYAN : COLOR_DARK_BG,
- border: `2px solid ${selectedCountry === country ? COLOR_CYAN : COLOR_GRAY}`,
- color: selectedCountry === country ? COLOR_DARK_BG : COLOR_WHITE,
+ backgroundColor: selectedCountry === country ? colors.accent : colors.background,
+ border: `2px solid ${selectedCountry === country ? colors.accent : colors.textMuted}`,
+ color: selectedCountry === country ? colors.background : colors.text,
fontSize: '10px',
fontWeight: 'bold',
cursor: 'pointer',
@@ -445,8 +435,8 @@ const EconomicCalendarTab: React.FC = () => {
{/* Events Table */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
flex: 1,
overflow: 'auto'
}}>
@@ -456,19 +446,19 @@ const EconomicCalendarTab: React.FC = () => {
gridTemplateColumns: '70px 60px 280px 80px 100px 100px 100px 80px',
padding: '10px 12px',
backgroundColor: 'rgba(255,165,0,0.1)',
- borderBottom: `2px solid ${COLOR_ORANGE}`,
+ borderBottom: `2px solid ${colors.primary}`,
position: 'sticky',
top: 0,
zIndex: 10
}}>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>TIME</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>CTRY</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>INDICATOR</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>IMPACT</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>ACTUAL</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>FORECAST</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>PREVIOUS</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>RESULT</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>TIME</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>CTRY</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>INDICATOR</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>IMPACT</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>ACTUAL</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>FORECAST</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>PREVIOUS</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>RESULT</div>
</div>
{/* Table Body */}
@@ -479,7 +469,7 @@ const EconomicCalendarTab: React.FC = () => {
gridTemplateColumns: '70px 60px 280px 80px 100px 100px 100px 80px',
padding: '12px',
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- borderBottom: `1px solid ${COLOR_GRAY}`,
+ borderBottom: `1px solid ${colors.textMuted}`,
cursor: 'pointer',
fontSize: '11px'
}}
@@ -489,13 +479,13 @@ const EconomicCalendarTab: React.FC = () => {
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent';
}}>
- <div style={{ color: COLOR_CYAN, fontWeight: 'bold' }}>{event.time}</div>
+ <div style={{ color: colors.accent, fontWeight: 'bold' }}>{event.time}</div>
<div style={{ fontSize: '16px' }}>{event.flag}</div>
<div>
- <div style={{ color: COLOR_WHITE, fontWeight: 'bold', marginBottom: '2px' }}>
+ <div style={{ color: colors.text, fontWeight: 'bold', marginBottom: '2px' }}>
{event.indicator}
</div>
- <div style={{ color: COLOR_GRAY, fontSize: '9px' }}>
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>
{event.category}
</div>
</div>
@@ -511,9 +501,9 @@ const EconomicCalendarTab: React.FC = () => {
{event.importance}
</span>
</div>
- <div style={{ color: COLOR_WHITE, fontWeight: 'bold' }}>{event.actual}</div>
- <div style={{ color: COLOR_YELLOW }}>{event.forecast}</div>
- <div style={{ color: COLOR_GRAY }}>{event.previous}</div>
+ <div style={{ color: colors.text, fontWeight: 'bold' }}>{event.actual}</div>
+ <div style={{ color: colors.warning }}>{event.forecast}</div>
+ <div style={{ color: colors.textMuted }}>{event.previous}</div>
<div>
<span style={{
color: getImpactColor(event.impact),
@@ -530,24 +520,24 @@ const EconomicCalendarTab: React.FC = () => {
{/* Footer */}
<div style={{
- borderTop: `3px solid ${COLOR_ORANGE}`,
- backgroundColor: COLOR_PANEL_BG,
+ borderTop: `3px solid ${colors.primary}`,
+ backgroundColor: colors.panel,
padding: '12px 16px',
fontSize: '11px',
- color: COLOR_WHITE,
+ color: colors.text,
flexShrink: 0
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
- <span style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '13px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '13px' }}>
ECONOMIC CALENDAR v1.0
</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_CYAN }}>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.accent }}>
Real-time economic events & data
</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_GREEN }}>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.secondary }}>
Showing: {filteredEvents.length} events
</span>
</div>
@@ -557,16 +547,16 @@ const EconomicCalendarTab: React.FC = () => {
justifyContent: 'space-between',
fontSize: '10px',
paddingTop: '8px',
- borderTop: `1px solid ${COLOR_GRAY}`
+ borderTop: `1px solid ${colors.textMuted}`
}}>
<div style={{ display: 'flex', gap: '16px' }}>
- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F1</span> Help</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F2</span> Export</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F3</span> Alerts</span>
+ <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F1</span> Help</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F2</span> Export</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F3</span> Alerts</span>
</div>
- <div style={{ color: COLOR_GRAY }}>
+ <div style={{ color: colors.textMuted }}>
© 2025 Fincept Labs • All Rights Reserved
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/EconomicsTab.tsx b/fincept-terminal-desktop/src/components/tabs/EconomicsTab.tsx
index 3d94ad674..5df003064 100644
--- a/fincept-terminal-desktop/src/components/tabs/EconomicsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/EconomicsTab.tsx
@@ -1,6 +1,8 @@
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import React, { useState } from 'react';
import { RefreshCw, Download, Globe, TrendingUp, BarChart3, PieChart } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
+import bisDataService from '@/services/bisDataService';
interface Indicator {
code: string;
@@ -33,6 +35,8 @@ interface ProfileData {
}
export default function EconomicsTab() {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
+ const [dataSource, setDataSource] = useState<'econdb' | 'bis'>('econdb');
const [view, setView] = useState<'indicator' | 'profile' | 'countries'>('indicator');
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState('Ready');
@@ -43,6 +47,47 @@ export default function EconomicsTab() {
const [selectedTransform, setSelectedTransform] = useState('level');
const [indicatorData, setIndicatorData] = useState<IndicatorData | null>(null);
+ // BIS-specific state
+ const [bisDataType, setBisDataType] = useState<
+ 'policy_rates' | 'effective_exchange' | 'property_prices' | 'total_credit' |
+ 'consumer_prices' | 'credit_gap' | 'debt_service' | 'cb_assets'
+ >('policy_rates');
+ const [bisStartDate, setBisStartDate] = useState(() => {
+ const date = new Date();
+ date.setFullYear(date.getFullYear() - 1); // 1 year ago
+ return date.toISOString().split('T')[0];
+ });
+ const [bisEndDate, setBisEndDate] = useState(() => new Date().toISOString().split('T')[0]);
+
+ // BIS available countries (only major economies with data)
+ const bisCountries = [
+ { code: 'US', name: 'United States' },
+ { code: 'CN', name: 'China' },
+ { code: 'JP', name: 'Japan' },
+ { code: 'GB', name: 'United Kingdom' },
+ { code: 'IN', name: 'India' },
+ { code: 'BR', name: 'Brazil' },
+ { code: 'CA', name: 'Canada' },
+ { code: 'KR', name: 'South Korea' },
+ { code: 'RU', name: 'Russia' },
+ { code: 'AU', name: 'Australia' },
+ { code: 'MX', name: 'Mexico' },
+ { code: 'ID', name: 'Indonesia' },
+ { code: 'SA', name: 'Saudi Arabia' },
+ { code: 'TR', name: 'Turkey' },
+ { code: 'CH', name: 'Switzerland' },
+ { code: 'ZA', name: 'South Africa' },
+ { code: 'AR', name: 'Argentina' },
+ { code: 'SE', name: 'Sweden' },
+ { code: 'NO', name: 'Norway' },
+ { code: 'PL', name: 'Poland' },
+ { code: 'TH', name: 'Thailand' },
+ { code: 'MY', name: 'Malaysia' },
+ { code: 'SG', name: 'Singapore' },
+ { code: 'HK', name: 'Hong Kong' },
+ { code: 'NZ', name: 'New Zealand' },
+ ];
+
// Profile view state
const [profileCountry, setProfileCountry] = useState('US');
const [profileData, setProfileData] = useState<ProfileData | null>(null);
@@ -101,21 +146,126 @@ export default function EconomicsTab() {
const fetchIndicator = async () => {
setLoading(true);
- setStatus(`Fetching ${selectedIndicator} for ${selectedCountry}...`);
+ setStatus(`Fetching data for ${selectedCountry}...`);
try {
- const result = await invoke('execute_python_script', {
- scriptName: 'econdb_data.py',
- args: ['indicator', selectedIndicator, selectedCountry, '', '', selectedTransform]
- }) as string;
-
- const data = JSON.parse(result);
-
- if (data.error) {
- setStatus(`Error: ${data.error}`);
+ if (dataSource === 'bis') {
+ // Fetch from BIS based on selected data type with date range
+ let result;
+
+ // Map data type to BIS dataset and frequency
+ const bisDatasetMap: Record<string, { flow: string; freq: string }> = {
+ policy_rates: { flow: 'WS_CBPOL', freq: 'D' },
+ effective_exchange: { flow: 'WS_EER', freq: 'M' },
+ property_prices: { flow: 'WS_SPP', freq: 'Q' },
+ total_credit: { flow: 'WS_TC', freq: 'Q' },
+ consumer_prices: { flow: 'WS_LONG_CPI', freq: 'M' },
+ credit_gap: { flow: 'WS_CREDIT_GAP', freq: 'Q' },
+ debt_service: { flow: 'WS_DSR', freq: 'Q' },
+ cb_assets: { flow: 'WS_CBTA', freq: 'M' },
+ };
+
+ const dataset = bisDatasetMap[bisDataType];
+
+ if (bisDataType === 'policy_rates') {
+ result = await bisDataService.getCentralBankPolicyRates([selectedCountry], bisStartDate, bisEndDate);
+ } else if (bisDataType === 'effective_exchange') {
+ result = await bisDataService.getEffectiveExchangeRates([selectedCountry], bisStartDate, bisEndDate);
+ } else {
+ // Use generic get_data for other datasets
+ result = await bisDataService.getData(
+ dataset.flow,
+ `${dataset.freq}.${selectedCountry}`,
+ bisStartDate,
+ bisEndDate
+ );
+ }
+
+ if (result.success && result.data) {
+ // Transform BIS SDMX-JSON data to match indicatorData format
+ let observations: Observation[] = [];
+
+ try {
+ // BIS returns SDMX-JSON format: data.data.dataSets[0].series["0:0"].observations
+ const dataSets = result.data.data?.dataSets || [];
+ if (dataSets.length > 0) {
+ const dataSet = dataSets[0];
+ const series = dataSet.series;
+ const seriesKey = Object.keys(series || {})[0];
+
+ if (seriesKey && series[seriesKey]) {
+ const obsData = series[seriesKey].observations;
+
+ // Try to get TIME_PERIOD dimension values from structure
+ const timeDimension = result.data.structure?.dimensions?.observation?.find(
+ (d: any) => d.id === 'TIME_PERIOD'
+ );
+ const timeValues = timeDimension?.values || [];
+
+ // Convert SDMX observations to our format
+ observations = Object.entries(obsData || {}).map(([index, value]: [string, any]) => {
+ const timeIndex = parseInt(index);
+ let dateValue: string;
+
+ // Use TIME_PERIOD values if available, otherwise generate from reportingBegin
+ if (timeValues.length > timeIndex) {
+ dateValue = timeValues[timeIndex].id || timeValues[timeIndex].name;
+ } else {
+ // Fallback: generate date from reportingBegin
+ const reportingBegin = dataSet.reportingBegin || '2020-01-01';
+ const startDate = new Date(reportingBegin.split('T')[0]);
+ const obsDate = new Date(startDate);
+ obsDate.setDate(obsDate.getDate() + timeIndex);
+ dateValue = obsDate.toISOString().split('T')[0];
+ }
+
+ const numValue = Array.isArray(value) ? parseFloat(value[0]) : parseFloat(value);
+
+ return {
+ date: dateValue,
+ value: isNaN(numValue) ? 0 : numValue
+ };
+ });
+ }
+ }
+ } catch (parseError) {
+ console.error('Error parsing BIS data:', parseError);
+ setStatus(`Error parsing BIS data: ${parseError}`);
+ return;
+ }
+
+ if (observations.length === 0) {
+ setStatus('No observations found in BIS data');
+ return;
+ }
+
+ setIndicatorData({
+ indicator: bisDataType,
+ country: selectedCountry,
+ transform: 'level',
+ observations: observations,
+ observation_count: observations.length,
+ metadata: result.data
+ });
+ setStatus(`Loaded ${observations.length} observations from BIS`);
+ } else {
+ setStatus(`Error: ${result.error || 'Failed to fetch BIS data'}`);
+ }
} else {
- setIndicatorData(data);
- setStatus(`Loaded ${data.observation_count} observations`);
+ // Fetch from EconDB
+ const result = await invoke('execute_python_script', {
+ scriptName: 'econdb_data.py',
+ args: ['indicator', selectedIndicator, selectedCountry, '', '', selectedTransform]
+ }) as string;
+
+ const data = JSON.parse(result);
+
+ if (data.error) {
+ setStatus(`Error: ${data.error}`);
+ } else {
+ setIndicatorData(data);
+ setStatus(`Loaded ${data.observation_count} observations from EconDB`);
+ }
}
} catch (error) {
setStatus(`Error: ${error}`);
@@ -185,7 +335,7 @@ export default function EconomicsTab() {
const yRange = yMax - yMin;
return (
- <svg width={w} height={h} style={{ backgroundColor: '#0a0a0a', width: '100%', height: 'auto' }}>
+ <svg width={w} height={h} style={{ backgroundColor: 'colors.panel', width: '100%', height: 'auto' }}>
{/* Axes */}
<line x1={ml} y1={mt} x2={ml} y2={h - mb} stroke="#404040" strokeWidth="1" />
<line x1={ml} y1={h - mb} x2={w - mr} y2={h - mb} stroke="#404040" strokeWidth="1" />
@@ -241,19 +391,52 @@ export default function EconomicsTab() {
};
return (
- <div style={{ width: '100%', height: '100%', backgroundColor: '#000', color: '#d4d4d4', fontFamily: 'Consolas, monospace', fontSize: '11px', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ <div style={{ width: '100%', height: '100%', backgroundColor: 'colors.background', color: '#d4d4d4', fontFamily: 'Consolas, monospace', fontSize: '11px', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
{/* Header */}
<div style={{ padding: '8px 12px', borderBottom: '1px solid #404040', display: 'flex', alignItems: 'center', gap: '12px', flexShrink: 0 }}>
- <span style={{ color: '#ea580c', fontWeight: 'bold' }}>ECONOMICS - ECONDB</span>
+ <span style={{ color: '#ea580c', fontWeight: 'bold' }}>ECONOMICS - {dataSource.toUpperCase()}</span>
<span style={{ color: '#10b981', fontSize: '10px' }}>● {status}</span>
<div style={{ flex: 1 }}></div>
- <button onClick={() => setView('indicator')} style={{ padding: '4px 10px', backgroundColor: view === 'indicator' ? '#ea580c' : '#2d2d2d', color: '#fff', border: 'none', cursor: 'pointer', fontSize: '9px' }}>
+
+ {/* Data Source Toggle */}
+ <div style={{ display: 'flex', gap: '4px', marginRight: '12px' }}>
+ <button
+ onClick={() => setDataSource('econdb')}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: dataSource === 'econdb' ? '#3b82f6' : '#2d2d2d',
+ color: colors.text,
+ border: 'none',
+ cursor: 'pointer',
+ fontSize: '9px',
+ borderRadius: '2px'
+ }}
+ >
+ EconDB
+ </button>
+ <button
+ onClick={() => setDataSource('bis')}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: dataSource === 'bis' ? '#3b82f6' : '#2d2d2d',
+ color: colors.text,
+ border: 'none',
+ cursor: 'pointer',
+ fontSize: '9px',
+ borderRadius: '2px'
+ }}
+ >
+ BIS
+ </button>
+ </div>
+
+ <button onClick={() => setView('indicator')} style={{ padding: '4px 10px', backgroundColor: view === 'indicator' ? '#ea580c' : '#2d2d2d', color: 'colors.text', border: 'none', cursor: 'pointer', fontSize: '9px' }}>
<BarChart3 size={10} style={{ display: 'inline', marginRight: '4px' }} />INDICATOR
</button>
- <button onClick={() => setView('profile')} style={{ padding: '4px 10px', backgroundColor: view === 'profile' ? '#ea580c' : '#2d2d2d', color: '#fff', border: 'none', cursor: 'pointer', fontSize: '9px' }}>
+ <button onClick={() => setView('profile')} style={{ padding: '4px 10px', backgroundColor: view === 'profile' ? '#ea580c' : '#2d2d2d', color: 'colors.text', border: 'none', cursor: 'pointer', fontSize: '9px' }}>
<PieChart size={10} style={{ display: 'inline', marginRight: '4px' }} />PROFILE
</button>
- <button onClick={() => setView('countries')} style={{ padding: '4px 10px', backgroundColor: view === 'countries' ? '#ea580c' : '#2d2d2d', color: '#fff', border: 'none', cursor: 'pointer', fontSize: '9px' }}>
+ <button onClick={() => setView('countries')} style={{ padding: '4px 10px', backgroundColor: view === 'countries' ? '#ea580c' : '#2d2d2d', color: 'colors.text', border: 'none', cursor: 'pointer', fontSize: '9px' }}>
<Globe size={10} style={{ display: 'inline', marginRight: '4px' }} />COUNTRIES
</button>
</div>
@@ -261,31 +444,87 @@ export default function EconomicsTab() {
{/* Main Content */}
<div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
{/* Left Panel - Controls */}
- <div style={{ width: '300px', borderRight: '1px solid #404040', display: 'flex', flexDirection: 'column', backgroundColor: '#0a0a0a', overflowY: 'auto' }}>
+ <div style={{ width: '300px', borderRight: '1px solid #404040', display: 'flex', flexDirection: 'column', backgroundColor: 'colors.panel', overflowY: 'auto' }}>
{view === 'indicator' && (
<div style={{ padding: '12px' }}>
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>INDICATOR</div>
- <select value={selectedIndicator} onChange={(e) => setSelectedIndicator(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>
- {indicators.map(ind => (
- <option key={ind.code} value={ind.code}>{ind.name}</option>
- ))}
- </select>
-
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>COUNTRY</div>
- <select value={selectedCountry} onChange={(e) => setSelectedCountry(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>
- {countries.map(c => (
- <option key={c.code} value={c.code}>{c.name}</option>
- ))}
- </select>
-
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>TRANSFORM</div>
- <select value={selectedTransform} onChange={(e) => setSelectedTransform(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '16px', fontSize: '10px' }}>
- {transforms.map(t => (
- <option key={t.code} value={t.code}>{t.name}</option>
- ))}
- </select>
+ {dataSource === 'bis' ? (
+ <>
+ {/* BIS-specific controls */}
+ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>BIS DATA TYPE</div>
+ <select value={bisDataType} onChange={(e) => setBisDataType(e.target.value as any)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>
+ <optgroup label="Interest Rates & FX">
+ <option value="policy_rates">Central Bank Policy Rates (Daily)</option>
+ <option value="effective_exchange">Effective Exchange Rates (Monthly)</option>
+ </optgroup>
+ <optgroup label="Property & Credit">
+ <option value="property_prices">Property Prices (Quarterly)</option>
+ <option value="total_credit">Total Credit (Quarterly)</option>
+ <option value="credit_gap">Credit-to-GDP Gaps (Quarterly)</option>
+ <option value="debt_service">Debt Service Ratios (Quarterly)</option>
+ </optgroup>
+ <optgroup label="Other Indicators">
+ <option value="consumer_prices">Consumer Prices (Monthly)</option>
+ <option value="cb_assets">Central Bank Assets (Monthly)</option>
+ </optgroup>
+ </select>
+
+ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>COUNTRY (G20 + Major Economies)</div>
+ <select value={selectedCountry} onChange={(e) => setSelectedCountry(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>
+ {bisCountries.map(c => (
+ <option key={c.code} value={c.code}>{c.name}</option>
+ ))}
+ </select>
+
+ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>START DATE</div>
+ <input
+ type="date"
+ value={bisStartDate}
+ onChange={(e) => setBisStartDate(e.target.value)}
+ style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}
+ />
+
+ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>END DATE</div>
+ <input
+ type="date"
+ value={bisEndDate}
+ onChange={(e) => setBisEndDate(e.target.value)}
+ style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}
+ />
+
+ <div style={{ padding: '8px', backgroundColor: '#1a1a1a', border: '1px solid #404040', fontSize: '9px', marginBottom: '12px' }}>
+ <div style={{ color: '#3b82f6', marginBottom: '4px' }}>ℹ️ BIS Data Info</div>
+ <div style={{ color: '#737373', lineHeight: '1.4' }}>
+ Limit date range to avoid slow loading. Recommended: 1-2 years max.
+ </div>
+ </div>
+ </>
+ ) : (
+ <>
+ {/* EconDB controls */}
+ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>INDICATOR</div>
+ <select value={selectedIndicator} onChange={(e) => setSelectedIndicator(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>
+ {indicators.map(ind => (
+ <option key={ind.code} value={ind.code}>{ind.name}</option>
+ ))}
+ </select>
+
+ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>COUNTRY</div>
+ <select value={selectedCountry} onChange={(e) => setSelectedCountry(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>
+ {countries.map(c => (
+ <option key={c.code} value={c.code}>{c.name}</option>
+ ))}
+ </select>
+
+ <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>TRANSFORM</div>
+ <select value={selectedTransform} onChange={(e) => setSelectedTransform(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '16px', fontSize: '10px' }}>
+ {transforms.map(t => (
+ <option key={t.code} value={t.code}>{t.name}</option>
+ ))}
+ </select>
+ </>
+ )}
- <button onClick={fetchIndicator} disabled={loading} style={{ width: '100%', padding: '8px', backgroundColor: '#ea580c', color: '#fff', border: 'none', cursor: loading ? 'not-allowed' : 'pointer', fontSize: '10px', marginBottom: '8px' }}>
+ <button onClick={fetchIndicator} disabled={loading} style={{ width: '100%', padding: '8px', backgroundColor: '#ea580c', color: 'colors.text', border: 'none', cursor: loading ? 'not-allowed' : 'pointer', fontSize: '10px', marginBottom: '8px' }}>
{loading ? 'Loading...' : 'FETCH DATA'}
</button>
@@ -314,7 +553,7 @@ export default function EconomicsTab() {
))}
</select>
- <button onClick={fetchProfile} disabled={loading} style={{ width: '100%', padding: '8px', backgroundColor: '#ea580c', color: '#fff', border: 'none', cursor: loading ? 'not-allowed' : 'pointer', fontSize: '10px' }}>
+ <button onClick={fetchProfile} disabled={loading} style={{ width: '100%', padding: '8px', backgroundColor: '#ea580c', color: 'colors.text', border: 'none', cursor: loading ? 'not-allowed' : 'pointer', fontSize: '10px' }}>
{loading ? 'Loading...' : 'LOAD PROFILE'}
</button>
</div>
@@ -350,7 +589,7 @@ export default function EconomicsTab() {
<div style={{ marginTop: '24px' }}>
<div style={{ color: '#ea580c', fontSize: '11px', marginBottom: '8px' }}>DATA TABLE</div>
- <div style={{ maxHeight: '400px', overflowY: 'auto', border: '1px solid #404040', backgroundColor: '#0a0a0a' }}>
+ <div style={{ maxHeight: '400px', overflowY: 'auto', border: '1px solid #404040', backgroundColor: 'colors.panel' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>
<thead style={{ position: 'sticky', top: 0, backgroundColor: '#1a1a1a' }}>
<tr>
@@ -379,9 +618,9 @@ export default function EconomicsTab() {
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '12px' }}>
{Object.entries(profileData.indicators).map(([name, data]) => (
- <div key={name} style={{ padding: '12px', backgroundColor: '#0a0a0a', border: '1px solid #404040' }}>
+ <div key={name} style={{ padding: '12px', backgroundColor: 'colors.panel', border: '1px solid #404040' }}>
<div style={{ color: '#fbbf24', fontSize: '10px', marginBottom: '8px' }}>{name}</div>
- <div style={{ color: '#fff', fontSize: '20px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: 'colors.text', fontSize: '20px', fontWeight: 'bold', marginBottom: '4px' }}>
{typeof data.value === 'number' ? data.value.toFixed(4) : data.value}
</div>
<div style={{ color: '#737373', fontSize: '9px' }}>{data.date}</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
index 8ae0e9d40..31f0fad8c 100644
--- a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
@@ -1,18 +1,19 @@
import React, { useState, useEffect, useRef } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { invoke } from '@tauri-apps/api/core';
import { createChart, CandlestickSeries, HistogramSeries, LineSeries, BarSeries } from 'lightweight-charts';
const COLORS = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- RED: '#FF0000',
- GREEN: '#00C800',
- YELLOW: '#FFFF00',
- GRAY: '#787878',
- BLUE: '#6496FA',
- CYAN: '#00FFFF',
- DARK_BG: '#000000',
- PANEL_BG: '#0a0a0a',
+ ORANGE: 'colors.primary',
+ WHITE: 'colors.text',
+ RED: 'colors.alert',
+ GREEN: 'colors.secondary',
+ YELLOW: 'colors.warning',
+ GRAY: 'colors.textMuted',
+ BLUE: 'colors.info',
+ CYAN: 'colors.accent',
+ DARK_BG: 'colors.background',
+ PANEL_BG: 'colors.panel',
BORDER: '#333333',
MAGENTA: '#FF00FF',
PURPLE: '#9D4EDD',
@@ -104,6 +105,7 @@ interface FinancialsData {
}
const EquityResearchTab: React.FC = () => {
+ const { colors, fontSize: themeFontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [searchSymbol, setSearchSymbol] = useState('');
const [currentSymbol, setCurrentSymbol] = useState('AAPL');
const [stockInfo, setStockInfo] = useState<StockInfo | null>(null);
diff --git a/fincept-terminal-desktop/src/components/tabs/FixedIncomeTab.tsx b/fincept-terminal-desktop/src/components/tabs/FixedIncomeTab.tsx
index a6be53533..ad8a644e1 100644
--- a/fincept-terminal-desktop/src/components/tabs/FixedIncomeTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/FixedIncomeTab.tsx
@@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface Bond {
ticker: string;
@@ -19,22 +20,11 @@ interface Bond {
}
const FixedIncomeTab: React.FC = () => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
const [selectedType, setSelectedType] = useState('ALL');
const [selectedRating, setSelectedRating] = useState('ALL');
- const COLOR_ORANGE = '#FFA500';
- const COLOR_WHITE = '#FFFFFF';
- const COLOR_RED = '#FF0000';
- const COLOR_GREEN = '#00C800';
- const COLOR_YELLOW = '#FFFF00';
- const COLOR_GRAY = '#787878';
- const COLOR_BLUE = '#6496FA';
- const COLOR_PURPLE = '#C864FF';
- const COLOR_CYAN = '#00FFFF';
- const COLOR_DARK_BG = '#000000';
- const COLOR_PANEL_BG = '#0a0a0a';
-
useEffect(() => {
const timer = setInterval(() => setCurrentTime(new Date()), 1000);
return () => clearInterval(timer);
@@ -200,27 +190,27 @@ const FixedIncomeTab: React.FC = () => {
const getTypeColor = (type: string) => {
switch(type) {
- case 'TREASURY': return COLOR_BLUE;
- case 'CORPORATE': return COLOR_GREEN;
- case 'MUNICIPAL': return COLOR_PURPLE;
- case 'AGENCY': return COLOR_CYAN;
- default: return COLOR_WHITE;
+ case 'TREASURY': return colors.info;
+ case 'CORPORATE': return colors.secondary;
+ case 'MUNICIPAL': return colors.purple;
+ case 'AGENCY': return colors.accent;
+ default: return colors.text;
}
};
const getRatingColor = (rating: string) => {
- if (rating.startsWith('AA')) return COLOR_GREEN;
- if (rating.startsWith('A')) return COLOR_CYAN;
- if (rating.startsWith('BB')) return COLOR_YELLOW;
- if (rating.startsWith('B')) return COLOR_ORANGE;
- return COLOR_RED;
+ if (rating.startsWith('AA')) return colors.secondary;
+ if (rating.startsWith('A')) return colors.accent;
+ if (rating.startsWith('BB')) return colors.warning;
+ if (rating.startsWith('B')) return colors.primary;
+ return colors.alert;
};
return (
<div style={{
height: '100%',
- backgroundColor: COLOR_DARK_BG,
- color: COLOR_WHITE,
+ backgroundColor: colors.background,
+ color: colors.text,
fontFamily: 'Consolas, monospace',
overflow: 'hidden',
display: 'flex',
@@ -229,21 +219,21 @@ const FixedIncomeTab: React.FC = () => {
}}>
{/* Header */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- borderBottom: `2px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `2px solid ${colors.textMuted}`,
padding: '8px 16px',
flexShrink: 0
}}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '16px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '16px' }}>
FIXED INCOME MARKETS
</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_CYAN }}>US TREASURIES • CORPORATES • CREDIT</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.accent }}>US TREASURIES • CORPORATES • CREDIT</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>
LAST UPDATE: {currentTime.toLocaleTimeString()}
</span>
</div>
@@ -256,12 +246,12 @@ const FixedIncomeTab: React.FC = () => {
<div style={{ width: '320px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
{/* Yield Curve */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
- borderLeft: `6px solid ${COLOR_BLUE}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
+ borderLeft: `6px solid ${colors.info}`,
padding: '12px'
}}>
- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
US TREASURY YIELD CURVE
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
@@ -274,17 +264,17 @@ const FixedIncomeTab: React.FC = () => {
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <span style={{ color: COLOR_GRAY, fontSize: '11px', width: '60px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '11px', width: '60px' }}>
{point.label}
</span>
<div style={{
width: `${point.yield * 15}px`,
height: '16px',
- backgroundColor: COLOR_BLUE,
+ backgroundColor: colors.info,
opacity: 0.7
}} />
</div>
- <span style={{ color: COLOR_CYAN, fontSize: '12px', fontWeight: 'bold' }}>
+ <span style={{ color: colors.accent, fontSize: '12px', fontWeight: 'bold' }}>
{point.yield.toFixed(3)}%
</span>
</div>
@@ -294,12 +284,12 @@ const FixedIncomeTab: React.FC = () => {
{/* Credit Spreads */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
- borderLeft: `6px solid ${COLOR_YELLOW}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
+ borderLeft: `6px solid ${colors.warning}`,
padding: '12px'
}}>
- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
CREDIT SPREADS (OAS)
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
@@ -307,17 +297,17 @@ const FixedIncomeTab: React.FC = () => {
<div key={index} style={{
padding: '8px',
backgroundColor: 'rgba(255,255,255,0.02)',
- border: `1px solid ${COLOR_GRAY}`
+ border: `1px solid ${colors.textMuted}`
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
<span style={{ color: getRatingColor(spread.rating), fontWeight: 'bold', fontSize: '11px' }}>
{spread.rating}
</span>
- <span style={{ color: COLOR_CYAN, fontWeight: 'bold', fontSize: '11px' }}>
+ <span style={{ color: colors.accent, fontWeight: 'bold', fontSize: '11px' }}>
{spread.spread} bps
</span>
</div>
- <div style={{ fontSize: '10px', color: spread.change > 0 ? COLOR_RED : COLOR_GREEN }}>
+ <div style={{ fontSize: '10px', color: spread.change > 0 ? colors.alert : colors.secondary }}>
{spread.change > 0 ? '▲' : '▼'} {Math.abs(spread.change)} bps
</div>
</div>
@@ -327,30 +317,30 @@ const FixedIncomeTab: React.FC = () => {
{/* Key Metrics */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
- borderLeft: `6px solid ${COLOR_GREEN}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
+ borderLeft: `6px solid ${colors.secondary}`,
padding: '12px'
}}>
- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
KEY METRICS
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px', fontSize: '11px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: COLOR_GRAY }}>10Y-2Y Spread:</span>
- <span style={{ color: COLOR_CYAN, fontWeight: 'bold' }}>78 bps</span>
+ <span style={{ color: colors.textMuted }}>10Y-2Y Spread:</span>
+ <span style={{ color: colors.accent, fontWeight: 'bold' }}>78 bps</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: COLOR_GRAY }}>Fed Funds Rate:</span>
- <span style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>5.50%</span>
+ <span style={{ color: colors.textMuted }}>Fed Funds Rate:</span>
+ <span style={{ color: colors.secondary, fontWeight: 'bold' }}>5.50%</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: COLOR_GRAY }}>Inflation (CPI):</span>
- <span style={{ color: COLOR_YELLOW, fontWeight: 'bold' }}>3.2%</span>
+ <span style={{ color: colors.textMuted }}>Inflation (CPI):</span>
+ <span style={{ color: colors.warning, fontWeight: 'bold' }}>3.2%</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: COLOR_GRAY }}>Real Yield (10Y):</span>
- <span style={{ color: COLOR_PURPLE, fontWeight: 'bold' }}>1.03%</span>
+ <span style={{ color: colors.textMuted }}>Real Yield (10Y):</span>
+ <span style={{ color: colors.purple, fontWeight: 'bold' }}>1.03%</span>
</div>
</div>
</div>
@@ -360,21 +350,21 @@ const FixedIncomeTab: React.FC = () => {
<div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
{/* Filters */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
padding: '12px',
marginBottom: '12px'
}}>
<div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>TYPE:</span>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>TYPE:</span>
{['ALL', 'TREASURY', 'CORPORATE', 'MUNICIPAL', 'AGENCY'].map((type) => (
<button key={type}
onClick={() => setSelectedType(type)}
style={{
padding: '6px 12px',
- backgroundColor: selectedType === type ? COLOR_ORANGE : COLOR_DARK_BG,
- border: `2px solid ${selectedType === type ? COLOR_ORANGE : COLOR_GRAY}`,
- color: selectedType === type ? COLOR_DARK_BG : COLOR_WHITE,
+ backgroundColor: selectedType === type ? colors.primary : colors.background,
+ border: `2px solid ${selectedType === type ? colors.primary : colors.textMuted}`,
+ color: selectedType === type ? colors.background : colors.text,
fontSize: '10px',
fontWeight: 'bold',
cursor: 'pointer',
@@ -383,16 +373,16 @@ const FixedIncomeTab: React.FC = () => {
{type}
</button>
))}
- <span style={{ color: COLOR_GRAY, marginLeft: '16px' }}>|</span>
- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>RATING:</span>
+ <span style={{ color: colors.textMuted, marginLeft: '16px' }}>|</span>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>RATING:</span>
{['ALL', 'AAA', 'AA', 'A', 'BBB', 'BB'].map((rating) => (
<button key={rating}
onClick={() => setSelectedRating(rating)}
style={{
padding: '6px 12px',
- backgroundColor: selectedRating === rating ? COLOR_CYAN : COLOR_DARK_BG,
- border: `2px solid ${selectedRating === rating ? COLOR_CYAN : COLOR_GRAY}`,
- color: selectedRating === rating ? COLOR_DARK_BG : COLOR_WHITE,
+ backgroundColor: selectedRating === rating ? colors.accent : colors.background,
+ border: `2px solid ${selectedRating === rating ? colors.accent : colors.textMuted}`,
+ color: selectedRating === rating ? colors.background : colors.text,
fontSize: '10px',
fontWeight: 'bold',
cursor: 'pointer',
@@ -406,8 +396,8 @@ const FixedIncomeTab: React.FC = () => {
{/* Bond Table */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
flex: 1,
overflow: 'auto'
}}>
@@ -417,21 +407,21 @@ const FixedIncomeTab: React.FC = () => {
gridTemplateColumns: '100px 180px 80px 100px 80px 80px 70px 60px 80px 80px',
padding: '10px 12px',
backgroundColor: 'rgba(255,165,0,0.1)',
- borderBottom: `2px solid ${COLOR_ORANGE}`,
+ borderBottom: `2px solid ${colors.primary}`,
position: 'sticky',
top: 0,
zIndex: 10
}}>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>TICKER</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>ISSUER</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>COUPON</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>MATURITY</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>YIELD</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>PRICE</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>RATING</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>DUR</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>SPREAD</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '10px' }}>VOLUME</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>TICKER</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>ISSUER</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>COUPON</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>MATURITY</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>YIELD</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>PRICE</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>RATING</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>DUR</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>SPREAD</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>VOLUME</div>
</div>
{/* Table Body */}
@@ -442,7 +432,7 @@ const FixedIncomeTab: React.FC = () => {
gridTemplateColumns: '100px 180px 80px 100px 80px 80px 70px 60px 80px 80px',
padding: '10px 12px',
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- borderBottom: `1px solid ${COLOR_GRAY}`,
+ borderBottom: `1px solid ${colors.textMuted}`,
cursor: 'pointer',
fontSize: '11px'
}}
@@ -453,22 +443,22 @@ const FixedIncomeTab: React.FC = () => {
e.currentTarget.style.backgroundColor = index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent';
}}>
<div style={{ color: getTypeColor(bond.type), fontWeight: 'bold' }}>{bond.ticker}</div>
- <div style={{ color: COLOR_WHITE }}>{bond.issuer}</div>
- <div style={{ color: COLOR_CYAN }}>{bond.coupon.toFixed(3)}%</div>
- <div style={{ color: COLOR_GRAY }}>{bond.maturity}</div>
+ <div style={{ color: colors.text }}>{bond.issuer}</div>
+ <div style={{ color: colors.accent }}>{bond.coupon.toFixed(3)}%</div>
+ <div style={{ color: colors.textMuted }}>{bond.maturity}</div>
<div>
- <div style={{ color: COLOR_YELLOW, fontWeight: 'bold' }}>{bond.yield.toFixed(3)}%</div>
- <div style={{ color: bond.yieldChange > 0 ? COLOR_RED : COLOR_GREEN, fontSize: '9px' }}>
+ <div style={{ color: colors.warning, fontWeight: 'bold' }}>{bond.yield.toFixed(3)}%</div>
+ <div style={{ color: bond.yieldChange > 0 ? colors.alert : colors.secondary, fontSize: '9px' }}>
{bond.yieldChange > 0 ? '▲' : '▼'} {Math.abs(bond.yieldChange).toFixed(3)}%
</div>
</div>
- <div style={{ color: COLOR_WHITE }}>{bond.price.toFixed(2)}</div>
+ <div style={{ color: colors.text }}>{bond.price.toFixed(2)}</div>
<div style={{ color: getRatingColor(bond.rating), fontWeight: 'bold' }}>{bond.rating}</div>
- <div style={{ color: COLOR_PURPLE }}>{bond.duration.toFixed(1)}</div>
- <div style={{ color: bond.spread > 150 ? COLOR_RED : COLOR_GREEN }}>
+ <div style={{ color: colors.purple }}>{bond.duration.toFixed(1)}</div>
+ <div style={{ color: bond.spread > 150 ? colors.alert : colors.secondary }}>
{bond.spread > 0 ? `+${bond.spread}` : '-'}
</div>
- <div style={{ color: COLOR_GRAY }}>{bond.volume}</div>
+ <div style={{ color: colors.textMuted }}>{bond.volume}</div>
</div>
))}
</div>
@@ -477,24 +467,24 @@ const FixedIncomeTab: React.FC = () => {
{/* Footer */}
<div style={{
- borderTop: `3px solid ${COLOR_ORANGE}`,
- backgroundColor: COLOR_PANEL_BG,
+ borderTop: `3px solid ${colors.primary}`,
+ backgroundColor: colors.panel,
padding: '12px 16px',
fontSize: '11px',
- color: COLOR_WHITE,
+ color: colors.text,
flexShrink: 0
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
- <span style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '13px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '13px' }}>
FIXED INCOME v1.0
</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_CYAN }}>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.accent }}>
Real-time bond prices & yields
</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_GREEN }}>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.secondary }}>
Showing: {filteredBonds.length} bonds
</span>
</div>
@@ -504,16 +494,16 @@ const FixedIncomeTab: React.FC = () => {
justifyContent: 'space-between',
fontSize: '10px',
paddingTop: '8px',
- borderTop: `1px solid ${COLOR_GRAY}`
+ borderTop: `1px solid ${colors.textMuted}`
}}>
<div style={{ display: 'flex', gap: '16px' }}>
- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F1</span> Help</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F2</span> Export</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F3</span> Calculator</span>
+ <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F1</span> Help</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F2</span> Export</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F3</span> Calculator</span>
</div>
- <div style={{ color: COLOR_GRAY }}>
+ <div style={{ color: colors.textMuted }}>
© 2025 Fincept Labs • All Rights Reserved
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx b/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx
index 483f43f25..da960701f 100644
--- a/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx
@@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { useAuth } from '../../contexts/AuthContext';
import { ForumApiService, ForumPost as APIForumPost, ForumCategory, ForumStats, ForumComment as APIForumComment } from '../../services/forumApi';
@@ -38,6 +39,7 @@ interface ForumUser {
}
const ForumTab: React.FC = () => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const { session } = useAuth();
const [currentTime, setCurrentTime] = useState(new Date());
const [activeCategory, setActiveCategory] = useState('ALL');
@@ -69,7 +71,7 @@ const ForumTab: React.FC = () => {
const [profileEdit, setProfileEdit] = useState({
display_name: '',
bio: '',
- avatar_color: '#FFA500',
+ avatar_color: 'colors.primary',
signature: ''
});
@@ -81,17 +83,17 @@ const ForumTab: React.FC = () => {
const [recentActivity, setRecentActivity] = useState<Array<{ user: string; action: string; target: string; time: string }>>([]);
// Bloomberg color scheme
- const BLOOMBERG_ORANGE = '#FFA500';
- const BLOOMBERG_WHITE = '#FFFFFF';
- const BLOOMBERG_RED = '#FF0000';
- const BLOOMBERG_GREEN = '#00C800';
- const BLOOMBERG_YELLOW = '#FFFF00';
- const BLOOMBERG_GRAY = '#787878';
- const BLOOMBERG_BLUE = '#6496FA';
+ const BLOOMBERG_ORANGE = 'colors.primary';
+ const BLOOMBERG_WHITE = 'colors.text';
+ const BLOOMBERG_RED = 'colors.alert';
+ const BLOOMBERG_GREEN = 'colors.secondary';
+ const BLOOMBERG_YELLOW = 'colors.warning';
+ const BLOOMBERG_GRAY = 'colors.textMuted';
+ const BLOOMBERG_BLUE = 'colors.info';
const BLOOMBERG_PURPLE = '#C864FF';
- const BLOOMBERG_CYAN = '#00FFFF';
- const BLOOMBERG_DARK_BG = '#000000';
- const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_CYAN = 'colors.accent';
+ const BLOOMBERG_DARK_BG = 'colors.background';
+ const BLOOMBERG_PANEL_BG = 'colors.panel';
// Top contributors - static for now
const topContributors: ForumUser[] = [
@@ -417,7 +419,7 @@ const ForumTab: React.FC = () => {
setProfileEdit({
display_name: profile.display_name || '',
bio: profile.bio || '',
- avatar_color: profile.avatar_color || '#FFA500',
+ avatar_color: profile.avatar_color || 'colors.primary',
signature: profile.signature || ''
});
setShowProfile(true);
diff --git a/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx b/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx
index a87dd46fa..92a9f0f5d 100644
--- a/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx
@@ -1,25 +1,14 @@
import React, { useState, useEffect } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, AreaChart, Area, ScatterChart, Scatter, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar } from 'recharts';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
const GeopoliticsTab: React.FC = () => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
const [activePanel, setActivePanel] = useState('overview');
const [alertCount, setAlertCount] = useState(127);
const [dataUpdateCount, setDataUpdateCount] = useState(0);
- // Bloomberg color scheme
- const BLOOMBERG_ORANGE = '#FFA500';
- const BLOOMBERG_WHITE = '#FFFFFF';
- const BLOOMBERG_RED = '#FF0000';
- const BLOOMBERG_GREEN = '#00C800';
- const BLOOMBERG_YELLOW = '#FFFF00';
- const BLOOMBERG_GRAY = '#787878';
- const BLOOMBERG_BLUE = '#64B4FF';
- const BLOOMBERG_PURPLE = '#C864FF';
- const BLOOMBERG_CYAN = '#00FFFF';
- const BLOOMBERG_DARK_BG = '#000000';
- const BLOOMBERG_PANEL_BG = '#0a0a0a';
-
// Risk colors
const RISK_CRITICAL = '#FF0000';
const RISK_HIGH = '#FF6400';
@@ -133,19 +122,19 @@ const GeopoliticsTab: React.FC = () => {
case "URGENT": return '#FF6400';
case "IMMEDIATE": return '#FFC800';
case "ROUTINE": return '#00C800';
- default: return BLOOMBERG_GRAY;
+ default: return colors.textMuted;
}
};
const createMatrixDisplay = () => (
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '6px',
height: '220px',
overflow: 'auto'
}}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '6px' }}>
+ <div style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold', marginBottom: '6px' }}>
CORRELATION MATRIX - GEOPOLITICAL RISK vs MARKETS
</div>
<div style={{
@@ -155,12 +144,12 @@ const GeopoliticsTab: React.FC = () => {
fontSize: '10px',
marginBottom: '4px'
}}>
- <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>Asset</div>
- <div style={{ color: BLOOMBERG_RED, fontWeight: 'bold' }}>MIL</div>
- <div style={{ color: BLOOMBERG_YELLOW, fontWeight: 'bold' }}>ECO</div>
- <div style={{ color: BLOOMBERG_BLUE, fontWeight: 'bold' }}>CYB</div>
- <div style={{ color: BLOOMBERG_PURPLE, fontWeight: 'bold' }}>NUC</div>
- <div style={{ color: BLOOMBERG_CYAN, fontWeight: 'bold' }}>VOL</div>
+ <div style={{ color: colors.text, fontWeight: 'bold' }}>Asset</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>MIL</div>
+ <div style={{ color: colors.warning, fontWeight: 'bold' }}>ECO</div>
+ <div style={{ color: colors.info, fontWeight: 'bold' }}>CYB</div>
+ <div style={{ color: colors.purple, fontWeight: 'bold' }}>NUC</div>
+ <div style={{ color: colors.accent, fontWeight: 'bold' }}>VOL</div>
</div>
{correlationMatrix.map((item, index) => (
<div key={index} style={{
@@ -171,7 +160,7 @@ const GeopoliticsTab: React.FC = () => {
marginBottom: '2px',
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent'
}}>
- <div style={{ color: BLOOMBERG_WHITE }}>{item.asset}</div>
+ <div style={{ color: colors.text }}>{item.asset}</div>
<div style={{ color: item.military > 0.8 ? RISK_CRITICAL : item.military > 0.6 ? RISK_HIGH : RISK_MEDIUM }}>
{item.military.toFixed(2)}
</div>
@@ -195,13 +184,15 @@ const GeopoliticsTab: React.FC = () => {
return (
<div style={{
height: '100%',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
- fontFamily: 'Consolas, monospace',
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontFamily: fontFamily,
+ fontWeight: fontWeight,
+ fontStyle: fontStyle,
overflow: 'hidden',
display: 'flex',
flexDirection: 'column',
- fontSize: '12px'
+ fontSize: fontSize.body
}}>
<style>{`
/* Custom scrollbar styles for Geopolitics Tab */
@@ -222,70 +213,70 @@ const GeopoliticsTab: React.FC = () => {
`}</style>
{/* Complex Header with Multiple Status Lines */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
padding: '4px 8px',
flexShrink: 0
}}>
{/* Main Status Line */}
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px' }}>
- <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>GEOPOLITICAL INTELLIGENCE SYSTEM</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>GEOPOLITICAL INTELLIGENCE SYSTEM</span>
+ <span style={{ color: colors.text }}>|</span>
<span style={{ color: RISK_HIGH, fontWeight: 'bold' }}>GLOBAL RISK: 7.34/10</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_RED }}>ACTIVE CONFLICTS: 15</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_YELLOW }}>SANCTIONS: 3,127 (+3)</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: alertCount > 125 ? BLOOMBERG_RED : BLOOMBERG_YELLOW }}>ALERTS: {alertCount}</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GREEN, animation: 'blink 1s infinite' }}>● INTEL: LIVE</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_WHITE }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.alert }}>ACTIVE CONFLICTS: 15</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.warning }}>SANCTIONS: 3,127 (+3)</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: alertCount > 125 ? colors.alert : colors.warning }}>ALERTS: {alertCount}</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.secondary, animation: 'blink 1s infinite' }}>● INTEL: LIVE</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.text }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
</div>
{/* Secondary Status Line */}
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px', marginBottom: '2px' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>FEEDS:</span>
- <span style={{ color: BLOOMBERG_GREEN }}>SIGINT●</span>
- <span style={{ color: BLOOMBERG_GREEN }}>HUMINT●</span>
- <span style={{ color: BLOOMBERG_GREEN }}>CYBINT●</span>
- <span style={{ color: BLOOMBERG_GREEN }}>ECONINT●</span>
- <span style={{ color: BLOOMBERG_YELLOW }}>GEOINT◐</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GRAY }}>LATENCY:</span>
- <span style={{ color: BLOOMBERG_GREEN }}>89ms</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GRAY }}>UPDATES:</span>
- <span style={{ color: BLOOMBERG_BLUE }}>{dataUpdateCount}</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GRAY }}>CLASSIFICATION:</span>
- <span style={{ color: BLOOMBERG_RED }}>TOP SECRET//SCI</span>
+ <span style={{ color: colors.textMuted }}>FEEDS:</span>
+ <span style={{ color: colors.secondary }}>SIGINT●</span>
+ <span style={{ color: colors.secondary }}>HUMINT●</span>
+ <span style={{ color: colors.secondary }}>CYBINT●</span>
+ <span style={{ color: colors.secondary }}>ECONINT●</span>
+ <span style={{ color: colors.warning }}>GEOINT◐</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>LATENCY:</span>
+ <span style={{ color: colors.secondary }}>89ms</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>UPDATES:</span>
+ <span style={{ color: colors.info }}>{dataUpdateCount}</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>CLASSIFICATION:</span>
+ <span style={{ color: colors.alert }}>TOP SECRET//SCI</span>
</div>
{/* Market Ticker */}
<div style={{ display: 'flex', alignItems: 'center', gap: '12px', fontSize: '11px' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>MARKETS:</span>
- <span style={{ color: BLOOMBERG_GREEN }}>NIFTY: 24,867 (+234)</span>
- <span style={{ color: BLOOMBERG_BLUE }}>INR: 83.14 (-0.08)</span>
- <span style={{ color: BLOOMBERG_GREEN }}>BRENT: $82.45 (+2.1)</span>
- <span style={{ color: BLOOMBERG_YELLOW }}>GOLD: $2,047 (+18.3)</span>
- <span style={{ color: BLOOMBERG_RED }}>VIX: 18.45 (-1.2)</span>
- <span style={{ color: BLOOMBERG_GREEN }}>DXY: 104.78 (+0.3)</span>
- <span style={{ color: BLOOMBERG_WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_GRAY }}>ENERGY:</span>
- <span style={{ color: BLOOMBERG_GREEN }}>+3.8%</span>
- <span style={{ color: BLOOMBERG_GRAY }}>DEFENSE:</span>
- <span style={{ color: BLOOMBERG_GREEN }}>+4.2%</span>
- <span style={{ color: BLOOMBERG_GRAY }}>TECH:</span>
- <span style={{ color: BLOOMBERG_RED }}>-2.1%</span>
+ <span style={{ color: colors.textMuted }}>MARKETS:</span>
+ <span style={{ color: colors.secondary }}>NIFTY: 24,867 (+234)</span>
+ <span style={{ color: colors.info }}>INR: 83.14 (-0.08)</span>
+ <span style={{ color: colors.secondary }}>BRENT: $82.45 (+2.1)</span>
+ <span style={{ color: colors.warning }}>GOLD: $2,047 (+18.3)</span>
+ <span style={{ color: colors.alert }}>VIX: 18.45 (-1.2)</span>
+ <span style={{ color: colors.secondary }}>DXY: 104.78 (+0.3)</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>ENERGY:</span>
+ <span style={{ color: colors.secondary }}>+3.8%</span>
+ <span style={{ color: colors.textMuted }}>DEFENSE:</span>
+ <span style={{ color: colors.secondary }}>+4.2%</span>
+ <span style={{ color: colors.textMuted }}>TECH:</span>
+ <span style={{ color: colors.alert }}>-2.1%</span>
</div>
</div>
{/* Function Keys with Sub-categories */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
padding: '3px 6px',
flexShrink: 0
}}>
@@ -305,9 +296,9 @@ const GeopoliticsTab: React.FC = () => {
{ key: "F12", label: "CYBER", status: "●" }
].map(item => (
<button key={item.key} style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: BLOOMBERG_WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.text,
padding: '2px 4px',
fontSize: '12px',
height: '18px',
@@ -315,12 +306,12 @@ const GeopoliticsTab: React.FC = () => {
alignItems: 'center',
justifyContent: 'center'
}}>
- <span style={{ color: BLOOMBERG_YELLOW }}>{item.key}:</span>
+ <span style={{ color: colors.warning }}>{item.key}:</span>
<span style={{ marginLeft: '2px' }}>{item.label}</span>
<span style={{
marginLeft: '2px',
- color: item.status === '●' ? BLOOMBERG_GREEN :
- item.status === '◐' ? BLOOMBERG_YELLOW : BLOOMBERG_GRAY
+ color: item.status === '●' ? colors.secondary :
+ item.status === '◐' ? colors.warning : colors.textMuted
}}>
{item.status}
</span>
@@ -335,15 +326,15 @@ const GeopoliticsTab: React.FC = () => {
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '4px', marginBottom: '4px', height: '180px' }}>
{/* Real-time Intelligence Stream */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px',
overflow: 'auto'
}}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
REAL-TIME INTELLIGENCE STREAM [CLASSIFICATION: TS//SCI]
</div>
- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '4px' }}></div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
{intelligenceStream.map((intel, index) => (
<div key={index} style={{
@@ -353,18 +344,18 @@ const GeopoliticsTab: React.FC = () => {
paddingLeft: '4px'
}}>
<div style={{ display: 'flex', gap: '4px', marginBottom: '1px' }}>
- <span style={{ color: BLOOMBERG_GRAY, minWidth: '50px' }}>{intel.time}</span>
+ <span style={{ color: colors.textMuted, minWidth: '50px' }}>{intel.time}</span>
<span style={{ color: getPriorityColor(intel.priority), fontWeight: 'bold', minWidth: '60px' }}>
[{intel.priority}]
</span>
- <span style={{ color: BLOOMBERG_BLUE, minWidth: '50px' }}>[{intel.source}]</span>
- <span style={{ color: BLOOMBERG_PURPLE, minWidth: '30px' }}>{intel.region}</span>
- <span style={{ color: BLOOMBERG_YELLOW, minWidth: '30px' }}>{intel.confidence}%</span>
+ <span style={{ color: colors.info, minWidth: '50px' }}>[{intel.source}]</span>
+ <span style={{ color: colors.purple, minWidth: '30px' }}>{intel.region}</span>
+ <span style={{ color: colors.warning, minWidth: '30px' }}>{intel.confidence}%</span>
</div>
- <div style={{ color: BLOOMBERG_WHITE, lineHeight: '1.1', marginBottom: '1px' }}>
+ <div style={{ color: colors.text, lineHeight: '1.1', marginBottom: '1px' }}>
{intel.event}
</div>
- <div style={{ color: BLOOMBERG_GRAY, fontSize: '7px' }}>
+ <div style={{ color: colors.textMuted, fontSize: '7px' }}>
Classification: {intel.classification}
</div>
</div>
@@ -373,12 +364,12 @@ const GeopoliticsTab: React.FC = () => {
{/* Country Risk Matrix */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px',
overflow: 'auto'
}}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
COUNTRY RISK ASSESSMENT MATRIX
</div>
<div style={{
@@ -388,13 +379,13 @@ const GeopoliticsTab: React.FC = () => {
fontSize: '12px',
marginBottom: '4px'
}}>
- <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>CTRY</div>
- <div style={{ color: BLOOMBERG_RED, fontWeight: 'bold' }}>MIL</div>
- <div style={{ color: BLOOMBERG_YELLOW, fontWeight: 'bold' }}>ECO</div>
- <div style={{ color: BLOOMBERG_BLUE, fontWeight: 'bold' }}>POL</div>
- <div style={{ color: BLOOMBERG_PURPLE, fontWeight: 'bold' }}>TOT</div>
- <div style={{ color: BLOOMBERG_CYAN, fontWeight: 'bold' }}>TRD</div>
- <div style={{ color: BLOOMBERG_GRAY, fontWeight: 'bold' }}>SAN</div>
+ <div style={{ color: colors.text, fontWeight: 'bold' }}>CTRY</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>MIL</div>
+ <div style={{ color: colors.warning, fontWeight: 'bold' }}>ECO</div>
+ <div style={{ color: colors.info, fontWeight: 'bold' }}>POL</div>
+ <div style={{ color: colors.purple, fontWeight: 'bold' }}>TOT</div>
+ <div style={{ color: colors.accent, fontWeight: 'bold' }}>TRD</div>
+ <div style={{ color: colors.textMuted, fontWeight: 'bold' }}>SAN</div>
</div>
{countryRiskData.map((country, index) => (
<div key={index} style={{
@@ -405,18 +396,18 @@ const GeopoliticsTab: React.FC = () => {
marginBottom: '1px',
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent'
}}>
- <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>{country.country}</div>
+ <div style={{ color: colors.text, fontWeight: 'bold' }}>{country.country}</div>
<div style={{ color: getRiskColor(country.military) }}>{country.military.toFixed(1)}</div>
<div style={{ color: getRiskColor(country.economic) }}>{country.economic.toFixed(1)}</div>
<div style={{ color: getRiskColor(country.political) }}>{country.political.toFixed(1)}</div>
<div style={{ color: getRiskColor(country.total) }}>{country.total.toFixed(1)}</div>
<div style={{
- color: country.trend === 'up' ? BLOOMBERG_RED :
- country.trend === 'down' ? BLOOMBERG_GREEN : BLOOMBERG_YELLOW
+ color: country.trend === 'up' ? colors.alert :
+ country.trend === 'down' ? colors.secondary : colors.warning
}}>
{country.trend === 'up' ? '↑' : country.trend === 'down' ? '↓' : '→'}
</div>
- <div style={{ color: country.sanctions > 500 ? BLOOMBERG_RED : country.sanctions > 50 ? BLOOMBERG_YELLOW : BLOOMBERG_GREEN }}>
+ <div style={{ color: country.sanctions > 500 ? colors.alert : country.sanctions > 50 ? colors.warning : colors.secondary }}>
{country.sanctions}
</div>
</div>
@@ -425,15 +416,15 @@ const GeopoliticsTab: React.FC = () => {
{/* Economic Indicators Dashboard */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px',
overflow: 'auto'
}}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
ECONOMIC THREAT INDICATORS
</div>
- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '4px' }}></div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
{economicIndicators.map((indicator, index) => (
<div key={index} style={{
@@ -446,31 +437,31 @@ const GeopoliticsTab: React.FC = () => {
padding: '1px 2px'
}}>
<div style={{ flex: 1 }}>
- <span style={{ color: BLOOMBERG_WHITE, fontWeight: indicator.alert ? 'bold' : 'normal' }}>
+ <span style={{ color: colors.text, fontWeight: indicator.alert ? 'bold' : 'normal' }}>
{indicator.name}
</span>
- {indicator.alert && <span style={{ color: BLOOMBERG_RED, marginLeft: '2px' }}>⚠</span>}
+ {indicator.alert && <span style={{ color: colors.alert, marginLeft: '2px' }}>⚠</span>}
</div>
<div style={{
- color: indicator.change > 0 ? BLOOMBERG_GREEN :
- indicator.change < 0 ? BLOOMBERG_RED : BLOOMBERG_GRAY,
+ color: indicator.change > 0 ? colors.secondary :
+ indicator.change < 0 ? colors.alert : colors.textMuted,
minWidth: '60px',
textAlign: 'right'
}}>
{indicator.current.toLocaleString()}
</div>
<div style={{
- color: indicator.change > 0 ? BLOOMBERG_GREEN :
- indicator.change < 0 ? BLOOMBERG_RED : BLOOMBERG_GRAY,
+ color: indicator.change > 0 ? colors.secondary :
+ indicator.change < 0 ? colors.alert : colors.textMuted,
minWidth: '40px',
textAlign: 'right'
}}>
{indicator.change > 0 ? '+' : ''}{indicator.change}
</div>
<div style={{
- color: indicator.impact === 'Critical' ? BLOOMBERG_RED :
- indicator.impact === 'High' ? BLOOMBERG_ORANGE :
- indicator.impact === 'Medium' ? BLOOMBERG_YELLOW : BLOOMBERG_GREEN,
+ color: indicator.impact === 'Critical' ? colors.alert :
+ indicator.impact === 'High' ? colors.primary :
+ indicator.impact === 'Medium' ? colors.warning : colors.secondary,
minWidth: '20px',
textAlign: 'center',
fontSize: '11px'
@@ -486,55 +477,55 @@ const GeopoliticsTab: React.FC = () => {
<div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: '4px', marginBottom: '4px', height: '240px' }}>
{/* Complex Risk Forecast Chart */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px'
}}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
MULTI-VECTOR RISK FORECAST - 90 DAY PREDICTIVE MODEL
</div>
<ResponsiveContainer width="100%" height={200}>
<LineChart data={riskForecastData.slice(0, 30)}>
- <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
- <XAxis dataKey="day" stroke={BLOOMBERG_WHITE} fontSize={10} />
- <YAxis stroke={BLOOMBERG_WHITE} fontSize={10} domain={[5, 10]} />
+ <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
+ <XAxis dataKey="day" stroke={colors.text} fontSize={10} />
+ <YAxis stroke={colors.text} fontSize={10} domain={[5, 10]} />
<Tooltip
contentStyle={{
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: BLOOMBERG_WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.text,
fontSize: '10px'
}}
/>
<Legend wrapperStyle={{ fontSize: '10px' }} />
- <Line type="monotone" dataKey="baseRisk" stroke={BLOOMBERG_GREEN} strokeWidth={1} name="Base Risk" dot={false} />
- <Line type="monotone" dataKey="militaryRisk" stroke={BLOOMBERG_RED} strokeWidth={1} name="Military" dot={false} />
- <Line type="monotone" dataKey="economicRisk" stroke={BLOOMBERG_YELLOW} strokeWidth={1} name="Economic" dot={false} />
- <Line type="monotone" dataKey="cyberRisk" stroke={BLOOMBERG_BLUE} strokeWidth={1} name="Cyber" dot={false} />
- <Line type="monotone" dataKey="nuclearRisk" stroke={BLOOMBERG_PURPLE} strokeWidth={1} name="Nuclear" dot={false} />
+ <Line type="monotone" dataKey="baseRisk" stroke={colors.secondary} strokeWidth={1} name="Base Risk" dot={false} />
+ <Line type="monotone" dataKey="militaryRisk" stroke={colors.alert} strokeWidth={1} name="Military" dot={false} />
+ <Line type="monotone" dataKey="economicRisk" stroke={colors.warning} strokeWidth={1} name="Economic" dot={false} />
+ <Line type="monotone" dataKey="cyberRisk" stroke={colors.info} strokeWidth={1} name="Cyber" dot={false} />
+ <Line type="monotone" dataKey="nuclearRisk" stroke={colors.purple} strokeWidth={1} name="Nuclear" dot={false} />
</LineChart>
</ResponsiveContainer>
</div>
{/* Threat Radar Chart */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px'
}}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
THREAT RADAR
</div>
<ResponsiveContainer width="100%" height={200}>
<RadarChart data={threatRadarData}>
- <PolarGrid stroke={BLOOMBERG_GRAY} />
- <PolarAngleAxis dataKey="threat" tick={{ fontSize: 10, fill: BLOOMBERG_WHITE }} />
- <PolarRadiusAxis angle={90} domain={[0, 10]} tick={{ fontSize: 9, fill: BLOOMBERG_GRAY }} />
+ <PolarGrid stroke={colors.textMuted} />
+ <PolarAngleAxis dataKey="threat" tick={{ fontSize: 10, fill: colors.text }} />
+ <PolarRadiusAxis angle={90} domain={[0, 10]} tick={{ fontSize: 9, fill: colors.textMuted }} />
<Radar
name="Current Threat"
dataKey="current"
- stroke={BLOOMBERG_RED}
- fill={BLOOMBERG_RED}
+ stroke={colors.alert}
+ fill={colors.alert}
fillOpacity={0.3}
strokeWidth={2}
/>
@@ -550,12 +541,12 @@ const GeopoliticsTab: React.FC = () => {
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '4px', height: '200px' }}>
{/* Market Impact Analysis */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px',
overflow: 'auto'
}}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
MARKET IMPACT ANALYSIS
</div>
<div style={{
@@ -565,11 +556,11 @@ const GeopoliticsTab: React.FC = () => {
fontSize: '12px',
marginBottom: '4px'
}}>
- <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>SECTOR</div>
- <div style={{ color: BLOOMBERG_BLUE, fontWeight: 'bold' }}>CORR</div>
- <div style={{ color: BLOOMBERG_GREEN, fontWeight: 'bold' }}>IMPL</div>
- <div style={{ color: BLOOMBERG_YELLOW, fontWeight: 'bold' }}>VOLUME</div>
- <div style={{ color: BLOOMBERG_PURPLE, fontWeight: 'bold' }}>CHG</div>
+ <div style={{ color: colors.text, fontWeight: 'bold' }}>SECTOR</div>
+ <div style={{ color: colors.info, fontWeight: 'bold' }}>CORR</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>IMPL</div>
+ <div style={{ color: colors.warning, fontWeight: 'bold' }}>VOLUME</div>
+ <div style={{ color: colors.purple, fontWeight: 'bold' }}>CHG</div>
</div>
{marketImpactData.map((market, index) => (
<div key={index} style={{
@@ -580,15 +571,15 @@ const GeopoliticsTab: React.FC = () => {
marginBottom: '1px',
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent'
}}>
- <div style={{ color: BLOOMBERG_WHITE }}>{market.sector}</div>
- <div style={{ color: market.correlation > 0.8 ? BLOOMBERG_RED : market.correlation > 0.6 ? BLOOMBERG_YELLOW : BLOOMBERG_GREEN }}>
+ <div style={{ color: colors.text }}>{market.sector}</div>
+ <div style={{ color: market.correlation > 0.8 ? colors.alert : market.correlation > 0.6 ? colors.warning : colors.secondary }}>
{market.correlation.toFixed(2)}
</div>
- <div style={{ color: market.impact > 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED }}>
+ <div style={{ color: market.impact > 0 ? colors.secondary : colors.alert }}>
{market.impact > 0 ? '+' : ''}{market.impact.toFixed(1)}
</div>
- <div style={{ color: BLOOMBERG_GRAY }}>{market.volume}</div>
- <div style={{ color: market.change.startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED }}>
+ <div style={{ color: colors.textMuted }}>{market.volume}</div>
+ <div style={{ color: market.change.startsWith('+') ? colors.secondary : colors.alert }}>
{market.change}
</div>
</div>
@@ -597,20 +588,20 @@ const GeopoliticsTab: React.FC = () => {
{/* Critical Trade Routes */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px',
overflow: 'auto'
}}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
CRITICAL TRADE ROUTE RISK
</div>
- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '4px' }}></div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
{tradeRouteRisk.map((route, index) => (
<div key={index} style={{ marginBottom: '6px', fontSize: '8px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold', fontSize: '9px' }}>
+ <span style={{ color: colors.text, fontWeight: 'bold', fontSize: '9px' }}>
{route.route}
</span>
<span style={{ color: getRiskColor(route.risk) }}>
@@ -618,14 +609,14 @@ const GeopoliticsTab: React.FC = () => {
</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>Throughput:</span>
- <span style={{ color: BLOOMBERG_BLUE }}>{route.throughput}</span>
+ <span style={{ color: colors.textMuted }}>Throughput:</span>
+ <span style={{ color: colors.info }}>{route.throughput}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>Threat:</span>
- <span style={{ color: BLOOMBERG_YELLOW }}>{route.threat}</span>
+ <span style={{ color: colors.textMuted }}>Threat:</span>
+ <span style={{ color: colors.warning }}>{route.threat}</span>
</div>
- <div style={{ color: BLOOMBERG_CYAN, fontSize: '7px', lineHeight: '1.1' }}>
+ <div style={{ color: colors.accent, fontSize: '7px', lineHeight: '1.1' }}>
India: {route.india}
</div>
</div>
@@ -634,42 +625,42 @@ const GeopoliticsTab: React.FC = () => {
{/* India Strategic Dashboard */}
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px',
overflow: 'auto'
}}>
- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
INDIA STRATEGIC POSITION ANALYSIS
</div>
- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '4px' }}></div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
<div style={{ marginBottom: '6px' }}>
- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '9px', fontWeight: 'bold', marginBottom: '2px' }}>
+ <div style={{ color: colors.warning, fontSize: '9px', fontWeight: 'bold', marginBottom: '2px' }}>
KEY METRICS
</div>
<div style={{ fontSize: '8px', lineHeight: '1.2' }}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>GDP Growth:</span>
- <span style={{ color: BLOOMBERG_GREEN }}>6.7% YoY</span>
+ <span style={{ color: colors.textMuted }}>GDP Growth:</span>
+ <span style={{ color: colors.secondary }}>6.7% YoY</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>FDI Inflows:</span>
- <span style={{ color: BLOOMBERG_GREEN }}>$83.6B</span>
+ <span style={{ color: colors.textMuted }}>FDI Inflows:</span>
+ <span style={{ color: colors.secondary }}>$83.6B</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>Defense Budget:</span>
- <span style={{ color: BLOOMBERG_BLUE }}>$75.6B</span>
+ <span style={{ color: colors.textMuted }}>Defense Budget:</span>
+ <span style={{ color: colors.info }}>$75.6B</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: BLOOMBERG_GRAY }}>Border Infra:</span>
- <span style={{ color: BLOOMBERG_YELLOW }}>67% Complete</span>
+ <span style={{ color: colors.textMuted }}>Border Infra:</span>
+ <span style={{ color: colors.warning }}>67% Complete</span>
</div>
</div>
</div>
<div style={{ marginBottom: '6px' }}>
- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '9px', fontWeight: 'bold', marginBottom: '2px' }}>
+ <div style={{ color: colors.warning, fontSize: '9px', fontWeight: 'bold', marginBottom: '2px' }}>
THREAT MATRIX
</div>
<div style={{ fontSize: '7px' }}>
@@ -681,7 +672,7 @@ const GeopoliticsTab: React.FC = () => {
{ threat: "Trade Disruption", level: 5.2, status: "LOW" }
].map((item, index) => (
<div key={index} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: BLOOMBERG_WHITE }}>{item.threat}:</span>
+ <span style={{ color: colors.text }}>{item.threat}:</span>
<span style={{ color: getRiskColor(item.level) }}>{item.level} [{item.status}]</span>
</div>
))}
@@ -689,10 +680,10 @@ const GeopoliticsTab: React.FC = () => {
</div>
<div>
- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '9px', fontWeight: 'bold', marginBottom: '2px' }}>
+ <div style={{ color: colors.warning, fontSize: '9px', fontWeight: 'bold', marginBottom: '2px' }}>
STRATEGIC INITIATIVES
</div>
- <div style={{ fontSize: '7px', color: BLOOMBERG_GREEN }}>
+ <div style={{ fontSize: '7px', color: colors.secondary }}>
<div>✓ Quad Alliance Operationalization</div>
<div>✓ IMEC Corridor Development</div>
<div>✓ Semiconductor Self-Reliance</div>
@@ -706,11 +697,11 @@ const GeopoliticsTab: React.FC = () => {
{/* Enhanced Status Bar */}
<div style={{
- borderTop: `1px solid ${BLOOMBERG_GRAY}`,
- backgroundColor: BLOOMBERG_PANEL_BG,
+ borderTop: `1px solid ${colors.textMuted}`,
+ backgroundColor: colors.panel,
padding: '2px 8px',
fontSize: '10px',
- color: BLOOMBERG_GRAY,
+ color: colors.textMuted,
flexShrink: 0
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
@@ -721,7 +712,7 @@ const GeopoliticsTab: React.FC = () => {
<div style={{ display: 'flex', gap: '16px' }}>
<span>Classification: TOP SECRET//SCI//NOFORN</span>
<span>Session: {currentTime.toTimeString().substring(0, 8)}</span>
- <span style={{ color: BLOOMBERG_GREEN }}>SCIF: AUTHORIZED</span>
+ <span style={{ color: colors.secondary }}>SCIF: AUTHORIZED</span>
</div>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/KrakenTab.tsx b/fincept-terminal-desktop/src/components/tabs/KrakenTab.tsx
new file mode 100644
index 000000000..f5ecb8f0e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/KrakenTab.tsx
@@ -0,0 +1,836 @@
+// Kraken Trading Terminal - Bloomberg-style interface
+import React, { useState, useEffect, useMemo, useRef } from 'react';
+import { useWebSocket } from '@/hooks/useWebSocket';
+import { getWebSocketManager } from '@/services/websocket';
+import { TrendingUp, TrendingDown, Activity, BookOpen, BarChart3, Zap } from 'lucide-react';
+import { createChart, ColorType, IChartApi, ISeriesApi, CandlestickData, CandlestickSeries } from 'lightweight-charts';
+
+// Popular Kraken trading pairs
+const POPULAR_PAIRS = [
+ 'BTC/USD', 'ETH/USD', 'XRP/USD', 'SOL/USD', 'ADA/USD',
+ 'MATIC/USD', 'AVAX/USD', 'DOT/USD', 'LINK/USD', 'UNI/USD'
+];
+
+const OHLC_INTERVALS = [
+ { label: '1m', value: 1 },
+ { label: '5m', value: 5 },
+ { label: '15m', value: 15 },
+ { label: '30m', value: 30 },
+ { label: '1h', value: 60 },
+ { label: '4h', value: 240 },
+ { label: '1D', value: 1440 }
+];
+
+const ORDERBOOK_DEPTHS = [10, 25, 100, 500, 1000];
+
+interface TickerData {
+ symbol: string;
+ bid: number;
+ ask: number;
+ last: number;
+ volume: number;
+ vwap: number;
+ high: number;
+ low: number;
+ change: number;
+ change_pct: number;
+}
+
+interface TradeData {
+ symbol: string;
+ price: number;
+ qty: number;
+ side: 'buy' | 'sell';
+ timestamp: number;
+}
+
+interface OrderBookLevel {
+ price: number;
+ qty: number;
+}
+
+interface OrderBookData {
+ symbol: string;
+ bids: OrderBookLevel[];
+ asks: OrderBookLevel[];
+ checksum?: number;
+}
+
+interface OHLCData {
+ timestamp: number | string;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+}
+
+export default function KrakenTab() {
+ const [selectedPair, setSelectedPair] = useState('BTC/USD');
+ const [ohlcInterval, setOhlcInterval] = useState(60);
+ const [bookDepth, setBookDepth] = useState(25);
+ const [tickerData, setTickerData] = useState<TickerData | null>(null);
+ const [trades, setTrades] = useState<TradeData[]>([]);
+ const [orderBook, setOrderBook] = useState<OrderBookData>({ symbol: '', bids: [], asks: [] });
+ const [isConnected, setIsConnected] = useState(false);
+ const [chartData, setChartData] = useState<OHLCData[]>([]);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [customPair, setCustomPair] = useState('');
+
+ const chartContainerRef = useRef<HTMLDivElement>(null);
+ const chartRef = useRef<IChartApi | null>(null);
+ const candlestickSeriesRef = useRef<any>(null);
+ const isMountedRef = useRef(true);
+ const lastCandleTimeRef = useRef<number>(0);
+
+ // Initialize WebSocket manager
+ useEffect(() => {
+ const manager = getWebSocketManager();
+ manager.setProviderConfig('kraken', {
+ provider_name: 'kraken',
+ enabled: true,
+ endpoint: 'wss://ws.kraken.com/v2'
+ });
+
+ // Connect to Kraken
+ const connectToKraken = async () => {
+ try {
+ await manager.connect('kraken');
+ setIsConnected(true);
+ } catch (error) {
+ console.error('Failed to connect to Kraken:', error);
+ setIsConnected(false);
+ }
+ };
+
+ connectToKraken();
+
+ return () => {
+ // Don't disconnect on unmount as other components might be using it
+ setIsConnected(false);
+ };
+ }, []);
+
+ // Fetch historical OHLC data from Kraken REST API
+ const fetchHistoricalData = async (pair: string, interval: number) => {
+ try {
+ // Convert pair format for Kraken API
+ // BTC/USD -> XBTUSD, ETH/USD -> ETHUSD, etc.
+ let krakenPair = pair.replace('/', '');
+
+ // Special case: BTC is XBT on Kraken
+ if (krakenPair.startsWith('BTC')) {
+ krakenPair = krakenPair.replace('BTC', 'XBT');
+ }
+
+ console.log(`Fetching historical data for ${pair} (Kraken: ${krakenPair}), interval: ${interval}`);
+
+ // Fetch last 100 candles
+ const response = await fetch(
+ `https://api.kraken.com/0/public/OHLC?pair=${krakenPair}&interval=${interval}`
+ );
+
+ const data = await response.json();
+
+ if (data.error && data.error.length > 0) {
+ console.error('Kraken API error:', data.error);
+ return [];
+ }
+
+ const result = data.result;
+ const pairKey = Object.keys(result).find(key => key !== 'last');
+
+ if (!pairKey) {
+ console.warn('No data found for pair:', krakenPair);
+ return [];
+ }
+
+ const ohlcData: OHLCData[] = result[pairKey].map((candle: any[]) => ({
+ timestamp: candle[0],
+ open: parseFloat(candle[1]),
+ high: parseFloat(candle[2]),
+ low: parseFloat(candle[3]),
+ close: parseFloat(candle[4]),
+ volume: parseFloat(candle[6])
+ }));
+
+ console.log(`Fetched ${ohlcData.length} candles for ${pair}`);
+ return ohlcData;
+ } catch (error) {
+ console.error('Failed to fetch historical data:', error);
+ return [];
+ }
+ };
+
+ // Initialize chart
+ useEffect(() => {
+ if (!chartContainerRef.current) return;
+
+ const chart = createChart(chartContainerRef.current, {
+ layout: {
+ background: { type: ColorType.Solid, color: '#0a0a0a' },
+ textColor: '#d1d5db',
+ },
+ grid: {
+ vertLines: { color: '#1f2937' },
+ horzLines: { color: '#1f2937' },
+ },
+ width: chartContainerRef.current.clientWidth,
+ height: chartContainerRef.current.clientHeight,
+ timeScale: {
+ timeVisible: true,
+ secondsVisible: false,
+ },
+ });
+
+ const candlestickSeries = chart.addSeries(CandlestickSeries, {
+ upColor: '#10b981',
+ downColor: '#ef4444',
+ borderUpColor: '#10b981',
+ borderDownColor: '#ef4444',
+ wickUpColor: '#10b981',
+ wickDownColor: '#ef4444',
+ });
+
+ chartRef.current = chart;
+ candlestickSeriesRef.current = candlestickSeries;
+
+ // Handle resize
+ const handleResize = () => {
+ if (isMountedRef.current && chartContainerRef.current && chartRef.current) {
+ try {
+ chartRef.current.applyOptions({
+ width: chartContainerRef.current.clientWidth,
+ height: chartContainerRef.current.clientHeight,
+ });
+ } catch (error) {
+ // Ignore errors if chart is being disposed
+ }
+ }
+ };
+
+ window.addEventListener('resize', handleResize);
+
+ return () => {
+ isMountedRef.current = false;
+ window.removeEventListener('resize', handleResize);
+ candlestickSeriesRef.current = null;
+ chartRef.current = null;
+ setTimeout(() => {
+ try {
+ chart.remove();
+ } catch (error) {
+ // Ignore errors during cleanup
+ }
+ }, 0);
+ };
+ }, []);
+
+ // Load historical data when pair or interval changes
+ useEffect(() => {
+ const loadData = async () => {
+ // Reset the last candle time when loading new data
+ lastCandleTimeRef.current = 0;
+
+ const historical = await fetchHistoricalData(selectedPair, ohlcInterval);
+ setChartData(historical);
+
+ if (candlestickSeriesRef.current && historical.length > 0) {
+ const chartCandles = historical.map((candle, idx) => {
+ // Ensure timestamp is a number (Unix timestamp in seconds)
+ let time: number;
+
+ if (typeof candle.timestamp === 'number') {
+ time = candle.timestamp;
+ } else if (typeof candle.timestamp === 'string') {
+ time = Math.floor(new Date(candle.timestamp).getTime() / 1000);
+ } else {
+ console.error('Invalid timestamp type in historical data:', candle.timestamp, 'at index:', idx);
+ time = 0;
+ }
+
+ // If it's in milliseconds, convert to seconds
+ if (time > 10000000000) {
+ time = Math.floor(time / 1000);
+ }
+
+ return {
+ time,
+ open: candle.open,
+ high: candle.high,
+ low: candle.low,
+ close: candle.close,
+ };
+ }).filter(candle => candle.time > 0) // Filter out invalid candles
+ .sort((a, b) => a.time - b.time); // Sort by time ascending
+
+ console.log('Setting chart data with', chartCandles.length, 'candles, first:', chartCandles[0], 'last:', chartCandles[chartCandles.length - 1]);
+
+ // Use setData to replace all chart data
+ candlestickSeriesRef.current.setData(chartCandles);
+
+ // Track the last candle time so we can update it with live data
+ const lastCandle = chartCandles[chartCandles.length - 1];
+ if (lastCandle) {
+ lastCandleTimeRef.current = lastCandle.time;
+ console.log('Last candle time set to:', lastCandleTimeRef.current);
+ }
+ }
+ };
+
+ loadData();
+ }, [selectedPair, ohlcInterval]);
+
+ // Ticker subscription
+ const { message: tickerMessage } = useWebSocket(
+ isConnected ? `kraken.ticker.${selectedPair}` : null,
+ null,
+ { autoSubscribe: true }
+ );
+
+ // Trade subscription
+ const { message: tradeMessage } = useWebSocket(
+ isConnected ? `kraken.trade.${selectedPair}` : null,
+ null,
+ { autoSubscribe: true }
+ );
+
+ // Order book subscription
+ const { message: bookMessage } = useWebSocket(
+ isConnected ? `kraken.book.${selectedPair}` : null,
+ null,
+ { autoSubscribe: true, params: { depth: bookDepth } }
+ );
+
+ // OHLC subscription
+ const { message: ohlcMessage } = useWebSocket(
+ isConnected ? `kraken.ohlc.${selectedPair}` : null,
+ null,
+ { autoSubscribe: true, params: { interval: ohlcInterval } }
+ );
+
+ // Update ticker data
+ useEffect(() => {
+ if (tickerMessage?.data) {
+ console.log('Ticker message received:', tickerMessage.data);
+ setTickerData(tickerMessage.data as TickerData);
+ }
+ }, [tickerMessage]);
+
+ // Update trades
+ useEffect(() => {
+ if (tradeMessage?.data) {
+ const trade = tradeMessage.data as TradeData;
+ setTrades(prev => [trade, ...prev].slice(0, 100));
+ }
+ }, [tradeMessage]);
+
+ // Update order book - merge instead of replace
+ useEffect(() => {
+ if (bookMessage?.data) {
+ const newBook = bookMessage.data as OrderBookData;
+ const messageType = (bookMessage.data as any).messageType;
+
+ if (messageType === 'snapshot') {
+ // Snapshot: replace entire book
+ setOrderBook(newBook);
+ } else {
+ // Update: merge with existing book
+ setOrderBook(prev => {
+ const updatedBids = [...prev.bids];
+ const updatedAsks = [...prev.asks];
+
+ // Update bids
+ newBook.bids?.forEach(newBid => {
+ const index = updatedBids.findIndex(b => b.price === newBid.price);
+ if (newBid.qty === 0) {
+ // Remove if quantity is 0
+ if (index !== -1) updatedBids.splice(index, 1);
+ } else {
+ if (index !== -1) {
+ // Update existing
+ updatedBids[index] = newBid;
+ } else {
+ // Add new
+ updatedBids.push(newBid);
+ }
+ }
+ });
+
+ // Update asks
+ newBook.asks?.forEach(newAsk => {
+ const index = updatedAsks.findIndex(a => a.price === newAsk.price);
+ if (newAsk.qty === 0) {
+ // Remove if quantity is 0
+ if (index !== -1) updatedAsks.splice(index, 1);
+ } else {
+ if (index !== -1) {
+ // Update existing
+ updatedAsks[index] = newAsk;
+ } else {
+ // Add new
+ updatedAsks.push(newAsk);
+ }
+ }
+ });
+
+ // Sort bids descending, asks ascending, and limit to depth
+ updatedBids.sort((a, b) => b.price - a.price);
+ updatedAsks.sort((a, b) => a.price - b.price);
+
+ return {
+ symbol: newBook.symbol || prev.symbol,
+ bids: updatedBids.slice(0, bookDepth),
+ asks: updatedAsks.slice(0, bookDepth),
+ checksum: newBook.checksum
+ };
+ });
+ }
+ }
+ }, [bookMessage, bookDepth]);
+
+ // Update chart with live OHLC data
+ useEffect(() => {
+ if (ohlcMessage?.data && candlestickSeriesRef.current) {
+ try {
+ const ohlc = ohlcMessage.data as any;
+
+ // Parse the interval_begin timestamp to determine the candle's time
+ // This represents when the candle period started
+ let candleTime: number;
+
+ if (ohlc.interval_begin) {
+ // Parse ISO string from interval_begin
+ candleTime = Math.floor(new Date(ohlc.interval_begin).getTime() / 1000);
+ } else {
+ // Fallback to the message timestamp
+ let timestamp = ohlcMessage.timestamp;
+ candleTime = typeof timestamp === 'number' ? Math.floor(timestamp / 1000) : 0;
+ }
+
+ // Validate that candleTime is actually a number
+ if (typeof candleTime !== 'number' || isNaN(candleTime)) {
+ console.error('Invalid candleTime:', candleTime, 'type:', typeof candleTime);
+ return;
+ }
+
+ // Skip old candles (this can happen when historical data is still loading)
+ // Only update if the candle is >= the last tracked candle
+ if (lastCandleTimeRef.current > 0 && candleTime < lastCandleTimeRef.current) {
+ console.log('Skipping old candle:', candleTime, 'last:', lastCandleTimeRef.current);
+ return;
+ }
+
+ console.log('Updating candle:', candleTime, 'last:', lastCandleTimeRef.current);
+
+ // Check if this is the same candle we're already tracking (update)
+ // or a new candle (which means the previous interval completed)
+ if (lastCandleTimeRef.current === candleTime) {
+ // Same candle - update it (this makes it "animate" like TradingView)
+ candlestickSeriesRef.current.update({
+ time: candleTime as any,
+ open: parseFloat(ohlc.open),
+ high: parseFloat(ohlc.high),
+ low: parseFloat(ohlc.low),
+ close: parseFloat(ohlc.close),
+ });
+ } else {
+ // New candle - the interval completed
+ lastCandleTimeRef.current = candleTime;
+ candlestickSeriesRef.current.update({
+ time: candleTime as any,
+ open: parseFloat(ohlc.open),
+ high: parseFloat(ohlc.high),
+ low: parseFloat(ohlc.low),
+ close: parseFloat(ohlc.close),
+ });
+ }
+ } catch (error) {
+ console.error('Failed to update chart with OHLC data:', error, ohlcMessage);
+ }
+ }
+ }, [ohlcMessage]);
+
+ const priceChangeColor = useMemo(() => {
+ if (!tickerData) return 'text-gray-400';
+ return tickerData.change >= 0 ? 'text-green-400' : 'text-red-400';
+ }, [tickerData]);
+
+ const spread = useMemo(() => {
+ if (!tickerData) return 0;
+ return ((tickerData.ask - tickerData.bid) / tickerData.bid * 100).toFixed(4);
+ }, [tickerData]);
+
+ // Filter popular pairs based on search query
+ const filteredPairs = useMemo(() => {
+ if (!searchQuery) return POPULAR_PAIRS;
+ const query = searchQuery.toLowerCase();
+ return POPULAR_PAIRS.filter(pair => pair.toLowerCase().includes(query));
+ }, [searchQuery]);
+
+ // Handle custom pair submission
+ const handleCustomPairSubmit = (e: React.FormEvent) => {
+ e.preventDefault();
+ if (customPair.trim()) {
+ // Format the pair (add / if not present)
+ const formattedPair = customPair.includes('/')
+ ? customPair.toUpperCase()
+ : customPair.toUpperCase().replace(/([A-Z]{3,})([A-Z]{3,})/, '$1/$2');
+ setSelectedPair(formattedPair);
+ setCustomPair('');
+ setSearchQuery('');
+ }
+ };
+
+ return (
+ <div className="h-full bg-[#0a0a0a] text-gray-100 flex flex-col overflow-hidden font-mono">
+ {/* Header */}
+ <div className="bg-[#111111] border-b border-gray-800 px-4 py-2 flex items-center justify-between">
+ <div className="flex items-center gap-4">
+ <div className="flex items-center gap-2">
+ <Zap className="w-5 h-5 text-yellow-400" />
+ <span className="text-lg font-bold text-yellow-400">KRAKEN</span>
+ <span className="text-xs text-gray-500">TERMINAL</span>
+ </div>
+ <div className="h-6 w-px bg-gray-700" />
+ <div className={`flex items-center gap-2 ${priceChangeColor}`}>
+ <span className="text-2xl font-bold">
+ {selectedPair}
+ </span>
+ {tickerData && (
+ <>
+ {tickerData.change >= 0 ? <TrendingUp className="w-5 h-5" /> : <TrendingDown className="w-5 h-5" />}
+ <span className="text-sm">
+ {tickerData.change >= 0 ? '+' : ''}{tickerData.change_pct?.toFixed(2)}%
+ </span>
+ </>
+ )}
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className={`w-2 h-2 rounded-full ${isConnected ? 'bg-green-400 animate-pulse' : 'bg-red-400'}`} />
+ <span className="text-xs text-gray-400">
+ {isConnected ? 'LIVE' : 'DISCONNECTED'}
+ </span>
+ </div>
+ </div>
+
+ {/* Symbol Selector */}
+ <div className="bg-[#0d0d0d] border-b border-gray-800 px-4 py-2">
+ <div className="flex items-center gap-3">
+ {/* Search Input */}
+ <div className="flex items-center gap-2 flex-shrink-0">
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder="Search pairs..."
+ className="bg-[#1a1a1a] text-gray-200 text-xs px-3 py-1 border border-gray-700 focus:outline-none focus:border-orange-500 w-32"
+ />
+ {/* Custom Pair Form */}
+ <form onSubmit={handleCustomPairSubmit} className="flex items-center gap-1">
+ <input
+ type="text"
+ value={customPair}
+ onChange={(e) => setCustomPair(e.target.value)}
+ placeholder="BTC/USD"
+ className="bg-[#1a1a1a] text-gray-200 text-xs px-3 py-1 border border-gray-700 focus:outline-none focus:border-orange-500 w-24"
+ />
+ <button
+ type="submit"
+ className="bg-orange-600 text-black text-xs px-2 py-1 font-semibold hover:bg-orange-500 transition-colors"
+ >
+ Go
+ </button>
+ </form>
+ </div>
+
+ {/* Pair Buttons */}
+ <div className="flex items-center gap-2 overflow-x-auto flex-1">
+ {filteredPairs.map(pair => (
+ <button
+ key={pair}
+ onClick={() => setSelectedPair(pair)}
+ className={`px-3 py-1 rounded text-xs font-semibold whitespace-nowrap transition-colors ${
+ selectedPair === pair
+ ? 'bg-orange-600 text-black'
+ : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
+ }`}
+ >
+ {pair}
+ </button>
+ ))}
+ {filteredPairs.length === 0 && (
+ <span className="text-xs text-gray-500">No pairs found</span>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Main Content */}
+ <div className="flex-1 flex overflow-hidden">
+ {/* Left Panel - Ticker & Stats */}
+ <div className="w-80 border-r border-gray-800 flex flex-col">
+ {/* Price Display */}
+ <div className="bg-[#0d0d0d] border-b border-gray-800 p-4">
+ <div className="mb-2">
+ <div className="text-xs text-gray-500 mb-1">LAST PRICE</div>
+ <div className={`text-3xl font-bold ${priceChangeColor}`}>
+ ${tickerData?.last?.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '---'}
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-3 text-xs">
+ <div>
+ <div className="text-gray-500">24H CHANGE</div>
+ <div className={priceChangeColor}>
+ {tickerData && tickerData.change !== undefined
+ ? `${tickerData.change >= 0 ? '+' : ''}${tickerData.change.toFixed(2)}`
+ : '---'}
+ <span className="ml-1">
+ ({tickerData?.change_pct?.toFixed(2) || '---'}%)
+ </span>
+ </div>
+ </div>
+ <div>
+ <div className="text-gray-500">SPREAD</div>
+ <div className="text-gray-300">{spread}%</div>
+ </div>
+ <div>
+ <div className="text-gray-500">24H HIGH</div>
+ <div className="text-green-400">${tickerData?.high?.toLocaleString() || '---'}</div>
+ </div>
+ <div>
+ <div className="text-gray-500">24H LOW</div>
+ <div className="text-red-400">${tickerData?.low?.toLocaleString() || '---'}</div>
+ </div>
+ <div>
+ <div className="text-gray-500">24H VOLUME</div>
+ <div className="text-gray-300">{tickerData?.volume?.toFixed(2) || '---'}</div>
+ </div>
+ <div>
+ <div className="text-gray-500">VWAP</div>
+ <div className="text-gray-300">${tickerData?.vwap?.toFixed(2) || '---'}</div>
+ </div>
+ </div>
+ </div>
+
+ {/* BID/ASK */}
+ <div className="bg-[#0d0d0d] border-b border-gray-800 p-4">
+ <div className="grid grid-cols-2 gap-3">
+ <div>
+ <div className="text-xs text-gray-500 mb-1">BID</div>
+ <div className="text-lg font-bold text-green-400">
+ ${tickerData?.bid?.toLocaleString('en-US', { minimumFractionDigits: 2 }) || '---'}
+ </div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 mb-1">ASK</div>
+ <div className="text-lg font-bold text-red-400">
+ ${tickerData?.ask?.toLocaleString('en-US', { minimumFractionDigits: 2 }) || '---'}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Trades Feed */}
+ <div className="flex-1 flex flex-col bg-[#0a0a0a]">
+ <div className="bg-[#0d0d0d] border-b border-gray-800 px-4 py-2 flex items-center gap-2">
+ <Activity className="w-4 h-4 text-orange-500" />
+ <span className="text-xs font-semibold text-gray-400">RECENT TRADES</span>
+ </div>
+ <div className="flex-1 overflow-y-auto">
+ <div className="text-[10px] px-2 py-1 bg-[#0d0d0d] grid grid-cols-3 gap-2 text-gray-500 sticky top-0">
+ <div>TIME</div>
+ <div className="text-right">PRICE</div>
+ <div className="text-right">SIZE</div>
+ </div>
+ {trades.map((trade, idx) => (
+ <div
+ key={`${trade.timestamp}-${idx}`}
+ className={`text-xs px-2 py-1 grid grid-cols-3 gap-2 border-b border-gray-900 hover:bg-gray-900 ${
+ trade.side === 'buy' ? 'bg-green-950/10' : 'bg-red-950/10'
+ }`}
+ >
+ <div className="text-gray-500">
+ {new Date(trade.timestamp).toLocaleTimeString('en-US', {
+ hour12: false,
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit'
+ })}
+ </div>
+ <div className={`text-right font-semibold ${trade.side === 'buy' ? 'text-green-400' : 'text-red-400'}`}>
+ ${trade.price.toFixed(2)}
+ </div>
+ <div className="text-right text-gray-300">
+ {trade.qty.toFixed(6)}
+ </div>
+ </div>
+ ))}
+ {trades.length === 0 && (
+ <div className="p-4 text-center text-gray-600 text-xs">
+ Waiting for trades...
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Center Panel - Chart */}
+ <div className="flex-1 flex flex-col bg-[#0a0a0a]">
+ {/* Chart Controls */}
+ <div className="bg-[#0d0d0d] border-b border-gray-800 px-4 py-2 flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <BarChart3 className="w-4 h-4 text-orange-500" />
+ <span className="text-xs font-semibold text-gray-400">CANDLESTICK CHART</span>
+ </div>
+ <div className="flex items-center gap-2">
+ {OHLC_INTERVALS.map(interval => (
+ <button
+ key={interval.value}
+ onClick={() => setOhlcInterval(interval.value)}
+ className={`px-2 py-1 rounded text-[10px] font-semibold transition-colors ${
+ ohlcInterval === interval.value
+ ? 'bg-orange-600 text-black'
+ : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
+ }`}
+ >
+ {interval.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Chart */}
+ <div ref={chartContainerRef} className="flex-1 bg-[#0a0a0a]" />
+ </div>
+
+ {/* Right Panel - Order Book */}
+ <div className="w-96 border-l border-gray-800 flex flex-col bg-[#0a0a0a]">
+ {/* Order Book Header */}
+ <div className="bg-[#0d0d0d] border-b border-gray-800 px-4 py-2 flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <BookOpen className="w-4 h-4 text-orange-500" />
+ <span className="text-xs font-semibold text-gray-400">ORDER BOOK</span>
+ </div>
+ <select
+ value={bookDepth}
+ onChange={(e) => setBookDepth(Number(e.target.value))}
+ className="bg-gray-800 text-gray-300 text-[10px] px-2 py-1 rounded border border-gray-700 focus:outline-none focus:border-orange-500"
+ >
+ {ORDERBOOK_DEPTHS.map(depth => (
+ <option key={depth} value={depth}>
+ DEPTH: {depth}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Order Book Content */}
+ <div className="flex-1 flex flex-col overflow-hidden">
+ {/* Asks (Sell Orders) */}
+ <div className="flex-1 flex flex-col-reverse overflow-y-auto">
+ <div className="text-[10px] px-3 py-1 bg-[#0d0d0d] grid grid-cols-3 gap-2 text-gray-500 sticky bottom-0">
+ <div className="text-right">PRICE</div>
+ <div className="text-right">SIZE</div>
+ <div className="text-right">TOTAL</div>
+ </div>
+ {orderBook.asks.slice(0, 15).reverse().map((level, idx) => {
+ const total = orderBook.asks.slice(0, idx + 1).reduce((sum, l) => sum + l.qty, 0);
+ const maxTotal = Math.max(...orderBook.asks.slice(0, 15).map((_, i) =>
+ orderBook.asks.slice(0, i + 1).reduce((sum, l) => sum + l.qty, 0)
+ ));
+ const percentage = maxTotal > 0 ? (total / maxTotal) * 100 : 0;
+
+ return (
+ <div
+ key={`ask-${level.price}-${idx}`}
+ className="text-xs px-3 py-0.5 grid grid-cols-3 gap-2 relative hover:bg-red-950/20"
+ >
+ <div
+ className="absolute inset-0 bg-red-950/20"
+ style={{ width: `${percentage}%`, right: 0, left: 'auto' }}
+ />
+ <div className="text-right text-red-400 font-semibold relative z-10">
+ {level.price.toFixed(2)}
+ </div>
+ <div className="text-right text-gray-300 relative z-10">
+ {level.qty.toFixed(6)}
+ </div>
+ <div className="text-right text-gray-500 relative z-10">
+ {total.toFixed(6)}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+
+ {/* Spread */}
+ <div className="bg-[#0d0d0d] border-y border-gray-800 px-3 py-2 text-center">
+ <div className="text-[10px] text-gray-500">SPREAD</div>
+ <div className="text-sm font-bold text-yellow-400">{spread}%</div>
+ </div>
+
+ {/* Bids (Buy Orders) */}
+ <div className="flex-1 overflow-y-auto">
+ <div className="text-[10px] px-3 py-1 bg-[#0d0d0d] grid grid-cols-3 gap-2 text-gray-500 sticky top-0">
+ <div className="text-right">PRICE</div>
+ <div className="text-right">SIZE</div>
+ <div className="text-right">TOTAL</div>
+ </div>
+ {orderBook.bids.slice(0, 15).map((level, idx) => {
+ const total = orderBook.bids.slice(0, idx + 1).reduce((sum, l) => sum + l.qty, 0);
+ const maxTotal = Math.max(...orderBook.bids.slice(0, 15).map((_, i) =>
+ orderBook.bids.slice(0, i + 1).reduce((sum, l) => sum + l.qty, 0)
+ ));
+ const percentage = maxTotal > 0 ? (total / maxTotal) * 100 : 0;
+
+ return (
+ <div
+ key={`bid-${level.price}-${idx}`}
+ className="text-xs px-3 py-0.5 grid grid-cols-3 gap-2 relative hover:bg-green-950/20"
+ >
+ <div
+ className="absolute inset-0 bg-green-950/20"
+ style={{ width: `${percentage}%`, right: 0, left: 'auto' }}
+ />
+ <div className="text-right text-green-400 font-semibold relative z-10">
+ {level.price.toFixed(2)}
+ </div>
+ <div className="text-right text-gray-300 relative z-10">
+ {level.qty.toFixed(6)}
+ </div>
+ <div className="text-right text-gray-500 relative z-10">
+ {total.toFixed(6)}
+ </div>
+ </div>
+ );
+ })}
+ {orderBook.bids.length === 0 && orderBook.asks.length === 0 && (
+ <div className="p-4 text-center text-gray-600 text-xs">
+ Loading order book...
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Status Bar */}
+ <div className="bg-[#0d0d0d] border-t border-gray-800 px-4 py-1 flex items-center justify-between text-[10px] text-gray-500">
+ <div className="flex items-center gap-4">
+ <span>KRAKEN WEBSOCKET v2</span>
+ <span>•</span>
+ <span>PAIR: {selectedPair}</span>
+ <span>•</span>
+ <span>INTERVAL: {OHLC_INTERVALS.find(i => i.value === ohlcInterval)?.label}</span>
+ <span>•</span>
+ <span>DEPTH: {bookDepth}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <span>{new Date().toLocaleTimeString('en-US', { hour12: false })}</span>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsx b/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsx
index b5ca15270..69da6b3ca 100644
--- a/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsx
@@ -1,4 +1,5 @@
import React, { useState, useEffect, useRef } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface MarkerData {
lat: number;
@@ -24,12 +25,14 @@ interface IntelligenceData {
}
export default function MaritimeTab() {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [markers, setMarkers] = useState<MarkerData[]>([]);
const [selectedRoute, setSelectedRoute] = useState<TradeRoute | null>(null);
const [markerType, setMarkerType] = useState<MarkerData['type']>('Ship');
const [showRoutes, setShowRoutes] = useState(true);
const [showShips, setShowShips] = useState(true);
const [showPlanes, setShowPlanes] = useState(true);
+ const [showSatellites, setShowSatellites] = useState(true);
const [isRotating, setIsRotating] = useState(true);
const [intelligence, setIntelligence] = useState<IntelligenceData>({
timestamp: new Date().toISOString(),
@@ -384,7 +387,7 @@ export default function MaritimeTab() {
lat: pos.lat,
lng: pos.lng,
size: 0.15,
- color: 'rgba(255, 255, 255, 0.95)',
+ color: 'rgba(100, 180, 255, 0.95)',
altitude: 0.003,
label: ship.label,
value: ship.value,
@@ -395,30 +398,37 @@ export default function MaritimeTab() {
allLabels = shipData;
- // Use customLayerData for ships - they rotate with the globe properly
+ // Use htmlElementsData for ships with ship icons (similar to planes)
const initialShipPoints = generateShipPoints(shipData);
world.customLayerData(initialShipPoints)
.customThreeObject(d => {
- // Create diamond/pyramid shape for ship marker (distinct from circular ports)
- const geometry = new THREE.TetrahedronGeometry(0.7);
- const material = new THREE.MeshBasicMaterial({
- color: 0x00ccff,
- transparent: true,
- opacity: 0.9
- });
- const mesh = new THREE.Mesh(geometry, material);
-
- // Add subtle glow effect
- const glowGeometry = new THREE.SphereGeometry(1.0, 8, 8);
- const glowMaterial = new THREE.MeshBasicMaterial({
- color: 0x00ccff,
+ // Create HTML element for ship icon
+ const el = document.createElement('div');
+ el.innerHTML = '🚢';
+ el.style.color = 'rgba(100, 180, 255, 0.95)';
+ el.style.fontSize = '16px';
+ el.style.cursor = 'pointer';
+ el.style.filter = 'drop-shadow(0 0 4px rgba(100, 180, 255, 0.8))';
+ el.title = \`\${d.label} - \${d.value} (\${d.vessels} vessels)\`;
+
+ // Convert HTML to texture for THREE.js
+ const canvas = document.createElement('canvas');
+ canvas.width = 64;
+ canvas.height = 64;
+ const ctx = canvas.getContext('2d');
+ ctx.font = '48px Arial';
+ ctx.fillText('🚢', 8, 48);
+
+ const texture = new THREE.CanvasTexture(canvas);
+ const material = new THREE.SpriteMaterial({
+ map: texture,
transparent: true,
- opacity: 0.2
+ opacity: 0.95
});
- const glow = new THREE.Mesh(glowGeometry, glowMaterial);
- mesh.add(glow);
+ const sprite = new THREE.Sprite(material);
+ sprite.scale.set(2, 2, 1);
- return mesh;
+ return sprite;
})
.customThreeObjectUpdate((obj, d) => {
Object.assign(obj.position, world.getCoords(d.lat, d.lng, d.altitude));
@@ -512,6 +522,235 @@ export default function MaritimeTab() {
}, 200);
}
+ function createSatellites() {
+ // Create satellite data in different orbits with unique orbital paths
+ // Speeds reduced significantly for more realistic and pleasant viewing
+ const satelliteOrbits = [
+ // Low Earth Orbit satellites (LEO) - closer to Earth, faster orbits
+ { name: 'GPS-1', inclination: 55, altitude: 0.35, speed: 0.0008, color: '#00ff00', orbitId: 'gps' },
+ { name: 'GPS-2', inclination: 55, altitude: 0.35, speed: 0.0008, color: '#00ff00', phaseOffset: Math.PI, orbitId: 'gps' },
+ { name: 'IRNSS-1', inclination: 29, altitude: 0.37, speed: 0.0007, color: '#ffd700', orbitId: 'irnss' },
+ { name: 'IRNSS-2', inclination: 29, altitude: 0.37, speed: 0.0007, color: '#ffd700', phaseOffset: Math.PI / 2, orbitId: 'irnss' },
+ { name: 'Starlink-1', inclination: 53, altitude: 0.32, speed: 0.0009, color: '#00ccff', orbitId: 'starlink' },
+ { name: 'Starlink-2', inclination: 53, altitude: 0.32, speed: 0.0009, color: '#00ccff', phaseOffset: 2 * Math.PI / 3, orbitId: 'starlink' },
+ { name: 'Starlink-3', inclination: 53, altitude: 0.32, speed: 0.0009, color: '#00ccff', phaseOffset: 4 * Math.PI / 3, orbitId: 'starlink' },
+ // Medium Earth Orbit (MEO) - higher altitude, medium speed
+ { name: 'GLONASS-1', inclination: 64.8, altitude: 0.42, speed: 0.0006, color: '#ff6b6b', orbitId: 'glonass' },
+ { name: 'GLONASS-2', inclination: 64.8, altitude: 0.42, speed: 0.0006, color: '#ff6b6b', phaseOffset: Math.PI / 3, orbitId: 'glonass' },
+ { name: 'Galileo-1', inclination: 56, altitude: 0.40, speed: 0.0007, color: '#9d4edd', orbitId: 'galileo' },
+ { name: 'Galileo-2', inclination: 56, altitude: 0.40, speed: 0.0007, color: '#9d4edd', phaseOffset: Math.PI / 2, orbitId: 'galileo' },
+ // Geostationary orbit representation (higher altitude, slowest)
+ { name: 'INSAT-1', inclination: 0, altitude: 0.50, speed: 0.0004, color: '#ff9500', orbitId: 'insat' },
+ { name: 'INSAT-2', inclination: 0, altitude: 0.50, speed: 0.0004, color: '#ff9500', phaseOffset: Math.PI, orbitId: 'insat' },
+ ];
+
+ const satellites = satelliteOrbits.map((orbit, idx) => ({
+ id: idx,
+ name: orbit.name,
+ inclination: orbit.inclination,
+ altitude: orbit.altitude,
+ speed: orbit.speed,
+ color: orbit.color,
+ orbitId: orbit.orbitId,
+ phase: orbit.phaseOffset || 0
+ }));
+
+ // Create orbital ring paths - draw complete circles for each unique orbit
+ function createOrbitalPaths() {
+ const uniqueOrbits = new Map();
+
+ satelliteOrbits.forEach(orbit => {
+ if (!uniqueOrbits.has(orbit.orbitId)) {
+ uniqueOrbits.set(orbit.orbitId, {
+ inclination: orbit.inclination,
+ altitude: orbit.altitude,
+ color: orbit.color,
+ name: orbit.orbitId
+ });
+ }
+ });
+
+ const orbitalPaths = [];
+ uniqueOrbits.forEach((orbit, orbitId) => {
+ const numPoints = 100; // Number of points to draw the orbital ring
+ const pathPoints = [];
+
+ for (let i = 0; i <= numPoints; i++) {
+ const angle = (i / numPoints) * 2 * Math.PI;
+ const inclinationRad = (orbit.inclination * Math.PI) / 180;
+
+ // Calculate position on orbit
+ const x = Math.cos(angle);
+ const y = Math.sin(angle) * Math.cos(inclinationRad);
+ const z = Math.sin(angle) * Math.sin(inclinationRad);
+
+ // Convert to lat/lng
+ const lat = Math.asin(y) * (180 / Math.PI);
+ const lng = Math.atan2(z, x) * (180 / Math.PI);
+
+ pathPoints.push([lat, lng]);
+ }
+
+ orbitalPaths.push({
+ id: orbitId,
+ color: orbit.color,
+ altitude: orbit.altitude,
+ points: pathPoints
+ });
+ });
+
+ return orbitalPaths;
+ }
+
+ const orbitalPaths = createOrbitalPaths();
+
+ // Store orbital paths for toggling
+ orbitalPathsData = orbitalPaths;
+
+ // Draw orbital rings using pathsData
+ world.pathsData(orbitalPaths)
+ .pathPoints('points')
+ .pathPointLat(p => p[0])
+ .pathPointLng(p => p[1])
+ .pathColor('color')
+ .pathStroke(0.8)
+ .pathDashLength(0.5)
+ .pathDashGap(0.1)
+ .pathDashAnimateTime(20000)
+ .pathTransitionDuration(0)
+ .pathPointAlt('altitude');
+
+ // Function to calculate satellite position in orbit
+ function calculateSatellitePosition(sat, time) {
+ const angle = sat.phase + time * sat.speed;
+
+ // Convert orbital elements to 3D position
+ const inclinationRad = (sat.inclination * Math.PI) / 180;
+
+ // Orbital position
+ const x = Math.cos(angle);
+ const y = Math.sin(angle) * Math.cos(inclinationRad);
+ const z = Math.sin(angle) * Math.sin(inclinationRad);
+
+ // Convert to lat/lng (approximate)
+ const lat = Math.asin(y) * (180 / Math.PI);
+ const lng = Math.atan2(z, x) * (180 / Math.PI);
+
+ return { lat, lng, altitude: sat.altitude };
+ }
+
+ // Create satellite objects with animation
+ const satelliteData = satellites.map((sat, idx) => ({
+ ...sat,
+ progress: (idx / satellites.length) // Distribute satellites evenly around orbit initially
+ }));
+
+ // Function to generate satellite HTML elements
+ function generateSatellitePoints(satsData) {
+ return satsData.map(sat => {
+ const angle = sat.progress * 2 * Math.PI;
+ const inclinationRad = (sat.inclination * Math.PI) / 180;
+
+ // Calculate position on orbit
+ const x = Math.cos(angle);
+ const y = Math.sin(angle) * Math.cos(inclinationRad);
+ const z = Math.sin(angle) * Math.sin(inclinationRad);
+
+ // Convert to lat/lng
+ const lat = Math.asin(y) * (180 / Math.PI);
+ const lng = Math.atan2(z, x) * (180 / Math.PI);
+
+ return {
+ lat: lat,
+ lng: lng,
+ altitude: sat.altitude,
+ name: sat.name,
+ color: sat.color
+ };
+ });
+ }
+
+ // Initial satellite positions - use objectsData for satellites (separate from planes)
+ const initialSatellitePoints = generateSatellitePoints(satelliteData);
+
+ world.objectsData(initialSatellitePoints)
+ .objectLat('lat')
+ .objectLng('lng')
+ .objectAltitude('altitude')
+ .objectLabel(d => \`
+ <div style="background: rgba(10,10,10,0.92); padding: 5px 9px; border-left: 2px solid \${d.color}; font-family: 'Segoe UI', sans-serif; font-size: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.4);">
+ <span style="color: #e0e0e0; font-weight: 500;">🛰 \${d.name}</span>
+ </div>
+ \`)
+ .objectThreeObject(d => {
+ // Create satellite icon using canvas texture with better visibility
+ const canvas = document.createElement('canvas');
+ canvas.width = 128;
+ canvas.height = 128;
+ const ctx = canvas.getContext('2d');
+
+ // Add colored background circle for visibility
+ ctx.beginPath();
+ ctx.arc(64, 64, 50, 0, 2 * Math.PI);
+ ctx.fillStyle = d.color;
+ ctx.globalAlpha = 0.4;
+ ctx.fill();
+ ctx.globalAlpha = 1.0;
+
+ // Add bright border
+ ctx.strokeStyle = d.color;
+ ctx.lineWidth = 3;
+ ctx.stroke();
+
+ // Draw satellite emoji larger and centered
+ ctx.font = 'bold 70px Arial';
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillStyle = '#ffffff';
+ ctx.fillText('🛰', 64, 64);
+
+ const texture = new THREE.CanvasTexture(canvas);
+ const material = new THREE.SpriteMaterial({
+ map: texture,
+ transparent: true,
+ opacity: 1.0,
+ sizeAttenuation: true
+ });
+ const sprite = new THREE.Sprite(material);
+ sprite.scale.set(4, 4, 1);
+
+ // Add pulsing glow ring around satellite
+ const ringGeometry = new THREE.RingGeometry(1.5, 2.0, 16);
+ const ringMaterial = new THREE.MeshBasicMaterial({
+ color: d.color,
+ transparent: true,
+ opacity: 0.6,
+ side: THREE.DoubleSide
+ });
+ const ring = new THREE.Mesh(ringGeometry, ringMaterial);
+
+ const group = new THREE.Group();
+ group.add(sprite);
+ group.add(ring);
+
+ return group;
+ });
+
+ // Animate satellites along their orbits at a gentle, realistic pace
+ setInterval(() => {
+ if (showSatellitesFlag) {
+ // Update progress for each satellite with reduced multiplier
+ satelliteData.forEach(sat => {
+ sat.progress = (sat.progress + sat.speed * 0.15) % 1.0;
+ });
+
+ // Regenerate satellite positions
+ const updatedSatellitePoints = generateSatellitePoints(satelliteData);
+ world.objectsData(updatedSatellitePoints);
+ }
+ }, 100);
+ }
+
window.addMarker = function(lat, lng, title, type) {
const icons = {
'Ship': '🚢',
@@ -614,6 +853,23 @@ export default function MaritimeTab() {
console.log('Globe rotation:', shouldRotate ? 'enabled' : 'disabled');
};
+ var showSatellitesFlag = true;
+ var orbitalPathsData = [];
+
+ window.toggleSatellites = function() {
+ showSatellitesFlag = !showSatellitesFlag;
+
+ if (!showSatellitesFlag) {
+ // Hide satellites and orbital paths
+ world.objectsData([]);
+ world.pathsData([]);
+ } else {
+ // Show orbital paths again
+ world.pathsData(orbitalPathsData);
+ // Satellites will be updated by the interval
+ }
+ };
+
// Enable auto-rotation with enhanced zoom
world.controls().autoRotate = true;
world.controls().autoRotateSpeed = 0.2; // Slower, more professional rotation
@@ -763,6 +1019,7 @@ export default function MaritimeTab() {
createRoutes();
createShips();
createPlanes();
+ createSatellites();
// Handle window resize
window.addEventListener('resize', () => {
@@ -854,10 +1111,26 @@ export default function MaritimeTab() {
<div style={{ color: '#888', fontSize: '8px' }}>ROUTES</div>
<div style={{ color: '#0ff', fontSize: '16px', fontWeight: 'bold' }}>{intelligence.monitored_routes}</div>
</div>
+ <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
+ <div style={{ color: '#888', fontSize: '8px' }}>AIRCRAFT</div>
+ <div style={{ color: 'rgba(255, 200, 100, 0.95)', fontSize: '16px', fontWeight: 'bold' }}>342</div>
+ </div>
+ <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
+ <div style={{ color: '#888', fontSize: '8px' }}>SATELLITES</div>
+ <div style={{ color: 'rgba(138, 43, 226, 0.9)', fontSize: '16px', fontWeight: 'bold' }}>13</div>
+ </div>
<div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px', gridColumn: 'span 2' }}>
<div style={{ color: '#888', fontSize: '8px' }}>TRADE VOLUME (24H)</div>
<div style={{ color: '#00ff00', fontSize: '16px', fontWeight: 'bold' }}>{intelligence.trade_volume}</div>
</div>
+ <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
+ <div style={{ color: '#888', fontSize: '8px' }}>MAJOR PORTS</div>
+ <div style={{ color: '#ffa500', fontSize: '14px', fontWeight: 'bold' }}>6</div>
+ </div>
+ <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
+ <div style={{ color: '#888', fontSize: '8px' }}>AIRPORTS</div>
+ <div style={{ color: '#9d4edd', fontSize: '14px', fontWeight: 'bold' }}>8</div>
+ </div>
</div>
</div>
@@ -965,6 +1238,26 @@ export default function MaritimeTab() {
>
AIRCRAFT
</button>
+ <button
+ onClick={() => {
+ setShowSatellites(!showSatellites);
+ if (mapRef.current?.contentWindow) {
+ (mapRef.current.contentWindow as any).toggleSatellites?.();
+ }
+ }}
+ style={{
+ flex: 1,
+ background: showSatellites ? 'rgba(138, 43, 226, 0.9)' : '#0a0a0a',
+ color: showSatellites ? '#fff' : 'rgba(138, 43, 226, 0.9)',
+ border: '1px solid rgba(138, 43, 226, 0.9)',
+ padding: '6px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: 'bold'
+ }}
+ >
+ SATELLITES
+ </button>
</div>
<button
onClick={() => {
@@ -1152,6 +1445,15 @@ export default function MaritimeTab() {
<div style={{ marginBottom: '4px' }}>
<span style={{ color: '#0ff' }}>●</span> AIS transponders: STREAMING
</div>
+ <div style={{ marginBottom: '4px' }}>
+ <span style={{ color: 'rgba(138, 43, 226, 0.9)' }}>●</span> Orbital tracking: 13 SATs
+ </div>
+ <div style={{ marginBottom: '4px' }}>
+ <span style={{ color: 'rgba(255, 200, 100, 0.95)' }}>●</span> Air traffic: MONITORED
+ </div>
+ <div style={{ marginBottom: '4px' }}>
+ <span style={{ color: '#0ff' }}>●</span> Maritime routes: {tradeRoutes.length} corridors
+ </div>
<div style={{ marginTop: '8px', padding: '6px', background: '#000', border: '1px solid #1a1a1a', color: '#ffd700' }}>
⚠ CLASSIFIED: For authorized personnel only
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx b/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx
index 33de75b7e..bc9098e4f 100644
--- a/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx
@@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { MarketplaceApiService, Dataset } from '@/services/marketplaceApi';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface MarketProduct {
id: string;
@@ -22,6 +23,20 @@ interface MarketProduct {
}
const MarketplaceTab: React.FC = () => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
+ const C = {
+ ORANGE: colors.primary,
+ WHITE: colors.text,
+ RED: colors.alert,
+ GREEN: colors.secondary,
+ YELLOW: colors.warning,
+ GRAY: colors.textMuted,
+ BLUE: colors.info,
+ PURPLE: colors.purple,
+ CYAN: colors.accent,
+ DARK_BG: colors.background,
+ PANEL_BG: colors.panel
+ };
const { session } = useAuth();
const [currentScreen, setCurrentScreen] = useState<'BROWSE' | 'DETAILS' | 'CART' | 'UPLOAD' | 'MY_PURCHASES' | 'ANALYTICS' | 'ADMIN_STATS'>('BROWSE');
const [selectedProduct, setSelectedProduct] = useState<MarketProduct | null>(null);
@@ -44,21 +59,6 @@ const MarketplaceTab: React.FC = () => {
tags: ''
});
- // Colors
- const C = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- RED: '#FF0000',
- GREEN: '#00C800',
- YELLOW: '#FFFF00',
- GRAY: '#787878',
- BLUE: '#6496FA',
- PURPLE: '#C864FF',
- CYAN: '#00FFFF',
- DARK_BG: '#000000',
- PANEL_BG: '#0a0a0a'
- };
-
// Fetch datasets from API
const fetchDatasets = async () => {
if (!session?.api_key) return;
diff --git a/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx b/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx
index a9d4367b5..2148e85ba 100644
--- a/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx
@@ -1,11 +1,13 @@
import React, { useState, useEffect } from 'react';
import { Edit2 } from 'lucide-react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { marketDataService, QuoteData } from '../../services/marketDataService';
import { tickerStorage } from '../../services/tickerStorageService';
import { sqliteService } from '../../services/sqliteService';
import TickerEditModal from './TickerEditModal';
const MarketsTab: React.FC = () => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
const [lastUpdate, setLastUpdate] = useState(new Date());
const [isUpdating, setIsUpdating] = useState(false);
@@ -25,15 +27,6 @@ const MarketsTab: React.FC = () => {
// User preferences
const [preferences, setPreferences] = useState(tickerStorage.loadPreferences());
- // Bloomberg colors
- const BLOOMBERG_ORANGE = '#FFA500';
- const BLOOMBERG_WHITE = '#FFFFFF';
- const BLOOMBERG_RED = '#FF0000';
- const BLOOMBERG_GREEN = '#00C800';
- const BLOOMBERG_GRAY = '#787878';
- const BLOOMBERG_DARK_BG = '#1a1a1a';
- const BLOOMBERG_PANEL_BG = '#000000';
-
// Fetch market data progressively (display as data arrives)
const fetchMarketData = async () => {
setIsUpdating(true);
@@ -147,8 +140,8 @@ const MarketsTab: React.FC = () => {
// Create market panel
const createMarketPanel = (title: string, quotes: QuoteData[]) => (
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
flex: '1 1 calc(33.333% - 16px)',
minWidth: '300px',
maxWidth: '600px',
@@ -159,13 +152,13 @@ const MarketsTab: React.FC = () => {
}}>
{/* Panel Header with Edit Icon */}
<div style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_ORANGE,
+ backgroundColor: colors.background,
+ color: colors.primary,
padding: '8px',
- fontSize: '14px',
+ fontSize: fontSize.subheading,
fontWeight: 'bold',
textAlign: 'center',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ borderBottom: `1px solid ${colors.textMuted}`,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
@@ -174,7 +167,7 @@ const MarketsTab: React.FC = () => {
{title.toUpperCase()}
<Edit2
size={14}
- style={{ cursor: 'pointer', color: BLOOMBERG_WHITE }}
+ style={{ cursor: 'pointer', color: colors.text }}
onClick={() => openEditModal(title)}
/>
</div>
@@ -185,11 +178,11 @@ const MarketsTab: React.FC = () => {
gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr 1fr',
gap: '4px',
padding: '4px 8px',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
- fontSize: '12px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontSize: fontSize.body,
fontWeight: 'bold',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ borderBottom: `1px solid ${colors.textMuted}`
}}>
<div>SYMBOL</div>
<div style={{ textAlign: 'right' }}>PRICE</div>
@@ -203,8 +196,8 @@ const MarketsTab: React.FC = () => {
<div style={{ flex: 1, overflow: 'auto' }}>
{quotes.length === 0 ? (
<div style={{
- color: BLOOMBERG_GRAY,
- fontSize: '11px',
+ color: colors.textMuted,
+ fontSize: fontSize.body,
textAlign: 'center',
padding: '16px'
}}>
@@ -217,28 +210,28 @@ const MarketsTab: React.FC = () => {
gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr 1fr',
gap: '4px',
padding: '2px 8px',
- fontSize: '10px',
+ fontSize: fontSize.small,
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
borderBottom: `1px solid rgba(120,120,120,0.3)`,
minHeight: '18px',
alignItems: 'center'
}}>
- <div style={{ color: BLOOMBERG_WHITE }}>{quote.symbol}</div>
- <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{quote.price.toFixed(2)}</div>
+ <div style={{ color: colors.text }}>{quote.symbol}</div>
+ <div style={{ color: colors.text, textAlign: 'right' }}>{quote.price.toFixed(2)}</div>
<div style={{
- color: quote.change >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ color: quote.change >= 0 ? colors.secondary : colors.alert,
textAlign: 'right'
}}>{formatChange(quote.change)}</div>
<div style={{
- color: quote.change_percent >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ color: quote.change_percent >= 0 ? colors.secondary : colors.alert,
textAlign: 'right'
}}>{formatPercent(quote.change_percent)}</div>
<div style={{
- color: BLOOMBERG_WHITE,
+ color: colors.text,
textAlign: 'right'
}}>{quote.high ? quote.high.toFixed(2) : '-'}</div>
<div style={{
- color: BLOOMBERG_WHITE,
+ color: colors.text,
textAlign: 'right'
}}>{quote.low ? quote.low.toFixed(2) : '-'}</div>
</div>
@@ -254,8 +247,8 @@ const MarketsTab: React.FC = () => {
return (
<div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
flex: '1 1 calc(33.333% - 16px)',
minWidth: '300px',
maxWidth: '600px',
@@ -266,13 +259,13 @@ const MarketsTab: React.FC = () => {
}}>
{/* Panel Header */}
<div style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_ORANGE,
+ backgroundColor: colors.background,
+ color: colors.primary,
padding: '8px',
- fontSize: '14px',
+ fontSize: fontSize.subheading,
fontWeight: 'bold',
textAlign: 'center',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ borderBottom: `1px solid ${colors.textMuted}`
}}>
{title.toUpperCase()} - LIVE DATA
</div>
@@ -283,11 +276,11 @@ const MarketsTab: React.FC = () => {
gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
gap: '4px',
padding: '4px 8px',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
- fontSize: '12px',
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontSize: fontSize.body,
fontWeight: 'bold',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ borderBottom: `1px solid ${colors.textMuted}`
}}>
<div>SYMBOL</div>
<div>NAME</div>
@@ -300,8 +293,8 @@ const MarketsTab: React.FC = () => {
<div style={{ flex: 1, overflow: 'auto' }}>
{quotes.length === 0 ? (
<div style={{
- color: BLOOMBERG_GRAY,
- fontSize: '11px',
+ color: colors.textMuted,
+ fontSize: fontSize.body,
textAlign: 'center',
padding: '16px'
}}>
@@ -316,23 +309,23 @@ const MarketsTab: React.FC = () => {
gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
gap: '4px',
padding: '2px 8px',
- fontSize: '10px',
+ fontSize: fontSize.small,
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
borderBottom: `1px solid rgba(120,120,120,0.3)`,
minHeight: '18px',
alignItems: 'center'
}}>
- <div style={{ color: BLOOMBERG_WHITE }}>{quote.symbol}</div>
- <div style={{ color: BLOOMBERG_WHITE, overflow: 'hidden', textOverflow: 'ellipsis' }}>
+ <div style={{ color: colors.text }}>{quote.symbol}</div>
+ <div style={{ color: colors.text, overflow: 'hidden', textOverflow: 'ellipsis' }}>
{tickerInfo?.name || quote.symbol}
</div>
- <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{quote.price.toFixed(2)}</div>
+ <div style={{ color: colors.text, textAlign: 'right' }}>{quote.price.toFixed(2)}</div>
<div style={{
- color: quote.change >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ color: quote.change >= 0 ? colors.secondary : colors.alert,
textAlign: 'right'
}}>{formatChange(quote.change)}</div>
<div style={{
- color: quote.change_percent >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ color: quote.change_percent >= 0 ? colors.secondary : colors.alert,
textAlign: 'right'
}}>{formatPercent(quote.change_percent)}</div>
</div>
@@ -347,9 +340,11 @@ const MarketsTab: React.FC = () => {
return (
<div style={{
height: '100%',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
- fontFamily: 'Consolas, monospace',
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontFamily: fontFamily,
+ fontWeight: fontWeight,
+ fontStyle: fontStyle,
overflow: 'hidden',
display: 'flex',
flexDirection: 'column'
@@ -377,16 +372,16 @@ const MarketsTab: React.FC = () => {
alignItems: 'center',
flexWrap: 'wrap',
padding: '8px 12px',
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
fontSize: '13px',
gap: '8px',
flexShrink: 0
}}>
- <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>FINCEPT</span>
- <span style={{ color: BLOOMBERG_WHITE }}>MARKET TERMINAL - LIVE DATA</span>
- <span style={{ color: BLOOMBERG_GRAY }}>|</span>
- <span style={{ color: BLOOMBERG_WHITE, fontSize: '11px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>FINCEPT</span>
+ <span style={{ color: colors.text }}>MARKET TERMINAL - LIVE DATA</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.text, fontSize: '11px' }}>
{currentTime.toISOString().replace('T', ' ').substring(0, 19)}
</span>
</div>
@@ -397,8 +392,8 @@ const MarketsTab: React.FC = () => {
alignItems: 'center',
flexWrap: 'wrap',
padding: '8px 12px',
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
fontSize: '12px',
gap: '8px',
flexShrink: 0
@@ -406,7 +401,7 @@ const MarketsTab: React.FC = () => {
<button
onClick={fetchMarketData}
style={{
- backgroundColor: BLOOMBERG_ORANGE,
+ backgroundColor: colors.primary,
color: 'black',
border: 'none',
padding: '4px 12px',
@@ -420,7 +415,7 @@ const MarketsTab: React.FC = () => {
<button
onClick={() => setAutoUpdate(!autoUpdate)}
style={{
- backgroundColor: autoUpdate ? BLOOMBERG_GREEN : BLOOMBERG_GRAY,
+ backgroundColor: autoUpdate ? colors.secondary : colors.textMuted,
color: 'black',
border: 'none',
padding: '4px 12px',
@@ -435,9 +430,9 @@ const MarketsTab: React.FC = () => {
value={updateInterval}
onChange={(e) => setUpdateInterval(Number(e.target.value))}
style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: BLOOMBERG_WHITE,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.text,
padding: '4px 8px',
fontSize: '11px',
cursor: 'pointer'
@@ -448,14 +443,14 @@ const MarketsTab: React.FC = () => {
<option value={1800000}>30 min</option>
<option value={3600000}>1 hour</option>
</select>
- <span style={{ color: BLOOMBERG_GRAY }}>|</span>
- <span style={{ color: BLOOMBERG_GRAY, fontSize: '11px' }}>LAST UPDATE:</span>
- <span style={{ color: BLOOMBERG_WHITE, fontSize: '11px' }}>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>LAST UPDATE:</span>
+ <span style={{ color: colors.text, fontSize: '11px' }}>
{lastUpdate.toTimeString().substring(0, 8)}
</span>
- <span style={{ color: BLOOMBERG_GRAY }}>|</span>
- <span style={{ color: isUpdating ? BLOOMBERG_ORANGE : BLOOMBERG_GREEN, fontSize: '14px' }}>●</span>
- <span style={{ color: isUpdating ? BLOOMBERG_ORANGE : BLOOMBERG_GREEN, fontSize: '11px', fontWeight: 'bold' }}>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: isUpdating ? colors.primary : colors.secondary, fontSize: '14px' }}>●</span>
+ <span style={{ color: isUpdating ? colors.primary : colors.secondary, fontSize: '11px', fontWeight: 'bold' }}>
{isUpdating ? 'UPDATING' : 'LIVE'}
</span>
</div>
@@ -470,7 +465,7 @@ const MarketsTab: React.FC = () => {
}}>
{/* Global Markets */}
<div style={{
- color: BLOOMBERG_ORANGE,
+ color: colors.primary,
fontSize: '14px',
fontWeight: 'bold',
marginBottom: '8px',
@@ -478,7 +473,7 @@ const MarketsTab: React.FC = () => {
}}>
GLOBAL MARKETS
</div>
- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '16px' }}></div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '16px' }}></div>
<div style={{
display: 'flex',
@@ -493,7 +488,7 @@ const MarketsTab: React.FC = () => {
{/* Regional Markets */}
<div style={{
- color: BLOOMBERG_ORANGE,
+ color: colors.primary,
fontSize: '14px',
fontWeight: 'bold',
marginBottom: '8px',
@@ -502,7 +497,7 @@ const MarketsTab: React.FC = () => {
}}>
REGIONAL MARKETS - LIVE DATA
</div>
- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '16px' }}></div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '16px' }}></div>
<div style={{
display: 'flex',
@@ -517,11 +512,11 @@ const MarketsTab: React.FC = () => {
{/* Status Bar */}
<div style={{
- borderTop: `1px solid ${BLOOMBERG_GRAY}`,
- backgroundColor: BLOOMBERG_PANEL_BG,
+ borderTop: `1px solid ${colors.textMuted}`,
+ backgroundColor: colors.panel,
padding: '6px 12px',
fontSize: '10px',
- color: BLOOMBERG_GRAY,
+ color: colors.textMuted,
flexShrink: 0
}}>
<div style={{
@@ -535,7 +530,7 @@ const MarketsTab: React.FC = () => {
<span style={{ whiteSpace: 'nowrap' }}>
Connected: {Object.keys(regionalData).length} regional markets
{dbInitialized && (
- <span style={{ marginLeft: '8px', color: BLOOMBERG_GREEN }}>
+ <span style={{ marginLeft: '8px', color: colors.secondary }}>
| Cache: ENABLED
</span>
)}
diff --git a/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
index dba6c86c7..ee9fd8af0 100644
--- a/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
@@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import { fetchNewsWithCache, type NewsArticle, getRSSFeedCount, getActiveSources, isUsingMockData } from '../../services/newsService';
// Extend Window interface for Tauri
@@ -9,6 +10,7 @@ declare global {
}
const NewsTab: React.FC = () => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
const [activeFilter, setActiveFilter] = useState('ALL');
const [newsUpdateCount, setNewsUpdateCount] = useState(0);
@@ -19,19 +21,6 @@ const NewsTab: React.FC = () => {
const [selectedArticle, setSelectedArticle] = useState<NewsArticle | null>(null);
const [showWebView, setShowWebView] = useState(false);
- // Professional Financial Terminal Colors
- const TERMINAL_ORANGE = '#FFA500';
- const TERMINAL_WHITE = '#FFFFFF';
- const TERMINAL_RED = '#FF0000';
- const TERMINAL_GREEN = '#00C800';
- const TERMINAL_YELLOW = '#FFFF00';
- const TERMINAL_GRAY = '#787878';
- const TERMINAL_BLUE = '#6496FA';
- const TERMINAL_PURPLE = '#C864FF';
- const TERMINAL_CYAN = '#00FFFF';
- const TERMINAL_DARK_BG = '#000000';
- const TERMINAL_PANEL_BG = '#0a0a0a';
-
// Manual refresh function with force refresh
const handleRefresh = async () => {
setLoading(true);
@@ -101,29 +90,29 @@ const NewsTab: React.FC = () => {
const getPriorityColor = (priority: string) => {
switch (priority) {
- case 'FLASH': return TERMINAL_RED;
- case 'URGENT': return TERMINAL_ORANGE;
- case 'BREAKING': return TERMINAL_YELLOW;
- case 'ROUTINE': return TERMINAL_GREEN;
- default: return TERMINAL_GRAY;
+ case 'FLASH': return colors.alert;
+ case 'URGENT': return colors.primary;
+ case 'BREAKING': return colors.warning;
+ case 'ROUTINE': return colors.secondary;
+ default: return colors.textMuted;
}
};
const getSentimentColor = (sentiment: string) => {
switch (sentiment) {
- case 'BULLISH': return TERMINAL_GREEN;
- case 'BEARISH': return TERMINAL_RED;
- case 'NEUTRAL': return TERMINAL_YELLOW;
- default: return TERMINAL_GRAY;
+ case 'BULLISH': return colors.secondary;
+ case 'BEARISH': return colors.alert;
+ case 'NEUTRAL': return colors.warning;
+ default: return colors.textMuted;
}
};
const getImpactColor = (impact: string) => {
switch (impact) {
- case 'HIGH': return TERMINAL_RED;
- case 'MEDIUM': return TERMINAL_YELLOW;
- case 'LOW': return TERMINAL_GREEN;
- default: return TERMINAL_GRAY;
+ case 'HIGH': return colors.alert;
+ case 'MEDIUM': return colors.warning;
+ case 'LOW': return colors.secondary;
+ default: return colors.textMuted;
}
};
@@ -146,39 +135,41 @@ const NewsTab: React.FC = () => {
return (
<div style={{
height: '100%',
- backgroundColor: TERMINAL_DARK_BG,
- color: TERMINAL_WHITE,
- fontFamily: 'Consolas, monospace',
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontFamily: fontFamily,
+ fontWeight: fontWeight,
+ fontStyle: fontStyle,
overflow: 'hidden',
display: 'flex',
flexDirection: 'column',
- fontSize: '12px'
+ fontSize: fontSize.body
}}>
{/* Complex Header with News Ticker */}
<div style={{
- backgroundColor: TERMINAL_PANEL_BG,
- borderBottom: `1px solid ${TERMINAL_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
padding: '4px 8px',
flexShrink: 0
}}>
{/* Main Status Line */}
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px' }}>
- <span style={{ color: TERMINAL_ORANGE, fontWeight: 'bold' }}>FINCEPT TERMINAL PROFESSIONAL NEWS</span>
- <span style={{ color: TERMINAL_WHITE }}>|</span>
- <span style={{ color: TERMINAL_RED, fontWeight: 'bold', animation: 'blink 1s infinite' }}>LIVE FEED</span>
- <span style={{ color: TERMINAL_WHITE }}>|</span>
- <span style={{ color: TERMINAL_YELLOW }}>ALERTS: {alertCount}</span>
- <span style={{ color: TERMINAL_WHITE }}>|</span>
- <span style={{ color: TERMINAL_GREEN }}>● {getRSSFeedCount()} SOURCES</span>
- <span style={{ color: TERMINAL_WHITE }}>|</span>
- <span style={{ color: TERMINAL_WHITE }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
- <span style={{ color: TERMINAL_WHITE }}>|</span>
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>FINCEPT TERMINAL PROFESSIONAL NEWS</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.alert, fontWeight: 'bold', animation: 'blink 1s infinite' }}>LIVE FEED</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.warning }}>ALERTS: {alertCount}</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.secondary }}>● {getRSSFeedCount()} SOURCES</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.text }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
+ <span style={{ color: colors.text }}>|</span>
<button
onClick={handleRefresh}
disabled={loading}
style={{
- backgroundColor: loading ? TERMINAL_GRAY : TERMINAL_GREEN,
- color: TERMINAL_DARK_BG,
+ backgroundColor: loading ? colors.textMuted : colors.secondary,
+ color: colors.background,
border: 'none',
padding: '2px 8px',
fontSize: '11px',
@@ -197,7 +188,7 @@ const NewsTab: React.FC = () => {
{/* News Ticker - Continuous seamless scroll like Bloomberg */}
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px', marginBottom: '2px' }}>
- <span style={{ color: TERMINAL_YELLOW, fontWeight: 'bold' }}>BREAKING:</span>
+ <span style={{ color: colors.warning, fontWeight: 'bold' }}>BREAKING:</span>
<div className="ticker-wrap" style={{
flex: 1,
overflow: 'hidden',
@@ -209,23 +200,23 @@ const NewsTab: React.FC = () => {
<span className="ticker-item">{newsTickerText}</span>
</div>
</div>
- <span style={{ color: TERMINAL_GREEN, fontSize: '9px' }}>
+ <span style={{ color: colors.secondary, fontSize: '9px' }}>
● LIVE
</span>
</div>
{/* Sources and Stats */}
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '10px', flexWrap: 'wrap' }}>
- <span style={{ color: TERMINAL_GRAY }}>ACTIVE SOURCES:</span>
+ <span style={{ color: colors.textMuted }}>ACTIVE SOURCES:</span>
{activeSources.slice(0, 12).map((source, idx) => (
- <span key={idx} style={{ color: TERMINAL_GREEN }}>{source}●</span>
+ <span key={idx} style={{ color: colors.secondary }}>{source}●</span>
))}
- <span style={{ color: TERMINAL_WHITE }}>|</span>
- <span style={{ color: TERMINAL_GRAY }}>ARTICLES:</span>
- <span style={{ color: TERMINAL_CYAN }}>{newsArticles.length}</span>
- <span style={{ color: TERMINAL_WHITE }}>|</span>
- <span style={{ color: TERMINAL_GRAY }}>STATUS:</span>
- <span style={{ color: loading ? TERMINAL_YELLOW : TERMINAL_GREEN }}>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>ARTICLES:</span>
+ <span style={{ color: colors.accent }}>{newsArticles.length}</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>STATUS:</span>
+ <span style={{ color: loading ? colors.warning : colors.secondary }}>
{loading ? 'UPDATING...' : (isUsingMockData() ? '● DEMO MODE' : '● LIVE')}
</span>
</div>
@@ -233,8 +224,8 @@ const NewsTab: React.FC = () => {
{/* Function Keys Bar */}
<div style={{
- backgroundColor: TERMINAL_PANEL_BG,
- borderBottom: `1px solid ${TERMINAL_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
padding: '2px 4px',
flexShrink: 0
}}>
@@ -268,9 +259,9 @@ const NewsTab: React.FC = () => {
}
}}
style={{
- backgroundColor: activeFilter === item.filter ? TERMINAL_ORANGE : TERMINAL_DARK_BG,
- border: `1px solid ${TERMINAL_GRAY}`,
- color: activeFilter === item.filter ? TERMINAL_DARK_BG : TERMINAL_WHITE,
+ backgroundColor: activeFilter === item.filter ? colors.primary : colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: activeFilter === item.filter ? colors.background : colors.text,
padding: '2px 4px',
fontSize: '9px',
height: '16px',
@@ -280,7 +271,7 @@ const NewsTab: React.FC = () => {
fontWeight: activeFilter === item.filter ? 'bold' : 'normal',
cursor: 'pointer'
}}>
- <span style={{ color: TERMINAL_YELLOW }}>{item.key}:</span>
+ <span style={{ color: colors.warning }}>{item.key}:</span>
<span style={{ marginLeft: '2px' }}>{item.label}</span>
</button>
))}
@@ -294,22 +285,22 @@ const NewsTab: React.FC = () => {
{/* Left Panel - Breaking News Stream (Primary Feed) */}
<div style={{
flex: 1,
- backgroundColor: TERMINAL_PANEL_BG,
- border: `1px solid ${TERMINAL_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px',
overflow: 'auto'
}}>
- <div style={{ color: TERMINAL_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
PRIMARY NEWS FEED [{activeFilter}]
</div>
- <div style={{ borderBottom: `1px solid ${TERMINAL_GRAY}`, marginBottom: '4px' }}></div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
{loading && newsArticles.length === 0 ? (
- <div style={{ color: TERMINAL_YELLOW, fontSize: '10px', textAlign: 'center', padding: '20px' }}>
+ <div style={{ color: colors.warning, fontSize: '10px', textAlign: 'center', padding: '20px' }}>
Loading news from {getRSSFeedCount()} RSS feeds...
</div>
) : filteredNews.length === 0 ? (
- <div style={{ color: TERMINAL_GRAY, fontSize: '10px', textAlign: 'center', padding: '20px' }}>
+ <div style={{ color: colors.textMuted, fontSize: '10px', textAlign: 'center', padding: '20px' }}>
No articles found for filter: {activeFilter}
</div>
) : null}
@@ -325,25 +316,25 @@ const NewsTab: React.FC = () => {
onClick={() => setSelectedArticle(article)}
>
<div style={{ display: 'flex', gap: '4px', marginBottom: '1px', fontSize: '8px' }}>
- <span style={{ color: TERMINAL_GRAY, minWidth: '50px' }}>{article.time}</span>
+ <span style={{ color: colors.textMuted, minWidth: '50px' }}>{article.time}</span>
<span style={{ color: getPriorityColor(article.priority), fontWeight: 'bold', minWidth: '60px' }}>
[{article.priority}]
</span>
- <span style={{ color: TERMINAL_BLUE, minWidth: '50px' }}>[{article.category}]</span>
- <span style={{ color: TERMINAL_PURPLE, minWidth: '30px' }}>{article.region}</span>
+ <span style={{ color: colors.info, minWidth: '50px' }}>[{article.category}]</span>
+ <span style={{ color: colors.purple, minWidth: '30px' }}>{article.region}</span>
<span style={{ color: getSentimentColor(article.sentiment), minWidth: '50px' }}>{article.sentiment}</span>
</div>
- <div style={{ color: TERMINAL_WHITE, fontWeight: 'bold', fontSize: '10px', lineHeight: '1.2', marginBottom: '2px' }}>
+ <div style={{ color: colors.text, fontWeight: 'bold', fontSize: '10px', lineHeight: '1.2', marginBottom: '2px' }}>
{article.headline}
</div>
- <div style={{ color: TERMINAL_GRAY, fontSize: '9px', lineHeight: '1.2', marginBottom: '2px' }}>
+ <div style={{ color: colors.textMuted, fontSize: '9px', lineHeight: '1.2', marginBottom: '2px' }}>
{article.summary}
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '8px' }}>
- <span style={{ color: TERMINAL_CYAN }}>{article.source}</span>
+ <span style={{ color: colors.accent }}>{article.source}</span>
<span style={{ color: getImpactColor(article.impact) }}>IMPACT: {article.impact}</span>
</div>
</div>
@@ -353,15 +344,15 @@ const NewsTab: React.FC = () => {
{/* Center Panel - Secondary News Feed */}
<div style={{
flex: 1,
- backgroundColor: TERMINAL_PANEL_BG,
- border: `1px solid ${TERMINAL_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px',
overflow: 'auto'
}}>
- <div style={{ color: TERMINAL_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
SECONDARY NEWS FEED [{activeFilter}]
</div>
- <div style={{ borderBottom: `1px solid ${TERMINAL_GRAY}`, marginBottom: '4px' }}></div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
{filteredNews.slice(Math.ceil(filteredNews.length / 3), Math.ceil(filteredNews.length * 2 / 3)).map((article, index) => (
<div key={article.id} style={{
@@ -374,25 +365,25 @@ const NewsTab: React.FC = () => {
onClick={() => setSelectedArticle(article)}
>
<div style={{ display: 'flex', gap: '4px', marginBottom: '1px', fontSize: '8px' }}>
- <span style={{ color: TERMINAL_GRAY, minWidth: '50px' }}>{article.time}</span>
+ <span style={{ color: colors.textMuted, minWidth: '50px' }}>{article.time}</span>
<span style={{ color: getPriorityColor(article.priority), fontWeight: 'bold', minWidth: '60px' }}>
[{article.priority}]
</span>
- <span style={{ color: TERMINAL_BLUE, minWidth: '50px' }}>[{article.category}]</span>
- <span style={{ color: TERMINAL_PURPLE, minWidth: '30px' }}>{article.region}</span>
+ <span style={{ color: colors.info, minWidth: '50px' }}>[{article.category}]</span>
+ <span style={{ color: colors.purple, minWidth: '30px' }}>{article.region}</span>
<span style={{ color: getSentimentColor(article.sentiment), minWidth: '50px' }}>{article.sentiment}</span>
</div>
- <div style={{ color: TERMINAL_WHITE, fontWeight: 'bold', fontSize: '10px', lineHeight: '1.2', marginBottom: '2px' }}>
+ <div style={{ color: colors.text, fontWeight: 'bold', fontSize: '10px', lineHeight: '1.2', marginBottom: '2px' }}>
{article.headline}
</div>
- <div style={{ color: TERMINAL_GRAY, fontSize: '9px', lineHeight: '1.2', marginBottom: '2px' }}>
+ <div style={{ color: colors.textMuted, fontSize: '9px', lineHeight: '1.2', marginBottom: '2px' }}>
{article.summary}
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '8px' }}>
- <span style={{ color: TERMINAL_CYAN }}>{article.source}</span>
+ <span style={{ color: colors.accent }}>{article.source}</span>
<span style={{ color: getImpactColor(article.impact) }}>IMPACT: {article.impact}</span>
</div>
</div>
@@ -402,38 +393,38 @@ const NewsTab: React.FC = () => {
{/* Right Panel - Tertiary Feed + Analytics */}
<div style={{
width: '400px',
- backgroundColor: TERMINAL_PANEL_BG,
- border: `1px solid ${TERMINAL_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.textMuted}`,
padding: '4px',
overflow: 'auto'
}}>
{/* News Analytics Section */}
<div style={{ marginBottom: '12px' }}>
- <div style={{ color: TERMINAL_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
REAL-TIME NEWS ANALYTICS
</div>
- <div style={{ borderBottom: `1px solid ${TERMINAL_GRAY}`, marginBottom: '6px' }}></div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '6px' }}></div>
{/* Sentiment Analysis */}
<div style={{ marginBottom: '8px', fontSize: '9px' }}>
- <div style={{ color: TERMINAL_YELLOW, fontWeight: 'bold', marginBottom: '3px' }}>
+ <div style={{ color: colors.warning, fontWeight: 'bold', marginBottom: '3px' }}>
SENTIMENT ANALYSIS
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: TERMINAL_GRAY }}>Bullish Articles:</span>
- <span style={{ color: TERMINAL_GREEN }}>{bullishCount} ({Math.round((bullishCount/totalCount)*100)}%)</span>
+ <span style={{ color: colors.textMuted }}>Bullish Articles:</span>
+ <span style={{ color: colors.secondary }}>{bullishCount} ({Math.round((bullishCount/totalCount)*100)}%)</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: TERMINAL_GRAY }}>Bearish Articles:</span>
- <span style={{ color: TERMINAL_RED }}>{bearishCount} ({Math.round((bearishCount/totalCount)*100)}%)</span>
+ <span style={{ color: colors.textMuted }}>Bearish Articles:</span>
+ <span style={{ color: colors.alert }}>{bearishCount} ({Math.round((bearishCount/totalCount)*100)}%)</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: TERMINAL_GRAY }}>Neutral Articles:</span>
- <span style={{ color: TERMINAL_YELLOW }}>{neutralCount} ({Math.round((neutralCount/totalCount)*100)}%)</span>
+ <span style={{ color: colors.textMuted }}>Neutral Articles:</span>
+ <span style={{ color: colors.warning }}>{neutralCount} ({Math.round((neutralCount/totalCount)*100)}%)</span>
</div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '2px', paddingTop: '2px', borderTop: `1px solid ${TERMINAL_GRAY}` }}>
- <span style={{ color: TERMINAL_CYAN, fontWeight: 'bold' }}>Sentiment Score:</span>
- <span style={{ color: parseFloat(sentimentScore) > 0 ? TERMINAL_GREEN : parseFloat(sentimentScore) < 0 ? TERMINAL_RED : TERMINAL_YELLOW, fontWeight: 'bold' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '2px', paddingTop: '2px', borderTop: `1px solid ${colors.textMuted}` }}>
+ <span style={{ color: colors.accent, fontWeight: 'bold' }}>Sentiment Score:</span>
+ <span style={{ color: parseFloat(sentimentScore) > 0 ? colors.secondary : parseFloat(sentimentScore) < 0 ? colors.alert : colors.warning, fontWeight: 'bold' }}>
{sentimentScore} ({parseFloat(sentimentScore) > 0 ? 'BULLISH' : parseFloat(sentimentScore) < 0 ? 'BEARISH' : 'NEUTRAL'})
</span>
</div>
@@ -441,38 +432,38 @@ const NewsTab: React.FC = () => {
{/* News Flow Statistics */}
<div style={{ marginBottom: '8px', fontSize: '9px' }}>
- <div style={{ color: TERMINAL_YELLOW, fontWeight: 'bold', marginBottom: '3px' }}>
+ <div style={{ color: colors.warning, fontWeight: 'bold', marginBottom: '3px' }}>
NEWS FLOW STATS
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: TERMINAL_GRAY }}>Total Articles:</span>
- <span style={{ color: TERMINAL_WHITE }}>{newsArticles.length}</span>
+ <span style={{ color: colors.textMuted }}>Total Articles:</span>
+ <span style={{ color: colors.text }}>{newsArticles.length}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: TERMINAL_GRAY }}>Breaking News:</span>
- <span style={{ color: TERMINAL_RED }}>{breakingCount}</span>
+ <span style={{ color: colors.textMuted }}>Breaking News:</span>
+ <span style={{ color: colors.alert }}>{breakingCount}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: TERMINAL_GRAY }}>Earnings Reports:</span>
- <span style={{ color: TERMINAL_BLUE }}>{earningsCount}</span>
+ <span style={{ color: colors.textMuted }}>Earnings Reports:</span>
+ <span style={{ color: colors.info }}>{earningsCount}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: TERMINAL_GRAY }}>Economic Data:</span>
- <span style={{ color: TERMINAL_PURPLE }}>{economicCount}</span>
+ <span style={{ color: colors.textMuted }}>Economic Data:</span>
+ <span style={{ color: colors.purple }}>{economicCount}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: TERMINAL_GRAY }}>High Priority:</span>
- <span style={{ color: TERMINAL_ORANGE }}>{alertCount}</span>
+ <span style={{ color: colors.textMuted }}>High Priority:</span>
+ <span style={{ color: colors.primary }}>{alertCount}</span>
</div>
</div>
</div>
{/* Tertiary News Feed */}
- <div style={{ borderTop: `2px solid ${TERMINAL_GRAY}`, paddingTop: '4px' }}>
- <div style={{ color: TERMINAL_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <div style={{ borderTop: `2px solid ${colors.textMuted}`, paddingTop: '4px' }}>
+ <div style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
ADDITIONAL HEADLINES
</div>
- <div style={{ borderBottom: `1px solid ${TERMINAL_GRAY}`, marginBottom: '4px' }}></div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
{filteredNews.slice(Math.ceil(filteredNews.length * 2 / 3)).map((article, index) => (
<div key={article.id} style={{
@@ -485,23 +476,23 @@ const NewsTab: React.FC = () => {
onClick={() => setSelectedArticle(article)}
>
<div style={{ display: 'flex', gap: '4px', marginBottom: '1px', fontSize: '8px' }}>
- <span style={{ color: TERMINAL_GRAY, minWidth: '50px' }}>{article.time}</span>
+ <span style={{ color: colors.textMuted, minWidth: '50px' }}>{article.time}</span>
<span style={{ color: getPriorityColor(article.priority), fontWeight: 'bold', minWidth: '60px' }}>
[{article.priority}]
</span>
- <span style={{ color: TERMINAL_BLUE, minWidth: '50px' }}>[{article.category}]</span>
+ <span style={{ color: colors.info, minWidth: '50px' }}>[{article.category}]</span>
</div>
- <div style={{ color: TERMINAL_WHITE, fontWeight: 'bold', fontSize: '10px', lineHeight: '1.2', marginBottom: '2px' }}>
+ <div style={{ color: colors.text, fontWeight: 'bold', fontSize: '10px', lineHeight: '1.2', marginBottom: '2px' }}>
{article.headline}
</div>
- <div style={{ color: TERMINAL_GRAY, fontSize: '9px', lineHeight: '1.2', marginBottom: '2px' }}>
+ <div style={{ color: colors.textMuted, fontSize: '9px', lineHeight: '1.2', marginBottom: '2px' }}>
{article.summary.slice(0, 150)}...
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '8px' }}>
- <span style={{ color: TERMINAL_CYAN }}>{article.source}</span>
+ <span style={{ color: colors.accent }}>{article.source}</span>
<span style={{ color: getSentimentColor(article.sentiment) }}>{article.sentiment}</span>
</div>
</div>
@@ -513,11 +504,11 @@ const NewsTab: React.FC = () => {
{/* Status Bar */}
<div style={{
- borderTop: `1px solid ${TERMINAL_GRAY}`,
- backgroundColor: TERMINAL_PANEL_BG,
+ borderTop: `1px solid ${colors.textMuted}`,
+ backgroundColor: colors.panel,
padding: '2px 8px',
fontSize: '10px',
- color: TERMINAL_GRAY,
+ color: colors.textMuted,
flexShrink: 0
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
@@ -528,7 +519,7 @@ const NewsTab: React.FC = () => {
<div style={{ display: 'flex', gap: '16px' }}>
<span>High Priority: {alertCount} | Sentiment: {sentimentScore}</span>
<span>Session: {currentTime.toTimeString().substring(0, 8)}</span>
- <span style={{ color: loading ? TERMINAL_YELLOW : TERMINAL_GREEN }}>
+ <span style={{ color: loading ? colors.warning : colors.secondary }}>
{loading ? 'UPDATING...' : 'FEED: LIVE'}
</span>
</div>
@@ -552,8 +543,8 @@ const NewsTab: React.FC = () => {
onClick={() => setSelectedArticle(null)}
>
<div style={{
- backgroundColor: TERMINAL_PANEL_BG,
- border: `2px solid ${TERMINAL_ORANGE}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.primary}`,
borderRadius: '4px',
width: showWebView ? '90vw' : '600px',
maxWidth: '95vw',
@@ -562,15 +553,15 @@ const NewsTab: React.FC = () => {
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
- boxShadow: `0 0 20px ${TERMINAL_ORANGE}`,
+ boxShadow: `0 0 20px ${colors.primary}`,
transition: 'all 0.3s ease'
}}
onClick={(e) => e.stopPropagation()}
>
{/* Modal Header */}
<div style={{
- backgroundColor: TERMINAL_DARK_BG,
- borderBottom: `2px solid ${TERMINAL_ORANGE}`,
+ backgroundColor: colors.background,
+ borderBottom: `2px solid ${colors.primary}`,
padding: '8px 12px',
display: 'flex',
justifyContent: 'space-between',
@@ -578,12 +569,12 @@ const NewsTab: React.FC = () => {
flexShrink: 0
}}>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center', fontSize: '11px' }}>
- <span style={{ color: TERMINAL_ORANGE, fontWeight: 'bold' }}>ARTICLE DETAILS</span>
- <span style={{ color: TERMINAL_WHITE }}>|</span>
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>ARTICLE DETAILS</span>
+ <span style={{ color: colors.text }}>|</span>
<span style={{ color: getPriorityColor(selectedArticle.priority), fontWeight: 'bold' }}>
[{selectedArticle.priority}]
</span>
- <span style={{ color: TERMINAL_BLUE }}>[{selectedArticle.category}]</span>
+ <span style={{ color: colors.info }}>[{selectedArticle.category}]</span>
</div>
<button
onClick={() => {
@@ -591,8 +582,8 @@ const NewsTab: React.FC = () => {
setShowWebView(false);
}}
style={{
- backgroundColor: TERMINAL_RED,
- color: TERMINAL_WHITE,
+ backgroundColor: colors.alert,
+ color: colors.text,
border: 'none',
padding: '4px 8px',
fontSize: '11px',
@@ -618,9 +609,9 @@ const NewsTab: React.FC = () => {
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
{/* Reader View Header */}
<div style={{
- backgroundColor: TERMINAL_DARK_BG,
+ backgroundColor: colors.background,
padding: '8px',
- borderBottom: `1px solid ${TERMINAL_GRAY}`,
+ borderBottom: `1px solid ${colors.textMuted}`,
display: 'flex',
alignItems: 'center',
gap: '8px',
@@ -629,8 +620,8 @@ const NewsTab: React.FC = () => {
<button
onClick={() => setShowWebView(false)}
style={{
- backgroundColor: TERMINAL_ORANGE,
- color: TERMINAL_DARK_BG,
+ backgroundColor: colors.primary,
+ color: colors.background,
border: 'none',
padding: '4px 8px',
fontSize: '10px',
@@ -641,10 +632,10 @@ const NewsTab: React.FC = () => {
>
← BACK TO SUMMARY
</button>
- <span style={{ color: TERMINAL_GRAY }}>|</span>
- <span style={{ color: TERMINAL_YELLOW, fontWeight: 'bold' }}>READER VIEW</span>
- <span style={{ color: TERMINAL_GRAY }}>|</span>
- <span style={{ color: TERMINAL_WHITE, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.warning, fontWeight: 'bold' }}>READER VIEW</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.text, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{selectedArticle.source}
</span>
<button
@@ -657,8 +648,8 @@ const NewsTab: React.FC = () => {
}
}}
style={{
- backgroundColor: TERMINAL_BLUE,
- color: TERMINAL_WHITE,
+ backgroundColor: colors.info,
+ color: colors.text,
border: 'none',
padding: '4px 8px',
fontSize: '10px',
@@ -683,7 +674,7 @@ const NewsTab: React.FC = () => {
<div style={{
marginBottom: '24px',
paddingBottom: '16px',
- borderBottom: `2px solid ${TERMINAL_ORANGE}`
+ borderBottom: `2px solid ${colors.primary}`
}}>
<div style={{
display: 'flex',
@@ -693,7 +684,7 @@ const NewsTab: React.FC = () => {
}}>
<span style={{
backgroundColor: getPriorityColor(selectedArticle.priority),
- color: TERMINAL_DARK_BG,
+ color: colors.background,
padding: '2px 8px',
borderRadius: '2px',
fontWeight: 'bold'
@@ -701,8 +692,8 @@ const NewsTab: React.FC = () => {
{selectedArticle.priority}
</span>
<span style={{
- backgroundColor: TERMINAL_BLUE,
- color: TERMINAL_WHITE,
+ backgroundColor: colors.info,
+ color: colors.text,
padding: '2px 8px',
borderRadius: '2px',
fontWeight: 'bold'
@@ -711,7 +702,7 @@ const NewsTab: React.FC = () => {
</span>
<span style={{
backgroundColor: getSentimentColor(selectedArticle.sentiment),
- color: TERMINAL_DARK_BG,
+ color: colors.background,
padding: '2px 8px',
borderRadius: '2px',
fontWeight: 'bold'
@@ -725,7 +716,7 @@ const NewsTab: React.FC = () => {
fontWeight: 'bold',
lineHeight: '1.3',
marginBottom: '12px',
- color: TERMINAL_WHITE
+ color: colors.text
}}>
{selectedArticle.headline}
</h1>
@@ -734,7 +725,7 @@ const NewsTab: React.FC = () => {
display: 'flex',
gap: '16px',
fontSize: '12px',
- color: TERMINAL_GRAY
+ color: colors.textMuted
}}>
<span>📰 {selectedArticle.source}</span>
<span>🕒 {selectedArticle.time}</span>
@@ -759,18 +750,18 @@ const NewsTab: React.FC = () => {
<div style={{
backgroundColor: 'rgba(255, 165, 0, 0.1)',
- border: `1px solid ${TERMINAL_ORANGE}`,
+ border: `1px solid ${colors.primary}`,
borderRadius: '4px',
padding: '16px',
marginTop: '24px'
}}>
- <p style={{ fontSize: '14px', color: TERMINAL_YELLOW, marginBottom: '8px', fontWeight: 'bold' }}>
+ <p style={{ fontSize: '14px', color: colors.warning, marginBottom: '8px', fontWeight: 'bold' }}>
ℹ️ Reader View Limitation
</p>
- <p style={{ fontSize: '13px', lineHeight: '1.6', color: TERMINAL_GRAY, marginBottom: '12px' }}>
+ <p style={{ fontSize: '13px', lineHeight: '1.6', color: colors.textMuted, marginBottom: '12px' }}>
Most news websites block embedding for security reasons. This reader view shows the article summary from the RSS feed.
</p>
- <p style={{ fontSize: '13px', lineHeight: '1.6', color: TERMINAL_GRAY }}>
+ <p style={{ fontSize: '13px', lineHeight: '1.6', color: colors.textMuted }}>
For the complete article with images, videos, and full content, please click the "🔗 OPEN FULL ARTICLE" button above to view it in your browser.
</p>
</div>
@@ -787,37 +778,37 @@ const NewsTab: React.FC = () => {
marginBottom: '12px',
padding: '8px',
backgroundColor: 'rgba(255, 165, 0, 0.05)',
- border: `1px solid ${TERMINAL_GRAY}`,
+ border: `1px solid ${colors.textMuted}`,
fontSize: '10px'
}}>
<div>
- <span style={{ color: TERMINAL_GRAY }}>SOURCE: </span>
- <span style={{ color: TERMINAL_CYAN, fontWeight: 'bold' }}>{selectedArticle.source}</span>
+ <span style={{ color: colors.textMuted }}>SOURCE: </span>
+ <span style={{ color: colors.accent, fontWeight: 'bold' }}>{selectedArticle.source}</span>
</div>
<div>
- <span style={{ color: TERMINAL_GRAY }}>TIME: </span>
- <span style={{ color: TERMINAL_WHITE }}>{selectedArticle.time}</span>
+ <span style={{ color: colors.textMuted }}>TIME: </span>
+ <span style={{ color: colors.text }}>{selectedArticle.time}</span>
</div>
<div>
- <span style={{ color: TERMINAL_GRAY }}>REGION: </span>
- <span style={{ color: TERMINAL_PURPLE }}>{selectedArticle.region}</span>
+ <span style={{ color: colors.textMuted }}>REGION: </span>
+ <span style={{ color: colors.purple }}>{selectedArticle.region}</span>
</div>
<div>
- <span style={{ color: TERMINAL_GRAY }}>SENTIMENT: </span>
+ <span style={{ color: colors.textMuted }}>SENTIMENT: </span>
<span style={{ color: getSentimentColor(selectedArticle.sentiment), fontWeight: 'bold' }}>
{selectedArticle.sentiment}
</span>
</div>
<div>
- <span style={{ color: TERMINAL_GRAY }}>IMPACT: </span>
+ <span style={{ color: colors.textMuted }}>IMPACT: </span>
<span style={{ color: getImpactColor(selectedArticle.impact), fontWeight: 'bold' }}>
{selectedArticle.impact}
</span>
</div>
{selectedArticle.tickers && selectedArticle.tickers.length > 0 && (
<div>
- <span style={{ color: TERMINAL_GRAY }}>TICKERS: </span>
- <span style={{ color: TERMINAL_GREEN, fontWeight: 'bold' }}>
+ <span style={{ color: colors.textMuted }}>TICKERS: </span>
+ <span style={{ color: colors.secondary, fontWeight: 'bold' }}>
{selectedArticle.tickers.join(', ')}
</span>
</div>
@@ -826,7 +817,7 @@ const NewsTab: React.FC = () => {
{/* Article Headline */}
<div style={{
- color: TERMINAL_WHITE,
+ color: colors.text,
fontSize: '14px',
fontWeight: 'bold',
lineHeight: '1.4',
@@ -840,7 +831,7 @@ const NewsTab: React.FC = () => {
{/* Article Summary */}
<div style={{
- color: TERMINAL_GRAY,
+ color: colors.textMuted,
fontSize: '12px',
lineHeight: '1.6',
marginBottom: '16px'
@@ -854,7 +845,7 @@ const NewsTab: React.FC = () => {
display: 'flex',
gap: '8px',
paddingTop: '12px',
- borderTop: `1px solid ${TERMINAL_GRAY}`
+ borderTop: `1px solid ${colors.textMuted}`
}}>
<button
onClick={(e) => {
@@ -862,8 +853,8 @@ const NewsTab: React.FC = () => {
setShowWebView(true);
}}
style={{
- backgroundColor: TERMINAL_GREEN,
- color: TERMINAL_DARK_BG,
+ backgroundColor: colors.secondary,
+ color: colors.background,
border: 'none',
padding: '6px 12px',
fontSize: '11px',
@@ -908,8 +899,8 @@ const NewsTab: React.FC = () => {
}
}}
style={{
- backgroundColor: TERMINAL_BLUE,
- color: TERMINAL_WHITE,
+ backgroundColor: colors.info,
+ color: colors.text,
border: 'none',
padding: '6px 12px',
fontSize: '11px',
@@ -935,8 +926,8 @@ const NewsTab: React.FC = () => {
}
}}
style={{
- backgroundColor: TERMINAL_GRAY,
- color: TERMINAL_WHITE,
+ backgroundColor: colors.textMuted,
+ color: colors.text,
border: 'none',
padding: '6px 12px',
fontSize: '11px',
@@ -976,7 +967,7 @@ const NewsTab: React.FC = () => {
.ticker-item {
display: inline-block;
padding-right: 3em;
- color: ${TERMINAL_WHITE};
+ color: ${colors.text};
font-size: 11px;
white-space: nowrap;
}
diff --git a/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
index 205da0e9f..39748caaf 100644
--- a/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
@@ -1,3 +1,4 @@
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import React, { useState, useCallback, useMemo, useEffect } from 'react';
import ReactFlow, {
Node,
@@ -123,7 +124,7 @@ const CustomNode = ({ data, id, selected }: any) => {
}}
autoFocus
style={{
- background: '#0a0a0a',
+ background: 'colors.panel',
border: `1px solid ${data.color}`,
color: data.color,
fontSize: '11px',
@@ -251,6 +252,7 @@ const NODE_CONFIGS = [
];
export default function NodeEditorTab() {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [mcpNodeConfigs, setMcpNodeConfigs] = useState<MCPNodeConfig[]>([]);
// Load MCP node configurations on mount
@@ -506,7 +508,7 @@ export default function NodeEditorTab() {
style={{
width: '100%',
height: '100%',
- backgroundColor: '#0a0a0a',
+ backgroundColor: 'colors.panel',
display: 'flex',
flexDirection: 'column',
}}
@@ -784,7 +786,7 @@ export default function NodeEditorTab() {
key={config.type}
onClick={() => addNode(config)}
style={{
- backgroundColor: '#0a0a0a',
+ backgroundColor: 'colors.panel',
color: config.color,
border: `1px solid ${config.color}40`,
padding: '8px 12px',
@@ -802,7 +804,7 @@ export default function NodeEditorTab() {
e.currentTarget.style.borderColor = config.color;
}}
onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = '#0a0a0a';
+ e.currentTarget.style.backgroundColor = 'colors.panel';
e.currentTarget.style.borderColor = `${config.color}40`;
}}
>
@@ -823,7 +825,7 @@ export default function NodeEditorTab() {
<div style={{ marginBottom: '12px' }}>
<div
style={{
- color: '#FFA500',
+ color: 'colors.primary',
fontSize: '10px',
marginBottom: '6px',
textTransform: 'uppercase',
@@ -838,9 +840,9 @@ export default function NodeEditorTab() {
key={config.id}
onClick={() => addNode(config)}
style={{
- backgroundColor: '#0a0a0a',
- color: '#FFA500',
- border: '1px solid #FFA50040',
+ backgroundColor: 'colors.panel',
+ color: 'colors.primary',
+ border: '1px solid colors.primary40',
padding: '8px 12px',
fontSize: '11px',
cursor: 'pointer',
@@ -852,18 +854,18 @@ export default function NodeEditorTab() {
marginBottom: '6px',
}}
onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#FFA50020';
- e.currentTarget.style.borderColor = '#FFA500';
+ e.currentTarget.style.backgroundColor = 'colors.primary20';
+ e.currentTarget.style.borderColor = 'colors.primary';
}}
onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = '#0a0a0a';
- e.currentTarget.style.borderColor = '#FFA50040';
+ e.currentTarget.style.backgroundColor = 'colors.panel';
+ e.currentTarget.style.borderColor = 'colors.primary40';
}}
>
<span style={{ fontSize: '14px' }}>{config.icon}</span>
<div style={{ flex: 1, textAlign: 'left' }}>
<div>{config.label}</div>
- <div style={{ fontSize: '9px', color: '#787878' }}>
+ <div style={{ fontSize: '9px', color: 'colors.textMuted' }}>
{config.serverId}
</div>
</div>
@@ -885,7 +887,7 @@ export default function NodeEditorTab() {
onSelectionChange={onSelectionChange}
nodeTypes={nodeTypes}
fitView
- style={{ background: '#0a0a0a' }}
+ style={{ background: 'colors.panel' }}
defaultEdgeOptions={{
animated: true,
style: { stroke: '#ea580c', strokeWidth: 2 },
@@ -895,7 +897,7 @@ export default function NodeEditorTab() {
color="#2d2d2d"
gap={20}
size={1}
- style={{ backgroundColor: '#0a0a0a' }}
+ style={{ backgroundColor: 'colors.panel' }}
/>
<Controls
style={{
diff --git a/fincept-terminal-desktop/src/components/tabs/OptionsTab.tsx b/fincept-terminal-desktop/src/components/tabs/OptionsTab.tsx
index 710dcb382..915200b43 100644
--- a/fincept-terminal-desktop/src/components/tabs/OptionsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/OptionsTab.tsx
@@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
interface OptionContract {
strike: number;
@@ -25,23 +26,12 @@ interface OptionContract {
}
const OptionsTab: React.FC = () => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
const [selectedSymbol, setSelectedSymbol] = useState('AAPL');
const [selectedExpiry, setSelectedExpiry] = useState('2025-03-21');
const [showGreeks, setShowGreeks] = useState(true);
- const COLOR_ORANGE = '#FFA500';
- const COLOR_WHITE = '#FFFFFF';
- const COLOR_RED = '#FF0000';
- const COLOR_GREEN = '#00C800';
- const COLOR_YELLOW = '#FFFF00';
- const COLOR_GRAY = '#787878';
- const COLOR_BLUE = '#6496FA';
- const COLOR_PURPLE = '#C864FF';
- const COLOR_CYAN = '#00FFFF';
- const COLOR_DARK_BG = '#000000';
- const COLOR_PANEL_BG = '#0a0a0a';
-
useEffect(() => {
const timer = setInterval(() => setCurrentTime(new Date()), 1000);
return () => clearInterval(timer);
@@ -129,8 +119,8 @@ const OptionsTab: React.FC = () => {
return (
<div style={{
height: '100%',
- backgroundColor: COLOR_DARK_BG,
- color: COLOR_WHITE,
+ backgroundColor: colors.background,
+ color: colors.text,
fontFamily: 'Consolas, monospace',
overflow: 'hidden',
display: 'flex',
@@ -139,26 +129,26 @@ const OptionsTab: React.FC = () => {
}}>
{/* Header */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- borderBottom: `2px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `2px solid ${colors.textMuted}`,
padding: '8px 16px',
flexShrink: 0
}}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '16px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '16px' }}>
OPTIONS CHAIN
</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
+ <span style={{ color: colors.textMuted }}>|</span>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>SYMBOL:</span>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>SYMBOL:</span>
<select
value={selectedSymbol}
onChange={(e) => setSelectedSymbol(e.target.value)}
style={{
- backgroundColor: COLOR_DARK_BG,
- color: COLOR_CYAN,
- border: `2px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.background,
+ color: colors.accent,
+ border: `2px solid ${colors.textMuted}`,
padding: '4px 8px',
fontSize: '11px',
fontFamily: 'Consolas, monospace',
@@ -168,21 +158,21 @@ const OptionsTab: React.FC = () => {
<option key={sym} value={sym}>{sym}</option>
))}
</select>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_GREEN, fontSize: '14px', fontWeight: 'bold' }}>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.secondary, fontSize: '14px', fontWeight: 'bold' }}>
${underlyingPrice.toFixed(2)}
</span>
</div>
- <span style={{ color: COLOR_GRAY }}>|</span>
+ <span style={{ color: colors.textMuted }}>|</span>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>EXPIRY:</span>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>EXPIRY:</span>
<select
value={selectedExpiry}
onChange={(e) => setSelectedExpiry(e.target.value)}
style={{
- backgroundColor: COLOR_DARK_BG,
- color: COLOR_YELLOW,
- border: `2px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.background,
+ color: colors.warning,
+ border: `2px solid ${colors.textMuted}`,
padding: '4px 8px',
fontSize: '11px',
fontFamily: 'Consolas, monospace',
@@ -199,9 +189,9 @@ const OptionsTab: React.FC = () => {
onClick={() => setShowGreeks(!showGreeks)}
style={{
padding: '6px 12px',
- backgroundColor: showGreeks ? COLOR_ORANGE : COLOR_DARK_BG,
- border: `2px solid ${COLOR_ORANGE}`,
- color: showGreeks ? COLOR_DARK_BG : COLOR_ORANGE,
+ backgroundColor: showGreeks ? colors.primary : colors.background,
+ border: `2px solid ${colors.primary}`,
+ color: showGreeks ? colors.background : colors.primary,
fontSize: '10px',
fontWeight: 'bold',
cursor: 'pointer',
@@ -209,7 +199,7 @@ const OptionsTab: React.FC = () => {
}}>
{showGreeks ? 'HIDE GREEKS' : 'SHOW GREEKS'}
</button>
- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>
{currentTime.toLocaleTimeString()}
</span>
</div>
@@ -222,70 +212,70 @@ const OptionsTab: React.FC = () => {
<div style={{ width: '280px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
{/* Portfolio Greeks */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
- borderLeft: `6px solid ${COLOR_GREEN}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
+ borderLeft: `6px solid ${colors.secondary}`,
padding: '12px'
}}>
- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
PORTFOLIO GREEKS
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<div style={{
padding: '8px',
backgroundColor: 'rgba(0,200,0,0.05)',
- border: `1px solid ${COLOR_GREEN}`
+ border: `1px solid ${colors.secondary}`
}}>
- <div style={{ color: COLOR_GRAY, fontSize: '10px', marginBottom: '2px' }}>DELTA</div>
- <div style={{ color: COLOR_GREEN, fontSize: '16px', fontWeight: 'bold' }}>
+ <div style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '2px' }}>DELTA</div>
+ <div style={{ color: colors.secondary, fontSize: '16px', fontWeight: 'bold' }}>
{portfolioGreeks.totalDelta.toFixed(2)}
</div>
- <div style={{ color: COLOR_GRAY, fontSize: '9px' }}>Directional exposure</div>
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>Directional exposure</div>
</div>
<div style={{
padding: '8px',
backgroundColor: 'rgba(100,150,250,0.05)',
- border: `1px solid ${COLOR_BLUE}`
+ border: `1px solid ${colors.info}`
}}>
- <div style={{ color: COLOR_GRAY, fontSize: '10px', marginBottom: '2px' }}>GAMMA</div>
- <div style={{ color: COLOR_BLUE, fontSize: '16px', fontWeight: 'bold' }}>
+ <div style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '2px' }}>GAMMA</div>
+ <div style={{ color: colors.info, fontSize: '16px', fontWeight: 'bold' }}>
{portfolioGreeks.totalGamma.toFixed(2)}
</div>
- <div style={{ color: COLOR_GRAY, fontSize: '9px' }}>Delta sensitivity</div>
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>Delta sensitivity</div>
</div>
<div style={{
padding: '8px',
backgroundColor: 'rgba(255,0,0,0.05)',
- border: `1px solid ${COLOR_RED}`
+ border: `1px solid ${colors.alert}`
}}>
- <div style={{ color: COLOR_GRAY, fontSize: '10px', marginBottom: '2px' }}>THETA</div>
- <div style={{ color: COLOR_RED, fontSize: '16px', fontWeight: 'bold' }}>
+ <div style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '2px' }}>THETA</div>
+ <div style={{ color: colors.alert, fontSize: '16px', fontWeight: 'bold' }}>
{portfolioGreeks.totalTheta.toFixed(2)}
</div>
- <div style={{ color: COLOR_GRAY, fontSize: '9px' }}>Time decay (per day)</div>
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>Time decay (per day)</div>
</div>
<div style={{
padding: '8px',
backgroundColor: 'rgba(200,100,255,0.05)',
- border: `1px solid ${COLOR_PURPLE}`
+ border: `1px solid ${colors.purple}`
}}>
- <div style={{ color: COLOR_GRAY, fontSize: '10px', marginBottom: '2px' }}>VEGA</div>
- <div style={{ color: COLOR_PURPLE, fontSize: '16px', fontWeight: 'bold' }}>
+ <div style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '2px' }}>VEGA</div>
+ <div style={{ color: colors.purple, fontSize: '16px', fontWeight: 'bold' }}>
{portfolioGreeks.totalVega.toFixed(2)}
</div>
- <div style={{ color: COLOR_GRAY, fontSize: '9px' }}>Volatility exposure</div>
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>Volatility exposure</div>
</div>
</div>
</div>
{/* Volatility Surface */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
- borderLeft: `6px solid ${COLOR_PURPLE}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
+ borderLeft: `6px solid ${colors.purple}`,
padding: '12px'
}}>
- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
IMPLIED VOLATILITY
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
@@ -293,15 +283,15 @@ const OptionsTab: React.FC = () => {
<div key={index} style={{
padding: '8px',
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- borderBottom: `1px solid ${COLOR_GRAY}`
+ borderBottom: `1px solid ${colors.textMuted}`
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>{vol.expiry}</span>
- <span style={{ color: COLOR_PURPLE, fontSize: '12px', fontWeight: 'bold' }}>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>{vol.expiry}</span>
+ <span style={{ color: colors.purple, fontSize: '12px', fontWeight: 'bold' }}>
{(vol.atm * 100).toFixed(1)}%
</span>
</div>
- <div style={{ fontSize: '9px', color: vol.skew < 0 ? COLOR_RED : COLOR_GREEN }}>
+ <div style={{ fontSize: '9px', color: vol.skew < 0 ? colors.alert : colors.secondary }}>
Skew: {(vol.skew * 100).toFixed(2)}%
</div>
</div>
@@ -311,30 +301,30 @@ const OptionsTab: React.FC = () => {
{/* Quick Stats */}
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
- borderLeft: `6px solid ${COLOR_CYAN}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
+ borderLeft: `6px solid ${colors.accent}`,
padding: '12px'
}}>
- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
QUICK STATS
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px', fontSize: '11px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: COLOR_GRAY }}>Total Call Vol:</span>
- <span style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>35,198</span>
+ <span style={{ color: colors.textMuted }}>Total Call Vol:</span>
+ <span style={{ color: colors.secondary, fontWeight: 'bold' }}>35,198</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: COLOR_GRAY }}>Total Put Vol:</span>
- <span style={{ color: COLOR_RED, fontWeight: 'bold' }}>23,409</span>
+ <span style={{ color: colors.textMuted }}>Total Put Vol:</span>
+ <span style={{ color: colors.alert, fontWeight: 'bold' }}>23,409</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: COLOR_GRAY }}>Put/Call Ratio:</span>
- <span style={{ color: COLOR_YELLOW, fontWeight: 'bold' }}>0.67</span>
+ <span style={{ color: colors.textMuted }}>Put/Call Ratio:</span>
+ <span style={{ color: colors.warning, fontWeight: 'bold' }}>0.67</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: COLOR_GRAY }}>Max Pain:</span>
- <span style={{ color: COLOR_CYAN, fontWeight: 'bold' }}>$177.50</span>
+ <span style={{ color: colors.textMuted }}>Max Pain:</span>
+ <span style={{ color: colors.accent, fontWeight: 'bold' }}>$177.50</span>
</div>
</div>
</div>
@@ -343,8 +333,8 @@ const OptionsTab: React.FC = () => {
{/* Right Panel - Options Chain */}
<div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
<div style={{
- backgroundColor: COLOR_PANEL_BG,
- border: `2px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.textMuted}`,
flex: 1,
overflow: 'auto'
}}>
@@ -356,7 +346,7 @@ const OptionsTab: React.FC = () => {
: '100px 80px 80px 80px 100px 80px 100px 80px 80px 80px 100px 80px',
padding: '10px 12px',
backgroundColor: 'rgba(255,165,0,0.1)',
- borderBottom: `2px solid ${COLOR_ORANGE}`,
+ borderBottom: `2px solid ${colors.primary}`,
position: 'sticky',
top: 0,
zIndex: 10,
@@ -365,30 +355,30 @@ const OptionsTab: React.FC = () => {
{showGreeks ? (
<>
{/* Calls */}
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold', textAlign: 'center' }}>
+ <div style={{ color: colors.secondary, fontWeight: 'bold', textAlign: 'center' }}>
========== CALLS ==========
</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold', textAlign: 'center' }}>STRIKE</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold', textAlign: 'center' }}>STRIKE</div>
{/* Puts */}
- <div style={{ color: COLOR_RED, fontWeight: 'bold', textAlign: 'center' }}>
+ <div style={{ color: colors.alert, fontWeight: 'bold', textAlign: 'center' }}>
========== PUTS ==========
</div>
</>
) : (
<>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>C.BID</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>C.ASK</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>C.LAST</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>C.VOL</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>C.OI</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>C.IV</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>STRIKE</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>P.BID</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>P.ASK</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>P.LAST</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>P.VOL</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>P.OI</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>P.IV</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>C.BID</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>C.ASK</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>C.LAST</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>C.VOL</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>C.OI</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>C.IV</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold' }}>STRIKE</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>P.BID</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>P.ASK</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>P.LAST</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>P.VOL</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>P.OI</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>P.IV</div>
</>
)}
</div>
@@ -398,34 +388,34 @@ const OptionsTab: React.FC = () => {
display: 'grid',
gridTemplateColumns: '80px 70px 70px 70px 80px 60px 60px 60px 60px 60px 80px 70px 70px 70px 80px 60px 60px 60px 60px 60px',
padding: '8px 12px',
- backgroundColor: COLOR_PANEL_BG,
- borderBottom: `1px solid ${COLOR_GRAY}`,
+ backgroundColor: colors.panel,
+ borderBottom: `1px solid ${colors.textMuted}`,
position: 'sticky',
top: '32px',
zIndex: 9,
fontSize: '9px'
}}>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>BID</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>ASK</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>LAST</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>VOL</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>OI</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>IV</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>Δ</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>Γ</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>Θ</div>
- <div style={{ color: COLOR_GREEN, fontWeight: 'bold' }}>V</div>
- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>STRIKE</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>BID</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>ASK</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>LAST</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>VOL</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>OI</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>IV</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>Δ</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>Γ</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>Θ</div>
- <div style={{ color: COLOR_RED, fontWeight: 'bold' }}>V</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>BID</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>ASK</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>LAST</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>VOL</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>OI</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>IV</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>Δ</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>Γ</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>Θ</div>
+ <div style={{ color: colors.secondary, fontWeight: 'bold' }}>V</div>
+ <div style={{ color: colors.primary, fontWeight: 'bold' }}>STRIKE</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>BID</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>ASK</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>LAST</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>VOL</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>OI</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>IV</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>Δ</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>Γ</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>Θ</div>
+ <div style={{ color: colors.alert, fontWeight: 'bold' }}>V</div>
</div>
)}
@@ -443,28 +433,28 @@ const OptionsTab: React.FC = () => {
: '100px 80px 80px 80px 100px 80px 100px 80px 80px 80px 100px 80px',
padding: '8px 12px',
backgroundColor: isATM ? 'rgba(255,165,0,0.1)' : (index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent'),
- borderBottom: `1px solid ${COLOR_GRAY}`,
+ borderBottom: `1px solid ${colors.textMuted}`,
fontSize: '10px'
}}>
{/* Calls */}
- <div style={{ color: COLOR_GREEN }}>${option.callBid.toFixed(2)}</div>
- <div style={{ color: COLOR_GREEN }}>${option.callAsk.toFixed(2)}</div>
- <div style={{ color: COLOR_WHITE, fontWeight: 'bold' }}>${option.callLast.toFixed(2)}</div>
- <div style={{ color: COLOR_CYAN }}>{option.callVolume.toLocaleString()}</div>
- <div style={{ color: COLOR_GRAY }}>{option.callOI.toLocaleString()}</div>
- <div style={{ color: COLOR_PURPLE }}>{(option.callIV * 100).toFixed(1)}%</div>
+ <div style={{ color: colors.secondary }}>${option.callBid.toFixed(2)}</div>
+ <div style={{ color: colors.secondary }}>${option.callAsk.toFixed(2)}</div>
+ <div style={{ color: colors.text, fontWeight: 'bold' }}>${option.callLast.toFixed(2)}</div>
+ <div style={{ color: colors.accent }}>{option.callVolume.toLocaleString()}</div>
+ <div style={{ color: colors.textMuted }}>{option.callOI.toLocaleString()}</div>
+ <div style={{ color: colors.purple }}>{(option.callIV * 100).toFixed(1)}%</div>
{showGreeks && (
<>
- <div style={{ color: COLOR_GREEN }}>{option.callDelta.toFixed(2)}</div>
- <div style={{ color: COLOR_BLUE }}>{option.callGamma.toFixed(3)}</div>
- <div style={{ color: COLOR_RED }}>{option.callTheta.toFixed(3)}</div>
- <div style={{ color: COLOR_PURPLE }}>{option.callVega.toFixed(3)}</div>
+ <div style={{ color: colors.secondary }}>{option.callDelta.toFixed(2)}</div>
+ <div style={{ color: colors.info }}>{option.callGamma.toFixed(3)}</div>
+ <div style={{ color: colors.alert }}>{option.callTheta.toFixed(3)}</div>
+ <div style={{ color: colors.purple }}>{option.callVega.toFixed(3)}</div>
</>
)}
{/* Strike */}
<div style={{
- color: isATM ? COLOR_ORANGE : COLOR_WHITE,
+ color: isATM ? colors.primary : colors.text,
fontWeight: isATM ? 'bold' : 'normal',
fontSize: isATM ? '12px' : '10px',
textAlign: 'center',
@@ -475,18 +465,18 @@ const OptionsTab: React.FC = () => {
</div>
{/* Puts */}
- <div style={{ color: COLOR_RED }}>${option.putBid.toFixed(2)}</div>
- <div style={{ color: COLOR_RED }}>${option.putAsk.toFixed(2)}</div>
- <div style={{ color: COLOR_WHITE, fontWeight: 'bold' }}>${option.putLast.toFixed(2)}</div>
- <div style={{ color: COLOR_CYAN }}>{option.putVolume.toLocaleString()}</div>
- <div style={{ color: COLOR_GRAY }}>{option.putOI.toLocaleString()}</div>
- <div style={{ color: COLOR_PURPLE }}>{(option.putIV * 100).toFixed(1)}%</div>
+ <div style={{ color: colors.alert }}>${option.putBid.toFixed(2)}</div>
+ <div style={{ color: colors.alert }}>${option.putAsk.toFixed(2)}</div>
+ <div style={{ color: colors.text, fontWeight: 'bold' }}>${option.putLast.toFixed(2)}</div>
+ <div style={{ color: colors.accent }}>{option.putVolume.toLocaleString()}</div>
+ <div style={{ color: colors.textMuted }}>{option.putOI.toLocaleString()}</div>
+ <div style={{ color: colors.purple }}>{(option.putIV * 100).toFixed(1)}%</div>
{showGreeks && (
<>
- <div style={{ color: COLOR_RED }}>{option.putDelta.toFixed(2)}</div>
- <div style={{ color: COLOR_BLUE }}>{option.putGamma.toFixed(3)}</div>
- <div style={{ color: COLOR_RED }}>{option.putTheta.toFixed(3)}</div>
- <div style={{ color: COLOR_PURPLE }}>{option.putVega.toFixed(3)}</div>
+ <div style={{ color: colors.alert }}>{option.putDelta.toFixed(2)}</div>
+ <div style={{ color: colors.info }}>{option.putGamma.toFixed(3)}</div>
+ <div style={{ color: colors.alert }}>{option.putTheta.toFixed(3)}</div>
+ <div style={{ color: colors.purple }}>{option.putVega.toFixed(3)}</div>
</>
)}
</div>
@@ -498,24 +488,24 @@ const OptionsTab: React.FC = () => {
{/* Footer */}
<div style={{
- borderTop: `3px solid ${COLOR_ORANGE}`,
- backgroundColor: COLOR_PANEL_BG,
+ borderTop: `3px solid ${colors.primary}`,
+ backgroundColor: colors.panel,
padding: '12px 16px',
fontSize: '11px',
- color: COLOR_WHITE,
+ color: colors.text,
flexShrink: 0
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
- <span style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '13px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '13px' }}>
OPTIONS ANALYTICS v1.0
</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_CYAN }}>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.accent }}>
Real-time options chain with Greeks
</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_GREEN }}>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.secondary }}>
{selectedSymbol} • Exp: {selectedExpiry}
</span>
</div>
@@ -525,16 +515,16 @@ const OptionsTab: React.FC = () => {
justifyContent: 'space-between',
fontSize: '10px',
paddingTop: '8px',
- borderTop: `1px solid ${COLOR_GRAY}`
+ borderTop: `1px solid ${colors.textMuted}`
}}>
<div style={{ display: 'flex', gap: '16px' }}>
- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F1</span> Help</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F2</span> Strategy Builder</span>
- <span style={{ color: COLOR_GRAY }}>|</span>
- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F3</span> Risk Analysis</span>
+ <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F1</span> Help</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F2</span> Strategy Builder</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F3</span> Risk Analysis</span>
</div>
- <div style={{ color: COLOR_GRAY }}>
+ <div style={{ color: colors.textMuted }}>
© 2025 Fincept Labs • All Rights Reserved
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/PolygonEqTab.tsx b/fincept-terminal-desktop/src/components/tabs/PolygonEqTab.tsx
index 8554acef0..74d4601ef 100644
--- a/fincept-terminal-desktop/src/components/tabs/PolygonEqTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/PolygonEqTab.tsx
@@ -1,22 +1,25 @@
import React, { useState, useEffect } from 'react';
import { polygonService } from '../../services/polygonService';
-
-const COLORS = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- RED: '#FF0000',
- GREEN: '#00C800',
- YELLOW: '#FFFF00',
- GRAY: '#787878',
- BLUE: '#6496FA',
- CYAN: '#00FFFF',
- DARK_BG: '#0a0a0a',
- PANEL_BG: '#000000',
- BORDER: '#222222',
- PANEL_HEADER_BG: '#1a1a1a',
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { yfinanceService, HistoricalDataPoint } from '../../services/yfinanceService';
+import CandlestickChart, { CandlestickDataPoint } from '../charts/CandlestickChart';
const PolygonEqTab: React.FC = () => {
+ const { colors } = useTerminalTheme();
+ const COLORS = {
+ ORANGE: colors.primary,
+ WHITE: colors.text,
+ RED: colors.alert,
+ GREEN: colors.secondary,
+ YELLOW: colors.warning,
+ GRAY: colors.textMuted,
+ BLUE: colors.info,
+ CYAN: colors.accent,
+ DARK_BG: colors.panel,
+ PANEL_BG: colors.background,
+ BORDER: '#222222',
+ PANEL_HEADER_BG: '#1a1a1a',
+ };
const [symbol, setSymbol] = useState('AAPL');
const [searchInput, setSearchInput] = useState('');
const [loading, setLoading] = useState(false);
@@ -56,6 +59,7 @@ const PolygonEqTab: React.FC = () => {
const [shortVolume, setShortVolume] = useState<any>(null);
const [trades, setTrades] = useState<any>(null);
const [quotes, setQuotes] = useState<any>(null);
+ const [chartData, setChartData] = useState<CandlestickDataPoint[]>([]);
useEffect(() => {
const loadApiKey = async () => {
@@ -72,6 +76,32 @@ const PolygonEqTab: React.FC = () => {
}
};
+ const fetchChartData = async (sym: string) => {
+ try {
+ // Fetch 30 days of historical data from yfinance
+ const historicalData = await yfinanceService.getRecentHistory(sym, 30);
+
+ if (historicalData && historicalData.length > 0) {
+ const candlesticks: CandlestickDataPoint[] = historicalData.map((point: HistoricalDataPoint) => ({
+ timestamp: point.timestamp,
+ open: point.open,
+ high: point.high,
+ low: point.low,
+ close: point.close,
+ volume: point.volume,
+ }));
+ setChartData(candlesticks);
+ console.log(`[PolygonEqTab] Loaded ${candlesticks.length} candlesticks for ${sym}`);
+ } else {
+ setChartData([]);
+ console.warn(`[PolygonEqTab] No chart data available for ${sym}`);
+ }
+ } catch (error) {
+ console.error('[PolygonEqTab] Error fetching chart data:', error);
+ setChartData([]);
+ }
+ };
+
const fetchAllData = async () => {
await polygonService.loadApiKey();
if (!apiKeyConfigured) return;
@@ -81,6 +111,8 @@ const PolygonEqTab: React.FC = () => {
setError(null);
try {
+ // Fetch chart data in parallel with other data
+ fetchChartData(symbol);
const [
detailsResp, snapResp, newsResp, relatedResp, marketStatusResp,
dividendsResp, splitsResp, lastTradeResp, lastQuoteResp, smaResp,
@@ -344,6 +376,7 @@ const PolygonEqTab: React.FC = () => {
flexDirection: 'column',
fontSize: '12px',
overflow: 'auto',
+ overflowX: 'hidden',
}} className="custom-scrollbar">
{/* TOP BAR WITH RELATED TICKERS */}
@@ -358,7 +391,7 @@ const PolygonEqTab: React.FC = () => {
}}>
{/* First Row: Search and Main Info */}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
<span style={{ color: COLORS.ORANGE, fontWeight: 'bold', fontSize: '13px' }}>POLYGON.IO</span>
<input
type="text"
@@ -390,6 +423,39 @@ const PolygonEqTab: React.FC = () => {
>
GO
</button>
+
+ {/* Related Tickers as Small Boxes */}
+ {relatedTickers.length > 0 && (
+ <>
+ <span style={{ color: COLORS.GRAY, fontSize: '10px', fontWeight: 'bold', marginLeft: '8px' }}>RELATED:</span>
+ {relatedTickers.slice(0, 8).map((ticker: any, idx: number) => (
+ <div
+ key={idx}
+ onClick={() => handleRelatedTickerClick(ticker.ticker)}
+ style={{
+ backgroundColor: COLORS.PANEL_HEADER_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ padding: '3px 8px',
+ cursor: 'pointer',
+ fontSize: '10px',
+ color: COLORS.CYAN,
+ fontWeight: 'bold',
+ transition: 'all 0.2s',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = COLORS.CYAN;
+ e.currentTarget.style.color = COLORS.DARK_BG;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = COLORS.PANEL_HEADER_BG;
+ e.currentTarget.style.color = COLORS.CYAN;
+ }}
+ >
+ {ticker.ticker}
+ </div>
+ ))}
+ </>
+ )}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
@@ -421,39 +487,6 @@ const PolygonEqTab: React.FC = () => {
</button>
</div>
</div>
-
- {/* Second Row: Related Tickers as Small Boxes */}
- {relatedTickers.length > 0 && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
- <span style={{ color: COLORS.GRAY, fontSize: '10px', fontWeight: 'bold' }}>RELATED:</span>
- {relatedTickers.slice(0, 8).map((ticker: any, idx: number) => (
- <div
- key={idx}
- onClick={() => handleRelatedTickerClick(ticker.ticker)}
- style={{
- backgroundColor: COLORS.PANEL_HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- padding: '3px 8px',
- cursor: 'pointer',
- fontSize: '10px',
- color: COLORS.CYAN,
- fontWeight: 'bold',
- transition: 'all 0.2s',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = COLORS.CYAN;
- e.currentTarget.style.color = COLORS.DARK_BG;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = COLORS.PANEL_HEADER_BG;
- e.currentTarget.style.color = COLORS.CYAN;
- }}
- >
- {ticker.ticker}
- </div>
- ))}
- </div>
- )}
</div>
{/* Error Banner */}
@@ -471,10 +504,10 @@ const PolygonEqTab: React.FC = () => {
)}
{/* MAIN CONTENT - All data visible, main window scrolls */}
- <div style={{ padding: '6px', flexShrink: 0 }}>
+ <div style={{ padding: '6px', flexShrink: 0, maxWidth: '100%', boxSizing: 'border-box' }}>
{/* ROW 1: Quote Data + Market Status + Technical Indicators - NO INTERNAL SCROLL */}
- <div style={{ display: 'grid', gridTemplateColumns: '25% 25% 25% 25%', gap: '8px', marginBottom: '8px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: '8px', marginBottom: '8px' }}>
{/* Quote Panel */}
<div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>
@@ -563,33 +596,89 @@ const PolygonEqTab: React.FC = () => {
</div>
{/* ROW 2: News (2 columns) + Trades & Quotes + Chart Placeholder */}
- <div style={{ display: 'grid', gridTemplateColumns: '50% 25% 25%', gap: '8px', marginBottom: '8px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: '8px', marginBottom: '8px' }}>
{/* News - Show 4 articles */}
<div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>
<SectionHeader title={`LATEST NEWS (${news.length})`} color={COLORS.ORANGE} />
- <div style={{ padding: '10px' }}>
+ <div style={{ padding: '10px', maxHeight: '240px', overflowY: 'auto' }}>
{news.length > 0 ? news.slice(0, 4).map((article: any) => (
<div key={article.id} style={{
- marginBottom: '8px',
- paddingBottom: '8px',
+ marginBottom: '10px',
+ paddingBottom: '10px',
borderBottom: `1px solid ${COLORS.BORDER}`,
- fontSize: '11px'
+ fontSize: '11px',
+ display: 'flex',
+ gap: '10px'
}}>
- <div style={{ color: COLORS.ORANGE, fontWeight: 'bold', marginBottom: '3px' }}>
- {article.title.substring(0, 80)}...
- </div>
- <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '3px' }}>
- {article.publisher?.name} | {new Date(article.published_utc).toLocaleDateString()}
+ {/* Article Image */}
+ {article.image_url && (
+ <div style={{
+ flexShrink: 0,
+ width: '80px',
+ height: '60px',
+ overflow: 'hidden',
+ borderRadius: '4px',
+ border: `1px solid ${COLORS.BORDER}`,
+ backgroundColor: COLORS.DARK_BG
+ }}>
+ <img
+ src={article.image_url}
+ alt={article.title}
+ style={{
+ width: '100%',
+ height: '100%',
+ objectFit: 'cover'
+ }}
+ onError={(e) => {
+ // Hide image if it fails to load
+ (e.target as HTMLImageElement).style.display = 'none';
+ }}
+ />
+ </div>
+ )}
+
+ {/* Article Content */}
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div style={{
+ color: COLORS.ORANGE,
+ fontWeight: 'bold',
+ marginBottom: '3px',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ display: '-webkit-box',
+ WebkitLineClamp: 2,
+ WebkitBoxOrient: 'vertical'
+ }}>
+ {article.title}
+ </div>
+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '4px' }}>
+ {article.publisher?.name} | {new Date(article.published_utc).toLocaleDateString()}
+ </div>
+ {article.description && (
+ <div style={{
+ color: COLORS.WHITE,
+ fontSize: '9px',
+ marginBottom: '4px',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ display: '-webkit-box',
+ WebkitLineClamp: 2,
+ WebkitBoxOrient: 'vertical',
+ lineHeight: '1.3'
+ }}>
+ {article.description}
+ </div>
+ )}
+ <a
+ href={article.article_url}
+ target="_blank"
+ rel="noopener noreferrer"
+ style={{ color: COLORS.CYAN, fontSize: '10px', textDecoration: 'underline' }}
+ >
+ READ MORE →
+ </a>
</div>
- <a
- href={article.article_url}
- target="_blank"
- rel="noopener noreferrer"
- style={{ color: COLORS.CYAN, fontSize: '10px', textDecoration: 'underline' }}
- >
- READ MORE →
- </a>
</div>
)) : (
<div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '15px', fontSize: '11px' }}>
@@ -621,21 +710,29 @@ const PolygonEqTab: React.FC = () => {
</div>
</div>
- {/* Chart Placeholder */}
- <div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>
- <SectionHeader title="CHART" color={COLORS.BLUE} />
+ {/* Candlestick Chart */}
+ <div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}`, display: 'flex', flexDirection: 'column', height: '100%' }}>
+ <SectionHeader title="30-DAY CHART" color={COLORS.BLUE} />
<div style={{
- padding: '20px',
+ flex: 1,
display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- flexDirection: 'column',
- color: COLORS.GRAY,
- fontSize: '9px',
- textAlign: 'center'
+ alignItems: 'stretch',
+ justifyContent: 'stretch',
+ padding: '4px',
}}>
- <div style={{ fontSize: '32px', marginBottom: '8px' }}>📈</div>
- <div>Chart integration<br/>ready here</div>
+ <CandlestickChart
+ data={chartData}
+ width={300}
+ height={230}
+ bullishColor={COLORS.GREEN}
+ bearishColor={COLORS.RED}
+ backgroundColor={COLORS.DARK_BG}
+ gridColor={COLORS.BORDER}
+ textColor={COLORS.GRAY}
+ showGrid={true}
+ showVolume={true}
+ showLabels={true}
+ />
</div>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/PortfolioTab.tsx b/fincept-terminal-desktop/src/components/tabs/PortfolioTab.tsx
index 53420a29b..ec55a798f 100644
--- a/fincept-terminal-desktop/src/components/tabs/PortfolioTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/PortfolioTab.tsx
@@ -14,9 +14,12 @@ import PerformanceView from './portfolio/PerformanceView';
import RiskMetricsView from './portfolio/RiskMetricsView';
import ReportsView from './portfolio/ReportsView';
import AlertsView from './portfolio/AlertsView';
-import { BLOOMBERG_COLORS, formatCurrency, formatPercent, formatNumber } from './portfolio/utils';
+import { getBloombergColors, formatCurrency, formatPercent, formatNumber } from './portfolio/utils';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
const PortfolioTab: React.FC = () => {
+ const { colors: themeColors } = useTerminalTheme();
+ const BLOOMBERG_COLORS = getBloombergColors();
const [currentTime, setCurrentTime] = useState(new Date());
const [portfolios, setPortfolios] = useState<Portfolio[]>([]);
const [selectedPortfolio, setSelectedPortfolio] = useState<Portfolio | null>(null);
diff --git a/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx b/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx
index 7bf3f66c6..18a6536ce 100644
--- a/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx
@@ -2,25 +2,25 @@ import React, { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useNavigation } from '@/contexts/NavigationContext';
import { UserApiService } from '@/services/userApi';
-
-// Bloomberg Terminal Colors
-const C = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- RED: '#FF0000',
- GREEN: '#00C800',
- YELLOW: '#FFFF00',
- GRAY: '#787878',
- BLUE: '#6496FA',
- PURPLE: '#C864FF',
- CYAN: '#00FFFF',
- DARK_BG: '#000000',
- PANEL_BG: '#0a0a0a'
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
type ProfileScreen = 'overview' | 'usage' | 'payments' | 'subscriptions' | 'support' | 'settings';
const ProfileTab: React.FC = () => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
+ const C = {
+ ORANGE: colors.primary,
+ WHITE: colors.text,
+ RED: colors.alert,
+ GREEN: colors.secondary,
+ YELLOW: colors.warning,
+ GRAY: colors.textMuted,
+ BLUE: colors.info,
+ PURPLE: colors.purple,
+ CYAN: colors.accent,
+ DARK_BG: colors.background,
+ PANEL_BG: colors.panel
+ };
const { session, logout } = useAuth();
const navigation = useNavigation();
const [currentTime, setCurrentTime] = useState(new Date());
diff --git a/fincept-terminal-desktop/src/components/tabs/ScreenerTab.tsx b/fincept-terminal-desktop/src/components/tabs/ScreenerTab.tsx
index 2dd8a4a20..a5afedb20 100644
--- a/fincept-terminal-desktop/src/components/tabs/ScreenerTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ScreenerTab.tsx
@@ -1,3 +1,4 @@
+import { useTerminalTheme } from '@/contexts/ThemeContext';
import React, { useState, useEffect, useMemo } from 'react';
import { Search, Download, TrendingUp, BarChart3, Loader2, AlertCircle, FolderTree, X, Plus, ArrowLeft, ChevronRight } from 'lucide-react';
import { LineChart, Line, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
@@ -57,6 +58,7 @@ const POPULAR_CATEGORIES = [
];
export default function ScreenerTab() {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [seriesIds, setSeriesIds] = useState('GDP');
const [startDate, setStartDate] = useState('2000-01-01');
const [endDate, setEndDate] = useState(new Date().toISOString().split('T')[0]);
@@ -329,10 +331,10 @@ export default function ScreenerTab() {
}, [searchQuery, showBrowser]);
return (
- <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: '#000', overflow: 'hidden' }}>
+ <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: 'colors.background', overflow: 'hidden' }}>
<style>{`
*::-webkit-scrollbar { width: 8px; height: 8px; }
- *::-webkit-scrollbar-track { background: #0a0a0a; }
+ *::-webkit-scrollbar-track { background: colors.panel; }
*::-webkit-scrollbar-thumb { background: #2a2a2a; border-radius: 4px; }
*::-webkit-scrollbar-thumb:hover { background: #3a3a3a; }
`}</style>
@@ -353,7 +355,7 @@ export default function ScreenerTab() {
padding: '20px'
}}>
<div style={{
- background: '#0a0a0a',
+ background: 'colors.panel',
border: '2px solid #ea580c',
borderRadius: '8px',
width: '90%',
@@ -370,7 +372,7 @@ export default function ScreenerTab() {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
- background: 'linear-gradient(180deg, #1a1a1a 0%, #0a0a0a 100%)'
+ background: 'linear-gradient(180deg, #1a1a1a 0%, colors.panel 100%)'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<FolderTree size={20} color="#ea580c" />
@@ -403,9 +405,9 @@ export default function ScreenerTab() {
onChange={(e) => setSearchQuery(e.target.value)}
style={{
width: '100%',
- background: '#000',
+ background: 'colors.background',
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: 'colors.text',
padding: '12px 12px 12px 40px',
fontSize: '11px',
borderRadius: '4px'
@@ -440,7 +442,7 @@ export default function ScreenerTab() {
<button
onClick={navigateBack}
style={{
- background: '#0a0a0a',
+ background: 'colors.panel',
border: '1px solid #2a2a2a',
color: '#ea580c',
padding: '4px 8px',
@@ -478,9 +480,9 @@ export default function ScreenerTab() {
key={`pop-${cat.id}-${idx}`}
onClick={() => navigateToCategory({ id: cat.id, name: cat.name.replace(/[^\w\s]/gi, '').trim() })}
style={{
- background: '#0a0a0a',
+ background: 'colors.panel',
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: 'colors.text',
padding: '6px 8px',
fontSize: '9px',
cursor: 'pointer',
@@ -515,9 +517,9 @@ export default function ScreenerTab() {
key={`cat-${cat.id}-${idx}`}
onClick={() => navigateToCategory(cat)}
style={{
- background: '#0a0a0a',
+ background: 'colors.panel',
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: 'colors.text',
padding: '8px 10px',
fontSize: '10px',
cursor: 'pointer',
@@ -553,7 +555,7 @@ export default function ScreenerTab() {
<div
key={result.id}
style={{
- background: '#0a0a0a',
+ background: 'colors.panel',
border: '1px solid #1a1a1a',
borderRadius: '4px',
padding: '12px',
@@ -572,7 +574,7 @@ export default function ScreenerTab() {
Pop: {result.popularity}
</span>
</div>
- <p style={{ color: '#fff', fontSize: '10px', marginBottom: '4px' }}>
+ <p style={{ color: 'colors.text', fontSize: '10px', marginBottom: '4px' }}>
{result.title}
</p>
<div style={{ display: 'flex', gap: '12px', fontSize: '9px', color: '#666' }}>
@@ -587,7 +589,7 @@ export default function ScreenerTab() {
style={{
background: currentSeriesIdsSet.has(result.id) ? '#1a3a1a' : '#ea580c',
border: 'none',
- color: '#fff',
+ color: 'colors.text',
padding: '6px 12px',
fontSize: '10px',
cursor: currentSeriesIdsSet.has(result.id) ? 'not-allowed' : 'pointer',
@@ -618,7 +620,7 @@ export default function ScreenerTab() {
<div
key={result.id}
style={{
- background: '#0a0a0a',
+ background: 'colors.panel',
border: '1px solid #1a1a1a',
borderRadius: '4px',
padding: '12px',
@@ -637,7 +639,7 @@ export default function ScreenerTab() {
Pop: {result.popularity}
</span>
</div>
- <p style={{ color: '#fff', fontSize: '10px', marginBottom: '4px' }}>
+ <p style={{ color: 'colors.text', fontSize: '10px', marginBottom: '4px' }}>
{result.title}
</p>
<div style={{ display: 'flex', gap: '12px', fontSize: '9px', color: '#666' }}>
@@ -652,7 +654,7 @@ export default function ScreenerTab() {
style={{
background: currentSeriesIdsSet.has(result.id) ? '#1a3a1a' : '#ea580c',
border: 'none',
- color: '#fff',
+ color: 'colors.text',
padding: '6px 12px',
fontSize: '10px',
cursor: currentSeriesIdsSet.has(result.id) ? 'not-allowed' : 'pointer',
@@ -697,7 +699,7 @@ export default function ScreenerTab() {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
- background: '#0a0a0a'
+ background: 'colors.panel'
}}>
<span style={{ color: '#666', fontSize: '9px' }}>
Federal Reserve Economic Data (FRED) | 800,000+ series available
@@ -707,7 +709,7 @@ export default function ScreenerTab() {
style={{
background: '#ea580c',
border: 'none',
- color: '#fff',
+ color: 'colors.text',
padding: '8px 16px',
fontSize: '10px',
cursor: 'pointer',
@@ -726,7 +728,7 @@ export default function ScreenerTab() {
<div style={{
borderBottom: '2px solid #ea580c',
padding: '12px 16px',
- background: 'linear-gradient(180deg, #1a1a1a 0%, #0a0a0a 100%)',
+ background: 'linear-gradient(180deg, #1a1a1a 0%, colors.panel 100%)',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
@@ -742,7 +744,7 @@ export default function ScreenerTab() {
<button
onClick={() => setChartType(chartType === 'line' ? 'area' : 'line')}
style={{
- background: '#0a0a0a',
+ background: 'colors.panel',
border: '1px solid #2a2a2a',
color: '#ea580c',
padding: '6px 12px',
@@ -758,7 +760,7 @@ export default function ScreenerTab() {
onClick={exportToCSV}
disabled={data.length === 0}
style={{
- background: '#0a0a0a',
+ background: 'colors.panel',
border: '1px solid #2a2a2a',
color: data.length > 0 ? '#00ff00' : '#666',
padding: '6px 12px',
@@ -804,7 +806,7 @@ export default function ScreenerTab() {
<div style={{
borderBottom: '1px solid #1a1a1a',
padding: '16px',
- background: '#0a0a0a',
+ background: 'colors.panel',
flexShrink: 0
}}>
<div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr auto', gap: '12px', marginBottom: '12px' }}>
@@ -819,9 +821,9 @@ export default function ScreenerTab() {
placeholder="GDP,UNRATE,CPIAUCSL"
style={{
width: '100%',
- background: '#000',
+ background: 'colors.background',
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: 'colors.text',
padding: '8px',
fontSize: '10px',
borderRadius: '3px'
@@ -838,9 +840,9 @@ export default function ScreenerTab() {
onChange={(e) => setStartDate(e.target.value)}
style={{
width: '100%',
- background: '#000',
+ background: 'colors.background',
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: 'colors.text',
padding: '8px',
fontSize: '10px',
borderRadius: '3px'
@@ -857,9 +859,9 @@ export default function ScreenerTab() {
onChange={(e) => setEndDate(e.target.value)}
style={{
width: '100%',
- background: '#000',
+ background: 'colors.background',
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: 'colors.text',
padding: '8px',
fontSize: '10px',
borderRadius: '3px'
@@ -872,7 +874,7 @@ export default function ScreenerTab() {
style={{
background: '#ea580c',
border: 'none',
- color: '#fff',
+ color: 'colors.text',
padding: '0 20px',
fontSize: '10px',
cursor: loading ? 'not-allowed' : 'pointer',
@@ -902,7 +904,7 @@ export default function ScreenerTab() {
key={series.id}
onClick={() => addPopularSeries(series.id)}
style={{
- background: currentSeriesIdsSet.has(series.id) ? '#1a3a1a' : '#0a0a0a',
+ background: currentSeriesIdsSet.has(series.id) ? '#1a3a1a' : 'colors.panel',
border: `1px solid ${currentSeriesIdsSet.has(series.id) ? '#00ff00' : '#2a2a2a'}`,
color: currentSeriesIdsSet.has(series.id) ? '#00ff00' : '#666',
padding: '4px 8px',
@@ -922,7 +924,7 @@ export default function ScreenerTab() {
style={{
background: 'linear-gradient(135deg, #ea580c 0%, #c2410c 100%)',
border: '1px solid #ea580c',
- color: '#fff',
+ color: 'colors.text',
padding: '8px 16px',
fontSize: '10px',
cursor: apiKeyConfigured ? 'pointer' : 'not-allowed',
@@ -948,7 +950,7 @@ export default function ScreenerTab() {
{/* Chart Section */}
<div style={{ flex: 2, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
<div style={{
- background: '#0a0a0a',
+ background: 'colors.panel',
border: '1px solid #1a1a1a',
borderRadius: '4px',
padding: '16px',
@@ -956,7 +958,7 @@ export default function ScreenerTab() {
display: 'flex',
flexDirection: 'column'
}}>
- <h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <h3 style={{ color: 'colors.text', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
TIME SERIES CHART
</h3>
@@ -999,7 +1001,7 @@ export default function ScreenerTab() {
<XAxis dataKey="date" stroke="#666" style={{ fontSize: '10px' }} />
<YAxis stroke="#666" style={{ fontSize: '10px' }} />
<Tooltip
- contentStyle={{ background: '#0a0a0a', border: '1px solid #2a2a2a', borderRadius: '3px', fontSize: '10px' }}
+ contentStyle={{ background: 'colors.panel', border: '1px solid #2a2a2a', borderRadius: '3px', fontSize: '10px' }}
labelStyle={{ color: '#ea580c' }}
/>
<Legend wrapperStyle={{ fontSize: '10px' }} />
@@ -1008,7 +1010,7 @@ export default function ScreenerTab() {
key={series.series_id}
type="monotone"
dataKey={series.series_id}
- stroke={['#ea580c', '#00ff00', '#00ffff', '#ff00ff', '#ffff00'][idx % 5]}
+ stroke={['#ea580c', '#00ff00', '#00ffff', '#ff00ff', 'colors.textf00'][idx % 5]}
strokeWidth={2}
dot={false}
/>
@@ -1020,7 +1022,7 @@ export default function ScreenerTab() {
<XAxis dataKey="date" stroke="#666" style={{ fontSize: '10px' }} />
<YAxis stroke="#666" style={{ fontSize: '10px' }} />
<Tooltip
- contentStyle={{ background: '#0a0a0a', border: '1px solid #2a2a2a', borderRadius: '3px', fontSize: '10px' }}
+ contentStyle={{ background: 'colors.panel', border: '1px solid #2a2a2a', borderRadius: '3px', fontSize: '10px' }}
labelStyle={{ color: '#ea580c' }}
/>
<Legend wrapperStyle={{ fontSize: '10px' }} />
@@ -1029,8 +1031,8 @@ export default function ScreenerTab() {
key={series.series_id}
type="monotone"
dataKey={series.series_id}
- stroke={['#ea580c', '#00ff00', '#00ffff', '#ff00ff', '#ffff00'][idx % 5]}
- fill={['#ea580c33', '#00ff0033', '#00ffff33', '#ff00ff33', '#ffff0033'][idx % 5]}
+ stroke={['#ea580c', '#00ff00', '#00ffff', '#ff00ff', 'colors.textf00'][idx % 5]}
+ fill={['#ea580c33', '#00ff0033', '#00ffff33', '#ff00ff33', 'colors.textf0033'][idx % 5]}
/>
))}
</AreaChart>
@@ -1047,7 +1049,7 @@ export default function ScreenerTab() {
<div
key={series.series_id}
style={{
- background: '#0a0a0a',
+ background: 'colors.panel',
border: '1px solid #1a1a1a',
borderRadius: '4px',
padding: '12px',
@@ -1070,7 +1072,7 @@ export default function ScreenerTab() {
<div style={{ maxHeight: '200px', overflowY: 'auto' }}>
<table style={{ width: '100%', fontSize: '9px', borderCollapse: 'collapse' }}>
- <thead style={{ position: 'sticky', top: 0, background: '#0a0a0a' }}>
+ <thead style={{ position: 'sticky', top: 0, background: 'colors.panel' }}>
<tr style={{ borderBottom: '1px solid #1a1a1a' }}>
<th style={{ color: '#888', textAlign: 'left', padding: '4px' }}>Date</th>
<th style={{ color: '#888', textAlign: 'right', padding: '4px' }}>Value</th>
@@ -1078,9 +1080,9 @@ export default function ScreenerTab() {
</thead>
<tbody>
{series.observations.slice(-20).reverse().map((obs, idx) => (
- <tr key={idx} style={{ borderBottom: '1px solid #0a0a0a' }}>
+ <tr key={idx} style={{ borderBottom: '1px solid colors.panel' }}>
<td style={{ color: '#666', padding: '4px' }}>{obs.date}</td>
- <td style={{ color: '#fff', textAlign: 'right', padding: '4px', fontFamily: 'monospace' }}>
+ <td style={{ color: 'colors.text', textAlign: 'right', padding: '4px', fontFamily: 'monospace' }}>
{obs.value.toFixed(2)}
</td>
</tr>
@@ -1097,7 +1099,7 @@ export default function ScreenerTab() {
<div style={{
borderTop: '1px solid #1a1a1a',
padding: '8px 16px',
- background: '#0a0a0a',
+ background: 'colors.panel',
fontSize: '9px',
color: '#666',
display: 'flex',
diff --git a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
index dbd2cbc9a..2de61fc6b 100644
--- a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
@@ -1,16 +1,48 @@
import React, { useState, useEffect } from 'react';
-import { Eye, EyeOff, Plus, Trash2, Save, RefreshCw, Lock, User, Settings as SettingsIcon, Database, Terminal, Bell, Bot, Edit3 } from 'lucide-react';
+import { Eye, EyeOff, Plus, Trash2, Save, RefreshCw, Lock, User, Settings as SettingsIcon, Database, Terminal, Bell, Bot, Edit3, Type, Palette, Wifi, WifiOff, Activity, Zap, Link } from 'lucide-react';
import { sqliteService, type Credential, type LLMConfig, type LLMGlobalSettings } from '@/services/sqliteService';
import { ollamaService } from '@/services/ollamaService';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { terminalThemeService, FONT_FAMILIES, COLOR_THEMES, FontSettings } from '@/services/terminalThemeService';
+import { getWebSocketManager, ConnectionStatus, getAvailableProviders } from '@/services/websocket';
+import { useWebSocketManager } from '@/hooks/useWebSocket';
export default function SettingsTab() {
- const [activeSection, setActiveSection] = useState<'credentials' | 'profile' | 'terminal' | 'notifications' | 'llm'>('credentials');
+ const { theme, updateTheme, resetTheme, colors, fontSize: themeFontSize, fontFamily: themeFontFamily, fontWeight: themeFontWeight, fontStyle } = useTerminalTheme();
+ const [activeSection, setActiveSection] = useState<'credentials' | 'profile' | 'terminal' | 'notifications' | 'llm' | 'dataConnections'>('credentials');
const [credentials, setCredentials] = useState<Credential[]>([]);
const [showPasswords, setShowPasswords] = useState<Record<number, boolean>>({});
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
const [dbInitialized, setDbInitialized] = useState(false);
+ // WebSocket Data Connections State
+ const { stats, statuses, metrics } = useWebSocketManager();
+ const [wsProviders, setWsProviders] = useState<Array<{
+ id: number;
+ provider_name: string;
+ enabled: boolean;
+ api_key: string | null;
+ api_secret: string | null;
+ endpoint: string | null;
+ config_data: string | null;
+ }>>([]);
+ const [selectedProvider, setSelectedProvider] = useState<string | null>(null);
+ const [providerForm, setProviderForm] = useState({
+ provider_name: '',
+ enabled: true,
+ api_key: '',
+ api_secret: '',
+ endpoint: ''
+ });
+
+ // Terminal appearance states
+ const [fontFamily, setFontFamily] = useState(theme.font.family);
+ const [baseSize, setBaseSize] = useState(theme.font.baseSize);
+ const [fontWeight, setFontWeight] = useState(theme.font.weight);
+ const [fontItalic, setFontItalic] = useState(theme.font.italic);
+ const [selectedTheme, setSelectedTheme] = useState(terminalThemeService.getCurrentThemeKey());
+
// LLM Configuration States
const [llmConfigs, setLlmConfigs] = useState<LLMConfig[]>([]);
const [llmGlobalSettings, setLlmGlobalSettings] = useState<LLMGlobalSettings>({
@@ -38,6 +70,7 @@ export default function SettingsTab() {
useEffect(() => {
initDB();
+ loadWSProviders();
}, []);
const initDB = async () => {
@@ -58,6 +91,7 @@ export default function SettingsTab() {
// Load initial data
await loadCredentials();
await loadLLMConfigs();
+ await loadWSProviders();
showMessage('success', `Database ready: ${healthCheck.message}`);
} catch (error) {
@@ -70,6 +104,138 @@ export default function SettingsTab() {
}
};
+ const loadWSProviders = async () => {
+ try {
+ const providers = await sqliteService.getWSProviderConfigs();
+ setWsProviders(providers);
+ } catch (error) {
+ console.error('Failed to load WS providers:', error);
+ }
+ };
+
+ const handleSaveWSProvider = async () => {
+ if (!providerForm.provider_name.trim()) {
+ showMessage('error', 'Provider name is required');
+ return;
+ }
+
+ try {
+ setLoading(true);
+ const result = await sqliteService.saveWSProviderConfig(providerForm);
+
+ if (result.success) {
+ showMessage('success', result.message);
+
+ // Initialize provider in WebSocket Manager
+ const manager = getWebSocketManager();
+ manager.setProviderConfig(providerForm.provider_name, {
+ provider_name: providerForm.provider_name,
+ enabled: providerForm.enabled,
+ api_key: providerForm.api_key || undefined,
+ api_secret: providerForm.api_secret || undefined,
+ endpoint: providerForm.endpoint || undefined
+ });
+
+ // Reset form
+ setProviderForm({
+ provider_name: '',
+ enabled: true,
+ api_key: '',
+ api_secret: '',
+ endpoint: ''
+ });
+ setSelectedProvider(null);
+ await loadWSProviders();
+ } else {
+ showMessage('error', result.message);
+ }
+ } catch (error) {
+ showMessage('error', 'Failed to save provider configuration');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleToggleWSProvider = async (providerName: string) => {
+ try {
+ const result = await sqliteService.toggleWSProviderEnabled(providerName);
+ if (result.success) {
+ showMessage('success', result.message);
+ await loadWSProviders();
+
+ // Reconnect or disconnect based on new state
+ const manager = getWebSocketManager();
+ if (result.enabled) {
+ const config = await sqliteService.getWSProviderConfig(providerName);
+ if (config) {
+ manager.setProviderConfig(providerName, config);
+ }
+ } else {
+ await manager.disconnect(providerName);
+ }
+ }
+ } catch (error) {
+ showMessage('error', 'Failed to toggle provider');
+ }
+ };
+
+ const handleDeleteWSProvider = async (providerName: string) => {
+ if (!confirm(`Delete configuration for ${providerName}?`)) return;
+
+ try {
+ setLoading(true);
+ const result = await sqliteService.deleteWSProviderConfig(providerName);
+
+ if (result.success) {
+ showMessage('success', result.message);
+
+ // Disconnect from WebSocket Manager
+ const manager = getWebSocketManager();
+ await manager.disconnect(providerName);
+
+ await loadWSProviders();
+ }
+ } catch (error) {
+ showMessage('error', 'Failed to delete provider');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleConnectProvider = async (providerName: string) => {
+ try {
+ const manager = getWebSocketManager();
+ const config = await sqliteService.getWSProviderConfig(providerName);
+ if (config) {
+ manager.setProviderConfig(providerName, config);
+ await manager.connect(providerName);
+ showMessage('success', `Connected to ${providerName}`);
+ }
+ } catch (error) {
+ showMessage('error', `Failed to connect to ${providerName}`);
+ }
+ };
+
+ const handleDisconnectProvider = async (providerName: string) => {
+ try {
+ const manager = getWebSocketManager();
+ await manager.disconnect(providerName);
+ showMessage('success', `Disconnected from ${providerName}`);
+ } catch (error) {
+ showMessage('error', `Failed to disconnect from ${providerName}`);
+ }
+ };
+
+ const handleTestProvider = async (providerName: string) => {
+ try {
+ const manager = getWebSocketManager();
+ const latency = await manager.ping(providerName);
+ showMessage('success', `Ping: ${latency}ms`);
+ } catch (error) {
+ showMessage('error', `Ping failed for ${providerName}`);
+ }
+ };
+
const loadCredentials = async () => {
try {
const creds = await sqliteService.getCredentials();
@@ -265,28 +431,69 @@ export default function SettingsTab() {
const getCurrentLLMConfig = () => llmConfigs.find(c => c.provider === activeProvider);
+ // Terminal appearance handlers
+ const handleSaveTerminalAppearance = () => {
+ const newTheme = {
+ font: {
+ family: fontFamily,
+ baseSize: baseSize,
+ weight: fontWeight,
+ italic: fontItalic
+ },
+ colors: COLOR_THEMES[selectedTheme]
+ };
+ updateTheme(newTheme);
+ showMessage('success', 'Terminal appearance saved successfully');
+ };
+
+ const handleResetTerminalAppearance = () => {
+ resetTheme();
+ const defaultTheme = terminalThemeService.getTheme();
+ setFontFamily(defaultTheme.font.family);
+ setBaseSize(defaultTheme.font.baseSize);
+ setFontWeight(defaultTheme.font.weight);
+ setFontItalic(defaultTheme.font.italic);
+ setSelectedTheme('bloomberg-classic');
+ showMessage('success', 'Reset to default appearance');
+ };
+
return (
- <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: '#000' }}>
+ <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: colors.background }}>
<style>{`
*::-webkit-scrollbar { width: 8px; height: 8px; }
- *::-webkit-scrollbar-track { background: #0a0a0a; }
+ *::-webkit-scrollbar-track { background: ${colors.panel}; }
*::-webkit-scrollbar-thumb { background: #2a2a2a; border-radius: 4px; }
*::-webkit-scrollbar-thumb:hover { background: #3a3a3a; }
+
+ @keyframes pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.5; }
+ }
+
+ @keyframes spin {
+ from { transform: rotate(0deg); }
+ to { transform: rotate(360deg); }
+ }
+
+ @keyframes slideIn {
+ from { transform: translateX(-10px); opacity: 0; }
+ to { transform: translateX(0); opacity: 1; }
+ }
`}</style>
{/* Header */}
<div style={{
- borderBottom: '2px solid #ea580c',
+ borderBottom: `2px solid ${colors.primary}`,
padding: '12px 16px',
- background: 'linear-gradient(180deg, #1a1a1a 0%, #0a0a0a 100%)',
+ background: `linear-gradient(180deg, #1a1a1a 0%, ${colors.panel} 100%)`,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
flexShrink: 0
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <SettingsIcon size={20} color="#ea580c" />
- <span style={{ color: '#ea580c', fontSize: '16px', fontWeight: 'bold', letterSpacing: '1px' }}>
+ <SettingsIcon size={20} color={colors.primary} />
+ <span style={{ color: colors.primary, fontSize: '16px', fontWeight: 'bold', letterSpacing: '1px' }}>
TERMINAL SETTINGS
</span>
</div>
@@ -323,11 +530,12 @@ export default function SettingsTab() {
<div style={{ flex: 1, display: 'flex', minHeight: 0, overflow: 'hidden' }}>
{/* Sidebar Navigation */}
- <div style={{ width: '220px', borderRight: '1px solid #1a1a1a', background: '#0a0a0a', flexShrink: 0 }}>
+ <div style={{ width: '220px', borderRight: '1px solid #1a1a1a', background: colors.panel, flexShrink: 0 }}>
<div style={{ padding: '16px 0' }}>
{[
{ id: 'credentials', icon: Lock, label: 'Credentials' },
{ id: 'llm', icon: Bot, label: 'LLM Configuration' },
+ { id: 'dataConnections', icon: Wifi, label: 'Data Connections' },
{ id: 'profile', icon: User, label: 'User Profile' },
{ id: 'terminal', icon: Terminal, label: 'Terminal Config' },
{ id: 'notifications', icon: Bell, label: 'Notifications' }
@@ -339,7 +547,7 @@ export default function SettingsTab() {
padding: '12px 16px',
cursor: 'pointer',
background: activeSection === item.id ? '#1a1a1a' : 'transparent',
- borderLeft: activeSection === item.id ? '3px solid #ea580c' : '3px solid transparent',
+ borderLeft: activeSection === item.id ? `3px solid ${colors.primary}` : '3px solid transparent',
display: 'flex',
alignItems: 'center',
gap: '12px',
@@ -352,8 +560,8 @@ export default function SettingsTab() {
if (activeSection !== item.id) e.currentTarget.style.background = 'transparent';
}}
>
- <item.icon size={16} color={activeSection === item.id ? '#ea580c' : '#666'} />
- <span style={{ color: activeSection === item.id ? '#fff' : '#666', fontSize: '11px', fontWeight: activeSection === item.id ? 'bold' : 'normal' }}>
+ <item.icon size={16} color={activeSection === item.id ? colors.primary : colors.textMuted} />
+ <span style={{ color: activeSection === item.id ? colors.text : colors.textMuted, fontSize: '11px', fontWeight: activeSection === item.id ? 'bold' : 'normal' }}>
{item.label}
</span>
</div>
@@ -369,29 +577,29 @@ export default function SettingsTab() {
{activeSection === 'credentials' && (
<div>
<div style={{ marginBottom: '24px' }}>
- <h2 style={{ color: '#ea580c', fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ <h2 style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
API KEY MANAGEMENT
</h2>
- <p style={{ color: '#888', fontSize: '10px' }}>
+ <p style={{ color: colors.textMuted, fontSize: '10px' }}>
Store API keys for services like FRED, Alpha Vantage, Polygon.io, etc. All data is encrypted and stored locally.
</p>
</div>
{/* Polygon.io Dedicated Field */}
<div style={{
- background: '#0a0a0a',
+ background: colors.panel,
border: '1px solid #1a1a1a',
padding: '16px',
marginBottom: '20px',
borderRadius: '4px'
}}>
- <h3 style={{ color: '#ea580c', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <h3 style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
Polygon.io API Key
</h3>
<div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '12px', alignItems: 'end' }}>
<div>
- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
API KEY *
</label>
<input
@@ -401,9 +609,9 @@ export default function SettingsTab() {
placeholder="Enter your Polygon.io API key"
style={{
width: '100%',
- background: '#000',
+ background: colors.background,
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: colors.text,
padding: '8px',
fontSize: '10px',
borderRadius: '3px'
@@ -414,8 +622,8 @@ export default function SettingsTab() {
onClick={handleSavePolygonKey}
disabled={loading}
style={{
- background: '#ea580c',
- color: '#fff',
+ background: colors.primary,
+ color: colors.text,
border: 'none',
padding: '8px 16px',
fontSize: '10px',
@@ -433,26 +641,26 @@ export default function SettingsTab() {
{loading ? 'SAVING...' : 'SAVE'}
</button>
</div>
- <p style={{ color: '#666', fontSize: '9px', marginTop: '8px' }}>
- Used for Polygon.io Equities data in the Polygon tab. Get your free API key at <span style={{ color: '#ea580c' }}>polygon.io</span>
+ <p style={{ color: colors.textMuted, fontSize: '9px', marginTop: '8px' }}>
+ Used for Polygon.io Equities data in the Polygon tab. Get your free API key at <span style={{ color: colors.primary }}>polygon.io</span>
</p>
</div>
{/* Add New API Key */}
<div style={{
- background: '#0a0a0a',
+ background: colors.panel,
border: '1px solid #1a1a1a',
padding: '16px',
marginBottom: '20px',
borderRadius: '4px'
}}>
- <h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <h3 style={{ color: colors.text, fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
Add New API Key
</h3>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr auto', gap: '12px', alignItems: 'end' }}>
<div>
- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
SERVICE NAME *
</label>
<input
@@ -462,9 +670,9 @@ export default function SettingsTab() {
placeholder="e.g., Polygon.io, FRED, AlphaVantage"
style={{
width: '100%',
- background: '#000',
+ background: colors.background,
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: colors.text,
padding: '8px',
fontSize: '10px',
borderRadius: '3px'
@@ -472,7 +680,7 @@ export default function SettingsTab() {
/>
</div>
<div>
- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
API KEY *
</label>
<input
@@ -482,9 +690,9 @@ export default function SettingsTab() {
placeholder="Your API key"
style={{
width: '100%',
- background: '#000',
+ background: colors.background,
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: colors.text,
padding: '8px',
fontSize: '10px',
borderRadius: '3px'
@@ -495,8 +703,8 @@ export default function SettingsTab() {
onClick={handleSaveApiKey}
disabled={loading}
style={{
- background: '#ea580c',
- color: '#fff',
+ background: colors.primary,
+ color: colors.text,
border: 'none',
padding: '8px 16px',
fontSize: '10px',
@@ -518,20 +726,20 @@ export default function SettingsTab() {
{/* Saved API Keys List */}
<div>
- <h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <h3 style={{ color: colors.text, fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
Saved API Keys ({credentials.length})
</h3>
{credentials.length === 0 ? (
<div style={{
- background: '#0a0a0a',
+ background: colors.panel,
border: '1px solid #1a1a1a',
padding: '32px',
textAlign: 'center',
borderRadius: '4px'
}}>
- <Lock size={32} color="#333" style={{ margin: '0 auto 12px' }} />
- <p style={{ color: '#666', fontSize: '11px' }}>No API keys saved yet</p>
+ <Lock size={32} color={colors.textMuted} style={{ margin: '0 auto 12px' }} />
+ <p style={{ color: colors.textMuted, fontSize: '11px' }}>No API keys saved yet</p>
</div>
) : (
<div style={{ display: 'grid', gap: '12px' }}>
@@ -539,7 +747,7 @@ export default function SettingsTab() {
<div
key={cred.id}
style={{
- background: '#0a0a0a',
+ background: colors.panel,
border: '1px solid #1a1a1a',
padding: '16px',
borderRadius: '4px',
@@ -549,12 +757,12 @@ export default function SettingsTab() {
}}
>
<div style={{ flex: 1 }}>
- <h4 style={{ color: '#ea580c', fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
+ <h4 style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
{cred.service_name}
</h4>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <span style={{ color: '#888', fontSize: '9px' }}>API Key:</span>
- <span style={{ color: '#fff', fontFamily: 'monospace', fontSize: '10px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '9px' }}>API Key:</span>
+ <span style={{ color: colors.text, fontFamily: 'monospace', fontSize: '10px' }}>
{showPasswords[cred.id!] ? cred.api_key : '•'.repeat(20)}
</span>
<button
@@ -567,10 +775,10 @@ export default function SettingsTab() {
display: 'flex'
}}
>
- {showPasswords[cred.id!] ? <EyeOff size={14} color="#888" /> : <Eye size={14} color="#888" />}
+ {showPasswords[cred.id!] ? <EyeOff size={14} color={colors.textMuted} /> : <Eye size={14} color={colors.textMuted} />}
</button>
</div>
- <p style={{ color: '#666', fontSize: '9px', marginTop: '4px' }}>
+ <p style={{ color: colors.textMuted, fontSize: '9px', marginTop: '4px' }}>
Added: {cred.created_at ? new Date(cred.created_at).toLocaleDateString() : 'N/A'}
</p>
</div>
@@ -604,17 +812,17 @@ export default function SettingsTab() {
{activeSection === 'llm' && (
<div>
<div style={{ marginBottom: '24px' }}>
- <h2 style={{ color: '#ea580c', fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ <h2 style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
LLM CONFIGURATION
</h2>
- <p style={{ color: '#888', fontSize: '10px' }}>
+ <p style={{ color: colors.textMuted, fontSize: '10px' }}>
Configure AI providers for the Chat tab. Changes here are reflected in both Chat and Settings screens.
</p>
</div>
{/* Provider Selection */}
<div style={{ marginBottom: '20px' }}>
- <h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
+ <h3 style={{ color: colors.text, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
Select Active Provider
</h3>
<div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
@@ -623,9 +831,9 @@ export default function SettingsTab() {
key={config.provider}
onClick={() => setActiveProvider(config.provider)}
style={{
- background: activeProvider === config.provider ? '#ea580c' : '#0a0a0a',
- color: activeProvider === config.provider ? '#000' : '#fff',
- border: `1px solid ${activeProvider === config.provider ? '#ea580c' : '#2a2a2a'}`,
+ background: activeProvider === config.provider ? colors.primary : colors.panel,
+ color: activeProvider === config.provider ? colors.background : colors.text,
+ border: `1px solid ${activeProvider === config.provider ? colors.primary : '#2a2a2a'}`,
padding: '8px 16px',
fontSize: '10px',
fontWeight: 'bold',
@@ -643,20 +851,20 @@ export default function SettingsTab() {
{/* Current Provider Config */}
{getCurrentLLMConfig() && (
<div style={{
- background: '#0a0a0a',
+ background: colors.panel,
border: '1px solid #1a1a1a',
padding: '16px',
marginBottom: '20px',
borderRadius: '4px'
}}>
- <h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <h3 style={{ color: colors.text, fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
{getCurrentLLMConfig()!.provider.toUpperCase()} Configuration
</h3>
<div style={{ display: 'grid', gap: '12px' }}>
{getCurrentLLMConfig()!.provider !== 'ollama' && (
<div>
- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
API KEY *
</label>
<input
@@ -666,9 +874,9 @@ export default function SettingsTab() {
placeholder={`Enter ${activeProvider} API key`}
style={{
width: '100%',
- background: '#000',
+ background: colors.background,
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: colors.text,
padding: '8px',
fontSize: '10px',
borderRadius: '3px'
@@ -679,7 +887,7 @@ export default function SettingsTab() {
{(getCurrentLLMConfig()!.provider === 'ollama' || getCurrentLLMConfig()!.provider === 'deepseek' || getCurrentLLMConfig()!.provider === 'openrouter') && (
<div>
- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
BASE URL
</label>
<input
@@ -689,9 +897,9 @@ export default function SettingsTab() {
placeholder={getCurrentLLMConfig()!.provider === 'ollama' ? 'http://localhost:11434' : 'Base URL'}
style={{
width: '100%',
- background: '#000',
+ background: colors.background,
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: colors.text,
padding: '8px',
fontSize: '10px',
borderRadius: '3px'
@@ -702,7 +910,7 @@ export default function SettingsTab() {
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
- <label style={{ color: '#888', fontSize: '9px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '9px' }}>
MODEL
</label>
{getCurrentLLMConfig()!.provider === 'ollama' && (
@@ -713,7 +921,7 @@ export default function SettingsTab() {
style={{
background: 'transparent',
border: '1px solid #2a2a2a',
- color: '#ea580c',
+ color: colors.primary,
padding: '4px 8px',
fontSize: '9px',
cursor: ollamaLoading ? 'not-allowed' : 'pointer',
@@ -732,7 +940,7 @@ export default function SettingsTab() {
style={{
background: 'transparent',
border: '1px solid #2a2a2a',
- color: '#888',
+ color: colors.textMuted,
padding: '4px 8px',
fontSize: '9px',
cursor: 'pointer',
@@ -757,9 +965,9 @@ export default function SettingsTab() {
disabled={ollamaLoading || ollamaModels.length === 0}
style={{
width: '100%',
- background: '#000',
+ background: colors.background,
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: colors.text,
padding: '8px',
fontSize: '10px',
borderRadius: '3px',
@@ -810,9 +1018,9 @@ export default function SettingsTab() {
placeholder="Model name"
style={{
width: '100%',
- background: '#000',
+ background: colors.background,
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: colors.text,
padding: '8px',
fontSize: '10px',
borderRadius: '3px'
@@ -826,19 +1034,19 @@ export default function SettingsTab() {
{/* Global Settings */}
<div style={{
- background: '#0a0a0a',
+ background: colors.panel,
border: '1px solid #1a1a1a',
padding: '16px',
marginBottom: '20px',
borderRadius: '4px'
}}>
- <h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <h3 style={{ color: colors.text, fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
Global AI Settings
</h3>
<div style={{ display: 'grid', gap: '12px' }}>
<div>
- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
TEMPERATURE (0.0 - 2.0)
</label>
<input
@@ -850,9 +1058,9 @@ export default function SettingsTab() {
onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, temperature: parseFloat(e.target.value) })}
style={{
width: '100%',
- background: '#000',
+ background: colors.background,
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: colors.text,
padding: '8px',
fontSize: '10px',
borderRadius: '3px'
@@ -861,7 +1069,7 @@ export default function SettingsTab() {
</div>
<div>
- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
MAX TOKENS
</label>
<input
@@ -872,9 +1080,9 @@ export default function SettingsTab() {
onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, max_tokens: parseInt(e.target.value) })}
style={{
width: '100%',
- background: '#000',
+ background: colors.background,
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: colors.text,
padding: '8px',
fontSize: '10px',
borderRadius: '3px'
@@ -883,7 +1091,7 @@ export default function SettingsTab() {
</div>
<div>
- <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
SYSTEM PROMPT
</label>
<textarea
@@ -892,9 +1100,9 @@ export default function SettingsTab() {
rows={4}
style={{
width: '100%',
- background: '#000',
+ background: colors.background,
border: '1px solid #2a2a2a',
- color: '#fff',
+ color: colors.text,
padding: '8px',
fontSize: '10px',
borderRadius: '3px',
@@ -909,8 +1117,8 @@ export default function SettingsTab() {
onClick={handleSaveLLMConfig}
disabled={loading}
style={{
- background: '#ea580c',
- color: '#fff',
+ background: colors.primary,
+ color: colors.text,
border: 'none',
padding: '10px 20px',
fontSize: '11px',
@@ -929,10 +1137,740 @@ export default function SettingsTab() {
</div>
)}
+ {/* Terminal Appearance Section */}
+ {activeSection === 'terminal' && (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
+ {/* Font Settings */}
+ <div style={{ background: colors.panel, border: `1px solid ${colors.textMuted}`, borderRadius: '4px', padding: '16px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>
+ <Type size={18} color={colors.primary} />
+ <span style={{ color: colors.text, fontSize: '14px', fontWeight: 'bold' }}>FONT SETTINGS</span>
+ </div>
+
+ {/* Font Family */}
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '11px', display: 'block', marginBottom: '6px' }}>Font Family</label>
+ <select value={fontFamily} onChange={(e) => setFontFamily(e.target.value)} style={{ width: '100%', padding: '8px', background: colors.background, border: '1px solid #444', color: colors.text, borderRadius: '3px' }}>
+ {FONT_FAMILIES.map(f => <option key={f.value} value={f.value}>{f.label}</option>)}
+ </select>
+ </div>
+
+ {/* Base Font Size */}
+ <div style={{ marginBottom: '16px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '11px' }}>Base Font Size</label>
+ <span style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold' }}>{baseSize}px</span>
+ </div>
+ <input type="range" min="9" max="18" value={baseSize} onChange={(e) => setBaseSize(Number(e.target.value))} style={{ width: '100%' }} />
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '4px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '9px' }}>Small (9px)</span>
+ <span style={{ color: colors.textMuted, fontSize: '9px' }}>Large (18px)</span>
+ </div>
+ </div>
+
+ {/* Font Weight */}
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: colors.textMuted, fontSize: '11px', display: 'block', marginBottom: '6px' }}>Font Weight</label>
+ <select value={fontWeight} onChange={(e) => setFontWeight(e.target.value as FontSettings['weight'])} style={{ width: '100%', padding: '8px', background: colors.background, border: '1px solid #444', color: colors.text, borderRadius: '3px' }}>
+ <option value="normal">Normal</option>
+ <option value="semibold">Semi-Bold</option>
+ <option value="bold">Bold</option>
+ </select>
+ </div>
+
+ {/* Font Style */}
+ <div style={{ marginBottom: '0' }}>
+ <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
+ <input type="checkbox" checked={fontItalic} onChange={(e) => setFontItalic(e.target.checked)} />
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>Enable Italic</span>
+ </label>
+ </div>
+ </div>
+
+ {/* Color Theme */}
+ <div style={{ background: colors.panel, border: `1px solid ${colors.textMuted}`, borderRadius: '4px', padding: '16px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>
+ <Palette size={18} color={colors.primary} />
+ <span style={{ color: colors.text, fontSize: '14px', fontWeight: 'bold' }}>COLOR THEME</span>
+ </div>
+
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
+ {Object.entries(COLOR_THEMES).map(([key, themeObj]) => (
+ <label key={key} style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '10px', background: selectedTheme === key ? '#1a1a1a' : 'transparent', border: `1px solid ${selectedTheme === key ? colors.primary : colors.textMuted}`, borderRadius: '4px', cursor: 'pointer' }}>
+ <input type="radio" name="theme" value={key} checked={selectedTheme === key} onChange={() => setSelectedTheme(key)} />
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <div style={{ width: '20px', height: '20px', background: themeObj.primary, border: '1px solid #444' }} title="Primary" />
+ <div style={{ width: '20px', height: '20px', background: themeObj.secondary, border: '1px solid #444' }} title="Secondary" />
+ <div style={{ width: '20px', height: '20px', background: themeObj.alert, border: '1px solid #444' }} title="Alert" />
+ </div>
+ <span style={{ color: colors.text, fontSize: '12px', flex: 1 }}>{themeObj.name}</span>
+ {selectedTheme === key && <span style={{ color: colors.primary, fontSize: '10px', fontWeight: 'bold' }}>✓ ACTIVE</span>}
+ </label>
+ ))}
+ </div>
+ </div>
+
+ {/* Preview Panel */}
+ <div style={{ background: theme.colors.background, border: `2px solid ${theme.colors.primary}`, borderRadius: '4px', padding: '16px' }}>
+ <div style={{ color: theme.colors.primary, fontSize: `${baseSize + 2}px`, fontFamily: `${fontFamily}, monospace`, fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700', fontStyle: fontItalic ? 'italic' : 'normal', marginBottom: '12px' }}>
+ FINCEPT TERMINAL PREVIEW
+ </div>
+ <div style={{ color: theme.colors.text, fontSize: `${baseSize}px`, fontFamily: `${fontFamily}, monospace`, fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700', fontStyle: fontItalic ? 'italic' : 'normal', marginBottom: '8px' }}>
+ Body Text: Lorem ipsum dolor sit amet
+ </div>
+ <div style={{ color: theme.colors.textMuted, fontSize: `${baseSize - 1}px`, fontFamily: `${fontFamily}, monospace`, fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700', fontStyle: fontItalic ? 'italic' : 'normal', marginBottom: '8px' }}>
+ Small Text: Market data and timestamps
+ </div>
+ <div style={{ display: 'flex', gap: '12px', marginTop: '12px' }}>
+ <span style={{ color: theme.colors.secondary }}>● LIVE</span>
+ <span style={{ color: theme.colors.alert }}>● ALERT</span>
+ <span style={{ color: theme.colors.warning }}>● WARNING</span>
+ </div>
+ </div>
+
+ {/* Action Buttons */}
+ <div style={{ display: 'flex', gap: '12px' }}>
+ <button onClick={handleSaveTerminalAppearance} style={{ flex: 1, background: colors.primary, color: colors.background, border: 'none', padding: '12px', fontSize: '12px', fontWeight: 'bold', borderRadius: '4px', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px' }}>
+ <Save size={14} /> SAVE APPEARANCE
+ </button>
+ <button onClick={handleResetTerminalAppearance} style={{ background: colors.textMuted, color: colors.text, border: 'none', padding: '12px 16px', fontSize: '12px', fontWeight: 'bold', borderRadius: '4px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <RefreshCw size={14} /> RESET
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Data Connections Section */}
+ {activeSection === 'dataConnections' && (
+ <div>
+ <div style={{ marginBottom: '24px' }}>
+ <h2 style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ WEBSOCKET DATA CONNECTIONS
+ </h2>
+ <p style={{ color: colors.textMuted, fontSize: '10px' }}>
+ Manage WebSocket connections to financial data providers. Configure API keys, endpoints, and monitor connection health.
+ </p>
+ </div>
+
+ {/* Connection Overview Stats */}
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '20px' }}>
+ <div style={{ background: colors.panel, border: `2px solid ${stats.registry.connectedProviders > 0 ? '#00ff00' : '#3a3a3a'}`, padding: '12px', borderRadius: '4px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
+ <Activity size={12} color={stats.registry.connectedProviders > 0 ? '#00ff00' : colors.textMuted} />
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>ACTIVE CONNECTIONS</div>
+ </div>
+ <div style={{ color: stats.registry.connectedProviders > 0 ? '#00ff00' : colors.textMuted, fontSize: '24px', fontWeight: 'bold' }}>
+ {stats.registry.connectedProviders}
+ </div>
+ <div style={{ color: colors.textMuted, fontSize: '8px', marginTop: '4px' }}>
+ of {wsProviders.length} configured
+ </div>
+ </div>
+ <div style={{ background: colors.panel, border: '1px solid #1a1a1a', padding: '12px', borderRadius: '4px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
+ <Zap size={12} color={colors.primary} />
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>TOTAL SUBSCRIPTIONS</div>
+ </div>
+ <div style={{ color: colors.primary, fontSize: '24px', fontWeight: 'bold' }}>
+ {stats.activeSubscriptions}
+ </div>
+ <div style={{ color: colors.textMuted, fontSize: '8px', marginTop: '4px' }}>
+ across all providers
+ </div>
+ </div>
+ <div style={{ background: colors.panel, border: '1px solid #1a1a1a', padding: '12px', borderRadius: '4px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
+ <Database size={12} color={colors.text} />
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>CONFIGURED PROVIDERS</div>
+ </div>
+ <div style={{ color: colors.text, fontSize: '24px', fontWeight: 'bold' }}>
+ {wsProviders.length}
+ </div>
+ <div style={{ color: colors.textMuted, fontSize: '8px', marginTop: '4px' }}>
+ {wsProviders.filter(p => p.enabled).length} enabled
+ </div>
+ </div>
+ <div style={{ background: colors.panel, border: '1px solid #1a1a1a', padding: '12px', borderRadius: '4px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
+ <Activity size={12} color={stats.eventBus ? colors.secondary : colors.textMuted} />
+ <div style={{ color: colors.textMuted, fontSize: '9px' }}>EVENT BUS</div>
+ </div>
+ <div style={{ color: colors.secondary, fontSize: '24px', fontWeight: 'bold' }}>
+ {stats.eventBus?.subscriptions || 0}
+ </div>
+ <div style={{ color: colors.textMuted, fontSize: '8px', marginTop: '4px' }}>
+ subscriptions
+ </div>
+ </div>
+ </div>
+
+ {/* Add New Provider */}
+ <div style={{
+ background: colors.panel,
+ border: '1px solid #1a1a1a',
+ padding: '16px',
+ marginBottom: '20px',
+ borderRadius: '4px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
+ <h3 style={{ color: colors.text, fontSize: '12px', fontWeight: 'bold' }}>
+ {selectedProvider ? `Edit Provider: ${selectedProvider.toUpperCase()}` : 'Add New Provider'}
+ </h3>
+ {selectedProvider && (
+ <button
+ onClick={() => {
+ setSelectedProvider(null);
+ setProviderForm({
+ provider_name: '',
+ enabled: true,
+ api_key: '',
+ api_secret: '',
+ endpoint: ''
+ });
+ }}
+ style={{
+ background: 'transparent',
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.textMuted,
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold'
+ }}
+ >
+ CANCEL EDIT
+ </button>
+ )}
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>
+ <div>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ PROVIDER NAME * (e.g., kraken, fyers, polygon)
+ </label>
+ <select
+ value={providerForm.provider_name}
+ onChange={(e) => setProviderForm({ ...providerForm, provider_name: e.target.value })}
+ disabled={!!selectedProvider}
+ style={{
+ width: '100%',
+ background: selectedProvider ? '#1a1a1a' : colors.background,
+ border: '1px solid #2a2a2a',
+ color: selectedProvider ? colors.textMuted : colors.text,
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px',
+ cursor: selectedProvider ? 'not-allowed' : 'pointer'
+ }}
+ >
+ <option value="">Select a provider</option>
+ {getAvailableProviders().map(p => (
+ <option key={p} value={p}>{p.toUpperCase()}</option>
+ ))}
+ </select>
+ {selectedProvider && (
+ <div style={{ color: colors.textMuted, fontSize: '8px', marginTop: '4px' }}>
+ Provider name cannot be changed during edit
+ </div>
+ )}
+ </div>
+ <div>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ ENDPOINT (optional, uses default if empty)
+ </label>
+ <input
+ type="text"
+ value={providerForm.endpoint}
+ onChange={(e) => setProviderForm({ ...providerForm, endpoint: e.target.value })}
+ placeholder="wss://..."
+ style={{
+ width: '100%',
+ background: colors.background,
+ border: '1px solid #2a2a2a',
+ color: colors.text,
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ API KEY (if required)
+ </label>
+ <input
+ type="password"
+ value={providerForm.api_key}
+ onChange={(e) => setProviderForm({ ...providerForm, api_key: e.target.value })}
+ placeholder="Optional"
+ style={{
+ width: '100%',
+ background: colors.background,
+ border: '1px solid #2a2a2a',
+ color: colors.text,
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ API SECRET (if required)
+ </label>
+ <input
+ type="password"
+ value={providerForm.api_secret}
+ onChange={(e) => setProviderForm({ ...providerForm, api_secret: e.target.value })}
+ placeholder="Optional"
+ style={{
+ width: '100%',
+ background: colors.background,
+ border: '1px solid #2a2a2a',
+ color: colors.text,
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ </div>
+
+ <div style={{ marginTop: '12px', display: 'flex', gap: '8px', alignItems: 'center' }}>
+ <label style={{ display: 'flex', alignItems: 'center', gap: '6px', cursor: 'pointer' }}>
+ <input
+ type="checkbox"
+ checked={providerForm.enabled}
+ onChange={(e) => setProviderForm({ ...providerForm, enabled: e.target.checked })}
+ />
+ <span style={{ color: colors.textMuted, fontSize: '10px' }}>Enable this provider</span>
+ </label>
+
+ <button
+ onClick={handleSaveWSProvider}
+ disabled={loading}
+ style={{
+ marginLeft: 'auto',
+ background: colors.primary,
+ color: colors.text,
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: loading ? 'not-allowed' : 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ opacity: loading ? 0.5 : 1
+ }}
+ >
+ <Save size={14} />
+ {loading ? 'SAVING...' : (selectedProvider ? 'UPDATE PROVIDER' : 'SAVE PROVIDER')}
+ </button>
+ </div>
+ </div>
+
+ {/* Provider Cards */}
+ <div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
+ <h3 style={{ color: colors.text, fontSize: '12px', fontWeight: 'bold' }}>
+ Configured Providers ({wsProviders.length})
+ </h3>
+ {wsProviders.length > 0 && (
+ <div style={{ display: 'flex', gap: '8px' }}>
+ <button
+ onClick={async () => {
+ try {
+ const manager = getWebSocketManager();
+ await manager.reconnectAll();
+ showMessage('success', 'Reconnecting all providers...');
+ } catch (error) {
+ showMessage('error', 'Failed to reconnect providers');
+ }
+ }}
+ style={{
+ background: 'transparent',
+ border: `1px solid ${colors.primary}`,
+ color: colors.primary,
+ padding: '6px 12px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ letterSpacing: '0.5px'
+ }}
+ >
+ <RefreshCw size={12} />
+ RECONNECT ALL
+ </button>
+ <button
+ onClick={async () => {
+ if (!confirm('Disconnect all active providers?')) return;
+ try {
+ const manager = getWebSocketManager();
+ for (const provider of wsProviders) {
+ await manager.disconnect(provider.provider_name);
+ }
+ showMessage('success', 'Disconnected all providers');
+ } catch (error) {
+ showMessage('error', 'Failed to disconnect all providers');
+ }
+ }}
+ style={{
+ background: 'transparent',
+ border: '1px solid #ff0000',
+ color: '#ff0000',
+ padding: '6px 12px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ letterSpacing: '0.5px'
+ }}
+ >
+ <WifiOff size={12} />
+ DISCONNECT ALL
+ </button>
+ </div>
+ )}
+ </div>
+
+ {wsProviders.length === 0 ? (
+ <div style={{
+ background: colors.panel,
+ border: '1px solid #1a1a1a',
+ padding: '32px',
+ textAlign: 'center',
+ borderRadius: '4px'
+ }}>
+ <Wifi size={32} color={colors.textMuted} style={{ margin: '0 auto 12px' }} />
+ <p style={{ color: colors.textMuted, fontSize: '11px' }}>No providers configured yet</p>
+ </div>
+ ) : (
+ <div style={{ display: 'grid', gap: '12px' }}>
+ {wsProviders.map((provider) => {
+ const providerStatus = statuses.get(provider.provider_name);
+ const providerMetrics = metrics.get(provider.provider_name);
+ const isConnected = providerStatus === ConnectionStatus.CONNECTED;
+ const isConnecting = providerStatus === ConnectionStatus.CONNECTING;
+ const isReconnecting = providerStatus === ConnectionStatus.RECONNECTING;
+ const hasError = providerStatus === ConnectionStatus.ERROR;
+
+ // Calculate connection uptime
+ let uptimeText = 'Not connected';
+ if (providerMetrics?.connectedAt) {
+ const uptimeMs = Date.now() - providerMetrics.connectedAt;
+ const uptimeMin = Math.floor(uptimeMs / 60000);
+ const uptimeSec = Math.floor((uptimeMs % 60000) / 1000);
+ if (uptimeMin > 0) {
+ uptimeText = `${uptimeMin}m ${uptimeSec}s`;
+ } else {
+ uptimeText = `${uptimeSec}s`;
+ }
+ }
+
+ return (
+ <div
+ key={provider.id}
+ style={{
+ background: colors.panel,
+ border: `2px solid ${isConnected ? '#00ff00' : hasError ? '#ff0000' : isConnecting || isReconnecting ? colors.primary : '#1a1a1a'}`,
+ padding: '16px',
+ borderRadius: '4px',
+ position: 'relative',
+ overflow: 'hidden'
+ }}
+ >
+ {/* Connection status indicator bar */}
+ {isConnected && (
+ <div style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ height: '3px',
+ background: 'linear-gradient(90deg, #00ff00, #00ff00, rgba(0, 255, 0, 0.3))',
+ backgroundSize: '200% 100%',
+ animation: 'pulse 2s ease-in-out infinite'
+ }} />
+ )}
+
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: '12px' }}>
+ <div style={{ flex: 1 }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px', flexWrap: 'wrap' }}>
+ {isConnected ? (
+ <Wifi size={16} color="#00ff00" />
+ ) : isConnecting || isReconnecting ? (
+ <Activity size={16} color={colors.primary} style={{ animation: 'spin 1s linear infinite' }} />
+ ) : (
+ <WifiOff size={16} color={hasError ? '#ff0000' : colors.textMuted} />
+ )}
+ <h4 style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', textTransform: 'uppercase', letterSpacing: '0.5px' }}>
+ {provider.provider_name}
+ </h4>
+ <span style={{
+ padding: '3px 8px',
+ background: isConnected ? '#0a3a0a' : hasError ? '#3a0a0a' : isConnecting || isReconnecting ? 'rgba(234, 88, 12, 0.1)' : '#2a2a2a',
+ border: `1px solid ${isConnected ? '#00ff00' : hasError ? '#ff0000' : isConnecting || isReconnecting ? colors.primary : '#555'}`,
+ borderRadius: '3px',
+ fontSize: '8px',
+ fontWeight: 'bold',
+ color: isConnected ? '#00ff00' : hasError ? '#ff0000' : isConnecting || isReconnecting ? colors.primary : '#888',
+ letterSpacing: '0.5px'
+ }}>
+ {providerStatus || 'DISCONNECTED'}
+ </span>
+ {provider.enabled ? (
+ <span style={{
+ padding: '3px 8px',
+ background: '#0a3a0a',
+ border: '1px solid #00ff00',
+ borderRadius: '3px',
+ fontSize: '8px',
+ fontWeight: 'bold',
+ color: '#00ff00',
+ letterSpacing: '0.5px'
+ }}>
+ ENABLED
+ </span>
+ ) : (
+ <span style={{
+ padding: '3px 8px',
+ background: '#2a2a2a',
+ border: '1px solid #555',
+ borderRadius: '3px',
+ fontSize: '8px',
+ fontWeight: 'bold',
+ color: '#888',
+ letterSpacing: '0.5px'
+ }}>
+ DISABLED
+ </span>
+ )}
+ </div>
+
+ {provider.endpoint && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px', background: colors.background, padding: '4px 6px', borderRadius: '3px' }}>
+ <Link size={10} color={colors.textMuted} />
+ <span style={{ color: colors.text, fontSize: '9px', fontFamily: 'monospace' }}>
+ {provider.endpoint}
+ </span>
+ </div>
+ )}
+
+ {/* Connection metrics */}
+ {isConnected && providerMetrics && (
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))',
+ gap: '8px',
+ marginTop: '10px',
+ padding: '8px',
+ background: colors.background,
+ borderRadius: '3px'
+ }}>
+ <div>
+ <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>LATENCY</div>
+ <div style={{ color: '#00ff00', fontSize: '11px', fontWeight: 'bold' }}>
+ {providerMetrics.latency ? `${providerMetrics.latency}ms` : 'N/A'}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>MESSAGES</div>
+ <div style={{ color: colors.text, fontSize: '11px', fontWeight: 'bold' }}>
+ {providerMetrics.messagesReceived.toLocaleString()}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>MSG/SEC</div>
+ <div style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold' }}>
+ {providerMetrics.messagesPerSecond.toFixed(1)}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>SUBSCRIPTIONS</div>
+ <div style={{ color: colors.secondary, fontSize: '11px', fontWeight: 'bold' }}>
+ {providerMetrics.subscriptions}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>UPTIME</div>
+ <div style={{ color: colors.text, fontSize: '11px', fontWeight: 'bold' }}>
+ {uptimeText}
+ </div>
+ </div>
+ {providerMetrics.errors && providerMetrics.errors.length > 0 && (
+ <div>
+ <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>ERRORS</div>
+ <div style={{ color: '#ff0000', fontSize: '11px', fontWeight: 'bold' }}>
+ {providerMetrics.errors.length}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Show last error if connection failed */}
+ {hasError && providerMetrics?.errors && providerMetrics.errors.length > 0 && (
+ <div style={{
+ marginTop: '8px',
+ padding: '6px 8px',
+ background: '#3a0a0a',
+ border: '1px solid #ff0000',
+ borderRadius: '3px'
+ }}>
+ <div style={{ color: '#ff0000', fontSize: '8px', fontWeight: 'bold', marginBottom: '2px' }}>LAST ERROR:</div>
+ <div style={{ color: colors.textMuted, fontSize: '9px', fontFamily: 'monospace' }}>
+ {providerMetrics.errors[providerMetrics.errors.length - 1].error}
+ </div>
+ </div>
+ )}
+ </div>
+
+ <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
+ {isConnected ? (
+ <button
+ onClick={() => handleDisconnectProvider(provider.provider_name)}
+ style={{
+ background: 'transparent',
+ border: '1px solid #ff0000',
+ color: '#ff0000',
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold'
+ }}
+ >
+ DISCONNECT
+ </button>
+ ) : (
+ <button
+ onClick={() => handleConnectProvider(provider.provider_name)}
+ disabled={!provider.enabled}
+ style={{
+ background: 'transparent',
+ border: '1px solid #00ff00',
+ color: '#00ff00',
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: provider.enabled ? 'pointer' : 'not-allowed',
+ borderRadius: '3px',
+ fontWeight: 'bold',
+ opacity: provider.enabled ? 1 : 0.5
+ }}
+ >
+ CONNECT
+ </button>
+ )}
+
+ {isConnected && (
+ <button
+ onClick={() => handleTestProvider(provider.provider_name)}
+ style={{
+ background: 'transparent',
+ border: `1px solid ${colors.primary}`,
+ color: colors.primary,
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold'
+ }}
+ >
+ PING
+ </button>
+ )}
+
+ <button
+ onClick={async () => {
+ // Load provider data into form for editing
+ setSelectedProvider(provider.provider_name);
+ setProviderForm({
+ provider_name: provider.provider_name,
+ enabled: provider.enabled,
+ api_key: provider.api_key || '',
+ api_secret: provider.api_secret || '',
+ endpoint: provider.endpoint || ''
+ });
+ // Scroll to form
+ window.scrollTo({ top: 0, behavior: 'smooth' });
+ showMessage('success', `Editing ${provider.provider_name} configuration`);
+ }}
+ style={{
+ background: 'transparent',
+ border: `1px solid ${colors.primary}`,
+ color: colors.primary,
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ fontWeight: 'bold'
+ }}
+ >
+ <Edit3 size={10} />
+ EDIT
+ </button>
+
+ <button
+ onClick={() => handleToggleWSProvider(provider.provider_name)}
+ style={{
+ background: 'transparent',
+ border: `1px solid ${colors.textMuted}`,
+ color: colors.textMuted,
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold'
+ }}
+ >
+ {provider.enabled ? 'DISABLE' : 'ENABLE'}
+ </button>
+
+ <button
+ onClick={() => handleDeleteWSProvider(provider.provider_name)}
+ style={{
+ background: 'transparent',
+ border: '1px solid #ff0000',
+ color: '#ff0000',
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ fontWeight: 'bold'
+ }}
+ >
+ <Trash2 size={10} />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
{/* Other sections remain the same... */}
- {activeSection === 'profile' && <div style={{ color: '#888' }}>User Profile section (implementation same as before)</div>}
- {activeSection === 'terminal' && <div style={{ color: '#888' }}>Terminal Config section (implementation same as before)</div>}
- {activeSection === 'notifications' && <div style={{ color: '#888' }}>Notifications section (implementation same as before)</div>}
+ {activeSection === 'profile' && <div style={{ color: colors.textMuted }}>User Profile section (implementation same as before)</div>}
+ {activeSection === 'notifications' && <div style={{ color: colors.textMuted }}>Notifications section (implementation same as before)</div>}
</div>
</div>
@@ -940,9 +1878,9 @@ export default function SettingsTab() {
{/* Footer */}
<div style={{
- borderTop: '2px solid #ea580c',
+ borderTop: `2px solid ${colors.primary}`,
padding: '8px 16px',
- background: 'linear-gradient(180deg, #0a0a0a 0%, #1a1a1a 100%)',
+ background: `linear-gradient(180deg, ${colors.panel} 0%, #1a1a1a 100%)`,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
@@ -951,13 +1889,13 @@ export default function SettingsTab() {
gap: '12px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '9px' }}>
- <span style={{ color: '#ea580c', fontWeight: 'bold' }}>SETTINGS v2.0.0</span>
- <span style={{ color: '#666' }}>|</span>
- <span style={{ color: '#888' }}>Database: SQLite</span>
- <span style={{ color: '#666' }}>|</span>
- <span style={{ color: '#888' }}>Storage: File-based</span>
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>SETTINGS v2.0.0</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.textMuted }}>Database: SQLite</span>
+ <span style={{ color: colors.textMuted }}>|</span>
+ <span style={{ color: colors.textMuted }}>Storage: File-based</span>
</div>
- <div style={{ fontSize: '9px', color: '#666' }}>
+ <div style={{ fontSize: '9px', color: colors.textMuted }}>
All data stored securely in fincept_terminal.db
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx b/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx
index c0eebb80a..2b565c074 100644
--- a/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx
@@ -1,25 +1,25 @@
import React, { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { SupportApiService } from '@/services/supportApi';
-
-// Bloomberg Terminal Colors
-const C = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- RED: '#FF0000',
- GREEN: '#00C800',
- YELLOW: '#FFFF00',
- GRAY: '#787878',
- BLUE: '#6496FA',
- PURPLE: '#C864FF',
- CYAN: '#00FFFF',
- DARK_BG: '#000000',
- PANEL_BG: '#0a0a0a'
-};
+import { useTerminalTheme } from '@/contexts/ThemeContext';
type SupportView = 'list' | 'create' | 'details';
const SupportTicketTab: React.FC = () => {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
+ const C = {
+ ORANGE: colors.primary,
+ WHITE: colors.text,
+ RED: colors.alert,
+ GREEN: colors.secondary,
+ YELLOW: colors.warning,
+ GRAY: colors.textMuted,
+ BLUE: colors.info,
+ PURPLE: colors.purple,
+ CYAN: colors.accent,
+ DARK_BG: colors.background,
+ PANEL_BG: colors.panel
+ };
const { session } = useAuth();
const [currentView, setCurrentView] = useState<SupportView>('list');
const [loading, setLoading] = useState(false);
diff --git a/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx b/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx
index aca7eafc9..1128bb30f 100644
--- a/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx
@@ -10,9 +10,12 @@ import StockListView from './watchlist/StockListView';
import StockDetailPanel from './watchlist/StockDetailPanel';
import CreateWatchlistModal from './watchlist/CreateWatchlistModal';
import AddStockModal from './watchlist/AddStockModal';
-import { BLOOMBERG_COLORS, SortCriteria, sortStocks, getNextWatchlistColor } from './watchlist/utils';
+import { getBloombergColors, SortCriteria, sortStocks, getNextWatchlistColor } from './watchlist/utils';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
const WatchlistTab: React.FC = () => {
+ const { colors: themeColors } = useTerminalTheme();
+ const BLOOMBERG_COLORS = getBloombergColors();
const [currentTime, setCurrentTime] = useState(new Date());
const [watchlists, setWatchlists] = useState<Array<Watchlist & { stock_count: number }>>([]);
const [selectedWatchlist, setSelectedWatchlist] = useState<(Watchlist & { stock_count: number }) | null>(null);
diff --git a/fincept-terminal-desktop/src/components/tabs/docs/DocsTab.tsx b/fincept-terminal-desktop/src/components/tabs/docs/DocsTab.tsx
index 46fbc6786..8aa82d782 100644
--- a/fincept-terminal-desktop/src/components/tabs/docs/DocsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/docs/DocsTab.tsx
@@ -2,9 +2,12 @@ import React, { useState } from 'react';
import { Book, Search, Code, ChevronRight } from 'lucide-react';
import { DOC_SECTIONS } from './content';
import { DocSubsection } from './types';
-import { COLORS } from './constants';
+import { getColors } from './constants';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
export default function DocsTab() {
+ const { colors: themeColors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
+ const COLORS = getColors();
const [selectedSection, setSelectedSection] = useState('getting-started');
const [searchQuery, setSearchQuery] = useState('');
const [expandedSections, setExpandedSections] = useState<string[]>(['finscript']);
diff --git a/fincept-terminal-desktop/src/components/tabs/docs/constants.ts b/fincept-terminal-desktop/src/components/tabs/docs/constants.ts
index c988686c6..cfb82a2b0 100644
--- a/fincept-terminal-desktop/src/components/tabs/docs/constants.ts
+++ b/fincept-terminal-desktop/src/components/tabs/docs/constants.ts
@@ -1,12 +1,19 @@
-export const COLORS = {
- ORANGE: '#FF8C00',
- WHITE: '#FFFFFF',
- GREEN: '#00FF00',
- BLUE: '#4169E1',
- CYAN: '#00FFFF',
- YELLOW: '#FFFF00',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0a0a0a',
- CODE_BG: '#1a1a1a'
-} as const;
+import { terminalThemeService } from '@/services/terminalThemeService';
+
+export const getColors = () => {
+ const theme = terminalThemeService.getTheme();
+ return {
+ ORANGE: theme.colors.primary,
+ WHITE: theme.colors.text,
+ GREEN: theme.colors.secondary,
+ BLUE: theme.colors.info,
+ CYAN: theme.colors.accent,
+ YELLOW: theme.colors.warning,
+ GRAY: theme.colors.textMuted,
+ DARK_BG: theme.colors.background,
+ PANEL_BG: theme.colors.panel,
+ CODE_BG: '#1a1a1a'
+ };
+};
+
+export const COLORS = getColors();
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/utils.ts b/fincept-terminal-desktop/src/components/tabs/portfolio/utils.ts
index d7c4fcba5..ff452de7b 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio/utils.ts
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/utils.ts
@@ -1,20 +1,26 @@
// Portfolio Utility Functions
// Formatting, calculations, and helper functions
+import { terminalThemeService } from '@/services/terminalThemeService';
-export const BLOOMBERG_COLORS = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- RED: '#FF0000',
- GREEN: '#00C800',
- GRAY: '#787878',
- DARK_BG: '#1a1a1a',
- PANEL_BG: '#000000',
- CYAN: '#00FFFF',
- YELLOW: '#FFFF00',
- BLUE: '#6496FA',
- PURPLE: '#C864FF'
+export const getBloombergColors = () => {
+ const theme = terminalThemeService.getTheme();
+ return {
+ ORANGE: theme.colors.primary,
+ WHITE: theme.colors.text,
+ RED: theme.colors.alert,
+ GREEN: theme.colors.secondary,
+ GRAY: theme.colors.textMuted,
+ DARK_BG: '#1a1a1a',
+ PANEL_BG: theme.colors.background,
+ CYAN: theme.colors.accent,
+ YELLOW: theme.colors.warning,
+ BLUE: theme.colors.info,
+ PURPLE: theme.colors.purple
+ };
};
+export const BLOOMBERG_COLORS = getBloombergColors();
+
// Currency symbols and formatting
const CURRENCY_SYMBOLS: Record<string, string> = {
USD: '$',
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/utils.ts b/fincept-terminal-desktop/src/components/tabs/watchlist/utils.ts
index 3b43906b5..bf6d55993 100644
--- a/fincept-terminal-desktop/src/components/tabs/watchlist/utils.ts
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/utils.ts
@@ -1,20 +1,26 @@
// Watchlist Utilities - Shared constants, formatting, and helper functions
+import { terminalThemeService } from '@/services/terminalThemeService';
// Bloomberg Color Scheme
-export const BLOOMBERG_COLORS = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- RED: '#FF0000',
- GREEN: '#00C800',
- YELLOW: '#FFFF00',
- GRAY: '#787878',
- BLUE: '#6496FA',
- PURPLE: '#C864FF',
- CYAN: '#00FFFF',
- DARK_BG: '#000000',
- PANEL_BG: '#0a0a0a'
+export const getBloombergColors = () => {
+ const theme = terminalThemeService.getTheme();
+ return {
+ ORANGE: theme.colors.primary,
+ WHITE: theme.colors.text,
+ RED: theme.colors.alert,
+ GREEN: theme.colors.secondary,
+ YELLOW: theme.colors.warning,
+ GRAY: theme.colors.textMuted,
+ BLUE: theme.colors.info,
+ PURPLE: theme.colors.purple,
+ CYAN: theme.colors.accent,
+ DARK_BG: theme.colors.background,
+ PANEL_BG: theme.colors.panel
+ };
};
+export const BLOOMBERG_COLORS = getBloombergColors();
+
// Format currency values
export const formatCurrency = (value: number | undefined | null): string => {
if (value === undefined || value === null) return 'N/A';
diff --git a/fincept-terminal-desktop/src/contexts/ThemeContext.tsx b/fincept-terminal-desktop/src/contexts/ThemeContext.tsx
new file mode 100644
index 000000000..9d274f9e9
--- /dev/null
+++ b/fincept-terminal-desktop/src/contexts/ThemeContext.tsx
@@ -0,0 +1,64 @@
+import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
+import { terminalThemeService, TerminalTheme, FontSizes, ColorTheme } from '@/services/terminalThemeService';
+
+interface ThemeContextValue {
+ theme: TerminalTheme;
+ colors: ColorTheme;
+ fontSize: FontSizes;
+ fontFamily: string;
+ fontWeight: string;
+ fontStyle: string;
+ updateTheme: (theme: TerminalTheme) => void;
+ resetTheme: () => void;
+}
+
+const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
+
+export const ThemeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
+ const [theme, setTheme] = useState<TerminalTheme>(terminalThemeService.getTheme());
+
+ // Update theme
+ const updateTheme = (newTheme: TerminalTheme) => {
+ terminalThemeService.saveTheme(newTheme);
+ setTheme(newTheme);
+ };
+
+ // Reset theme to default
+ const resetTheme = () => {
+ terminalThemeService.resetToDefault();
+ setTheme(terminalThemeService.getTheme());
+ };
+
+ // Computed values
+ const colors = theme.colors;
+ const fontSize = terminalThemeService.getFontSizes();
+ const fontFamily = terminalThemeService.getFontFamily();
+ const fontWeight = terminalThemeService.getFontWeight();
+ const fontStyle = terminalThemeService.getFontStyle();
+
+ const value: ThemeContextValue = {
+ theme,
+ colors,
+ fontSize,
+ fontFamily,
+ fontWeight,
+ fontStyle,
+ updateTheme,
+ resetTheme
+ };
+
+ return (
+ <ThemeContext.Provider value={value}>
+ {children}
+ </ThemeContext.Provider>
+ );
+};
+
+// Custom hook to use theme
+export const useTerminalTheme = () => {
+ const context = useContext(ThemeContext);
+ if (!context) {
+ throw new Error('useTerminalTheme must be used within ThemeProvider');
+ }
+ return context;
+};
diff --git a/fincept-terminal-desktop/src/hooks/useWebSocket.ts b/fincept-terminal-desktop/src/hooks/useWebSocket.ts
new file mode 100644
index 000000000..6d09fe339
--- /dev/null
+++ b/fincept-terminal-desktop/src/hooks/useWebSocket.ts
@@ -0,0 +1,387 @@
+// File: src/hooks/useWebSocket.ts
+// React hook for WebSocket subscriptions
+
+import { useState, useEffect, useCallback, useRef } from 'react';
+import {
+ getWebSocketManager,
+ Subscription,
+ NormalizedMessage,
+ ConnectionStatus,
+ MessageCallback
+} from '@/services/websocket';
+
+/**
+ * Hook options
+ */
+export interface UseWebSocketOptions {
+ /**
+ * Auto-connect on mount (default: true)
+ */
+ autoConnect?: boolean;
+
+ /**
+ * Auto-subscribe on mount (default: true)
+ */
+ autoSubscribe?: boolean;
+
+ /**
+ * Optional subscription parameters
+ */
+ params?: Record<string, any>;
+
+ /**
+ * Custom error handler
+ */
+ onError?: (error: Error) => void;
+
+ /**
+ * Connection status change handler
+ */
+ onStatusChange?: (status: ConnectionStatus) => void;
+}
+
+/**
+ * Hook return value
+ */
+export interface UseWebSocketReturn {
+ /**
+ * Latest message received
+ */
+ message: NormalizedMessage | null;
+
+ /**
+ * All messages received (up to maxMessages)
+ */
+ messages: NormalizedMessage[];
+
+ /**
+ * Connection status
+ */
+ status: ConnectionStatus | null;
+
+ /**
+ * Loading state (connecting or subscribing)
+ */
+ isLoading: boolean;
+
+ /**
+ * Error state
+ */
+ error: Error | null;
+
+ /**
+ * Subscribe to topic manually
+ */
+ subscribe: (topic: string, params?: Record<string, any>) => Promise<void>;
+
+ /**
+ * Unsubscribe from current topic
+ */
+ unsubscribe: () => void;
+
+ /**
+ * Send message (for two-way communication if supported)
+ */
+ send: (data: any) => Promise<void>;
+
+ /**
+ * Reconnect to provider
+ */
+ reconnect: () => Promise<void>;
+
+ /**
+ * Clear message history
+ */
+ clearMessages: () => void;
+}
+
+/**
+ * useWebSocket - React hook for WebSocket subscriptions
+ *
+ * @param topic - Topic to subscribe to (format: "provider.channel.symbol")
+ * @param callback - Optional message callback (alternative to using message state)
+ * @param options - Hook options
+ *
+ * @example
+ * ```typescript
+ * // Simple usage with state
+ * const { message, status } = useWebSocket('kraken.ticker.BTC/USD');
+ *
+ * // With callback
+ * useWebSocket('kraken.ticker.BTC/USD', (msg) => {
+ * console.log('Price:', msg.data.last);
+ * });
+ *
+ * // Manual subscription control
+ * const { subscribe, unsubscribe, messages } = useWebSocket(
+ * 'kraken.ticker.BTC/USD',
+ * null,
+ * { autoSubscribe: false }
+ * );
+ * ```
+ */
+export function useWebSocket(
+ topic: string | null,
+ callback?: MessageCallback | null,
+ options: UseWebSocketOptions = {}
+): UseWebSocketReturn {
+ const {
+ autoConnect = true,
+ autoSubscribe = true,
+ params,
+ onError,
+ onStatusChange
+ } = options;
+
+ // State
+ const [message, setMessage] = useState<NormalizedMessage | null>(null);
+ const [messages, setMessages] = useState<NormalizedMessage[]>([]);
+ const [status, setStatus] = useState<ConnectionStatus | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<Error | null>(null);
+
+ // Refs
+ const subscriptionRef = useRef<Subscription | null>(null);
+ const callbackRef = useRef<MessageCallback | null>(callback || null);
+ const maxMessages = 100; // Keep last 100 messages
+
+ // Update callback ref when it changes
+ useEffect(() => {
+ callbackRef.current = callback || null;
+ }, [callback]);
+
+ /**
+ * Internal message handler
+ */
+ const handleMessage = useCallback((msg: NormalizedMessage) => {
+ setMessage(msg);
+ setMessages(prev => {
+ const updated = [...prev, msg];
+ return updated.slice(-maxMessages);
+ });
+
+ // Call user callback if provided
+ if (callbackRef.current) {
+ callbackRef.current(msg);
+ }
+ }, []);
+
+ /**
+ * Subscribe to topic
+ */
+ const subscribe = useCallback(async (
+ subscribeTopic: string,
+ subscribeParams?: Record<string, any>
+ ) => {
+ try {
+ setIsLoading(true);
+ setError(null);
+
+ const manager = getWebSocketManager();
+
+ // Parse provider from topic
+ const provider = subscribeTopic.split('.')[0];
+
+ // Get or create provider config if needed
+ // Note: Config should be set via setProviderConfig before subscribing
+ // This is handled in SettingsTab
+
+ // Subscribe
+ const sub = await manager.subscribe(
+ subscribeTopic,
+ handleMessage,
+ subscribeParams || params
+ );
+
+ subscriptionRef.current = sub;
+
+ // Update status
+ const providerStatus = manager.getStatus(provider);
+ setStatus(providerStatus);
+
+ if (onStatusChange && providerStatus) {
+ onStatusChange(providerStatus);
+ }
+ } catch (err) {
+ const error = err instanceof Error ? err : new Error(String(err));
+ setError(error);
+
+ if (onError) {
+ onError(error);
+ }
+
+ console.error('[useWebSocket] Subscribe error:', error);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [handleMessage, params, onError, onStatusChange]);
+
+ /**
+ * Unsubscribe
+ */
+ const unsubscribe = useCallback(() => {
+ if (subscriptionRef.current) {
+ subscriptionRef.current.unsubscribe();
+ subscriptionRef.current = null;
+ setStatus(ConnectionStatus.DISCONNECTED);
+ }
+ }, []);
+
+ /**
+ * Send message
+ */
+ const send = useCallback(async (data: any) => {
+ if (!topic) {
+ throw new Error('No topic specified');
+ }
+
+ const manager = getWebSocketManager();
+ const provider = topic.split('.')[0];
+ const adapter = (manager as any).registry.get(provider);
+
+ if (!adapter) {
+ throw new Error(`Provider ${provider} not connected`);
+ }
+
+ await adapter.send(data);
+ }, [topic]);
+
+ /**
+ * Reconnect
+ */
+ const reconnect = useCallback(async () => {
+ if (!topic) {
+ throw new Error('No topic specified');
+ }
+
+ try {
+ setIsLoading(true);
+ setError(null);
+
+ const manager = getWebSocketManager();
+ const provider = topic.split('.')[0];
+
+ await manager.reconnect(provider);
+
+ // Resubscribe
+ if (subscriptionRef.current) {
+ unsubscribe();
+ await subscribe(topic, params);
+ }
+ } catch (err) {
+ const error = err instanceof Error ? err : new Error(String(err));
+ setError(error);
+
+ if (onError) {
+ onError(error);
+ }
+ } finally {
+ setIsLoading(false);
+ }
+ }, [topic, params, onError, subscribe, unsubscribe]);
+
+ /**
+ * Clear messages
+ */
+ const clearMessages = useCallback(() => {
+ setMessages([]);
+ setMessage(null);
+ }, []);
+
+ /**
+ * Auto-subscribe on mount if enabled
+ */
+ useEffect(() => {
+ if (topic && autoSubscribe && autoConnect) {
+ subscribe(topic, params);
+ }
+
+ // Cleanup on unmount
+ return () => {
+ unsubscribe();
+ };
+ }, [topic, autoSubscribe, autoConnect]); // Intentionally limited dependencies
+
+ return {
+ message,
+ messages,
+ status,
+ isLoading,
+ error,
+ subscribe,
+ unsubscribe,
+ send,
+ reconnect,
+ clearMessages
+ };
+}
+
+/**
+ * useWebSocketManager - Hook for accessing WebSocketManager directly
+ */
+export function useWebSocketManager() {
+ const manager = getWebSocketManager();
+ const [stats, setStats] = useState(manager.getStats());
+
+ useEffect(() => {
+ // Update stats periodically
+ const interval = setInterval(() => {
+ setStats(manager.getStats());
+ }, 1000);
+
+ return () => clearInterval(interval);
+ }, [manager]);
+
+ return {
+ manager,
+ stats,
+ statuses: manager.getAllStatuses(),
+ metrics: manager.getAllMetrics()
+ };
+}
+
+/**
+ * useWebSocketConnection - Hook for managing provider connection
+ */
+export function useWebSocketConnection(provider: string) {
+ const manager = getWebSocketManager();
+ const [status, setStatus] = useState<ConnectionStatus | null>(
+ manager.getStatus(provider)
+ );
+ const [metrics, setMetrics] = useState(manager.getMetrics(provider));
+
+ useEffect(() => {
+ // Update status and metrics periodically
+ const interval = setInterval(() => {
+ setStatus(manager.getStatus(provider));
+ setMetrics(manager.getMetrics(provider));
+ }, 1000);
+
+ return () => clearInterval(interval);
+ }, [manager, provider]);
+
+ const connect = useCallback(async () => {
+ await manager.connect(provider);
+ }, [manager, provider]);
+
+ const disconnect = useCallback(async () => {
+ await manager.disconnect(provider);
+ }, [manager, provider]);
+
+ const reconnect = useCallback(async () => {
+ await manager.reconnect(provider);
+ }, [manager, provider]);
+
+ const ping = useCallback(async () => {
+ return manager.ping(provider);
+ }, [manager, provider]);
+
+ return {
+ status,
+ metrics,
+ connect,
+ disconnect,
+ reconnect,
+ ping
+ };
+}
diff --git a/fincept-terminal-desktop/src/services/bisDataService.ts b/fincept-terminal-desktop/src/services/bisDataService.ts
new file mode 100644
index 000000000..6484d1ec0
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/bisDataService.ts
@@ -0,0 +1,334 @@
+import { invoke } from '@tauri-apps/api/core';
+
+// Type definitions for BIS API responses
+export interface BISDataResponse {
+ success: boolean;
+ data?: any;
+ error?: string;
+ endpoint?: string;
+ timestamp?: string;
+}
+
+export interface BISEconomicOverview {
+ economic_overview: {
+ effective_exchange_rates?: BISDataResponse;
+ central_bank_policy_rates?: BISDataResponse;
+ long_term_interest_rates?: BISDataResponse;
+ short_term_interest_rates?: BISDataResponse;
+ exchange_rates?: BISDataResponse;
+ credit_to_non_financial_sector?: BISDataResponse;
+ };
+ countries: string[];
+ period: {
+ start: string;
+ end: string;
+ };
+ indicators_requested: number;
+ indicators_retrieved: number;
+}
+
+/**
+ * BIS Data Service
+ * Provides access to Bank for International Settlements data via Tauri commands
+ */
+class BISDataService {
+ /**
+ * Get comprehensive economic overview for countries
+ */
+ async getEconomicOverview(
+ countries?: string[],
+ startPeriod?: string,
+ endPeriod?: string
+ ): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('get_bis_economic_overview', {
+ countries: countries || null,
+ startPeriod: startPeriod || null,
+ endPeriod: endPeriod || null,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error fetching BIS economic overview:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Get central bank policy rates
+ */
+ async getCentralBankPolicyRates(
+ countries?: string[],
+ startPeriod?: string,
+ endPeriod?: string
+ ): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('get_bis_central_bank_policy_rates', {
+ countries: countries || null,
+ startPeriod: startPeriod || null,
+ endPeriod: endPeriod || null,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error fetching central bank policy rates:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Get effective exchange rates
+ */
+ async getEffectiveExchangeRates(
+ countries?: string[],
+ startPeriod?: string,
+ endPeriod?: string
+ ): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('get_bis_effective_exchange_rates', {
+ countries: countries || null,
+ startPeriod: startPeriod || null,
+ endPeriod: endPeriod || null,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error fetching effective exchange rates:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Get interest rates (long-term or short-term)
+ */
+ async getInterestRates(
+ type: 'long_term' | 'short_term',
+ countries?: string[],
+ startPeriod?: string,
+ endPeriod?: string
+ ): Promise<BISDataResponse> {
+ try {
+ const command = type === 'long_term'
+ ? 'get_bis_long_term_interest_rates'
+ : 'get_bis_short_term_interest_rates';
+
+ const response = await invoke<string>(command, {
+ countries: countries || null,
+ startPeriod: startPeriod || null,
+ endPeriod: endPeriod || null,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error(`Error fetching ${type} interest rates:`, error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Get exchange rates
+ */
+ async getExchangeRates(
+ currencies?: string[],
+ startPeriod?: string,
+ endPeriod?: string
+ ): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('get_bis_exchange_rates', {
+ currencyPairs: currencies || null,
+ startPeriod: startPeriod || null,
+ endPeriod: endPeriod || null,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error fetching exchange rates:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Get credit to non-financial sector
+ */
+ async getCreditToNonFinancialSector(
+ countries?: string[],
+ sectors?: string[],
+ startPeriod?: string,
+ endPeriod?: string
+ ): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('get_bis_credit_to_non_financial_sector', {
+ countries: countries || null,
+ sectors: sectors || null,
+ startPeriod: startPeriod || null,
+ endPeriod: endPeriod || null,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error fetching credit data:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Get house prices
+ */
+ async getHousePrices(
+ countries?: string[],
+ startPeriod?: string,
+ endPeriod?: string
+ ): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('get_bis_house_prices', {
+ countries: countries || null,
+ startPeriod: startPeriod || null,
+ endPeriod: endPeriod || null,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error fetching house prices:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Get available datasets
+ */
+ async getAvailableDatasets(): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('get_bis_available_datasets');
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error fetching available datasets:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Search datasets by query
+ */
+ async searchDatasets(query: string): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('search_bis_datasets', {
+ query,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error searching datasets:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Get raw data for a specific flow
+ */
+ async getData(
+ flow: string,
+ key?: string,
+ startPeriod?: string,
+ endPeriod?: string
+ ): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('get_bis_data', {
+ flow,
+ key: key || 'all',
+ startPeriod: startPeriod || null,
+ endPeriod: endPeriod || null,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error fetching BIS data:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Get dataset metadata
+ */
+ async getDatasetMetadata(flow: string): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('get_bis_dataset_metadata', {
+ flow,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error fetching dataset metadata:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Get monetary policy overview
+ */
+ async getMonetaryPolicyOverview(
+ countries?: string[],
+ startPeriod?: string,
+ endPeriod?: string
+ ): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('get_bis_monetary_policy_overview', {
+ countries: countries || null,
+ startPeriod: startPeriod || null,
+ endPeriod: endPeriod || null,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error fetching monetary policy overview:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * Execute custom BIS command
+ */
+ async executeCommand(command: string, args: string[]): Promise<BISDataResponse> {
+ try {
+ const response = await invoke<string>('execute_bis_command', {
+ command,
+ args,
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ console.error('Error executing BIS command:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+}
+
+// Export singleton instance
+export const bisDataService = new BISDataService();
+export default bisDataService;
diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.ts
index e1d87a99d..439a4e920 100644
--- a/fincept-terminal-desktop/src/services/sqliteService.ts
+++ b/fincept-terminal-desktop/src/services/sqliteService.ts
@@ -345,6 +345,21 @@ class SQLiteService {
)
`);
+ // WebSocket Provider Configurations table
+ await this.db.execute(`
+ CREATE TABLE IF NOT EXISTS ws_provider_configs (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ provider_name TEXT NOT NULL UNIQUE,
+ enabled INTEGER DEFAULT 1,
+ api_key TEXT,
+ api_secret TEXT,
+ endpoint TEXT,
+ config_data TEXT,
+ created_at TEXT DEFAULT (datetime('now')),
+ updated_at TEXT DEFAULT (datetime('now'))
+ )
+ `);
+
// Create indexes
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_credentials_service ON credentials(service_name)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_settings_category ON settings(category)`);
@@ -362,6 +377,7 @@ class SQLiteService {
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_portfolio_snapshots_date ON portfolio_snapshots(snapshot_date DESC)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_watchlist_stocks_watchlist ON watchlist_stocks(watchlist_id)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_watchlist_stocks_symbol ON watchlist_stocks(symbol)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_ws_providers_enabled ON ws_provider_configs(enabled)`);
}
private async seedDefaultSettings(): Promise<void> {
@@ -1210,6 +1226,173 @@ class SQLiteService {
`DELETE FROM market_data_cache WHERE datetime(cached_at) <= datetime('now', '-${maxAgeMinutes} minutes')`
);
}
+
+ // ==================== WEBSOCKET PROVIDER CONFIGS ====================
+
+ /**
+ * Save or update WebSocket provider configuration
+ */
+ async saveWSProviderConfig(config: {
+ provider_name: string;
+ enabled: boolean;
+ api_key?: string;
+ api_secret?: string;
+ endpoint?: string;
+ config_data?: string;
+ }): Promise<{ success: boolean; message: string; id?: number }> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ try {
+ // Check if exists
+ const existing = await this.db.select<Array<{ id: number }>>(
+ 'SELECT id FROM ws_provider_configs WHERE provider_name = $1',
+ [config.provider_name]
+ );
+
+ if (existing.length > 0) {
+ // Update
+ await this.db.execute(
+ `UPDATE ws_provider_configs SET enabled = $1, api_key = $2, api_secret = $3,
+ endpoint = $4, config_data = $5, updated_at = datetime('now') WHERE id = $6`,
+ [config.enabled ? 1 : 0, config.api_key || null, config.api_secret || null,
+ config.endpoint || null, config.config_data || null, existing[0].id]
+ );
+ return { success: true, message: 'Provider config updated successfully', id: existing[0].id };
+ } else {
+ // Insert
+ const result = await this.db.execute(
+ `INSERT INTO ws_provider_configs (provider_name, enabled, api_key, api_secret, endpoint, config_data)
+ VALUES ($1, $2, $3, $4, $5, $6)`,
+ [config.provider_name, config.enabled ? 1 : 0, config.api_key || null,
+ config.api_secret || null, config.endpoint || null, config.config_data || null]
+ );
+ return { success: true, message: 'Provider config saved successfully', id: result.lastInsertId || undefined };
+ }
+ } catch (error: any) {
+ return { success: false, message: error.message };
+ }
+ }
+
+ /**
+ * Get all WebSocket provider configurations
+ */
+ async getWSProviderConfigs(): Promise<Array<{
+ id: number;
+ provider_name: string;
+ enabled: boolean;
+ api_key: string | null;
+ api_secret: string | null;
+ endpoint: string | null;
+ config_data: string | null;
+ created_at: string;
+ updated_at: string;
+ }>> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const configs = await this.db.select<Array<any>>(
+ 'SELECT * FROM ws_provider_configs ORDER BY provider_name ASC'
+ );
+
+ return configs.map(c => ({
+ ...c,
+ enabled: c.enabled === 1
+ }));
+ }
+
+ /**
+ * Get WebSocket provider configuration by name
+ */
+ async getWSProviderConfig(providerName: string): Promise<{
+ id: number;
+ provider_name: string;
+ enabled: boolean;
+ api_key: string | null;
+ api_secret: string | null;
+ endpoint: string | null;
+ config_data: string | null;
+ created_at: string;
+ updated_at: string;
+ } | null> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const configs = await this.db.select<Array<any>>(
+ 'SELECT * FROM ws_provider_configs WHERE provider_name = $1',
+ [providerName]
+ );
+
+ if (configs.length === 0) return null;
+
+ return {
+ ...configs[0],
+ enabled: configs[0].enabled === 1
+ };
+ }
+
+ /**
+ * Get only enabled WebSocket provider configurations
+ */
+ async getEnabledWSProviderConfigs(): Promise<Array<{
+ id: number;
+ provider_name: string;
+ enabled: boolean;
+ api_key: string | null;
+ api_secret: string | null;
+ endpoint: string | null;
+ config_data: string | null;
+ created_at: string;
+ updated_at: string;
+ }>> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const configs = await this.db.select<Array<any>>(
+ 'SELECT * FROM ws_provider_configs WHERE enabled = 1 ORDER BY provider_name ASC'
+ );
+
+ return configs.map(c => ({
+ ...c,
+ enabled: true
+ }));
+ }
+
+ /**
+ * Toggle WebSocket provider enabled status
+ */
+ async toggleWSProviderEnabled(providerName: string): Promise<{ success: boolean; message: string; enabled: boolean }> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ try {
+ const config = await this.getWSProviderConfig(providerName);
+
+ if (!config) {
+ return { success: false, message: 'Provider not found', enabled: false };
+ }
+
+ const newEnabled = !config.enabled;
+
+ await this.db.execute(
+ `UPDATE ws_provider_configs SET enabled = $1, updated_at = datetime('now') WHERE provider_name = $2`,
+ [newEnabled ? 1 : 0, providerName]
+ );
+
+ return { success: true, message: `Provider ${newEnabled ? 'enabled' : 'disabled'} successfully`, enabled: newEnabled };
+ } catch (error: any) {
+ return { success: false, message: error.message, enabled: false };
+ }
+ }
+
+ /**
+ * Delete WebSocket provider configuration
+ */
+ async deleteWSProviderConfig(providerName: string): Promise<{ success: boolean; message: string }> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ try {
+ await this.db.execute('DELETE FROM ws_provider_configs WHERE provider_name = $1', [providerName]);
+ return { success: true, message: 'Provider config deleted successfully' };
+ } catch (error: any) {
+ return { success: false, message: error.message };
+ }
+ }
}
// Singleton instance
diff --git a/fincept-terminal-desktop/src/services/terminalThemeService.ts b/fincept-terminal-desktop/src/services/terminalThemeService.ts
new file mode 100644
index 000000000..33f523b73
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/terminalThemeService.ts
@@ -0,0 +1,252 @@
+// Terminal Theme Service
+// Manages terminal appearance settings: fonts, sizes, colors
+
+export interface FontSettings {
+ family: string;
+ baseSize: number;
+ weight: 'normal' | 'semibold' | 'bold';
+ italic: boolean;
+}
+
+export interface ColorTheme {
+ name: string;
+ primary: string; // Replaces BLOOMBERG_ORANGE
+ secondary: string; // Replaces BLOOMBERG_GREEN
+ alert: string; // Replaces BLOOMBERG_RED
+ warning: string; // BLOOMBERG_YELLOW
+ info: string; // BLOOMBERG_BLUE
+ accent: string; // BLOOMBERG_CYAN
+ purple: string; // BLOOMBERG_PURPLE
+ text: string; // BLOOMBERG_WHITE
+ textMuted: string; // BLOOMBERG_GRAY
+ background: string; // BLOOMBERG_DARK_BG
+ panel: string; // BLOOMBERG_PANEL_BG
+}
+
+export interface TerminalTheme {
+ font: FontSettings;
+ colors: ColorTheme;
+}
+
+export interface FontSizes {
+ heading: string; // H1
+ subheading: string; // H2
+ body: string; // Normal text
+ small: string; // Labels, metadata
+ tiny: string; // Very small text
+}
+
+// Predefined color themes
+export const COLOR_THEMES: Record<string, ColorTheme> = {
+ 'bloomberg-classic': {
+ name: 'Bloomberg Classic',
+ primary: '#FFA500',
+ secondary: '#00C800',
+ alert: '#FF0000',
+ warning: '#FFFF00',
+ info: '#6496FA',
+ accent: '#00FFFF',
+ purple: '#C864FF',
+ text: '#FFFFFF',
+ textMuted: '#787878',
+ background: '#000000',
+ panel: '#0a0a0a'
+ },
+ 'matrix-green': {
+ name: 'Matrix Green',
+ primary: '#00FF41',
+ secondary: '#008F11',
+ alert: '#FF0000',
+ warning: '#FFD700',
+ info: '#00D4AA',
+ accent: '#00FFAA',
+ purple: '#00FF88',
+ text: '#00FF41',
+ textMuted: '#005500',
+ background: '#000000',
+ panel: '#001100'
+ },
+ 'blue-terminal': {
+ name: 'Blue Terminal',
+ primary: '#00D4FF',
+ secondary: '#00FF88',
+ alert: '#FF6B6B',
+ warning: '#FFD93D',
+ info: '#6BCF7F',
+ accent: '#A0E7E5',
+ purple: '#B4A7FF',
+ text: '#E8F4F8',
+ textMuted: '#5A7C8C',
+ background: '#000814',
+ panel: '#001D3D'
+ },
+ 'amber-retro': {
+ name: 'Amber Retro',
+ primary: '#FFAA00',
+ secondary: '#00FF00',
+ alert: '#FF0000',
+ warning: '#FFCC00',
+ info: '#88CCFF',
+ accent: '#FFDD88',
+ purple: '#FF88CC',
+ text: '#FFBB33',
+ textMuted: '#886600',
+ background: '#000000',
+ panel: '#0a0600'
+ },
+ 'purple-neon': {
+ name: 'Purple Neon',
+ primary: '#C864FF',
+ secondary: '#00FFA3',
+ alert: '#FF4D6D',
+ warning: '#FFD23F',
+ info: '#64D2FF',
+ accent: '#FF6AC1',
+ purple: '#9B4FD8',
+ text: '#F0E6FF',
+ textMuted: '#8B7BA8',
+ background: '#0D0221',
+ panel: '#1A0B3C'
+ }
+};
+
+// Font family options
+export const FONT_FAMILIES = [
+ { value: 'Consolas', label: 'Consolas' },
+ { value: 'Courier New', label: 'Courier New' },
+ { value: 'Monaco', label: 'Monaco' },
+ { value: 'Fira Code', label: 'Fira Code' },
+ { value: 'JetBrains Mono', label: 'JetBrains Mono' },
+ { value: 'Source Code Pro', label: 'Source Code Pro' }
+];
+
+const STORAGE_KEY = 'terminal-theme-settings';
+
+class TerminalThemeService {
+ private theme: TerminalTheme;
+
+ constructor() {
+ this.theme = this.loadTheme();
+ }
+
+ // Load theme from localStorage or use defaults
+ private loadTheme(): TerminalTheme {
+ try {
+ const stored = localStorage.getItem(STORAGE_KEY);
+ if (stored) {
+ const parsed = JSON.parse(stored);
+ // Merge with defaults to handle missing properties
+ return {
+ font: {
+ family: parsed.font?.family || 'Consolas',
+ baseSize: parsed.font?.baseSize || 11,
+ weight: parsed.font?.weight || 'normal',
+ italic: parsed.font?.italic || false
+ },
+ colors: parsed.colors || COLOR_THEMES['bloomberg-classic']
+ };
+ }
+ } catch (error) {
+ console.error('Failed to load theme from localStorage:', error);
+ }
+
+ // Default theme
+ return {
+ font: {
+ family: 'Consolas',
+ baseSize: 11,
+ weight: 'normal',
+ italic: false
+ },
+ colors: COLOR_THEMES['bloomberg-classic']
+ };
+ }
+
+ // Save theme to localStorage
+ saveTheme(theme: TerminalTheme): void {
+ this.theme = theme;
+ try {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(theme));
+ } catch (error) {
+ console.error('Failed to save theme to localStorage:', error);
+ }
+ }
+
+ // Get current theme
+ getTheme(): TerminalTheme {
+ return this.theme;
+ }
+
+ // Update font settings
+ updateFont(font: Partial<FontSettings>): void {
+ this.theme.font = { ...this.theme.font, ...font };
+ this.saveTheme(this.theme);
+ }
+
+ // Update color theme
+ updateColors(themeKey: string): void {
+ if (COLOR_THEMES[themeKey]) {
+ this.theme.colors = COLOR_THEMES[themeKey];
+ this.saveTheme(this.theme);
+ }
+ }
+
+ // Get calculated font sizes based on base size
+ getFontSizes(): FontSizes {
+ const base = this.theme.font.baseSize;
+ return {
+ heading: `${base + 4}px`,
+ subheading: `${base + 2}px`,
+ body: `${base}px`,
+ small: `${base - 1}px`,
+ tiny: `${base - 2}px`
+ };
+ }
+
+ // Get font family with fallback
+ getFontFamily(): string {
+ return `${this.theme.font.family}, monospace`;
+ }
+
+ // Get font weight
+ getFontWeight(): string {
+ const weights = {
+ normal: '400',
+ semibold: '600',
+ bold: '700'
+ };
+ return weights[this.theme.font.weight];
+ }
+
+ // Get font style
+ getFontStyle(): string {
+ return this.theme.font.italic ? 'italic' : 'normal';
+ }
+
+ // Reset to defaults
+ resetToDefault(): void {
+ this.theme = {
+ font: {
+ family: 'Consolas',
+ baseSize: 11,
+ weight: 'normal',
+ italic: false
+ },
+ colors: COLOR_THEMES['bloomberg-classic']
+ };
+ this.saveTheme(this.theme);
+ }
+
+ // Get current color theme key
+ getCurrentThemeKey(): string {
+ const currentColors = this.theme.colors;
+ for (const [key, theme] of Object.entries(COLOR_THEMES)) {
+ if (theme.primary === currentColors.primary) {
+ return key;
+ }
+ }
+ return 'bloomberg-classic';
+ }
+}
+
+export const terminalThemeService = new TerminalThemeService();
diff --git a/fincept-terminal-desktop/src/services/websocket/EventBus.ts b/fincept-terminal-desktop/src/services/websocket/EventBus.ts
new file mode 100644
index 000000000..8e09d0564
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/websocket/EventBus.ts
@@ -0,0 +1,341 @@
+// File: src/services/websocket/EventBus.ts
+// Lightweight pub/sub event bus for distributing WebSocket messages
+
+import { EventBusEvent, MessageCallback, NormalizedMessage } from './types';
+
+/**
+ * Topic subscription metadata
+ */
+interface TopicSubscription {
+ id: string;
+ topic: string;
+ pattern: RegExp;
+ callback: MessageCallback;
+ subscribedAt: number;
+}
+
+/**
+ * EventBus - Centralized message distribution using pub/sub pattern
+ *
+ * Features:
+ * - Topic-based subscriptions with wildcard support
+ * - Memory-efficient using WeakMap where possible
+ * - Topic pattern matching (exact, wildcard, regex)
+ * - Message history (optional, for debugging)
+ * - Performance monitoring
+ */
+export class EventBus {
+ private subscriptions: Map<string, TopicSubscription[]> = new Map();
+ private messageHistory: EventBusEvent[] = [];
+ private maxHistorySize: number = 100;
+ private enableHistory: boolean = false;
+ private enableLogging: boolean = false;
+
+ // Performance metrics
+ private messageCount: number = 0;
+ private lastMessageTime: number = 0;
+ private messageRate: number = 0;
+
+ constructor(options?: {
+ enableHistory?: boolean;
+ maxHistorySize?: number;
+ enableLogging?: boolean;
+ }) {
+ this.enableHistory = options?.enableHistory ?? false;
+ this.maxHistorySize = options?.maxHistorySize ?? 100;
+ this.enableLogging = options?.enableLogging ?? false;
+
+ if (this.enableLogging) {
+ console.log('[EventBus] Initialized with history:', this.enableHistory);
+ }
+ }
+
+ /**
+ * Subscribe to a topic with optional wildcard support
+ *
+ * Examples:
+ * - "kraken.ticker.BTC/USD" - exact match
+ * - "kraken.ticker.*" - all tickers from Kraken
+ * - "kraken.*" - all messages from Kraken
+ * - "*.ticker.BTC/USD" - BTC/USD ticker from any provider
+ * - "*" - all messages (use sparingly)
+ *
+ * @returns Unsubscribe function
+ */
+ subscribe(topic: string, callback: MessageCallback): () => void {
+ const subscriptionId = this.generateSubscriptionId();
+ const pattern = this.topicToRegex(topic);
+
+ const subscription: TopicSubscription = {
+ id: subscriptionId,
+ topic,
+ pattern,
+ callback,
+ subscribedAt: Date.now()
+ };
+
+ // Store by exact topic for efficient lookup
+ const key = this.getSubscriptionKey(topic);
+ if (!this.subscriptions.has(key)) {
+ this.subscriptions.set(key, []);
+ }
+ this.subscriptions.get(key)!.push(subscription);
+
+ if (this.enableLogging) {
+ console.log(`[EventBus] Subscribed to topic: ${topic} (ID: ${subscriptionId})`);
+ }
+
+ // Return unsubscribe function
+ return () => this.unsubscribe(subscriptionId, topic);
+ }
+
+ /**
+ * Unsubscribe from a topic
+ */
+ private unsubscribe(subscriptionId: string, topic: string): void {
+ const key = this.getSubscriptionKey(topic);
+ const subs = this.subscriptions.get(key);
+
+ if (subs) {
+ const index = subs.findIndex(s => s.id === subscriptionId);
+ if (index !== -1) {
+ subs.splice(index, 1);
+
+ // Clean up empty subscription arrays
+ if (subs.length === 0) {
+ this.subscriptions.delete(key);
+ }
+
+ if (this.enableLogging) {
+ console.log(`[EventBus] Unsubscribed from topic: ${topic} (ID: ${subscriptionId})`);
+ }
+ }
+ }
+ }
+
+ /**
+ * Publish a message to all matching subscribers
+ */
+ publish(topic: string, message: NormalizedMessage): void {
+ const event: EventBusEvent = {
+ topic,
+ message,
+ timestamp: Date.now()
+ };
+
+ // Update metrics
+ this.updateMetrics();
+
+ // Add to history if enabled
+ if (this.enableHistory) {
+ this.addToHistory(event);
+ }
+
+ // Find all matching subscriptions
+ const matchingSubscriptions = this.findMatchingSubscriptions(topic);
+
+ if (this.enableLogging && matchingSubscriptions.length > 0) {
+ console.log(`[EventBus] Publishing to ${matchingSubscriptions.length} subscribers: ${topic}`);
+ }
+
+ // Deliver message to all matching subscribers
+ matchingSubscriptions.forEach(sub => {
+ try {
+ sub.callback(message);
+ } catch (error) {
+ console.error(`[EventBus] Error in subscription callback for ${topic}:`, error);
+ }
+ });
+ }
+
+ /**
+ * Find all subscriptions matching a topic
+ */
+ private findMatchingSubscriptions(topic: string): TopicSubscription[] {
+ const matches: TopicSubscription[] = [];
+
+ // Check all subscription patterns
+ this.subscriptions.forEach(subs => {
+ subs.forEach(sub => {
+ if (sub.pattern.test(topic)) {
+ matches.push(sub);
+ }
+ });
+ });
+
+ return matches;
+ }
+
+ /**
+ * Convert topic pattern to RegExp
+ * Supports wildcards: * (any segment), ** (any number of segments)
+ */
+ private topicToRegex(topic: string): RegExp {
+ // Escape special regex characters except *
+ const escaped = topic.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
+
+ // Replace wildcards
+ const pattern = escaped
+ .replace(/\\\*\\\*/g, '.*') // ** matches anything
+ .replace(/\\\*/g, '[^.]+'); // * matches one segment
+
+ return new RegExp(`^${pattern}$`);
+ }
+
+ /**
+ * Get subscription key for efficient storage
+ * Groups similar patterns together
+ */
+ private getSubscriptionKey(topic: string): string {
+ // Use the first non-wildcard segment as key
+ const parts = topic.split('.');
+ const firstPart = parts[0];
+ return firstPart === '*' ? '__wildcard__' : firstPart;
+ }
+
+ /**
+ * Generate unique subscription ID
+ */
+ private generateSubscriptionId(): string {
+ return `sub_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
+ }
+
+ /**
+ * Add event to message history
+ */
+ private addToHistory(event: EventBusEvent): void {
+ this.messageHistory.push(event);
+
+ // Trim history if it exceeds max size
+ if (this.messageHistory.length > this.maxHistorySize) {
+ this.messageHistory = this.messageHistory.slice(-this.maxHistorySize);
+ }
+ }
+
+ /**
+ * Update performance metrics
+ */
+ private updateMetrics(): void {
+ this.messageCount++;
+ const now = Date.now();
+
+ if (this.lastMessageTime > 0) {
+ const timeDiff = (now - this.lastMessageTime) / 1000; // seconds
+ this.messageRate = 1 / timeDiff;
+ }
+
+ this.lastMessageTime = now;
+ }
+
+ /**
+ * Get message history
+ */
+ getHistory(limit?: number): EventBusEvent[] {
+ if (!this.enableHistory) {
+ console.warn('[EventBus] History is disabled');
+ return [];
+ }
+
+ if (limit) {
+ return this.messageHistory.slice(-limit);
+ }
+
+ return [...this.messageHistory];
+ }
+
+ /**
+ * Get history for a specific topic
+ */
+ getHistoryForTopic(topic: string, limit?: number): EventBusEvent[] {
+ const pattern = this.topicToRegex(topic);
+ const matching = this.messageHistory.filter(event => pattern.test(event.topic));
+
+ if (limit) {
+ return matching.slice(-limit);
+ }
+
+ return matching;
+ }
+
+ /**
+ * Clear message history
+ */
+ clearHistory(): void {
+ this.messageHistory = [];
+ if (this.enableLogging) {
+ console.log('[EventBus] History cleared');
+ }
+ }
+
+ /**
+ * Get current subscription count
+ */
+ getSubscriptionCount(): number {
+ let count = 0;
+ this.subscriptions.forEach(subs => {
+ count += subs.length;
+ });
+ return count;
+ }
+
+ /**
+ * Get all active subscriptions
+ */
+ getSubscriptions(): Map<string, TopicSubscription[]> {
+ return new Map(this.subscriptions);
+ }
+
+ /**
+ * Get metrics
+ */
+ getMetrics() {
+ return {
+ totalMessages: this.messageCount,
+ messagesPerSecond: this.messageRate,
+ subscriptions: this.getSubscriptionCount(),
+ historySize: this.messageHistory.length,
+ lastMessageAt: this.lastMessageTime
+ };
+ }
+
+ /**
+ * Clear all subscriptions (useful for cleanup)
+ */
+ clear(): void {
+ this.subscriptions.clear();
+ this.clearHistory();
+ this.messageCount = 0;
+ this.lastMessageTime = 0;
+ this.messageRate = 0;
+
+ if (this.enableLogging) {
+ console.log('[EventBus] All subscriptions cleared');
+ }
+ }
+
+ /**
+ * Enable/disable logging at runtime
+ */
+ setLogging(enabled: boolean): void {
+ this.enableLogging = enabled;
+ }
+
+ /**
+ * Enable/disable history at runtime
+ */
+ setHistory(enabled: boolean, maxSize?: number): void {
+ this.enableHistory = enabled;
+ if (maxSize !== undefined) {
+ this.maxHistorySize = maxSize;
+ }
+ if (!enabled) {
+ this.clearHistory();
+ }
+ }
+}
+
+// Singleton instance for global use
+export const globalEventBus = new EventBus({
+ enableHistory: false,
+ enableLogging: false
+});
diff --git a/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts b/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts
new file mode 100644
index 000000000..542fe133c
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts
@@ -0,0 +1,444 @@
+// File: src/services/websocket/WebSocketManager.ts
+// Central WebSocket manager - orchestrates all WebSocket connections
+
+import {
+ IWebSocketAdapter,
+ ConnectionStatus,
+ ProviderConfig,
+ Subscription,
+ NormalizedMessage,
+ MessageCallback,
+ WebSocketManagerConfig,
+ DEFAULT_MANAGER_CONFIG,
+ parseTopic
+} from './types';
+import { EventBus, globalEventBus } from './EventBus';
+import { WebSocketRegistry } from './WebSocketRegistry';
+import { createAdapter, isProviderAvailable } from './adapters';
+import { generateId } from './utils';
+
+/**
+ * WebSocketManager - Central orchestrator for all WebSocket connections
+ *
+ * Features:
+ * - Automatic connection management
+ * - Connection pooling (single connection per provider)
+ * - Topic-based subscriptions with pub/sub
+ * - Metrics and health monitoring
+ * - Configuration management
+ *
+ * Usage:
+ * ```typescript
+ * const manager = new WebSocketManager();
+ *
+ * // Subscribe to a topic
+ * const subscription = await manager.subscribe('kraken.ticker.BTC/USD', (message) => {
+ * console.log('Price update:', message.data);
+ * });
+ *
+ * // Unsubscribe
+ * subscription.unsubscribe();
+ * ```
+ */
+export class WebSocketManager {
+ private eventBus: EventBus;
+ private registry: WebSocketRegistry;
+ private config: WebSocketManagerConfig;
+ private providerConfigs: Map<string, ProviderConfig> = new Map();
+
+ // Track subscriptions for cleanup
+ private activeSubscriptions: Map<string, Subscription> = new Map();
+
+ constructor(config?: Partial<WebSocketManagerConfig>) {
+ this.config = { ...DEFAULT_MANAGER_CONFIG, ...config };
+ this.eventBus = globalEventBus;
+ this.registry = new WebSocketRegistry(this.eventBus, {
+ enableLogging: this.config.enableLogging
+ });
+
+ // Configure event bus
+ this.eventBus.setLogging(this.config.enableLogging);
+ this.eventBus.setHistory(this.config.enableMetrics, 100);
+
+ this.log('WebSocketManager initialized');
+ }
+
+ /**
+ * Subscribe to a topic
+ * @param topic - Format: "provider.channel.symbol" e.g., "kraken.ticker.BTC/USD"
+ * @param callback - Message handler callback
+ * @param params - Optional subscription parameters
+ */
+ async subscribe(
+ topic: string,
+ callback: MessageCallback,
+ params?: Record<string, any>
+ ): Promise<Subscription> {
+ try {
+ const parsed = parseTopic(topic);
+ const { provider, channel, symbol } = parsed;
+
+ // Ensure adapter exists and is connected
+ await this.ensureConnection(provider);
+
+ // Get adapter
+ const adapter = this.registry.get(provider);
+ if (!adapter) {
+ throw new Error(`Adapter not found for provider: ${provider}`);
+ }
+
+ // Subscribe via adapter (only if not already subscribed)
+ const adapterTopic = symbol ? `${channel}.${symbol}` : channel;
+ const existingSubscriptions = adapter.getSubscriptions();
+
+ if (!existingSubscriptions.includes(adapterTopic)) {
+ await adapter.subscribe(adapterTopic, params);
+ }
+
+ // Create event bus subscription
+ const eventBusUnsubscribe = this.eventBus.subscribe(topic, callback);
+
+ // Track reference
+ this.registry.addRef(provider);
+
+ // Create subscription object
+ const subscriptionId = generateId('sub');
+ const subscription: Subscription = {
+ id: subscriptionId,
+ topic,
+ callback,
+ unsubscribe: () => this.unsubscribe(subscriptionId, topic, provider, adapterTopic, eventBusUnsubscribe)
+ };
+
+ this.activeSubscriptions.set(subscriptionId, subscription);
+
+ this.log(`Subscribed to: ${topic} (ID: ${subscriptionId})`);
+
+ return subscription;
+ } catch (error) {
+ console.error(`[WebSocketManager] Subscribe failed for ${topic}:`, error);
+ throw error;
+ }
+ }
+
+ /**
+ * Unsubscribe from a topic
+ */
+ private async unsubscribe(
+ subscriptionId: string,
+ topic: string,
+ provider: string,
+ adapterTopic: string,
+ eventBusUnsubscribe: () => void
+ ): Promise<void> {
+ try {
+ // Remove from active subscriptions first to avoid recursion
+ const subscription = this.activeSubscriptions.get(subscriptionId);
+ if (!subscription) {
+ return; // Already unsubscribed
+ }
+
+ this.activeSubscriptions.delete(subscriptionId);
+
+ // Unsubscribe from event bus
+ eventBusUnsubscribe();
+
+ // Release reference
+ this.registry.release(provider);
+
+ // Check if topic has other subscribers
+ const hasOtherSubscribers = Array.from(this.activeSubscriptions.values())
+ .some(sub => sub.topic === topic);
+
+ // Unsubscribe from adapter if no other subscribers
+ if (!hasOtherSubscribers) {
+ const adapter = this.registry.get(provider);
+ if (adapter) {
+ await adapter.unsubscribe(adapterTopic);
+ }
+ }
+
+ this.log(`Unsubscribed from: ${topic} (ID: ${subscriptionId})`);
+ } catch (error) {
+ console.error(`[WebSocketManager] Unsubscribe failed:`, error);
+ }
+ }
+
+ /**
+ * Ensure connection to provider exists and is healthy
+ */
+ private async ensureConnection(provider: string): Promise<void> {
+ // Check if adapter exists
+ if (!isProviderAvailable(provider)) {
+ throw new Error(`Provider not supported: ${provider}`);
+ }
+
+ // Check if already connected
+ if (this.registry.has(provider) && this.registry.isConnected(provider)) {
+ return;
+ }
+
+ // Get provider config
+ const config = this.providerConfigs.get(provider);
+ if (!config) {
+ throw new Error(`No configuration found for provider: ${provider}. Use setProviderConfig() first.`);
+ }
+
+ // Create adapter if doesn't exist
+ if (!this.registry.has(provider)) {
+ const adapter = createAdapter(provider);
+
+ // Setup message handler
+ adapter.onMessage((message: NormalizedMessage) => {
+ // Publish to event bus with full topic path
+ const fullTopic = this.buildFullTopic(message);
+ this.eventBus.publish(fullTopic, message);
+ });
+
+ // Setup error handler
+ adapter.onError((error) => {
+ this.log(`Error from ${provider}:`, error);
+ });
+
+ // Setup status change handler
+ adapter.onStatusChange((status) => {
+ this.log(`${provider} status changed to: ${status}`);
+ });
+
+ // Register adapter
+ this.registry.register(provider, adapter, config);
+ }
+
+ // Connect
+ const adapter = this.registry.get(provider);
+ if (adapter && adapter.status !== ConnectionStatus.CONNECTED) {
+ await adapter.connect(config);
+ }
+ }
+
+ /**
+ * Build full topic path from message
+ */
+ private buildFullTopic(message: NormalizedMessage): string {
+ const parts = [message.provider, message.channel];
+
+ if (message.symbol) {
+ parts.push(message.symbol);
+ }
+
+ return parts.join('.');
+ }
+
+ /**
+ * Set provider configuration
+ */
+ setProviderConfig(provider: string, config: ProviderConfig): void {
+ this.providerConfigs.set(provider, config);
+ this.log(`Configuration set for provider: ${provider}`);
+ }
+
+ /**
+ * Get provider configuration
+ */
+ getProviderConfig(provider: string): ProviderConfig | undefined {
+ return this.providerConfigs.get(provider);
+ }
+
+ /**
+ * Connect to a provider manually
+ */
+ async connect(provider: string): Promise<void> {
+ await this.ensureConnection(provider);
+ }
+
+ /**
+ * Disconnect from a provider
+ */
+ async disconnect(provider: string): Promise<void> {
+ if (this.registry.has(provider)) {
+ await this.registry.unregister(provider);
+ this.log(`Disconnected from provider: ${provider}`);
+ }
+ }
+
+ /**
+ * Get connection status for a provider
+ */
+ getStatus(provider: string): ConnectionStatus | null {
+ return this.registry.getStatus(provider);
+ }
+
+ /**
+ * Get all connection statuses
+ */
+ getAllStatuses(): Map<string, ConnectionStatus> {
+ return this.registry.getAllStatuses();
+ }
+
+ /**
+ * Get metrics for a provider
+ */
+ getMetrics(provider: string) {
+ return this.registry.getMetrics(provider);
+ }
+
+ /**
+ * Get all metrics
+ */
+ getAllMetrics() {
+ return this.registry.getAllMetrics();
+ }
+
+ /**
+ * Get registry statistics
+ */
+ getStats() {
+ return {
+ registry: this.registry.getStats(),
+ eventBus: this.eventBus.getMetrics(),
+ activeSubscriptions: this.activeSubscriptions.size,
+ configuredProviders: this.providerConfigs.size
+ };
+ }
+
+ /**
+ * Ping a provider
+ */
+ async ping(provider: string): Promise<number> {
+ const adapter = this.registry.get(provider);
+
+ if (!adapter) {
+ throw new Error(`Provider not connected: ${provider}`);
+ }
+
+ return adapter.ping();
+ }
+
+ /**
+ * Ping all connected providers
+ */
+ async pingAll(): Promise<Map<string, number>> {
+ return this.registry.pingAll();
+ }
+
+ /**
+ * Reconnect a provider
+ */
+ async reconnect(provider: string): Promise<void> {
+ await this.registry.reconnect(provider);
+ }
+
+ /**
+ * Reconnect all providers
+ */
+ async reconnectAll(): Promise<void> {
+ await this.registry.reconnectAll();
+ }
+
+ /**
+ * Get message history from event bus
+ */
+ getMessageHistory(topic?: string, limit?: number) {
+ if (topic) {
+ return this.eventBus.getHistoryForTopic(topic, limit);
+ }
+ return this.eventBus.getHistory(limit);
+ }
+
+ /**
+ * Clear message history
+ */
+ clearHistory(): void {
+ this.eventBus.clearHistory();
+ }
+
+ /**
+ * Get active subscriptions
+ */
+ getSubscriptions(): Subscription[] {
+ return Array.from(this.activeSubscriptions.values());
+ }
+
+ /**
+ * Get subscriptions for a specific provider
+ */
+ getProviderSubscriptions(provider: string): Subscription[] {
+ return Array.from(this.activeSubscriptions.values())
+ .filter(sub => sub.topic.startsWith(`${provider}.`));
+ }
+
+ /**
+ * Enable/disable logging
+ */
+ setLogging(enabled: boolean): void {
+ this.config.enableLogging = enabled;
+ this.eventBus.setLogging(enabled);
+ this.registry.setLogging(enabled);
+ }
+
+ /**
+ * Update configuration
+ */
+ updateConfig(config: Partial<WebSocketManagerConfig>): void {
+ this.config = { ...this.config, ...config };
+ }
+
+ /**
+ * Cleanup all resources
+ */
+ async destroy(): Promise<void> {
+ this.log('Destroying WebSocketManager...');
+
+ // Unsubscribe all
+ const subscriptionIds = Array.from(this.activeSubscriptions.keys());
+ for (const id of subscriptionIds) {
+ const sub = this.activeSubscriptions.get(id);
+ if (sub) {
+ sub.unsubscribe();
+ }
+ }
+
+ // Cleanup registry
+ await this.registry.destroy();
+
+ // Clear event bus
+ this.eventBus.clear();
+
+ this.log('WebSocketManager destroyed');
+ }
+
+ /**
+ * Log helper
+ */
+ private log(...args: any[]): void {
+ if (this.config.enableLogging) {
+ console.log('[WebSocketManager]', ...args);
+ }
+ }
+}
+
+// Global singleton instance
+let globalManagerInstance: WebSocketManager | null = null;
+
+/**
+ * Get global WebSocketManager instance (singleton)
+ */
+export function getWebSocketManager(): WebSocketManager {
+ if (!globalManagerInstance) {
+ globalManagerInstance = new WebSocketManager({
+ enableLogging: false,
+ enableMetrics: true
+ });
+ }
+ return globalManagerInstance;
+}
+
+/**
+ * Reset global instance (useful for testing)
+ */
+export function resetWebSocketManager(): void {
+ if (globalManagerInstance) {
+ globalManagerInstance.destroy();
+ globalManagerInstance = null;
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/websocket/WebSocketRegistry.ts b/fincept-terminal-desktop/src/services/websocket/WebSocketRegistry.ts
new file mode 100644
index 000000000..83cb48cb5
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/websocket/WebSocketRegistry.ts
@@ -0,0 +1,408 @@
+// File: src/services/websocket/WebSocketRegistry.ts
+// Connection registry for managing WebSocket adapter instances and lifecycle
+
+import {
+ IWebSocketAdapter,
+ ConnectionStatus,
+ ConnectionMetrics,
+ ProviderConfig
+} from './types';
+import { EventBus } from './EventBus';
+
+/**
+ * Registry entry for a WebSocket adapter
+ */
+interface RegistryEntry {
+ adapter: IWebSocketAdapter;
+ config: ProviderConfig;
+ createdAt: number;
+ refCount: number; // Track number of active subscribers
+}
+
+/**
+ * WebSocketRegistry - Manages lifecycle and pooling of WebSocket adapters
+ *
+ * Features:
+ * - Single instance per provider (connection pooling)
+ * - Reference counting for automatic cleanup
+ * - Health monitoring
+ * - Automatic reconnection
+ * - Connection metrics tracking
+ */
+export class WebSocketRegistry {
+ private registry: Map<string, RegistryEntry> = new Map();
+ private eventBus: EventBus;
+ private enableLogging: boolean = false;
+
+ // Cleanup settings
+ private cleanupIntervalMs: number = 60000; // 1 minute
+ private cleanupTimeoutMs: number = 300000; // 5 minutes of inactivity
+ private cleanupTimer: NodeJS.Timeout | null = null;
+
+ constructor(eventBus: EventBus, options?: {
+ enableLogging?: boolean;
+ cleanupIntervalMs?: number;
+ cleanupTimeoutMs?: number;
+ }) {
+ this.eventBus = eventBus;
+ this.enableLogging = options?.enableLogging ?? false;
+ this.cleanupIntervalMs = options?.cleanupIntervalMs ?? 60000;
+ this.cleanupTimeoutMs = options?.cleanupTimeoutMs ?? 300000;
+
+ this.startCleanupTimer();
+
+ if (this.enableLogging) {
+ console.log('[WebSocketRegistry] Initialized');
+ }
+ }
+
+ /**
+ * Register a new adapter instance
+ */
+ register(provider: string, adapter: IWebSocketAdapter, config: ProviderConfig): void {
+ if (this.registry.has(provider)) {
+ throw new Error(`Provider ${provider} is already registered`);
+ }
+
+ const entry: RegistryEntry = {
+ adapter,
+ config,
+ createdAt: Date.now(),
+ refCount: 0
+ };
+
+ this.registry.set(provider, entry);
+
+ if (this.enableLogging) {
+ console.log(`[WebSocketRegistry] Registered provider: ${provider}`);
+ }
+ }
+
+ /**
+ * Unregister an adapter and cleanup
+ */
+ async unregister(provider: string): Promise<void> {
+ const entry = this.registry.get(provider);
+
+ if (!entry) {
+ console.warn(`[WebSocketRegistry] Provider not found: ${provider}`);
+ return;
+ }
+
+ // Disconnect and cleanup
+ try {
+ await entry.adapter.disconnect();
+ entry.adapter.destroy();
+ } catch (error) {
+ console.error(`[WebSocketRegistry] Error cleaning up ${provider}:`, error);
+ }
+
+ this.registry.delete(provider);
+
+ if (this.enableLogging) {
+ console.log(`[WebSocketRegistry] Unregistered provider: ${provider}`);
+ }
+ }
+
+ /**
+ * Get adapter instance (creates if doesn't exist)
+ */
+ get(provider: string): IWebSocketAdapter | null {
+ const entry = this.registry.get(provider);
+ return entry ? entry.adapter : null;
+ }
+
+ /**
+ * Check if provider is registered
+ */
+ has(provider: string): boolean {
+ return this.registry.has(provider);
+ }
+
+ /**
+ * Get all registered providers
+ */
+ getProviders(): string[] {
+ return Array.from(this.registry.keys());
+ }
+
+ /**
+ * Increment reference count (track active subscribers)
+ */
+ addRef(provider: string): void {
+ const entry = this.registry.get(provider);
+ if (entry) {
+ entry.refCount++;
+
+ if (this.enableLogging) {
+ console.log(`[WebSocketRegistry] ${provider} refCount: ${entry.refCount}`);
+ }
+ }
+ }
+
+ /**
+ * Decrement reference count
+ */
+ release(provider: string): void {
+ const entry = this.registry.get(provider);
+ if (entry) {
+ entry.refCount = Math.max(0, entry.refCount - 1);
+
+ if (this.enableLogging) {
+ console.log(`[WebSocketRegistry] ${provider} refCount: ${entry.refCount}`);
+ }
+
+ // Schedule cleanup if no active references
+ if (entry.refCount === 0) {
+ this.scheduleCleanup(provider);
+ }
+ }
+ }
+
+ /**
+ * Get reference count for provider
+ */
+ getRefCount(provider: string): number {
+ const entry = this.registry.get(provider);
+ return entry ? entry.refCount : 0;
+ }
+
+ /**
+ * Get metrics for a provider
+ */
+ getMetrics(provider: string): ConnectionMetrics | null {
+ const entry = this.registry.get(provider);
+ return entry ? entry.adapter.metrics : null;
+ }
+
+ /**
+ * Get metrics for all providers
+ */
+ getAllMetrics(): Map<string, ConnectionMetrics> {
+ const metrics = new Map<string, ConnectionMetrics>();
+
+ this.registry.forEach((entry, provider) => {
+ metrics.set(provider, entry.adapter.metrics);
+ });
+
+ return metrics;
+ }
+
+ /**
+ * Get connection status for a provider
+ */
+ getStatus(provider: string): ConnectionStatus | null {
+ const entry = this.registry.get(provider);
+ return entry ? entry.adapter.status : null;
+ }
+
+ /**
+ * Check if provider is connected
+ */
+ isConnected(provider: string): boolean {
+ const status = this.getStatus(provider);
+ return status === ConnectionStatus.CONNECTED;
+ }
+
+ /**
+ * Get all connection statuses
+ */
+ getAllStatuses(): Map<string, ConnectionStatus> {
+ const statuses = new Map<string, ConnectionStatus>();
+
+ this.registry.forEach((entry, provider) => {
+ statuses.set(provider, entry.adapter.status);
+ });
+
+ return statuses;
+ }
+
+ /**
+ * Schedule cleanup for idle connections
+ */
+ private scheduleCleanup(provider: string): void {
+ // Don't cleanup if there are active references
+ const entry = this.registry.get(provider);
+ if (!entry || entry.refCount > 0) {
+ return;
+ }
+
+ // Cleanup will happen in the cleanup timer if still idle
+ }
+
+ /**
+ * Start periodic cleanup timer
+ */
+ private startCleanupTimer(): void {
+ this.cleanupTimer = setInterval(() => {
+ this.performCleanup();
+ }, this.cleanupIntervalMs);
+ }
+
+ /**
+ * Perform cleanup of idle connections
+ */
+ private async performCleanup(): Promise<void> {
+ const now = Date.now();
+ const toCleanup: string[] = [];
+
+ this.registry.forEach((entry, provider) => {
+ // Skip if has active references
+ if (entry.refCount > 0) {
+ return;
+ }
+
+ // Check if connection has been idle too long
+ const metrics = entry.adapter.metrics;
+ const lastActivity = metrics.lastMessageAt || entry.createdAt;
+ const idleTime = now - lastActivity;
+
+ if (idleTime > this.cleanupTimeoutMs) {
+ toCleanup.push(provider);
+ }
+ });
+
+ // Cleanup idle connections
+ for (const provider of toCleanup) {
+ if (this.enableLogging) {
+ console.log(`[WebSocketRegistry] Cleaning up idle connection: ${provider}`);
+ }
+ await this.unregister(provider);
+ }
+ }
+
+ /**
+ * Force cleanup of all connections
+ */
+ async cleanup(): Promise<void> {
+ const providers = this.getProviders();
+
+ for (const provider of providers) {
+ await this.unregister(provider);
+ }
+
+ if (this.cleanupTimer) {
+ clearInterval(this.cleanupTimer);
+ this.cleanupTimer = null;
+ }
+
+ if (this.enableLogging) {
+ console.log('[WebSocketRegistry] All connections cleaned up');
+ }
+ }
+
+ /**
+ * Get registry statistics
+ */
+ getStats() {
+ const stats = {
+ totalProviders: this.registry.size,
+ connectedProviders: 0,
+ totalSubscriptions: 0,
+ totalMessages: 0,
+ providers: new Map<string, {
+ status: ConnectionStatus;
+ refCount: number;
+ uptime: number;
+ subscriptions: number;
+ }>()
+ };
+
+ this.registry.forEach((entry, provider) => {
+ const metrics = entry.adapter.metrics;
+
+ if (entry.adapter.status === ConnectionStatus.CONNECTED) {
+ stats.connectedProviders++;
+ }
+
+ stats.totalSubscriptions += metrics.subscriptions;
+ stats.totalMessages += metrics.messagesReceived;
+
+ stats.providers.set(provider, {
+ status: entry.adapter.status,
+ refCount: entry.refCount,
+ uptime: metrics.uptime || 0,
+ subscriptions: metrics.subscriptions
+ });
+ });
+
+ return stats;
+ }
+
+ /**
+ * Reconnect a provider
+ */
+ async reconnect(provider: string): Promise<void> {
+ const entry = this.registry.get(provider);
+
+ if (!entry) {
+ throw new Error(`Provider not found: ${provider}`);
+ }
+
+ if (this.enableLogging) {
+ console.log(`[WebSocketRegistry] Reconnecting provider: ${provider}`);
+ }
+
+ try {
+ await entry.adapter.disconnect();
+ await entry.adapter.connect(entry.config);
+ } catch (error) {
+ console.error(`[WebSocketRegistry] Failed to reconnect ${provider}:`, error);
+ throw error;
+ }
+ }
+
+ /**
+ * Reconnect all providers
+ */
+ async reconnectAll(): Promise<void> {
+ const providers = this.getProviders();
+
+ for (const provider of providers) {
+ try {
+ await this.reconnect(provider);
+ } catch (error) {
+ console.error(`[WebSocketRegistry] Failed to reconnect ${provider}:`, error);
+ }
+ }
+ }
+
+ /**
+ * Ping all connected providers
+ */
+ async pingAll(): Promise<Map<string, number>> {
+ const results = new Map<string, number>();
+
+ for (const [provider, entry] of this.registry.entries()) {
+ if (entry.adapter.status === ConnectionStatus.CONNECTED) {
+ try {
+ const latency = await entry.adapter.ping();
+ results.set(provider, latency);
+ } catch (error) {
+ console.error(`[WebSocketRegistry] Ping failed for ${provider}:`, error);
+ results.set(provider, -1);
+ }
+ }
+ }
+
+ return results;
+ }
+
+ /**
+ * Enable/disable logging
+ */
+ setLogging(enabled: boolean): void {
+ this.enableLogging = enabled;
+ }
+
+ /**
+ * Destroy registry and cleanup all resources
+ */
+ async destroy(): Promise<void> {
+ await this.cleanup();
+
+ if (this.enableLogging) {
+ console.log('[WebSocketRegistry] Destroyed');
+ }
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/BaseAdapter.ts b/fincept-terminal-desktop/src/services/websocket/adapters/BaseAdapter.ts
new file mode 100644
index 000000000..8931ca9ce
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/websocket/adapters/BaseAdapter.ts
@@ -0,0 +1,544 @@
+// File: src/services/websocket/adapters/BaseAdapter.ts
+// Abstract base class for WebSocket adapters - provides common functionality
+
+import {
+ IWebSocketAdapter,
+ ConnectionStatus,
+ ConnectionMetrics,
+ ConnectionError,
+ ProviderConfig,
+ NormalizedMessage,
+ DEFAULT_RECONNECTION_POLICY,
+ DEFAULT_RATE_LIMIT
+} from '../types';
+import {
+ ReconnectionManager,
+ RateLimiter,
+ CircuitBreaker,
+ HeartbeatMonitor,
+ PerformanceMetrics,
+ generateId
+} from '../utils';
+
+/**
+ * Base WebSocket Adapter
+ * Provides common functionality for all provider adapters:
+ * - Connection management
+ * - Automatic reconnection
+ * - Rate limiting
+ * - Health monitoring
+ * - Error handling
+ * - Metrics collection
+ */
+export abstract class BaseAdapter implements IWebSocketAdapter {
+ abstract readonly provider: string;
+
+ protected ws: WebSocket | null = null;
+ protected _status: ConnectionStatus = ConnectionStatus.DISCONNECTED;
+ protected config: ProviderConfig | null = null;
+
+ // Utilities
+ protected reconnectionManager: ReconnectionManager;
+ protected rateLimiter: RateLimiter;
+ protected circuitBreaker: CircuitBreaker;
+ protected heartbeatMonitor: HeartbeatMonitor;
+ protected performanceMetrics: PerformanceMetrics;
+
+ // Callbacks
+ private messageCallbacks: Array<(message: NormalizedMessage) => void> = [];
+ private errorCallbacks: Array<(error: ConnectionError) => void> = [];
+ private statusCallbacks: Array<(status: ConnectionStatus) => void> = [];
+
+ // Subscriptions tracking
+ protected subscriptions: Set<string> = new Set();
+
+ // Metrics
+ protected _metrics: ConnectionMetrics;
+
+ // Logging
+ protected enableLogging: boolean = false;
+
+ constructor() {
+ // Initialize metrics with empty provider (will be set by getter)
+ this._metrics = {
+ provider: '',
+ status: ConnectionStatus.DISCONNECTED,
+ messagesReceived: 0,
+ messagesPerSecond: 0,
+ reconnectionAttempts: 0,
+ errors: [],
+ subscriptions: 0
+ };
+
+ this.reconnectionManager = new ReconnectionManager(DEFAULT_RECONNECTION_POLICY);
+ this.rateLimiter = new RateLimiter(DEFAULT_RATE_LIMIT);
+ this.circuitBreaker = new CircuitBreaker(5, 60000, 2);
+ this.heartbeatMonitor = new HeartbeatMonitor(30000, 60000);
+ this.performanceMetrics = new PerformanceMetrics();
+ }
+
+ /**
+ * Getter for current status
+ */
+ get status(): ConnectionStatus {
+ return this._status;
+ }
+
+ /**
+ * Getter for metrics
+ */
+ get metrics(): ConnectionMetrics {
+ const perfMetrics = this.performanceMetrics.getMetrics();
+
+ return {
+ ...this._metrics,
+ provider: this.provider,
+ status: this._status,
+ messagesReceived: perfMetrics.messageCount,
+ messagesPerSecond: perfMetrics.messagesPerSecond,
+ reconnectionAttempts: this.reconnectionManager.getAttempts(),
+ subscriptions: this.subscriptions.size
+ };
+ }
+
+ /**
+ * Connect to WebSocket
+ */
+ async connect(config: ProviderConfig): Promise<void> {
+ if (!this.circuitBreaker.isAllowed()) {
+ throw new Error(`Circuit breaker is open for ${this.provider}`);
+ }
+
+ this.config = config;
+ this.setStatus(ConnectionStatus.CONNECTING);
+
+ try {
+ const url = this.getWebSocketUrl(config);
+ this.ws = new WebSocket(url);
+
+ this.setupWebSocketHandlers();
+
+ // Wait for connection
+ await this.waitForConnection();
+
+ this.reconnectionManager.recordSuccess();
+ this.circuitBreaker.recordSuccess();
+ this.setStatus(ConnectionStatus.CONNECTED);
+ this._metrics.connectedAt = Date.now();
+
+ // Start heartbeat monitoring
+ this.heartbeatMonitor.start(() => this.handleStaleConnection());
+
+ // Perform provider-specific initialization
+ await this.onConnected();
+
+ this.log('Connected successfully');
+ } catch (error) {
+ this.circuitBreaker.recordFailure();
+ this.reconnectionManager.recordAttempt();
+
+ const errorObj: ConnectionError = {
+ timestamp: Date.now(),
+ error: error instanceof Error ? error.message : String(error)
+ };
+ this.addError(errorObj);
+ this.notifyError(errorObj);
+
+ this.setStatus(ConnectionStatus.ERROR);
+
+ // Attempt reconnection if policy allows
+ if (this.reconnectionManager.shouldAttempt()) {
+ await this.scheduleReconnection();
+ } else {
+ throw error;
+ }
+ }
+ }
+
+ /**
+ * Disconnect from WebSocket
+ */
+ async disconnect(): Promise<void> {
+ this.log('Disconnecting...');
+
+ this.heartbeatMonitor.stop();
+
+ if (this.ws) {
+ // Remove event listeners to prevent reconnection
+ this.ws.onclose = null;
+ this.ws.onerror = null;
+
+ if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
+ this.ws.close();
+ }
+
+ this.ws = null;
+ }
+
+ this.setStatus(ConnectionStatus.DISCONNECTED);
+ this.subscriptions.clear();
+
+ await this.onDisconnected();
+ }
+
+ /**
+ * Subscribe to a topic
+ */
+ async subscribe(topic: string, params?: Record<string, any>): Promise<void> {
+ if (this._status !== ConnectionStatus.CONNECTED) {
+ throw new Error(`Cannot subscribe: connection status is ${this._status}`);
+ }
+
+ // Check rate limit
+ if (!this.rateLimiter.tryConsume()) {
+ const waitTime = this.rateLimiter.getWaitTime();
+ this.log(`Rate limited, waiting ${waitTime}ms before subscribing to ${topic}`);
+ await new Promise(resolve => setTimeout(resolve, waitTime));
+ }
+
+ await this.performSubscribe(topic, params);
+ this.subscriptions.add(topic);
+
+ this.log(`Subscribed to: ${topic}`);
+ }
+
+ /**
+ * Unsubscribe from a topic
+ */
+ async unsubscribe(topic: string): Promise<void> {
+ if (this._status !== ConnectionStatus.CONNECTED) {
+ this.log(`Cannot unsubscribe: connection status is ${this._status}`);
+ return;
+ }
+
+ await this.performUnsubscribe(topic);
+ this.subscriptions.delete(topic);
+
+ this.log(`Unsubscribed from: ${topic}`);
+ }
+
+ /**
+ * Send raw message
+ */
+ async send(message: any): Promise<void> {
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
+ throw new Error('WebSocket is not connected');
+ }
+
+ const data = typeof message === 'string' ? message : JSON.stringify(message);
+ this.ws.send(data);
+ }
+
+ /**
+ * Ping/health check
+ */
+ async ping(): Promise<number> {
+ const start = Date.now();
+ await this.performPing();
+ const latency = Date.now() - start;
+
+ this._metrics.latency = latency;
+ this.performanceMetrics.recordLatency(latency);
+
+ return latency;
+ }
+
+ /**
+ * Get current subscriptions
+ */
+ getSubscriptions(): string[] {
+ return Array.from(this.subscriptions);
+ }
+
+ /**
+ * Register message callback
+ */
+ onMessage(callback: (message: NormalizedMessage) => void): void {
+ this.messageCallbacks.push(callback);
+ }
+
+ /**
+ * Register error callback
+ */
+ onError(callback: (error: ConnectionError) => void): void {
+ this.errorCallbacks.push(callback);
+ }
+
+ /**
+ * Register status change callback
+ */
+ onStatusChange(callback: (status: ConnectionStatus) => void): void {
+ this.statusCallbacks.push(callback);
+ }
+
+ /**
+ * Cleanup resources
+ */
+ destroy(): void {
+ this.heartbeatMonitor.stop();
+ this.messageCallbacks = [];
+ this.errorCallbacks = [];
+ this.statusCallbacks = [];
+ this.subscriptions.clear();
+ this.ws = null;
+ }
+
+ // ==================== Abstract Methods (Provider-Specific) ====================
+
+ /**
+ * Get WebSocket URL for provider
+ */
+ protected abstract getWebSocketUrl(config: ProviderConfig): string;
+
+ /**
+ * Handle incoming message (parse and normalize)
+ */
+ protected abstract handleMessage(event: MessageEvent): void;
+
+ /**
+ * Perform subscription (provider-specific)
+ */
+ protected abstract performSubscribe(topic: string, params?: Record<string, any>): Promise<void>;
+
+ /**
+ * Perform unsubscription (provider-specific)
+ */
+ protected abstract performUnsubscribe(topic: string): Promise<void>;
+
+ /**
+ * Perform ping (provider-specific)
+ */
+ protected abstract performPing(): Promise<void>;
+
+ /**
+ * Called after successful connection (optional hook)
+ */
+ protected async onConnected(): Promise<void> {
+ // Override in subclass if needed
+ }
+
+ /**
+ * Called after disconnection (optional hook)
+ */
+ protected async onDisconnected(): Promise<void> {
+ // Override in subclass if needed
+ }
+
+ // ==================== Protected Helper Methods ====================
+
+ /**
+ * Setup WebSocket event handlers
+ */
+ protected setupWebSocketHandlers(): void {
+ if (!this.ws) return;
+
+ this.ws.onopen = () => {
+ this.log('WebSocket connection opened');
+ };
+
+ this.ws.onmessage = (event: MessageEvent) => {
+ this.heartbeatMonitor.beat();
+ this._metrics.lastMessageAt = Date.now();
+ this.performanceMetrics.recordMessage(event.data?.length);
+
+ try {
+ this.handleMessage(event);
+ } catch (error) {
+ console.error(`[${this.provider}] Error handling message:`, error);
+ this.addError({
+ timestamp: Date.now(),
+ error: `Message handling error: ${error}`
+ });
+ }
+ };
+
+ this.ws.onerror = (event: Event) => {
+ this.log('WebSocket error', event);
+ this.addError({
+ timestamp: Date.now(),
+ error: 'WebSocket error occurred'
+ });
+ this.setStatus(ConnectionStatus.ERROR);
+ };
+
+ this.ws.onclose = (event: CloseEvent) => {
+ this.log(`WebSocket closed: ${event.code} - ${event.reason}`);
+
+ if (this._status !== ConnectionStatus.DISCONNECTED) {
+ // Unexpected close, attempt reconnection
+ this.handleUnexpectedClose(event);
+ }
+ };
+ }
+
+ /**
+ * Wait for WebSocket connection to open
+ */
+ protected waitForConnection(timeout: number = 10000): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (!this.ws) {
+ reject(new Error('WebSocket is null'));
+ return;
+ }
+
+ const timer = setTimeout(() => {
+ reject(new Error('Connection timeout'));
+ }, timeout);
+
+ this.ws.addEventListener('open', () => {
+ clearTimeout(timer);
+ resolve();
+ }, { once: true });
+
+ this.ws.addEventListener('error', (error) => {
+ clearTimeout(timer);
+ reject(error);
+ }, { once: true });
+ });
+ }
+
+ /**
+ * Handle unexpected connection close
+ */
+ protected async handleUnexpectedClose(event: CloseEvent): Promise<void> {
+ this.log(`Unexpected close: ${event.code} - ${event.reason}`);
+
+ if (this.reconnectionManager.shouldAttempt()) {
+ await this.scheduleReconnection();
+ } else {
+ this.setStatus(ConnectionStatus.ERROR);
+ this.addError({
+ timestamp: Date.now(),
+ error: 'Max reconnection attempts reached',
+ code: event.code
+ });
+ }
+ }
+
+ /**
+ * Schedule reconnection attempt
+ */
+ protected async scheduleReconnection(): Promise<void> {
+ const delay = this.reconnectionManager.getNextDelay();
+ this.setStatus(ConnectionStatus.RECONNECTING);
+
+ this.log(`Scheduling reconnection in ${delay}ms (attempt ${this.reconnectionManager.getAttempts() + 1})`);
+
+ await new Promise(resolve => setTimeout(resolve, delay));
+
+ if (this.config) {
+ try {
+ await this.connect(this.config);
+
+ // Resubscribe to previous topics
+ await this.resubscribe();
+ } catch (error) {
+ console.error(`[${this.provider}] Reconnection failed:`, error);
+ }
+ }
+ }
+
+ /**
+ * Resubscribe to all topics after reconnection
+ */
+ protected async resubscribe(): Promise<void> {
+ const topics = Array.from(this.subscriptions);
+ this.subscriptions.clear();
+
+ for (const topic of topics) {
+ try {
+ await this.subscribe(topic);
+ } catch (error) {
+ console.error(`[${this.provider}] Failed to resubscribe to ${topic}:`, error);
+ }
+ }
+ }
+
+ /**
+ * Handle stale connection (heartbeat timeout)
+ */
+ protected async handleStaleConnection(): Promise<void> {
+ this.log('Connection appears stale, forcing reconnect');
+
+ await this.disconnect();
+
+ if (this.config && this.reconnectionManager.shouldAttempt()) {
+ await this.connect(this.config);
+ }
+ }
+
+ /**
+ * Notify message to all callbacks
+ */
+ protected notifyMessage(message: NormalizedMessage): void {
+ this.messageCallbacks.forEach(callback => {
+ try {
+ callback(message);
+ } catch (error) {
+ console.error(`[${this.provider}] Error in message callback:`, error);
+ }
+ });
+ }
+
+ /**
+ * Notify error to all callbacks
+ */
+ protected notifyError(error: ConnectionError): void {
+ this.errorCallbacks.forEach(callback => {
+ try {
+ callback(error);
+ } catch (err) {
+ console.error(`[${this.provider}] Error in error callback:`, err);
+ }
+ });
+ }
+
+ /**
+ * Set connection status and notify listeners
+ */
+ protected setStatus(status: ConnectionStatus): void {
+ if (this._status !== status) {
+ this._status = status;
+ this._metrics.status = status;
+
+ this.statusCallbacks.forEach(callback => {
+ try {
+ callback(status);
+ } catch (error) {
+ console.error(`[${this.provider}] Error in status callback:`, error);
+ }
+ });
+
+ this.log(`Status changed to: ${status}`);
+ }
+ }
+
+ /**
+ * Add error to metrics
+ */
+ protected addError(error: ConnectionError): void {
+ this._metrics.errors.push(error);
+ this.performanceMetrics.recordError();
+
+ // Keep only last 50 errors
+ if (this._metrics.errors.length > 50) {
+ this._metrics.errors = this._metrics.errors.slice(-50);
+ }
+ }
+
+ /**
+ * Log message (if logging enabled)
+ */
+ protected log(...args: any[]): void {
+ if (this.enableLogging) {
+ console.log(`[${this.provider}]`, ...args);
+ }
+ }
+
+ /**
+ * Enable/disable logging
+ */
+ setLogging(enabled: boolean): void {
+ this.enableLogging = enabled;
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/KrakenAdapter.ts b/fincept-terminal-desktop/src/services/websocket/adapters/KrakenAdapter.ts
new file mode 100644
index 000000000..c770c37f0
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/websocket/adapters/KrakenAdapter.ts
@@ -0,0 +1,325 @@
+// File: src/services/websocket/adapters/KrakenAdapter.ts
+// Kraken WebSocket v2 API adapter
+// Documentation: https://docs.kraken.com/api/docs/websocket-v2
+
+import { BaseAdapter } from './BaseAdapter';
+import { ProviderConfig, NormalizedMessage } from '../types';
+
+/**
+ * Kraken WebSocket v2 message types
+ */
+interface KrakenMessage {
+ method?: string;
+ result?: any;
+ success?: boolean;
+ error?: string;
+ channel?: string;
+ type?: 'snapshot' | 'update';
+ data?: any[];
+ timestamp?: string;
+}
+
+/**
+ * KrakenAdapter - WebSocket v2 adapter for Kraken exchange
+ *
+ * Supported channels:
+ * - ticker: Real-time ticker updates (bid, ask, last, volume, vwap, high, low, change)
+ * - book: Level 2 order book (depth: 10, 25, 100, 500, 1000)
+ * - trade: Recent trades
+ * - ohlc: OHLC/candlestick data (intervals: 1, 5, 15, 30, 60, 240, 1440, 10080, 21600 minutes)
+ * - instrument: Reference data for assets and trading pairs
+ * - level3: Level 3 order book (requires authentication)
+ *
+ * Topic format: "channel.symbol" e.g., "ticker.BTC/USD"
+ */
+export class KrakenAdapter extends BaseAdapter {
+ readonly provider = 'kraken';
+
+ private readonly WS_URL = 'wss://ws.kraken.com/v2';
+ private readonly WS_AUTH_URL = 'wss://ws-auth.kraken.com/v2';
+
+ private reqIdCounter: number = 1;
+
+ /**
+ * Get WebSocket URL based on config
+ */
+ protected getWebSocketUrl(config: ProviderConfig): string {
+ // Use authenticated endpoint for level3 or if API key provided
+ return config.api_key ? this.WS_AUTH_URL : this.WS_URL;
+ }
+
+ /**
+ * Handle incoming messages from Kraken
+ */
+ protected handleMessage(event: MessageEvent): void {
+ try {
+ const message: KrakenMessage = JSON.parse(event.data);
+
+ this.log('Received message:', message);
+
+ // Handle different message types
+ if (message.method === 'pong') {
+ this.handlePong();
+ } else if (message.method === 'subscribe' || message.method === 'unsubscribe') {
+ this.handleSubscriptionResponse(message);
+ } else if (message.channel) {
+ this.handleChannelMessage(message);
+ } else if (message.error) {
+ this.handleErrorMessage(message);
+ }
+ } catch (error) {
+ console.error('[KrakenAdapter] Failed to parse message:', error);
+ }
+ }
+
+ /**
+ * Subscribe to a channel
+ * @param topic - Format: "channel.symbol" e.g., "ticker.BTC/USD"
+ * @param params - Optional parameters (depth, interval, event_trigger, snapshot, token)
+ */
+ protected async performSubscribe(topic: string, params?: Record<string, any>): Promise<void> {
+ const { channel, symbol } = this.parseTopic(topic);
+
+ const subscribeMessage: any = {
+ method: 'subscribe',
+ params: {
+ channel,
+ snapshot: params?.snapshot ?? true
+ },
+ req_id: this.getNextReqId()
+ };
+
+ // Add symbol array if provided
+ if (symbol) {
+ subscribeMessage.params.symbol = [symbol];
+ }
+
+ // Channel-specific parameters
+ if (channel === 'book' || channel === 'level3') {
+ // Depth: 10, 25, 100, 500, 1000 (default: 10)
+ subscribeMessage.params.depth = params?.depth ?? 10;
+ }
+
+ if (channel === 'ohlc') {
+ // Interval in minutes: 1, 5, 15, 30, 60, 240, 1440, 10080, 21600
+ subscribeMessage.params.interval = params?.interval ?? 1;
+ }
+
+ if (channel === 'ticker' && params?.event_trigger) {
+ // Event trigger: 'bbo' or 'trades'
+ subscribeMessage.params.event_trigger = params.event_trigger;
+ }
+
+ if (channel === 'level3' && this.config?.api_key) {
+ // Authentication token for level3
+ subscribeMessage.params.token = this.config.api_key;
+ }
+
+ if (channel === 'instrument' && params?.include_tokenized_assets !== undefined) {
+ subscribeMessage.params.include_tokenized_assets = params.include_tokenized_assets;
+ }
+
+ await this.send(subscribeMessage);
+ this.log(`Subscribed to ${channel}${symbol ? ` for ${symbol}` : ''}`);
+ }
+
+ /**
+ * Unsubscribe from a channel
+ */
+ protected async performUnsubscribe(topic: string): Promise<void> {
+ const { channel, symbol } = this.parseTopic(topic);
+
+ const unsubscribeMessage: any = {
+ method: 'unsubscribe',
+ params: {
+ channel
+ },
+ req_id: this.getNextReqId()
+ };
+
+ if (symbol) {
+ unsubscribeMessage.params.symbol = [symbol];
+ }
+
+ await this.send(unsubscribeMessage);
+ this.log(`Sent unsubscription request for ${topic}`);
+ }
+
+ /**
+ * Perform ping
+ */
+ protected async performPing(): Promise<void> {
+ const pingMessage = {
+ method: 'ping',
+ req_id: this.getNextReqId()
+ };
+
+ await this.send(pingMessage);
+ }
+
+ /**
+ * Called after successful connection
+ */
+ protected async onConnected(): Promise<void> {
+ this.log('WebSocket connected successfully');
+ }
+
+ /**
+ * Handle channel data messages
+ */
+ private handleChannelMessage(message: KrakenMessage): void {
+ if (!message.channel || !message.data) {
+ return;
+ }
+
+ // Normalize message based on channel type
+ const normalizedMessages = this.normalizeMessage(message);
+
+ // Emit each normalized message
+ normalizedMessages.forEach(msg => {
+ this.notifyMessage(msg);
+ });
+ }
+
+ /**
+ * Normalize Kraken v2 message to standard format
+ */
+ private normalizeMessage(message: KrakenMessage): NormalizedMessage[] {
+ const normalized: NormalizedMessage[] = [];
+
+ if (!message.data || message.data.length === 0) {
+ return normalized;
+ }
+
+ const channel = message.channel || 'unknown';
+ const messageType = message.type || 'update';
+
+ message.data.forEach((dataItem: any) => {
+ let type: NormalizedMessage['type'] = 'custom';
+ const symbol = dataItem.symbol;
+
+ // Map channel to normalized type
+ switch (channel) {
+ case 'ticker':
+ type = 'ticker';
+ break;
+ case 'trade':
+ type = 'trade';
+ break;
+ case 'ohlc':
+ type = 'candle';
+ break;
+ case 'book':
+ case 'level3':
+ type = 'orderbook';
+ break;
+ case 'instrument':
+ type = 'status';
+ break;
+ default:
+ type = 'custom';
+ }
+
+ normalized.push({
+ provider: this.provider,
+ channel,
+ type,
+ symbol,
+ timestamp: message.timestamp ? new Date(message.timestamp).getTime() : Date.now(),
+ data: {
+ ...dataItem,
+ messageType // 'snapshot' or 'update'
+ },
+ raw: message
+ });
+ });
+
+ return normalized;
+ }
+
+ /**
+ * Handle subscription response
+ */
+ private handleSubscriptionResponse(message: KrakenMessage): void {
+ if (message.success) {
+ this.log('Subscription successful:', message);
+ } else if (message.error) {
+ console.error('[KrakenAdapter] Subscription error:', message.error);
+ this.addError({
+ timestamp: Date.now(),
+ error: message.error
+ });
+ }
+ }
+
+ /**
+ * Handle error messages
+ */
+ private handleErrorMessage(message: KrakenMessage): void {
+ const error = {
+ timestamp: Date.now(),
+ error: message.error || 'Unknown error'
+ };
+
+ this.addError(error);
+ this.notifyError(error);
+ this.log('Error message:', message.error);
+ }
+
+ /**
+ * Handle pong response
+ */
+ private handlePong(): void {
+ this.log('Received pong');
+ }
+
+ /**
+ * Parse topic into channel and symbol
+ */
+ private parseTopic(topic: string): { channel: string; symbol?: string } {
+ const parts = topic.split('.');
+
+ if (parts.length === 1) {
+ // Just channel, no symbol
+ return { channel: parts[0] };
+ } else {
+ // channel.symbol format
+ return {
+ channel: parts[0],
+ symbol: parts.slice(1).join('.')
+ };
+ }
+ }
+
+ /**
+ * Get next request ID
+ */
+ private getNextReqId(): number {
+ return this.reqIdCounter++;
+ }
+}
+
+/**
+ * Kraken WebSocket v2 Usage Examples:
+ *
+ * Ticker (bid, ask, last, volume, vwap, high, low, change):
+ * subscribe('ticker.BTC/USD')
+ * subscribe('ticker.ETH/USD', { event_trigger: 'bbo' })
+ *
+ * Order Book Level 2 (depth: 10, 25, 100, 500, 1000):
+ * subscribe('book.BTC/USD', { depth: 10 })
+ * subscribe('book.ETH/USD', { depth: 100, snapshot: true })
+ *
+ * Trades:
+ * subscribe('trade.BTC/USD')
+ *
+ * OHLC Candles (intervals: 1, 5, 15, 30, 60, 240, 1440, 10080, 21600 minutes):
+ * subscribe('ohlc.BTC/USD', { interval: 1 })
+ * subscribe('ohlc.ETH/USD', { interval: 60 })
+ *
+ * Instrument Reference Data:
+ * subscribe('instrument', { include_tokenized_assets: false })
+ *
+ * Level 3 Order Book (requires authentication):
+ * subscribe('level3.BTC/USD', { depth: 10 })
+ */
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/index.ts b/fincept-terminal-desktop/src/services/websocket/adapters/index.ts
new file mode 100644
index 000000000..8d3b94933
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/websocket/adapters/index.ts
@@ -0,0 +1,50 @@
+// File: src/services/websocket/adapters/index.ts
+// Export all adapters and adapter registry
+
+import { AdapterRegistry, IWebSocketAdapter } from '../types';
+import { BaseAdapter } from './BaseAdapter';
+import { KrakenAdapter } from './KrakenAdapter';
+
+/**
+ * Global registry of available WebSocket adapters
+ * Add new adapters here as they are implemented
+ */
+export const adapters: AdapterRegistry = {
+ kraken: KrakenAdapter,
+ // Add more adapters here:
+ // fyers: FyersAdapter,
+ // polygon: PolygonAdapter,
+ // binance: BinanceAdapter,
+ // etc.
+};
+
+/**
+ * Get list of available provider names
+ */
+export function getAvailableProviders(): string[] {
+ return Object.keys(adapters);
+}
+
+/**
+ * Check if provider is available
+ */
+export function isProviderAvailable(provider: string): boolean {
+ return provider in adapters;
+}
+
+/**
+ * Create adapter instance for a provider
+ */
+export function createAdapter(provider: string): IWebSocketAdapter {
+ const AdapterClass = adapters[provider];
+
+ if (!AdapterClass) {
+ throw new Error(`Adapter not found for provider: ${provider}`);
+ }
+
+ return new AdapterClass();
+}
+
+// Export adapter classes
+export { BaseAdapter } from './BaseAdapter';
+export { KrakenAdapter } from './KrakenAdapter';
diff --git a/fincept-terminal-desktop/src/services/websocket/index.ts b/fincept-terminal-desktop/src/services/websocket/index.ts
new file mode 100644
index 000000000..47b42a4fe
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/websocket/index.ts
@@ -0,0 +1,110 @@
+// File: src/services/websocket/index.ts
+// Main entry point for WebSocket management system
+
+// Core Manager
+export { WebSocketManager, getWebSocketManager, resetWebSocketManager } from './WebSocketManager';
+
+// Event Bus
+export { EventBus, globalEventBus } from './EventBus';
+
+// Registry
+export { WebSocketRegistry } from './WebSocketRegistry';
+
+// Types
+export type {
+ IWebSocketAdapter,
+ ConnectionMetrics,
+ ConnectionError,
+ ProviderConfig,
+ NormalizedMessage,
+ Subscription,
+ SubscriptionTopic,
+ MessageCallback,
+ RateLimitConfig,
+ ReconnectionPolicy,
+ WebSocketManagerConfig,
+ EventBusEvent,
+ AdapterRegistry,
+ HealthCheckResult,
+ ParsedTopic,
+ QueuedMessage
+} from './types';
+
+export {
+ ConnectionStatus, // enum (both type and value)
+ DEFAULT_RATE_LIMIT,
+ DEFAULT_RECONNECTION_POLICY,
+ DEFAULT_MANAGER_CONFIG,
+ parseTopic,
+ buildTopic
+} from './types';
+
+// Utilities
+export {
+ ReconnectionManager,
+ RateLimiter,
+ CircuitBreaker,
+ MessageThrottler,
+ HeartbeatMonitor,
+ PerformanceMetrics,
+ retryWithBackoff,
+ generateId,
+ safeJsonParse,
+ debounce
+} from './utils';
+
+// Adapters
+export { BaseAdapter } from './adapters/BaseAdapter';
+export { KrakenAdapter } from './adapters/KrakenAdapter';
+export {
+ adapters,
+ getAvailableProviders,
+ isProviderAvailable,
+ createAdapter
+} from './adapters';
+
+/**
+ * Quick start guide:
+ *
+ * 1. Set up provider configuration:
+ * ```typescript
+ * import { getWebSocketManager } from '@/services/websocket';
+ *
+ * const manager = getWebSocketManager();
+ *
+ * manager.setProviderConfig('kraken', {
+ * provider_name: 'kraken',
+ * enabled: true,
+ * endpoint: 'wss://ws.kraken.com/v2'
+ * });
+ * ```
+ *
+ * 2. Subscribe to topics:
+ * ```typescript
+ * const subscription = await manager.subscribe(
+ * 'kraken.ticker.BTC/USD',
+ * (message) => {
+ * console.log('Price update:', message.data);
+ * }
+ * );
+ * ```
+ *
+ * 3. Use in React components:
+ * ```typescript
+ * import { useWebSocket } from '@/hooks/useWebSocket';
+ *
+ * function PriceDisplay() {
+ * const { message, status } = useWebSocket('kraken.ticker.BTC/USD');
+ *
+ * return (
+ * <div>
+ * <p>Status: {status}</p>
+ * <p>Price: {message?.data.last}</p>
+ * </div>
+ * );
+ * }
+ * ```
+ *
+ * 4. Monitor connections in Settings:
+ * See useWebSocketManager hook in hooks/useWebSocket.ts for connection monitoring
+ */
diff --git a/fincept-terminal-desktop/src/services/websocket/types.ts b/fincept-terminal-desktop/src/services/websocket/types.ts
new file mode 100644
index 000000000..3e012db49
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/websocket/types.ts
@@ -0,0 +1,313 @@
+// File: src/services/websocket/types.ts
+// Core TypeScript types and interfaces for WebSocket management system
+
+/**
+ * Connection status for WebSocket providers
+ */
+export enum ConnectionStatus {
+ DISCONNECTED = 'disconnected',
+ CONNECTING = 'connecting',
+ CONNECTED = 'connected',
+ RECONNECTING = 'reconnecting',
+ ERROR = 'error',
+ RATE_LIMITED = 'rate_limited'
+}
+
+/**
+ * Standard message format across all providers
+ * Providers normalize their messages to this format
+ */
+export interface NormalizedMessage {
+ provider: string;
+ channel: string;
+ type: 'ticker' | 'trade' | 'orderbook' | 'candle' | 'status' | 'error' | 'custom';
+ symbol?: string;
+ timestamp: number;
+ data: any;
+ raw?: any; // Original message for debugging
+}
+
+/**
+ * Subscription topic structure
+ * Example: "kraken.ticker.BTC/USD" or "fyers.orderbook.NSE:RELIANCE-EQ"
+ */
+export interface SubscriptionTopic {
+ provider: string;
+ channel: string;
+ symbol?: string;
+ params?: Record<string, any>;
+}
+
+/**
+ * Callback function for message subscriptions
+ */
+export type MessageCallback = (message: NormalizedMessage) => void;
+
+/**
+ * Subscription handle returned to subscribers
+ */
+export interface Subscription {
+ id: string;
+ topic: string;
+ callback: MessageCallback;
+ unsubscribe: () => void;
+}
+
+/**
+ * Provider configuration stored in SQLite
+ */
+export interface ProviderConfig {
+ id?: number;
+ provider_name: string;
+ enabled: boolean;
+ api_key?: string | null;
+ api_secret?: string | null;
+ endpoint?: string | null;
+ config_data?: string | null; // JSON string for additional config
+ created_at?: string;
+ updated_at?: string;
+}
+
+/**
+ * Connection health metrics
+ */
+export interface ConnectionMetrics {
+ provider: string;
+ status: ConnectionStatus;
+ connectedAt?: number;
+ lastMessageAt?: number;
+ uptime?: number; // milliseconds
+ latency?: number; // milliseconds
+ messagesReceived: number;
+ messagesPerSecond: number;
+ reconnectionAttempts: number;
+ errors: ConnectionError[];
+ subscriptions: number;
+}
+
+/**
+ * Connection error tracking
+ */
+export interface ConnectionError {
+ timestamp: number;
+ error: string;
+ code?: string | number;
+ details?: any;
+}
+
+/**
+ * Rate limiting configuration
+ */
+export interface RateLimitConfig {
+ maxMessagesPerSecond: number;
+ maxSubscriptions: number;
+ throttleMs: number;
+ enabled: boolean;
+}
+
+/**
+ * Reconnection policy configuration
+ */
+export interface ReconnectionPolicy {
+ enabled: boolean;
+ maxAttempts: number;
+ initialDelayMs: number;
+ maxDelayMs: number;
+ backoffMultiplier: number;
+ resetAfterMs: number; // Reset attempt counter after successful connection
+}
+
+/**
+ * Abstract WebSocket adapter interface
+ * All provider adapters must implement this
+ */
+export interface IWebSocketAdapter {
+ readonly provider: string;
+ readonly status: ConnectionStatus;
+ readonly metrics: ConnectionMetrics;
+
+ /**
+ * Initialize connection with provider-specific config
+ */
+ connect(config: ProviderConfig): Promise<void>;
+
+ /**
+ * Gracefully disconnect
+ */
+ disconnect(): Promise<void>;
+
+ /**
+ * Subscribe to a channel/topic
+ * @param topic - Topic string (e.g., "ticker.BTC/USD")
+ * @param params - Additional subscription parameters
+ */
+ subscribe(topic: string, params?: Record<string, any>): Promise<void>;
+
+ /**
+ * Unsubscribe from a channel/topic
+ */
+ unsubscribe(topic: string): Promise<void>;
+
+ /**
+ * Send raw message to provider (for advanced use)
+ */
+ send(message: any): Promise<void>;
+
+ /**
+ * Register message handler
+ */
+ onMessage(callback: (message: NormalizedMessage) => void): void;
+
+ /**
+ * Register error handler
+ */
+ onError(callback: (error: ConnectionError) => void): void;
+
+ /**
+ * Register status change handler
+ */
+ onStatusChange(callback: (status: ConnectionStatus) => void): void;
+
+ /**
+ * Ping/health check
+ */
+ ping(): Promise<number>; // Returns latency in ms
+
+ /**
+ * Get current subscriptions
+ */
+ getSubscriptions(): string[];
+
+ /**
+ * Cleanup resources
+ */
+ destroy(): void;
+}
+
+/**
+ * WebSocket Manager configuration
+ */
+export interface WebSocketManagerConfig {
+ maxConnectionsPerProvider: number;
+ globalRateLimit: RateLimitConfig;
+ defaultReconnectionPolicy: ReconnectionPolicy;
+ enableMetrics: boolean;
+ enableLogging: boolean;
+ logLevel: 'debug' | 'info' | 'warn' | 'error';
+}
+
+/**
+ * Event bus event structure
+ */
+export interface EventBusEvent {
+ topic: string;
+ message: NormalizedMessage;
+ timestamp: number;
+}
+
+/**
+ * Provider adapter constructor signature
+ */
+export type AdapterConstructor = new () => IWebSocketAdapter;
+
+/**
+ * Registry of available adapters
+ */
+export interface AdapterRegistry {
+ [provider: string]: AdapterConstructor;
+}
+
+/**
+ * Health check result
+ */
+export interface HealthCheckResult {
+ provider: string;
+ healthy: boolean;
+ latency?: number;
+ error?: string;
+ timestamp: number;
+}
+
+/**
+ * Topic parser result
+ */
+export interface ParsedTopic {
+ provider: string;
+ channel: string;
+ symbol?: string;
+ params?: Record<string, any>;
+ raw: string;
+}
+
+/**
+ * Message queue item for backpressure handling
+ */
+export interface QueuedMessage {
+ message: NormalizedMessage;
+ timestamp: number;
+ retries: number;
+}
+
+/**
+ * Default configurations
+ */
+export const DEFAULT_RATE_LIMIT: RateLimitConfig = {
+ maxMessagesPerSecond: 100,
+ maxSubscriptions: 50,
+ throttleMs: 10,
+ enabled: true
+};
+
+export const DEFAULT_RECONNECTION_POLICY: ReconnectionPolicy = {
+ enabled: true,
+ maxAttempts: 10,
+ initialDelayMs: 1000,
+ maxDelayMs: 30000,
+ backoffMultiplier: 2,
+ resetAfterMs: 60000
+};
+
+export const DEFAULT_MANAGER_CONFIG: WebSocketManagerConfig = {
+ maxConnectionsPerProvider: 10,
+ globalRateLimit: DEFAULT_RATE_LIMIT,
+ defaultReconnectionPolicy: DEFAULT_RECONNECTION_POLICY,
+ enableMetrics: true,
+ enableLogging: true,
+ logLevel: 'info'
+};
+
+/**
+ * Topic format: "provider.channel.symbol"
+ * Examples:
+ * - "kraken.ticker.BTC/USD"
+ * - "fyers.orderbook.NSE:RELIANCE-EQ"
+ * - "polygon.trades.AAPL"
+ * - "binance.candles.BTCUSDT.1m"
+ */
+export function parseTopic(topic: string): ParsedTopic {
+ const parts = topic.split('.');
+
+ if (parts.length < 2) {
+ throw new Error(`Invalid topic format: ${topic}. Expected "provider.channel[.symbol]"`);
+ }
+
+ const [provider, channel, symbol, ...paramParts] = parts;
+
+ return {
+ provider,
+ channel,
+ symbol,
+ params: paramParts.length > 0 ? { extra: paramParts.join('.') } : undefined,
+ raw: topic
+ };
+}
+
+/**
+ * Build topic string from components
+ */
+export function buildTopic(provider: string, channel: string, symbol?: string, params?: string[]): string {
+ const parts = [provider, channel];
+ if (symbol) parts.push(symbol);
+ if (params && params.length > 0) parts.push(...params);
+ return parts.join('.');
+}
diff --git a/fincept-terminal-desktop/src/services/websocket/utils.ts b/fincept-terminal-desktop/src/services/websocket/utils.ts
new file mode 100644
index 000000000..bf13fc102
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/websocket/utils.ts
@@ -0,0 +1,621 @@
+// File: src/services/websocket/utils.ts
+// Utility functions for WebSocket management (reconnection, rate limiting, etc.)
+
+import { ReconnectionPolicy, RateLimitConfig } from './types';
+
+/**
+ * Exponential backoff calculator for reconnection delays
+ */
+export class ReconnectionManager {
+ private attempts: number = 0;
+ private lastAttemptTime: number = 0;
+ private lastSuccessTime: number = 0;
+ private policy: ReconnectionPolicy;
+
+ constructor(policy: ReconnectionPolicy) {
+ this.policy = policy;
+ }
+
+ /**
+ * Calculate next reconnection delay using exponential backoff
+ */
+ getNextDelay(): number {
+ if (!this.policy.enabled) {
+ return 0;
+ }
+
+ // Reset attempts if enough time has passed since last success
+ if (
+ this.lastSuccessTime > 0 &&
+ Date.now() - this.lastSuccessTime > this.policy.resetAfterMs
+ ) {
+ this.reset();
+ }
+
+ const delay = Math.min(
+ this.policy.initialDelayMs * Math.pow(this.policy.backoffMultiplier, this.attempts),
+ this.policy.maxDelayMs
+ );
+
+ return delay;
+ }
+
+ /**
+ * Record a reconnection attempt
+ */
+ recordAttempt(): void {
+ this.attempts++;
+ this.lastAttemptTime = Date.now();
+ }
+
+ /**
+ * Record successful connection
+ */
+ recordSuccess(): void {
+ this.lastSuccessTime = Date.now();
+ this.reset();
+ }
+
+ /**
+ * Check if should attempt reconnection
+ */
+ shouldAttempt(): boolean {
+ return this.policy.enabled && this.attempts < this.policy.maxAttempts;
+ }
+
+ /**
+ * Get current attempt count
+ */
+ getAttempts(): number {
+ return this.attempts;
+ }
+
+ /**
+ * Reset attempt counter
+ */
+ reset(): void {
+ this.attempts = 0;
+ }
+
+ /**
+ * Update policy at runtime
+ */
+ updatePolicy(policy: Partial<ReconnectionPolicy>): void {
+ this.policy = { ...this.policy, ...policy };
+ }
+}
+
+/**
+ * Rate limiter using token bucket algorithm
+ */
+export class RateLimiter {
+ private tokens: number;
+ private maxTokens: number;
+ private refillRate: number; // tokens per second
+ private lastRefill: number;
+ private config: RateLimitConfig;
+ private messageQueue: Array<() => void> = [];
+
+ constructor(config: RateLimitConfig) {
+ this.config = config;
+ this.maxTokens = config.maxMessagesPerSecond;
+ this.tokens = this.maxTokens;
+ this.refillRate = config.maxMessagesPerSecond;
+ this.lastRefill = Date.now();
+ }
+
+ /**
+ * Check if action is allowed (consumes token if available)
+ */
+ tryConsume(): boolean {
+ if (!this.config.enabled) {
+ return true;
+ }
+
+ this.refill();
+
+ if (this.tokens >= 1) {
+ this.tokens -= 1;
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Refill tokens based on time elapsed
+ */
+ private refill(): void {
+ const now = Date.now();
+ const timePassed = (now - this.lastRefill) / 1000; // seconds
+ const tokensToAdd = timePassed * this.refillRate;
+
+ this.tokens = Math.min(this.maxTokens, this.tokens + tokensToAdd);
+ this.lastRefill = now;
+ }
+
+ /**
+ * Wait for available token (returns delay in ms)
+ */
+ getWaitTime(): number {
+ if (!this.config.enabled) {
+ return 0;
+ }
+
+ this.refill();
+
+ if (this.tokens >= 1) {
+ return 0;
+ }
+
+ // Calculate time until next token is available
+ const tokensNeeded = 1 - this.tokens;
+ const waitTime = (tokensNeeded / this.refillRate) * 1000;
+
+ return Math.max(waitTime, this.config.throttleMs);
+ }
+
+ /**
+ * Execute action with rate limiting
+ */
+ async execute<T>(action: () => Promise<T>): Promise<T> {
+ if (!this.config.enabled) {
+ return action();
+ }
+
+ const waitTime = this.getWaitTime();
+
+ if (waitTime > 0) {
+ await this.sleep(waitTime);
+ }
+
+ this.tryConsume();
+ return action();
+ }
+
+ /**
+ * Queue action for later execution when tokens available
+ */
+ queue(action: () => void): void {
+ this.messageQueue.push(action);
+ this.processQueue();
+ }
+
+ /**
+ * Process queued actions
+ */
+ private async processQueue(): Promise<void> {
+ while (this.messageQueue.length > 0) {
+ if (this.tryConsume()) {
+ const action = this.messageQueue.shift();
+ if (action) {
+ try {
+ action();
+ } catch (error) {
+ console.error('[RateLimiter] Error executing queued action:', error);
+ }
+ }
+ } else {
+ // Wait for next token
+ const waitTime = this.getWaitTime();
+ await this.sleep(waitTime);
+ }
+ }
+ }
+
+ /**
+ * Get current token count
+ */
+ getAvailableTokens(): number {
+ this.refill();
+ return Math.floor(this.tokens);
+ }
+
+ /**
+ * Reset rate limiter
+ */
+ reset(): void {
+ this.tokens = this.maxTokens;
+ this.lastRefill = Date.now();
+ this.messageQueue = [];
+ }
+
+ /**
+ * Update configuration at runtime
+ */
+ updateConfig(config: Partial<RateLimitConfig>): void {
+ this.config = { ...this.config, ...config };
+ this.maxTokens = this.config.maxMessagesPerSecond;
+ this.refillRate = this.config.maxMessagesPerSecond;
+ }
+
+ private sleep(ms: number): Promise<void> {
+ return new Promise(resolve => setTimeout(resolve, ms));
+ }
+}
+
+/**
+ * Circuit breaker for handling repeated failures
+ */
+export class CircuitBreaker {
+ private failures: number = 0;
+ private lastFailureTime: number = 0;
+ private state: 'closed' | 'open' | 'half-open' = 'closed';
+ private successCount: number = 0;
+
+ constructor(
+ private failureThreshold: number = 5,
+ private timeout: number = 60000, // 1 minute
+ private successThreshold: number = 2
+ ) {}
+
+ /**
+ * Record successful operation
+ */
+ recordSuccess(): void {
+ this.failures = 0;
+ this.lastFailureTime = 0;
+
+ if (this.state === 'half-open') {
+ this.successCount++;
+ if (this.successCount >= this.successThreshold) {
+ this.state = 'closed';
+ this.successCount = 0;
+ }
+ }
+ }
+
+ /**
+ * Record failed operation
+ */
+ recordFailure(): void {
+ this.failures++;
+ this.lastFailureTime = Date.now();
+
+ if (this.failures >= this.failureThreshold) {
+ this.state = 'open';
+ }
+
+ if (this.state === 'half-open') {
+ this.state = 'open';
+ this.successCount = 0;
+ }
+ }
+
+ /**
+ * Check if operation is allowed
+ */
+ isAllowed(): boolean {
+ if (this.state === 'closed') {
+ return true;
+ }
+
+ if (this.state === 'open') {
+ // Check if timeout has passed
+ if (Date.now() - this.lastFailureTime >= this.timeout) {
+ this.state = 'half-open';
+ this.successCount = 0;
+ return true;
+ }
+ return false;
+ }
+
+ // half-open state
+ return true;
+ }
+
+ /**
+ * Get current state
+ */
+ getState(): 'closed' | 'open' | 'half-open' {
+ return this.state;
+ }
+
+ /**
+ * Reset circuit breaker
+ */
+ reset(): void {
+ this.failures = 0;
+ this.lastFailureTime = 0;
+ this.state = 'closed';
+ this.successCount = 0;
+ }
+}
+
+/**
+ * Message throttler for preventing UI overload
+ */
+export class MessageThrottler {
+ private lastExecutionTime: number = 0;
+ private pendingMessage: any = null;
+ private timeoutId: NodeJS.Timeout | null = null;
+
+ constructor(private throttleMs: number = 100) {}
+
+ /**
+ * Throttle message delivery
+ */
+ throttle<T>(message: T, callback: (message: T) => void): void {
+ const now = Date.now();
+ const timeSinceLastExecution = now - this.lastExecutionTime;
+
+ if (timeSinceLastExecution >= this.throttleMs) {
+ // Execute immediately
+ callback(message);
+ this.lastExecutionTime = now;
+ this.pendingMessage = null;
+
+ // Clear any pending timeout
+ if (this.timeoutId) {
+ clearTimeout(this.timeoutId);
+ this.timeoutId = null;
+ }
+ } else {
+ // Store message and schedule execution
+ this.pendingMessage = message;
+
+ if (!this.timeoutId) {
+ const delay = this.throttleMs - timeSinceLastExecution;
+ this.timeoutId = setTimeout(() => {
+ if (this.pendingMessage) {
+ callback(this.pendingMessage);
+ this.lastExecutionTime = Date.now();
+ this.pendingMessage = null;
+ }
+ this.timeoutId = null;
+ }, delay);
+ }
+ }
+ }
+
+ /**
+ * Flush any pending message immediately
+ */
+ flush<T>(callback: (message: T) => void): void {
+ if (this.pendingMessage) {
+ callback(this.pendingMessage);
+ this.pendingMessage = null;
+ this.lastExecutionTime = Date.now();
+ }
+
+ if (this.timeoutId) {
+ clearTimeout(this.timeoutId);
+ this.timeoutId = null;
+ }
+ }
+
+ /**
+ * Clear throttler
+ */
+ clear(): void {
+ this.pendingMessage = null;
+ if (this.timeoutId) {
+ clearTimeout(this.timeoutId);
+ this.timeoutId = null;
+ }
+ }
+}
+
+/**
+ * Heartbeat monitor for detecting stale connections
+ */
+export class HeartbeatMonitor {
+ private lastHeartbeat: number = Date.now();
+ private timeoutId: NodeJS.Timeout | null = null;
+ private onTimeout?: () => void;
+
+ constructor(
+ private intervalMs: number = 30000, // 30 seconds
+ private timeoutMs: number = 60000 // 1 minute
+ ) {}
+
+ /**
+ * Start heartbeat monitoring
+ */
+ start(onTimeout: () => void): void {
+ this.onTimeout = onTimeout;
+ this.lastHeartbeat = Date.now();
+ this.scheduleCheck();
+ }
+
+ /**
+ * Record heartbeat (call this when receiving messages)
+ */
+ beat(): void {
+ this.lastHeartbeat = Date.now();
+ }
+
+ /**
+ * Stop monitoring
+ */
+ stop(): void {
+ if (this.timeoutId) {
+ clearTimeout(this.timeoutId);
+ this.timeoutId = null;
+ }
+ this.onTimeout = undefined;
+ }
+
+ /**
+ * Schedule next heartbeat check
+ */
+ private scheduleCheck(): void {
+ if (this.timeoutId) {
+ clearTimeout(this.timeoutId);
+ }
+
+ this.timeoutId = setTimeout(() => {
+ const timeSinceLastBeat = Date.now() - this.lastHeartbeat;
+
+ if (timeSinceLastBeat > this.timeoutMs) {
+ // Connection appears stale
+ if (this.onTimeout) {
+ this.onTimeout();
+ }
+ } else {
+ // Schedule next check
+ this.scheduleCheck();
+ }
+ }, this.intervalMs);
+ }
+
+ /**
+ * Get time since last heartbeat
+ */
+ getTimeSinceLastBeat(): number {
+ return Date.now() - this.lastHeartbeat;
+ }
+
+ /**
+ * Check if connection appears healthy
+ */
+ isHealthy(): boolean {
+ return this.getTimeSinceLastBeat() < this.timeoutMs;
+ }
+}
+
+/**
+ * Performance metrics collector
+ */
+export class PerformanceMetrics {
+ private messageCount: number = 0;
+ private errorCount: number = 0;
+ private startTime: number = Date.now();
+ private messageSizes: number[] = [];
+ private latencies: number[] = [];
+ private maxSamples: number = 100;
+
+ /**
+ * Record message received
+ */
+ recordMessage(size?: number): void {
+ this.messageCount++;
+
+ if (size !== undefined) {
+ this.messageSizes.push(size);
+ if (this.messageSizes.length > this.maxSamples) {
+ this.messageSizes.shift();
+ }
+ }
+ }
+
+ /**
+ * Record error
+ */
+ recordError(): void {
+ this.errorCount++;
+ }
+
+ /**
+ * Record latency measurement
+ */
+ recordLatency(latencyMs: number): void {
+ this.latencies.push(latencyMs);
+ if (this.latencies.length > this.maxSamples) {
+ this.latencies.shift();
+ }
+ }
+
+ /**
+ * Get metrics summary
+ */
+ getMetrics() {
+ const uptime = Date.now() - this.startTime;
+ const uptimeSeconds = uptime / 1000;
+
+ return {
+ messageCount: this.messageCount,
+ errorCount: this.errorCount,
+ messagesPerSecond: uptimeSeconds > 0 ? this.messageCount / uptimeSeconds : 0,
+ errorRate: this.messageCount > 0 ? this.errorCount / this.messageCount : 0,
+ averageMessageSize: this.average(this.messageSizes),
+ averageLatency: this.average(this.latencies),
+ uptime,
+ uptimeHours: uptime / (1000 * 60 * 60)
+ };
+ }
+
+ /**
+ * Reset metrics
+ */
+ reset(): void {
+ this.messageCount = 0;
+ this.errorCount = 0;
+ this.startTime = Date.now();
+ this.messageSizes = [];
+ this.latencies = [];
+ }
+
+ private average(arr: number[]): number {
+ if (arr.length === 0) return 0;
+ return arr.reduce((a, b) => a + b, 0) / arr.length;
+ }
+}
+
+/**
+ * Retry helper with exponential backoff
+ */
+export async function retryWithBackoff<T>(
+ fn: () => Promise<T>,
+ maxRetries: number = 3,
+ initialDelay: number = 1000,
+ maxDelay: number = 10000,
+ multiplier: number = 2
+): Promise<T> {
+ let lastError: Error | undefined;
+
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
+ try {
+ return await fn();
+ } catch (error) {
+ lastError = error instanceof Error ? error : new Error(String(error));
+
+ if (attempt < maxRetries) {
+ const delay = Math.min(initialDelay * Math.pow(multiplier, attempt), maxDelay);
+ await new Promise(resolve => setTimeout(resolve, delay));
+ }
+ }
+ }
+
+ throw lastError || new Error('Max retries exceeded');
+}
+
+/**
+ * Generate unique ID
+ */
+export function generateId(prefix: string = 'ws'): string {
+ return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
+}
+
+/**
+ * Safe JSON parse with fallback
+ */
+export function safeJsonParse<T = any>(json: string, fallback: T): T {
+ try {
+ return JSON.parse(json);
+ } catch {
+ return fallback;
+ }
+}
+
+/**
+ * Debounce function
+ */
+export function debounce<T extends (...args: any[]) => any>(
+ func: T,
+ wait: number
+): (...args: Parameters<T>) => void {
+ let timeout: NodeJS.Timeout | null = null;
+
+ return function (this: any, ...args: Parameters<T>) {
+ const context = this;
+
+ if (timeout) {
+ clearTimeout(timeout);
+ }
+
+ timeout = setTimeout(() => {
+ func.apply(context, args);
+ }, wait);
+ };
+}
diff --git a/fincept-terminal-desktop/src/services/yfinanceService.ts b/fincept-terminal-desktop/src/services/yfinanceService.ts
new file mode 100644
index 000000000..7956f0a91
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/yfinanceService.ts
@@ -0,0 +1,139 @@
+// YFinance Service - TypeScript wrapper for Tauri yfinance commands
+// Provides historical data and stock information
+
+import { invoke } from '@tauri-apps/api/core';
+
+export interface HistoricalDataPoint {
+ symbol: string;
+ timestamp: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+ adj_close: number;
+}
+
+export interface HistoricalResponse {
+ success: boolean;
+ data: HistoricalDataPoint[];
+ error?: string;
+}
+
+export interface StockInfo {
+ symbol: string;
+ company_name: string;
+ sector: string;
+ industry: string;
+ market_cap?: number;
+ pe_ratio?: number;
+ dividend_yield?: number;
+ beta?: number;
+ fifty_two_week_high?: number;
+ fifty_two_week_low?: number;
+ description?: string;
+ website?: string;
+ country?: string;
+ [key: string]: any;
+}
+
+export interface StockInfoResponse {
+ success: boolean;
+ data?: StockInfo;
+ error?: string;
+}
+
+/**
+ * YFinance Service
+ * Provides historical market data and stock information via yfinance Python library
+ */
+class YFinanceService {
+ /**
+ * Fetch historical data for a symbol
+ * @param symbol Stock symbol (e.g., "AAPL")
+ * @param startDate Start date in YYYY-MM-DD format
+ * @param endDate End date in YYYY-MM-DD format
+ */
+ async getHistoricalData(
+ symbol: string,
+ startDate: string,
+ endDate: string
+ ): Promise<HistoricalDataPoint[]> {
+ try {
+ const response = await invoke<HistoricalResponse>('get_historical_data', {
+ symbol,
+ startDate,
+ endDate,
+ });
+
+ if (response.success && response.data) {
+ return response.data;
+ } else {
+ console.warn(
+ `[YFinanceService] Failed to fetch historical data for ${symbol}:`,
+ response.error
+ );
+ return [];
+ }
+ } catch (error) {
+ console.error(
+ `[YFinanceService] Error fetching historical data for ${symbol}:`,
+ error
+ );
+ return [];
+ }
+ }
+
+ /**
+ * Fetch stock information and company details
+ * @param symbol Stock symbol (e.g., "AAPL")
+ */
+ async getStockInfo(symbol: string): Promise<StockInfo | null> {
+ try {
+ const response = await invoke<StockInfoResponse>('get_stock_info', {
+ symbol,
+ });
+
+ if (response.success && response.data) {
+ return response.data;
+ } else {
+ console.warn(
+ `[YFinanceService] Failed to fetch stock info for ${symbol}:`,
+ response.error
+ );
+ return null;
+ }
+ } catch (error) {
+ console.error(
+ `[YFinanceService] Error fetching stock info for ${symbol}:`,
+ error
+ );
+ return null;
+ }
+ }
+
+ /**
+ * Helper to get recent historical data (e.g., last 30 days)
+ * @param symbol Stock symbol
+ * @param days Number of days to look back (default: 30)
+ */
+ async getRecentHistory(symbol: string, days: number = 30): Promise<HistoricalDataPoint[]> {
+ const endDate = new Date();
+ const startDate = new Date();
+ startDate.setDate(startDate.getDate() - days);
+
+ const formatDate = (date: Date) => {
+ return date.toISOString().split('T')[0];
+ };
+
+ return this.getHistoricalData(
+ symbol,
+ formatDate(startDate),
+ formatDate(endDate)
+ );
+ }
+}
+
+// Export singleton instance
+export const yfinanceService = new YFinanceService();
+export default yfinanceService;