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.

general updates

tilakpatel222bc1b2f8ca8d
diff --git a/fincept-terminal-desktop/package-lock.json b/fincept-terminal-desktop/package-lock.json
index 0a60c98b2..287ea9359 100644
--- a/fincept-terminal-desktop/package-lock.json
+++ b/fincept-terminal-desktop/package-lock.json
@@ -74,6 +74,7 @@
"react-dom": "^19.1.0",
"react-grid-layout": "^1.5.2",
"react-markdown": "^10.1.0",
+ "react-router-dom": "^7.9.6",
"reactflow": "^11.11.4",
"recharts": "^2.15.4",
"remark-gfm": "^4.0.1",
@@ -5229,6 +5230,19 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/cookie": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
+ "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
"node_modules/create-require": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
@@ -8936,6 +8950,44 @@
"react": ">= 16.3"
}
},
+ "node_modules/react-router": {
+ "version": "7.9.6",
+ "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.9.6.tgz",
+ "integrity": "sha512-Y1tUp8clYRXpfPITyuifmSoE2vncSME18uVLgaqyxh9H35JWpIfzHo+9y3Fzh5odk/jxPW29IgLgzcdwxGqyNA==",
+ "license": "MIT",
+ "dependencies": {
+ "cookie": "^1.0.1",
+ "set-cookie-parser": "^2.6.0"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ },
+ "peerDependencies": {
+ "react": ">=18",
+ "react-dom": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/react-router-dom": {
+ "version": "7.9.6",
+ "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.9.6.tgz",
+ "integrity": "sha512-2MkC2XSXq6HjGcihnx1s0DBWQETI4mlis4Ux7YTLvP67xnGxCvq+BcCQSO81qQHVUTM1V53tl4iVVaY5sReCOA==",
+ "license": "MIT",
+ "dependencies": {
+ "react-router": "7.9.6"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ },
+ "peerDependencies": {
+ "react": ">=18",
+ "react-dom": ">=18"
+ }
+ },
"node_modules/react-smooth": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz",
@@ -9266,6 +9318,12 @@
"semver": "bin/semver.js"
}
},
+ "node_modules/set-cookie-parser": {
+ "version": "2.7.2",
+ "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
+ "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
+ "license": "MIT"
+ },
"node_modules/simple-wcswidth": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/simple-wcswidth/-/simple-wcswidth-1.1.2.tgz",
diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.json
index 4ee36269a..98810a1db 100644
--- a/fincept-terminal-desktop/package.json
+++ b/fincept-terminal-desktop/package.json
@@ -77,6 +77,7 @@
"react-dom": "^19.1.0",
"react-grid-layout": "^1.5.2",
"react-markdown": "^10.1.0",
+ "react-router-dom": "^7.9.6",
"reactflow": "^11.11.4",
"recharts": "^2.15.4",
"remark-gfm": "^4.0.1",
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/equityInvestment/get_historical_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/equityInvestment/get_historical_data.py
new file mode 100644
index 000000000..720d995c9
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/equityInvestment/get_historical_data.py
@@ -0,0 +1,50 @@
+"""
+Historical Data Fetcher
+Fetches historical price data for stocks using yfinance
+"""
+
+import sys
+import json
+import yfinance as yf
+from datetime import datetime
+
+
+def main():
+ try:
+ if len(sys.argv) < 2:
+ raise ValueError("Usage: python get_historical_data.py <symbol> [period] [interval]")
+
+ symbol = sys.argv[1]
+ period = sys.argv[2] if len(sys.argv) > 2 else '1y'
+ interval = sys.argv[3] if len(sys.argv) > 3 else '1d'
+
+ # Fetch data
+ ticker = yf.Ticker(symbol)
+ data = ticker.history(period=period, interval=interval)
+
+ if data.empty:
+ raise ValueError(f"No data found for symbol {symbol}")
+
+ # Convert to JSON format
+ result = []
+ for idx, row in data.iterrows():
+ result.append({
+ 'Date': idx.isoformat(),
+ 'timestamp': int(idx.timestamp()),
+ 'Open': float(row['Open']),
+ 'High': float(row['High']),
+ 'Low': float(row['Low']),
+ 'Close': float(row['Close']),
+ 'Volume': int(row['Volume'])
+ })
+
+ print(json.dumps(result))
+
+ except Exception as e:
+ error_msg = {'error': str(e)}
+ print(json.dumps(error_msg))
+ sys.exit(1)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/technical_analysis/momentum_indicators.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/technical_analysis/momentum_indicators.py
new file mode 100644
index 000000000..9e67c674b
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/technical_analysis/momentum_indicators.py
@@ -0,0 +1,294 @@
+"""
+Momentum Indicators Calculator
+Calculates various momentum indicators for technical analysis
+"""
+
+import sys
+import json
+import yfinance as yf
+import pandas as pd
+import numpy as np
+from datetime import datetime
+
+
+def calculate_rsi(data, period=14):
+ """Calculate Relative Strength Index"""
+ delta = data['Close'].diff()
+ gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
+ loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
+
+ rs = gain / loss
+ rsi = 100 - (100 / (1 + rs))
+
+ result = []
+ for idx, value in rsi.items():
+ result.append({
+ 'time': idx.isoformat(),
+ 'value': float(value) if not pd.isna(value) else None
+ })
+
+ return {'values': result}
+
+
+def calculate_macd(data, fast_period=12, slow_period=26, signal_period=9):
+ """Calculate MACD (Moving Average Convergence Divergence)"""
+ exp1 = data['Close'].ewm(span=fast_period, adjust=False).mean()
+ exp2 = data['Close'].ewm(span=slow_period, adjust=False).mean()
+
+ macd_line = exp1 - exp2
+ signal_line = macd_line.ewm(span=signal_period, adjust=False).mean()
+ histogram = macd_line - signal_line
+
+ macd_result = []
+ signal_result = []
+ histogram_result = []
+
+ for idx in macd_line.index:
+ macd_result.append({
+ 'time': idx.isoformat(),
+ 'value': float(macd_line[idx]) if not pd.isna(macd_line[idx]) else None
+ })
+ signal_result.append({
+ 'time': idx.isoformat(),
+ 'value': float(signal_line[idx]) if not pd.isna(signal_line[idx]) else None
+ })
+ histogram_result.append({
+ 'time': idx.isoformat(),
+ 'value': float(histogram[idx]) if not pd.isna(histogram[idx]) else None
+ })
+
+ return {
+ 'macd_line': macd_result,
+ 'signal_line': signal_result,
+ 'histogram': histogram_result
+ }
+
+
+def calculate_stochastic(data, k_period=14, d_period=3):
+ """Calculate Stochastic Oscillator"""
+ low_min = data['Low'].rolling(window=k_period).min()
+ high_max = data['High'].rolling(window=k_period).max()
+
+ k_values = 100 * ((data['Close'] - low_min) / (high_max - low_min))
+ d_values = k_values.rolling(window=d_period).mean()
+
+ k_result = []
+ d_result = []
+
+ for idx in k_values.index:
+ k_result.append({
+ 'time': idx.isoformat(),
+ 'value': float(k_values[idx]) if not pd.isna(k_values[idx]) else None
+ })
+ d_result.append({
+ 'time': idx.isoformat(),
+ 'value': float(d_values[idx]) if not pd.isna(d_values[idx]) else None
+ })
+
+ return {
+ 'k_values': k_result,
+ 'd_values': d_result
+ }
+
+
+def calculate_cci(data, period=20):
+ """Calculate Commodity Channel Index"""
+ tp = (data['High'] + data['Low'] + data['Close']) / 3
+ sma = tp.rolling(window=period).mean()
+ mad = tp.rolling(window=period).apply(lambda x: np.fabs(x - x.mean()).mean())
+
+ cci = (tp - sma) / (0.015 * mad)
+
+ result = []
+ for idx, value in cci.items():
+ result.append({
+ 'time': idx.isoformat(),
+ 'value': float(value) if not pd.isna(value) else None
+ })
+
+ return {'values': result}
+
+
+def calculate_roc(data, period=12):
+ """Calculate Rate of Change"""
+ roc = ((data['Close'] - data['Close'].shift(period)) / data['Close'].shift(period)) * 100
+
+ result = []
+ for idx, value in roc.items():
+ result.append({
+ 'time': idx.isoformat(),
+ 'value': float(value) if not pd.isna(value) else None
+ })
+
+ return {'values': result}
+
+
+def calculate_williams_r(data, period=14):
+ """Calculate Williams %R"""
+ high_max = data['High'].rolling(window=period).max()
+ low_min = data['Low'].rolling(window=period).min()
+
+ williams_r = -100 * ((high_max - data['Close']) / (high_max - low_min))
+
+ result = []
+ for idx, value in williams_r.items():
+ result.append({
+ 'time': idx.isoformat(),
+ 'value': float(value) if not pd.isna(value) else None
+ })
+
+ return {'values': result}
+
+
+def calculate_awesome_oscillator(data, fast_period=5, slow_period=34):
+ """Calculate Awesome Oscillator"""
+ median_price = (data['High'] + data['Low']) / 2
+
+ fast_sma = median_price.rolling(window=fast_period).mean()
+ slow_sma = median_price.rolling(window=slow_period).mean()
+
+ ao = fast_sma - slow_sma
+
+ result = []
+ for idx, value in ao.items():
+ result.append({
+ 'time': idx.isoformat(),
+ 'value': float(value) if not pd.isna(value) else None
+ })
+
+ return {'values': result}
+
+
+def calculate_tsi(data, long_period=25, short_period=13, signal_period=13):
+ """Calculate True Strength Index"""
+ price_change = data['Close'].diff()
+
+ # Double smoothed momentum
+ first_smooth = price_change.ewm(span=long_period, adjust=False).mean()
+ double_smooth = first_smooth.ewm(span=short_period, adjust=False).mean()
+
+ # Double smoothed absolute momentum
+ abs_first_smooth = price_change.abs().ewm(span=long_period, adjust=False).mean()
+ abs_double_smooth = abs_first_smooth.ewm(span=short_period, adjust=False).mean()
+
+ tsi = 100 * (double_smooth / abs_double_smooth)
+ signal_line = tsi.ewm(span=signal_period, adjust=False).mean()
+
+ tsi_result = []
+ signal_result = []
+
+ for idx in tsi.index:
+ tsi_result.append({
+ 'time': idx.isoformat(),
+ 'value': float(tsi[idx]) if not pd.isna(tsi[idx]) else None
+ })
+ signal_result.append({
+ 'time': idx.isoformat(),
+ 'value': float(signal_line[idx]) if not pd.isna(signal_line[idx]) else None
+ })
+
+ return {
+ 'values': tsi_result,
+ 'signal_line': signal_result
+ }
+
+
+def calculate_ultimate_oscillator(data, period1=7, period2=14, period3=28, weight1=4, weight2=2, weight3=1):
+ """Calculate Ultimate Oscillator"""
+ bp = data['Close'] - data[['Low', 'Close']].shift(1).min(axis=1)
+ tr = data[['High', 'Close']].shift(1).max(axis=1) - data[['Low', 'Close']].shift(1).min(axis=1)
+
+ avg1 = bp.rolling(window=period1).sum() / tr.rolling(window=period1).sum()
+ avg2 = bp.rolling(window=period2).sum() / tr.rolling(window=period2).sum()
+ avg3 = bp.rolling(window=period3).sum() / tr.rolling(window=period3).sum()
+
+ uo = 100 * ((weight1 * avg1) + (weight2 * avg2) + (weight3 * avg3)) / (weight1 + weight2 + weight3)
+
+ result = []
+ for idx, value in uo.items():
+ result.append({
+ 'time': idx.isoformat(),
+ 'value': float(value) if not pd.isna(value) else None
+ })
+
+ return {'values': result}
+
+
+def main():
+ try:
+ if len(sys.argv) < 3:
+ raise ValueError("Usage: python momentum_indicators.py <symbol> <indicator_type> <params_json>")
+
+ symbol = sys.argv[1]
+ indicator_type = sys.argv[2]
+ params = json.loads(sys.argv[3]) if len(sys.argv) > 3 else {}
+
+ # Get timeframe and interval
+ timeframe = params.get('timeframe', '1y')
+ interval = params.get('interval', '1d')
+
+ # Fetch data
+ ticker = yf.Ticker(symbol)
+ data = ticker.history(period=timeframe, interval=interval)
+
+ if data.empty:
+ raise ValueError(f"No data found for symbol {symbol}")
+
+ # Calculate indicator based on type
+ if indicator_type == 'rsi':
+ result = calculate_rsi(data, params.get('period', 14))
+ elif indicator_type == 'macd':
+ result = calculate_macd(
+ data,
+ params.get('fast_period', 12),
+ params.get('slow_period', 26),
+ params.get('signal_period', 9)
+ )
+ elif indicator_type == 'stochastic':
+ result = calculate_stochastic(
+ data,
+ params.get('k_period', 14),
+ params.get('d_period', 3)
+ )
+ elif indicator_type == 'cci':
+ result = calculate_cci(data, params.get('period', 20))
+ elif indicator_type == 'roc':
+ result = calculate_roc(data, params.get('period', 12))
+ elif indicator_type == 'williams_r':
+ result = calculate_williams_r(data, params.get('period', 14))
+ elif indicator_type == 'awesome_oscillator':
+ result = calculate_awesome_oscillator(
+ data,
+ params.get('fast_period', 5),
+ params.get('slow_period', 34)
+ )
+ elif indicator_type == 'tsi':
+ result = calculate_tsi(
+ data,
+ params.get('long_period', 25),
+ params.get('short_period', 13),
+ params.get('signal_period', 13)
+ )
+ elif indicator_type == 'ultimate_oscillator':
+ result = calculate_ultimate_oscillator(
+ data,
+ params.get('period1', 7),
+ params.get('period2', 14),
+ params.get('period3', 28),
+ params.get('weight1', 4),
+ params.get('weight2', 2),
+ params.get('weight3', 1)
+ )
+ else:
+ raise ValueError(f"Unknown indicator type: {indicator_type}")
+
+ print(json.dumps(result))
+
+ except Exception as e:
+ error_msg = {'error': str(e)}
+ print(json.dumps(error_msg))
+ sys.exit(1)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs b/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs
index c42b123e4..6f566c77b 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs
@@ -7,7 +7,6 @@
use serde::{Deserialize, Serialize};
use std::process::{Command, Stdio};
-use std::io::{BufRead, BufReader};
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use tauri::State;
@@ -77,7 +76,7 @@ pub async fn execute_lean_cli(
let args = &parts[1..];
// Execute command
- let mut child = Command::new(program)
+ let child = Command::new(program)
.args(args)
.current_dir(&working_dir)
.stdout(Stdio::piped())
@@ -300,22 +299,3 @@ fn get_python_path() -> String {
"python3".to_string()
}
}
-
-/**
- * Parse command string into program and arguments
- */
-fn parse_command(command: &str) -> (String, Vec<String>) {
- let parts: Vec<String> = command
- .split_whitespace()
- .map(|s| s.to_string())
- .collect();
-
- if parts.is_empty() {
- return (String::new(), Vec::new());
- }
-
- let program = parts[0].clone();
- let args = parts[1..].to_vec();
-
- (program, args)
-}
diff --git a/fincept-terminal-desktop/src-tauri/tauri.conf.json b/fincept-terminal-desktop/src-tauri/tauri.conf.json
index 493167b65..a189a4ab5 100644
--- a/fincept-terminal-desktop/src-tauri/tauri.conf.json
+++ b/fincept-terminal-desktop/src-tauri/tauri.conf.json
@@ -45,13 +45,7 @@
"shortDescription": "Professional-grade financial analysis platform with AI-powered insights",
"longDescription": "FinceptTerminal is an AI-Powered Finance Terminal For Investment Research. Access real-time market data, advanced analytics, and institutional-grade tools for informed investment decisions.",
"resources": [
- "resources/scripts",
- "resources/python-windows",
- "resources/python-macos",
- "resources/python-linux",
- "resources/bun-windows",
- "resources/bun-macos",
- "resources/bun-linux"
+ "resources/scripts"
],
"externalBin": [],
"windows": {
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 341564d92..1e847c634 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -217,6 +217,7 @@ export default function FinxeptTerminal() {
} else if (session.user_type === 'registered') {
const username = session.user_info?.username || session.user_info?.email || 'User';
const accountType = session.user_info?.account_type || 'free';
+ const creditBalance = session.user_info?.credit_balance ?? 0;
const hasSubscription = (session.subscription as any)?.data?.has_subscription || session.subscription?.has_subscription;
const planName = hasSubscription
? ((session.subscription as any)?.data?.subscription?.plan?.name || session.subscription?.subscription?.plan?.name || accountType)
@@ -232,6 +233,14 @@ export default function FinxeptTerminal() {
👤 {username}
</span>
<span style={{ color: '#787878' }}>|</span>
+ <span
+ onClick={() => setActiveTab('profile')}
+ style={{ cursor: 'pointer', textDecoration: 'underline', color: creditBalance > 0 ? '#10b981' : '#ef4444' }}
+ title="View Credits"
+ >
+ 💳 {creditBalance.toFixed(2)} Credits
+ </span>
+ <span style={{ color: '#787878' }}>|</span>
<span
onClick={() => navigation.navigateToPricing()}
style={{ cursor: 'pointer', textDecoration: 'underline' }}
@@ -272,95 +281,248 @@ export default function FinxeptTerminal() {
};
const handleMenuAction = async (item: any) => {
+ // If action is a function (tab navigation), execute it directly
+ if (typeof item.action === 'function') {
+ item.action();
+ setStatusMessage(`Navigated to ${item.label}`);
+ setTimeout(() => setStatusMessage(''), 2000);
+ return;
+ }
+
setStatusMessage(`${item.label} clicked`);
- // Handle specific actions
+ // Handle specific string actions
switch(item.action) {
case 'fullscreen':
toggleFullscreen();
break;
case 'refresh':
+ case 'refresh_all':
+ setStatusMessage("Refreshing all data...");
window.location.reload();
break;
case 'export':
- setStatusMessage("Export functionality not implemented");
+ case 'export_portfolio':
+ setStatusMessage("Export Portfolio - Feature coming soon");
+ setTimeout(() => setStatusMessage(''), 3000);
+ break;
+ case 'import_data':
+ setStatusMessage("Import Data - Feature coming soon");
+ setTimeout(() => setStatusMessage(''), 3000);
+ break;
+ case 'new_workspace':
+ setStatusMessage("New Workspace - Feature coming soon");
+ setTimeout(() => setStatusMessage(''), 3000);
+ break;
+ case 'open_workspace':
+ setStatusMessage("Open Workspace - Feature coming soon");
+ setTimeout(() => setStatusMessage(''), 3000);
+ break;
+ case 'save_workspace':
+ setStatusMessage("Save Workspace - Feature coming soon");
+ setTimeout(() => setStatusMessage(''), 3000);
+ break;
+ case 'zoom_in':
+ setStatusMessage("Zoom In - Use Ctrl++ in browser");
+ setTimeout(() => setStatusMessage(''), 3000);
+ break;
+ case 'zoom_out':
+ setStatusMessage("Zoom Out - Use Ctrl+- in browser");
+ setTimeout(() => setStatusMessage(''), 3000);
+ break;
+ case 'zoom_reset':
+ setStatusMessage("Reset Zoom - Use Ctrl+0 in browser");
+ setTimeout(() => setStatusMessage(''), 3000);
+ break;
+ case 'toggle_theme':
+ setStatusMessage("Toggle Theme - Feature coming soon");
+ setTimeout(() => setStatusMessage(''), 3000);
+ break;
+ case 'show_shortcuts':
+ setStatusMessage("Keyboard Shortcuts - Press F1-F12 to navigate tabs");
+ setTimeout(() => setStatusMessage(''), 5000);
+ break;
+ case 'show_about':
+ setStatusMessage(`Fincept Terminal v${APP_VERSION} - Professional Financial Platform`);
+ setTimeout(() => setStatusMessage(''), 3000);
+ break;
+ case 'check_updates':
+ setStatusMessage("Checking for updates...");
+ setTimeout(() => setStatusMessage("You are running the latest version"), 3000);
break;
case 'logout':
setStatusMessage("Logging out...");
await logout();
- // Redirect to login will be handled by App.tsx
window.location.href = '/';
break;
+ case 'exit':
+ setStatusMessage("Use Alt+F4 to close the application");
+ setTimeout(() => setStatusMessage(''), 3000);
+ break;
default:
- setTimeout(() => setStatusMessage(""), 3000);
+ setTimeout(() => setStatusMessage(''), 3000);
}
};
- // Menu configurations
+ // Keyboard shortcuts handler
+ useEffect(() => {
+ const handleKeyPress = (event: KeyboardEvent) => {
+ // Don't trigger if user is typing in an input field
+ const target = event.target as HTMLElement;
+ if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
+ return;
+ }
+
+ // Only trigger function keys without modifiers (except F11 which browser handles)
+ if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
+ return;
+ }
+
+ switch (event.key) {
+ case 'F1':
+ event.preventDefault();
+ setActiveTab('dashboard');
+ setStatusMessage('Navigated to Dashboard (F1)');
+ setTimeout(() => setStatusMessage(''), 2000);
+ break;
+ case 'F2':
+ event.preventDefault();
+ setActiveTab('markets');
+ setStatusMessage('Navigated to Markets (F2)');
+ setTimeout(() => setStatusMessage(''), 2000);
+ break;
+ case 'F3':
+ event.preventDefault();
+ setActiveTab('news');
+ setStatusMessage('Navigated to News (F3)');
+ setTimeout(() => setStatusMessage(''), 2000);
+ break;
+ case 'F4':
+ event.preventDefault();
+ setActiveTab('portfolio');
+ setStatusMessage('Navigated to Portfolio (F4)');
+ setTimeout(() => setStatusMessage(''), 2000);
+ break;
+ case 'F5':
+ event.preventDefault();
+ setActiveTab('analytics');
+ setStatusMessage('Navigated to Analytics (F5)');
+ setTimeout(() => setStatusMessage(''), 2000);
+ break;
+ case 'F6':
+ event.preventDefault();
+ setActiveTab('watchlist');
+ setStatusMessage('Navigated to Watchlist (F6)');
+ setTimeout(() => setStatusMessage(''), 2000);
+ break;
+ case 'F7':
+ event.preventDefault();
+ setActiveTab('research');
+ setStatusMessage('Navigated to Equity Research (F7)');
+ setTimeout(() => setStatusMessage(''), 2000);
+ break;
+ case 'F8':
+ event.preventDefault();
+ setActiveTab('screener');
+ setStatusMessage('Navigated to Screener (F8)');
+ setTimeout(() => setStatusMessage(''), 2000);
+ break;
+ case 'F9':
+ event.preventDefault();
+ setActiveTab('trading');
+ setStatusMessage('Navigated to Trading (F9)');
+ setTimeout(() => setStatusMessage(''), 2000);
+ break;
+ case 'F10':
+ event.preventDefault();
+ setActiveTab('chat');
+ setStatusMessage('Navigated to AI Chat (F10)');
+ setTimeout(() => setStatusMessage(''), 2000);
+ break;
+ case 'F11':
+ // Let browser handle F11 for fullscreen
+ break;
+ case 'F12':
+ event.preventDefault();
+ setActiveTab('profile');
+ setStatusMessage('Navigated to Profile (F12)');
+ setTimeout(() => setStatusMessage(''), 2000);
+ break;
+ }
+ };
+
+ window.addEventListener('keydown', handleKeyPress);
+ return () => window.removeEventListener('keydown', handleKeyPress);
+ }, []);
+
+ // Menu configurations with tab navigation
const fileMenuItems = [
- { label: 'New Workspace', shortcut: 'Ctrl+N', icon: null },
- { label: 'Open Workspace', shortcut: 'Ctrl+O', icon: null },
- { label: 'Save Workspace', shortcut: 'Ctrl+S', icon: null },
- { label: 'Export Data', shortcut: 'Ctrl+E', icon: <Download size={12} />, action: 'export', separator: true },
- { label: 'Import Settings', icon: null },
- { label: 'Exit', shortcut: 'Alt+F4', icon: null, separator: true }
+ { label: 'New Workspace', shortcut: 'Ctrl+N', icon: null, action: 'new_workspace' },
+ { label: 'Open Workspace', shortcut: 'Ctrl+O', icon: null, action: 'open_workspace' },
+ { label: 'Save Workspace', shortcut: 'Ctrl+S', icon: null, action: 'save_workspace' },
+ { label: 'Export Portfolio', shortcut: 'Ctrl+E', icon: <Download size={12} />, action: 'export', separator: true },
+ { label: 'Import Data', icon: null, action: 'import_data' },
+ { label: 'Exit', shortcut: 'Alt+F4', icon: null, action: 'exit', separator: true }
];
- const tabsMenuItems = [
- { label: 'New Tab', shortcut: 'Ctrl+T', icon: null },
- { label: 'Close Tab', shortcut: 'Ctrl+W', icon: null },
- { label: 'Close Other Tabs', icon: null },
- { label: 'Duplicate Tab', icon: null, separator: true },
- { label: 'Tab Settings', icon: <Settings size={12} /> }
+ const marketsMenuItems = [
+ { label: 'Live Markets', shortcut: 'F2', action: () => setActiveTab('markets') },
+ { label: 'Stock Screener', shortcut: 'F8', action: () => setActiveTab('screener') },
+ { label: 'Polygon Data', action: () => setActiveTab('polygon'), separator: true },
+ { label: 'Kraken Crypto', action: () => setActiveTab('kraken') },
+ { label: 'Economics', action: () => setActiveTab('economics') },
+ { label: 'DBnomics', action: () => setActiveTab('dbnomics') }
];
- const sessionMenuItems = [
- { label: 'Session Info', icon: <User size={12} /> },
- { label: 'Switch User', icon: null },
- { label: 'Extend Session', icon: null, separator: true },
- { label: 'Logout', icon: <LogOut size={12} />, action: 'logout' }
+ const researchMenuItems = [
+ { label: 'Equity Research', shortcut: 'F7', action: () => setActiveTab('research') },
+ { label: 'Geopolitics', action: () => setActiveTab('geopolitics') },
+ { label: 'Maritime Intelligence', action: () => setActiveTab('maritime') },
+ { label: 'News Feed', shortcut: 'F3', action: () => setActiveTab('news') }
];
- const apiMenuItems = [
- { label: 'API Status', icon: null },
- { label: 'Rate Limits', icon: null },
- { label: 'API Keys', icon: null, separator: true },
- { label: 'Documentation', icon: null },
- { label: 'Test Connection', icon: <RefreshCw size={12} />, action: 'refresh' }
+ const tradingMenuItems = [
+ { label: 'Trading Desk', shortcut: 'F9', action: () => setActiveTab('trading') },
+ { label: 'Fyers Broker', action: () => setActiveTab('fyers') },
+ { label: 'Backtesting', action: () => setActiveTab('backtesting'), separator: true },
+ { label: 'Portfolio', shortcut: 'F4', action: () => setActiveTab('portfolio') },
+ { label: 'Analytics', shortcut: 'F5', action: () => setActiveTab('analytics') },
+ { label: 'Watchlist', shortcut: 'F6', action: () => setActiveTab('watchlist') }
];
- const databaseMenuItems = [
- { label: 'Connect Database', icon: <Database size={12} /> },
- { label: 'Query Builder', icon: null },
- { label: 'Schema Browser', icon: null, separator: true },
- { label: 'Backup Data', icon: null },
- { label: 'Import Data', icon: null }
+ const toolsMenuItems = [
+ { label: 'AI Assistant', shortcut: 'F10', action: () => setActiveTab('chat') },
+ { label: 'MCP Servers', action: () => setActiveTab('mcp'), separator: true },
+ { label: 'Node Editor', action: () => setActiveTab('nodes') },
+ { label: 'Code Editor', action: () => setActiveTab('code') },
+ { label: 'Data Sources', action: () => setActiveTab('datasources'), separator: true },
+ { label: 'Data Mapping', action: () => setActiveTab('datamapping') },
+ { label: 'Report Builder', action: () => setActiveTab('reportbuilder') },
+ { label: 'Recorded Contexts', action: () => setActiveTab('contexts') },
+ { label: 'Settings', action: () => setActiveTab('settings'), separator: true }
];
- const viewMenuItems = [
- { label: 'Fullscreen', shortcut: 'F11', icon: isFullscreen ? <Minimize size={12} /> : <Maximize size={12} />, action: 'fullscreen' },
- { label: 'Zoom In', shortcut: 'Ctrl++', icon: null },
- { label: 'Zoom Out', shortcut: 'Ctrl+-', icon: null },
- { label: 'Reset Zoom', shortcut: 'Ctrl+0', icon: null, separator: true },
- { label: 'Show Toolbar', icon: <Eye size={12} /> },
- { label: 'Show Sidebar', icon: null }
+ const communityMenuItems = [
+ { label: 'Forum', action: () => setActiveTab('forum') },
+ { label: 'Marketplace', action: () => setActiveTab('marketplace') },
+ { label: 'Documentation', action: () => setActiveTab('docs') }
];
- const toolsMenuItems = [
- { label: 'Calculator', icon: null },
- { label: 'Screen Capture', icon: null },
- { label: 'Color Picker', icon: null, separator: true },
- { label: 'Settings', icon: <Settings size={12} /> },
- { label: 'Preferences', shortcut: 'Ctrl+,', icon: null }
+ const viewMenuItems = [
+ { label: 'Fullscreen', shortcut: 'F11', icon: isFullscreen ? <Minimize size={12} /> : <Maximize size={12} />, action: 'fullscreen' },
+ { label: 'Zoom In', shortcut: 'Ctrl++', icon: null, action: 'zoom_in' },
+ { label: 'Zoom Out', shortcut: 'Ctrl+-', icon: null, action: 'zoom_out' },
+ { label: 'Reset Zoom', shortcut: 'Ctrl+0', icon: null, action: 'zoom_reset', separator: true },
+ { label: 'Toggle Theme', icon: <Eye size={12} />, action: 'toggle_theme' }
];
const helpMenuItems = [
- { label: 'User Manual', icon: <HelpCircle size={12} /> },
- { label: 'Keyboard Shortcuts', shortcut: 'Ctrl+?', icon: null },
- { label: 'Video Tutorials', icon: null, separator: true },
- { label: 'Contact Support', icon: null },
- { label: 'Report Bug', icon: null, separator: true },
- { label: `About Finxept v${APP_VERSION}`, icon: null }
+ { label: 'Documentation', action: () => setActiveTab('docs') },
+ { label: 'Support Tickets', action: () => setActiveTab('support') },
+ { label: 'Keyboard Shortcuts', shortcut: 'Ctrl+/', action: 'show_shortcuts', separator: true },
+ { label: 'About Fincept', action: 'show_about' },
+ { label: 'Check for Updates', action: 'check_updates' },
+ { label: 'Logout', icon: <LogOut size={12} />, action: 'logout', separator: true }
];
const tabStyles = {
@@ -420,12 +582,12 @@ export default function FinxeptTerminal() {
}}>
<div style={{ display: 'flex', gap: '16px' }}>
<DropdownMenu label="File" items={fileMenuItems} onItemClick={handleMenuAction} />
- <DropdownMenu label="Tabs" items={tabsMenuItems} onItemClick={handleMenuAction} />
- <DropdownMenu label="Session" items={sessionMenuItems} onItemClick={handleMenuAction} />
- <DropdownMenu label="API" items={apiMenuItems} onItemClick={handleMenuAction} />
- <DropdownMenu label="Database" items={databaseMenuItems} onItemClick={handleMenuAction} />
- <DropdownMenu label="View" items={viewMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="Markets" items={marketsMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="Research" items={researchMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="Trading" items={tradingMenuItems} onItemClick={handleMenuAction} />
<DropdownMenu label="Tools" items={toolsMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="Community" items={communityMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="View" items={viewMenuItems} onItemClick={handleMenuAction} />
<DropdownMenu label="Help" items={helpMenuItems} onItemClick={handleMenuAction} />
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
@@ -547,191 +709,90 @@ export default function FinxeptTerminal() {
width: 'max-content',
minWidth: '100%'
}}>
- <TabsTrigger
- value="dashboard"
+ {/* PRIMARY TABS - F1 to F12 */}
+ <TabsTrigger
+ value="dashboard"
style={activeTab === 'dashboard' ? tabStyles.active : tabStyles.default}
+ title="Dashboard (F1)"
>
Dashboard
</TabsTrigger>
- <TabsTrigger
- value="markets"
+ <TabsTrigger
+ value="markets"
style={activeTab === 'markets' ? tabStyles.active : tabStyles.default}
+ title="Markets (F2)"
>
Markets
</TabsTrigger>
- <TabsTrigger
- value="news"
+ <TabsTrigger
+ value="news"
style={activeTab === 'news' ? tabStyles.active : tabStyles.default}
+ title="News (F3)"
>
News
</TabsTrigger>
- <TabsTrigger
- value="forum"
- style={activeTab === 'forum' ? tabStyles.active : tabStyles.default}
- >
- Forum
- </TabsTrigger>
- <TabsTrigger
- value="watchlist"
- style={activeTab === 'watchlist' ? tabStyles.active : tabStyles.default}
- >
- Watchlist
- </TabsTrigger>
- <TabsTrigger
- value="geopolitics"
- style={activeTab === 'geopolitics' ? tabStyles.active : tabStyles.default}
- >
- Geopolitics
- </TabsTrigger>
- <TabsTrigger
- value="chat"
- style={activeTab === 'chat' ? tabStyles.active : tabStyles.default}
- >
- AI Chat
- </TabsTrigger>
- <TabsTrigger
- value="fyers"
- style={activeTab === 'fyers' ? tabStyles.active : tabStyles.default}
- >
- Fyers
- </TabsTrigger>
- <TabsTrigger
- value="mcp"
- style={activeTab === 'mcp' ? tabStyles.active : tabStyles.default}
- >
- MCP
- </TabsTrigger>
- <TabsTrigger
- value="profile"
- style={activeTab === 'profile' ? tabStyles.active : tabStyles.default}
- >
- Profile
- </TabsTrigger>
- <TabsTrigger
- value="marketplace"
- style={activeTab === 'marketplace' ? tabStyles.active : tabStyles.default}
- >
- Marketplace
- </TabsTrigger>
<TabsTrigger
value="portfolio"
style={activeTab === 'portfolio' ? tabStyles.active : tabStyles.default}
+ title="Portfolio (F4)"
>
Portfolio
</TabsTrigger>
<TabsTrigger
value="analytics"
style={activeTab === 'analytics' ? tabStyles.active : tabStyles.default}
+ title="Analytics (F5)"
>
Analytics
</TabsTrigger>
<TabsTrigger
- value="backtesting"
- style={activeTab === 'backtesting' ? tabStyles.active : tabStyles.default}
+ value="watchlist"
+ style={activeTab === 'watchlist' ? tabStyles.active : tabStyles.default}
+ title="Watchlist (F6)"
>
- Backtesting
+ Watchlist
</TabsTrigger>
<TabsTrigger
value="research"
style={activeTab === 'research' ? tabStyles.active : tabStyles.default}
+ title="Equity Research (F7)"
>
- Equity Research
- </TabsTrigger>
- <TabsTrigger
- value="polygon"
- style={activeTab === 'polygon' ? tabStyles.active : tabStyles.default}
- >
- Polygon EQ
+ Research
</TabsTrigger>
<TabsTrigger
value="screener"
style={activeTab === 'screener' ? tabStyles.active : tabStyles.default}
+ title="Screener (F8)"
>
Screener
</TabsTrigger>
- <TabsTrigger
- value="dbnomics"
- style={activeTab === 'dbnomics' ? tabStyles.active : tabStyles.default}
- >
- DBnomics
- </TabsTrigger>
- <TabsTrigger
- value="economics"
- style={activeTab === 'economics' ? tabStyles.active : tabStyles.default}
- >
- Economics
- </TabsTrigger>
- <TabsTrigger
- value="code"
- style={activeTab === 'code' ? tabStyles.active : tabStyles.default}
- >
- Code Editor
- </TabsTrigger>
- <TabsTrigger
- value="docs"
- style={activeTab === 'docs' ? tabStyles.active : tabStyles.default}
- >
- Docs
- </TabsTrigger>
- <TabsTrigger
- value="maritime"
- style={activeTab === 'maritime' ? tabStyles.active : tabStyles.default}
- >
- Maritime
- </TabsTrigger>
- <TabsTrigger
- value="kraken"
- style={activeTab === 'kraken' ? tabStyles.active : tabStyles.default}
- >
- Kraken
- </TabsTrigger>
<TabsTrigger
value="trading"
style={activeTab === 'trading' ? tabStyles.active : tabStyles.default}
+ title="Trading (F9)"
>
Trading
</TabsTrigger>
<TabsTrigger
- value="settings"
- style={activeTab === 'settings' ? tabStyles.active : tabStyles.default}
- >
- Settings
- </TabsTrigger>
- <TabsTrigger
- value="nodes"
- style={activeTab === 'nodes' ? tabStyles.active : tabStyles.default}
- >
- Node Editor
- </TabsTrigger>
- <TabsTrigger
- value="datasources"
- style={activeTab === 'datasources' ? tabStyles.active : tabStyles.default}
- >
- Data Sources
- </TabsTrigger>
- <TabsTrigger
- value="datamapping"
- style={activeTab === 'datamapping' ? tabStyles.active : tabStyles.default}
- >
- Data Mapping
- </TabsTrigger>
- <TabsTrigger
- value="support"
- style={activeTab === 'support' ? tabStyles.active : tabStyles.default}
+ value="chat"
+ style={activeTab === 'chat' ? tabStyles.active : tabStyles.default}
+ title="AI Chat (F10)"
>
- Support
+ AI Chat
</TabsTrigger>
<TabsTrigger
- value="contexts"
- style={activeTab === 'contexts' ? tabStyles.active : tabStyles.default}
+ value="settings"
+ style={activeTab === 'settings' ? tabStyles.active : tabStyles.default}
+ title="Settings"
>
- Recorded Contexts
+ Settings
</TabsTrigger>
<TabsTrigger
- value="reportbuilder"
- style={activeTab === 'reportbuilder' ? tabStyles.active : tabStyles.default}
+ value="profile"
+ style={activeTab === 'profile' ? tabStyles.active : tabStyles.default}
+ title="Profile (F12)"
>
- Report Builder
+ Profile
</TabsTrigger>
</TabsList>
</Tabs>
@@ -773,16 +834,24 @@ export default function FinxeptTerminal() {
height: '20px',
display: 'flex',
alignItems: 'center',
- gap: '16px',
- flexShrink: 0
+ gap: '12px',
+ flexShrink: 0,
+ fontSize: '10px'
}}>
- <span style={{ color: '#fbbf24', fontSize: '10px' }}>F1:HELP</span>
- <span style={{ color: '#fbbf24', fontSize: '10px' }}>F2:MARKETS</span>
- <span style={{ color: '#fbbf24', fontSize: '10px' }}>F3:NEWS</span>
- <span style={{ color: '#fbbf24', fontSize: '10px' }}>F4:PORT</span>
- <span style={{ color: '#fbbf24', fontSize: '10px' }}>F5:MOVERS</span>
- <span style={{ color: '#fbbf24', fontSize: '10px' }}>F6:ECON</span>
- <span style={{ color: '#fbbf24', fontSize: '10px' }}>F11:FULLSCREEN</span>
+ <span style={{ color: '#fbbf24' }}>F1:DASH</span>
+ <span style={{ color: '#fbbf24' }}>F2:MKTS</span>
+ <span style={{ color: '#fbbf24' }}>F3:NEWS</span>
+ <span style={{ color: '#fbbf24' }}>F4:PORT</span>
+ <span style={{ color: '#fbbf24' }}>F5:ANLY</span>
+ <span style={{ color: '#fbbf24' }}>F6:WATCH</span>
+ <span style={{ color: '#fbbf24' }}>F7:RSRCH</span>
+ <span style={{ color: '#fbbf24' }}>F8:SCRN</span>
+ <span style={{ color: '#fbbf24' }}>F9:TRADE</span>
+ <span style={{ color: '#fbbf24' }}>F10:AI</span>
+ <span style={{ color: '#fbbf24' }}>F11:FULL</span>
+ <span style={{ color: '#fbbf24' }}>F12:PROF</span>
+ <span style={{ color: '#666', marginLeft: '8px' }}>|</span>
+ <span style={{ color: '#10b981' }}>More tabs in toolbar menus</span>
</div>
{/* Main Content Area with Tab Content */}
diff --git a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
index e744854c6..7301bb964 100644
--- a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
@@ -2,6 +2,7 @@ import React, { useState, useEffect, useRef } from 'react';
import { useTerminalTheme } from '@/contexts/ThemeContext';
import { invoke } from '@tauri-apps/api/core';
import { createChart, CandlestickSeries, HistogramSeries, LineSeries, BarSeries } from 'lightweight-charts';
+import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ComposedChart, Bar, Area } from 'recharts';
const COLORS = {
ORANGE: '#FFA500',
@@ -104,6 +105,629 @@ interface FinancialsData {
timestamp: number;
}
+// Lightweight Indicator Box Component with Parameter Controls
+const IndicatorBox: React.FC<{
+ name: string;
+ latestValue: number;
+ min: number;
+ max: number;
+ avg: number;
+ values: number[];
+ priceData: any[];
+ color: string;
+ category: string;
+ onRecompute?: (params: any) => void;
+}> = ({ name, latestValue, min, max, avg, values, priceData, color, category, onRecompute }) => {
+ const [showSettings, setShowSettings] = useState(false);
+ const [customThresholds, setCustomThresholds] = useState<{ upper: number; lower: number } | null>(null);
+ const [customParams, setCustomParams] = useState<any>(null);
+
+ const formatValue = (val: number) => {
+ if (Math.abs(val) < 0.01) return val.toFixed(6);
+ if (Math.abs(val) < 1) return val.toFixed(4);
+ if (Math.abs(val) < 100) return val.toFixed(2);
+ return val.toFixed(0);
+ };
+
+ // Only create indicator chart data (no price data for performance)
+ const chartData = values.map((value, i) => ({
+ index: i,
+ value: value || null,
+ }));
+
+ // Get default parameters for this indicator
+ const getDefaultParams = (): any => {
+ const nameUpper = name.toUpperCase();
+
+ // Moving Averages
+ if (nameUpper.includes('SMA_5')) return { period: 5 };
+ if (nameUpper.includes('SMA_10')) return { period: 10 };
+ if (nameUpper.includes('SMA_20')) return { period: 20 };
+ if (nameUpper.includes('SMA_50')) return { period: 50 };
+ if (nameUpper.includes('SMA_200')) return { period: 200 };
+ if (nameUpper.includes('EMA_9')) return { period: 9 };
+ if (nameUpper.includes('EMA_12')) return { period: 12 };
+ if (nameUpper.includes('EMA_21')) return { period: 21 };
+ if (nameUpper.includes('EMA_26')) return { period: 26 };
+ if (nameUpper.includes('EMA_50')) return { period: 50 };
+ if (nameUpper.includes('WMA')) return { period: 9 };
+
+ // RSI
+ if (nameUpper.includes('RSI')) return { period: 14 };
+
+ // MACD
+ if (nameUpper.includes('MACD')) return { fast: 12, slow: 26, signal: 9 };
+
+ // Stochastic
+ if (nameUpper.includes('STOCH')) return { k_period: 14, d_period: 3 };
+
+ // Bollinger Bands
+ if (nameUpper.includes('BB_')) return { period: 20, std: 2 };
+
+ // ATR
+ if (nameUpper.includes('ATR')) return { period: 14 };
+
+ // ADX
+ if (nameUpper.includes('ADX')) return { period: 14 };
+
+ // CCI
+ if (nameUpper.includes('CCI')) return { period: 20 };
+
+ // Williams %R
+ if (nameUpper.includes('WILLIAMS')) return { period: 14 };
+
+ // ROC
+ if (nameUpper.includes('ROC')) return { period: 12 };
+
+ // MFI
+ if (nameUpper === 'MFI') return { period: 14 };
+
+ // Aroon
+ if (nameUpper.includes('AROON')) return { period: 25 };
+
+ // Awesome Oscillator
+ if (nameUpper.includes('AWESOME') || nameUpper === 'AO') return { fast: 5, slow: 34 };
+
+ // TSI
+ if (nameUpper === 'TSI') return { long: 25, short: 13 };
+
+ // Ultimate Oscillator
+ if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) return { period1: 7, period2: 14, period3: 28 };
+
+ return null;
+ };
+
+ // Get default thresholds for this indicator
+ const getDefaultThresholds = (): { upper: number; lower: number; label: string } => {
+ const nameUpper = name.toUpperCase();
+
+ if (nameUpper.includes('RSI')) return { upper: 70, lower: 30, label: 'Overbought/Oversold' };
+ if (nameUpper.includes('STOCH')) return { upper: 80, lower: 20, label: 'Overbought/Oversold' };
+ if (nameUpper.includes('WILLIAMS')) return { upper: -20, lower: -80, label: 'Overbought/Oversold' };
+ if (nameUpper.includes('CCI')) return { upper: 100, lower: -100, label: 'Overbought/Oversold' };
+ if (nameUpper === 'TSI') return { upper: 25, lower: -25, label: 'Overbought/Oversold' };
+ if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) return { upper: 70, lower: 30, label: 'Overbought/Oversold' };
+ if (nameUpper === 'MFI') return { upper: 80, lower: 20, label: 'Overbought/Oversold' };
+ if (nameUpper.includes('ROC')) return { upper: 5, lower: -5, label: 'Strength %' };
+ if (nameUpper.includes('ADX') && !nameUpper.includes('POS') && !nameUpper.includes('NEG')) return { upper: 25, lower: 20, label: 'Trend Strength' };
+ if (nameUpper.includes('AROON')) return { upper: 70, lower: 30, label: 'Trend Strength' };
+ if (nameUpper.includes('BB_PBAND') || nameUpper.includes('KC_PBAND') || nameUpper.includes('DC_PBAND')) return { upper: 0.8, lower: 0.2, label: 'Band Position' };
+ if (nameUpper.includes('CMF')) return { upper: 0.1, lower: -0.1, label: 'Money Flow' };
+
+ return { upper: 0, lower: 0, label: 'Custom' };
+ };
+
+ const defaultThresholds = getDefaultThresholds();
+ const activeThresholds = customThresholds || defaultThresholds;
+ const defaultParams = getDefaultParams();
+ const activeParams = customParams || defaultParams;
+
+ // Comprehensive signal detection for ALL 80+ indicators
+ const getSignal = (): { signal: 'BUY' | 'SELL' | 'NEUTRAL'; reason: string } => {
+ const nameUpper = name.toUpperCase();
+ const prevValue = values[values.length - 2] || 0;
+
+ // === MOMENTUM INDICATORS ===
+ if (nameUpper.includes('RSI')) {
+ if (latestValue <= activeThresholds.lower) return { signal: 'BUY', reason: `Oversold <${activeThresholds.lower}` };
+ if (latestValue >= activeThresholds.upper) return { signal: 'SELL', reason: `Overbought >${activeThresholds.upper}` };
+ return { signal: 'NEUTRAL', reason: `${activeThresholds.lower}-${activeThresholds.upper} range` };
+ }
+
+ if (nameUpper.includes('STOCH') && !nameUpper.includes('RSI')) {
+ if (latestValue <= activeThresholds.lower) return { signal: 'BUY', reason: `Oversold <${activeThresholds.lower}` };
+ if (latestValue >= activeThresholds.upper) return { signal: 'SELL', reason: `Overbought >${activeThresholds.upper}` };
+ return { signal: 'NEUTRAL', reason: `${activeThresholds.lower}-${activeThresholds.upper} range` };
+ }
+
+ if (nameUpper.includes('WILLIAMS')) {
+ if (latestValue <= -80) return { signal: 'BUY', reason: 'Oversold' };
+ if (latestValue >= -20) return { signal: 'SELL', reason: 'Overbought' };
+ return { signal: 'NEUTRAL', reason: '-20 to -80' };
+ }
+
+ if (nameUpper === 'AO' || nameUpper.includes('AWESOME')) {
+ if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };
+ if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };
+ return { signal: 'NEUTRAL', reason: 'No crossover' };
+ }
+
+ if (nameUpper.includes('ROC')) {
+ if (latestValue > 5) return { signal: 'BUY', reason: 'Strong >5%' };
+ if (latestValue < -5) return { signal: 'SELL', reason: 'Weak <-5%' };
+ return { signal: 'NEUTRAL', reason: '-5% to 5%' };
+ }
+
+ if (nameUpper === 'TSI') {
+ if (latestValue < -25) return { signal: 'BUY', reason: 'Oversold' };
+ if (latestValue > 25) return { signal: 'SELL', reason: 'Overbought' };
+ return { signal: 'NEUTRAL', reason: '-25 to 25' };
+ }
+
+ if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) {
+ if (latestValue < 30) return { signal: 'BUY', reason: 'Oversold <30' };
+ if (latestValue > 70) return { signal: 'SELL', reason: 'Overbought >70' };
+ return { signal: 'NEUTRAL', reason: '30-70 range' };
+ }
+
+ if (nameUpper.includes('PPO') && !nameUpper.includes('SIGNAL') && !nameUpper.includes('HIST')) {
+ if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };
+ if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };
+ return { signal: 'NEUTRAL', reason: 'No crossover' };
+ }
+
+ // === TREND INDICATORS ===
+ if (nameUpper.includes('MACD') && !nameUpper.includes('SIGNAL') && !nameUpper.includes('DIFF')) {
+ if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Bullish crossover' };
+ if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Bearish crossover' };
+ return { signal: 'NEUTRAL', reason: 'No crossover' };
+ }
+
+ if (nameUpper.includes('CCI')) {
+ if (latestValue <= -100) return { signal: 'BUY', reason: 'Oversold <-100' };
+ if (latestValue >= 100) return { signal: 'SELL', reason: 'Overbought >100' };
+ return { signal: 'NEUTRAL', reason: '-100 to 100' };
+ }
+
+ if (nameUpper.includes('ADX') && !nameUpper.includes('POS') && !nameUpper.includes('NEG')) {
+ if (latestValue > 25) return { signal: 'BUY', reason: 'Strong trend >25' };
+ if (latestValue < 20) return { signal: 'NEUTRAL', reason: 'Weak trend <20' };
+ return { signal: 'NEUTRAL', reason: 'Moderate 20-25' };
+ }
+
+ if (nameUpper.includes('AROON_UP')) {
+ if (latestValue > 70) return { signal: 'BUY', reason: 'Strong uptrend' };
+ return { signal: 'NEUTRAL', reason: 'Weak uptrend' };
+ }
+
+ if (nameUpper.includes('AROON_DOWN')) {
+ if (latestValue > 70) return { signal: 'SELL', reason: 'Strong downtrend' };
+ return { signal: 'NEUTRAL', reason: 'Weak downtrend' };
+ }
+
+ if (nameUpper.includes('AROON_INDICATOR')) {
+ if (latestValue > 50) return { signal: 'BUY', reason: 'Bullish' };
+ if (latestValue < -50) return { signal: 'SELL', reason: 'Bearish' };
+ return { signal: 'NEUTRAL', reason: '-50 to 50' };
+ }
+
+ if (nameUpper.includes('PSAR_UP_INDICATOR')) {
+ if (latestValue === 1) return { signal: 'BUY', reason: 'Uptrend active' };
+ return { signal: 'NEUTRAL', reason: 'No uptrend' };
+ }
+
+ if (nameUpper.includes('PSAR_DOWN_INDICATOR')) {
+ if (latestValue === 1) return { signal: 'SELL', reason: 'Downtrend active' };
+ return { signal: 'NEUTRAL', reason: 'No downtrend' };
+ }
+
+ if (nameUpper.includes('TRIX')) {
+ if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };
+ if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };
+ return { signal: 'NEUTRAL', reason: 'No crossover' };
+ }
+
+ if (nameUpper.includes('KST') && !nameUpper.includes('SIGNAL')) {
+ if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };
+ if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };
+ return { signal: 'NEUTRAL', reason: 'No crossover' };
+ }
+
+ if (nameUpper.includes('VORTEX_POS')) {
+ if (latestValue > 1) return { signal: 'BUY', reason: 'Positive >1' };
+ return { signal: 'NEUTRAL', reason: 'Weak' };
+ }
+
+ if (nameUpper.includes('VORTEX_NEG')) {
+ if (latestValue > 1) return { signal: 'SELL', reason: 'Negative >1' };
+ return { signal: 'NEUTRAL', reason: 'Weak' };
+ }
+
+ // === VOLATILITY INDICATORS ===
+ if (nameUpper.includes('BB_PBAND') || nameUpper.includes('KC_PBAND') || nameUpper.includes('DC_PBAND')) {
+ if (latestValue < 0.2) return { signal: 'BUY', reason: 'Near lower band' };
+ if (latestValue > 0.8) return { signal: 'SELL', reason: 'Near upper band' };
+ return { signal: 'NEUTRAL', reason: 'Middle band' };
+ }
+
+ if (nameUpper.includes('BB_HBAND_INDICATOR')) {
+ if (latestValue === 1) return { signal: 'SELL', reason: 'Above upper BB' };
+ return { signal: 'NEUTRAL', reason: 'Below upper BB' };
+ }
+
+ if (nameUpper.includes('BB_LBAND_INDICATOR')) {
+ if (latestValue === 1) return { signal: 'BUY', reason: 'Below lower BB' };
+ return { signal: 'NEUTRAL', reason: 'Above lower BB' };
+ }
+
+ if (nameUpper.includes('ATR')) {
+ if (latestValue > avg * 1.5) return { signal: 'NEUTRAL', reason: 'High volatility' };
+ if (latestValue < avg * 0.5) return { signal: 'NEUTRAL', reason: 'Low volatility' };
+ return { signal: 'NEUTRAL', reason: 'Normal volatility' };
+ }
+
+ if (nameUpper.includes('UI') || nameUpper.includes('ULCER')) {
+ if (latestValue > avg * 1.5) return { signal: 'SELL', reason: 'High risk' };
+ return { signal: 'NEUTRAL', reason: 'Normal risk' };
+ }
+
+ // === VOLUME INDICATORS ===
+ if (nameUpper === 'MFI') {
+ if (latestValue <= 20) return { signal: 'BUY', reason: 'Oversold <20' };
+ if (latestValue >= 80) return { signal: 'SELL', reason: 'Overbought >80' };
+ return { signal: 'NEUTRAL', reason: '20-80 range' };
+ }
+
+ if (nameUpper.includes('CMF')) {
+ if (latestValue > 0.1) return { signal: 'BUY', reason: 'Positive flow' };
+ if (latestValue < -0.1) return { signal: 'SELL', reason: 'Negative flow' };
+ return { signal: 'NEUTRAL', reason: 'Neutral flow' };
+ }
+
+ if (nameUpper === 'OBV' || nameUpper.includes('ADI') || nameUpper.includes('VPT')) {
+ if (latestValue > prevValue) return { signal: 'BUY', reason: 'Volume rising' };
+ if (latestValue < prevValue) return { signal: 'SELL', reason: 'Volume falling' };
+ return { signal: 'NEUTRAL', reason: 'Volume stable' };
+ }
+
+ if (nameUpper.includes('EOM')) {
+ if (latestValue > 0) return { signal: 'BUY', reason: 'Ease of movement +' };
+ if (latestValue < 0) return { signal: 'SELL', reason: 'Ease of movement -' };
+ return { signal: 'NEUTRAL', reason: 'No movement' };
+ }
+
+ if (nameUpper.includes('FI') && !nameUpper.includes('MFI')) {
+ if (latestValue > 0) return { signal: 'BUY', reason: 'Force positive' };
+ if (latestValue < 0) return { signal: 'SELL', reason: 'Force negative' };
+ return { signal: 'NEUTRAL', reason: 'No force' };
+ }
+
+ // === OTHERS (RETURNS) ===
+ if (nameUpper.includes('RETURN')) {
+ if (latestValue > 2) return { signal: 'BUY', reason: 'Positive return' };
+ if (latestValue < -2) return { signal: 'SELL', reason: 'Negative return' };
+ return { signal: 'NEUTRAL', reason: 'Flat return' };
+ }
+
+ // Default for moving averages and others
+ if (nameUpper.includes('SMA') || nameUpper.includes('EMA') || nameUpper.includes('WMA')) {
+ return { signal: 'NEUTRAL', reason: 'Compare to price' };
+ }
+
+ return { signal: 'NEUTRAL', reason: 'Monitor indicator' };
+ };
+
+ const { signal, reason } = getSignal();
+ const signalColor = signal === 'BUY' ? COLORS.GREEN : signal === 'SELL' ? COLORS.RED : COLORS.GRAY;
+
+ return (
+ <div style={{
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ borderLeft: `3px solid ${color}`,
+ borderRadius: '6px',
+ padding: '12px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '8px',
+ minHeight: showSettings ? '480px' : '320px',
+ height: 'auto',
+ boxShadow: '0 1px 3px rgba(0, 0, 0, 0.3)',
+ transition: 'all 0.2s ease',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = color;
+ e.currentTarget.style.boxShadow = `0 4px 12px rgba(0, 0, 0, 0.5)`;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = COLORS.BORDER;
+ e.currentTarget.style.boxShadow = '0 1px 3px rgba(0, 0, 0, 0.3)';
+ }}
+ >
+ {/* Header */}
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <div style={{ color: color, fontSize: '10px', fontWeight: 'bold', marginBottom: '2px' }}>
+ {category}
+ </div>
+ <div style={{ color: COLORS.WHITE, fontSize: '11px', fontWeight: 'bold' }}>
+ {name.toUpperCase().replace(/_/g, ' ')}
+ </div>
+ </div>
+ <div style={{ textAlign: 'right' }}>
+ <div style={{ color: COLORS.WHITE, fontSize: '16px', fontWeight: 'bold' }}>
+ {formatValue(latestValue)}
+ </div>
+ <div style={{ color: COLORS.GRAY, fontSize: '9px' }}>
+ Current
+ </div>
+ </div>
+ </div>
+
+ {/* Lightweight Chart - ONLY indicator line */}
+ <div style={{ width: '100%', height: '80px', flex: '0 0 auto' }}>
+ <ResponsiveContainer width="100%" height="100%">
+ <LineChart data={chartData} margin={{ top: 5, right: 5, left: 5, bottom: 5 }}>
+ <CartesianGrid strokeDasharray="3 3" stroke={COLORS.BORDER} opacity={0.3} />
+ <XAxis dataKey="index" hide />
+ <YAxis domain={['auto', 'auto']} hide />
+ <Tooltip
+ contentStyle={{
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ borderRadius: '4px',
+ fontSize: '10px',
+ }}
+ formatter={(value: any) => formatValue(value)}
+ />
+ <Line
+ type="monotone"
+ dataKey="value"
+ stroke={color}
+ strokeWidth={2}
+ dot={false}
+ connectNulls
+ isAnimationActive={false}
+ />
+ </LineChart>
+ </ResponsiveContainer>
+ </div>
+
+ {/* Signal Badge */}
+ <div style={{
+ display: 'flex',
+ justifyContent: 'center',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '4px',
+ backgroundColor: `${signalColor}15`,
+ border: `1px solid ${signalColor}`,
+ borderRadius: '4px',
+ }}>
+ <span style={{ color: signalColor, fontSize: '11px', fontWeight: 'bold' }}>
+ {signal}
+ </span>
+ <span style={{ color: COLORS.GRAY, fontSize: '9px' }}>
+ {reason}
+ </span>
+ </div>
+
+ {/* Settings Toggle & Parameters */}
+ <div style={{ flex: '0 0 auto' }}>
+ <button
+ onClick={() => setShowSettings(!showSettings)}
+ style={{
+ fontSize: '9px',
+ fontWeight: '500',
+ textAlign: 'center',
+ padding: '4px 8px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ width: '100%',
+ userSelect: 'none',
+ backgroundColor: showSettings ? COLORS.DARK_BG : COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ borderRadius: '3px',
+ color: COLORS.GRAY,
+ transition: 'all 0.15s ease',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = COLORS.ORANGE;
+ e.currentTarget.style.color = COLORS.ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = COLORS.BORDER;
+ e.currentTarget.style.color = COLORS.GRAY;
+ }}
+ >
+ <span style={{ fontSize: '10px' }}>⚙️</span>
+ <span>{showSettings ? 'Hide' : 'Adjust'}</span>
+ </button>
+
+ {showSettings && (
+ <div style={{
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ borderRadius: '4px',
+ padding: '10px',
+ marginTop: '8px',
+ fontSize: '10px',
+ }}>
+ {/* Indicator Parameters Section */}
+ {defaultParams && (
+ <div style={{ marginBottom: defaultThresholds.upper !== 0 ? '12px' : '0' }}>
+ <div style={{ color: COLORS.CYAN, fontWeight: 'bold', marginBottom: '8px', fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <span>📊</span>
+ <span>Indicator Parameters</span>
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))', gap: '8px', marginBottom: '8px' }}>
+ {Object.keys(defaultParams).map((key) => (
+ <div key={key}>
+ <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px', textTransform: 'capitalize' }}>
+ {key.replace(/_/g, ' ')}
+ </label>
+ <input
+ type="number"
+ step="1"
+ value={customParams?.[key] ?? defaultParams[key]}
+ onChange={(e) => setCustomParams({
+ ...defaultParams,
+ ...customParams,
+ [key]: parseInt(e.target.value) || 1
+ })}
+ style={{
+ width: '100%',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ borderRadius: '3px',
+ color: COLORS.WHITE,
+ padding: '4px 6px',
+ fontSize: '10px',
+ }}
+ />
+ </div>
+ ))}
+ </div>
+
+ {customParams && (
+ <button
+ onClick={() => {
+ // Call recompute with new parameters
+ if (onRecompute) {
+ onRecompute({ indicator: name, params: customParams });
+ }
+ }}
+ style={{
+ width: '100%',
+ backgroundColor: COLORS.CYAN,
+ border: 'none',
+ borderRadius: '3px',
+ color: COLORS.DARK_BG,
+ padding: '6px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ fontWeight: 'bold',
+ marginBottom: '6px',
+ }}
+ >
+ 🔄 Recompute with New Parameters
+ </button>
+ )}
+ </div>
+ )}
+
+ {/* Signal Thresholds Section */}
+ {defaultThresholds.upper !== 0 && (
+ <div>
+ <div style={{ color: COLORS.ORANGE, fontWeight: 'bold', marginBottom: '8px', fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <span>🎯</span>
+ <span>{defaultThresholds.label}</span>
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '8px' }}>
+ <div>
+ <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px' }}>
+ Upper Threshold
+ </label>
+ <input
+ type="number"
+ step="0.1"
+ value={customThresholds?.upper ?? defaultThresholds.upper}
+ onChange={(e) => setCustomThresholds({
+ upper: parseFloat(e.target.value),
+ lower: customThresholds?.lower ?? defaultThresholds.lower
+ })}
+ style={{
+ width: '100%',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ borderRadius: '3px',
+ color: COLORS.WHITE,
+ padding: '4px 6px',
+ fontSize: '10px',
+ }}
+ />
+ </div>
+
+ <div>
+ <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px' }}>
+ Lower Threshold
+ </label>
+ <input
+ type="number"
+ step="0.1"
+ value={customThresholds?.lower ?? defaultThresholds.lower}
+ onChange={(e) => setCustomThresholds({
+ upper: customThresholds?.upper ?? defaultThresholds.upper,
+ lower: parseFloat(e.target.value)
+ })}
+ style={{
+ width: '100%',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ borderRadius: '3px',
+ color: COLORS.WHITE,
+ padding: '4px 6px',
+ fontSize: '10px',
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Reset Button */}
+ <button
+ onClick={() => {
+ setCustomThresholds(null);
+ setCustomParams(null);
+ }}
+ style={{
+ width: '100%',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ borderRadius: '3px',
+ color: COLORS.GRAY,
+ padding: '5px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: '600',
+ }}
+ >
+ Reset All to Defaults
+ </button>
+ </div>
+ )}
+ </div>
+
+ {/* Stats */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', fontSize: '9px' }}>
+ <div>
+ <div style={{ color: COLORS.GRAY }}>MIN</div>
+ <div style={{ color: COLORS.RED, fontWeight: 'bold' }}>{formatValue(min)}</div>
+ </div>
+ <div>
+ <div style={{ color: COLORS.GRAY }}>AVG</div>
+ <div style={{ color: COLORS.YELLOW, fontWeight: 'bold' }}>{formatValue(avg)}</div>
+ </div>
+ <div>
+ <div style={{ color: COLORS.GRAY }}>MAX</div>
+ <div style={{ color: COLORS.GREEN, fontWeight: 'bold' }}>{formatValue(max)}</div>
+ </div>
+ </div>
+
+ {/* Data Points Count */}
+ <div style={{ color: COLORS.GRAY, fontSize: '9px', textAlign: 'center', borderTop: `1px solid ${COLORS.BORDER}`, paddingTop: '4px' }}>
+ {values.length} data points
+ </div>
+ </div>
+ );
+};
+
const EquityResearchTab: React.FC = () => {
const { colors, fontSize: themeFontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [searchSymbol, setSearchSymbol] = useState('');
@@ -252,6 +876,48 @@ const EquityResearchTab: React.FC = () => {
}
};
+ // Fetch company news
+ const fetchNews = async () => {
+ if (!currentSymbol) {
+ console.log('No symbol selected for news fetch');
+ return;
+ }
+
+ setNewsLoading(true);
+ console.log('Fetching news for:', currentSymbol);
+
+ try {
+ // Use company name if available, otherwise use symbol
+ const query = stockInfo?.company_name || currentSymbol;
+
+ const response: any = await invoke('fetch_company_news', {
+ query: query,
+ maxResults: 20,
+ period: '7d',
+ language: 'en',
+ country: 'US'
+ });
+
+ console.log('News response:', response);
+
+ if (typeof response === 'string') {
+ const parsed = JSON.parse(response);
+ setNewsData(parsed);
+ } else {
+ setNewsData(response);
+ }
+ } catch (error) {
+ console.error('Error fetching news:', error);
+ setNewsData({
+ success: false,
+ error: String(error),
+ data: []
+ });
+ } finally {
+ setNewsLoading(false);
+ }
+ };
+
// Initialize price chart with volume
useEffect(() => {
if (chartContainerRef.current && !chartRef.current) {
@@ -493,6 +1159,13 @@ const EquityResearchTab: React.FC = () => {
const computeTechnicals = async (historical: HistoricalData[]) => {
setTechnicalsLoading(true);
try {
+ // Validate historical data
+ if (!historical || !Array.isArray(historical) || historical.length === 0) {
+ console.error('Invalid historical data for technicals computation');
+ setTechnicalsData(null);
+ return;
+ }
+
// Convert historical data to format expected by Python script
const historicalJson = JSON.stringify(historical.map(d => ({
timestamp: d.timestamp,
@@ -503,24 +1176,38 @@ const EquityResearchTab: React.FC = () => {
volume: d.volume
})));
+ console.log('Sending historical data for technicals computation:', historical.length, 'data points');
+
const response: any = await invoke('compute_all_technicals', {
historicalData: historicalJson
});
console.log('Technicals response:', response);
+ console.log('Response type:', typeof response);
+ console.log('Response keys:', response ? Object.keys(response) : 'null');
if (typeof response === 'string') {
- const parsed = JSON.parse(response);
- if (parsed.success && parsed.data) {
- setTechnicalsData(parsed);
- } else {
- console.error('Error computing technicals:', parsed.error);
+ try {
+ const parsed = JSON.parse(response);
+ if (parsed.success && parsed.data && Array.isArray(parsed.data) && parsed.data.length > 0) {
+ setTechnicalsData(parsed);
+ } else {
+ console.error('Error computing technicals:', parsed.error || 'Invalid data structure');
+ setTechnicalsData(null);
+ }
+ } catch (parseError) {
+ console.error('Error parsing technicals response:', parseError);
+ setTechnicalsData(null);
}
- } else if (response.success && response.data) {
+ } else if (response && response.success && response.data && Array.isArray(response.data) && response.data.length > 0) {
setTechnicalsData(response);
+ } else {
+ console.error('Invalid technicals response structure');
+ setTechnicalsData(null);
}
} catch (error) {
console.error('Error computing technicals:', error);
+ setTechnicalsData(null);
} finally {
setTechnicalsLoading(false);
}
@@ -538,6 +1225,13 @@ const EquityResearchTab: React.FC = () => {
}
}, [historicalData]);
+ // Fetch news when news tab is activated or symbol changes
+ useEffect(() => {
+ if (activeTab === 'news' && currentSymbol) {
+ fetchNews();
+ }
+ }, [activeTab, currentSymbol]);
+
const handleSearch = () => {
if (searchSymbol.trim()) {
setCurrentSymbol(searchSymbol.trim().toUpperCase());
@@ -1701,6 +2395,208 @@ const EquityResearchTab: React.FC = () => {
</div>
)}
+ {/* News Tab */}
+ {activeTab === 'news' && (
+ <div style={{ padding: '8px', height: 'calc(100vh - 280px)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
+ {newsLoading ? (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '400px',
+ gap: '16px',
+ }}>
+ <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>
+ ⏳ FETCHING LATEST NEWS...
+ </div>
+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>
+ Loading news for {currentSymbol}
+ </div>
+ </div>
+ ) : !newsData || !newsData.success ? (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '400px',
+ gap: '16px',
+ }}>
+ <div style={{ color: COLORS.RED, fontSize: '14px', fontWeight: 'bold' }}>
+ ⚠️ NO NEWS AVAILABLE
+ </div>
+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>
+ {newsData?.error || 'Unable to fetch news at this time'}
+ </div>
+ <button
+ onClick={fetchNews}
+ style={{
+ backgroundColor: COLORS.ORANGE,
+ border: 'none',
+ color: COLORS.DARK_BG,
+ padding: '8px 16px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ fontWeight: 'bold',
+ marginTop: '8px',
+ }}
+ >
+ RETRY
+ </button>
+ </div>
+ ) : newsData.data && newsData.data.length === 0 ? (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '400px',
+ gap: '16px',
+ }}>
+ <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>
+ 📰 NO NEWS FOUND
+ </div>
+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>
+ No recent news articles found for {stockInfo?.company_name || currentSymbol}
+ </div>
+ </div>
+ ) : (
+ <>
+ {/* News Header */}
+ <div style={{
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ padding: '8px 12px',
+ marginBottom: '8px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexShrink: 0,
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <span style={{ color: COLORS.ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
+ 📰 LATEST NEWS
+ </span>
+ <span style={{ color: COLORS.GRAY, fontSize: '9px' }}>
+ {newsData.count || 0} articles found
+ </span>
+ <span style={{ color: COLORS.CYAN, fontSize: '9px' }}>
+ {stockInfo?.company_name || currentSymbol}
+ </span>
+ </div>
+ <button
+ onClick={fetchNews}
+ style={{
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ padding: '4px 12px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: 'bold',
+ }}
+ >
+ 🔄 REFRESH
+ </button>
+ </div>
+
+ {/* News Articles List */}
+ <div style={{
+ flex: 1,
+ overflow: 'auto',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '8px',
+ }} className="custom-scrollbar">
+ {newsData.data.map((article: any, index: number) => (
+ <div
+ key={index}
+ style={{
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ padding: '12px',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#252525';
+ e.currentTarget.style.borderColor = COLORS.ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = COLORS.PANEL_BG;
+ e.currentTarget.style.borderColor = COLORS.BORDER;
+ }}
+ onClick={() => {
+ if (article.url && article.url !== '#') {
+ window.open(article.url, '_blank');
+ }
+ }}
+ >
+ {/* Article Header */}
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
+ <div style={{ flex: 1, marginRight: '12px' }}>
+ <h3 style={{
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ margin: 0,
+ marginBottom: '6px',
+ lineHeight: '1.4',
+ }}>
+ {article.title}
+ </h3>
+ <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
+ <span style={{
+ color: COLORS.CYAN,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ }}>
+ {article.publisher || 'Unknown Source'}
+ </span>
+ <span style={{
+ color: COLORS.GRAY,
+ fontSize: '9px',
+ }}>
+ {article.published_date || 'Unknown Date'}
+ </span>
+ </div>
+ </div>
+ </div>
+
+ {/* Article Description */}
+ {article.description && article.description !== 'N/A' && (
+ <div style={{
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ lineHeight: '1.5',
+ marginBottom: '8px',
+ }}>
+ {article.description}
+ </div>
+ )}
+
+ {/* Read More Link */}
+ {article.url && article.url !== '#' && (
+ <div style={{
+ color: COLORS.ORANGE,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}>
+ READ FULL ARTICLE →
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ )}
+
{/* Technicals Tab */}
{activeTab === 'technicals' && (
<div style={{ padding: '8px' }}>
@@ -1737,145 +2633,159 @@ const EquityResearchTab: React.FC = () => {
</div>
</div>
) : (
- <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '8px', height: 'calc(100vh - 280px)' }}>
- {/* Left Side - Charts */}
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', overflow: 'auto' }} className="custom-scrollbar">
+ <div style={{ padding: '8px', overflow: 'auto', height: 'calc(100vh - 280px)' }} className="custom-scrollbar">
+ {/* Check if we have valid indicator data */}
+ {(!technicalsData.indicator_columns || !technicalsData.data || !Array.isArray(technicalsData.data) || technicalsData.data.length === 0) ? (
<div style={{
backgroundColor: COLORS.PANEL_BG,
border: `1px solid ${COLORS.BORDER}`,
- padding: '12px',
+ padding: '16px',
+ textAlign: 'center',
+ color: COLORS.YELLOW,
}}>
- <div style={{ color: COLORS.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>
- TECHNICAL INDICATORS - CHARTS (Coming Soon)
+ <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ ⚠️ NO INDICATOR DATA
</div>
- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>
- Interactive charts for RSI, MACD, Bollinger Bands, and other indicators will be displayed here.
+ <div style={{ fontSize: '11px', color: COLORS.GRAY }}>
+ Technical indicators could not be computed. Please try again or select a different symbol.
</div>
</div>
- </div>
+ ) : (
+ <>
+ {/* Render Individual Indicator Boxes */}
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))', gap: '16px' }}>
+ {/* Trend Indicators */}
+ {technicalsData.indicator_columns?.trend && Array.isArray(technicalsData.indicator_columns.trend) &&
+ technicalsData.indicator_columns.trend.map((indicator: string) => {
+ const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);
+ if (values.length === 0) return null;
+ const latestValue = values[values.length - 1];
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;
- {/* Right Side - Values */}
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', overflow: 'auto' }} className="custom-scrollbar">
- {/* Trend Indicators */}
- {technicalsData.indicator_columns?.trend && (
- <div style={{
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- padding: '8px',
- }}>
- <div style={{ color: COLORS.CYAN, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>
- TREND INDICATORS
- </div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>
- {technicalsData.indicator_columns.trend.slice(0, 10).map((indicator: string) => {
- const latestValue = technicalsData.data[technicalsData.data.length - 1]?.[indicator];
return (
- <div key={indicator} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}>
- <span style={{ color: COLORS.GRAY }}>{indicator.toUpperCase()}:</span>
- <span style={{ color: COLORS.WHITE }}>{latestValue != null ? formatNumber(latestValue, 4) : 'N/A'}</span>
- </div>
+ <IndicatorBox
+ key={indicator}
+ name={indicator}
+ latestValue={latestValue}
+ min={min}
+ max={max}
+ avg={avg}
+ values={values}
+ priceData={historicalData}
+ color={COLORS.CYAN}
+ category="TREND"
+ />
);
})}
- </div>
- </div>
- )}
- {/* Momentum Indicators */}
- {technicalsData.indicator_columns?.momentum && (
- <div style={{
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- padding: '8px',
- }}>
- <div style={{ color: COLORS.GREEN, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>
- MOMENTUM INDICATORS
- </div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>
- {technicalsData.indicator_columns.momentum.slice(0, 10).map((indicator: string) => {
- const latestValue = technicalsData.data[technicalsData.data.length - 1]?.[indicator];
+ {/* Momentum Indicators */}
+ {technicalsData.indicator_columns?.momentum && Array.isArray(technicalsData.indicator_columns.momentum) &&
+ technicalsData.indicator_columns.momentum.map((indicator: string) => {
+ const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);
+ if (values.length === 0) return null;
+ const latestValue = values[values.length - 1];
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;
+
return (
- <div key={indicator} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}>
- <span style={{ color: COLORS.GRAY }}>{indicator.toUpperCase()}:</span>
- <span style={{ color: COLORS.WHITE }}>{latestValue != null ? formatNumber(latestValue, 4) : 'N/A'}</span>
- </div>
+ <IndicatorBox
+ key={indicator}
+ name={indicator}
+ latestValue={latestValue}
+ min={min}
+ max={max}
+ avg={avg}
+ values={values}
+ priceData={historicalData}
+ color={COLORS.GREEN}
+ category="MOMENTUM"
+ />
);
})}
- </div>
- </div>
- )}
- {/* Volatility Indicators */}
- {technicalsData.indicator_columns?.volatility && (
- <div style={{
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- padding: '8px',
- }}>
- <div style={{ color: COLORS.YELLOW, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>
- VOLATILITY INDICATORS
- </div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>
- {technicalsData.indicator_columns.volatility.slice(0, 10).map((indicator: string) => {
- const latestValue = technicalsData.data[technicalsData.data.length - 1]?.[indicator];
+ {/* Volatility Indicators */}
+ {technicalsData.indicator_columns?.volatility && Array.isArray(technicalsData.indicator_columns.volatility) &&
+ technicalsData.indicator_columns.volatility.map((indicator: string) => {
+ const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);
+ if (values.length === 0) return null;
+ const latestValue = values[values.length - 1];
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;
+
return (
- <div key={indicator} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}>
- <span style={{ color: COLORS.GRAY }}>{indicator.toUpperCase()}:</span>
- <span style={{ color: COLORS.WHITE }}>{latestValue != null ? formatNumber(latestValue, 4) : 'N/A'}</span>
- </div>
+ <IndicatorBox
+ key={indicator}
+ name={indicator}
+ latestValue={latestValue}
+ min={min}
+ max={max}
+ avg={avg}
+ values={values}
+ priceData={historicalData}
+ color={COLORS.YELLOW}
+ category="VOLATILITY"
+ />
);
})}
- </div>
- </div>
- )}
- {/* Volume Indicators */}
- {technicalsData.indicator_columns?.volume && (
- <div style={{
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- padding: '8px',
- }}>
- <div style={{ color: COLORS.BLUE, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>
- VOLUME INDICATORS
- </div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>
- {technicalsData.indicator_columns.volume.map((indicator: string) => {
- const latestValue = technicalsData.data[technicalsData.data.length - 1]?.[indicator];
+ {/* Volume Indicators */}
+ {technicalsData.indicator_columns?.volume && Array.isArray(technicalsData.indicator_columns.volume) &&
+ technicalsData.indicator_columns.volume.map((indicator: string) => {
+ const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);
+ if (values.length === 0) return null;
+ const latestValue = values[values.length - 1];
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;
+
return (
- <div key={indicator} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}>
- <span style={{ color: COLORS.GRAY }}>{indicator.toUpperCase()}:</span>
- <span style={{ color: COLORS.WHITE }}>{latestValue != null ? formatNumber(latestValue, 4) : 'N/A'}</span>
- </div>
+ <IndicatorBox
+ key={indicator}
+ name={indicator}
+ latestValue={latestValue}
+ min={min}
+ max={max}
+ avg={avg}
+ values={values}
+ priceData={historicalData}
+ color={COLORS.BLUE}
+ category="VOLUME"
+ />
);
})}
- </div>
- </div>
- )}
- {/* Others Indicators */}
- {technicalsData.indicator_columns?.others && (
- <div style={{
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- padding: '8px',
- }}>
- <div style={{ color: COLORS.MAGENTA, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>
- RETURN METRICS
- </div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>
- {technicalsData.indicator_columns.others.map((indicator: string) => {
- const latestValue = technicalsData.data[technicalsData.data.length - 1]?.[indicator];
+ {/* Others Indicators */}
+ {technicalsData.indicator_columns?.others && Array.isArray(technicalsData.indicator_columns.others) &&
+ technicalsData.indicator_columns.others.map((indicator: string) => {
+ const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);
+ if (values.length === 0) return null;
+ const latestValue = values[values.length - 1];
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;
+
return (
- <div key={indicator} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}>
- <span style={{ color: COLORS.GRAY }}>{indicator.toUpperCase()}:</span>
- <span style={{ color: COLORS.WHITE }}>{latestValue != null ? formatNumber(latestValue, 6) : 'N/A'}</span>
- </div>
+ <IndicatorBox
+ key={indicator}
+ name={indicator}
+ latestValue={latestValue}
+ min={min}
+ max={max}
+ avg={avg}
+ values={values}
+ priceData={historicalData}
+ color={COLORS.MAGENTA}
+ category="RETURN"
+ />
);
})}
- </div>
</div>
- )}
- </div>
+ </>
+ )}
</div>
)}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx b/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx
index 18a6536ce..13762b6a7 100644
--- a/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx
@@ -7,20 +7,7 @@ import { useTerminalTheme } from '@/contexts/ThemeContext';
type ProfileScreen = 'overview' | 'usage' | 'payments' | 'subscriptions' | 'support' | 'settings';
const ProfileTab: React.FC = () => {
- const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
- const C = {
- ORANGE: colors.primary,
- WHITE: colors.text,
- RED: colors.alert,
- GREEN: colors.secondary,
- YELLOW: colors.warning,
- GRAY: colors.textMuted,
- BLUE: colors.info,
- PURPLE: colors.purple,
- CYAN: colors.accent,
- DARK_BG: colors.background,
- PANEL_BG: colors.panel
- };
+ const { colors } = useTerminalTheme();
const { session, logout } = useAuth();
const navigation = useNavigation();
const [currentTime, setCurrentTime] = useState(new Date());
@@ -39,6 +26,17 @@ const ProfileTab: React.FC = () => {
return () => clearInterval(timer);
}, []);
+ // F11 fullscreen toggle
+ const toggleFullscreen = () => {
+ if (!document.fullscreenElement) {
+ document.documentElement.requestFullscreen();
+ } else {
+ if (document.exitFullscreen) {
+ document.exitFullscreen();
+ }
+ }
+ };
+
// Fetch data based on current screen
useEffect(() => {
if (!session?.api_key) return;
@@ -54,7 +52,6 @@ const ProfileTab: React.FC = () => {
const result = await UserApiService.getUserUsage(session.api_key || '');
if (result.success) setUsageData(result.data);
- // Also fetch detailed usage
const detailedResult = await UserApiService.getUsageDetails(session.api_key || '');
if (detailedResult.success) setDetailedUsage(detailedResult.data);
}
@@ -125,18 +122,6 @@ const ProfileTab: React.FC = () => {
}
};
- const reactivateSubscription = async () => {
- if (!session?.api_key) return;
- setLoading(true);
- const result = await UserApiService.reactivateSubscription(session.api_key || '');
- setLoading(false);
- if (result.success) {
- alert('Subscription reactivated successfully!');
- } else {
- alert(`Failed to reactivate subscription: ${result.error}`);
- }
- };
-
const deleteAccount = async () => {
if (!session?.api_key) return;
const confirmation = prompt('This action cannot be undone. Type "DELETE MY ACCOUNT" to confirm:');
@@ -166,42 +151,7 @@ const ProfileTab: React.FC = () => {
return `$${(amount / 100).toFixed(2)}`;
};
- // Navigation buttons
- const renderNavigationButtons = () => {
- const buttons: { id: ProfileScreen; label: string; color: string }[] = [
- { id: 'overview', label: 'OVERVIEW', color: C.ORANGE },
- { id: 'usage', label: 'USAGE STATS', color: C.CYAN },
- { id: 'payments', label: 'PAYMENTS', color: C.GREEN },
- { id: 'subscriptions', label: 'SUBSCRIPTIONS', color: C.PURPLE },
- { id: 'support', label: 'SUPPORT', color: C.BLUE },
- { id: 'settings', label: 'SETTINGS', color: C.RED },
- ];
-
- return (
- <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', flexWrap: 'wrap' }}>
- {buttons.map((btn) => (
- <button
- key={btn.id}
- onClick={() => setCurrentScreen(btn.id)}
- style={{
- padding: '8px 16px',
- backgroundColor: currentScreen === btn.id ? btn.color : C.DARK_BG,
- border: `2px solid ${btn.color}`,
- color: currentScreen === btn.id ? C.DARK_BG : btn.color,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- transition: 'all 0.2s'
- }}
- >
- {btn.label}
- </button>
- ))}
- </div>
- );
- };
-
+ // Guest Profile View
const renderGuestProfile = () => {
const displayDeviceId = session?.device_id?.substring(0, 30) + "..." || 'Unknown';
const requestsToday = session?.requests_today || usageData?.requests_today || 0;
@@ -210,465 +160,478 @@ const ProfileTab: React.FC = () => {
const usagePercent = (requestsToday / dailyLimit) * 100;
return (
- <div style={{ height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: C.DARK_BG }}>
+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: colors.background, overflow: 'hidden' }}>
{/* Header */}
- <div style={{ backgroundColor: C.PANEL_BG, borderBottom: `2px solid ${C.GRAY}`, padding: '12px 16px' }}>
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: C.ORANGE, fontWeight: 'bold', fontSize: '16px', fontFamily: 'Consolas, monospace' }}>
- 👤 GUEST PROFILE
- </span>
- <span style={{ color: C.GRAY }}>|</span>
- <span style={{ color: C.CYAN, fontSize: '12px', fontFamily: 'Consolas, monospace' }}>
- {currentTime.toLocaleTimeString()}
- </span>
- </div>
- <button
- onClick={logoutUser}
- style={{
- padding: '6px 12px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.RED}`,
- color: C.RED,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- 🚪 LOGOUT
- </button>
+ <div style={{ backgroundColor: colors.panel, borderBottom: `1px solid ${colors.textMuted}`, padding: '4px 8px', flexShrink: 0 }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>FINCEPT TERMINAL GUEST PROFILE</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.text }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>REQUESTS:</span>
+ <span style={{ color: colors.accent }}>{requestsToday}/{dailyLimit}</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>REMAINING:</span>
+ <span style={{ color: remaining > 10 ? colors.secondary : colors.alert }}>{remaining}</span>
</div>
</div>
- {/* Content */}
- <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
- {renderNavigationButtons()}
+ {/* Function Keys Bar */}
+ <div style={{ backgroundColor: colors.panel, borderBottom: `1px solid ${colors.textMuted}`, padding: '2px 4px', flexShrink: 0 }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '2px' }}>
+ {[
+ { key: "F1", label: "OVERVIEW", screen: "overview" },
+ { key: "F2", label: "USAGE", screen: "usage" },
+ { key: "F3", label: "SETTINGS", screen: "settings" },
+ { key: "F4", label: "EXTEND", action: 'extend' },
+ { key: "F5", label: "PRICING", action: 'pricing' },
+ { key: "F6", label: "LOGOUT", action: 'logout' }
+ ].map(item => (
+ <button key={item.key}
+ onClick={() => {
+ if (item.action === 'extend') extendSession();
+ else if (item.action === 'pricing') navigation.navigateToPricing();
+ else if (item.action === 'logout') logoutUser();
+ else if (item.screen) setCurrentScreen(item.screen as ProfileScreen);
+ }}
+ disabled={loading && (item.action === 'extend')}
+ style={{
+ backgroundColor: currentScreen === item.screen ? colors.primary : colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: currentScreen === item.screen ? colors.background : colors.text,
+ padding: '2px 4px',
+ fontSize: '12px',
+ height: '16px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontWeight: currentScreen === item.screen ? 'bold' : 'normal',
+ cursor: 'pointer'
+ }}>
+ <span style={{ color: colors.warning }}>{item.key}:</span>
+ <span style={{ marginLeft: '2px' }}>{item.label}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ {/* Main Content */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '4px', backgroundColor: '#050505' }}>
{currentScreen === 'overview' && (
- <>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px', marginBottom: '16px' }}>
- {/* Session Info */}
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.BLUE}`, padding: '16px' }}>
- <div style={{ color: C.BLUE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- SESSION INFORMATION
+ <div style={{ display: 'flex', gap: '4px', height: '100%' }}>
+ {/* Left Column */}
+ <div style={{ flex: 1, backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '4px', overflow: 'auto' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ SESSION INFORMATION
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
+
+ <div style={{ marginBottom: '8px', fontSize: '12px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Account Type:</span>
+ <span style={{ color: colors.warning, fontWeight: 'bold' }}>GUEST</span>
</div>
- <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.8' }}>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Account Type:</span>
- <span style={{ color: C.YELLOW, marginLeft: '8px', fontWeight: 'bold' }}>GUEST USER</span>
- </div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Device ID:</span>
- <div style={{ color: C.WHITE, marginTop: '4px', fontSize: '10px' }}>{displayDeviceId}</div>
- </div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>API Key:</span>
- <div style={{ color: C.WHITE, marginTop: '4px', fontSize: '10px' }}>
- {session?.api_key ? `${session.api_key.substring(0, 20)}...` : 'N/A'}
- </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Session Expires:</span>
+ <span style={{ color: colors.alert }}>{session?.expires_at ? formatDate(session.expires_at) : 'N/A'}</span>
+ </div>
+ <div style={{ marginBottom: '2px', paddingTop: '4px', borderTop: `1px solid ${colors.textMuted}` }}>
+ <span style={{ color: colors.textMuted }}>Device ID:</span>
+ <div style={{ color: colors.text, fontSize: '11px', marginTop: '2px', wordBreak: 'break-all' }}>
+ {displayDeviceId}
</div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Session Expires:</span>
- <span style={{ color: C.ORANGE, marginLeft: '8px' }}>
- {session?.expires_at ? formatDate(session.expires_at) : 'N/A'}
- </span>
+ </div>
+ <div style={{ marginBottom: '2px', paddingTop: '4px', borderTop: `1px solid ${colors.textMuted}` }}>
+ <span style={{ color: colors.textMuted }}>API Key:</span>
+ <div style={{ color: colors.text, fontSize: '11px', marginTop: '2px', wordBreak: 'break-all' }}>
+ {session?.api_key ? `${session.api_key.substring(0, 40)}...` : 'N/A'}
</div>
- <button
- onClick={extendSession}
- disabled={loading}
- style={{
- marginTop: '12px',
- padding: '8px 16px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.CYAN}`,
- color: C.CYAN,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- width: '100%'
- }}
- >
- ⏰ EXTEND SESSION
- </button>
</div>
</div>
- {/* Usage Stats */}
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.ORANGE}`, padding: '16px' }}>
- <div style={{ color: C.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- DAILY USAGE
+ <div style={{ marginTop: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ DAILY USAGE STATS
</div>
- <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.8' }}>
- <div style={{ marginBottom: '12px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: C.GRAY }}>Today's Requests:</span>
- <span style={{ color: C.WHITE, fontWeight: 'bold' }}>{requestsToday} / {dailyLimit}</span>
- </div>
- <div style={{ backgroundColor: C.DARK_BG, height: '8px', borderRadius: '4px', overflow: 'hidden' }}>
- <div
- style={{
- width: `${usagePercent}%`,
- height: '100%',
- backgroundColor: remaining > 10 ? C.GREEN : C.RED,
- transition: 'width 0.3s'
- }}
- />
- </div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
+
+ <div style={{ fontSize: '12px', marginBottom: '6px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Today's Requests:</span>
+ <span style={{ color: colors.text, fontWeight: 'bold' }}>{requestsToday}/{dailyLimit}</span>
+ </div>
+ <div style={{ backgroundColor: colors.background, height: '6px', marginBottom: '4px', border: `1px solid ${colors.textMuted}` }}>
+ <div style={{
+ width: `${usagePercent}%`,
+ height: '100%',
+ backgroundColor: remaining > 10 ? colors.secondary : colors.alert,
+ transition: 'width 0.3s'
+ }} />
</div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Remaining:</span>
- <span style={{ color: remaining > 10 ? C.GREEN : C.RED, marginLeft: '8px', fontWeight: 'bold' }}>
- {remaining} requests
- </span>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Remaining:</span>
+ <span style={{ color: remaining > 10 ? colors.secondary : colors.alert, fontWeight: 'bold' }}>{remaining}</span>
</div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Status:</span>
- <span style={{ color: C.GREEN, marginLeft: '8px', fontWeight: 'bold' }}>● ACTIVE</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: colors.textMuted }}>Status:</span>
+ <span style={{ color: colors.secondary }}>ACTIVE</span>
</div>
</div>
</div>
</div>
- {/* Features */}
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.GREEN}`, padding: '16px', marginBottom: '16px' }}>
- <div style={{ color: C.GREEN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- ✓ GUEST ACCESS FEATURES
- </div>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', color: C.WHITE, fontSize: '11px', fontFamily: 'Consolas, monospace' }}>
- <div>✓ Basic market data</div>
- <div>✓ Real-time quotes</div>
- <div>✓ Public databases</div>
- <div>✓ Forum access</div>
- <div>✓ News feeds</div>
- <div>✓ Basic charts</div>
+ {/* Right Column */}
+ <div style={{ flex: 1, backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '4px', overflow: 'auto' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ UPGRADE TO FULL ACCESS
</div>
- </div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
- {/* Upgrade Section */}
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.ORANGE}`, borderLeft: `6px solid ${C.ORANGE}`, padding: '16px' }}>
- <div style={{ color: C.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- 🔑 UPGRADE TO FULL ACCESS
- </div>
- <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', marginBottom: '16px', lineHeight: '1.8' }}>
- <div style={{ color: C.YELLOW, marginBottom: '8px' }}>Create a free account to unlock:</div>
- <div>• Unlimited API requests</div>
- <div>• Permanent API key</div>
- <div>• All database access</div>
- <div>• Premium features & tools</div>
- <div>• Data marketplace</div>
- <div>• Advanced analytics</div>
- </div>
- <div style={{ display: 'flex', gap: '12px' }}>
- <button
- onClick={() => navigation.navigateToPricing()}
- style={{
- padding: '10px 20px',
- backgroundColor: C.ORANGE,
- border: 'none',
- color: C.DARK_BG,
- fontSize: '12px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- flex: 1
- }}
- >
- 📦 VIEW PLANS
- </button>
+ <div style={{ fontSize: '12px', color: colors.text, lineHeight: '1.4', marginBottom: '8px' }}>
+ <div style={{ color: colors.warning, fontWeight: 'bold', marginBottom: '4px' }}>
+ Create a free account to unlock:
+ </div>
+ <div style={{ marginLeft: '8px' }}>
+ <div>- Unlimited API requests</div>
+ <div>- Permanent API key</div>
+ <div>- All database access</div>
+ <div>- Premium features & tools</div>
+ <div>- Data marketplace</div>
+ <div>- Advanced analytics</div>
+ </div>
</div>
+
+ <button
+ onClick={() => navigation.navigateToPricing()}
+ style={{
+ width: '100%',
+ padding: '6px',
+ backgroundColor: colors.primary,
+ border: 'none',
+ color: colors.background,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ VIEW PRICING PLANS
+ </button>
</div>
- </>
+ </div>
)}
{currentScreen === 'usage' && renderUsageScreen()}
{currentScreen === 'settings' && renderGuestSettingsScreen()}
</div>
+
+ {/* Status Bar */}
+ <div style={{ borderTop: `1px solid ${colors.textMuted}`, backgroundColor: colors.panel, padding: '2px 8px', fontSize: '11px', color: colors.textMuted, flexShrink: 0 }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span>FinceptTerminal v3.0.11 | Guest Session</span>
+ <span>Device: {session?.device_id?.substring(0, 20) || 'UNKNOWN'} | Status: {loading ? 'UPDATING' : 'READY'}</span>
+ </div>
+ </div>
</div>
);
};
+ // Registered User Profile View
const renderUserProfile = () => {
const userInfo = session?.user_info;
const accountType = userInfo?.account_type || 'free';
const hasSubscription = (session?.subscription as any)?.data?.has_subscription || session?.subscription?.has_subscription;
const subscriptionPlan = (session?.subscription as any)?.data?.subscription?.plan || session?.subscription?.subscription?.plan;
const subscriptionStatus = (session?.subscription as any)?.data?.subscription?.status || session?.subscription?.subscription?.status;
+ const creditBalance = userInfo?.credit_balance ?? 0;
const accountTypeColor = {
- free: C.GRAY,
- starter: C.BLUE,
- professional: C.PURPLE,
- enterprise: C.ORANGE,
- unlimited: C.YELLOW
- }[accountType] || C.WHITE;
+ free: colors.textMuted,
+ starter: colors.info,
+ professional: colors.purple,
+ enterprise: colors.primary,
+ unlimited: colors.warning
+ }[accountType] || colors.text;
+
+ const totalRequests = usageData?.total_requests || 0;
+ const todayRequests = usageData?.requests_today || usageData?.today_requests || 0;
return (
- <div style={{ height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: C.DARK_BG }}>
+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: colors.background, overflow: 'hidden' }}>
{/* Header */}
- <div style={{ backgroundColor: C.PANEL_BG, borderBottom: `2px solid ${C.GRAY}`, padding: '12px 16px' }}>
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: C.ORANGE, fontWeight: 'bold', fontSize: '16px', fontFamily: 'Consolas, monospace' }}>
- 🔑 {userInfo?.username?.toUpperCase() || 'USER'} PROFILE
- </span>
- <span style={{ color: C.GRAY }}>|</span>
- <span style={{ color: C.CYAN, fontSize: '12px', fontFamily: 'Consolas, monospace' }}>
- {currentTime.toLocaleTimeString()}
- </span>
- </div>
- <button
- onClick={logoutUser}
- style={{
- padding: '6px 12px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.RED}`,
- color: C.RED,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- 🚪 LOGOUT
- </button>
+ <div style={{ backgroundColor: colors.panel, borderBottom: `1px solid ${colors.textMuted}`, padding: '4px 8px', flexShrink: 0 }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px' }}>
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>FINCEPT TERMINAL PROFILE</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.accent, fontWeight: 'bold' }}>
+ {userInfo?.username?.toUpperCase() || userInfo?.email?.split('@')[0]?.toUpperCase() || 'USER'}
+ </span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.text }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>CREDITS:</span>
+ <span style={{ color: creditBalance > 0 ? colors.secondary : colors.alert, fontWeight: 'bold' }}>
+ {creditBalance.toFixed(2)}
+ </span>
+ <span style={{ color: colors.text }}>|</span>
+ <span style={{ color: colors.textMuted }}>PLAN:</span>
+ <span style={{ color: accountTypeColor, fontWeight: 'bold' }}>{accountType.toUpperCase()}</span>
</div>
</div>
- {/* Content */}
- <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
- {renderNavigationButtons()}
+ {/* Function Keys Bar */}
+ <div style={{ backgroundColor: colors.panel, borderBottom: `1px solid ${colors.textMuted}`, padding: '2px 4px', flexShrink: 0 }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: '2px' }}>
+ {[
+ { key: "F1", label: "OVERVIEW", screen: "overview" },
+ { key: "F2", label: "USAGE", screen: "usage" },
+ { key: "F3", label: "PAYMENTS", screen: "payments" },
+ { key: "F4", label: "SUBS", screen: "subscriptions" },
+ { key: "F5", label: "SUPPORT", screen: "support" },
+ { key: "F6", label: "SETTINGS", screen: "settings" },
+ { key: "F7", label: "CREDITS", action: 'pricing' },
+ { key: "F8", label: "REGEN", action: 'regen' },
+ { key: "F9", label: "", screen: "" },
+ { key: "F10", label: "", screen: "" },
+ { key: "F11", label: "FULL", action: 'fullscreen' },
+ { key: "F12", label: "LOGOUT", action: 'logout' }
+ ].map(item => (
+ <button key={item.key}
+ onClick={() => {
+ if (item.action === 'logout') logoutUser();
+ else if (item.action === 'pricing') navigation.navigateToPricing();
+ else if (item.action === 'regen') regenerateApiKey();
+ else if (item.action === 'fullscreen') toggleFullscreen();
+ else if (item.screen) setCurrentScreen(item.screen as ProfileScreen);
+ }}
+ disabled={!item.label || (loading && item.action === 'regen')}
+ style={{
+ backgroundColor: currentScreen === item.screen ? colors.primary : colors.background,
+ border: `1px solid ${colors.textMuted}`,
+ color: currentScreen === item.screen ? colors.background : colors.text,
+ padding: '2px 4px',
+ fontSize: '12px',
+ height: '16px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontWeight: currentScreen === item.screen ? 'bold' : 'normal',
+ cursor: item.label ? 'pointer' : 'default',
+ opacity: item.label ? 1 : 0.3
+ }}>
+ <span style={{ color: colors.warning }}>{item.key}:</span>
+ {item.label && <span style={{ marginLeft: '2px' }}>{item.label}</span>}
+ </button>
+ ))}
+ </div>
+ </div>
+ {/* Main Content */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '4px', backgroundColor: '#050505' }}>
{currentScreen === 'overview' && (
- <>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px', marginBottom: '16px' }}>
+ <div style={{ display: 'flex', gap: '4px', height: '100%' }}>
+ {/* Left Column */}
+ <div style={{ flex: 1, backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '4px', overflow: 'auto' }}>
+ {/* Credits Section */}
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ CREDIT BALANCE
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
+ <div style={{ color: colors.text, fontSize: '24px', fontWeight: 'bold' }}>
+ {creditBalance.toFixed(2)}
+ </div>
+ <button
+ onClick={() => navigation.navigateToPricing()}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: colors.secondary,
+ border: 'none',
+ color: colors.background,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ ADD CREDITS
+ </button>
+ </div>
+ <div style={{ color: colors.textMuted, fontSize: '11px' }}>
+ Available for API calls and premium features
+ </div>
+ </div>
+
{/* Account Details */}
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.BLUE}`, padding: '16px' }}>
- <div style={{ color: C.BLUE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
ACCOUNT DETAILS
</div>
- <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.8' }}>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Username:</span>
- <span style={{ color: C.WHITE, marginLeft: '8px', fontWeight: 'bold' }}>{userInfo?.username || 'N/A'}</span>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
+ <div style={{ fontSize: '12px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Username:</span>
+ <span style={{ color: colors.text, fontWeight: 'bold' }}>{userInfo?.username || 'N/A'}</span>
</div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Email:</span>
- <span style={{ color: C.WHITE, marginLeft: '8px' }}>{userInfo?.email || 'N/A'}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Email:</span>
+ <span style={{ color: colors.text }}>{userInfo?.email || 'N/A'}</span>
</div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Account Type:</span>
- <span style={{ color: accountTypeColor, marginLeft: '8px', fontWeight: 'bold' }}>
- {accountType.toUpperCase()}
- </span>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Account Type:</span>
+ <span style={{ color: accountTypeColor, fontWeight: 'bold' }}>{accountType.toUpperCase()}</span>
</div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Member Since:</span>
- <span style={{ color: C.WHITE, marginLeft: '8px' }}>
- {formatDate((userInfo as any)?.created_at)}
- </span>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Member Since:</span>
+ <span style={{ color: colors.text }}>{formatDate((userInfo as any)?.created_at)}</span>
</div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>User ID:</span>
- <span style={{ color: C.GRAY, marginLeft: '8px', fontSize: '10px' }}>#{(userInfo as any)?.id || 'N/A'}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: colors.textMuted }}>User ID:</span>
+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>#{(userInfo as any)?.id || 'N/A'}</span>
</div>
</div>
</div>
+ {/* API Key */}
+ <div>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ API AUTHENTICATION
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
+ <div style={{ fontSize: '12px' }}>
+ <div style={{ color: colors.textMuted, marginBottom: '2px' }}>API Key:</div>
+ <div style={{ backgroundColor: colors.background, padding: '4px', marginBottom: '4px', border: `1px solid ${colors.textMuted}`, fontSize: '11px', wordBreak: 'break-all', color: colors.text }}>
+ {session?.api_key || 'No API key available'}
+ </div>
+ <button
+ onClick={regenerateApiKey}
+ disabled={loading}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.purple}`,
+ color: colors.purple,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ width: '100%'
+ }}
+ >
+ REGENERATE API KEY
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Right Column */}
+ <div style={{ flex: 1, backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '4px', overflow: 'auto' }}>
{/* Subscription Info */}
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${hasSubscription ? C.GREEN : C.ORANGE}`, padding: '16px' }}>
- <div style={{ color: hasSubscription ? C.GREEN : C.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- {hasSubscription ? '✓ SUBSCRIPTION ACTIVE' : '📦 NO SUBSCRIPTION'}
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ SUBSCRIPTION STATUS
</div>
- <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.8' }}>
- {hasSubscription && subscriptionPlan ? (
- <>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Plan:</span>
- <span style={{ color: C.GREEN, marginLeft: '8px', fontWeight: 'bold' }}>{subscriptionPlan.name}</span>
- </div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Price:</span>
- <span style={{ color: C.WHITE, marginLeft: '8px' }}>${subscriptionPlan.price_usd / 100}/month</span>
- </div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>API Calls:</span>
- <span style={{ color: C.CYAN, marginLeft: '8px', fontWeight: 'bold' }}>
- {subscriptionPlan.api_calls_limit === -1 ? 'UNLIMITED' :
- subscriptionPlan.api_calls_limit != null ? subscriptionPlan.api_calls_limit.toLocaleString() : 'N/A'}
- </span>
- </div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Status:</span>
- <span style={{ color: C.GREEN, marginLeft: '8px', fontWeight: 'bold' }}>● {subscriptionStatus?.toUpperCase()}</span>
- </div>
- <div style={{ display: 'flex', gap: '8px', marginTop: '12px' }}>
- <button
- onClick={cancelSubscription}
- disabled={loading}
- style={{
- flex: 1,
- padding: '8px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.RED}`,
- color: C.RED,
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- CANCEL
- </button>
- <button
- onClick={() => navigation.navigateToPricing()}
- style={{
- flex: 1,
- padding: '8px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.BLUE}`,
- color: C.BLUE,
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- CHANGE
- </button>
- </div>
- </>
- ) : (
- <>
- <div style={{ color: C.YELLOW, marginBottom: '8px' }}>Upgrade to unlock:</div>
- <div>• Unlimited API requests</div>
- <div>• Priority support</div>
- <div>• Advanced features</div>
- <div>• Data marketplace access</div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
+ {hasSubscription && subscriptionPlan ? (
+ <div style={{ fontSize: '12px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Plan:</span>
+ <span style={{ color: colors.secondary, fontWeight: 'bold' }}>{subscriptionPlan.name}</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Price:</span>
+ <span style={{ color: colors.text }}>${subscriptionPlan.price_usd / 100}/mo</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>API Calls:</span>
+ <span style={{ color: colors.accent, fontWeight: 'bold' }}>
+ {subscriptionPlan.api_calls_limit === -1 ? 'UNLIMITED' :
+ subscriptionPlan.api_calls_limit != null ? subscriptionPlan.api_calls_limit.toLocaleString() : 'N/A'}
+ </span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
+ <span style={{ color: colors.textMuted }}>Status:</span>
+ <span style={{ color: colors.secondary, fontWeight: 'bold' }}>{subscriptionStatus?.toUpperCase()}</span>
+ </div>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <button
+ onClick={cancelSubscription}
+ disabled={loading}
+ style={{
+ flex: 1,
+ padding: '4px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.alert}`,
+ color: colors.alert,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CANCEL
+ </button>
<button
onClick={() => navigation.navigateToPricing()}
style={{
- marginTop: '12px',
- padding: '10px',
- backgroundColor: C.ORANGE,
- border: 'none',
- color: C.DARK_BG,
+ flex: 1,
+ padding: '4px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.info}`,
+ color: colors.info,
fontSize: '11px',
fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- width: '100%'
+ cursor: 'pointer'
}}
>
- 📦 VIEW PLANS
+ CHANGE
</button>
- </>
- )}
- </div>
+ </div>
+ </div>
+ ) : (
+ <div style={{ fontSize: '12px' }}>
+ <div style={{ color: colors.warning, marginBottom: '4px', fontWeight: 'bold' }}>No active subscription</div>
+ <div style={{ color: colors.text, marginBottom: '6px', lineHeight: '1.4' }}>
+ <div>- Unlimited API requests</div>
+ <div>- Priority support</div>
+ <div>- Advanced features</div>
+ <div>- Data marketplace access</div>
+ </div>
+ <button
+ onClick={() => navigation.navigateToPricing()}
+ style={{
+ width: '100%',
+ padding: '6px',
+ backgroundColor: colors.primary,
+ border: 'none',
+ color: colors.background,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ VIEW PLANS
+ </button>
+ </div>
+ )}
</div>
- </div>
- {/* API Key */}
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.PURPLE}`, padding: '16px', marginBottom: '16px' }}>
- <div style={{ color: C.PURPLE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- 🔐 API AUTHENTICATION
- </div>
- <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace' }}>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>API Key:</span>
+ {/* Usage Stats Quick View */}
+ <div>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ API USAGE SUMMARY
</div>
- <div style={{ backgroundColor: C.DARK_BG, padding: '8px', marginBottom: '12px', border: `1px solid ${C.GRAY}`, fontSize: '10px', wordBreak: 'break-all' }}>
- {session?.api_key || 'No API key available'}
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
+ <div style={{ fontSize: '12px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Total Requests:</span>
+ <span style={{ color: colors.text }}>{totalRequests.toLocaleString()}</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: colors.textMuted }}>Today's Requests:</span>
+ <span style={{ color: colors.accent }}>{todayRequests}</span>
+ </div>
</div>
- <button
- onClick={regenerateApiKey}
- disabled={loading}
- style={{
- padding: '8px 16px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.PURPLE}`,
- color: C.PURPLE,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- 🔄 REGENERATE API KEY
- </button>
- </div>
- </div>
-
- {/* Quick Actions */}
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.ORANGE}`, padding: '16px' }}>
- <div style={{ color: C.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- ⚡ QUICK ACTIONS
- </div>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>
- <button
- onClick={() => setCurrentScreen('usage')}
- style={{
- padding: '12px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.CYAN}`,
- color: C.CYAN,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- 📊 USAGE STATS
- </button>
- <button
- onClick={() => setCurrentScreen('payments')}
- style={{
- padding: '12px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.GREEN}`,
- color: C.GREEN,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- 💳 PAYMENT HISTORY
- </button>
- <button
- onClick={() => setCurrentScreen('subscriptions')}
- style={{
- padding: '12px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.PURPLE}`,
- color: C.PURPLE,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- 💾 SUBSCRIPTIONS
- </button>
- <button
- onClick={() => setCurrentScreen('support')}
- style={{
- padding: '12px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.BLUE}`,
- color: C.BLUE,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- 🎫 SUPPORT
- </button>
</div>
</div>
- </>
+ </div>
)}
{currentScreen === 'usage' && renderUsageScreen()}
@@ -677,52 +640,55 @@ const ProfileTab: React.FC = () => {
{currentScreen === 'support' && renderSupportScreen()}
{currentScreen === 'settings' && renderSettingsScreen()}
</div>
+
+ {/* Status Bar */}
+ <div style={{ borderTop: `1px solid ${colors.textMuted}`, backgroundColor: colors.panel, padding: '2px 8px', fontSize: '11px', color: colors.textMuted, flexShrink: 0 }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span>FinceptTerminal v3.0.11 | User: {userInfo?.username || 'N/A'}</span>
+ <span>Account: {accountType.toUpperCase()} | Requests: {todayRequests.toLocaleString()} | Status: {loading ? 'UPDATING' : 'READY'}</span>
+ </div>
+ </div>
</div>
);
};
const renderUsageScreen = () => {
return (
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.CYAN}`, padding: '16px' }}>
- <div style={{ color: C.CYAN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- 📊 API USAGE STATISTICS
+ <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '4px', height: '100%', overflow: 'auto' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ API USAGE STATISTICS
</div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
{loading ? (
- <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>Loading usage data...</div>
+ <div style={{ color: colors.textMuted, fontSize: '12px' }}>Loading usage data...</div>
) : usageData ? (
- <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.8' }}>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Total Requests:</span>
- <span style={{ color: C.WHITE, marginLeft: '8px', fontWeight: 'bold' }}>
- {usageData.total_requests?.toLocaleString() || 'N/A'}
- </span>
+ <div style={{ fontSize: '12px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Total Requests:</span>
+ <span style={{ color: colors.text, fontWeight: 'bold' }}>{usageData.total_requests?.toLocaleString() || 'N/A'}</span>
</div>
- <div style={{ marginBottom: '8px' }}>
- <span style={{ color: C.GRAY }}>Today's Requests:</span>
- <span style={{ color: C.CYAN, marginLeft: '8px', fontWeight: 'bold' }}>
- {usageData.requests_today || usageData.today_requests || 0}
- </span>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>Today's Requests:</span>
+ <span style={{ color: colors.accent, fontWeight: 'bold' }}>{usageData.requests_today || usageData.today_requests || 0}</span>
</div>
{detailedUsage && (
<>
- <div style={{ marginTop: '16px', color: C.ORANGE, fontWeight: 'bold' }}>Detailed Usage:</div>
- <div style={{ marginTop: '8px' }}>
- <span style={{ color: C.GRAY }}>This Month:</span>
- <span style={{ color: C.WHITE, marginLeft: '8px' }}>
- {detailedUsage.this_month?.toLocaleString() || 'N/A'}
- </span>
- </div>
- <div style={{ marginTop: '8px' }}>
- <span style={{ color: C.GRAY }}>Last 30 Days:</span>
- <span style={{ color: C.WHITE, marginLeft: '8px' }}>
- {detailedUsage.last_30_days?.toLocaleString() || 'N/A'}
- </span>
+ <div style={{ borderTop: `1px solid ${colors.textMuted}`, marginTop: '6px', paddingTop: '6px' }}>
+ <div style={{ color: colors.warning, fontWeight: 'bold', marginBottom: '4px' }}>Detailed Usage</div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
+ <span style={{ color: colors.textMuted }}>This Month:</span>
+ <span style={{ color: colors.text }}>{detailedUsage.this_month?.toLocaleString() || 'N/A'}</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: colors.textMuted }}>Last 30 Days:</span>
+ <span style={{ color: colors.text }}>{detailedUsage.last_30_days?.toLocaleString() || 'N/A'}</span>
+ </div>
</div>
</>
)}
</div>
) : (
- <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>No usage data available</div>
+ <div style={{ color: colors.textMuted, fontSize: '12px' }}>No usage data available</div>
)}
</div>
);
@@ -730,47 +696,42 @@ const ProfileTab: React.FC = () => {
const renderPaymentsScreen = () => {
return (
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.GREEN}`, padding: '16px' }}>
- <div style={{ color: C.GREEN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- 💳 PAYMENT HISTORY
+ <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '4px', height: '100%', overflow: 'auto' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ PAYMENT HISTORY
</div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
{loading ? (
- <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>Loading payment history...</div>
+ <div style={{ color: colors.textMuted, fontSize: '12px' }}>Loading payment history...</div>
) : paymentHistory.length > 0 ? (
- <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
- {paymentHistory.map((payment: any, idx: number) => (
- <div
- key={idx}
- style={{
- backgroundColor: C.DARK_BG,
- border: `1px solid ${C.GRAY}`,
- padding: '12px',
- marginBottom: '8px',
- fontFamily: 'Consolas, monospace',
- fontSize: '11px'
- }}
- >
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: C.GRAY }}>Amount:</span>
- <span style={{ color: C.GREEN, fontWeight: 'bold' }}>
- {formatCurrency(payment.amount || payment.amount_paid || 0)}
- </span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: C.GRAY }}>Date:</span>
- <span style={{ color: C.WHITE }}>{formatDate(payment.created_at || payment.payment_date)}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: C.GRAY }}>Status:</span>
- <span style={{ color: payment.status === 'completed' ? C.GREEN : C.YELLOW }}>
- {payment.status?.toUpperCase() || 'N/A'}
- </span>
- </div>
+ paymentHistory.map((payment: any, idx: number) => (
+ <div key={idx} style={{
+ backgroundColor: idx % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
+ borderLeft: `2px solid ${colors.secondary}`,
+ paddingLeft: '4px',
+ marginBottom: '4px',
+ fontSize: '12px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
+ <span style={{ color: colors.textMuted }}>Amount:</span>
+ <span style={{ color: colors.secondary, fontWeight: 'bold' }}>
+ {formatCurrency(payment.amount || payment.amount_paid || 0)}
+ </span>
</div>
- ))}
- </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
+ <span style={{ color: colors.textMuted }}>Date:</span>
+ <span style={{ color: colors.text }}>{formatDate(payment.created_at || payment.payment_date)}</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: colors.textMuted }}>Status:</span>
+ <span style={{ color: payment.status === 'completed' ? colors.secondary : colors.warning, fontWeight: 'bold' }}>
+ {payment.status?.toUpperCase() || 'N/A'}
+ </span>
+ </div>
+ </div>
+ ))
) : (
- <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>No payment history found</div>
+ <div style={{ color: colors.textMuted, fontSize: '12px' }}>No payment history found</div>
)}
</div>
);
@@ -778,37 +739,32 @@ const ProfileTab: React.FC = () => {
const renderSubscriptionsScreen = () => {
return (
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.PURPLE}`, padding: '16px' }}>
- <div style={{ color: C.PURPLE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- 💾 DATABASE SUBSCRIPTIONS
+ <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '4px', height: '100%', overflow: 'auto' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ DATABASE SUBSCRIPTIONS
</div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
{loading ? (
- <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>Loading subscriptions...</div>
+ <div style={{ color: colors.textMuted, fontSize: '12px' }}>Loading subscriptions...</div>
) : subscriptions.length > 0 ? (
- <div>
- {subscriptions.map((sub: any, idx: number) => (
- <div
- key={idx}
- style={{
- backgroundColor: C.DARK_BG,
- border: `1px solid ${C.GRAY}`,
- padding: '12px',
- marginBottom: '8px',
- fontFamily: 'Consolas, monospace',
- fontSize: '11px'
- }}
- >
- <div style={{ color: C.PURPLE, fontWeight: 'bold', marginBottom: '4px' }}>
- {sub.database_name || sub.name || 'Unknown Database'}
- </div>
- <div style={{ color: C.GRAY }}>
- Subscribed: {formatDate(sub.subscribed_at || sub.created_at)}
- </div>
+ subscriptions.map((sub: any, idx: number) => (
+ <div key={idx} style={{
+ backgroundColor: idx % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
+ borderLeft: `2px solid ${colors.purple}`,
+ paddingLeft: '4px',
+ marginBottom: '4px',
+ fontSize: '12px'
+ }}>
+ <div style={{ color: colors.purple, fontWeight: 'bold', marginBottom: '1px' }}>
+ {sub.database_name || sub.name || 'Unknown Database'}
</div>
- ))}
- </div>
+ <div style={{ color: colors.textMuted }}>
+ Subscribed: {formatDate(sub.subscribed_at || sub.created_at)}
+ </div>
+ </div>
+ ))
) : (
- <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>No database subscriptions found</div>
+ <div style={{ color: colors.textMuted, fontSize: '12px' }}>No database subscriptions found</div>
)}
</div>
);
@@ -816,58 +772,52 @@ const ProfileTab: React.FC = () => {
const renderSupportScreen = () => {
return (
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.BLUE}`, padding: '16px' }}>
- <div style={{ color: C.BLUE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- 🎫 SUPPORT TICKETS
+ <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '4px', height: '100%', overflow: 'auto' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ SUPPORT TICKETS
</div>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
{loading ? (
- <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>Loading tickets...</div>
+ <div style={{ color: colors.textMuted, fontSize: '12px' }}>Loading tickets...</div>
) : supportTickets.length > 0 ? (
- <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
- {supportTickets.map((ticket: any, idx: number) => (
- <div
- key={idx}
- style={{
- backgroundColor: C.DARK_BG,
- border: `1px solid ${C.GRAY}`,
- padding: '12px',
- marginBottom: '8px',
- fontFamily: 'Consolas, monospace',
- fontSize: '11px'
- }}
- >
- <div style={{ color: C.BLUE, fontWeight: 'bold', marginBottom: '4px' }}>
- #{ticket.id} - {ticket.subject}
- </div>
- <div style={{ color: C.GRAY, marginBottom: '4px' }}>{ticket.description?.substring(0, 100)}...</div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: C.GRAY }}>Status:</span>
- <span style={{ color: ticket.status === 'closed' ? C.GREEN : C.YELLOW }}>
- {ticket.status?.toUpperCase()}
- </span>
- </div>
+ supportTickets.map((ticket: any, idx: number) => (
+ <div key={idx} style={{
+ backgroundColor: idx % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
+ borderLeft: `2px solid ${colors.info}`,
+ paddingLeft: '4px',
+ marginBottom: '4px',
+ fontSize: '12px'
+ }}>
+ <div style={{ color: colors.info, fontWeight: 'bold', marginBottom: '1px' }}>
+ #{ticket.id} - {ticket.subject}
</div>
- ))}
- </div>
+ <div style={{ color: colors.textMuted, marginBottom: '2px', fontSize: '11px' }}>
+ {ticket.description?.substring(0, 100)}...
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: colors.textMuted }}>Status:</span>
+ <span style={{ color: ticket.status === 'closed' ? colors.secondary : colors.warning, fontWeight: 'bold' }}>
+ {ticket.status?.toUpperCase()}
+ </span>
+ </div>
+ </div>
+ ))
) : (
<div>
- <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px', marginBottom: '16px' }}>
- No support tickets found
- </div>
+ <div style={{ color: colors.textMuted, fontSize: '12px', marginBottom: '6px' }}>No support tickets found</div>
<button
onClick={() => alert('Create ticket feature coming soon')}
style={{
- padding: '10px 20px',
- backgroundColor: C.BLUE,
+ padding: '6px',
+ backgroundColor: colors.info,
border: 'none',
- color: C.DARK_BG,
- fontSize: '11px',
+ color: colors.background,
+ fontSize: '12px',
fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
+ cursor: 'pointer'
}}
>
- + CREATE NEW TICKET
+ CREATE NEW TICKET
</button>
</div>
)}
@@ -877,33 +827,31 @@ const ProfileTab: React.FC = () => {
const renderSettingsScreen = () => {
return (
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.RED}`, padding: '16px' }}>
- <div style={{ color: C.RED, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- ⚙️ ACCOUNT SETTINGS
+ <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '4px', height: '100%', overflow: 'auto' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ ACCOUNT SETTINGS - DANGER ZONE
</div>
- <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace' }}>
- <div style={{ marginBottom: '16px' }}>
- <div style={{ color: C.YELLOW, fontWeight: 'bold', marginBottom: '8px' }}>⚠️ DANGER ZONE</div>
- <div style={{ color: C.GRAY, marginBottom: '12px' }}>
- Deleting your account is permanent and cannot be undone. All your data will be lost.
- </div>
- <button
- onClick={deleteAccount}
- disabled={loading}
- style={{
- padding: '10px 20px',
- backgroundColor: C.RED,
- border: 'none',
- color: C.WHITE,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- 🗑️ DELETE ACCOUNT
- </button>
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
+ <div style={{ fontSize: '12px' }}>
+ <div style={{ color: colors.warning, fontWeight: 'bold', marginBottom: '4px' }}>WARNING</div>
+ <div style={{ color: colors.textMuted, marginBottom: '8px', lineHeight: '1.4' }}>
+ Deleting your account is permanent and cannot be undone. All your data, subscriptions, payment history, and API access will be permanently removed.
</div>
+ <button
+ onClick={deleteAccount}
+ disabled={loading}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: colors.alert,
+ border: 'none',
+ color: colors.text,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ DELETE ACCOUNT PERMANENTLY
+ </button>
</div>
</div>
);
@@ -911,47 +859,45 @@ const ProfileTab: React.FC = () => {
const renderGuestSettingsScreen = () => {
return (
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.RED}`, padding: '16px' }}>
- <div style={{ color: C.RED, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- ⚙️ SESSION SETTINGS
+ <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.textMuted}`, padding: '4px', height: '100%', overflow: 'auto' }}>
+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>
+ SESSION SETTINGS - DANGER ZONE
</div>
- <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace' }}>
- <div style={{ marginBottom: '16px' }}>
- <div style={{ color: C.YELLOW, fontWeight: 'bold', marginBottom: '8px' }}>⚠️ DANGER ZONE</div>
- <div style={{ color: C.GRAY, marginBottom: '12px' }}>
- Deleting your guest session will remove all your data. This action cannot be undone.
- </div>
- <button
- onClick={async () => {
- if (confirm('Are you sure you want to delete your guest session?')) {
- if (session?.api_key) {
- setLoading(true);
- const result = await UserApiService.deleteGuestSession(session.api_key || '');
- setLoading(false);
- if (result.success) {
- alert('Guest session deleted successfully.');
- await logout();
- } else {
- alert(`Failed to delete session: ${result.error}`);
- }
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
+ <div style={{ fontSize: '12px' }}>
+ <div style={{ color: colors.warning, fontWeight: 'bold', marginBottom: '4px' }}>WARNING</div>
+ <div style={{ color: colors.textMuted, marginBottom: '8px', lineHeight: '1.4' }}>
+ Deleting your guest session will remove all your data. This action cannot be undone.
+ </div>
+ <button
+ onClick={async () => {
+ if (confirm('Are you sure you want to delete your guest session?')) {
+ if (session?.api_key) {
+ setLoading(true);
+ const result = await UserApiService.deleteGuestSession(session.api_key || '');
+ setLoading(false);
+ if (result.success) {
+ alert('Guest session deleted successfully.');
+ await logout();
+ } else {
+ alert(`Failed to delete session: ${result.error}`);
}
}
- }}
- disabled={loading}
- style={{
- padding: '10px 20px',
- backgroundColor: C.RED,
- border: 'none',
- color: C.WHITE,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- 🗑️ DELETE SESSION
- </button>
- </div>
+ }
+ }}
+ disabled={loading}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: colors.alert,
+ border: 'none',
+ color: colors.text,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ DELETE SESSION PERMANENTLY
+ </button>
</div>
</div>
);
@@ -960,10 +906,10 @@ const ProfileTab: React.FC = () => {
// Main render
if (!session) {
return (
- <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: C.DARK_BG, color: C.WHITE, fontFamily: 'Consolas, monospace' }}>
- <div style={{ textAlign: 'center' }}>
- <div style={{ fontSize: '16px', color: C.ORANGE, marginBottom: '12px' }}>❌ NO SESSION</div>
- <div style={{ fontSize: '12px', color: C.GRAY }}>Unable to load profile</div>
+ <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: colors.background, color: colors.text }}>
+ <div style={{ textAlign: 'center', fontSize: '12px' }}>
+ <div style={{ color: colors.alert, marginBottom: '8px', fontWeight: 'bold' }}>NO SESSION</div>
+ <div style={{ color: colors.textMuted }}>Unable to load profile</div>
</div>
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx b/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx
index 2b565c074..8e21d9c5e 100644
--- a/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx
@@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { SupportApiService } from '@/services/supportApi';
import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { RefreshCw, Plus, ArrowLeft, Send, CheckCircle2, XCircle, Clock } from 'lucide-react';
type SupportView = 'list' | 'create' | 'details';
@@ -20,13 +21,61 @@ const SupportTicketTab: React.FC = () => {
DARK_BG: colors.background,
PANEL_BG: colors.panel
};
+
const { session } = useAuth();
+ const [currentTime, setCurrentTime] = useState(new Date());
const [currentView, setCurrentView] = useState<SupportView>('list');
const [loading, setLoading] = useState(false);
- const [tickets, setTickets] = useState<any[]>([]);
+
+ // Demo ticket to show users how the system works
+ const DEMO_TICKET = {
+ id: 'DEMO-001',
+ ticket_id: 'DEMO-001',
+ subject: 'Welcome to Fincept Support - Demo Ticket',
+ description: `This is a demonstration ticket to help you understand how our support system works.
+
+HOW TO USE SUPPORT:
+1. Click "+ CREATE TICKET" to submit a new support request
+2. Fill in the subject, category, priority, and detailed description
+3. Our support team will respond within 24 hours
+4. You can add messages to continue the conversation
+5. Close the ticket when your issue is resolved
+
+AVAILABLE CATEGORIES:
+- Technical Issue: For bugs, errors, or technical problems
+- Billing: Questions about payments, subscriptions, or invoices
+- Feature Request: Suggest new features or improvements
+- Bug Report: Report software bugs with detailed steps
+- Account: Account access, settings, or profile issues
+- Other: General inquiries
+
+This demo ticket shows you exactly how your real support tickets will appear. Feel free to explore and create your own ticket when you need assistance!`,
+ category: 'technical',
+ priority: 'medium',
+ status: 'open',
+ created_at: new Date().toISOString(),
+ messages: [
+ {
+ sender_type: 'support',
+ message: 'Welcome to Fincept Terminal Support! This is how our support team will respond to your tickets. We typically respond within 24 hours during business days.',
+ created_at: new Date(Date.now() - 3600000).toISOString()
+ },
+ {
+ sender_type: 'user',
+ message: 'Thank you! I understand how the system works now.',
+ created_at: new Date(Date.now() - 1800000).toISOString()
+ },
+ {
+ sender_type: 'support',
+ message: 'Great! Feel free to create a real ticket anytime you need help. Our team is here to assist you 24/7.',
+ created_at: new Date(Date.now() - 900000).toISOString()
+ }
+ ]
+ };
+
+ const [tickets, setTickets] = useState<any[]>([DEMO_TICKET]);
const [selectedTicket, setSelectedTicket] = useState<any>(null);
- const [categories, setCategories] = useState<any[]>([]);
- const [stats, setStats] = useState<any>(null);
+ const [stats, setStats] = useState<any>({ total_tickets: 1, open_tickets: 1, resolved_tickets: 0 });
// Create ticket form
const [newTicket, setNewTicket] = useState({
@@ -39,10 +88,15 @@ const SupportTicketTab: React.FC = () => {
// Message form
const [newMessage, setNewMessage] = useState('');
+ // Update clock
+ useEffect(() => {
+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);
+ return () => clearInterval(timer);
+ }, []);
+
useEffect(() => {
if (session?.api_key) {
loadTickets();
- loadCategories();
loadStats();
}
}, [session]);
@@ -52,18 +106,14 @@ const SupportTicketTab: React.FC = () => {
setLoading(true);
const result = await SupportApiService.getUserTickets(session.api_key);
if (result.success) {
- setTickets(result.data?.tickets || result.data || []);
+ const apiTickets = result.data?.tickets || result.data || [];
+ setTickets([DEMO_TICKET, ...apiTickets]);
+ } else {
+ setTickets([DEMO_TICKET]);
}
setLoading(false);
};
- const loadCategories = async () => {
- const result = await SupportApiService.getSupportCategories();
- if (result.success) {
- setCategories(result.data?.categories || result.data || []);
- }
- };
-
const loadStats = async () => {
if (!session?.api_key) return;
const result = await SupportApiService.getSupportStats(session.api_key);
@@ -92,10 +142,16 @@ const SupportTicketTab: React.FC = () => {
}
};
- const viewTicketDetails = async (ticketId: number) => {
+ const viewTicketDetails = async (ticketId: number | string) => {
+ if (ticketId === 'DEMO-001') {
+ setSelectedTicket(DEMO_TICKET);
+ setCurrentView('details');
+ return;
+ }
+
if (!session?.api_key) return;
setLoading(true);
- const result = await SupportApiService.getTicketDetails(session.api_key, ticketId);
+ const result = await SupportApiService.getTicketDetails(session.api_key, ticketId as number);
setLoading(false);
if (result.success) {
@@ -184,482 +240,698 @@ const SupportTicketTab: React.FC = () => {
}
};
- const renderListView = () => (
- <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
- {/* Header */}
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
- <div>
- <div style={{ color: C.ORANGE, fontSize: '18px', fontWeight: 'bold', fontFamily: 'Consolas, monospace' }}>
- 🎫 SUPPORT TICKETS
- </div>
- {stats && (
- <div style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace', marginTop: '4px' }}>
- Total: {stats.total_tickets || 0} | Open: {stats.open_tickets || 0} | Resolved: {stats.resolved_tickets || 0}
- </div>
- )}
+ const getStatusIcon = (status: string) => {
+ switch (status?.toLowerCase()) {
+ case 'open':
+ case 'in_progress':
+ return <Clock size={14} />;
+ case 'resolved':
+ case 'closed':
+ return <CheckCircle2 size={14} />;
+ default:
+ return <XCircle size={14} />;
+ }
+ };
+
+ // Main render
+ if (!session) {
+ return (
+ <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: C.DARK_BG }}>
+ <div style={{ textAlign: 'center', fontFamily: 'Consolas, monospace' }}>
+ <div style={{ color: C.ORANGE, fontSize: '16px', marginBottom: '8px', fontWeight: 'bold' }}>AUTHENTICATION REQUIRED</div>
+ <div style={{ color: C.GRAY, fontSize: '12px' }}>Please login to access support tickets</div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: C.DARK_BG,
+ color: C.WHITE,
+ fontFamily: 'Consolas, monospace',
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ <style>{`
+ *::-webkit-scrollbar {
+ width: 8px;
+ height: 8px;
+ }
+ *::-webkit-scrollbar-track {
+ background: #1a1a1a;
+ }
+ *::-webkit-scrollbar-thumb {
+ background: #404040;
+ border-radius: 4px;
+ }
+ *::-webkit-scrollbar-thumb:hover {
+ background: #525252;
+ }
+ `}</style>
+
+ {/* Header Bar */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '8px 12px',
+ backgroundColor: C.PANEL_BG,
+ borderBottom: `1px solid ${C.GRAY}`,
+ fontSize: '13px',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: C.ORANGE, fontWeight: 'bold' }}>FINCEPT</span>
+ <span style={{ color: C.WHITE }}>SUPPORT TERMINAL</span>
+ <span style={{ color: C.GRAY }}>|</span>
+ <span style={{ color: C.WHITE, fontSize: '11px' }}>
+ {currentTime.toISOString().replace('T', ' ').substring(0, 19)}
+ </span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: C.GRAY, fontSize: '11px' }}>TICKETS:</span>
+ <span style={{ color: C.CYAN, fontSize: '11px', fontWeight: 'bold' }}>{stats.total_tickets || 0}</span>
+ <span style={{ color: C.GRAY }}>|</span>
+ <span style={{ color: C.YELLOW, fontSize: '11px' }}>OPEN:</span>
+ <span style={{ color: C.YELLOW, fontSize: '11px', fontWeight: 'bold' }}>{stats.open_tickets || 0}</span>
+ <span style={{ color: C.GRAY }}>|</span>
+ <span style={{ color: C.GREEN, fontSize: '11px' }}>RESOLVED:</span>
+ <span style={{ color: C.GREEN, fontSize: '11px', fontWeight: 'bold' }}>{stats.resolved_tickets || 0}</span>
</div>
- <button
- onClick={() => setCurrentView('create')}
- style={{
- padding: '10px 20px',
- backgroundColor: C.GREEN,
- border: 'none',
- color: C.DARK_BG,
- fontSize: '12px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- + CREATE TICKET
- </button>
</div>
- {/* Tickets List */}
- <div style={{ flex: 1, overflowY: 'auto' }}>
- {loading ? (
- <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px' }}>
- Loading tickets...
- </div>
- ) : tickets.length > 0 ? (
- <div style={{ display: 'grid', gap: '12px' }}>
- {tickets.map((ticket: any) => (
- <div
- key={ticket.id || ticket.ticket_id}
- onClick={() => viewTicketDetails(ticket.id || ticket.ticket_id)}
+ {/* Control Panel */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '8px 12px',
+ backgroundColor: C.PANEL_BG,
+ borderBottom: `1px solid ${C.GRAY}`,
+ fontSize: '12px',
+ gap: '8px',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ {currentView === 'list' && (
+ <>
+ <button
+ onClick={loadTickets}
+ disabled={loading}
style={{
- backgroundColor: C.PANEL_BG,
- border: `2px solid ${C.GRAY}`,
- borderLeft: `6px solid ${getStatusColor(ticket.status)}`,
- padding: '16px',
- cursor: 'pointer',
- transition: 'all 0.2s',
- fontFamily: 'Consolas, monospace'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.borderColor = C.ORANGE;
- e.currentTarget.style.backgroundColor = '#1a1a1a';
+ backgroundColor: C.ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: loading ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
}}
- onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = C.GRAY;
- e.currentTarget.style.backgroundColor = C.PANEL_BG;
+ >
+ <RefreshCw size={12} />
+ REFRESH
+ </button>
+ <button
+ onClick={() => setCurrentView('create')}
+ style={{
+ backgroundColor: C.GREEN,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
}}
>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
- <div>
- <span style={{ color: C.GRAY, fontSize: '11px' }}>#{ticket.id || ticket.ticket_id}</span>
- <div style={{ color: C.WHITE, fontSize: '14px', fontWeight: 'bold', marginTop: '4px' }}>
- {ticket.subject}
- </div>
- </div>
- <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
- <span
- style={{
- padding: '4px 8px',
- backgroundColor: getStatusColor(ticket.status),
- color: C.DARK_BG,
- fontSize: '10px',
- fontWeight: 'bold',
- borderRadius: '2px'
- }}
- >
- {ticket.status?.toUpperCase()}
- </span>
- <span
- style={{
- padding: '4px 8px',
- backgroundColor: getPriorityColor(ticket.priority),
- color: C.DARK_BG,
- fontSize: '10px',
- fontWeight: 'bold',
- borderRadius: '2px'
- }}
- >
- {ticket.priority?.toUpperCase()}
- </span>
- </div>
- </div>
-
- <div style={{ color: C.GRAY, fontSize: '11px', marginBottom: '8px' }}>
- {ticket.description?.substring(0, 150)}
- {ticket.description?.length > 150 && '...'}
- </div>
-
- <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px' }}>
- <span style={{ color: C.GRAY }}>
- Category: <span style={{ color: C.CYAN }}>{ticket.category}</span>
- </span>
- <span style={{ color: C.GRAY }}>
- Created: <span style={{ color: C.WHITE }}>{formatDate(ticket.created_at)}</span>
- </span>
- </div>
- </div>
- ))}
- </div>
- ) : (
- <div style={{ color: C.GRAY, fontFamily: 'Consolas, monospace', fontSize: '12px', textAlign: 'center', marginTop: '40px' }}>
- No support tickets found. Create your first ticket to get started!
- </div>
- )}
- </div>
- </div>
- );
-
- const renderCreateView = () => (
- <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
- {/* Header */}
- <div style={{ marginBottom: '16px' }}>
- <button
- onClick={() => setCurrentView('list')}
- style={{
- padding: '6px 12px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.GRAY}`,
- color: C.GRAY,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- marginBottom: '12px'
- }}
- >
- ← BACK TO LIST
- </button>
- <div style={{ color: C.ORANGE, fontSize: '18px', fontWeight: 'bold', fontFamily: 'Consolas, monospace' }}>
- CREATE NEW TICKET
- </div>
- </div>
-
- {/* Form */}
- <div style={{ flex: 1, overflowY: 'auto' }}>
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.GREEN}`, padding: '20px' }}>
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace', display: 'block', marginBottom: '4px' }}>
- Subject *
- </label>
- <input
- type="text"
- value={newTicket.subject}
- onChange={(e) => setNewTicket({ ...newTicket, subject: e.target.value })}
- placeholder="Brief description of your issue"
- style={{
- width: '100%',
- padding: '10px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.GRAY}`,
- color: C.WHITE,
- fontSize: '12px',
- fontFamily: 'Consolas, monospace',
- outline: 'none'
- }}
- />
- </div>
-
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace', display: 'block', marginBottom: '4px' }}>
- Category *
- </label>
- <select
- value={newTicket.category}
- onChange={(e) => setNewTicket({ ...newTicket, category: e.target.value })}
- style={{
- width: '100%',
- padding: '10px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.GRAY}`,
- color: C.WHITE,
- fontSize: '12px',
- fontFamily: 'Consolas, monospace',
- outline: 'none'
- }}
- >
- <option value="technical">Technical Issue</option>
- <option value="billing">Billing</option>
- <option value="feature">Feature Request</option>
- <option value="bug">Bug Report</option>
- <option value="account">Account</option>
- <option value="other">Other</option>
- </select>
- </div>
-
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace', display: 'block', marginBottom: '4px' }}>
- Priority
- </label>
- <select
- value={newTicket.priority}
- onChange={(e) => setNewTicket({ ...newTicket, priority: e.target.value })}
+ <Plus size={12} />
+ CREATE TICKET
+ </button>
+ </>
+ )}
+ {(currentView === 'create' || currentView === 'details') && (
+ <button
+ onClick={() => setCurrentView('list')}
style={{
- width: '100%',
- padding: '10px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.GRAY}`,
- color: C.WHITE,
- fontSize: '12px',
- fontFamily: 'Consolas, monospace',
- outline: 'none'
+ backgroundColor: C.GRAY,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
}}
>
- <option value="low">Low</option>
- <option value="medium">Medium</option>
- <option value="high">High</option>
- </select>
- </div>
-
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace', display: 'block', marginBottom: '4px' }}>
- Description *
- </label>
- <textarea
- value={newTicket.description}
- onChange={(e) => setNewTicket({ ...newTicket, description: e.target.value })}
- placeholder="Provide detailed information about your issue..."
- rows={8}
- style={{
- width: '100%',
- padding: '10px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.GRAY}`,
- color: C.WHITE,
- fontSize: '12px',
- fontFamily: 'Consolas, monospace',
- outline: 'none',
- resize: 'vertical'
- }}
- />
- </div>
-
- <button
- onClick={createTicket}
- disabled={loading}
- style={{
- padding: '12px 24px',
- backgroundColor: loading ? C.GRAY : C.GREEN,
- border: 'none',
- color: C.DARK_BG,
- fontSize: '12px',
- fontWeight: 'bold',
- cursor: loading ? 'not-allowed' : 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- {loading ? 'CREATING...' : 'CREATE TICKET'}
- </button>
+ <ArrowLeft size={12} />
+ BACK TO LIST
+ </button>
+ )}
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: loading ? C.ORANGE : C.GREEN, fontSize: '14px' }}>●</span>
+ <span style={{ color: loading ? C.ORANGE : C.GREEN, fontSize: '11px', fontWeight: 'bold' }}>
+ {loading ? 'UPDATING' : 'READY'}
+ </span>
</div>
</div>
- </div>
- );
- const renderDetailsView = () => {
- if (!selectedTicket) return null;
+ {/* Main Content */}
+ <div style={{
+ flex: 1,
+ overflow: 'auto',
+ padding: '12px'
+ }}>
+ {currentView === 'list' && (
+ <>
+ {/* Section Header */}
+ <div style={{
+ color: C.ORANGE,
+ fontSize: '14px',
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ letterSpacing: '0.5px'
+ }}>
+ SUPPORT TICKETS
+ </div>
+ <div style={{ borderBottom: `1px solid ${C.GRAY}`, marginBottom: '16px' }}></div>
- const messages = selectedTicket.messages || [];
+ {/* Tickets Grid */}
+ {loading && tickets.length === 0 ? (
+ <div style={{ color: C.GRAY, fontSize: '12px', textAlign: 'center', marginTop: '40px' }}>
+ Loading tickets...
+ </div>
+ ) : tickets.length > 0 ? (
+ <div style={{ display: 'grid', gap: '8px' }}>
+ {tickets.map((ticket: any) => {
+ const isDemoTicket = ticket.id === 'DEMO-001' || ticket.ticket_id === 'DEMO-001';
+ return (
+ <div
+ key={ticket.id || ticket.ticket_id}
+ onClick={() => viewTicketDetails(ticket.id || ticket.ticket_id)}
+ style={{
+ backgroundColor: C.PANEL_BG,
+ border: `1px solid ${isDemoTicket ? C.BLUE : C.GRAY}`,
+ borderLeft: `4px solid ${getStatusColor(ticket.status)}`,
+ padding: '12px',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ position: 'relative'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = C.ORANGE;
+ e.currentTarget.style.backgroundColor = '#1a1a1a';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = isDemoTicket ? C.BLUE : C.GRAY;
+ e.currentTarget.style.backgroundColor = C.PANEL_BG;
+ }}
+ >
+ {isDemoTicket && (
+ <div style={{
+ position: 'absolute',
+ top: '8px',
+ right: '8px',
+ backgroundColor: C.BLUE,
+ color: 'black',
+ padding: '2px 8px',
+ fontSize: '9px',
+ fontWeight: 'bold'
+ }}>
+ DEMO
+ </div>
+ )}
+
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '80px 1fr 120px 120px 120px 150px',
+ gap: '12px',
+ alignItems: 'center',
+ fontSize: '11px'
+ }}>
+ <div style={{ color: C.GRAY }}>
+ #{ticket.id || ticket.ticket_id}
+ </div>
+ <div style={{ color: C.WHITE, fontWeight: 'bold', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ {ticket.subject}
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ {getStatusIcon(ticket.status)}
+ <span style={{ color: getStatusColor(ticket.status), fontWeight: 'bold' }}>
+ {ticket.status?.toUpperCase()}
+ </span>
+ </div>
+ <div style={{
+ backgroundColor: getPriorityColor(ticket.priority),
+ color: 'black',
+ padding: '2px 8px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ textAlign: 'center'
+ }}>
+ {ticket.priority?.toUpperCase()}
+ </div>
+ <div style={{ color: C.CYAN, textAlign: 'center' }}>
+ {ticket.category?.toUpperCase()}
+ </div>
+ <div style={{ color: C.GRAY, fontSize: '10px', textAlign: 'right' }}>
+ {formatDate(ticket.created_at)}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <div style={{ color: C.GRAY, fontSize: '12px', textAlign: 'center', marginTop: '40px' }}>
+ No support tickets found. Create your first ticket to get started!
+ </div>
+ )}
+ </>
+ )}
- return (
- <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
- {/* Header */}
- <div style={{ marginBottom: '16px' }}>
- <button
- onClick={() => setCurrentView('list')}
- style={{
- padding: '6px 12px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.GRAY}`,
- color: C.GRAY,
- fontSize: '11px',
+ {currentView === 'create' && (
+ <>
+ {/* Section Header */}
+ <div style={{
+ color: C.ORANGE,
+ fontSize: '14px',
fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- marginBottom: '12px'
- }}
- >
- ← BACK TO LIST
- </button>
-
- {/* Ticket Header */}
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${getStatusColor(selectedTicket.status)}`, padding: '16px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>
- <div>
- <span style={{ color: C.GRAY, fontSize: '11px', fontFamily: 'Consolas, monospace' }}>
- TICKET #{selectedTicket.id || selectedTicket.ticket_id}
- </span>
- <div style={{ color: C.WHITE, fontSize: '16px', fontWeight: 'bold', marginTop: '4px', fontFamily: 'Consolas, monospace' }}>
- {selectedTicket.subject}
- </div>
- </div>
- <div style={{ display: 'flex', gap: '8px' }}>
- {selectedTicket.status !== 'closed' && (
- <button
- onClick={() => updateTicketStatus('closed')}
- disabled={loading}
+ marginBottom: '8px',
+ letterSpacing: '0.5px'
+ }}>
+ CREATE NEW TICKET
+ </div>
+ <div style={{ borderBottom: `1px solid ${C.GRAY}`, marginBottom: '16px' }}></div>
+
+ {/* Form */}
+ <div style={{
+ backgroundColor: C.PANEL_BG,
+ border: `1px solid ${C.GRAY}`,
+ borderLeft: `4px solid ${C.GREEN}`,
+ padding: '20px',
+ maxWidth: '800px'
+ }}>
+ <div style={{ display: 'grid', gap: '16px' }}>
+ <div>
+ <label style={{ color: C.GRAY, fontSize: '11px', display: 'block', marginBottom: '4px' }}>
+ SUBJECT *
+ </label>
+ <input
+ type="text"
+ value={newTicket.subject}
+ onChange={(e) => setNewTicket({ ...newTicket, subject: e.target.value })}
+ placeholder="Brief description of your issue"
style={{
- padding: '6px 12px',
+ width: '100%',
+ padding: '8px',
backgroundColor: C.DARK_BG,
- border: `2px solid ${C.RED}`,
- color: C.RED,
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
+ border: `1px solid ${C.GRAY}`,
+ color: C.WHITE,
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ outline: 'none'
}}
- >
- CLOSE
- </button>
- )}
- {selectedTicket.status === 'closed' && (
- <button
- onClick={() => updateTicketStatus('open')}
- disabled={loading}
+ />
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
+ <div>
+ <label style={{ color: C.GRAY, fontSize: '11px', display: 'block', marginBottom: '4px' }}>
+ CATEGORY *
+ </label>
+ <select
+ value={newTicket.category}
+ onChange={(e) => setNewTicket({ ...newTicket, category: e.target.value })}
+ style={{
+ width: '100%',
+ padding: '8px',
+ backgroundColor: C.DARK_BG,
+ border: `1px solid ${C.GRAY}`,
+ color: C.WHITE,
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ outline: 'none',
+ cursor: 'pointer'
+ }}
+ >
+ <option value="technical">Technical Issue</option>
+ <option value="billing">Billing</option>
+ <option value="feature">Feature Request</option>
+ <option value="bug">Bug Report</option>
+ <option value="account">Account</option>
+ <option value="other">Other</option>
+ </select>
+ </div>
+
+ <div>
+ <label style={{ color: C.GRAY, fontSize: '11px', display: 'block', marginBottom: '4px' }}>
+ PRIORITY
+ </label>
+ <select
+ value={newTicket.priority}
+ onChange={(e) => setNewTicket({ ...newTicket, priority: e.target.value })}
+ style={{
+ width: '100%',
+ padding: '8px',
+ backgroundColor: C.DARK_BG,
+ border: `1px solid ${C.GRAY}`,
+ color: C.WHITE,
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ outline: 'none',
+ cursor: 'pointer'
+ }}
+ >
+ <option value="low">Low</option>
+ <option value="medium">Medium</option>
+ <option value="high">High</option>
+ </select>
+ </div>
+ </div>
+
+ <div>
+ <label style={{ color: C.GRAY, fontSize: '11px', display: 'block', marginBottom: '4px' }}>
+ DESCRIPTION *
+ </label>
+ <textarea
+ value={newTicket.description}
+ onChange={(e) => setNewTicket({ ...newTicket, description: e.target.value })}
+ placeholder="Provide detailed information about your issue..."
+ rows={12}
style={{
- padding: '6px 12px',
+ width: '100%',
+ padding: '8px',
backgroundColor: C.DARK_BG,
- border: `2px solid ${C.GREEN}`,
- color: C.GREEN,
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
+ border: `1px solid ${C.GRAY}`,
+ color: C.WHITE,
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ outline: 'none',
+ resize: 'vertical'
}}
- >
- REOPEN
- </button>
- )}
- </div>
- </div>
+ />
+ </div>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', fontSize: '11px', fontFamily: 'Consolas, monospace' }}>
- <div>
- <span style={{ color: C.GRAY }}>Status: </span>
- <span style={{ color: getStatusColor(selectedTicket.status), fontWeight: 'bold' }}>
- {selectedTicket.status?.toUpperCase()}
- </span>
- </div>
- <div>
- <span style={{ color: C.GRAY }}>Priority: </span>
- <span style={{ color: getPriorityColor(selectedTicket.priority), fontWeight: 'bold' }}>
- {selectedTicket.priority?.toUpperCase()}
- </span>
- </div>
- <div>
- <span style={{ color: C.GRAY }}>Category: </span>
- <span style={{ color: C.CYAN }}>{selectedTicket.category}</span>
- </div>
- <div>
- <span style={{ color: C.GRAY }}>Created: </span>
- <span style={{ color: C.WHITE }}>{formatDate(selectedTicket.created_at)}</span>
+ <button
+ onClick={createTicket}
+ disabled={loading}
+ style={{
+ padding: '10px 20px',
+ backgroundColor: loading ? C.GRAY : C.GREEN,
+ border: 'none',
+ color: 'black',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: loading ? 'not-allowed' : 'pointer',
+ width: 'fit-content'
+ }}
+ >
+ {loading ? 'CREATING...' : 'CREATE TICKET'}
+ </button>
</div>
</div>
+ </>
+ )}
- <div style={{ marginTop: '12px', padding: '12px', backgroundColor: C.DARK_BG, borderLeft: `4px solid ${C.BLUE}` }}>
- <div style={{ color: C.WHITE, fontSize: '12px', fontFamily: 'Consolas, monospace', lineHeight: '1.6' }}>
- {selectedTicket.description}
- </div>
+ {currentView === 'details' && selectedTicket && (
+ <>
+ {/* Section Header */}
+ <div style={{
+ color: C.ORANGE,
+ fontSize: '14px',
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ letterSpacing: '0.5px'
+ }}>
+ TICKET DETAILS - #{selectedTicket.id || selectedTicket.ticket_id}
</div>
- </div>
- </div>
+ <div style={{ borderBottom: `1px solid ${C.GRAY}`, marginBottom: '16px' }}></div>
+
+ {(() => {
+ const isDemoTicket = selectedTicket.id === 'DEMO-001' || selectedTicket.ticket_id === 'DEMO-001';
+ const messages = selectedTicket.messages || [];
+
+ return (
+ <>
+ {isDemoTicket && (
+ <div style={{
+ backgroundColor: C.BLUE,
+ color: 'black',
+ padding: '8px 12px',
+ marginBottom: '12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ textAlign: 'center'
+ }}>
+ DEMO TICKET - This shows you how the support system works. Create your own ticket to get real support!
+ </div>
+ )}
- {/* Messages */}
- <div style={{ flex: 1, overflowY: 'auto', marginBottom: '16px' }}>
- <div style={{ color: C.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', fontFamily: 'Consolas, monospace' }}>
- CONVERSATION ({messages.length})
- </div>
-
- {messages.length > 0 ? (
- <div style={{ display: 'grid', gap: '12px' }}>
- {messages.map((msg: any, idx: number) => (
- <div
- key={idx}
- style={{
+ {/* Ticket Header */}
+ <div style={{
backgroundColor: C.PANEL_BG,
- border: `2px solid ${C.GRAY}`,
- borderLeft: `6px solid ${msg.sender_type === 'user' ? C.CYAN : C.PURPLE}`,
- padding: '12px',
- fontFamily: 'Consolas, monospace'
- }}
- >
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
- <span style={{ color: msg.sender_type === 'user' ? C.CYAN : C.PURPLE, fontSize: '11px', fontWeight: 'bold' }}>
- {msg.sender_type === 'user' ? 'YOU' : 'SUPPORT TEAM'}
- </span>
- <span style={{ color: C.GRAY, fontSize: '10px' }}>
- {formatDate(msg.created_at)}
- </span>
- </div>
- <div style={{ color: C.WHITE, fontSize: '12px', lineHeight: '1.6' }}>
- {msg.message}
+ border: `1px solid ${isDemoTicket ? C.BLUE : C.GRAY}`,
+ borderLeft: `4px solid ${getStatusColor(selectedTicket.status)}`,
+ padding: '16px',
+ marginBottom: '16px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>
+ <div>
+ <div style={{ color: C.WHITE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ {selectedTicket.subject}
+ </div>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, auto)',
+ gap: '16px',
+ fontSize: '11px'
+ }}>
+ <div>
+ <span style={{ color: C.GRAY }}>Status: </span>
+ <span style={{ color: getStatusColor(selectedTicket.status), fontWeight: 'bold' }}>
+ {selectedTicket.status?.toUpperCase()}
+ </span>
+ </div>
+ <div>
+ <span style={{ color: C.GRAY }}>Priority: </span>
+ <span style={{ color: getPriorityColor(selectedTicket.priority), fontWeight: 'bold' }}>
+ {selectedTicket.priority?.toUpperCase()}
+ </span>
+ </div>
+ <div>
+ <span style={{ color: C.GRAY }}>Category: </span>
+ <span style={{ color: C.CYAN }}>{selectedTicket.category?.toUpperCase()}</span>
+ </div>
+ <div>
+ <span style={{ color: C.GRAY }}>Created: </span>
+ <span style={{ color: C.WHITE }}>{formatDate(selectedTicket.created_at)}</span>
+ </div>
+ </div>
+ </div>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ {!isDemoTicket && selectedTicket.status !== 'closed' && (
+ <button
+ onClick={() => updateTicketStatus('closed')}
+ disabled={loading}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: C.DARK_BG,
+ border: `1px solid ${C.RED}`,
+ color: C.RED,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CLOSE
+ </button>
+ )}
+ {!isDemoTicket && selectedTicket.status === 'closed' && (
+ <button
+ onClick={() => updateTicketStatus('open')}
+ disabled={loading}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: C.DARK_BG,
+ border: `1px solid ${C.GREEN}`,
+ color: C.GREEN,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ REOPEN
+ </button>
+ )}
+ </div>
+ </div>
+
+ <div style={{
+ padding: '12px',
+ backgroundColor: C.DARK_BG,
+ borderLeft: `4px solid ${C.BLUE}`,
+ color: C.WHITE,
+ fontSize: '11px',
+ lineHeight: '1.6',
+ whiteSpace: 'pre-wrap'
+ }}>
+ {selectedTicket.description}
+ </div>
</div>
- </div>
- ))}
- </div>
- ) : (
- <div style={{ color: C.GRAY, fontSize: '12px', fontFamily: 'Consolas, monospace', textAlign: 'center', padding: '20px' }}>
- No messages yet
- </div>
- )}
- </div>
- {/* Add Message */}
- {selectedTicket.status !== 'closed' && (
- <div style={{ backgroundColor: C.PANEL_BG, border: `2px solid ${C.GRAY}`, borderLeft: `6px solid ${C.GREEN}`, padding: '16px' }}>
- <div style={{ color: C.GREEN, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px', fontFamily: 'Consolas, monospace' }}>
- ADD MESSAGE
- </div>
- <textarea
- value={newMessage}
- onChange={(e) => setNewMessage(e.target.value)}
- placeholder="Type your message here..."
- rows={4}
- style={{
- width: '100%',
- padding: '10px',
- backgroundColor: C.DARK_BG,
- border: `2px solid ${C.GRAY}`,
- color: C.WHITE,
- fontSize: '12px',
- fontFamily: 'Consolas, monospace',
- outline: 'none',
- resize: 'vertical',
- marginBottom: '12px'
- }}
- />
- <button
- onClick={addMessage}
- disabled={loading || !newMessage.trim()}
- style={{
- padding: '10px 20px',
- backgroundColor: loading || !newMessage.trim() ? C.GRAY : C.GREEN,
- border: 'none',
- color: C.DARK_BG,
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: loading || !newMessage.trim() ? 'not-allowed' : 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- {loading ? 'SENDING...' : 'SEND MESSAGE'}
- </button>
- </div>
+ {/* Messages */}
+ <div style={{
+ color: C.ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ letterSpacing: '0.5px'
+ }}>
+ CONVERSATION ({messages.length})
+ </div>
+ <div style={{ borderBottom: `1px solid ${C.GRAY}`, marginBottom: '12px' }}></div>
+
+ {messages.length > 0 ? (
+ <div style={{ display: 'grid', gap: '8px', marginBottom: '16px' }}>
+ {messages.map((msg: any, idx: number) => (
+ <div
+ key={idx}
+ style={{
+ backgroundColor: C.PANEL_BG,
+ border: `1px solid ${C.GRAY}`,
+ borderLeft: `4px solid ${msg.sender_type === 'user' ? C.CYAN : C.PURPLE}`,
+ padding: '12px'
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
+ <span style={{ color: msg.sender_type === 'user' ? C.CYAN : C.PURPLE, fontSize: '11px', fontWeight: 'bold' }}>
+ {msg.sender_type === 'user' ? 'YOU' : 'SUPPORT TEAM'}
+ </span>
+ <span style={{ color: C.GRAY, fontSize: '10px' }}>
+ {formatDate(msg.created_at)}
+ </span>
+ </div>
+ <div style={{ color: C.WHITE, fontSize: '11px', lineHeight: '1.6' }}>
+ {msg.message}
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div style={{ color: C.GRAY, fontSize: '11px', textAlign: 'center', padding: '20px' }}>
+ No messages yet
+ </div>
+ )}
+
+ {/* Add Message */}
+ {selectedTicket.status !== 'closed' && !isDemoTicket && (
+ <div style={{
+ backgroundColor: C.PANEL_BG,
+ border: `1px solid ${C.GRAY}`,
+ borderLeft: `4px solid ${C.GREEN}`,
+ padding: '16px'
+ }}>
+ <div style={{ color: C.GREEN, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
+ ADD MESSAGE
+ </div>
+ <textarea
+ value={newMessage}
+ onChange={(e) => setNewMessage(e.target.value)}
+ placeholder="Type your message here..."
+ rows={4}
+ style={{
+ width: '100%',
+ padding: '8px',
+ backgroundColor: C.DARK_BG,
+ border: `1px solid ${C.GRAY}`,
+ color: C.WHITE,
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ outline: 'none',
+ resize: 'vertical',
+ marginBottom: '12px'
+ }}
+ />
+ <button
+ onClick={addMessage}
+ disabled={loading || !newMessage.trim()}
+ style={{
+ padding: '8px 16px',
+ backgroundColor: loading || !newMessage.trim() ? C.GRAY : C.GREEN,
+ border: 'none',
+ color: 'black',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: loading || !newMessage.trim() ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Send size={12} />
+ {loading ? 'SENDING...' : 'SEND MESSAGE'}
+ </button>
+ </div>
+ )}
+
+ {isDemoTicket && (
+ <div style={{
+ backgroundColor: C.PANEL_BG,
+ border: `1px solid ${C.BLUE}`,
+ borderLeft: `4px solid ${C.BLUE}`,
+ padding: '16px'
+ }}>
+ <div style={{ color: C.BLUE, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
+ DEMO TICKET - READ ONLY
+ </div>
+ <div style={{ color: C.GRAY, fontSize: '10px', lineHeight: '1.6' }}>
+ This is a demonstration ticket. You cannot add messages to demo tickets.
+ <br /><br />
+ To create a real support ticket and communicate with our team:
+ <br />
+ 1. Click "BACK TO LIST"
+ <br />
+ 2. Click "+ CREATE TICKET"
+ <br />
+ 3. Fill in your issue details
+ <br />
+ 4. Submit and receive support from our team
+ </div>
+ </div>
+ )}
+ </>
+ );
+ })()}
+ </>
)}
</div>
- );
- };
- if (!session) {
- return (
- <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: C.DARK_BG }}>
- <div style={{ textAlign: 'center', fontFamily: 'Consolas, monospace' }}>
- <div style={{ color: C.ORANGE, fontSize: '16px', marginBottom: '8px' }}>⚠️ AUTHENTICATION REQUIRED</div>
- <div style={{ color: C.GRAY, fontSize: '12px' }}>Please login to access support tickets</div>
- </div>
+ {/* Status Bar */}
+ <div style={{
+ borderTop: `1px solid ${C.GRAY}`,
+ backgroundColor: C.PANEL_BG,
+ padding: '6px 12px',
+ fontSize: '10px',
+ color: C.GRAY,
+ flexShrink: 0,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <span>Fincept Terminal Support System | 24/7 Customer Service</span>
+ <span>Response Time: &lt; 24 hours | Status: {loading ? 'UPDATING' : 'READY'}</span>
</div>
- );
- }
-
- return (
- <div style={{ height: '100%', backgroundColor: C.DARK_BG, padding: '20px', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
- {currentView === 'list' && renderListView()}
- {currentView === 'create' && renderCreateView()}
- {currentView === 'details' && renderDetailsView()}
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/tabs/docs/DocsTab.tsx b/fincept-terminal-desktop/src/components/tabs/docs/DocsTab.tsx
index 22d4f6429..c3bb4396f 100644
--- a/fincept-terminal-desktop/src/components/tabs/docs/DocsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/docs/DocsTab.tsx
@@ -1,16 +1,23 @@
-import React, { useState, useMemo } from 'react';
-import { Book, Search, Code, ChevronRight, Hash, FileText } from 'lucide-react';
+import React, { useState, useEffect } from 'react';
+import { Book, Search, Code, ChevronRight, FileText, HelpCircle, RefreshCw } from 'lucide-react';
import { DOC_SECTIONS } from './content';
import { DocSubsection } from './types';
import { getColors } from './constants';
import { useTerminalTheme } from '@/contexts/ThemeContext';
export default function DocsTab() {
- const { colors: themeColors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
+ const { colors: themeColors } = useTerminalTheme();
const COLORS = getColors();
+ const [currentTime, setCurrentTime] = useState(new Date());
const [selectedSection, setSelectedSection] = useState('getting-started');
const [searchQuery, setSearchQuery] = useState('');
- const [expandedSections, setExpandedSections] = useState<string[]>(['finscript']);
+ const [expandedSections, setExpandedSections] = useState<string[]>(['getting-started', 'finscript']);
+
+ // Update clock
+ useEffect(() => {
+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);
+ return () => clearInterval(timer);
+ }, []);
const toggleSection = (sectionId: string) => {
setExpandedSections((prev) =>
@@ -32,6 +39,10 @@ export default function DocsTab() {
(sub) => sub.id === selectedSection
);
+ // Get total count of doc sections
+ const totalSections = DOC_SECTIONS.length;
+ const totalTopics = DOC_SECTIONS.reduce((acc, section) => acc + section.subsections.length, 0);
+
return (
<div
style={{
@@ -41,157 +52,133 @@ export default function DocsTab() {
fontFamily: 'Consolas, monospace',
overflow: 'hidden',
display: 'flex',
- flexDirection: 'column',
- fontSize: '12px'
+ flexDirection: 'column'
}}
>
<style>{`
- .docs-scroll::-webkit-scrollbar { width: 10px; }
- .docs-scroll::-webkit-scrollbar-track { background: #0a0a0a; }
- .docs-scroll::-webkit-scrollbar-thumb { background: #404040; border-radius: 5px; }
- .docs-scroll::-webkit-scrollbar-thumb:hover { background: #525252; }
+ *::-webkit-scrollbar {
+ width: 8px;
+ height: 8px;
+ }
+ *::-webkit-scrollbar-track {
+ background: #1a1a1a;
+ }
+ *::-webkit-scrollbar-thumb {
+ background: #404040;
+ border-radius: 4px;
+ }
+ *::-webkit-scrollbar-thumb:hover {
+ background: #525252;
+ }
.docs-content h1 {
color: ${COLORS.ORANGE};
- font-size: 32px;
- font-weight: 700;
- margin: 0 0 24px 0;
- font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif;
- letter-spacing: -0.5px;
+ font-size: 18px;
+ font-weight: bold;
+ margin: 0 0 16px 0;
+ font-family: 'Consolas', monospace;
+ letter-spacing: 0.5px;
+ text-transform: uppercase;
}
.docs-content h2 {
color: ${COLORS.CYAN};
- font-size: 22px;
- font-weight: 600;
- margin: 32px 0 16px 0;
- font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif;
- display: flex;
- align-items: center;
- gap: 8px;
+ font-size: 14px;
+ font-weight: bold;
+ margin: 16px 0 8px 0;
+ font-family: 'Consolas', monospace;
+ text-transform: uppercase;
}
.docs-content h3 {
color: ${COLORS.WHITE};
- font-size: 18px;
- font-weight: 600;
- margin: 24px 0 12px 0;
- font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif;
+ font-size: 12px;
+ font-weight: bold;
+ margin: 12px 0 6px 0;
+ font-family: 'Consolas', monospace;
}
.docs-content p {
- line-height: 1.8;
- margin: 0 0 16px 0;
- font-size: 15px;
- font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif;
- color: rgba(255, 255, 255, 0.9);
+ line-height: 1.6;
+ margin: 0 0 12px 0;
+ font-size: 11px;
+ font-family: 'Consolas', monospace;
+ color: ${COLORS.WHITE};
}
.docs-content ul {
- margin: 16px 0;
+ margin: 12px 0;
padding-left: 0;
list-style: none;
}
.docs-content li {
- margin: 8px 0;
- padding-left: 28px;
- line-height: 1.7;
- font-size: 15px;
- font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif;
+ margin: 6px 0;
+ padding-left: 20px;
+ line-height: 1.5;
+ font-size: 11px;
+ font-family: 'Consolas', monospace;
position: relative;
- color: rgba(255, 255, 255, 0.85);
+ color: ${COLORS.WHITE};
}
.docs-content li::before {
- content: '•';
+ content: '■';
position: absolute;
- left: 12px;
+ left: 8px;
color: ${COLORS.ORANGE};
- font-weight: bold;
+ font-size: 8px;
}
.docs-content strong {
color: ${COLORS.CYAN};
- font-weight: 600;
+ font-weight: bold;
}
.docs-content code {
background: rgba(255, 165, 0, 0.1);
- padding: 2px 6px;
- border-radius: 3px;
- font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace;
- font-size: 14px;
- color: ${COLORS.ORANGE};
- }
- .section-badge {
- display: inline-block;
- padding: 4px 10px;
- background: rgba(255, 165, 0, 0.15);
- border: 1px solid ${COLORS.ORANGE};
- border-radius: 4px;
+ padding: 2px 4px;
+ border-radius: 2px;
+ font-family: 'Consolas', monospace;
font-size: 11px;
- font-weight: 600;
color: ${COLORS.ORANGE};
- text-transform: uppercase;
- letter-spacing: 0.5px;
- margin-bottom: 16px;
}
`}</style>
- {/* Header */}
- <div
- style={{
- backgroundColor: COLORS.PANEL_BG,
- borderBottom: `2px solid ${COLORS.ORANGE}`,
- padding: '12px 20px',
- flexShrink: 0
- }}
- >
- <div
- style={{
- display: 'flex',
- alignItems: 'center',
- gap: '16px',
- flexWrap: 'wrap'
- }}
- >
- <Book size={24} style={{ color: COLORS.ORANGE }} />
- <span style={{
- color: COLORS.ORANGE,
- fontWeight: '700',
- fontSize: '18px',
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif"
- }}>
- DOCUMENTATION
- </span>
+ {/* Header Bar */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '8px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ borderBottom: `1px solid ${COLORS.GRAY}`,
+ fontSize: '13px',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: COLORS.ORANGE, fontWeight: 'bold' }}>FINCEPT</span>
+ <span style={{ color: COLORS.WHITE }}>DOCUMENTATION TERMINAL</span>
<span style={{ color: COLORS.GRAY }}>|</span>
- <span style={{
- color: COLORS.CYAN,
- fontSize: '14px',
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif"
- }}>
- Complete Guide & API Reference
+ <span style={{ color: COLORS.WHITE, fontSize: '11px' }}>
+ {currentTime.toISOString().replace('T', ' ').substring(0, 19)}
</span>
</div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: COLORS.GRAY, fontSize: '11px' }}>SECTIONS:</span>
+ <span style={{ color: COLORS.CYAN, fontSize: '11px', fontWeight: 'bold' }}>{totalSections}</span>
+ <span style={{ color: COLORS.GRAY }}>|</span>
+ <span style={{ color: COLORS.GREEN, fontSize: '11px' }}>TOPICS:</span>
+ <span style={{ color: COLORS.GREEN, fontSize: '11px', fontWeight: 'bold' }}>{totalTopics}</span>
+ </div>
</div>
- {/* Search Bar */}
- <div
- style={{
- backgroundColor: COLORS.PANEL_BG,
- borderBottom: `1px solid ${COLORS.GRAY}`,
- padding: '14px 20px',
- flexShrink: 0
- }}
- >
- <div
- style={{
- display: 'flex',
- alignItems: 'center',
- gap: '10px',
- backgroundColor: COLORS.DARK_BG,
- border: `2px solid ${COLORS.GRAY}`,
- padding: '10px 16px',
- borderRadius: '6px',
- transition: 'border-color 0.2s'
- }}
- onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
- onBlur={(e) => e.currentTarget.style.borderColor = COLORS.GRAY}
- >
- <Search size={18} style={{ color: COLORS.ORANGE, flexShrink: 0 }} />
+ {/* Control Panel */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '8px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ borderBottom: `1px solid ${COLORS.GRAY}`,
+ fontSize: '12px',
+ gap: '8px',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>
+ <Search size={14} style={{ color: COLORS.ORANGE, flexShrink: 0 }} />
<input
type="text"
placeholder="Search documentation..."
@@ -199,89 +186,130 @@ export default function DocsTab() {
onChange={(e) => setSearchQuery(e.target.value)}
style={{
flex: 1,
- backgroundColor: 'transparent',
- border: 'none',
- outline: 'none',
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.GRAY}`,
color: COLORS.WHITE,
- fontSize: '14px',
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif",
- minWidth: '150px'
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ padding: '4px 8px',
+ outline: 'none',
+ maxWidth: '400px'
}}
/>
+ {searchQuery && (
+ <button
+ onClick={() => setSearchQuery('')}
+ style={{
+ backgroundColor: COLORS.GRAY,
+ color: 'black',
+ border: 'none',
+ padding: '4px 8px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CLEAR
+ </button>
+ )}
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: COLORS.GREEN, fontSize: '14px' }}>●</span>
+ <span style={{ color: COLORS.GREEN, fontSize: '11px', fontWeight: 'bold' }}>
+ READY
+ </span>
</div>
</div>
{/* Main Content Area */}
- <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
+ <div style={{ flex: 1, display: 'flex', minHeight: 0, overflow: 'hidden' }}>
{/* Sidebar Navigation */}
- <div
- className="docs-scroll"
- style={{
- width: '320px',
- borderRight: `2px solid ${COLORS.GRAY}`,
- backgroundColor: COLORS.PANEL_BG,
- overflowY: 'auto',
- padding: '16px',
- flexShrink: 0
- }}
- >
+ <div style={{
+ width: '280px',
+ borderRight: `1px solid ${COLORS.GRAY}`,
+ backgroundColor: COLORS.PANEL_BG,
+ overflowY: 'auto',
+ flexShrink: 0
+ }}>
+ {/* Section Header */}
+ <div style={{
+ color: COLORS.ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ padding: '12px',
+ borderBottom: `1px solid ${COLORS.GRAY}`,
+ letterSpacing: '0.5px'
+ }}>
+ NAVIGATION
+ </div>
+
+ {/* Navigation Tree */}
{filteredDocs.map((section) => (
- <div key={section.id} style={{ marginBottom: '12px' }}>
+ <div key={section.id} style={{ borderBottom: `1px solid ${COLORS.GRAY}` }}>
<div
onClick={() => toggleSection(section.id)}
style={{
display: 'flex',
alignItems: 'center',
- gap: '10px',
- padding: '12px 14px',
+ gap: '8px',
+ padding: '8px 12px',
backgroundColor: expandedSections.includes(section.id) ? COLORS.DARK_BG : 'transparent',
cursor: 'pointer',
- border: `1px solid ${expandedSections.includes(section.id) ? COLORS.ORANGE : COLORS.GRAY}`,
- borderRadius: '6px',
- transition: 'all 0.2s',
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif"
+ borderLeft: `4px solid ${expandedSections.includes(section.id) ? COLORS.ORANGE : 'transparent'}`,
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (!expandedSections.includes(section.id)) {
+ e.currentTarget.style.backgroundColor = '#1a1a1a';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (!expandedSections.includes(section.id)) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
}}
>
- <section.icon size={16} style={{ color: COLORS.ORANGE }} />
- <span style={{ flex: 1, fontSize: '13px', fontWeight: '600', color: COLORS.WHITE }}>
- {section.title}
- </span>
<ChevronRight
- size={16}
+ size={12}
style={{
color: COLORS.ORANGE,
transform: expandedSections.includes(section.id) ? 'rotate(90deg)' : 'rotate(0deg)',
transition: 'transform 0.2s'
}}
/>
+ <section.icon size={14} style={{ color: COLORS.ORANGE }} />
+ <span style={{ flex: 1, fontSize: '11px', fontWeight: 'bold', color: COLORS.WHITE }}>
+ {section.title.toUpperCase()}
+ </span>
+ <span style={{ fontSize: '9px', color: COLORS.GRAY }}>
+ ({section.subsections.length})
+ </span>
</div>
{expandedSections.includes(section.id) && (
- <div style={{ marginTop: '6px', marginLeft: '8px' }}>
+ <div style={{ backgroundColor: COLORS.DARK_BG }}>
{section.subsections.map((sub) => (
<div
key={sub.id}
onClick={() => setSelectedSection(sub.id)}
style={{
- padding: '10px 16px',
- fontSize: '13px',
+ padding: '6px 12px 6px 40px',
+ fontSize: '10px',
color: selectedSection === sub.id ? COLORS.ORANGE : COLORS.GRAY,
backgroundColor: selectedSection === sub.id ? 'rgba(255, 165, 0, 0.1)' : 'transparent',
cursor: 'pointer',
- borderLeft: `3px solid ${selectedSection === sub.id ? COLORS.ORANGE : 'transparent'}`,
- borderRadius: '4px',
- marginBottom: '4px',
- transition: 'all 0.15s',
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif",
- fontWeight: selectedSection === sub.id ? '500' : '400'
+ borderLeft: `4px solid ${selectedSection === sub.id ? COLORS.ORANGE : 'transparent'}`,
+ transition: 'all 0.15s'
}}
onMouseEnter={(e) => {
if (selectedSection !== sub.id) {
e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.05)';
+ e.currentTarget.style.color = COLORS.WHITE;
}
}}
onMouseLeave={(e) => {
if (selectedSection !== sub.id) {
e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = COLORS.GRAY;
}
}}
>
@@ -295,222 +323,247 @@ export default function DocsTab() {
</div>
{/* Content Area */}
- <div className="docs-scroll" style={{ flex: 1, overflowY: 'auto', padding: '40px 60px', backgroundColor: '#0a0a0a' }}>
- {activeSubsection ? (
- <div style={{ maxWidth: '100%', width: '100%' }}>
- {/* Section Category Badge */}
- <div className="section-badge">
- {DOC_SECTIONS.find(s => s.subsections.some(sub => sub.id === activeSubsection.id))?.title || 'Documentation'}
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ {activeSubsection && (
+ <>
+ {/* Content Header */}
+ <div style={{
+ backgroundColor: COLORS.PANEL_BG,
+ borderBottom: `1px solid ${COLORS.GRAY}`,
+ padding: '8px 12px',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <FileText size={14} style={{ color: COLORS.CYAN }} />
+ <span style={{ color: COLORS.CYAN, fontSize: '12px', fontWeight: 'bold' }}>
+ {activeSubsection.title.toUpperCase()}
+ </span>
+ <span style={{ color: COLORS.GRAY }}>|</span>
+ <span style={{ color: COLORS.GRAY, fontSize: '10px' }}>
+ {DOC_SECTIONS.find(s => s.subsections.some(sub => sub.id === activeSubsection.id))?.title || 'Documentation'}
+ </span>
+ </div>
</div>
- <h1 className="docs-content">
- {activeSubsection.title}
- </h1>
+ {/* Content Body */}
+ <div style={{ flex: 1, overflowY: 'auto', padding: '20px', backgroundColor: '#0a0a0a' }}>
+ <div style={{ maxWidth: '900px' }}>
+ {/* Section Badge */}
+ <div style={{
+ display: 'inline-block',
+ padding: '4px 8px',
+ backgroundColor: 'rgba(255, 165, 0, 0.15)',
+ border: `1px solid ${COLORS.ORANGE}`,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ color: COLORS.ORANGE,
+ marginBottom: '12px',
+ letterSpacing: '0.5px'
+ }}>
+ {DOC_SECTIONS.find(s => s.subsections.some(sub => sub.id === activeSubsection.id))?.title.toUpperCase() || 'DOCUMENTATION'}
+ </div>
+
+ <h1 className="docs-content">
+ {activeSubsection.title}
+ </h1>
- <div className="docs-content" style={{ fontSize: '15px', lineHeight: '1.8', color: COLORS.WHITE }}>
- {activeSubsection.content.split('\n\n').map((para, idx) => {
- const lines = para.split('\n');
- const isListSection = lines.some(line => line.startsWith('•'));
+ <div className="docs-content" style={{ fontSize: '11px', lineHeight: '1.6', color: COLORS.WHITE }}>
+ {activeSubsection.content.split('\n\n').map((para, idx) => {
+ const lines = para.split('\n');
+ const isListSection = lines.some(line => line.startsWith('•'));
- if (isListSection) {
- // Find the header line (if exists) and the list items
- const headerLine = lines.find(line => line.startsWith('**') && line.endsWith('**'));
- const listItems = lines.filter(line => line.startsWith('•'));
+ if (isListSection) {
+ const headerLine = lines.find(line => line.startsWith('**') && line.endsWith('**'));
+ const listItems = lines.filter(line => line.startsWith('•'));
- return (
- <div key={idx} style={{ marginBottom: '24px' }}>
- {headerLine && (
- <h3 style={{
- color: COLORS.CYAN,
- fontWeight: '600',
+ return (
+ <div key={idx} style={{ marginBottom: '16px' }}>
+ {headerLine && (
+ <h3 style={{
+ color: COLORS.CYAN,
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ fontSize: '12px',
+ fontFamily: 'Consolas, monospace'
+ }}>
+ {headerLine.replace(/\*\*/g, '')}
+ </h3>
+ )}
+ <ul style={{ margin: '0', paddingLeft: '0', listStyle: 'none' }}>
+ {listItems.map((item, itemIdx) => (
+ <li key={itemIdx}>
+ {item.substring(1).trim()}
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+ } else {
+ return (
+ <p key={idx} style={{
marginBottom: '12px',
- fontSize: '18px',
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif"
+ fontFamily: 'Consolas, monospace',
+ fontSize: '11px',
+ lineHeight: '1.6'
}}>
- {headerLine.replace(/\*\*/g, '')}
- </h3>
- )}
- <ul style={{ margin: '0', paddingLeft: '0', listStyle: 'none' }}>
- {listItems.map((item, itemIdx) => (
- <li key={itemIdx}>
- {item.substring(1).trim()}
- </li>
- ))}
- </ul>
+ {para}
+ </p>
+ );
+ }
+ })}
+ </div>
+
+ {activeSubsection.codeExample && (
+ <div style={{
+ marginTop: '24px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.GRAY}`,
+ borderLeft: `4px solid ${COLORS.GREEN}`,
+ padding: '16px'
+ }}>
+ <div style={{
+ color: COLORS.ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ fontFamily: 'Consolas, monospace'
+ }}>
+ <Code size={14} />
+ CODE EXAMPLE
</div>
- );
- } else {
- // Regular paragraph
- return (
- <p key={idx} style={{
- marginBottom: '20px',
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif",
- fontSize: '15px',
- lineHeight: '1.8'
+ <pre style={{
+ backgroundColor: '#0d0d0d',
+ border: `1px solid ${COLORS.GRAY}`,
+ padding: '12px',
+ overflowX: 'auto',
+ fontSize: '11px',
+ lineHeight: '1.5',
+ color: COLORS.GREEN,
+ fontFamily: 'Consolas, monospace',
+ margin: 0
}}>
- {para}
- </p>
- );
- }
- })}
+ <code>{activeSubsection.codeExample}</code>
+ </pre>
+ </div>
+ )}
+ </div>
</div>
+ </>
+ )}
- {activeSubsection.codeExample && (
- <div style={{ marginTop: '40px' }}>
- <div
- style={{
- color: COLORS.ORANGE,
- fontSize: '16px',
- fontWeight: '600',
- marginBottom: '12px',
- display: 'flex',
- alignItems: 'center',
- gap: '10px',
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif"
- }}
- >
- <Code size={18} />
- Code Example
- </div>
- <pre
- style={{
- backgroundColor: '#0d0d0d',
- border: `2px solid ${COLORS.GRAY}`,
- padding: '24px',
- borderRadius: '8px',
- overflowX: 'auto',
- fontSize: '14px',
- lineHeight: '1.7',
- color: COLORS.GREEN,
- fontFamily: "'JetBrains Mono', 'Fira Code', 'Consolas', monospace",
- boxShadow: '0 4px 12px rgba(0, 0, 0, 0.3)'
- }}
- >
- <code>{activeSubsection.codeExample}</code>
- </pre>
- </div>
- )}
- </div>
- ) : (
+ {!activeSubsection && (
<div style={{
- textAlign: 'center',
- paddingTop: '100px',
- color: COLORS.GRAY,
- maxWidth: '600px',
- margin: '0 auto'
+ flex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: '#0a0a0a',
+ padding: '40px'
}}>
- <Book size={64} style={{ marginBottom: '24px', opacity: 0.3, color: COLORS.ORANGE }} />
- <div style={{
- fontSize: '24px',
- fontWeight: '600',
- marginBottom: '12px',
- color: COLORS.WHITE,
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif"
- }}>
- Welcome to Fincept Terminal Documentation
- </div>
- <div style={{
- fontSize: '15px',
- lineHeight: '1.6',
- marginBottom: '32px',
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif"
- }}>
- Select a topic from the sidebar to get started with the comprehensive guide and API reference.
- </div>
<div style={{
- display: 'grid',
- gridTemplateColumns: 'repeat(2, 1fr)',
- gap: '16px',
- textAlign: 'left'
+ textAlign: 'center',
+ maxWidth: '600px'
}}>
- {DOC_SECTIONS.slice(0, 4).map((section) => (
- <div
- key={section.id}
- onClick={() => {
- toggleSection(section.id);
- setSelectedSection(section.subsections[0]?.id);
- }}
- style={{
- padding: '20px',
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.GRAY}`,
- borderRadius: '8px',
- cursor: 'pointer',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.borderColor = COLORS.ORANGE;
- e.currentTarget.style.backgroundColor = COLORS.DARK_BG;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = COLORS.GRAY;
- e.currentTarget.style.backgroundColor = COLORS.PANEL_BG;
- }}
- >
- <section.icon size={24} style={{ color: COLORS.ORANGE, marginBottom: '12px' }} />
- <div style={{
- fontSize: '16px',
- fontWeight: '600',
- color: COLORS.WHITE,
- marginBottom: '8px',
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif"
- }}>
- {section.title}
- </div>
- <div style={{
- fontSize: '13px',
- color: COLORS.GRAY,
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif"
- }}>
- {section.subsections.length} topics
+ <HelpCircle size={64} style={{ marginBottom: '24px', opacity: 0.3, color: COLORS.ORANGE }} />
+ <div style={{
+ fontSize: '16px',
+ fontWeight: 'bold',
+ marginBottom: '12px',
+ color: COLORS.ORANGE,
+ fontFamily: 'Consolas, monospace',
+ letterSpacing: '0.5px'
+ }}>
+ FINCEPT TERMINAL DOCUMENTATION
+ </div>
+ <div style={{
+ fontSize: '11px',
+ lineHeight: '1.6',
+ marginBottom: '24px',
+ color: COLORS.GRAY,
+ fontFamily: 'Consolas, monospace'
+ }}>
+ Select a topic from the navigation panel to view comprehensive guides and API reference.
+ </div>
+
+ {/* Quick Links Grid */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(2, 1fr)',
+ gap: '12px',
+ textAlign: 'left',
+ marginTop: '32px'
+ }}>
+ {DOC_SECTIONS.slice(0, 4).map((section) => (
+ <div
+ key={section.id}
+ onClick={() => {
+ toggleSection(section.id);
+ setSelectedSection(section.subsections[0]?.id);
+ }}
+ style={{
+ padding: '16px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.GRAY}`,
+ borderLeft: `4px solid ${COLORS.ORANGE}`,
+ cursor: 'pointer',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = COLORS.ORANGE;
+ e.currentTarget.style.backgroundColor = COLORS.DARK_BG;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = COLORS.GRAY;
+ e.currentTarget.style.borderLeftColor = COLORS.ORANGE;
+ e.currentTarget.style.backgroundColor = COLORS.PANEL_BG;
+ }}
+ >
+ <section.icon size={20} style={{ color: COLORS.ORANGE, marginBottom: '8px' }} />
+ <div style={{
+ fontSize: '11px',
+ fontWeight: 'bold',
+ color: COLORS.WHITE,
+ marginBottom: '4px',
+ fontFamily: 'Consolas, monospace'
+ }}>
+ {section.title.toUpperCase()}
+ </div>
+ <div style={{
+ fontSize: '10px',
+ color: COLORS.GRAY,
+ fontFamily: 'Consolas, monospace'
+ }}>
+ {section.subsections.length} topics available
+ </div>
</div>
- </div>
- ))}
+ ))}
+ </div>
</div>
</div>
)}
</div>
</div>
- {/* Footer */}
- <div
- style={{
- borderTop: `2px solid ${COLORS.ORANGE}`,
- backgroundColor: COLORS.PANEL_BG,
- padding: '10px 20px',
- fontSize: '12px',
- flexShrink: 0
- }}
- >
- <div
- style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- flexWrap: 'wrap',
- gap: '16px'
- }}
- >
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '16px',
- flexWrap: 'wrap',
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif"
- }}>
- <span style={{ color: COLORS.ORANGE, fontWeight: '600' }}>FINCEPT DOCS v3.0</span>
- <span style={{ color: COLORS.GRAY }}>|</span>
- <span style={{ color: COLORS.CYAN }}>FinScript Language Reference</span>
- <span style={{ color: COLORS.GRAY }}>|</span>
- <span style={{ color: COLORS.BLUE }}>API Documentation</span>
- </div>
- <div style={{
- color: COLORS.GRAY,
- fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif"
- }}>
- {activeSubsection ? `📖 ${activeSubsection.title}` : 'Browse Documentation'}
- </div>
+ {/* Status Bar */}
+ <div style={{
+ borderTop: `1px solid ${COLORS.GRAY}`,
+ backgroundColor: COLORS.PANEL_BG,
+ padding: '6px 12px',
+ fontSize: '10px',
+ color: COLORS.GRAY,
+ flexShrink: 0,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
+ <span>Fincept Terminal Documentation v3.0 | Complete API Reference & Guides</span>
+ <span>Sections: {totalSections} | Topics: {totalTopics}</span>
</div>
+ <span>{activeSubsection ? `Current: ${activeSubsection.title}` : 'Select a topic to begin'}</span>
</div>
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/MomentumAnalysis.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/MomentumAnalysis.tsx
new file mode 100644
index 000000000..78986c391
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/MomentumAnalysis.tsx
@@ -0,0 +1,270 @@
+// Main component for Momentum Indicators Analysis
+
+import React, { useState, useEffect, useCallback } from 'react';
+import { Search, RefreshCw, Activity } from 'lucide-react';
+import { SimpleCandlestickChart } from './components/SimpleCandlestickChart';
+import { IndicatorControls } from './components/IndicatorControls';
+import {
+ CandleData,
+ MomentumIndicatorParams,
+ MomentumIndicatorResult,
+ DEFAULT_MOMENTUM_PARAMS,
+ IndicatorType,
+ TimeFrame,
+ TIME_FRAMES,
+ TimeFrameConfig,
+} from './types';
+import { fetchHistoricalData, calculateAllMomentumIndicators } from './services/momentumIndicators';
+import { aggregateSignals } from './utils/signalAnalyzer';
+
+export const MomentumAnalysis: React.FC = () => {
+ const [symbol, setSymbol] = useState<string>('AAPL');
+ const [searchInput, setSearchInput] = useState<string>('AAPL');
+ const [timeFrame, setTimeFrame] = useState<TimeFrameConfig>(TIME_FRAMES[5]); // Default: 1 year
+ const [candleData, setCandleData] = useState<CandleData[]>([]);
+ const [indicators, setIndicators] = useState<MomentumIndicatorResult>({});
+ const [params, setParams] = useState<MomentumIndicatorParams>(DEFAULT_MOMENTUM_PARAMS);
+ const [activeIndicators, setActiveIndicators] = useState<Set<IndicatorType>>(
+ new Set(['rsi', 'macd', 'stochastic'])
+ );
+ const [loading, setLoading] = useState<boolean>(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Fetch data and calculate indicators
+ const fetchData = useCallback(async () => {
+ if (!symbol) return;
+
+ setLoading(true);
+ setError(null);
+
+ try {
+ // Fetch historical price data
+ const priceData = await fetchHistoricalData(symbol, timeFrame.value, timeFrame.interval);
+ setCandleData(priceData);
+
+ // Calculate only active indicators
+ const activeParams: MomentumIndicatorParams = {};
+ activeIndicators.forEach((indicator) => {
+ if (params[indicator]) {
+ (activeParams as any)[indicator] = params[indicator];
+ }
+ });
+
+ if (Object.keys(activeParams).length > 0) {
+ const indicatorResults = await calculateAllMomentumIndicators(
+ symbol,
+ activeParams,
+ timeFrame.value,
+ timeFrame.interval
+ );
+ setIndicators(indicatorResults);
+ } else {
+ setIndicators({});
+ }
+ } catch (err) {
+ console.error('Error fetching data:', err);
+ setError(err instanceof Error ? err.message : 'Failed to fetch data');
+ } finally {
+ setLoading(false);
+ }
+ }, [symbol, timeFrame, params, activeIndicators]);
+
+ // Initial load
+ useEffect(() => {
+ fetchData();
+ }, []);
+
+ // Handle search
+ const handleSearch = () => {
+ if (searchInput.trim()) {
+ setSymbol(searchInput.trim().toUpperCase());
+ }
+ };
+
+ // Handle parameter changes
+ const handleParamsChange = (newParams: MomentumIndicatorParams) => {
+ setParams(newParams);
+ };
+
+ // Handle indicator toggle
+ const handleToggleIndicator = (indicator: IndicatorType) => {
+ const newActiveIndicators = new Set(activeIndicators);
+ if (newActiveIndicators.has(indicator)) {
+ newActiveIndicators.delete(indicator);
+ } else {
+ newActiveIndicators.add(indicator);
+ }
+ setActiveIndicators(newActiveIndicators);
+ };
+
+ // Handle refresh
+ const handleRefresh = () => {
+ fetchData();
+ };
+
+ // Calculate aggregate signal
+ const getAggregateSignal = () => {
+ const signals = Object.values(indicators)
+ .filter((ind) => ind && 'signal' in ind)
+ .map((ind) => ({
+ signal: ind.signal,
+ strength: 70, // Default strength
+ reason: '',
+ }));
+
+ return aggregateSignals(signals);
+ };
+
+ const aggregateSignal = indicators && Object.keys(indicators).length > 0 ? getAggregateSignal() : null;
+
+ return (
+ <div className="h-full bg-[#0a0a0a] text-white overflow-hidden flex flex-col">
+ {/* Header */}
+ <div className="border-b border-[#333333] bg-[#0f0f0f] p-4">
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-3">
+ <Activity className="w-6 h-6 text-orange-500" />
+ <h2 className="text-2xl font-bold">Momentum Indicators Analysis</h2>
+ </div>
+ {aggregateSignal && (
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-gray-400">Overall Signal:</span>
+ <span
+ className={`px-3 py-1 rounded font-semibold ${
+ aggregateSignal.signal === 'BUY'
+ ? 'bg-green-500/20 text-green-400'
+ : aggregateSignal.signal === 'SELL'
+ ? 'bg-red-500/20 text-red-400'
+ : 'bg-gray-500/20 text-gray-400'
+ }`}
+ >
+ {aggregateSignal.signal}
+ </span>
+ <span className="text-xs text-gray-400">({aggregateSignal.strength.toFixed(0)}% confidence)</span>
+ </div>
+ )}
+ </div>
+
+ {/* Search and Controls */}
+ <div className="flex items-center gap-4">
+ <div className="flex-1 flex items-center gap-2">
+ <div className="relative flex-1 max-w-md">
+ <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
+ <input
+ type="text"
+ value={searchInput}
+ onChange={(e) => setSearchInput(e.target.value)}
+ onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
+ placeholder="Enter stock symbol (e.g., AAPL)"
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded-lg pl-10 pr-4 py-2 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-orange-500"
+ />
+ </div>
+ <button
+ onClick={handleSearch}
+ disabled={loading}
+ className="px-4 py-2 bg-orange-500 hover:bg-orange-600 disabled:bg-gray-600 rounded-lg font-semibold transition-colors"
+ >
+ Search
+ </button>
+ </div>
+
+ {/* Timeframe Selector */}
+ <select
+ value={TIME_FRAMES.findIndex((tf) => tf.value === timeFrame.value)}
+ onChange={(e) => setTimeFrame(TIME_FRAMES[parseInt(e.target.value)])}
+ className="bg-[#1a1a1a] border border-[#333333] rounded-lg px-4 py-2 text-white focus:outline-none focus:ring-2 focus:ring-orange-500"
+ >
+ {TIME_FRAMES.map((tf, index) => (
+ <option key={tf.value} value={index}>
+ {tf.label}
+ </option>
+ ))}
+ </select>
+
+ <button
+ onClick={handleRefresh}
+ disabled={loading}
+ className="p-2 bg-[#1a1a1a] hover:bg-[#222222] disabled:bg-gray-600 border border-[#333333] rounded-lg transition-colors"
+ title="Refresh data"
+ >
+ <RefreshCw className={`w-5 h-5 ${loading ? 'animate-spin' : ''}`} />
+ </button>
+ </div>
+ </div>
+
+ {/* Content */}
+ <div className="flex-1 overflow-hidden flex">
+ {/* Chart Area */}
+ <div className="flex-1 overflow-auto p-4">
+ {error && (
+ <div className="mb-4 p-4 bg-red-500/20 border border-red-500/30 rounded-lg text-red-400">
+ <p className="font-semibold">Error:</p>
+ <p className="text-sm">{error}</p>
+ </div>
+ )}
+
+ {loading && (
+ <div className="flex items-center justify-center h-64">
+ <div className="text-center">
+ <RefreshCw className="w-8 h-8 animate-spin text-orange-500 mx-auto mb-2" />
+ <p className="text-gray-400">Loading data for {symbol}...</p>
+ </div>
+ </div>
+ )}
+
+ {!loading && !error && candleData.length > 0 && (
+ <div className="space-y-4">
+ <div className="bg-[#0f0f0f] border border-[#333333] rounded-lg p-4">
+ <div className="flex items-center justify-between mb-4">
+ <h3 className="text-lg font-semibold">
+ {symbol} - {timeFrame.label}
+ </h3>
+ <div className="text-sm text-gray-400">
+ {candleData.length} candles | Interval: {timeFrame.interval}
+ </div>
+ </div>
+ <SimpleCandlestickChart
+ data={candleData}
+ indicators={indicators}
+ activeIndicators={activeIndicators}
+ height={700}
+ />
+ </div>
+ </div>
+ )}
+
+ {!loading && !error && candleData.length === 0 && (
+ <div className="flex items-center justify-center h-64">
+ <div className="text-center text-gray-400">
+ <Activity className="w-12 h-12 mx-auto mb-2 opacity-50" />
+ <p>Enter a stock symbol and click Search to analyze</p>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Indicator Controls Sidebar */}
+ <div className="w-96 border-l border-[#333333] bg-[#0f0f0f] overflow-y-auto p-4">
+ <IndicatorControls
+ params={params}
+ results={indicators}
+ activeIndicators={activeIndicators}
+ onParamsChange={handleParamsChange}
+ onToggleIndicator={handleToggleIndicator}
+ />
+
+ <div className="mt-6 p-4 bg-[#1a1a1a] border border-[#333333] rounded-lg">
+ <h4 className="font-semibold mb-2">How to use:</h4>
+ <ul className="text-sm text-gray-400 space-y-1">
+ <li>• Check indicators to enable them on the chart</li>
+ <li>• Click on an indicator to expand and adjust parameters</li>
+ <li>• Changes update instantly on the chart</li>
+ <li>• Use the reset button to restore default values</li>
+ <li>• Green = BUY signal, Red = SELL signal</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/README.md b/fincept-terminal-desktop/src/components/tabs/equity-research/README.md
new file mode 100644
index 000000000..db4c325f5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/README.md
@@ -0,0 +1,253 @@
+# Equity Research - Momentum Indicators Module
+
+Professional momentum indicators analysis with interactive candlestick charts, real-time parameter adjustment, and buy/sell signal generation.
+
+## Features
+
+✅ **Professional Candlestick Charts**
+- Powered by TradingView's lightweight-charts
+- High performance with large datasets
+- Synchronized main chart and indicator panel
+- Interactive crosshair and time range selection
+
+✅ **9 Momentum Indicators**
+1. **RSI** (Relative Strength Index)
+2. **MACD** (Moving Average Convergence Divergence)
+3. **Stochastic Oscillator**
+4. **CCI** (Commodity Channel Index)
+5. **ROC** (Rate of Change)
+6. **Williams %R**
+7. **Awesome Oscillator**
+8. **TSI** (True Strength Index)
+9. **Ultimate Oscillator**
+
+✅ **Real-time Parameter Adjustment**
+- Instant updates on chart
+- Custom overbought/oversold levels
+- Period adjustments for all indicators
+- Reset to default values
+
+✅ **Intelligent Signal Analysis**
+- BUY/SELL/NEUTRAL signals for each indicator
+- Signal strength (0-100%)
+- Aggregated overall signal
+- Detailed reasoning for each signal
+
+✅ **Multiple Timeframes**
+- 1 Day to Max (all available data)
+- Automatic interval selection
+- Seamless data fetching
+
+## Architecture
+
+```
+equity-research/
+├── components/
+│ ├── CandlestickChart.tsx # Main chart component
+│ └── IndicatorControls.tsx # Parameter controls sidebar
+├── services/
+│ └── momentumIndicators.ts # Python backend integration
+├── utils/
+│ └── signalAnalyzer.ts # Signal analysis logic
+├── types/
+│ └── index.ts # TypeScript type definitions
+├── MomentumAnalysis.tsx # Main container component
+└── README.md # This file
+```
+
+## Usage
+
+### Basic Usage
+
+```typescript
+import { MomentumAnalysis } from './equity-research/MomentumAnalysis';
+
+function MyTab() {
+ return <MomentumAnalysis />;
+}
+```
+
+### Customizing Indicators
+
+The component automatically loads with RSI, MACD, and Stochastic enabled. Users can:
+
+1. **Enable/Disable Indicators**: Check/uncheck in the sidebar
+2. **Adjust Parameters**: Click on indicator to expand settings
+3. **Change Timeframe**: Select from dropdown
+4. **Search Stocks**: Enter symbol and click Search
+
+### Signal Interpretation
+
+**BUY Signals** (Green):
+- RSI < 30 (oversold)
+- MACD bullish crossover
+- Stochastic oversold with bullish divergence
+- CCI < -100
+- Williams %R < -80
+- etc.
+
+**SELL Signals** (Red):
+- RSI > 70 (overbought)
+- MACD bearish crossover
+- Stochastic overbought with bearish divergence
+- CCI > 100
+- Williams %R > -20
+- etc.
+
+**NEUTRAL Signals** (Gray):
+- Indicators in normal range
+- No clear directional bias
+
+## Python Backend
+
+### Scripts Location
+```
+src-tauri/resources/scripts/Analytics/
+├── technical_analysis/
+│ └── momentum_indicators.py
+└── equityInvestment/
+ └── get_historical_data.py
+```
+
+### Data Flow
+
+1. User searches for symbol
+2. Frontend calls `fetchHistoricalData()` → Python script
+3. yfinance fetches price data
+4. Frontend calls `calculateAllMomentumIndicators()` → Python script
+5. Python calculates indicators with custom parameters
+6. Signal analyzer determines BUY/SELL/NEUTRAL
+7. Charts update with new data
+
+## Adding New Indicators
+
+### 1. Update Types (`types/index.ts`)
+
+```typescript
+export interface MomentumIndicatorParams {
+ // ... existing
+ my_indicator?: {
+ period: number;
+ threshold: number;
+ };
+}
+
+export const DEFAULT_MOMENTUM_PARAMS = {
+ // ... existing
+ my_indicator: {
+ period: 14,
+ threshold: 50,
+ },
+};
+```
+
+### 2. Add Signal Analyzer (`utils/signalAnalyzer.ts`)
+
+```typescript
+export function analyzeMyIndicator(
+ values: IndicatorData[],
+ params: MomentumIndicatorParams['my_indicator']
+): SignalResult {
+ // Your signal logic
+ return { signal: 'BUY', strength: 80, reason: 'Condition met' };
+}
+```
+
+### 3. Create Service Method (`services/momentumIndicators.ts`)
+
+```typescript
+export async function calculateMyIndicator(
+ symbol: string,
+ params: MomentumIndicatorParams['my_indicator'],
+ period: string,
+ interval: string
+): Promise<MomentumIndicatorResult['my_indicator']> {
+ // Call Python script and parse result
+}
+```
+
+### 4. Add Python Implementation
+
+Update `momentum_indicators.py`:
+
+```python
+def calculate_my_indicator(data, period=14, threshold=50):
+ # Your calculation logic
+ return {'values': result}
+```
+
+### 5. Update Chart Component
+
+Add your indicator to `CandlestickChart.tsx` in the indicators rendering section.
+
+### 6. Add Controls
+
+Update `IndicatorControls.tsx` to include parameter controls for your indicator.
+
+## Performance Optimization
+
+- **Debounced parameter updates**: 300ms delay
+- **Memoized chart data**: React.memo on expensive components
+- **Efficient data structures**: Map for series management
+- **Lazy loading**: Only active indicators are calculated
+- **WebGL rendering**: Handled by lightweight-charts
+
+## Dependencies
+
+- `lightweight-charts`: Professional charting library
+- `yfinance`: Python stock data fetching
+- `pandas`, `numpy`: Data processing
+- `lucide-react`: Icons
+- `@tauri-apps/api`: Backend integration
+
+## Color Scheme
+
+```typescript
+const CHART_COLORS = {
+ upColor: '#10b981', // Green candlesticks
+ downColor: '#ef4444', // Red candlesticks
+ background: '#0a0a0a', // Dark background
+ rsi: '#FFA500', // Orange
+ macd: '#2962FF', // Blue
+ stochasticK: '#00CED1', // Cyan
+ // ... etc
+};
+```
+
+## Future Enhancements
+
+- [ ] Volume indicators (OBV, VWAP)
+- [ ] Trend indicators (EMA, SMA, Bollinger Bands)
+- [ ] Volatility indicators (ATR, Keltner Channels)
+- [ ] Pattern recognition (Head & Shoulders, Triangles)
+- [ ] Multi-symbol comparison
+- [ ] Saved configurations
+- [ ] Alert system
+- [ ] Export to PNG/CSV
+
+## Troubleshooting
+
+### Charts not rendering
+- Check browser console for errors
+- Verify lightweight-charts is installed: `npm list lightweight-charts`
+- Ensure container has height set
+
+### Python scripts failing
+- Check Python is bundled: `src-tauri/resources/python/`
+- Verify yfinance is installed in bundled Python
+- Check Tauri command output in terminal
+
+### Indicators not updating
+- Check network tab for Python script execution
+- Verify symbol is valid
+- Check parameter values are within valid ranges
+
+## License
+
+Part of Fincept Terminal - All Rights Reserved
+
+---
+
+**Last Updated**: 2025-01-30
+**Version**: 1.0.0
+**Author**: Fincept Corporation
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/components/IndicatorControls.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/components/IndicatorControls.tsx
new file mode 100644
index 000000000..bb262678d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/components/IndicatorControls.tsx
@@ -0,0 +1,409 @@
+// Indicator controls for parameter adjustment and display
+
+import React, { useState } from 'react';
+import {
+ MomentumIndicatorParams,
+ DEFAULT_MOMENTUM_PARAMS,
+ IndicatorType,
+ MomentumIndicatorResult,
+} from '../types';
+import { ChevronDown, ChevronUp, Settings, TrendingUp } from 'lucide-react';
+
+interface IndicatorControlsProps {
+ params: MomentumIndicatorParams;
+ results: MomentumIndicatorResult;
+ activeIndicators: Set<IndicatorType>;
+ onParamsChange: (params: MomentumIndicatorParams) => void;
+ onToggleIndicator: (indicator: IndicatorType) => void;
+}
+
+const INDICATOR_CONFIGS: Record<
+ IndicatorType,
+ { name: string; description: string; color: string }
+> = {
+ rsi: {
+ name: 'RSI',
+ description: 'Relative Strength Index',
+ color: '#FFA500',
+ },
+ macd: {
+ name: 'MACD',
+ description: 'Moving Average Convergence Divergence',
+ color: '#2962FF',
+ },
+ stochastic: {
+ name: 'Stochastic',
+ description: 'Stochastic Oscillator',
+ color: '#00CED1',
+ },
+ cci: {
+ name: 'CCI',
+ description: 'Commodity Channel Index',
+ color: '#FFD700',
+ },
+ roc: {
+ name: 'ROC',
+ description: 'Rate of Change',
+ color: '#9370DB',
+ },
+ williams_r: {
+ name: 'Williams %R',
+ description: 'Williams Percent Range',
+ color: '#00FA9A',
+ },
+ awesome_oscillator: {
+ name: 'Awesome Oscillator',
+ description: 'Awesome Oscillator',
+ color: '#FF1493',
+ },
+ tsi: {
+ name: 'TSI',
+ description: 'True Strength Index',
+ color: '#4169E1',
+ },
+ ultimate_oscillator: {
+ name: 'Ultimate Oscillator',
+ description: 'Ultimate Oscillator',
+ color: '#32CD32',
+ },
+};
+
+export const IndicatorControls: React.FC<IndicatorControlsProps> = ({
+ params,
+ results,
+ activeIndicators,
+ onParamsChange,
+ onToggleIndicator,
+}) => {
+ const [expandedIndicator, setExpandedIndicator] = useState<IndicatorType | null>(null);
+
+ const getSignalBadge = (signal: 'BUY' | 'SELL' | 'NEUTRAL') => {
+ const colors = {
+ BUY: 'bg-green-500/20 text-green-400 border-green-500/30',
+ SELL: 'bg-red-500/20 text-red-400 border-red-500/30',
+ NEUTRAL: 'bg-gray-500/20 text-gray-400 border-gray-500/30',
+ };
+
+ return (
+ <span
+ className={`px-2 py-0.5 text-xs font-semibold rounded border ${colors[signal]}`}
+ >
+ {signal}
+ </span>
+ );
+ };
+
+ const updateParam = (indicator: IndicatorType, key: string, value: number) => {
+ const newParams = {
+ ...params,
+ [indicator]: {
+ ...params[indicator],
+ [key]: value,
+ },
+ };
+ onParamsChange(newParams);
+ };
+
+ const resetParams = (indicator: IndicatorType) => {
+ const newParams = {
+ ...params,
+ [indicator]: DEFAULT_MOMENTUM_PARAMS[indicator],
+ };
+ onParamsChange(newParams);
+ };
+
+ const renderRSIControls = () => {
+ const rsiParams = params.rsi || DEFAULT_MOMENTUM_PARAMS.rsi!;
+ const rsiResult = results.rsi;
+
+ return (
+ <div className="space-y-3">
+ <div className="grid grid-cols-3 gap-3">
+ <div>
+ <label className="text-xs text-gray-400 block mb-1">Period</label>
+ <input
+ type="number"
+ value={rsiParams.period}
+ onChange={(e) => updateParam('rsi', 'period', parseInt(e.target.value))}
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded px-2 py-1 text-sm text-white"
+ min="2"
+ max="100"
+ />
+ </div>
+ <div>
+ <label className="text-xs text-gray-400 block mb-1">Overbought</label>
+ <input
+ type="number"
+ value={rsiParams.overbought}
+ onChange={(e) => updateParam('rsi', 'overbought', parseInt(e.target.value))}
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded px-2 py-1 text-sm text-white"
+ min="50"
+ max="100"
+ />
+ </div>
+ <div>
+ <label className="text-xs text-gray-400 block mb-1">Oversold</label>
+ <input
+ type="number"
+ value={rsiParams.oversold}
+ onChange={(e) => updateParam('rsi', 'oversold', parseInt(e.target.value))}
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded px-2 py-1 text-sm text-white"
+ min="0"
+ max="50"
+ />
+ </div>
+ </div>
+ {rsiResult && (
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-gray-400">
+ Current: <span className="text-white font-semibold">{rsiResult.current_value.toFixed(2)}</span>
+ </span>
+ {getSignalBadge(rsiResult.signal)}
+ </div>
+ )}
+ </div>
+ );
+ };
+
+ const renderMACDControls = () => {
+ const macdParams = params.macd || DEFAULT_MOMENTUM_PARAMS.macd!;
+ const macdResult = results.macd;
+
+ return (
+ <div className="space-y-3">
+ <div className="grid grid-cols-3 gap-3">
+ <div>
+ <label className="text-xs text-gray-400 block mb-1">Fast Period</label>
+ <input
+ type="number"
+ value={macdParams.fast_period}
+ onChange={(e) => updateParam('macd', 'fast_period', parseInt(e.target.value))}
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded px-2 py-1 text-sm text-white"
+ min="2"
+ max="50"
+ />
+ </div>
+ <div>
+ <label className="text-xs text-gray-400 block mb-1">Slow Period</label>
+ <input
+ type="number"
+ value={macdParams.slow_period}
+ onChange={(e) => updateParam('macd', 'slow_period', parseInt(e.target.value))}
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded px-2 py-1 text-sm text-white"
+ min="2"
+ max="100"
+ />
+ </div>
+ <div>
+ <label className="text-xs text-gray-400 block mb-1">Signal Period</label>
+ <input
+ type="number"
+ value={macdParams.signal_period}
+ onChange={(e) => updateParam('macd', 'signal_period', parseInt(e.target.value))}
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded px-2 py-1 text-sm text-white"
+ min="2"
+ max="50"
+ />
+ </div>
+ </div>
+ {macdResult && (
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-gray-400">
+ Histogram: <span className="text-white font-semibold">{macdResult.current_histogram.toFixed(4)}</span>
+ </span>
+ {getSignalBadge(macdResult.signal)}
+ </div>
+ )}
+ </div>
+ );
+ };
+
+ const renderStochasticControls = () => {
+ const stochParams = params.stochastic || DEFAULT_MOMENTUM_PARAMS.stochastic!;
+ const stochResult = results.stochastic;
+
+ return (
+ <div className="space-y-3">
+ <div className="grid grid-cols-4 gap-3">
+ <div>
+ <label className="text-xs text-gray-400 block mb-1">K Period</label>
+ <input
+ type="number"
+ value={stochParams.k_period}
+ onChange={(e) => updateParam('stochastic', 'k_period', parseInt(e.target.value))}
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded px-2 py-1 text-sm text-white"
+ min="2"
+ max="50"
+ />
+ </div>
+ <div>
+ <label className="text-xs text-gray-400 block mb-1">D Period</label>
+ <input
+ type="number"
+ value={stochParams.d_period}
+ onChange={(e) => updateParam('stochastic', 'd_period', parseInt(e.target.value))}
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded px-2 py-1 text-sm text-white"
+ min="2"
+ max="20"
+ />
+ </div>
+ <div>
+ <label className="text-xs text-gray-400 block mb-1">Overbought</label>
+ <input
+ type="number"
+ value={stochParams.overbought}
+ onChange={(e) => updateParam('stochastic', 'overbought', parseInt(e.target.value))}
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded px-2 py-1 text-sm text-white"
+ min="50"
+ max="100"
+ />
+ </div>
+ <div>
+ <label className="text-xs text-gray-400 block mb-1">Oversold</label>
+ <input
+ type="number"
+ value={stochParams.oversold}
+ onChange={(e) => updateParam('stochastic', 'oversold', parseInt(e.target.value))}
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded px-2 py-1 text-sm text-white"
+ min="0"
+ max="50"
+ />
+ </div>
+ </div>
+ {stochResult && (
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-gray-400">
+ %K: <span className="text-white font-semibold">{stochResult.current_k.toFixed(2)}</span>
+ {' | '}
+ %D: <span className="text-white font-semibold">{stochResult.current_d.toFixed(2)}</span>
+ </span>
+ {getSignalBadge(stochResult.signal)}
+ </div>
+ )}
+ </div>
+ );
+ };
+
+ const renderSimpleIndicatorControls = (
+ indicator: IndicatorType,
+ paramKeys: string[]
+ ) => {
+ const indicatorParams = params[indicator] || DEFAULT_MOMENTUM_PARAMS[indicator];
+ const result = results[indicator];
+
+ if (!indicatorParams) return null;
+
+ return (
+ <div className="space-y-3">
+ <div className="grid grid-cols-3 gap-3">
+ {paramKeys.map((key) => (
+ <div key={key}>
+ <label className="text-xs text-gray-400 block mb-1 capitalize">
+ {key.replace(/_/g, ' ')}
+ </label>
+ <input
+ type="number"
+ value={(indicatorParams as any)[key]}
+ onChange={(e) => updateParam(indicator, key, parseInt(e.target.value))}
+ className="w-full bg-[#1a1a1a] border border-[#333333] rounded px-2 py-1 text-sm text-white"
+ min="1"
+ max="200"
+ />
+ </div>
+ ))}
+ </div>
+ {result && 'current_value' in result && (
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-gray-400">
+ Current: <span className="text-white font-semibold">{result.current_value.toFixed(2)}</span>
+ </span>
+ {getSignalBadge(result.signal)}
+ </div>
+ )}
+ </div>
+ );
+ };
+
+ const renderIndicatorPanel = (indicator: IndicatorType) => {
+ const config = INDICATOR_CONFIGS[indicator];
+ const isActive = activeIndicators.has(indicator);
+ const isExpanded = expandedIndicator === indicator;
+
+ return (
+ <div
+ key={indicator}
+ className="border border-[#333333] rounded-lg overflow-hidden bg-[#1a1a1a]"
+ >
+ <div
+ className="flex items-center justify-between p-3 cursor-pointer hover:bg-[#222222] transition-colors"
+ onClick={() => setExpandedIndicator(isExpanded ? null : indicator)}
+ >
+ <div className="flex items-center gap-3">
+ <input
+ type="checkbox"
+ checked={isActive}
+ onChange={(e) => {
+ e.stopPropagation();
+ onToggleIndicator(indicator);
+ }}
+ className="w-4 h-4 rounded border-[#333333] bg-[#0a0a0a] text-orange-500 focus:ring-orange-500"
+ />
+ <div className="flex items-center gap-2">
+ <div
+ className="w-3 h-3 rounded-full"
+ style={{ backgroundColor: config.color }}
+ />
+ <div>
+ <div className="font-semibold text-white">{config.name}</div>
+ <div className="text-xs text-gray-400">{config.description}</div>
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ resetParams(indicator);
+ }}
+ className="p-1 hover:bg-[#333333] rounded transition-colors"
+ title="Reset to defaults"
+ >
+ <Settings className="w-4 h-4 text-gray-400" />
+ </button>
+ {isExpanded ? (
+ <ChevronUp className="w-5 h-5 text-gray-400" />
+ ) : (
+ <ChevronDown className="w-5 h-5 text-gray-400" />
+ )}
+ </div>
+ </div>
+
+ {isExpanded && (
+ <div className="p-3 border-t border-[#333333] bg-[#0f0f0f]">
+ {indicator === 'rsi' && renderRSIControls()}
+ {indicator === 'macd' && renderMACDControls()}
+ {indicator === 'stochastic' && renderStochasticControls()}
+ {indicator === 'cci' && renderSimpleIndicatorControls('cci', ['period', 'overbought', 'oversold'])}
+ {indicator === 'roc' && renderSimpleIndicatorControls('roc', ['period'])}
+ {indicator === 'williams_r' && renderSimpleIndicatorControls('williams_r', ['period', 'overbought', 'oversold'])}
+ {indicator === 'awesome_oscillator' && renderSimpleIndicatorControls('awesome_oscillator', ['fast_period', 'slow_period'])}
+ {indicator === 'tsi' && renderSimpleIndicatorControls('tsi', ['long_period', 'short_period', 'signal_period'])}
+ {indicator === 'ultimate_oscillator' && renderSimpleIndicatorControls('ultimate_oscillator', ['period1', 'period2', 'period3', 'weight1', 'weight2', 'weight3'])}
+ </div>
+ )}
+ </div>
+ );
+ };
+
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2 mb-4">
+ <TrendingUp className="w-5 h-5 text-orange-500" />
+ <h3 className="text-lg font-semibold text-white">Momentum Indicators</h3>
+ </div>
+ {Object.keys(INDICATOR_CONFIGS).map((indicator) =>
+ renderIndicatorPanel(indicator as IndicatorType)
+ )}
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/components/SimpleCandlestickChart.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/components/SimpleCandlestickChart.tsx
new file mode 100644
index 000000000..980fd4115
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/components/SimpleCandlestickChart.tsx
@@ -0,0 +1,345 @@
+// Simple professional candlestick chart with Recharts
+
+import React from 'react';
+import {
+ ComposedChart,
+ Line,
+ Bar,
+ XAxis,
+ YAxis,
+ CartesianGrid,
+ Tooltip,
+ Legend,
+ ResponsiveContainer,
+ Area,
+} from 'recharts';
+import { CandleData, IndicatorData, MomentumIndicatorResult, IndicatorType } from '../types';
+
+interface SimpleCandlestickChartProps {
+ data: CandleData[];
+ indicators: MomentumIndicatorResult;
+ activeIndicators: Set<IndicatorType>;
+ height?: number;
+}
+
+const CHART_COLORS = {
+ upColor: '#10b981',
+ downColor: '#ef4444',
+ rsi: '#FFA500',
+ macd: '#2962FF',
+ macdSignal: '#FF6347',
+ macdHistogram: '#787878',
+ stochasticK: '#00CED1',
+ stochasticD: '#FF69B4',
+ cci: '#FFD700',
+ roc: '#9370DB',
+ williamsR: '#00FA9A',
+ ao: '#FF1493',
+ tsi: '#4169E1',
+ tsiSignal: '#FF8C00',
+ uo: '#32CD32',
+};
+
+export const SimpleCandlestickChart: React.FC<SimpleCandlestickChartProps> = ({
+ data,
+ indicators,
+ activeIndicators,
+ height = 700,
+}) => {
+ // Merge price data with indicators
+ const chartData = data.map((candle, index) => {
+ const dataPoint: any = {
+ time: new Date(candle.time * 1000).toLocaleDateString(),
+ open: candle.open,
+ high: candle.high,
+ low: candle.low,
+ close: candle.close,
+ volume: candle.volume,
+ wickHigh: candle.high,
+ wickLow: candle.low,
+ bodyHigh: Math.max(candle.open, candle.close),
+ bodyLow: Math.min(candle.open, candle.close),
+ color: candle.close >= candle.open ? CHART_COLORS.upColor : CHART_COLORS.downColor,
+ };
+
+ // Add indicator values
+ if (activeIndicators.has('rsi') && indicators.rsi) {
+ const rsiValue = indicators.rsi.values[index]?.value;
+ if (rsiValue !== null && rsiValue !== undefined) {
+ dataPoint.rsi = rsiValue;
+ }
+ }
+
+ if (activeIndicators.has('macd') && indicators.macd) {
+ const macdValue = indicators.macd.macd_line[index]?.value;
+ const signalValue = indicators.macd.signal_line[index]?.value;
+ const histValue = indicators.macd.histogram[index]?.value;
+ if (macdValue !== null) dataPoint.macd = macdValue;
+ if (signalValue !== null) dataPoint.macdSignal = signalValue;
+ if (histValue !== null) dataPoint.macdHistogram = histValue;
+ }
+
+ if (activeIndicators.has('stochastic') && indicators.stochastic) {
+ const kValue = indicators.stochastic.k_values[index]?.value;
+ const dValue = indicators.stochastic.d_values[index]?.value;
+ if (kValue !== null) dataPoint.stochK = kValue;
+ if (dValue !== null) dataPoint.stochD = dValue;
+ }
+
+ if (activeIndicators.has('cci') && indicators.cci) {
+ const cciValue = indicators.cci.values[index]?.value;
+ if (cciValue !== null) dataPoint.cci = cciValue;
+ }
+
+ if (activeIndicators.has('roc') && indicators.roc) {
+ const rocValue = indicators.roc.values[index]?.value;
+ if (rocValue !== null) dataPoint.roc = rocValue;
+ }
+
+ if (activeIndicators.has('williams_r') && indicators.williams_r) {
+ const wrValue = indicators.williams_r.values[index]?.value;
+ if (wrValue !== null) dataPoint.williamsR = wrValue;
+ }
+
+ if (activeIndicators.has('awesome_oscillator') && indicators.awesome_oscillator) {
+ const aoValue = indicators.awesome_oscillator.values[index]?.value;
+ if (aoValue !== null) dataPoint.ao = aoValue;
+ }
+
+ if (activeIndicators.has('tsi') && indicators.tsi) {
+ const tsiValue = indicators.tsi.values[index]?.value;
+ const tsiSignalValue = indicators.tsi.signal_line[index]?.value;
+ if (tsiValue !== null) dataPoint.tsi = tsiValue;
+ if (tsiSignalValue !== null) dataPoint.tsiSignal = tsiSignalValue;
+ }
+
+ if (activeIndicators.has('ultimate_oscillator') && indicators.ultimate_oscillator) {
+ const uoValue = indicators.ultimate_oscillator.values[index]?.value;
+ if (uoValue !== null) dataPoint.uo = uoValue;
+ }
+
+ return dataPoint;
+ });
+
+ const mainChartHeight = Math.floor(height * 0.65);
+ const indicatorChartHeight = Math.floor(height * 0.35);
+
+ return (
+ <div className="space-y-4">
+ {/* Main Price Chart */}
+ <ResponsiveContainer width="100%" height={mainChartHeight}>
+ <ComposedChart
+ data={chartData}
+ margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
+ >
+ <CartesianGrid strokeDasharray="3 3" stroke="#1a1a1a" />
+ <XAxis
+ dataKey="time"
+ stroke="#666"
+ tick={{ fill: '#999' }}
+ tickLine={{ stroke: '#333' }}
+ />
+ <YAxis
+ stroke="#666"
+ tick={{ fill: '#999' }}
+ tickLine={{ stroke: '#333' }}
+ domain={['auto', 'auto']}
+ />
+ <Tooltip
+ contentStyle={{
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #333',
+ borderRadius: '8px',
+ color: '#fff',
+ }}
+ />
+ <Legend wrapperStyle={{ color: '#999' }} />
+
+ {/* Candlestick bodies */}
+ <Bar
+ dataKey={(entry) => [entry.bodyLow, entry.bodyHigh]}
+ fill={CHART_COLORS.upColor}
+ stroke="none"
+ barSize={8}
+ name="Price"
+ />
+
+ {/* Close price line for easier trending */}
+ <Line
+ type="monotone"
+ dataKey="close"
+ stroke="#FFA500"
+ strokeWidth={1.5}
+ dot={false}
+ name="Close"
+ />
+ </ComposedChart>
+ </ResponsiveContainer>
+
+ {/* Indicator Chart */}
+ {activeIndicators.size > 0 && (
+ <ResponsiveContainer width="100%" height={indicatorChartHeight}>
+ <ComposedChart
+ data={chartData}
+ margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
+ >
+ <CartesianGrid strokeDasharray="3 3" stroke="#1a1a1a" />
+ <XAxis
+ dataKey="time"
+ stroke="#666"
+ tick={{ fill: '#999' }}
+ tickLine={{ stroke: '#333' }}
+ />
+ <YAxis
+ stroke="#666"
+ tick={{ fill: '#999' }}
+ tickLine={{ stroke: '#333' }}
+ />
+ <Tooltip
+ contentStyle={{
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #333',
+ borderRadius: '8px',
+ color: '#fff',
+ }}
+ />
+ <Legend wrapperStyle={{ color: '#999' }} />
+
+ {activeIndicators.has('rsi') && (
+ <Line
+ type="monotone"
+ dataKey="rsi"
+ stroke={CHART_COLORS.rsi}
+ strokeWidth={2}
+ dot={false}
+ name="RSI"
+ />
+ )}
+
+ {activeIndicators.has('macd') && (
+ <>
+ <Line
+ type="monotone"
+ dataKey="macd"
+ stroke={CHART_COLORS.macd}
+ strokeWidth={2}
+ dot={false}
+ name="MACD"
+ />
+ <Line
+ type="monotone"
+ dataKey="macdSignal"
+ stroke={CHART_COLORS.macdSignal}
+ strokeWidth={2}
+ dot={false}
+ name="Signal"
+ />
+ <Bar
+ dataKey="macdHistogram"
+ fill={CHART_COLORS.macdHistogram}
+ opacity={0.6}
+ name="Histogram"
+ />
+ </>
+ )}
+
+ {activeIndicators.has('stochastic') && (
+ <>
+ <Line
+ type="monotone"
+ dataKey="stochK"
+ stroke={CHART_COLORS.stochasticK}
+ strokeWidth={2}
+ dot={false}
+ name="%K"
+ />
+ <Line
+ type="monotone"
+ dataKey="stochD"
+ stroke={CHART_COLORS.stochasticD}
+ strokeWidth={2}
+ dot={false}
+ name="%D"
+ />
+ </>
+ )}
+
+ {activeIndicators.has('cci') && (
+ <Line
+ type="monotone"
+ dataKey="cci"
+ stroke={CHART_COLORS.cci}
+ strokeWidth={2}
+ dot={false}
+ name="CCI"
+ />
+ )}
+
+ {activeIndicators.has('roc') && (
+ <Line
+ type="monotone"
+ dataKey="roc"
+ stroke={CHART_COLORS.roc}
+ strokeWidth={2}
+ dot={false}
+ name="ROC"
+ />
+ )}
+
+ {activeIndicators.has('williams_r') && (
+ <Line
+ type="monotone"
+ dataKey="williamsR"
+ stroke={CHART_COLORS.williamsR}
+ strokeWidth={2}
+ dot={false}
+ name="Williams %R"
+ />
+ )}
+
+ {activeIndicators.has('awesome_oscillator') && (
+ <Bar
+ dataKey="ao"
+ fill={CHART_COLORS.ao}
+ opacity={0.7}
+ name="AO"
+ />
+ )}
+
+ {activeIndicators.has('tsi') && (
+ <>
+ <Line
+ type="monotone"
+ dataKey="tsi"
+ stroke={CHART_COLORS.tsi}
+ strokeWidth={2}
+ dot={false}
+ name="TSI"
+ />
+ <Line
+ type="monotone"
+ dataKey="tsiSignal"
+ stroke={CHART_COLORS.tsiSignal}
+ strokeWidth={2}
+ dot={false}
+ name="TSI Signal"
+ />
+ </>
+ )}
+
+ {activeIndicators.has('ultimate_oscillator') && (
+ <Line
+ type="monotone"
+ dataKey="uo"
+ stroke={CHART_COLORS.uo}
+ strokeWidth={2}
+ dot={false}
+ name="UO"
+ />
+ )}
+ </ComposedChart>
+ </ResponsiveContainer>
+ )}
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/services/momentumIndicators.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/services/momentumIndicators.ts
new file mode 100644
index 000000000..dc7bac696
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/services/momentumIndicators.ts
@@ -0,0 +1,552 @@
+// Service for calculating and parsing momentum indicators
+
+import { invoke } from '@tauri-apps/api/core';
+import {
+ MomentumIndicatorParams,
+ MomentumIndicatorResult,
+ IndicatorData,
+ CandleData,
+} from '../types';
+import * as SignalAnalyzer from '../utils/signalAnalyzer';
+
+/**
+ * Fetches historical price data for a symbol
+ */
+export async function fetchHistoricalData(
+ symbol: string,
+ period: string = '1y',
+ interval: string = '1d'
+): Promise<CandleData[]> {
+ try {
+ const result = await invoke<string>('run_python_script', {
+ scriptName: 'Analytics/equityInvestment/get_historical_data.py',
+ args: [symbol, period, interval],
+ });
+
+ const data = JSON.parse(result);
+
+ if (!data || !Array.isArray(data)) {
+ throw new Error('Invalid historical data format');
+ }
+
+ return data.map((item: any) => ({
+ time: new Date(item.Date || item.timestamp).getTime() / 1000, // Convert to Unix timestamp in seconds
+ open: parseFloat(item.Open),
+ high: parseFloat(item.High),
+ low: parseFloat(item.Low),
+ close: parseFloat(item.Close),
+ volume: parseInt(item.Volume),
+ }));
+ } catch (error) {
+ console.error('Error fetching historical data:', error);
+ throw error;
+ }
+}
+
+/**
+ * Calculates RSI (Relative Strength Index)
+ */
+export async function calculateRSI(
+ symbol: string,
+ params: MomentumIndicatorParams['rsi'],
+ period: string = '1y',
+ interval: string = '1d'
+): Promise<MomentumIndicatorResult['rsi']> {
+ try {
+ const result = await invoke<string>('run_python_script', {
+ scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
+ args: [
+ symbol,
+ 'rsi',
+ JSON.stringify({
+ period: params?.period || 14,
+ timeframe: period,
+ interval: interval,
+ }),
+ ],
+ });
+
+ const data = JSON.parse(result);
+
+ const values: IndicatorData[] = data.values.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const currentValue = values[values.length - 1]?.value || 0;
+ const signal = SignalAnalyzer.analyzeRSI(values, params!);
+
+ return {
+ values,
+ signal: signal.signal,
+ current_value: currentValue,
+ params: params!,
+ };
+ } catch (error) {
+ console.error('Error calculating RSI:', error);
+ throw error;
+ }
+}
+
+/**
+ * Calculates MACD (Moving Average Convergence Divergence)
+ */
+export async function calculateMACD(
+ symbol: string,
+ params: MomentumIndicatorParams['macd'],
+ period: string = '1y',
+ interval: string = '1d'
+): Promise<MomentumIndicatorResult['macd']> {
+ try {
+ const result = await invoke<string>('run_python_script', {
+ scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
+ args: [
+ symbol,
+ 'macd',
+ JSON.stringify({
+ fast_period: params?.fast_period || 12,
+ slow_period: params?.slow_period || 26,
+ signal_period: params?.signal_period || 9,
+ timeframe: period,
+ interval: interval,
+ }),
+ ],
+ });
+
+ const data = JSON.parse(result);
+
+ const macdLine: IndicatorData[] = data.macd_line.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const signalLine: IndicatorData[] = data.signal_line.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const histogram: IndicatorData[] = data.histogram.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const currentMACD = macdLine[macdLine.length - 1]?.value || 0;
+ const currentSignal = signalLine[signalLine.length - 1]?.value || 0;
+ const currentHistogram = histogram[histogram.length - 1]?.value || 0;
+
+ const signal = SignalAnalyzer.analyzeMACD(macdLine, signalLine, histogram);
+
+ return {
+ macd_line: macdLine,
+ signal_line: signalLine,
+ histogram,
+ signal: signal.signal,
+ current_macd: currentMACD,
+ current_signal: currentSignal,
+ current_histogram: currentHistogram,
+ params: params!,
+ };
+ } catch (error) {
+ console.error('Error calculating MACD:', error);
+ throw error;
+ }
+}
+
+/**
+ * Calculates Stochastic Oscillator
+ */
+export async function calculateStochastic(
+ symbol: string,
+ params: MomentumIndicatorParams['stochastic'],
+ period: string = '1y',
+ interval: string = '1d'
+): Promise<MomentumIndicatorResult['stochastic']> {
+ try {
+ const result = await invoke<string>('run_python_script', {
+ scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
+ args: [
+ symbol,
+ 'stochastic',
+ JSON.stringify({
+ k_period: params?.k_period || 14,
+ d_period: params?.d_period || 3,
+ timeframe: period,
+ interval: interval,
+ }),
+ ],
+ });
+
+ const data = JSON.parse(result);
+
+ const kValues: IndicatorData[] = data.k_values.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const dValues: IndicatorData[] = data.d_values.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const currentK = kValues[kValues.length - 1]?.value || 0;
+ const currentD = dValues[dValues.length - 1]?.value || 0;
+
+ const signal = SignalAnalyzer.analyzeStochastic(kValues, dValues, params!);
+
+ return {
+ k_values: kValues,
+ d_values: dValues,
+ signal: signal.signal,
+ current_k: currentK,
+ current_d: currentD,
+ params: params!,
+ };
+ } catch (error) {
+ console.error('Error calculating Stochastic:', error);
+ throw error;
+ }
+}
+
+/**
+ * Calculates CCI (Commodity Channel Index)
+ */
+export async function calculateCCI(
+ symbol: string,
+ params: MomentumIndicatorParams['cci'],
+ period: string = '1y',
+ interval: string = '1d'
+): Promise<MomentumIndicatorResult['cci']> {
+ try {
+ const result = await invoke<string>('run_python_script', {
+ scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
+ args: [
+ symbol,
+ 'cci',
+ JSON.stringify({
+ period: params?.period || 20,
+ timeframe: period,
+ interval: interval,
+ }),
+ ],
+ });
+
+ const data = JSON.parse(result);
+
+ const values: IndicatorData[] = data.values.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const currentValue = values[values.length - 1]?.value || 0;
+ const signal = SignalAnalyzer.analyzeCCI(values, params!);
+
+ return {
+ values,
+ signal: signal.signal,
+ current_value: currentValue,
+ params: params!,
+ };
+ } catch (error) {
+ console.error('Error calculating CCI:', error);
+ throw error;
+ }
+}
+
+/**
+ * Calculates ROC (Rate of Change)
+ */
+export async function calculateROC(
+ symbol: string,
+ params: MomentumIndicatorParams['roc'],
+ period: string = '1y',
+ interval: string = '1d'
+): Promise<MomentumIndicatorResult['roc']> {
+ try {
+ const result = await invoke<string>('run_python_script', {
+ scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
+ args: [
+ symbol,
+ 'roc',
+ JSON.stringify({
+ period: params?.period || 12,
+ timeframe: period,
+ interval: interval,
+ }),
+ ],
+ });
+
+ const data = JSON.parse(result);
+
+ const values: IndicatorData[] = data.values.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const currentValue = values[values.length - 1]?.value || 0;
+ const signal = SignalAnalyzer.analyzeROC(values);
+
+ return {
+ values,
+ signal: signal.signal,
+ current_value: currentValue,
+ params: params!,
+ };
+ } catch (error) {
+ console.error('Error calculating ROC:', error);
+ throw error;
+ }
+}
+
+/**
+ * Calculates Williams %R
+ */
+export async function calculateWilliamsR(
+ symbol: string,
+ params: MomentumIndicatorParams['williams_r'],
+ period: string = '1y',
+ interval: string = '1d'
+): Promise<MomentumIndicatorResult['williams_r']> {
+ try {
+ const result = await invoke<string>('run_python_script', {
+ scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
+ args: [
+ symbol,
+ 'williams_r',
+ JSON.stringify({
+ period: params?.period || 14,
+ timeframe: period,
+ interval: interval,
+ }),
+ ],
+ });
+
+ const data = JSON.parse(result);
+
+ const values: IndicatorData[] = data.values.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const currentValue = values[values.length - 1]?.value || 0;
+ const signal = SignalAnalyzer.analyzeWilliamsR(values, params!);
+
+ return {
+ values,
+ signal: signal.signal,
+ current_value: currentValue,
+ params: params!,
+ };
+ } catch (error) {
+ console.error('Error calculating Williams %R:', error);
+ throw error;
+ }
+}
+
+/**
+ * Calculates Awesome Oscillator
+ */
+export async function calculateAwesomeOscillator(
+ symbol: string,
+ params: MomentumIndicatorParams['awesome_oscillator'],
+ period: string = '1y',
+ interval: string = '1d'
+): Promise<MomentumIndicatorResult['awesome_oscillator']> {
+ try {
+ const result = await invoke<string>('run_python_script', {
+ scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
+ args: [
+ symbol,
+ 'awesome_oscillator',
+ JSON.stringify({
+ fast_period: params?.fast_period || 5,
+ slow_period: params?.slow_period || 34,
+ timeframe: period,
+ interval: interval,
+ }),
+ ],
+ });
+
+ const data = JSON.parse(result);
+
+ const values: IndicatorData[] = data.values.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const currentValue = values[values.length - 1]?.value || 0;
+ const signal = SignalAnalyzer.analyzeAwesomeOscillator(values);
+
+ return {
+ values,
+ signal: signal.signal,
+ current_value: currentValue,
+ params: params!,
+ };
+ } catch (error) {
+ console.error('Error calculating Awesome Oscillator:', error);
+ throw error;
+ }
+}
+
+/**
+ * Calculates TSI (True Strength Index)
+ */
+export async function calculateTSI(
+ symbol: string,
+ params: MomentumIndicatorParams['tsi'],
+ period: string = '1y',
+ interval: string = '1d'
+): Promise<MomentumIndicatorResult['tsi']> {
+ try {
+ const result = await invoke<string>('run_python_script', {
+ scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
+ args: [
+ symbol,
+ 'tsi',
+ JSON.stringify({
+ long_period: params?.long_period || 25,
+ short_period: params?.short_period || 13,
+ signal_period: params?.signal_period || 13,
+ timeframe: period,
+ interval: interval,
+ }),
+ ],
+ });
+
+ const data = JSON.parse(result);
+
+ const values: IndicatorData[] = data.values.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const signalLine: IndicatorData[] = data.signal_line.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const currentValue = values[values.length - 1]?.value || 0;
+ const currentSignal = signalLine[signalLine.length - 1]?.value || 0;
+
+ const signal = SignalAnalyzer.analyzeTSI(values, signalLine);
+
+ return {
+ values,
+ signal_line: signalLine,
+ signal: signal.signal,
+ current_value: currentValue,
+ current_signal: currentSignal,
+ params: params!,
+ };
+ } catch (error) {
+ console.error('Error calculating TSI:', error);
+ throw error;
+ }
+}
+
+/**
+ * Calculates Ultimate Oscillator
+ */
+export async function calculateUltimateOscillator(
+ symbol: string,
+ params: MomentumIndicatorParams['ultimate_oscillator'],
+ period: string = '1y',
+ interval: string = '1d'
+): Promise<MomentumIndicatorResult['ultimate_oscillator']> {
+ try {
+ const result = await invoke<string>('run_python_script', {
+ scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
+ args: [
+ symbol,
+ 'ultimate_oscillator',
+ JSON.stringify({
+ period1: params?.period1 || 7,
+ period2: params?.period2 || 14,
+ period3: params?.period3 || 28,
+ weight1: params?.weight1 || 4,
+ weight2: params?.weight2 || 2,
+ weight3: params?.weight3 || 1,
+ timeframe: period,
+ interval: interval,
+ }),
+ ],
+ });
+
+ const data = JSON.parse(result);
+
+ const values: IndicatorData[] = data.values.map((item: any) => ({
+ time: new Date(item.time).getTime() / 1000,
+ value: item.value !== null ? parseFloat(item.value) : null,
+ }));
+
+ const currentValue = values[values.length - 1]?.value || 0;
+ const signal = SignalAnalyzer.analyzeUltimateOscillator(values);
+
+ return {
+ values,
+ signal: signal.signal,
+ current_value: currentValue,
+ params: params!,
+ };
+ } catch (error) {
+ console.error('Error calculating Ultimate Oscillator:', error);
+ throw error;
+ }
+}
+
+/**
+ * Calculates all momentum indicators
+ */
+export async function calculateAllMomentumIndicators(
+ symbol: string,
+ params: MomentumIndicatorParams,
+ period: string = '1y',
+ interval: string = '1d'
+): Promise<MomentumIndicatorResult> {
+ const results: MomentumIndicatorResult = {};
+
+ try {
+ if (params.rsi) {
+ results.rsi = await calculateRSI(symbol, params.rsi, period, interval);
+ }
+ if (params.macd) {
+ results.macd = await calculateMACD(symbol, params.macd, period, interval);
+ }
+ if (params.stochastic) {
+ results.stochastic = await calculateStochastic(symbol, params.stochastic, period, interval);
+ }
+ if (params.cci) {
+ results.cci = await calculateCCI(symbol, params.cci, period, interval);
+ }
+ if (params.roc) {
+ results.roc = await calculateROC(symbol, params.roc, period, interval);
+ }
+ if (params.williams_r) {
+ results.williams_r = await calculateWilliamsR(symbol, params.williams_r, period, interval);
+ }
+ if (params.awesome_oscillator) {
+ results.awesome_oscillator = await calculateAwesomeOscillator(
+ symbol,
+ params.awesome_oscillator,
+ period,
+ interval
+ );
+ }
+ if (params.tsi) {
+ results.tsi = await calculateTSI(symbol, params.tsi, period, interval);
+ }
+ if (params.ultimate_oscillator) {
+ results.ultimate_oscillator = await calculateUltimateOscillator(
+ symbol,
+ params.ultimate_oscillator,
+ period,
+ interval
+ );
+ }
+
+ return results;
+ } catch (error) {
+ console.error('Error calculating momentum indicators:', error);
+ throw error;
+ }
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/types/index.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/types/index.ts
new file mode 100644
index 000000000..6a27dc967
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/types/index.ts
@@ -0,0 +1,208 @@
+// Type definitions for Equity Research module
+
+export interface CandleData {
+ time: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+}
+
+export interface IndicatorData {
+ time: number;
+ value: number | null;
+}
+
+export interface MomentumIndicatorParams {
+ rsi?: {
+ period: number;
+ overbought: number;
+ oversold: number;
+ };
+ macd?: {
+ fast_period: number;
+ slow_period: number;
+ signal_period: number;
+ };
+ stochastic?: {
+ k_period: number;
+ d_period: number;
+ overbought: number;
+ oversold: number;
+ };
+ cci?: {
+ period: number;
+ overbought: number;
+ oversold: number;
+ };
+ roc?: {
+ period: number;
+ };
+ williams_r?: {
+ period: number;
+ overbought: number;
+ oversold: number;
+ };
+ awesome_oscillator?: {
+ fast_period: number;
+ slow_period: number;
+ };
+ tsi?: {
+ long_period: number;
+ short_period: number;
+ signal_period: number;
+ };
+ ultimate_oscillator?: {
+ period1: number;
+ period2: number;
+ period3: number;
+ weight1: number;
+ weight2: number;
+ weight3: number;
+ };
+}
+
+export interface MomentumIndicatorResult {
+ rsi?: {
+ values: IndicatorData[];
+ signal: 'BUY' | 'SELL' | 'NEUTRAL';
+ current_value: number;
+ params: MomentumIndicatorParams['rsi'];
+ };
+ macd?: {
+ macd_line: IndicatorData[];
+ signal_line: IndicatorData[];
+ histogram: IndicatorData[];
+ signal: 'BUY' | 'SELL' | 'NEUTRAL';
+ current_macd: number;
+ current_signal: number;
+ current_histogram: number;
+ params: MomentumIndicatorParams['macd'];
+ };
+ stochastic?: {
+ k_values: IndicatorData[];
+ d_values: IndicatorData[];
+ signal: 'BUY' | 'SELL' | 'NEUTRAL';
+ current_k: number;
+ current_d: number;
+ params: MomentumIndicatorParams['stochastic'];
+ };
+ cci?: {
+ values: IndicatorData[];
+ signal: 'BUY' | 'SELL' | 'NEUTRAL';
+ current_value: number;
+ params: MomentumIndicatorParams['cci'];
+ };
+ roc?: {
+ values: IndicatorData[];
+ signal: 'BUY' | 'SELL' | 'NEUTRAL';
+ current_value: number;
+ params: MomentumIndicatorParams['roc'];
+ };
+ williams_r?: {
+ values: IndicatorData[];
+ signal: 'BUY' | 'SELL' | 'NEUTRAL';
+ current_value: number;
+ params: MomentumIndicatorParams['williams_r'];
+ };
+ awesome_oscillator?: {
+ values: IndicatorData[];
+ signal: 'BUY' | 'SELL' | 'NEUTRAL';
+ current_value: number;
+ params: MomentumIndicatorParams['awesome_oscillator'];
+ };
+ tsi?: {
+ values: IndicatorData[];
+ signal_line: IndicatorData[];
+ signal: 'BUY' | 'SELL' | 'NEUTRAL';
+ current_value: number;
+ current_signal: number;
+ params: MomentumIndicatorParams['tsi'];
+ };
+ ultimate_oscillator?: {
+ values: IndicatorData[];
+ signal: 'BUY' | 'SELL' | 'NEUTRAL';
+ current_value: number;
+ params: MomentumIndicatorParams['ultimate_oscillator'];
+ };
+}
+
+export type TimeFrame = '1d' | '5d' | '1mo' | '3mo' | '6mo' | '1y' | '2y' | '5y' | 'max';
+
+export interface TimeFrameConfig {
+ value: TimeFrame;
+ label: string;
+ interval: '1m' | '5m' | '15m' | '30m' | '1h' | '1d' | '1wk' | '1mo';
+}
+
+export const TIME_FRAMES: TimeFrameConfig[] = [
+ { value: '1d', label: '1 Day', interval: '5m' },
+ { value: '5d', label: '5 Days', interval: '15m' },
+ { value: '1mo', label: '1 Month', interval: '1h' },
+ { value: '3mo', label: '3 Months', interval: '1d' },
+ { value: '6mo', label: '6 Months', interval: '1d' },
+ { value: '1y', label: '1 Year', interval: '1d' },
+ { value: '2y', label: '2 Years', interval: '1wk' },
+ { value: '5y', label: '5 Years', interval: '1wk' },
+ { value: 'max', label: 'Max', interval: '1mo' },
+];
+
+export const DEFAULT_MOMENTUM_PARAMS: MomentumIndicatorParams = {
+ rsi: {
+ period: 14,
+ overbought: 70,
+ oversold: 30,
+ },
+ macd: {
+ fast_period: 12,
+ slow_period: 26,
+ signal_period: 9,
+ },
+ stochastic: {
+ k_period: 14,
+ d_period: 3,
+ overbought: 80,
+ oversold: 20,
+ },
+ cci: {
+ period: 20,
+ overbought: 100,
+ oversold: -100,
+ },
+ roc: {
+ period: 12,
+ },
+ williams_r: {
+ period: 14,
+ overbought: -20,
+ oversold: -80,
+ },
+ awesome_oscillator: {
+ fast_period: 5,
+ slow_period: 34,
+ },
+ tsi: {
+ long_period: 25,
+ short_period: 13,
+ signal_period: 13,
+ },
+ ultimate_oscillator: {
+ period1: 7,
+ period2: 14,
+ period3: 28,
+ weight1: 4,
+ weight2: 2,
+ weight3: 1,
+ },
+};
+
+export type IndicatorType = keyof MomentumIndicatorParams;
+
+export interface IndicatorDisplayConfig {
+ type: IndicatorType;
+ name: string;
+ description: string;
+ enabled: boolean;
+ color: string;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/utils/signalAnalyzer.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/utils/signalAnalyzer.ts
new file mode 100644
index 000000000..4cc74bd8f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/utils/signalAnalyzer.ts
@@ -0,0 +1,570 @@
+// Signal analysis utilities for technical indicators
+
+import { MomentumIndicatorParams, IndicatorData } from '../types';
+
+export type Signal = 'BUY' | 'SELL' | 'NEUTRAL';
+
+export interface SignalResult {
+ signal: Signal;
+ strength: number; // 0-100
+ reason: string;
+}
+
+/**
+ * Analyzes RSI indicator for buy/sell signals
+ */
+export function analyzeRSI(
+ values: IndicatorData[],
+ params: MomentumIndicatorParams['rsi']
+): SignalResult {
+ if (!params || values.length === 0) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'Insufficient data' };
+ }
+
+ const currentValue = values[values.length - 1]?.value;
+ if (currentValue === null || currentValue === undefined) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'No current value' };
+ }
+
+ if (currentValue <= params.oversold) {
+ const strength = Math.min(100, ((params.oversold - currentValue) / params.oversold) * 100);
+ return {
+ signal: 'BUY',
+ strength,
+ reason: `RSI ${currentValue.toFixed(2)} is in oversold territory (<${params.oversold})`,
+ };
+ }
+
+ if (currentValue >= params.overbought) {
+ const strength = Math.min(100, ((currentValue - params.overbought) / (100 - params.overbought)) * 100);
+ return {
+ signal: 'SELL',
+ strength,
+ reason: `RSI ${currentValue.toFixed(2)} is in overbought territory (>${params.overbought})`,
+ };
+ }
+
+ return {
+ signal: 'NEUTRAL',
+ strength: 50,
+ reason: `RSI ${currentValue.toFixed(2)} is neutral (${params.oversold}-${params.overbought})`,
+ };
+}
+
+/**
+ * Analyzes MACD indicator for buy/sell signals
+ */
+export function analyzeMACD(
+ macdLine: IndicatorData[],
+ signalLine: IndicatorData[],
+ histogram: IndicatorData[]
+): SignalResult {
+ if (macdLine.length < 2 || signalLine.length < 2 || histogram.length < 2) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'Insufficient data' };
+ }
+
+ const currentHistogram = histogram[histogram.length - 1]?.value;
+ const previousHistogram = histogram[histogram.length - 2]?.value;
+ const currentMACD = macdLine[macdLine.length - 1]?.value;
+ const currentSignal = signalLine[signalLine.length - 1]?.value;
+
+ if (
+ currentHistogram === null ||
+ previousHistogram === null ||
+ currentMACD === null ||
+ currentSignal === null
+ ) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'No current values' };
+ }
+
+ // Bullish crossover
+ if (previousHistogram <= 0 && currentHistogram > 0) {
+ return {
+ signal: 'BUY',
+ strength: 80,
+ reason: 'MACD bullish crossover - MACD line crossed above signal line',
+ };
+ }
+
+ // Bearish crossover
+ if (previousHistogram >= 0 && currentHistogram < 0) {
+ return {
+ signal: 'SELL',
+ strength: 80,
+ reason: 'MACD bearish crossover - MACD line crossed below signal line',
+ };
+ }
+
+ // Strong bullish momentum
+ if (currentHistogram > 0 && currentHistogram > previousHistogram) {
+ const strength = Math.min(100, Math.abs(currentHistogram) * 50);
+ return {
+ signal: 'BUY',
+ strength,
+ reason: 'MACD shows increasing bullish momentum',
+ };
+ }
+
+ // Strong bearish momentum
+ if (currentHistogram < 0 && currentHistogram < previousHistogram) {
+ const strength = Math.min(100, Math.abs(currentHistogram) * 50);
+ return {
+ signal: 'SELL',
+ strength,
+ reason: 'MACD shows increasing bearish momentum',
+ };
+ }
+
+ return {
+ signal: 'NEUTRAL',
+ strength: 50,
+ reason: 'MACD shows neutral momentum',
+ };
+}
+
+/**
+ * Analyzes Stochastic Oscillator for buy/sell signals
+ */
+export function analyzeStochastic(
+ kValues: IndicatorData[],
+ dValues: IndicatorData[],
+ params: MomentumIndicatorParams['stochastic']
+): SignalResult {
+ if (!params || kValues.length < 2 || dValues.length < 2) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'Insufficient data' };
+ }
+
+ const currentK = kValues[kValues.length - 1]?.value;
+ const currentD = dValues[dValues.length - 1]?.value;
+ const previousK = kValues[kValues.length - 2]?.value;
+ const previousD = dValues[dValues.length - 2]?.value;
+
+ if (currentK === null || currentD === null || previousK === null || previousD === null) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'No current values' };
+ }
+
+ // Oversold with bullish crossover
+ if (currentK < params.oversold && previousK < previousD && currentK > currentD) {
+ return {
+ signal: 'BUY',
+ strength: 90,
+ reason: `Stochastic oversold bullish crossover (K=${currentK.toFixed(2)})`,
+ };
+ }
+
+ // Overbought with bearish crossover
+ if (currentK > params.overbought && previousK > previousD && currentK < currentD) {
+ return {
+ signal: 'SELL',
+ strength: 90,
+ reason: `Stochastic overbought bearish crossover (K=${currentK.toFixed(2)})`,
+ };
+ }
+
+ // Oversold condition
+ if (currentK < params.oversold) {
+ return {
+ signal: 'BUY',
+ strength: 70,
+ reason: `Stochastic in oversold territory (K=${currentK.toFixed(2)})`,
+ };
+ }
+
+ // Overbought condition
+ if (currentK > params.overbought) {
+ return {
+ signal: 'SELL',
+ strength: 70,
+ reason: `Stochastic in overbought territory (K=${currentK.toFixed(2)})`,
+ };
+ }
+
+ return {
+ signal: 'NEUTRAL',
+ strength: 50,
+ reason: `Stochastic neutral (K=${currentK.toFixed(2)}, D=${currentD.toFixed(2)})`,
+ };
+}
+
+/**
+ * Analyzes CCI (Commodity Channel Index) for buy/sell signals
+ */
+export function analyzeCCI(
+ values: IndicatorData[],
+ params: MomentumIndicatorParams['cci']
+): SignalResult {
+ if (!params || values.length === 0) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'Insufficient data' };
+ }
+
+ const currentValue = values[values.length - 1]?.value;
+ if (currentValue === null || currentValue === undefined) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'No current value' };
+ }
+
+ if (currentValue <= params.oversold) {
+ const strength = Math.min(100, (Math.abs(currentValue - params.oversold) / 100) * 100);
+ return {
+ signal: 'BUY',
+ strength,
+ reason: `CCI ${currentValue.toFixed(2)} indicates oversold condition`,
+ };
+ }
+
+ if (currentValue >= params.overbought) {
+ const strength = Math.min(100, (Math.abs(currentValue - params.overbought) / 100) * 100);
+ return {
+ signal: 'SELL',
+ strength,
+ reason: `CCI ${currentValue.toFixed(2)} indicates overbought condition`,
+ };
+ }
+
+ return {
+ signal: 'NEUTRAL',
+ strength: 50,
+ reason: `CCI ${currentValue.toFixed(2)} is neutral`,
+ };
+}
+
+/**
+ * Analyzes Rate of Change (ROC) for buy/sell signals
+ */
+export function analyzeROC(values: IndicatorData[]): SignalResult {
+ if (values.length < 2) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'Insufficient data' };
+ }
+
+ const currentValue = values[values.length - 1]?.value;
+ const previousValue = values[values.length - 2]?.value;
+
+ if (currentValue === null || previousValue === null) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'No current values' };
+ }
+
+ // Strong positive momentum
+ if (currentValue > 5 && currentValue > previousValue) {
+ const strength = Math.min(100, Math.abs(currentValue) * 5);
+ return {
+ signal: 'BUY',
+ strength,
+ reason: `Strong positive ROC ${currentValue.toFixed(2)}%`,
+ };
+ }
+
+ // Strong negative momentum
+ if (currentValue < -5 && currentValue < previousValue) {
+ const strength = Math.min(100, Math.abs(currentValue) * 5);
+ return {
+ signal: 'SELL',
+ strength,
+ reason: `Strong negative ROC ${currentValue.toFixed(2)}%`,
+ };
+ }
+
+ // Reversal from negative to positive
+ if (previousValue < 0 && currentValue > 0) {
+ return {
+ signal: 'BUY',
+ strength: 75,
+ reason: 'ROC turning positive - momentum reversal',
+ };
+ }
+
+ // Reversal from positive to negative
+ if (previousValue > 0 && currentValue < 0) {
+ return {
+ signal: 'SELL',
+ strength: 75,
+ reason: 'ROC turning negative - momentum reversal',
+ };
+ }
+
+ return {
+ signal: 'NEUTRAL',
+ strength: 50,
+ reason: `ROC ${currentValue.toFixed(2)}% shows neutral momentum`,
+ };
+}
+
+/**
+ * Analyzes Williams %R for buy/sell signals
+ */
+export function analyzeWilliamsR(
+ values: IndicatorData[],
+ params: MomentumIndicatorParams['williams_r']
+): SignalResult {
+ if (!params || values.length === 0) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'Insufficient data' };
+ }
+
+ const currentValue = values[values.length - 1]?.value;
+ if (currentValue === null || currentValue === undefined) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'No current value' };
+ }
+
+ if (currentValue <= params.oversold) {
+ const strength = Math.min(100, ((params.oversold - currentValue) / 20) * 100);
+ return {
+ signal: 'BUY',
+ strength,
+ reason: `Williams %R ${currentValue.toFixed(2)} is oversold`,
+ };
+ }
+
+ if (currentValue >= params.overbought) {
+ const strength = Math.min(100, ((currentValue - params.overbought) / 20) * 100);
+ return {
+ signal: 'SELL',
+ strength,
+ reason: `Williams %R ${currentValue.toFixed(2)} is overbought`,
+ };
+ }
+
+ return {
+ signal: 'NEUTRAL',
+ strength: 50,
+ reason: `Williams %R ${currentValue.toFixed(2)} is neutral`,
+ };
+}
+
+/**
+ * Analyzes Awesome Oscillator for buy/sell signals
+ */
+export function analyzeAwesomeOscillator(values: IndicatorData[]): SignalResult {
+ if (values.length < 3) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'Insufficient data' };
+ }
+
+ const current = values[values.length - 1]?.value;
+ const previous = values[values.length - 2]?.value;
+ const twoBarsAgo = values[values.length - 3]?.value;
+
+ if (current === null || previous === null || twoBarsAgo === null) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'No current values' };
+ }
+
+ // Twin Peaks (bullish)
+ if (previous < 0 && current > previous && previous < twoBarsAgo) {
+ return {
+ signal: 'BUY',
+ strength: 85,
+ reason: 'AO bullish twin peaks pattern',
+ };
+ }
+
+ // Twin Peaks (bearish)
+ if (previous > 0 && current < previous && previous > twoBarsAgo) {
+ return {
+ signal: 'SELL',
+ strength: 85,
+ reason: 'AO bearish twin peaks pattern',
+ };
+ }
+
+ // Zero line cross (bullish)
+ if (previous <= 0 && current > 0) {
+ return {
+ signal: 'BUY',
+ strength: 80,
+ reason: 'AO crossed above zero line',
+ };
+ }
+
+ // Zero line cross (bearish)
+ if (previous >= 0 && current < 0) {
+ return {
+ signal: 'SELL',
+ strength: 80,
+ reason: 'AO crossed below zero line',
+ };
+ }
+
+ // Momentum strength
+ if (current > 0 && current > previous) {
+ const strength = Math.min(100, Math.abs(current) * 50);
+ return {
+ signal: 'BUY',
+ strength,
+ reason: `AO shows bullish momentum (${current.toFixed(4)})`,
+ };
+ }
+
+ if (current < 0 && current < previous) {
+ const strength = Math.min(100, Math.abs(current) * 50);
+ return {
+ signal: 'SELL',
+ strength,
+ reason: `AO shows bearish momentum (${current.toFixed(4)})`,
+ };
+ }
+
+ return {
+ signal: 'NEUTRAL',
+ strength: 50,
+ reason: `AO neutral at ${current.toFixed(4)}`,
+ };
+}
+
+/**
+ * Analyzes TSI (True Strength Index) for buy/sell signals
+ */
+export function analyzeTSI(
+ values: IndicatorData[],
+ signalLine: IndicatorData[]
+): SignalResult {
+ if (values.length < 2 || signalLine.length < 2) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'Insufficient data' };
+ }
+
+ const currentTSI = values[values.length - 1]?.value;
+ const previousTSI = values[values.length - 2]?.value;
+ const currentSignal = signalLine[signalLine.length - 1]?.value;
+ const previousSignal = signalLine[signalLine.length - 2]?.value;
+
+ if (
+ currentTSI === null ||
+ previousTSI === null ||
+ currentSignal === null ||
+ previousSignal === null
+ ) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'No current values' };
+ }
+
+ // Bullish crossover
+ if (previousTSI < previousSignal && currentTSI > currentSignal) {
+ return {
+ signal: 'BUY',
+ strength: 85,
+ reason: 'TSI bullish crossover',
+ };
+ }
+
+ // Bearish crossover
+ if (previousTSI > previousSignal && currentTSI < currentSignal) {
+ return {
+ signal: 'SELL',
+ strength: 85,
+ reason: 'TSI bearish crossover',
+ };
+ }
+
+ // Overbought (>25)
+ if (currentTSI > 25) {
+ return {
+ signal: 'SELL',
+ strength: 70,
+ reason: `TSI overbought at ${currentTSI.toFixed(2)}`,
+ };
+ }
+
+ // Oversold (<-25)
+ if (currentTSI < -25) {
+ return {
+ signal: 'BUY',
+ strength: 70,
+ reason: `TSI oversold at ${currentTSI.toFixed(2)}`,
+ };
+ }
+
+ return {
+ signal: 'NEUTRAL',
+ strength: 50,
+ reason: `TSI neutral at ${currentTSI.toFixed(2)}`,
+ };
+}
+
+/**
+ * Analyzes Ultimate Oscillator for buy/sell signals
+ */
+export function analyzeUltimateOscillator(values: IndicatorData[]): SignalResult {
+ if (values.length < 2) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'Insufficient data' };
+ }
+
+ const currentValue = values[values.length - 1]?.value;
+ const previousValue = values[values.length - 2]?.value;
+
+ if (currentValue === null || previousValue === null) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'No current values' };
+ }
+
+ // Oversold with bullish divergence
+ if (currentValue < 30 && currentValue > previousValue) {
+ return {
+ signal: 'BUY',
+ strength: 85,
+ reason: `Ultimate Oscillator oversold reversal (${currentValue.toFixed(2)})`,
+ };
+ }
+
+ // Overbought with bearish divergence
+ if (currentValue > 70 && currentValue < previousValue) {
+ return {
+ signal: 'SELL',
+ strength: 85,
+ reason: `Ultimate Oscillator overbought reversal (${currentValue.toFixed(2)})`,
+ };
+ }
+
+ // Oversold
+ if (currentValue < 30) {
+ return {
+ signal: 'BUY',
+ strength: 70,
+ reason: `Ultimate Oscillator oversold at ${currentValue.toFixed(2)}`,
+ };
+ }
+
+ // Overbought
+ if (currentValue > 70) {
+ return {
+ signal: 'SELL',
+ strength: 70,
+ reason: `Ultimate Oscillator overbought at ${currentValue.toFixed(2)}`,
+ };
+ }
+
+ return {
+ signal: 'NEUTRAL',
+ strength: 50,
+ reason: `Ultimate Oscillator neutral at ${currentValue.toFixed(2)}`,
+ };
+}
+
+/**
+ * Aggregates signals from multiple indicators
+ */
+export function aggregateSignals(signals: SignalResult[]): SignalResult {
+ if (signals.length === 0) {
+ return { signal: 'NEUTRAL', strength: 0, reason: 'No indicators' };
+ }
+
+ const buySignals = signals.filter((s) => s.signal === 'BUY');
+ const sellSignals = signals.filter((s) => s.signal === 'SELL');
+
+ const buyStrength = buySignals.reduce((sum, s) => sum + s.strength, 0) / signals.length;
+ const sellStrength = sellSignals.reduce((sum, s) => sum + s.strength, 0) / signals.length;
+
+ if (buySignals.length > sellSignals.length && buyStrength > 60) {
+ return {
+ signal: 'BUY',
+ strength: buyStrength,
+ reason: `${buySignals.length}/${signals.length} indicators suggest BUY`,
+ };
+ }
+
+ if (sellSignals.length > buySignals.length && sellStrength > 60) {
+ return {
+ signal: 'SELL',
+ strength: sellStrength,
+ reason: `${sellSignals.length}/${signals.length} indicators suggest SELL`,
+ };
+ }
+
+ return {
+ signal: 'NEUTRAL',
+ strength: 50,
+ reason: 'Mixed signals from indicators',
+ };
+}
diff --git a/fincept-terminal-desktop/src/services/userApi.tsx b/fincept-terminal-desktop/src/services/userApi.tsx
index 29c1deed8..0aca58209 100644
--- a/fincept-terminal-desktop/src/services/userApi.tsx
+++ b/fincept-terminal-desktop/src/services/userApi.tsx
@@ -81,6 +81,10 @@ export class UserApiService {
return makeApiRequest('/user/usage', 'GET', apiKey);
}
+ static async getUserCredits(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('/user/credits', 'GET', apiKey);
+ }
+
static async deleteUserAccount(apiKey: string, confirmationData: any): Promise<ApiResponse> {
return makeApiRequest('/user/account', 'DELETE', apiKey, confirmationData);
}