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.

feat: Add timezone support and AI trading panels

Aviral0405c214ea25
diff --git a/fincept-terminal-desktop/src/components/common/TimezoneSelector.tsx b/fincept-terminal-desktop/src/components/common/TimezoneSelector.tsx
new file mode 100644
index 000000000..90eebfdd5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/common/TimezoneSelector.tsx
@@ -0,0 +1,218 @@
+/**
+ * TimezoneSelector.tsx
+ *
+ * A compact timezone selector widget for terminal headers.
+ * Displays current time with timezone code and allows switching
+ * between major financial market timezones.
+ */
+
+import React, { useState, useRef, useEffect } from 'react';
+import { Clock, ChevronDown, Globe } from 'lucide-react';
+import { useTimezone, useCurrentTime, TIMEZONE_OPTIONS } from '../../contexts/TimezoneContext';
+
+// Bloomberg-style colors
+const COLORS = {
+ DARK_BG: '#0a0a0a',
+ PANEL_BG: '#141414',
+ BORDER: '#333333',
+ ORANGE: '#FFA500',
+ CYAN: '#00D4FF',
+ WHITE: '#FFFFFF',
+ GRAY: '#888888',
+ HOVER: '#1a1a1a',
+};
+
+interface TimezoneSelectorProps {
+ /** Compact mode shows only time + short code */
+ compact?: boolean;
+ /** Custom styling */
+ style?: React.CSSProperties;
+}
+
+export const TimezoneSelector: React.FC<TimezoneSelectorProps> = ({
+ compact = false,
+ style
+}) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const dropdownRef = useRef<HTMLDivElement>(null);
+ const { timezone, setTimezone, options } = useTimezone();
+ const { formattedTime } = useCurrentTime();
+
+ // Close dropdown when clicking outside
+ useEffect(() => {
+ const handleClickOutside = (event: MouseEvent) => {
+ if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
+ setIsOpen(false);
+ }
+ };
+
+ if (isOpen) {
+ document.addEventListener('mousedown', handleClickOutside);
+ }
+
+ return () => {
+ document.removeEventListener('mousedown', handleClickOutside);
+ };
+ }, [isOpen]);
+
+ // Handle timezone selection
+ const handleSelect = (id: string) => {
+ setTimezone(id);
+ setIsOpen(false);
+ };
+
+ return (
+ <div
+ ref={dropdownRef}
+ style={{
+ position: 'relative',
+ display: 'inline-block',
+ ...style
+ }}
+ >
+ {/* Trigger Button */}
+ <button
+ onClick={() => setIsOpen(!isOpen)}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ padding: compact ? '2px 6px' : '4px 10px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${isOpen ? COLORS.CYAN : COLORS.BORDER}`,
+ borderRadius: '3px',
+ color: COLORS.CYAN,
+ cursor: 'pointer',
+ fontSize: compact ? '10px' : '11px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ fontWeight: 500,
+ transition: 'all 0.2s ease',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = COLORS.CYAN;
+ e.currentTarget.style.backgroundColor = COLORS.HOVER;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = isOpen ? COLORS.CYAN : COLORS.BORDER;
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }}
+ title={`Current timezone: ${timezone.label}`}
+ >
+ <Clock size={compact ? 10 : 12} />
+ <span style={{ fontVariantNumeric: 'tabular-nums' }}>
+ {formattedTime}
+ </span>
+ <span style={{
+ color: COLORS.ORANGE,
+ fontWeight: 700,
+ fontSize: compact ? '8px' : '9px',
+ }}>
+ {timezone.shortLabel}
+ </span>
+ <ChevronDown
+ size={compact ? 8 : 10}
+ style={{
+ transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
+ transition: 'transform 0.2s ease',
+ }}
+ />
+ </button>
+
+ {/* Dropdown Menu */}
+ {isOpen && (
+ <div
+ style={{
+ position: 'absolute',
+ top: '100%',
+ right: 0,
+ marginTop: '4px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ borderRadius: '4px',
+ minWidth: '200px',
+ zIndex: 9999,
+ boxShadow: `0 4px 16px rgba(0,0,0,0.5)`,
+ overflow: 'hidden',
+ }}
+ >
+ {/* Header */}
+ <div
+ style={{
+ padding: '8px 12px',
+ borderBottom: `1px solid ${COLORS.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}
+ >
+ <Globe size={12} color={COLORS.ORANGE} />
+ <span style={{
+ color: COLORS.ORANGE,
+ fontSize: '10px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ }}>
+ SELECT TIMEZONE
+ </span>
+ </div>
+
+ {/* Options */}
+ {options.map((option) => (
+ <div
+ key={option.id}
+ onClick={() => handleSelect(option.id)}
+ style={{
+ padding: '10px 12px',
+ cursor: 'pointer',
+ fontSize: '11px',
+ backgroundColor: timezone.id === option.id ? `${COLORS.ORANGE}15` : 'transparent',
+ borderLeft: timezone.id === option.id
+ ? `3px solid ${COLORS.ORANGE}`
+ : '3px solid transparent',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ transition: 'all 0.15s ease',
+ }}
+ onMouseEnter={(e) => {
+ if (timezone.id !== option.id) {
+ e.currentTarget.style.backgroundColor = COLORS.HOVER;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (timezone.id !== option.id) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
+ >
+ <div>
+ <div style={{
+ color: timezone.id === option.id ? COLORS.ORANGE : COLORS.WHITE,
+ fontWeight: 600,
+ marginBottom: '2px',
+ }}>
+ {option.label}
+ </div>
+ <div style={{
+ color: COLORS.GRAY,
+ fontSize: '9px',
+ }}>
+ {option.zone || 'System default'}
+ </div>
+ </div>
+ <span style={{
+ color: timezone.id === option.id ? COLORS.ORANGE : COLORS.CYAN,
+ fontWeight: 700,
+ fontSize: '10px',
+ }}>
+ {option.shortLabel}
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default TimezoneSelector;
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/DebateArenaPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/DebateArenaPanel.tsx
new file mode 100644
index 000000000..2b976eb19
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/DebateArenaPanel.tsx
@@ -0,0 +1,632 @@
+/**
+ * Debate Arena Panel
+ * Bull vs Bear vs Analyst - Multi-agent trading debate system
+ */
+
+import React, { useState, useEffect } from 'react';
+import { MessageSquare, TrendingUp, TrendingDown, Brain, Loader2, AlertCircle, CheckCircle, Zap, Play } from 'lucide-react';
+import agnoTradingService, { type DebateResult } from '../../../../services/agnoTradingService';
+
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A'
+};
+
+interface DebateArenaPanelProps {
+ selectedSymbol: string;
+ currentPrice?: number;
+ marketData?: any;
+}
+
+export function DebateArenaPanel({ selectedSymbol, currentPrice, marketData }: DebateArenaPanelProps) {
+ const [bullModel, setBullModel] = useState('openai:gpt-4o-mini');
+ const [bearModel, setBearModel] = useState('anthropic:claude-sonnet-4');
+ const [analystModel, setAnalystModel] = useState('google:gemini-2.0-flash-exp');
+ const [isDebating, setIsDebating] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [debateResult, setDebateResult] = useState<DebateResult | null>(null);
+ const [recentDebates, setRecentDebates] = useState<any[]>([]);
+ const [availableModels, setAvailableModels] = useState<Array<{ value: string; label: string; color: string }>>([]);
+
+ // Load available models on mount
+ useEffect(() => {
+ loadAvailableModels();
+ loadRecentDebates();
+ }, []);
+
+ const loadAvailableModels = async () => {
+ try {
+ const { sqliteService } = await import('../../../../services/sqliteService');
+ const configs = await sqliteService.getLLMConfigs();
+
+ const configured = configs.filter(c => c.api_key && c.api_key.trim().length > 0);
+
+ const models = configured.map(c => ({
+ value: `${c.provider}:${c.model}`,
+ label: `${c.provider.charAt(0).toUpperCase() + c.provider.slice(1)} - ${c.model}`,
+ color: getModelColor(c.provider)
+ }));
+
+ setAvailableModels(models);
+
+ // Auto-select first 3 if available
+ if (models.length >= 3) {
+ setBullModel(models[0].value);
+ setBearModel(models[1].value);
+ setAnalystModel(models[2].value);
+ }
+ } catch (err) {
+ console.error('Failed to load models:', err);
+ }
+ };
+
+ const loadRecentDebates = async () => {
+ try {
+ const response = await agnoTradingService.getRecentDebates(5);
+ if (response.success && response.data) {
+ setRecentDebates(response.data.debates || []);
+ }
+ } catch (err) {
+ console.error('Failed to load debates:', err);
+ }
+ };
+
+ const getModelColor = (provider: string) => {
+ const colors: Record<string, string> = {
+ openai: BLOOMBERG.GREEN,
+ anthropic: BLOOMBERG.ORANGE,
+ google: BLOOMBERG.BLUE,
+ gemini: BLOOMBERG.BLUE,
+ groq: BLOOMBERG.PURPLE,
+ deepseek: BLOOMBERG.CYAN,
+ xai: BLOOMBERG.YELLOW
+ };
+ return colors[provider.toLowerCase()] || BLOOMBERG.GRAY;
+ };
+
+ const handleStartDebate = async () => {
+ if (!selectedSymbol) {
+ setError('No symbol selected');
+ return;
+ }
+
+ if (bullModel === bearModel || bearModel === analystModel || bullModel === analystModel) {
+ setError('Please select different models for each role');
+ return;
+ }
+
+ setIsDebating(true);
+ setError(null);
+ setDebateResult(null);
+
+ try {
+ const market = {
+ price: currentPrice || 0,
+ symbol: selectedSymbol,
+ ...marketData
+ };
+
+ const response = await agnoTradingService.runDebate(
+ selectedSymbol,
+ market,
+ bullModel,
+ bearModel,
+ analystModel
+ );
+
+ if (response.success && response.data) {
+ setDebateResult(response.data);
+ await loadRecentDebates(); // Refresh history
+ } else {
+ setError(response.error || 'Debate failed');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setIsDebating(false);
+ }
+ };
+
+ const canStartDebate = availableModels.length >= 3 && !isDebating;
+
+ return (
+ <div style={{
+ height: '100%',
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {/* Header */}
+ <div style={{
+ background: BLOOMBERG.HEADER_BG,
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '8px 10px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <MessageSquare size={14} color={BLOOMBERG.ORANGE} />
+ <span style={{
+ color: BLOOMBERG.WHITE,
+ fontSize: '11px',
+ fontWeight: '600',
+ letterSpacing: '0.5px'
+ }}>
+ DEBATE ARENA
+ </span>
+ {isDebating && (
+ <Loader2 size={12} color={BLOOMBERG.ORANGE} className="animate-spin" />
+ )}
+ </div>
+ <span style={{ color: BLOOMBERG.GRAY, fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}>
+ {selectedSymbol}
+ </span>
+ </div>
+
+ {/* Content */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '10px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
+
+ {/* Model Selection */}
+ {!debateResult && (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {/* Bull Model */}
+ <div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '4px'
+ }}>
+ <TrendingUp size={10} color={BLOOMBERG.GREEN} />
+ <label style={{
+ color: BLOOMBERG.GREEN,
+ fontSize: '9px',
+ fontWeight: '600',
+ letterSpacing: '0.5px'
+ }}>
+ BULL AGENT
+ </label>
+ </div>
+ <select
+ value={bullModel}
+ onChange={(e) => setBullModel(e.target.value)}
+ disabled={isDebating || availableModels.length === 0}
+ style={{
+ width: '100%',
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.GREEN}`,
+ color: BLOOMBERG.WHITE,
+ padding: '5px 8px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ cursor: 'pointer'
+ }}
+ >
+ {availableModels.map(m => (
+ <option key={m.value} value={m.value}>{m.label}</option>
+ ))}
+ </select>
+ </div>
+
+ {/* Bear Model */}
+ <div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '4px'
+ }}>
+ <TrendingDown size={10} color={BLOOMBERG.RED} />
+ <label style={{
+ color: BLOOMBERG.RED,
+ fontSize: '9px',
+ fontWeight: '600',
+ letterSpacing: '0.5px'
+ }}>
+ BEAR AGENT
+ </label>
+ </div>
+ <select
+ value={bearModel}
+ onChange={(e) => setBearModel(e.target.value)}
+ disabled={isDebating || availableModels.length === 0}
+ style={{
+ width: '100%',
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.RED}`,
+ color: BLOOMBERG.WHITE,
+ padding: '5px 8px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ cursor: 'pointer'
+ }}
+ >
+ {availableModels.map(m => (
+ <option key={m.value} value={m.value}>{m.label}</option>
+ ))}
+ </select>
+ </div>
+
+ {/* Analyst Model */}
+ <div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '4px'
+ }}>
+ <Brain size={10} color={BLOOMBERG.ORANGE} />
+ <label style={{
+ color: BLOOMBERG.ORANGE,
+ fontSize: '9px',
+ fontWeight: '600',
+ letterSpacing: '0.5px'
+ }}>
+ ANALYST AGENT
+ </label>
+ </div>
+ <select
+ value={analystModel}
+ onChange={(e) => setAnalystModel(e.target.value)}
+ disabled={isDebating || availableModels.length === 0}
+ style={{
+ width: '100%',
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.ORANGE}`,
+ color: BLOOMBERG.WHITE,
+ padding: '5px 8px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ cursor: 'pointer'
+ }}
+ >
+ {availableModels.map(m => (
+ <option key={m.value} value={m.value}>{m.label}</option>
+ ))}
+ </select>
+ </div>
+
+ {/* Start Button */}
+ <button
+ onClick={handleStartDebate}
+ disabled={!canStartDebate}
+ style={{
+ width: '100%',
+ background: canStartDebate ? BLOOMBERG.ORANGE : BLOOMBERG.GRAY,
+ border: 'none',
+ color: canStartDebate ? BLOOMBERG.DARK_BG : BLOOMBERG.MUTED,
+ padding: '10px',
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontWeight: '700',
+ cursor: canStartDebate ? 'pointer' : 'not-allowed',
+ opacity: canStartDebate ? 1 : 0.5,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ letterSpacing: '0.5px',
+ marginTop: '4px'
+ }}
+ >
+ {isDebating ? (
+ <>
+ <Loader2 size={14} className="animate-spin" />
+ DEBATING...
+ </>
+ ) : (
+ <>
+ <Play size={14} />
+ START DEBATE
+ </>
+ )}
+ </button>
+
+ {availableModels.length < 3 && (
+ <div style={{
+ background: `${BLOOMBERG.YELLOW}15`,
+ border: `1px solid ${BLOOMBERG.YELLOW}`,
+ borderRadius: '2px',
+ padding: '6px 8px',
+ fontSize: '8px',
+ color: BLOOMBERG.YELLOW
+ }}>
+ Configure at least 3 models in Settings → LLM Config
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Error Display */}
+ {error && (
+ <div style={{
+ background: `${BLOOMBERG.RED}15`,
+ border: `1px solid ${BLOOMBERG.RED}`,
+ borderRadius: '2px',
+ padding: '8px',
+ display: 'flex',
+ alignItems: 'flex-start',
+ gap: '6px'
+ }}>
+ <AlertCircle size={12} color={BLOOMBERG.RED} style={{ flexShrink: 0, marginTop: '1px' }} />
+ <div>
+ <div style={{ color: BLOOMBERG.RED, fontSize: '9px', fontWeight: '600' }}>ERROR</div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '8px', marginTop: '2px' }}>{error}</div>
+ </div>
+ </div>
+ )}
+
+ {/* Debate Result */}
+ {debateResult && (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
+ {/* Final Decision Card */}
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `2px solid ${BLOOMBERG.ORANGE}`,
+ borderRadius: '4px',
+ padding: '10px'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '8px'
+ }}>
+ <CheckCircle size={14} color={BLOOMBERG.ORANGE} />
+ <span style={{ color: BLOOMBERG.ORANGE, fontSize: '10px', fontWeight: '700', letterSpacing: '0.5px' }}>
+ FINAL DECISION
+ </span>
+ </div>
+
+ <div style={{
+ background: BLOOMBERG.PANEL_BG,
+ borderRadius: '2px',
+ padding: '8px',
+ marginBottom: '8px'
+ }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '8px' }}>
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '7px', marginBottom: '3px' }}>ACTION</div>
+ <div style={{
+ color: debateResult.final_action === 'BUY' ? BLOOMBERG.GREEN :
+ debateResult.final_action === 'SELL' ? BLOOMBERG.RED : BLOOMBERG.YELLOW,
+ fontSize: '14px',
+ fontWeight: '700',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {debateResult.final_action}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '7px', marginBottom: '3px' }}>CONFIDENCE</div>
+ <div style={{
+ color: BLOOMBERG.CYAN,
+ fontSize: '14px',
+ fontWeight: '700',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {debateResult.confidence}%
+ </div>
+ </div>
+ </div>
+
+ {debateResult.entry_price && (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '6px', fontSize: '8px' }}>
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, marginBottom: '2px' }}>ENTRY</div>
+ <div style={{ color: BLOOMBERG.WHITE, fontWeight: '600', fontFamily: '"IBM Plex Mono", monospace' }}>
+ ${debateResult.entry_price.toFixed(2)}
+ </div>
+ </div>
+ {debateResult.stop_loss && (
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, marginBottom: '2px' }}>STOP</div>
+ <div style={{ color: BLOOMBERG.RED, fontWeight: '600', fontFamily: '"IBM Plex Mono", monospace' }}>
+ ${debateResult.stop_loss.toFixed(2)}
+ </div>
+ </div>
+ )}
+ {debateResult.take_profit && (
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, marginBottom: '2px' }}>TARGET</div>
+ <div style={{ color: BLOOMBERG.GREEN, fontWeight: '600', fontFamily: '"IBM Plex Mono", monospace' }}>
+ ${debateResult.take_profit.toFixed(2)}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ <button
+ onClick={() => setDebateResult(null)}
+ style={{
+ width: '100%',
+ background: 'transparent',
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ color: BLOOMBERG.GRAY,
+ padding: '6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: 'pointer',
+ letterSpacing: '0.3px'
+ }}
+ >
+ NEW DEBATE
+ </button>
+ </div>
+
+ {/* Arguments */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {/* Bull Argument */}
+ <DebateArgumentCard
+ role="BULL"
+ model={bullModel}
+ argument={debateResult.bull_argument}
+ color={BLOOMBERG.GREEN}
+ />
+
+ {/* Bear Argument */}
+ <DebateArgumentCard
+ role="BEAR"
+ model={bearModel}
+ argument={debateResult.bear_argument}
+ color={BLOOMBERG.RED}
+ />
+
+ {/* Analyst Decision */}
+ <DebateArgumentCard
+ role="ANALYST"
+ model={analystModel}
+ argument={debateResult.analyst_decision}
+ color={BLOOMBERG.ORANGE}
+ />
+ </div>
+
+ {/* Execution Time */}
+ <div style={{
+ textAlign: 'center',
+ color: BLOOMBERG.MUTED,
+ fontSize: '8px',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ Execution time: {(debateResult.execution_time_ms / 1000).toFixed(1)}s
+ </div>
+ </div>
+ )}
+
+ {/* Recent Debates */}
+ {!debateResult && recentDebates.length > 0 && (
+ <div style={{ marginTop: '10px' }}>
+ <div style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '9px',
+ fontWeight: '600',
+ marginBottom: '6px',
+ letterSpacing: '0.5px'
+ }}>
+ RECENT DEBATES
+ </div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ {recentDebates.slice(0, 5).map((debate, idx) => (
+ <div
+ key={idx}
+ style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ padding: '6px 8px',
+ fontSize: '8px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}
+ >
+ <span style={{ color: BLOOMBERG.WHITE, fontFamily: '"IBM Plex Mono", monospace' }}>
+ {debate.symbol}
+ </span>
+ <span style={{
+ color: debate.final_action === 'BUY' ? BLOOMBERG.GREEN :
+ debate.final_action === 'SELL' ? BLOOMBERG.RED : BLOOMBERG.YELLOW,
+ fontWeight: '700'
+ }}>
+ {debate.final_action}
+ </span>
+ <span style={{ color: BLOOMBERG.GRAY }}>
+ {new Date(debate.timestamp * 1000).toLocaleTimeString()}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// ============================================================================
+// Debate Argument Card Component
+// ============================================================================
+
+interface DebateArgumentCardProps {
+ role: string;
+ model: string;
+ argument: string;
+ color: string;
+}
+
+function DebateArgumentCard({ role, model, argument, color }: DebateArgumentCardProps) {
+ const [isExpanded, setIsExpanded] = useState(false);
+
+ return (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${color}`,
+ borderRadius: '2px',
+ overflow: 'hidden'
+ }}>
+ <div
+ onClick={() => setIsExpanded(!isExpanded)}
+ style={{
+ padding: '6px 8px',
+ background: `${color}10`,
+ borderBottom: isExpanded ? `1px solid ${BLOOMBERG.BORDER}` : 'none',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ {role === 'BULL' && <TrendingUp size={10} color={color} />}
+ {role === 'BEAR' && <TrendingDown size={10} color={color} />}
+ {role === 'ANALYST' && <Brain size={10} color={color} />}
+ <span style={{ color, fontSize: '9px', fontWeight: '700', letterSpacing: '0.3px' }}>
+ {role}
+ </span>
+ </div>
+ <span style={{ color: BLOOMBERG.GRAY, fontSize: '8px', fontFamily: '"IBM Plex Mono", monospace' }}>
+ {model.split(':')[1] || model}
+ </span>
+ </div>
+ {isExpanded && (
+ <div style={{
+ padding: '8px',
+ color: BLOOMBERG.WHITE,
+ fontSize: '9px',
+ lineHeight: '1.5',
+ maxHeight: '200px',
+ overflow: 'auto',
+ whiteSpace: 'pre-wrap',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {argument.substring(0, 500)}{argument.length > 500 ? '...' : ''}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default DebateArenaPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/DecisionFeedPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/DecisionFeedPanel.tsx
new file mode 100644
index 000000000..457cbaf88
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/DecisionFeedPanel.tsx
@@ -0,0 +1,378 @@
+/**
+ * Decision Feed Panel
+ * Real-time feed of all agent decisions
+ */
+
+import React, { useState, useEffect } from 'react';
+import { Activity, Brain, Target, Shield, TrendingUp, Filter, RefreshCw } from 'lucide-react';
+import agnoTradingService, { type Decision } from '../../../../services/agnoTradingService';
+
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A'
+};
+
+interface DecisionFeedPanelProps {
+ agentId?: string;
+ autoRefresh?: boolean;
+ refreshInterval?: number;
+}
+
+export function DecisionFeedPanel({
+ agentId,
+ autoRefresh = true,
+ refreshInterval = 5000
+}: DecisionFeedPanelProps) {
+ const [decisions, setDecisions] = useState<Decision[]>([]);
+ const [isLoading, setIsLoading] = useState(false);
+ const [filterType, setFilterType] = useState<string>('all');
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ fetchDecisions();
+
+ if (autoRefresh) {
+ const interval = setInterval(fetchDecisions, refreshInterval);
+ return () => clearInterval(interval);
+ }
+ }, [agentId, filterType, autoRefresh, refreshInterval]);
+
+ const fetchDecisions = async () => {
+ try {
+ setIsLoading(true);
+ setError(null);
+
+ const response = await agnoTradingService.getDbDecisions(50, agentId);
+
+ if (response.success && response.data) {
+ let filtered = response.data.decisions || [];
+
+ // Apply filter
+ if (filterType !== 'all') {
+ filtered = filtered.filter(d => d.decision_type === filterType);
+ }
+
+ setDecisions(filtered);
+ } else {
+ setError(response.error || 'Failed to load decisions');
+ }
+ } catch (err) {
+ console.error('Failed to fetch decisions:', err);
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const getDecisionTypeColor = (type: string) => {
+ const colors: Record<string, string> = {
+ analysis: BLOOMBERG.BLUE,
+ signal: BLOOMBERG.GREEN,
+ trade: BLOOMBERG.ORANGE,
+ risk: BLOOMBERG.RED
+ };
+ return colors[type] || BLOOMBERG.GRAY;
+ };
+
+ const getDecisionTypeIcon = (type: string) => {
+ const icons: Record<string, any> = {
+ analysis: Brain,
+ signal: Target,
+ trade: TrendingUp,
+ risk: Shield
+ };
+ const Icon = icons[type] || Activity;
+ return <Icon size={10} />;
+ };
+
+ return (
+ <div style={{
+ height: '100%',
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {/* Header */}
+ <div style={{
+ background: BLOOMBERG.HEADER_BG,
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '8px 10px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Activity size={14} color={BLOOMBERG.CYAN} />
+ <span style={{
+ color: BLOOMBERG.WHITE,
+ fontSize: '11px',
+ fontWeight: '600',
+ letterSpacing: '0.5px'
+ }}>
+ DECISION FEED
+ </span>
+ {isLoading && (
+ <RefreshCw size={10} color={BLOOMBERG.ORANGE} className="animate-spin" />
+ )}
+ </div>
+
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {/* Filter Buttons */}
+ {['all', 'analysis', 'signal', 'trade', 'risk'].map(type => (
+ <button
+ key={type}
+ onClick={() => setFilterType(type)}
+ style={{
+ background: filterType === type ? BLOOMBERG.ORANGE : 'transparent',
+ border: `1px solid ${filterType === type ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ color: filterType === type ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ padding: '2px 6px',
+ borderRadius: '2px',
+ fontSize: '8px',
+ fontWeight: '700',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ textTransform: 'uppercase',
+ letterSpacing: '0.3px'
+ }}
+ >
+ {type}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Content */}
+ <div style={{
+ flex: 1,
+ overflow: 'auto',
+ padding: '8px'
+ }}>
+ {error && (
+ <div style={{
+ background: `${BLOOMBERG.RED}15`,
+ border: `1px solid ${BLOOMBERG.RED}`,
+ borderRadius: '2px',
+ padding: '8px',
+ marginBottom: '8px',
+ color: BLOOMBERG.RED,
+ fontSize: '9px'
+ }}>
+ {error}
+ </div>
+ )}
+
+ {decisions.length === 0 && !isLoading && (
+ <div style={{
+ textAlign: 'center',
+ color: BLOOMBERG.GRAY,
+ fontSize: '10px',
+ marginTop: '40px'
+ }}>
+ {filterType === 'all' ? 'No decisions yet' : `No ${filterType} decisions`}
+ </div>
+ )}
+
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
+ {decisions.map((decision, idx) => (
+ <DecisionCard key={decision.id || idx} decision={decision} />
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// ============================================================================
+// Decision Card Component
+// ============================================================================
+
+interface DecisionCardProps {
+ decision: Decision;
+}
+
+function DecisionCard({ decision }: DecisionCardProps) {
+ const [isExpanded, setIsExpanded] = useState(false);
+
+ const getDecisionTypeColor = (type: string) => {
+ const colors: Record<string, string> = {
+ analysis: BLOOMBERG.BLUE,
+ signal: BLOOMBERG.GREEN,
+ trade: BLOOMBERG.ORANGE,
+ risk: BLOOMBERG.RED
+ };
+ return colors[type] || BLOOMBERG.GRAY;
+ };
+
+ const getDecisionTypeIcon = (type: string) => {
+ const icons: Record<string, any> = {
+ analysis: Brain,
+ signal: Target,
+ trade: TrendingUp,
+ risk: Shield
+ };
+ const Icon = icons[type] || Activity;
+ return <Icon size={10} />;
+ };
+
+ const typeColor = getDecisionTypeColor(decision.decision_type);
+ const TypeIcon = getDecisionTypeIcon(decision.decision_type);
+
+ return (
+ <div
+ onClick={() => setIsExpanded(!isExpanded)}
+ style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${typeColor}30`,
+ borderLeft: `3px solid ${typeColor}`,
+ borderRadius: '2px',
+ padding: '8px',
+ cursor: 'pointer',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.background = BLOOMBERG.HOVER;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.background = BLOOMBERG.DARK_BG;
+ }}
+ >
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: isExpanded ? '8px' : '0'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <div style={{ color: typeColor }}>
+ {TypeIcon}
+ </div>
+ <span style={{
+ color: typeColor,
+ fontSize: '9px',
+ fontWeight: '700',
+ textTransform: 'uppercase',
+ letterSpacing: '0.3px'
+ }}>
+ {decision.decision_type}
+ </span>
+ {decision.symbol && (
+ <span style={{
+ color: BLOOMBERG.WHITE,
+ fontSize: '9px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ fontWeight: '600'
+ }}>
+ {decision.symbol}
+ </span>
+ )}
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ {decision.confidence !== undefined && (
+ <span style={{
+ color: BLOOMBERG.CYAN,
+ fontSize: '8px',
+ fontWeight: '700',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {decision.confidence}%
+ </span>
+ )}
+ <span style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '8px',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {new Date(decision.timestamp * 1000).toLocaleTimeString()}
+ </span>
+ </div>
+ </div>
+
+ {/* Decision Text */}
+ <div style={{
+ color: BLOOMBERG.WHITE,
+ fontSize: '9px',
+ lineHeight: '1.4',
+ fontFamily: '"IBM Plex Mono", monospace',
+ marginBottom: isExpanded && decision.reasoning ? '6px' : '0'
+ }}>
+ {isExpanded ? decision.decision : decision.decision.substring(0, 60) + (decision.decision.length > 60 ? '...' : '')}
+ </div>
+
+ {/* Reasoning (when expanded) */}
+ {isExpanded && decision.reasoning && (
+ <div style={{
+ background: BLOOMBERG.PANEL_BG,
+ borderRadius: '2px',
+ padding: '6px',
+ marginTop: '6px'
+ }}>
+ <div style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '7px',
+ fontWeight: '700',
+ marginBottom: '4px',
+ letterSpacing: '0.5px'
+ }}>
+ REASONING
+ </div>
+ <div style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '8px',
+ lineHeight: '1.4',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {decision.reasoning.substring(0, 200)}{decision.reasoning.length > 200 ? '...' : ''}
+ </div>
+ </div>
+ )}
+
+ {/* Footer */}
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginTop: '6px',
+ paddingTop: '6px',
+ borderTop: `1px solid ${BLOOMBERG.BORDER}`
+ }}>
+ <span style={{
+ color: BLOOMBERG.MUTED,
+ fontSize: '8px',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {decision.model.split(':')[1] || decision.model}
+ </span>
+ {decision.execution_time_ms !== undefined && (
+ <span style={{
+ color: BLOOMBERG.MUTED,
+ fontSize: '7px',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {decision.execution_time_ms}ms
+ </span>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default DecisionFeedPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/TradeHistoryPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/TradeHistoryPanel.tsx
new file mode 100644
index 000000000..80b151b0e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/TradeHistoryPanel.tsx
@@ -0,0 +1,549 @@
+/**
+ * Trade History Panel
+ * Display agent trade history and performance metrics
+ */
+
+import React, { useState, useEffect } from 'react';
+import { TrendingUp, TrendingDown, Activity, BarChart3, RefreshCw, Filter, ArrowUpDown } from 'lucide-react';
+import agnoTradingService, { type AgentTrade, type AgentPerformance } from '../../../../services/agnoTradingService';
+
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A'
+};
+
+interface TradeHistoryPanelProps {
+ agentId?: string;
+ autoRefresh?: boolean;
+ refreshInterval?: number;
+}
+
+type SortField = 'date' | 'symbol' | 'pnl' | 'pnl_percent';
+type SortDirection = 'asc' | 'desc';
+
+export function TradeHistoryPanel({
+ agentId,
+ autoRefresh = true,
+ refreshInterval = 10000
+}: TradeHistoryPanelProps) {
+ const [trades, setTrades] = useState<AgentTrade[]>([]);
+ const [performance, setPerformance] = useState<AgentPerformance | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [filterStatus, setFilterStatus] = useState<string>('all');
+ const [sortField, setSortField] = useState<SortField>('date');
+ const [sortDirection, setSortDirection] = useState<SortDirection>('desc');
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ fetchData();
+
+ if (autoRefresh) {
+ const interval = setInterval(fetchData, refreshInterval);
+ return () => clearInterval(interval);
+ }
+ }, [agentId, filterStatus, autoRefresh, refreshInterval]);
+
+ const fetchData = async () => {
+ try {
+ setIsLoading(true);
+ setError(null);
+
+ // Fetch trades
+ const tradesResponse = await agnoTradingService.getAgentTrades(
+ agentId || 'all',
+ 100,
+ filterStatus === 'all' ? undefined : filterStatus
+ );
+
+ if (tradesResponse.success && tradesResponse.data) {
+ setTrades(tradesResponse.data.trades || []);
+ }
+
+ // Fetch performance if agent specified
+ if (agentId) {
+ const perfResponse = await agnoTradingService.getAgentPerformance(agentId);
+ if (perfResponse.success && perfResponse.data) {
+ setPerformance(perfResponse.data.performance);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to fetch trade data:', err);
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleSort = (field: SortField) => {
+ if (sortField === field) {
+ setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
+ } else {
+ setSortField(field);
+ setSortDirection('desc');
+ }
+ };
+
+ const sortedTrades = [...trades].sort((a, b) => {
+ const multiplier = sortDirection === 'asc' ? 1 : -1;
+
+ switch (sortField) {
+ case 'date':
+ return (a.entry_timestamp - b.entry_timestamp) * multiplier;
+ case 'symbol':
+ return a.symbol.localeCompare(b.symbol) * multiplier;
+ case 'pnl':
+ return (a.pnl - b.pnl) * multiplier;
+ case 'pnl_percent':
+ return (a.pnl_percent - b.pnl_percent) * multiplier;
+ default:
+ return 0;
+ }
+ });
+
+ return (
+ <div style={{
+ height: '100%',
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {/* Header */}
+ <div style={{
+ background: BLOOMBERG.HEADER_BG,
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '8px 10px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <BarChart3 size={14} color={BLOOMBERG.CYAN} />
+ <span style={{
+ color: BLOOMBERG.WHITE,
+ fontSize: '11px',
+ fontWeight: '600',
+ letterSpacing: '0.5px'
+ }}>
+ TRADE HISTORY
+ </span>
+ {isLoading && (
+ <RefreshCw size={10} color={BLOOMBERG.ORANGE} className="animate-spin" />
+ )}
+ </div>
+
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {/* Status Filter */}
+ {['all', 'open', 'closed'].map(status => (
+ <button
+ key={status}
+ onClick={() => setFilterStatus(status)}
+ style={{
+ background: filterStatus === status ? BLOOMBERG.ORANGE : 'transparent',
+ border: `1px solid ${filterStatus === status ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ color: filterStatus === status ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ padding: '2px 6px',
+ borderRadius: '2px',
+ fontSize: '8px',
+ fontWeight: '700',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ textTransform: 'uppercase',
+ letterSpacing: '0.3px'
+ }}
+ >
+ {status}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Performance Summary */}
+ {performance && (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '8px 10px',
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: '8px'
+ }}>
+ <MetricCard
+ label="TOTAL P&L"
+ value={`$${performance.total_pnl.toFixed(2)}`}
+ color={performance.total_pnl >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED}
+ />
+ <MetricCard
+ label="WIN RATE"
+ value={`${performance.win_rate.toFixed(1)}%`}
+ color={performance.win_rate >= 50 ? BLOOMBERG.GREEN : BLOOMBERG.RED}
+ />
+ <MetricCard
+ label="SHARPE"
+ value={performance.sharpe_ratio.toFixed(2)}
+ color={performance.sharpe_ratio >= 1 ? BLOOMBERG.GREEN : BLOOMBERG.ORANGE}
+ />
+ <MetricCard
+ label="TRADES"
+ value={performance.total_trades.toString()}
+ color={BLOOMBERG.CYAN}
+ />
+ <MetricCard
+ label="DAILY P&L"
+ value={`$${performance.daily_pnl.toFixed(2)}`}
+ color={performance.daily_pnl >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED}
+ />
+ <MetricCard
+ label="MAX DD"
+ value={`${performance.max_drawdown.toFixed(2)}%`}
+ color={BLOOMBERG.RED}
+ />
+ <MetricCard
+ label="PROFIT FACTOR"
+ value={performance.profit_factor.toFixed(2)}
+ color={performance.profit_factor >= 1.5 ? BLOOMBERG.GREEN : BLOOMBERG.ORANGE}
+ />
+ <MetricCard
+ label="STREAK"
+ value={`${performance.consecutive_wins}W / ${performance.consecutive_losses}L`}
+ color={BLOOMBERG.GRAY}
+ />
+ </div>
+ )}
+
+ {/* Error Display */}
+ {error && (
+ <div style={{
+ background: `${BLOOMBERG.RED}15`,
+ border: `1px solid ${BLOOMBERG.RED}`,
+ borderRadius: '2px',
+ padding: '8px',
+ margin: '8px',
+ color: BLOOMBERG.RED,
+ fontSize: '9px'
+ }}>
+ {error}
+ </div>
+ )}
+
+ {/* Trade Table */}
+ <div style={{
+ flex: 1,
+ overflow: 'auto',
+ padding: '8px'
+ }}>
+ {trades.length === 0 && !isLoading && (
+ <div style={{
+ textAlign: 'center',
+ color: BLOOMBERG.GRAY,
+ fontSize: '10px',
+ marginTop: '40px'
+ }}>
+ No trades yet
+ </div>
+ )}
+
+ {trades.length > 0 && (
+ <table style={{
+ width: '100%',
+ borderCollapse: 'collapse',
+ fontSize: '9px',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ <thead>
+ <tr style={{
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ color: BLOOMBERG.GRAY
+ }}>
+ <SortableHeader
+ label="SYMBOL"
+ field="symbol"
+ currentField={sortField}
+ direction={sortDirection}
+ onSort={handleSort}
+ />
+ <th style={{ padding: '6px 4px', textAlign: 'left', fontSize: '8px', fontWeight: '700' }}>
+ SIDE
+ </th>
+ <th style={{ padding: '6px 4px', textAlign: 'right', fontSize: '8px', fontWeight: '700' }}>
+ ENTRY
+ </th>
+ <th style={{ padding: '6px 4px', textAlign: 'right', fontSize: '8px', fontWeight: '700' }}>
+ EXIT
+ </th>
+ <SortableHeader
+ label="P&L"
+ field="pnl"
+ currentField={sortField}
+ direction={sortDirection}
+ onSort={handleSort}
+ align="right"
+ />
+ <SortableHeader
+ label="P&L%"
+ field="pnl_percent"
+ currentField={sortField}
+ direction={sortDirection}
+ onSort={handleSort}
+ align="right"
+ />
+ <th style={{ padding: '6px 4px', textAlign: 'center', fontSize: '8px', fontWeight: '700' }}>
+ STATUS
+ </th>
+ <SortableHeader
+ label="DATE"
+ field="date"
+ currentField={sortField}
+ direction={sortDirection}
+ onSort={handleSort}
+ align="right"
+ />
+ </tr>
+ </thead>
+ <tbody>
+ {sortedTrades.map((trade, idx) => (
+ <TradeRow key={trade.id || idx} trade={trade} />
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// ============================================================================
+// Metric Card Component
+// ============================================================================
+
+interface MetricCardProps {
+ label: string;
+ value: string;
+ color: string;
+}
+
+function MetricCard({ label, value, color }: MetricCardProps) {
+ return (
+ <div style={{
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ padding: '4px 6px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '2px'
+ }}>
+ <span style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '7px',
+ fontWeight: '700',
+ letterSpacing: '0.5px'
+ }}>
+ {label}
+ </span>
+ <span style={{
+ color: color,
+ fontSize: '10px',
+ fontWeight: '600',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {value}
+ </span>
+ </div>
+ );
+}
+
+// ============================================================================
+// Sortable Header Component
+// ============================================================================
+
+interface SortableHeaderProps {
+ label: string;
+ field: SortField;
+ currentField: SortField;
+ direction: SortDirection;
+ onSort: (field: SortField) => void;
+ align?: 'left' | 'right' | 'center';
+}
+
+function SortableHeader({
+ label,
+ field,
+ currentField,
+ direction,
+ onSort,
+ align = 'left'
+}: SortableHeaderProps) {
+ const isActive = currentField === field;
+
+ return (
+ <th
+ onClick={() => onSort(field)}
+ style={{
+ padding: '6px 4px',
+ textAlign: align,
+ fontSize: '8px',
+ fontWeight: '700',
+ cursor: 'pointer',
+ userSelect: 'none',
+ transition: 'color 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.color = BLOOMBERG.ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.color = isActive ? BLOOMBERG.ORANGE : BLOOMBERG.GRAY;
+ }}
+ >
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '2px',
+ justifyContent: align === 'right' ? 'flex-end' : align === 'center' ? 'center' : 'flex-start',
+ color: isActive ? BLOOMBERG.ORANGE : BLOOMBERG.GRAY
+ }}>
+ {label}
+ {isActive && (
+ <ArrowUpDown size={8} style={{
+ transform: direction === 'asc' ? 'rotate(180deg)' : 'none',
+ transition: 'transform 0.2s'
+ }} />
+ )}
+ </div>
+ </th>
+ );
+}
+
+// ============================================================================
+// Trade Row Component
+// ============================================================================
+
+interface TradeRowProps {
+ trade: AgentTrade;
+}
+
+function TradeRow({ trade }: TradeRowProps) {
+ const pnlColor = trade.pnl >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED;
+ const statusColor = trade.status === 'open' ? BLOOMBERG.CYAN :
+ trade.status === 'closed' ? BLOOMBERG.GRAY :
+ BLOOMBERG.YELLOW;
+
+ return (
+ <tr
+ style={{
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ transition: 'background 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.background = BLOOMBERG.HOVER;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.background = 'transparent';
+ }}
+ >
+ {/* Symbol */}
+ <td style={{
+ padding: '6px 4px',
+ color: BLOOMBERG.WHITE,
+ fontWeight: '600'
+ }}>
+ {trade.symbol}
+ </td>
+
+ {/* Side */}
+ <td style={{
+ padding: '6px 4px',
+ color: trade.side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.RED,
+ fontWeight: '700',
+ textTransform: 'uppercase'
+ }}>
+ {trade.side}
+ </td>
+
+ {/* Entry Price */}
+ <td style={{
+ padding: '6px 4px',
+ textAlign: 'right',
+ color: BLOOMBERG.WHITE
+ }}>
+ ${trade.entry_price.toFixed(2)}
+ </td>
+
+ {/* Exit Price */}
+ <td style={{
+ padding: '6px 4px',
+ textAlign: 'right',
+ color: trade.exit_price ? BLOOMBERG.WHITE : BLOOMBERG.MUTED
+ }}>
+ {trade.exit_price ? `$${trade.exit_price.toFixed(2)}` : '-'}
+ </td>
+
+ {/* P&L */}
+ <td style={{
+ padding: '6px 4px',
+ textAlign: 'right',
+ color: pnlColor,
+ fontWeight: '700'
+ }}>
+ {trade.pnl >= 0 ? '+' : ''}${trade.pnl.toFixed(2)}
+ </td>
+
+ {/* P&L % */}
+ <td style={{
+ padding: '6px 4px',
+ textAlign: 'right',
+ color: pnlColor,
+ fontWeight: '700'
+ }}>
+ {trade.pnl_percent >= 0 ? '+' : ''}{trade.pnl_percent.toFixed(2)}%
+ </td>
+
+ {/* Status */}
+ <td style={{
+ padding: '6px 4px',
+ textAlign: 'center'
+ }}>
+ <span style={{
+ background: `${statusColor}20`,
+ border: `1px solid ${statusColor}`,
+ borderRadius: '2px',
+ padding: '1px 4px',
+ color: statusColor,
+ fontSize: '7px',
+ fontWeight: '700',
+ textTransform: 'uppercase',
+ letterSpacing: '0.3px'
+ }}>
+ {trade.status}
+ </span>
+ </td>
+
+ {/* Date */}
+ <td style={{
+ padding: '6px 4px',
+ textAlign: 'right',
+ color: BLOOMBERG.GRAY,
+ fontSize: '8px'
+ }}>
+ {new Date(trade.entry_timestamp * 1000).toLocaleDateString()}
+ </td>
+ </tr>
+ );
+}
+
+export default TradeHistoryPanel;
diff --git a/fincept-terminal-desktop/src/contexts/TimezoneContext.tsx b/fincept-terminal-desktop/src/contexts/TimezoneContext.tsx
new file mode 100644
index 000000000..1ef0a3dd2
--- /dev/null
+++ b/fincept-terminal-desktop/src/contexts/TimezoneContext.tsx
@@ -0,0 +1,341 @@
+/**
+ * TimezoneContext.tsx
+ *
+ * Global timezone state management for Fincept Terminal.
+ * Provides dual-timezone support:
+ * - Default Timezone: Persisted in localStorage, used by navigation bar
+ * - Session Timezone: Per-session, used by dashboard widgets
+ */
+
+import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
+
+// ============================================================================
+// Types & Constants
+// ============================================================================
+
+export interface TimezoneOption {
+ id: string;
+ label: string;
+ shortLabel: string;
+ zone: string | undefined; // undefined = use system locale
+}
+
+export const TIMEZONE_OPTIONS: TimezoneOption[] = [
+ // System
+ { id: 'local', label: 'Local (System)', shortLabel: 'LOC', zone: undefined },
+ { id: 'utc', label: 'UTC (Coordinated)', shortLabel: 'UTC', zone: 'UTC' },
+
+ // Americas
+ { id: 'new-york', label: 'New York (EST/EDT)', shortLabel: 'NYC', zone: 'America/New_York' },
+ { id: 'chicago', label: 'Chicago (CST/CDT)', shortLabel: 'CHI', zone: 'America/Chicago' },
+ { id: 'denver', label: 'Denver (MST/MDT)', shortLabel: 'DEN', zone: 'America/Denver' },
+ { id: 'los-angeles', label: 'Los Angeles (PST/PDT)', shortLabel: 'LAX', zone: 'America/Los_Angeles' },
+ { id: 'toronto', label: 'Toronto (EST/EDT)', shortLabel: 'TOR', zone: 'America/Toronto' },
+ { id: 'vancouver', label: 'Vancouver (PST/PDT)', shortLabel: 'VAN', zone: 'America/Vancouver' },
+ { id: 'mexico-city', label: 'Mexico City (CST)', shortLabel: 'MEX', zone: 'America/Mexico_City' },
+ { id: 'sao-paulo', label: 'São Paulo (BRT)', shortLabel: 'SAO', zone: 'America/Sao_Paulo' },
+ { id: 'buenos-aires', label: 'Buenos Aires (ART)', shortLabel: 'BUE', zone: 'America/Buenos_Aires' },
+
+ // Europe
+ { id: 'london', label: 'London (GMT/BST)', shortLabel: 'LDN', zone: 'Europe/London' },
+ { id: 'paris', label: 'Paris (CET/CEST)', shortLabel: 'PAR', zone: 'Europe/Paris' },
+ { id: 'berlin', label: 'Berlin (CET/CEST)', shortLabel: 'BER', zone: 'Europe/Berlin' },
+ { id: 'amsterdam', label: 'Amsterdam (CET/CEST)', shortLabel: 'AMS', zone: 'Europe/Amsterdam' },
+ { id: 'zurich', label: 'Zurich (CET/CEST)', shortLabel: 'ZRH', zone: 'Europe/Zurich' },
+ { id: 'moscow', label: 'Moscow (MSK)', shortLabel: 'MOW', zone: 'Europe/Moscow' },
+ { id: 'istanbul', label: 'Istanbul (TRT)', shortLabel: 'IST', zone: 'Europe/Istanbul' },
+
+ // Asia
+ { id: 'dubai', label: 'Dubai (GST)', shortLabel: 'DXB', zone: 'Asia/Dubai' },
+ { id: 'mumbai', label: 'Mumbai (IST)', shortLabel: 'BOM', zone: 'Asia/Kolkata' },
+ { id: 'delhi', label: 'Delhi (IST)', shortLabel: 'DEL', zone: 'Asia/Kolkata' },
+ { id: 'bangkok', label: 'Bangkok (ICT)', shortLabel: 'BKK', zone: 'Asia/Bangkok' },
+ { id: 'singapore', label: 'Singapore (SGT)', shortLabel: 'SIN', zone: 'Asia/Singapore' },
+ { id: 'hong-kong', label: 'Hong Kong (HKT)', shortLabel: 'HKG', zone: 'Asia/Hong_Kong' },
+ { id: 'shanghai', label: 'Shanghai (CST)', shortLabel: 'SHA', zone: 'Asia/Shanghai' },
+ { id: 'tokyo', label: 'Tokyo (JST)', shortLabel: 'TYO', zone: 'Asia/Tokyo' },
+ { id: 'seoul', label: 'Seoul (KST)', shortLabel: 'SEL', zone: 'Asia/Seoul' },
+
+ // Pacific & Oceania
+ { id: 'sydney', label: 'Sydney (AEST/AEDT)', shortLabel: 'SYD', zone: 'Australia/Sydney' },
+ { id: 'melbourne', label: 'Melbourne (AEST/AEDT)', shortLabel: 'MEL', zone: 'Australia/Melbourne' },
+ { id: 'perth', label: 'Perth (AWST)', shortLabel: 'PER', zone: 'Australia/Perth' },
+ { id: 'auckland', label: 'Auckland (NZST/NZDT)', shortLabel: 'AKL', zone: 'Pacific/Auckland' },
+
+ // Africa & Middle East
+ { id: 'johannesburg', label: 'Johannesburg (SAST)', shortLabel: 'JNB', zone: 'Africa/Johannesburg' },
+ { id: 'cairo', label: 'Cairo (EET)', shortLabel: 'CAI', zone: 'Africa/Cairo' },
+ { id: 'lagos', label: 'Lagos (WAT)', shortLabel: 'LOS', zone: 'Africa/Lagos' },
+ { id: 'riyadh', label: 'Riyadh (AST)', shortLabel: 'RUH', zone: 'Asia/Riyadh' },
+ { id: 'tel-aviv', label: 'Tel Aviv (IST)', shortLabel: 'TLV', zone: 'Asia/Jerusalem' },
+];
+
+const DEFAULT_STORAGE_KEY = 'fincept_default_timezone';
+const SESSION_STORAGE_KEY = 'fincept_timezone';
+const DEFAULT_TIMEZONE_ID = 'local';
+
+// ============================================================================
+// Context Definition
+// ============================================================================
+
+interface TimezoneContextValue {
+ /** Default timezone (persisted, used by nav bar) */
+ defaultTimezone: TimezoneOption;
+ /** Session timezone (per-session, used by dashboard widgets) */
+ timezone: TimezoneOption;
+ /** All available timezone options */
+ options: TimezoneOption[];
+ /** Update the default timezone (persisted in settings) */
+ setDefaultTimezone: (timezoneId: string) => void;
+ /** Update the session timezone (for dashboard widgets) */
+ setTimezone: (timezoneId: string) => void;
+ /** Format a Date object according to a specific timezone */
+ formatTime: (date: Date, options?: Intl.DateTimeFormatOptions) => string;
+ /** Format a Date object according to the default timezone */
+ formatTimeWithDefault: (date: Date, options?: Intl.DateTimeFormatOptions) => string;
+ /** Format a Date object to a short time string (HH:MM:SS) */
+ formatTimeShort: (date: Date) => string;
+ /** Get the current time formatted in the selected timezone */
+ getCurrentTimeFormatted: () => string;
+}
+
+const TimezoneContext = createContext<TimezoneContextValue | undefined>(undefined);
+
+// ============================================================================
+// Provider Component
+// ============================================================================
+
+interface TimezoneProviderProps {
+ children: ReactNode;
+}
+
+export const TimezoneProvider: React.FC<TimezoneProviderProps> = ({ children }) => {
+ // Initialize default timezone from localStorage
+ const [defaultTimezoneId, setDefaultTimezoneId] = useState<string>(() => {
+ try {
+ const stored = localStorage.getItem(DEFAULT_STORAGE_KEY);
+ if (stored && TIMEZONE_OPTIONS.find(tz => tz.id === stored)) {
+ return stored;
+ }
+ } catch (e) {
+ console.warn('[TimezoneContext] Failed to read default timezone from localStorage:', e);
+ }
+ return DEFAULT_TIMEZONE_ID;
+ });
+
+ // Initialize session timezone (can be same as default or different)
+ const [sessionTimezoneId, setSessionTimezoneId] = useState<string>(() => {
+ try {
+ const stored = localStorage.getItem(SESSION_STORAGE_KEY);
+ if (stored && TIMEZONE_OPTIONS.find(tz => tz.id === stored)) {
+ return stored;
+ }
+ // Fall back to default timezone
+ const defaultStored = localStorage.getItem(DEFAULT_STORAGE_KEY);
+ if (defaultStored && TIMEZONE_OPTIONS.find(tz => tz.id === defaultStored)) {
+ return defaultStored;
+ }
+ } catch (e) {
+ console.warn('[TimezoneContext] Failed to read session timezone from localStorage:', e);
+ }
+ return DEFAULT_TIMEZONE_ID;
+ });
+
+ // Get the full timezone option objects
+ const defaultTimezone = TIMEZONE_OPTIONS.find(tz => tz.id === defaultTimezoneId) || TIMEZONE_OPTIONS[0];
+ const timezone = TIMEZONE_OPTIONS.find(tz => tz.id === sessionTimezoneId) || TIMEZONE_OPTIONS[0];
+
+ // Persist default timezone to localStorage when it changes
+ useEffect(() => {
+ try {
+ localStorage.setItem(DEFAULT_STORAGE_KEY, defaultTimezoneId);
+ } catch (e) {
+ console.warn('[TimezoneContext] Failed to save default timezone to localStorage:', e);
+ }
+ }, [defaultTimezoneId]);
+
+ // Persist session timezone to localStorage when it changes
+ useEffect(() => {
+ try {
+ localStorage.setItem(SESSION_STORAGE_KEY, sessionTimezoneId);
+ } catch (e) {
+ console.warn('[TimezoneContext] Failed to save session timezone to localStorage:', e);
+ }
+ }, [sessionTimezoneId]);
+
+ // Set default timezone by ID (used in Settings)
+ const setDefaultTimezone = useCallback((id: string) => {
+ if (TIMEZONE_OPTIONS.find(tz => tz.id === id)) {
+ setDefaultTimezoneId(id);
+ } else {
+ console.warn(`[TimezoneContext] Unknown timezone ID: ${id}`);
+ }
+ }, []);
+
+ // Set session timezone by ID (used in dashboard widgets)
+ const setTimezone = useCallback((id: string) => {
+ if (TIMEZONE_OPTIONS.find(tz => tz.id === id)) {
+ setSessionTimezoneId(id);
+ } else {
+ console.warn(`[TimezoneContext] Unknown timezone ID: ${id}`);
+ }
+ }, []);
+
+ // Format a date according to the session timezone
+ const formatTime = useCallback((date: Date, options?: Intl.DateTimeFormatOptions): string => {
+ const defaultOptions: Intl.DateTimeFormatOptions = {
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ hour12: false,
+ ...options,
+ };
+
+ // Add timezone if not using local
+ if (timezone.zone) {
+ defaultOptions.timeZone = timezone.zone;
+ }
+
+ try {
+ return new Intl.DateTimeFormat('en-US', defaultOptions).format(date);
+ } catch (e) {
+ console.error('[TimezoneContext] Format error:', e);
+ return date.toLocaleTimeString('en-US', { hour12: false });
+ }
+ }, [timezone]);
+
+ // Format a date according to the DEFAULT timezone (for nav bar)
+ const formatTimeWithDefault = useCallback((date: Date, options?: Intl.DateTimeFormatOptions): string => {
+ const defaultOptions: Intl.DateTimeFormatOptions = {
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ hour12: false,
+ ...options,
+ };
+
+ // Add timezone if not using local
+ if (defaultTimezone.zone) {
+ defaultOptions.timeZone = defaultTimezone.zone;
+ }
+
+ try {
+ return new Intl.DateTimeFormat('en-US', defaultOptions).format(date);
+ } catch (e) {
+ console.error('[TimezoneContext] Format error:', e);
+ return date.toLocaleTimeString('en-US', { hour12: false });
+ }
+ }, [defaultTimezone]);
+
+ // Short format: HH:MM:SS
+ const formatTimeShort = useCallback((date: Date): string => {
+ return formatTime(date, {
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ hour12: false,
+ });
+ }, [formatTime]);
+
+ // Get current time formatted
+ const getCurrentTimeFormatted = useCallback((): string => {
+ return formatTimeShort(new Date());
+ }, [formatTimeShort]);
+
+ const value: TimezoneContextValue = {
+ defaultTimezone,
+ timezone,
+ options: TIMEZONE_OPTIONS,
+ setDefaultTimezone,
+ setTimezone,
+ formatTime,
+ formatTimeWithDefault,
+ formatTimeShort,
+ getCurrentTimeFormatted,
+ };
+
+ return (
+ <TimezoneContext.Provider value={value}>
+ {children}
+ </TimezoneContext.Provider>
+ );
+};
+
+// ============================================================================
+// Hook
+// ============================================================================
+
+/**
+ * Hook to access timezone context.
+ * Must be used within a TimezoneProvider.
+ */
+export const useTimezone = (): TimezoneContextValue => {
+ const context = useContext(TimezoneContext);
+ if (!context) {
+ throw new Error('useTimezone must be used within a TimezoneProvider');
+ }
+ return context;
+};
+
+// ============================================================================
+// Utility Hook: useCurrentTime (for dashboard widgets)
+// ============================================================================
+
+/**
+ * Hook that provides a ticking current time, automatically formatted
+ * according to the SESSION timezone (for dashboard widgets).
+ *
+ * @param refreshInterval - Update interval in milliseconds (default: 1000)
+ * @returns Object with currentTime (Date) and formattedTime (string)
+ */
+export const useCurrentTime = (refreshInterval: number = 1000) => {
+ const [currentTime, setCurrentTime] = useState(new Date());
+ const { formatTimeShort, timezone } = useTimezone();
+
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setCurrentTime(new Date());
+ }, refreshInterval);
+
+ return () => clearInterval(timer);
+ }, [refreshInterval]);
+
+ return {
+ currentTime,
+ formattedTime: formatTimeShort(currentTime),
+ timezone,
+ };
+};
+
+// ============================================================================
+// Utility Hook: useDefaultTime (for navigation bar)
+// ============================================================================
+
+/**
+ * Hook that provides a ticking current time, automatically formatted
+ * according to the DEFAULT timezone (for navigation bar).
+ *
+ * @param refreshInterval - Update interval in milliseconds (default: 1000)
+ * @returns Object with currentTime (Date), formattedTime (string), and timezone
+ */
+export const useDefaultTime = (refreshInterval: number = 1000) => {
+ const [currentTime, setCurrentTime] = useState(new Date());
+ const { formatTimeWithDefault, defaultTimezone } = useTimezone();
+
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setCurrentTime(new Date());
+ }, refreshInterval);
+
+ return () => clearInterval(timer);
+ }, [refreshInterval]);
+
+ return {
+ currentTime,
+ formattedTime: formatTimeWithDefault(currentTime),
+ timezone: defaultTimezone,
+ };
+};
+
+export default TimezoneContext;
+
diff --git a/fincept-terminal-desktop/src/services/sqliteService.original.ts b/fincept-terminal-desktop/src/services/sqliteService.original.ts
new file mode 100644
index 000000000..b976db25c
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/sqliteService.original.ts
@@ -0,0 +1,2444 @@
+/**
+ * SQLite Database Service
+ * Uses Tauri SQL plugin for database operations
+ */
+
+import Database from '@tauri-apps/plugin-sql';
+import { sqliteLogger } from './loggerService';
+
+// Type definitions
+export interface Credential {
+ id?: number;
+ service_name: string;
+ username: string;
+ password: string;
+ api_key?: string;
+ api_secret?: string;
+ additional_data?: string;
+ created_at?: string;
+ updated_at?: string;
+}
+
+// Predefined API Keys structure
+export interface ApiKeys {
+ FRED_API_KEY?: string;
+ POLYGON_API_KEY?: string;
+ ALPHA_VANTAGE_API_KEY?: string;
+ OPENAI_API_KEY?: string;
+ ANTHROPIC_API_KEY?: string;
+ COINGECKO_API_KEY?: string;
+ NASDAQ_API_KEY?: string;
+ FINANCIAL_MODELING_PREP_API_KEY?: string;
+ [key: string]: string | undefined;
+}
+
+export const PREDEFINED_API_KEYS = [
+ { key: 'FRED_API_KEY', label: 'FRED API Key', description: 'Federal Reserve Economic Data' },
+ { key: 'POLYGON_API_KEY', label: 'Polygon.io API Key', description: 'Stock market data' },
+ { key: 'ALPHA_VANTAGE_API_KEY', label: 'Alpha Vantage API Key', description: 'Stock & crypto data' },
+ { key: 'OPENAI_API_KEY', label: 'OpenAI API Key', description: 'GPT models' },
+ { key: 'ANTHROPIC_API_KEY', label: 'Anthropic API Key', description: 'Claude models' },
+ { key: 'COINGECKO_API_KEY', label: 'CoinGecko API Key', description: 'Cryptocurrency data' },
+ { key: 'NASDAQ_API_KEY', label: 'NASDAQ API Key', description: 'NASDAQ market data' },
+ { key: 'FINANCIAL_MODELING_PREP_API_KEY', label: 'Financial Modeling Prep', description: 'Financial statements & ratios' },
+] as const;
+
+export interface Setting {
+ setting_key: string;
+ setting_value: string;
+ category?: string;
+ updated_at?: string;
+}
+
+export interface LLMConfig {
+ provider: string;
+ api_key?: string;
+ base_url?: string;
+ model: string;
+ is_active: boolean;
+ created_at?: string;
+ updated_at?: string;
+}
+
+export interface LLMGlobalSettings {
+ temperature: number;
+ max_tokens: number;
+ system_prompt: string;
+}
+
+export interface ChatSession {
+ session_uuid: string;
+ title: string;
+ message_count: number;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface ChatMessage {
+ id: string;
+ session_uuid: string;
+ role: 'user' | 'assistant';
+ content: string;
+ timestamp: string;
+ provider?: string;
+ model?: string;
+ tokens_used?: number;
+}
+
+export interface DataSource {
+ id: string;
+ alias: string;
+ display_name: string;
+ description?: string;
+ type: 'websocket' | 'rest_api';
+ provider: string;
+ category?: string;
+ config: string;
+ enabled: boolean;
+ tags?: string;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface WSProviderConfig {
+ 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;
+}
+
+export interface MCPServer {
+ id: string;
+ name: string;
+ description: string;
+ command: string;
+ args: string;
+ env?: string | null;
+ category: string;
+ icon: string;
+ enabled: boolean;
+ auto_start: boolean;
+ status: string;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface RecordedContext {
+ id: string;
+ tab_name: string;
+ data_type: string;
+ label?: string;
+ raw_data: string;
+ metadata?: string;
+ data_size: number;
+ created_at: string;
+ tags?: string;
+}
+
+export interface RecordingSession {
+ id: string;
+ tab_name: string;
+ is_active: boolean;
+ auto_record: boolean;
+ filters?: string;
+ started_at: string;
+ ended_at?: string;
+}
+
+export interface ChatContextLink {
+ chat_session_uuid: string;
+ context_id: string;
+ added_at: string;
+ is_active: boolean;
+}
+
+export interface BacktestingProvider {
+ id: string;
+ name: string;
+ adapter_type: string;
+ config: string;
+ enabled: boolean;
+ is_active: boolean;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface BacktestingStrategy {
+ id: string;
+ name: string;
+ description?: string;
+ version: string;
+ author?: string;
+ provider_type: string;
+ strategy_type: 'code' | 'visual' | 'template';
+ strategy_definition: string;
+ tags?: string;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface BacktestRun {
+ id: string;
+ strategy_id?: string;
+ provider_name: string;
+ config: string;
+ results?: string;
+ status: 'completed' | 'failed' | 'running' | 'cancelled';
+ performance_metrics?: string;
+ error_message?: string;
+ created_at: string;
+ completed_at?: string;
+ duration_seconds?: number;
+}
+
+export interface OptimizationRun {
+ id: string;
+ strategy_id?: string;
+ provider_name: string;
+ parameter_grid: string;
+ objective: string;
+ best_parameters?: string;
+ best_result?: string;
+ all_results?: string;
+ iterations?: number;
+ status: 'completed' | 'failed' | 'running' | 'cancelled';
+ error_message?: string;
+ created_at: string;
+ completed_at?: string;
+ duration_seconds?: number;
+}
+
+class SQLiteService {
+ private db: Database | null = null;
+ private initPromise: Promise<void> | null = null;
+
+ /**
+ * Initialize database connection and schema
+ */
+ async initialize(): Promise<void> {
+ if (this.initPromise) {
+ return this.initPromise;
+ }
+
+ this.initPromise = this._initializeDatabase();
+ return this.initPromise;
+ }
+
+ private async _initializeDatabase(): Promise<void> {
+ try {
+ sqliteLogger.info('Initializing database...');
+
+ // Connect to SQLite database
+ this.db = await Database.load('sqlite:fincept_terminal.db');
+
+ sqliteLogger.debug('Creating schema...');
+ await this.createSchema();
+
+ sqliteLogger.info('Database initialized successfully');
+ } catch (error) {
+ sqliteLogger.error('Failed to initialize:', error);
+ throw error;
+ }
+ }
+
+ private async createSchema(): Promise<void> {
+ if (!this.db) throw new Error('Database not connected');
+
+ const statements = [
+ // Credentials table
+ `CREATE TABLE IF NOT EXISTS credentials (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ service_name TEXT NOT NULL UNIQUE,
+ username TEXT,
+ password TEXT,
+ api_key TEXT,
+ api_secret TEXT,
+ additional_data TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // Settings table
+ `CREATE TABLE IF NOT EXISTS settings (
+ setting_key TEXT PRIMARY KEY,
+ setting_value TEXT NOT NULL,
+ category TEXT,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // LLM configurations table
+ `CREATE TABLE IF NOT EXISTS llm_configs (
+ provider TEXT PRIMARY KEY,
+ api_key TEXT,
+ base_url TEXT,
+ model TEXT NOT NULL,
+ is_active INTEGER DEFAULT 0,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // LLM global settings table
+ `CREATE TABLE IF NOT EXISTS llm_global_settings (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ temperature REAL DEFAULT 0.7,
+ max_tokens INTEGER DEFAULT 2000,
+ system_prompt TEXT DEFAULT ''
+ )`,
+
+ // Chat sessions table
+ `CREATE TABLE IF NOT EXISTS chat_sessions (
+ session_uuid TEXT PRIMARY KEY,
+ title TEXT NOT NULL,
+ message_count INTEGER DEFAULT 0,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // Chat messages table
+ `CREATE TABLE IF NOT EXISTS chat_messages (
+ id TEXT PRIMARY KEY,
+ session_uuid TEXT NOT NULL,
+ role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),
+ content TEXT NOT NULL,
+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP,
+ provider TEXT,
+ model TEXT,
+ tokens_used INTEGER,
+ FOREIGN KEY (session_uuid) REFERENCES chat_sessions(session_uuid) ON DELETE CASCADE
+ )`,
+
+ // Data sources table
+ `CREATE TABLE IF NOT EXISTS data_sources (
+ id TEXT PRIMARY KEY,
+ alias TEXT NOT NULL UNIQUE,
+ display_name TEXT NOT NULL,
+ description TEXT,
+ type TEXT NOT NULL CHECK (type IN ('websocket', 'rest_api')),
+ provider TEXT NOT NULL,
+ category TEXT,
+ config TEXT NOT NULL,
+ enabled INTEGER DEFAULT 1,
+ tags TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // WebSocket provider configs table
+ `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 CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // Paper trading portfolios table
+ `CREATE TABLE IF NOT EXISTS paper_trading_portfolios (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ provider TEXT NOT NULL,
+ initial_balance REAL NOT NULL DEFAULT 100000,
+ current_balance REAL NOT NULL,
+ currency TEXT DEFAULT 'USD',
+ margin_mode TEXT DEFAULT 'cross',
+ leverage REAL DEFAULT 1,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // Paper trading positions table
+ `CREATE TABLE IF NOT EXISTS paper_trading_positions (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ side TEXT NOT NULL CHECK (side IN ('long', 'short')),
+ entry_price REAL NOT NULL,
+ quantity REAL NOT NULL,
+ position_value REAL,
+ current_price REAL,
+ unrealized_pnl REAL,
+ realized_pnl REAL DEFAULT 0,
+ leverage REAL DEFAULT 1,
+ margin_mode TEXT DEFAULT 'cross',
+ liquidation_price REAL,
+ opened_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ closed_at TEXT,
+ status TEXT NOT NULL CHECK (status IN ('open', 'closed')),
+ FOREIGN KEY (portfolio_id) REFERENCES paper_trading_portfolios(id) ON DELETE CASCADE
+ )`,
+
+ // Paper trading orders table
+ `CREATE TABLE IF NOT EXISTS paper_trading_orders (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ side TEXT NOT NULL CHECK (side IN ('buy', 'sell')),
+ type TEXT NOT NULL CHECK (type IN ('market', 'limit', 'stop_market', 'stop_limit')),
+ quantity REAL NOT NULL,
+ price REAL,
+ stop_price REAL,
+ filled_quantity REAL DEFAULT 0,
+ avg_fill_price REAL,
+ status TEXT NOT NULL CHECK (status IN ('pending', 'filled', 'partial', 'cancelled', 'rejected', 'triggered')),
+ time_in_force TEXT DEFAULT 'GTC',
+ post_only INTEGER DEFAULT 0,
+ reduce_only INTEGER DEFAULT 0,
+ trailing_percent REAL,
+ trailing_amount REAL,
+ iceberg_qty REAL,
+ leverage REAL,
+ margin_mode TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ filled_at TEXT,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (portfolio_id) REFERENCES paper_trading_portfolios(id) ON DELETE CASCADE
+ )`,
+
+ // Paper trading trades table
+ `CREATE TABLE IF NOT EXISTS paper_trading_trades (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ order_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ side TEXT NOT NULL,
+ price REAL NOT NULL,
+ quantity REAL NOT NULL,
+ fee REAL DEFAULT 0,
+ fee_rate REAL DEFAULT 0,
+ is_maker INTEGER DEFAULT 0,
+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (portfolio_id) REFERENCES paper_trading_portfolios(id) ON DELETE CASCADE,
+ FOREIGN KEY (order_id) REFERENCES paper_trading_orders(id) ON DELETE CASCADE
+ )`,
+
+ // Indexes for paper trading tables
+ `CREATE INDEX IF NOT EXISTS idx_paper_positions_portfolio ON paper_trading_positions(portfolio_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_paper_positions_status ON paper_trading_positions(status)`,
+ `CREATE INDEX IF NOT EXISTS idx_paper_orders_portfolio ON paper_trading_orders(portfolio_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_paper_orders_status ON paper_trading_orders(status)`,
+ `CREATE INDEX IF NOT EXISTS idx_paper_trades_portfolio ON paper_trading_trades(portfolio_id)`,
+
+ // MCP servers table
+ `CREATE TABLE IF NOT EXISTS mcp_servers (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ description TEXT,
+ command TEXT NOT NULL,
+ args TEXT,
+ env TEXT,
+ category TEXT,
+ icon TEXT,
+ enabled INTEGER DEFAULT 1,
+ auto_start INTEGER DEFAULT 0,
+ status TEXT DEFAULT 'stopped',
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // MCP tools table
+ `CREATE TABLE IF NOT EXISTS mcp_tools (
+ id TEXT PRIMARY KEY,
+ server_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ description TEXT,
+ input_schema TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (server_id) REFERENCES mcp_servers(id) ON DELETE CASCADE
+ )`,
+
+ // MCP tool usage logs table
+ `CREATE TABLE IF NOT EXISTS mcp_tool_usage_logs (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ server_id TEXT NOT NULL,
+ tool_name TEXT NOT NULL,
+ args TEXT,
+ result TEXT,
+ success INTEGER,
+ execution_time INTEGER,
+ error TEXT,
+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // Market data cache table
+ `CREATE TABLE IF NOT EXISTS market_data_cache (
+ symbol TEXT NOT NULL,
+ category TEXT NOT NULL,
+ quote_data TEXT NOT NULL,
+ cached_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (symbol, category)
+ )`,
+
+ // Data source connections table
+ `CREATE TABLE IF NOT EXISTS data_source_connections (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ type TEXT NOT NULL,
+ category TEXT NOT NULL,
+ config TEXT NOT NULL,
+ status TEXT NOT NULL,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ last_tested TEXT,
+ error_message TEXT
+ )`,
+
+ // Forum cache tables
+ `CREATE TABLE IF NOT EXISTS forum_categories_cache (
+ id INTEGER PRIMARY KEY,
+ data TEXT NOT NULL,
+ cached_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ `CREATE TABLE IF NOT EXISTS forum_posts_cache (
+ cache_key TEXT PRIMARY KEY,
+ category_id INTEGER,
+ sort_by TEXT,
+ data TEXT NOT NULL,
+ cached_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ `CREATE TABLE IF NOT EXISTS forum_stats_cache (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ data TEXT NOT NULL,
+ cached_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ `CREATE TABLE IF NOT EXISTS forum_post_details_cache (
+ post_uuid TEXT PRIMARY KEY,
+ data TEXT NOT NULL,
+ comments_data TEXT NOT NULL,
+ cached_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // Context Recording tables
+ `CREATE TABLE IF NOT EXISTS recorded_contexts (
+ id TEXT PRIMARY KEY,
+ tab_name TEXT NOT NULL,
+ data_type TEXT NOT NULL,
+ label TEXT,
+ raw_data TEXT NOT NULL,
+ metadata TEXT,
+ data_size INTEGER,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ tags TEXT
+ )`,
+
+ `CREATE INDEX IF NOT EXISTS idx_recorded_contexts_tab ON recorded_contexts(tab_name)`,
+ `CREATE INDEX IF NOT EXISTS idx_recorded_contexts_type ON recorded_contexts(data_type)`,
+ `CREATE INDEX IF NOT EXISTS idx_recorded_contexts_created ON recorded_contexts(created_at DESC)`,
+
+ `CREATE TABLE IF NOT EXISTS recording_sessions (
+ id TEXT PRIMARY KEY,
+ tab_name TEXT NOT NULL,
+ is_active INTEGER DEFAULT 1,
+ auto_record INTEGER DEFAULT 0,
+ filters TEXT,
+ started_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ ended_at TEXT
+ )`,
+
+ `CREATE TABLE IF NOT EXISTS chat_context_links (
+ chat_session_uuid TEXT NOT NULL,
+ context_id TEXT NOT NULL,
+ added_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ is_active INTEGER DEFAULT 1,
+ PRIMARY KEY (chat_session_uuid, context_id),
+ FOREIGN KEY(chat_session_uuid) REFERENCES chat_sessions(session_uuid) ON DELETE CASCADE,
+ FOREIGN KEY(context_id) REFERENCES recorded_contexts(id) ON DELETE CASCADE
+ )`,
+
+ `CREATE TABLE IF NOT EXISTS report_templates (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ description TEXT,
+ template_data TEXT NOT NULL,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // Backtesting providers table
+ `CREATE TABLE IF NOT EXISTS backtesting_providers (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL UNIQUE,
+ adapter_type TEXT NOT NULL,
+ config TEXT NOT NULL,
+ enabled INTEGER DEFAULT 1,
+ is_active INTEGER DEFAULT 0,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // Backtesting strategies table
+ `CREATE TABLE IF NOT EXISTS backtesting_strategies (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ description TEXT,
+ version TEXT DEFAULT '1.0.0',
+ author TEXT,
+ provider_type TEXT NOT NULL,
+ strategy_type TEXT NOT NULL CHECK (strategy_type IN ('code', 'visual', 'template')),
+ strategy_definition TEXT NOT NULL,
+ tags TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ `CREATE INDEX IF NOT EXISTS idx_strategies_provider ON backtesting_strategies(provider_type)`,
+ `CREATE INDEX IF NOT EXISTS idx_strategies_type ON backtesting_strategies(strategy_type)`,
+
+ // Backtest runs table
+ `CREATE TABLE IF NOT EXISTS backtest_runs (
+ id TEXT PRIMARY KEY,
+ strategy_id TEXT,
+ provider_name TEXT NOT NULL,
+ config TEXT NOT NULL,
+ results TEXT,
+ status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'running', 'cancelled')),
+ performance_metrics TEXT,
+ error_message TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ completed_at TEXT,
+ duration_seconds INTEGER,
+ FOREIGN KEY(strategy_id) REFERENCES backtesting_strategies(id) ON DELETE SET NULL
+ )`,
+
+ `CREATE INDEX IF NOT EXISTS idx_backtest_runs_strategy ON backtest_runs(strategy_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_backtest_runs_provider ON backtest_runs(provider_name)`,
+ `CREATE INDEX IF NOT EXISTS idx_backtest_runs_status ON backtest_runs(status)`,
+ `CREATE INDEX IF NOT EXISTS idx_backtest_runs_created ON backtest_runs(created_at DESC)`,
+
+ // Optimization runs table
+ `CREATE TABLE IF NOT EXISTS optimization_runs (
+ id TEXT PRIMARY KEY,
+ strategy_id TEXT,
+ provider_name TEXT NOT NULL,
+ parameter_grid TEXT NOT NULL,
+ objective TEXT NOT NULL,
+ best_parameters TEXT,
+ best_result TEXT,
+ all_results TEXT,
+ iterations INTEGER,
+ status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'running', 'cancelled')),
+ error_message TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ completed_at TEXT,
+ duration_seconds INTEGER,
+ FOREIGN KEY(strategy_id) REFERENCES backtesting_strategies(id) ON DELETE SET NULL
+ )`,
+
+ `CREATE INDEX IF NOT EXISTS idx_optimization_runs_strategy ON optimization_runs(strategy_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_optimization_runs_provider ON optimization_runs(provider_name)`,
+ `CREATE INDEX IF NOT EXISTS idx_optimization_runs_status ON optimization_runs(status)`,
+
+ // Insert default LLM global settings
+ `INSERT OR IGNORE INTO llm_global_settings (id, temperature, max_tokens, system_prompt)
+ VALUES (1, 0.7, 2000, 'You are a helpful AI assistant specialized in financial analysis and market data.')`,
+ ];
+
+ for (const sql of statements) {
+ try {
+ await this.db.execute(sql);
+ } catch (error: any) {
+ // Ignore "duplicate column" errors from ALTER TABLE
+ if (!error.message?.includes('duplicate column')) {
+ throw error;
+ }
+ }
+ }
+
+ // Update existing positions to populate position_value
+ try {
+ await this.db.execute(`
+ UPDATE paper_trading_positions
+ SET position_value = entry_price * quantity
+ WHERE position_value IS NULL
+ `);
+ } catch (error) {
+ sqliteLogger.error('Failed to populate position_value:', error);
+ }
+ }
+
+ // =========================
+ // CREDENTIALS METHODS
+ // =========================
+
+ async saveCredential(credential: Omit<Credential, 'id' | 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO credentials (service_name, username, password, api_key, api_secret, additional_data, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP)`,
+ [
+ credential.service_name,
+ credential.username || null,
+ credential.password || null,
+ credential.api_key || null,
+ credential.api_secret || null,
+ credential.additional_data || null,
+ ]
+ );
+ return { success: true, message: 'Credential saved successfully' };
+ } catch (error) {
+ sqliteLogger.error('Failed to save credential:', error);
+ return { success: false, message: 'Failed to save credential' };
+ }
+ }
+
+ async getCredentials(): Promise<Credential[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<Credential[]>('SELECT * FROM credentials ORDER BY service_name');
+ }
+
+ async getCredentialByService(serviceName: string): Promise<Credential | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<Credential[]>(
+ 'SELECT * FROM credentials WHERE service_name = $1',
+ [serviceName]
+ );
+ return results[0] || null;
+ }
+
+ async getApiKey(serviceName: string): Promise<string | null> {
+ // Use settings table for predefined API keys
+ const keyName = serviceName.toUpperCase().replace(/[^A-Z0-9]/g, '_') + '_API_KEY';
+ return await this.getSetting(keyName);
+ }
+
+ async setApiKey(keyName: string, value: string): Promise<void> {
+ await this.saveSetting(keyName, value, 'api_keys');
+ }
+
+ async getAllApiKeys(): Promise<ApiKeys> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<Setting[]>(
+ "SELECT * FROM settings WHERE category = 'api_keys'"
+ );
+
+ const keys: ApiKeys = {};
+ results.forEach(row => {
+ keys[row.setting_key] = row.setting_value;
+ });
+ return keys;
+ }
+
+ async deleteCredential(id: number): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+ await this.db!.execute('DELETE FROM credentials WHERE id = $1', [id]);
+ return { success: true, message: 'Credential deleted successfully' };
+ } catch (error) {
+ sqliteLogger.error('Failed to delete credential:', error);
+ return { success: false, message: 'Failed to delete credential' };
+ }
+ }
+
+ // =========================
+ // SETTINGS METHODS
+ // =========================
+
+ async saveSetting(key: string, value: string, category?: string): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO settings (setting_key, setting_value, category, updated_at)
+ VALUES ($1, $2, $3, CURRENT_TIMESTAMP)`,
+ [key, value, category || null]
+ );
+ }
+
+ async getSetting(key: string): Promise<string | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<Setting[]>(
+ 'SELECT * FROM settings WHERE setting_key = $1',
+ [key]
+ );
+ return results[0]?.setting_value || null;
+ }
+
+ async getSettingsByCategory(category: string): Promise<Setting[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<Setting[]>(
+ 'SELECT * FROM settings WHERE category = $1',
+ [category]
+ );
+ }
+
+ async getAllSettings(): Promise<Setting[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<Setting[]>('SELECT * FROM settings');
+ }
+
+ // =========================
+ // LLM METHODS
+ // =========================
+
+ async getLLMConfigs(): Promise<LLMConfig[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<LLMConfig[]>('SELECT * FROM llm_configs ORDER BY provider');
+ }
+
+ async getLLMConfig(provider: string): Promise<LLMConfig | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<LLMConfig[]>(
+ 'SELECT * FROM llm_configs WHERE provider = $1',
+ [provider]
+ );
+ return results[0] || null;
+ }
+
+ async getActiveLLMConfig(): Promise<LLMConfig | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<LLMConfig[]>(
+ 'SELECT * FROM llm_configs WHERE is_active = 1 LIMIT 1'
+ );
+ return results[0] || null;
+ }
+
+ async saveLLMConfig(config: Omit<LLMConfig, 'created_at' | 'updated_at'>): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO llm_configs (provider, api_key, base_url, model, is_active, updated_at)
+ VALUES ($1, $2, $3, $4, $5, CURRENT_TIMESTAMP)`,
+ [
+ config.provider,
+ config.api_key || null,
+ config.base_url || null,
+ config.model,
+ config.is_active ? 1 : 0,
+ ]
+ );
+ }
+
+ async setActiveLLMProvider(provider: string): Promise<void> {
+ await this.ensureInitialized();
+
+ // Deactivate all
+ await this.db!.execute('UPDATE llm_configs SET is_active = 0');
+
+ // Activate the selected one
+ await this.db!.execute(
+ 'UPDATE llm_configs SET is_active = 1 WHERE provider = $1',
+ [provider]
+ );
+ }
+
+ async ensureDefaultLLMConfigs(): Promise<void> {
+ await this.ensureInitialized();
+
+ const configs = await this.getLLMConfigs();
+
+ // If no configs exist, create defaults
+ if (configs.length === 0) {
+ const defaultConfigs = [
+ { provider: 'ollama', model: 'llama3.2:3b', base_url: 'http://localhost:11434', is_active: true },
+ { provider: 'openai', model: 'gpt-4o-mini', is_active: false },
+ { provider: 'anthropic', model: 'claude-sonnet-4', is_active: false },
+ { provider: 'google', model: 'gemini-2.0-flash-exp', is_active: false },
+ { provider: 'groq', model: 'llama-3.1-70b-versatile', is_active: false },
+ { provider: 'deepseek', model: 'deepseek-chat', base_url: 'https://api.deepseek.com', is_active: false },
+ { provider: 'xai', model: 'grok-beta', is_active: false },
+ { provider: 'cohere', model: 'command-r-plus', is_active: false },
+ { provider: 'mistral', model: 'mistral-large-latest', is_active: false },
+ { provider: 'together', model: 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo', is_active: false },
+ { provider: 'fireworks', model: 'accounts/fireworks/models/llama-v3p1-70b-instruct', is_active: false },
+ { provider: 'openrouter', model: 'meta-llama/llama-3.1-8b-instruct:free', base_url: 'https://openrouter.ai/api/v1', is_active: false },
+ ];
+
+ for (const config of defaultConfigs) {
+ await this.saveLLMConfig(config);
+ }
+
+ sqliteLogger.info('Initialized default LLM configurations');
+ }
+ }
+
+ async getLLMGlobalSettings(): Promise<LLMGlobalSettings> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<LLMGlobalSettings[]>(
+ 'SELECT temperature, max_tokens, system_prompt FROM llm_global_settings WHERE id = 1'
+ );
+
+ return results[0] || {
+ temperature: 0.7,
+ max_tokens: 2000,
+ system_prompt: 'You are a helpful AI assistant specialized in financial analysis and market data.',
+ };
+ }
+
+ async saveLLMGlobalSettings(settings: LLMGlobalSettings): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `UPDATE llm_global_settings
+ SET temperature = $1, max_tokens = $2, system_prompt = $3
+ WHERE id = 1`,
+ [settings.temperature, settings.max_tokens, settings.system_prompt]
+ );
+ }
+
+ // =========================
+ // CHAT METHODS
+ // =========================
+
+ async createChatSession(title: string): Promise<ChatSession> {
+ await this.ensureInitialized();
+
+ const sessionUuid = crypto.randomUUID();
+ const timestamp = new Date().toISOString();
+
+ await this.db!.execute(
+ `INSERT INTO chat_sessions (session_uuid, title, message_count, created_at, updated_at)
+ VALUES ($1, $2, 0, $3, $4)`,
+ [sessionUuid, title, timestamp, timestamp]
+ );
+
+ // Return the full session object
+ return {
+ session_uuid: sessionUuid,
+ title: title,
+ message_count: 0,
+ created_at: timestamp,
+ updated_at: timestamp
+ };
+ }
+
+ async getChatSessions(limit: number = 50): Promise<ChatSession[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<ChatSession[]>(
+ `SELECT * FROM chat_sessions ORDER BY updated_at DESC LIMIT $1`,
+ [limit]
+ );
+ }
+
+ async getChatSession(sessionUuid: string): Promise<ChatSession | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<ChatSession[]>(
+ 'SELECT * FROM chat_sessions WHERE session_uuid = $1',
+ [sessionUuid]
+ );
+ return results[0] || null;
+ }
+
+ async updateChatSessionTitle(sessionUuid: string, title: string): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `UPDATE chat_sessions SET title = $1, updated_at = CURRENT_TIMESTAMP WHERE session_uuid = $2`,
+ [title, sessionUuid]
+ );
+ }
+
+ async deleteChatSession(sessionUuid: string): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute('DELETE FROM chat_sessions WHERE session_uuid = $1', [sessionUuid]);
+ }
+
+ async addChatMessage(message: Omit<ChatMessage, 'id' | 'timestamp'>): Promise<ChatMessage> {
+ await this.ensureInitialized();
+
+ const messageId = crypto.randomUUID();
+ const timestamp = new Date().toISOString();
+
+ await this.db!.execute(
+ `INSERT INTO chat_messages (id, session_uuid, role, content, timestamp, provider, model, tokens_used)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
+ [
+ messageId,
+ message.session_uuid,
+ message.role,
+ message.content,
+ timestamp,
+ message.provider || null,
+ message.model || null,
+ message.tokens_used || null,
+ ]
+ );
+
+ // Update message count
+ await this.db!.execute(
+ `UPDATE chat_sessions
+ SET message_count = message_count + 1, updated_at = CURRENT_TIMESTAMP
+ WHERE session_uuid = $1`,
+ [message.session_uuid]
+ );
+
+ // Return the full message object
+ return {
+ id: messageId,
+ session_uuid: message.session_uuid,
+ role: message.role,
+ content: message.content,
+ timestamp: timestamp,
+ provider: message.provider,
+ model: message.model,
+ tokens_used: message.tokens_used,
+ };
+ }
+
+ async getChatMessages(sessionUuid: string): Promise<ChatMessage[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<ChatMessage[]>(
+ 'SELECT * FROM chat_messages WHERE session_uuid = $1 ORDER BY timestamp ASC',
+ [sessionUuid]
+ );
+ }
+
+ async deleteChatMessage(id: string): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute('DELETE FROM chat_messages WHERE id = $1', [id]);
+ }
+
+ async clearChatSessionMessages(sessionUuid: string): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute('DELETE FROM chat_messages WHERE session_uuid = $1', [sessionUuid]);
+ await this.db!.execute(
+ 'UPDATE chat_sessions SET message_count = 0, updated_at = CURRENT_TIMESTAMP WHERE session_uuid = $1',
+ [sessionUuid]
+ );
+ }
+
+ // =========================
+ // DATA SOURCES METHODS
+ // =========================
+
+ async saveDataSource(source: Omit<DataSource, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string; id?: string }> {
+ try {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO data_sources
+ (id, alias, display_name, description, type, provider, category, config, enabled, tags, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, CURRENT_TIMESTAMP)`,
+ [
+ source.id,
+ source.alias,
+ source.display_name,
+ source.description || null,
+ source.type,
+ source.provider,
+ source.category || null,
+ source.config,
+ source.enabled ? 1 : 0,
+ source.tags || null,
+ ]
+ );
+ return { success: true, message: 'Data source saved successfully', id: source.id };
+ } catch (error) {
+ console.error('[SQLite] Failed to save data source:', error);
+ return { success: false, message: 'Failed to save data source' };
+ }
+ }
+
+ async getAllDataSources(): Promise<DataSource[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<DataSource[]>('SELECT * FROM data_sources ORDER BY display_name');
+ }
+
+ async getDataSourceById(id: string): Promise<DataSource | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<DataSource[]>(
+ 'SELECT * FROM data_sources WHERE id = $1',
+ [id]
+ );
+ return results[0] || null;
+ }
+
+ async getDataSourceByAlias(alias: string): Promise<DataSource | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<DataSource[]>(
+ 'SELECT * FROM data_sources WHERE alias = $1',
+ [alias]
+ );
+ return results[0] || null;
+ }
+
+ async getDataSourcesByType(type: 'websocket' | 'rest_api'): Promise<DataSource[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<DataSource[]>(
+ 'SELECT * FROM data_sources WHERE type = $1',
+ [type]
+ );
+ }
+
+ async getDataSourcesByProvider(provider: string): Promise<DataSource[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<DataSource[]>(
+ 'SELECT * FROM data_sources WHERE provider = $1',
+ [provider]
+ );
+ }
+
+ async getEnabledDataSources(): Promise<DataSource[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<DataSource[]>(
+ 'SELECT * FROM data_sources WHERE enabled = 1'
+ );
+ }
+
+ async toggleDataSourceEnabled(id: string): Promise<{ success: boolean; message: string; enabled: boolean }> {
+ try {
+ await this.ensureInitialized();
+
+ // Get current state
+ const source = await this.getDataSourceById(id);
+ if (!source) {
+ return { success: false, message: 'Data source not found', enabled: false };
+ }
+
+ const newEnabledState = !source.enabled;
+
+ await this.db!.execute(
+ 'UPDATE data_sources SET enabled = NOT enabled, updated_at = CURRENT_TIMESTAMP WHERE id = $1',
+ [id]
+ );
+
+ return { success: true, message: `Data source ${newEnabledState ? 'enabled' : 'disabled'}`, enabled: newEnabledState };
+ } catch (error) {
+ console.error('[SQLite] Failed to toggle data source:', error);
+ return { success: false, message: 'Failed to toggle data source', enabled: false };
+ }
+ }
+
+ async deleteDataSource(id: string): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+ await this.db!.execute('DELETE FROM data_sources WHERE id = $1', [id]);
+ return { success: true, message: 'Data source deleted successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to delete data source:', error);
+ return { success: false, message: 'Failed to delete data source' };
+ }
+ }
+
+ async searchDataSources(query: string): Promise<DataSource[]> {
+ await this.ensureInitialized();
+ const searchPattern = `%${query}%`;
+ return await this.db!.select<DataSource[]>(
+ `SELECT * FROM data_sources
+ WHERE display_name LIKE $1 OR alias LIKE $1 OR provider LIKE $1 OR tags LIKE $1`,
+ [searchPattern]
+ );
+ }
+
+ // =========================
+ // WS PROVIDER CONFIG METHODS
+ // =========================
+
+ async saveWSProviderConfig(config: Omit<WSProviderConfig, 'id' | 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO ws_provider_configs
+ (provider_name, enabled, api_key, api_secret, endpoint, config_data, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP)`,
+ [
+ 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: 'WebSocket provider configuration saved successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to save WS provider config:', error);
+ return { success: false, message: 'Failed to save WebSocket provider configuration' };
+ }
+ }
+
+ async getWSProviderConfigs(): Promise<WSProviderConfig[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<WSProviderConfig[]>('SELECT * FROM ws_provider_configs ORDER BY provider_name');
+ }
+
+ async getWSProviderConfig(providerName: string): Promise<WSProviderConfig | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<WSProviderConfig[]>(
+ 'SELECT * FROM ws_provider_configs WHERE provider_name = $1',
+ [providerName]
+ );
+ return results[0] || null;
+ }
+
+ async getEnabledWSProviderConfigs(): Promise<WSProviderConfig[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<WSProviderConfig[]>(
+ 'SELECT * FROM ws_provider_configs WHERE enabled = 1'
+ );
+ }
+
+ async toggleWSProviderEnabled(providerName: string): Promise<{ success: boolean; message: string; enabled: boolean }> {
+ try {
+ await this.ensureInitialized();
+
+ // Get current state
+ const config = await this.getWSProviderConfig(providerName);
+ if (!config) {
+ return { success: false, message: 'Provider configuration not found', enabled: false };
+ }
+
+ const newEnabledState = !config.enabled;
+
+ await this.db!.execute(
+ 'UPDATE ws_provider_configs SET enabled = NOT enabled, updated_at = CURRENT_TIMESTAMP WHERE provider_name = $1',
+ [providerName]
+ );
+
+ return { success: true, message: `Provider ${newEnabledState ? 'enabled' : 'disabled'}`, enabled: newEnabledState };
+ } catch (error) {
+ console.error('[SQLite] Failed to toggle WS provider:', error);
+ return { success: false, message: 'Failed to toggle provider', enabled: false };
+ }
+ }
+
+ async deleteWSProviderConfig(providerName: string): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+ await this.db!.execute('DELETE FROM ws_provider_configs WHERE provider_name = $1', [providerName]);
+ return { success: true, message: 'Provider configuration deleted successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to delete WS provider config:', error);
+ return { success: false, message: 'Failed to delete provider configuration' };
+ }
+ }
+
+ // =========================
+ // MCP METHODS
+ // =========================
+
+ async addMCPServer(server: Omit<MCPServer, 'created_at' | 'updated_at'>): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO mcp_servers
+ (id, name, description, command, args, env, category, icon, enabled, auto_start, status, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, CURRENT_TIMESTAMP)`,
+ [
+ server.id,
+ server.name,
+ server.description,
+ server.command,
+ server.args,
+ server.env || null,
+ server.category,
+ server.icon,
+ server.enabled ? 1 : 0,
+ server.auto_start ? 1 : 0,
+ server.status,
+ ]
+ );
+ }
+
+ async getMCPServers(): Promise<MCPServer[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<MCPServer[]>('SELECT * FROM mcp_servers ORDER BY name');
+ }
+
+ async getMCPServer(id: string): Promise<MCPServer | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<MCPServer[]>(
+ 'SELECT * FROM mcp_servers WHERE id = $1',
+ [id]
+ );
+ return results[0] || null;
+ }
+
+ async updateMCPServerStatus(id: string, status: string): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute(
+ 'UPDATE mcp_servers SET status = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2',
+ [status, id]
+ );
+ }
+
+ async updateMCPServerConfig(id: string, updates: Partial<MCPServer>): Promise<void> {
+ await this.ensureInitialized();
+
+ const fields: string[] = [];
+ const values: any[] = [];
+ let paramIndex = 1;
+
+ if (updates.name !== undefined) {
+ fields.push(`name = $${paramIndex++}`);
+ values.push(updates.name);
+ }
+ if (updates.description !== undefined) {
+ fields.push(`description = $${paramIndex++}`);
+ values.push(updates.description);
+ }
+ if (updates.command !== undefined) {
+ fields.push(`command = $${paramIndex++}`);
+ values.push(updates.command);
+ }
+ if (updates.args !== undefined) {
+ fields.push(`args = $${paramIndex++}`);
+ values.push(updates.args);
+ }
+ if (updates.env !== undefined) {
+ fields.push(`env = $${paramIndex++}`);
+ values.push(updates.env);
+ }
+ if (updates.category !== undefined) {
+ fields.push(`category = $${paramIndex++}`);
+ values.push(updates.category);
+ }
+ if (updates.icon !== undefined) {
+ fields.push(`icon = $${paramIndex++}`);
+ values.push(updates.icon);
+ }
+ if (updates.enabled !== undefined) {
+ fields.push(`enabled = $${paramIndex++}`);
+ values.push(updates.enabled ? 1 : 0);
+ }
+ if (updates.auto_start !== undefined) {
+ fields.push(`auto_start = $${paramIndex++}`);
+ values.push(updates.auto_start ? 1 : 0);
+ }
+
+ if (fields.length === 0) return;
+
+ fields.push(`updated_at = CURRENT_TIMESTAMP`);
+ values.push(id);
+
+ const sql = `UPDATE mcp_servers SET ${fields.join(', ')} WHERE id = $${paramIndex}`;
+ await this.db!.execute(sql, values);
+ }
+
+ async deleteMCPServer(id: string): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute('DELETE FROM mcp_servers WHERE id = $1', [id]);
+ }
+
+ async getAutoStartServers(): Promise<MCPServer[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<MCPServer[]>(
+ 'SELECT * FROM mcp_servers WHERE auto_start = 1 AND enabled = 1'
+ );
+ }
+
+ async cacheMCPTools(serverId: string, tools: any[]): Promise<void> {
+ await this.ensureInitialized();
+
+ // Delete existing tools for this server
+ await this.db!.execute('DELETE FROM mcp_tools WHERE server_id = $1', [serverId]);
+
+ // Insert new tools
+ for (const tool of tools) {
+ await this.db!.execute(
+ `INSERT INTO mcp_tools (id, server_id, name, description, input_schema)
+ VALUES ($1, $2, $3, $4, $5)`,
+ [
+ `${serverId}_${tool.name}`,
+ serverId,
+ tool.name,
+ tool.description || null,
+ tool.inputSchema ? JSON.stringify(tool.inputSchema) : null
+ ]
+ );
+ }
+ }
+
+ async getMCPServerStats(serverId: string): Promise<{ toolCount: number; callsToday: number; lastUsed: string | null }> {
+ await this.ensureInitialized();
+
+ // Get tool count
+ const toolCountResult = await this.db!.select<{ count: number }[]>(
+ 'SELECT COUNT(*) as count FROM mcp_tools WHERE server_id = $1',
+ [serverId]
+ );
+ const toolCount = toolCountResult[0]?.count || 0;
+
+ // Get calls today
+ const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
+ const callsTodayResult = await this.db!.select<{ count: number }[]>(
+ `SELECT COUNT(*) as count FROM mcp_tool_usage_logs
+ WHERE server_id = $1 AND DATE(timestamp) = $2`,
+ [serverId, today]
+ );
+ const callsToday = callsTodayResult[0]?.count || 0;
+
+ // Get last used timestamp
+ const lastUsedResult = await this.db!.select<{ timestamp: string }[]>(
+ `SELECT timestamp FROM mcp_tool_usage_logs
+ WHERE server_id = $1 ORDER BY timestamp DESC LIMIT 1`,
+ [serverId]
+ );
+ const lastUsed = lastUsedResult[0]?.timestamp || null;
+
+ return {
+ toolCount,
+ callsToday,
+ lastUsed
+ };
+ }
+
+ async logMCPToolUsage(log: {
+ serverId: string;
+ toolName: string;
+ args: string;
+ result: string | null;
+ success: boolean;
+ executionTime: number;
+ error?: string;
+ }): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT INTO mcp_tool_usage_logs (server_id, tool_name, args, result, success, execution_time, error)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,
+ [
+ log.serverId,
+ log.toolName,
+ log.args,
+ log.result,
+ log.success ? 1 : 0,
+ log.executionTime,
+ log.error || null
+ ]
+ );
+ }
+
+ async getMCPTools(): Promise<any[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<any[]>(
+ 'SELECT * FROM mcp_tools ORDER BY name'
+ );
+ }
+
+ async getMCPToolsByServer(serverId: string): Promise<any[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<any[]>(
+ 'SELECT * FROM mcp_tools WHERE server_id = $1 ORDER BY name',
+ [serverId]
+ );
+ }
+
+ // =========================
+ // MARKET DATA CACHE METHODS
+ // =========================
+
+ async saveMarketDataCache(symbol: string, category: string, quoteData: any): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO market_data_cache (symbol, category, quote_data, cached_at)
+ VALUES ($1, $2, $3, CURRENT_TIMESTAMP)`,
+ [symbol, category, JSON.stringify(quoteData)]
+ );
+ }
+
+ async getCachedMarketData(symbol: string, category: string, maxAgeMinutes: number = 5): Promise<any | null> {
+ await this.ensureInitialized();
+
+ const results = await this.db!.select<{ quote_data: string; cached_at: string }[]>(
+ `SELECT quote_data, cached_at FROM market_data_cache
+ WHERE symbol = $1 AND category = $2
+ AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`,
+ [symbol, category]
+ );
+
+ if (!results[0]) return null;
+
+ return JSON.parse(results[0].quote_data);
+ }
+
+ async clearMarketDataCache(): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute('DELETE FROM market_data_cache');
+ }
+
+ async clearExpiredMarketCache(maxAgeMinutes: number = 60): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute(
+ `DELETE FROM market_data_cache
+ WHERE datetime(cached_at) < datetime('now', '-${maxAgeMinutes} minutes')`
+ );
+ }
+
+ async getCachedCategoryData(category: string, symbols: string[], maxAgeMinutes: number = 5): Promise<Map<string, any>> {
+ await this.ensureInitialized();
+
+ const result = new Map<string, any>();
+
+ try {
+ // Build placeholders using $ syntax
+ const placeholders = symbols.map((_, i) => `$${i + 1}`).join(',');
+ const categoryParam = symbols.length + 1;
+
+ const results = await this.db!.select<{ symbol: string; quote_data: string; cached_at: string }[]>(
+ `SELECT symbol, quote_data, cached_at FROM market_data_cache
+ WHERE symbol IN (${placeholders}) AND category = $${categoryParam}
+ AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`,
+ [...symbols, category]
+ );
+
+ for (const row of results) {
+ result.set(row.symbol, JSON.parse(row.quote_data));
+ }
+ } catch (error) {
+ console.error('[SQLite] Error getting cached category data:', error);
+ }
+
+ return result;
+ }
+
+ // =========================
+ // DATA SOURCE CONNECTIONS METHODS
+ // =========================
+
+ async saveDataSourceConnection(connection: {
+ id: string;
+ name: string;
+ type: string;
+ category: string;
+ config: string;
+ status: string;
+ lastTested?: string;
+ errorMessage?: string;
+ }): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO data_source_connections
+ (id, name, type, category, config, status, updated_at, last_tested, error_message)
+ VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP, $7, $8)`,
+ [
+ connection.id,
+ connection.name,
+ connection.type,
+ connection.category,
+ connection.config,
+ connection.status,
+ connection.lastTested || null,
+ connection.errorMessage || null,
+ ]
+ );
+ }
+
+ async getDataSourceConnection(id: string): Promise<any | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<any[]>(
+ 'SELECT * FROM data_source_connections WHERE id = $1',
+ [id]
+ );
+ return results[0] || null;
+ }
+
+ async getAllDataSourceConnections(): Promise<any[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<any[]>(
+ 'SELECT * FROM data_source_connections ORDER BY created_at DESC'
+ );
+ }
+
+ async getDataSourceConnectionsByCategory(category: string): Promise<any[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<any[]>(
+ 'SELECT * FROM data_source_connections WHERE category = $1 ORDER BY created_at DESC',
+ [category]
+ );
+ }
+
+ async getDataSourceConnectionsByType(type: string): Promise<any[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<any[]>(
+ 'SELECT * FROM data_source_connections WHERE type = $1',
+ [type]
+ );
+ }
+
+ async updateDataSourceConnection(
+ id: string,
+ updates: {
+ name?: string;
+ config?: string;
+ status?: string;
+ lastTested?: string;
+ errorMessage?: string;
+ }
+ ): Promise<void> {
+ await this.ensureInitialized();
+
+ const fields: string[] = [];
+ const values: any[] = [];
+ let paramIndex = 1;
+
+ if (updates.name !== undefined) {
+ fields.push(`name = $${paramIndex++}`);
+ values.push(updates.name);
+ }
+ if (updates.config !== undefined) {
+ fields.push(`config = $${paramIndex++}`);
+ values.push(updates.config);
+ }
+ if (updates.status !== undefined) {
+ fields.push(`status = $${paramIndex++}`);
+ values.push(updates.status);
+ }
+ if (updates.lastTested !== undefined) {
+ fields.push(`last_tested = $${paramIndex++}`);
+ values.push(updates.lastTested);
+ }
+ if (updates.errorMessage !== undefined) {
+ fields.push(`error_message = $${paramIndex++}`);
+ values.push(updates.errorMessage);
+ }
+
+ if (fields.length === 0) return;
+
+ fields.push(`updated_at = CURRENT_TIMESTAMP`);
+ values.push(id);
+
+ const sql = `UPDATE data_source_connections SET ${fields.join(', ')} WHERE id = $${paramIndex}`;
+ await this.db!.execute(sql, values);
+ }
+
+ async deleteDataSourceConnection(id: string): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute('DELETE FROM data_source_connections WHERE id = $1', [id]);
+ }
+
+ // =========================
+ // FORUM CACHE METHODS
+ // =========================
+
+ /**
+ * Cache forum categories
+ */
+ async cacheForumCategories(categories: any[]): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO forum_categories_cache (id, data, cached_at)
+ VALUES (1, $1, CURRENT_TIMESTAMP)`,
+ [JSON.stringify(categories)]
+ );
+ }
+
+ /**
+ * Get cached forum categories
+ */
+ async getCachedForumCategories(maxAgeMinutes: number = 5): Promise<any[] | null> {
+ await this.ensureInitialized();
+
+ const results = await this.db!.select<{ data: string; cached_at: string }[]>(
+ `SELECT data, cached_at FROM forum_categories_cache
+ WHERE id = 1
+ AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`
+ );
+
+ if (!results[0]) return null;
+
+ return JSON.parse(results[0].data);
+ }
+
+ /**
+ * Cache forum posts by category and sort type
+ */
+ async cacheForumPosts(categoryId: number | null, sortBy: string, posts: any[]): Promise<void> {
+ await this.ensureInitialized();
+
+ const cacheKey = `${categoryId || 'all'}_${sortBy}`;
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO forum_posts_cache (cache_key, category_id, sort_by, data, cached_at)
+ VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)`,
+ [cacheKey, categoryId, sortBy, JSON.stringify(posts)]
+ );
+ }
+
+ /**
+ * Get cached forum posts
+ */
+ async getCachedForumPosts(categoryId: number | null, sortBy: string, maxAgeMinutes: number = 5): Promise<any[] | null> {
+ await this.ensureInitialized();
+
+ const cacheKey = `${categoryId || 'all'}_${sortBy}`;
+ const results = await this.db!.select<{ data: string; cached_at: string }[]>(
+ `SELECT data, cached_at FROM forum_posts_cache
+ WHERE cache_key = $1
+ AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`,
+ [cacheKey]
+ );
+
+ if (!results[0]) return null;
+
+ return JSON.parse(results[0].data);
+ }
+
+ /**
+ * Cache forum statistics
+ */
+ async cacheForumStats(stats: any): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO forum_stats_cache (id, data, cached_at)
+ VALUES (1, $1, CURRENT_TIMESTAMP)`,
+ [JSON.stringify(stats)]
+ );
+ }
+
+ /**
+ * Get cached forum statistics
+ */
+ async getCachedForumStats(maxAgeMinutes: number = 5): Promise<any | null> {
+ await this.ensureInitialized();
+
+ const results = await this.db!.select<{ data: string; cached_at: string }[]>(
+ `SELECT data, cached_at FROM forum_stats_cache
+ WHERE id = 1
+ AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`
+ );
+
+ if (!results[0]) return null;
+
+ return JSON.parse(results[0].data);
+ }
+
+ /**
+ * Cache forum post details with comments
+ */
+ async cacheForumPostDetails(postUuid: string, post: any, comments: any[]): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO forum_post_details_cache (post_uuid, data, comments_data, cached_at)
+ VALUES ($1, $2, $3, CURRENT_TIMESTAMP)`,
+ [postUuid, JSON.stringify(post), JSON.stringify(comments)]
+ );
+ }
+
+ /**
+ * Get cached forum post details
+ */
+ async getCachedForumPostDetails(postUuid: string, maxAgeMinutes: number = 5): Promise<{ post: any; comments: any[] } | null> {
+ await this.ensureInitialized();
+
+ const results = await this.db!.select<{ data: string; comments_data: string; cached_at: string }[]>(
+ `SELECT data, comments_data, cached_at FROM forum_post_details_cache
+ WHERE post_uuid = $1
+ AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`,
+ [postUuid]
+ );
+
+ if (!results[0]) return null;
+
+ return {
+ post: JSON.parse(results[0].data),
+ comments: JSON.parse(results[0].comments_data)
+ };
+ }
+
+ /**
+ * Clear all forum cache
+ */
+ async clearForumCache(): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute('DELETE FROM forum_categories_cache');
+ await this.db!.execute('DELETE FROM forum_posts_cache');
+ await this.db!.execute('DELETE FROM forum_stats_cache');
+ await this.db!.execute('DELETE FROM forum_post_details_cache');
+ }
+
+ /**
+ * Clear expired forum cache
+ */
+ async clearExpiredForumCache(maxAgeMinutes: number = 60): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `DELETE FROM forum_categories_cache
+ WHERE datetime(cached_at) < datetime('now', '-${maxAgeMinutes} minutes')`
+ );
+
+ await this.db!.execute(
+ `DELETE FROM forum_posts_cache
+ WHERE datetime(cached_at) < datetime('now', '-${maxAgeMinutes} minutes')`
+ );
+
+ await this.db!.execute(
+ `DELETE FROM forum_stats_cache
+ WHERE datetime(cached_at) < datetime('now', '-${maxAgeMinutes} minutes')`
+ );
+
+ await this.db!.execute(
+ `DELETE FROM forum_post_details_cache
+ WHERE datetime(cached_at) < datetime('now', '-${maxAgeMinutes} minutes')`
+ );
+ }
+
+ // =========================
+ // CONTEXT RECORDING METHODS
+ // =========================
+
+ /**
+ * Save recorded context data
+ */
+ async saveRecordedContext(context: Omit<RecordedContext, 'created_at'>): Promise<void> {
+ await this.ensureInitialized();
+
+ const dataSize = new TextEncoder().encode(context.raw_data).length;
+
+ await this.db!.execute(
+ `INSERT INTO recorded_contexts (id, tab_name, data_type, label, raw_data, metadata, data_size, tags)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
+ [
+ context.id,
+ context.tab_name,
+ context.data_type,
+ context.label || null,
+ context.raw_data,
+ context.metadata || null,
+ dataSize,
+ context.tags || null
+ ]
+ );
+ }
+
+ /**
+ * Get all recorded contexts with optional filters
+ */
+ async getRecordedContexts(filters?: {
+ tabName?: string;
+ dataType?: string;
+ tags?: string[];
+ limit?: number;
+ }): Promise<RecordedContext[]> {
+ await this.ensureInitialized();
+
+ let sql = 'SELECT * FROM recorded_contexts WHERE 1=1';
+ const params: any[] = [];
+ let paramIndex = 1;
+
+ if (filters?.tabName) {
+ sql += ` AND tab_name = $${paramIndex++}`;
+ params.push(filters.tabName);
+ }
+
+ if (filters?.dataType) {
+ sql += ` AND data_type = $${paramIndex++}`;
+ params.push(filters.dataType);
+ }
+
+ if (filters?.tags && filters.tags.length > 0) {
+ const tagConditions = filters.tags.map(() => `tags LIKE $${paramIndex++}`).join(' OR ');
+ sql += ` AND (${tagConditions})`;
+ params.push(...filters.tags.map(tag => `%${tag}%`));
+ }
+
+ sql += ' ORDER BY created_at DESC';
+
+ if (filters?.limit) {
+ sql += ` LIMIT $${paramIndex}`;
+ params.push(filters.limit);
+ }
+
+ return await this.db!.select<RecordedContext[]>(sql, params);
+ }
+
+ /**
+ * Get context by ID
+ */
+ async getRecordedContext(id: string): Promise<RecordedContext | null> {
+ await this.ensureInitialized();
+
+ const results = await this.db!.select<RecordedContext[]>(
+ 'SELECT * FROM recorded_contexts WHERE id = $1',
+ [id]
+ );
+
+ return results[0] || null;
+ }
+
+ /**
+ * Delete recorded context
+ */
+ async deleteRecordedContext(id: string): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute('DELETE FROM recorded_contexts WHERE id = $1', [id]);
+ }
+
+ /**
+ * Clear old contexts
+ */
+ async clearOldContexts(maxAgeDays: number): Promise<void> {
+ await this.ensureInitialized();
+ await this.db!.execute(
+ `DELETE FROM recorded_contexts
+ WHERE datetime(created_at) < datetime('now', '-${maxAgeDays} days')`
+ );
+ }
+
+ /**
+ * Get storage statistics
+ */
+ async getContextStorageStats(): Promise<{ count: number; totalSize: number }> {
+ await this.ensureInitialized();
+
+ const result = await this.db!.select<{ count: number; total_size: number }[]>(
+ 'SELECT COUNT(*) as count, SUM(data_size) as total_size FROM recorded_contexts'
+ );
+
+ return {
+ count: result[0]?.count || 0,
+ totalSize: result[0]?.total_size || 0
+ };
+ }
+
+ /**
+ * Start recording session
+ */
+ async startRecordingSession(session: Omit<RecordingSession, 'started_at'>): Promise<void> {
+ await this.ensureInitialized();
+
+ // End any existing active session for this tab
+ await this.db!.execute(
+ `UPDATE recording_sessions SET is_active = 0, ended_at = CURRENT_TIMESTAMP
+ WHERE tab_name = $1 AND is_active = 1`,
+ [session.tab_name]
+ );
+
+ // Start new session
+ await this.db!.execute(
+ `INSERT INTO recording_sessions (id, tab_name, is_active, auto_record, filters)
+ VALUES ($1, $2, $3, $4, $5)`,
+ [
+ session.id,
+ session.tab_name,
+ session.is_active ? 1 : 0,
+ session.auto_record ? 1 : 0,
+ session.filters || null
+ ]
+ );
+ }
+
+ /**
+ * Get active recording session for tab
+ */
+ async getActiveRecordingSession(tabName: string): Promise<RecordingSession | null> {
+ await this.ensureInitialized();
+
+ const results = await this.db!.select<RecordingSession[]>(
+ 'SELECT * FROM recording_sessions WHERE tab_name = $1 AND is_active = 1 LIMIT 1',
+ [tabName]
+ );
+
+ return results[0] || null;
+ }
+
+ /**
+ * Stop recording session
+ */
+ async stopRecordingSession(tabName: string): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `UPDATE recording_sessions SET is_active = 0, ended_at = CURRENT_TIMESTAMP
+ WHERE tab_name = $1 AND is_active = 1`,
+ [tabName]
+ );
+ }
+
+ /**
+ * Link context to chat session
+ */
+ async linkContextToChat(chatSessionUuid: string, contextId: string): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO chat_context_links (chat_session_uuid, context_id)
+ VALUES ($1, $2)`,
+ [chatSessionUuid, contextId]
+ );
+ }
+
+ /**
+ * Unlink context from chat session
+ */
+ async unlinkContextFromChat(chatSessionUuid: string, contextId: string): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ 'DELETE FROM chat_context_links WHERE chat_session_uuid = $1 AND context_id = $2',
+ [chatSessionUuid, contextId]
+ );
+ }
+
+ /**
+ * Get active contexts for chat session
+ */
+ async getChatContexts(chatSessionUuid: string): Promise<RecordedContext[]> {
+ await this.ensureInitialized();
+
+ return await this.db!.select<RecordedContext[]>(
+ `SELECT rc.* FROM recorded_contexts rc
+ INNER JOIN chat_context_links ccl ON rc.id = ccl.context_id
+ WHERE ccl.chat_session_uuid = $1 AND ccl.is_active = 1
+ ORDER BY ccl.added_at DESC`,
+ [chatSessionUuid]
+ );
+ }
+
+ /**
+ * Toggle context active state in chat
+ */
+ async toggleChatContextActive(chatSessionUuid: string, contextId: string): Promise<void> {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `UPDATE chat_context_links SET is_active = NOT is_active
+ WHERE chat_session_uuid = $1 AND context_id = $2`,
+ [chatSessionUuid, contextId]
+ );
+ }
+
+ // =========================
+ // BACKTESTING METHODS
+ // =========================
+
+ async saveBacktestingProvider(provider: Omit<BacktestingProvider, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO backtesting_providers (id, name, adapter_type, config, enabled, is_active, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP)`,
+ [provider.id, provider.name, provider.adapter_type, provider.config, provider.enabled ? 1 : 0, provider.is_active ? 1 : 0]
+ );
+
+ return { success: true, message: 'Backtesting provider saved successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to save backtesting provider:', error);
+ return { success: false, message: 'Failed to save backtesting provider' };
+ }
+ }
+
+ async getBacktestingProviders(): Promise<BacktestingProvider[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<BacktestingProvider[]>('SELECT * FROM backtesting_providers ORDER BY name');
+ }
+
+ async getBacktestingProvider(name: string): Promise<BacktestingProvider | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<BacktestingProvider[]>(
+ 'SELECT * FROM backtesting_providers WHERE name = $1',
+ [name]
+ );
+ return results[0] || null;
+ }
+
+ async getActiveBacktestingProvider(): Promise<BacktestingProvider | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<BacktestingProvider[]>(
+ 'SELECT * FROM backtesting_providers WHERE is_active = 1 LIMIT 1'
+ );
+ return results[0] || null;
+ }
+
+ async setActiveBacktestingProvider(name: string): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ // Deactivate all providers first
+ await this.db!.execute('UPDATE backtesting_providers SET is_active = 0');
+
+ // Activate the specified provider
+ await this.db!.execute(
+ 'UPDATE backtesting_providers SET is_active = 1, updated_at = CURRENT_TIMESTAMP WHERE name = $1',
+ [name]
+ );
+
+ return { success: true, message: `Activated backtesting provider: ${name}` };
+ } catch (error) {
+ console.error('[SQLite] Failed to set active provider:', error);
+ return { success: false, message: 'Failed to set active provider' };
+ }
+ }
+
+ async deleteBacktestingProvider(name: string): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ 'DELETE FROM backtesting_providers WHERE name = $1',
+ [name]
+ );
+
+ return { success: true, message: 'Provider deleted successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to delete provider:', error);
+ return { success: false, message: 'Failed to delete provider' };
+ }
+ }
+
+ async saveBacktestingStrategy(strategy: Omit<BacktestingStrategy, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT OR REPLACE INTO backtesting_strategies
+ (id, name, description, version, author, provider_type, strategy_type, strategy_definition, tags, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, CURRENT_TIMESTAMP)`,
+ [
+ strategy.id,
+ strategy.name,
+ strategy.description || null,
+ strategy.version,
+ strategy.author || null,
+ strategy.provider_type,
+ strategy.strategy_type,
+ strategy.strategy_definition,
+ strategy.tags || null,
+ ]
+ );
+
+ return { success: true, message: 'Strategy saved successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to save strategy:', error);
+ return { success: false, message: 'Failed to save strategy' };
+ }
+ }
+
+ async getBacktestingStrategies(): Promise<BacktestingStrategy[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<BacktestingStrategy[]>('SELECT * FROM backtesting_strategies ORDER BY updated_at DESC');
+ }
+
+ async getBacktestingStrategy(id: string): Promise<BacktestingStrategy | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<BacktestingStrategy[]>(
+ 'SELECT * FROM backtesting_strategies WHERE id = $1',
+ [id]
+ );
+ return results[0] || null;
+ }
+
+ async getBacktestingStrategiesByProvider(providerType: string): Promise<BacktestingStrategy[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<BacktestingStrategy[]>(
+ 'SELECT * FROM backtesting_strategies WHERE provider_type = $1 ORDER BY updated_at DESC',
+ [providerType]
+ );
+ }
+
+ async deleteBacktestingStrategy(id: string): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ 'DELETE FROM backtesting_strategies WHERE id = $1',
+ [id]
+ );
+
+ return { success: true, message: 'Strategy deleted successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to delete strategy:', error);
+ return { success: false, message: 'Failed to delete strategy' };
+ }
+ }
+
+ async saveBacktestRun(run: Omit<BacktestRun, 'created_at' | 'completed_at' | 'duration_seconds'>): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT INTO backtest_runs
+ (id, strategy_id, provider_name, config, results, status, performance_metrics, error_message)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
+ [
+ run.id,
+ run.strategy_id || null,
+ run.provider_name,
+ run.config,
+ run.results || null,
+ run.status,
+ run.performance_metrics || null,
+ run.error_message || null,
+ ]
+ );
+
+ return { success: true, message: 'Backtest run saved successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to save backtest run:', error);
+ return { success: false, message: 'Failed to save backtest run' };
+ }
+ }
+
+ async updateBacktestRun(id: string, updates: Partial<BacktestRun>): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ const fields: string[] = [];
+ const values: any[] = [];
+
+ if (updates.results !== undefined) {
+ fields.push('results = $' + (values.length + 1));
+ values.push(updates.results);
+ }
+ if (updates.status !== undefined) {
+ fields.push('status = $' + (values.length + 1));
+ values.push(updates.status);
+ }
+ if (updates.performance_metrics !== undefined) {
+ fields.push('performance_metrics = $' + (values.length + 1));
+ values.push(updates.performance_metrics);
+ }
+ if (updates.error_message !== undefined) {
+ fields.push('error_message = $' + (values.length + 1));
+ values.push(updates.error_message);
+ }
+ if (updates.completed_at !== undefined) {
+ fields.push('completed_at = $' + (values.length + 1));
+ values.push(updates.completed_at);
+ }
+ if (updates.duration_seconds !== undefined) {
+ fields.push('duration_seconds = $' + (values.length + 1));
+ values.push(updates.duration_seconds);
+ }
+
+ if (fields.length === 0) {
+ return { success: true, message: 'No updates to apply' };
+ }
+
+ values.push(id);
+ await this.db!.execute(
+ `UPDATE backtest_runs SET ${fields.join(', ')} WHERE id = $${values.length}`,
+ values
+ );
+
+ return { success: true, message: 'Backtest run updated successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to update backtest run:', error);
+ return { success: false, message: 'Failed to update backtest run' };
+ }
+ }
+
+ async getBacktestRuns(limit?: number): Promise<BacktestRun[]> {
+ await this.ensureInitialized();
+ const sql = limit
+ ? `SELECT * FROM backtest_runs ORDER BY created_at DESC LIMIT ${limit}`
+ : 'SELECT * FROM backtest_runs ORDER BY created_at DESC';
+ return await this.db!.select<BacktestRun[]>(sql);
+ }
+
+ async getBacktestRun(id: string): Promise<BacktestRun | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<BacktestRun[]>(
+ 'SELECT * FROM backtest_runs WHERE id = $1',
+ [id]
+ );
+ return results[0] || null;
+ }
+
+ async getBacktestRunsByStrategy(strategyId: string): Promise<BacktestRun[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<BacktestRun[]>(
+ 'SELECT * FROM backtest_runs WHERE strategy_id = $1 ORDER BY created_at DESC',
+ [strategyId]
+ );
+ }
+
+ async getBacktestRunsByProvider(providerName: string): Promise<BacktestRun[]> {
+ await this.ensureInitialized();
+ return await this.db!.select<BacktestRun[]>(
+ 'SELECT * FROM backtest_runs WHERE provider_name = $1 ORDER BY created_at DESC',
+ [providerName]
+ );
+ }
+
+ async deleteBacktestRun(id: string): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ 'DELETE FROM backtest_runs WHERE id = $1',
+ [id]
+ );
+
+ return { success: true, message: 'Backtest run deleted successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to delete backtest run:', error);
+ return { success: false, message: 'Failed to delete backtest run' };
+ }
+ }
+
+ async saveOptimizationRun(run: Omit<OptimizationRun, 'created_at' | 'completed_at' | 'duration_seconds'>): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ `INSERT INTO optimization_runs
+ (id, strategy_id, provider_name, parameter_grid, objective, best_parameters, best_result, all_results, iterations, status, error_message)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
+ [
+ run.id,
+ run.strategy_id || null,
+ run.provider_name,
+ run.parameter_grid,
+ run.objective,
+ run.best_parameters || null,
+ run.best_result || null,
+ run.all_results || null,
+ run.iterations || null,
+ run.status,
+ run.error_message || null,
+ ]
+ );
+
+ return { success: true, message: 'Optimization run saved successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to save optimization run:', error);
+ return { success: false, message: 'Failed to save optimization run' };
+ }
+ }
+
+ async updateOptimizationRun(id: string, updates: Partial<OptimizationRun>): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ const fields: string[] = [];
+ const values: any[] = [];
+
+ if (updates.best_parameters !== undefined) {
+ fields.push('best_parameters = $' + (values.length + 1));
+ values.push(updates.best_parameters);
+ }
+ if (updates.best_result !== undefined) {
+ fields.push('best_result = $' + (values.length + 1));
+ values.push(updates.best_result);
+ }
+ if (updates.all_results !== undefined) {
+ fields.push('all_results = $' + (values.length + 1));
+ values.push(updates.all_results);
+ }
+ if (updates.iterations !== undefined) {
+ fields.push('iterations = $' + (values.length + 1));
+ values.push(updates.iterations);
+ }
+ if (updates.status !== undefined) {
+ fields.push('status = $' + (values.length + 1));
+ values.push(updates.status);
+ }
+ if (updates.error_message !== undefined) {
+ fields.push('error_message = $' + (values.length + 1));
+ values.push(updates.error_message);
+ }
+ if (updates.completed_at !== undefined) {
+ fields.push('completed_at = $' + (values.length + 1));
+ values.push(updates.completed_at);
+ }
+ if (updates.duration_seconds !== undefined) {
+ fields.push('duration_seconds = $' + (values.length + 1));
+ values.push(updates.duration_seconds);
+ }
+
+ if (fields.length === 0) {
+ return { success: true, message: 'No updates to apply' };
+ }
+
+ values.push(id);
+ await this.db!.execute(
+ `UPDATE optimization_runs SET ${fields.join(', ')} WHERE id = $${values.length}`,
+ values
+ );
+
+ return { success: true, message: 'Optimization run updated successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to update optimization run:', error);
+ return { success: false, message: 'Failed to update optimization run' };
+ }
+ }
+
+ async getOptimizationRuns(limit?: number): Promise<OptimizationRun[]> {
+ await this.ensureInitialized();
+ const sql = limit
+ ? `SELECT * FROM optimization_runs ORDER BY created_at DESC LIMIT ${limit}`
+ : 'SELECT * FROM optimization_runs ORDER BY created_at DESC';
+ return await this.db!.select<OptimizationRun[]>(sql);
+ }
+
+ async getOptimizationRun(id: string): Promise<OptimizationRun | null> {
+ await this.ensureInitialized();
+ const results = await this.db!.select<OptimizationRun[]>(
+ 'SELECT * FROM optimization_runs WHERE id = $1',
+ [id]
+ );
+ return results[0] || null;
+ }
+
+ async deleteOptimizationRun(id: string): Promise<{ success: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+
+ await this.db!.execute(
+ 'DELETE FROM optimization_runs WHERE id = $1',
+ [id]
+ );
+
+ return { success: true, message: 'Optimization run deleted successfully' };
+ } catch (error) {
+ console.error('[SQLite] Failed to delete optimization run:', error);
+ return { success: false, message: 'Failed to delete optimization run' };
+ }
+ }
+
+ // =========================
+ // UTILITY METHODS
+ // =========================
+
+ private async ensureInitialized(): Promise<void> {
+ if (!this.db) {
+ await this.initialize();
+ }
+ }
+
+ isReady(): boolean {
+ return this.db !== null;
+ }
+
+ /**
+ * Execute raw SQL statement
+ */
+ async execute(sql: string, params?: any[]): Promise<any> {
+ await this.ensureInitialized();
+ return await this.db!.execute(sql, params);
+ }
+
+ /**
+ * Execute raw SQL select query
+ */
+ async select<T = any>(sql: string, params?: any[]): Promise<T> {
+ await this.ensureInitialized();
+ return await this.db!.select<T>(sql, params);
+ }
+
+ async healthCheck(): Promise<{ healthy: boolean; message: string }> {
+ try {
+ await this.ensureInitialized();
+ const results = await this.db!.select<{ result: number }[]>('SELECT 1 as result');
+
+ if (results[0]?.result === 1) {
+ return { healthy: true, message: 'Database connection healthy' };
+ }
+
+ return { healthy: false, message: 'Unexpected query result' };
+ } catch (error) {
+ const errorMsg = error instanceof Error ? error.message : String(error);
+ return { healthy: false, message: `Health check failed: ${errorMsg}` };
+ }
+ }
+}
+
+// Export singleton instance
+export const sqliteService = new SQLiteService();
+export default sqliteService;