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.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
code editor tab and maritime tab update
tilakpatel22d9e0ad69b6be
diff --git a/fincept-terminal-desktop/package-lock.json b/fincept-terminal-desktop/package-lock.jsonindex ccd1a63fc..e6954dc6c 100644--- a/fincept-terminal-desktop/package-lock.json+++ b/fincept-terminal-desktop/package-lock.json@@ -37,6 +37,7 @@"@radix-ui/react-tooltip": "^1.2.8","@tailwindcss/vite": "^4.1.13","@tauri-apps/api": "^2.8.0",+ "@tauri-apps/plugin-dialog": "^2.4.2","@tauri-apps/plugin-http": "^2.5.2","@tauri-apps/plugin-opener": "^2","@tauri-apps/plugin-sql": "^2.3.0",@@ -4055,6 +4056,15 @@"node": ">= 10"}},+ "node_modules/@tauri-apps/plugin-dialog": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-dialog/-/plugin-dialog-2.4.2.tgz",+ "integrity": "sha512-lNIn5CZuw8WZOn8zHzmFmDSzg5zfohWoa3mdULP0YFh/VogVdMVWZPcWSHlydsiJhRQYaTNSYKN7RmZKE2lCYQ==",+ "license": "MIT OR Apache-2.0",+ "dependencies": {+ "@tauri-apps/api": "^2.8.0"+ }+ },"node_modules/@tauri-apps/plugin-http": {"version": "2.5.2","resolved": "https://registry.npmjs.org/@tauri-apps/plugin-http/-/plugin-http-2.5.2.tgz",diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.jsonindex bbb32303e..f6bd427a1 100644--- a/fincept-terminal-desktop/package.json+++ b/fincept-terminal-desktop/package.json@@ -39,6 +39,7 @@"@radix-ui/react-tooltip": "^1.2.8","@tailwindcss/vite": "^4.1.13","@tauri-apps/api": "^2.8.0",+ "@tauri-apps/plugin-dialog": "^2.4.2","@tauri-apps/plugin-http": "^2.5.2","@tauri-apps/plugin-opener": "^2","@tauri-apps/plugin-sql": "^2.3.0",diff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lockindex 3e2629325..bab3df755 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.lock+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock@@ -62,6 +62,27 @@ version = "1.0.99"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b0674a1ddeecb70197781e945de4b3b8ffb61fa939a5597bcf48503737663100"+[[package]]+name = "ashpd"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6cbdf310d77fd3aaee6ea2093db7011dc2d35d2eb3481e5607f1f8d942ed99df"+dependencies = [+ "enumflags2",+ "futures-channel",+ "futures-util",+ "rand 0.9.2",+ "raw-window-handle",+ "serde",+ "serde_repr",+ "tokio",+ "url",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "zbus",+]+[[package]]name = "async-broadcast"version = "0.7.2"@@ -832,6 +853,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "89a09f22a6c6069a18470eb92d2298acf25463f14256d24778e1230d789a2aec"dependencies = ["bitflags 2.9.4",+ "block2 0.6.1",+ "libc","objc2 0.6.2",]@@ -846,6 +869,15 @@ dependencies = ["syn 2.0.106",]+[[package]]+name = "dlib"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412"+dependencies = [+ "libloading",+]+[[package]]name = "dlopen2"version = "0.8.0"@@ -884,6 +916,12 @@ version = "0.15.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"+[[package]]+name = "downcast-rs"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"+[[package]]name = "dpi"version = "0.1.2"@@ -1081,9 +1119,11 @@ dependencies = ["tauri","tauri-build","tauri-plugin-cors-fetch",+ "tauri-plugin-dialog","tauri-plugin-opener","tauri-plugin-sql","tokio",+ "uuid",][[package]]@@ -3032,7 +3072,7 @@ checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07"dependencies = ["base64 0.22.1","indexmap 2.11.4",- "quick-xml",+ "quick-xml 0.38.3","serde","time",]@@ -3178,6 +3218,15 @@ dependencies = ["psl-types",]+[[package]]+name = "quick-xml"+version = "0.37.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"+dependencies = [+ "memchr",+]+[[package]]name = "quick-xml"version = "0.38.3"@@ -3488,6 +3537,31 @@ dependencies = ["webpki-roots",]+[[package]]+name = "rfd"+version = "0.15.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef2bee61e6cffa4635c72d7d81a84294e28f0930db0ddcb0f66d10244674ebed"+dependencies = [+ "ashpd",+ "block2 0.6.1",+ "dispatch2",+ "glib-sys",+ "gobject-sys",+ "gtk-sys",+ "js-sys",+ "log",+ "objc2 0.6.2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation 0.3.1",+ "raw-window-handle",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "windows-sys 0.59.0",+]+[[package]]name = "ring"version = "0.17.14"@@ -3663,6 +3737,12 @@ dependencies = ["syn 2.0.106",]+[[package]]+name = "scoped-tls"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"+[[package]]name = "scopeguard"version = "1.2.0"@@ -4571,6 +4651,46 @@ dependencies = ["url",]+[[package]]+name = "tauri-plugin-dialog"+version = "2.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "313f8138692ddc4a2127c4c9607d616a46f5c042e77b3722450866da0aad2f19"+dependencies = [+ "log",+ "raw-window-handle",+ "rfd",+ "serde",+ "serde_json",+ "tauri",+ "tauri-plugin",+ "tauri-plugin-fs",+ "thiserror 2.0.16",+ "url",+]++[[package]]+name = "tauri-plugin-fs"+version = "2.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47df422695255ecbe7bac7012440eddaeefd026656171eac9559f5243d3230d9"+dependencies = [+ "anyhow",+ "dunce",+ "glob",+ "percent-encoding",+ "schemars 0.8.22",+ "serde",+ "serde_json",+ "serde_repr",+ "tauri",+ "tauri-plugin",+ "tauri-utils",+ "thiserror 2.0.16",+ "toml 0.9.7",+ "url",+]+[[package]]name = "tauri-plugin-opener"version = "2.5.0"@@ -4849,6 +4969,7 @@ dependencies = ["slab","socket2","tokio-macros",+ "tracing","windows-sys 0.59.0",]@@ -5427,6 +5548,66 @@ dependencies = ["web-sys",]+[[package]]+name = "wayland-backend"+version = "0.3.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "673a33c33048a5ade91a6b139580fa174e19fb0d23f396dca9fa15f2e1e49b35"+dependencies = [+ "cc",+ "downcast-rs",+ "rustix",+ "scoped-tls",+ "smallvec",+ "wayland-sys",+]++[[package]]+name = "wayland-client"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c66a47e840dc20793f2264eb4b3e4ecb4b75d91c0dd4af04b456128e0bdd449d"+dependencies = [+ "bitflags 2.9.4",+ "rustix",+ "wayland-backend",+ "wayland-scanner",+]++[[package]]+name = "wayland-protocols"+version = "0.32.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "efa790ed75fbfd71283bd2521a1cfdc022aabcc28bdcff00851f9e4ae88d9901"+dependencies = [+ "bitflags 2.9.4",+ "wayland-backend",+ "wayland-client",+ "wayland-scanner",+]++[[package]]+name = "wayland-scanner"+version = "0.31.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "54cb1e9dc49da91950bdfd8b848c49330536d9d1fb03d4bfec8cae50caa50ae3"+dependencies = [+ "proc-macro2",+ "quick-xml 0.37.5",+ "quote",+]++[[package]]+name = "wayland-sys"+version = "0.31.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34949b42822155826b41db8e5d0c1be3a2bd296c747577a43a3e6daefc296142"+dependencies = [+ "dlib",+ "log",+ "pkg-config",+]+[[package]]name = "web-sys"version = "0.3.80"@@ -6180,6 +6361,7 @@ dependencies = ["ordered-stream","serde","serde_repr",+ "tokio","tracing","uds_windows","windows-sys 0.60.2",@@ -6305,6 +6487,7 @@ dependencies = ["endi","enumflags2","serde",+ "url","winnow 0.7.13","zvariant_derive","zvariant_utils",diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.tomlindex 007f2a357..c71cdbde9 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.toml+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml@@ -25,9 +25,11 @@ tauri = { version = "2", features = ["devtools"] }tauri-plugin-opener = "2"tauri-plugin-cors-fetch = "4"tauri-plugin-sql = { version = "2", features = ["sqlite"] }+tauri-plugin-dialog = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"sha2 = "0.10"tokio = { version = "1", features = ["full"] }anyhow = "1.0"chrono = "0.4"+uuid = { version = "1.11", features = ["v4", "serde"] }diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/polygon_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/polygon_data.pyindex 80ea70524..e74f99c4c 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/polygon_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/polygon_data.py@@ -2558,10 +2558,10 @@ def get_sma('min_value': min(sma_values_list),'max_value': max(sma_values_list),'avg_value': sum(sma_values_list) / len(sma_values_list),- 'latest_value': sma_values_list[-1] if sma_values_list else None,- 'first_value': sma_values_list[0] if sma_values_list else None,- 'total_change': sma_values_list[-1] - sma_values_list[0] if len(sma_values_list) > 1 else 0,- 'percent_change': ((sma_values_list[-1] - sma_values_list[0]) / sma_values_list[0] * 100) if len(sma_values_list) > 1 and sma_values_list[0] != 0 else 0+ 'latest_value': sma_values_list[0] if sma_values_list else None,+ 'first_value': sma_values_list[-1] if sma_values_list else None,+ 'total_change': sma_values_list[0] - sma_values_list[-1] if len(sma_values_list) > 1 else 0,+ 'percent_change': ((sma_values_list[0] - sma_values_list[-1]) / sma_values_list[-1] * 100) if len(sma_values_list) > 1 and sma_values_list[-1] != 0 else 0}else:sma_stats = {'count': 0, 'message': 'No valid SMA values found'}@@ -2749,10 +2749,10 @@ def get_ema('min_value': min(ema_values_list),'max_value': max(ema_values_list),'avg_value': sum(ema_values_list) / len(ema_values_list),- 'latest_value': ema_values_list[-1] if ema_values_list else None,- 'first_value': ema_values_list[0] if ema_values_list else None,- 'total_change': ema_values_list[-1] - ema_values_list[0] if len(ema_values_list) > 1 else 0,- 'percent_change': ((ema_values_list[-1] - ema_values_list[0]) / ema_values_list[0] * 100) if len(ema_values_list) > 1 and ema_values_list[0] != 0 else 0+ 'latest_value': ema_values_list[0] if ema_values_list else None,+ 'first_value': ema_values_list[-1] if ema_values_list else None,+ 'total_change': ema_values_list[0] - ema_values_list[-1] if len(ema_values_list) > 1 else 0,+ 'percent_change': ((ema_values_list[0] - ema_values_list[-1]) / ema_values_list[-1] * 100) if len(ema_values_list) > 1 and ema_values_list[-1] != 0 else 0}else:ema_stats = {'count': 0, 'message': 'No valid EMA values found'}@@ -2988,10 +2988,10 @@ def get_macd('min_value': min(macd_values_list),'max_value': max(macd_values_list),'avg_value': sum(macd_values_list) / len(macd_values_list),- 'latest_value': macd_values_list[-1] if macd_values_list else None,- 'first_value': macd_values_list[0] if macd_values_list else None,- 'total_change': macd_values_list[-1] - macd_values_list[0] if len(macd_values_list) > 1 else 0,- 'percent_change': ((macd_values_list[-1] - macd_values_list[0]) / macd_values_list[0] * 100) if len(macd_values_list) > 1 and macd_values_list[0] != 0 else 0+ 'latest_value': macd_values_list[0] if macd_values_list else None,+ 'first_value': macd_values_list[-1] if macd_values_list else None,+ 'total_change': macd_values_list[0] - macd_values_list[-1] if len(macd_values_list) > 1 else 0,+ 'percent_change': ((macd_values_list[0] - macd_values_list[-1]) / macd_values_list[-1] * 100) if len(macd_values_list) > 1 and macd_values_list[-1] != 0 else 0}else:macd_stats = {'count': 0, 'message': 'No valid MACD values found'}@@ -3002,8 +3002,8 @@ def get_macd('min_value': min(signal_values_list),'max_value': max(signal_values_list),'avg_value': sum(signal_values_list) / len(signal_values_list),- 'latest_value': signal_values_list[-1] if signal_values_list else None,- 'first_value': signal_values_list[0] if signal_values_list else None+ 'latest_value': signal_values_list[0] if signal_values_list else None,+ 'first_value': signal_values_list[-1] if signal_values_list else None}else:signal_stats = {'message': 'No signal line data found'}@@ -3014,7 +3014,7 @@ def get_macd('min_value': min(histogram_values_list),'max_value': max(histogram_values_list),'avg_value': sum(histogram_values_list) / len(histogram_values_list),- 'latest_value': histogram_values_list[-1] if histogram_values_list else None,+ 'latest_value': histogram_values_list[0] if histogram_values_list else None,'positive_periods': sum(1 for h in histogram_values_list if h > 0),'negative_periods': sum(1 for h in histogram_values_list if h < 0),'zero_periods': sum(1 for h in histogram_values_list if abs(h) < 0.001)@@ -3261,10 +3261,10 @@ def get_rsi('min_value': min(rsi_values_list),'max_value': max(rsi_values_list),'avg_value': sum(rsi_values_list) / len(rsi_values_list),- 'latest_value': rsi_values_list[-1] if rsi_values_list else None,- 'first_value': rsi_values_list[0] if rsi_values_list else None,- 'total_change': rsi_values_list[-1] - rsi_values_list[0] if len(rsi_values_list) > 1 else 0,- 'percent_change': ((rsi_values_list[-1] - rsi_values_list[0]) / rsi_values_list[0] * 100) if len(rsi_values_list) > 1 and rsi_values_list[0] != 0 else 0+ 'latest_value': rsi_values_list[0] if rsi_values_list else None,+ 'first_value': rsi_values_list[-1] if rsi_values_list else None,+ 'total_change': rsi_values_list[0] - rsi_values_list[-1] if len(rsi_values_list) > 1 else 0,+ 'percent_change': ((rsi_values_list[0] - rsi_values_list[-1]) / rsi_values_list[-1] * 100) if len(rsi_values_list) > 1 and rsi_values_list[-1] != 0 else 0}else:rsi_stats = {'count': 0, 'message': 'No valid RSI values found'}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/jupyter.rs b/fincept-terminal-desktop/src-tauri/src/commands/jupyter.rsnew file mode 100644index 000000000..39bc4fe28--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/jupyter.rs@@ -0,0 +1,311 @@+// Jupyter notebook command module+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::path::PathBuf;+use std::process::Command;++#[cfg(target_os = "windows")]+use std::os::windows::process::CommandExt;++#[cfg(target_os = "windows")]+const CREATE_NO_WINDOW: u32 = 0x08000000;++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NotebookCell {+ pub id: String,+ pub cell_type: String, // "code" or "markdown"+ pub source: Vec<String>,+ pub outputs: Vec<CellOutput>,+ pub execution_count: Option<i32>,+ pub metadata: HashMap<String, serde_json::Value>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CellOutput {+ pub output_type: String, // "execute_result", "display_data", "stream", "error"+ pub data: Option<HashMap<String, Vec<String>>>,+ pub text: Option<Vec<String>>,+ pub name: Option<String>, // for stream outputs (stdout/stderr)+ pub ename: Option<String>, // for error outputs+ pub evalue: Option<String>,+ pub traceback: Option<Vec<String>>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NotebookMetadata {+ pub kernelspec: KernelSpec,+ pub language_info: LanguageInfo,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct KernelSpec {+ pub display_name: String,+ pub language: String,+ pub name: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct LanguageInfo {+ pub name: String,+ pub version: String,+ pub mimetype: String,+ pub file_extension: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct JupyterNotebook {+ pub cells: Vec<NotebookCell>,+ pub metadata: NotebookMetadata,+ pub nbformat: i32,+ pub nbformat_minor: i32,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ExecutionResult {+ pub success: bool,+ pub outputs: Vec<CellOutput>,+ pub execution_count: i32,+ pub error: Option<String>,+}++/// Execute Python code and return structured output+#[tauri::command]+pub async fn execute_python_code(+ app: tauri::AppHandle,+ code: String,+ execution_count: i32,+) -> Result<ExecutionResult, String> {+ // Get bundled Python path+ let python_path = crate::utils::python::get_python_path(&app)?;++ // Verify Python exists+ if !python_path.exists() {+ return Err(format!(+ "Bundled Python not found at: {}",+ python_path.display()+ ));+ }++ // Create temporary Python script+ let temp_dir = std::env::temp_dir();+ let script_path = temp_dir.join(format!("jupyter_cell_{}.py", execution_count));++ // Write code to temporary file+ std::fs::write(&script_path, &code)+ .map_err(|e| format!("Failed to write temp script: {}", e))?;++ // Execute Python code+ let mut cmd = Command::new(&python_path);+ cmd.arg(&script_path);++ // Hide console window on Windows+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ // Set PYTHONIOENCODING to UTF-8 for proper encoding+ cmd.env("PYTHONIOENCODING", "utf-8");++ // Execute and capture output+ let output = cmd+ .output()+ .map_err(|e| format!("Failed to execute Python: {}", e))?;++ // Clean up temp file+ let _ = std::fs::remove_file(&script_path);++ let mut outputs = Vec::new();++ if output.status.success() {+ let stdout = String::from_utf8_lossy(&output.stdout);+ if !stdout.is_empty() {+ outputs.push(CellOutput {+ output_type: "stream".to_string(),+ data: None,+ text: Some(stdout.lines().map(|s| s.to_string()).collect()),+ name: Some("stdout".to_string()),+ ename: None,+ evalue: None,+ traceback: None,+ });+ }++ Ok(ExecutionResult {+ success: true,+ outputs,+ execution_count,+ error: None,+ })+ } else {+ let stderr = String::from_utf8_lossy(&output.stderr);+ outputs.push(CellOutput {+ output_type: "error".to_string(),+ data: None,+ text: None,+ name: None,+ ename: Some("ExecutionError".to_string()),+ evalue: Some(stderr.lines().last().unwrap_or("Unknown error").to_string()),+ traceback: Some(stderr.lines().map(|s| s.to_string()).collect()),+ });++ Ok(ExecutionResult {+ success: false,+ outputs,+ execution_count,+ error: Some(stderr.to_string()),+ })+ }+}++/// Open and parse a .ipynb file+#[tauri::command]+pub async fn open_notebook(file_path: String) -> Result<JupyterNotebook, String> {+ let path = PathBuf::from(&file_path);++ if !path.exists() {+ return Err(format!("File not found: {}", file_path));+ }++ let content = std::fs::read_to_string(&path)+ .map_err(|e| format!("Failed to read file: {}", e))?;++ let notebook: JupyterNotebook = serde_json::from_str(&content)+ .map_err(|e| format!("Failed to parse notebook: {}", e))?;++ Ok(notebook)+}++/// Save notebook to .ipynb file+#[tauri::command]+pub async fn save_notebook(+ file_path: String,+ notebook: JupyterNotebook,+) -> Result<String, String> {+ let path = PathBuf::from(&file_path);++ let json = serde_json::to_string_pretty(¬ebook)+ .map_err(|e| format!("Failed to serialize notebook: {}", e))?;++ std::fs::write(&path, json).map_err(|e| format!("Failed to write file: {}", e))?;++ Ok(format!("Notebook saved to: {}", file_path))+}++/// Create a new empty notebook+#[tauri::command]+pub async fn create_new_notebook() -> Result<JupyterNotebook, String> {+ Ok(JupyterNotebook {+ cells: vec![NotebookCell {+ id: uuid::Uuid::new_v4().to_string(),+ cell_type: "code".to_string(),+ source: vec![],+ outputs: vec![],+ execution_count: None,+ metadata: HashMap::new(),+ }],+ metadata: NotebookMetadata {+ kernelspec: KernelSpec {+ display_name: "Python 3".to_string(),+ language: "python".to_string(),+ name: "python3".to_string(),+ },+ language_info: LanguageInfo {+ name: "python".to_string(),+ version: "3.12.0".to_string(),+ mimetype: "text/x-python".to_string(),+ file_extension: ".py".to_string(),+ },+ },+ nbformat: 4,+ nbformat_minor: 5,+ })+}++/// Get Python version from bundled interpreter+#[tauri::command]+pub async fn get_python_version(app: tauri::AppHandle) -> Result<String, String> {+ let python_path = crate::utils::python::get_python_path(&app)?;++ let mut cmd = Command::new(&python_path);+ cmd.arg("--version");++ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ let output = cmd+ .output()+ .map_err(|e| format!("Failed to get Python version: {}", e))?;++ let version = String::from_utf8_lossy(&output.stdout);+ let version_stderr = String::from_utf8_lossy(&output.stderr);++ // Python sometimes outputs version to stderr+ let result = if !version.is_empty() {+ version.trim().to_string()+ } else {+ version_stderr.trim().to_string()+ };++ Ok(result)+}++/// Install a Python package using pip+#[tauri::command]+pub async fn install_python_package(+ app: tauri::AppHandle,+ package_name: String,+) -> Result<String, String> {+ let python_path = crate::utils::python::get_python_path(&app)?;++ let mut cmd = Command::new(&python_path);+ cmd.args(&["-m", "pip", "install", &package_name]);++ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ let output = cmd+ .output()+ .map_err(|e| format!("Failed to install package: {}", e))?;++ if output.status.success() {+ Ok(format!(+ "Successfully installed {}",+ String::from_utf8_lossy(&output.stdout)+ ))+ } else {+ Err(format!(+ "Failed to install package: {}",+ String::from_utf8_lossy(&output.stderr)+ ))+ }+}++/// List installed Python packages+#[tauri::command]+pub async fn list_python_packages(app: tauri::AppHandle) -> Result<Vec<String>, String> {+ let python_path = crate::utils::python::get_python_path(&app)?;++ let mut cmd = Command::new(&python_path);+ cmd.args(&["-m", "pip", "list", "--format=freeze"]);++ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ let output = cmd+ .output()+ .map_err(|e| format!("Failed to list packages: {}", e))?;++ if output.status.success() {+ let stdout = String::from_utf8_lossy(&output.stdout);+ let packages: Vec<String> = stdout.lines().map(|s| s.to_string()).collect();+ Ok(packages)+ } else {+ Err(format!(+ "Failed to list packages: {}",+ String::from_utf8_lossy(&output.stderr)+ ))+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rsindex 3104c2453..e7d21b49b 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs@@ -50,3 +50,6 @@ pub mod openafrica;pub mod economic_calendar;pub mod databento;pub mod sentinelhub;++// Code editor and Jupyter notebook+pub mod jupyter;diff --git a/fincept-terminal-desktop/src-tauri/src/commands/polygon.rs b/fincept-terminal-desktop/src-tauri/src/commands/polygon.rsindex 3a08a58c6..6d3359db4 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/polygon.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/polygon.rs@@ -15,7 +15,13 @@ pub async fn execute_polygon_command(app: tauri::AppHandle,command: String,args: Vec<String>,+ api_key: Option<String>,) -> Result<String, String> {+ // Set API key environment variable if provided+ if let Some(key) = api_key {+ std::env::set_var("POLYGON_API_KEY", key);+ }+// Build command argumentslet mut cmd_args = vec![command];cmd_args.extend(args);diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex da0118314..072883580 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -371,6 +371,7 @@ pub fn run() {.plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_cors_fetch::init()).plugin(tauri_plugin_sql::Builder::default().build())+ .plugin(tauri_plugin_dialog::init()).manage(MCPState {processes: Mutex::new(HashMap::new()),})@@ -905,7 +906,15 @@ pub fn run() {commands::sentinelhub::execute_sentinelhub_command,commands::sentinelhub::get_sentinelhub_imagery,commands::sentinelhub::get_sentinelhub_collections,- commands::sentinelhub::search_sentinelhub_data+ commands::sentinelhub::search_sentinelhub_data,+ // Jupyter Notebook Commands+ commands::jupyter::execute_python_code,+ commands::jupyter::open_notebook,+ commands::jupyter::save_notebook,+ commands::jupyter::create_new_notebook,+ commands::jupyter::get_python_version,+ commands::jupyter::install_python_package,+ commands::jupyter::list_python_packages]).run(tauri::generate_context!()).expect("error while running tauri application");diff --git a/fincept-terminal-desktop/src-tauri/src/utils/python.rs b/fincept-terminal-desktop/src-tauri/src/utils/python.rsindex d353a99d3..d06d33447 100644--- a/fincept-terminal-desktop/src-tauri/src/utils/python.rs+++ b/fincept-terminal-desktop/src-tauri/src/utils/python.rs@@ -103,6 +103,12 @@ pub fn execute_python_command(let mut cmd = Command::new(&python_path);cmd.arg(&script_path).args(args);+ // Get Polygon API key from window storage via webview+ // For now, we'll check common environment variable+ if let Ok(api_key) = std::env::var("POLYGON_API_KEY") {+ cmd.env("POLYGON_API_KEY", api_key);+ }+// Hide console window on Windows#[cfg(target_os = "windows")]cmd.creation_flags(CREATE_NO_WINDOW);diff --git a/fincept-terminal-desktop/src/components/tabs/CodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/CodeEditorTab.tsxindex 082a197aa..44bd5860e 100644--- a/fincept-terminal-desktop/src/components/tabs/CodeEditorTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/CodeEditorTab.tsx@@ -1,5 +1,8 @@-import React, { useState, useRef } from 'react';-import { Play, Save, FileText, Plus, X, RefreshCw, Terminal as TerminalIcon, Download } from 'lucide-react';+import React, { useState, useRef, useEffect } from 'react';+import { Play, Save, FileText, Plus, X, RefreshCw, Terminal as TerminalIcon, Download, Upload, Trash2, ChevronUp, ChevronDown, Package, History, Search, Clock, Folder } from 'lucide-react';+import { invoke } from '@tauri-apps/api/core';+import { open, save } from '@tauri-apps/plugin-dialog';+import { notebookService } from '@/services/notebookService';interface EditorFile {id: string;@@ -15,6 +18,55 @@ interface ExecutionResult {timestamp: Date;}+interface NotebookCell {+ id: string;+ cellType: string;+ source: string[];+ outputs: CellOutput[];+ executionCount: number | null;+ metadata: Record<string, any>;+}++interface CellOutput {+ outputType: string;+ data?: Record<string, string[]>;+ text?: string[];+ name?: string;+ ename?: string;+ evalue?: string;+ traceback?: string[];+}++interface JupyterNotebook {+ cells: NotebookCell[];+ metadata: {+ kernelspec: {+ displayName: string;+ language: string;+ name: string;+ };+ languageInfo: {+ name: string;+ version: string;+ mimetype: string;+ fileExtension: string;+ };+ };+ nbformat: number;+ nbformatMinor: number;+}++interface NotebookHistory {+ id?: number;+ name: string;+ content: string;+ path: string | null;+ created_at: string;+ updated_at: string;+ cell_count: number;+ execution_count: number;+}+export default function CodeEditorTab() {const [editorMode, setEditorMode] = useState<'code' | 'notebook'>('code');const [files, setFiles] = useState<EditorFile[]>([@@ -43,6 +95,22 @@ plot_candlestick AAPL, "Apple Stock Chart"`,const [output, setOutput] = useState<ExecutionResult[]>([]);const [isRunning, setIsRunning] = useState(false);+ // Jupyter notebook state+ const [notebookCells, setNotebookCells] = useState<NotebookCell[]>([]);+ const [currentNotebookPath, setCurrentNotebookPath] = useState<string | null>(null);+ const [currentNotebookId, setCurrentNotebookId] = useState<number | null>(null);+ const [executionCounter, setExecutionCounter] = useState(1);+ const [pythonVersion, setPythonVersion] = useState<string>('Loading...');+ const [installedPackages, setInstalledPackages] = useState<string[]>([]);+ const [showPackageManager, setShowPackageManager] = useState(false);+ const [packageToInstall, setPackageToInstall] = useState('');++ // History sidebar state+ const [showHistory, setShowHistory] = useState(false);+ const [notebookHistory, setNotebookHistory] = useState<NotebookHistory[]>([]);+ const [historySearch, setHistorySearch] = useState('');+ const [isLoadingHistory, setIsLoadingHistory] = useState(false);+const textareaRef = useRef<HTMLTextAreaElement>(null);// Colors@@ -62,6 +130,180 @@ plot_candlestick AAPL, "Apple Stock Chart"`,const activeFile = files.find(f => f.id === activeFileId) || files[0];+ // Initialize Python version and load history on mount+ useEffect(() => {+ if (editorMode === 'notebook') {+ loadPythonVersion();+ loadHistory();+ }+ }, [editorMode]);++ const loadHistory = async () => {+ setIsLoadingHistory(true);+ try {+ const history = await notebookService.getHistory(50);+ setNotebookHistory(history);+ } catch (error) {+ console.error('Failed to load history:', error);+ } finally {+ setIsLoadingHistory(false);+ }+ };++ const searchHistory = async (query: string) => {+ if (!query.trim()) {+ loadHistory();+ return;+ }++ setIsLoadingHistory(true);+ try {+ const results = await notebookService.searchHistory(query);+ setNotebookHistory(results);+ } catch (error) {+ console.error('Failed to search history:', error);+ } finally {+ setIsLoadingHistory(false);+ }+ };++ const saveCurrentToHistory = async () => {+ try {+ const notebookContent = JSON.stringify({+ cells: notebookCells,+ metadata: {+ kernelspec: {+ displayName: 'Python 3',+ language: 'python',+ name: 'python3'+ },+ languageInfo: {+ name: 'python',+ version: '3.12.0',+ mimetype: 'text/x-python',+ fileExtension: '.py'+ }+ },+ nbformat: 4,+ nbformatMinor: 5+ });++ const historyEntry: NotebookHistory = {+ name: currentNotebookPath ? currentNotebookPath.split(/[/\\]/).pop() || 'Untitled' : 'Untitled',+ content: notebookContent,+ path: currentNotebookPath,+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ cell_count: notebookCells.length,+ execution_count: executionCounter - 1+ };++ if (currentNotebookId) {+ await notebookService.updateHistory(currentNotebookId, historyEntry);+ } else {+ const id = await notebookService.saveToHistory(historyEntry);+ setCurrentNotebookId(id);+ }++ await loadHistory();+ } catch (error) {+ console.error('Failed to save to history:', error);+ }+ };++ const loadFromHistory = async (historyId: number) => {+ try {+ const entry = await notebookService.getNotebookById(historyId);+ if (!entry) return;++ const notebook: JupyterNotebook = JSON.parse(entry.content);+ setNotebookCells(notebook.cells);+ setCurrentNotebookPath(entry.path);+ setCurrentNotebookId(historyId);++ // Find the highest execution count+ const maxCount = Math.max(+ ...notebook.cells+ .map(c => c.executionCount || 0)+ .filter(c => c > 0),+ 0+ );+ setExecutionCounter(maxCount + 1);++ setOutput([...output, {+ output: `Loaded from history: ${entry.name}`,+ timestamp: new Date()+ }]);+ } catch (error) {+ setOutput([...output, {+ output: `Failed to load from history: ${error}`,+ error: String(error),+ timestamp: new Date()+ }]);+ }+ };++ const deleteFromHistory = async (historyId: number) => {+ try {+ await notebookService.deleteFromHistory(historyId);+ await loadHistory();++ if (currentNotebookId === historyId) {+ setCurrentNotebookId(null);+ }+ } catch (error) {+ console.error('Failed to delete from history:', error);+ }+ };++ const loadPythonVersion = async () => {+ try {+ const version = await invoke<string>('get_python_version');+ setPythonVersion(version);+ } catch (error) {+ setPythonVersion('Error loading Python version');+ console.error('Failed to get Python version:', error);+ }+ };++ const loadInstalledPackages = async () => {+ try {+ const packages = await invoke<string[]>('list_python_packages');+ setInstalledPackages(packages);+ } catch (error) {+ console.error('Failed to load packages:', error);+ }+ };++ const installPackage = async () => {+ if (!packageToInstall.trim()) return;++ try {+ setOutput([...output, {+ output: `Installing package: ${packageToInstall}...`,+ timestamp: new Date()+ }]);++ const result = await invoke<string>('install_python_package', {+ packageName: packageToInstall.trim()+ });++ setOutput([...output, {+ output: result,+ timestamp: new Date()+ }]);++ setPackageToInstall('');+ loadInstalledPackages();+ } catch (error) {+ setOutput([...output, {+ output: `Failed to install package: ${error}`,+ error: String(error),+ timestamp: new Date()+ }]);+ }+ };+const updateFileContent = (content: string) => {setFiles(files.map(f =>f.id === activeFileId ? { ...f, content, unsaved: true } : f@@ -136,35 +378,54 @@ Memory Used: 2.4 MB}, 1500);};- const executePython = async () => {+ const runCode = () => {+ if (activeFile.language === 'finscript') {+ executeFinScript();+ } else if (activeFile.language === 'python') {+ executePythonCode(activeFile.content);+ }+ };++ const executePythonCode = async (code: string) => {setIsRunning(true);setOutput([...output, {output: `Executing Python code...`,timestamp: new Date()}]);- setTimeout(() => {- const mockOutput = `-=== Python Execution Results ===-Hello from Python!-Numpy version: 1.24.3-Pandas version: 2.0.2+ try {+ const result = await invoke<{+ success: boolean;+ outputs: CellOutput[];+ executionCount: number;+ error?: string;+ }>('execute_python_code', {+ code: code,+ executionCount: executionCounter+ });++ const outputText = result.outputs+ .map(out => {+ if (out.text) return out.text.join('\n');+ if (out.traceback) return out.traceback.join('\n');+ return '';+ })+ .join('\n');-Successfully executed.-`;setOutput([...output, {- output: mockOutput,+ output: outputText || 'Code executed successfully (no output)',+ error: result.error,timestamp: new Date()}]);- setIsRunning(false);- }, 1000);- };- const runCode = () => {- if (activeFile.language === 'finscript') {- executeFinScript();- } else if (activeFile.language === 'python') {- executePython();+ setIsRunning(false);+ } catch (error) {+ setOutput([...output, {+ output: `Execution failed: ${error}`,+ error: String(error),+ timestamp: new Date()+ }]);+ setIsRunning(false);}};@@ -179,6 +440,324 @@ Successfully executed.}};+ // Jupyter Notebook Functions+ const createNewNotebook = async () => {+ try {+ // Save current notebook to history before creating new one+ if (notebookCells.length > 0) {+ await saveCurrentToHistory();+ }++ const notebook = await invoke<JupyterNotebook>('create_new_notebook');+ setNotebookCells(notebook.cells);+ setCurrentNotebookPath(null);+ setCurrentNotebookId(null);+ setExecutionCounter(1);++ setOutput([...output, {+ output: 'Created new notebook',+ timestamp: new Date()+ }]);+ } catch (error) {+ console.error('Failed to create notebook:', error);+ }+ };++ const openNotebook = async () => {+ try {+ // Save current notebook to history before opening new one+ if (notebookCells.length > 0) {+ await saveCurrentToHistory();+ }++ const selected = await open({+ multiple: false,+ filters: [{+ name: 'Jupyter Notebook',+ extensions: ['ipynb']+ }]+ });++ if (!selected) return;++ const path = selected as string;+ const notebook = await invoke<JupyterNotebook>('open_notebook', {+ filePath: path+ });++ setNotebookCells(notebook.cells);+ setCurrentNotebookPath(path);+ setCurrentNotebookId(null);++ // Find the highest execution count+ const maxCount = Math.max(+ ...notebook.cells+ .map(c => c.executionCount || 0)+ .filter(c => c > 0),+ 0+ );+ setExecutionCounter(maxCount + 1);++ // Save to history+ await saveCurrentToHistory();++ setOutput([...output, {+ output: `Notebook opened: ${path}`,+ timestamp: new Date()+ }]);+ } catch (error) {+ setOutput([...output, {+ output: `Failed to open notebook: ${error}`,+ error: String(error),+ timestamp: new Date()+ }]);+ }+ };++ const saveNotebook = async () => {+ try {+ let path = currentNotebookPath;++ if (!path) {+ const selected = await save({+ filters: [{+ name: 'Jupyter Notebook',+ extensions: ['ipynb']+ }]+ });++ if (!selected) return;+ path = selected as string;+ }++ const notebook: JupyterNotebook = {+ cells: notebookCells,+ metadata: {+ kernelspec: {+ displayName: 'Python 3',+ language: 'python',+ name: 'python3'+ },+ languageInfo: {+ name: 'python',+ version: '3.12.0',+ mimetype: 'text/x-python',+ fileExtension: '.py'+ }+ },+ nbformat: 4,+ nbformatMinor: 5+ };++ await invoke('save_notebook', {+ filePath: path,+ notebook: notebook+ });++ setCurrentNotebookPath(path);++ // Save to history+ await saveCurrentToHistory();++ setOutput([...output, {+ output: `Notebook saved: ${path}`,+ timestamp: new Date()+ }]);+ } catch (error) {+ setOutput([...output, {+ output: `Failed to save notebook: ${error}`,+ error: String(error),+ timestamp: new Date()+ }]);+ }+ };++ const addCell = (index?: number) => {+ const newCell: NotebookCell = {+ id: `cell-${Date.now()}`,+ cellType: 'code',+ source: [],+ outputs: [],+ executionCount: null,+ metadata: {}+ };++ if (index !== undefined) {+ const newCells = [...notebookCells];+ newCells.splice(index + 1, 0, newCell);+ setNotebookCells(newCells);+ } else {+ setNotebookCells([...notebookCells, newCell]);+ }+ };++ const deleteCell = (index: number) => {+ if (notebookCells.length === 1) return;+ setNotebookCells(notebookCells.filter((_, i) => i !== index));+ };++ const moveCellUp = (index: number) => {+ if (index === 0) return;+ const newCells = [...notebookCells];+ [newCells[index - 1], newCells[index]] = [newCells[index], newCells[index - 1]];+ setNotebookCells(newCells);+ };++ const moveCellDown = (index: number) => {+ if (index === notebookCells.length - 1) return;+ const newCells = [...notebookCells];+ [newCells[index], newCells[index + 1]] = [newCells[index + 1], newCells[index]];+ setNotebookCells(newCells);+ };++ const updateCellContent = (index: number, content: string) => {+ const newCells = [...notebookCells];+ newCells[index].source = content.split('\n');+ setNotebookCells(newCells);+ };++ const toggleCellType = (index: number) => {+ const newCells = [...notebookCells];+ newCells[index].cellType = newCells[index].cellType === 'code' ? 'markdown' : 'code';+ setNotebookCells(newCells);+ };++ const executeCell = async (index: number) => {+ const cell = notebookCells[index];+ if (cell.cellType !== 'code') return;++ const code = cell.source.join('\n');+ if (!code.trim()) return;++ try {+ const result = await invoke<{+ success: boolean;+ outputs: CellOutput[];+ executionCount: number;+ error?: string;+ }>('execute_python_code', {+ code: code,+ executionCount: executionCounter+ });++ const newCells = [...notebookCells];+ newCells[index].outputs = result.outputs;+ newCells[index].executionCount = result.executionCount;+ setNotebookCells(newCells);+ setExecutionCounter(executionCounter + 1);+ } catch (error) {+ const errorOutput: CellOutput = {+ outputType: 'error',+ ename: 'ExecutionError',+ evalue: String(error),+ traceback: [String(error)]+ };++ const newCells = [...notebookCells];+ newCells[index].outputs = [errorOutput];+ newCells[index].executionCount = executionCounter;+ setNotebookCells(newCells);+ setExecutionCounter(executionCounter + 1);+ }+ };++ const executeAllCells = async () => {+ for (let i = 0; i < notebookCells.length; i++) {+ if (notebookCells[i].cellType === 'code') {+ await executeCell(i);+ }+ }+ };++ const clearCellOutput = (index: number) => {+ const newCells = [...notebookCells];+ newCells[index].outputs = [];+ newCells[index].executionCount = null;+ setNotebookCells(newCells);+ };++ const clearAllOutputs = () => {+ const newCells = notebookCells.map(cell => ({+ ...cell,+ outputs: [],+ executionCount: null+ }));+ setNotebookCells(newCells);+ setExecutionCounter(1);+ };++ const renderCellOutput = (outputs: CellOutput[]) => {+ if (!outputs || outputs.length === 0) {+ return (+ <div style={{ color: C.GRAY, fontSize: '11px', fontStyle: 'italic' }}>+ Execute cell to see output+ </div>+ );+ }++ return outputs.map((output, idx) => {+ if (output.outputType === 'stream') {+ return (+ <div key={idx} style={{ color: C.GREEN, fontSize: '12px', whiteSpace: 'pre-wrap' }}>+ {output.text?.join('\n')}+ </div>+ );+ } else if (output.outputType === 'error') {+ return (+ <div key={idx} style={{ color: C.RED, fontSize: '12px', whiteSpace: 'pre-wrap' }}>+ <div style={{ fontWeight: 'bold' }}>{output.ename}: {output.evalue}</div>+ {output.traceback && <div>{output.traceback.join('\n')}</div>}+ </div>+ );+ } else if (output.outputType === 'execute_result' || output.outputType === 'display_data') {+ if (output.data) {+ if (output.data['text/plain']) {+ return (+ <div key={idx} style={{ color: C.CYAN, fontSize: '12px', whiteSpace: 'pre-wrap' }}>+ {output.data['text/plain'].join('\n')}+ </div>+ );+ }+ if (output.data['text/html']) {+ return (+ <div key={idx} dangerouslySetInnerHTML={{ __html: output.data['text/html'].join('') }} />+ );+ }+ if (output.data['image/png']) {+ return (+ <img key={idx} src={`data:image/png;base64,${output.data['image/png'][0]}`} alt="Output" style={{ maxWidth: '100%' }} />+ );+ }+ }+ }+ return null;+ });+ };++ // Initialize with a single cell if in notebook mode and no cells exist+ useEffect(() => {+ if (editorMode === 'notebook' && notebookCells.length === 0) {+ createNewNotebook();+ }+ }, [editorMode]);++ const formatDate = (dateString: string) => {+ const date = new Date(dateString);+ const now = new Date();+ const diff = now.getTime() - date.getTime();+ const hours = Math.floor(diff / (1000 * 60 * 60));++ if (hours < 1) {+ const minutes = Math.floor(diff / (1000 * 60));+ return `${minutes}m ago`;+ } else if (hours < 24) {+ return `${hours}h ago`;+ } else {+ const days = Math.floor(hours / 24);+ return `${days}d ago`;+ }+ };+return (<div style={{ width: '100%', height: '100%', backgroundColor: C.DARK_BG, color: C.WHITE, fontFamily: 'Consolas, monospace', display: 'flex', flexDirection: 'column' }}><style>{`@@ -203,6 +782,19 @@ Successfully executed.user-select: none;border-right: 1px solid #404040;}++ .cell-actions {+ opacity: 0;+ transition: opacity 0.2s;+ }++ .notebook-cell:hover .cell-actions {+ opacity: 1;+ }++ .history-item:hover {+ background-color: #2a2a2a;+ }`}</style>{/* Header */}@@ -217,36 +809,196 @@ Successfully executed.<button onClick={() => setEditorMode('notebook')} style={{ padding: '4px 12px', backgroundColor: editorMode === 'notebook' ? C.ORANGE : C.DARK_BG, border: `2px solid ${C.GRAY}`, color: editorMode === 'notebook' ? C.DARK_BG : C.WHITE, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>JUPYTER NOTEBOOK</button>+ {editorMode === 'notebook' && (+ <>+ <span style={{ color: C.GRAY }}>|</span>+ <span style={{ color: C.CYAN, fontSize: '10px' }}>{pythonVersion}</span>+ </>+ )}</div><div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <button onClick={createNewFile} style={{ padding: '6px 12px', backgroundColor: C.DARK_BG, border: `2px solid ${C.GREEN}`, color: C.GREEN, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>- <Plus size={14} style={{ display: 'inline', marginRight: '4px' }} />NEW FILE- </button>- <button onClick={saveFile} disabled={!activeFile.unsaved} style={{ padding: '6px 12px', backgroundColor: C.DARK_BG, border: `2px solid ${activeFile.unsaved ? C.YELLOW : C.GRAY}`, color: activeFile.unsaved ? C.YELLOW : C.GRAY, fontSize: '11px', fontWeight: 'bold', cursor: activeFile.unsaved ? 'pointer' : 'not-allowed', fontFamily: 'Consolas, monospace' }}>- <Save size={14} style={{ display: 'inline', marginRight: '4px' }} />SAVE- </button>- <button onClick={runCode} disabled={isRunning} style={{ padding: '6px 12px', backgroundColor: isRunning ? C.GRAY : C.GREEN, border: 'none', color: C.DARK_BG, fontSize: '11px', fontWeight: 'bold', cursor: isRunning ? 'not-allowed' : 'pointer', fontFamily: 'Consolas, monospace' }}>- <Play size={14} style={{ display: 'inline', marginRight: '4px' }} />{isRunning ? 'RUNNING...' : 'RUN CODE'}- </button>+ {editorMode === 'code' ? (+ <>+ <button onClick={createNewFile} style={{ padding: '6px 12px', backgroundColor: C.DARK_BG, border: `2px solid ${C.GREEN}`, color: C.GREEN, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ <Plus size={14} style={{ display: 'inline', marginRight: '4px' }} />NEW FILE+ </button>+ <button onClick={saveFile} disabled={!activeFile.unsaved} style={{ padding: '6px 12px', backgroundColor: C.DARK_BG, border: `2px solid ${activeFile.unsaved ? C.YELLOW : C.GRAY}`, color: activeFile.unsaved ? C.YELLOW : C.GRAY, fontSize: '11px', fontWeight: 'bold', cursor: activeFile.unsaved ? 'pointer' : 'not-allowed', fontFamily: 'Consolas, monospace' }}>+ <Save size={14} style={{ display: 'inline', marginRight: '4px' }} />SAVE+ </button>+ <button onClick={runCode} disabled={isRunning} style={{ padding: '6px 12px', backgroundColor: isRunning ? C.GRAY : C.GREEN, border: 'none', color: C.DARK_BG, fontSize: '11px', fontWeight: 'bold', cursor: isRunning ? 'not-allowed' : 'pointer', fontFamily: 'Consolas, monospace' }}>+ <Play size={14} style={{ display: 'inline', marginRight: '4px' }} />{isRunning ? 'RUNNING...' : 'RUN CODE'}+ </button>+ </>+ ) : (+ <>+ <button onClick={createNewNotebook} style={{ padding: '6px 12px', backgroundColor: C.DARK_BG, border: `2px solid ${C.GREEN}`, color: C.GREEN, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ <Plus size={14} style={{ display: 'inline', marginRight: '4px' }} />NEW+ </button>+ <button onClick={openNotebook} style={{ padding: '6px 12px', backgroundColor: C.DARK_BG, border: `2px solid ${C.BLUE}`, color: C.BLUE, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ <Upload size={14} style={{ display: 'inline', marginRight: '4px' }} />OPEN+ </button>+ <button onClick={saveNotebook} style={{ padding: '6px 12px', backgroundColor: C.DARK_BG, border: `2px solid ${C.YELLOW}`, color: C.YELLOW, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ <Save size={14} style={{ display: 'inline', marginRight: '4px' }} />SAVE+ </button>+ <button onClick={executeAllCells} style={{ padding: '6px 12px', backgroundColor: C.GREEN, border: 'none', color: C.DARK_BG, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ <Play size={14} style={{ display: 'inline', marginRight: '4px' }} />RUN ALL+ </button>+ <button onClick={() => setShowPackageManager(!showPackageManager)} style={{ padding: '6px 12px', backgroundColor: C.DARK_BG, border: `2px solid ${C.CYAN}`, color: C.CYAN, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ <Package size={14} style={{ display: 'inline', marginRight: '4px' }} />PACKAGES+ </button>+ <button onClick={() => setShowHistory(!showHistory)} style={{ padding: '6px 12px', backgroundColor: showHistory ? C.ORANGE : C.DARK_BG, border: `2px solid ${C.ORANGE}`, color: showHistory ? C.DARK_BG : C.ORANGE, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ <History size={14} style={{ display: 'inline', marginRight: '4px' }} />HISTORY+ </button>+ </>+ )}</div></div></div>- {/* File Tabs */}- <div style={{ backgroundColor: C.PANEL_BG, borderBottom: `1px solid ${C.GRAY}`, display: 'flex', alignItems: 'center', padding: '4px 8px', gap: '4px', overflowX: 'auto' }}>- {files.map(file => (- <div key={file.id} onClick={() => setActiveFileId(file.id)} style={{ display: 'flex', alignItems: 'center', gap: '6px', padding: '6px 12px', backgroundColor: activeFileId === file.id ? C.EDITOR_BG : C.DARK_BG, border: `1px solid ${activeFileId === file.id ? getLanguageColor(file.language) : C.GRAY}`, cursor: 'pointer', fontSize: '11px' }}>- <FileText size={12} style={{ color: getLanguageColor(file.language) }} />- <span style={{ color: file.unsaved ? C.YELLOW : C.WHITE }}>{file.name}{file.unsaved && '*'}</span>- {files.length > 1 && (- <X size={12} onClick={(e) => { e.stopPropagation(); closeFile(file.id); }} style={{ color: C.GRAY, cursor: 'pointer' }} />+ {/* File Tabs (Code Mode) */}+ {editorMode === 'code' && (+ <div style={{ backgroundColor: C.PANEL_BG, borderBottom: `1px solid ${C.GRAY}`, display: 'flex', alignItems: 'center', padding: '4px 8px', gap: '4px', overflowX: 'auto' }}>+ {files.map(file => (+ <div key={file.id} onClick={() => setActiveFileId(file.id)} style={{ display: 'flex', alignItems: 'center', gap: '6px', padding: '6px 12px', backgroundColor: activeFileId === file.id ? C.EDITOR_BG : C.DARK_BG, border: `1px solid ${activeFileId === file.id ? getLanguageColor(file.language) : C.GRAY}`, cursor: 'pointer', fontSize: '11px' }}>+ <FileText size={12} style={{ color: getLanguageColor(file.language) }} />+ <span style={{ color: file.unsaved ? C.YELLOW : C.WHITE }}>{file.name}{file.unsaved && '*'}</span>+ {files.length > 1 && (+ <X size={12} onClick={(e) => { e.stopPropagation(); closeFile(file.id); }} style={{ color: C.GRAY, cursor: 'pointer' }} />+ )}+ </div>+ ))}+ </div>+ )}++ {/* Package Manager Modal */}+ {showPackageManager && editorMode === 'notebook' && (+ <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', backgroundColor: C.PANEL_BG, border: `2px solid ${C.ORANGE}`, padding: '20px', zIndex: 1000, width: '500px', maxHeight: '400px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>+ <span style={{ color: C.ORANGE, fontWeight: 'bold', fontSize: '14px' }}>PACKAGE MANAGER</span>+ <X size={16} onClick={() => setShowPackageManager(false)} style={{ cursor: 'pointer', color: C.GRAY }} />+ </div>++ <div style={{ marginBottom: '16px' }}>+ <div style={{ display: 'flex', gap: '8px' }}>+ <input+ type="text"+ value={packageToInstall}+ onChange={(e) => setPackageToInstall(e.target.value)}+ onKeyPress={(e) => e.key === 'Enter' && installPackage()}+ placeholder="Package name (e.g., numpy, pandas, matplotlib)"+ style={{ flex: 1, backgroundColor: C.EDITOR_BG, border: `1px solid ${C.GRAY}`, color: C.WHITE, padding: '6px 8px', fontSize: '12px', fontFamily: 'Consolas, monospace' }}+ />+ <button onClick={installPackage} style={{ padding: '6px 12px', backgroundColor: C.GREEN, border: 'none', color: C.DARK_BG, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ INSTALL+ </button>+ </div>+ </div>++ <div style={{ fontSize: '11px', color: C.CYAN, marginBottom: '8px' }}>Installed Packages:</div>+ <div className="code-scroll" style={{ maxHeight: '250px', overflowY: 'auto', backgroundColor: C.EDITOR_BG, padding: '8px', fontSize: '10px' }}>+ {installedPackages.length === 0 ? (+ <div style={{ color: C.GRAY }}>Click to load packages...</div>+ ) : (+ installedPackages.map((pkg, idx) => (+ <div key={idx} style={{ color: C.WHITE, marginBottom: '2px' }}>{pkg}</div>+ )))}</div>- ))}- </div>+ {installedPackages.length === 0 && (+ <button onClick={loadInstalledPackages} style={{ marginTop: '8px', padding: '4px 8px', backgroundColor: C.BLUE, border: 'none', color: C.WHITE, fontSize: '10px', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ LOAD PACKAGES+ </button>+ )}+ </div>+ )}{/* Main Content */}<div style={{ flex: 1, display: 'flex', minHeight: 0 }}>+ {/* History Sidebar */}+ {showHistory && editorMode === 'notebook' && (+ <div style={{ width: '300px', backgroundColor: C.PANEL_BG, borderRight: `1px solid ${C.GRAY}`, display: 'flex', flexDirection: 'column' }}>+ <div style={{ backgroundColor: C.DARK_BG, padding: '8px 12px', borderBottom: `1px solid ${C.GRAY}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>+ <History size={14} style={{ color: C.ORANGE }} />+ <span style={{ color: C.ORANGE, fontSize: '12px', fontWeight: 'bold' }}>NOTEBOOK HISTORY</span>+ </div>+ <div style={{ display: 'flex', gap: '4px' }}>+ <input+ type="text"+ value={historySearch}+ onChange={(e) => {+ setHistorySearch(e.target.value);+ searchHistory(e.target.value);+ }}+ placeholder="Search..."+ style={{ flex: 1, backgroundColor: C.EDITOR_BG, border: `1px solid ${C.GRAY}`, color: C.WHITE, padding: '4px 8px', fontSize: '11px', fontFamily: 'Consolas, monospace' }}+ />+ <button onClick={loadHistory} style={{ padding: '4px 8px', backgroundColor: C.DARK_BG, border: `1px solid ${C.BLUE}`, color: C.BLUE, fontSize: '10px', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ <RefreshCw size={12} />+ </button>+ </div>+ </div>++ <div className="code-scroll" style={{ flex: 1, overflowY: 'auto', padding: '8px' }}>+ {isLoadingHistory ? (+ <div style={{ color: C.GRAY, textAlign: 'center', padding: '20px', fontSize: '11px' }}>+ Loading history...+ </div>+ ) : notebookHistory.length === 0 ? (+ <div style={{ color: C.GRAY, textAlign: 'center', padding: '20px', fontSize: '11px' }}>+ No notebook history yet+ </div>+ ) : (+ notebookHistory.map((entry) => (+ <div+ key={entry.id}+ className="history-item"+ style={{+ backgroundColor: currentNotebookId === entry.id ? C.EDITOR_BG : C.DARK_BG,+ border: `1px solid ${currentNotebookId === entry.id ? C.ORANGE : C.GRAY}`,+ padding: '8px',+ marginBottom: '8px',+ cursor: 'pointer',+ fontSize: '11px'+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: '4px' }}>+ <div onClick={() => loadFromHistory(entry.id!)} style={{ flex: 1 }}>+ <div style={{ color: C.CYAN, fontWeight: 'bold', marginBottom: '4px', display: 'flex', alignItems: 'center', gap: '4px' }}>+ <Folder size={10} />+ {entry.name}+ </div>+ <div style={{ color: C.GRAY, fontSize: '10px', marginBottom: '4px', display: 'flex', alignItems: 'center', gap: '4px' }}>+ <Clock size={10} />+ {formatDate(entry.updated_at)}+ </div>+ <div style={{ color: C.GRAY, fontSize: '9px', display: 'flex', gap: '12px' }}>+ <span>{entry.cell_count} cells</span>+ <span>Ex: {entry.execution_count}</span>+ </div>+ </div>+ <button+ onClick={(e) => {+ e.stopPropagation();+ deleteFromHistory(entry.id!);+ }}+ style={{ padding: '2px 4px', backgroundColor: 'transparent', border: `1px solid ${C.RED}`, color: C.RED, fontSize: '9px', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}+ >+ <Trash2 size={10} />+ </button>+ </div>+ {entry.path && (+ <div style={{ color: C.GRAY, fontSize: '9px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {entry.path}+ </div>+ )}+ </div>+ ))+ )}+ </div>+ </div>+ )}+{editorMode === 'code' ? (<>{/* Editor Panel */}@@ -330,73 +1082,79 @@ Successfully executed.) : (// Jupyter Notebook Mode<div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>- <div style={{ backgroundColor: C.PANEL_BG, padding: '12px', borderBottom: `1px solid ${C.GRAY}` }}>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>- <span style={{ color: C.ORANGE, fontSize: '12px', fontWeight: 'bold' }}>JUPYTER NOTEBOOK</span>- <div style={{ display: 'flex', gap: '8px' }}>- <button style={{ padding: '6px 12px', backgroundColor: C.DARK_BG, border: `2px solid ${C.BLUE}`, color: C.BLUE, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>- <Plus size={14} style={{ display: 'inline', marginRight: '4px' }} />ADD CELL- </button>- <button style={{ padding: '6px 12px', backgroundColor: C.GREEN, border: 'none', color: C.DARK_BG, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>- <Play size={14} style={{ display: 'inline', marginRight: '4px' }} />RUN ALL- </button>- </div>- </div>- </div>-<div className="code-scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px', backgroundColor: '#050505' }}><div style={{ maxWidth: '1200px', margin: '0 auto' }}>- {/* Cell 1 */}- <div style={{ backgroundColor: C.PANEL_BG, border: `1px solid ${C.GRAY}`, marginBottom: '16px' }}>- <div style={{ backgroundColor: C.DARK_BG, padding: '6px 12px', borderBottom: `1px solid ${C.GRAY}`, fontSize: '10px', color: C.BLUE }}>- In [1]: Python Code- </div>- <textarea- placeholder="import pandas as pd import numpy as np # Your Python code here..."- style={{- width: '100%',- minHeight: '120px',- backgroundColor: C.EDITOR_BG,- color: C.WHITE,- border: 'none',- outline: 'none',- resize: 'vertical',- padding: '12px',- fontSize: '13px',- fontFamily: 'Consolas, monospace'- }}- />- <div style={{ backgroundColor: C.DARK_BG, padding: '12px', borderTop: `1px solid ${C.GRAY}` }}>- <div style={{ color: C.GREEN, fontSize: '10px', marginBottom: '4px' }}>Output:</div>- <div style={{ color: C.GRAY, fontSize: '11px', fontStyle: 'italic' }}>Execute cell to see output</div>- </div>- </div>+ {notebookCells.map((cell, index) => (+ <div key={cell.id} className="notebook-cell" style={{ backgroundColor: C.PANEL_BG, border: `1px solid ${C.GRAY}`, marginBottom: '16px', position: 'relative' }}>+ {/* Cell Header */}+ <div style={{ backgroundColor: C.DARK_BG, padding: '6px 12px', borderBottom: `1px solid ${C.GRAY}`, fontSize: '10px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <span style={{ color: cell.cellType === 'code' ? C.BLUE : C.ORANGE }}>+ {cell.cellType === 'code'+ ? `In [${cell.executionCount || ' '}]:`+ : 'Markdown'+ }+ </span>+ <div className="cell-actions" style={{ display: 'flex', gap: '8px' }}>+ <button onClick={() => toggleCellType(index)} style={{ padding: '2px 6px', backgroundColor: 'transparent', border: `1px solid ${C.CYAN}`, color: C.CYAN, fontSize: '9px', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ {cell.cellType === 'code' ? 'MD' : 'CODE'}+ </button>+ <ChevronUp size={12} onClick={() => moveCellUp(index)} style={{ color: index === 0 ? C.GRAY : C.WHITE, cursor: index === 0 ? 'not-allowed' : 'pointer' }} />+ <ChevronDown size={12} onClick={() => moveCellDown(index)} style={{ color: index === notebookCells.length - 1 ? C.GRAY : C.WHITE, cursor: index === notebookCells.length - 1 ? 'not-allowed' : 'pointer' }} />+ {cell.cellType === 'code' && (+ <Play size={12} onClick={() => executeCell(index)} style={{ color: C.GREEN, cursor: 'pointer' }} />+ )}+ <Trash2 size={12} onClick={() => deleteCell(index)} style={{ color: notebookCells.length === 1 ? C.GRAY : C.RED, cursor: notebookCells.length === 1 ? 'not-allowed' : 'pointer' }} />+ </div>+ </div>- {/* Cell 2 */}- <div style={{ backgroundColor: C.PANEL_BG, border: `1px solid ${C.GRAY}`, marginBottom: '16px' }}>- <div style={{ backgroundColor: C.DARK_BG, padding: '6px 12px', borderBottom: `1px solid ${C.GRAY}`, fontSize: '10px', color: C.BLUE }}>- In [2]: Data Analysis+ {/* Cell Content */}+ <textarea+ value={cell.source.join('\n')}+ onChange={(e) => updateCellContent(index, e.target.value)}+ placeholder={cell.cellType === 'code' ? "# Enter Python code here..." : "Enter markdown text here..."}+ style={{+ width: '100%',+ minHeight: '100px',+ backgroundColor: C.EDITOR_BG,+ color: C.WHITE,+ border: 'none',+ outline: 'none',+ resize: 'vertical',+ padding: '12px',+ fontSize: '13px',+ fontFamily: 'Consolas, monospace'+ }}+ />++ {/* Cell Output (only for code cells) */}+ {cell.cellType === 'code' && (+ <div style={{ backgroundColor: C.DARK_BG, padding: '12px', borderTop: `1px solid ${C.GRAY}` }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>+ <div style={{ color: C.GREEN, fontSize: '10px' }}>+ Output {cell.executionCount ? `[${cell.executionCount}]` : ''}:+ </div>+ {cell.outputs.length > 0 && (+ <button onClick={() => clearCellOutput(index)} style={{ padding: '2px 6px', backgroundColor: 'transparent', border: `1px solid ${C.RED}`, color: C.RED, fontSize: '8px', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ CLEAR+ </button>+ )}+ </div>+ {renderCellOutput(cell.outputs)}+ </div>+ )}++ {/* Add Cell Button */}+ <div style={{ textAlign: 'center', padding: '4px', backgroundColor: C.DARK_BG, borderTop: `1px solid ${C.GRAY}`, opacity: 0.7 }}>+ <button onClick={() => addCell(index)} style={{ padding: '4px 8px', backgroundColor: 'transparent', border: `1px dashed ${C.GRAY}`, color: C.GRAY, fontSize: '9px', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ + ADD CELL BELOW+ </button>+ </div></div>- <textarea- placeholder="# Financial data analysis # Use pandas, matplotlib, seaborn..."- style={{- width: '100%',- minHeight: '120px',- backgroundColor: C.EDITOR_BG,- color: C.WHITE,- border: 'none',- outline: 'none',- resize: 'vertical',- padding: '12px',- fontSize: '13px',- fontFamily: 'Consolas, monospace'- }}- />- </div>+ ))}<div style={{ textAlign: 'center', padding: '20px' }}>- <button style={{ padding: '8px 16px', backgroundColor: C.DARK_BG, border: `2px dashed ${C.GRAY}`, color: C.GRAY, fontSize: '11px', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>- + Add New Cell+ <button onClick={() => addCell()} style={{ padding: '8px 16px', backgroundColor: C.DARK_BG, border: `2px dashed ${C.GREEN}`, color: C.GREEN, fontSize: '11px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'Consolas, monospace' }}>+ + ADD CELL</button></div></div>@@ -414,12 +1172,19 @@ Successfully executed.<span style={{ color: C.CYAN }}>FinScript Language Support</span><span style={{ color: C.GRAY }}>|</span><span style={{ color: C.BLUE }}>Jupyter Integration</span>+ {editorMode === 'notebook' && currentNotebookPath && (+ <>+ <span style={{ color: C.GRAY }}>|</span>+ <span style={{ color: C.YELLOW, fontSize: '10px' }}>{currentNotebookPath.split(/[/\\]/).pop()}</span>+ </>+ )}</div><div style={{ color: C.GRAY }}>- Mode: <span style={{ color: C.ORANGE, fontWeight: 'bold' }}>{editorMode.toUpperCase()}</span> | Files: {files.length}+ Mode: <span style={{ color: C.ORANGE, fontWeight: 'bold' }}>{editorMode.toUpperCase()}</span>+ {editorMode === 'code' ? ` | Files: ${files.length}` : ` | Cells: ${notebookCells.length} | Exec: ${executionCounter - 1}`}</div></div></div></div>);-}\ No newline at end of file+}diff --git a/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsx b/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsxindex b90153a59..b5ca15270 100644--- a/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsx@@ -29,6 +29,8 @@ export default function MaritimeTab() {const [markerType, setMarkerType] = useState<MarkerData['type']>('Ship');const [showRoutes, setShowRoutes] = useState(true);const [showShips, setShowShips] = useState(true);+ const [showPlanes, setShowPlanes] = useState(true);+ const [isRotating, setIsRotating] = useState(true);const [intelligence, setIntelligence] = useState<IntelligenceData>({timestamp: new Date().toISOString(),threat_level: 'low',@@ -39,16 +41,16 @@ export default function MaritimeTab() {const mapRef = useRef<HTMLIFrameElement>(null);const tradeRoutes: TradeRoute[] = [- { name: 'Mumbai → Rotterdam', value: '$45B', status: 'active', vessels: 23, coordinates: [[19.0760, 72.8777], [51.9244, 4.4777]] },- { name: 'Mumbai → Shanghai', value: '$156B', status: 'active', vessels: 89, coordinates: [[19.0760, 72.8777], [31.2304, 121.4737]] },- { name: 'Mumbai → Singapore', value: '$89B', status: 'active', vessels: 45, coordinates: [[19.0760, 72.8777], [1.3521, 103.8198]] },- { name: 'Chennai → Tokyo', value: '$67B', status: 'delayed', vessels: 34, coordinates: [[13.0827, 80.2707], [35.6762, 139.6503]] },- { name: 'Kolkata → Hong Kong', value: '$45B', status: 'active', vessels: 28, coordinates: [[22.5726, 88.3639], [22.3193, 114.1694]] },- { name: 'Mumbai → Dubai', value: '$78B', status: 'critical', vessels: 12, coordinates: [[19.0760, 72.8777], [25.2048, 55.2708]] },- { name: 'Mumbai → New York', value: '$123B', status: 'active', vessels: 56, coordinates: [[19.0760, 72.8777], [40.7128, -74.0060]] },- { name: 'Chennai → Sydney', value: '$54B', status: 'active', vessels: 31, coordinates: [[13.0827, 80.2707], [-33.8688, 151.2093]] },- { name: 'Cochin → Malacca', value: '$34B', status: 'active', vessels: 19, coordinates: [[9.9312, 76.2673], [1.3521, 103.8198]] },- { name: 'Mumbai → Cape Town', value: '$28B', status: 'delayed', vessels: 8, coordinates: [[19.0760, 72.8777], [-33.9249, 18.4241]] }+ { name: 'Mumbai → Rotterdam', value: '$45B', status: 'active', vessels: 23, coordinates: [[18.9388, 72.8354], [51.9553, 4.1392]] },+ { name: 'Mumbai → Shanghai', value: '$156B', status: 'active', vessels: 89, coordinates: [[18.9388, 72.8354], [31.3548, 121.6431]] },+ { name: 'Mumbai → Singapore', value: '$89B', status: 'active', vessels: 45, coordinates: [[18.9388, 72.8354], [1.2644, 103.8224]] },+ { name: 'Chennai → Tokyo', value: '$67B', status: 'delayed', vessels: 34, coordinates: [[13.0827, 80.2707], [35.4437, 139.6380]] },+ { name: 'Kolkata → Hong Kong', value: '$45B', status: 'active', vessels: 28, coordinates: [[22.5726, 88.3639], [22.2855, 114.1577]] },+ { name: 'Mumbai → Dubai', value: '$78B', status: 'critical', vessels: 12, coordinates: [[18.9388, 72.8354], [24.9857, 55.0272]] },+ { name: 'Mumbai → New York', value: '$123B', status: 'active', vessels: 56, coordinates: [[18.9388, 72.8354], [40.6655, -74.0781]] },+ { name: 'Chennai → Sydney', value: '$54B', status: 'active', vessels: 31, coordinates: [[13.0827, 80.2707], [-33.9544, 151.2093]] },+ { name: 'Cochin → Klang', value: '$34B', status: 'active', vessels: 19, coordinates: [[9.9667, 76.2667], [3.0048, 101.3975]] },+ { name: 'Mumbai → Cape Town', value: '$28B', status: 'delayed', vessels: 8, coordinates: [[18.9388, 72.8354], [-33.9055, 18.4232]] }];const addMarker = (title: string, lat: number, lng: number) => {@@ -61,10 +63,12 @@ export default function MaritimeTab() {};const presetLocations = [- { name: 'Mumbai Port', lat: 19.0760, lng: 72.8777, type: 'Port' as const },- { name: 'Shanghai Port', lat: 31.2304, lng: 121.4737, type: 'Port' as const },- { name: 'Singapore Port', lat: 1.3521, lng: 103.8198, type: 'Port' as const },- { name: 'Hong Kong Port', lat: 22.3193, lng: 114.1694, type: 'Port' as const },+ { name: 'Mumbai Port', lat: 18.9388, lng: 72.8354, type: 'Port' as const },+ { name: 'Shanghai Port', lat: 31.3548, lng: 121.6431, type: 'Port' as const },+ { name: 'Singapore Port', lat: 1.2644, lng: 103.8224, type: 'Port' as const },+ { name: 'Hong Kong Port', lat: 22.2855, lng: 114.1577, type: 'Port' as const },+ { name: 'Rotterdam Port', lat: 51.9553, lng: 4.1392, type: 'Port' as const },+ { name: 'Dubai Port', lat: 24.9857, lng: 55.0272, type: 'Port' as const },];const addPreset = (preset: typeof presetLocations[0]) => {@@ -89,113 +93,688 @@ export default function MaritimeTab() {<meta charset="utf-8" /><link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" /><style>- body { margin: 0; padding: 0; background: #000; }- #map { height: 100vh; width: 100vw; }- .ocean-route { stroke: #00ffff; stroke-width: 2; stroke-opacity: 0.8; stroke-dasharray: 8,4; }- .route-animation { animation: routeFlow 3s linear infinite; }- @keyframes routeFlow { 0% { stroke-dashoffset: 0; } 100% { stroke-dashoffset: -24; } }- .ship-marker { animation: shipBob 2s ease-in-out infinite; z-index: 1000 !important; }- @keyframes shipBob { 0%, 100% { transform: translateY(0px); } 50% { transform: translateY(-3px); } }+ body { margin: 0; padding: 0; background: #000; overflow: hidden; }+ #globeViz { height: 100vh; width: 100vw; background: #000; position: absolute; top: 0; left: 0; }+ #mapViz { height: 100vh; width: 100vw; position: absolute; top: 0; left: 0; display: none; }+ #modeIndicator {+ position: absolute;+ top: 16px;+ right: 16px;+ background: rgba(0, 255, 255, 0.9);+ color: #000;+ padding: 8px 16px;+ border-radius: 4px;+ font-family: 'Consolas', monospace;+ font-size: 12px;+ font-weight: bold;+ z-index: 1000;+ box-shadow: 0 0 10px rgba(0, 255, 255, 0.5);+ }</style></head><body>- <div id="map"></div>+ <div id="modeIndicator">3D GLOBE MODE</div>+ <div id="globeViz"></div>+ <div id="mapViz"></div>+ <script src="https://unpkg.com/[email protected]/build/three.min.js"></script>+ <script src="https://unpkg.com/[email protected]/dist/globe.gl.min.js"></script><script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script><script>- var map = L.map('map', { zoomControl: true }).setView([20.0, 75.0], 4);-- L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {- attribution: 'FINCEPT MARITIME INTELLIGENCE',- maxZoom: 18- }).addTo(map);-- var markers = [];- var routesLayer = null;- var shipsLayer = null;-- function createIcon(type, size = 24) {- var icons = {- 'Ship': { symbol: '🚢', color: '#1e90ff' },- 'Port': { symbol: '⚓', color: '#ff8c00' },- 'Industry': { symbol: '🏭', color: '#ff4500' },- 'Bank': { symbol: '🏦', color: '#ffd700' },- 'Exchange': { symbol: '💱', color: '#ff1493' }+ console.log('Initializing Hybrid Globe/Map System...');++ // Wait for libraries to load+ setTimeout(() => {+ try {+ console.log('Creating globe...');++ // Create professional globe with natural appearance+ const world = Globe()+ (document.getElementById('globeViz'))+ .globeImageUrl('https://unpkg.com/[email protected]/example/img/earth-blue-marble.jpg')+ .bumpImageUrl('https://unpkg.com/[email protected]/example/img/earth-topology.png')+ .backgroundColor('#0a0a0a')+ .backgroundImageUrl('https://unpkg.com/three-globe/example/img/night-sky.png')+ .showAtmosphere(true)+ .atmosphereColor('#4a90e2')+ .atmosphereAltitude(0.12)+ .width(window.innerWidth)+ .height(window.innerHeight);++ console.log('Globe created successfully');++ // Initialize 2D Leaflet map for close zoom (lazy - will initialize when needed)+ let map2D = null;++ function initMap2D() {+ if (!map2D) {+ map2D = L.map('mapViz', {+ zoomControl: true,+ attributionControl: false,+ preferCanvas: false+ }).setView([20, 75], 12);++ // Add satellite imagery layer (Google Satellite)+ L.tileLayer('https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {+ attribution: 'FINCEPT MARITIME INTELLIGENCE | Satellite Imagery',+ maxZoom: 20,+ minZoom: 3,+ subdomains: ['mt0', 'mt1', 'mt2', 'mt3']+ }).addTo(map2D);++ // Monitor 2D map zoom to switch back to 3D+ map2D.on('zoomend', function() {+ const zoom = map2D.getZoom();+ console.log('2D map zoom:', zoom);+ if (zoom < 8 && currentMode === '2D') {+ const center = map2D.getCenter();+ switchTo3D(center.lat, center.lng, 2.0);+ }+ });++ // Force map to resize and load tiles+ setTimeout(() => {+ map2D.invalidateSize();+ console.log('2D map resized and tiles loading');+ }, 100);++ console.log('2D map initialized');+ }+ }++ console.log('2D map setup ready');++ // Professional balanced lighting+ const scene = world.scene();+ const ambientLight = new THREE.AmbientLight(0x808080, 0.7); // Balanced ambient light+ const directionalLight = new THREE.DirectionalLight(0xaaaaaa, 0.6); // Natural directional light+ directionalLight.position.set(5, 3, 5);+ scene.add(ambientLight);+ scene.add(directionalLight);++ console.log('Professional lighting added');++ // Set initial point of view+ world.pointOfView({ lat: 20, lng: 75, altitude: 2.0 }, 1000);++ console.log('Camera positioned');++ // Hybrid mode state+ let currentMode = '3D'; // '3D' or '2D'+ let lastGlobeView = { lat: 20, lng: 75, altitude: 2.0 };+ let targetCoords = { lat: 20, lng: 75 }; // Track where user is actually looking+ const ZOOM_THRESHOLD = 0.3; // Switch to 2D when altitude < 0.3 (very close)++ var markers = [];+ var allArcs = [];+ var allLabels = [];+ var planeLabels = [];+ var showRoutesFlag = true;+ var showShipsFlag = true;+ var showPlanesFlag = true;++ var oceanRoutes = [+ // Mumbai Port (18.9388° N, 72.8354° E) - actual port coordinates+ { name: "Mumbai → Rotterdam", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 51.9553, lng: 4.1392}, value: "$45B", vessels: 23, color: 'rgba(100, 180, 255, 0.6)', width: 0.8 },+ { name: "Mumbai → Shanghai", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 31.3548, lng: 121.6431}, value: "$156B", vessels: 89, color: 'rgba(120, 200, 255, 0.7)', width: 1.2 },+ { name: "Mumbai → Singapore", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 1.2644, lng: 103.8224}, value: "$89B", vessels: 45, color: 'rgba(100, 180, 255, 0.65)', width: 1.0 },+ // Chennai Port (13.0827° N, 80.2707° E)+ { name: "Chennai → Tokyo", start: {lat: 13.0827, lng: 80.2707}, end: {lat: 35.4437, lng: 139.6380}, value: "$67B", vessels: 34, color: 'rgba(150, 220, 255, 0.6)', width: 0.9 },+ // Kolkata Port (22.5726° N, 88.3639° E)+ { name: "Kolkata → Hong Kong", start: {lat: 22.5726, lng: 88.3639}, end: {lat: 22.2855, lng: 114.1577}, value: "$45B", vessels: 28, color: 'rgba(100, 180, 255, 0.55)', width: 0.8 },+ // Mumbai → Dubai (Port Jebel Ali: 24.9857° N, 55.0272° E)+ { name: "Mumbai → Dubai", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 24.9857, lng: 55.0272}, value: "$78B", vessels: 12, color: 'rgba(255, 160, 100, 0.6)', width: 0.9 },+ // Mumbai → New York (Port of NY/NJ: 40.6655° N, 74.0781° W)+ { name: "Mumbai → New York", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 40.6655, lng: -74.0781}, value: "$123B", vessels: 56, color: 'rgba(120, 200, 255, 0.75)', width: 1.2 },+ // Chennai → Sydney (Port Botany: 33.9544° S, 151.2093° E)+ { name: "Chennai → Sydney", start: {lat: 13.0827, lng: 80.2707}, end: {lat: -33.9544, lng: 151.2093}, value: "$54B", vessels: 31, color: 'rgba(130, 190, 255, 0.6)', width: 0.9 },+ // Cochin Port (9.9667° N, 76.2667° E) → Port Klang, Malaysia (3.0048° N, 101.3975° E)+ { name: "Cochin → Klang", start: {lat: 9.9667, lng: 76.2667}, end: {lat: 3.0048, lng: 101.3975}, value: "$34B", vessels: 19, color: 'rgba(180, 200, 255, 0.5)', width: 0.7 },+ // Mumbai → Cape Town (33.9055° S, 18.4232° E)+ { name: "Mumbai → Cape Town", start: {lat: 18.9388, lng: 72.8354}, end: {lat: -33.9055, lng: 18.4232}, value: "$28B", vessels: 8, color: 'rgba(160, 180, 255, 0.5)', width: 0.7 }+ ];++ var airRoutes = [+ // Major international air cargo routes+ { name: "Mumbai → London", start: {lat: 19.0896, lng: 72.8656}, end: {lat: 51.4700, lng: -0.4543}, value: "$12B", flights: 45, color: 'rgba(255, 200, 100, 0.7)', width: 0.6 },+ { name: "Delhi → New York", start: {lat: 28.5562, lng: 77.1000}, end: {lat: 40.6413, lng: -73.7781}, value: "$18B", flights: 67, color: 'rgba(255, 200, 100, 0.75)', width: 0.8 },+ { name: "Mumbai → Dubai", start: {lat: 19.0896, lng: 72.8656}, end: {lat: 25.2532, lng: 55.3657}, value: "$22B", flights: 123, color: 'rgba(255, 200, 100, 0.8)', width: 0.9 },+ { name: "Bangalore → Singapore", start: {lat: 13.1979, lng: 77.7063}, end: {lat: 1.3644, lng: 103.9915}, value: "$8B", flights: 89, color: 'rgba(255, 200, 100, 0.65)', width: 0.6 },+ { name: "Delhi → Frankfurt", start: {lat: 28.5562, lng: 77.1000}, end: {lat: 50.0379, lng: 8.5622}, value: "$15B", flights: 56, color: 'rgba(255, 200, 100, 0.7)', width: 0.7 },+ { name: "Mumbai → Hong Kong", start: {lat: 19.0896, lng: 72.8656}, end: {lat: 22.3080, lng: 113.9185}, value: "$11B", flights: 78, color: 'rgba(255, 200, 100, 0.65)', width: 0.6 },+ { name: "Chennai → Tokyo", start: {lat: 12.9941, lng: 80.1709}, end: {lat: 35.7720, lng: 140.3929}, value: "$9B", flights: 34, color: 'rgba(255, 200, 100, 0.6)', width: 0.6 },+ { name: "Delhi → Sydney", start: {lat: 28.5562, lng: 77.1000}, end: {lat: -33.9399, lng: 151.1753}, value: "$7B", flights: 28, color: 'rgba(255, 200, 100, 0.6)', width: 0.5 }+ ];++ function createRoutes() {+ // Combine ocean and air routes+ const oceanArcsData = oceanRoutes.map(route => ({+ startLat: route.start.lat,+ startLng: route.start.lng,+ endLat: route.end.lat,+ endLng: route.end.lng,+ color: route.color,+ name: route.name,+ value: route.value,+ width: route.width || 0.5,+ type: 'ocean'+ }));++ const airArcsData = airRoutes.map(route => ({+ startLat: route.start.lat,+ startLng: route.start.lng,+ endLat: route.end.lat,+ endLng: route.end.lng,+ color: route.color,+ name: route.name,+ value: route.value,+ width: route.width || 0.5,+ type: 'air'+ }));++ const allArcsData = [...oceanArcsData, ...airArcsData];+ allArcs = allArcsData;+ world.arcsData(allArcsData)+ .arcColor('color')+ .arcStroke((d) => d.width) // Thin, professional lines+ .arcDashLength(1.0) // Full solid lines+ .arcDashGap(0) // No gaps - complete lines+ .arcDashInitialGap(0) // Start from beginning+ .arcDashAnimateTime(0) // No animation to avoid cutting+ .arcAltitude((d) => d.type === 'air' ? 0.15 : 0.1) // Higher for air, moderate for ocean+ .arcAltitudeAutoScale(0.5) // More curve for visibility+ .arcLabel((d) => \`+ <div style="background: rgba(10,10,10,0.92); padding: 6px 10px; border-left: 2px solid \${d.type === 'air' ? 'rgba(255, 200, 100, 0.8)' : 'rgba(100, 180, 255, 0.8)'}; font-family: 'Segoe UI', sans-serif; font-size: 11px; box-shadow: 0 2px 8px rgba(0,0,0,0.4);">+ <div style="color: #e0e0e0; font-weight: 500; margin-bottom: 2px;">\${d.type === 'air' ? '✈' : '🚢'} \${d.name}</div>+ <div style="color: #999; font-size: 9px;">\${d.value}</div>+ </div>+ \`);++ // Extract unique ports and airports+ const uniquePorts = new Map();+ oceanRoutes.forEach(route => {+ const startName = route.name.split(' → ')[0];+ const endName = route.name.split(' → ')[1];++ if (!uniquePorts.has(startName)) {+ uniquePorts.set(startName, { lat: route.start.lat, lng: route.start.lng, type: 'port' });+ }+ if (!uniquePorts.has(endName)) {+ uniquePorts.set(endName, { lat: route.end.lat, lng: route.end.lng, type: 'port' });+ }+ });++ const uniqueAirports = new Map();+ airRoutes.forEach(route => {+ const startName = route.name.split(' → ')[0];+ const endName = route.name.split(' → ')[1];++ if (!uniqueAirports.has(startName)) {+ uniqueAirports.set(startName, { lat: route.start.lat, lng: route.start.lng, type: 'airport' });+ }+ if (!uniqueAirports.has(endName)) {+ uniqueAirports.set(endName, { lat: route.end.lat, lng: route.end.lng, type: 'airport' });+ }+ });++ const portPoints = Array.from(uniquePorts.entries()).map(([name, data]) => ({+ lat: data.lat,+ lng: data.lng,+ size: 0.6,+ color: 'rgba(255, 180, 100, 0.85)', // Orange for ports+ label: name,+ type: 'port'+ }));++ const airportPoints = Array.from(uniqueAirports.entries()).map(([name, data]) => ({+ lat: data.lat,+ lng: data.lng,+ size: 0.5,+ color: 'rgba(180, 100, 255, 0.85)', // Purple for airports+ label: name,+ type: 'airport'+ }));++ const allPoints = [...portPoints, ...airportPoints];++ // Professional markers - ports (orange) and airports (purple)+ world.pointsData(allPoints)+ .pointAltitude(0.002)+ .pointRadius('size')+ .pointColor('color')+ .pointLabel((d) => \`+ <div style="background: rgba(10,10,10,0.92); padding: 5px 9px; border-left: 2px solid \${d.color}; font-family: 'Segoe UI', sans-serif; font-size: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.4);">+ <span style="color: #e0e0e0; font-weight: 500;">\${d.type === 'port' ? '⚓' : '✈'} \${d.label}</span>+ </div>+ \`);+ }++ function createShips() {+ // Professional ship visualization using proper globe coordinates+ const shipData = oceanRoutes.map((route, routeIdx) => ({+ routeIdx: routeIdx,+ progress: Math.random(),+ startLat: route.start.lat,+ startLng: route.start.lng,+ endLat: route.end.lat,+ endLng: route.end.lng,+ label: route.name,+ value: route.value,+ vessels: route.vessels+ }));++ // Calculate interpolated positions along great circle arc+ function interpolateArc(startLat, startLng, endLat, endLng, progress) {+ // Simple linear interpolation for latitude and longitude+ const lat = startLat + (endLat - startLat) * progress;+ const lng = startLng + (endLng - startLng) * progress;+ return { lat, lng };+ }++ // Generate ship positions+ function generateShipPoints(shipsData) {+ return shipsData.map(ship => {+ const pos = interpolateArc(+ ship.startLat,+ ship.startLng,+ ship.endLat,+ ship.endLng,+ ship.progress+ );+ return {+ lat: pos.lat,+ lng: pos.lng,+ size: 0.15,+ color: 'rgba(255, 255, 255, 0.95)',+ altitude: 0.003,+ label: ship.label,+ value: ship.value,+ vessels: ship.vessels+ };+ });+ }++ allLabels = shipData;++ // Use customLayerData for ships - they rotate with the globe properly+ const initialShipPoints = generateShipPoints(shipData);+ world.customLayerData(initialShipPoints)+ .customThreeObject(d => {+ // Create diamond/pyramid shape for ship marker (distinct from circular ports)+ const geometry = new THREE.TetrahedronGeometry(0.7);+ const material = new THREE.MeshBasicMaterial({+ color: 0x00ccff,+ transparent: true,+ opacity: 0.9+ });+ const mesh = new THREE.Mesh(geometry, material);++ // Add subtle glow effect+ const glowGeometry = new THREE.SphereGeometry(1.0, 8, 8);+ const glowMaterial = new THREE.MeshBasicMaterial({+ color: 0x00ccff,+ transparent: true,+ opacity: 0.2+ });+ const glow = new THREE.Mesh(glowGeometry, glowMaterial);+ mesh.add(glow);++ return mesh;+ })+ .customThreeObjectUpdate((obj, d) => {+ Object.assign(obj.position, world.getCoords(d.lat, d.lng, d.altitude));+ });++ // Animate ships along routes+ setInterval(() => {+ // Update progress for each ship+ shipData.forEach(ship => {+ ship.progress = (ship.progress + 0.0002) % 1.0;+ });++ // Regenerate ship positions+ const updatedShipPoints = generateShipPoints(shipData);+ world.customLayerData(updatedShipPoints);+ }, 200);+ }++ function createPlanes() {+ // Professional plane visualization using proper globe coordinates+ const planeData = airRoutes.map((route, routeIdx) => ({+ routeIdx: routeIdx,+ progress: Math.random(),+ startLat: route.start.lat,+ startLng: route.start.lng,+ endLat: route.end.lat,+ endLng: route.end.lng,+ label: route.name,+ value: route.value,+ flights: route.flights+ }));++ // Calculate interpolated positions along arc+ function interpolateArc(startLat, startLng, endLat, endLng, progress) {+ const lat = startLat + (endLat - startLat) * progress;+ const lng = startLng + (endLng - startLng) * progress;+ return { lat, lng };+ }++ // Generate plane positions+ function generatePlanePoints(planesData) {+ return planesData.map(plane => {+ const pos = interpolateArc(+ plane.startLat,+ plane.startLng,+ plane.endLat,+ plane.endLng,+ plane.progress+ );+ return {+ lat: pos.lat,+ lng: pos.lng,+ size: 0.15,+ color: 'rgba(255, 200, 100, 0.95)',+ altitude: 0.01, // Higher altitude for planes+ label: plane.label,+ value: plane.value,+ flights: plane.flights+ };+ });+ }++ planeLabels = planeData;++ // Use separate layer for planes+ const initialPlanePoints = generatePlanePoints(planeData);+ world.htmlElementsData(initialPlanePoints)+ .htmlElement(d => {+ const el = document.createElement('div');+ el.innerHTML = '✈';+ el.style.color = 'rgba(255, 200, 100, 0.95)';+ el.style.fontSize = '16px';+ el.style.cursor = 'pointer';+ el.style.filter = 'drop-shadow(0 0 4px rgba(255, 200, 100, 0.8))';+ el.style.transform = 'rotate(-45deg)';+ el.title = \`\${d.label} - \${d.value} (\${d.flights} flights/week)\`;+ return el;+ })+ .htmlAltitude(d => d.altitude);++ // Animate planes along routes (faster than ships)+ setInterval(() => {+ // Update progress for each plane+ planeData.forEach(plane => {+ plane.progress = (plane.progress + 0.0004) % 1.0; // Faster than ships+ });++ // Regenerate plane positions+ const updatedPlanePoints = generatePlanePoints(planeData);+ world.htmlElementsData(updatedPlanePoints);+ }, 200);+ }++ window.addMarker = function(lat, lng, title, type) {+ const icons = {+ 'Ship': '🚢',+ 'Port': '⚓',+ 'Industry': '🏭',+ 'Bank': '🏦',+ 'Exchange': '💱'+ };++ markers.push({ lat, lng, title, type, icon: icons[type] || icons['Ship'] });++ world.htmlElementsData([...allLabels, ...markers])+ .htmlElement(d => {+ const el = document.createElement('div');+ el.innerHTML = d.icon || d.label;+ el.style.color = d.color || '#ff8c00';+ el.style.fontSize = '20px';+ el.style.cursor = 'pointer';+ el.style.textShadow = '0 0 5px ' + (d.color || '#ff8c00');+ el.title = d.title || d.label || '';+ return el;+ });+ };++ window.clearMarkers = function() {+ markers = [];+ world.htmlElementsData(allLabels);+ };++ window.toggleRoutes = function() {+ if (showRoutesFlag) {+ world.arcsData([]);+ } else {+ createRoutes();+ }+ showRoutesFlag = !showRoutesFlag;};- var config = icons[type] || icons['Ship'];- return L.divIcon({- html: '<div style="width:' + size + 'px;height:' + size + 'px;border-radius:50%;background:#0a0a0a;border:3px solid ' + config.color + ';display:flex;align-items:center;justify-content:center;font-size:' + (size-8) + 'px;box-shadow:0 0 20px ' + config.color + ';">' + config.symbol + '</div>',- iconSize: [size, size],- iconAnchor: [size/2, size/2],- className: type === 'Ship' ? 'ship-marker' : ''- });- }- var oceanRoutes = [- { name: "Mumbai-Rotterdam", coords: [[19.0760, 72.8777], [15.0, 60.0], [12.0, 45.0], [15.0, 35.0], [30.0, 32.0], [35.0, 25.0], [38.0, 15.0], [40.0, 5.0], [42.0, -5.0], [45.0, -15.0], [51.9244, 4.4777]], value: "45B USD" },- { name: "Mumbai-Shanghai", coords: [[19.0760, 72.8777], [15.0, 68.0], [10.0, 75.0], [5.0, 85.0], [10.0, 95.0], [20.0, 110.0], [31.2304, 121.4737]], value: "156B USD" },- { name: "Mumbai-Singapore", coords: [[19.0760, 72.8777], [15.0, 75.0], [10.0, 80.0], [5.0, 90.0], [1.3521, 103.8198]], value: "89B USD" },- { name: "Chennai-Tokyo", coords: [[13.0827, 80.2707], [10.0, 90.0], [15.0, 105.0], [25.0, 125.0], [35.6762, 139.6503]], value: "67B USD" },- { name: "Kolkata-Hong Kong", coords: [[22.5726, 88.3639], [18.0, 95.0], [15.0, 105.0], [22.3193, 114.1694]], value: "45B USD" },- { name: "Mumbai-Dubai", coords: [[19.0760, 72.8777], [20.0, 65.0], [23.0, 58.0], [25.2048, 55.2708]], value: "78B USD" },- { name: "Mumbai-New York", coords: [[19.0760, 72.8777], [15.0, 60.0], [10.0, 40.0], [5.0, 20.0], [0.0, 0.0], [10.0, -20.0], [25.0, -40.0], [35.0, -60.0], [40.7128, -74.0060]], value: "123B USD" },- { name: "Chennai-Sydney", coords: [[13.0827, 80.2707], [5.0, 90.0], [-10.0, 105.0], [-25.0, 130.0], [-33.8688, 151.2093]], value: "54B USD" },- { name: "Cochin-Malacca", coords: [[9.9312, 76.2673], [7.0, 79.0], [6.9271, 79.8612], [3.0, 95.0], [1.3521, 103.8198]], value: "34B USD" },- { name: "Mumbai-Cape Town", coords: [[19.0760, 72.8777], [10.0, 60.0], [-5.0, 50.0], [-20.0, 35.0], [-33.9249, 18.4241]], value: "28B USD" }- ];-- function createRoutes() {- if (routesLayer) map.removeLayer(routesLayer);- routesLayer = L.layerGroup();- oceanRoutes.forEach(route => {- var polyline = L.polyline(route.coords, {- color: '#00ffff',- weight: 2,- opacity: 0.8,- className: 'route-animation ocean-route'+ window.toggleShips = function() {+ if (showShipsFlag) {+ world.customLayerData([]);+ } else {+ // Regenerate ship positions+ function interpolateArc(startLat, startLng, endLat, endLng, progress) {+ const lat = startLat + (endLat - startLat) * progress;+ const lng = startLng + (endLng - startLng) * progress;+ return { lat, lng };+ }++ const shipPoints = allLabels.map(ship => {+ const pos = interpolateArc(ship.startLat, ship.startLng, ship.endLat, ship.endLng, ship.progress);+ return {+ lat: pos.lat,+ lng: pos.lng,+ size: 0.15,+ color: 'rgba(255, 255, 255, 0.95)',+ altitude: 0.003,+ label: ship.label,+ value: ship.value,+ vessels: ship.vessels+ };+ });+ world.customLayerData(shipPoints);+ }+ showShipsFlag = !showShipsFlag;+ };++ window.togglePlanes = function() {+ if (showPlanesFlag) {+ world.htmlElementsData([]);+ } else {+ // Regenerate plane positions+ function interpolateArc(startLat, startLng, endLat, endLng, progress) {+ const lat = startLat + (endLat - startLat) * progress;+ const lng = startLng + (endLng - startLng) * progress;+ return { lat, lng };+ }++ const planePoints = planeLabels.map(plane => {+ const pos = interpolateArc(plane.startLat, plane.startLng, plane.endLat, plane.endLng, plane.progress);+ return {+ lat: pos.lat,+ lng: pos.lng,+ size: 0.15,+ color: 'rgba(255, 200, 100, 0.95)',+ altitude: 0.01,+ label: plane.label,+ value: plane.value,+ flights: plane.flights+ };+ });+ world.htmlElementsData(planePoints);+ }+ showPlanesFlag = !showPlanesFlag;+ };++ window.toggleRotation = function(shouldRotate) {+ userPausedRotation = !shouldRotate;+ world.controls().autoRotate = shouldRotate;+ console.log('Globe rotation:', shouldRotate ? 'enabled' : 'disabled');+ };++ // Enable auto-rotation with enhanced zoom+ world.controls().autoRotate = true;+ world.controls().autoRotateSpeed = 0.2; // Slower, more professional rotation+ world.controls().enableDamping = true;+ world.controls().dampingFactor = 0.05;++ // Allow deep zoom but not too extreme on 3D globe+ world.controls().minDistance = 50; // Don't go too close on 3D (will switch to 2D)+ world.controls().maxDistance = 800; // Very far zoom (space view)+ world.controls().zoomSpeed = 1.5; // Faster zoom for better control+ world.controls().enableZoom = true;++ console.log('Controls configured');++ // Keep rotation state controlled by user toggle+ let userPausedRotation = false;+ let interactionTimeout;+ const resumeRotation = () => {+ clearTimeout(interactionTimeout);+ world.controls().autoRotate = false;+ interactionTimeout = setTimeout(() => {+ // Only resume if user hasn't manually paused+ if (!userPausedRotation) {+ world.controls().autoRotate = true;+ }+ }, 3000); // Resume after 3 seconds of inactivity (only if not manually paused)+ };++ // Function to switch between 3D and 2D modes+ function switchTo2D(lat, lng) {+ if (currentMode === '2D') return; // Prevent multiple switches++ // Use the most recent target coordinates (where user was actually looking)+ const finalLat = targetCoords.lat;+ const finalLng = targetCoords.lng;++ initMap2D(); // Initialize if needed++ document.getElementById('globeViz').style.display = 'none';+ document.getElementById('mapViz').style.display = 'block';+ document.getElementById('modeIndicator').textContent = '2D MAP MODE - Street Level';+ document.getElementById('modeIndicator').style.background = 'rgba(255, 215, 0, 0.9)';++ // Calculate zoom based on altitude (lower altitude = higher zoom)+ // More aggressive zoom calculation for better street detail+ const altitudeFactor = Math.max(0, 0.3 - lastGlobeView.altitude);+ const zoom2D = Math.max(14, Math.min(18, Math.floor(16 + altitudeFactor * 20)));++ console.log('Switching to 2D - Final coords:', finalLat.toFixed(6), finalLng.toFixed(6), 'zoom:', zoom2D);++ // Set view and force map refresh+ setTimeout(() => {+ map2D.setView([finalLat, finalLng], zoom2D);+ map2D.invalidateSize();++ // Force tile refresh+ setTimeout(() => {+ map2D.eachLayer(function(layer) {+ if (layer instanceof L.TileLayer) {+ layer.redraw();+ }+ });+ console.log('2D map centered at:', finalLat.toFixed(6), finalLng.toFixed(6));+ }, 100);+ }, 50);++ currentMode = '2D';+ }++ function switchTo3D(lat, lng, altitude) {+ document.getElementById('globeViz').style.display = 'block';+ document.getElementById('mapViz').style.display = 'none';+ document.getElementById('modeIndicator').textContent = '3D GLOBE MODE';+ document.getElementById('modeIndicator').style.background = 'rgba(0, 255, 255, 0.9)';++ world.pointOfView({ lat, lng, altitude }, 500);+ currentMode = '3D';+ console.log('Switched to 3D mode at altitude:', altitude);+ }++ // Monitor zoom level and switch modes+ world.onZoom((view) => {+ lastGlobeView = view;+ targetCoords = { lat: view.lat, lng: view.lng };+ console.log('Globe zoom - altitude:', view.altitude, 'lat:', view.lat.toFixed(4), 'lng:', view.lng.toFixed(4));++ if (view.altitude < ZOOM_THRESHOLD && currentMode === '3D') {+ console.log('Triggering switch to 2D at exact position:', view.lat, view.lng);+ switchTo2D(view.lat, view.lng);+ }});- polyline.bindPopup('<div style="background:#000;color:#0ff;padding:8px;border:1px solid #0ff;font-family:Consolas;font-size:10px;"><b>' + route.name + '</b><br/>Value: ' + route.value + '</div>');- routesLayer.addLayer(polyline);- });- map.addLayer(routesLayer);- }- function createShips() {- if (shipsLayer) map.removeLayer(shipsLayer);- shipsLayer = L.layerGroup();- oceanRoutes.forEach(route => {- for (var i = 1; i < route.coords.length - 1; i += 2) {- var ship = L.marker(route.coords[i], { icon: createIcon('Ship', 28) });- ship.bindPopup('<div style="background:#000;color:#1e90ff;padding:8px;border:1px solid #1e90ff;font-family:Consolas;font-size:10px;"><b>🚢 VESSEL</b><br/>Route: ' + route.name.split('-')[0] + '<br/>Speed: ' + (Math.floor(Math.random()*10+15)) + ' knots</div>');- shipsLayer.addLayer(ship);+ // Listen for user interactions+ const container = document.getElementById('globeViz');++ // Track mouse position for accurate zoom targeting+ let mousePos = null;+ container.addEventListener('mousemove', (e) => {+ mousePos = { x: e.clientX, y: e.clientY };+ });++ // Get lat/lng from screen coordinates+ function getLatLngFromScreen(x, y) {+ try {+ const scene = world.scene();+ const camera = world.camera();+ const raycaster = new THREE.Raycaster();+ const mouse = new THREE.Vector2(+ (x / window.innerWidth) * 2 - 1,+ -(y / window.innerHeight) * 2 + 1+ );++ raycaster.setFromCamera(mouse, camera);+ const intersects = raycaster.intersectObject(scene.children.find(c => c.type === 'Mesh'), true);++ if (intersects.length > 0) {+ const point = intersects[0].point;+ const lat = Math.asin(point.y / Math.sqrt(point.x * point.x + point.y * point.y + point.z * point.z)) * 180 / Math.PI;+ const lng = Math.atan2(point.x, point.z) * 180 / Math.PI;+ return { lat, lng };+ }+ } catch (e) {+ console.log('Could not get exact coordinates, using view center');+ }+ return null;}- });- map.addLayer(shipsLayer);- }+ container.addEventListener('mousedown', resumeRotation);+ container.addEventListener('wheel', (e) => {+ resumeRotation();++ // Update target coords based on mouse position+ if (mousePos) {+ const coords = getLatLngFromScreen(mousePos.x, mousePos.y);+ if (coords) {+ targetCoords = coords;+ console.log('Updated target from mouse:', targetCoords.lat.toFixed(4), targetCoords.lng.toFixed(4));+ }+ }+ });+ container.addEventListener('touchstart', resumeRotation);++ // Start with auto-rotation enabled+ world.controls().autoRotate = true;- window.addMarker = function(lat, lng, title, type) {- var marker = L.marker([lat, lng], { icon: createIcon(type, 28) });- marker.bindPopup('<div style="background:#000;color:#ff8c00;padding:8px;border:1px solid #ff8c00;font-family:Consolas;font-size:10px;"><b>' + title + '</b><br/>Type: ' + type + '<br/>Coords: ' + lat.toFixed(4) + ', ' + lng.toFixed(4) + '</div>');- marker.addTo(map);- markers.push(marker);- };-- window.clearMarkers = function() {- markers.forEach(m => map.removeLayer(m));- markers = [];- };-- window.toggleRoutes = function() {- if (map.hasLayer(routesLayer)) map.removeLayer(routesLayer);- else createRoutes();- };-- window.toggleShips = function() {- if (map.hasLayer(shipsLayer)) map.removeLayer(shipsLayer);- else createShips();- };-- createRoutes();- createShips();+ console.log('Event listeners added');++ createRoutes();+ createShips();+ createPlanes();++ // Handle window resize+ window.addEventListener('resize', () => {+ world.width(window.innerWidth).height(window.innerHeight);+ });++ console.log('3D Globe fully initialized');+ } catch (error) {+ console.error('Error initializing Globe:', error);+ document.body.innerHTML = '<div style="color: red; padding: 20px; font-family: monospace;">ERROR: Failed to load 3D Globe<br>Check console for details<br><br>' + error.message + '</div>';+ }+ }, 500); // Wait 500ms for libraries to load</script></body></html>@@ -228,6 +807,28 @@ export default function MaritimeTab() {<span style={{ color: '#0ff', fontSize: '10px' }}>CLASSIFIED // TRADE ROUTE ANALYSIS</span></div><div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>+ <button+ onClick={() => {+ const newRotating = !isRotating;+ setIsRotating(newRotating);+ if (mapRef.current?.contentWindow) {+ (mapRef.current.contentWindow as any).toggleRotation?.(newRotating);+ }+ }}+ style={{+ background: isRotating ? '#0a0a0a' : '#1a1a1a',+ color: isRotating ? '#00ff00' : '#888',+ border: `1px solid ${isRotating ? '#00ff00' : '#444'}`,+ padding: '4px 10px',+ fontSize: '9px',+ cursor: 'pointer',+ fontWeight: 'bold',+ fontFamily: 'Consolas, monospace',+ transition: 'all 0.2s'+ }}+ >+ {isRotating ? '● ROTATING' : '○ PAUSED'}+ </button><span style={{ color: intelligence.threat_level === 'critical' ? '#ff0000' : intelligence.threat_level === 'high' ? '#ff8c00' : intelligence.threat_level === 'medium' ? '#ffd700' : '#00ff00', fontSize: '10px', fontWeight: 'bold' }}>THREAT: {intelligence.threat_level.toUpperCase()}</span>@@ -343,6 +944,28 @@ export default function MaritimeTab() {VESSELS</button></div>+ <div style={{ display: 'flex', gap: '6px', marginBottom: '6px' }}>+ <button+ onClick={() => {+ setShowPlanes(!showPlanes);+ if (mapRef.current?.contentWindow) {+ (mapRef.current.contentWindow as any).togglePlanes?.();+ }+ }}+ style={{+ flex: 1,+ background: showPlanes ? 'rgba(255, 200, 100, 0.9)' : '#0a0a0a',+ color: showPlanes ? '#000' : 'rgba(255, 200, 100, 0.9)',+ border: '1px solid rgba(255, 200, 100, 0.9)',+ padding: '6px',+ fontSize: '9px',+ cursor: 'pointer',+ fontWeight: 'bold'+ }}+ >+ AIRCRAFT+ </button>+ </div><buttononClick={() => {clearMarkers();@@ -390,9 +1013,10 @@ export default function MaritimeTab() {fontSize: '9px',fontFamily: 'Consolas, monospace'}}>- <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>SATELLITE UPLINK ACTIVE</div>+ <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>HYBRID 3D/2D SYSTEM ACTIVE</div><div>CENTER: 20.0000° N, 75.0000° E</div>- <div>ZOOM: 4 | TILES: ESRI World Imagery</div>+ <div>MODE: Globe.GL 3D → Auto-switches → Leaflet 2D</div>+ <div style={{ marginTop: '4px', color: '#ffd700' }}>🔍 ZOOM: Deep zoom auto-switches to street-level map!</div></div></div>@@ -520,13 +1144,13 @@ export default function MaritimeTab() {<div style={{ color: '#00ff00', fontSize: '9px', fontWeight: 'bold', marginBottom: '6px' }}>SYSTEM STATUS</div><div style={{ fontSize: '8px', color: '#888', lineHeight: '1.4' }}><div style={{ marginBottom: '4px' }}>- <span style={{ color: '#0ff' }}>●</span> Satellite feed: ACTIVE+ <span style={{ color: '#0ff' }}>●</span> 3D Globe: ACTIVE</div><div style={{ marginBottom: '4px' }}>- <span style={{ color: '#0ff' }}>●</span> AIS transponders: ONLINE+ <span style={{ color: '#0ff' }}>●</span> Satellite imagery: ONLINE</div><div style={{ marginBottom: '4px' }}>- <span style={{ color: '#0ff' }}>●</span> Trade data: STREAMING+ <span style={{ color: '#0ff' }}>●</span> AIS transponders: STREAMING</div><div style={{ marginTop: '8px', padding: '6px', background: '#000', border: '1px solid #1a1a1a', color: '#ffd700' }}>⚠ CLASSIFIED: For authorized personnel only@@ -559,7 +1183,7 @@ export default function MaritimeTab() {<span style={{ color: '#0ff', whiteSpace: 'nowrap' }}>Data Latency: 2.3ms</span></div><div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '9px', flexWrap: 'wrap' }}>- <span style={{ color: '#888', whiteSpace: 'nowrap' }}>Powered by Leaflet.js + ESRI Imagery</span>+ <span style={{ color: '#888', whiteSpace: 'nowrap' }}>Powered by Globe.GL 3D Visualization</span><span style={{ color: '#888' }}>|</span><span style={{ color: '#ffd700', whiteSpace: 'nowrap' }}>CLEARANCE: TOP SECRET // SCI</span></div>diff --git a/fincept-terminal-desktop/src/components/tabs/PolygonEqTab.tsx b/fincept-terminal-desktop/src/components/tabs/PolygonEqTab.tsxindex fdd04cd25..8554acef0 100644--- a/fincept-terminal-desktop/src/components/tabs/PolygonEqTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/PolygonEqTab.tsx@@ -10,9 +10,10 @@ const COLORS = {GRAY: '#787878',BLUE: '#6496FA',CYAN: '#00FFFF',- DARK_BG: '#1a1a1a',+ DARK_BG: '#0a0a0a',PANEL_BG: '#000000',- BORDER: '#333333',+ BORDER: '#222222',+ PANEL_HEADER_BG: '#1a1a1a',};const PolygonEqTab: React.FC = () => {@@ -21,43 +22,58 @@ const PolygonEqTab: React.FC = () => {const [loading, setLoading] = useState(false);const [apiKeyConfigured, setApiKeyConfigured] = useState(false);const [error, setError] = useState<string | null>(null);+ const [activeTab, setActiveTab] = useState<'financials' | 'actions' | 'short' | 'market' | 'reference'>('financials');- // First 5 endpoints data states+ // All data states (31 endpoints)const [tickerDetails, setTickerDetails] = useState<any>(null);const [snapshot, setSnapshot] = useState<any>(null);const [news, setNews] = useState<any[]>([]);const [relatedTickers, setRelatedTickers] = useState<any[]>([]);const [marketStatus, setMarketStatus] = useState<any>(null);-- // Next 5 endpoints data states (Phase 2)const [dividends, setDividends] = useState<any[]>([]);const [splits, setSplits] = useState<any[]>([]);const [lastTrade, setLastTrade] = useState<any>(null);const [lastQuote, setLastQuote] = useState<any>(null);const [smaData, setSmaData] = useState<any>(null);-- // Phase 3 endpoints data statesconst [emaData, setEmaData] = useState<any>(null);const [macdData, setMacdData] = useState<any>(null);const [rsiData, setRsiData] = useState<any>(null);const [incomeStmt, setIncomeStmt] = useState<any>(null);const [balanceSheet, setBalanceSheet] = useState<any>(null);+ const [allTickers, setAllTickers] = useState<any[]>([]);+ const [tickerTypes, setTickerTypes] = useState<any[]>([]);+ const [tickerEvents, setTickerEvents] = useState<any>(null);+ const [exchanges, setExchanges] = useState<any[]>([]);+ const [conditionCodes, setConditionCodes] = useState<any[]>([]);+ const [marketHolidays, setMarketHolidays] = useState<any[]>([]);+ const [marketStatusFull, setMarketStatusFull] = useState<any>(null);+ const [smaFull, setSmaFull] = useState<any>(null);+ const [emaFull, setEmaFull] = useState<any>(null);+ const [macdFull, setMacdFull] = useState<any>(null);+ const [cashFlowStatements, setCashFlowStatements] = useState<any>(null);+ const [financialRatios, setFinancialRatios] = useState<any>(null);+ const [shortInterest, setShortInterest] = useState<any>(null);+ const [shortVolume, setShortVolume] = useState<any>(null);+ const [trades, setTrades] = useState<any>(null);+ const [quotes, setQuotes] = useState<any>(null);useEffect(() => {- const apiKey = polygonService.getApiKey();- setApiKeyConfigured(!!apiKey);+ const loadApiKey = async () => {+ const apiKey = await polygonService.loadApiKey();+ setApiKeyConfigured(!!apiKey);+ };+ loadApiKey();}, []);- const handleConfigureApiKey = () => {- const key = prompt('Enter your Polygon.io API key:');- if (key && key.trim()) {- polygonService.setApiKey(key.trim());- setApiKeyConfigured(true);- fetchAllData();+ const handleGoToSettings = () => {+ const settingsTab = document.querySelector('[data-tab="settings"]') as HTMLElement;+ if (settingsTab) {+ settingsTab.click();}};const fetchAllData = async () => {+ await polygonService.loadApiKey();if (!apiKeyConfigured) return;console.log('=== FETCHING DATA FOR:', symbol, '===');@@ -65,196 +81,131 @@ const PolygonEqTab: React.FC = () => {setError(null);try {- // Fetch first 15 endpoints in parallel (Phase 1 + Phase 2 + Phase 3)const [- detailsResp,- snapResp,- newsResp,- relatedResp,- marketStatusResp,- dividendsResp,- splitsResp,- lastTradeResp,- lastQuoteResp,- smaResp,- emaResp,- macdResp,- rsiResp,- incomeResp,- balanceResp,+ detailsResp, snapResp, newsResp, relatedResp, marketStatusResp,+ dividendsResp, splitsResp, lastTradeResp, lastQuoteResp, smaResp,+ emaResp, macdResp, rsiResp, incomeResp, balanceResp,+ allTickersResp, tickerTypesResp, tickerEventsResp, exchangesResp, conditionCodesResp,+ marketHolidaysResp, marketStatusFullResp, smaFullResp, emaFullResp, macdFullResp,+ cashFlowResp, financialRatiosResp, shortInterestResp, shortVolumeResp, tradesResp, quotesResp,] = await Promise.all([- // Phase 1 endpoints- polygonService.getTickerDetails(symbol).catch((e) => {- console.error('Ticker details error:', e);- return { success: false, error: e.message };- }),- polygonService.getSingleTickerSnapshot(symbol).catch((e) => {- console.error('Snapshot error:', e);- return { success: false, error: e.message };- }),- polygonService.getNews({ ticker: symbol, limit: 10 }).catch((e) => {- console.error('News error:', e);- return { success: false, error: e.message };- }),- polygonService.getRelatedTickers(symbol).catch((e) => {- console.error('Related tickers error:', e);- return { success: false, error: e.message };- }),- polygonService.getMarketStatus().catch((e) => {- console.error('Market status error:', e);- return { success: false, error: e.message };- }),- // Phase 2 endpoints- polygonService.getDividends({ ticker: symbol, limit: 10 }).catch((e) => {- console.error('Dividends error:', e);- return { success: false, error: e.message };- }),- polygonService.getSplits({ ticker: symbol, limit: 10 }).catch((e) => {- console.error('Splits error:', e);- return { success: false, error: e.message };- }),- polygonService.getLastTrade(symbol).catch((e) => {- console.error('Last trade error:', e);- return { success: false, error: e.message };- }),- polygonService.getLastQuote(symbol).catch((e) => {- console.error('Last quote error:', e);- return { success: false, error: e.message };- }),- polygonService.getSMA(symbol, { window: 20, timespan: 'day', limit: 50 }).catch((e) => {- console.error('SMA error:', e);- return { success: false, error: e.message };- }),- // Phase 3 endpoints- polygonService.getEMA(symbol, { window: 20, timespan: 'day', limit: 50 }).catch((e) => {- console.error('EMA error:', e);- return { success: false, error: e.message };- }),- polygonService.getMACD(symbol, { shortWindow: 12, longWindow: 26, signalWindow: 9, timespan: 'day', limit: 50 }).catch((e) => {- console.error('MACD error:', e);- return { success: false, error: e.message };- }),- polygonService.getRSI(symbol, { window: 14, timespan: 'day', limit: 50 }).catch((e) => {- console.error('RSI error:', e);- return { success: false, error: e.message };- }),- polygonService.getIncomeStatements(symbol, { timeframe: 'annual', limit: 5 }).catch((e) => {- console.error('Income statements error:', e);- return { success: false, error: e.message };- }),- polygonService.getBalanceSheets(symbol, { timeframe: 'annual', limit: 5 }).catch((e) => {- console.error('Balance sheets error:', e);- return { success: false, error: e.message };- }),+ polygonService.getTickerDetails(symbol).catch((e) => ({ success: false, error: e.message })),+ polygonService.getSingleTickerSnapshot(symbol).catch((e) => ({ success: false, error: e.message })),+ polygonService.getNews({ ticker: symbol, limit: 10 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getRelatedTickers(symbol).catch((e) => ({ success: false, error: e.message })),+ polygonService.getMarketStatus().catch((e) => ({ success: false, error: e.message })),+ polygonService.getDividends({ ticker: symbol, limit: 10 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getSplits({ ticker: symbol, limit: 10 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getLastTrade(symbol).catch((e) => ({ success: false, error: e.message })),+ polygonService.getLastQuote(symbol).catch((e) => ({ success: false, error: e.message })),+ polygonService.getSMA(symbol, { window: 20, timespan: 'day', limit: 50 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getEMA(symbol, { window: 20, timespan: 'day', limit: 50 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getMACD(symbol, { shortWindow: 12, longWindow: 26, signalWindow: 9, timespan: 'day', limit: 50 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getRSI(symbol, { window: 14, timespan: 'day', limit: 50 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getIncomeStatements(symbol, { timeframe: 'annual', limit: 5 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getBalanceSheets(symbol, { timeframe: 'annual', limit: 5 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getAllTickers({ search: symbol, limit: 10 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getTickerTypes().catch((e) => ({ success: false, error: e.message })),+ polygonService.getTickerEvents(symbol).catch((e) => ({ success: false, error: e.message })),+ polygonService.getExchanges().catch((e) => ({ success: false, error: e.message })),+ polygonService.getConditionCodes({ limit: 20 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getMarketHolidays().catch((e) => ({ success: false, error: e.message })),+ polygonService.getMarketStatus().catch((e) => ({ success: false, error: e.message })),+ polygonService.getSMA(symbol, { window: 50, timespan: 'day', limit: 100 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getEMA(symbol, { window: 50, timespan: 'day', limit: 100 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getMACD(symbol, { shortWindow: 12, longWindow: 26, signalWindow: 9, timespan: 'day', limit: 100 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getCashFlowStatements(symbol, { timeframe: 'annual', limit: 5 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getFinancialRatios(symbol, { limit: 10 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getShortInterest(symbol, { limit: 10 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getShortVolume(symbol, { limit: 10 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getTrades(symbol, { limit: 10 }).catch((e) => ({ success: false, error: e.message })),+ polygonService.getQuotes(symbol, { limit: 10 }).catch((e) => ({ success: false, error: e.message })),]);- // Parse Ticker Details- if (detailsResp?.success && detailsResp?.ticker_details) {- setTickerDetails(detailsResp.ticker_details);- }-- // Parse Snapshot- if (snapResp?.success && snapResp?.snapshot) {- setSnapshot(snapResp.snapshot);- }-- // Parse News- if (newsResp?.success && newsResp?.news_articles) {- setNews(newsResp.news_articles);- } else {- setNews([]);- }+ // Parse all responses+ if (detailsResp?.success && detailsResp?.ticker_details) setTickerDetails(detailsResp.ticker_details);+ if (snapResp?.success && snapResp?.snapshot) setSnapshot(snapResp.snapshot);+ if (newsResp?.success && newsResp?.news_articles) setNews(newsResp.news_articles);+ else setNews([]);- // Parse Related Tickersif (relatedResp?.success && relatedResp?.related_tickers) {- // Convert string array to object array with ticker property- const tickersArray = relatedResp.related_tickers.map((ticker: any) => {- if (typeof ticker === 'string') {- return { ticker: ticker, name: null };- }- return ticker;- });+ const tickersArray = relatedResp.related_tickers.map((ticker: any) =>+ typeof ticker === 'string' ? { ticker: ticker, name: null } : ticker+ );setRelatedTickers(tickersArray);- } else {- setRelatedTickers([]);- }+ } else setRelatedTickers([]);- // Parse Market Status- if (marketStatusResp?.success && marketStatusResp?.market_status) {- setMarketStatus(marketStatusResp.market_status);- }+ if (marketStatusResp?.success && marketStatusResp?.market_status) setMarketStatus(marketStatusResp.market_status);+ if (dividendsResp?.success && dividendsResp?.dividends) setDividends(dividendsResp.dividends);+ else setDividends([]);- // Parse Dividends- if (dividendsResp?.success && dividendsResp?.dividends) {- setDividends(dividendsResp.dividends);- } else {- setDividends([]);- }+ if (splitsResp?.success && splitsResp?.splits) setSplits(splitsResp.splits);+ else setSplits([]);- // Parse Splits- if (splitsResp?.success && splitsResp?.splits) {- setSplits(splitsResp.splits);- } else {- setSplits([]);- }+ if (lastTradeResp?.success && lastTradeResp?.last_trade) setLastTrade(lastTradeResp.last_trade);+ if (lastQuoteResp?.success && lastQuoteResp?.last_quote) setLastQuote(lastQuoteResp.last_quote);+ if (smaResp?.success && smaResp?.sma_data) setSmaData(smaResp.sma_data);+ if (emaResp?.success && emaResp?.ema_data) setEmaData(emaResp.ema_data);+ if (macdResp?.success && macdResp?.macd_data) setMacdData(macdResp.macd_data);+ if (rsiResp?.success && rsiResp?.rsi_data) setRsiData(rsiResp.rsi_data);- // Parse Last Trade- if (lastTradeResp?.success && lastTradeResp?.last_trade) {- setLastTrade(lastTradeResp.last_trade);+ if (incomeResp?.success && incomeResp?.income_statement_data) {+ setIncomeStmt(incomeResp.income_statement_data);}- // Parse Last Quote- if (lastQuoteResp?.success && lastQuoteResp?.last_quote) {- setLastQuote(lastQuoteResp.last_quote);+ if (balanceResp?.success && balanceResp?.balance_sheet_data) {+ setBalanceSheet(balanceResp.balance_sheet_data);}- // Parse SMA- if (smaResp?.success && smaResp?.sma_data) {- setSmaData(smaResp.sma_data);- }+ if (allTickersResp?.success && allTickersResp?.tickers) setAllTickers(allTickersResp.tickers);+ else setAllTickers([]);- // Parse EMA- if (emaResp?.success && emaResp?.ema_data) {- setEmaData(emaResp.ema_data);- }+ if (tickerTypesResp?.success && tickerTypesResp?.ticker_types) setTickerTypes(tickerTypesResp.ticker_types);+ else setTickerTypes([]);- // Parse MACD - DEBUG ONLY- console.log('=== MACD DEBUG ===');- console.log('MACD Response:', JSON.stringify(macdResp, null, 2));- if (macdResp?.success && macdResp?.macd_data) {- console.log('MACD data structure:', JSON.stringify(macdResp.macd_data, null, 2));- console.log('MACD statistics:', macdResp.macd_data.statistics);- setMacdData(macdResp.macd_data);- } else {- console.error('MACD failed:', macdResp?.error);- }+ if (tickerEventsResp?.success && tickerEventsResp?.ticker_events) setTickerEvents(tickerEventsResp.ticker_events);+ else setTickerEvents(null);- // Parse RSI- if (rsiResp?.success && rsiResp?.rsi_data) {- setRsiData(rsiResp.rsi_data);- }+ if (exchangesResp?.success && exchangesResp?.exchanges) setExchanges(exchangesResp.exchanges);+ else setExchanges([]);- // Parse Income Statements - DEBUG ONLY- console.log('=== INCOME STATEMENTS DEBUG ===');- console.log('Income Response:', JSON.stringify(incomeResp, null, 2));- if (incomeResp?.success && incomeResp?.income_statement_data) {- console.log('Income statement structure:', JSON.stringify(incomeResp.income_statement_data, null, 2));- setIncomeStmt(incomeResp.income_statement_data);- } else {- console.error('Income statements failed:', incomeResp?.error);- }+ if (conditionCodesResp?.success && conditionCodesResp?.condition_codes) setConditionCodes(conditionCodesResp.condition_codes);+ else setConditionCodes([]);- // Parse Balance Sheets - DEBUG ONLY- console.log('=== BALANCE SHEETS DEBUG ===');- console.log('Balance Response:', JSON.stringify(balanceResp, null, 2));- if (balanceResp?.success && balanceResp?.balance_sheet_data) {- console.log('Balance sheet structure:', JSON.stringify(balanceResp.balance_sheet_data, null, 2));- setBalanceSheet(balanceResp.balance_sheet_data);- } else {- console.error('Balance sheets failed:', balanceResp?.error);- }+ if (marketHolidaysResp?.success && marketHolidaysResp?.market_holidays) setMarketHolidays(marketHolidaysResp.market_holidays);+ else setMarketHolidays([]);++ if (marketStatusFullResp?.success && marketStatusFullResp?.market_status) setMarketStatusFull(marketStatusFullResp.market_status);+ else setMarketStatusFull(null);++ if (smaFullResp?.success && smaFullResp?.sma_data) setSmaFull(smaFullResp.sma_data);+ else setSmaFull(null);++ if (emaFullResp?.success && emaFullResp?.ema_data) setEmaFull(emaFullResp.ema_data);+ else setEmaFull(null);++ if (macdFullResp?.success && macdFullResp?.macd_data) setMacdFull(macdFullResp.macd_data);+ else setMacdFull(null);- console.log('=== DATA FETCH COMPLETE ===');+ if (cashFlowResp?.success) setCashFlowStatements(cashFlowResp);+ else setCashFlowStatements(null);++ if (financialRatiosResp?.success) setFinancialRatios(financialRatiosResp);+ else setFinancialRatios(null);++ if (shortInterestResp?.success) setShortInterest(shortInterestResp);+ else setShortInterest(null);++ if (shortVolumeResp?.success) setShortVolume(shortVolumeResp);+ else setShortVolume(null);++ if (tradesResp?.success) setTrades(tradesResp);+ else setTrades(null);++ if (quotesResp?.success) setQuotes(quotesResp);+ else setQuotes(null);++ console.log('=== DATA FETCH COMPLETE (31/31 ENDPOINTS) ===');} catch (error: any) {console.error('Critical error:', error);@@ -278,7 +229,6 @@ const PolygonEqTab: React.FC = () => {};const handleRelatedTickerClick = (ticker: string) => {- console.log('Clicked related ticker:', ticker);setSymbol(ticker);};@@ -292,9 +242,11 @@ const PolygonEqTab: React.FC = () => {if (num >= 1e12) return `$${(num / 1e12).toFixed(2)}T`;if (num >= 1e9) return `$${(num / 1e9).toFixed(2)}B`;if (num >= 1e6) return `$${(num / 1e6).toFixed(2)}M`;+ if (num >= 1e3) return `$${(num / 1e3).toFixed(2)}K`;return `$${num.toFixed(2)}`;};+ // API Key Config Screenif (!apiKeyConfigured) {return (<div style={{@@ -310,19 +262,26 @@ const PolygonEqTab: React.FC = () => {backgroundColor: COLORS.PANEL_BG,border: `2px solid ${COLORS.ORANGE}`,padding: '40px',- maxWidth: '500px',+ maxWidth: '600px',textAlign: 'center',}}><div style={{ color: COLORS.ORANGE, fontSize: '24px', fontWeight: 'bold', marginBottom: '20px' }}>POLYGON.IO API KEY REQUIRED</div>- <div style={{ color: COLORS.GRAY, fontSize: '14px', marginBottom: '20px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '14px', marginBottom: '20px', lineHeight: '1.6' }}>Configure your Polygon.io API key to access institutional-grade financial data.<br /><br />- Get your API key at: <span style={{ color: COLORS.CYAN }}>polygon.io</span>+ <strong style={{ color: COLORS.CYAN }}>Steps to configure:</strong>+ <ol style={{ textAlign: 'left', marginTop: '10px', paddingLeft: '40px' }}>+ <li>Get your free API key at: <span style={{ color: COLORS.CYAN }}>polygon.io</span></li>+ <li>Go to Settings → Credentials section</li>+ <li>Add new API key with service name: <span style={{ color: COLORS.CYAN }}>Polygon.io</span></li>+ <li>Paste your API key and save</li>+ <li>Return to this tab and refresh</li>+ </ol></div><button- onClick={handleConfigureApiKey}+ onClick={handleGoToSettings}style={{backgroundColor: COLORS.ORANGE,border: 'none',@@ -333,26 +292,48 @@ const PolygonEqTab: React.FC = () => {fontWeight: 'bold',}}>- CONFIGURE API KEY+ GO TO SETTINGS</button></div></div>);}- // Calculate price change - use todays_change if available, otherwise calculate from prev_day+ // Calculate price changeconst currentPrice = snapshot?.day?.close || snapshot?.prev_day?.close || 0;const prevClose = snapshot?.prev_day?.close || 0;-let priceChange = snapshot?.todays_change || 0;let priceChangePercent = snapshot?.todays_change_perc || 0;- // If todays_change is 0 but we have current and previous prices, calculate manuallyif (priceChange === 0 && currentPrice > 0 && prevClose > 0) {priceChange = currentPrice - prevClose;priceChangePercent = ((priceChange / prevClose) * 100);}+ // Section Header Component+ const SectionHeader: React.FC<{ title: string; color?: string }> = ({ title, color = COLORS.ORANGE }) => (+ <div style={{+ backgroundColor: COLORS.PANEL_HEADER_BG,+ borderBottom: `1px solid ${color}`,+ padding: '6px 10px',+ color: color,+ fontSize: '12px',+ fontWeight: 'bold',+ letterSpacing: '0.5px',+ }}>+ {title}+ </div>+ );++ // Data Row Component+ const DataRow: React.FC<{ label: string; value: string | number; valueColor?: string; small?: boolean }> =+ ({ label, value, valueColor = COLORS.WHITE, small = false }) => (+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: small ? '3px' : '6px', fontSize: small ? '11px' : '12px' }}>+ <span style={{ color: COLORS.GRAY }}>{label}:</span>+ <span style={{ color: valueColor, fontWeight: 'bold' }}>{value}</span>+ </div>+ );+return (<div style={{height: '100%',@@ -361,33 +342,37 @@ const PolygonEqTab: React.FC = () => {fontFamily: 'Consolas, monospace',display: 'flex',flexDirection: 'column',- fontSize: '13px',- overflow: 'hidden',- }}>- {/* Header */}+ fontSize: '12px',+ overflow: 'auto',+ }} className="custom-scrollbar">++ {/* TOP BAR WITH RELATED TICKERS */}<div style={{backgroundColor: COLORS.PANEL_BG,borderBottom: `1px solid ${COLORS.BORDER}`,- padding: '10px 15px',+ padding: '8px 12px',+ display: 'flex',+ flexDirection: 'column',+ gap: '8px',flexShrink: 0,}}>- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>- <span style={{ color: COLORS.ORANGE, fontWeight: 'bold', fontSize: '16px' }}>POLYGON.IO TERMINAL</span>- <span style={{ color: COLORS.GRAY }}>|</span>+ {/* First Row: Search and Main Info */}+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <span style={{ color: COLORS.ORANGE, fontWeight: 'bold', fontSize: '13px' }}>POLYGON.IO</span><inputtype="text"value={searchInput}onChange={(e) => setSearchInput(e.target.value)}onKeyPress={(e) => e.key === 'Enter' && handleSearch()}- placeholder="Enter symbol..."+ placeholder="Symbol..."style={{backgroundColor: COLORS.DARK_BG,border: `1px solid ${COLORS.BORDER}`,color: COLORS.WHITE,- padding: '6px 12px',- fontSize: '13px',- width: '180px',+ padding: '4px 10px',+ fontSize: '12px',+ width: '120px',fontFamily: 'Consolas, monospace',}}/>@@ -397,28 +382,37 @@ const PolygonEqTab: React.FC = () => {backgroundColor: COLORS.ORANGE,border: 'none',color: COLORS.DARK_BG,- padding: '6px 18px',- fontSize: '13px',+ padding: '4px 14px',+ fontSize: '11px',cursor: 'pointer',fontWeight: 'bold',}}>- SEARCH+ GO</button></div>- <div style={{ display: 'flex', alignItems: 'center', gap: '15px', fontSize: '13px' }}>- <span style={{ color: COLORS.CYAN, fontWeight: 'bold', fontSize: '18px' }}>{symbol}</span>- {loading && <span style={{ color: COLORS.YELLOW }}>● LOADING...</span>}- {!loading && !error && <span style={{ color: COLORS.GREEN }}>● LIVE</span>}- {!loading && error && <span style={{ color: COLORS.RED }}>● ERROR</span>}++ <div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>+ <span style={{ color: COLORS.CYAN, fontSize: '18px', fontWeight: 'bold' }}>{symbol}</span>+ <span style={{ color: COLORS.GRAY, fontSize: '12px', maxWidth: '250px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {tickerDetails?.name || ''}+ </span>+ <span style={{ color: COLORS.WHITE, fontSize: '16px', fontWeight: 'bold' }}>+ ${formatNumber(currentPrice)}+ </span>+ <span style={{ color: priceChange >= 0 ? COLORS.GREEN : COLORS.RED, fontSize: '13px', fontWeight: 'bold' }}>+ {priceChange >= 0 ? '▲' : '▼'} {Math.abs(priceChange).toFixed(2)} ({priceChangePercent.toFixed(2)}%)+ </span>+ {loading && <span style={{ color: COLORS.YELLOW, fontSize: '10px' }}>● LOAD</span>}+ {!loading && !error && <span style={{ color: COLORS.GREEN, fontSize: '10px' }}>● LIVE</span>}<buttononClick={() => fetchAllData()}style={{backgroundColor: COLORS.BLUE,border: 'none',color: COLORS.WHITE,- padding: '5px 15px',- fontSize: '12px',+ padding: '4px 12px',+ fontSize: '10px',cursor: 'pointer',fontWeight: 'bold',}}@@ -427,931 +421,629 @@ const PolygonEqTab: React.FC = () => {</button></div></div>++ {/* Second Row: Related Tickers as Small Boxes */}+ {relatedTickers.length > 0 && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>+ <span style={{ color: COLORS.GRAY, fontSize: '10px', fontWeight: 'bold' }}>RELATED:</span>+ {relatedTickers.slice(0, 8).map((ticker: any, idx: number) => (+ <div+ key={idx}+ onClick={() => handleRelatedTickerClick(ticker.ticker)}+ style={{+ backgroundColor: COLORS.PANEL_HEADER_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '3px 8px',+ cursor: 'pointer',+ fontSize: '10px',+ color: COLORS.CYAN,+ fontWeight: 'bold',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = COLORS.CYAN;+ e.currentTarget.style.color = COLORS.DARK_BG;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = COLORS.PANEL_HEADER_BG;+ e.currentTarget.style.color = COLORS.CYAN;+ }}+ >+ {ticker.ticker}+ </div>+ ))}+ </div>+ )}</div>{/* Error Banner */}{error && (<div style={{- backgroundColor: '#331111',- border: `1px solid ${COLORS.RED}`,- padding: '10px 15px',- margin: '10px',+ backgroundColor: '#1a0000',+ borderBottom: `1px solid ${COLORS.RED}`,+ padding: '6px 12px',color: COLORS.RED,- fontSize: '13px',+ fontSize: '11px',flexShrink: 0,}}><strong>ERROR:</strong> {error}</div>)}- {/* Price Header */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '20px',- margin: '10px',- marginBottom: '0',- flexShrink: 0,- }}>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>- <div>- <div style={{ display: 'flex', alignItems: 'center', gap: '20px', marginBottom: '8px' }}>- <span style={{ color: COLORS.ORANGE, fontSize: '28px', fontWeight: 'bold' }}>{symbol}</span>- <span style={{ color: COLORS.WHITE, fontSize: '18px' }}>{tickerDetails?.name || 'Loading...'}</span>- {tickerDetails?.type && (- <span style={{- color: COLORS.BLUE,- fontSize: '12px',- padding: '4px 10px',- backgroundColor: 'rgba(100,150,250,0.2)',- border: `1px solid ${COLORS.BLUE}`,- }}>- {tickerDetails.type}- </span>- )}- </div>- <div style={{ fontSize: '13px', color: COLORS.GRAY }}>- {tickerDetails?.primary_exchange || 'N/A'} | {tickerDetails?.market || 'N/A'} | Market Cap: {formatLargeNumber(tickerDetails?.market_cap)}- </div>- </div>- <div style={{ textAlign: 'right' }}>- <div style={{ fontSize: '32px', fontWeight: 'bold', color: COLORS.WHITE, marginBottom: '5px' }}>- ${formatNumber(currentPrice)}- </div>- <div style={{ fontSize: '16px', color: priceChange >= 0 ? COLORS.GREEN : COLORS.RED }}>- {priceChange >= 0 ? '▲' : '▼'} ${Math.abs(priceChange).toFixed(2)} ({priceChangePercent.toFixed(2)}%)+ {/* MAIN CONTENT - All data visible, main window scrolls */}+ <div style={{ padding: '6px', flexShrink: 0 }}>++ {/* ROW 1: Quote Data + Market Status + Technical Indicators - NO INTERNAL SCROLL */}+ <div style={{ display: 'grid', gridTemplateColumns: '25% 25% 25% 25%', gap: '8px', marginBottom: '8px' }}>++ {/* Quote Panel */}+ <div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <SectionHeader title="QUOTE" color={COLORS.CYAN} />+ <div style={{ padding: '10px', fontSize: '11px' }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', marginBottom: '6px' }}>+ <div><span style={{ color: COLORS.GRAY, fontSize: '10px' }}>OPEN:</span> <span style={{ color: COLORS.CYAN }}>${formatNumber(snapshot?.day?.open)}</span></div>+ <div><span style={{ color: COLORS.GRAY, fontSize: '10px' }}>HIGH:</span> <span style={{ color: COLORS.GREEN }}>${formatNumber(snapshot?.day?.high)}</span></div>+ <div><span style={{ color: COLORS.GRAY, fontSize: '10px' }}>LOW:</span> <span style={{ color: COLORS.RED }}>${formatNumber(snapshot?.day?.low)}</span></div>+ <div><span style={{ color: COLORS.GRAY, fontSize: '10px' }}>VOL:</span> <span style={{ color: COLORS.YELLOW }}>{formatNumber(snapshot?.day?.volume, 0)}</span></div>+ </div>+ <DataRow label="VWAP" value={`$${formatNumber(snapshot?.day?.vwap)}`} valueColor={COLORS.CYAN} small />+ <div style={{ borderTop: `1px solid ${COLORS.BORDER}`, marginTop: '6px', paddingTop: '6px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '3px' }}>LAST TRADE</div>+ <DataRow label="Price" value={`$${formatNumber(lastTrade?.price)}`} valueColor={COLORS.GREEN} small />+ <DataRow label="Size" value={formatNumber(lastTrade?.size, 0)} valueColor={COLORS.WHITE} small />+ </div></div></div>- </div>- </div>- {/* Main Content - Single Screen Layout */}- <div style={{- flex: 1,- overflow: 'auto',- padding: '10px',- paddingTop: '0',- }} className="custom-scrollbar">-- {/* Row 1: Today's Trading + Market Status + Related Tickers */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '10px', marginBottom: '10px' }}>-- {/* Today's Trading */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- TODAY'S TRADING DATA- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '15px', fontSize: '13px' }}>- <div>- <span style={{ color: COLORS.GRAY }}>OPEN:</span>- <div style={{ color: COLORS.CYAN, fontSize: '18px', fontWeight: 'bold' }}>${formatNumber(snapshot?.day?.open)}</div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>HIGH:</span>- <div style={{ color: COLORS.GREEN, fontSize: '18px', fontWeight: 'bold' }}>${formatNumber(snapshot?.day?.high)}</div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>LOW:</span>- <div style={{ color: COLORS.RED, fontSize: '18px', fontWeight: 'bold' }}>${formatNumber(snapshot?.day?.low)}</div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>VOLUME:</span>- <div style={{ color: COLORS.YELLOW, fontSize: '18px', fontWeight: 'bold' }}>{formatNumber(snapshot?.day?.volume, 0)}</div>+ {/* Bid/Ask Panel */}+ <div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <SectionHeader title="BID/ASK" color={COLORS.GREEN} />+ <div style={{ padding: '10px', fontSize: '11px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>+ <div>+ <div style={{ color: COLORS.GRAY, fontSize: '10px' }}>BID</div>+ <div style={{ color: COLORS.GREEN, fontSize: '14px', fontWeight: 'bold' }}>${formatNumber(lastQuote?.bid_price)}</div>+ <div style={{ color: COLORS.GRAY, fontSize: '10px' }}>x{formatNumber(lastQuote?.bid_size, 0)}</div>+ </div>+ <div style={{ textAlign: 'right' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '10px' }}>ASK</div>+ <div style={{ color: COLORS.RED, fontSize: '14px', fontWeight: 'bold' }}>${formatNumber(lastQuote?.ask_price)}</div>+ <div style={{ color: COLORS.GRAY, fontSize: '10px' }}>x{formatNumber(lastQuote?.ask_size, 0)}</div>+ </div></div>- <div>- <span style={{ color: COLORS.GRAY }}>VWAP:</span>- <div style={{ color: COLORS.CYAN, fontSize: '18px', fontWeight: 'bold' }}>${formatNumber(snapshot?.day?.vwap)}</div>+ <DataRow label="Spread" value={`$${formatNumber((lastQuote?.ask_price || 0) - (lastQuote?.bid_price || 0), 3)}`} valueColor={COLORS.YELLOW} small />+ <div style={{ borderTop: `1px solid ${COLORS.BORDER}`, marginTop: '6px', paddingTop: '6px' }}>+ <DataRow label="Mkt Cap" value={formatLargeNumber(tickerDetails?.market_cap)} valueColor={COLORS.GREEN} small />+ <DataRow label="Exchange" value={tickerDetails?.primary_exchange || 'N/A'} valueColor={COLORS.WHITE} small /></div></div></div>{/* Market Status */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.GREEN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- MARKET STATUS- </div>- <div style={{ fontSize: '13px', display: 'flex', flexDirection: 'column', gap: '15px' }}>- <div>- <span style={{ color: COLORS.GRAY }}>Market:</span>- <div style={{- color: marketStatus?.market === 'open' ? COLORS.GREEN : COLORS.RED,- fontWeight: 'bold',- fontSize: '20px',- marginTop: '5px'- }}>- {marketStatus?.market?.toUpperCase() || 'N/A'}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Server Time:</span>- <div style={{ color: COLORS.CYAN, fontSize: '15px', marginTop: '5px' }}>- {marketStatus?.serverTime || 'N/A'}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Exchanges:</span>- <div style={{ color: COLORS.BLUE, fontSize: '15px', marginTop: '5px' }}>- {marketStatus?.exchanges ? Object.keys(marketStatus.exchanges).length : 'N/A'}- </div>+ <div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <SectionHeader title="MARKET STATUS" color={COLORS.GREEN} />+ <div style={{ padding: '10px', fontSize: '11px', textAlign: 'center' }}>+ <div style={{+ color: marketStatus?.market === 'open' ? COLORS.GREEN : COLORS.RED,+ fontSize: '16px',+ fontWeight: 'bold',+ marginBottom: '6px'+ }}>+ {marketStatus?.market?.toUpperCase() || 'N/A'}</div>- <div>- <span style={{ color: COLORS.GRAY }}>Currencies:</span>- <div style={{ color: COLORS.YELLOW, fontSize: '15px', marginTop: '5px' }}>- {marketStatus?.currencies ? Object.keys(marketStatus.currencies).length : 'N/A'}- </div>+ <div style={{ color: COLORS.CYAN, fontSize: '10px', marginBottom: '8px' }}>+ {marketStatus?.serverTime || 'N/A'}</div>+ <DataRow label="Exchanges" value={marketStatus?.exchanges ? Object.keys(marketStatus.exchanges).length : 'N/A'} valueColor={COLORS.BLUE} small />+ <DataRow label="Currencies" value={marketStatus?.currencies ? Object.keys(marketStatus.currencies).length : 'N/A'} valueColor={COLORS.YELLOW} small /></div></div>- {/* Related Tickers */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.CYAN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- RELATED TICKERS ({relatedTickers.length})- </div>- <div style={{ maxHeight: '300px', overflow: 'auto' }} className="custom-scrollbar">- {relatedTickers.length > 0 ? relatedTickers.map((ticker: any, idx: number) => (- <div- key={idx}- onClick={() => handleRelatedTickerClick(ticker.ticker)}- style={{- padding: '10px',- borderBottom: `1px solid ${COLORS.BORDER}`,- cursor: 'pointer',- transition: 'background-color 0.2s',- }}- onMouseEnter={(e) => e.currentTarget.style.backgroundColor = COLORS.BORDER}- onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}- >- <div style={{ color: COLORS.CYAN, fontSize: '14px', fontWeight: 'bold', marginBottom: '3px' }}>- {ticker.ticker}- </div>- {ticker.name && (- <div style={{ color: COLORS.GRAY, fontSize: '12px' }}>- {ticker.name}- </div>- )}- </div>- )) : (- <div style={{ color: COLORS.GRAY, fontSize: '13px', padding: '15px', textAlign: 'center' }}>- No related tickers available+ {/* Technical Indicators */}+ <div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <SectionHeader title="TECHNICALS" color={COLORS.YELLOW} />+ <div style={{ padding: '10px', fontSize: '11px' }}>+ <DataRow label="SMA(20)" value={`$${formatNumber(smaData?.statistics?.latest_value)}`} valueColor={COLORS.CYAN} small />+ <DataRow label="EMA(20)" value={`$${formatNumber(emaData?.statistics?.latest_value)}`} valueColor={COLORS.BLUE} small />+ <DataRow label="RSI(14)" value={formatNumber(rsiData?.statistics?.rsi_stats?.latest_value, 1)}+ valueColor={(rsiData?.statistics?.rsi_stats?.latest_value || 0) > 70 ? COLORS.RED : (rsiData?.statistics?.rsi_stats?.latest_value || 0) < 30 ? COLORS.GREEN : COLORS.YELLOW} small />+ <div style={{ borderTop: `1px solid ${COLORS.BORDER}`, marginTop: '6px', paddingTop: '6px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '3px' }}>MACD Signal</div>+ <div style={{+ color: macdData?.macd_values?.[0]?.crossover_analysis?.macd_above_signal ? COLORS.GREEN : COLORS.RED,+ fontSize: '12px',+ fontWeight: 'bold',+ textAlign: 'center'+ }}>+ {macdData?.macd_values?.[0]?.crossover_analysis?.macd_above_signal ? '▲ BULLISH' : '▼ BEARISH'}</div>- )}+ </div></div></div></div>- {/* Row 2: Latest News */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '10px', marginBottom: '10px' }}>- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- LATEST NEWS - {symbol}- </div>- <div style={{ maxHeight: '400px', overflow: 'auto' }} className="custom-scrollbar">- {news.length > 0 ? news.map((article: any) => (- <div- key={article.id}- style={{- marginBottom: '15px',- paddingBottom: '15px',- borderBottom: `1px solid ${COLORS.BORDER}`,- }}- >- <div style={{ display: 'flex', gap: '15px' }}>- {article.image_url && (- <img- src={article.image_url}- alt=""- style={{ width: '100px', height: '75px', objectFit: 'cover', borderRadius: '4px' }}- />- )}- <div style={{ flex: 1 }}>- <div style={{ color: COLORS.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '6px' }}>- {article.title}- </div>- <div style={{ color: COLORS.GRAY, fontSize: '12px', marginBottom: '6px' }}>- {article.publisher?.name} | {new Date(article.published_utc).toLocaleString()}- </div>- {article.description && (- <div style={{ color: COLORS.WHITE, fontSize: '12px', marginBottom: '6px', opacity: 0.8 }}>- {article.description.substring(0, 150)}...- </div>- )}- <a- href={article.article_url}- target="_blank"- rel="noopener noreferrer"- style={{ color: COLORS.CYAN, fontSize: '12px', textDecoration: 'underline' }}- >- READ MORE →- </a>- </div>+ {/* ROW 2: News (2 columns) + Trades & Quotes + Chart Placeholder */}+ <div style={{ display: 'grid', gridTemplateColumns: '50% 25% 25%', gap: '8px', marginBottom: '8px' }}>++ {/* News - Show 4 articles */}+ <div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <SectionHeader title={`LATEST NEWS (${news.length})`} color={COLORS.ORANGE} />+ <div style={{ padding: '10px' }}>+ {news.length > 0 ? news.slice(0, 4).map((article: any) => (+ <div key={article.id} style={{+ marginBottom: '8px',+ paddingBottom: '8px',+ borderBottom: `1px solid ${COLORS.BORDER}`,+ fontSize: '11px'+ }}>+ <div style={{ color: COLORS.ORANGE, fontWeight: 'bold', marginBottom: '3px' }}>+ {article.title.substring(0, 80)}...+ </div>+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '3px' }}>+ {article.publisher?.name} | {new Date(article.published_utc).toLocaleDateString()}</div>+ <a+ href={article.article_url}+ target="_blank"+ rel="noopener noreferrer"+ style={{ color: COLORS.CYAN, fontSize: '10px', textDecoration: 'underline' }}+ >+ READ MORE →+ </a></div>)) : (- <div style={{ color: COLORS.GRAY, fontSize: '13px', padding: '15px', textAlign: 'center' }}>+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '15px', fontSize: '11px' }}>No news available</div>)}</div></div>- </div>- {/* Row 3: Last Trade + Last Quote + SMA */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '10px', marginBottom: '10px' }}>-- {/* Last Trade */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.BLUE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- LAST TRADE- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', fontSize: '13px' }}>- <div>- <span style={{ color: COLORS.GRAY }}>Price:</span>- <div style={{ color: COLORS.CYAN, fontSize: '20px', fontWeight: 'bold' }}>- ${formatNumber(lastTrade?.price)}- </div>+ {/* Trades & Quotes Panel */}+ <div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <SectionHeader title="TRADES & QUOTES" color={COLORS.CYAN} />+ <div style={{ padding: '10px', fontSize: '11px' }}>+ {/* Recent Trades */}+ <div style={{ marginBottom: '8px' }}>+ <div style={{ color: COLORS.ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>LAST TRADE</div>+ <DataRow label="Price" value={`$${formatNumber(lastTrade?.price)}`} valueColor={COLORS.GREEN} small />+ <DataRow label="Size" value={formatNumber(lastTrade?.size, 0)} small />+ <DataRow label="Time" value={lastTrade?.participant_timestamp ? new Date(lastTrade.participant_timestamp / 1000000).toLocaleTimeString() : 'N/A'} valueColor={COLORS.GRAY} small /></div>- <div>- <span style={{ color: COLORS.GRAY }}>Size:</span>- <div style={{ color: COLORS.YELLOW, fontSize: '16px', fontWeight: 'bold' }}>- {formatNumber(lastTrade?.size, 0)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Exchange:</span>- <div style={{ color: COLORS.WHITE, fontSize: '14px' }}>- {lastTrade?.tape_description || 'N/A'}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Time:</span>- <div style={{ color: COLORS.GRAY, fontSize: '12px' }}>- {lastTrade?.trade_time_formatted || 'N/A'}- </div>- </div>- </div>- </div>- {/* Last Quote */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.GREEN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- LAST QUOTE- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', fontSize: '13px' }}>- <div>- <span style={{ color: COLORS.GRAY }}>Bid:</span>- <div style={{ color: COLORS.GREEN, fontSize: '18px', fontWeight: 'bold' }}>- ${formatNumber(lastQuote?.bid_price)}- <span style={{ color: COLORS.GRAY, fontSize: '12px', marginLeft: '8px' }}>- x{formatNumber(lastQuote?.bid_size, 0)}- </span>- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Ask:</span>- <div style={{ color: COLORS.RED, fontSize: '18px', fontWeight: 'bold' }}>- ${formatNumber(lastQuote?.ask_price)}- <span style={{ color: COLORS.GRAY, fontSize: '12px', marginLeft: '8px' }}>- x{formatNumber(lastQuote?.ask_size, 0)}- </span>- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Spread:</span>- <div style={{ color: COLORS.YELLOW, fontSize: '16px', fontWeight: 'bold' }}>- ${formatNumber((lastQuote?.ask_price || 0) - (lastQuote?.bid_price || 0), 3)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Time:</span>- <div style={{ color: COLORS.GRAY, fontSize: '12px' }}>- {lastQuote?.quote_time_formatted || 'N/A'}- </div>+ {/* Recent Quotes */}+ <div style={{ borderTop: `1px solid ${COLORS.BORDER}`, paddingTop: '8px' }}>+ <div style={{ color: COLORS.ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>LAST QUOTE</div>+ <DataRow label="Bid" value={`$${formatNumber(lastQuote?.bid_price)}`} valueColor={COLORS.RED} small />+ <DataRow label="Ask" value={`$${formatNumber(lastQuote?.ask_price)}`} valueColor={COLORS.GREEN} small />+ <DataRow label="Spread" value={`$${formatNumber((lastQuote?.ask_price || 0) - (lastQuote?.bid_price || 0))}`} valueColor={COLORS.YELLOW} small /></div></div></div>- {/* SMA Indicator */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.CYAN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- SMA (20-DAY)- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', fontSize: '13px' }}>- <div>- <span style={{ color: COLORS.GRAY }}>Latest Value:</span>- <div style={{ color: COLORS.CYAN, fontSize: '20px', fontWeight: 'bold' }}>- ${formatNumber(smaData?.statistics?.latest_value)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Min:</span>- <div style={{ color: COLORS.RED, fontSize: '16px', fontWeight: 'bold' }}>- ${formatNumber(smaData?.statistics?.min_value)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Max:</span>- <div style={{ color: COLORS.GREEN, fontSize: '16px', fontWeight: 'bold' }}>- ${formatNumber(smaData?.statistics?.max_value)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Average:</span>- <div style={{ color: COLORS.YELLOW, fontSize: '14px' }}>- ${formatNumber(smaData?.statistics?.avg_value)}- </div>- </div>+ {/* Chart Placeholder */}+ <div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <SectionHeader title="CHART" color={COLORS.BLUE} />+ <div style={{+ padding: '20px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexDirection: 'column',+ color: COLORS.GRAY,+ fontSize: '9px',+ textAlign: 'center'+ }}>+ <div style={{ fontSize: '32px', marginBottom: '8px' }}>📈</div>+ <div>Chart integration<br/>ready here</div></div></div></div>- {/* Row 4: EMA + MACD + RSI */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '10px', marginBottom: '10px' }}>-- {/* EMA Indicator */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.BLUE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- EMA (20-DAY)- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', fontSize: '13px' }}>- <div>- <span style={{ color: COLORS.GRAY }}>Latest Value:</span>- <div style={{ color: COLORS.BLUE, fontSize: '20px', fontWeight: 'bold' }}>- ${formatNumber(emaData?.statistics?.latest_value)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Min:</span>- <div style={{ color: COLORS.RED, fontSize: '16px', fontWeight: 'bold' }}>- ${formatNumber(emaData?.statistics?.min_value)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Max:</span>- <div style={{ color: COLORS.GREEN, fontSize: '16px', fontWeight: 'bold' }}>- ${formatNumber(emaData?.statistics?.max_value)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Average:</span>- <div style={{ color: COLORS.YELLOW, fontSize: '14px' }}>- ${formatNumber(emaData?.statistics?.avg_value)}- </div>- </div>- </div>+ {/* ROW 3: TABBED BOTTOM SECTION - All data shown without scroll */}+ <div style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>++ {/* Tab Bar */}+ <div style={{ display: 'flex', borderBottom: `1px solid ${COLORS.BORDER}`, backgroundColor: COLORS.PANEL_HEADER_BG }}>+ {[+ { id: 'financials', label: 'FINANCIALS' },+ { id: 'actions', label: 'ACTIONS' },+ { id: 'short', label: 'SHORT' },+ { id: 'market', label: 'MARKET' },+ { id: 'reference', label: 'REFERENCE' },+ ].map((tab) => (+ <button+ key={tab.id}+ onClick={() => setActiveTab(tab.id as any)}+ style={{+ padding: '6px 15px',+ backgroundColor: activeTab === tab.id ? COLORS.PANEL_BG : 'transparent',+ border: 'none',+ borderBottom: activeTab === tab.id ? `2px solid ${COLORS.ORANGE}` : 'none',+ color: activeTab === tab.id ? COLORS.ORANGE : COLORS.GRAY,+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace',+ }}+ >+ {tab.label}+ </button>+ ))}</div>- {/* MACD Indicator */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.GREEN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- MACD (12,26,9)- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', fontSize: '13px' }}>- <div>- <span style={{ color: COLORS.GRAY }}>Latest MACD:</span>- <div style={{ color: COLORS.GREEN, fontSize: '18px', fontWeight: 'bold' }}>- {formatNumber(macdData?.macd_values?.[0]?.macd_value)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Signal:</span>- <div style={{ color: COLORS.ORANGE, fontSize: '16px', fontWeight: 'bold' }}>- {formatNumber(macdData?.macd_values?.[0]?.signal_line)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Histogram:</span>- <div style={{ color: macdData?.macd_values?.[0]?.histogram >= 0 ? COLORS.GREEN : COLORS.RED, fontSize: '16px', fontWeight: 'bold' }}>- {formatNumber(macdData?.macd_values?.[0]?.histogram)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Signal:</span>- <div style={{- color: macdData?.macd_values?.[0]?.crossover_analysis?.macd_above_signal ? COLORS.GREEN : COLORS.RED,- fontSize: '14px',- fontWeight: 'bold'- }}>- {macdData?.macd_values?.[0]?.crossover_analysis?.macd_above_signal ? 'BULLISH' : 'BEARISH'}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Date:</span>- <div style={{ color: COLORS.GRAY, fontSize: '12px' }}>- {macdData?.macd_values?.[0]?.date || 'N/A'}- </div>- </div>- </div>- </div>+ {/* Tab Content - No scroll, all visible */}+ <div style={{ padding: '8px' }}>- {/* RSI Indicator */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- RSI (14-DAY)- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', fontSize: '13px' }}>- <div>- <span style={{ color: COLORS.GRAY }}>Latest RSI:</span>- <div style={{- color: (rsiData?.statistics?.rsi_stats?.latest_value || 0) > 70 ? COLORS.RED :- (rsiData?.statistics?.rsi_stats?.latest_value || 0) < 30 ? COLORS.GREEN : COLORS.YELLOW,- fontSize: '24px',- fontWeight: 'bold'- }}>- {formatNumber(rsiData?.statistics?.rsi_stats?.latest_value, 1)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Signal:</span>- <div style={{- color: (rsiData?.statistics?.rsi_stats?.latest_value || 0) > 70 ? COLORS.RED :- (rsiData?.statistics?.rsi_stats?.latest_value || 0) < 30 ? COLORS.GREEN : COLORS.CYAN,- fontSize: '16px',- fontWeight: 'bold'- }}>- {(rsiData?.statistics?.rsi_stats?.latest_value || 0) > 70 ? 'OVERBOUGHT' :- (rsiData?.statistics?.rsi_stats?.latest_value || 0) < 30 ? 'OVERSOLD' : 'NEUTRAL'}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Min:</span>- <div style={{ color: COLORS.GREEN, fontSize: '14px' }}>- {formatNumber(rsiData?.statistics?.rsi_stats?.min_value, 1)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Max:</span>- <div style={{ color: COLORS.RED, fontSize: '14px' }}>- {formatNumber(rsiData?.statistics?.rsi_stats?.max_value, 1)}- </div>- </div>- </div>- </div>- </div>+ {/* FINANCIALS TAB */}+ {activeTab === 'financials' && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>- {/* Row 5: Income Statements (Full Width) */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '10px', marginBottom: '10px' }}>-- {/* Income Statements - Enhanced */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.GREEN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- INCOME STATEMENTS (ANNUAL) - DETAILED ANALYSIS- </div>- <div style={{ maxHeight: '400px', overflow: 'auto' }} className="custom-scrollbar">- {incomeStmt?.results && incomeStmt.results.length > 0 ? (+ {/* Income Statement */}<div>- {incomeStmt.results.slice(0, 2).map((r: any, i: number) => (- <div key={i} style={{ marginBottom: '20px', paddingBottom: '20px', borderBottom: `1px solid ${COLORS.BORDER}` }}>- {/* Header */}- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '15px' }}>- <div>- <span style={{ color: COLORS.ORANGE, fontSize: '20px', fontWeight: 'bold' }}>FY {r.fiscal_year}</span>- <span style={{ color: COLORS.GRAY, fontSize: '14px', marginLeft: '10px' }}>Period: {r.period_end}</span>- {r.profitability_health && (- <span style={{- color: r.profitability_health.health_rating === 'Good' || r.profitability_health.health_rating === 'Excellent' ? COLORS.GREEN : COLORS.YELLOW,- fontSize: '14px',- marginLeft: '10px',- padding: '3px 10px',- backgroundColor: 'rgba(0,200,0,0.1)',- border: `1px solid ${COLORS.GREEN}`,- }}>- {r.profitability_health.health_rating} ({r.profitability_health.health_score}/100)- </span>- )}- </div>- {r.business_model_analysis && (- <span style={{ color: COLORS.CYAN, fontSize: '14px' }}>- {r.business_model_analysis.model_type}- </span>- )}- </div>-- {/* Core Financials */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '15px', marginBottom: '15px' }}>- <div>- <span style={{ color: COLORS.GRAY, fontSize: '13px' }}>Revenue</span>- <div style={{ color: COLORS.GREEN, fontSize: '20px', fontWeight: 'bold' }}>- {formatLargeNumber(r.revenue)}- </div>- <div style={{ color: COLORS.GRAY, fontSize: '12px' }}>- EPS: ${formatNumber(r.diluted_earnings_per_share)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY, fontSize: '13px' }}>Gross Profit</span>- <div style={{ color: COLORS.CYAN, fontSize: '20px', fontWeight: 'bold' }}>- {formatLargeNumber(r.gross_profit)}- </div>- <div style={{ color: COLORS.GREEN, fontSize: '12px' }}>- Margin: {formatNumber(r.profitability_ratios?.margin_analysis?.gross_profit_margin * 100, 1)}%+ <div style={{ color: COLORS.GREEN, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ INCOME STATEMENT+ </div>+ {incomeStmt?.results && incomeStmt.results.length > 0 ? (+ <div style={{ fontSize: '8px' }}>+ {incomeStmt.results.slice(0, 1).map((r: any, i: number) => (+ <div key={i}>+ <div style={{ color: COLORS.ORANGE, fontWeight: 'bold', marginBottom: '4px' }}>+ FY {r.fiscal_year}</div>+ <DataRow label="Revenue" value={formatLargeNumber(r.revenue)} valueColor={COLORS.GREEN} small />+ <DataRow label="Gross Profit" value={formatLargeNumber(r.gross_profit)} valueColor={COLORS.CYAN} small />+ <DataRow label="Operating Inc" value={formatLargeNumber(r.operating_income)} valueColor={COLORS.BLUE} small />+ <DataRow label="Net Income" value={formatLargeNumber(r.consolidated_net_income_loss)}+ valueColor={r.consolidated_net_income_loss >= 0 ? COLORS.GREEN : COLORS.RED} small />+ <DataRow label="EBITDA" value={formatLargeNumber(r.ebitda)} valueColor={COLORS.YELLOW} small />+ <DataRow label="EPS" value={`$${formatNumber(r.diluted_earnings_per_share)}`} valueColor={COLORS.WHITE} small /></div>- <div>- <span style={{ color: COLORS.GRAY, fontSize: '13px' }}>Operating Income</span>- <div style={{ color: COLORS.BLUE, fontSize: '20px', fontWeight: 'bold' }}>- {formatLargeNumber(r.operating_income)}- </div>- <div style={{ color: COLORS.GREEN, fontSize: '12px' }}>- Margin: {formatNumber(r.profitability_ratios?.margin_analysis?.operating_profit_margin * 100, 1)}%+ ))}+ </div>+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '10px', fontSize: '8px' }}>No data</div>+ )}+ </div>++ {/* Balance Sheet */}+ <div>+ <div style={{ color: COLORS.BLUE, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ BALANCE SHEET+ </div>+ {balanceSheet?.results && balanceSheet.results.length > 0 ? (+ <div style={{ fontSize: '8px' }}>+ {balanceSheet.results.slice(0, 1).map((r: any, i: number) => (+ <div key={i}>+ <div style={{ color: COLORS.ORANGE, fontWeight: 'bold', marginBottom: '4px' }}>+ FY {r.fiscal_year}</div>+ <DataRow label="Total Assets" value={formatLargeNumber(r.total_assets)} valueColor={COLORS.GREEN} small />+ <DataRow label="Current Assets" value={formatLargeNumber(r.total_current_assets)} valueColor={COLORS.CYAN} small />+ <DataRow label="Total Liab" value={formatLargeNumber(r.total_liabilities)} valueColor={COLORS.RED} small />+ <DataRow label="Total Equity" value={formatLargeNumber(r.total_equity)} valueColor={COLORS.YELLOW} small />+ <DataRow label="Cash" value={formatLargeNumber(r.cash_and_equivalents)} valueColor={COLORS.GREEN} small />+ <DataRow label="Current Ratio" value={formatNumber(r.financial_ratios?.liquidity_ratios?.current_ratio, 2)}+ valueColor={r.financial_ratios?.liquidity_ratios?.current_ratio >= 1 ? COLORS.GREEN : COLORS.RED} small /></div>- <div>- <span style={{ color: COLORS.GRAY, fontSize: '13px' }}>Net Income</span>- <div style={{ color: r.consolidated_net_income_loss >= 0 ? COLORS.GREEN : COLORS.RED, fontSize: '20px', fontWeight: 'bold' }}>- {formatLargeNumber(r.consolidated_net_income_loss)}+ ))}+ </div>+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '10px', fontSize: '8px' }}>No data</div>+ )}+ </div>++ {/* Cash Flow & Ratios */}+ <div>+ <div style={{ color: COLORS.YELLOW, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ CASH FLOW & RATIOS+ </div>+ <div style={{ fontSize: '8px' }}>+ {cashFlowStatements?.cash_flow_data?.results && cashFlowStatements.cash_flow_data.results.length > 0 && (+ <div style={{ marginBottom: '6px' }}>+ {cashFlowStatements.cash_flow_data.results.slice(0, 1).map((cf: any, idx: number) => (+ <div key={idx}>+ <DataRow label="Operating CF" value={formatLargeNumber(cf.net_cash_from_operating_activities)} valueColor={COLORS.GREEN} small />+ <DataRow label="Investing CF" value={formatLargeNumber(cf.net_cash_from_investing_activities)} valueColor={COLORS.BLUE} small />+ <DataRow label="Financing CF" value={formatLargeNumber(cf.net_cash_from_financing_activities)} valueColor={COLORS.ORANGE} small />+ <DataRow label="Free CF" value={formatLargeNumber(cf.cash_flow_ratios?.profitability_metrics?.free_cash_flow)} valueColor={COLORS.GREEN} small /></div>- <div style={{ color: COLORS.GREEN, fontSize: '12px' }}>- Margin: {formatNumber(r.profitability_ratios?.margin_analysis?.net_profit_margin * 100, 1)}%+ ))}+ </div>+ )}+ {financialRatios?.ratios_data?.results && financialRatios.ratios_data.results.length > 0 && (+ <div>+ {financialRatios.ratios_data.results.slice(0, 1).map((ratio: any, idx: number) => (+ <div key={idx}>+ <DataRow label="P/E Ratio" value={formatNumber(ratio.price_to_earnings_ratio, 2)} valueColor={COLORS.WHITE} small />+ <DataRow label="ROE" value={`${formatNumber(ratio.return_on_equity * 100, 2)}%`} valueColor={COLORS.GREEN} small />+ <DataRow label="ROA" value={`${formatNumber(ratio.return_on_assets * 100, 2)}%`} valueColor={COLORS.GREEN} small /></div>- </div>+ ))}</div>+ )}+ </div>+ </div>+ </div>+ )}- {/* Additional Metrics */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '10px', fontSize: '13px' }}>- <div>- <span style={{ color: COLORS.GRAY }}>EBITDA:</span>- <span style={{ color: COLORS.YELLOW, marginLeft: '5px', fontWeight: 'bold' }}>- {formatLargeNumber(r.ebitda)}- </span>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>R&D:</span>- <span style={{ color: COLORS.ORANGE, marginLeft: '5px', fontWeight: 'bold' }}>- {formatLargeNumber(r.research_development)}- </span>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Tax Rate:</span>- <span style={{ color: COLORS.CYAN, marginLeft: '5px', fontWeight: 'bold' }}>- {formatNumber(r.profitability_ratios?.financial_metrics?.effective_tax_rate * 100, 1)}%- </span>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Shares:</span>- <span style={{ color: COLORS.WHITE, marginLeft: '5px', fontWeight: 'bold' }}>- {formatNumber(r.diluted_shares_outstanding / 1e9, 2)}B- </span>- </div>- </div>+ {/* CORPORATE ACTIONS TAB */}+ {activeTab === 'actions' && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>- {/* Health Factors */}- {r.profitability_health?.health_factors && (- <div style={{ marginTop: '10px' }}>- <div style={{ color: COLORS.GRAY, fontSize: '12px', marginBottom: '5px' }}>Health Factors:</div>- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '5px' }}>- {r.profitability_health.health_factors.slice(0, 4).map((factor: string, idx: number) => (- <span key={idx} style={{- color: COLORS.CYAN,- fontSize: '11px',- padding: '3px 8px',- backgroundColor: 'rgba(0,255,255,0.1)',- border: `1px solid ${COLORS.CYAN}`,- }}>- {factor}- </span>- ))}- </div>+ {/* Dividends */}+ <div>+ <div style={{ color: COLORS.GREEN, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ DIVIDENDS ({dividends.length})+ </div>+ {dividends.length > 0 ? (+ <div style={{ fontSize: '8px' }}>+ {dividends.slice(0, 8).map((d: any, i: number) => (+ <div key={i} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px', paddingBottom: '3px', borderBottom: `1px solid ${COLORS.BORDER}` }}>+ <span style={{ color: COLORS.CYAN }}>{d.ex_dividend_date}</span>+ <span style={{ color: COLORS.GREEN, fontWeight: 'bold' }}>${formatNumber(d.cash_amount, 3)}</span></div>- )}+ ))}</div>- ))}- </div>- ) : (- <div style={{ color: COLORS.GRAY, fontSize: '13px', padding: '15px', textAlign: 'center' }}>- No income statement data available+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '10px', fontSize: '8px' }}>No dividends</div>+ )}</div>- )}- </div>- </div>- </div>- {/* Row 6: Balance Sheets (Full Width) */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '10px', marginBottom: '10px' }}>-- {/* Balance Sheets - Enhanced */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.BLUE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- BALANCE SHEETS (ANNUAL) - DETAILED ANALYSIS- </div>- <div style={{ maxHeight: '400px', overflow: 'auto' }} className="custom-scrollbar">- {balanceSheet?.results && balanceSheet.results.length > 0 ? (+ {/* Stock Splits */}<div>- {balanceSheet.results.slice(0, 2).map((r: any, i: number) => (- <div key={i} style={{ marginBottom: '20px', paddingBottom: '20px', borderBottom: `1px solid ${COLORS.BORDER}` }}>- {/* Header */}- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '15px' }}>- <div>- <span style={{ color: COLORS.ORANGE, fontSize: '20px', fontWeight: 'bold' }}>FY {r.fiscal_year}</span>- <span style={{ color: COLORS.GRAY, fontSize: '14px', marginLeft: '10px' }}>Period: {r.period_end}</span>- {r.financial_health && (- <span style={{- color: r.financial_health.health_rating === 'Good' || r.financial_health.health_rating === 'Excellent' ? COLORS.GREEN :- r.financial_health.health_rating === 'Poor' ? COLORS.RED : COLORS.YELLOW,- fontSize: '14px',- marginLeft: '10px',- padding: '3px 10px',- backgroundColor: r.financial_health.health_rating === 'Poor' ? 'rgba(255,0,0,0.1)' : 'rgba(255,165,0,0.1)',- border: `1px solid ${r.financial_health.health_rating === 'Poor' ? COLORS.RED : COLORS.ORANGE}`,- }}>- {r.financial_health.health_rating} ({r.financial_health.health_score}/100)- </span>- )}+ <div style={{ color: COLORS.YELLOW, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ SPLITS ({splits.length})+ </div>+ {splits.length > 0 ? (+ <div style={{ fontSize: '8px' }}>+ {splits.slice(0, 8).map((s: any, i: number) => (+ <div key={i} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px', paddingBottom: '3px', borderBottom: `1px solid ${COLORS.BORDER}` }}>+ <span style={{ color: COLORS.CYAN }}>{s.execution_date}</span>+ <span style={{ color: COLORS.YELLOW, fontWeight: 'bold' }}>{s.split_from}:{s.split_to}</span></div>- </div>+ ))}+ </div>+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '10px', fontSize: '8px' }}>No splits</div>+ )}+ </div>+ </div>+ )}- {/* Core Balance Sheet */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '15px', marginBottom: '15px' }}>- <div>- <span style={{ color: COLORS.GRAY, fontSize: '13px' }}>Total Assets</span>- <div style={{ color: COLORS.GREEN, fontSize: '20px', fontWeight: 'bold' }}>- {formatLargeNumber(r.total_assets)}- </div>- <div style={{ color: COLORS.GRAY, fontSize: '12px' }}>- Current: {formatLargeNumber(r.total_current_assets)}- </div>- </div>- <div>- <span style={{ color: COLORS.GRAY, fontSize: '13px' }}>Total Liabilities</span>- <div style={{ color: COLORS.RED, fontSize: '20px', fontWeight: 'bold' }}>- {formatLargeNumber(r.total_liabilities)}- </div>- <div style={{ color: COLORS.GRAY, fontSize: '12px' }}>- Current: {formatLargeNumber(r.total_current_liabilities)}- </div>+ {/* SHORT INTEREST TAB */}+ {activeTab === 'short' && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>++ {/* Short Interest */}+ <div>+ <div style={{ color: COLORS.RED, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ SHORT INTEREST+ </div>+ {shortInterest?.short_interest_data && shortInterest.short_interest_data.length > 0 ? (+ <div style={{ fontSize: '8px' }}>+ {shortInterest.short_interest_data.slice(0, 5).map((data: any, idx: number) => (+ <div key={idx} style={{ marginBottom: '4px', paddingBottom: '4px', borderBottom: `1px solid ${COLORS.BORDER}` }}>+ <div style={{ color: COLORS.CYAN, fontWeight: 'bold', marginBottom: '2px' }}>{data.settlement_date}</div>+ <DataRow label="Interest" value={formatNumber(data.short_interest)} valueColor={COLORS.WHITE} small />+ <DataRow label="% Float" value={`${formatNumber(data.percent_of_float, 2)}%`} valueColor={COLORS.RED} small /></div>- <div>- <span style={{ color: COLORS.GRAY, fontSize: '13px' }}>Total Equity</span>- <div style={{ color: COLORS.YELLOW, fontSize: '20px', fontWeight: 'bold' }}>- {formatLargeNumber(r.total_equity)}- </div>- <div style={{ color: COLORS.GRAY, fontSize: '12px' }}>- Working Capital: {formatLargeNumber(r.financial_ratios?.liquidity_ratios?.working_capital)}- </div>+ ))}+ </div>+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '10px', fontSize: '8px' }}>No data</div>+ )}+ </div>++ {/* Short Volume */}+ <div>+ <div style={{ color: COLORS.ORANGE, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ SHORT VOLUME+ </div>+ {shortVolume?.short_volume_data && shortVolume.short_volume_data.length > 0 ? (+ <div style={{ fontSize: '8px' }}>+ {shortVolume.short_volume_data.slice(0, 5).map((data: any, idx: number) => (+ <div key={idx} style={{ marginBottom: '4px', paddingBottom: '4px', borderBottom: `1px solid ${COLORS.BORDER}` }}>+ <div style={{ color: COLORS.CYAN, fontWeight: 'bold', marginBottom: '2px' }}>{data.date}</div>+ <DataRow label="Volume" value={formatNumber(data.volume)} valueColor={COLORS.WHITE} small />+ <DataRow label="Short Vol" value={formatNumber(data.short_volume)} valueColor={COLORS.ORANGE} small /></div>- </div>+ ))}+ </div>+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '10px', fontSize: '8px' }}>No data</div>+ )}+ </div>- {/* Liquidity Ratios */}- <div style={{ marginBottom: '12px' }}>- <div style={{ color: COLORS.CYAN, fontSize: '13px', marginBottom: '8px', fontWeight: 'bold' }}>Liquidity Ratios</div>- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '10px', fontSize: '13px' }}>- <div>- <span style={{ color: COLORS.GRAY }}>Current Ratio:</span>- <span style={{- color: r.financial_ratios?.liquidity_ratios?.current_ratio >= 1 ? COLORS.GREEN : COLORS.RED,- marginLeft: '5px',- fontWeight: 'bold'- }}>- {formatNumber(r.financial_ratios?.liquidity_ratios?.current_ratio, 2)}- </span>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Quick Ratio:</span>- <span style={{ color: COLORS.YELLOW, marginLeft: '5px', fontWeight: 'bold' }}>- {formatNumber(r.financial_ratios?.liquidity_ratios?.quick_ratio, 2)}- </span>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Cash Ratio:</span>- <span style={{ color: COLORS.CYAN, marginLeft: '5px', fontWeight: 'bold' }}>- {formatNumber(r.financial_ratios?.liquidity_ratios?.cash_ratio, 2)}- </span>+ {/* Trades & Quotes */}+ <div>+ <div style={{ color: COLORS.GREEN, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ TRADES & QUOTES+ </div>+ <div style={{ fontSize: '8px' }}>+ {trades?.trades && trades.trades.length > 0 ? (+ <div style={{ marginBottom: '6px' }}>+ {trades.trades.slice(0, 3).map((trade: any, idx: number) => (+ <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px', fontSize: '7px' }}>+ <span style={{ color: COLORS.GRAY }}>{trade.time}</span>+ <span style={{ color: COLORS.GREEN }}>${formatNumber(trade.price, 2)}</span>+ <span style={{ color: COLORS.WHITE }}>{formatNumber(trade.size)}</span></div>- <div>- <span style={{ color: COLORS.GRAY }}>Cash & Equiv:</span>- <span style={{ color: COLORS.GREEN, marginLeft: '5px', fontWeight: 'bold' }}>- {formatLargeNumber(r.cash_and_equivalents)}- </span>+ ))}+ </div>+ ) : null}+ {quotes?.quotes && quotes.quotes.length > 0 ? (+ <div>+ {quotes.quotes.slice(0, 3).map((quote: any, idx: number) => (+ <div key={idx} style={{ marginBottom: '2px', fontSize: '7px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>{quote.time}</span>+ <span style={{ color: COLORS.GREEN }}>B: ${formatNumber(quote.bid_price, 2)}</span>+ <span style={{ color: COLORS.RED }}>A: ${formatNumber(quote.ask_price, 2)}</span>+ </div></div>- </div>+ ))}</div>+ ) : null}+ </div>+ </div>+ </div>+ )}- {/* Leverage Ratios */}- <div style={{ marginBottom: '12px' }}>- <div style={{ color: COLORS.ORANGE, fontSize: '13px', marginBottom: '8px', fontWeight: 'bold' }}>Leverage Ratios</div>- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '10px', fontSize: '13px' }}>- <div>- <span style={{ color: COLORS.GRAY }}>Debt/Equity:</span>- <span style={{- color: r.financial_ratios?.leverage_ratios?.debt_to_equity > 2 ? COLORS.RED : COLORS.YELLOW,- marginLeft: '5px',- fontWeight: 'bold'- }}>- {formatNumber(r.financial_ratios?.leverage_ratios?.debt_to_equity, 2)}- </span>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Debt/Assets:</span>- <span style={{ color: COLORS.CYAN, marginLeft: '5px', fontWeight: 'bold' }}>- {formatNumber(r.financial_ratios?.leverage_ratios?.debt_to_assets, 2)}- </span>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>LT Debt:</span>- <span style={{ color: COLORS.RED, marginLeft: '5px', fontWeight: 'bold' }}>- {formatLargeNumber(r.long_term_debt_and_capital_lease_obligations)}- </span>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>Equity Multi:</span>- <span style={{ color: COLORS.YELLOW, marginLeft: '5px', fontWeight: 'bold' }}>- {formatNumber(r.financial_ratios?.leverage_ratios?.equity_multiplier, 2)}- </span>- </div>+ {/* MARKET DATA TAB */}+ {activeTab === 'market' && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>++ {/* Ticker Search */}+ <div>+ <div style={{ color: COLORS.ORANGE, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ TICKER SEARCH ({allTickers.length})+ </div>+ {allTickers.length > 0 ? (+ <div style={{ fontSize: '8px' }}>+ {allTickers.slice(0, 8).map((t: any, i: number) => (+ <div key={i} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px', paddingBottom: '2px', borderBottom: `1px solid ${COLORS.BORDER}` }}>+ <span style={{ color: COLORS.CYAN, fontWeight: 'bold' }}>{t.ticker}</span>+ <span style={{ color: COLORS.WHITE, fontSize: '7px' }}>{t.name?.substring(0, 20) || 'N/A'}</span>+ <span style={{ color: COLORS.YELLOW }}>{t.type}</span></div>- </div>+ ))}+ </div>+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '10px', fontSize: '8px' }}>No results</div>+ )}+ </div>- {/* Health Factors */}- {r.financial_health?.health_factors && (- <div style={{ marginTop: '10px' }}>- <div style={{ color: COLORS.GRAY, fontSize: '12px', marginBottom: '5px' }}>Health Factors:</div>- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '5px' }}>- {r.financial_health.health_factors.slice(0, 4).map((factor: string, idx: number) => (- <span key={idx} style={{- color: factor.includes('concern') || factor.includes('distress') || factor.includes('Low') || factor.includes('High debt') || factor.includes('Negative') ? COLORS.RED : COLORS.CYAN,- fontSize: '11px',- padding: '3px 8px',- backgroundColor: factor.includes('concern') ? 'rgba(255,0,0,0.1)' : 'rgba(0,255,255,0.1)',- border: `1px solid ${factor.includes('concern') ? COLORS.RED : COLORS.CYAN}`,- }}>- {factor}- </span>- ))}+ {/* Market Holidays */}+ <div>+ <div style={{ color: COLORS.BLUE, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ MARKET HOLIDAYS ({marketHolidays.length})+ </div>+ {marketHolidays.length > 0 ? (+ <div style={{ fontSize: '8px' }}>+ {marketHolidays.slice(0, 8).map((holiday: any, i: number) => (+ <div key={i} style={{ marginBottom: '3px', paddingBottom: '3px', borderBottom: `1px solid ${COLORS.BORDER}` }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.CYAN, fontWeight: 'bold' }}>{holiday.date}</span>+ <span style={{ color: holiday.status === 'closed' ? COLORS.RED : COLORS.YELLOW, fontSize: '7px' }}>{holiday.status?.toUpperCase()}</span></div>+ <div style={{ color: COLORS.WHITE, fontSize: '7px' }}>{holiday.name}</div></div>- )}+ ))}</div>- ))}+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '10px', fontSize: '8px' }}>No holidays</div>+ )}</div>- ) : (- <div style={{ color: COLORS.GRAY, fontSize: '13px', padding: '15px', textAlign: 'center' }}>- No balance sheet data available+ </div>+ )}++ {/* REFERENCE DATA TAB */}+ {activeTab === 'reference' && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>++ {/* Ticker Types */}+ <div>+ <div style={{ color: COLORS.BLUE, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ TICKER TYPES ({tickerTypes.length})+ </div>+ {tickerTypes.length > 0 ? (+ <div style={{ fontSize: '8px' }}>+ {tickerTypes.slice(0, 8).map((tt: any, i: number) => (+ <div key={i} style={{ marginBottom: '3px', paddingBottom: '3px', borderBottom: `1px solid ${COLORS.BORDER}` }}>+ <div style={{ color: COLORS.CYAN, fontWeight: 'bold' }}>{tt.code}</div>+ <div style={{ color: COLORS.WHITE, fontSize: '7px' }}>{tt.description?.substring(0, 30)}</div>+ </div>+ ))}+ </div>+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '10px', fontSize: '8px' }}>No types</div>+ )}</div>- )}- </div>- </div>- </div>- {/* Row 7: Dividends + Splits */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>-- {/* Dividends */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.GREEN, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- DIVIDEND HISTORY ({dividends.length})- </div>- <div style={{ maxHeight: '250px', overflow: 'auto' }} className="custom-scrollbar">- {dividends.length > 0 ? (- <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '12px' }}>- <thead>- <tr style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}>- <th style={{ color: COLORS.GRAY, textAlign: 'left', padding: '8px', fontSize: '11px' }}>Ex-Date</th>- <th style={{ color: COLORS.GRAY, textAlign: 'right', padding: '8px', fontSize: '11px' }}>Amount</th>- <th style={{ color: COLORS.GRAY, textAlign: 'left', padding: '8px', fontSize: '11px' }}>Type</th>- </tr>- </thead>- <tbody>- {dividends.map((d: any, i: number) => (- <tr key={i} style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}>- <td style={{ color: COLORS.CYAN, padding: '8px' }}>{d.ex_dividend_date}</td>- <td style={{ color: COLORS.GREEN, textAlign: 'right', padding: '8px', fontWeight: 'bold' }}>- ${formatNumber(d.cash_amount, 3)}- </td>- <td style={{ color: COLORS.GRAY, padding: '8px', fontSize: '11px' }}>{d.dividend_type}</td>- </tr>- ))}- </tbody>- </table>- ) : (- <div style={{ color: COLORS.GRAY, fontSize: '13px', padding: '15px', textAlign: 'center' }}>- No dividend history available+ {/* Exchanges */}+ <div>+ <div style={{ color: COLORS.GREEN, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ EXCHANGES ({exchanges.length})+ </div>+ {exchanges.length > 0 ? (+ <div style={{ fontSize: '8px' }}>+ {exchanges.slice(0, 8).map((ex: any, i: number) => (+ <div key={i} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px', paddingBottom: '2px', borderBottom: `1px solid ${COLORS.BORDER}` }}>+ <span style={{ color: COLORS.CYAN, fontWeight: 'bold' }}>{ex.mic}</span>+ <span style={{ color: COLORS.WHITE, fontSize: '7px' }}>{ex.name?.substring(0, 20)}</span>+ </div>+ ))}+ </div>+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '10px', fontSize: '8px' }}>No exchanges</div>+ )}</div>- )}- </div>- </div>- {/* Stock Splits */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '15px',- }}>- <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '8px' }}>- STOCK SPLITS ({splits.length})- </div>- <div style={{ maxHeight: '250px', overflow: 'auto' }} className="custom-scrollbar">- {splits.length > 0 ? (- <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '12px' }}>- <thead>- <tr style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}>- <th style={{ color: COLORS.GRAY, textAlign: 'left', padding: '8px', fontSize: '11px' }}>Execution Date</th>- <th style={{ color: COLORS.GRAY, textAlign: 'right', padding: '8px', fontSize: '11px' }}>Ratio</th>- </tr>- </thead>- <tbody>- {splits.map((s: any, i: number) => (- <tr key={i} style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}>- <td style={{ color: COLORS.CYAN, padding: '8px' }}>{s.execution_date}</td>- <td style={{ color: COLORS.YELLOW, textAlign: 'right', padding: '8px', fontWeight: 'bold' }}>- {s.split_from}:{s.split_to}- </td>- </tr>- ))}- </tbody>- </table>- ) : (- <div style={{ color: COLORS.GRAY, fontSize: '13px', padding: '15px', textAlign: 'center' }}>- No split history available+ {/* Events & Condition Codes */}+ <div>+ <div style={{ color: COLORS.YELLOW, fontSize: '9px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ EVENTS & CODES+ </div>+ <div style={{ fontSize: '8px' }}>+ {tickerEvents && tickerEvents.events && tickerEvents.events.length > 0 ? (+ <div style={{ marginBottom: '6px' }}>+ <div style={{ color: COLORS.CYAN, marginBottom: '3px', fontSize: '8px' }}>Events: {tickerEvents.events.length}</div>+ {tickerEvents.events.slice(0, 3).map((evt: any, i: number) => (+ <div key={i} style={{ color: COLORS.WHITE, fontSize: '7px', marginBottom: '2px' }}>+ {evt.date} - {evt.type}+ </div>+ ))}+ </div>+ ) : null}+ {conditionCodes.length > 0 ? (+ <div>+ <div style={{ color: COLORS.CYAN, marginBottom: '3px', fontSize: '8px' }}>Codes: {conditionCodes.length}</div>+ {conditionCodes.slice(0, 4).map((cc: any, i: number) => (+ <div key={i} style={{ color: COLORS.WHITE, fontSize: '7px', marginBottom: '2px' }}>+ {cc.id} - {cc.type}+ </div>+ ))}+ </div>+ ) : null}+ </div></div>- )}- </div>+ </div>+ )}</div></div>-</div>- {/* Footer */}+ {/* FOOTER - Compact */}<div style={{borderTop: `1px solid ${COLORS.BORDER}`,backgroundColor: COLORS.PANEL_BG,- padding: '6px 15px',- fontSize: '11px',+ padding: '4px 10px',+ fontSize: '8px',color: COLORS.GRAY,+ display: 'flex',+ justifyContent: 'space-between',flexShrink: 0,}}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span>Powered by Polygon.io API | Phase 3: 15/31 Endpoints | Institutional-Grade Market Data</span>- <span>{symbol} | {new Date().toLocaleString()}</span>- </div>+ <span>Polygon.io API | 31/31 Endpoints | Institutional Data</span>+ <span>{symbol} | {new Date().toLocaleString()}</span></div>- {/* Custom Scrollbar */}+ {/* Custom Scrollbar - Only main window scrolls */}<style>{`.custom-scrollbar::-webkit-scrollbar {width: 8px;height: 8px;}.custom-scrollbar::-webkit-scrollbar-track {- background: transparent;+ background: #0a0a0a;}.custom-scrollbar::-webkit-scrollbar-thumb {- background: rgba(120, 120, 120, 0.3);+ background: rgba(255, 165, 0, 0.3);border-radius: 4px;}.custom-scrollbar::-webkit-scrollbar-thumb:hover {- background: rgba(120, 120, 120, 0.5);+ background: rgba(255, 165, 0, 0.5);}`}</style></div>diff --git a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsxindex 2b0a38ad4..dbd2cbc9a 100644--- a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx@@ -32,6 +32,9 @@ export default function SettingsTab() {api_key: ''});+ // Polygon.io dedicated field+ const [polygonApiKey, setPolygonApiKey] = useState('');+useEffect(() => {initDB();@@ -71,6 +74,12 @@ export default function SettingsTab() {try {const creds = await sqliteService.getCredentials();setCredentials(creds);++ // Load Polygon.io key if it exists+ const polygonCred = creds.find(c => c.service_name.toLowerCase() === 'polygon.io');+ if (polygonCred?.api_key) {+ setPolygonApiKey(polygonCred.api_key);+ }} catch (error) {console.error('Failed to load credentials:', error);}@@ -145,6 +154,49 @@ export default function SettingsTab() {}};+ const handleSavePolygonKey = async () => {+ if (!polygonApiKey.trim()) {+ showMessage('error', 'Polygon.io API key is required');+ return;+ }++ try {+ setLoading(true);++ // Check if Polygon.io credential already exists+ const existingCreds = await sqliteService.getCredentials();+ const existingPolygon = existingCreds.find(c => c.service_name.toLowerCase() === 'polygon.io');++ if (existingPolygon?.id) {+ // Delete existing credential first+ await sqliteService.deleteCredential(existingPolygon.id);+ }++ // Save new credential+ const credential: Credential = {+ service_name: 'Polygon.io',+ username: 'api',+ password: 'key',+ api_key: polygonApiKey,+ api_secret: '',+ additional_data: ''+ };++ const result = await sqliteService.saveCredential(credential);++ if (result.success) {+ showMessage('success', 'Polygon.io API key saved successfully');+ await loadCredentials();+ } else {+ showMessage('error', result.message);+ }+ } catch (error) {+ showMessage('error', 'Failed to save Polygon.io API key');+ } finally {+ setLoading(false);+ }+ };+const handleSaveLLMConfig = async () => {try {setLoading(true);@@ -321,7 +373,68 @@ export default function SettingsTab() {API KEY MANAGEMENT</h2><p style={{ color: '#888', fontSize: '10px' }}>- Store API keys for services like FRED, Alpha Vantage, etc. All data is encrypted and stored locally.+ Store API keys for services like FRED, Alpha Vantage, Polygon.io, etc. All data is encrypted and stored locally.+ </p>+ </div>++ {/* Polygon.io Dedicated Field */}+ <div style={{+ background: '#0a0a0a',+ border: '1px solid #1a1a1a',+ padding: '16px',+ marginBottom: '20px',+ borderRadius: '4px'+ }}>+ <h3 style={{ color: '#ea580c', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>+ Polygon.io API Key+ </h3>++ <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '12px', alignItems: 'end' }}>+ <div>+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>+ API KEY *+ </label>+ <input+ type="text"+ value={polygonApiKey}+ onChange={(e) => setPolygonApiKey(e.target.value)}+ placeholder="Enter your Polygon.io API key"+ style={{+ width: '100%',+ background: '#000',+ border: '1px solid #2a2a2a',+ color: '#fff',+ padding: '8px',+ fontSize: '10px',+ borderRadius: '3px'+ }}+ />+ </div>+ <button+ onClick={handleSavePolygonKey}+ disabled={loading}+ style={{+ background: '#ea580c',+ color: '#fff',+ border: 'none',+ padding: '8px 16px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: loading ? 'not-allowed' : 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: loading ? 0.5 : 1,+ whiteSpace: 'nowrap'+ }}+ >+ <Save size={14} />+ {loading ? 'SAVING...' : 'SAVE'}+ </button>+ </div>+ <p style={{ color: '#666', fontSize: '9px', marginTop: '8px' }}>+ Used for Polygon.io Equities data in the Polygon tab. Get your free API key at <span style={{ color: '#ea580c' }}>polygon.io</span></p></div>@@ -346,7 +459,7 @@ export default function SettingsTab() {type="text"value={newApiKey.service_name}onChange={(e) => setNewApiKey({ ...newApiKey, service_name: e.target.value })}- placeholder="e.g., FRED, AlphaVantage"+ placeholder="e.g., Polygon.io, FRED, AlphaVantage"style={{width: '100%',background: '#000',diff --git a/fincept-terminal-desktop/src/services/notebookService.ts b/fincept-terminal-desktop/src/services/notebookService.tsnew file mode 100644index 000000000..d13675c3b--- /dev/null+++ b/fincept-terminal-desktop/src/services/notebookService.ts@@ -0,0 +1,201 @@+import { invoke } from '@tauri-apps/api/core';+import Database from '@tauri-apps/plugin-sql';++interface NotebookHistory {+ id?: number;+ name: string;+ content: string;+ path: string | null;+ created_at: string;+ updated_at: string;+ cell_count: number;+ execution_count: number;+}++class NotebookService {+ private db: Database | null = null;+ private isInitialized = false;++ async initialize() {+ if (this.isInitialized) return;++ try {+ this.db = await Database.load('sqlite:notebooks.db');++ // Create notebooks history table+ await this.db.execute(`+ CREATE TABLE IF NOT EXISTS notebook_history (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ name TEXT NOT NULL,+ content TEXT NOT NULL,+ path TEXT,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ cell_count INTEGER DEFAULT 0,+ execution_count INTEGER DEFAULT 0+ )+ `);++ // Create index on updated_at for faster queries+ await this.db.execute(`+ CREATE INDEX IF NOT EXISTS idx_notebook_updated+ ON notebook_history(updated_at DESC)+ `);++ this.isInitialized = true;+ console.log('Notebook service initialized successfully');+ } catch (error) {+ console.error('Failed to initialize notebook service:', error);+ throw error;+ }+ }++ async saveToHistory(notebook: NotebookHistory): Promise<number> {+ await this.initialize();++ try {+ const result = await this.db!.execute(+ `INSERT INTO notebook_history+ (name, content, path, created_at, updated_at, cell_count, execution_count)+ VALUES (?, ?, ?, ?, ?, ?, ?)`,+ [+ notebook.name,+ notebook.content,+ notebook.path,+ notebook.created_at,+ notebook.updated_at,+ notebook.cell_count,+ notebook.execution_count+ ]+ );++ return result.lastInsertId;+ } catch (error) {+ console.error('Failed to save notebook to history:', error);+ throw error;+ }+ }++ async updateHistory(id: number, notebook: Partial<NotebookHistory>): Promise<void> {+ await this.initialize();++ try {+ const updates: string[] = [];+ const values: any[] = [];++ if (notebook.name !== undefined) {+ updates.push('name = ?');+ values.push(notebook.name);+ }+ if (notebook.content !== undefined) {+ updates.push('content = ?');+ values.push(notebook.content);+ }+ if (notebook.path !== undefined) {+ updates.push('path = ?');+ values.push(notebook.path);+ }+ if (notebook.cell_count !== undefined) {+ updates.push('cell_count = ?');+ values.push(notebook.cell_count);+ }+ if (notebook.execution_count !== undefined) {+ updates.push('execution_count = ?');+ values.push(notebook.execution_count);+ }++ updates.push('updated_at = ?');+ values.push(new Date().toISOString());++ values.push(id);++ await this.db!.execute(+ `UPDATE notebook_history SET ${updates.join(', ')} WHERE id = ?`,+ values+ );+ } catch (error) {+ console.error('Failed to update notebook history:', error);+ throw error;+ }+ }++ async getHistory(limit: number = 50): Promise<NotebookHistory[]> {+ await this.initialize();++ try {+ const result = await this.db!.select<NotebookHistory[]>(+ `SELECT * FROM notebook_history+ ORDER BY updated_at DESC+ LIMIT ?`,+ [limit]+ );++ return result;+ } catch (error) {+ console.error('Failed to get notebook history:', error);+ return [];+ }+ }++ async getNotebookById(id: number): Promise<NotebookHistory | null> {+ await this.initialize();++ try {+ const result = await this.db!.select<NotebookHistory[]>(+ 'SELECT * FROM notebook_history WHERE id = ?',+ [id]+ );++ return result.length > 0 ? result[0] : null;+ } catch (error) {+ console.error('Failed to get notebook by ID:', error);+ return null;+ }+ }++ async deleteFromHistory(id: number): Promise<void> {+ await this.initialize();++ try {+ await this.db!.execute(+ 'DELETE FROM notebook_history WHERE id = ?',+ [id]+ );+ } catch (error) {+ console.error('Failed to delete notebook from history:', error);+ throw error;+ }+ }++ async searchHistory(query: string): Promise<NotebookHistory[]> {+ await this.initialize();++ try {+ const result = await this.db!.select<NotebookHistory[]>(+ `SELECT * FROM notebook_history+ WHERE name LIKE ? OR path LIKE ?+ ORDER BY updated_at DESC+ LIMIT 50`,+ [`%${query}%`, `%${query}%`]+ );++ return result;+ } catch (error) {+ console.error('Failed to search notebook history:', error);+ return [];+ }+ }++ async clearHistory(): Promise<void> {+ await this.initialize();++ try {+ await this.db!.execute('DELETE FROM notebook_history');+ } catch (error) {+ console.error('Failed to clear notebook history:', error);+ throw error;+ }+ }+}++export const notebookService = new NotebookService();diff --git a/fincept-terminal-desktop/src/services/polygonService.ts b/fincept-terminal-desktop/src/services/polygonService.tsindex 029b3b78b..104db056d 100644--- a/fincept-terminal-desktop/src/services/polygonService.ts+++ b/fincept-terminal-desktop/src/services/polygonService.ts@@ -1,24 +1,43 @@import { invoke } from '@tauri-apps/api/core';+import { sqliteService } from './sqliteService';+// Polygon.io Service Layer - Comprehensive Coverage of 31 Endpointsclass PolygonService {private apiKey: string = '';- setApiKey(key: string) {- this.apiKey = key;- localStorage.setItem('polygon_api_key', key);+ async loadApiKey(): Promise<string> {+ try {+ const credentials = await sqliteService.getCredentials();+ const polygonCred = credentials.find(c => c.service_name.toLowerCase() === 'polygon.io');+ if (polygonCred?.api_key) {+ this.apiKey = polygonCred.api_key;+ // Set environment variable for Python script+ localStorage.setItem('POLYGON_API_KEY', polygonCred.api_key);+ return polygonCred.api_key;+ }+ } catch (error) {+ console.error('Failed to load Polygon API key from database:', error);+ }+ return '';}getApiKey(): string {- if (!this.apiKey) {- this.apiKey = localStorage.getItem('polygon_api_key') || '';- }return this.apiKey;}private async executeCommand(command: string, args: string[]): Promise<any> {try {- const result = await invoke<string>('execute_polygon_command', { command, args });+ // Ensure API key is loaded+ if (!this.apiKey) {+ await this.loadApiKey();+ }++ const result = await invoke<string>('execute_polygon_command', {+ command,+ args,+ apiKey: this.apiKey || null+ });return JSON.parse(result);} catch (error) {console.error('Polygon API error:', error);diff --git a/fincept-terminal-desktop/temp.txt b/fincept-terminal-desktop/temp.txtnew file mode 100644index 000000000..f2afebe87--- /dev/null+++ b/fincept-terminal-desktop/temp.txt@@ -0,0 +1,8 @@+ TCP [::1]:1420 [::]:0 LISTENING 8452+ TCP [::1]:1420 [::1]:49774 TIME_WAIT 0+ TCP [::1]:1420 [::1]:51945 TIME_WAIT 0+ TCP [::1]:1420 [::1]:55589 TIME_WAIT 0+ TCP [::1]:1420 [::1]:59273 TIME_WAIT 0+ TCP [::1]:1420 [::1]:61966 TIME_WAIT 0+ TCP [::1]:1420 [::1]:64211 TIME_WAIT 0+ TCP [::1]:57094 [::1]:1420 TIME_WAIT 0