Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

markets tab update

tilakpatel2254083d43e7d8
diff --git a/fincept-terminal-desktop/package-lock.json b/fincept-terminal-desktop/package-lock.json
index 001fcf439..46f166240 100644
--- a/fincept-terminal-desktop/package-lock.json
+++ b/fincept-terminal-desktop/package-lock.json
@@ -56,6 +56,7 @@
"lucide-react": "^0.544.0",
"next-themes": "^0.4.6",
"ollama": "^0.6.0",
+ "otpauth": "^9.4.1",
"otplib": "^12.0.1",
"playwright": "^1.55.1",
"react": "^19.1.0",
@@ -1734,6 +1735,18 @@
"@langchain/core": ">=0.2.21 <0.4.0"
}
},
+ "node_modules/@noble/hashes": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
+ "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
+ "license": "MIT",
+ "engines": {
+ "node": "^14.21.3 || >=16"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
"node_modules/@otplib/core": {
"version": "12.0.1",
"resolved": "https://registry.npmjs.org/@otplib/core/-/core-12.0.1.tgz",
@@ -8211,6 +8224,18 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/otpauth": {
+ "version": "9.4.1",
+ "resolved": "https://registry.npmjs.org/otpauth/-/otpauth-9.4.1.tgz",
+ "integrity": "sha512-+iVvys36CFsyXEqfNftQm1II7SW23W1wx9RwNk0Cd97lbvorqAhBDksb/0bYry087QMxjiuBS0wokdoZ0iUeAw==",
+ "license": "MIT",
+ "dependencies": {
+ "@noble/hashes": "1.8.0"
+ },
+ "funding": {
+ "url": "https://github.com/hectorm/otpauth?sponsor=1"
+ }
+ },
"node_modules/otplib": {
"version": "12.0.1",
"resolved": "https://registry.npmjs.org/otplib/-/otplib-12.0.1.tgz",
diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.json
index 6ff67948a..2c903f26f 100644
--- a/fincept-terminal-desktop/package.json
+++ b/fincept-terminal-desktop/package.json
@@ -58,6 +58,7 @@
"lucide-react": "^0.544.0",
"next-themes": "^0.4.6",
"ollama": "^0.6.0",
+ "otpauth": "^9.4.1",
"otplib": "^12.0.1",
"playwright": "^1.55.1",
"react": "^19.1.0",
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lock
index 21b5bad55..0dd0c5a59 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.lock
+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock
@@ -270,6 +270,21 @@ version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba"
+[[package]]
+name = "bit-set"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"
+dependencies = [
+ "bit-vec",
+]
+
+[[package]]
+name = "bit-vec"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
+
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -938,7 +953,7 @@ dependencies = [
"rustc_version",
"toml 0.9.7",
"vswhom",
- "winreg",
+ "winreg 0.55.0",
]
[[package]]
@@ -1071,13 +1086,18 @@ dependencies = [
name = "fincept-terminal-desktop"
version = "0.1.0"
dependencies = [
+ "anyhow",
"serde",
"serde_json",
+ "sha2",
"tauri",
"tauri-build",
"tauri-plugin-cors-fetch",
"tauri-plugin-opener",
"tauri-plugin-sql",
+ "time",
+ "tokio",
+ "yahoo_finance_api",
]
[[package]]
@@ -1572,6 +1592,25 @@ dependencies = [
"syn 2.0.106",
]
+[[package]]
+name = "h2"
+version = "0.3.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d"
+dependencies = [
+ "bytes",
+ "fnv",
+ "futures-core",
+ "futures-sink",
+ "futures-util",
+ "http 0.2.12",
+ "indexmap 2.11.4",
+ "slab",
+ "tokio",
+ "tokio-util",
+ "tracing",
+]
+
[[package]]
name = "h2"
version = "0.4.12"
@@ -1583,7 +1622,7 @@ dependencies = [
"fnv",
"futures-core",
"futures-sink",
- "http",
+ "http 1.3.1",
"indexmap 2.11.4",
"slab",
"tokio",
@@ -1674,6 +1713,20 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "html5ever"
+version = "0.26.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bea68cab48b8459f17cf1c944c67ddc572d272d9f2b274140f223ecb1da4a3b7"
+dependencies = [
+ "log",
+ "mac",
+ "markup5ever 0.11.0",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
[[package]]
name = "html5ever"
version = "0.29.1"
@@ -1682,10 +1735,21 @@ checksum = "3b7410cae13cbc75623c98ac4cbfd1f0bedddf3227afc24f370cf0f50a44a11c"
dependencies = [
"log",
"mac",
- "markup5ever",
+ "markup5ever 0.14.1",
"match_token",
]
+[[package]]
+name = "http"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1"
+dependencies = [
+ "bytes",
+ "fnv",
+ "itoa",
+]
+
[[package]]
name = "http"
version = "1.3.1"
@@ -1697,6 +1761,17 @@ dependencies = [
"itoa",
]
+[[package]]
+name = "http-body"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2"
+dependencies = [
+ "bytes",
+ "http 0.2.12",
+ "pin-project-lite",
+]
+
[[package]]
name = "http-body"
version = "1.0.1"
@@ -1704,7 +1779,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
dependencies = [
"bytes",
- "http",
+ "http 1.3.1",
]
[[package]]
@@ -1715,8 +1790,8 @@ checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
dependencies = [
"bytes",
"futures-core",
- "http",
- "http-body",
+ "http 1.3.1",
+ "http-body 1.0.1",
"pin-project-lite",
]
@@ -1726,6 +1801,36 @@ version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
+[[package]]
+name = "hyper"
+version = "0.14.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7"
+dependencies = [
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "futures-util",
+ "h2 0.3.27",
+ "http 0.2.12",
+ "http-body 0.4.6",
+ "httparse",
+ "httpdate",
+ "itoa",
+ "pin-project-lite",
+ "socket2 0.5.10",
+ "tokio",
+ "tower-service",
+ "tracing",
+ "want",
+]
+
[[package]]
name = "hyper"
version = "1.7.0"
@@ -1736,9 +1841,9 @@ dependencies = [
"bytes",
"futures-channel",
"futures-core",
- "h2",
- "http",
- "http-body",
+ "h2 0.4.12",
+ "http 1.3.1",
+ "http-body 1.0.1",
"httparse",
"itoa",
"pin-project-lite",
@@ -1748,21 +1853,35 @@ dependencies = [
"want",
]
+[[package]]
+name = "hyper-rustls"
+version = "0.24.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590"
+dependencies = [
+ "futures-util",
+ "http 0.2.12",
+ "hyper 0.14.32",
+ "rustls 0.21.12",
+ "tokio",
+ "tokio-rustls 0.24.1",
+]
+
[[package]]
name = "hyper-rustls"
version = "0.27.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"
dependencies = [
- "http",
- "hyper",
+ "http 1.3.1",
+ "hyper 1.7.0",
"hyper-util",
- "rustls",
+ "rustls 0.23.32",
"rustls-pki-types",
"tokio",
- "tokio-rustls",
+ "tokio-rustls 0.26.4",
"tower-service",
- "webpki-roots",
+ "webpki-roots 1.0.2",
]
[[package]]
@@ -1776,15 +1895,15 @@ dependencies = [
"futures-channel",
"futures-core",
"futures-util",
- "http",
- "http-body",
- "hyper",
+ "http 1.3.1",
+ "http-body 1.0.1",
+ "hyper 1.7.0",
"ipnet",
"libc",
"percent-encoding",
"pin-project-lite",
- "socket2",
- "system-configuration",
+ "socket2 0.6.0",
+ "system-configuration 0.6.1",
"tokio",
"tower-service",
"tracing",
@@ -2117,7 +2236,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02cb977175687f33fa4afa0c95c112b987ea1443e5a51c8f8ff27dc618270cc2"
dependencies = [
"cssparser",
- "html5ever",
+ "html5ever 0.29.1",
"indexmap 2.11.4",
"selectors",
]
@@ -2245,6 +2364,20 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
+[[package]]
+name = "markup5ever"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016"
+dependencies = [
+ "log",
+ "phf 0.10.1",
+ "phf_codegen 0.10.0",
+ "string_cache",
+ "string_cache_codegen",
+ "tendril",
+]
+
[[package]]
name = "markup5ever"
version = "0.14.1"
@@ -2259,6 +2392,18 @@ dependencies = [
"tendril",
]
+[[package]]
+name = "markup5ever_rcdom"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9521dd6750f8e80ee6c53d65e2e4656d7de37064f3a7a5d2d11d05df93839c2"
+dependencies = [
+ "html5ever 0.26.0",
+ "markup5ever 0.11.0",
+ "tendril",
+ "xml5ever",
+]
+
[[package]]
name = "match_token"
version = "0.1.0"
@@ -2874,6 +3019,16 @@ dependencies = [
"phf_shared 0.8.0",
]
+[[package]]
+name = "phf_codegen"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd"
+dependencies = [
+ "phf_generator 0.10.0",
+ "phf_shared 0.10.0",
+]
+
[[package]]
name = "phf_codegen"
version = "0.11.3"
@@ -3193,8 +3348,8 @@ dependencies = [
"quinn-proto",
"quinn-udp",
"rustc-hash",
- "rustls",
- "socket2",
+ "rustls 0.23.32",
+ "socket2 0.6.0",
"thiserror 2.0.16",
"tokio",
"tracing",
@@ -3213,7 +3368,7 @@ dependencies = [
"rand 0.9.2",
"ring",
"rustc-hash",
- "rustls",
+ "rustls 0.23.32",
"rustls-pki-types",
"slab",
"thiserror 2.0.16",
@@ -3231,7 +3386,7 @@ dependencies = [
"cfg_aliases",
"libc",
"once_cell",
- "socket2",
+ "socket2 0.6.0",
"tracing",
"windows-sys 0.60.2",
]
@@ -3436,6 +3591,47 @@ version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001"
+[[package]]
+name = "reqwest"
+version = "0.11.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62"
+dependencies = [
+ "base64 0.21.7",
+ "bytes",
+ "encoding_rs",
+ "futures-core",
+ "futures-util",
+ "h2 0.3.27",
+ "http 0.2.12",
+ "http-body 0.4.6",
+ "hyper 0.14.32",
+ "hyper-rustls 0.24.2",
+ "ipnet",
+ "js-sys",
+ "log",
+ "mime",
+ "once_cell",
+ "percent-encoding",
+ "pin-project-lite",
+ "rustls 0.21.12",
+ "rustls-pemfile",
+ "serde",
+ "serde_json",
+ "serde_urlencoded",
+ "sync_wrapper 0.1.2",
+ "system-configuration 0.5.1",
+ "tokio",
+ "tokio-rustls 0.24.1",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "webpki-roots 0.25.4",
+ "winreg 0.50.0",
+]
+
[[package]]
name = "reqwest"
version = "0.12.23"
@@ -3449,12 +3645,12 @@ dependencies = [
"encoding_rs",
"futures-core",
"futures-util",
- "h2",
- "http",
- "http-body",
+ "h2 0.4.12",
+ "http 1.3.1",
+ "http-body 1.0.1",
"http-body-util",
- "hyper",
- "hyper-rustls",
+ "hyper 1.7.0",
+ "hyper-rustls 0.27.7",
"hyper-util",
"js-sys",
"log",
@@ -3462,14 +3658,14 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"quinn",
- "rustls",
+ "rustls 0.23.32",
"rustls-pki-types",
"serde",
"serde_json",
"serde_urlencoded",
- "sync_wrapper",
+ "sync_wrapper 1.0.2",
"tokio",
- "tokio-rustls",
+ "tokio-rustls 0.26.4",
"tokio-util",
"tower",
"tower-http",
@@ -3479,7 +3675,7 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams",
"web-sys",
- "webpki-roots",
+ "webpki-roots 1.0.2",
]
[[package]]
@@ -3550,6 +3746,18 @@ dependencies = [
"windows-sys 0.61.0",
]
+[[package]]
+name = "rustls"
+version = "0.21.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e"
+dependencies = [
+ "log",
+ "ring",
+ "rustls-webpki 0.101.7",
+ "sct",
+]
+
[[package]]
name = "rustls"
version = "0.23.32"
@@ -3559,11 +3767,20 @@ dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
- "rustls-webpki",
+ "rustls-webpki 0.103.6",
"subtle",
"zeroize",
]
+[[package]]
+name = "rustls-pemfile"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c"
+dependencies = [
+ "base64 0.21.7",
+]
+
[[package]]
name = "rustls-pki-types"
version = "1.12.0"
@@ -3574,6 +3791,16 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "rustls-webpki"
+version = "0.101.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765"
+dependencies = [
+ "ring",
+ "untrusted",
+]
+
[[package]]
name = "rustls-webpki"
version = "0.103.6"
@@ -3663,6 +3890,27 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "sct"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414"
+dependencies = [
+ "ring",
+ "untrusted",
+]
+
+[[package]]
+name = "select"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5910c1d91bd7e6e178c0f8eb9e4ad01f814064b4a1c0ae3c906224a3cbf12879"
+dependencies = [
+ "bit-set",
+ "html5ever 0.26.0",
+ "markup5ever_rcdom",
+]
+
[[package]]
name = "selectors"
version = "0.24.0"
@@ -3942,6 +4190,16 @@ dependencies = [
"serde",
]
+[[package]]
+name = "socket2"
+version = "0.5.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"
+dependencies = [
+ "libc",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "socket2"
version = "0.6.0"
@@ -4304,6 +4562,12 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "sync_wrapper"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160"
+
[[package]]
name = "sync_wrapper"
version = "1.0.2"
@@ -4324,6 +4588,17 @@ dependencies = [
"syn 2.0.106",
]
+[[package]]
+name = "system-configuration"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7"
+dependencies = [
+ "bitflags 1.3.2",
+ "core-foundation 0.9.4",
+ "system-configuration-sys 0.5.0",
+]
+
[[package]]
name = "system-configuration"
version = "0.6.1"
@@ -4332,7 +4607,17 @@ checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b"
dependencies = [
"bitflags 2.9.4",
"core-foundation 0.9.4",
- "system-configuration-sys",
+ "system-configuration-sys 0.6.0",
+]
+
+[[package]]
+name = "system-configuration-sys"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
]
[[package]]
@@ -4431,7 +4716,7 @@ dependencies = [
"glob",
"gtk",
"heck 0.5.0",
- "http",
+ "http 1.3.1",
"jni",
"libc",
"log",
@@ -4445,7 +4730,7 @@ dependencies = [
"percent-encoding",
"plist",
"raw-window-handle",
- "reqwest",
+ "reqwest 0.12.23",
"serde",
"serde_json",
"serde_repr",
@@ -4553,9 +4838,9 @@ version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bbb818e0e97f72dc9d353d38fa5799ed1dd4cf7371ff3195bd1231072d6fc2d"
dependencies = [
- "http",
+ "http 1.3.1",
"once_cell",
- "reqwest",
+ "reqwest 0.12.23",
"serde",
"serde_json",
"tauri",
@@ -4615,7 +4900,7 @@ dependencies = [
"cookie",
"dpi",
"gtk",
- "http",
+ "http 1.3.1",
"jni",
"objc2 0.6.2",
"objc2-ui-kit",
@@ -4638,7 +4923,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1fe9d48bd122ff002064e88cfcd7027090d789c4302714e68fcccba0f4b7807"
dependencies = [
"gtk",
- "http",
+ "http 1.3.1",
"jni",
"log",
"objc2 0.6.2",
@@ -4670,8 +4955,8 @@ dependencies = [
"ctor",
"dunce",
"glob",
- "html5ever",
- "http",
+ "html5ever 0.29.1",
+ "http 1.3.1",
"infer",
"json-patch",
"kuchikiki",
@@ -4837,9 +5122,11 @@ dependencies = [
"io-uring",
"libc",
"mio",
+ "parking_lot",
"pin-project-lite",
+ "signal-hook-registry",
"slab",
- "socket2",
+ "socket2 0.6.0",
"tokio-macros",
"windows-sys 0.59.0",
]
@@ -4855,13 +5142,23 @@ dependencies = [
"syn 2.0.106",
]
+[[package]]
+name = "tokio-rustls"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081"
+dependencies = [
+ "rustls 0.21.12",
+ "tokio",
+]
+
[[package]]
name = "tokio-rustls"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
dependencies = [
- "rustls",
+ "rustls 0.23.32",
"tokio",
]
@@ -4994,7 +5291,7 @@ dependencies = [
"futures-core",
"futures-util",
"pin-project-lite",
- "sync_wrapper",
+ "sync_wrapper 1.0.2",
"tokio",
"tower-layer",
"tower-service",
@@ -5009,8 +5306,8 @@ dependencies = [
"bitflags 2.9.4",
"bytes",
"futures-util",
- "http",
- "http-body",
+ "http 1.3.1",
+ "http-body 1.0.1",
"iri-string",
"pin-project-lite",
"tower",
@@ -5483,6 +5780,12 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "webpki-roots"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1"
+
[[package]]
name = "webpki-roots"
version = "1.0.2"
@@ -6067,6 +6370,16 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "winreg"
+version = "0.50.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1"
+dependencies = [
+ "cfg-if",
+ "windows-sys 0.48.0",
+]
+
[[package]]
name = "winreg"
version = "0.55.0"
@@ -6104,8 +6417,8 @@ dependencies = [
"dunce",
"gdkx11",
"gtk",
- "html5ever",
- "http",
+ "html5ever 0.29.1",
+ "http 1.3.1",
"javascriptcore-rs",
"jni",
"kuchikiki",
@@ -6155,6 +6468,31 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "xml5ever"
+version = "0.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4034e1d05af98b51ad7214527730626f019682d797ba38b51689212118d8e650"
+dependencies = [
+ "log",
+ "mac",
+ "markup5ever 0.11.0",
+]
+
+[[package]]
+name = "yahoo_finance_api"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a32a69f83101eba8819cf8eb07391f21b461acf7ee61f83375ee18977de6a973"
+dependencies = [
+ "reqwest 0.11.27",
+ "select",
+ "serde",
+ "serde_json",
+ "thiserror 1.0.69",
+ "time",
+]
+
[[package]]
name = "yoke"
version = "0.8.0"
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.toml
index 6c01b0abc..17f8fea77 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.toml
+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml
@@ -24,4 +24,9 @@ tauri-plugin-cors-fetch = "4"
tauri-plugin-sql = { version = "2", features = ["sqlite"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+sha2 = "0.10"
+yahoo_finance_api = "1.2"
+tokio = { version = "1", features = ["full"] }
+anyhow = "1.0"
+time = "0.3"
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/market_data.rs b/fincept-terminal-desktop/src-tauri/src/commands/market_data.rs
new file mode 100644
index 000000000..928b0271c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/market_data.rs
@@ -0,0 +1,99 @@
+// Market data Tauri commands
+// Frontend can call these commands to fetch live market data
+
+use crate::data_sources::yfinance::{YFinanceProvider, QuoteData};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct QuoteResponse {
+ pub success: bool,
+ pub data: Option<QuoteData>,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct QuotesResponse {
+ pub success: bool,
+ pub data: Vec<QuoteData>,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct PeriodReturns {
+ pub symbol: String,
+ pub seven_day: f64,
+ pub thirty_day: f64,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct PeriodReturnsResponse {
+ pub success: bool,
+ pub data: Option<PeriodReturns>,
+ pub error: Option<String>,
+}
+
+/// Fetch a single quote
+#[tauri::command]
+pub async fn get_market_quote(symbol: String) -> Result<QuoteResponse, String> {
+
+ let provider = YFinanceProvider::new();
+
+ match provider.get_quote(&symbol).await {
+ Some(quote) => Ok(QuoteResponse {
+ success: true,
+ data: Some(quote),
+ error: None,
+ }),
+ None => Ok(QuoteResponse {
+ success: false,
+ data: None,
+ error: Some(format!("Failed to fetch quote for {}", symbol)),
+ }),
+ }
+}
+
+/// Fetch multiple quotes (batch)
+#[tauri::command]
+pub async fn get_market_quotes(symbols: Vec<String>) -> Result<QuotesResponse, String> {
+
+ let provider = YFinanceProvider::new();
+ let quotes = provider.get_quotes(symbols).await;
+
+ Ok(QuotesResponse {
+ success: true,
+ data: quotes,
+ error: None,
+ })
+}
+
+/// Fetch period returns (7D, 30D)
+#[tauri::command]
+pub async fn get_period_returns(symbol: String) -> Result<PeriodReturnsResponse, String> {
+
+ let provider = YFinanceProvider::new();
+
+ match provider.get_period_returns(&symbol).await {
+ Some((seven_day, thirty_day)) => Ok(PeriodReturnsResponse {
+ success: true,
+ data: Some(PeriodReturns {
+ symbol,
+ seven_day,
+ thirty_day,
+ }),
+ error: None,
+ }),
+ None => Ok(PeriodReturnsResponse {
+ success: false,
+ data: None,
+ error: Some(format!("Failed to fetch returns for {}", symbol)),
+ }),
+ }
+}
+
+/// Health check for market data provider
+#[tauri::command]
+pub async fn check_market_data_health() -> Result<bool, String> {
+
+ let provider = YFinanceProvider::new();
+ Ok(provider.health_check().await)
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
new file mode 100644
index 000000000..89cc96aae
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
@@ -0,0 +1,2 @@
+// Tauri commands module
+pub mod market_data;
diff --git a/fincept-terminal-desktop/src-tauri/src/data_sources/mod.rs b/fincept-terminal-desktop/src-tauri/src/data_sources/mod.rs
new file mode 100644
index 000000000..d8ff36036
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/data_sources/mod.rs
@@ -0,0 +1,2 @@
+// Data sources module - modular architecture for different market data providers
+pub mod yfinance;
diff --git a/fincept-terminal-desktop/src-tauri/src/data_sources/yfinance.rs b/fincept-terminal-desktop/src-tauri/src/data_sources/yfinance.rs
new file mode 100644
index 000000000..afc717832
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/data_sources/yfinance.rs
@@ -0,0 +1,316 @@
+// YFinance data source wrapper
+// Modular design: if this fails, app continues working with other data sources
+
+use serde::{Deserialize, Serialize};
+use yahoo_finance_api as yahoo;
+use anyhow::{Result, Context};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct QuoteData {
+ pub symbol: String,
+ pub price: f64,
+ pub change: f64,
+ pub change_percent: f64,
+ pub volume: Option<u64>,
+ pub high: Option<f64>,
+ pub low: Option<f64>,
+ pub open: Option<f64>,
+ pub previous_close: Option<f64>,
+ pub timestamp: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct HistoricalData {
+ pub symbol: String,
+ pub timestamp: i64,
+ pub open: f64,
+ pub high: f64,
+ pub low: f64,
+ pub close: f64,
+ pub volume: u64,
+ pub adj_close: f64,
+}
+
+pub struct YFinanceProvider {
+ provider: yahoo::YahooConnector,
+}
+
+impl YFinanceProvider {
+ /// Create a new YFinance provider instance
+ pub fn new() -> Self {
+ Self {
+ provider: yahoo::YahooConnector::new(),
+ }
+ }
+
+ /// Fetch real-time quote for a single symbol
+ /// Returns None if fetch fails (graceful degradation)
+ pub async fn get_quote(&self, symbol: &str) -> Option<QuoteData> {
+ match self.fetch_quote(symbol).await {
+ Ok(quote) => Some(quote),
+ Err(_e) => {
+ // Silent fail for production
+ None
+ }
+ }
+ }
+
+ /// Fetch real-time quotes for multiple symbols
+ /// Returns only successful fetches (partial success)
+ pub async fn get_quotes(&self, symbols: Vec<String>) -> Vec<QuoteData> {
+ let mut quotes = Vec::new();
+
+ for symbol in symbols {
+ if let Some(quote) = self.get_quote(&symbol).await {
+ quotes.push(quote);
+ }
+ // Small delay to avoid rate limiting
+ tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;
+ }
+
+ quotes
+ }
+
+ /// Internal fetch method with error handling
+ async fn fetch_quote(&self, symbol: &str) -> Result<QuoteData> {
+ // TEMPORARY: Mock data until Yahoo Finance API is fixed
+ // TODO: Replace with actual API call or switch to Alpha Vantage/Finnhub
+
+ use std::collections::HashMap;
+
+ let mut mock_prices: HashMap<&str, f64> = HashMap::new();
+ // Stock Indices
+ mock_prices.insert("^GSPC", 5870.62);
+ mock_prices.insert("^IXIC", 18489.55);
+ mock_prices.insert("^DJI", 38546.12);
+ mock_prices.insert("^RUT", 2087.45);
+ mock_prices.insert("^VIX", 18.23);
+ mock_prices.insert("^FTSE", 7623.98);
+ mock_prices.insert("^GDAXI", 18245.67);
+ mock_prices.insert("^N225", 35897.45);
+ mock_prices.insert("^FCHI", 7890.12);
+ mock_prices.insert("^HSI", 18654.23);
+
+ // Forex
+ mock_prices.insert("EURUSD=X", 1.0840);
+ mock_prices.insert("GBPUSD=X", 1.2567);
+ mock_prices.insert("JPY=X", 151.45);
+ mock_prices.insert("CHF=X", 0.8923);
+ mock_prices.insert("CAD=X", 1.3578);
+ mock_prices.insert("AUDUSD=X", 0.6634);
+ mock_prices.insert("NZDUSD=X", 0.6089);
+ mock_prices.insert("EURGBP=X", 0.8623);
+ mock_prices.insert("EURJPY=X", 164.23);
+ mock_prices.insert("GBPJPY=X", 190.45);
+
+ // Commodities
+ mock_prices.insert("GC=F", 2312.80);
+ mock_prices.insert("SI=F", 28.45);
+ mock_prices.insert("CL=F", 78.35);
+ mock_prices.insert("BZ=F", 82.10);
+ mock_prices.insert("NG=F", 3.45);
+ mock_prices.insert("HG=F", 4.23);
+ mock_prices.insert("PL=F", 987.50);
+ mock_prices.insert("PA=F", 1045.20);
+ mock_prices.insert("ZW=F", 567.80);
+ mock_prices.insert("ZC=F", 478.90);
+
+ // Bonds
+ mock_prices.insert("^TNX", 4.35);
+ mock_prices.insert("^TYX", 4.52);
+ mock_prices.insert("^IRX", 4.89);
+ mock_prices.insert("DE10Y=X", 2.45);
+ mock_prices.insert("GB10Y=X", 4.12);
+ mock_prices.insert("JP10Y=X", 0.78);
+ mock_prices.insert("FR10Y=X", 2.98);
+ mock_prices.insert("IT10Y=X", 4.23);
+ mock_prices.insert("ES10Y=X", 3.67);
+ mock_prices.insert("CA10Y=X", 3.89);
+
+ // ETFs
+ mock_prices.insert("SPY", 523.45);
+ mock_prices.insert("QQQ", 412.67);
+ mock_prices.insert("DIA", 385.23);
+ mock_prices.insert("EEM", 41.78);
+ mock_prices.insert("GLD", 231.45);
+ mock_prices.insert("XLK", 198.90);
+ mock_prices.insert("XLE", 89.34);
+ mock_prices.insert("XLF", 42.56);
+ mock_prices.insert("XLV", 156.78);
+ mock_prices.insert("VNQ", 78.90);
+
+ // Cryptocurrencies
+ mock_prices.insert("BTC-USD", 67890.45);
+ mock_prices.insert("ETH-USD", 3789.23);
+ mock_prices.insert("BNB-USD", 567.89);
+ mock_prices.insert("SOL-USD", 234.56);
+ mock_prices.insert("DOGE-USD", 0.1234);
+ mock_prices.insert("MATIC-USD", 1.23);
+ mock_prices.insert("LINK-USD", 23.45);
+ mock_prices.insert("ADA-USD", 0.67);
+ mock_prices.insert("DOT-USD", 12.34);
+ mock_prices.insert("AVAX-USD", 45.67);
+
+ // Regional - India
+ mock_prices.insert("RELIANCE.NS", 2500.45);
+ mock_prices.insert("TCS.NS", 3456.78);
+ mock_prices.insert("HDFCBANK.NS", 1678.90);
+ mock_prices.insert("INFY.NS", 1234.56);
+ mock_prices.insert("HINDUNILVR.NS", 2345.67);
+ mock_prices.insert("ICICIBANK.NS", 987.65);
+ mock_prices.insert("SBIN.NS", 678.90);
+ mock_prices.insert("BHARTIARTL.NS", 876.54);
+
+ // Regional - China
+ mock_prices.insert("BABA", 85.67);
+ mock_prices.insert("PDD", 123.45);
+ mock_prices.insert("JD", 34.56);
+ mock_prices.insert("BIDU", 145.67);
+ mock_prices.insert("TCEHY", 45.78);
+ mock_prices.insert("NIO", 12.34);
+ mock_prices.insert("LI", 23.45);
+ mock_prices.insert("XPEV", 15.67);
+
+ // Regional - US
+ mock_prices.insert("AAPL", 175.43);
+ mock_prices.insert("MSFT", 420.67);
+ mock_prices.insert("GOOGL", 140.23);
+ mock_prices.insert("AMZN", 145.32);
+ mock_prices.insert("NVDA", 800.45);
+ mock_prices.insert("META", 345.67);
+ mock_prices.insert("TSLA", 200.78);
+ mock_prices.insert("JPM", 156.89);
+
+ let base_price = mock_prices.get(symbol).copied().unwrap_or(100.0);
+
+ // Add some random variation
+ use std::hash::{Hash, Hasher};
+ use std::collections::hash_map::DefaultHasher;
+ let mut hasher = DefaultHasher::new();
+ symbol.hash(&mut hasher);
+ let hash = hasher.finish();
+ let variation = (hash % 1000) as f64 / 10000.0; // 0-10% variation
+
+ let price = base_price * (1.0 + variation);
+ let previous_close = base_price;
+ let change = price - previous_close;
+ let change_percent = (change / previous_close) * 100.0;
+
+ Ok(QuoteData {
+ symbol: symbol.to_string(),
+ price,
+ change,
+ change_percent,
+ volume: Some(1_000_000),
+ high: Some(price * 1.02),
+ low: Some(price * 0.98),
+ open: Some(previous_close),
+ previous_close: Some(previous_close),
+ timestamp: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs() as i64,
+ })
+ }
+
+ /// Fetch historical data for a symbol
+ /// Returns None if fetch fails (graceful degradation)
+ pub async fn get_historical(
+ &self,
+ symbol: &str,
+ start: i64,
+ end: i64,
+ ) -> Option<Vec<HistoricalData>> {
+ match self.fetch_historical(symbol, start, end).await {
+ Ok(data) => Some(data),
+ Err(_e) => {
+ // Silent fail for production
+ None
+ }
+ }
+ }
+
+ /// Internal historical fetch method
+ async fn fetch_historical(
+ &self,
+ symbol: &str,
+ start: i64,
+ end: i64,
+ ) -> Result<Vec<HistoricalData>> {
+ use time::OffsetDateTime;
+
+ let start_time = OffsetDateTime::from_unix_timestamp(start)
+ .context("Invalid start timestamp")?;
+ let end_time = OffsetDateTime::from_unix_timestamp(end)
+ .context("Invalid end timestamp")?;
+
+ let response = self.provider
+ .get_quote_history(symbol, start_time, end_time)
+ .await
+ .context("Failed to fetch historical data")?;
+
+ let quotes = response.quotes()
+ .context("No historical quotes available")?;
+
+ let historical: Vec<HistoricalData> = quotes
+ .iter()
+ .map(|q| HistoricalData {
+ symbol: symbol.to_string(),
+ timestamp: q.timestamp as i64,
+ open: q.open,
+ high: q.high,
+ low: q.low,
+ close: q.close,
+ volume: q.volume,
+ adj_close: q.adjclose,
+ })
+ .collect();
+
+ Ok(historical)
+ }
+
+ /// Calculate period returns (7D, 30D) for a symbol
+ pub async fn get_period_returns(&self, symbol: &str) -> Option<(f64, f64)> {
+ // TEMPORARY: Mock data
+ use std::hash::{Hash, Hasher};
+ use std::collections::hash_map::DefaultHasher;
+
+ let mut hasher = DefaultHasher::new();
+ symbol.hash(&mut hasher);
+ let hash = hasher.finish();
+
+ let seven_day = ((hash % 200) as f64 - 100.0) / 10.0; // -10% to +10%
+ let thirty_day = ((hash % 300) as f64 - 150.0) / 10.0; // -15% to +15%
+
+ Some((seven_day, thirty_day))
+ }
+
+ /// Health check - tests if the provider is working
+ pub async fn health_check(&self) -> bool {
+ self.get_quote("AAPL").await.is_some()
+ }
+}
+
+impl Default for YFinanceProvider {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn test_quote_fetch() {
+ let provider = YFinanceProvider::new();
+ let quote = provider.get_quote("AAPL").await;
+ assert!(quote.is_some());
+ }
+
+ #[tokio::test]
+ async fn test_health_check() {
+ let provider = YFinanceProvider::new();
+ assert!(provider.health_check().await);
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index e305e3aa6..43d4b775f 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -1,16 +1,226 @@
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
+
+use std::collections::HashMap;
+use std::process::{Child, Command, Stdio};
+use std::sync::Mutex;
+use std::io::{BufRead, BufReader, Write};
+use serde::Serialize;
+use sha2::{Sha256, Digest};
+
+// Data sources and commands modules
+mod data_sources;
+mod commands;
+
+// Global state to manage MCP server processes
+struct MCPState {
+ processes: Mutex<HashMap<String, Child>>,
+}
+
+#[derive(Debug, Serialize)]
+struct SpawnResult {
+ pid: u32,
+ success: bool,
+ error: Option<String>,
+}
+
#[tauri::command]
fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}
+// Spawn an MCP server process
+#[tauri::command]
+fn spawn_mcp_server(
+ state: tauri::State<MCPState>,
+ server_id: String,
+ command: String,
+ args: Vec<String>,
+ env: HashMap<String, String>,
+) -> Result<SpawnResult, String> {
+ println!("[Tauri] Spawning MCP server: {} with command: {} {:?}", server_id, command, args);
+
+ // Build command
+ let mut cmd = Command::new(&command);
+ cmd.args(&args)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ // Add environment variables
+ for (key, value) in env {
+ cmd.env(key, value);
+ }
+
+ // Spawn process
+ match cmd.spawn() {
+ Ok(child) => {
+ let pid = child.id();
+ println!("[Tauri] MCP server spawned successfully with PID: {}", pid);
+
+ // Store process
+ let mut processes = state.processes.lock().unwrap();
+ processes.insert(server_id.clone(), child);
+
+ Ok(SpawnResult {
+ pid,
+ success: true,
+ error: None,
+ })
+ }
+ Err(e) => {
+ eprintln!("[Tauri] Failed to spawn MCP server: {}", e);
+ Ok(SpawnResult {
+ pid: 0,
+ success: false,
+ error: Some(format!("Failed to spawn process: {}", e)),
+ })
+ }
+ }
+}
+
+// Send JSON-RPC request to MCP server
+#[tauri::command]
+fn send_mcp_request(
+ state: tauri::State<MCPState>,
+ server_id: String,
+ request: String,
+) -> Result<String, String> {
+ println!("[Tauri] Sending request to server {}: {}", server_id, request);
+
+ let mut processes = state.processes.lock().unwrap();
+
+ if let Some(child) = processes.get_mut(&server_id) {
+ // Get stdin handle
+ if let Some(ref mut stdin) = child.stdin {
+ // Write request
+ if let Err(e) = writeln!(stdin, "{}", request) {
+ return Err(format!("Failed to write to stdin: {}", e));
+ }
+
+ if let Err(e) = stdin.flush() {
+ return Err(format!("Failed to flush stdin: {}", e));
+ }
+
+ // Read response from stdout
+ if let Some(ref mut stdout) = child.stdout {
+ let reader = BufReader::new(stdout);
+ if let Some(Ok(line)) = reader.lines().next() {
+ println!("[Tauri] Received response: {}", line);
+ return Ok(line);
+ } else {
+ return Err("No response from server".to_string());
+ }
+ } else {
+ return Err("No stdout available".to_string());
+ }
+ } else {
+ return Err("No stdin available".to_string());
+ }
+ } else {
+ return Err(format!("Server {} not found", server_id));
+ }
+}
+
+// Send notification (fire and forget)
+#[tauri::command]
+fn send_mcp_notification(
+ state: tauri::State<MCPState>,
+ server_id: String,
+ notification: String,
+) -> Result<(), String> {
+ println!("[Tauri] Sending notification to server {}: {}", server_id, notification);
+
+ let mut processes = state.processes.lock().unwrap();
+
+ if let Some(child) = processes.get_mut(&server_id) {
+ if let Some(ref mut stdin) = child.stdin {
+ writeln!(stdin, "{}", notification)
+ .map_err(|e| format!("Failed to write notification: {}", e))?;
+ stdin.flush()
+ .map_err(|e| format!("Failed to flush: {}", e))?;
+ Ok(())
+ } else {
+ Err("No stdin available".to_string())
+ }
+ } else {
+ Err(format!("Server {} not found", server_id))
+ }
+}
+
+// Ping MCP server to check if alive
+#[tauri::command]
+fn ping_mcp_server(
+ state: tauri::State<MCPState>,
+ server_id: String,
+) -> Result<bool, String> {
+ let mut processes = state.processes.lock().unwrap();
+
+ if let Some(child) = processes.get_mut(&server_id) {
+ // Check if process is still running
+ match child.try_wait() {
+ Ok(Some(_)) => Ok(false), // Process has exited
+ Ok(None) => Ok(true), // Process is still running
+ Err(_) => Ok(false), // Error checking status
+ }
+ } else {
+ Ok(false) // Server not found
+ }
+}
+
+// Kill MCP server
+#[tauri::command]
+fn kill_mcp_server(
+ state: tauri::State<MCPState>,
+ server_id: String,
+) -> Result<(), String> {
+ println!("[Tauri] Killing MCP server: {}", server_id);
+
+ let mut processes = state.processes.lock().unwrap();
+
+ if let Some(mut child) = processes.remove(&server_id) {
+ match child.kill() {
+ Ok(_) => {
+ println!("[Tauri] Server {} killed successfully", server_id);
+ Ok(())
+ }
+ Err(e) => Err(format!("Failed to kill server: {}", e)),
+ }
+ } else {
+ Ok(()) // Server not found, consider it killed
+ }
+}
+
+// SHA256 hash for Fyers authentication
+#[tauri::command]
+fn sha256_hash(input: String) -> String {
+ let mut hasher = Sha256::new();
+ hasher.update(input.as_bytes());
+ let result = hasher.finalize();
+ format!("{:x}", result)
+}
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_cors_fetch::init())
.plugin(tauri_plugin_sql::Builder::default().build())
- .invoke_handler(tauri::generate_handler![greet])
+ .manage(MCPState {
+ processes: Mutex::new(HashMap::new()),
+ })
+ .invoke_handler(tauri::generate_handler![
+ greet,
+ spawn_mcp_server,
+ send_mcp_request,
+ send_mcp_notification,
+ ping_mcp_server,
+ kill_mcp_server,
+ sha256_hash,
+ commands::market_data::get_market_quote,
+ commands::market_data::get_market_quotes,
+ commands::market_data::get_period_returns,
+ commands::market_data::check_market_data_health
+ ])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
diff --git a/fincept-terminal-desktop/src/App.css b/fincept-terminal-desktop/src/App.css
index 83bc82fb9..091f0984c 100644
--- a/fincept-terminal-desktop/src/App.css
+++ b/fincept-terminal-desktop/src/App.css
@@ -118,3 +118,28 @@
@apply bg-background text-foreground;
}
}
+
+/* Custom transparent scrollbar for Fyers Market Data Panel */
+.custom-scrollbar::-webkit-scrollbar {
+ width: 8px;
+ height: 8px;
+}
+
+.custom-scrollbar::-webkit-scrollbar-track {
+ background: transparent;
+}
+
+.custom-scrollbar::-webkit-scrollbar-thumb {
+ background: rgba(255, 165, 0, 0.2);
+ border-radius: 4px;
+}
+
+.custom-scrollbar::-webkit-scrollbar-thumb:hover {
+ background: rgba(255, 165, 0, 0.4);
+}
+
+/* Firefox scrollbar */
+.custom-scrollbar {
+ scrollbar-width: thin;
+ scrollbar-color: rgba(255, 165, 0, 0.2) transparent;
+}
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index e0275e03c..614dfc564 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -28,6 +28,8 @@ import NodeEditorTab from '@/components/tabs/NodeEditorTab';
import DataSourcesTab from '@/components/tabs/data-sources/DataSourcesTab';
import AgentsTab from '@/components/tabs/agents/AgentsTab';
import DataMappingTab from '@/components/tabs/data-mapping/DataMappingTab';
+import MCPTab from '@/components/tabs/mcp';
+import FyersTab from '@/components/tabs/fyers';
// Dropdown Menu Component
const DropdownMenu = ({ label, items, onItemClick }: { label: string; items: any[]; onItemClick: (item: any) => void }) => {
@@ -502,6 +504,18 @@ export default function FinxeptTerminal() {
>
AI Chat
</TabsTrigger>
+ <TabsTrigger
+ value="fyers"
+ style={activeTab === 'fyers' ? tabStyles.active : tabStyles.default}
+ >
+ Fyers
+ </TabsTrigger>
+ <TabsTrigger
+ value="mcp"
+ style={activeTab === 'mcp' ? tabStyles.active : tabStyles.default}
+ >
+ MCP
+ </TabsTrigger>
<TabsTrigger
value="profile"
style={activeTab === 'profile' ? tabStyles.active : tabStyles.default}
@@ -695,6 +709,12 @@ export default function FinxeptTerminal() {
<TabsContent value="chat" className="h-full m-0 p-0">
<ChatTab />
</TabsContent>
+ <TabsContent value="fyers" className="h-full m-0 p-0">
+ <FyersTab />
+ </TabsContent>
+ <TabsContent value="mcp" className="h-full m-0 p-0">
+ <MCPTab />
+ </TabsContent>
<TabsContent value="profile" className="h-full m-0 p-0">
<ProfileTab />
</TabsContent>
diff --git a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
index 40160dc14..31457bebb 100644
--- a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
@@ -314,24 +314,61 @@ const ChatTab: React.FC = () => {
content: msg.content
}));
- // Call LLM API with streaming
- const response = await llmApiService.chat(
- userContent,
- conversationHistory,
- (chunk: string, done: boolean) => {
- if (!done) {
- flushSync(() => {
- setStreamingContent(prev => prev + chunk);
- });
- } else {
- flushSync(() => {
- setIsTyping(false);
- setStreamingContent('');
- setSystemStatus('STATUS: READY');
- });
- }
- }
- );
+ // Get MCP tools if available
+ let mcpTools: any[] = [];
+ try {
+ const { mcpManager } = await import('../../services/mcpManager');
+ mcpTools = await mcpManager.getAllTools();
+ console.log(`[Chat] Found ${mcpTools.length} MCP tools`);
+ } catch (error) {
+ console.log('[Chat] No MCP tools available');
+ }
+
+ // Call LLM API with tools if available
+ const response = mcpTools.length > 0
+ ? await llmApiService.chatWithTools(
+ userContent,
+ conversationHistory,
+ mcpTools,
+ (chunk: string, done: boolean) => {
+ if (!done) {
+ flushSync(() => {
+ setStreamingContent(prev => prev + chunk);
+ });
+ } else {
+ flushSync(() => {
+ setIsTyping(false);
+ setStreamingContent('');
+ setSystemStatus('STATUS: READY');
+ });
+ }
+ },
+ (toolName: string, args: any, result?: any) => {
+ // Tool call callback
+ if (!result) {
+ setSystemStatus(`STATUS: Calling tool ${toolName}...`);
+ } else {
+ setSystemStatus(`STATUS: Tool ${toolName} completed`);
+ }
+ }
+ )
+ : await llmApiService.chat(
+ userContent,
+ conversationHistory,
+ (chunk: string, done: boolean) => {
+ if (!done) {
+ flushSync(() => {
+ setStreamingContent(prev => prev + chunk);
+ });
+ } else {
+ flushSync(() => {
+ setIsTyping(false);
+ setStreamingContent('');
+ setSystemStatus('STATUS: READY');
+ });
+ }
+ }
+ );
if (response.error) {
const errorMessage = await sqliteService.addChatMessage({
diff --git a/fincept-terminal-desktop/src/components/tabs/MarketsTab.old.tsx b/fincept-terminal-desktop/src/components/tabs/MarketsTab.old.tsx
new file mode 100644
index 000000000..06184ca73
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/MarketsTab.old.tsx
@@ -0,0 +1,524 @@
+import React, { useState, useEffect } from 'react';
+
+const MarketsTab: React.FC = () => {
+ const [currentTime, setCurrentTime] = useState(new Date());
+ const [lastUpdate, setLastUpdate] = useState(new Date());
+ const [isUpdating, setIsUpdating] = useState(false);
+ const [autoUpdate, setAutoUpdate] = useState(true);
+
+ // Bloomberg color scheme (exact from Python)
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_RED = '#FF0000';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#1a1a1a';
+ const BLOOMBERG_PANEL_BG = '#000000';
+
+ // Market data (exact structure from Python)
+ const marketData: { [key: string]: string[][] } = {
+ 'Stock Indices': [
+ ['S&P 500', '5232.35', '+23.45', '+0.45%', '+2.1%', '+5.4%'],
+ ['Nasdaq 100', '16412.87', '-15.23', '-0.09%', '+1.8%', '+7.2%'],
+ ['Dow Jones', '38546.12', '+156.78', '+0.41%', '+1.5%', '+3.9%'],
+ ['Russell 2000', '2087.45', '+8.90', '+0.43%', '+2.3%', '+4.1%'],
+ ['VIX', '18.23', '-0.45', '-2.41%', '-5.2%', '-8.7%'],
+ ['FTSE 100', '7623.98', '+12.34', '+0.16%', '+0.8%', '+2.3%'],
+ ['DAX 40', '18245.67', '+89.23', '+0.49%', '+1.2%', '+4.6%'],
+ ['Nikkei 225', '35897.45', '-123.45', '-0.34%', '-0.5%', '+1.8%'],
+ ['CAC 40', '7890.12', '+45.67', '+0.58%', '+1.8%', '+4.2%'],
+ ['Hang Seng', '18654.23', '-89.45', '-0.48%', '-1.2%', '+2.8%']
+ ],
+ 'Forex': [
+ ['EUR/USD', '1.0840', '+0.0023', '+0.21%', '+0.8%', '+2.1%'],
+ ['GBP/USD', '1.2567', '-0.0012', '-0.10%', '-0.3%', '+1.5%'],
+ ['USD/JPY', '151.45', '+0.35', '+0.23%', '+1.2%', '+3.4%'],
+ ['USD/CHF', '0.8923', '-0.0034', '-0.38%', '-0.7%', '-1.2%'],
+ ['USD/CAD', '1.3578', '+0.0089', '+0.66%', '+0.4%', '+1.8%'],
+ ['AUD/USD', '0.6634', '+0.0067', '+1.02%', '+2.1%', '+4.3%'],
+ ['NZD/USD', '0.6089', '-0.0034', '-0.56%', '-0.8%', '+1.2%'],
+ ['EUR/GBP', '0.8623', '+0.0012', '+0.14%', '+0.3%', '+0.9%'],
+ ['EUR/JPY', '164.23', '+0.89', '+0.54%', '+1.8%', '+5.1%'],
+ ['GBP/JPY', '190.45', '-1.23', '-0.64%', '-0.9%', '+2.3%']
+ ],
+ 'Commodities': [
+ ['Gold', '2312.80', '+12.45', '+0.54%', '+1.8%', '+5.2%'],
+ ['Silver', '28.45', '-0.67', '-2.30%', '-1.2%', '+3.1%'],
+ ['Crude Oil (WTI)', '78.35', '-1.23', '-1.55%', '-2.8%', '-0.5%'],
+ ['Brent Crude', '82.10', '-0.89', '-1.07%', '-2.1%', '+1.2%'],
+ ['Natural Gas', '3.45', '+0.12', '+3.60%', '+8.2%', '+12.4%'],
+ ['Copper', '4.23', '+0.045', '+1.08%', '+2.3%', '+6.7%'],
+ ['Platinum', '987.50', '+8.90', '+0.91%', '+2.1%', '+4.8%'],
+ ['Palladium', '1045.20', '-12.45', '-1.18%', '-2.3%', '-5.1%'],
+ ['Wheat', '567.80', '+5.67', '+1.01%', '+3.2%', '+7.9%'],
+ ['Corn', '478.90', '-3.45', '-0.72%', '-1.8%', '+2.4%']
+ ],
+ 'Bonds': [
+ ['US 10Y Treasury', '4.35%', '+0.02', '+0.46%', '+1.2%', '+3.4%'],
+ ['US 30Y Treasury', '4.52%', '+0.01', '+0.22%', '+0.8%', '+2.1%'],
+ ['US 2Y Treasury', '4.89%', '-0.03', '-0.61%', '-0.5%', '+1.8%'],
+ ['Germany 10Y', '2.45%', '+0.01', '+0.41%', '+0.6%', '+1.9%'],
+ ['UK 10Y', '4.12%', '-0.02', '-0.48%', '-0.3%', '+2.3%'],
+ ['Japan 10Y', '0.78%', '+0.01', '+1.30%', '+2.1%', '+8.7%'],
+ ['France 10Y', '2.98%', '+0.02', '+0.67%', '+0.9%', '+2.8%'],
+ ['Italy 10Y', '4.23%', '-0.01', '-0.24%', '-0.2%', '+1.5%'],
+ ['Spain 10Y', '3.67%', '+0.03', '+0.82%', '+1.1%', '+3.2%'],
+ ['Canada 10Y', '3.89%', '+0.01', '+0.26%', '+0.7%', '+2.1%']
+ ],
+ 'ETFs': [
+ ['SPY (S&P 500)', '523.45', '+2.34', '+0.45%', '+2.1%', '+5.4%'],
+ ['QQQ (Nasdaq)', '412.67', '-1.23', '-0.30%', '+1.8%', '+7.2%'],
+ ['DIA (Dow)', '385.23', '+1.56', '+0.41%', '+1.5%', '+3.9%'],
+ ['EEM (Emerging)', '41.78', '+0.34', '+0.82%', '+3.2%', '+6.8%'],
+ ['GLD (Gold)', '231.45', '+1.23', '+0.53%', '+1.8%', '+5.1%'],
+ ['XLK (Tech)', '198.90', '-0.89', '-0.45%', '+2.3%', '+8.9%'],
+ ['XLE (Energy)', '89.34', '+1.45', '+1.65%', '+3.8%', '+7.2%'],
+ ['XLF (Finance)', '42.56', '-0.67', '-1.55%', '-1.2%', '+2.1%'],
+ ['XLV (Health)', '156.78', '+0.98', '+0.63%', '+1.1%', '+3.7%'],
+ ['VNQ (REIT)', '78.90', '-1.12', '-1.40%', '-2.3%', '+1.8%']
+ ],
+ 'Cryptocurrencies': [
+ ['Bitcoin', '67890.45', '+1234.56', '+1.85%', '+8.2%', '+15.7%'],
+ ['Ethereum', '3789.23', '-67.89', '-1.76%', '+5.4%', '+12.3%'],
+ ['Binance Coin', '567.89', '+12.34', '+2.22%', '+6.8%', '+18.9%'],
+ ['Solana', '234.56', '+8.90', '+3.94%', '+12.1%', '+25.6%'],
+ ['Dogecoin', '0.1234', '-0.0045', '-3.52%', '-2.1%', '+8.7%'],
+ ['Polygon', '1.23', '+0.045', '+3.80%', '+9.8%', '+21.4%'],
+ ['Chainlink', '23.45', '+0.89', '+3.94%', '+7.2%', '+14.8%'],
+ ['Cardano', '0.67', '-0.023', '-3.32%', '-1.8%', '+5.4%'],
+ ['Polkadot', '12.34', '+0.56', '+4.76%', '+8.9%', '+19.2%'],
+ ['Avalanche', '45.67', '-1.23', '-2.62%', '-3.1%', '+11.7%']
+ ]
+ };
+
+ // Regional data (exact from Python)
+ const regionalData: { [key: string]: string[][] } = {
+ 'India': [
+ ['RELIANCE.NS', 'Reliance Industries', '2500.45', '+23.45', '+0.95%'],
+ ['TCS.NS', 'Tata Consultancy', '3456.78', '-12.34', '-0.36%'],
+ ['HDFCBANK.NS', 'HDFC Bank', '1678.90', '+8.90', '+0.53%'],
+ ['INFY.NS', 'Infosys', '1234.56', '+15.67', '+1.29%'],
+ ['HINDUNILVR.NS', 'Hindustan Unilever', '2345.67', '-5.43', '-0.23%'],
+ ['ICICIBANK.NS', 'ICICI Bank', '987.65', '+12.34', '+1.27%'],
+ ['SBIN.NS', 'State Bank of India', '678.90', '+3.45', '+0.51%'],
+ ['BHARTIARTL.NS', 'Bharti Airtel', '876.54', '-7.89', '-0.89%']
+ ],
+ 'China': [
+ ['BABA', 'Alibaba Group', '85.67', '+2.34', '+2.81%'],
+ ['PDD', 'PDD Holdings', '123.45', '-1.23', '-0.99%'],
+ ['JD', 'JD.com', '34.56', '+0.89', '+2.64%'],
+ ['BIDU', 'Baidu', '145.67', '+3.45', '+2.43%'],
+ ['TCEHY', 'Tencent Holdings', '45.78', '-0.67', '-1.44%'],
+ ['NIO', 'NIO Inc', '12.34', '+0.45', '+3.78%'],
+ ['LI', 'Li Auto', '23.45', '+1.23', '+5.54%'],
+ ['XPEV', 'XPeng', '15.67', '-0.89', '-5.38%']
+ ],
+ 'United States': [
+ ['AAPL', 'Apple Inc', '175.43', '+2.34', '+1.35%'],
+ ['MSFT', 'Microsoft Corp', '420.67', '+4.12', '+0.99%'],
+ ['GOOGL', 'Alphabet Inc', '140.23', '-1.23', '-0.87%'],
+ ['AMZN', 'Amazon.com', '145.32', '+1.89', '+1.32%'],
+ ['NVDA', 'NVIDIA Corp', '800.45', '+12.45', '+1.58%'],
+ ['META', 'Meta Platforms', '345.67', '-2.34', '-0.67%'],
+ ['TSLA', 'Tesla Inc', '200.78', '-5.67', '-2.75%'],
+ ['JPM', 'JPMorgan Chase', '156.89', '+1.23', '+0.79%']
+ ]
+ };
+
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setCurrentTime(new Date());
+ if (autoUpdate) {
+ setIsUpdating(true);
+ setLastUpdate(new Date());
+ setTimeout(() => setIsUpdating(false), 1000);
+ }
+ }, 5000);
+ return () => clearInterval(timer);
+ }, [autoUpdate]);
+
+ // Create market panel (responsive layout)
+ const createMarketPanel = (title: string, data: string[][]) => (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ flex: '1 1 calc(33.333% - 16px)',
+ minWidth: '300px',
+ maxWidth: '600px',
+ height: '280px',
+ margin: '8px',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Panel Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_ORANGE,
+ padding: '8px',
+ fontSize: '14px',
+ fontWeight: 'bold',
+ textAlign: 'center',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ {title.toUpperCase()}
+ </div>
+
+ {/* Table Header */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr 1fr',
+ gap: '4px',
+ padding: '4px 8px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <div>SYMBOL</div>
+ <div style={{ textAlign: 'right' }}>PRICE</div>
+ <div style={{ textAlign: 'right' }}>CHANGE</div>
+ <div style={{ textAlign: 'right' }}>%CHG</div>
+ <div style={{ textAlign: 'right' }}>7D</div>
+ <div style={{ textAlign: 'right' }}>30D</div>
+ </div>
+
+ {/* Data Rows */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {data.map((row, index) => (
+ <div key={index} style={{
+ display: 'grid',
+ gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr 1fr',
+ gap: '4px',
+ padding: '2px 8px',
+ fontSize: '10px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`,
+ minHeight: '18px',
+ alignItems: 'center'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE }}>{row[0]}</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{row[1]}</div>
+ <div style={{
+ color: row[2].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[2]}</div>
+ <div style={{
+ color: row[3].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[3]}</div>
+ <div style={{
+ color: row[4].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[4]}</div>
+ <div style={{
+ color: row[5].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[5]}</div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+
+ // Create regional panel (responsive layout)
+ const createRegionalPanel = (title: string, data: string[][]) => (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ flex: '1 1 calc(33.333% - 16px)',
+ minWidth: '300px',
+ maxWidth: '600px',
+ height: '300px',
+ margin: '8px',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Panel Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_ORANGE,
+ padding: '8px',
+ fontSize: '14px',
+ fontWeight: 'bold',
+ textAlign: 'center',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ {title.toUpperCase()} - LIVE DATA
+ </div>
+
+ {/* Table Header */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
+ gap: '4px',
+ padding: '4px 8px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <div>SYMBOL</div>
+ <div>NAME</div>
+ <div style={{ textAlign: 'right' }}>PRICE</div>
+ <div style={{ textAlign: 'right' }}>CHANGE</div>
+ <div style={{ textAlign: 'right' }}>%CHG</div>
+ </div>
+
+ {/* Data Rows */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {data.map((row, index) => (
+ <div key={index} style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
+ gap: '4px',
+ padding: '2px 8px',
+ fontSize: '10px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`,
+ minHeight: '18px',
+ alignItems: 'center'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE }}>{row[0]}</div>
+ <div style={{ color: BLOOMBERG_WHITE, overflow: 'hidden', textOverflow: 'ellipsis' }}>{row[1]}</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{row[2]}</div>
+ <div style={{
+ color: row[3].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[3]}</div>
+ <div style={{
+ color: row[4].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[4]}</div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+
+ const categories = Object.keys(marketData);
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontFamily: 'Consolas, monospace',
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ <style>{`
+ /* Custom scrollbar styles */
+ *::-webkit-scrollbar {
+ width: 8px;
+ height: 8px;
+ }
+ *::-webkit-scrollbar-track {
+ background: #1a1a1a;
+ }
+ *::-webkit-scrollbar-thumb {
+ background: #404040;
+ border-radius: 4px;
+ }
+ *::-webkit-scrollbar-thumb:hover {
+ background: #525252;
+ }
+ `}</style>
+ {/* Header Bar - Responsive */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ flexWrap: 'wrap',
+ padding: '8px 12px',
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ fontSize: '13px',
+ gap: '8px',
+ flexShrink: 0
+ }}>
+ <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>FINCEPT</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>MARKET TERMINAL</span>
+ <span style={{ color: BLOOMBERG_GRAY }}>|</span>
+ <input
+ type="text"
+ placeholder="Search Symbol"
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ flex: '0 1 200px',
+ minWidth: '120px',
+ fontSize: '11px'
+ }}
+ />
+ <button style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ minWidth: '70px'
+ }}>
+ SEARCH
+ </button>
+ <span style={{ color: BLOOMBERG_GRAY }}>|</span>
+ <span style={{ color: BLOOMBERG_WHITE, fontSize: '11px' }}>
+ {currentTime.toISOString().replace('T', ' ').substring(0, 19)}
+ </span>
+ </div>
+
+ {/* Control Panel - Responsive */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ flexWrap: 'wrap',
+ padding: '8px 12px',
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ fontSize: '12px',
+ gap: '8px',
+ flexShrink: 0
+ }}>
+ <button
+ onClick={() => { setIsUpdating(true); setLastUpdate(new Date()); setTimeout(() => setIsUpdating(false), 1000); }}
+ style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ minWidth: '70px'
+ }}
+ >
+ REFRESH
+ </button>
+ <button
+ onClick={() => setAutoUpdate(!autoUpdate)}
+ style={{
+ backgroundColor: autoUpdate ? BLOOMBERG_GREEN : BLOOMBERG_GRAY,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ minWidth: '70px'
+ }}
+ >
+ AUTO {autoUpdate ? 'ON' : 'OFF'}
+ </button>
+ <select style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '11px',
+ minWidth: '70px',
+ cursor: 'pointer'
+ }}>
+ <option>1 min</option>
+ <option>5 min</option>
+ <option>10 min</option>
+ <option>30 min</option>
+ </select>
+ <span style={{ color: BLOOMBERG_GRAY }}>|</span>
+ <span style={{ color: BLOOMBERG_GRAY, fontSize: '11px' }}>LAST UPDATE:</span>
+ <span style={{ color: BLOOMBERG_WHITE, fontSize: '11px' }}>
+ {lastUpdate.toTimeString().substring(0, 8)}
+ </span>
+ <span style={{ color: BLOOMBERG_GRAY }}>|</span>
+ <span style={{ color: isUpdating ? BLOOMBERG_ORANGE : BLOOMBERG_GREEN, fontSize: '14px' }}>●</span>
+ <span style={{ color: isUpdating ? BLOOMBERG_ORANGE : BLOOMBERG_GREEN, fontSize: '11px', fontWeight: 'bold' }}>
+ {isUpdating ? 'UPDATING' : 'LIVE'}
+ </span>
+ </div>
+
+ {/* Main Content - Responsive */}
+ <div style={{
+ flex: 1,
+ overflow: 'auto',
+ padding: '12px',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Global Markets Section */}
+ <div style={{
+ color: BLOOMBERG_ORANGE,
+ fontSize: '14px',
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ letterSpacing: '0.5px'
+ }}>
+ GLOBAL MARKETS
+ </div>
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '16px' }}></div>
+
+ {/* Responsive Market Grid */}
+ <div style={{
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: '0',
+ marginBottom: '24px'
+ }}>
+ {categories.map(category =>
+ createMarketPanel(category, marketData[category])
+ )}
+ </div>
+
+ {/* Regional Markets Section */}
+ <div style={{
+ color: BLOOMBERG_ORANGE,
+ fontSize: '14px',
+ fontWeight: 'bold',
+ marginBottom: '8px',
+ marginTop: '16px',
+ letterSpacing: '0.5px'
+ }}>
+ REGIONAL MARKETS - LIVE DATA
+ </div>
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '16px' }}></div>
+
+ {/* Responsive Regional Panels */}
+ <div style={{
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: '0'
+ }}>
+ {Object.keys(regionalData).map(region =>
+ createRegionalPanel(region, regionalData[region])
+ )}
+ </div>
+ </div>
+
+ {/* Status Bar - Responsive */}
+ <div style={{
+ borderTop: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ padding: '6px 12px',
+ fontSize: '10px',
+ color: BLOOMBERG_GRAY,
+ flexShrink: 0
+ }}>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexWrap: 'wrap',
+ gap: '8px'
+ }}>
+ <span>Data provided by Bloomberg Terminal API | Updates every 5 seconds</span>
+ <span style={{ whiteSpace: 'nowrap' }}>Connected: {Object.keys(regionalData).length} regional markets</span>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default MarketsTab;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx b/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx
index 06184ca73..3f3f35f41 100644
--- a/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx
@@ -1,12 +1,29 @@
import React, { useState, useEffect } from 'react';
+import { Edit2 } from 'lucide-react';
+import { marketDataService, QuoteData } from '../../services/marketDataService';
+import { tickerStorage } from '../../services/tickerStorageService';
+import TickerEditModal from './TickerEditModal';
const MarketsTab: React.FC = () => {
const [currentTime, setCurrentTime] = useState(new Date());
const [lastUpdate, setLastUpdate] = useState(new Date());
const [isUpdating, setIsUpdating] = useState(false);
const [autoUpdate, setAutoUpdate] = useState(true);
+ const [updateInterval, setUpdateInterval] = useState(600000); // 10 minutes default
- // Bloomberg color scheme (exact from Python)
+ // Market data state
+ const [marketData, setMarketData] = useState<Record<string, QuoteData[]>>({});
+ const [regionalData, setRegionalData] = useState<Record<string, QuoteData[]>>({});
+
+ // Edit modal state
+ const [editModalOpen, setEditModalOpen] = useState(false);
+ const [editingCategory, setEditingCategory] = useState<string>('');
+ const [editingTickers, setEditingTickers] = useState<string[]>([]);
+
+ // User preferences
+ const [preferences, setPreferences] = useState(tickerStorage.loadPreferences());
+
+ // Bloomberg colors
const BLOOMBERG_ORANGE = '#FFA500';
const BLOOMBERG_WHITE = '#FFFFFF';
const BLOOMBERG_RED = '#FF0000';
@@ -15,130 +32,81 @@ const MarketsTab: React.FC = () => {
const BLOOMBERG_DARK_BG = '#1a1a1a';
const BLOOMBERG_PANEL_BG = '#000000';
- // Market data (exact structure from Python)
- const marketData: { [key: string]: string[][] } = {
- 'Stock Indices': [
- ['S&P 500', '5232.35', '+23.45', '+0.45%', '+2.1%', '+5.4%'],
- ['Nasdaq 100', '16412.87', '-15.23', '-0.09%', '+1.8%', '+7.2%'],
- ['Dow Jones', '38546.12', '+156.78', '+0.41%', '+1.5%', '+3.9%'],
- ['Russell 2000', '2087.45', '+8.90', '+0.43%', '+2.3%', '+4.1%'],
- ['VIX', '18.23', '-0.45', '-2.41%', '-5.2%', '-8.7%'],
- ['FTSE 100', '7623.98', '+12.34', '+0.16%', '+0.8%', '+2.3%'],
- ['DAX 40', '18245.67', '+89.23', '+0.49%', '+1.2%', '+4.6%'],
- ['Nikkei 225', '35897.45', '-123.45', '-0.34%', '-0.5%', '+1.8%'],
- ['CAC 40', '7890.12', '+45.67', '+0.58%', '+1.8%', '+4.2%'],
- ['Hang Seng', '18654.23', '-89.45', '-0.48%', '-1.2%', '+2.8%']
- ],
- 'Forex': [
- ['EUR/USD', '1.0840', '+0.0023', '+0.21%', '+0.8%', '+2.1%'],
- ['GBP/USD', '1.2567', '-0.0012', '-0.10%', '-0.3%', '+1.5%'],
- ['USD/JPY', '151.45', '+0.35', '+0.23%', '+1.2%', '+3.4%'],
- ['USD/CHF', '0.8923', '-0.0034', '-0.38%', '-0.7%', '-1.2%'],
- ['USD/CAD', '1.3578', '+0.0089', '+0.66%', '+0.4%', '+1.8%'],
- ['AUD/USD', '0.6634', '+0.0067', '+1.02%', '+2.1%', '+4.3%'],
- ['NZD/USD', '0.6089', '-0.0034', '-0.56%', '-0.8%', '+1.2%'],
- ['EUR/GBP', '0.8623', '+0.0012', '+0.14%', '+0.3%', '+0.9%'],
- ['EUR/JPY', '164.23', '+0.89', '+0.54%', '+1.8%', '+5.1%'],
- ['GBP/JPY', '190.45', '-1.23', '-0.64%', '-0.9%', '+2.3%']
- ],
- 'Commodities': [
- ['Gold', '2312.80', '+12.45', '+0.54%', '+1.8%', '+5.2%'],
- ['Silver', '28.45', '-0.67', '-2.30%', '-1.2%', '+3.1%'],
- ['Crude Oil (WTI)', '78.35', '-1.23', '-1.55%', '-2.8%', '-0.5%'],
- ['Brent Crude', '82.10', '-0.89', '-1.07%', '-2.1%', '+1.2%'],
- ['Natural Gas', '3.45', '+0.12', '+3.60%', '+8.2%', '+12.4%'],
- ['Copper', '4.23', '+0.045', '+1.08%', '+2.3%', '+6.7%'],
- ['Platinum', '987.50', '+8.90', '+0.91%', '+2.1%', '+4.8%'],
- ['Palladium', '1045.20', '-12.45', '-1.18%', '-2.3%', '-5.1%'],
- ['Wheat', '567.80', '+5.67', '+1.01%', '+3.2%', '+7.9%'],
- ['Corn', '478.90', '-3.45', '-0.72%', '-1.8%', '+2.4%']
- ],
- 'Bonds': [
- ['US 10Y Treasury', '4.35%', '+0.02', '+0.46%', '+1.2%', '+3.4%'],
- ['US 30Y Treasury', '4.52%', '+0.01', '+0.22%', '+0.8%', '+2.1%'],
- ['US 2Y Treasury', '4.89%', '-0.03', '-0.61%', '-0.5%', '+1.8%'],
- ['Germany 10Y', '2.45%', '+0.01', '+0.41%', '+0.6%', '+1.9%'],
- ['UK 10Y', '4.12%', '-0.02', '-0.48%', '-0.3%', '+2.3%'],
- ['Japan 10Y', '0.78%', '+0.01', '+1.30%', '+2.1%', '+8.7%'],
- ['France 10Y', '2.98%', '+0.02', '+0.67%', '+0.9%', '+2.8%'],
- ['Italy 10Y', '4.23%', '-0.01', '-0.24%', '-0.2%', '+1.5%'],
- ['Spain 10Y', '3.67%', '+0.03', '+0.82%', '+1.1%', '+3.2%'],
- ['Canada 10Y', '3.89%', '+0.01', '+0.26%', '+0.7%', '+2.1%']
- ],
- 'ETFs': [
- ['SPY (S&P 500)', '523.45', '+2.34', '+0.45%', '+2.1%', '+5.4%'],
- ['QQQ (Nasdaq)', '412.67', '-1.23', '-0.30%', '+1.8%', '+7.2%'],
- ['DIA (Dow)', '385.23', '+1.56', '+0.41%', '+1.5%', '+3.9%'],
- ['EEM (Emerging)', '41.78', '+0.34', '+0.82%', '+3.2%', '+6.8%'],
- ['GLD (Gold)', '231.45', '+1.23', '+0.53%', '+1.8%', '+5.1%'],
- ['XLK (Tech)', '198.90', '-0.89', '-0.45%', '+2.3%', '+8.9%'],
- ['XLE (Energy)', '89.34', '+1.45', '+1.65%', '+3.8%', '+7.2%'],
- ['XLF (Finance)', '42.56', '-0.67', '-1.55%', '-1.2%', '+2.1%'],
- ['XLV (Health)', '156.78', '+0.98', '+0.63%', '+1.1%', '+3.7%'],
- ['VNQ (REIT)', '78.90', '-1.12', '-1.40%', '-2.3%', '+1.8%']
- ],
- 'Cryptocurrencies': [
- ['Bitcoin', '67890.45', '+1234.56', '+1.85%', '+8.2%', '+15.7%'],
- ['Ethereum', '3789.23', '-67.89', '-1.76%', '+5.4%', '+12.3%'],
- ['Binance Coin', '567.89', '+12.34', '+2.22%', '+6.8%', '+18.9%'],
- ['Solana', '234.56', '+8.90', '+3.94%', '+12.1%', '+25.6%'],
- ['Dogecoin', '0.1234', '-0.0045', '-3.52%', '-2.1%', '+8.7%'],
- ['Polygon', '1.23', '+0.045', '+3.80%', '+9.8%', '+21.4%'],
- ['Chainlink', '23.45', '+0.89', '+3.94%', '+7.2%', '+14.8%'],
- ['Cardano', '0.67', '-0.023', '-3.32%', '-1.8%', '+5.4%'],
- ['Polkadot', '12.34', '+0.56', '+4.76%', '+8.9%', '+19.2%'],
- ['Avalanche', '45.67', '-1.23', '-2.62%', '-3.1%', '+11.7%']
- ]
- };
+ // Fetch market data
+ const fetchMarketData = async () => {
+ setIsUpdating(true);
+
+ // Fetch global markets
+ const globalPromises = preferences.globalMarkets.map(async (market) => {
+ const quotes = await marketDataService.getEnhancedQuotes(market.tickers);
+ return { category: market.category, quotes };
+ });
+
+ // Fetch regional markets
+ const regionalPromises = preferences.regionalMarkets.map(async (market) => {
+ const symbols = market.tickers.map(t => t.symbol);
+ const quotes = await marketDataService.getEnhancedQuotes(symbols);
+ return { region: market.region, quotes };
+ });
+
+ const globalResults = await Promise.all(globalPromises);
+ const regionalResults = await Promise.all(regionalPromises);
+
+ // Update state
+ const newMarketData: Record<string, QuoteData[]> = {};
+ globalResults.forEach(({ category, quotes }) => {
+ newMarketData[category] = quotes;
+ });
+ setMarketData(newMarketData);
- // Regional data (exact from Python)
- const regionalData: { [key: string]: string[][] } = {
- 'India': [
- ['RELIANCE.NS', 'Reliance Industries', '2500.45', '+23.45', '+0.95%'],
- ['TCS.NS', 'Tata Consultancy', '3456.78', '-12.34', '-0.36%'],
- ['HDFCBANK.NS', 'HDFC Bank', '1678.90', '+8.90', '+0.53%'],
- ['INFY.NS', 'Infosys', '1234.56', '+15.67', '+1.29%'],
- ['HINDUNILVR.NS', 'Hindustan Unilever', '2345.67', '-5.43', '-0.23%'],
- ['ICICIBANK.NS', 'ICICI Bank', '987.65', '+12.34', '+1.27%'],
- ['SBIN.NS', 'State Bank of India', '678.90', '+3.45', '+0.51%'],
- ['BHARTIARTL.NS', 'Bharti Airtel', '876.54', '-7.89', '-0.89%']
- ],
- 'China': [
- ['BABA', 'Alibaba Group', '85.67', '+2.34', '+2.81%'],
- ['PDD', 'PDD Holdings', '123.45', '-1.23', '-0.99%'],
- ['JD', 'JD.com', '34.56', '+0.89', '+2.64%'],
- ['BIDU', 'Baidu', '145.67', '+3.45', '+2.43%'],
- ['TCEHY', 'Tencent Holdings', '45.78', '-0.67', '-1.44%'],
- ['NIO', 'NIO Inc', '12.34', '+0.45', '+3.78%'],
- ['LI', 'Li Auto', '23.45', '+1.23', '+5.54%'],
- ['XPEV', 'XPeng', '15.67', '-0.89', '-5.38%']
- ],
- 'United States': [
- ['AAPL', 'Apple Inc', '175.43', '+2.34', '+1.35%'],
- ['MSFT', 'Microsoft Corp', '420.67', '+4.12', '+0.99%'],
- ['GOOGL', 'Alphabet Inc', '140.23', '-1.23', '-0.87%'],
- ['AMZN', 'Amazon.com', '145.32', '+1.89', '+1.32%'],
- ['NVDA', 'NVIDIA Corp', '800.45', '+12.45', '+1.58%'],
- ['META', 'Meta Platforms', '345.67', '-2.34', '-0.67%'],
- ['TSLA', 'Tesla Inc', '200.78', '-5.67', '-2.75%'],
- ['JPM', 'JPMorgan Chase', '156.89', '+1.23', '+0.79%']
- ]
+ const newRegionalData: Record<string, QuoteData[]> = {};
+ regionalResults.forEach(({ region, quotes }) => {
+ newRegionalData[region] = quotes;
+ });
+ setRegionalData(newRegionalData);
+
+ setLastUpdate(new Date());
+ setIsUpdating(false);
};
+ // Initial fetch
+ useEffect(() => {
+ fetchMarketData();
+ }, []);
+
+ // Auto-update timer
useEffect(() => {
const timer = setInterval(() => {
setCurrentTime(new Date());
if (autoUpdate) {
- setIsUpdating(true);
- setLastUpdate(new Date());
- setTimeout(() => setIsUpdating(false), 1000);
+ fetchMarketData();
}
- }, 5000);
+ }, updateInterval);
+
return () => clearInterval(timer);
- }, [autoUpdate]);
+ }, [autoUpdate, updateInterval, preferences]);
- // Create market panel (responsive layout)
- const createMarketPanel = (title: string, data: string[][]) => (
+ // Open edit modal
+ const openEditModal = (category: string) => {
+ const tickers = tickerStorage.getCategoryTickers(category);
+ setEditingCategory(category);
+ setEditingTickers(tickers);
+ setEditModalOpen(true);
+ };
+
+ // Save edited tickers
+ const handleSaveTickers = (tickers: string[]) => {
+ tickerStorage.updateCategoryTickers(editingCategory, tickers);
+ setPreferences(tickerStorage.loadPreferences());
+ fetchMarketData(); // Refresh data
+ };
+
+ // Format helpers
+ const formatChange = (value: number) => value >= 0 ? `+${value.toFixed(2)}` : value.toFixed(2);
+ const formatPercent = (value: number) => value >= 0 ? `+${value.toFixed(2)}%` : `${value.toFixed(2)}%`;
+
+ // Create market panel
+ const createMarketPanel = (title: string, quotes: QuoteData[]) => (
<div style={{
backgroundColor: BLOOMBERG_PANEL_BG,
border: `1px solid ${BLOOMBERG_GRAY}`,
@@ -150,7 +118,7 @@ const MarketsTab: React.FC = () => {
display: 'flex',
flexDirection: 'column'
}}>
- {/* Panel Header */}
+ {/* Panel Header with Edit Icon */}
<div style={{
backgroundColor: BLOOMBERG_DARK_BG,
color: BLOOMBERG_ORANGE,
@@ -158,9 +126,18 @@ const MarketsTab: React.FC = () => {
fontSize: '14px',
fontWeight: 'bold',
textAlign: 'center',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px'
}}>
{title.toUpperCase()}
+ <Edit2
+ size={14}
+ style={{ cursor: 'pointer', color: BLOOMBERG_WHITE }}
+ onClick={() => openEditModal(title)}
+ />
</div>
{/* Table Header */}
@@ -185,119 +162,148 @@ const MarketsTab: React.FC = () => {
{/* Data Rows */}
<div style={{ flex: 1, overflow: 'auto' }}>
- {data.map((row, index) => (
- <div key={index} style={{
- display: 'grid',
- gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr 1fr',
- gap: '4px',
- padding: '2px 8px',
- fontSize: '10px',
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
- borderBottom: `1px solid rgba(120,120,120,0.3)`,
- minHeight: '18px',
- alignItems: 'center'
+ {quotes.length === 0 ? (
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '11px',
+ textAlign: 'center',
+ padding: '16px'
}}>
- <div style={{ color: BLOOMBERG_WHITE }}>{row[0]}</div>
- <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{row[1]}</div>
- <div style={{
- color: row[2].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[2]}</div>
- <div style={{
- color: row[3].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[3]}</div>
- <div style={{
- color: row[4].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[4]}</div>
- <div style={{
- color: row[5].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[5]}</div>
+ {isUpdating ? 'Loading...' : 'No data available'}
</div>
- ))}
+ ) : (
+ quotes.map((quote, index) => (
+ <div key={index} style={{
+ display: 'grid',
+ gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr 1fr',
+ gap: '4px',
+ padding: '2px 8px',
+ fontSize: '10px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`,
+ minHeight: '18px',
+ alignItems: 'center'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE }}>{quote.symbol}</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{quote.price.toFixed(2)}</div>
+ <div style={{
+ color: quote.change >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{formatChange(quote.change)}</div>
+ <div style={{
+ color: quote.change_percent >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{formatPercent(quote.change_percent)}</div>
+ <div style={{
+ color: (quote as any).seven_day >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{(quote as any).seven_day ? formatPercent((quote as any).seven_day) : '-'}</div>
+ <div style={{
+ color: (quote as any).thirty_day >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{(quote as any).thirty_day ? formatPercent((quote as any).thirty_day) : '-'}</div>
+ </div>
+ ))
+ )}
</div>
</div>
);
- // Create regional panel (responsive layout)
- const createRegionalPanel = (title: string, data: string[][]) => (
- <div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- flex: '1 1 calc(33.333% - 16px)',
- minWidth: '300px',
- maxWidth: '600px',
- height: '300px',
- margin: '8px',
- display: 'flex',
- flexDirection: 'column'
- }}>
- {/* Panel Header */}
- <div style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_ORANGE,
- padding: '8px',
- fontSize: '14px',
- fontWeight: 'bold',
- textAlign: 'center',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`
- }}>
- {title.toUpperCase()} - LIVE DATA
- </div>
+ // Create regional panel
+ const createRegionalPanel = (title: string, quotes: QuoteData[]) => {
+ const regionConfig = preferences.regionalMarkets.find(r => r.region === title);
- {/* Table Header */}
+ return (
<div style={{
- display: 'grid',
- gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
- gap: '4px',
- padding: '4px 8px',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
- fontSize: '12px',
- fontWeight: 'bold',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ flex: '1 1 calc(33.333% - 16px)',
+ minWidth: '300px',
+ maxWidth: '600px',
+ height: '300px',
+ margin: '8px',
+ display: 'flex',
+ flexDirection: 'column'
}}>
- <div>SYMBOL</div>
- <div>NAME</div>
- <div style={{ textAlign: 'right' }}>PRICE</div>
- <div style={{ textAlign: 'right' }}>CHANGE</div>
- <div style={{ textAlign: 'right' }}>%CHG</div>
- </div>
+ {/* Panel Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_ORANGE,
+ padding: '8px',
+ fontSize: '14px',
+ fontWeight: 'bold',
+ textAlign: 'center',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ {title.toUpperCase()} - LIVE DATA
+ </div>
- {/* Data Rows */}
- <div style={{ flex: 1, overflow: 'auto' }}>
- {data.map((row, index) => (
- <div key={index} style={{
- display: 'grid',
- gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
- gap: '4px',
- padding: '2px 8px',
- fontSize: '10px',
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
- borderBottom: `1px solid rgba(120,120,120,0.3)`,
- minHeight: '18px',
- alignItems: 'center'
- }}>
- <div style={{ color: BLOOMBERG_WHITE }}>{row[0]}</div>
- <div style={{ color: BLOOMBERG_WHITE, overflow: 'hidden', textOverflow: 'ellipsis' }}>{row[1]}</div>
- <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{row[2]}</div>
- <div style={{
- color: row[3].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[3]}</div>
+ {/* Table Header */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
+ gap: '4px',
+ padding: '4px 8px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <div>SYMBOL</div>
+ <div>NAME</div>
+ <div style={{ textAlign: 'right' }}>PRICE</div>
+ <div style={{ textAlign: 'right' }}>CHANGE</div>
+ <div style={{ textAlign: 'right' }}>%CHG</div>
+ </div>
+
+ {/* Data Rows */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {quotes.length === 0 ? (
<div style={{
- color: row[4].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[4]}</div>
- </div>
- ))}
+ color: BLOOMBERG_GRAY,
+ fontSize: '11px',
+ textAlign: 'center',
+ padding: '16px'
+ }}>
+ {isUpdating ? 'Loading...' : 'No data available'}
+ </div>
+ ) : (
+ quotes.map((quote, index) => {
+ const tickerInfo = regionConfig?.tickers.find(t => t.symbol === quote.symbol);
+ return (
+ <div key={index} style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
+ gap: '4px',
+ padding: '2px 8px',
+ fontSize: '10px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`,
+ minHeight: '18px',
+ alignItems: 'center'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE }}>{quote.symbol}</div>
+ <div style={{ color: BLOOMBERG_WHITE, overflow: 'hidden', textOverflow: 'ellipsis' }}>
+ {tickerInfo?.name || quote.symbol}
+ </div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{quote.price.toFixed(2)}</div>
+ <div style={{
+ color: quote.change >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{formatChange(quote.change)}</div>
+ <div style={{
+ color: quote.change_percent >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{formatPercent(quote.change_percent)}</div>
+ </div>
+ );
+ })
+ )}
+ </div>
</div>
- </div>
- );
-
- const categories = Object.keys(marketData);
+ );
+ };
return (
<div style={{
@@ -310,7 +316,6 @@ const MarketsTab: React.FC = () => {
flexDirection: 'column'
}}>
<style>{`
- /* Custom scrollbar styles */
*::-webkit-scrollbar {
width: 8px;
height: 8px;
@@ -326,7 +331,8 @@ const MarketsTab: React.FC = () => {
background: #525252;
}
`}</style>
- {/* Header Bar - Responsive */}
+
+ {/* Header Bar */}
<div style={{
display: 'flex',
alignItems: 'center',
@@ -339,40 +345,14 @@ const MarketsTab: React.FC = () => {
flexShrink: 0
}}>
<span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>FINCEPT</span>
- <span style={{ color: BLOOMBERG_WHITE }}>MARKET TERMINAL</span>
- <span style={{ color: BLOOMBERG_GRAY }}>|</span>
- <input
- type="text"
- placeholder="Search Symbol"
- style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: BLOOMBERG_WHITE,
- padding: '4px 8px',
- flex: '0 1 200px',
- minWidth: '120px',
- fontSize: '11px'
- }}
- />
- <button style={{
- backgroundColor: BLOOMBERG_ORANGE,
- color: 'black',
- border: 'none',
- padding: '4px 12px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- minWidth: '70px'
- }}>
- SEARCH
- </button>
+ <span style={{ color: BLOOMBERG_WHITE }}>MARKET TERMINAL - LIVE DATA</span>
<span style={{ color: BLOOMBERG_GRAY }}>|</span>
<span style={{ color: BLOOMBERG_WHITE, fontSize: '11px' }}>
{currentTime.toISOString().replace('T', ' ').substring(0, 19)}
</span>
</div>
- {/* Control Panel - Responsive */}
+ {/* Control Panel */}
<div style={{
display: 'flex',
alignItems: 'center',
@@ -385,7 +365,7 @@ const MarketsTab: React.FC = () => {
flexShrink: 0
}}>
<button
- onClick={() => { setIsUpdating(true); setLastUpdate(new Date()); setTimeout(() => setIsUpdating(false), 1000); }}
+ onClick={fetchMarketData}
style={{
backgroundColor: BLOOMBERG_ORANGE,
color: 'black',
@@ -393,8 +373,7 @@ const MarketsTab: React.FC = () => {
padding: '4px 12px',
fontSize: '11px',
fontWeight: 'bold',
- cursor: 'pointer',
- minWidth: '70px'
+ cursor: 'pointer'
}}
>
REFRESH
@@ -408,25 +387,27 @@ const MarketsTab: React.FC = () => {
padding: '4px 12px',
fontSize: '11px',
fontWeight: 'bold',
- cursor: 'pointer',
- minWidth: '70px'
+ cursor: 'pointer'
}}
>
AUTO {autoUpdate ? 'ON' : 'OFF'}
</button>
- <select style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: BLOOMBERG_WHITE,
- padding: '4px 8px',
- fontSize: '11px',
- minWidth: '70px',
- cursor: 'pointer'
- }}>
- <option>1 min</option>
- <option>5 min</option>
- <option>10 min</option>
- <option>30 min</option>
+ <select
+ value={updateInterval}
+ onChange={(e) => setUpdateInterval(Number(e.target.value))}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '11px',
+ cursor: 'pointer'
+ }}
+ >
+ <option value={600000}>10 min</option>
+ <option value={900000}>15 min</option>
+ <option value={1800000}>30 min</option>
+ <option value={3600000}>1 hour</option>
</select>
<span style={{ color: BLOOMBERG_GRAY }}>|</span>
<span style={{ color: BLOOMBERG_GRAY, fontSize: '11px' }}>LAST UPDATE:</span>
@@ -440,7 +421,7 @@ const MarketsTab: React.FC = () => {
</span>
</div>
- {/* Main Content - Responsive */}
+ {/* Main Content */}
<div style={{
flex: 1,
overflow: 'auto',
@@ -448,7 +429,7 @@ const MarketsTab: React.FC = () => {
display: 'flex',
flexDirection: 'column'
}}>
- {/* Global Markets Section */}
+ {/* Global Markets */}
<div style={{
color: BLOOMBERG_ORANGE,
fontSize: '14px',
@@ -460,19 +441,18 @@ const MarketsTab: React.FC = () => {
</div>
<div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '16px' }}></div>
- {/* Responsive Market Grid */}
<div style={{
display: 'flex',
flexWrap: 'wrap',
gap: '0',
marginBottom: '24px'
}}>
- {categories.map(category =>
- createMarketPanel(category, marketData[category])
+ {preferences.globalMarkets.map(market =>
+ createMarketPanel(market.category, marketData[market.category] || [])
)}
</div>
- {/* Regional Markets Section */}
+ {/* Regional Markets */}
<div style={{
color: BLOOMBERG_ORANGE,
fontSize: '14px',
@@ -485,19 +465,18 @@ const MarketsTab: React.FC = () => {
</div>
<div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '16px' }}></div>
- {/* Responsive Regional Panels */}
<div style={{
display: 'flex',
flexWrap: 'wrap',
gap: '0'
}}>
- {Object.keys(regionalData).map(region =>
- createRegionalPanel(region, regionalData[region])
+ {preferences.regionalMarkets.map(market =>
+ createRegionalPanel(market.region, regionalData[market.region] || [])
)}
</div>
</div>
- {/* Status Bar - Responsive */}
+ {/* Status Bar */}
<div style={{
borderTop: `1px solid ${BLOOMBERG_GRAY}`,
backgroundColor: BLOOMBERG_PANEL_BG,
@@ -513,12 +492,23 @@ const MarketsTab: React.FC = () => {
flexWrap: 'wrap',
gap: '8px'
}}>
- <span>Data provided by Bloomberg Terminal API | Updates every 5 seconds</span>
- <span style={{ whiteSpace: 'nowrap' }}>Connected: {Object.keys(regionalData).length} regional markets</span>
+ <span>Data provided by Yahoo Finance API | Real-time updates</span>
+ <span style={{ whiteSpace: 'nowrap' }}>
+ Connected: {Object.keys(regionalData).length} regional markets
+ </span>
</div>
</div>
+
+ {/* Edit Modal */}
+ <TickerEditModal
+ isOpen={editModalOpen}
+ onClose={() => setEditModalOpen(false)}
+ title={editingCategory}
+ tickers={editingTickers}
+ onSave={handleSaveTickers}
+ />
</div>
);
};
-export default MarketsTab;
\ No newline at end of file
+export default MarketsTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/TickerEditModal.tsx b/fincept-terminal-desktop/src/components/tabs/TickerEditModal.tsx
new file mode 100644
index 000000000..ae0d699e7
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/TickerEditModal.tsx
@@ -0,0 +1,256 @@
+// Ticker Edit Modal - UI for managing tickers in a category/region
+import React, { useState } from 'react';
+import { X, Plus, Trash2, GripVertical } from 'lucide-react';
+
+interface TickerEditModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ title: string;
+ tickers: string[];
+ onSave: (tickers: string[]) => void;
+}
+
+const TickerEditModal: React.FC<TickerEditModalProps> = ({
+ isOpen,
+ onClose,
+ title,
+ tickers,
+ onSave
+}) => {
+ const [editedTickers, setEditedTickers] = useState<string[]>([...tickers]);
+ const [newTicker, setNewTicker] = useState('');
+
+ if (!isOpen) return null;
+
+ const handleAdd = () => {
+ const trimmed = newTicker.trim().toUpperCase();
+ if (trimmed && !editedTickers.includes(trimmed)) {
+ setEditedTickers([...editedTickers, trimmed]);
+ setNewTicker('');
+ }
+ };
+
+ const handleRemove = (index: number) => {
+ setEditedTickers(editedTickers.filter((_, i) => i !== index));
+ };
+
+ const handleMoveUp = (index: number) => {
+ if (index === 0) return;
+ const newList = [...editedTickers];
+ [newList[index - 1], newList[index]] = [newList[index], newList[index - 1]];
+ setEditedTickers(newList);
+ };
+
+ const handleMoveDown = (index: number) => {
+ if (index === editedTickers.length - 1) return;
+ const newList = [...editedTickers];
+ [newList[index], newList[index + 1]] = [newList[index + 1], newList[index]];
+ setEditedTickers(newList);
+ };
+
+ const handleSave = () => {
+ onSave(editedTickers);
+ onClose();
+ };
+
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#1a1a1a';
+ const BLOOMBERG_PANEL_BG = '#000000';
+
+ return (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.8)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 9999
+ }}>
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `2px solid ${BLOOMBERG_ORANGE}`,
+ width: '90%',
+ maxWidth: '600px',
+ maxHeight: '80vh',
+ display: 'flex',
+ flexDirection: 'column',
+ fontFamily: 'Consolas, monospace'
+ }}>
+ {/* Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_ORANGE,
+ padding: '12px 16px',
+ fontSize: '14px',
+ fontWeight: 'bold',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <span>EDIT {title.toUpperCase()}</span>
+ <X
+ size={20}
+ style={{ cursor: 'pointer', color: BLOOMBERG_WHITE }}
+ onClick={onClose}
+ />
+ </div>
+
+ {/* Add Ticker Section */}
+ <div style={{
+ padding: '16px',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: BLOOMBERG_DARK_BG
+ }}>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ <input
+ type="text"
+ value={newTicker}
+ onChange={(e) => setNewTicker(e.target.value)}
+ onKeyPress={(e) => e.key === 'Enter' && handleAdd()}
+ placeholder="Enter ticker symbol (e.g., AAPL)"
+ style={{
+ flex: 1,
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px 12px',
+ fontSize: '12px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ <button
+ onClick={handleAdd}
+ style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ border: 'none',
+ color: 'black',
+ padding: '8px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Plus size={14} /> ADD
+ </button>
+ </div>
+ </div>
+
+ {/* Ticker List */}
+ <div style={{
+ flex: 1,
+ overflow: 'auto',
+ padding: '8px'
+ }}>
+ {editedTickers.length === 0 ? (
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '12px',
+ textAlign: 'center',
+ padding: '32px'
+ }}>
+ No tickers added. Add tickers using the form above.
+ </div>
+ ) : (
+ editedTickers.map((ticker, index) => (
+ <div
+ key={index}
+ style={{
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '8px 12px',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ fontSize: '12px'
+ }}
+ >
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '2px'
+ }}>
+ <GripVertical
+ size={12}
+ style={{
+ color: BLOOMBERG_GRAY,
+ cursor: index > 0 ? 'pointer' : 'default',
+ opacity: index > 0 ? 1 : 0.3
+ }}
+ onClick={() => handleMoveUp(index)}
+ />
+ <GripVertical
+ size={12}
+ style={{
+ color: BLOOMBERG_GRAY,
+ cursor: index < editedTickers.length - 1 ? 'pointer' : 'default',
+ opacity: index < editedTickers.length - 1 ? 1 : 0.3
+ }}
+ onClick={() => handleMoveDown(index)}
+ />
+ </div>
+ <span style={{ color: BLOOMBERG_WHITE, flex: 1 }}>{ticker}</span>
+ <Trash2
+ size={16}
+ style={{ color: '#FF0000', cursor: 'pointer' }}
+ onClick={() => handleRemove(index)}
+ />
+ </div>
+ ))
+ )}
+ </div>
+
+ {/* Footer */}
+ <div style={{
+ padding: '16px',
+ borderTop: `1px solid ${BLOOMBERG_GRAY}`,
+ display: 'flex',
+ justifyContent: 'flex-end',
+ gap: '8px',
+ backgroundColor: BLOOMBERG_DARK_BG
+ }}>
+ <button
+ onClick={onClose}
+ style={{
+ backgroundColor: BLOOMBERG_GRAY,
+ border: 'none',
+ color: 'black',
+ padding: '8px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CANCEL
+ </button>
+ <button
+ onClick={handleSave}
+ style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ border: 'none',
+ color: 'black',
+ padding: '8px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ SAVE CHANGES
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default TickerEditModal;
diff --git a/fincept-terminal-desktop/src/components/tabs/ToolCallDisplay.tsx b/fincept-terminal-desktop/src/components/tabs/ToolCallDisplay.tsx
new file mode 100644
index 000000000..135517258
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ToolCallDisplay.tsx
@@ -0,0 +1,162 @@
+// Tool Call Display Component
+// Shows MCP tool execution in chat messages
+
+import React from 'react';
+import { Wrench, CheckCircle, XCircle, Clock } from 'lucide-react';
+
+interface ToolCallDisplayProps {
+ toolName: string;
+ args: any;
+ result?: any;
+ status: 'pending' | 'success' | 'error';
+ executionTime?: number;
+}
+
+const ToolCallDisplay: React.FC<ToolCallDisplayProps> = ({
+ toolName,
+ args,
+ result,
+ status,
+ executionTime
+}) => {
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_RED = '#FF0000';
+ const BLOOMBERG_YELLOW = '#FFFF00';
+
+ const statusColor = {
+ pending: BLOOMBERG_YELLOW,
+ success: BLOOMBERG_GREEN,
+ error: BLOOMBERG_RED
+ }[status];
+
+ const StatusIcon = {
+ pending: Clock,
+ success: CheckCircle,
+ error: XCircle
+ }[status];
+
+ // Parse server and tool name
+ const [serverId, actualToolName] = toolName.includes('__')
+ ? toolName.split('__')
+ : ['unknown', toolName];
+
+ return (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${statusColor}`,
+ borderLeft: `3px solid ${statusColor}`,
+ padding: '8px',
+ marginBottom: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}>
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '6px'
+ }}>
+ <Wrench size={12} color={BLOOMBERG_ORANGE} />
+ <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold', fontSize: '11px' }}>
+ TOOL CALL
+ </span>
+ <span style={{ color: BLOOMBERG_WHITE }}>→</span>
+ <span style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>{actualToolName}</span>
+ <span style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '9px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ padding: '2px 4px'
+ }}>
+ {serverId}
+ </span>
+ <StatusIcon size={12} color={statusColor} style={{ marginLeft: 'auto' }} />
+ {status === 'pending' && (
+ <span style={{ color: statusColor, fontSize: '10px' }}>Running...</span>
+ )}
+ {status === 'success' && (
+ <span style={{ color: statusColor, fontSize: '10px' }}>✓ Success</span>
+ )}
+ {status === 'error' && (
+ <span style={{ color: statusColor, fontSize: '10px' }}>✗ Failed</span>
+ )}
+ </div>
+
+ {/* Arguments */}
+ <div style={{ marginBottom: '6px' }}>
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '9px',
+ marginBottom: '2px',
+ fontWeight: 'bold'
+ }}>
+ Arguments:
+ </div>
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px 6px',
+ fontSize: '9px',
+ color: BLOOMBERG_WHITE,
+ fontFamily: 'Consolas, monospace',
+ maxHeight: '100px',
+ overflow: 'auto'
+ }}>
+ <pre style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
+ {JSON.stringify(args, null, 2)}
+ </pre>
+ </div>
+ </div>
+
+ {/* Result (if available) */}
+ {result && (
+ <div>
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '9px',
+ marginBottom: '2px',
+ fontWeight: 'bold'
+ }}>
+ Result:
+ </div>
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px 6px',
+ fontSize: '9px',
+ color: BLOOMBERG_WHITE,
+ fontFamily: 'Consolas, monospace',
+ maxHeight: '200px',
+ overflow: 'auto'
+ }}>
+ <pre style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
+ {typeof result === 'string'
+ ? result
+ : JSON.stringify(result, null, 2)}
+ </pre>
+ </div>
+ </div>
+ )}
+
+ {/* Execution time */}
+ {executionTime !== undefined && (
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '8px',
+ marginTop: '4px',
+ textAlign: 'right'
+ }}>
+ Executed in {executionTime}ms
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default ToolCallDisplay;
diff --git a/fincept-terminal-desktop/src/components/tabs/fyers/FyersAuthModal.tsx b/fincept-terminal-desktop/src/components/tabs/fyers/FyersAuthModal.tsx
new file mode 100644
index 000000000..dc682c404
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/fyers/FyersAuthModal.tsx
@@ -0,0 +1,406 @@
+// Fyers Authentication Modal
+// Automated authentication with TOTP
+
+import React, { useState } from 'react';
+import { X } from 'lucide-react';
+import { fyersService } from '../../../services/fyersService';
+import { authenticateFyers, FyersAuthConfig } from '../../../services/fyersAuth';
+
+interface FyersAuthModalProps {
+ onClose: () => void;
+ onSuccess: () => void;
+}
+
+const FyersAuthModal: React.FC<FyersAuthModalProps> = ({ onClose, onSuccess }) => {
+ const [clientId, setClientId] = useState('');
+ const [pin, setPin] = useState('');
+ const [appId, setAppId] = useState('');
+ const [appType, setAppType] = useState('100');
+ const [appSecret, setAppSecret] = useState('');
+ const [totpKey, setTotpKey] = useState('');
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState('');
+ const [statusMessage, setStatusMessage] = useState('');
+
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+
+ const handleConnect = async () => {
+ if (!clientId || !pin || !appId || !appSecret || !totpKey) {
+ setError('Please fill all required fields');
+ return;
+ }
+
+ setIsLoading(true);
+ setError('');
+ setStatusMessage('Starting authentication...');
+
+ try {
+ const config: FyersAuthConfig = {
+ clientId,
+ pin,
+ appId,
+ appType,
+ appSecret,
+ totpKey
+ };
+
+ setStatusMessage('Generating TOTP and authenticating...');
+ const authResult = await authenticateFyers(config);
+
+ setStatusMessage('Saving credentials...');
+
+ // Save to database with appType
+ await fyersService.saveCredentials({
+ appId,
+ appType,
+ redirectUrl: 'https://trade.fyers.in/api-login/redirect-uri/index.html',
+ accessToken: authResult.accessToken
+ });
+
+ // Also save the full config for re-authentication
+ const { sqliteService } = await import('../../../services/sqliteService');
+ await sqliteService.saveCredential({
+ service_name: 'fyers_config',
+ username: clientId,
+ password: pin,
+ api_key: appId,
+ api_secret: appSecret,
+ additional_data: JSON.stringify({
+ appType,
+ totpKey,
+ connectionString: authResult.connectionString
+ })
+ });
+
+ setStatusMessage('Testing connection...');
+ await fyersService.getProfile();
+
+ setStatusMessage('Connected successfully!');
+ setTimeout(() => {
+ setIsLoading(false);
+ onSuccess();
+ }, 1000);
+ } catch (err) {
+ setIsLoading(false);
+ setStatusMessage('');
+ setError(err instanceof Error ? err.message : 'Authentication failed');
+ }
+ };
+
+ return (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0, 0, 0, 0.9)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000,
+ fontFamily: 'Consolas, monospace'
+ }}>
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `2px solid ${BLOOMBERG_ORANGE}`,
+ width: '500px',
+ maxWidth: '90%'
+ }}>
+ {/* Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ borderBottom: `1px solid ${BLOOMBERG_ORANGE}`,
+ padding: '10px 12px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <span style={{
+ color: BLOOMBERG_ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold'
+ }}>
+ CONNECT FYERS ACCOUNT
+ </span>
+ <button
+ onClick={onClose}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: BLOOMBERG_WHITE,
+ cursor: 'pointer',
+ padding: '4px'
+ }}
+ >
+ <X size={16} />
+ </button>
+ </div>
+
+ {/* Body */}
+ <div style={{ padding: '20px' }}>
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '10px',
+ marginBottom: '20px',
+ lineHeight: '1.5'
+ }}>
+ Enter your Fyers credentials. Authentication will be automated using TOTP.
+ </div>
+
+ {/* Client ID */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_WHITE,
+ fontSize: '10px',
+ marginBottom: '5px',
+ fontWeight: 'bold'
+ }}>
+ Client ID *
+ </label>
+ <input
+ type="text"
+ value={clientId}
+ onChange={(e) => setClientId(e.target.value.toUpperCase())}
+ placeholder="XB02507"
+ disabled={isLoading}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: 'Consolas, monospace',
+ boxSizing: 'border-box'
+ }}
+ />
+ </div>
+
+ {/* PIN */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_WHITE,
+ fontSize: '10px',
+ marginBottom: '5px',
+ fontWeight: 'bold'
+ }}>
+ PIN *
+ </label>
+ <input
+ type="password"
+ value={pin}
+ onChange={(e) => setPin(e.target.value)}
+ placeholder="1590"
+ disabled={isLoading}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: 'Consolas, monospace',
+ boxSizing: 'border-box'
+ }}
+ />
+ </div>
+
+ {/* App ID */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_WHITE,
+ fontSize: '10px',
+ marginBottom: '5px',
+ fontWeight: 'bold'
+ }}>
+ App ID *
+ </label>
+ <input
+ type="text"
+ value={appId}
+ onChange={(e) => setAppId(e.target.value.toUpperCase())}
+ placeholder="NDM5TDN9DB"
+ disabled={isLoading}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: 'Consolas, monospace',
+ boxSizing: 'border-box'
+ }}
+ />
+ </div>
+
+ {/* App Type */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_WHITE,
+ fontSize: '10px',
+ marginBottom: '5px',
+ fontWeight: 'bold'
+ }}>
+ App Type
+ </label>
+ <input
+ type="text"
+ value={appType}
+ onChange={(e) => setAppType(e.target.value)}
+ placeholder="100"
+ disabled={isLoading}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: 'Consolas, monospace',
+ boxSizing: 'border-box'
+ }}
+ />
+ </div>
+
+ {/* App Secret */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_WHITE,
+ fontSize: '10px',
+ marginBottom: '5px',
+ fontWeight: 'bold'
+ }}>
+ App Secret *
+ </label>
+ <input
+ type="password"
+ value={appSecret}
+ onChange={(e) => setAppSecret(e.target.value.toUpperCase())}
+ placeholder="UR9IJU1U0E"
+ disabled={isLoading}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '10px',
+ fontFamily: 'Consolas, monospace',
+ boxSizing: 'border-box'
+ }}
+ />
+ </div>
+
+ {/* TOTP Key */}
+ <div style={{ marginBottom: '15px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_WHITE,
+ fontSize: '10px',
+ marginBottom: '5px',
+ fontWeight: 'bold'
+ }}>
+ TOTP Key *
+ </label>
+ <input
+ type="password"
+ value={totpKey}
+ onChange={(e) => setTotpKey(e.target.value.toUpperCase())}
+ placeholder="XOYMD3QRDV6QPNSWK3WSKMD642KGODJQ"
+ disabled={isLoading}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '9px',
+ fontFamily: 'Consolas, monospace',
+ boxSizing: 'border-box'
+ }}
+ />
+ </div>
+
+ {/* Status Message */}
+ {statusMessage && (
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_ORANGE}`,
+ color: BLOOMBERG_ORANGE,
+ padding: '8px',
+ fontSize: '9px',
+ marginBottom: '15px',
+ textAlign: 'center'
+ }}>
+ {statusMessage}
+ </div>
+ )}
+
+ {/* Error Message */}
+ {error && (
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: '1px solid #FF0000',
+ color: '#FF0000',
+ padding: '8px',
+ fontSize: '9px',
+ marginBottom: '15px'
+ }}>
+ {error}
+ </div>
+ )}
+
+ {/* Actions */}
+ <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
+ <button
+ onClick={onClose}
+ disabled={isLoading}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px 16px',
+ fontSize: '10px',
+ cursor: isLoading ? 'not-allowed' : 'pointer',
+ fontFamily: 'Consolas, monospace',
+ opacity: isLoading ? 0.5 : 1
+ }}
+ >
+ CANCEL
+ </button>
+ <button
+ onClick={handleConnect}
+ disabled={isLoading}
+ style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ border: 'none',
+ color: 'black',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: isLoading ? 'not-allowed' : 'pointer',
+ fontFamily: 'Consolas, monospace',
+ opacity: isLoading ? 0.5 : 1
+ }}
+ >
+ {isLoading ? 'CONNECTING...' : 'CONNECT'}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default FyersAuthModal;
diff --git a/fincept-terminal-desktop/src/components/tabs/fyers/FyersFundsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/fyers/FyersFundsPanel.tsx
new file mode 100644
index 000000000..dc5ac8a55
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/fyers/FyersFundsPanel.tsx
@@ -0,0 +1,217 @@
+// Fyers Funds Panel
+// Display account funds and limits
+
+import React, { useState, useEffect } from 'react';
+import { Wallet } from 'lucide-react';
+import { fyersService, FyersFund } from '../../../services/fyersService';
+
+const FyersFundsPanel: React.FC = () => {
+ const [funds, setFunds] = useState<FyersFund[]>([]);
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState('');
+
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_RED = '#FF0000';
+
+ useEffect(() => {
+ loadFunds();
+ }, []);
+
+ const loadFunds = async () => {
+ setIsLoading(true);
+ setError('');
+
+ try {
+ const data = await fyersService.getFunds();
+ setFunds(data);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load funds');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const formatCurrency = (amount: number) => {
+ return `₹${amount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+ };
+
+ if (isLoading) {
+ return (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '12px',
+ marginBottom: '12px'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px' }}>Loading funds...</div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid #FF0000`,
+ padding: '12px',
+ marginBottom: '12px'
+ }}>
+ <div style={{ color: '#FF0000', fontSize: '10px' }}>{error}</div>
+ </div>
+ );
+ }
+
+ // Find key fund items
+ const availableBalance = funds.find(f => f.id === 10);
+ const utilizedAmount = funds.find(f => f.id === 2);
+ const realizedPL = funds.find(f => f.id === 4);
+
+ return (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_ORANGE}`,
+ padding: '12px',
+ marginBottom: '12px'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <Wallet size={12} color={BLOOMBERG_ORANGE} />
+ <span style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
+ FUNDS & LIMITS
+ </span>
+ </div>
+
+ {/* Summary Cards */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, 1fr)',
+ gap: '12px',
+ marginBottom: '12px'
+ }}>
+ {/* Available Balance */}
+ {availableBalance && (
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GREEN}`,
+ padding: '10px'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '8px', marginBottom: '4px' }}>
+ AVAILABLE BALANCE
+ </div>
+ <div style={{ color: BLOOMBERG_GREEN, fontSize: '13px', fontWeight: 'bold' }}>
+ {formatCurrency(availableBalance.equityAmount)}
+ </div>
+ {availableBalance.commodityAmount > 0 && (
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '8px', marginTop: '2px' }}>
+ Commodity: {formatCurrency(availableBalance.commodityAmount)}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Utilized */}
+ {utilizedAmount && (
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_ORANGE}`,
+ padding: '10px'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '8px', marginBottom: '4px' }}>
+ UTILIZED AMOUNT
+ </div>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '13px', fontWeight: 'bold' }}>
+ {formatCurrency(utilizedAmount.equityAmount)}
+ </div>
+ </div>
+ )}
+
+ {/* Realized P&L */}
+ {realizedPL && (
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${realizedPL.equityAmount >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED}`,
+ padding: '10px'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '8px', marginBottom: '4px' }}>
+ REALIZED P&L
+ </div>
+ <div style={{
+ color: realizedPL.equityAmount >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ fontSize: '13px',
+ fontWeight: 'bold'
+ }}>
+ {formatCurrency(realizedPL.equityAmount)}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Detailed Breakdown */}
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ maxHeight: '200px',
+ overflow: 'auto'
+ }}>
+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '9px' }}>
+ <thead>
+ <tr style={{ backgroundColor: BLOOMBERG_PANEL_BG, borderBottom: `1px solid ${BLOOMBERG_GRAY}` }}>
+ <th style={{ padding: '6px', textAlign: 'left', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ CATEGORY
+ </th>
+ <th style={{ padding: '6px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ EQUITY
+ </th>
+ <th style={{ padding: '6px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ COMMODITY
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {funds.map((fund, index) => (
+ <tr
+ key={fund.id}
+ style={{
+ borderBottom: index < funds.length - 1 ? `1px solid ${BLOOMBERG_GRAY}` : 'none'
+ }}
+ >
+ <td style={{ padding: '6px', color: BLOOMBERG_WHITE }}>
+ {fund.title}
+ </td>
+ <td style={{
+ padding: '6px',
+ textAlign: 'right',
+ color: fund.equityAmount >= 0 ? BLOOMBERG_WHITE : BLOOMBERG_RED,
+ fontFamily: 'Consolas, monospace'
+ }}>
+ {formatCurrency(fund.equityAmount)}
+ </td>
+ <td style={{
+ padding: '6px',
+ textAlign: 'right',
+ color: BLOOMBERG_GRAY,
+ fontFamily: 'Consolas, monospace'
+ }}>
+ {formatCurrency(fund.commodityAmount)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ );
+};
+
+export default FyersFundsPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/fyers/FyersHoldingsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/fyers/FyersHoldingsPanel.tsx
new file mode 100644
index 000000000..ae87eb3ff
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/fyers/FyersHoldingsPanel.tsx
@@ -0,0 +1,294 @@
+// Fyers Holdings Panel
+// Display long-term holdings with P&L
+
+import React, { useState, useEffect } from 'react';
+import { Package, RefreshCw } from 'lucide-react';
+import { fyersService, FyersHoldingsResponse } from '../../../services/fyersService';
+
+const FyersHoldingsPanel: React.FC = () => {
+ const [holdings, setHoldings] = useState<FyersHoldingsResponse | null>(null);
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState('');
+
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_RED = '#FF0000';
+
+ useEffect(() => {
+ loadHoldings();
+ }, []);
+
+ const loadHoldings = async () => {
+ setIsLoading(true);
+ setError('');
+
+ try {
+ const data = await fyersService.getHoldings();
+ setHoldings(data);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load holdings');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const formatCurrency = (amount: number) => {
+ return `₹${amount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+ };
+
+ const formatPercent = (value: number) => {
+ return `${value >= 0 ? '+' : ''}${value.toFixed(2)}%`;
+ };
+
+ if (isLoading) {
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px' }}>Loading holdings...</div>
+ </div>
+ );
+ }
+
+ if (error || !holdings) {
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexDirection: 'column',
+ gap: '10px'
+ }}>
+ <div style={{ color: BLOOMBERG_RED, fontSize: '10px' }}>{error || 'Failed to load holdings'}</div>
+ <button
+ onClick={loadHoldings}
+ style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '6px 12px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ RETRY
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Header with Summary */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '12px',
+ flexShrink: 0
+ }}>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '12px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Package size={12} color={BLOOMBERG_ORANGE} />
+ <span style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
+ HOLDINGS ({holdings.overall.count_total})
+ </span>
+ </div>
+
+ <button
+ onClick={loadHoldings}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <RefreshCw size={10} />
+ REFRESH
+ </button>
+ </div>
+
+ {/* Overall Summary */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: '12px'
+ }}>
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '8px'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '8px', marginBottom: '4px' }}>
+ TOTAL INVESTMENT
+ </div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '11px', fontWeight: 'bold' }}>
+ {formatCurrency(holdings.overall.total_investment)}
+ </div>
+ </div>
+
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '8px'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '8px', marginBottom: '4px' }}>
+ CURRENT VALUE
+ </div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '11px', fontWeight: 'bold' }}>
+ {formatCurrency(holdings.overall.total_current_value)}
+ </div>
+ </div>
+
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${holdings.overall.total_pl >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED}`,
+ padding: '8px'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '8px', marginBottom: '4px' }}>
+ TOTAL P&L
+ </div>
+ <div style={{
+ color: holdings.overall.total_pl >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ fontSize: '11px',
+ fontWeight: 'bold'
+ }}>
+ {formatCurrency(holdings.overall.total_pl)}
+ </div>
+ </div>
+
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${holdings.overall.pnl_perc >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED}`,
+ padding: '8px'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '8px', marginBottom: '4px' }}>
+ P&L %
+ </div>
+ <div style={{
+ color: holdings.overall.pnl_perc >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ fontSize: '11px',
+ fontWeight: 'bold'
+ }}>
+ {formatPercent(holdings.overall.pnl_perc)}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Holdings Table */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
+ {holdings.holdings.length === 0 ? (
+ <div style={{
+ textAlign: 'center',
+ color: BLOOMBERG_GRAY,
+ padding: '40px',
+ fontSize: '10px'
+ }}>
+ No holdings found
+ </div>
+ ) : (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '9px' }}>
+ <thead>
+ <tr style={{ backgroundColor: BLOOMBERG_DARK_BG, borderBottom: `1px solid ${BLOOMBERG_GRAY}` }}>
+ <th style={{ padding: '8px', textAlign: 'left', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ SYMBOL
+ </th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ QTY
+ </th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ AVG COST
+ </th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ LTP
+ </th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ MARKET VALUE
+ </th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ P&L
+ </th>
+ <th style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ TYPE
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {holdings.holdings.map((holding, index) => (
+ <tr
+ key={holding.fyToken}
+ style={{
+ borderBottom: index < holdings.holdings.length - 1 ? `1px solid ${BLOOMBERG_GRAY}` : 'none',
+ backgroundColor: index % 2 === 0 ? BLOOMBERG_DARK_BG : BLOOMBERG_PANEL_BG
+ }}
+ >
+ <td style={{ padding: '8px', color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>
+ {holding.symbol.replace('NSE:', '').replace('-EQ', '')}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_WHITE, fontFamily: 'Consolas, monospace' }}>
+ {holding.quantity}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_GRAY, fontFamily: 'Consolas, monospace' }}>
+ {formatCurrency(holding.costPrice)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_WHITE, fontFamily: 'Consolas, monospace' }}>
+ {formatCurrency(holding.ltp)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_WHITE, fontFamily: 'Consolas, monospace' }}>
+ {formatCurrency(holding.marketVal)}
+ </td>
+ <td style={{
+ padding: '8px',
+ textAlign: 'right',
+ color: holding.pl >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ fontFamily: 'Consolas, monospace',
+ fontWeight: 'bold'
+ }}>
+ {formatCurrency(holding.pl)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG_GRAY, fontSize: '8px' }}>
+ {holding.holdingType}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default FyersHoldingsPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/fyers/FyersMarketDataPanel.tsx b/fincept-terminal-desktop/src/components/tabs/fyers/FyersMarketDataPanel.tsx
new file mode 100644
index 000000000..7f3f5a08c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/fyers/FyersMarketDataPanel.tsx
@@ -0,0 +1,1116 @@
+// Fyers Market Data Panel - Bloomberg-style Screener
+// Real-time quotes with autocomplete search and dynamic price flashing
+
+import React, { useState, useEffect, useRef } from 'react';
+import { Search, TrendingUp, X, Plus, RefreshCw } from 'lucide-react';
+import { fyersService, FyersQuote } from '../../../services/fyersService';
+
+interface PriceFlash {
+ [symbol: string]: 'up' | 'down' | null;
+}
+
+interface HistoricalData {
+ [symbol: string]: number[];
+}
+
+interface OrderModalState {
+ isOpen: boolean;
+ symbol: string;
+ side: 'BUY' | 'SELL';
+ ltp: number;
+}
+
+interface GTTModalState {
+ isOpen: boolean;
+ symbol: string;
+ ltp: number;
+}
+
+// Nifty 50 stocks
+const NIFTY_50_SYMBOLS = [
+ 'NSE:NIFTY50-INDEX',
+ 'NSE:RELIANCE-EQ',
+ 'NSE:TCS-EQ',
+ 'NSE:HDFCBANK-EQ',
+ 'NSE:INFY-EQ',
+ 'NSE:ICICIBANK-EQ',
+ 'NSE:HINDUNILVR-EQ',
+ 'NSE:ITC-EQ',
+ 'NSE:SBIN-EQ',
+ 'NSE:BHARTIARTL-EQ',
+ 'NSE:KOTAKBANK-EQ',
+ 'NSE:BAJFINANCE-EQ',
+ 'NSE:LT-EQ',
+ 'NSE:HCLTECH-EQ',
+ 'NSE:ASIANPAINT-EQ',
+ 'NSE:MARUTI-EQ',
+ 'NSE:AXISBANK-EQ',
+ 'NSE:SUNPHARMA-EQ',
+ 'NSE:TITAN-EQ',
+ 'NSE:ULTRACEMCO-EQ',
+ 'NSE:WIPRO-EQ',
+ 'NSE:ONGC-EQ',
+ 'NSE:NTPC-EQ',
+ 'NSE:NESTLEIND-EQ',
+ 'NSE:POWERGRID-EQ',
+ 'NSE:M&M-EQ',
+ 'NSE:TATAMOTORS-EQ',
+ 'NSE:TATASTEEL-EQ',
+ 'NSE:BAJAJFINSV-EQ',
+ 'NSE:ADANIENT-EQ',
+ 'NSE:TECHM-EQ',
+ 'NSE:ADANIPORTS-EQ',
+ 'NSE:JSWSTEEL-EQ',
+ 'NSE:HINDALCO-EQ',
+ 'NSE:INDUSINDBK-EQ',
+ 'NSE:DIVISLAB-EQ',
+ 'NSE:BRITANNIA-EQ',
+ 'NSE:TATACONSUM-EQ',
+ 'NSE:COALINDIA-EQ',
+ 'NSE:CIPLA-EQ',
+ 'NSE:EICHERMOT-EQ',
+ 'NSE:DRREDDY-EQ',
+ 'NSE:GRASIM-EQ',
+ 'NSE:APOLLOHOSP-EQ',
+ 'NSE:BPCL-EQ',
+ 'NSE:UPL-EQ',
+ 'NSE:LTIM-EQ',
+ 'NSE:HEROMOTOCO-EQ',
+ 'NSE:BAJAJ-AUTO-EQ',
+ 'NSE:ADANIGREEN-EQ'
+];
+
+const FyersMarketDataPanel: React.FC = () => {
+ const [searchQuery, setSearchQuery] = useState('');
+ const [selectedSymbols, setSelectedSymbols] = useState<string[]>(NIFTY_50_SYMBOLS);
+ const [quotes, setQuotes] = useState<Record<string, FyersQuote>>({});
+ const [previousQuotes, setPreviousQuotes] = useState<Record<string, FyersQuote>>({});
+ const [priceFlash, setPriceFlash] = useState<PriceFlash>({});
+ const [isLoading, setIsLoading] = useState(false);
+ const [symbolMasterLoaded, setSymbolMasterLoaded] = useState(false);
+ const [marketOpen, setMarketOpen] = useState(false);
+ const [showSuggestions, setShowSuggestions] = useState(false);
+ const [historicalData, setHistoricalData] = useState<HistoricalData>({});
+ const [orderModal, setOrderModal] = useState<OrderModalState>({ isOpen: false, symbol: '', side: 'BUY', ltp: 0 });
+ const [gttModal, setGttModal] = useState<GTTModalState>({ isOpen: false, symbol: '', ltp: 0 });
+ const [orderQty, setOrderQty] = useState(1);
+ const [orderType, setOrderType] = useState<1 | 2 | 3>(2); // 1=Limit, 2=Market, 3=Stop
+ const [limitPrice, setLimitPrice] = useState(0);
+ const [stopPrice, setStopPrice] = useState(0);
+ const [productType, setProductType] = useState<'INTRADAY' | 'MARGIN' | 'CNC'>('INTRADAY');
+ const [gttSide, setGttSide] = useState<1 | -1>(1); // 1=Buy, -1=Sell
+ const [gttQty, setGttQty] = useState(1);
+ const [gttPrice, setGttPrice] = useState(0);
+ const [gttTriggerPrice, setGttTriggerPrice] = useState(0);
+ const [gttProductType, setGttProductType] = useState<'INTRADAY' | 'MARGIN' | 'CNC'>('CNC');
+ const searchInputRef = useRef<HTMLInputElement>(null);
+ const scrollContainerRef = useRef<HTMLDivElement>(null);
+
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_RED = '#FF0000';
+
+ useEffect(() => {
+ const isOpen = fyersService.isMarketOpen();
+ setMarketOpen(isOpen);
+
+ fyersService.loadSymbolMaster().then(() => {
+ setSymbolMasterLoaded(true);
+ }).catch(console.error);
+
+ loadQuotes();
+
+ // Load historical data incrementally - only load missing data
+ const loadMissingHistoricalData = async () => {
+ const missingSymbols = selectedSymbols.filter(symbol => !historicalData[symbol]);
+ if (missingSymbols.length > 0) {
+ await loadHistoricalDataForSymbols(missingSymbols);
+ }
+ };
+
+ loadMissingHistoricalData();
+
+ const refreshInterval = isOpen ? 3000 : 30000;
+ const interval = setInterval(() => {
+ loadQuotes();
+ setMarketOpen(fyersService.isMarketOpen());
+ }, refreshInterval);
+
+ return () => clearInterval(interval);
+ }, [selectedSymbols]);
+
+ const loadQuotes = async () => {
+ if (selectedSymbols.length === 0) return;
+
+ setIsLoading(true);
+ try {
+ setPreviousQuotes(quotes);
+ const data = await fyersService.getQuotes(selectedSymbols);
+ setQuotes(data);
+
+ // Detect price changes and flash
+ const newFlash: PriceFlash = {};
+ Object.keys(data).forEach(symbol => {
+ if (previousQuotes[symbol] && data[symbol]) {
+ const oldPrice = previousQuotes[symbol].ltp;
+ const newPrice = data[symbol].ltp;
+ if (oldPrice !== newPrice) {
+ newFlash[symbol] = newPrice > oldPrice ? 'up' : 'down';
+ }
+ }
+ });
+ setPriceFlash(newFlash);
+
+ setTimeout(() => setPriceFlash({}), 500);
+ } catch (error) {
+ console.error('[Market Data] Failed to load quotes:', error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const loadHistoricalDataForSymbols = async (symbols: string[]) => {
+ try {
+ const now = Math.floor(Date.now() / 1000);
+ const thirtyDaysAgo = now - (30 * 24 * 60 * 60);
+
+ // Load history ONE at a time with 1 second delay to respect rate limit
+ for (let i = 0; i < symbols.length; i++) {
+ const symbol = symbols[i];
+
+ try {
+ // Save scroll position before updating
+ const scrollTop = scrollContainerRef.current?.scrollTop || 0;
+
+ const history = await fyersService.getHistory({
+ symbol,
+ resolution: 'D',
+ date_format: '0',
+ range_from: thirtyDaysAgo.toString(),
+ range_to: now.toString(),
+ cont_flag: '1'
+ });
+
+ if (history.s === 'ok' && history.candles && history.candles.length > 0) {
+ // Get last 15 data points for smoother chart
+ const closePrices = history.candles.map((candle: any[]) => candle[4]);
+
+ // Update state without triggering scroll jumps
+ setHistoricalData(prev => ({ ...prev, [symbol]: closePrices.slice(-15) }));
+
+ // Restore scroll position after state update
+ requestAnimationFrame(() => {
+ if (scrollContainerRef.current) {
+ scrollContainerRef.current.scrollTop = scrollTop;
+ }
+ });
+ }
+ } catch (err: any) {
+ if (err?.code === 429) {
+ console.warn(`Rate limit for ${symbol}, waiting longer...`);
+ await new Promise(resolve => setTimeout(resolve, 2000));
+ }
+ }
+
+ // 1 second delay between each request to respect rate limit
+ if (i < symbols.length - 1) {
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ }
+ }
+ } catch (error) {
+ console.error('[Market Data] Failed to load historical data:', error);
+ }
+ };
+
+ const loadHistoricalData = async () => {
+ await loadHistoricalDataForSymbols(selectedSymbols);
+ };
+
+ const handleAddSymbol = (symbol: string) => {
+ if (!symbol.trim() || selectedSymbols.includes(symbol)) return;
+ setSelectedSymbols([...selectedSymbols, symbol]);
+ setSearchQuery('');
+ setShowSuggestions(false);
+ };
+
+ const handleRemoveSymbol = (symbol: string) => {
+ setSelectedSymbols(selectedSymbols.filter(s => s !== symbol));
+ };
+
+ const handleOpenOrderModal = (symbol: string, side: 'BUY' | 'SELL', ltp: number) => {
+ setOrderModal({ isOpen: true, symbol, side, ltp });
+ setLimitPrice(ltp);
+ setOrderQty(1);
+ setOrderType(2); // Market order by default
+ };
+
+ const handleOpenGTTModal = (symbol: string, ltp: number) => {
+ setGttModal({ isOpen: true, symbol, ltp });
+ setGttPrice(ltp);
+ setGttTriggerPrice(ltp);
+ setGttQty(1);
+ setGttSide(1);
+ setGttProductType('CNC');
+ };
+
+ const handlePlaceOrder = async () => {
+ try {
+ const orderPayload = {
+ symbol: orderModal.symbol,
+ qty: orderQty,
+ type: orderType, // 1=Limit, 2=Market, 3=Stop
+ side: orderModal.side === 'BUY' ? 1 : -1,
+ productType: productType,
+ limitPrice: orderType === 1 ? limitPrice : 0,
+ stopPrice: orderType === 3 ? stopPrice : 0,
+ disclosedQty: 0,
+ validity: 'DAY',
+ offlineOrder: false,
+ stopLoss: 0,
+ takeProfit: 0,
+ orderTag: 'fincept-terminal'
+ };
+
+ const response = await fyersService.placeOrder(orderPayload);
+
+ if (response.s === 'ok') {
+ alert(`Order placed successfully! Order ID: ${response.id || 'N/A'}`);
+ setOrderModal({ isOpen: false, symbol: '', side: 'BUY', ltp: 0 });
+ } else {
+ alert(`Order failed: ${response.message || 'Unknown error'}`);
+ }
+ } catch (error: any) {
+ console.error('Order placement error:', error);
+ alert(`Order failed: ${error.message || 'Unknown error'}`);
+ }
+ };
+
+ const handlePlaceGTTOrder = async () => {
+ try {
+ const gttPayload = {
+ side: gttSide,
+ symbol: gttModal.symbol,
+ productType: gttProductType,
+ orderInfo: {
+ leg1: {
+ price: gttPrice,
+ triggerPrice: gttTriggerPrice,
+ qty: gttQty
+ }
+ }
+ };
+
+ const response = await fyersService.placeGTTOrder(gttPayload);
+
+ if (response.s === 'ok') {
+ alert(`GTT Order placed successfully! Order ID: ${response.id || 'N/A'}`);
+ setGttModal({ isOpen: false, symbol: '', ltp: 0 });
+ } else {
+ alert(`GTT Order failed: ${response.message || 'Unknown error'}`);
+ }
+ } catch (error: any) {
+ console.error('GTT Order placement error:', error);
+ alert(`GTT Order failed: ${error.message || 'Unknown error'}`);
+ }
+ };
+
+ const handleManualRefresh = () => {
+ loadQuotes();
+ loadHistoricalData();
+ };
+
+ const searchResults = () => {
+ if (!symbolMasterLoaded || !searchQuery || searchQuery.length < 2) return [];
+ return fyersService.searchSymbols(searchQuery, 10);
+ };
+
+ const formatCurrency = (amount: number | undefined) => {
+ if (amount === undefined || amount === null || isNaN(amount)) return '...';
+ return `₹${amount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+ };
+
+ const formatPercent = (value: number | undefined) => {
+ if (value === undefined || value === null || isNaN(value)) return '...';
+ return `${value >= 0 ? '+' : ''}${value.toFixed(2)}%`;
+ };
+
+ const getFlashColor = (symbol: string) => {
+ const flash = priceFlash[symbol];
+ if (!flash) return 'transparent';
+ return flash === 'up' ? 'rgba(0, 200, 0, 0.3)' : 'rgba(255, 0, 0, 0.3)';
+ };
+
+ const getPriceColor = (symbol: string) => {
+ const quote = quotes[symbol];
+ if (!quote || !quote.ch) return BLOOMBERG_WHITE;
+ return quote.ch > 0 ? BLOOMBERG_GREEN : quote.ch < 0 ? BLOOMBERG_RED : BLOOMBERG_WHITE;
+ };
+
+ const Sparkline: React.FC<{ data: number[], width: number, height: number, color: string }> = ({ data, width, height, color }) => {
+ if (!data || data.length < 2) return null;
+
+ const min = Math.min(...data);
+ const max = Math.max(...data);
+ const range = max - min || 1;
+
+ // Create area chart path
+ const areaPoints: string[] = [];
+ const linePoints: string[] = [];
+
+ data.forEach((value, index) => {
+ const x = (index / (data.length - 1)) * width;
+ const y = height - ((value - min) / range) * (height - 4); // Leave 4px padding
+ linePoints.push(`${x},${y}`);
+ });
+
+ // Create area path (line + bottom closing)
+ const areaPath = `M 0,${height} L ${linePoints.join(' L ')} L ${width},${height} Z`;
+
+ return (
+ <svg width={width} height={height} style={{ display: 'block', margin: 'auto' }}>
+ {/* Area fill */}
+ <path
+ d={areaPath}
+ fill={color}
+ fillOpacity="0.15"
+ />
+ {/* Line */}
+ <polyline
+ points={linePoints.join(' ')}
+ fill="none"
+ stroke={color}
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ );
+ };
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ display: 'flex',
+ flexDirection: 'column',
+ fontFamily: 'Consolas, monospace'
+ }}>
+ {/* Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '8px 12px',
+ flexShrink: 0
+ }}>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '8px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <TrendingUp size={12} color={BLOOMBERG_ORANGE} />
+ <span style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
+ MARKET SCREENER
+ </span>
+ <span style={{
+ fontSize: '9px',
+ color: marketOpen ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ fontWeight: 'bold',
+ padding: '2px 6px',
+ border: `1px solid ${marketOpen ? BLOOMBERG_GREEN : BLOOMBERG_RED}`,
+ backgroundColor: marketOpen ? 'rgba(0, 200, 0, 0.1)' : 'rgba(255, 0, 0, 0.1)'
+ }}>
+ {marketOpen ? 'LIVE' : 'CLOSED'}
+ </span>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <button
+ onClick={handleManualRefresh}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_ORANGE}`,
+ color: BLOOMBERG_ORANGE,
+ padding: '4px 10px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: 'bold',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <RefreshCw size={10} />
+ REFRESH CHARTS
+ </button>
+ <span style={{ color: BLOOMBERG_GRAY, fontSize: '9px' }}>
+ {selectedSymbols.length} SYMBOLS
+ </span>
+ </div>
+ </div>
+
+ {/* Search with Autocomplete */}
+ <div style={{ position: 'relative' }}>
+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
+ <Search size={12} color={BLOOMBERG_GRAY} />
+ <input
+ ref={searchInputRef}
+ type="text"
+ value={searchQuery}
+ onChange={(e) => {
+ setSearchQuery(e.target.value);
+ setShowSuggestions(e.target.value.length >= 2);
+ }}
+ onFocus={() => setShowSuggestions(searchQuery.length >= 2)}
+ onBlur={() => setTimeout(() => setShowSuggestions(false), 200)}
+ placeholder="Search symbols... (e.g., RELIANCE, TCS, INFY)"
+ style={{
+ flex: 1,
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px 8px',
+ fontSize: '10px',
+ outline: 'none'
+ }}
+ />
+ </div>
+
+ {/* Autocomplete Dropdown */}
+ {showSuggestions && searchResults().length > 0 && (
+ <div style={{
+ position: 'absolute',
+ top: '100%',
+ left: 0,
+ right: 0,
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_ORANGE}`,
+ maxHeight: '200px',
+ overflowY: 'auto',
+ zIndex: 1000,
+ marginTop: '2px'
+ }}>
+ {searchResults().map((result, idx) => (
+ <div
+ key={idx}
+ onClick={() => handleAddSymbol(result.symbol)}
+ style={{
+ padding: '8px',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ cursor: 'pointer',
+ backgroundColor: BLOOMBERG_PANEL_BG
+ }}
+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = BLOOMBERG_DARK_BG}
+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = BLOOMBERG_PANEL_BG}
+ >
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold' }}>
+ {result.shortName || result.symbol}
+ </div>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px' }}>
+ {result.displayName || result.description}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Bloomberg-style Screener Table */}
+ <div
+ ref={scrollContainerRef}
+ style={{
+ flex: 1,
+ overflow: 'auto',
+ backgroundColor: BLOOMBERG_DARK_BG
+ }}
+ className="custom-scrollbar">
+ <table style={{
+ width: '100%',
+ borderCollapse: 'collapse',
+ fontSize: '11px'
+ }}>
+ <thead style={{
+ position: 'sticky',
+ top: 0,
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `2px solid ${BLOOMBERG_ORANGE}`
+ }}>
+ <tr>
+ <th style={{ padding: '8px', textAlign: 'left', color: BLOOMBERG_ORANGE, fontWeight: 'bold', width: '14%' }}>SYMBOL</th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold', width: '10%' }}>LTP</th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold', width: '8%' }}>CHG</th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold', width: '8%' }}>CHG%</th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold', width: '9%' }}>HIGH</th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold', width: '9%' }}>LOW</th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold', width: '10%' }}>VOL</th>
+ <th style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG_ORANGE, fontWeight: 'bold', width: '14%' }}>TREND (15D)</th>
+ <th style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG_ORANGE, fontWeight: 'bold', width: '16%' }}>ACTION</th>
+ <th style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG_ORANGE, fontWeight: 'bold', width: '2%' }}></th>
+ </tr>
+ </thead>
+ <tbody>
+ {selectedSymbols.map((symbol, idx) => {
+ const quote = quotes[symbol];
+ const loading = !quote;
+
+ return (
+ <tr
+ key={symbol}
+ style={{
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: idx % 2 === 0 ? BLOOMBERG_DARK_BG : BLOOMBERG_PANEL_BG
+ }}
+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#111111'}
+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = idx % 2 === 0 ? BLOOMBERG_DARK_BG : BLOOMBERG_PANEL_BG}
+ >
+ <td style={{ padding: '8px', color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>
+ {symbol.split(':')[1] || symbol}
+ </td>
+ <td style={{
+ padding: '8px',
+ textAlign: 'right',
+ color: loading ? BLOOMBERG_GRAY : getPriceColor(symbol),
+ fontWeight: 'bold',
+ backgroundColor: getFlashColor(symbol),
+ transition: 'background-color 0.5s ease'
+ }}>
+ {loading ? '...' : formatCurrency(quote?.ltp)}
+ </td>
+ <td style={{
+ padding: '8px',
+ textAlign: 'right',
+ color: loading ? BLOOMBERG_GRAY : ((quote?.ch || 0) > 0 ? BLOOMBERG_GREEN : (quote?.ch || 0) < 0 ? BLOOMBERG_RED : BLOOMBERG_WHITE)
+ }}>
+ {loading ? '...' : formatCurrency(Math.abs(quote?.ch || 0))}
+ </td>
+ <td style={{
+ padding: '8px',
+ textAlign: 'right',
+ color: loading ? BLOOMBERG_GRAY : ((quote?.chp || 0) > 0 ? BLOOMBERG_GREEN : (quote?.chp || 0) < 0 ? BLOOMBERG_RED : BLOOMBERG_WHITE),
+ fontWeight: 'bold'
+ }}>
+ {loading ? '...' : formatPercent(quote?.chp)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_WHITE }}>
+ {loading ? '...' : formatCurrency(quote?.high)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_WHITE }}>
+ {loading ? '...' : formatCurrency(quote?.low)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_WHITE }}>
+ {loading ? '...' : ((quote?.volume || 0) > 0 ? (quote?.volume || 0).toLocaleString('en-IN') : '...')}
+ </td>
+ <td style={{
+ padding: '8px 12px',
+ textAlign: 'center',
+ verticalAlign: 'middle'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ minHeight: '24px'
+ }}>
+ {historicalData[symbol] && historicalData[symbol].length > 0 ? (
+ <Sparkline
+ data={historicalData[symbol]}
+ width={100}
+ height={28}
+ color={quote?.chp > 0 ? BLOOMBERG_GREEN : quote?.chp < 0 ? BLOOMBERG_RED : BLOOMBERG_GRAY}
+ />
+ ) : (
+ <span style={{ color: BLOOMBERG_GRAY, fontSize: '9px' }}>Loading...</span>
+ )}
+ </div>
+ </td>
+ <td style={{ padding: '6px', textAlign: 'center' }}>
+ <div style={{ display: 'flex', gap: '4px', justifyContent: 'center', flexWrap: 'wrap' }}>
+ <button
+ onClick={() => handleOpenOrderModal(symbol, 'BUY', quote?.ltp || 0)}
+ disabled={loading || !quote}
+ style={{
+ backgroundColor: BLOOMBERG_GREEN,
+ color: 'black',
+ border: 'none',
+ padding: '4px 10px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: loading || !quote ? 'not-allowed' : 'pointer',
+ opacity: loading || !quote ? 0.5 : 1,
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ BUY
+ </button>
+ <button
+ onClick={() => handleOpenOrderModal(symbol, 'SELL', quote?.ltp || 0)}
+ disabled={loading || !quote}
+ style={{
+ backgroundColor: BLOOMBERG_RED,
+ color: BLOOMBERG_WHITE,
+ border: 'none',
+ padding: '4px 10px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: loading || !quote ? 'not-allowed' : 'pointer',
+ opacity: loading || !quote ? 0.5 : 1,
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ SELL
+ </button>
+ <button
+ onClick={() => handleOpenGTTModal(symbol, quote?.ltp || 0)}
+ disabled={loading || !quote}
+ style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '4px 10px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: loading || !quote ? 'not-allowed' : 'pointer',
+ opacity: loading || !quote ? 0.5 : 1,
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ GTT
+ </button>
+ </div>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center' }}>
+ <X
+ size={12}
+ color={BLOOMBERG_RED}
+ style={{ cursor: 'pointer' }}
+ onClick={() => handleRemoveSymbol(symbol)}
+ />
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+
+ {selectedSymbols.length === 0 && (
+ <div style={{
+ padding: '40px',
+ textAlign: 'center',
+ color: BLOOMBERG_GRAY,
+ fontSize: '11px'
+ }}>
+ No symbols added. Use search above to add symbols to your screener.
+ </div>
+ )}
+ </div>
+
+ {/* Order Modal */}
+ {orderModal.isOpen && (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0, 0, 0, 0.8)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 9999
+ }}>
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `2px solid ${BLOOMBERG_ORANGE}`,
+ padding: '24px',
+ minWidth: '400px',
+ maxWidth: '500px'
+ }}>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '20px',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ paddingBottom: '12px'
+ }}>
+ <h3 style={{
+ color: orderModal.side === 'BUY' ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ margin: 0,
+ fontSize: '16px',
+ fontWeight: 'bold'
+ }}>
+ {orderModal.side} {orderModal.symbol.split(':')[1] || orderModal.symbol}
+ </h3>
+ <X
+ size={18}
+ color={BLOOMBERG_GRAY}
+ style={{ cursor: 'pointer' }}
+ onClick={() => setOrderModal({ isOpen: false, symbol: '', side: 'BUY', ltp: 0 })}
+ />
+ </div>
+
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: BLOOMBERG_WHITE, fontSize: '11px', display: 'block', marginBottom: '6px' }}>
+ Order Type
+ </label>
+ <select
+ value={orderType}
+ onChange={(e) => setOrderType(Number(e.target.value) as 1 | 2 | 3)}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <option value={2}>MARKET</option>
+ <option value={1}>LIMIT</option>
+ <option value={3}>STOP</option>
+ </select>
+ </div>
+
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: BLOOMBERG_WHITE, fontSize: '11px', display: 'block', marginBottom: '6px' }}>
+ Product Type
+ </label>
+ <select
+ value={productType}
+ onChange={(e) => setProductType(e.target.value as 'INTRADAY' | 'MARGIN' | 'CNC')}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <option value="INTRADAY">INTRADAY</option>
+ <option value="CNC">CNC (DELIVERY)</option>
+ <option value="MARGIN">MARGIN</option>
+ </select>
+ </div>
+
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: BLOOMBERG_WHITE, fontSize: '11px', display: 'block', marginBottom: '6px' }}>
+ Quantity
+ </label>
+ <input
+ type="number"
+ value={orderQty}
+ onChange={(e) => setOrderQty(Math.max(1, parseInt(e.target.value) || 1))}
+ min={1}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {orderType === 1 && (
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: BLOOMBERG_WHITE, fontSize: '11px', display: 'block', marginBottom: '6px' }}>
+ Limit Price (Current LTP: ₹{orderModal.ltp.toFixed(2)})
+ </label>
+ <input
+ type="number"
+ value={limitPrice}
+ onChange={(e) => setLimitPrice(parseFloat(e.target.value) || 0)}
+ step={0.05}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+ )}
+
+ {orderType === 3 && (
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: BLOOMBERG_WHITE, fontSize: '11px', display: 'block', marginBottom: '6px' }}>
+ Stop Price
+ </label>
+ <input
+ type="number"
+ value={stopPrice}
+ onChange={(e) => setStopPrice(parseFloat(e.target.value) || 0)}
+ step={0.05}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+ )}
+
+ <div style={{
+ display: 'flex',
+ gap: '12px',
+ marginTop: '24px',
+ paddingTop: '16px',
+ borderTop: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <button
+ onClick={handlePlaceOrder}
+ style={{
+ flex: 1,
+ backgroundColor: orderModal.side === 'BUY' ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ color: orderModal.side === 'BUY' ? 'black' : BLOOMBERG_WHITE,
+ border: 'none',
+ padding: '10px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ PLACE {orderModal.side} ORDER
+ </button>
+ <button
+ onClick={() => setOrderModal({ isOpen: false, symbol: '', side: 'BUY', ltp: 0 })}
+ style={{
+ flex: 0.4,
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '10px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ CANCEL
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* GTT Order Modal */}
+ {gttModal.isOpen && (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0, 0, 0, 0.8)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 9999
+ }}>
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `2px solid ${BLOOMBERG_ORANGE}`,
+ padding: '24px',
+ minWidth: '400px',
+ maxWidth: '500px'
+ }}>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '20px',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ paddingBottom: '12px'
+ }}>
+ <h3 style={{
+ color: BLOOMBERG_ORANGE,
+ margin: 0,
+ fontSize: '16px',
+ fontWeight: 'bold'
+ }}>
+ GTT ORDER - {gttModal.symbol.split(':')[1] || gttModal.symbol}
+ </h3>
+ <X
+ size={18}
+ color={BLOOMBERG_GRAY}
+ style={{ cursor: 'pointer' }}
+ onClick={() => setGttModal({ isOpen: false, symbol: '', ltp: 0 })}
+ />
+ </div>
+
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: BLOOMBERG_WHITE, fontSize: '11px', display: 'block', marginBottom: '6px' }}>
+ Side
+ </label>
+ <select
+ value={gttSide}
+ onChange={(e) => setGttSide(Number(e.target.value) as 1 | -1)}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <option value={1}>BUY</option>
+ <option value={-1}>SELL</option>
+ </select>
+ </div>
+
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: BLOOMBERG_WHITE, fontSize: '11px', display: 'block', marginBottom: '6px' }}>
+ Product Type
+ </label>
+ <select
+ value={gttProductType}
+ onChange={(e) => setGttProductType(e.target.value as 'INTRADAY' | 'MARGIN' | 'CNC')}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <option value="CNC">CNC (DELIVERY)</option>
+ <option value="INTRADAY">INTRADAY</option>
+ <option value="MARGIN">MARGIN</option>
+ </select>
+ </div>
+
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: BLOOMBERG_WHITE, fontSize: '11px', display: 'block', marginBottom: '6px' }}>
+ Quantity
+ </label>
+ <input
+ type="number"
+ value={gttQty}
+ onChange={(e) => setGttQty(Math.max(1, parseInt(e.target.value) || 1))}
+ min={1}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: BLOOMBERG_WHITE, fontSize: '11px', display: 'block', marginBottom: '6px' }}>
+ Trigger Price (Current LTP: ₹{gttModal.ltp.toFixed(2)})
+ </label>
+ <input
+ type="number"
+ value={gttTriggerPrice}
+ onChange={(e) => setGttTriggerPrice(parseFloat(e.target.value) || 0)}
+ step={0.05}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{ color: BLOOMBERG_WHITE, fontSize: '11px', display: 'block', marginBottom: '6px' }}>
+ Limit Price
+ </label>
+ <input
+ type="number"
+ value={gttPrice}
+ onChange={(e) => setGttPrice(parseFloat(e.target.value) || 0)}
+ step={0.05}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ <div style={{
+ display: 'flex',
+ gap: '12px',
+ marginTop: '24px',
+ paddingTop: '16px',
+ borderTop: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <button
+ onClick={handlePlaceGTTOrder}
+ style={{
+ flex: 1,
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '10px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ PLACE GTT ORDER
+ </button>
+ <button
+ onClick={() => setGttModal({ isOpen: false, symbol: '', ltp: 0 })}
+ style={{
+ flex: 0.4,
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '10px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ CANCEL
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default FyersMarketDataPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/fyers/FyersOrdersPanel.tsx b/fincept-terminal-desktop/src/components/tabs/fyers/FyersOrdersPanel.tsx
new file mode 100644
index 000000000..ba06495fc
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/fyers/FyersOrdersPanel.tsx
@@ -0,0 +1,272 @@
+// Fyers Orders Panel
+// View and place orders with live updates
+
+import React, { useState, useEffect } from 'react';
+import { FileText, RefreshCw, Plus } from 'lucide-react';
+import { fyersService, FyersOrder } from '../../../services/fyersService';
+import { fyersWebSocket } from '../../../services/fyersWebSocket';
+
+interface FyersOrdersPanelProps {
+ wsConnected: boolean;
+}
+
+const FyersOrdersPanel: React.FC<FyersOrdersPanelProps> = ({ wsConnected }) => {
+ const [orders, setOrders] = useState<FyersOrder[]>([]);
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState('');
+
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_RED = '#FF0000';
+ const BLOOMBERG_YELLOW = '#FFFF00';
+
+ useEffect(() => {
+ loadOrders();
+
+ // Subscribe to order updates if WebSocket connected
+ if (wsConnected) {
+ fyersWebSocket.onOrderUpdate((update) => {
+ console.log('[Orders] WebSocket update:', update);
+ loadOrders(); // Refresh orders on update
+ });
+ }
+
+ return () => {
+ fyersWebSocket.clearCallbacks();
+ };
+ }, [wsConnected]);
+
+ const loadOrders = async () => {
+ setIsLoading(true);
+ setError('');
+
+ try {
+ const data = await fyersService.getOrders();
+ setOrders(data);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load orders');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const getOrderStatusColor = (status: number) => {
+ // Status codes: 1=Pending, 2=Placed, 5=Partially Filled, 6=Filled, 7=Rejected, 8=Cancelled
+ if (status === 6) return BLOOMBERG_GREEN; // Filled
+ if (status === 7) return BLOOMBERG_RED; // Rejected
+ if (status === 8) return BLOOMBERG_GRAY; // Cancelled
+ if (status === 5) return BLOOMBERG_YELLOW; // Partially Filled
+ return BLOOMBERG_ORANGE; // Pending/Placed
+ };
+
+ const getOrderStatusText = (status: number) => {
+ const statusMap: Record<number, string> = {
+ 1: 'PENDING',
+ 2: 'PLACED',
+ 5: 'PARTIAL',
+ 6: 'FILLED',
+ 7: 'REJECTED',
+ 8: 'CANCELLED',
+ 90: 'COMPLETE'
+ };
+ return statusMap[status] || `STATUS_${status}`;
+ };
+
+ const formatCurrency = (amount: number) => {
+ return `₹${amount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+ };
+
+ if (isLoading && orders.length === 0) {
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px' }}>Loading orders...</div>
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '12px',
+ flexShrink: 0,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <FileText size={12} color={BLOOMBERG_ORANGE} />
+ <span style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
+ ORDER BOOK ({orders.length})
+ </span>
+ {wsConnected && (
+ <span style={{
+ color: BLOOMBERG_GREEN,
+ fontSize: '8px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ padding: '2px 6px',
+ border: `1px solid ${BLOOMBERG_GREEN}`
+ }}>
+ LIVE
+ </span>
+ )}
+ </div>
+
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={loadOrders}
+ disabled={isLoading}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: isLoading ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ opacity: isLoading ? 0.5 : 1
+ }}
+ >
+ <RefreshCw size={10} />
+ REFRESH
+ </button>
+ </div>
+ </div>
+
+ {/* Orders Table */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
+ {error && (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_RED}`,
+ color: BLOOMBERG_RED,
+ padding: '10px',
+ fontSize: '9px',
+ marginBottom: '12px'
+ }}>
+ {error}
+ </div>
+ )}
+
+ {orders.length === 0 ? (
+ <div style={{
+ textAlign: 'center',
+ color: BLOOMBERG_GRAY,
+ padding: '40px',
+ fontSize: '10px'
+ }}>
+ No orders found
+ </div>
+ ) : (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '9px' }}>
+ <thead>
+ <tr style={{ backgroundColor: BLOOMBERG_DARK_BG, borderBottom: `1px solid ${BLOOMBERG_GRAY}` }}>
+ <th style={{ padding: '8px', textAlign: 'left', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ TIME
+ </th>
+ <th style={{ padding: '8px', textAlign: 'left', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ SYMBOL
+ </th>
+ <th style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ TYPE
+ </th>
+ <th style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ SIDE
+ </th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ QTY
+ </th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ PRICE
+ </th>
+ <th style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ STATUS
+ </th>
+ <th style={{ padding: '8px', textAlign: 'left', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ ORDER ID
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {orders.map((order, index) => (
+ <tr
+ key={order.id}
+ style={{
+ borderBottom: index < orders.length - 1 ? `1px solid ${BLOOMBERG_GRAY}` : 'none',
+ backgroundColor: index % 2 === 0 ? BLOOMBERG_DARK_BG : BLOOMBERG_PANEL_BG
+ }}
+ >
+ <td style={{ padding: '8px', color: BLOOMBERG_GRAY, fontSize: '8px' }}>
+ {order.orderDateTime}
+ </td>
+ <td style={{ padding: '8px', color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>
+ {order.symbol}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG_GRAY, fontSize: '8px' }}>
+ {order.type === 1 ? 'LIMIT' : order.type === 2 ? 'MARKET' : `TYPE_${order.type}`}
+ </td>
+ <td style={{
+ padding: '8px',
+ textAlign: 'center',
+ color: order.side === 1 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ fontWeight: 'bold',
+ fontSize: '8px'
+ }}>
+ {order.side === 1 ? 'BUY' : 'SELL'}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_WHITE, fontFamily: 'Consolas, monospace' }}>
+ {order.filledQty}/{order.qty}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_GRAY, fontFamily: 'Consolas, monospace' }}>
+ {formatCurrency(order.limitPrice)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center' }}>
+ <span style={{
+ color: getOrderStatusColor(order.status),
+ fontSize: '8px',
+ fontWeight: 'bold',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ padding: '2px 6px',
+ border: `1px solid ${getOrderStatusColor(order.status)}`
+ }}>
+ {getOrderStatusText(order.status)}
+ </span>
+ </td>
+ <td style={{ padding: '8px', color: BLOOMBERG_GRAY, fontSize: '8px', fontFamily: 'Consolas, monospace' }}>
+ {order.id}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default FyersOrdersPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/fyers/FyersPositionsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/fyers/FyersPositionsPanel.tsx
new file mode 100644
index 000000000..9e27c97a9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/fyers/FyersPositionsPanel.tsx
@@ -0,0 +1,234 @@
+// Fyers Positions Panel
+// Display open positions with live updates
+
+import React, { useState, useEffect } from 'react';
+import { Activity, RefreshCw } from 'lucide-react';
+import { fyersService, FyersPosition } from '../../../services/fyersService';
+import { fyersWebSocket } from '../../../services/fyersWebSocket';
+
+interface FyersPositionsPanelProps {
+ wsConnected: boolean;
+}
+
+const FyersPositionsPanel: React.FC<FyersPositionsPanelProps> = ({ wsConnected }) => {
+ const [positions, setPositions] = useState<FyersPosition[]>([]);
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState('');
+
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_RED = '#FF0000';
+
+ useEffect(() => {
+ loadPositions();
+
+ // Subscribe to position updates if WebSocket connected
+ if (wsConnected) {
+ fyersWebSocket.onPositionUpdate((update) => {
+ console.log('[Positions] WebSocket update:', update);
+ loadPositions(); // Refresh positions on update
+ });
+ }
+
+ return () => {
+ fyersWebSocket.clearCallbacks();
+ };
+ }, [wsConnected]);
+
+ const loadPositions = async () => {
+ setIsLoading(true);
+ setError('');
+
+ try {
+ const data = await fyersService.getPositions();
+ setPositions(data);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load positions');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const formatCurrency = (amount: number) => {
+ return `₹${amount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+ };
+
+ if (isLoading && positions.length === 0) {
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px' }}>Loading positions...</div>
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '12px',
+ flexShrink: 0,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Activity size={12} color={BLOOMBERG_ORANGE} />
+ <span style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
+ POSITIONS ({positions.length})
+ </span>
+ {wsConnected && (
+ <span style={{
+ color: BLOOMBERG_GREEN,
+ fontSize: '8px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ padding: '2px 6px',
+ border: `1px solid ${BLOOMBERG_GREEN}`
+ }}>
+ LIVE
+ </span>
+ )}
+ </div>
+
+ <button
+ onClick={loadPositions}
+ disabled={isLoading}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: isLoading ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ opacity: isLoading ? 0.5 : 1
+ }}
+ >
+ <RefreshCw size={10} />
+ REFRESH
+ </button>
+ </div>
+
+ {/* Positions Table */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
+ {error && (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_RED}`,
+ color: BLOOMBERG_RED,
+ padding: '10px',
+ fontSize: '9px',
+ marginBottom: '12px'
+ }}>
+ {error}
+ </div>
+ )}
+
+ {positions.length === 0 ? (
+ <div style={{
+ textAlign: 'center',
+ color: BLOOMBERG_GRAY,
+ padding: '40px',
+ fontSize: '10px'
+ }}>
+ No open positions
+ </div>
+ ) : (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '9px' }}>
+ <thead>
+ <tr style={{ backgroundColor: BLOOMBERG_DARK_BG, borderBottom: `1px solid ${BLOOMBERG_GRAY}` }}>
+ <th style={{ padding: '8px', textAlign: 'left', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ SYMBOL
+ </th>
+ <th style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ PRODUCT
+ </th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ QTY
+ </th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ AVG PRICE
+ </th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ LTP
+ </th>
+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>
+ P&L
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {positions.map((position, index) => (
+ <tr
+ key={position.id || index}
+ style={{
+ borderBottom: index < positions.length - 1 ? `1px solid ${BLOOMBERG_GRAY}` : 'none',
+ backgroundColor: index % 2 === 0 ? BLOOMBERG_DARK_BG : BLOOMBERG_PANEL_BG
+ }}
+ >
+ <td style={{ padding: '8px', color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>
+ {position.symbol}
+ <span style={{
+ marginLeft: '6px',
+ color: position.netQty > 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ fontSize: '8px',
+ fontWeight: 'bold'
+ }}>
+ {position.netQty > 0 ? 'LONG' : 'SHORT'}
+ </span>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG_GRAY, fontSize: '8px' }}>
+ {position.productType}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_WHITE, fontFamily: 'Consolas, monospace' }}>
+ {Math.abs(position.netQty)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_GRAY, fontFamily: 'Consolas, monospace' }}>
+ {formatCurrency(position.netAvg)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG_WHITE, fontFamily: 'Consolas, monospace' }}>
+ {formatCurrency(position.ltp)}
+ </td>
+ <td style={{
+ padding: '8px',
+ textAlign: 'right',
+ color: position.pl >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ fontFamily: 'Consolas, monospace',
+ fontWeight: 'bold'
+ }}>
+ {formatCurrency(position.pl)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default FyersPositionsPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/fyers/FyersProfilePanel.tsx b/fincept-terminal-desktop/src/components/tabs/fyers/FyersProfilePanel.tsx
new file mode 100644
index 000000000..3c8172248
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/fyers/FyersProfilePanel.tsx
@@ -0,0 +1,120 @@
+// Fyers Profile Panel
+// Display user profile information
+
+import React, { useState, useEffect } from 'react';
+import { User } from 'lucide-react';
+import { fyersService, FyersProfile } from '../../../services/fyersService';
+
+const FyersProfilePanel: React.FC = () => {
+ const [profile, setProfile] = useState<FyersProfile | null>(null);
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState('');
+
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+
+ useEffect(() => {
+ loadProfile();
+ }, []);
+
+ const loadProfile = async () => {
+ setIsLoading(true);
+ setError('');
+
+ try {
+ const data = await fyersService.getProfile();
+ setProfile(data);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load profile');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ if (isLoading) {
+ return (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '12px',
+ marginBottom: '12px'
+ }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px' }}>Loading profile...</div>
+ </div>
+ );
+ }
+
+ if (error || !profile) {
+ return (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid #FF0000`,
+ padding: '12px',
+ marginBottom: '12px'
+ }}>
+ <div style={{ color: '#FF0000', fontSize: '10px' }}>{error || 'Failed to load profile'}</div>
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_ORANGE}`,
+ padding: '12px',
+ marginBottom: '12px'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <User size={12} color={BLOOMBERG_ORANGE} />
+ <span style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
+ PROFILE
+ </span>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px' }}>
+ {/* Profile Image */}
+ {profile.image && (
+ <img
+ src={profile.image}
+ alt={profile.name}
+ style={{
+ width: '50px',
+ height: '50px',
+ borderRadius: '2px',
+ border: `1px solid ${BLOOMBERG_GRAY}`
+ }}
+ />
+ )}
+
+ {/* Profile Details */}
+ <div style={{ flex: 1 }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: '8px', fontSize: '10px' }}>
+ <div style={{ color: BLOOMBERG_GRAY }}>Name:</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>{profile.name}</div>
+
+ <div style={{ color: BLOOMBERG_GRAY }}>Display Name:</div>
+ <div style={{ color: BLOOMBERG_WHITE }}>{profile.display_name}</div>
+
+ <div style={{ color: BLOOMBERG_GRAY }}>Email:</div>
+ <div style={{ color: BLOOMBERG_WHITE }}>{profile.email_id}</div>
+
+ <div style={{ color: BLOOMBERG_GRAY }}>PAN:</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontFamily: 'Consolas, monospace' }}>{profile.PAN}</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default FyersProfilePanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/fyers/FyersTradingPanel.tsx b/fincept-terminal-desktop/src/components/tabs/fyers/FyersTradingPanel.tsx
new file mode 100644
index 000000000..7e8b184bc
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/fyers/FyersTradingPanel.tsx
@@ -0,0 +1,931 @@
+// Fyers Trading Panel - Order Placement and Margin Calculator
+import React, { useState, useEffect } from 'react';
+import { TrendingUp, TrendingDown, Calculator, DollarSign, Activity } from 'lucide-react';
+import { fyersService } from '../../../services/fyersService';
+
+const BLOOMBERG_ORANGE = '#FFA500';
+const BLOOMBERG_WHITE = '#FFFFFF';
+const BLOOMBERG_GRAY = '#787878';
+const BLOOMBERG_DARK_BG = '#000000';
+const BLOOMBERG_PANEL_BG = '#0a0a0a';
+const BLOOMBERG_GREEN = '#00C800';
+const BLOOMBERG_RED = '#FF0000';
+
+interface Order {
+ symbol: string;
+ qty: number;
+ side: 'BUY' | 'SELL';
+ type: 'MARKET' | 'LIMIT' | 'STOP';
+ productType: 'CNC' | 'INTRADAY' | 'MARGIN';
+ limitPrice?: number;
+ stopLoss?: number;
+ stopPrice?: number;
+ takeProfit?: number;
+}
+
+const FyersTradingPanel: React.FC = () => {
+ const [activeSection, setActiveSection] = useState<'order' | 'gtt' | 'margin'>('order');
+
+ // Order state
+ const [orderSymbol, setOrderSymbol] = useState('');
+ const [orderQty, setOrderQty] = useState<number>(1);
+ const [orderSide, setOrderSide] = useState<'BUY' | 'SELL'>('BUY');
+ const [orderType, setOrderType] = useState<'MARKET' | 'LIMIT' | 'STOP'>('MARKET');
+ const [orderProduct, setOrderProduct] = useState<'CNC' | 'INTRADAY' | 'MARGIN'>('INTRADAY');
+ const [orderLimitPrice, setOrderLimitPrice] = useState<number>(0);
+ const [orderStopPrice, setOrderStopPrice] = useState<number>(0);
+
+ // GTT state
+ const [gttSymbol, setGttSymbol] = useState('');
+ const [gttQty, setGttQty] = useState<number>(1);
+ const [gttSide, setGttSide] = useState<'BUY' | 'SELL'>('BUY');
+ const [gttProduct, setGttProduct] = useState<'CNC' | 'INTRADAY' | 'MARGIN'>('INTRADAY');
+ const [gttTriggerPrice, setGttTriggerPrice] = useState<number>(0);
+ const [gttLimitPrice, setGttLimitPrice] = useState<number>(0);
+
+ // Margin calculator state
+ const [marginOrders, setMarginOrders] = useState<Order[]>([]);
+ const [marginResult, setMarginResult] = useState<any>(null);
+ const [marginLoading, setMarginLoading] = useState(false);
+
+ // New order for margin calculator
+ const [newMarginOrder, setNewMarginOrder] = useState<Order>({
+ symbol: '',
+ qty: 1,
+ side: 'BUY',
+ type: 'LIMIT',
+ productType: 'INTRADAY',
+ limitPrice: 0
+ });
+
+ const handlePlaceOrder = async () => {
+ if (!orderSymbol.trim()) {
+ alert('Please enter a symbol');
+ return;
+ }
+
+ try {
+ const orderPayload: any = {
+ symbol: orderSymbol.toUpperCase(),
+ qty: orderQty,
+ type: orderType === 'MARKET' ? 2 : orderType === 'LIMIT' ? 1 : 3,
+ side: orderSide === 'BUY' ? 1 : -1,
+ productType: orderProduct,
+ validity: 'DAY',
+ disclosedQty: 0,
+ offlineOrder: false
+ };
+
+ if (orderType === 'LIMIT') {
+ orderPayload.limitPrice = orderLimitPrice;
+ }
+
+ if (orderType === 'STOP') {
+ orderPayload.stopPrice = orderStopPrice;
+ orderPayload.limitPrice = orderLimitPrice;
+ }
+
+ const response = await fyersService.placeOrder(orderPayload);
+
+ if (response.s === 'ok') {
+ alert(`Order placed successfully! Order ID: ${response.id || 'N/A'}`);
+ // Reset form
+ setOrderSymbol('');
+ setOrderQty(1);
+ setOrderLimitPrice(0);
+ setOrderStopPrice(0);
+ } else {
+ alert(`Order failed: ${response.message || 'Unknown error'}`);
+ }
+ } catch (error: any) {
+ console.error('Order placement error:', error);
+ alert(`Order failed: ${error.message || 'Unknown error'}`);
+ }
+ };
+
+ const handlePlaceGTT = async () => {
+ if (!gttSymbol.trim()) {
+ alert('Please enter a symbol');
+ return;
+ }
+
+ try {
+ const gttPayload = {
+ side: gttSide === 'BUY' ? 1 : -1,
+ symbol: gttSymbol.toUpperCase(),
+ productType: gttProduct,
+ orderInfo: {
+ leg1: {
+ price: gttLimitPrice,
+ triggerPrice: gttTriggerPrice,
+ qty: gttQty
+ }
+ }
+ };
+
+ const response = await fyersService.placeGTTOrder(gttPayload);
+
+ if (response.s === 'ok') {
+ alert(`GTT Order placed successfully! Order ID: ${response.id || 'N/A'}`);
+ // Reset form
+ setGttSymbol('');
+ setGttQty(1);
+ setGttTriggerPrice(0);
+ setGttLimitPrice(0);
+ } else {
+ alert(`GTT Order failed: ${response.message || 'Unknown error'}`);
+ }
+ } catch (error: any) {
+ console.error('GTT Order placement error:', error);
+ alert(`GTT Order failed: ${error.message || 'Unknown error'}`);
+ }
+ };
+
+ const addMarginOrder = () => {
+ if (!newMarginOrder.symbol.trim()) {
+ alert('Please enter a symbol');
+ return;
+ }
+
+ setMarginOrders([...marginOrders, { ...newMarginOrder, symbol: newMarginOrder.symbol.toUpperCase() }]);
+
+ // Reset new order form
+ setNewMarginOrder({
+ symbol: '',
+ qty: 1,
+ side: 'BUY',
+ type: 'LIMIT',
+ productType: 'INTRADAY',
+ limitPrice: 0
+ });
+ };
+
+ const removeMarginOrder = (index: number) => {
+ setMarginOrders(marginOrders.filter((_, i) => i !== index));
+ };
+
+ const calculateMargin = async () => {
+ if (marginOrders.length === 0) {
+ alert('Please add at least one order to calculate margin');
+ return;
+ }
+
+ setMarginLoading(true);
+ try {
+ const response = await fyersService.calculateMultiOrderMargin(marginOrders);
+ setMarginResult(response);
+ } catch (error: any) {
+ console.error('Margin calculation error:', error);
+ alert(`Margin calculation failed: ${error.message || 'Unknown error'}`);
+ } finally {
+ setMarginLoading(false);
+ }
+ };
+
+ return (
+ <div style={{
+ padding: '12px',
+ fontFamily: 'Consolas, monospace',
+ fontSize: '11px',
+ color: BLOOMBERG_WHITE
+ }}>
+ {/* Section Tabs */}
+ <div style={{
+ display: 'flex',
+ gap: '2px',
+ marginBottom: '16px',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ {[
+ { id: 'order', label: 'PLACE ORDER', icon: TrendingUp },
+ { id: 'gtt', label: 'GTT ORDER', icon: Activity },
+ { id: 'margin', label: 'MARGIN CALCULATOR', icon: Calculator }
+ ].map(({ id, label, icon: Icon }) => (
+ <button
+ key={id}
+ onClick={() => setActiveSection(id as any)}
+ style={{
+ backgroundColor: activeSection === id ? BLOOMBERG_DARK_BG : 'transparent',
+ border: 'none',
+ borderBottom: activeSection === id ? `2px solid ${BLOOMBERG_ORANGE}` : '2px solid transparent',
+ color: activeSection === id ? BLOOMBERG_ORANGE : BLOOMBERG_GRAY,
+ padding: '8px 16px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: 'bold',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <Icon size={12} />
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {/* Place Order Section */}
+ {activeSection === 'order' && (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ padding: '16px',
+ border: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold', marginBottom: '16px', fontSize: '12px' }}>
+ PLACE ORDER
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ {/* Symbol */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ SYMBOL
+ </label>
+ <input
+ type="text"
+ value={orderSymbol}
+ onChange={(e) => setOrderSymbol(e.target.value)}
+ placeholder="e.g., NSE:SBIN-EQ"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {/* Quantity */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ QUANTITY
+ </label>
+ <input
+ type="number"
+ value={orderQty}
+ onChange={(e) => setOrderQty(Number(e.target.value))}
+ min="1"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {/* Side */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ SIDE
+ </label>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <button
+ onClick={() => setOrderSide('BUY')}
+ style={{
+ flex: 1,
+ backgroundColor: orderSide === 'BUY' ? BLOOMBERG_GREEN : BLOOMBERG_DARK_BG,
+ color: orderSide === 'BUY' ? 'black' : BLOOMBERG_GREEN,
+ border: `1px solid ${BLOOMBERG_GREEN}`,
+ padding: '6px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ BUY
+ </button>
+ <button
+ onClick={() => setOrderSide('SELL')}
+ style={{
+ flex: 1,
+ backgroundColor: orderSide === 'SELL' ? BLOOMBERG_RED : BLOOMBERG_DARK_BG,
+ color: orderSide === 'SELL' ? BLOOMBERG_WHITE : BLOOMBERG_RED,
+ border: `1px solid ${BLOOMBERG_RED}`,
+ padding: '6px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ SELL
+ </button>
+ </div>
+ </div>
+
+ {/* Type */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ ORDER TYPE
+ </label>
+ <select
+ value={orderType}
+ onChange={(e) => setOrderType(e.target.value as any)}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <option value="MARKET">MARKET</option>
+ <option value="LIMIT">LIMIT</option>
+ <option value="STOP">STOP</option>
+ </select>
+ </div>
+
+ {/* Product Type */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ PRODUCT TYPE
+ </label>
+ <select
+ value={orderProduct}
+ onChange={(e) => setOrderProduct(e.target.value as any)}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <option value="CNC">CNC</option>
+ <option value="INTRADAY">INTRADAY</option>
+ <option value="MARGIN">MARGIN</option>
+ </select>
+ </div>
+
+ {/* Limit Price (show if LIMIT or STOP) */}
+ {(orderType === 'LIMIT' || orderType === 'STOP') && (
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ LIMIT PRICE
+ </label>
+ <input
+ type="number"
+ value={orderLimitPrice}
+ onChange={(e) => setOrderLimitPrice(Number(e.target.value))}
+ step="0.05"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+ )}
+
+ {/* Stop Price (show if STOP) */}
+ {orderType === 'STOP' && (
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ STOP PRICE
+ </label>
+ <input
+ type="number"
+ value={orderStopPrice}
+ onChange={(e) => setOrderStopPrice(Number(e.target.value))}
+ step="0.05"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+ )}
+ </div>
+
+ <button
+ onClick={handlePlaceOrder}
+ style={{
+ marginTop: '16px',
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '10px 20px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ width: '100%',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ PLACE ORDER
+ </button>
+ </div>
+ )}
+
+ {/* GTT Order Section */}
+ {activeSection === 'gtt' && (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ padding: '16px',
+ border: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold', marginBottom: '16px', fontSize: '12px' }}>
+ GTT ORDER (GOOD TILL TRIGGERED)
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ {/* Symbol */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ SYMBOL
+ </label>
+ <input
+ type="text"
+ value={gttSymbol}
+ onChange={(e) => setGttSymbol(e.target.value)}
+ placeholder="e.g., NSE:SBIN-EQ"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {/* Quantity */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ QUANTITY
+ </label>
+ <input
+ type="number"
+ value={gttQty}
+ onChange={(e) => setGttQty(Number(e.target.value))}
+ min="1"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {/* Side */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ SIDE
+ </label>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <button
+ onClick={() => setGttSide('BUY')}
+ style={{
+ flex: 1,
+ backgroundColor: gttSide === 'BUY' ? BLOOMBERG_GREEN : BLOOMBERG_DARK_BG,
+ color: gttSide === 'BUY' ? 'black' : BLOOMBERG_GREEN,
+ border: `1px solid ${BLOOMBERG_GREEN}`,
+ padding: '6px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ BUY
+ </button>
+ <button
+ onClick={() => setGttSide('SELL')}
+ style={{
+ flex: 1,
+ backgroundColor: gttSide === 'SELL' ? BLOOMBERG_RED : BLOOMBERG_DARK_BG,
+ color: gttSide === 'SELL' ? BLOOMBERG_WHITE : BLOOMBERG_RED,
+ border: `1px solid ${BLOOMBERG_RED}`,
+ padding: '6px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ SELL
+ </button>
+ </div>
+ </div>
+
+ {/* Product Type */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ PRODUCT TYPE
+ </label>
+ <select
+ value={gttProduct}
+ onChange={(e) => setGttProduct(e.target.value as any)}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <option value="CNC">CNC</option>
+ <option value="INTRADAY">INTRADAY</option>
+ <option value="MARGIN">MARGIN</option>
+ </select>
+ </div>
+
+ {/* Trigger Price */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ TRIGGER PRICE
+ </label>
+ <input
+ type="number"
+ value={gttTriggerPrice}
+ onChange={(e) => setGttTriggerPrice(Number(e.target.value))}
+ step="0.05"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {/* Limit Price */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ LIMIT PRICE
+ </label>
+ <input
+ type="number"
+ value={gttLimitPrice}
+ onChange={(e) => setGttLimitPrice(Number(e.target.value))}
+ step="0.05"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+ </div>
+
+ <button
+ onClick={handlePlaceGTT}
+ style={{
+ marginTop: '16px',
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '10px 20px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ width: '100%',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ PLACE GTT ORDER
+ </button>
+ </div>
+ )}
+
+ {/* Margin Calculator Section */}
+ {activeSection === 'margin' && (
+ <div>
+ {/* Add Order Form */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ padding: '16px',
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ marginBottom: '12px'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold', marginBottom: '16px', fontSize: '12px' }}>
+ ADD ORDER TO CALCULATE MARGIN
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>
+ {/* Symbol */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ SYMBOL
+ </label>
+ <input
+ type="text"
+ value={newMarginOrder.symbol}
+ onChange={(e) => setNewMarginOrder({ ...newMarginOrder, symbol: e.target.value })}
+ placeholder="e.g., NSE:SBIN-EQ"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {/* Quantity */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ QTY
+ </label>
+ <input
+ type="number"
+ value={newMarginOrder.qty}
+ onChange={(e) => setNewMarginOrder({ ...newMarginOrder, qty: Number(e.target.value) })}
+ min="1"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {/* Side */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ SIDE
+ </label>
+ <select
+ value={newMarginOrder.side}
+ onChange={(e) => setNewMarginOrder({ ...newMarginOrder, side: e.target.value as any })}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <option value="BUY">BUY</option>
+ <option value="SELL">SELL</option>
+ </select>
+ </div>
+
+ {/* Type */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ TYPE
+ </label>
+ <select
+ value={newMarginOrder.type}
+ onChange={(e) => setNewMarginOrder({ ...newMarginOrder, type: e.target.value as any })}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <option value="MARKET">MARKET</option>
+ <option value="LIMIT">LIMIT</option>
+ <option value="STOP">STOP</option>
+ </select>
+ </div>
+
+ {/* Product Type */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ PRODUCT
+ </label>
+ <select
+ value={newMarginOrder.productType}
+ onChange={(e) => setNewMarginOrder({ ...newMarginOrder, productType: e.target.value as any })}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <option value="CNC">CNC</option>
+ <option value="INTRADAY">INTRADAY</option>
+ <option value="MARGIN">MARGIN</option>
+ </select>
+ </div>
+
+ {/* Limit Price */}
+ <div>
+ <label style={{ display: 'block', color: BLOOMBERG_GRAY, marginBottom: '4px', fontSize: '9px' }}>
+ LIMIT PRICE
+ </label>
+ <input
+ type="number"
+ value={newMarginOrder.limitPrice || 0}
+ onChange={(e) => setNewMarginOrder({ ...newMarginOrder, limitPrice: Number(e.target.value) })}
+ step="0.05"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+ </div>
+
+ <button
+ onClick={addMarginOrder}
+ style={{
+ marginTop: '12px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_ORANGE}`,
+ color: BLOOMBERG_ORANGE,
+ padding: '8px 16px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ + ADD ORDER
+ </button>
+ </div>
+
+ {/* Orders List */}
+ {marginOrders.length > 0 && (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ padding: '16px',
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ marginBottom: '12px'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold', marginBottom: '12px', fontSize: '12px' }}>
+ ORDERS ({marginOrders.length})
+ </div>
+
+ <div style={{ maxHeight: '200px', overflow: 'auto' }}>
+ {marginOrders.map((order, index) => (
+ <div
+ key={index}
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ padding: '8px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ marginBottom: '4px',
+ fontSize: '10px'
+ }}
+ >
+ <div style={{ flex: 1 }}>
+ <span style={{ color: BLOOMBERG_WHITE }}>{order.symbol}</span>
+ <span style={{ color: BLOOMBERG_GRAY, marginLeft: '8px' }}>
+ {order.side} {order.qty} @ {order.limitPrice || 'MKT'}
+ </span>
+ <span style={{ color: BLOOMBERG_GRAY, marginLeft: '8px' }}>
+ {order.productType}
+ </span>
+ </div>
+ <button
+ onClick={() => removeMarginOrder(index)}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${BLOOMBERG_RED}`,
+ color: BLOOMBERG_RED,
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer'
+ }}
+ >
+ REMOVE
+ </button>
+ </div>
+ ))}
+ </div>
+
+ <button
+ onClick={calculateMargin}
+ disabled={marginLoading}
+ style={{
+ marginTop: '12px',
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '10px 20px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: marginLoading ? 'not-allowed' : 'pointer',
+ width: '100%',
+ fontFamily: 'Consolas, monospace',
+ opacity: marginLoading ? 0.5 : 1
+ }}
+ >
+ {marginLoading ? 'CALCULATING...' : 'CALCULATE MARGIN'}
+ </button>
+ </div>
+ )}
+
+ {/* Margin Result */}
+ {marginResult && (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ padding: '16px',
+ border: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold', marginBottom: '12px', fontSize: '12px' }}>
+ MARGIN CALCULATION RESULT
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ <div>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px', marginBottom: '4px' }}>
+ AVAILABLE MARGIN
+ </div>
+ <div style={{ color: BLOOMBERG_GREEN, fontSize: '14px', fontWeight: 'bold' }}>
+ ₹{marginResult.margin_avail?.toFixed(2) || '0.00'}
+ </div>
+ </div>
+
+ <div>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px', marginBottom: '4px' }}>
+ REQUIRED MARGIN
+ </div>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '14px', fontWeight: 'bold' }}>
+ ₹{marginResult.total?.toFixed(2) || '0.00'}
+ </div>
+ </div>
+ </div>
+
+ {marginResult.data && marginResult.data.length > 0 && (
+ <div style={{ marginTop: '12px' }}>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px', marginBottom: '8px' }}>
+ ORDER-WISE BREAKDOWN
+ </div>
+ {marginResult.data.map((item: any, index: number) => (
+ <div
+ key={index}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ padding: '8px',
+ marginBottom: '4px',
+ fontSize: '10px'
+ }}
+ >
+ <div style={{ color: BLOOMBERG_WHITE }}>{item.symbol || marginOrders[index]?.symbol}</div>
+ <div style={{ color: BLOOMBERG_GRAY, marginTop: '4px' }}>
+ Margin: ₹{item.margin?.toFixed(2) || '0.00'}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default FyersTradingPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/fyers/index.tsx b/fincept-terminal-desktop/src/components/tabs/fyers/index.tsx
new file mode 100644
index 000000000..dc67e8cca
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/fyers/index.tsx
@@ -0,0 +1,346 @@
+// Fyers Broker Integration Tab
+// Complete trading dashboard for Fyers broker
+
+import React, { useState, useEffect } from 'react';
+import { RefreshCw, Power, TrendingUp, Wallet, Package, FileText, Activity } from 'lucide-react';
+import { fyersService } from '../../../services/fyersService';
+import { fyersWebSocket } from '../../../services/fyersWebSocket';
+import FyersAuthModal from './FyersAuthModal';
+import FyersProfilePanel from './FyersProfilePanel';
+import FyersFundsPanel from './FyersFundsPanel';
+import FyersHoldingsPanel from './FyersHoldingsPanel';
+import FyersPositionsPanel from './FyersPositionsPanel';
+import FyersOrdersPanel from './FyersOrdersPanel';
+import FyersMarketDataPanel from './FyersMarketDataPanel';
+import FyersTradingPanel from './FyersTradingPanel';
+
+const FyersTab: React.FC = () => {
+ const [isConnected, setIsConnected] = useState(false);
+ const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
+ const [isLoading, setIsLoading] = useState(true);
+ const [activePanel, setActivePanel] = useState<'overview' | 'holdings' | 'positions' | 'orders' | 'market' | 'trading'>('overview');
+ const [wsConnected, setWsConnected] = useState(false);
+
+ // Bloomberg colors
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_RED = '#FF0000';
+
+ useEffect(() => {
+ checkConnection();
+ }, []);
+
+ const checkConnection = async () => {
+ setIsLoading(true);
+ try {
+ // Ensure SQLite is initialized first
+ const { sqliteService } = await import('../../../services/sqliteService');
+ await sqliteService.initialize();
+
+ const initialized = await fyersService.initialize();
+ if (initialized) {
+ // Test connection with profile fetch
+ await fyersService.getProfile();
+ setIsConnected(true);
+
+ // Load symbol master in background
+ fyersService.loadSymbolMaster().catch(console.error);
+ } else {
+ setIsConnected(false);
+ }
+ } catch (error) {
+ console.error('[Fyers] Connection check failed:', error);
+ setIsConnected(false);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleConnect = async () => {
+ await checkConnection();
+ setIsAuthModalOpen(false);
+ };
+
+ const handleDisconnect = () => {
+ fyersWebSocket.disconnect();
+ setWsConnected(false);
+ setIsConnected(false);
+ };
+
+ const toggleWebSocket = async () => {
+ // Check if market is open
+ const marketOpen = fyersService.isMarketOpen();
+
+ if (wsConnected) {
+ fyersWebSocket.disconnect();
+ setWsConnected(false);
+ } else {
+ if (!marketOpen) {
+ console.warn('[Fyers] Cannot start WebSocket - market is closed');
+ alert('Market is currently closed. Live updates are not available.');
+ return;
+ }
+
+ try {
+ // Get credentials from service (already loaded)
+ const creds = await fyersService.initialize();
+ if (creds) {
+ // Access credentials from sqliteService
+ const { sqliteService } = await import('../../../services/sqliteService');
+ const savedCreds = await sqliteService.getCredentialByService('fyers');
+
+ if (savedCreds && savedCreds.api_key && savedCreds.password) {
+ fyersWebSocket.connect(savedCreds.api_key, savedCreds.password);
+ setWsConnected(true);
+ }
+ }
+ } catch (error) {
+ console.error('[Fyers] WebSocket connection failed:', error);
+ }
+ }
+ };
+
+ if (isLoading) {
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontFamily: 'Consolas, monospace',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: '11px'
+ }}>
+ <div style={{ textAlign: 'center' }}>
+ <div style={{ color: BLOOMBERG_ORANGE, marginBottom: '10px' }}>Loading Fyers...</div>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px' }}>Checking connection status</div>
+ </div>
+ </div>
+ );
+ }
+
+ if (!isConnected) {
+ return (
+ <>
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontFamily: 'Consolas, monospace',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexDirection: 'column',
+ fontSize: '11px'
+ }}>
+ <div style={{
+ textAlign: 'center',
+ padding: '40px',
+ border: `2px solid ${BLOOMBERG_ORANGE}`,
+ backgroundColor: BLOOMBERG_PANEL_BG
+ }}>
+ <div style={{
+ color: BLOOMBERG_ORANGE,
+ fontSize: '14px',
+ fontWeight: 'bold',
+ marginBottom: '10px'
+ }}>
+ FYERS NOT CONNECTED
+ </div>
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '10px',
+ marginBottom: '20px',
+ lineHeight: '1.5'
+ }}>
+ Connect your Fyers broker account to access<br />
+ trading, portfolio, and market data features.
+ </div>
+ <button
+ onClick={() => setIsAuthModalOpen(true)}
+ style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '10px 20px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ CONNECT FYERS
+ </button>
+ </div>
+ </div>
+
+ {isAuthModalOpen && (
+ <FyersAuthModal
+ onClose={() => setIsAuthModalOpen(false)}
+ onSuccess={handleConnect}
+ />
+ )}
+ </>
+ );
+ }
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontFamily: 'Consolas, monospace',
+ display: 'flex',
+ flexDirection: 'column',
+ fontSize: '11px'
+ }}>
+ {/* Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '8px 12px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold', fontSize: '12px' }}>
+ FYERS BROKER
+ </span>
+ <span style={{ color: BLOOMBERG_GRAY }}>|</span>
+ <span style={{
+ color: wsConnected ? BLOOMBERG_GREEN : BLOOMBERG_GRAY,
+ fontSize: '9px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <Activity size={10} />
+ {wsConnected ? 'LIVE' : 'OFFLINE'}
+ </span>
+ </div>
+
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={toggleWebSocket}
+ style={{
+ backgroundColor: wsConnected ? BLOOMBERG_RED : BLOOMBERG_GREEN,
+ color: wsConnected ? BLOOMBERG_WHITE : 'black',
+ border: 'none',
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: 'bold',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Activity size={10} />
+ {wsConnected ? 'STOP LIVE' : 'START LIVE'}
+ </button>
+
+ <button
+ onClick={() => window.location.reload()}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <RefreshCw size={10} />
+ REFRESH
+ </button>
+
+ <button
+ onClick={handleDisconnect}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_RED}`,
+ color: BLOOMBERG_RED,
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Power size={10} />
+ DISCONNECT
+ </button>
+ </div>
+ </div>
+
+ {/* Navigation Tabs */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '0 12px',
+ display: 'flex',
+ gap: '2px',
+ flexShrink: 0
+ }}>
+ {[
+ { id: 'overview', label: 'OVERVIEW', icon: TrendingUp },
+ { id: 'holdings', label: 'HOLDINGS', icon: Package },
+ { id: 'positions', label: 'POSITIONS', icon: Activity },
+ { id: 'orders', label: 'ORDERS', icon: FileText },
+ { id: 'market', label: 'MARKET', icon: Wallet },
+ { id: 'trading', label: 'TRADING', icon: TrendingUp }
+ ].map(({ id, label, icon: Icon }) => (
+ <button
+ key={id}
+ onClick={() => setActivePanel(id as any)}
+ style={{
+ backgroundColor: activePanel === id ? BLOOMBERG_DARK_BG : 'transparent',
+ border: 'none',
+ borderBottom: activePanel === id ? `2px solid ${BLOOMBERG_ORANGE}` : '2px solid transparent',
+ color: activePanel === id ? BLOOMBERG_ORANGE : BLOOMBERG_GRAY,
+ padding: '8px 12px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: 'bold',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Icon size={10} />
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {/* Content Area */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {activePanel === 'overview' && (
+ <div style={{ padding: '12px' }}>
+ <FyersProfilePanel />
+ <FyersFundsPanel />
+ </div>
+ )}
+
+ {activePanel === 'holdings' && <FyersHoldingsPanel />}
+ {activePanel === 'positions' && <FyersPositionsPanel wsConnected={wsConnected} />}
+ {activePanel === 'orders' && <FyersOrdersPanel wsConnected={wsConnected} />}
+ {activePanel === 'market' && <FyersMarketDataPanel />}
+ {activePanel === 'trading' && <FyersTradingPanel />}
+ </div>
+ </div>
+ );
+};
+
+export default FyersTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/MCPAddServerModal.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/MCPAddServerModal.tsx
new file mode 100644
index 000000000..c05272f5a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/MCPAddServerModal.tsx
@@ -0,0 +1,356 @@
+// MCP Add Server Modal Component
+// Add custom MCP servers manually
+
+import React, { useState } from 'react';
+import { X } from 'lucide-react';
+
+interface MCPAddServerModalProps {
+ onClose: () => void;
+ onAdd: (serverConfig: any) => void;
+}
+
+const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd }) => {
+ const [formData, setFormData] = useState({
+ name: '',
+ description: '',
+ command: 'npx',
+ args: '',
+ envVars: '',
+ category: 'custom',
+ icon: '🔧'
+ });
+
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_RED = '#FF0000';
+
+ const handleSubmit = (e: React.FormEvent) => {
+ e.preventDefault();
+
+ if (!formData.name || !formData.command || !formData.args) {
+ alert('Please fill in all required fields');
+ return;
+ }
+
+ // Parse args (space or comma separated)
+ const args = formData.args
+ .trim()
+ .split(/[\s,]+/)
+ .filter(arg => arg.length > 0);
+
+ // Parse env vars (KEY=VALUE format, one per line)
+ const env: Record<string, string> = {};
+ if (formData.envVars.trim()) {
+ formData.envVars.split('\n').forEach(line => {
+ const [key, ...valueParts] = line.trim().split('=');
+ if (key && valueParts.length > 0) {
+ env[key.trim()] = valueParts.join('=').trim();
+ }
+ });
+ }
+
+ // Generate ID from name
+ const id = formData.name.toLowerCase().replace(/[^a-z0-9]/g, '-');
+
+ const serverConfig = {
+ id,
+ name: formData.name,
+ description: formData.description || `Custom MCP server: ${formData.name}`,
+ command: formData.command,
+ args,
+ env,
+ category: formData.category,
+ icon: formData.icon
+ };
+
+ onAdd(serverConfig);
+ };
+
+ return (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0, 0, 0, 0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000,
+ fontFamily: 'Consolas, monospace'
+ }}>
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `2px solid ${BLOOMBERG_ORANGE}`,
+ width: '500px',
+ maxHeight: '80vh',
+ overflow: 'auto'
+ }}>
+ {/* Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ borderBottom: `1px solid ${BLOOMBERG_ORANGE}`,
+ padding: '10px 12px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <span style={{
+ color: BLOOMBERG_ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold'
+ }}>
+ ADD CUSTOM MCP SERVER
+ </span>
+ <button
+ onClick={onClose}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: BLOOMBERG_WHITE,
+ cursor: 'pointer',
+ padding: '4px'
+ }}
+ >
+ <X size={16} />
+ </button>
+ </div>
+
+ {/* Form */}
+ <form onSubmit={handleSubmit} style={{ padding: '12px' }}>
+ {/* Server Name */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_ORANGE,
+ fontSize: '10px',
+ marginBottom: '4px',
+ fontWeight: 'bold'
+ }}>
+ SERVER NAME *
+ </label>
+ <input
+ type="text"
+ value={formData.name}
+ onChange={(e) => setFormData({ ...formData, name: e.target.value })}
+ placeholder="e.g., My Custom Server"
+ required
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '10px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {/* Description */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_ORANGE,
+ fontSize: '10px',
+ marginBottom: '4px',
+ fontWeight: 'bold'
+ }}>
+ DESCRIPTION
+ </label>
+ <input
+ type="text"
+ value={formData.description}
+ onChange={(e) => setFormData({ ...formData, description: e.target.value })}
+ placeholder="What does this server do?"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '10px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {/* Command */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_ORANGE,
+ fontSize: '10px',
+ marginBottom: '4px',
+ fontWeight: 'bold'
+ }}>
+ COMMAND *
+ </label>
+ <input
+ type="text"
+ value={formData.command}
+ onChange={(e) => setFormData({ ...formData, command: e.target.value })}
+ placeholder="npx, node, python, etc."
+ required
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '10px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {/* Arguments */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_ORANGE,
+ fontSize: '10px',
+ marginBottom: '4px',
+ fontWeight: 'bold'
+ }}>
+ ARGUMENTS * (space or comma separated)
+ </label>
+ <input
+ type="text"
+ value={formData.args}
+ onChange={(e) => setFormData({ ...formData, args: e.target.value })}
+ placeholder="e.g., -y @modelcontextprotocol/server-example"
+ required
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '10px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '8px',
+ marginTop: '2px'
+ }}>
+ Example: -y @modelcontextprotocol/server-postgres
+ </div>
+ </div>
+
+ {/* Environment Variables */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_ORANGE,
+ fontSize: '10px',
+ marginBottom: '4px',
+ fontWeight: 'bold'
+ }}>
+ ENVIRONMENT VARIABLES (one per line)
+ </label>
+ <textarea
+ value={formData.envVars}
+ onChange={(e) => setFormData({ ...formData, envVars: e.target.value })}
+ placeholder={'DATABASE_URL=postgresql://...\nAPI_KEY=your-key-here'}
+ rows={3}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '10px',
+ fontFamily: 'Consolas, monospace',
+ resize: 'vertical'
+ }}
+ />
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '8px',
+ marginTop: '2px'
+ }}>
+ Format: KEY=VALUE (one per line)
+ </div>
+ </div>
+
+ {/* Icon */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: BLOOMBERG_ORANGE,
+ fontSize: '10px',
+ marginBottom: '4px',
+ fontWeight: 'bold'
+ }}>
+ ICON (emoji)
+ </label>
+ <input
+ type="text"
+ value={formData.icon}
+ onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
+ placeholder="🔧"
+ maxLength={2}
+ style={{
+ width: '60px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px',
+ fontSize: '16px',
+ textAlign: 'center'
+ }}
+ />
+ </div>
+
+ {/* Actions */}
+ <div style={{
+ display: 'flex',
+ gap: '8px',
+ justifyContent: 'flex-end',
+ marginTop: '16px',
+ paddingTop: '12px',
+ borderTop: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <button
+ type="button"
+ onClick={onClose}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '6px 12px',
+ fontSize: '10px',
+ cursor: 'pointer'
+ }}
+ >
+ CANCEL
+ </button>
+ <button
+ type="submit"
+ style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ border: 'none',
+ color: 'black',
+ padding: '6px 12px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ ADD SERVER
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+};
+
+export default MCPAddServerModal;
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/MCPMarketplace.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/MCPMarketplace.tsx
new file mode 100644
index 000000000..83d8a7019
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/MCPMarketplace.tsx
@@ -0,0 +1,303 @@
+// MCP Marketplace Component
+// Browse and install curated MCP servers
+
+import React, { useState } from 'react';
+import { Search, Download } from 'lucide-react';
+
+interface MCPMarketplaceProps {
+ onInstall: (serverConfig: any) => void;
+}
+
+// Curated MCP servers from the ecosystem
+const MARKETPLACE_SERVERS = [
+ {
+ id: 'postgres',
+ name: 'PostgreSQL',
+ description: 'Connect to PostgreSQL databases for queries and analysis',
+ category: 'data',
+ icon: '📊',
+ command: 'npx',
+ args: ['-y', '@modelcontextprotocol/server-postgres'],
+ env: { DATABASE_URL: '' },
+ tools: ['query', 'describe_table', 'list_tables', 'explain_query', 'get_indexes']
+ },
+ {
+ id: 'fetch',
+ name: 'Web Fetch',
+ description: 'Fetch and extract content from any URL',
+ category: 'web',
+ icon: '🌐',
+ command: 'npx',
+ args: ['-y', '@modelcontextprotocol/server-fetch'],
+ env: {},
+ tools: ['fetch']
+ },
+ {
+ id: 'brave-search',
+ name: 'Brave Search',
+ description: 'Web search using Brave Search API',
+ category: 'web',
+ icon: '🔍',
+ command: 'npx',
+ args: ['-y', '@modelcontextprotocol/server-brave-search'],
+ env: { BRAVE_API_KEY: '' },
+ tools: ['brave_web_search', 'brave_local_search']
+ },
+ {
+ id: 'filesystem',
+ name: 'FileSystem',
+ description: 'Read and write files on your system',
+ category: 'productivity',
+ icon: '📁',
+ command: 'npx',
+ args: ['-y', '@modelcontextprotocol/server-filesystem'],
+ env: { ALLOWED_DIRECTORIES: '' },
+ tools: ['read_file', 'write_file', 'list_directory', 'search_files']
+ },
+ {
+ id: 'sqlite',
+ name: 'SQLite',
+ description: 'Query and manage SQLite databases',
+ category: 'data',
+ icon: '💾',
+ command: 'npx',
+ args: ['-y', '@modelcontextprotocol/server-sqlite'],
+ env: { SQLITE_DB_PATH: '' },
+ tools: ['query', 'list_tables', 'describe_table']
+ },
+ {
+ id: 'github',
+ name: 'GitHub',
+ description: 'Interact with GitHub repositories and issues',
+ category: 'dev',
+ icon: '🐙',
+ command: 'npx',
+ args: ['-y', '@modelcontextprotocol/server-github'],
+ env: { GITHUB_TOKEN: '' },
+ tools: ['create_issue', 'create_pr', 'search_repos', 'get_file_contents']
+ },
+ {
+ id: 'puppeteer',
+ name: 'Puppeteer',
+ description: 'Browser automation for web scraping',
+ category: 'web',
+ icon: '🎭',
+ command: 'npx',
+ args: ['-y', '@modelcontextprotocol/server-puppeteer'],
+ env: {},
+ tools: ['puppeteer_navigate', 'puppeteer_screenshot', 'puppeteer_click', 'puppeteer_fill']
+ },
+ {
+ id: 'slack',
+ name: 'Slack',
+ description: 'Send messages and interact with Slack',
+ category: 'productivity',
+ icon: '💬',
+ command: 'npx',
+ args: ['-y', '@modelcontextprotocol/server-slack'],
+ env: { SLACK_BOT_TOKEN: '' },
+ tools: ['post_message', 'list_channels', 'get_channel_history']
+ }
+];
+
+const MCPMarketplace: React.FC<MCPMarketplaceProps> = ({ onInstall }) => {
+ const [searchQuery, setSearchQuery] = useState('');
+ const [selectedCategory, setSelectedCategory] = useState<string>('all');
+
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_YELLOW = '#FFFF00';
+
+ const filteredServers = MARKETPLACE_SERVERS.filter(server => {
+ const matchesSearch = server.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ server.description.toLowerCase().includes(searchQuery.toLowerCase());
+ const matchesCategory = selectedCategory === 'all' || server.category === selectedCategory;
+ return matchesSearch && matchesCategory;
+ });
+
+ const categories = ['all', 'data', 'web', 'productivity', 'dev'];
+ const categoryLabels = {
+ all: 'ALL',
+ data: 'DATA',
+ web: 'WEB',
+ productivity: 'TOOLS',
+ dev: 'DEV'
+ };
+
+ const hasRequiredEnv = (server: typeof MARKETPLACE_SERVERS[0]) => {
+ return Object.keys(server.env).length > 0;
+ };
+
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
+ {/* Header */}
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ flexShrink: 0
+ }}>
+ <span style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
+ MARKETPLACE
+ </span>
+ </div>
+
+ {/* Search and Filters */}
+ <div style={{ padding: '8px', flexShrink: 0 }}>
+ <div style={{ position: 'relative', marginBottom: '8px' }}>
+ <Search
+ size={12}
+ color={BLOOMBERG_GRAY}
+ style={{ position: 'absolute', left: '6px', top: '6px' }}
+ />
+ <input
+ type="text"
+ placeholder="Search servers..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 4px 4px 24px',
+ fontSize: '10px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ {/* Categories */}
+ <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
+ {categories.map(cat => (
+ <button
+ key={cat}
+ onClick={() => setSelectedCategory(cat)}
+ style={{
+ backgroundColor: selectedCategory === cat ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,
+ color: selectedCategory === cat ? 'black' : BLOOMBERG_WHITE,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '3px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: selectedCategory === cat ? 'bold' : 'normal'
+ }}
+ >
+ {categoryLabels[cat as keyof typeof categoryLabels]}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Server List */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ {filteredServers.length === 0 ? (
+ <div style={{
+ textAlign: 'center',
+ color: BLOOMBERG_GRAY,
+ padding: '40px 20px',
+ fontSize: '10px'
+ }}>
+ No servers found matching your search.
+ </div>
+ ) : (
+ filteredServers.map(server => (
+ <div
+ key={server.id}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '8px',
+ marginBottom: '6px'
+ }}
+ >
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'flex-start',
+ marginBottom: '4px'
+ }}>
+ <div style={{ flex: 1 }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '3px'
+ }}>
+ <span style={{ fontSize: '14px' }}>{server.icon}</span>
+ <span style={{
+ color: BLOOMBERG_WHITE,
+ fontSize: '11px',
+ fontWeight: 'bold'
+ }}>
+ {server.name}
+ </span>
+ <span style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '8px',
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ padding: '2px 4px'
+ }}>
+ {server.tools.length} tools
+ </span>
+ </div>
+
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '9px',
+ marginBottom: '4px'
+ }}>
+ {server.description}
+ </div>
+
+ {hasRequiredEnv(server) && (
+ <div style={{
+ color: BLOOMBERG_YELLOW,
+ fontSize: '8px',
+ marginBottom: '4px'
+ }}>
+ ⚠️ Requires: {Object.keys(server.env).join(', ')}
+ </div>
+ )}
+
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '8px',
+ fontFamily: 'Consolas, monospace'
+ }}>
+ {server.command} {server.args.join(' ')}
+ </div>
+ </div>
+ </div>
+
+ <button
+ onClick={() => onInstall(server)}
+ style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '4px 10px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ marginTop: '6px'
+ }}
+ >
+ <Download size={10} />
+ INSTALL
+ </button>
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default MCPMarketplace;
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/MCPServerCard.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/MCPServerCard.tsx
new file mode 100644
index 000000000..c3a03d7ef
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/MCPServerCard.tsx
@@ -0,0 +1,240 @@
+// MCP Server Card Component
+// Individual server display with controls
+
+import React from 'react';
+import { Play, Square, Trash2 } from 'lucide-react';
+import { MCPServerWithStats } from '../../../services/mcpManager';
+
+interface MCPServerCardProps {
+ server: MCPServerWithStats;
+ onStart: () => void;
+ onStop: () => void;
+ onRemove: () => void;
+ onToggleAutoStart: (enabled: boolean) => void;
+ healthInfo?: { errorCount: number; lastError?: string; lastErrorTime?: number } | null;
+}
+
+const MCPServerCard: React.FC<MCPServerCardProps> = ({
+ server,
+ onStart,
+ onStop,
+ onRemove,
+ onToggleAutoStart,
+ healthInfo
+}) => {
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_RED = '#FF0000';
+ const BLOOMBERG_YELLOW = '#FFFF00';
+
+ const statusColor = {
+ running: BLOOMBERG_GREEN,
+ stopped: BLOOMBERG_GRAY,
+ error: BLOOMBERG_RED
+ }[server.status] || BLOOMBERG_GRAY;
+
+ const statusIcon = {
+ running: '🟢',
+ stopped: '🔴',
+ error: '❌'
+ }[server.status] || '⚪';
+
+ const statusText = {
+ running: `Running | ${server.callsToday} calls today`,
+ stopped: 'Stopped',
+ error: 'Connection error'
+ }[server.status] || 'Unknown';
+
+ return (
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${statusColor}`,
+ padding: '8px',
+ marginBottom: '6px',
+ borderRadius: '2px'
+ }}>
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'flex-start',
+ marginBottom: '6px'
+ }}>
+ <div style={{ flex: 1 }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '3px' }}>
+ <span style={{ fontSize: '14px' }}>{server.icon || '🔧'}</span>
+ <span style={{ fontSize: '12px' }}>{statusIcon}</span>
+ <span style={{ color: BLOOMBERG_WHITE, fontSize: '11px', fontWeight: 'bold' }}>
+ {server.name}
+ </span>
+ <span style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '8px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '2px 4px'
+ }}>
+ {server.toolCount} tools
+ </span>
+ </div>
+
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px', marginBottom: '4px' }}>
+ {server.description}
+ </div>
+
+ <div style={{
+ color: server.status === 'running' ? BLOOMBERG_GREEN : BLOOMBERG_GRAY,
+ fontSize: '9px'
+ }}>
+ {statusText}
+ </div>
+
+ {/* Health Status */}
+ {healthInfo && healthInfo.errorCount > 0 && (
+ <div style={{
+ marginTop: '4px',
+ padding: '4px 6px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_RED}`,
+ borderRadius: '2px'
+ }}>
+ <div style={{
+ color: BLOOMBERG_RED,
+ fontSize: '8px',
+ fontWeight: 'bold',
+ marginBottom: '2px'
+ }}>
+ ⚠ HEALTH WARNING: {healthInfo.errorCount} errors
+ </div>
+ {healthInfo.lastError && (
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '8px',
+ fontFamily: 'Consolas, monospace'
+ }}>
+ Last: {healthInfo.lastError}
+ </div>
+ )}
+ {healthInfo.lastErrorTime && (
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ fontSize: '7px',
+ marginTop: '2px'
+ }}>
+ {new Date(healthInfo.lastErrorTime).toLocaleString()}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Command Info */}
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px 6px',
+ marginBottom: '6px',
+ fontSize: '8px',
+ color: BLOOMBERG_GRAY,
+ fontFamily: 'Consolas, monospace',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap'
+ }}>
+ {server.command} {Array.isArray(server.args) ? server.args.join(' ') : JSON.parse(server.args).join(' ')}
+ </div>
+
+ {/* Auto-start Toggle */}
+ <div style={{
+ marginBottom: '6px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px'
+ }}>
+ <label style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ color: BLOOMBERG_WHITE,
+ fontSize: '9px',
+ cursor: 'pointer'
+ }}>
+ <input
+ type="checkbox"
+ checked={server.auto_start}
+ onChange={(e) => onToggleAutoStart(e.target.checked)}
+ style={{ cursor: 'pointer' }}
+ />
+ Auto-start on launch
+ </label>
+ </div>
+
+ {/* Actions */}
+ <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
+ {server.status === 'running' ? (
+ <button
+ onClick={onStop}
+ style={{
+ backgroundColor: BLOOMBERG_RED,
+ color: BLOOMBERG_WHITE,
+ border: 'none',
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '3px',
+ fontWeight: 'bold'
+ }}
+ >
+ <Square size={10} fill="white" />
+ STOP
+ </button>
+ ) : (
+ <button
+ onClick={onStart}
+ style={{
+ backgroundColor: BLOOMBERG_GREEN,
+ color: 'black',
+ border: 'none',
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '3px',
+ fontWeight: 'bold'
+ }}
+ >
+ <Play size={10} fill="black" />
+ START
+ </button>
+ )}
+
+ <button
+ onClick={onRemove}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_RED,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '3px'
+ }}
+ >
+ <Trash2 size={10} />
+ REMOVE
+ </button>
+ </div>
+ </div>
+ );
+};
+
+export default MCPServerCard;
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/MCPServerLogsModal.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/MCPServerLogsModal.tsx
new file mode 100644
index 000000000..565a8b4da
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/MCPServerLogsModal.tsx
@@ -0,0 +1,282 @@
+// MCP Server Logs Viewer Component
+// Shows stdout/stderr logs from MCP servers
+
+import React, { useState, useEffect } from 'react';
+import { X, Download, Trash2 } from 'lucide-react';
+import { invoke } from '@tauri-apps/api/core';
+
+interface MCPServerLogsModalProps {
+ serverId: string;
+ serverName: string;
+ onClose: () => void;
+}
+
+interface LogEntry {
+ timestamp: string;
+ type: 'stdout' | 'stderr' | 'system';
+ message: string;
+}
+
+const MCPServerLogsModal: React.FC<MCPServerLogsModalProps> = ({
+ serverId,
+ serverName,
+ onClose
+}) => {
+ const [logs, setLogs] = useState<LogEntry[]>([]);
+ const [autoScroll, setAutoScroll] = useState(true);
+ const logsEndRef = React.useRef<HTMLDivElement>(null);
+
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_RED = '#FF0000';
+ const BLOOMBERG_YELLOW = '#FFFF00';
+
+ useEffect(() => {
+ loadLogs();
+
+ // Refresh logs every second
+ const interval = setInterval(() => {
+ loadLogs();
+ }, 1000);
+
+ return () => clearInterval(interval);
+ }, [serverId]);
+
+ useEffect(() => {
+ if (autoScroll) {
+ logsEndRef.current?.scrollIntoView({ behavior: 'smooth' });
+ }
+ }, [logs, autoScroll]);
+
+ const loadLogs = async () => {
+ try {
+ // Get logs from Tauri (this would need to be implemented in Rust)
+ // For now, we'll use mock data
+ // In production, you'd call: invoke('get_mcp_server_logs', { serverId })
+
+ // Mock implementation
+ const mockLogs: LogEntry[] = [
+ {
+ timestamp: new Date().toISOString(),
+ type: 'system',
+ message: `Server ${serverId} initialized`
+ },
+ {
+ timestamp: new Date().toISOString(),
+ type: 'stdout',
+ message: 'MCP server listening on stdio'
+ }
+ ];
+
+ setLogs(mockLogs);
+ } catch (error) {
+ console.error('Failed to load logs:', error);
+ }
+ };
+
+ const clearLogs = () => {
+ setLogs([]);
+ };
+
+ const downloadLogs = () => {
+ const logText = logs
+ .map(log => `[${log.timestamp}] [${log.type}] ${log.message}`)
+ .join('\n');
+
+ const blob = new Blob([logText], { type: 'text/plain' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `${serverId}-logs-${Date.now()}.txt`;
+ a.click();
+ URL.revokeObjectURL(url);
+ };
+
+ const getLogColor = (type: LogEntry['type']) => {
+ switch (type) {
+ case 'stdout':
+ return BLOOMBERG_WHITE;
+ case 'stderr':
+ return BLOOMBERG_RED;
+ case 'system':
+ return BLOOMBERG_YELLOW;
+ default:
+ return BLOOMBERG_GRAY;
+ }
+ };
+
+ return (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0, 0, 0, 0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000,
+ fontFamily: 'Consolas, monospace'
+ }}>
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `2px solid ${BLOOMBERG_ORANGE}`,
+ width: '80%',
+ height: '80%',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ borderBottom: `1px solid ${BLOOMBERG_ORANGE}`,
+ padding: '10px 12px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexShrink: 0
+ }}>
+ <span style={{
+ color: BLOOMBERG_ORANGE,
+ fontSize: '12px',
+ fontWeight: 'bold'
+ }}>
+ SERVER LOGS: {serverName}
+ </span>
+
+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
+ <label style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ color: BLOOMBERG_WHITE,
+ fontSize: '10px'
+ }}>
+ <input
+ type="checkbox"
+ checked={autoScroll}
+ onChange={(e) => setAutoScroll(e.target.checked)}
+ />
+ Auto-scroll
+ </label>
+
+ <button
+ onClick={clearLogs}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Trash2 size={12} />
+ Clear
+ </button>
+
+ <button
+ onClick={downloadLogs}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Download size={12} />
+ Download
+ </button>
+
+ <button
+ onClick={onClose}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: BLOOMBERG_WHITE,
+ cursor: 'pointer',
+ padding: '4px'
+ }}
+ >
+ <X size={16} />
+ </button>
+ </div>
+ </div>
+
+ {/* Logs Content */}
+ <div style={{
+ flex: 1,
+ backgroundColor: BLOOMBERG_DARK_BG,
+ padding: '10px',
+ overflow: 'auto',
+ fontFamily: 'Consolas, monospace',
+ fontSize: '10px'
+ }}>
+ {logs.length === 0 ? (
+ <div style={{
+ color: BLOOMBERG_GRAY,
+ textAlign: 'center',
+ padding: '40px'
+ }}>
+ No logs available. Server may not be running.
+ </div>
+ ) : (
+ logs.map((log, index) => (
+ <div
+ key={index}
+ style={{
+ marginBottom: '4px',
+ display: 'flex',
+ gap: '8px',
+ color: getLogColor(log.type)
+ }}
+ >
+ <span style={{ color: BLOOMBERG_GRAY, minWidth: '180px' }}>
+ [{new Date(log.timestamp).toLocaleTimeString()}]
+ </span>
+ <span style={{
+ color: BLOOMBERG_YELLOW,
+ minWidth: '60px',
+ fontWeight: 'bold'
+ }}>
+ [{log.type.toUpperCase()}]
+ </span>
+ <span style={{ flex: 1, whiteSpace: 'pre-wrap' }}>
+ {log.message}
+ </span>
+ </div>
+ ))
+ )}
+ <div ref={logsEndRef} />
+ </div>
+
+ {/* Footer */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderTop: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '6px 12px',
+ fontSize: '9px',
+ color: BLOOMBERG_GRAY,
+ flexShrink: 0
+ }}>
+ {logs.length} log entries | Server ID: {serverId}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default MCPServerLogsModal;
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx
new file mode 100644
index 000000000..308fffd80
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx
@@ -0,0 +1,345 @@
+// MCP Integrations Tab - Main Component
+// Manage MCP servers and tools in Bloomberg-style interface
+
+import React, { useState, useEffect } from 'react';
+import { Plus, RefreshCw } from 'lucide-react';
+import { mcpManager, MCPServerWithStats } from '../../../services/mcpManager';
+import { sqliteService } from '../../../services/sqliteService';
+import MCPServerCard from './MCPServerCard';
+import MCPMarketplace from './MCPMarketplace';
+import MCPAddServerModal from './MCPAddServerModal';
+
+const MCPTab: React.FC = () => {
+ const [servers, setServers] = useState<MCPServerWithStats[]>([]);
+ const [tools, setTools] = useState<any[]>([]);
+ const [isAddModalOpen, setIsAddModalOpen] = useState(false);
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ const [statusMessage, setStatusMessage] = useState('Initializing...');
+
+ // Bloomberg colors
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+ const BLOOMBERG_GREEN = '#00C800';
+
+ useEffect(() => {
+ // Auto-start servers on mount
+ const initializeServers = async () => {
+ try {
+ await mcpManager.startAutoStartServers();
+ } catch (error) {
+ console.error('Failed to auto-start servers:', error);
+ }
+ loadData();
+ };
+
+ initializeServers();
+
+ // Auto-refresh every 5 seconds
+ const interval = setInterval(() => {
+ loadData(true);
+ }, 5000);
+
+ return () => clearInterval(interval);
+ }, []);
+
+ const loadData = async (silent = false) => {
+ try {
+ if (!silent) setStatusMessage('Loading servers...');
+
+ const serversData = await mcpManager.getServersWithStats();
+ setServers(serversData);
+
+ const toolsData = await sqliteService.getMCPTools();
+ setTools(toolsData);
+
+ const runningCount = serversData.filter(s => s.status === 'running').length;
+ setStatusMessage(`${runningCount} servers connected | ${toolsData.length} tools available`);
+ } catch (error) {
+ console.error('Failed to load MCP data:', error);
+ setStatusMessage('Error loading data');
+ }
+ };
+
+ const handleRefresh = async () => {
+ setIsRefreshing(true);
+ await loadData();
+ setTimeout(() => setIsRefreshing(false), 500);
+ };
+
+ const handleInstallServer = async (config: any) => {
+ try {
+ setStatusMessage('Installing server...');
+ await mcpManager.installServer(config);
+ await loadData();
+ setStatusMessage('Server installed successfully');
+ } catch (error) {
+ console.error('Failed to install server:', error);
+ setStatusMessage(`Installation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ }
+ };
+
+ const handleStartServer = async (serverId: string) => {
+ try {
+ setStatusMessage('Starting server...');
+ await mcpManager.startServer(serverId);
+ await loadData();
+ } catch (error) {
+ console.error('Failed to start server:', error);
+ setStatusMessage(`Start failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ }
+ };
+
+ const handleStopServer = async (serverId: string) => {
+ try {
+ setStatusMessage('Stopping server...');
+ await mcpManager.stopServer(serverId);
+ await loadData();
+ } catch (error) {
+ console.error('Failed to stop server:', error);
+ setStatusMessage(`Stop failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ }
+ };
+
+ const handleRemoveServer = async (serverId: string) => {
+ if (!confirm('Remove this MCP server? This will delete all associated data.')) {
+ return;
+ }
+
+ try {
+ setStatusMessage('Removing server...');
+ await mcpManager.removeServer(serverId);
+ await loadData();
+ setStatusMessage('Server removed');
+ } catch (error) {
+ console.error('Failed to remove server:', error);
+ setStatusMessage(`Remove failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ }
+ };
+
+ const handleToggleAutoStart = async (serverId: string, enabled: boolean) => {
+ try {
+ await mcpManager.updateServerConfig(serverId, { auto_start: enabled });
+ await loadData();
+ setStatusMessage(enabled ? 'Auto-start enabled' : 'Auto-start disabled');
+ } catch (error) {
+ console.error('Failed to toggle auto-start:', error);
+ setStatusMessage(`Auto-start toggle failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ }
+ };
+
+ const runningServers = servers.filter(s => s.status === 'running').length;
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontFamily: 'Consolas, monospace',
+ display: 'flex',
+ flexDirection: 'column',
+ fontSize: '11px'
+ }}>
+ {/* Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '8px 12px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold', fontSize: '12px' }}>
+ MCP INTEGRATIONS
+ </span>
+ <span style={{ color: BLOOMBERG_GRAY }}>|</span>
+ <span style={{ color: runningServers > 0 ? BLOOMBERG_GREEN : BLOOMBERG_GRAY, fontSize: '10px' }}>
+ {runningServers} Running
+ </span>
+ <span style={{ color: BLOOMBERG_GRAY }}>|</span>
+ <span style={{ color: BLOOMBERG_WHITE, fontSize: '10px' }}>
+ {tools.length} Tools
+ </span>
+ </div>
+
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={handleRefresh}
+ disabled={isRefreshing}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 10px',
+ fontSize: '10px',
+ cursor: isRefreshing ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ opacity: isRefreshing ? 0.5 : 1
+ }}
+ >
+ <RefreshCw size={12} style={{ animation: isRefreshing ? 'spin 1s linear infinite' : 'none' }} />
+ REFRESH
+ </button>
+
+ <button
+ onClick={() => setIsAddModalOpen(true)}
+ style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '4px 10px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Plus size={12} />
+ ADD SERVER
+ </button>
+ </div>
+ </div>
+
+ {/* Main Content */}
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* Left Panel: Installed Servers */}
+ <div style={{
+ width: '50%',
+ borderRight: `1px solid ${BLOOMBERG_GRAY}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ flexShrink: 0
+ }}>
+ <span style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
+ INSTALLED SERVERS ({servers.length})
+ </span>
+ </div>
+
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ {servers.length === 0 ? (
+ <div style={{
+ textAlign: 'center',
+ color: BLOOMBERG_GRAY,
+ padding: '40px 20px',
+ fontSize: '10px'
+ }}>
+ <div style={{ marginBottom: '8px' }}>No MCP servers installed.</div>
+ <div>Install from marketplace or add a custom server.</div>
+ </div>
+ ) : (
+ servers.map(server => {
+ const healthInfo = mcpManager.getServerHealthInfo(server.id);
+ return (
+ <MCPServerCard
+ key={server.id}
+ server={server}
+ onStart={() => handleStartServer(server.id)}
+ onStop={() => handleStopServer(server.id)}
+ onRemove={() => handleRemoveServer(server.id)}
+ onToggleAutoStart={(enabled) => handleToggleAutoStart(server.id, enabled)}
+ healthInfo={healthInfo}
+ />
+ );
+ })
+ )}
+ </div>
+ </div>
+
+ {/* Right Panel: Marketplace */}
+ <div style={{ width: '50%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ <MCPMarketplace onInstall={handleInstallServer} />
+ </div>
+ </div>
+
+ {/* Bottom Panel: Available Tools */}
+ <div style={{
+ height: '140px',
+ borderTop: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ overflow: 'auto',
+ padding: '8px',
+ flexShrink: 0
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '6px' }}>
+ AVAILABLE TOOLS ({tools.length})
+ </div>
+
+ {tools.length === 0 ? (
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px', textAlign: 'center', padding: '20px' }}>
+ No tools available. Start an MCP server to see its tools.
+ </div>
+ ) : (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px' }}>
+ {tools.map(tool => (
+ <div
+ key={tool.id}
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px 6px',
+ fontSize: '9px'
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '2px' }}>
+ <span style={{ color: BLOOMBERG_ORANGE }}>🔧</span>
+ <span style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>{tool.name}</span>
+ </div>
+ {tool.description && (
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '8px' }}>
+ {tool.description.substring(0, 60)}{tool.description.length > 60 ? '...' : ''}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Status Bar */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderTop: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px 12px',
+ fontSize: '9px',
+ color: BLOOMBERG_GRAY,
+ flexShrink: 0
+ }}>
+ STATUS: {statusMessage}
+ </div>
+
+ {/* Add Server Modal */}
+ {isAddModalOpen && (
+ <MCPAddServerModal
+ onClose={() => setIsAddModalOpen(false)}
+ onAdd={(config) => {
+ handleInstallServer(config);
+ setIsAddModalOpen(false);
+ }}
+ />
+ )}
+
+ <style>{`
+ @keyframes spin {
+ from { transform: rotate(0deg); }
+ to { transform: rotate(360deg); }
+ }
+ `}</style>
+ </div>
+ );
+};
+
+export default MCPTab;
diff --git a/fincept-terminal-desktop/src/services/fyersAuth.ts b/fincept-terminal-desktop/src/services/fyersAuth.ts
new file mode 100644
index 000000000..25cbb2918
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/fyersAuth.ts
@@ -0,0 +1,209 @@
+// Fyers Authentication Service
+// Automated token generation flow
+
+import * as OTPAuth from 'otpauth';
+import { invoke } from '@tauri-apps/api/core';
+
+export interface FyersAuthConfig {
+ clientId: string;
+ pin: string;
+ appId: string;
+ appType: string;
+ appSecret: string;
+ totpKey: string;
+}
+
+export interface FyersAuthResult {
+ accessToken: string;
+ connectionString: string; // APP_ID-APP_TYPE:ACCESS_TOKEN format for WebSocket
+}
+
+/**
+ * Automated Fyers authentication flow
+ * Follows the complete OAuth flow with TOTP
+ */
+export async function authenticateFyers(config: FyersAuthConfig): Promise<FyersAuthResult> {
+ console.log('[FyersAuth] Starting authentication...');
+
+ try {
+ // Step 1: Send login OTP
+ console.log('[FyersAuth] Step 1: Sending login OTP...');
+ let response = await fetch('https://api-t2.fyers.in/vagator/v2/send_login_otp', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ fy_id: config.clientId,
+ app_id: '2'
+ })
+ });
+
+ let data = await response.json();
+ console.log('[FyersAuth] OTP Response status:', response.status);
+ console.log('[FyersAuth] OTP Response data:', data);
+
+ if (response.status !== 200) {
+ throw new Error(`Failed to send OTP: HTTP ${response.status}`);
+ }
+
+ if (!data.request_key) {
+ throw new Error(`Failed to send OTP: ${JSON.stringify(data)}`);
+ }
+
+ let requestKey = data.request_key;
+ console.log('[FyersAuth] ✓ OTP sent successfully');
+
+ // Step 2: Generate TOTP and verify
+ console.log('[FyersAuth] Step 2: Generating TOTP...');
+ const totpGenerator = new OTPAuth.TOTP({
+ secret: config.totpKey
+ });
+ const totp = totpGenerator.generate();
+ console.log('[FyersAuth] TOTP generated:', totp);
+
+ response = await fetch('https://api-t2.fyers.in/vagator/v2/verify_otp', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ request_key: requestKey,
+ otp: totp
+ })
+ });
+
+ data = await response.json();
+ console.log('[FyersAuth] Verify OTP Response status:', response.status);
+ console.log('[FyersAuth] Verify OTP Response data:', data);
+
+ if (response.status !== 200) {
+ throw new Error(`Failed to verify OTP: HTTP ${response.status}`);
+ }
+
+ if (!data.request_key) {
+ throw new Error(`Failed to verify OTP: ${JSON.stringify(data)}`);
+ }
+
+ requestKey = data.request_key;
+ console.log('[FyersAuth] ✓ TOTP verified successfully');
+
+ // Step 3: Verify PIN
+ console.log('[FyersAuth] Step 3: Verifying PIN...');
+ response = await fetch('https://api-t2.fyers.in/vagator/v2/verify_pin', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ request_key: requestKey,
+ identity_type: 'pin',
+ identifier: config.pin
+ })
+ });
+
+ data = await response.json();
+ console.log('[FyersAuth] Verify PIN Response status:', response.status);
+ console.log('[FyersAuth] Verify PIN Response data:', data);
+
+ if (response.status !== 200) {
+ throw new Error(`Failed to verify PIN: HTTP ${response.status}`);
+ }
+
+ if (!data.data?.access_token) {
+ throw new Error(`Failed to verify PIN: ${JSON.stringify(data)}`);
+ }
+
+ const token1 = data.data.access_token;
+ console.log('[FyersAuth] ✓ PIN verified successfully');
+
+ // Step 4: Get authorization code (expects HTTP 308 redirect)
+ console.log('[FyersAuth] Step 4: Getting authorization code...');
+ response = await fetch('https://api-t1.fyers.in/api/v3/token', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${token1}`
+ },
+ body: JSON.stringify({
+ fyers_id: config.clientId,
+ app_id: config.appId,
+ redirect_uri: 'https://trade.fyers.in/api-login/redirect-uri/index.html',
+ appType: config.appType,
+ code_challenge: '',
+ state: 'sample_state',
+ scope: '',
+ nonce: '',
+ response_type: 'code',
+ create_cookie: true
+ })
+ });
+
+ data = await response.json();
+ console.log('[FyersAuth] Token API Response status:', response.status);
+ console.log('[FyersAuth] Token API Response data:', data);
+
+ if (response.status !== 308) {
+ throw new Error(`Expected HTTP 308 but got ${response.status}: ${JSON.stringify(data)}`);
+ }
+
+ if (!data?.Url) {
+ throw new Error('Failed to get authorization URL');
+ }
+
+ const authUrl = new URL(data.Url);
+ const authCode = authUrl.searchParams.get('auth_code');
+
+ if (!authCode) {
+ throw new Error('No auth_code in response URL');
+ }
+
+ console.log('[FyersAuth] ✓ Authorization code obtained');
+
+ // Step 5: Generate app hash and validate auth code
+ console.log('[FyersAuth] Step 5: Validating auth code...');
+ const appIdHash = await invoke<string>('sha256_hash', {
+ input: `${config.appId}-${config.appType}:${config.appSecret}`
+ });
+
+ console.log('[FyersAuth] Generated appIdHash');
+
+ response = await fetch('https://api-t1.fyers.in/api/v3/validate-authcode', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ grant_type: 'authorization_code',
+ appIdHash: appIdHash,
+ code: authCode
+ })
+ });
+
+ data = await response.json();
+ console.log('[FyersAuth] Validate Auth Code Response status:', response.status);
+ console.log('[FyersAuth] Validate Auth Code Response data:', data);
+
+ if (response.status !== 200) {
+ throw new Error(`Failed to validate auth code: HTTP ${response.status}`);
+ }
+
+ if (!data.access_token) {
+ throw new Error(`Failed to validate auth code: ${JSON.stringify(data)}`);
+ }
+
+ const accessToken = data.access_token;
+ const connectionString = `${config.appId}-${config.appType}:${accessToken}`;
+
+ console.log('[FyersAuth] ✓ Authentication successful!');
+ console.log('[FyersAuth] Final access token obtained');
+
+ return {
+ accessToken,
+ connectionString
+ };
+ } catch (error: any) {
+ console.error('[FyersAuth] Authentication failed:', error);
+ throw new Error(error.message || 'Authentication failed');
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/fyersService.ts b/fincept-terminal-desktop/src/services/fyersService.ts
new file mode 100644
index 000000000..497b93d21
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/fyersService.ts
@@ -0,0 +1,702 @@
+// Fyers Broker Integration Service
+// Handles all Fyers API interactions: auth, trading, market data, portfolio
+
+import { fyersModel } from 'fyers-web-sdk-v3';
+import { sqliteService } from './sqliteService';
+
+// ==================== TYPE DEFINITIONS ====================
+
+export interface FyersCredentials {
+ appId: string;
+ appType?: string;
+ redirectUrl: string;
+ accessToken: string;
+}
+
+export interface FyersProfile {
+ name: string;
+ image: string;
+ display_name: string;
+ email_id: string;
+ PAN: string;
+}
+
+export interface FyersFund {
+ id: number;
+ title: string;
+ equityAmount: number;
+ commodityAmount: number;
+}
+
+export interface FyersHolding {
+ costPrice: number;
+ id: number;
+ fyToken: string;
+ symbol: string;
+ isin: string;
+ quantity: number;
+ exchange: number;
+ segment: number;
+ qty_t1: number;
+ remainingQuantity: number;
+ collateralQuantity: number;
+ remainingPledgeQuantity: number;
+ pl: number;
+ ltp: number;
+ marketVal: number;
+ holdingType: string;
+}
+
+export interface FyersHoldingsResponse {
+ overall: {
+ count_total: number;
+ pnl_perc: number;
+ total_current_value: number;
+ total_investment: number;
+ total_pl: number;
+ };
+ holdings: FyersHolding[];
+}
+
+export interface FyersPosition {
+ id: string;
+ symbol: string;
+ fyToken: string;
+ side: number;
+ segment: number;
+ qty: number;
+ buyQty: number;
+ sellQty: number;
+ buyAvg: number;
+ sellAvg: number;
+ netQty: number;
+ netAvg: number;
+ ltp: number;
+ pl: number;
+ realized_profit: number;
+ unrealized_profit: number;
+ productType: string;
+}
+
+export interface PlaceOrderRequest {
+ symbol: string;
+ qty: number;
+ type: number; // 1=Limit, 2=Market, 3=Stop, 4=Stoplimit
+ side: number; // 1=Buy, -1=Sell
+ productType: string; // "INTRADAY", "MARGIN", "CNC", "CO", "BO"
+ limitPrice: number;
+ stopPrice: number;
+ disclosedQty: number;
+ validity: string; // "DAY", "IOC"
+ offlineOrder: boolean;
+ stopLoss: number;
+ takeProfit: number;
+ orderTag?: string;
+}
+
+export interface FyersOrder {
+ clientId: string;
+ id: string;
+ exchOrdId: string;
+ qty: number;
+ filledQty: number;
+ limitPrice: number;
+ type: number;
+ fyToken: string;
+ exchange: number;
+ segment: number;
+ symbol: string;
+ orderDateTime: string;
+ orderValidity: string;
+ productType: string;
+ side: number;
+ status: number;
+ ex_sym: string;
+ description: string;
+}
+
+export interface FyersMarketStatus {
+ exchange: number;
+ market_type: string;
+ segment: number;
+ status: string;
+}
+
+export interface FyersQuote {
+ n: string; // symbol
+ s: string; // status
+ v: {
+ ch: number; // change
+ chp: number; // change percent
+ lp: number; // last price
+ spread: number;
+ ask: number;
+ bid: number;
+ open_price: number;
+ high_price: number;
+ low_price: number;
+ prev_close_price: number;
+ volume: number;
+ };
+}
+
+export interface FyersMarketDepth {
+ totalbuyqty: number;
+ totalsellqty: number;
+ bids: Array<{ price: number; volume: number; ord: number }>;
+ ask: Array<{ price: number; volume: number; ord: number }>;
+ o: number; // open
+ h: number; // high
+ l: number; // low
+ c: number; // close
+ chp: number; // change percent
+ ch: number; // change
+ ltp: number; // last traded price
+ v: number; // volume
+ atp: number; // average traded price
+ lower_ckt: number;
+ upper_ckt: number;
+}
+
+export interface FyersHistoryCandle {
+ timestamp: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+}
+
+export interface SymbolMasterEntry {
+ fytoken: string;
+ symbol: string;
+ description: string;
+ exchange: string;
+ segment: string;
+ isin?: string;
+ lotsize?: number;
+ tick_size?: number;
+}
+
+// ==================== FYERS SERVICE CLASS ====================
+
+class FyersService {
+ private fyers: any = null;
+ private isInitialized = false;
+ private symbolMasterCache: SymbolMasterEntry[] = [];
+
+ /**
+ * Initialize Fyers client with credentials from database
+ */
+ async initialize(): Promise<boolean> {
+ try {
+ const creds = await sqliteService.getCredentialByService('fyers');
+
+ if (!creds || !creds.api_key || !creds.api_secret || !creds.password) {
+ return false;
+ }
+
+ const additionalData = creds.additional_data ? JSON.parse(creds.additional_data) : {};
+ const appType = additionalData.appType || '100';
+
+ const fullAccessToken = `${creds.api_key}-${appType}:${creds.password}`;
+
+ this.fyers = new fyersModel({
+ AccessToken: fullAccessToken,
+ AppID: creds.api_key,
+ RedirectURL: creds.api_secret,
+ enableLogging: false
+ });
+
+ this.isInitialized = true;
+ return true;
+ } catch (error) {
+ console.error('[Fyers] ✗ Initialization error:', error);
+ this.isInitialized = false;
+ return false;
+ }
+ }
+
+ /**
+ * Save Fyers credentials to database
+ */
+ async saveCredentials(credentials: FyersCredentials): Promise<void> {
+
+ await sqliteService.saveCredential({
+ service_name: 'fyers',
+ username: 'fyers_user',
+ api_key: credentials.appId,
+ api_secret: credentials.redirectUrl,
+ password: credentials.accessToken,
+ additional_data: JSON.stringify({
+ appType: credentials.appType || '100',
+ connected_at: new Date().toISOString()
+ })
+ });
+
+ await this.initialize();
+ }
+
+ /**
+ * Check if service is ready
+ */
+ isReady(): boolean {
+ return this.isInitialized && this.fyers !== null;
+ }
+
+ // ==================== PROFILE & FUNDS ====================
+
+ /**
+ * Get user profile
+ */
+ async getProfile(): Promise<FyersProfile> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.get_profile();
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to fetch profile');
+ }
+
+ return response.data;
+ }
+
+ /**
+ * Get funds/limits
+ */
+ async getFunds(): Promise<FyersFund[]> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.get_funds();
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to fetch funds');
+ }
+
+ return response.fund_limit;
+ }
+
+ // ==================== HOLDINGS & POSITIONS ====================
+
+ /**
+ * Get holdings
+ */
+ async getHoldings(): Promise<FyersHoldingsResponse> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.get_holdings();
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to fetch holdings');
+ }
+
+ return {
+ overall: response.overall,
+ holdings: response.holdings
+ };
+ }
+
+ /**
+ * Get positions
+ */
+ async getPositions(): Promise<FyersPosition[]> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.get_positions();
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to fetch positions');
+ }
+
+ return response.netPositions || [];
+ }
+
+ // ==================== ORDERS ====================
+
+ /**
+ * Place an order
+ */
+ async placeOrder(orderRequest: PlaceOrderRequest): Promise<{ orderId: string; message: string }> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.place_order(orderRequest);
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to place order');
+ }
+
+ return {
+ orderId: response.id || '',
+ message: response.message || 'Order placed successfully'
+ };
+ }
+
+ /**
+ * Get order book
+ */
+ async getOrders(): Promise<FyersOrder[]> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.get_orders();
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to fetch orders');
+ }
+
+ return response.orderBook || [];
+ }
+
+ /**
+ * Cancel an order
+ */
+ async cancelOrder(orderId: string): Promise<void> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.cancel_order({ id: orderId });
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to cancel order');
+ }
+ }
+
+ // ==================== MARKET DATA ====================
+
+ /**
+ * Get market status
+ */
+ async getMarketStatus(): Promise<FyersMarketStatus[]> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.market_status();
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to fetch market status');
+ }
+
+ return response.marketStatus;
+ }
+
+ /**
+ * Place order
+ */
+ async placeOrder(orderPayload: any): Promise<any> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.place_order(orderPayload);
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Order placement failed');
+ }
+
+ return response;
+ }
+
+ /**
+ * Place GTT order
+ */
+ async placeGTTOrder(gttPayload: any): Promise<any> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.place_gtt_order(gttPayload);
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'GTT Order placement failed');
+ }
+
+ return response;
+ }
+
+ /**
+ * Get quotes for symbols
+ */
+ async getQuotes(symbols: string[]): Promise<Record<string, FyersQuote>> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.getQuotes(symbols);
+
+ if (response.s !== 'ok') {
+ console.error('[Fyers] Quote API error:', response);
+ throw new Error(response.message || 'Failed to fetch quotes');
+ }
+
+ const dataArray = response.d || response.data || [];
+
+ if (!Array.isArray(dataArray) || dataArray.length === 0) {
+ console.error('[Fyers] Invalid or empty quote data');
+ return {};
+ }
+
+ const quotesMap: Record<string, FyersQuote> = {};
+ dataArray.forEach((quote: any) => {
+ const symbol = quote.n || quote.symbol;
+ if (!symbol) return;
+
+ // Data is nested inside 'v' object
+ const data = quote.v || quote;
+
+ quotesMap[symbol] = {
+ n: symbol,
+ lp: data.lp || data.last_price || 0,
+ ltp: data.lp || data.ltp || data.last_price || 0,
+ ch: data.ch || data.change || 0,
+ chp: data.chp || data.change_percent || 0,
+ high: data.high_price || data.h || data.high || 0,
+ low: data.low_price || data.l || data.low || 0,
+ open: data.open_price || data.o || data.open || 0,
+ volume: data.volume || data.v || 0,
+ v: data.volume || data.v || 0,
+ o: data.open_price || data.o || data.open || 0,
+ h: data.high_price || data.h || data.high || 0,
+ l: data.low_price || data.l || data.low || 0,
+ ...data
+ };
+ });
+
+ return quotesMap;
+ }
+
+ /**
+ * Get market depth
+ */
+ async getMarketDepth(symbols: string[], includeOHLCV: boolean = true): Promise<Record<string, FyersMarketDepth>> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.getMarketDepth({
+ symbol: symbols,
+ ohlcv_flag: includeOHLCV ? 1 : 0
+ });
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to fetch market depth');
+ }
+
+ return response.d;
+ }
+
+ /**
+ * Get historical data
+ */
+ async getHistory(params: {
+ symbol: string;
+ resolution: string;
+ date_format: string;
+ range_from: string;
+ range_to: string;
+ cont_flag: string;
+ }): Promise<any> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.getHistory(params);
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to fetch history');
+ }
+
+ return response;
+ }
+
+ /**
+ * Get option chain
+ */
+ async getOptionChain(symbol: string, strikeCount: number = 5, timestamp: string = ""): Promise<any> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const response = await this.fyers.getOptionChain({
+ symbol,
+ strikecount: strikeCount,
+ timestamp
+ });
+
+ if (response.code !== 200) {
+ throw new Error(response.message || 'Failed to fetch option chain');
+ }
+
+ return response.data;
+ }
+
+ // ==================== MARKET HOURS ====================
+
+ /**
+ * Check if market is currently open (NSE/BSE hours)
+ * NSE: 9:15 AM - 3:30 PM IST, Monday-Friday
+ */
+ isMarketOpen(): boolean {
+ const now = new Date();
+
+ // Convert to IST (UTC+5:30)
+ const istOffset = 5.5 * 60 * 60 * 1000;
+ const istTime = new Date(now.getTime() + istOffset);
+
+ const day = istTime.getUTCDay(); // 0 = Sunday, 6 = Saturday
+ const hour = istTime.getUTCHours();
+ const minute = istTime.getUTCMinutes();
+ const timeInMinutes = hour * 60 + minute;
+
+ // Weekend check
+ if (day === 0 || day === 6) {
+ return false;
+ }
+
+ // Market hours: 9:15 AM (555 min) to 3:30 PM (930 min)
+ const marketOpen = 9 * 60 + 15;
+ const marketClose = 15 * 60 + 30;
+
+ return timeInMinutes >= marketOpen && timeInMinutes <= marketClose;
+ }
+
+ // ==================== SYMBOL SEARCH ====================
+
+ /**
+ * Load symbol master from Fyers API
+ */
+ async loadSymbolMaster(): Promise<void> {
+ try {
+ const response = await fetch('https://public.fyers.in/sym_details/NSE_CM_sym_master.json');
+ const data = await response.json();
+
+ // The format is an object with symbol keys, not an array
+ if (data && typeof data === 'object' && !Array.isArray(data)) {
+ // Convert object to array of entries with symbol as key
+ this.symbolMasterCache = Object.entries(data).map(([symbol, details]: [string, any]) => ({
+ symbol: symbol,
+ fyToken: details.fyToken,
+ description: details.symbolDesc || details.symDetails || '',
+ exchange: details.exchangeName || 'NSE',
+ segment: details.exSeries || '',
+ lotSize: details.minLotSize || 1,
+ tickSize: details.tickSize || 0.05,
+ shortName: details.short_name || details.exSymbol || '',
+ displayName: details.display_format_mob || details.exSymName || ''
+ }));
+ } else if (Array.isArray(data)) {
+ this.symbolMasterCache = data;
+ } else {
+ this.symbolMasterCache = [];
+ }
+ } catch (error) {
+ console.error('[Fyers] ✗ Failed to load symbol master:', error);
+ this.symbolMasterCache = []; // Ensure it's always an array
+ }
+ }
+
+ /**
+ * Search symbols
+ */
+ searchSymbols(query: string, limit: number = 20): SymbolMasterEntry[] {
+ if (!Array.isArray(this.symbolMasterCache) || this.symbolMasterCache.length === 0) {
+ console.warn('[Fyers] Symbol master not loaded or invalid');
+ return [];
+ }
+
+ if (!query || query.trim().length === 0) {
+ return [];
+ }
+
+ const queryLower = query.toLowerCase().trim();
+ try {
+ return this.symbolMasterCache
+ .filter(entry => {
+ if (!entry) return false;
+ const symbol = entry.symbol?.toLowerCase() || '';
+ const desc = entry.description?.toLowerCase() || '';
+ const shortName = entry.shortName?.toLowerCase() || '';
+ const displayName = entry.displayName?.toLowerCase() || '';
+
+ return symbol.includes(queryLower) ||
+ desc.includes(queryLower) ||
+ shortName.includes(queryLower) ||
+ displayName.includes(queryLower);
+ })
+ .slice(0, limit);
+ } catch (error) {
+ console.error('[Fyers] Error searching symbols:', error);
+ return [];
+ }
+ }
+
+ /**
+ * Get symbol by exact match
+ */
+ getSymbol(symbol: string): SymbolMasterEntry | undefined {
+ return this.symbolMasterCache.find(entry => entry.symbol === symbol);
+ }
+
+ // ==================== MARGIN CALCULATOR ====================
+
+ /**
+ * Calculate margin for a single order (span_margin endpoint)
+ */
+ async calculateSpanMargin(order: {
+ symbol: string;
+ qty: number;
+ side: 'BUY' | 'SELL';
+ type: 'MARKET' | 'LIMIT' | 'STOP';
+ productType: 'CNC' | 'INTRADAY' | 'MARGIN';
+ limitPrice?: number;
+ stopLoss?: number;
+ stopPrice?: number;
+ takeProfit?: number;
+ }): Promise<any> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const payload = {
+ symbol: order.symbol,
+ qty: order.qty,
+ side: order.side === 'BUY' ? 1 : -1,
+ type: order.type === 'MARKET' ? 2 : order.type === 'LIMIT' ? 1 : 3,
+ productType: order.productType,
+ limitPrice: order.limitPrice || 0,
+ stopLoss: order.stopLoss || 0,
+ stopPrice: order.stopPrice || 0,
+ takeProfit: order.takeProfit || 0
+ };
+
+ const response = await this.fyers.span_margin(payload);
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to calculate margin');
+ }
+
+ return response;
+ }
+
+ /**
+ * Calculate margin for multiple orders (multiorder/margin endpoint)
+ */
+ async calculateMultiOrderMargin(orders: Array<{
+ symbol: string;
+ qty: number;
+ side: 'BUY' | 'SELL';
+ type: 'MARKET' | 'LIMIT' | 'STOP';
+ productType: 'CNC' | 'INTRADAY' | 'MARGIN';
+ limitPrice?: number;
+ stopLoss?: number;
+ stopPrice?: number;
+ takeProfit?: number;
+ }>): Promise<any> {
+ if (!this.isReady()) throw new Error('Fyers service not initialized');
+
+ const payload = orders.map(order => ({
+ symbol: order.symbol,
+ qty: order.qty,
+ side: order.side === 'BUY' ? 1 : -1,
+ type: order.type === 'MARKET' ? 2 : order.type === 'LIMIT' ? 1 : 3,
+ productType: order.productType,
+ limitPrice: order.limitPrice || 0,
+ stopLoss: order.stopLoss || 0,
+ stopPrice: order.stopPrice || 0,
+ takeProfit: order.takeProfit || 0
+ }));
+
+ const response = await this.fyers.multiorder_margin(payload);
+
+ if (response.s !== 'ok') {
+ throw new Error(response.message || 'Failed to calculate multi-order margin');
+ }
+
+ return response;
+ }
+}
+
+// Singleton instance
+export const fyersService = new FyersService();
diff --git a/fincept-terminal-desktop/src/services/fyersWebSocket.ts b/fincept-terminal-desktop/src/services/fyersWebSocket.ts
new file mode 100644
index 000000000..c466c8a39
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/fyersWebSocket.ts
@@ -0,0 +1,210 @@
+// Fyers WebSocket Service
+// Handles real-time streaming for orders, trades, positions
+
+import { fyersOrderSocket } from 'fyers-web-sdk-v3';
+
+export interface FyersOrderUpdate {
+ clientId: string;
+ id: string;
+ exchOrdId: string;
+ qty: number;
+ filledQty: number;
+ limitPrice: number;
+ type: number;
+ fyToken: string;
+ exchange: number;
+ segment: number;
+ symbol: string;
+ orderDateTime: string;
+ orderValidity: string;
+ productType: string;
+ side: number;
+ status: number;
+ ex_sym: string;
+ description: string;
+}
+
+export interface FyersTradeUpdate {
+ id: string;
+ orderId: string;
+ symbol: string;
+ side: number;
+ qty: number;
+ price: number;
+ tradeDateTime: string;
+}
+
+export interface FyersPositionUpdate {
+ symbol: string;
+ netQty: number;
+ avgPrice: number;
+ ltp: number;
+ pl: number;
+ side: number;
+}
+
+type OrderCallback = (order: FyersOrderUpdate) => void;
+type TradeCallback = (trade: FyersTradeUpdate) => void;
+type PositionCallback = (position: FyersPositionUpdate) => void;
+type GeneralCallback = (data: any) => void;
+type ErrorCallback = (error: any) => void;
+
+class FyersWebSocketService {
+ private socket: any = null;
+ private isConnected = false;
+ private connectionString = '';
+
+ private orderCallbacks: OrderCallback[] = [];
+ private tradeCallbacks: TradeCallback[] = [];
+ private positionCallbacks: PositionCallback[] = [];
+ private generalCallbacks: GeneralCallback[] = [];
+ private errorCallbacks: ErrorCallback[] = [];
+
+ /**
+ * Initialize WebSocket connection
+ * @param appId - Fyers App ID
+ * @param accessToken - Access token
+ */
+ connect(appId: string, accessToken: string): void {
+ if (this.isConnected) {
+ console.log('[FyersWS] Already connected');
+ return;
+ }
+
+ this.connectionString = `${appId}:${accessToken}`;
+ this.socket = new fyersOrderSocket(this.connectionString);
+
+ // Error handler
+ this.socket.on('error', (error: any) => {
+ console.error('[FyersWS] Error:', error);
+ this.errorCallbacks.forEach(cb => cb(error));
+ });
+
+ // Connection established
+ this.socket.on('connect', () => {
+ console.log('[FyersWS] Connected successfully');
+ this.isConnected = true;
+
+ // Subscribe to all channels
+ this.socket.subscribe([
+ this.socket.orderUpdates,
+ this.socket.tradeUpdates,
+ this.socket.positionUpdates,
+ this.socket.edis,
+ this.socket.pricealerts
+ ]);
+ });
+
+ // Connection closed
+ this.socket.on('close', () => {
+ console.log('[FyersWS] Connection closed');
+ this.isConnected = false;
+ });
+
+ // Order updates
+ this.socket.on('orders', (data: any) => {
+ console.log('[FyersWS] Order update:', data);
+ if (data.orders) {
+ this.orderCallbacks.forEach(cb => cb(data.orders));
+ }
+ });
+
+ // Trade updates
+ this.socket.on('trades', (data: any) => {
+ console.log('[FyersWS] Trade update:', data);
+ if (data.trades) {
+ this.tradeCallbacks.forEach(cb => cb(data.trades));
+ }
+ });
+
+ // Position updates
+ this.socket.on('positions', (data: any) => {
+ console.log('[FyersWS] Position update:', data);
+ if (data.positions) {
+ this.positionCallbacks.forEach(cb => cb(data.positions));
+ }
+ });
+
+ // General updates (EDIS, price alerts)
+ this.socket.on('general', (data: any) => {
+ console.log('[FyersWS] General update:', data);
+ this.generalCallbacks.forEach(cb => cb(data));
+ });
+
+ // Enable auto-reconnect
+ this.socket.autoreconnect();
+
+ // Connect
+ this.socket.connect();
+ }
+
+ /**
+ * Disconnect WebSocket
+ */
+ disconnect(): void {
+ if (this.socket && this.isConnected) {
+ this.socket.close();
+ this.socket = null;
+ this.isConnected = false;
+ console.log('[FyersWS] Disconnected');
+ }
+ }
+
+ /**
+ * Check connection status
+ */
+ getConnectionStatus(): boolean {
+ return this.isConnected;
+ }
+
+ // ==================== EVENT LISTENERS ====================
+
+ /**
+ * Subscribe to order updates
+ */
+ onOrderUpdate(callback: OrderCallback): void {
+ this.orderCallbacks.push(callback);
+ }
+
+ /**
+ * Subscribe to trade updates
+ */
+ onTradeUpdate(callback: TradeCallback): void {
+ this.tradeCallbacks.push(callback);
+ }
+
+ /**
+ * Subscribe to position updates
+ */
+ onPositionUpdate(callback: PositionCallback): void {
+ this.positionCallbacks.push(callback);
+ }
+
+ /**
+ * Subscribe to general updates
+ */
+ onGeneralUpdate(callback: GeneralCallback): void {
+ this.generalCallbacks.push(callback);
+ }
+
+ /**
+ * Subscribe to errors
+ */
+ onError(callback: ErrorCallback): void {
+ this.errorCallbacks.push(callback);
+ }
+
+ /**
+ * Remove all callbacks
+ */
+ clearCallbacks(): void {
+ this.orderCallbacks = [];
+ this.tradeCallbacks = [];
+ this.positionCallbacks = [];
+ this.generalCallbacks = [];
+ this.errorCallbacks = [];
+ }
+}
+
+// Singleton instance
+export const fyersWebSocket = new FyersWebSocketService();
diff --git a/fincept-terminal-desktop/src/services/llmApi.ts b/fincept-terminal-desktop/src/services/llmApi.ts
index 4d4cfeb40..18799eef4 100644
--- a/fincept-terminal-desktop/src/services/llmApi.ts
+++ b/fincept-terminal-desktop/src/services/llmApi.ts
@@ -453,6 +453,198 @@ class LLMApiService {
}
}
+ // Chat with MCP tools support (Full Implementation)
+ async chatWithTools(
+ userMessage: string,
+ conversationHistory: ChatMessage[] = [],
+ tools: Array<any> = [],
+ onStream?: StreamCallback,
+ onToolCall?: (toolName: string, args: any, result?: any) => void
+ ): Promise<LLMResponse> {
+ try {
+ // Get active provider config
+ const activeConfig = await sqliteService.getActiveLLMConfig();
+ if (!activeConfig) {
+ return {
+ content: '',
+ error: 'No active LLM provider configured. Please check settings.'
+ };
+ }
+
+ // Only OpenAI and OpenRouter support function calling well
+ if (activeConfig.provider !== 'openai' && activeConfig.provider !== 'openrouter') {
+ // Fall back to regular chat for other providers
+ return this.chat(userMessage, conversationHistory, onStream);
+ }
+
+ // If no tools provided, fall back to regular chat
+ if (tools.length === 0) {
+ return this.chat(userMessage, conversationHistory, onStream);
+ }
+
+ const globalSettings = await sqliteService.getLLMGlobalSettings();
+
+ const config: LLMConfig = {
+ provider: activeConfig.provider,
+ apiKey: activeConfig.api_key,
+ baseUrl: activeConfig.base_url,
+ model: activeConfig.model,
+ temperature: globalSettings.temperature,
+ maxTokens: globalSettings.max_tokens,
+ systemPrompt: globalSettings.system_prompt
+ };
+
+ // Build messages
+ let messages: any[] = [
+ { role: 'system', content: config.systemPrompt || 'You are a helpful assistant with access to tools. Use them when needed.' },
+ ...conversationHistory.map(msg => ({ role: msg.role, content: msg.content })),
+ { role: 'user', content: userMessage }
+ ];
+
+ // Convert MCP tools to OpenAI function format
+ const functions = tools.map(tool => ({
+ type: 'function',
+ function: {
+ name: tool.name,
+ description: tool.description || '',
+ parameters: tool.inputSchema || { type: 'object', properties: {} }
+ }
+ }));
+
+ const url = `${config.baseUrl || 'https://api.openai.com/v1'}/chat/completions`;
+
+ // First call - with tools
+ let response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${config.apiKey}`,
+ ...(activeConfig.provider === 'openrouter' ? {
+ 'HTTP-Referer': window.location.origin,
+ 'X-Title': 'Fincept Terminal'
+ } : {})
+ },
+ body: JSON.stringify({
+ model: config.model,
+ messages: messages,
+ tools: functions,
+ tool_choice: 'auto',
+ temperature: config.temperature,
+ max_tokens: config.maxTokens
+ })
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error?.message || `API error: ${response.status}`);
+ }
+
+ let data = await response.json();
+ let assistantMessage = data.choices[0].message;
+
+ // Check if AI wants to call tools
+ if (assistantMessage.tool_calls && assistantMessage.tool_calls.length > 0) {
+ // Add assistant's tool call message to conversation
+ messages.push(assistantMessage);
+
+ // Execute each tool call
+ for (const toolCall of assistantMessage.tool_calls) {
+ const toolName = toolCall.function.name;
+ const toolArgs = JSON.parse(toolCall.function.arguments);
+
+ console.log(`[MCP] Calling tool: ${toolName}`, toolArgs);
+
+ // Notify UI that tool is being called
+ if (onToolCall) {
+ onToolCall(toolName, toolArgs);
+ }
+
+ // Import mcpManager dynamically to avoid circular dependency
+ const { mcpManager } = await import('./mcpManager');
+
+ // Execute the tool
+ try {
+ // Parse server ID from tool name (format: serverId__toolName)
+ const [serverId, actualToolName] = toolName.includes('__')
+ ? toolName.split('__')
+ : [toolName, toolName];
+
+ const toolResult = await mcpManager.callTool(serverId, actualToolName, toolArgs);
+
+ // Format result for OpenAI
+ const resultContent = toolResult.content
+ .map((c: any) => c.text || JSON.stringify(c.data || c))
+ .join('\n');
+
+ // Add tool result to conversation
+ messages.push({
+ role: 'tool',
+ tool_call_id: toolCall.id,
+ content: resultContent
+ });
+
+ // Notify UI of result
+ if (onToolCall) {
+ onToolCall(toolName, toolArgs, toolResult);
+ }
+
+ console.log(`[MCP] Tool result:`, resultContent);
+ } catch (error) {
+ console.error(`[MCP] Tool execution error:`, error);
+ messages.push({
+ role: 'tool',
+ tool_call_id: toolCall.id,
+ content: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`
+ });
+ }
+ }
+
+ // Second call - get final response with tool results
+ response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${config.apiKey}`,
+ ...(activeConfig.provider === 'openrouter' ? {
+ 'HTTP-Referer': window.location.origin,
+ 'X-Title': 'Fincept Terminal'
+ } : {})
+ },
+ body: JSON.stringify({
+ model: config.model,
+ messages: messages,
+ temperature: config.temperature,
+ max_tokens: config.maxTokens
+ })
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error?.message || `API error: ${response.status}`);
+ }
+
+ data = await response.json();
+ assistantMessage = data.choices[0].message;
+ }
+
+ return {
+ content: assistantMessage.content || '',
+ usage: {
+ promptTokens: data.usage?.prompt_tokens || 0,
+ completionTokens: data.usage?.completion_tokens || 0,
+ totalTokens: data.usage?.total_tokens || 0
+ }
+ };
+
+ } catch (error) {
+ console.error('Error in chatWithTools:', error);
+ return {
+ content: '',
+ error: error instanceof Error ? error.message : 'Unknown error'
+ };
+ }
+ }
+
// Test connection
async testConnection(): Promise<{ success: boolean; error?: string; model?: string }> {
try {
diff --git a/fincept-terminal-desktop/src/services/marketDataService.ts b/fincept-terminal-desktop/src/services/marketDataService.ts
new file mode 100644
index 000000000..326c26e34
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/marketDataService.ts
@@ -0,0 +1,189 @@
+// Market Data Service - TypeScript wrapper for Tauri market data commands
+// Modular design: gracefully handles failures and can be extended with other data sources
+
+import { invoke } from '@tauri-apps/api/core';
+
+export interface QuoteData {
+ symbol: string;
+ price: number;
+ change: number;
+ change_percent: number;
+ volume?: number;
+ high?: number;
+ low?: number;
+ open?: number;
+ previous_close?: number;
+ timestamp: number;
+}
+
+export interface QuoteResponse {
+ success: boolean;
+ data?: QuoteData;
+ error?: string;
+}
+
+export interface QuotesResponse {
+ success: boolean;
+ data: QuoteData[];
+ error?: string;
+}
+
+export interface PeriodReturns {
+ symbol: string;
+ seven_day: number;
+ thirty_day: number;
+}
+
+export interface PeriodReturnsResponse {
+ success: boolean;
+ data?: PeriodReturns;
+ error?: string;
+}
+
+/**
+ * Market Data Service
+ * Provides a clean TypeScript interface to fetch market data
+ * Handles errors gracefully and provides fallback behavior
+ */
+class MarketDataService {
+ private isAvailable: boolean | null = null;
+
+ /**
+ * Check if market data service is available
+ */
+ async checkHealth(): Promise<boolean> {
+ try {
+ const result = await invoke<boolean>('check_market_data_health');
+ this.isAvailable = result;
+ return result;
+ } catch (error) {
+ console.error('[MarketDataService] Health check failed:', error);
+ this.isAvailable = false;
+ return false;
+ }
+ }
+
+ /**
+ * Fetch a single quote
+ * Returns null if fetch fails (graceful degradation)
+ */
+ async getQuote(symbol: string): Promise<QuoteData | null> {
+ try {
+ const response = await invoke<QuoteResponse>('get_market_quote', { symbol });
+
+ if (response.success && response.data) {
+ return response.data;
+ } else {
+ console.warn(`[MarketDataService] Failed to fetch quote for ${symbol}:`, response.error);
+ return null;
+ }
+ } catch (error) {
+ console.error(`[MarketDataService] Error fetching quote for ${symbol}:`, error);
+ return null;
+ }
+ }
+
+ /**
+ * Fetch multiple quotes in batch
+ * Returns only successful fetches (partial success model)
+ */
+ async getQuotes(symbols: string[]): Promise<QuoteData[]> {
+ try {
+ const response = await invoke<QuotesResponse>('get_market_quotes', { symbols });
+
+ if (response.success) {
+ return response.data;
+ } else {
+ console.warn('[MarketDataService] Failed to fetch quotes:', response.error);
+ return [];
+ }
+ } catch (error) {
+ console.error('[MarketDataService] Error fetching quotes:', error);
+ return [];
+ }
+ }
+
+ /**
+ * Fetch period returns (7D, 30D)
+ * Returns null if fetch fails
+ */
+ async getPeriodReturns(symbol: string): Promise<PeriodReturns | null> {
+ try {
+ const response = await invoke<PeriodReturnsResponse>('get_period_returns', { symbol });
+
+ if (response.success && response.data) {
+ return response.data;
+ } else {
+ console.warn(`[MarketDataService] Failed to fetch returns for ${symbol}:`, response.error);
+ return null;
+ }
+ } catch (error) {
+ console.error(`[MarketDataService] Error fetching returns for ${symbol}:`, error);
+ return null;
+ }
+ }
+
+ /**
+ * Fetch enhanced quote with period returns
+ * Combines quote data with 7D/30D returns
+ */
+ async getEnhancedQuote(symbol: string): Promise<(QuoteData & { seven_day?: number; thirty_day?: number }) | null> {
+ const [quote, returns] = await Promise.all([
+ this.getQuote(symbol),
+ this.getPeriodReturns(symbol)
+ ]);
+
+ if (!quote) return null;
+
+ return {
+ ...quote,
+ seven_day: returns?.seven_day,
+ thirty_day: returns?.thirty_day
+ };
+ }
+
+ /**
+ * Fetch enhanced quotes for multiple symbols
+ * Fetches quotes and returns in parallel
+ */
+ async getEnhancedQuotes(symbols: string[]): Promise<(QuoteData & { seven_day?: number; thirty_day?: number })[]> {
+ const quotes = await this.getQuotes(symbols);
+
+ // Fetch returns for all symbols in parallel
+ const returnsPromises = symbols.map(symbol => this.getPeriodReturns(symbol));
+ const returns = await Promise.all(returnsPromises);
+
+ // Merge quotes with returns
+ return quotes.map((quote, index) => ({
+ ...quote,
+ seven_day: returns[index]?.seven_day,
+ thirty_day: returns[index]?.thirty_day
+ }));
+ }
+
+ /**
+ * Format price change with sign
+ */
+ formatChange(value: number): string {
+ return value >= 0 ? `+${value.toFixed(2)}` : value.toFixed(2);
+ }
+
+ /**
+ * Format percentage change with sign
+ */
+ formatChangePercent(value: number): string {
+ return value >= 0 ? `+${value.toFixed(2)}%` : `${value.toFixed(2)}%`;
+ }
+
+ /**
+ * Check if service is likely available
+ * (cached result from last health check)
+ */
+ isLikelyAvailable(): boolean {
+ return this.isAvailable !== false;
+ }
+}
+
+// Export singleton instance
+export const marketDataService = new MarketDataService();
+export default marketDataService;
diff --git a/fincept-terminal-desktop/src/services/mcpClient.ts b/fincept-terminal-desktop/src/services/mcpClient.ts
new file mode 100644
index 000000000..37d9edcc4
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcpClient.ts
@@ -0,0 +1,283 @@
+// MCP Client - Model Context Protocol Implementation
+// Handles stdio/SSE transport for MCP servers
+
+import { invoke } from '@tauri-apps/api/core';
+
+export interface MCPTool {
+ name: string;
+ description?: string;
+ inputSchema: {
+ type: string;
+ properties?: Record<string, any>;
+ required?: string[];
+ };
+}
+
+export interface MCPResource {
+ uri: string;
+ name: string;
+ description?: string;
+ mimeType?: string;
+}
+
+export interface MCPServerCapabilities {
+ tools?: { listChanged?: boolean };
+ resources?: { subscribe?: boolean; listChanged?: boolean };
+ prompts?: { listChanged?: boolean };
+}
+
+export interface MCPToolResult {
+ content: Array<{
+ type: string;
+ text?: string;
+ data?: any;
+ }>;
+ isError?: boolean;
+}
+
+export interface MCPConnectionConfig {
+ serverId: string;
+ command: string;
+ args: string[];
+ env?: Record<string, string>;
+}
+
+class MCPClient {
+ private serverId: string;
+ private processId: number | null = null;
+ private messageId = 0;
+ private pendingRequests = new Map<number, {
+ resolve: (value: any) => void;
+ reject: (error: any) => void;
+ }>();
+ private isInitialized = false;
+ private capabilities: MCPServerCapabilities = {};
+
+ constructor(serverId: string) {
+ this.serverId = serverId;
+ }
+
+ // Connect to MCP server via stdio
+ async connect(config: MCPConnectionConfig): Promise<void> {
+ try {
+ console.log(`[MCP] Connecting to server: ${config.serverId}`);
+
+ // Spawn MCP server process via Tauri
+ const result = await invoke<{ pid: number; success: boolean; error?: string }>(
+ 'spawn_mcp_server',
+ {
+ serverId: config.serverId,
+ command: config.command,
+ args: config.args,
+ env: config.env || {}
+ }
+ );
+
+ if (!result.success || result.error) {
+ throw new Error(result.error || 'Failed to spawn MCP server');
+ }
+
+ this.processId = result.pid;
+ console.log(`[MCP] Server spawned with PID: ${this.processId}`);
+
+ // Initialize MCP protocol
+ await this.initialize();
+ console.log(`[MCP] Server initialized successfully`);
+ } catch (error) {
+ console.error('[MCP] Connection error:', error);
+ throw error;
+ }
+ }
+
+ // Initialize MCP protocol handshake
+ private async initialize(): Promise<void> {
+ const response = await this.sendRequest('initialize', {
+ protocolVersion: '2024-11-05',
+ capabilities: {
+ roots: {
+ listChanged: false
+ },
+ sampling: {}
+ },
+ clientInfo: {
+ name: 'fincept-terminal',
+ version: '1.0.0'
+ }
+ });
+
+ this.capabilities = response.capabilities || {};
+ this.isInitialized = true;
+
+ // Send initialized notification
+ await this.sendNotification('notifications/initialized');
+ }
+
+ // List all available tools
+ async listTools(): Promise<MCPTool[]> {
+ if (!this.isInitialized) {
+ throw new Error('MCP client not initialized');
+ }
+
+ try {
+ const response = await this.sendRequest('tools/list', {});
+ return response.tools || [];
+ } catch (error) {
+ console.error('[MCP] Error listing tools:', error);
+ return [];
+ }
+ }
+
+ // Call a tool
+ async callTool(name: string, args: Record<string, any> = {}): Promise<MCPToolResult> {
+ if (!this.isInitialized) {
+ throw new Error('MCP client not initialized');
+ }
+
+ try {
+ const response = await this.sendRequest('tools/call', {
+ name,
+ arguments: args
+ });
+
+ return response;
+ } catch (error) {
+ console.error(`[MCP] Error calling tool ${name}:`, error);
+ return {
+ content: [{
+ type: 'text',
+ text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`
+ }],
+ isError: true
+ };
+ }
+ }
+
+ // List resources
+ async listResources(): Promise<MCPResource[]> {
+ if (!this.isInitialized) {
+ throw new Error('MCP client not initialized');
+ }
+
+ try {
+ const response = await this.sendRequest('resources/list', {});
+ return response.resources || [];
+ } catch (error) {
+ console.error('[MCP] Error listing resources:', error);
+ return [];
+ }
+ }
+
+ // Read a resource
+ async readResource(uri: string): Promise<any> {
+ if (!this.isInitialized) {
+ throw new Error('MCP client not initialized');
+ }
+
+ try {
+ const response = await this.sendRequest('resources/read', { uri });
+ return response.contents || [];
+ } catch (error) {
+ console.error(`[MCP] Error reading resource ${uri}:`, error);
+ throw error;
+ }
+ }
+
+ // Ping server to check if alive
+ async ping(): Promise<boolean> {
+ if (!this.processId) return false;
+
+ try {
+ const result = await invoke<boolean>('ping_mcp_server', {
+ serverId: this.serverId
+ });
+ return result;
+ } catch (error) {
+ console.error('[MCP] Ping error:', error);
+ return false;
+ }
+ }
+
+ // Disconnect from server
+ async disconnect(): Promise<void> {
+ if (this.processId) {
+ try {
+ await invoke('kill_mcp_server', {
+ serverId: this.serverId
+ });
+ console.log(`[MCP] Server ${this.serverId} disconnected`);
+ } catch (error) {
+ console.error('[MCP] Disconnect error:', error);
+ }
+
+ this.processId = null;
+ this.isInitialized = false;
+ this.pendingRequests.clear();
+ }
+ }
+
+ // Send JSON-RPC request
+ private async sendRequest(method: string, params: any): Promise<any> {
+ const id = this.messageId++;
+
+ const request = {
+ jsonrpc: '2.0',
+ id,
+ method,
+ params
+ };
+
+ return new Promise(async (resolve, reject) => {
+ this.pendingRequests.set(id, { resolve, reject });
+
+ try {
+ const response = await invoke<string>('send_mcp_request', {
+ serverId: this.serverId,
+ request: JSON.stringify(request)
+ });
+
+ const parsed = JSON.parse(response);
+
+ if (parsed.error) {
+ reject(new Error(parsed.error.message || 'MCP request failed'));
+ this.pendingRequests.delete(id);
+ } else {
+ resolve(parsed.result);
+ this.pendingRequests.delete(id);
+ }
+ } catch (error) {
+ reject(error);
+ this.pendingRequests.delete(id);
+ }
+ });
+ }
+
+ // Send notification (no response expected)
+ private async sendNotification(method: string, params?: any): Promise<void> {
+ const notification = {
+ jsonrpc: '2.0',
+ method,
+ params
+ };
+
+ try {
+ await invoke('send_mcp_notification', {
+ serverId: this.serverId,
+ notification: JSON.stringify(notification)
+ });
+ } catch (error) {
+ console.error('[MCP] Notification error:', error);
+ }
+ }
+
+ // Get server capabilities
+ getCapabilities(): MCPServerCapabilities {
+ return this.capabilities;
+ }
+
+ // Check if connected
+ isConnected(): boolean {
+ return this.isInitialized && this.processId !== null;
+ }
+}
+
+export default MCPClient;
diff --git a/fincept-terminal-desktop/src/services/mcpManager.ts b/fincept-terminal-desktop/src/services/mcpManager.ts
new file mode 100644
index 000000000..2fe520d7d
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcpManager.ts
@@ -0,0 +1,431 @@
+// MCP Manager - Server Lifecycle Management
+// Handles server installation, startup, shutdown, and tool aggregation
+
+import MCPClient, { MCPTool, MCPConnectionConfig } from './mcpClient';
+import { sqliteService } from './sqliteService';
+
+export interface MCPServer {
+ id: string;
+ name: string;
+ description: string;
+ command: string;
+ args: string[];
+ env?: Record<string, string>;
+ category: string;
+ icon: string;
+ enabled: boolean;
+ auto_start: boolean;
+ status: 'running' | 'stopped' | 'error';
+ created_at: string;
+ updated_at: string;
+}
+
+export interface MCPServerWithStats extends MCPServer {
+ toolCount: number;
+ callsToday: number;
+ lastUsed?: string;
+}
+
+class MCPManager {
+ private clients = new Map<string, MCPClient>();
+ private healthCheckInterval: NodeJS.Timeout | null = null;
+ private serverErrors = new Map<string, { count: number; lastError: string; lastErrorTime: number }>();
+
+ constructor() {
+ // Start health check on initialization
+ this.startHealthCheck();
+ }
+
+ // Install a new MCP server
+ async installServer(config: {
+ id: string;
+ name: string;
+ description: string;
+ command: string;
+ args: string[];
+ env?: Record<string, string>;
+ category: string;
+ icon: string;
+ }): Promise<void> {
+ try {
+ console.log(`[MCPManager] Installing server: ${config.name}`);
+
+ // Add to database
+ await sqliteService.addMCPServer({
+ id: config.id,
+ name: config.name,
+ description: config.description,
+ command: config.command,
+ args: JSON.stringify(config.args),
+ env: config.env ? JSON.stringify(config.env) : null,
+ category: config.category,
+ icon: config.icon,
+ enabled: true
+ });
+
+ // Try to start the server immediately
+ await this.startServer(config.id);
+
+ console.log(`[MCPManager] Server ${config.name} installed successfully`);
+ } catch (error) {
+ console.error('[MCPManager] Installation error:', error);
+ throw error;
+ }
+ }
+
+ // Start an MCP server
+ async startServer(serverId: string): Promise<void> {
+ try {
+ // Get server config from database
+ const server = await sqliteService.getMCPServer(serverId);
+ if (!server) {
+ throw new Error(`Server ${serverId} not found`);
+ }
+
+ if (!server.enabled) {
+ throw new Error(`Server ${serverId} is disabled`);
+ }
+
+ console.log(`[MCPManager] Starting server: ${server.name}`);
+
+ // Create client if doesn't exist
+ if (!this.clients.has(serverId)) {
+ this.clients.set(serverId, new MCPClient(serverId));
+ }
+
+ const client = this.clients.get(serverId)!;
+
+ // Check if already connected
+ if (client.isConnected()) {
+ console.log(`[MCPManager] Server ${serverId} already running`);
+ return;
+ }
+
+ // Parse config
+ const args = JSON.parse(server.args);
+ const env = server.env ? JSON.parse(server.env) : undefined;
+
+ // Connect
+ await client.connect({
+ serverId,
+ command: server.command,
+ args,
+ env
+ });
+
+ // Update status
+ await sqliteService.updateMCPServerStatus(serverId, 'running');
+
+ // Fetch and cache tools
+ const tools = await client.listTools();
+ await sqliteService.cacheMCPTools(serverId, tools);
+
+ // Clear error tracking on successful start
+ this.serverErrors.delete(serverId);
+
+ console.log(`[MCPManager] Server ${server.name} started with ${tools.length} tools`);
+ } catch (error) {
+ console.error(`[MCPManager] Error starting server ${serverId}:`, error);
+
+ // Track error
+ const errorMsg = error instanceof Error ? error.message : 'Unknown error';
+ const existing = this.serverErrors.get(serverId) || { count: 0, lastError: '', lastErrorTime: 0 };
+ this.serverErrors.set(serverId, {
+ count: existing.count + 1,
+ lastError: errorMsg,
+ lastErrorTime: Date.now()
+ });
+
+ await sqliteService.updateMCPServerStatus(serverId, 'error');
+ throw error;
+ }
+ }
+
+ // Stop an MCP server
+ async stopServer(serverId: string): Promise<void> {
+ try {
+ const client = this.clients.get(serverId);
+ if (client) {
+ await client.disconnect();
+ this.clients.delete(serverId);
+ }
+
+ await sqliteService.updateMCPServerStatus(serverId, 'stopped');
+ console.log(`[MCPManager] Server ${serverId} stopped`);
+ } catch (error) {
+ console.error(`[MCPManager] Error stopping server ${serverId}:`, error);
+ throw error;
+ }
+ }
+
+ // Remove an MCP server
+ async removeServer(serverId: string): Promise<void> {
+ try {
+ // Stop if running
+ await this.stopServer(serverId);
+
+ // Remove from database
+ await sqliteService.deleteMCPServer(serverId);
+
+ console.log(`[MCPManager] Server ${serverId} removed`);
+ } catch (error) {
+ console.error(`[MCPManager] Error removing server ${serverId}:`, error);
+ throw error;
+ }
+ }
+
+ // Get all servers with stats
+ async getServersWithStats(): Promise<MCPServerWithStats[]> {
+ const servers = await sqliteService.getMCPServers();
+
+ const serversWithStats = await Promise.all(
+ servers.map(async (server) => {
+ const stats = await sqliteService.getMCPServerStats(server.id);
+ return {
+ ...server,
+ args: JSON.parse(server.args),
+ env: server.env ? JSON.parse(server.env) : undefined,
+ status: (server.status as 'running' | 'stopped' | 'error'),
+ toolCount: stats.toolCount,
+ callsToday: stats.callsToday,
+ lastUsed: stats.lastUsed || undefined
+ };
+ })
+ );
+
+ return serversWithStats as MCPServerWithStats[];
+ }
+
+ // Get all available tools from all running servers
+ async getAllTools(): Promise<Array<MCPTool & { serverId: string; serverName: string }>> {
+ const allTools: Array<MCPTool & { serverId: string; serverName: string }> = [];
+
+ for (const [serverId, client] of this.clients.entries()) {
+ if (client.isConnected()) {
+ try {
+ const tools = await client.listTools();
+ const server = await sqliteService.getMCPServer(serverId);
+
+ const enrichedTools = tools.map(tool => ({
+ ...tool,
+ serverId,
+ serverName: server?.name || serverId
+ }));
+
+ allTools.push(...enrichedTools);
+ } catch (error) {
+ console.error(`[MCPManager] Error getting tools from ${serverId}:`, error);
+ }
+ }
+ }
+
+ return allTools;
+ }
+
+ // Call a tool on a specific server
+ async callTool(
+ serverId: string,
+ toolName: string,
+ args: Record<string, any> = {}
+ ): Promise<any> {
+ const client = this.clients.get(serverId);
+
+ if (!client || !client.isConnected()) {
+ throw new Error(`Server ${serverId} is not connected`);
+ }
+
+ const startTime = Date.now();
+
+ try {
+ const result = await client.callTool(toolName, args);
+ const executionTime = Date.now() - startTime;
+
+ // Log usage
+ await sqliteService.logMCPToolUsage({
+ serverId,
+ toolName,
+ args: JSON.stringify(args),
+ result: JSON.stringify(result),
+ success: !result.isError,
+ executionTime
+ });
+
+ return result;
+ } catch (error) {
+ const executionTime = Date.now() - startTime;
+
+ // Log error
+ await sqliteService.logMCPToolUsage({
+ serverId,
+ toolName,
+ args: JSON.stringify(args),
+ result: null,
+ success: false,
+ executionTime,
+ error: error instanceof Error ? error.message : 'Unknown error'
+ });
+
+ throw error;
+ }
+ }
+
+ // Update server configuration
+ async updateServerConfig(
+ serverId: string,
+ updates: {
+ env?: Record<string, string>;
+ enabled?: boolean;
+ auto_start?: boolean;
+ }
+ ): Promise<void> {
+ await sqliteService.updateMCPServerConfig(serverId, updates);
+
+ // If server is running and env changed, restart it
+ if (updates.env && this.clients.has(serverId)) {
+ await this.stopServer(serverId);
+ if (updates.enabled !== false) {
+ await this.startServer(serverId);
+ }
+ }
+ }
+
+ // Start all enabled servers
+ async startAllEnabledServers(): Promise<void> {
+ const servers = await sqliteService.getMCPServers();
+ const enabledServers = servers.filter(s => s.enabled);
+
+ console.log(`[MCPManager] Starting ${enabledServers.length} enabled servers`);
+
+ for (const server of enabledServers) {
+ try {
+ await this.startServer(server.id);
+ } catch (error) {
+ console.error(`[MCPManager] Failed to start ${server.name}:`, error);
+ }
+ }
+ }
+
+ // Start auto-start enabled servers on launch
+ async startAutoStartServers(): Promise<void> {
+ try {
+ const autoStartServers = await sqliteService.getAutoStartServers();
+
+ console.log(`[MCPManager] Auto-starting ${autoStartServers.length} servers`);
+
+ for (const server of autoStartServers) {
+ try {
+ await this.startServer(server.id);
+ console.log(`[MCPManager] Auto-started: ${server.name}`);
+ } catch (error) {
+ console.error(`[MCPManager] Failed to auto-start ${server.name}:`, error);
+ }
+ }
+ } catch (error) {
+ console.error('[MCPManager] Error during auto-start:', error);
+ }
+ }
+
+ // Stop all servers
+ async stopAllServers(): Promise<void> {
+ const serverIds = Array.from(this.clients.keys());
+
+ for (const serverId of serverIds) {
+ try {
+ await this.stopServer(serverId);
+ } catch (error) {
+ console.error(`[MCPManager] Error stopping ${serverId}:`, error);
+ }
+ }
+ }
+
+ // Health check - ping all servers periodically with automatic restart
+ private startHealthCheck(): void {
+ if (this.healthCheckInterval) {
+ clearInterval(this.healthCheckInterval);
+ }
+
+ this.healthCheckInterval = setInterval(async () => {
+ for (const [serverId, client] of this.clients.entries()) {
+ try {
+ const isAlive = await client.ping();
+
+ if (!isAlive) {
+ console.warn(`[MCPManager] Server ${serverId} is not responding`);
+
+ // Get server config to check if we should auto-restart
+ const server = await sqliteService.getMCPServer(serverId);
+
+ if (server && server.enabled) {
+ const errorInfo = this.serverErrors.get(serverId) || { count: 0, lastError: '', lastErrorTime: 0 };
+
+ // Only attempt restart if we haven't exceeded max retries (3)
+ if (errorInfo.count < 3) {
+ console.log(`[MCPManager] Attempting automatic restart of ${serverId} (attempt ${errorInfo.count + 1}/3)`);
+
+ try {
+ // Stop and restart
+ await this.stopServer(serverId);
+ await this.startServer(serverId);
+ console.log(`[MCPManager] Successfully restarted ${serverId}`);
+ } catch (restartError) {
+ console.error(`[MCPManager] Failed to restart ${serverId}:`, restartError);
+ }
+ } else {
+ console.error(`[MCPManager] Server ${serverId} exceeded max restart attempts (3)`);
+ await sqliteService.updateMCPServerStatus(serverId, 'error');
+ }
+ } else {
+ await sqliteService.updateMCPServerStatus(serverId, 'error');
+ }
+ } else {
+ // Server is healthy, clear any error tracking
+ if (this.serverErrors.has(serverId)) {
+ this.serverErrors.delete(serverId);
+ }
+ }
+ } catch (error) {
+ console.error(`[MCPManager] Health check failed for ${serverId}:`, error);
+
+ // Track the error
+ const errorMsg = error instanceof Error ? error.message : 'Unknown error';
+ const existing = this.serverErrors.get(serverId) || { count: 0, lastError: '', lastErrorTime: 0 };
+ this.serverErrors.set(serverId, {
+ count: existing.count + 1,
+ lastError: errorMsg,
+ lastErrorTime: Date.now()
+ });
+ }
+ }
+ }, 30000); // Check every 30 seconds
+ }
+
+ // Get server health info
+ getServerHealthInfo(serverId: string): { errorCount: number; lastError?: string; lastErrorTime?: number } | null {
+ const errorInfo = this.serverErrors.get(serverId);
+ if (!errorInfo) return null;
+
+ return {
+ errorCount: errorInfo.count,
+ lastError: errorInfo.lastError,
+ lastErrorTime: errorInfo.lastErrorTime
+ };
+ }
+
+ // Clear error tracking for a server
+ clearServerErrors(serverId: string): void {
+ this.serverErrors.delete(serverId);
+ }
+
+ // Cleanup
+ async cleanup(): Promise<void> {
+ if (this.healthCheckInterval) {
+ clearInterval(this.healthCheckInterval);
+ this.healthCheckInterval = null;
+ }
+
+ await this.stopAllServers();
+ }
+}
+
+// Singleton instance
+export const mcpManager = new MCPManager();
diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.ts
index 3574daf1f..710fa6cae 100644
--- a/fincept-terminal-desktop/src/services/sqliteService.ts
+++ b/fincept-terminal-desktop/src/services/sqliteService.ts
@@ -204,11 +204,62 @@ class SQLiteService {
)
`);
+ // MCP servers table
+ await this.db.execute(`
+ CREATE TABLE IF NOT EXISTS mcp_servers (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ description TEXT,
+ command TEXT NOT NULL,
+ args TEXT NOT NULL,
+ env TEXT,
+ category TEXT,
+ icon TEXT,
+ enabled INTEGER DEFAULT 1,
+ auto_start INTEGER DEFAULT 0,
+ status TEXT DEFAULT 'stopped',
+ created_at TEXT DEFAULT (datetime('now')),
+ updated_at TEXT DEFAULT (datetime('now'))
+ )
+ `);
+
+ // MCP tools cache table
+ await this.db.execute(`
+ CREATE TABLE IF NOT EXISTS mcp_tools (
+ id TEXT PRIMARY KEY,
+ server_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ description TEXT,
+ input_schema TEXT,
+ created_at TEXT DEFAULT (datetime('now')),
+ FOREIGN KEY (server_id) REFERENCES mcp_servers(id) ON DELETE CASCADE
+ )
+ `);
+
+ // MCP tool usage logs
+ await this.db.execute(`
+ CREATE TABLE IF NOT EXISTS mcp_tool_usage (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ server_id TEXT NOT NULL,
+ tool_name TEXT NOT NULL,
+ args TEXT,
+ result TEXT,
+ success INTEGER,
+ execution_time INTEGER,
+ error TEXT,
+ timestamp TEXT DEFAULT (datetime('now')),
+ FOREIGN KEY (server_id) REFERENCES mcp_servers(id) ON DELETE CASCADE
+ )
+ `);
+
// Create indexes
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_credentials_service ON credentials(service_name)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_settings_category ON settings(category)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_messages_session ON chat_messages(session_uuid)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_sessions_updated ON chat_sessions(updated_at DESC)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_mcp_tools_server ON mcp_tools(server_id)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_mcp_usage_server ON mcp_tool_usage(server_id)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_mcp_usage_timestamp ON mcp_tool_usage(timestamp DESC)`);
}
private async seedDefaultSettings(): Promise<void> {
@@ -614,6 +665,334 @@ class SQLiteService {
await this.close();
await this.initialize();
}
+
+ // ==================== MCP SERVER METHODS ====================
+
+ /**
+ * Add a new MCP server
+ */
+ async addMCPServer(server: {
+ id: string;
+ name: string;
+ description: string;
+ command: string;
+ args: string;
+ env?: string | null;
+ category: string;
+ icon: string;
+ enabled: boolean;
+ auto_start?: boolean;
+ }): Promise<void> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ await this.db.execute(
+ `INSERT INTO mcp_servers (id, name, description, command, args, env, category, icon, enabled, auto_start, status)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'stopped')`,
+ [server.id, server.name, server.description, server.command, server.args, server.env, server.category, server.icon, server.enabled ? 1 : 0, server.auto_start ? 1 : 0]
+ );
+ }
+
+ /**
+ * Get all MCP servers
+ */
+ async getMCPServers(): Promise<Array<{
+ id: string;
+ name: string;
+ description: string;
+ command: string;
+ args: string;
+ env: string | null;
+ category: string;
+ icon: string;
+ enabled: boolean;
+ auto_start: boolean;
+ status: string;
+ created_at: string;
+ updated_at: string;
+ }>> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const servers = await this.db.select<Array<any>>(
+ 'SELECT * FROM mcp_servers ORDER BY created_at DESC'
+ );
+
+ return servers.map(s => ({
+ ...s,
+ enabled: s.enabled === 1,
+ auto_start: s.auto_start === 1
+ }));
+ }
+
+ /**
+ * Get a single MCP server by ID
+ */
+ async getMCPServer(id: string): Promise<{
+ id: string;
+ name: string;
+ description: string;
+ command: string;
+ args: string;
+ env: string | null;
+ category: string;
+ icon: string;
+ enabled: boolean;
+ auto_start: boolean;
+ status: string;
+ created_at: string;
+ updated_at: string;
+ } | null> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const servers = await this.db.select<Array<any>>(
+ 'SELECT * FROM mcp_servers WHERE id = $1',
+ [id]
+ );
+
+ if (servers.length === 0) return null;
+
+ return {
+ ...servers[0],
+ enabled: servers[0].enabled === 1,
+ auto_start: servers[0].auto_start === 1
+ };
+ }
+
+ /**
+ * Update MCP server status
+ */
+ async updateMCPServerStatus(id: string, status: string): Promise<void> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ await this.db.execute(
+ `UPDATE mcp_servers SET status = $1, updated_at = datetime('now') WHERE id = $2`,
+ [status, id]
+ );
+ }
+
+ /**
+ * Update MCP server configuration
+ */
+ async updateMCPServerConfig(id: string, updates: {
+ env?: Record<string, string>;
+ enabled?: boolean;
+ auto_start?: boolean;
+ }): Promise<void> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const sets: string[] = [];
+ const values: any[] = [];
+
+ if (updates.env !== undefined) {
+ sets.push('env = $' + (values.length + 1));
+ values.push(JSON.stringify(updates.env));
+ }
+
+ if (updates.enabled !== undefined) {
+ sets.push('enabled = $' + (values.length + 1));
+ values.push(updates.enabled ? 1 : 0);
+ }
+
+ if (updates.auto_start !== undefined) {
+ sets.push('auto_start = $' + (values.length + 1));
+ values.push(updates.auto_start ? 1 : 0);
+ }
+
+ if (sets.length > 0) {
+ sets.push('updated_at = datetime(\'now\')');
+ values.push(id);
+
+ await this.db.execute(
+ `UPDATE mcp_servers SET ${sets.join(', ')} WHERE id = $${values.length}`,
+ values
+ );
+ }
+ }
+
+ /**
+ * Delete MCP server
+ */
+ async deleteMCPServer(id: string): Promise<void> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ await this.db.execute('DELETE FROM mcp_servers WHERE id = $1', [id]);
+ }
+
+ /**
+ * Get all auto-start enabled servers
+ */
+ async getAutoStartServers(): Promise<Array<{
+ id: string;
+ name: string;
+ description: string;
+ command: string;
+ args: string;
+ env: string | null;
+ category: string;
+ icon: string;
+ enabled: boolean;
+ auto_start: boolean;
+ status: string;
+ }>> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const servers = await this.db.select<Array<any>>(
+ 'SELECT * FROM mcp_servers WHERE auto_start = 1 AND enabled = 1'
+ );
+
+ return servers.map(s => ({
+ ...s,
+ enabled: s.enabled === 1,
+ auto_start: s.auto_start === 1
+ }));
+ }
+
+ /**
+ * Cache tools for an MCP server
+ */
+ async cacheMCPTools(serverId: string, tools: Array<{
+ name: string;
+ description?: string;
+ inputSchema: any;
+ }>): Promise<void> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ // Delete existing tools for this server
+ await this.db.execute('DELETE FROM mcp_tools WHERE server_id = $1', [serverId]);
+
+ // Insert new tools
+ for (const tool of tools) {
+ const toolId = `${serverId}__${tool.name}`;
+ await this.db.execute(
+ `INSERT INTO mcp_tools (id, server_id, name, description, input_schema)
+ VALUES ($1, $2, $3, $4, $5)`,
+ [toolId, serverId, tool.name, tool.description || '', JSON.stringify(tool.inputSchema)]
+ );
+ }
+ }
+
+ /**
+ * Get all cached MCP tools
+ */
+ async getMCPTools(): Promise<Array<{
+ id: string;
+ server_id: string;
+ name: string;
+ description: string;
+ input_schema: string;
+ created_at: string;
+ }>> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ return await this.db.select<Array<any>>(
+ 'SELECT * FROM mcp_tools ORDER BY server_id, name'
+ );
+ }
+
+ /**
+ * Get tools for a specific server
+ */
+ async getMCPToolsForServer(serverId: string): Promise<Array<{
+ id: string;
+ server_id: string;
+ name: string;
+ description: string;
+ input_schema: string;
+ created_at: string;
+ }>> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ return await this.db.select<Array<any>>(
+ 'SELECT * FROM mcp_tools WHERE server_id = $1 ORDER BY name',
+ [serverId]
+ );
+ }
+
+ /**
+ * Log MCP tool usage
+ */
+ async logMCPToolUsage(log: {
+ serverId: string;
+ toolName: string;
+ args: string;
+ result: string | null;
+ success: boolean;
+ executionTime: number;
+ error?: string;
+ }): Promise<void> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ await this.db.execute(
+ `INSERT INTO mcp_tool_usage (server_id, tool_name, args, result, success, execution_time, error)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,
+ [log.serverId, log.toolName, log.args, log.result, log.success ? 1 : 0, log.executionTime, log.error || null]
+ );
+ }
+
+ /**
+ * Get MCP server statistics
+ */
+ async getMCPServerStats(serverId: string): Promise<{
+ toolCount: number;
+ callsToday: number;
+ lastUsed: string | null;
+ }> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ // Get tool count
+ const toolCountResult = await this.db.select<Array<{ count: number }>>(
+ 'SELECT COUNT(*) as count FROM mcp_tools WHERE server_id = $1',
+ [serverId]
+ );
+
+ // Get calls today
+ const callsTodayResult = await this.db.select<Array<{ count: number }>>(
+ `SELECT COUNT(*) as count FROM mcp_tool_usage
+ WHERE server_id = $1 AND date(timestamp) = date('now')`,
+ [serverId]
+ );
+
+ // Get last used
+ const lastUsedResult = await this.db.select<Array<{ timestamp: string | null }>>(
+ `SELECT timestamp FROM mcp_tool_usage
+ WHERE server_id = $1
+ ORDER BY timestamp DESC
+ LIMIT 1`,
+ [serverId]
+ );
+
+ return {
+ toolCount: toolCountResult[0]?.count || 0,
+ callsToday: callsTodayResult[0]?.count || 0,
+ lastUsed: lastUsedResult[0]?.timestamp || null
+ };
+ }
+
+ /**
+ * Get recent MCP tool usage logs
+ */
+ async getMCPToolUsageLogs(limit: number = 50): Promise<Array<{
+ id: number;
+ server_id: string;
+ tool_name: string;
+ args: string;
+ result: string;
+ success: boolean;
+ execution_time: number;
+ error: string | null;
+ timestamp: string;
+ }>> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const logs = await this.db.select<Array<any>>(
+ 'SELECT * FROM mcp_tool_usage ORDER BY timestamp DESC LIMIT $1',
+ [limit]
+ );
+
+ return logs.map(log => ({
+ ...log,
+ success: log.success === 1
+ }));
+ }
}
// Singleton instance
diff --git a/fincept-terminal-desktop/src/services/tickerStorageService.ts b/fincept-terminal-desktop/src/services/tickerStorageService.ts
new file mode 100644
index 000000000..c68264140
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/tickerStorageService.ts
@@ -0,0 +1,239 @@
+// Ticker Storage Service - localStorage-based user preferences
+// Stores user's custom ticker lists, panel arrangements, and watchlists
+
+export interface TickerList {
+ category: string;
+ tickers: string[];
+}
+
+export interface RegionalTickerList {
+ region: string;
+ tickers: Array<{ symbol: string; name: string }>;
+}
+
+export interface UserMarketPreferences {
+ globalMarkets: TickerList[];
+ regionalMarkets: RegionalTickerList[];
+ lastUpdated: number;
+}
+
+const STORAGE_KEY = 'fincept_market_preferences';
+
+// Default tickers matching original static data
+const DEFAULT_PREFERENCES: UserMarketPreferences = {
+ globalMarkets: [
+ {
+ category: 'Stock Indices',
+ tickers: ['^GSPC', '^IXIC', '^DJI', '^RUT', '^VIX', '^FTSE', '^GDAXI', '^N225', '^FCHI', '^HSI']
+ },
+ {
+ category: 'Forex',
+ tickers: ['EURUSD=X', 'GBPUSD=X', 'JPY=X', 'CHF=X', 'CAD=X', 'AUDUSD=X', 'NZDUSD=X', 'EURGBP=X', 'EURJPY=X', 'GBPJPY=X']
+ },
+ {
+ category: 'Commodities',
+ tickers: ['GC=F', 'SI=F', 'CL=F', 'BZ=F', 'NG=F', 'HG=F', 'PL=F', 'PA=F', 'ZW=F', 'ZC=F']
+ },
+ {
+ category: 'Bonds',
+ tickers: ['^TNX', '^TYX', '^IRX', 'DE10Y=X', 'GB10Y=X', 'JP10Y=X', 'FR10Y=X', 'IT10Y=X', 'ES10Y=X', 'CA10Y=X']
+ },
+ {
+ category: 'ETFs',
+ tickers: ['SPY', 'QQQ', 'DIA', 'EEM', 'GLD', 'XLK', 'XLE', 'XLF', 'XLV', 'VNQ']
+ },
+ {
+ category: 'Cryptocurrencies',
+ tickers: ['BTC-USD', 'ETH-USD', 'BNB-USD', 'SOL-USD', 'DOGE-USD', 'MATIC-USD', 'LINK-USD', 'ADA-USD', 'DOT-USD', 'AVAX-USD']
+ }
+ ],
+ regionalMarkets: [
+ {
+ region: 'India',
+ tickers: [
+ { symbol: 'RELIANCE.NS', name: 'Reliance Industries' },
+ { symbol: 'TCS.NS', name: 'Tata Consultancy' },
+ { symbol: 'HDFCBANK.NS', name: 'HDFC Bank' },
+ { symbol: 'INFY.NS', name: 'Infosys' },
+ { symbol: 'HINDUNILVR.NS', name: 'Hindustan Unilever' },
+ { symbol: 'ICICIBANK.NS', name: 'ICICI Bank' },
+ { symbol: 'SBIN.NS', name: 'State Bank of India' },
+ { symbol: 'BHARTIARTL.NS', name: 'Bharti Airtel' }
+ ]
+ },
+ {
+ region: 'China',
+ tickers: [
+ { symbol: 'BABA', name: 'Alibaba Group' },
+ { symbol: 'PDD', name: 'PDD Holdings' },
+ { symbol: 'JD', name: 'JD.com' },
+ { symbol: 'BIDU', name: 'Baidu' },
+ { symbol: 'TCEHY', name: 'Tencent Holdings' },
+ { symbol: 'NIO', name: 'NIO Inc' },
+ { symbol: 'LI', name: 'Li Auto' },
+ { symbol: 'XPEV', name: 'XPeng' }
+ ]
+ },
+ {
+ region: 'United States',
+ tickers: [
+ { symbol: 'AAPL', name: 'Apple Inc' },
+ { symbol: 'MSFT', name: 'Microsoft Corp' },
+ { symbol: 'GOOGL', name: 'Alphabet Inc' },
+ { symbol: 'AMZN', name: 'Amazon.com' },
+ { symbol: 'NVDA', name: 'NVIDIA Corp' },
+ { symbol: 'META', name: 'Meta Platforms' },
+ { symbol: 'TSLA', name: 'Tesla Inc' },
+ { symbol: 'JPM', name: 'JPMorgan Chase' }
+ ]
+ }
+ ],
+ lastUpdated: Date.now()
+};
+
+class TickerStorageService {
+ /**
+ * Load user preferences from localStorage
+ */
+ loadPreferences(): UserMarketPreferences {
+ try {
+ const stored = localStorage.getItem(STORAGE_KEY);
+ if (stored) {
+ const parsed = JSON.parse(stored);
+ return parsed;
+ }
+ } catch (error) {
+ console.error('[TickerStorage] Failed to load preferences:', error);
+ }
+
+ // Return defaults if nothing stored or error
+ return DEFAULT_PREFERENCES;
+ }
+
+ /**
+ * Save user preferences to localStorage
+ */
+ savePreferences(preferences: UserMarketPreferences): boolean {
+ try {
+ preferences.lastUpdated = Date.now();
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(preferences));
+ return true;
+ } catch (error) {
+ console.error('[TickerStorage] Failed to save preferences:', error);
+ return false;
+ }
+ }
+
+ /**
+ * Get tickers for a specific category
+ */
+ getCategoryTickers(category: string): string[] {
+ const prefs = this.loadPreferences();
+ const found = prefs.globalMarkets.find(m => m.category === category);
+ return found?.tickers || [];
+ }
+
+ /**
+ * Update tickers for a specific category
+ */
+ updateCategoryTickers(category: string, tickers: string[]): boolean {
+ const prefs = this.loadPreferences();
+ const index = prefs.globalMarkets.findIndex(m => m.category === category);
+
+ if (index !== -1) {
+ prefs.globalMarkets[index].tickers = tickers;
+ return this.savePreferences(prefs);
+ }
+
+ return false;
+ }
+
+ /**
+ * Add ticker to category
+ */
+ addTickerToCategory(category: string, ticker: string): boolean {
+ const tickers = this.getCategoryTickers(category);
+ if (!tickers.includes(ticker)) {
+ tickers.push(ticker);
+ return this.updateCategoryTickers(category, tickers);
+ }
+ return false;
+ }
+
+ /**
+ * Remove ticker from category
+ */
+ removeTickerFromCategory(category: string, ticker: string): boolean {
+ const tickers = this.getCategoryTickers(category);
+ const filtered = tickers.filter(t => t !== ticker);
+ if (filtered.length !== tickers.length) {
+ return this.updateCategoryTickers(category, filtered);
+ }
+ return false;
+ }
+
+ /**
+ * Reorder tickers in category
+ */
+ reorderCategoryTickers(category: string, fromIndex: number, toIndex: number): boolean {
+ const tickers = this.getCategoryTickers(category);
+ const [removed] = tickers.splice(fromIndex, 1);
+ tickers.splice(toIndex, 0, removed);
+ return this.updateCategoryTickers(category, tickers);
+ }
+
+ /**
+ * Get regional market tickers
+ */
+ getRegionalTickers(region: string): Array<{ symbol: string; name: string }> {
+ const prefs = this.loadPreferences();
+ const found = prefs.regionalMarkets.find(m => m.region === region);
+ return found?.tickers || [];
+ }
+
+ /**
+ * Update regional market tickers
+ */
+ updateRegionalTickers(region: string, tickers: Array<{ symbol: string; name: string }>): boolean {
+ const prefs = this.loadPreferences();
+ const index = prefs.regionalMarkets.findIndex(m => m.region === region);
+
+ if (index !== -1) {
+ prefs.regionalMarkets[index].tickers = tickers;
+ return this.savePreferences(prefs);
+ }
+
+ return false;
+ }
+
+ /**
+ * Reset to defaults
+ */
+ resetToDefaults(): boolean {
+ return this.savePreferences(DEFAULT_PREFERENCES);
+ }
+
+ /**
+ * Export preferences as JSON
+ */
+ exportPreferences(): string {
+ const prefs = this.loadPreferences();
+ return JSON.stringify(prefs, null, 2);
+ }
+
+ /**
+ * Import preferences from JSON
+ */
+ importPreferences(json: string): boolean {
+ try {
+ const parsed = JSON.parse(json);
+ return this.savePreferences(parsed);
+ } catch (error) {
+ console.error('[TickerStorage] Failed to import preferences:', error);
+ return false;
+ }
+ }
+}
+
+export const tickerStorage = new TickerStorageService();
+export default tickerStorage;
diff --git a/fincept-terminal-desktop/src/types/fyers-web-sdk-v3.d.ts b/fincept-terminal-desktop/src/types/fyers-web-sdk-v3.d.ts
new file mode 100644
index 000000000..b63828ea4
--- /dev/null
+++ b/fincept-terminal-desktop/src/types/fyers-web-sdk-v3.d.ts
@@ -0,0 +1,45 @@
+declare module 'fyers-web-sdk-v3' {
+ export class fyersModel {
+ constructor(config?: any);
+ setAccessToken(token: string): void;
+ get_profile(): Promise<any>;
+ get_funds(): Promise<any>;
+ get_holdings(): Promise<any>;
+ get_positions(): Promise<any>;
+ get_orders(): Promise<any>;
+ place_order(orderData: any): Promise<any>;
+ modify_order(orderData: any): Promise<any>;
+ cancel_order(orderId: string): Promise<any>;
+ get_quotes(symbols: any): Promise<any>;
+ get_market_depth(symbol: any): Promise<any>;
+ get_history(params: any): Promise<any>;
+ get_option_chain(params: any): Promise<any>;
+ }
+
+ export class fyersOrderSocket {
+ constructor(accessToken: string);
+ on(event: string, callback: (data: any) => void): void;
+ subscribe(channels: any[]): void;
+ unsubscribe(channels: any[]): void;
+ disconnect(): void;
+ autoreconnect(enable?: boolean): void;
+ orderUpdates: any;
+ tradeUpdates: any;
+ positionUpdates: any;
+ edis: any;
+ pricealerts: any;
+ }
+
+ export class fyersDataSocket {
+ constructor(accessToken: string);
+ on(event: string, callback: (data: any) => void): void;
+ subscribe(symbols: any[]): void;
+ unsubscribe(symbols: any[]): void;
+ disconnect(): void;
+ autoreconnect(enable?: boolean): void;
+ symbolData: any;
+ symbolUpdate: any;
+ ltpc: any;
+ depth: any;
+ }
+}