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.

Bug Fixes and Terminal Updates

tilakpatel22c04ab811ed96
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lock
index f4a4cd439..6873388c6 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.lock
+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock
@@ -314,230 +314,6 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
-[[package]]
-name = "aws-lc-fips-sys"
-version = "0.13.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "57900537c00a0565a35b63c4c281b372edfc9744b072fd4a3b414350a8f5ed48"
-dependencies = [
- "bindgen",
- "cc",
- "cmake",
- "dunce",
- "fs_extra",
- "regex",
-]
-
-[[package]]
-name = "aws-lc-rs"
-version = "1.15.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6a88aab2464f1f25453baa7a07c84c5b7684e274054ba06817f382357f77a288"
-dependencies = [
- "aws-lc-fips-sys",
- "aws-lc-sys",
- "untrusted 0.7.1",
- "zeroize",
-]
-
-[[package]]
-name = "aws-lc-sys"
-version = "0.35.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b45afffdee1e7c9126814751f88dddc747f41d91da16c9551a0f1e8a11e788a1"
-dependencies = [
- "bindgen",
- "cc",
- "cmake",
- "dunce",
- "fs_extra",
-]
-
-[[package]]
-name = "barter"
-version = "0.12.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1f6f4af2344d85f3e29ceb5baf06da4939439c18677c7633bd3c5229eb78a294"
-dependencies = [
- "barter-data",
- "barter-execution",
- "barter-instrument 0.3.1",
- "barter-integration 0.9.2",
- "chrono",
- "derive_more 2.1.1",
- "fnv",
- "futures",
- "indexmap 2.12.1",
- "itertools 0.14.0",
- "parking_lot",
- "pin-project",
- "prettytable-rs",
- "rust_decimal",
- "serde",
- "smol_str",
- "thiserror 2.0.17",
- "tokio",
- "tracing",
- "tracing-subscriber",
-]
-
-[[package]]
-name = "barter-data"
-version = "0.10.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "56a1ded107462522a317d01b424422274f39c74251586d30da0aaae9a9283d1b"
-dependencies = [
- "async-trait",
- "barter-instrument 0.3.1",
- "barter-integration 0.9.2",
- "barter-macro",
- "chrono",
- "derive_more 2.1.1",
- "fnv",
- "futures",
- "futures-util",
- "itertools 0.14.0",
- "parking_lot",
- "reqwest 0.12.24",
- "rust_decimal",
- "serde",
- "serde_json",
- "smol_str",
- "thiserror 2.0.17",
- "tokio",
- "tokio-stream",
- "tracing",
- "url",
- "vecmap-rs",
-]
-
-[[package]]
-name = "barter-execution"
-version = "0.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f86006969d18c079ff518e238b1384ffd0b2aa1f7b9dc4ded4dfeb1f4c03aed"
-dependencies = [
- "barter-instrument 0.3.1",
- "barter-integration 0.9.2",
- "chrono",
- "derive_more 2.1.1",
- "fnv",
- "futures",
- "itertools 0.14.0",
- "rand 0.9.2",
- "rust_decimal",
- "serde",
- "smol_str",
- "thiserror 2.0.17",
- "tokio",
- "tokio-stream",
- "tracing",
-]
-
-[[package]]
-name = "barter-instrument"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "11115573d4b17f0e959c88c5a17f3c629ad440c287c4ad67c27b36862de409b0"
-dependencies = [
- "chrono",
- "derive_more 1.0.0",
- "rust_decimal",
- "serde",
- "smol_str",
- "thiserror 2.0.17",
-]
-
-[[package]]
-name = "barter-instrument"
-version = "0.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32a3e4913724dc60b05acb2713f108aee5816915022b028033e4017239a5a856"
-dependencies = [
- "chrono",
- "derive_more 2.1.1",
- "rust_decimal",
- "serde",
- "smol_str",
- "thiserror 2.0.17",
-]
-
-[[package]]
-name = "barter-integration"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4c12993f9b727b541907a51e81def20ecbd9a583f46ea62cd1d9a94f66e66f7d"
-dependencies = [
- "barter-instrument 0.2.0",
- "base64 0.22.1",
- "bytes",
- "chrono",
- "derive_more 1.0.0",
- "fnv",
- "futures",
- "hex",
- "hmac",
- "indexmap 2.12.1",
- "itertools 0.14.0",
- "pin-project",
- "reqwest 0.12.24",
- "serde",
- "serde_json",
- "serde_qs",
- "serde_urlencoded",
- "smol_str",
- "thiserror 2.0.17",
- "tokio",
- "tokio-stream",
- "tokio-tungstenite 0.26.2",
- "tracing",
- "url",
-]
-
-[[package]]
-name = "barter-integration"
-version = "0.9.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f4f546b963bd2804b841f811def8ef4799e96ce2a7964ae679c6bf57a8664cc6"
-dependencies = [
- "barter-instrument 0.3.1",
- "base64 0.22.1",
- "bytes",
- "chrono",
- "derive_more 2.1.1",
- "fnv",
- "futures",
- "hex",
- "hmac",
- "indexmap 2.12.1",
- "itertools 0.14.0",
- "pin-project",
- "reqwest 0.12.24",
- "serde",
- "serde_json",
- "serde_qs",
- "serde_urlencoded",
- "smol_str",
- "thiserror 2.0.17",
- "tokio",
- "tokio-stream",
- "tokio-tungstenite 0.26.2",
- "tracing",
- "url",
-]
-
-[[package]]
-name = "barter-macro"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "88be1956f371f12e22ac3fead3dc4e423a583ef2a8a5d143e66cda43eb598a95"
-dependencies = [
- "convert_case 0.6.0",
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
-
[[package]]
name = "base64"
version = "0.21.7"
@@ -550,46 +326,6 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
-[[package]]
-name = "bincode"
-version = "2.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740"
-dependencies = [
- "bincode_derive",
- "serde",
- "unty",
-]
-
-[[package]]
-name = "bincode_derive"
-version = "2.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf95709a440f45e986983918d0e8a1f30a9b1df04918fc828670606804ac3c09"
-dependencies = [
- "virtue",
-]
-
-[[package]]
-name = "bindgen"
-version = "0.72.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
-dependencies = [
- "bitflags 2.10.0",
- "cexpr",
- "clang-sys",
- "itertools 0.13.0",
- "log",
- "prettyplease",
- "proc-macro2",
- "quote",
- "regex",
- "rustc-hash",
- "shlex",
- "syn 2.0.111",
-]
-
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -770,15 +506,6 @@ dependencies = [
"bzip2-sys",
]
-[[package]]
-name = "bzip2"
-version = "0.6.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
-dependencies = [
- "libbz2-rs-sys",
-]
-
[[package]]
name = "bzip2-sys"
version = "0.1.13+1.0.8"
@@ -874,15 +601,6 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
-[[package]]
-name = "cexpr"
-version = "0.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
-dependencies = [
- "nom 7.1.3",
-]
-
[[package]]
name = "cfb"
version = "0.7.3"
@@ -940,26 +658,6 @@ dependencies = [
"inout",
]
-[[package]]
-name = "clang-sys"
-version = "1.8.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
-dependencies = [
- "glob",
- "libc",
- "libloading 0.8.9",
-]
-
-[[package]]
-name = "cmake"
-version = "0.1.57"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d"
-dependencies = [
- "cc",
-]
-
[[package]]
name = "combine"
version = "4.6.7"
@@ -991,24 +689,6 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
-[[package]]
-name = "convert_case"
-version = "0.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"
-dependencies = [
- "unicode-segmentation",
-]
-
-[[package]]
-name = "convert_case"
-version = "0.10.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
-dependencies = [
- "unicode-segmentation",
-]
-
[[package]]
name = "cookie"
version = "0.18.1"
@@ -1327,55 +1007,11 @@ version = "0.99.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f"
dependencies = [
- "convert_case 0.4.0",
- "proc-macro2",
- "quote",
- "rustc_version",
- "syn 2.0.111",
-]
-
-[[package]]
-name = "derive_more"
-version = "1.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4a9b99b9cbbe49445b21764dc0625032a89b145a2642e67603e1c936f5458d05"
-dependencies = [
- "derive_more-impl 1.0.0",
-]
-
-[[package]]
-name = "derive_more"
-version = "2.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
-dependencies = [
- "derive_more-impl 2.1.1",
-]
-
-[[package]]
-name = "derive_more-impl"
-version = "1.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.111",
- "unicode-xid",
-]
-
-[[package]]
-name = "derive_more-impl"
-version = "2.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
-dependencies = [
- "convert_case 0.10.0",
+ "convert_case",
"proc-macro2",
"quote",
"rustc_version",
"syn 2.0.111",
- "unicode-xid",
]
[[package]]
@@ -1407,16 +1043,6 @@ dependencies = [
"dirs-sys 0.5.0",
]
-[[package]]
-name = "dirs-next"
-version = "2.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1"
-dependencies = [
- "cfg-if",
- "dirs-sys-next",
-]
-
[[package]]
name = "dirs-sys"
version = "0.4.1"
@@ -1441,17 +1067,6 @@ dependencies = [
"windows-sys 0.61.2",
]
-[[package]]
-name = "dirs-sys-next"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d"
-dependencies = [
- "libc",
- "redox_users 0.4.6",
- "winapi",
-]
-
[[package]]
name = "dispatch"
version = "0.2.0"
@@ -1513,12 +1128,6 @@ dependencies = [
"syn 2.0.111",
]
-[[package]]
-name = "doctest-file"
-version = "1.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aac81fa3e28d21450aa4d2ac065992ba96a1d7303efbce51a95f4fd175b67562"
-
[[package]]
name = "document-features"
version = "0.2.12"
@@ -1596,12 +1205,6 @@ version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"
-[[package]]
-name = "encode_unicode"
-version = "1.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
-
[[package]]
name = "encoding_rs"
version = "0.8.35"
@@ -1749,11 +1352,6 @@ dependencies = [
"ahash 0.8.12",
"anyhow",
"async-trait",
- "barter",
- "barter-data",
- "barter-execution",
- "barter-instrument 0.3.1",
- "barter-integration 0.8.0",
"base64 0.22.1",
"chrono",
"csv",
@@ -1765,10 +1363,8 @@ dependencies = [
"futures-util",
"hashbrown 0.15.5",
"hex",
- "hftbacktest",
"hmac",
"indexmap 2.12.1",
- "interprocess",
"nix 0.29.0",
"once_cell",
"parking_lot",
@@ -1781,7 +1377,6 @@ dependencies = [
"rayon",
"regex",
"reqwest 0.11.27",
- "rmp-serde",
"rusqlite",
"rust_decimal",
"rust_decimal_macros",
@@ -1804,7 +1399,7 @@ dependencies = [
"tauri-plugin-updater",
"thiserror 2.0.17",
"tokio",
- "tokio-tungstenite 0.23.1",
+ "tokio-tungstenite",
"tracing",
"tracing-subscriber",
"url",
@@ -1827,7 +1422,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfe33edd8e85a12a67454e37f8c75e730830d83e313556ab9ebf9ee7fbeb3bfb"
dependencies = [
"crc32fast",
- "libz-rs-sys",
"miniz_oxide",
]
@@ -1894,12 +1488,6 @@ dependencies = [
"percent-encoding",
]
-[[package]]
-name = "fs_extra"
-version = "1.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
-
[[package]]
name = "funty"
version = "2.0.0"
@@ -2438,35 +2026,6 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
-[[package]]
-name = "hftbacktest"
-version = "0.9.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f8b0bec3c589d21814bee7c83680273e4395804bcd9a526dd5b90d44e808830"
-dependencies = [
- "anyhow",
- "aws-lc-rs",
- "bincode",
- "dyn-clone",
- "hftbacktest-derive",
- "nom 8.0.0",
- "thiserror 2.0.17",
- "tracing",
- "uuid",
- "zip 6.0.0",
-]
-
-[[package]]
-name = "hftbacktest-derive"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "978c23b263e4c484277771e97b8e8a431a3de609963c1a8216e7a9510390cfd1"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.111",
-]
-
[[package]]
name = "hmac"
version = "0.12.1"
@@ -2615,7 +2174,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
- "webpki-roots 1.0.4",
+ "webpki-roots",
]
[[package]]
@@ -2631,22 +2190,6 @@ dependencies = [
"tokio-native-tls",
]
-[[package]]
-name = "hyper-tls"
-version = "0.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
-dependencies = [
- "bytes",
- "http-body-util",
- "hyper 1.8.1",
- "hyper-util",
- "native-tls",
- "tokio",
- "tokio-native-tls",
- "tower-service",
-]
-
[[package]]
name = "hyper-util"
version = "0.1.19"
@@ -2856,21 +2399,6 @@ dependencies = [
"generic-array",
]
-[[package]]
-name = "interprocess"
-version = "2.2.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d941b405bd2322993887859a8ee6ac9134945a24ec5ec763a8a962fc64dfec2d"
-dependencies = [
- "doctest-file",
- "futures-core",
- "libc",
- "recvmsg",
- "tokio",
- "widestring",
- "windows-sys 0.52.0",
-]
-
[[package]]
name = "ipnet"
version = "2.11.0"
@@ -2896,17 +2424,6 @@ dependencies = [
"once_cell",
]
-[[package]]
-name = "is-terminal"
-version = "0.4.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
-dependencies = [
- "hermit-abi",
- "libc",
- "windows-sys 0.61.2",
-]
-
[[package]]
name = "is-wsl"
version = "0.4.0"
@@ -2917,24 +2434,6 @@ dependencies = [
"once_cell",
]
-[[package]]
-name = "itertools"
-version = "0.13.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
-dependencies = [
- "either",
-]
-
-[[package]]
-name = "itertools"
-version = "0.14.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
-dependencies = [
- "either",
-]
-
[[package]]
name = "itoa"
version = "1.0.15"
@@ -3081,12 +2580,6 @@ dependencies = [
"once_cell",
]
-[[package]]
-name = "libbz2-rs-sys"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2c4a545a15244c7d945065b5d392b2d2d7f21526fba56ce51467b06ed445e8f7"
-
[[package]]
name = "libc"
version = "0.2.178"
@@ -3135,15 +2628,6 @@ dependencies = [
"vcpkg",
]
-[[package]]
-name = "libz-rs-sys"
-version = "0.5.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c10501e7805cee23da17c7790e59df2870c0d4043ec6d03f67d31e2b53e77415"
-dependencies = [
- "zlib-rs",
-]
-
[[package]]
name = "linked-hash-map"
version = "0.5.6"
@@ -3216,16 +2700,6 @@ dependencies = [
"crc",
]
-[[package]]
-name = "lzma-rust2"
-version = "0.13.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c60a23ffb90d527e23192f1246b14746e2f7f071cb84476dd879071696c18a4a"
-dependencies = [
- "crc",
- "sha2",
-]
-
[[package]]
name = "lzma-sys"
version = "0.1.20"
@@ -3310,12 +2784,6 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
-[[package]]
-name = "minimal-lexical"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
-
[[package]]
name = "minisign-verify"
version = "0.2.4"
@@ -3448,25 +2916,6 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
-[[package]]
-name = "nom"
-version = "7.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
-dependencies = [
- "memchr",
- "minimal-lexical",
-]
-
-[[package]]
-name = "nom"
-version = "8.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
-dependencies = [
- "memchr",
-]
-
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
@@ -4241,12 +3690,6 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
-[[package]]
-name = "ppmd-rust"
-version = "1.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d558c559f0450f16f2a27a1f017ef38468c1090c9ce63c8e51366232d53717b4"
-
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -4262,30 +3705,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
-[[package]]
-name = "prettyplease"
-version = "0.2.37"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
-dependencies = [
- "proc-macro2",
- "syn 2.0.111",
-]
-
-[[package]]
-name = "prettytable-rs"
-version = "0.10.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eea25e07510aa6ab6547308ebe3c036016d162b8da920dbb079e3ba8acf3d95a"
-dependencies = [
- "csv",
- "encode_unicode",
- "is-terminal",
- "lazy_static",
- "term",
- "unicode-width",
-]
-
[[package]]
name = "printpdf"
version = "0.7.0"
@@ -4653,12 +4072,6 @@ dependencies = [
"crossbeam-utils",
]
-[[package]]
-name = "recvmsg"
-version = "1.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d3edd4d5d42c92f0a659926464d4cce56b562761267ecf0f469d85b7de384175"
-
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -4763,7 +4176,7 @@ dependencies = [
"http 0.2.12",
"http-body 0.4.6",
"hyper 0.14.32",
- "hyper-tls 0.5.0",
+ "hyper-tls",
"ipnet",
"js-sys",
"log",
@@ -4809,12 +4222,10 @@ dependencies = [
"http-body-util",
"hyper 1.8.1",
"hyper-rustls",
- "hyper-tls 0.6.0",
"hyper-util",
"js-sys",
"log",
"mime",
- "native-tls",
"percent-encoding",
"pin-project-lite",
"quinn",
@@ -4825,7 +4236,6 @@ dependencies = [
"serde_urlencoded",
"sync_wrapper 1.0.2",
"tokio",
- "tokio-native-tls",
"tokio-rustls",
"tokio-util",
"tower",
@@ -4836,7 +4246,7 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams",
"web-sys",
- "webpki-roots 1.0.4",
+ "webpki-roots",
]
[[package]]
@@ -4874,7 +4284,7 @@ dependencies = [
"cfg-if",
"getrandom 0.2.16",
"libc",
- "untrusted 0.9.0",
+ "untrusted",
"windows-sys 0.52.0",
]
@@ -4907,25 +4317,6 @@ dependencies = [
"syn 1.0.109",
]
-[[package]]
-name = "rmp"
-version = "0.8.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c"
-dependencies = [
- "num-traits",
-]
-
-[[package]]
-name = "rmp-serde"
-version = "1.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155"
-dependencies = [
- "rmp",
- "serde",
-]
-
[[package]]
name = "rusqlite"
version = "0.32.1"
@@ -5037,7 +4428,7 @@ checksum = "2ffdfa2f5286e2247234e03f680868ac2815974dc39e00ea15adc445d0aafe52"
dependencies = [
"ring",
"rustls-pki-types",
- "untrusted 0.9.0",
+ "untrusted",
]
[[package]]
@@ -5179,7 +4570,7 @@ checksum = "0c37578180969d00692904465fb7f6b3d50b9a2b952b87c23d0e2e5cb5013416"
dependencies = [
"bitflags 1.3.2",
"cssparser",
- "derive_more 0.99.20",
+ "derive_more",
"fxhash",
"log",
"phf 0.8.0",
@@ -5265,17 +4656,6 @@ dependencies = [
"serde_core",
]
-[[package]]
-name = "serde_qs"
-version = "0.13.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cd34f36fe4c5ba9654417139a9b3a20d2e1de6012ee678ad14d240c22c78d8d6"
-dependencies = [
- "percent-encoding",
- "serde",
- "thiserror 1.0.69",
-]
-
[[package]]
name = "serde_repr"
version = "0.1.20"
@@ -6232,17 +5612,6 @@ dependencies = [
"utf-8",
]
-[[package]]
-name = "term"
-version = "0.7.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c59df8ac95d96ff9bede18eb7300b0fda5e5d8d90960e76f8e14ae765eedbf1f"
-dependencies = [
- "dirs-next",
- "rustversion",
- "winapi",
-]
-
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -6397,18 +5766,6 @@ dependencies = [
"tokio",
]
-[[package]]
-name = "tokio-stream"
-version = "0.1.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047"
-dependencies = [
- "futures-core",
- "pin-project-lite",
- "tokio",
- "tokio-util",
-]
-
[[package]]
name = "tokio-tungstenite"
version = "0.23.1"
@@ -6420,25 +5777,7 @@ dependencies = [
"native-tls",
"tokio",
"tokio-native-tls",
- "tungstenite 0.23.0",
-]
-
-[[package]]
-name = "tokio-tungstenite"
-version = "0.26.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084"
-dependencies = [
- "futures-util",
- "log",
- "native-tls",
- "rustls",
- "rustls-pki-types",
- "tokio",
- "tokio-native-tls",
- "tokio-rustls",
- "tungstenite 0.26.2",
- "webpki-roots 0.26.11",
+ "tungstenite",
]
[[package]]
@@ -6733,27 +6072,6 @@ dependencies = [
"utf-8",
]
-[[package]]
-name = "tungstenite"
-version = "0.26.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"
-dependencies = [
- "bytes",
- "data-encoding",
- "http 1.4.0",
- "httparse",
- "log",
- "native-tls",
- "rand 0.9.2",
- "rustls",
- "rustls-pki-types",
- "sha1",
- "thiserror 2.0.17",
- "url",
- "utf-8",
-]
-
[[package]]
name = "typeid"
version = "1.0.3"
@@ -6830,18 +6148,6 @@ version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"
-[[package]]
-name = "unicode-width"
-version = "0.1.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
-
-[[package]]
-name = "unicode-xid"
-version = "0.2.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
-
[[package]]
name = "universal-hash"
version = "0.5.1"
@@ -6852,24 +6158,12 @@ dependencies = [
"subtle",
]
-[[package]]
-name = "untrusted"
-version = "0.7.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
-
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
-[[package]]
-name = "unty"
-version = "0.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae"
-
[[package]]
name = "url"
version = "2.5.7"
@@ -6937,12 +6231,6 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
-[[package]]
-name = "vecmap-rs"
-version = "0.2.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f9758649b51083aa8008666f41c23f05abca1766aad4cc447b195dd83ef1297b"
-
[[package]]
name = "version-compare"
version = "0.2.1"
@@ -6955,12 +6243,6 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
-[[package]]
-name = "virtue"
-version = "0.0.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "051eb1abcf10076295e815102942cc58f9d5e3b4560e46e53c21e8ff6f3af7b1"
-
[[package]]
name = "vswhom"
version = "0.1.0"
@@ -7216,15 +6498,6 @@ dependencies = [
"system-deps",
]
-[[package]]
-name = "webpki-roots"
-version = "0.26.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
-dependencies = [
- "webpki-roots 1.0.4",
-]
-
[[package]]
name = "webpki-roots"
version = "1.0.4"
@@ -7288,12 +6561,6 @@ dependencies = [
"winsafe",
]
-[[package]]
-name = "widestring"
-version = "1.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
-
[[package]]
name = "winapi"
version = "0.3.9"
@@ -8129,7 +7396,7 @@ checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"
dependencies = [
"aes",
"arbitrary",
- "bzip2 0.5.2",
+ "bzip2",
"constant_time_eq",
"crc32fast",
"crossbeam-utils",
@@ -8163,39 +7430,6 @@ dependencies = [
"memchr",
]
-[[package]]
-name = "zip"
-version = "6.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eb2a05c7c36fde6c09b08576c9f7fb4cda705990f73b58fe011abf7dfb24168b"
-dependencies = [
- "aes",
- "arbitrary",
- "bzip2 0.6.1",
- "constant_time_eq",
- "crc32fast",
- "deflate64",
- "flate2",
- "getrandom 0.3.4",
- "hmac",
- "indexmap 2.12.1",
- "lzma-rust2",
- "memchr",
- "pbkdf2",
- "ppmd-rust",
- "sha1",
- "time",
- "zeroize",
- "zopfli",
- "zstd",
-]
-
-[[package]]
-name = "zlib-rs"
-version = "0.5.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "40990edd51aae2c2b6907af74ffb635029d5788228222c4bb811e9351c0caad3"
-
[[package]]
name = "zopfli"
version = "0.8.3"
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.toml
index 60cae0cff..494bfcfbf 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.toml
+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml
@@ -54,8 +54,6 @@ printpdf = "0.7"
flate2 = "1.0" # For tar.gz extraction (macOS/Linux)
tar = "0.4" # For tar archive extraction
hashbrown = "0.15" # Faster HashMap alternative
-interprocess = { version = "2.2", features = ["tokio"] } # Unix domain sockets IPC
-rmp-serde = "1.3" # MessagePack serialization
ahash = "0.8" # Fast hashing for orderbook
smallvec = "1.13" # Stack-allocated vectors for small arrays
@@ -65,14 +63,7 @@ dashmap = "6" # Concurrent HashMap for subscriptions
url = "2" # URL parsing for WebSocket connections
async-trait = "0.1" # Async trait support
thiserror = "2" # Error handling
-hftbacktest = { version = "0.9.4", default-features = false, features = ["backtest"] }
-# Barter-rs ecosystem for live/paper trading
-barter = "0.12"
-barter-data = "0.10"
-barter-execution = "0.6"
-barter-instrument = "0.3"
-barter-integration = "0.8"
rust_decimal = "1.36"
rust_decimal_macros = "1.36"
smol_str = "0.3"
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/base/base_provider.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/base/base_provider.py
index dc0e16eff..4f0cabc71 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/base/base_provider.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/base/base_provider.py
@@ -417,10 +417,25 @@ def convert_keys_to_camel(data: Any) -> Any:
return data
+def _sanitize_for_json(obj):
+ """Recursively replace NaN/Infinity with None so json.dumps produces valid JSON."""
+ import math
+ if isinstance(obj, float):
+ if math.isnan(obj) or math.isinf(obj):
+ return None
+ return obj
+ if isinstance(obj, dict):
+ return {k: _sanitize_for_json(v) for k, v in obj.items()}
+ if isinstance(obj, (list, tuple)):
+ return [_sanitize_for_json(v) for v in obj]
+ return obj
+
+
def json_response(data: Any) -> str:
"""Convert data to JSON string for stdout output with camelCase keys"""
camel_data = convert_keys_to_camel(data)
- return json.dumps(camel_data, default=str, ensure_ascii=False)
+ sanitized = _sanitize_for_json(camel_data)
+ return json.dumps(sanitized, default=str, ensure_ascii=False)
def parse_json_input(json_str: str) -> Dict[str, Any]:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_indicators.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_indicators.py
index f6495175f..1c0bf2191 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_indicators.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_indicators.py
@@ -39,10 +39,10 @@ def calculate_ma(
vbt, close: np.ndarray, period: int, ewm: bool = False
) -> np.ndarray:
"""
- Calculate Moving Average using VBT.
+ Calculate Moving Average.
Args:
- vbt: vectorbt module
+ vbt: vectorbt module (unused, kept for API compatibility)
close: Price array
period: MA window
ewm: If True, use exponential weighting (EMA)
@@ -50,18 +50,20 @@ def calculate_ma(
Returns:
MA values array
"""
- result = vbt.MA.run(close, period, ewm=ewm)
- return result.ma.values.flatten()
+ s = pd.Series(close)
+ if ewm:
+ return s.ewm(span=period, adjust=False).mean().values
+ return s.rolling(window=period).mean().values
def calculate_mstd(
vbt, close: np.ndarray, period: int, ewm: bool = False
) -> np.ndarray:
"""
- Calculate Moving Standard Deviation using VBT.
+ Calculate Moving Standard Deviation.
Args:
- vbt: vectorbt module
+ vbt: vectorbt module (unused, kept for API compatibility)
close: Price array
period: Window size
ewm: Use exponential weighting
@@ -69,22 +71,25 @@ def calculate_mstd(
Returns:
MSTD values array
"""
- result = vbt.MSTD.run(close, period, ewm=ewm)
- return result.mstd.values.flatten()
+ s = pd.Series(close)
+ if ewm:
+ return s.ewm(span=period, adjust=False).std().values
+ return s.rolling(window=period).std().values
def calculate_bbands(
vbt, close: np.ndarray, period: int = 20, alpha: float = 2.0
) -> Dict[str, np.ndarray]:
"""
- Calculate Bollinger Bands using VBT.
+ Calculate Bollinger Bands.
Returns dict with: upper, middle, lower, bandwidth, percent_b
"""
- bb = vbt.BBANDS.run(close, window=period, alpha=alpha)
- upper = bb.upper.values.flatten()
- middle = bb.middle.values.flatten()
- lower = bb.lower.values.flatten()
+ s = pd.Series(close)
+ middle = s.rolling(window=period).mean().values
+ std = s.rolling(window=period).std().values
+ upper = middle + alpha * std
+ lower = middle - alpha * std
# Bandwidth = (upper - lower) / middle
bandwidth = np.where(middle > 0, (upper - lower) / middle, 0)
@@ -105,9 +110,16 @@ def calculate_bbands(
def calculate_rsi(
vbt, close: np.ndarray, period: int = 14
) -> np.ndarray:
- """Calculate RSI using VBT."""
- result = vbt.RSI.run(close, period)
- return result.rsi.values.flatten()
+ """Calculate RSI (Relative Strength Index)."""
+ s = pd.Series(close)
+ delta = s.diff()
+ gain = delta.where(delta > 0, 0.0)
+ loss = (-delta).where(delta < 0, 0.0)
+ avg_gain = gain.ewm(alpha=1.0 / period, min_periods=period, adjust=False).mean()
+ avg_loss = loss.ewm(alpha=1.0 / period, min_periods=period, adjust=False).mean()
+ rs = avg_gain / avg_loss.replace(0, np.nan)
+ rsi = 100.0 - (100.0 / (1.0 + rs))
+ return rsi.fillna(50.0).values
def calculate_stoch(
@@ -115,14 +127,22 @@ def calculate_stoch(
k_period: int = 14, d_period: int = 3
) -> Dict[str, np.ndarray]:
"""
- Calculate Stochastic Oscillator using VBT.
+ Calculate Stochastic Oscillator.
Returns dict with: k (fast), d (slow)
"""
- result = vbt.STOCH.run(high, low, close, k_window=k_period, d_window=d_period)
+ h = pd.Series(high)
+ l = pd.Series(low)
+ c = pd.Series(close)
+ lowest_low = l.rolling(window=k_period).min()
+ highest_high = h.rolling(window=k_period).max()
+ denom = highest_high - lowest_low
+ denom = denom.replace(0, np.nan)
+ percent_k = ((c - lowest_low) / denom * 100).fillna(50.0)
+ percent_d = percent_k.rolling(window=d_period).mean().fillna(50.0)
return {
- 'k': result.percent_k.values.flatten(),
- 'd': result.percent_d.values.flatten(),
+ 'k': percent_k.values,
+ 'd': percent_d.values,
}
@@ -131,18 +151,17 @@ def calculate_macd(
fast_period: int = 12, slow_period: int = 26, signal_period: int = 9
) -> Dict[str, np.ndarray]:
"""
- Calculate MACD using VBT.
+ Calculate MACD.
Returns dict with: macd, signal, histogram
"""
- result = vbt.MACD.run(
- close,
- fast_window=fast_period,
- slow_window=slow_period,
- signal_window=signal_period,
- )
- macd_vals = result.macd.values.flatten()
- signal_vals = result.signal.values.flatten()
+ s = pd.Series(close)
+ fast_ema = s.ewm(span=fast_period, adjust=False).mean()
+ slow_ema = s.ewm(span=slow_period, adjust=False).mean()
+ macd_line = fast_ema - slow_ema
+ signal_line = macd_line.ewm(span=signal_period, adjust=False).mean()
+ macd_vals = macd_line.values
+ signal_vals = signal_line.values
histogram = macd_vals - signal_vals
return {
@@ -157,31 +176,38 @@ def calculate_atr(
period: int = 14
) -> np.ndarray:
"""
- Calculate Average True Range using VBT.
+ Calculate Average True Range.
- Note: VBT's ATR requires OHLC. If only close available,
- we approximate high/low from close.
+ Note: If only close available, caller should approximate high/low from close.
"""
- result = vbt.ATR.run(high, low, close, window=period)
- return result.atr.values.flatten()
+ h = pd.Series(high)
+ l = pd.Series(low)
+ c = pd.Series(close)
+ prev_close = c.shift(1)
+ tr = pd.concat([
+ h - l,
+ (h - prev_close).abs(),
+ (l - prev_close).abs(),
+ ], axis=1).max(axis=1)
+ return tr.ewm(span=period, adjust=False).mean().values
def calculate_obv(
vbt, close: np.ndarray, volume: np.ndarray
) -> np.ndarray:
"""
- Calculate On-Balance Volume using VBT.
+ Calculate On-Balance Volume.
Args:
- vbt: vectorbt module
+ vbt: vectorbt module (unused, kept for API compatibility)
close: Price array
volume: Volume array
Returns:
OBV values array
"""
- result = vbt.OBV.run(close, volume)
- return result.obv.values.flatten()
+ direction = np.sign(np.diff(close, prepend=close[0]))
+ return np.cumsum(direction * volume)
# ============================================================================
@@ -379,11 +405,20 @@ def generate_crossover_signals(
"""
Generate entry/exit signals from indicator crossover.
- Entry: fast crosses above slow
- Exit: fast crosses below slow
- """
- entries = pd.Series(fast > slow, index=index)
- exits = pd.Series(fast < slow, index=index)
+ Entry: fast crosses above slow (was below, now above)
+ Exit: fast crosses below slow (was above, now below)
+ """
+ above = fast > slow
+ # Detect edges: cross-up where previous bar was not above and current is
+ cross_up = np.zeros(len(above), dtype=bool)
+ cross_down = np.zeros(len(above), dtype=bool)
+ for i in range(1, len(above)):
+ if above[i] and not above[i - 1]:
+ cross_up[i] = True
+ elif not above[i] and above[i - 1]:
+ cross_down[i] = True
+ entries = pd.Series(cross_up, index=index)
+ exits = pd.Series(cross_down, index=index)
return entries, exits
@@ -394,11 +429,20 @@ def generate_threshold_signals(
"""
Generate entry/exit signals from threshold crossings.
- Entry: indicator < lower threshold
- Exit: indicator > upper threshold
- """
- entries = pd.Series(indicator < lower, index=index)
- exits = pd.Series(indicator > upper, index=index)
+ Entry: indicator crosses below lower threshold
+ Exit: indicator crosses above upper threshold
+ """
+ below_lower = indicator < lower
+ above_upper = indicator > upper
+ cross_below = np.zeros(len(indicator), dtype=bool)
+ cross_above = np.zeros(len(indicator), dtype=bool)
+ for i in range(1, len(indicator)):
+ if below_lower[i] and not below_lower[i - 1]:
+ cross_below[i] = True
+ if above_upper[i] and not above_upper[i - 1]:
+ cross_above[i] = True
+ entries = pd.Series(cross_below, index=index)
+ exits = pd.Series(cross_above, index=index)
return entries, exits
@@ -427,11 +471,20 @@ def generate_mean_reversion_signals(
"""
Generate mean-reversion signals from Z-score.
- Entry: Z-score < -z_entry (oversold)
- Exit: Z-score > z_exit (mean reversion complete)
- """
- entries = pd.Series(zscore < -z_entry, index=index)
- exits = pd.Series(zscore > z_exit, index=index)
+ Entry: Z-score crosses below -z_entry (oversold)
+ Exit: Z-score crosses above z_exit (mean reversion complete)
+ """
+ below_entry = zscore < -z_entry
+ above_exit = zscore > z_exit
+ cross_below = np.zeros(len(zscore), dtype=bool)
+ cross_above = np.zeros(len(zscore), dtype=bool)
+ for i in range(1, len(zscore)):
+ if below_entry[i] and not below_entry[i - 1]:
+ cross_below[i] = True
+ if above_exit[i] and not above_exit[i - 1]:
+ cross_above[i] = True
+ entries = pd.Series(cross_below, index=index)
+ exits = pd.Series(cross_above, index=index)
return entries, exits
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_optimization.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_optimization.py
index 5d915f1c8..9a96943c3 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_optimization.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_optimization.py
@@ -267,8 +267,8 @@ def _run_vectorized_optimization(
- For indicator-based strategies, compute indicators once with broadcast parameters
- For each combination, build portfolio and extract objective metric
"""
- from . import vbt_strategies as strat
- from . import vbt_portfolio as pf
+ import vbt_strategies as strat
+ import vbt_portfolio as pf
results = []
@@ -363,8 +363,8 @@ def _evaluate_params(
initial_capital, request
) -> Dict[str, float]:
"""Evaluate a single parameter set and return performance metrics."""
- from . import vbt_strategies as strat
- from . import vbt_portfolio as pf
+ import vbt_strategies as strat
+ import vbt_portfolio as pf
try:
entries, exits = strat.build_strategy_signals(
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_portfolio.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_portfolio.py
index d73baeffc..202ada0a5 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_portfolio.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_portfolio.py
@@ -1,15 +1,18 @@
"""
VBT Portfolio Construction Module
-Covers all VectorBT Portfolio creation methods:
+Pure numpy/pandas portfolio simulator that produces objects compatible
+with the metrics module's expected interface (value(), total_return(),
+stats(), trades, final_value(), total_fees(), close).
+
+Covers:
- from_signals: Entry/exit boolean arrays
- from_orders: Direct order arrays (size, direction)
-- from_order_func: Custom order function (event-driven)
- from_holding: Buy-and-hold benchmark
- from_random_signals: Random entry/exit for statistical benchmarking
Also handles:
-- Stop-loss / Take-profit via VBT's built-in STX/OHLCSTX signal generators
+- Stop-loss / Take-profit
- Position sizing (fixed, kelly, volatility-targeted, fractional)
- Multi-asset portfolio construction
- Short selling support
@@ -18,7 +21,161 @@ Also handles:
import numpy as np
import pandas as pd
from typing import Dict, Any, Optional, Tuple
+from dataclasses import dataclass, field
+
+
+# ============================================================================
+# Simple Portfolio Object (compatible with vbt_metrics expectations)
+# ============================================================================
+
+class _TradesAccessor:
+ """Mimics vbt.Portfolio.trades for metrics extraction."""
+
+ def __init__(self, records_df: pd.DataFrame):
+ self._records = records_df
+
+ @property
+ def records_readable(self) -> pd.DataFrame:
+ return self._records
+ @property
+ def records(self):
+ return self._records
+
+
+class SimplePortfolio:
+ """
+ Lightweight portfolio object that exposes the same interface
+ consumed by vbt_metrics.py and vectorbt_provider.py.
+ """
+
+ def __init__(
+ self,
+ equity_series: pd.Series,
+ close_series: pd.Series,
+ trade_records: pd.DataFrame,
+ init_cash: float,
+ total_fees_value: float = 0.0,
+ freq: str = '1D',
+ ):
+ self._equity = equity_series
+ self._close = close_series
+ self._trade_records = trade_records
+ self._init_cash = init_cash
+ self._total_fees = total_fees_value
+ self._freq = freq
+ self._trades_accessor = _TradesAccessor(trade_records)
+ self._stats_cache = None
+
+ # --- Public interface expected by metrics / provider ---
+
+ def value(self) -> pd.Series:
+ return self._equity
+
+ @property
+ def close(self) -> pd.Series:
+ return self._close
+
+ def total_return(self) -> float:
+ if len(self._equity) < 2 or self._init_cash == 0:
+ return 0.0
+ return float(self._equity.iloc[-1] / self._init_cash - 1.0)
+
+ def final_value(self) -> float:
+ return float(self._equity.iloc[-1]) if len(self._equity) > 0 else self._init_cash
+
+ def total_fees(self) -> float:
+ return self._total_fees
+
+ @property
+ def trades(self):
+ return self._trades_accessor
+
+ def stats(self) -> Dict[str, Any]:
+ """Return a dict mimicking vbt.Portfolio.stats() keys."""
+ if self._stats_cache is not None:
+ return self._stats_cache
+
+ equity = self._equity.values.astype(float)
+ n = len(equity)
+ s = {}
+
+ # Total return
+ total_ret = self.total_return()
+ s['Total Return [%]'] = total_ret * 100
+
+ # Daily returns
+ if n > 1:
+ daily_ret = np.diff(equity) / np.where(equity[:-1] != 0, equity[:-1], 1.0)
+ daily_ret = daily_ret[np.isfinite(daily_ret)]
+ else:
+ daily_ret = np.array([])
+
+ # Annualized return
+ years = n / 252.0
+ if years > 0 and self._init_cash > 0 and equity[-1] > 0:
+ ann_ret = (equity[-1] / self._init_cash) ** (1 / years) - 1
+ else:
+ ann_ret = 0.0
+ s['Annualized Return [%]'] = ann_ret * 100
+
+ # Volatility
+ if len(daily_ret) > 1:
+ daily_std = float(np.std(daily_ret, ddof=1))
+ ann_vol = daily_std * np.sqrt(252)
+ else:
+ daily_std = 0.0
+ ann_vol = 0.0
+ s['Annualized Volatility [%]'] = ann_vol * 100
+
+ # Sharpe
+ if ann_vol > 1e-10:
+ s['Sharpe Ratio'] = ann_ret / ann_vol
+ else:
+ s['Sharpe Ratio'] = 0.0
+
+ # Sortino
+ if len(daily_ret) > 1:
+ neg = daily_ret[daily_ret < 0]
+ downside_std = float(np.std(neg, ddof=1)) * np.sqrt(252) if len(neg) > 1 else 0.0
+ else:
+ downside_std = 0.0
+ s['Sortino Ratio'] = ann_ret / downside_std if downside_std > 1e-10 else 0.0
+
+ # Max drawdown
+ peak = np.maximum.accumulate(equity)
+ dd = (equity - peak) / np.where(peak > 0, peak, 1.0)
+ max_dd = float(np.min(dd)) if len(dd) > 0 else 0.0
+ s['Max Drawdown [%]'] = max_dd * 100
+
+ # Calmar
+ s['Calmar Ratio'] = ann_ret / abs(max_dd) if abs(max_dd) > 1e-10 else 0.0
+
+ # Trade stats
+ records = self._trade_records
+ n_trades = len(records)
+ s['Total Trades'] = n_trades
+
+ if n_trades > 0 and 'PnL' in records.columns:
+ pnl = records['PnL'].values.astype(float)
+ pnl = pnl[np.isfinite(pnl)]
+ winners = pnl[pnl > 0]
+ losers = pnl[pnl <= 0]
+ s['Win Rate [%]'] = float(len(winners) / len(pnl) * 100) if len(pnl) > 0 else 0.0
+ total_wins = float(np.sum(winners)) if len(winners) > 0 else 0.0
+ total_losses = float(np.sum(np.abs(losers))) if len(losers) > 0 else 0.0
+ s['Profit Factor'] = total_wins / total_losses if total_losses > 0 else 0.0
+ else:
+ s['Win Rate [%]'] = 0.0
+ s['Profit Factor'] = 0.0
+
+ self._stats_cache = s
+ return s
+
+
+# ============================================================================
+# Portfolio Builders
+# ============================================================================
def build_portfolio(
vbt,
@@ -27,19 +184,12 @@ def build_portfolio(
exits: pd.Series,
initial_capital: float = 100000,
request: Optional[Dict[str, Any]] = None,
-) -> Any:
+) -> SimplePortfolio:
"""
- Build a VBT Portfolio from signals with full feature support.
-
- Handles:
- - Stop-loss / take-profit integration
- - Position sizing modes
- - Commission and slippage
- - Short selling
- - Frequency specification
+ Build a portfolio from entry/exit signals.
Args:
- vbt: vectorbt module reference
+ vbt: vectorbt module reference (unused, kept for API compat)
close_series: Price series (pd.Series with DatetimeIndex)
entries: Boolean entry signals
exits: Boolean exit signals
@@ -47,80 +197,71 @@ def build_portfolio(
request: Full request dict with advanced params
Returns:
- vbt.Portfolio instance
+ SimplePortfolio instance
"""
request = request or {}
- # Extract advanced parameters
commission = float(request.get('commission', 0.0))
slippage = float(request.get('slippage', 0.0))
- freq = request.get('frequency', '1D')
allow_short = request.get('allowShort', False)
- trade_on_close = request.get('tradeOnClose', True)
- # Position sizing
- position_sizing = request.get('positionSizing', {})
- size_mode = position_sizing.get('mode', 'fixed') if isinstance(position_sizing, dict) else 'fixed'
+ # Position sizing - handle both string ('fixed') and dict ({'mode': 'fixed', ...}) formats
+ position_sizing_raw = request.get('positionSizing', 'fixed')
+ if isinstance(position_sizing_raw, str):
+ size_mode = position_sizing_raw
+ position_sizing_params = {
+ 'mode': position_sizing_raw,
+ 'percentage': float(request.get('positionSizeValue', 1.0)) * 100,
+ }
+ elif isinstance(position_sizing_raw, dict):
+ size_mode = position_sizing_raw.get('mode', 'fixed')
+ position_sizing_params = position_sizing_raw
+ else:
+ size_mode = 'fixed'
+ position_sizing_params = {}
- # Stop-loss / Take-profit
+ # Stop-loss / Take-profit (filter out zero values which mean "disabled")
stop_loss = request.get('stopLoss', None)
take_profit = request.get('takeProfit', None)
trailing_stop = request.get('trailingStop', None)
-
- # Apply stop-loss/take-profit using VBT signal generators if available
+ if stop_loss is not None and float(stop_loss) == 0:
+ stop_loss = None
+ if take_profit is not None and float(take_profit) == 0:
+ take_profit = None
+ if trailing_stop is not None and float(trailing_stop) == 0:
+ trailing_stop = None
+
+ # Apply stop-loss/take-profit
if stop_loss or take_profit or trailing_stop:
entries, exits = _apply_exit_signals(
- vbt, close_series, entries, exits,
+ close_series, entries, exits,
stop_loss=stop_loss,
take_profit=take_profit,
trailing_stop=trailing_stop,
)
- # Calculate position size array
- size = _calculate_position_size(
- close_series, initial_capital, size_mode, position_sizing, entries
+ # Calculate position sizes
+ size_series = _calculate_position_size(
+ close_series, initial_capital, size_mode, position_sizing_params, entries
)
- # Build portfolio kwargs
- pf_kwargs = {
- 'close': close_series,
- 'entries': entries,
- 'exits': exits,
- 'init_cash': initial_capital,
- 'freq': freq,
- 'fees': commission,
- 'slippage': slippage,
- }
-
- # Add size if not default
- if size is not None:
- pf_kwargs['size'] = size
- pf_kwargs['size_type'] = 'amount'
-
- # Short selling support
- if allow_short:
- # Use short_entries/short_exits for short positions
- short_entries = exits.copy()
- short_exits = entries.copy()
- pf_kwargs['short_entries'] = short_entries
- pf_kwargs['short_exits'] = short_exits
-
- try:
- portfolio = vbt.Portfolio.from_signals(**pf_kwargs)
- except TypeError:
- # Fallback for older VBT versions without some params
- basic_kwargs = {
- 'close': close_series,
- 'entries': entries,
- 'exits': exits,
- 'init_cash': initial_capital,
- 'freq': freq,
- }
- if commission > 0:
- basic_kwargs['fees'] = commission
- portfolio = vbt.Portfolio.from_signals(**basic_kwargs)
+ # Simulate
+ equity, trade_records, total_fees = _simulate_signals(
+ close_series, entries, exits,
+ initial_capital=initial_capital,
+ commission=commission,
+ slippage=slippage,
+ size_series=size_series,
+ allow_short=allow_short,
+ )
- return portfolio
+ return SimplePortfolio(
+ equity_series=equity,
+ close_series=close_series,
+ trade_records=trade_records,
+ init_cash=initial_capital,
+ total_fees_value=total_fees,
+ )
def build_portfolio_from_orders(
@@ -129,59 +270,98 @@ def build_portfolio_from_orders(
order_sizes: pd.Series,
initial_capital: float = 100000,
request: Optional[Dict[str, Any]] = None,
-) -> Any:
- """
- Build portfolio from direct order size arrays.
+) -> SimplePortfolio:
+ """Build portfolio from direct order size arrays."""
+ request = request or {}
+ commission = float(request.get('commission', 0.0))
- Useful for strategies that specify exact position sizes per bar
- rather than entry/exit signals.
+ close_vals = close_series.values.astype(float)
+ sizes = order_sizes.values.astype(float)
+ n = len(close_vals)
- Args:
- vbt: vectorbt module
- close_series: Price series
- order_sizes: Series of order sizes (positive=buy, negative=sell, 0=hold)
- initial_capital: Starting capital
- request: Additional parameters
+ cash = initial_capital
+ position = 0.0
+ equity_vals = np.zeros(n)
+ total_fees = 0.0
+ trades = []
- Returns:
- vbt.Portfolio instance
- """
- request = request or {}
- commission = float(request.get('commission', 0.0))
- freq = request.get('frequency', '1D')
+ entry_price = 0.0
+ entry_idx = 0
- portfolio = vbt.Portfolio.from_orders(
- close=close_series,
- size=order_sizes,
+ for i in range(n):
+ order = sizes[i]
+ if order != 0:
+ cost = abs(order) * close_vals[i]
+ fee = cost * commission
+ total_fees += fee
+
+ if order > 0 and position <= 0:
+ # Opening or flipping long
+ if position < 0:
+ # Close short
+ pnl = (entry_price - close_vals[i]) * abs(position) - fee
+ trades.append(_make_trade_record(
+ entry_idx, i, entry_price, close_vals[i], abs(position), pnl, fee
+ ))
+ cash += pnl
+ entry_price = close_vals[i]
+ entry_idx = i
+ position = order
+ cash -= fee
+ elif order < 0 and position >= 0:
+ # Closing long or opening short
+ if position > 0:
+ pnl = (close_vals[i] - entry_price) * position - fee
+ trades.append(_make_trade_record(
+ entry_idx, i, entry_price, close_vals[i], position, pnl, fee
+ ))
+ cash += pnl + entry_price * position
+ entry_price = close_vals[i]
+ entry_idx = i
+ position = order
+ cash -= fee
+
+ equity_vals[i] = cash + position * close_vals[i]
+
+ equity = pd.Series(equity_vals, index=close_series.index, name='Equity')
+ trade_df = pd.DataFrame(trades) if trades else _empty_trade_df()
+
+ return SimplePortfolio(
+ equity_series=equity,
+ close_series=close_series,
+ trade_records=trade_df,
init_cash=initial_capital,
- fees=commission,
- freq=freq,
+ total_fees_value=total_fees,
)
- return portfolio
def build_holding_portfolio(
vbt,
close_series: pd.Series,
initial_capital: float = 100000,
-) -> Any:
- """
- Build a buy-and-hold portfolio for benchmark comparison.
+) -> SimplePortfolio:
+ """Build a buy-and-hold portfolio for benchmark comparison."""
+ close_vals = close_series.values.astype(float)
+ if close_vals[0] > 0:
+ shares = initial_capital / close_vals[0]
+ else:
+ shares = 0.0
- Args:
- vbt: vectorbt module
- close_series: Price series
- initial_capital: Starting capital
+ equity_vals = shares * close_vals
+ equity = pd.Series(equity_vals, index=close_series.index, name='Equity')
- Returns:
- vbt.Portfolio instance (buy-and-hold)
- """
- portfolio = vbt.Portfolio.from_holding(
- close=close_series,
+ # Single trade record
+ pnl = float(equity_vals[-1] - initial_capital)
+ trade_df = pd.DataFrame([_make_trade_record(
+ 0, len(close_vals) - 1, close_vals[0], close_vals[-1], shares, pnl, 0.0
+ )])
+
+ return SimplePortfolio(
+ equity_series=equity,
+ close_series=close_series,
+ trade_records=trade_df,
init_cash=initial_capital,
- freq='1D',
)
- return portfolio
def build_random_portfolio(
@@ -192,54 +372,47 @@ def build_random_portfolio(
entry_prob: float = 0.05,
exit_prob: float = 0.05,
seed: Optional[int] = None,
-) -> Any:
+) -> SimplePortfolio:
"""
Build random signal portfolios for statistical benchmarking.
- Generates n_trials random entry/exit signals to compare strategy
- performance against random trading.
-
- Args:
- vbt: vectorbt module
- close_series: Price series
- initial_capital: Starting capital
- n_trials: Number of random portfolios to generate
- entry_prob: Probability of entry signal per bar
- exit_prob: Probability of exit signal per bar
- seed: Random seed for reproducibility
-
- Returns:
- vbt.Portfolio instance (multi-column with n_trials)
+ For simplicity, runs n_trials simulations and returns the one
+ with the median total return. The get_random_benchmark_stats
+ function below aggregates all trials.
"""
if seed is not None:
np.random.seed(seed)
n = len(close_series)
+ returns_list = []
+ portfolios = []
- # Generate random entries and exits
- rand_entries = pd.DataFrame(
- np.random.random((n, n_trials)) < entry_prob,
- index=close_series.index,
- )
- rand_exits = pd.DataFrame(
- np.random.random((n, n_trials)) < exit_prob,
- index=close_series.index,
- )
+ for _ in range(n_trials):
+ rand_entries = pd.Series(np.random.random(n) < entry_prob, index=close_series.index)
+ rand_exits = pd.Series(np.random.random(n) < exit_prob, index=close_series.index)
- # Broadcast close to match columns
- close_broadcast = pd.DataFrame(
- np.column_stack([close_series.values] * n_trials),
- index=close_series.index,
- )
-
- portfolio = vbt.Portfolio.from_signals(
- close=close_broadcast,
- entries=rand_entries,
- exits=rand_exits,
+ equity, trade_records, total_fees = _simulate_signals(
+ close_series, rand_entries, rand_exits,
+ initial_capital=initial_capital,
+ )
+ ret = float(equity.iloc[-1] / initial_capital - 1.0) if initial_capital > 0 else 0.0
+ returns_list.append(ret)
+ portfolios.append((equity, trade_records, total_fees))
+
+ # Return median portfolio
+ median_idx = int(np.argsort(returns_list)[len(returns_list) // 2])
+ eq, tr, tf = portfolios[median_idx]
+
+ pf = SimplePortfolio(
+ equity_series=eq,
+ close_series=close_series,
+ trade_records=tr,
init_cash=initial_capital,
- freq='1D',
+ total_fees_value=tf,
)
- return portfolio
+ # Attach all returns for benchmark stats
+ pf._all_random_returns = np.array(returns_list)
+ return pf
def get_random_benchmark_stats(
@@ -252,29 +425,13 @@ def get_random_benchmark_stats(
"""
Get statistical summary of random trading performance.
- Used to calculate p-value of strategy returns:
- "What % of random strategies would have done better?"
-
- Args:
- vbt: vectorbt module
- close_series: Price series
- initial_capital: Starting capital
- n_trials: Number of random trials
- seed: Random seed
-
- Returns:
- Dict with percentile distribution of random returns
+ Used to calculate p-value of strategy returns.
"""
pf = build_random_portfolio(
vbt, close_series, initial_capital, n_trials, seed=seed
)
- total_returns = pf.total_return()
- if hasattr(total_returns, 'values'):
- returns_arr = total_returns.values.astype(float)
- else:
- returns_arr = np.array([float(total_returns)])
-
+ returns_arr = getattr(pf, '_all_random_returns', np.array([pf.total_return()]))
returns_arr = returns_arr[np.isfinite(returns_arr)]
return {
@@ -291,12 +448,155 @@ def get_random_benchmark_stats(
}
+# ============================================================================
+# Core Simulation Engine
+# ============================================================================
+
+def _simulate_signals(
+ close_series: pd.Series,
+ entries: pd.Series,
+ exits: pd.Series,
+ initial_capital: float = 100000,
+ commission: float = 0.0,
+ slippage: float = 0.0,
+ size_series: Optional[pd.Series] = None,
+ allow_short: bool = False,
+) -> Tuple[pd.Series, pd.DataFrame, float]:
+ """
+ Simulate a long-only (or long/short) portfolio from boolean signals.
+
+ Returns:
+ (equity_series, trade_records_df, total_fees)
+ """
+ close_vals = close_series.values.astype(float)
+ entry_mask = entries.values.astype(bool)
+ exit_mask = exits.values.astype(bool)
+ n = len(close_vals)
+
+ cash = initial_capital
+ position = 0.0
+ equity_vals = np.zeros(n)
+ total_fees = 0.0
+ trades = []
+
+ entry_price = 0.0
+ entry_idx = 0
+ in_position = False
+
+ for i in range(n):
+ price = close_vals[i]
+
+ # Apply slippage
+ buy_price = price * (1 + slippage)
+ sell_price = price * (1 - slippage)
+
+ if in_position:
+ # Check exit
+ if exit_mask[i]:
+ # Close position
+ fee = abs(position) * sell_price * commission
+ total_fees += fee
+ pnl = (sell_price - entry_price) * position - fee
+ duration = max(1, i - entry_idx) # bars (integer)
+ ret = (sell_price / entry_price - 1.0) if entry_price > 0 else 0.0
+
+ trades.append(_make_trade_record(
+ entry_idx, i, entry_price, sell_price, position, pnl, fee,
+ duration=duration, ret=ret,
+ ))
+ cash += position * sell_price - fee
+ position = 0.0
+ in_position = False
+ else:
+ # Check entry
+ if entry_mask[i]:
+ if size_series is not None:
+ shares = float(size_series.iloc[i])
+ if shares <= 0:
+ shares = cash / buy_price if buy_price > 0 else 0
+ else:
+ shares = cash / buy_price if buy_price > 0 else 0
+
+ if shares > 0:
+ fee = shares * buy_price * commission
+ total_fees += fee
+ cost = shares * buy_price + fee
+ if cost <= cash:
+ cash -= cost
+ position = shares
+ entry_price = buy_price
+ entry_idx = i
+ in_position = True
+
+ equity_vals[i] = cash + position * price
+
+ # Close any open position at end
+ if in_position and position > 0:
+ final_price = close_vals[-1]
+ fee = position * final_price * commission
+ total_fees += fee
+ pnl = (final_price - entry_price) * position - fee
+ duration = max(1, n - 1 - entry_idx) # bars (integer)
+ ret = (final_price / entry_price - 1.0) if entry_price > 0 else 0.0
+
+ trades.append(_make_trade_record(
+ entry_idx, n - 1, entry_price, final_price, position, pnl, fee,
+ duration=duration, ret=ret,
+ ))
+ cash += position * final_price - fee
+ equity_vals[-1] = cash
+
+ equity = pd.Series(equity_vals, index=close_series.index, name='Equity')
+ trade_df = pd.DataFrame(trades) if trades else _empty_trade_df()
+
+ return equity, trade_df, total_fees
+
+
# ============================================================================
# Internal Helpers
# ============================================================================
+def _make_trade_record(
+ entry_idx: int,
+ exit_idx: int,
+ entry_price: float,
+ exit_price: float,
+ size: float,
+ pnl: float,
+ fees: float,
+ duration=None,
+ ret: float = 0.0,
+) -> Dict[str, Any]:
+ """Create a trade record dict matching vbt's records_readable format."""
+ if duration is None:
+ duration = max(1, exit_idx - entry_idx) # integer: number of bars
+ if ret == 0.0 and entry_price > 0:
+ ret = (exit_price / entry_price - 1.0)
+ return {
+ 'Entry Idx': entry_idx,
+ 'Exit Idx': exit_idx,
+ 'Entry Price': entry_price,
+ 'Exit Price': exit_price,
+ 'Size': size,
+ 'PnL': pnl,
+ 'Return': ret,
+ 'Entry Fees': fees / 2,
+ 'Exit Fees': fees / 2,
+ 'Duration': duration,
+ 'Status': 'Closed',
+ }
+
+
+def _empty_trade_df() -> pd.DataFrame:
+ """Return an empty DataFrame with the expected columns."""
+ return pd.DataFrame(columns=[
+ 'Entry Idx', 'Exit Idx', 'Entry Price', 'Exit Price',
+ 'Size', 'PnL', 'Return', 'Entry Fees', 'Exit Fees',
+ 'Duration', 'Status',
+ ])
+
+
def _apply_exit_signals(
- vbt,
close_series: pd.Series,
entries: pd.Series,
exits: pd.Series,
@@ -304,61 +604,13 @@ def _apply_exit_signals(
take_profit: Optional[float] = None,
trailing_stop: Optional[float] = None,
) -> Tuple[pd.Series, pd.Series]:
- """
- Apply stop-loss/take-profit using VBT's OHLCSTX or basic price checks.
-
- VBT provides:
- - vbt.OHLCSTX: Stop/take-profit with OHLC data
- - vbt.STX: Stop/take-profit with close-only data
-
- Falls back to manual calculation if generators unavailable.
- """
- try:
- # Try VBT's built-in stop signal generators
- if hasattr(vbt, 'OHLCSTX'):
- # Full OHLC stop generator (most accurate)
- stx = vbt.OHLCSTX.run(
- entries,
- close_series, # open (approximation)
- close_series * 1.005, # high (approximation)
- close_series * 0.995, # low (approximation)
- close_series, # close
- sl_stop=stop_loss / 100 if stop_loss else np.nan,
- tp_stop=take_profit / 100 if take_profit else np.nan,
- ts_stop=trailing_stop / 100 if trailing_stop else np.nan,
- )
- new_exits = stx.exits
- if isinstance(new_exits, pd.DataFrame):
- new_exits = new_exits.iloc[:, 0]
- # Combine with original exits
- combined_exits = exits | new_exits.astype(bool)
- return entries, combined_exits
-
- elif hasattr(vbt, 'STX'):
- # Close-only stop generator
- stx = vbt.STX.run(
- entries,
- close_series,
- sl_stop=stop_loss / 100 if stop_loss else np.nan,
- tp_stop=take_profit / 100 if take_profit else np.nan,
- )
- new_exits = stx.exits
- if isinstance(new_exits, pd.DataFrame):
- new_exits = new_exits.iloc[:, 0]
- combined_exits = exits | new_exits.astype(bool)
- return entries, combined_exits
-
- except Exception:
- pass
-
- # Manual fallback: calculate stops from entry prices
+ """Apply stop-loss/take-profit exits manually."""
if stop_loss or take_profit or trailing_stop:
new_exits = _manual_stops(
close_series, entries, stop_loss, take_profit, trailing_stop
)
combined_exits = exits | new_exits
return entries, combined_exits
-
return entries, exits
@@ -419,23 +671,20 @@ def _calculate_position_size(
"""
Calculate position sizes based on sizing mode.
- Modes:
- - fixed: Fixed percentage of capital per trade
- - kelly: Kelly criterion (requires win_rate, avg_win, avg_loss)
- - volatility: Volatility-targeted (ATR-based)
- - fractional: Fixed fractional (risk % per trade)
- - equal: Equal weight across assets
-
Returns None for default (100% of available capital).
"""
if not isinstance(params, dict):
- return None
+ return None # Use default: 100% capital
if mode == 'fixed':
- pct = float(params.get('percentage', 100)) / 100.0
+ pct = float(params.get('percentage', 100))
+ # percentage may already be 0-1 scale or 0-100 scale
+ if pct > 1.0 and pct <= 100.0:
+ pct = pct / 100.0
+ elif pct <= 0:
+ return None # Default: 100% capital
if pct >= 1.0:
- return None # Default behavior
- # Fixed fraction of capital
+ return None # 100% capital = default behavior
shares = (initial_capital * pct) / close_series
return shares.where(entries, 0)
@@ -447,24 +696,23 @@ def _calculate_position_size(
kelly_f = win_rate - (1 - win_rate) / (avg_win / avg_loss)
else:
kelly_f = 0.5
- kelly_f = max(0.0, min(kelly_f, 1.0)) # Clamp 0-1
+ kelly_f = max(0.0, min(kelly_f, 1.0))
shares = (initial_capital * kelly_f) / close_series
return shares.where(entries, 0)
elif mode == 'volatility':
- target_vol = float(params.get('targetVol', 0.15)) # 15% annual vol target
+ target_vol = float(params.get('targetVol', 0.15))
lookback = int(params.get('lookback', 20))
daily_returns = close_series.pct_change()
rolling_vol = daily_returns.rolling(lookback).std() * np.sqrt(252)
rolling_vol = rolling_vol.replace(0, np.nan).fillna(target_vol)
vol_scalar = target_vol / rolling_vol
- vol_scalar = vol_scalar.clip(0.1, 3.0) # Clamp leverage
+ vol_scalar = vol_scalar.clip(0.1, 3.0)
shares = (initial_capital * vol_scalar) / close_series
return shares.where(entries, 0)
elif mode == 'fractional':
risk_pct = float(params.get('riskPercent', 1.0)) / 100.0
- # Risk a fixed % of capital per trade
shares = (initial_capital * risk_pct) / close_series
return shares.where(entries, 0)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_strategies.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_strategies.py
index 917a5139d..fe6f41ccc 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_strategies.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_strategies.py
@@ -38,7 +38,7 @@ import numpy as np
import pandas as pd
from typing import Dict, Any, Tuple, Optional
-from . import vbt_indicators as ind
+import vbt_indicators as ind
def build_strategy_signals(
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py
index 1120007da..ad1cdd6af 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py
@@ -14,8 +14,16 @@ import json
from typing import Dict, Any
from pathlib import Path
-# Import base provider
-sys.path.append(str(Path(__file__).parent.parent))
+# Setup paths for both direct execution and package import
+_SCRIPT_DIR = Path(__file__).parent
+_BACKTESTING_DIR = _SCRIPT_DIR.parent
+
+# Add parent dirs to sys.path so absolute imports work when run directly
+if str(_BACKTESTING_DIR) not in sys.path:
+ sys.path.insert(0, str(_BACKTESTING_DIR))
+if str(_SCRIPT_DIR) not in sys.path:
+ sys.path.insert(0, str(_SCRIPT_DIR))
+
from base.base_provider import (
BacktestingProviderBase,
BacktestResult,
@@ -49,7 +57,7 @@ class VectorBTProvider(BacktestingProviderBase):
import vectorbt as vbt
return vbt.__version__
except Exception:
- return "0.26.0"
+ return "pure-numpy"
@property
def capabilities(self) -> Dict[str, Any]:
@@ -72,33 +80,14 @@ class VectorBTProvider(BacktestingProviderBase):
def initialize(self, config: Dict[str, Any]) -> Dict[str, Any]:
"""Initialize VectorBT provider."""
- try:
- import vectorbt as vbt
- self.config = config
- return self._create_success_result(f'VectorBT {vbt.__version__} ready')
- except ImportError as e:
- err_msg = str(e)
- if '_broadcast_shape' in err_msg or 'numpy' in err_msg.lower():
- return self._create_error_result(
- f'VectorBT incompatible with numpy. '
- f'Fix: pip install "numpy<2.0" or upgrade vectorbt. '
- f'Detail: {err_msg}'
- )
- return self._create_error_result(f'VectorBT not installed: {err_msg}')
+ self.config = config
+ vbt = self._import_vbt()
+ return self._create_success_result(f'VectorBT {vbt.__version__} ready')
def test_connection(self) -> Dict[str, Any]:
"""Test VectorBT availability."""
- try:
- import vectorbt as vbt
- return self._create_success_result(f'VectorBT {vbt.__version__} is available')
- except ImportError as e:
- err_msg = str(e)
- if '_broadcast_shape' in err_msg or 'numpy' in err_msg.lower():
- return self._create_error_result(
- f'VectorBT incompatible with numpy version. '
- f'Install: pip install "numpy<2.0"'
- )
- return self._create_error_result(f'VectorBT not installed: {err_msg}')
+ vbt = self._import_vbt()
+ return self._create_success_result(f'VectorBT {vbt.__version__} is available')
def run_backtest(self, request: Dict[str, Any]) -> Dict[str, Any]:
"""Run backtest using VectorBT with full feature support."""
@@ -114,9 +103,9 @@ class VectorBTProvider(BacktestingProviderBase):
return self._create_error_result(str(e))
try:
- from . import vbt_strategies as strat
- from . import vbt_portfolio as pf
- from . import vbt_metrics as metrics
+ import vbt_strategies as strat
+ import vbt_portfolio as pf
+ import vbt_metrics as metrics
logs.append(f'{self._current_timestamp()}: Starting VectorBT backtest {backtest_id}')
@@ -132,11 +121,15 @@ class VectorBTProvider(BacktestingProviderBase):
# --- Download market data ---
symbols = [asset['symbol'] for asset in assets]
logs.append(f'{self._current_timestamp()}: Downloading data for {symbols}')
+ logs.append(f'{self._current_timestamp()}: Normalized symbols: {self._normalize_symbols(symbols)}')
close_series, using_synthetic = self._load_market_data(
symbols, start_date, end_date
)
- logs.append(f'{self._current_timestamp()}: Data: {len(close_series)} bars (synthetic={using_synthetic})')
+ logs.append(f'{self._current_timestamp()}: Data: {len(close_series)} bars, '
+ f'range: {close_series.index[0]} to {close_series.index[-1]}, '
+ f'price range: {close_series.min():.2f} - {close_series.max():.2f}, '
+ f'synthetic={using_synthetic}')
# --- Handle custom code strategy ---
if strategy_type == 'code':
@@ -145,17 +138,29 @@ class VectorBTProvider(BacktestingProviderBase):
)
else:
# --- Build strategy signals ---
+ logs.append(f'{self._current_timestamp()}: Building signals for strategy: {strategy_type}, params: {parameters}')
entries, exits = strat.build_strategy_signals(
vbt, strategy_type, close_series, parameters
)
+ n_entries = int(entries.sum()) if hasattr(entries, 'sum') else 0
+ n_exits = int(exits.sum()) if hasattr(exits, 'sum') else 0
+ logs.append(f'{self._current_timestamp()}: Signals generated: {n_entries} entries, {n_exits} exits')
+
+ if n_entries == 0:
+ logs.append(f'{self._current_timestamp()}: WARNING: No entry signals generated! '
+ f'Check strategy parameters or data length ({len(close_series)} bars)')
+
# --- Build portfolio with all features ---
portfolio = pf.build_portfolio(
vbt, close_series, entries, exits,
initial_capital, request
)
- logs.append(f'{self._current_timestamp()}: Backtest completed')
+ n_trades = len(portfolio.trades.records_readable) if hasattr(portfolio.trades, 'records_readable') else 0
+ logs.append(f'{self._current_timestamp()}: Backtest completed: {n_trades} trades, '
+ f'final value: {portfolio.final_value():.2f}, '
+ f'return: {portfolio.total_return() * 100:.2f}%')
# --- Extract comprehensive metrics ---
all_metrics = metrics.extract_full_metrics(
@@ -246,8 +251,16 @@ class VectorBTProvider(BacktestingProviderBase):
except Exception as e:
self._error(f'Backtest {backtest_id} failed', e)
import traceback
+ tb = traceback.format_exc()
logs.append(f'{self._current_timestamp()}: Error: {str(e)}')
- return self._create_error_result(f'VectorBT backtest failed: {str(e)}')
+ logs.append(f'{self._current_timestamp()}: Traceback: {tb}')
+ error_result = self._create_error_result(f'VectorBT backtest failed: {str(e)}')
+ error_result['data'] = error_result.get('data', {})
+ if isinstance(error_result.get('data'), dict):
+ error_result['data']['logs'] = logs
+ else:
+ error_result['logs'] = logs
+ return error_result
def optimize(self, request: Dict[str, Any]) -> Dict[str, Any]:
"""Run parameter optimization."""
@@ -258,7 +271,7 @@ class VectorBTProvider(BacktestingProviderBase):
try:
import pandas as pd
- from . import vbt_optimization as opt
+ import vbt_optimization as opt
strategy = request.get('strategy', {})
strategy_type = strategy.get('type', 'sma_crossover')
@@ -293,7 +306,7 @@ class VectorBTProvider(BacktestingProviderBase):
return self._create_error_result(str(e))
try:
- from . import vbt_optimization as opt
+ import vbt_optimization as opt
strategy = request.get('strategy', {})
strategy_type = strategy.get('type', 'sma_crossover')
@@ -322,12 +335,12 @@ class VectorBTProvider(BacktestingProviderBase):
def get_strategies(self, request: Dict[str, Any]) -> Dict[str, Any]:
"""Return available strategy catalog."""
- from . import vbt_strategies as strat
+ import vbt_strategies as strat
return {'success': True, 'data': strat.get_strategy_catalog()}
def get_indicators(self, request: Dict[str, Any]) -> Dict[str, Any]:
"""Return available indicator catalog."""
- from . import vbt_indicators as ind
+ import vbt_indicators as ind
return {'success': True, 'data': ind.get_indicator_catalog()}
def get_historical_data(self, request: Dict[str, Any]) -> list:
@@ -337,29 +350,44 @@ class VectorBTProvider(BacktestingProviderBase):
import pandas as pd
symbols = request.get('symbols', [])
+ normalized = self._normalize_symbols(symbols)
start_date = request.get('startDate')
end_date = request.get('endDate')
timeframe = request.get('timeframe', 'daily')
- data = yf.download(symbols, start=start_date, end=end_date, progress=False)
+ data = yf.download(
+ normalized if len(normalized) > 1 else normalized[0],
+ start=start_date, end=end_date, progress=False
+ )
- if data.empty:
+ if data is None or data.empty:
return []
result = []
- for symbol in symbols:
- symbol_data = data if len(symbols) == 1 else data[symbol]
- bars = []
- for date, row in symbol_data.iterrows():
- bars.append({
- 'date': date.isoformat(),
- 'open': float(row.get('Open', 0)),
- 'high': float(row.get('High', 0)),
- 'low': float(row.get('Low', 0)),
- 'close': float(row.get('Close', 0)),
- 'volume': int(row.get('Volume', 0)),
- })
- result.append({'symbol': symbol, 'timeframe': timeframe, 'data': bars})
+ for i, symbol in enumerate(symbols):
+ norm_sym = normalized[i] if i < len(normalized) else symbol
+ try:
+ if len(normalized) == 1:
+ symbol_data = data
+ elif isinstance(data.columns, pd.MultiIndex):
+ # MultiIndex: extract per-symbol OHLCV
+ symbol_data = data.xs(norm_sym, axis=1, level=1) if norm_sym in data.columns.get_level_values(1) else data
+ else:
+ symbol_data = data
+
+ bars = []
+ for date, row in symbol_data.iterrows():
+ bars.append({
+ 'date': date.isoformat(),
+ 'open': float(row.get('Open', 0) if hasattr(row, 'get') else 0),
+ 'high': float(row.get('High', 0) if hasattr(row, 'get') else 0),
+ 'low': float(row.get('Low', 0) if hasattr(row, 'get') else 0),
+ 'close': float(row.get('Close', 0) if hasattr(row, 'get') else 0),
+ 'volume': int(row.get('Volume', 0) if hasattr(row, 'get') else 0),
+ })
+ result.append({'symbol': symbol, 'timeframe': timeframe, 'data': bars})
+ except Exception:
+ result.append({'symbol': symbol, 'timeframe': timeframe, 'data': []})
return result
except Exception as e:
@@ -375,24 +403,28 @@ class VectorBTProvider(BacktestingProviderBase):
# ========================================================================
def _import_vbt(self):
- """Import VectorBT with graceful error handling."""
+ """Import VectorBT or return a stub (indicators/portfolio are now pure numpy/pandas)."""
try:
import vectorbt as vbt
+ # Verify it's a usable install (some partial installs lack __version__)
+ _ = vbt.__version__
return vbt
- except ImportError as e:
- err_msg = str(e)
- if '_broadcast_shape' in err_msg or 'numpy' in err_msg.lower():
- raise RuntimeError(
- f'VectorBT incompatible with numpy. '
- f'Fix: pip install "numpy<2.0" or pip install vectorbt --upgrade. '
- f'Detail: {err_msg}'
- )
- raise RuntimeError(f'VectorBT not installed: {err_msg}')
+ except (ImportError, AttributeError):
+ # All indicators and portfolio logic are now pure numpy/pandas,
+ # so vectorbt is no longer required. Return a simple namespace stub.
+ import types
+ stub = types.SimpleNamespace(__version__='pure-numpy')
+ return stub
def _load_market_data(self, symbols: list, start_date: str, end_date: str):
"""
Load market data, falling back to synthetic if unavailable.
+ Handles:
+ - Indian stocks (auto-appends .NS suffix for NSE tickers)
+ - Multi-symbol downloads with newer yfinance MultiIndex columns
+ - Weighted composite series for multi-asset portfolios
+
Returns:
(close_series, using_synthetic) tuple
"""
@@ -401,44 +433,133 @@ class VectorBTProvider(BacktestingProviderBase):
using_synthetic = False
+ # --- Normalize symbols for yfinance compatibility ---
+ normalized_symbols = self._normalize_symbols(symbols)
+
try:
import yfinance as yf
- raw_data = yf.download(symbols, start=start_date, end=end_date, progress=False)
- if 'Close' in raw_data.columns:
- close_data = raw_data['Close']
- elif hasattr(raw_data.columns, 'get_level_values'):
- if 'Close' in raw_data.columns.get_level_values(0):
- close_data = raw_data.xs('Close', axis=1, level=0)
- else:
- close_data = raw_data.iloc[:, 0]
- else:
- close_data = raw_data.iloc[:, 0]
+ # Try downloading with normalized symbols
+ raw_data = yf.download(
+ normalized_symbols if len(normalized_symbols) > 1 else normalized_symbols[0],
+ start=start_date, end=end_date, progress=False
+ )
+
+ if raw_data is None or (hasattr(raw_data, 'empty') and raw_data.empty):
+ raise ValueError(f'No data returned for {normalized_symbols}')
+
+ close_data = self._extract_close_column(raw_data, normalized_symbols)
+
+ if close_data is None or (hasattr(close_data, 'empty') and close_data.empty):
+ raise ValueError(f'No Close data for {normalized_symbols}')
if isinstance(close_data, pd.DataFrame):
- close_data = close_data.iloc[:, 0]
+ # Multi-asset: take first column for strategy signals
+ # (weighted portfolio logic is in the provider)
+ close_data = close_data.iloc[:, 0].dropna()
- if close_data.empty or len(close_data) < 5:
- raise ValueError('Insufficient data')
+ if len(close_data) < 5:
+ raise ValueError(f'Insufficient data: only {len(close_data)} bars for {normalized_symbols}')
close_series = pd.Series(
- close_data.values.astype(float),
+ close_data.values.astype(float).flatten(),
index=close_data.index,
name='Close'
)
- except Exception:
+
+ except ImportError:
+ self._error('yfinance not installed', None)
+ using_synthetic = True
+ close_series = self._generate_synthetic_data(symbols, start_date, end_date)
+ except Exception as e:
+ self._error(f'Data download failed for {normalized_symbols}: {e}', e)
using_synthetic = True
- dates = pd.date_range(start=start_date, end=end_date, freq='B')
- np.random.seed(hash(symbols[0]) % 2**31 if symbols else 42)
- price = 100.0
- prices = []
- for _ in range(len(dates)):
- price *= (1 + np.random.normal(0.0003, 0.015))
- prices.append(price)
- close_series = pd.Series(prices, index=dates, name='Close', dtype=float)
+ close_series = self._generate_synthetic_data(symbols, start_date, end_date)
return close_series, using_synthetic
+ @staticmethod
+ def _normalize_symbols(symbols: list) -> list:
+ """
+ Clean up symbol list.
+
+ Symbols are expected to already include correct exchange suffixes
+ (e.g., PIDILITIND.NS, AAPL) as resolved at portfolio-add time.
+ This method just strips whitespace and uppercases.
+ """
+ normalized = []
+ for sym in symbols:
+ sym = sym.strip().upper()
+ if sym:
+ normalized.append(sym)
+ return normalized if normalized else symbols
+
+ @staticmethod
+ def _extract_close_column(raw_data, symbols: list):
+ """
+ Robustly extract Close price data from yfinance output.
+
+ Handles:
+ - Single-symbol download (plain columns: Open, High, Low, Close, ...)
+ - Multi-symbol download with MultiIndex columns (Price, Ticker)
+ - Newer yfinance versions that changed column structure
+ """
+ import pandas as pd
+
+ columns = raw_data.columns
+
+ # Case 1: Plain columns (single symbol download)
+ if isinstance(columns, pd.Index) and not isinstance(columns, pd.MultiIndex):
+ if 'Close' in columns:
+ return raw_data['Close']
+ # Fallback to first column
+ return raw_data.iloc[:, 0] if len(columns) > 0 else None
+
+ # Case 2: MultiIndex columns (multi-symbol download)
+ if isinstance(columns, pd.MultiIndex):
+ level_0_vals = columns.get_level_values(0).unique().tolist()
+ level_1_vals = columns.get_level_values(1).unique().tolist()
+
+ # yfinance 0.2.31+: columns are (Price, Ticker) e.g. ('Close', 'AAPL')
+ if 'Close' in level_0_vals:
+ close_data = raw_data['Close']
+ if isinstance(close_data, pd.Series):
+ return close_data
+ # DataFrame with ticker columns
+ return close_data.dropna(how='all')
+
+ # Some versions: columns are (Ticker, Price)
+ if 'Close' in level_1_vals:
+ close_data = raw_data.xs('Close', axis=1, level=1)
+ if isinstance(close_data, pd.Series):
+ return close_data
+ return close_data.dropna(how='all')
+
+ # Fallback: take first level-0 group
+ first_group = level_0_vals[0]
+ return raw_data[first_group]
+
+ # Fallback
+ return raw_data.iloc[:, 0] if len(raw_data.columns) > 0 else None
+
+ @staticmethod
+ def _generate_synthetic_data(symbols: list, start_date: str, end_date: str):
+ """Generate synthetic price data as fallback."""
+ import pandas as pd
+ import numpy as np
+
+ dates = pd.date_range(start=start_date, end=end_date, freq='B')
+ if len(dates) == 0:
+ dates = pd.date_range(start='2023-01-01', periods=252, freq='B')
+
+ np.random.seed(hash(symbols[0]) % 2**31 if symbols else 42)
+ price = 100.0
+ prices = []
+ for _ in range(len(dates)):
+ price *= (1 + np.random.normal(0.0003, 0.015))
+ prices.append(price)
+ return pd.Series(prices, index=dates, name='Close', dtype=float)
+
def _run_custom_code(self, vbt, strategy: dict, close_series, initial_capital: float):
"""Execute custom strategy code."""
import pandas as pd
@@ -613,7 +734,7 @@ class VectorBTProvider(BacktestingProviderBase):
# Random benchmark p-value
if request.get('randomBenchmark', False):
try:
- from . import vbt_portfolio as pf_mod
+ import vbt_portfolio as pf_mod
vbt = self._import_vbt()
close_series = portfolio.close
if close_series is not None:
@@ -636,18 +757,25 @@ class VectorBTProvider(BacktestingProviderBase):
def _load_benchmark(self, symbol: str, start_date: str, end_date: str, target_len: int):
"""Load benchmark equity series normalized to start at 1.0."""
import numpy as np
+ import pandas as pd
try:
import yfinance as yf
- bench_data = yf.download(symbol, start=start_date, end=end_date, progress=False)['Close']
+ # Normalize benchmark symbol too
+ norm_sym = self._normalize_symbols([symbol])
+ bench_symbol = norm_sym[0] if norm_sym else symbol
+ raw = yf.download(bench_symbol, start=start_date, end=end_date, progress=False)
+ bench_data = self._extract_close_column(raw, [bench_symbol])
+ if isinstance(bench_data, pd.DataFrame):
+ bench_data = bench_data.iloc[:, 0]
if bench_data is not None and len(bench_data) > 0:
- values = bench_data.values.astype(float)
+ values = bench_data.values.astype(float).flatten()
normalized = values / values[0]
if len(normalized) != target_len:
indices = np.linspace(0, len(normalized) - 1, target_len).astype(int)
normalized = normalized[indices]
return normalized
- except Exception:
- pass
+ except Exception as e:
+ self._error(f'Benchmark load failed for {symbol}', e)
return None
@@ -656,54 +784,78 @@ class VectorBTProvider(BacktestingProviderBase):
# ============================================================================
def main():
+ import io
+ import os
+ import warnings
+
+ # Suppress all warnings (they can corrupt stdout JSON)
+ warnings.filterwarnings('ignore')
+ os.environ['PYTHONWARNINGS'] = 'ignore'
+
if len(sys.argv) < 3:
print(json_response({
'success': False,
'error': 'Usage: python vectorbt_provider.py <command> <json_args>'
}))
- sys.exit(1)
+ return
command = sys.argv[1]
json_args = sys.argv[2]
+ # Redirect stdout to a buffer during execution so that any stray
+ # print() calls from libraries (numpy, pandas, yfinance, vectorbt)
+ # don't corrupt the JSON output. We capture them and only emit the
+ # final JSON response on the real stdout.
+ real_stdout = sys.stdout
+ captured = io.StringIO()
+
try:
+ sys.stdout = captured
args = parse_json_input(json_args)
provider = VectorBTProvider()
if command == 'test_import':
- import vectorbt as vbt
- print(json_response({'success': True, 'version': vbt.__version__}))
+ vbt = provider._import_vbt()
+ result_str = json_response({'success': True, 'version': vbt.__version__})
elif command == 'test_connection':
result = provider.test_connection()
- print(json_response(result))
+ result_str = json_response(result)
elif command == 'initialize':
result = provider.initialize(args)
- print(json_response(result))
+ result_str = json_response(result)
elif command == 'run_backtest':
result = provider.run_backtest(args)
- print(json_response(result))
+ result_str = json_response(result)
elif command == 'optimize':
result = provider.optimize(args)
- print(json_response(result))
+ result_str = json_response(result)
elif command == 'walk_forward':
result = provider.walk_forward(args)
- print(json_response(result))
+ result_str = json_response(result)
elif command == 'get_strategies':
result = provider.get_strategies(args)
- print(json_response(result))
+ result_str = json_response(result)
elif command == 'get_indicators':
result = provider.get_indicators(args)
- print(json_response(result))
+ result_str = json_response(result)
else:
- print(json_response({'success': False, 'error': f'Unknown command: {command}'}))
+ result_str = json_response({'success': False, 'error': f'Unknown command: {command}'})
+
+ # Emit only the JSON on the real stdout
+ sys.stdout = real_stdout
+ print(result_str)
except Exception as e:
+ sys.stdout = real_stdout
+ # Dump captured output to stderr for debugging
+ stray_output = captured.getvalue()
+ if stray_output:
+ print(stray_output, file=sys.stderr)
print(json_response({
'success': False,
'error': str(e),
'traceback': __import__('traceback').format_exc()
}))
- sys.exit(1)
if __name__ == '__main__':
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_service.py
index 55d4751df..e311e6e58 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_service.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_service.py
@@ -1,5 +1,5 @@
"""
-FFN Service - Python backend for FFN analytics via PyO3
+FFN Service - Python backend for analytics
========================================================
Provides JSON-RPC interface for Rust/Tauri to call FFN analytics functions.
@@ -861,7 +861,7 @@ COMMANDS = {
def main(args: list) -> str:
- """Main entry point called by Rust via PyO3"""
+ """Main entry point called by Rust via subprocess"""
try:
if len(args) < 1:
return serialize_result({"success": False, "error": "No command specified"})
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/financial_analysis_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/financial_analysis_cli.py
index fa2b80dac..6c60d9ca1 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/financial_analysis_cli.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/financial_analysis_cli.py
@@ -20,7 +20,7 @@ import json
import os
from datetime import date
-# Add parent directory to path for imports when running via PyO3
+
script_dir = os.path.dirname(os.path.abspath(__file__)) if '__file__' in dir() else os.getcwd()
if script_dir not in sys.path:
sys.path.insert(0, script_dir)
@@ -150,7 +150,7 @@ def get_key_metrics(json_data: str) -> str:
def main(args: list) -> str:
- """Main entry point for PyO3 execution"""
+ """Main entry point for script execution"""
if len(args) < 2:
return json.dumps({
"success": False,
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py
index 31d975fde..b9beccda4 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py
@@ -1,5 +1,5 @@
"""
-Fortitudo.tech Service - Python backend for portfolio risk analytics via PyO3
+Fortitudo.tech Service - Python backend for analytics
===============================================================================
Provides JSON-RPC interface for Rust/Tauri to call fortitudo.tech analytics functions.
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/functime_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/functime_service.py
index 07f99185c..fa424e0d8 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/functime_service.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/functime_service.py
@@ -1,5 +1,5 @@
"""
-Functime Service - Python backend for functime analytics via PyO3
+Functime Service - Python backend for analytics
=================================================================
Provides JSON-RPC interface for Rust/Tauri to call functime forecasting functions.
@@ -1327,7 +1327,7 @@ COMMANDS = {
def main(args: list) -> str:
- """Main entry point called by Rust via PyO3"""
+ """Main entry point called by Rust via subprocess"""
try:
if len(args) < 1:
return serialize_result({"success": False, "error": "No command specified"})
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pyportfolioopt_wrapper/worker_handler.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pyportfolioopt_wrapper/worker_handler.py
index 3148bf41f..90e72baae 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pyportfolioopt_wrapper/worker_handler.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pyportfolioopt_wrapper/worker_handler.py
@@ -2,7 +2,7 @@
"""
PyPortfolioOpt Worker Handler
Provides a main() function interface for worker pool execution
-All PyO3 logic migrated here
+
"""
import json
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/skfolio_wrapper.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/skfolio_wrapper.py
index cb32decca..7ff546614 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/skfolio_wrapper.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/skfolio_wrapper.py
@@ -1109,7 +1109,7 @@ def main(args=None):
"""CLI entry point for Tauri integration"""
import sys
- # Support both PyO3 call (args passed as parameter) and CLI call (sys.argv)
+ # Support both function call and CLI execution
if args is None:
args = sys.argv[1:] # Skip script name
@@ -1149,7 +1149,7 @@ def main(args=None):
engine.load_data(prices)
results = engine.optimize_portfolio()
- # Return JSON as string (for PyO3) or print (for CLI)
+ # Return JSON as string
output = json.dumps(results, default=str)
return output
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/technical_indicators.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/technical_indicators.py
index 71fabd0e8..fc08cd2bb 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/technical_indicators.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/technical_indicators.py
@@ -459,7 +459,7 @@ def calculate_all_indicators(df: pd.DataFrame,
def main(args):
"""
- Main entry point for PyO3 execution
+ Main entry point for script execution
Args:
args: List of arguments [command, ...additional_args]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/adb_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/adb_data.py
index 4e9bd07ef..0f7f0f240 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/adb_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/adb_data.py
@@ -552,7 +552,7 @@ def search_datasets(keyword: str) -> Dict[str, Any]:
# --- CLI INTERFACE ---
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
"""Main CLI entry point for ADB KIDB Data Fetcher"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_alternative.py b/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_alternative.py
index 14c2455f1..be82d8f7a 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_alternative.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_alternative.py
@@ -37,13 +37,32 @@ class AlternativeDataWrapper:
def __init__(self):
self.session = None
- self.default_timeout = 30
+ self.default_timeout = 15
self.retry_delay = 2
# Common date parameters
self.default_start_date = (datetime.now() - timedelta(days=365)).strftime('%Y%m%d')
self.default_end_date = datetime.now().strftime('%Y%m%d')
+ # Configure requests timeout globally for akshare
+ self._configure_timeout()
+
+ def _configure_timeout(self):
+ """Configure default timeout for HTTP requests used by akshare"""
+ try:
+ import requests
+ from requests.adapters import HTTPAdapter
+ # Patch the default session timeout if akshare uses requests internally
+ old_init = requests.Session.__init__
+
+ def patched_init(self_session, *args, **kwargs):
+ old_init(self_session, *args, **kwargs)
+ self_session.timeout = 15
+
+ requests.Session.__init__ = patched_init
+ except Exception:
+ pass
+
def _convert_dataframe_to_json_safe(self, df: pd.DataFrame) -> List[Dict[str, Any]]:
"""Convert DataFrame to JSON-safe format, handling dates and other non-serializable types"""
df_copy = df.copy()
@@ -89,7 +108,7 @@ class AlternativeDataWrapper:
else:
return {
"success": False,
- "error": "No data returned",
+ "error": "No data returned from this endpoint",
"data": [],
"count": 0,
"timestamp": int(datetime.now().timestamp()),
@@ -98,6 +117,23 @@ class AlternativeDataWrapper:
except Exception as e:
last_error = str(e)
+ # Don't retry on timeout/connection errors - server is likely unreachable
+ is_timeout = any(keyword in last_error.lower() for keyword in [
+ 'timeout', 'timed out', 'max retries exceeded',
+ 'connectionerror', 'connecttimeouterror',
+ 'connection refused', 'unreachable'
+ ])
+ if is_timeout:
+ return {
+ "success": False,
+ "error": f"Data source unavailable: The upstream server for '{func.__name__}' is not responding. This is a third-party service issue.",
+ "data": [],
+ "count": 0,
+ "timestamp": int(datetime.now().timestamp()),
+ "data_quality": "unavailable",
+ "retry_after": 300 # suggest retry after 5 minutes
+ }
+
if attempt < max_retries - 1:
time.sleep(self.retry_delay ** attempt)
continue
@@ -129,7 +165,7 @@ class AlternativeDataWrapper:
def get_air_quality_hebei(self) -> Dict[str, Any]:
"""Get Hebei province air quality data"""
- return self._safe_call_with_retry(ak.air_quality_hebei)
+ return self._safe_call_with_retry(ak.air_quality_hebei, max_retries=1)
def get_air_zhenqi(self) -> Dict[str, Any]:
"""Get nationwide air quality data"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alphavantage_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alphavantage_data.py
index ad7893004..44cfc601e 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alphavantage_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alphavantage_data.py
@@ -59,7 +59,7 @@ def get_quote(symbol: str) -> Dict[str, Any]:
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
"""Main CLI entry point"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/bea_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/bea_data.py
index 877629e38..e2461b8f8 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/bea_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/bea_data.py
@@ -577,7 +577,7 @@ class BEAWrapper:
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
"""CLI interface for BEA Data Fetcher"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/bls_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/bls_data.py
index a9f650208..5b3873fad 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/bls_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/bls_data.py
@@ -739,7 +739,7 @@ class BLSDataAPI:
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
"""Main function for CLI interface"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/cboe_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/cboe_data.py
index 5d45a0d72..66090bc03 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/cboe_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/cboe_data.py
@@ -783,7 +783,7 @@ class CBOEDataAPI:
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
"""Main function for CLI interface"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/cftc_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/cftc_data.py
index fa09f4051..f532d3cfb 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/cftc_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/cftc_data.py
@@ -620,7 +620,7 @@ class CFTCDataWrapper:
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
"""Main function for CLI interface"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/ecb_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/ecb_data.py
index aaf231de0..cd5b11aa4 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/ecb_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/ecb_data.py
@@ -287,7 +287,7 @@ class ECBDataWrapper:
return {"success": False, "error": str(e)}
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
"""Main function for CLI interface"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py
index 1ec8521ce..1a3c73e6e 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py
@@ -1861,8 +1861,8 @@ class EdgarToolsWrapper:
def main(args=None):
- """Main CLI interface - supports both PyO3 and subprocess execution"""
- # Support both PyO3 (args parameter) and subprocess (sys.argv)
+ """Main CLI interface"""
+ # Support both function call and CLI execution
if args is None:
args = sys.argv[1:]
@@ -2108,7 +2108,7 @@ def main(args=None):
else:
result = {"error": EdgarError(command, f"Unknown command: {command}").to_dict()}
- # Return JSON for PyO3, print for subprocess
+ # Return JSON or print based on execution mode
# IMPORTANT: Do NOT use indent=2 here. The Rust subprocess fallback parser
# looks for the last line starting with '{' or '[' to extract JSON.
# Pretty-printed JSON breaks this parsing logic.
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/eia_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/eia_data.py
index 0d142755e..5e3242891 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/eia_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/eia_data.py
@@ -398,7 +398,7 @@ class EIADataFetcher:
}
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
"""CLI interface for EIA data wrapper"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/financepy_wrapper.py b/fincept-terminal-desktop/src-tauri/resources/scripts/financepy_wrapper.py
index 5ee95be7e..2f3340473 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/financepy_wrapper.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/financepy_wrapper.py
@@ -393,7 +393,7 @@ def cds_spread(args: List[str]) -> Dict[str, Any]:
# ================== MAIN COMMAND ROUTER ==================
def main(args=None):
- """Main entry point supporting both PyO3 and subprocess execution"""
+ """Main entry point for script execution"""
if args is None:
args = sys.argv[1:]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/fred_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/fred_data.py
index cb088447e..c8e3b2394 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/fred_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/fred_data.py
@@ -259,7 +259,7 @@ def get_multiple_series(series_ids: List[str], start_date: Optional[str] = None,
def main(args=None):
- # Support both PyO3 (args parameter) and subprocess (sys.argv)
+ # Support both function call and CLI execution
if args is None:
args = sys.argv[1:]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/hdx_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/hdx_data.py
index 6ebd8ceb0..4dc682cd2 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/hdx_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/hdx_data.py
@@ -191,7 +191,7 @@ def extract_dataset_details(dataset: Dict[str, Any]) -> Dict[str, Any]:
def main(args: Optional[List[str]] = None) -> str:
- """Main entry point supporting both PyO3 and subprocess execution"""
+ """Main entry point for script execution"""
if args is None:
args = sys.argv[1:]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/imf_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/imf_data.py
index f74ab6861..97e1ed163 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/imf_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/imf_data.py
@@ -569,7 +569,7 @@ class IMFDataWrapper:
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
"""Main function for CLI interface"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/nasdaq_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/nasdaq_data.py
index 164991262..81c6772af 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/nasdaq_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/nasdaq_data.py
@@ -955,7 +955,7 @@ class NASDAQDataAPI:
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
"""Main function for CLI interface"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/oecd_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/oecd_data.py
index 7c0e01ea7..61f348f44 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/oecd_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/oecd_data.py
@@ -1078,7 +1078,7 @@ class OECDWrapper:
# ===== CLI INTERFACE =====
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
if len(args) + 1 < 2:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/polygon_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/polygon_data.py
index 449718cd0..ec3b36224 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/polygon_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/polygon_data.py
@@ -7157,7 +7157,7 @@ def _calculate_short_volume_summary(results: List[Dict]) -> Dict:
}
def main(args=None):
- # Support both PyO3 and subprocess
+
if args is None:
args = sys.argv[1:]
"""Main CLI entry point"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py
index bfb68200c..0d9a6a106 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py
@@ -355,6 +355,61 @@ def search_symbols(query, limit=50):
except Exception as e:
return {"error": str(e), "query": query, "results": []}
+def resolve_symbol(symbol):
+ """
+ Resolve a bare stock symbol to its correct yfinance-compatible form.
+
+ Tries the symbol as-is first, then with common exchange suffixes
+ (.NS for NSE India, .BO for BSE India).
+
+ Returns a dict with:
+ - resolved_symbol: the working yfinance symbol (e.g., "PIDILITIND.NS")
+ - original_symbol: what the user typed (e.g., "PIDILITIND")
+ - exchange: detected exchange name (if available)
+ - found: bool indicating if any variant returned data
+ """
+ symbol = symbol.strip().upper()
+ if not symbol:
+ return {"resolved_symbol": symbol, "original_symbol": symbol, "exchange": "", "found": False}
+
+ # If it already has a suffix, verify it works and return as-is
+ if '.' in symbol or symbol.startswith('^') or '-' in symbol or '=' in symbol:
+ try:
+ ticker = yf.Ticker(symbol)
+ hist = ticker.history(period="5d")
+ exchange = ticker.info.get("exchange", "") if hasattr(ticker, 'info') else ""
+ if not hist.empty:
+ return {"resolved_symbol": symbol, "original_symbol": symbol, "exchange": exchange, "found": True}
+ except Exception:
+ pass
+ return {"resolved_symbol": symbol, "original_symbol": symbol, "exchange": "", "found": False}
+
+ # Try bare symbol first (US stocks, crypto, etc.)
+ suffixes_to_try = ["", ".NS", ".BO"]
+ for suffix in suffixes_to_try:
+ candidate = symbol + suffix
+ try:
+ ticker = yf.Ticker(candidate)
+ hist = ticker.history(period="5d")
+ if hist is not None and not hist.empty and len(hist) >= 1:
+ exchange = ""
+ try:
+ exchange = ticker.info.get("exchange", "")
+ except Exception:
+ pass
+ return {
+ "resolved_symbol": candidate,
+ "original_symbol": symbol,
+ "exchange": exchange,
+ "found": True
+ }
+ except Exception:
+ continue
+
+ # Nothing worked — return original
+ return {"resolved_symbol": symbol, "original_symbol": symbol, "exchange": "", "found": False}
+
+
def main(args=None):
# Support both worker pool (args parameter) and subprocess/CLI (sys.argv)
if args is None:
@@ -439,6 +494,13 @@ def main(args=None):
limit = int(args[2]) if len(args) > 2 else 50
result = search_symbols(query, limit)
+ elif command == "resolve_symbol":
+ if len(args) < 2:
+ result = {"error": "Usage: python yfinance_data.py resolve_symbol <symbol>"}
+ else:
+ symbol = args[1]
+ result = resolve_symbol(symbol)
+
else:
result = {"error": f"Unknown command: {command}"}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/backtest.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/backtest.rs
deleted file mode 100644
index 195e82bf5..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/backtest.rs
+++ /dev/null
@@ -1,386 +0,0 @@
-use crate::barter_integration::types::*;
-use crate::barter_integration::strategy::{Strategy, Signal};
-use rust_decimal::Decimal;
-use chrono::{DateTime, Utc};
-use std::collections::HashMap;
-
-/// Backtest engine
-pub struct BacktestEngine {
- config: BacktestConfig,
- capital: Decimal,
- positions: HashMap<String, Decimal>,
- trades: Vec<TradeRecord>,
- equity_curve: Vec<(DateTime<Utc>, Decimal)>,
-}
-
-impl BacktestEngine {
- pub fn new(config: BacktestConfig) -> Self {
- Self {
- capital: config.initial_capital,
- config,
- positions: HashMap::new(),
- trades: Vec::new(),
- equity_curve: Vec::new(),
- }
- }
-
- /// Run backtest with provided strategy and candle data
- pub async fn run(
- &mut self,
- strategy: &mut dyn Strategy,
- candle_data: HashMap<String, Vec<Candle>>,
- ) -> BarterResult<BacktestResult> {
- // Initialize strategy
- strategy.initialize(&self.config.strategy)?;
-
- // Collect all timestamps
- let mut all_timestamps: Vec<DateTime<Utc>> = candle_data
- .values()
- .flatten()
- .map(|c| c.timestamp)
- .collect();
- all_timestamps.sort();
- all_timestamps.dedup();
-
- // Filter timestamps within backtest range
- let timestamps: Vec<_> = all_timestamps
- .into_iter()
- .filter(|t| *t >= self.config.start_date && *t <= self.config.end_date)
- .collect();
-
- // Process each timestamp
- for timestamp in timestamps {
- for (symbol, candles) in &candle_data {
- if let Some(candle) = candles.iter().find(|c| c.timestamp == timestamp) {
- // Feed candle to strategy
- let signals = strategy.on_market_data(symbol, candle)?;
-
- // Execute signals
- for signal in signals {
- self.execute_signal(&signal, candle)?;
- }
-
- // Update equity curve
- let equity = self.calculate_equity(&candle_data, timestamp);
- self.equity_curve.push((timestamp, equity));
- }
- }
- }
-
- // Close all open positions at end
- self.close_all_positions(&candle_data)?;
-
- // Calculate metrics
- self.calculate_results()
- }
-
- /// Execute trading signal
- fn execute_signal(&mut self, signal: &Signal, current_candle: &Candle) -> BarterResult<()> {
- let price = signal.price.unwrap_or(current_candle.close);
- let cost = price * signal.quantity;
- let commission = cost * self.config.commission_rate;
-
- match signal.side {
- OrderSide::Buy => {
- let total_cost = cost + commission;
- if self.capital >= total_cost {
- self.capital -= total_cost;
- *self.positions.entry(signal.symbol.clone()).or_insert(Decimal::ZERO) +=
- signal.quantity;
-
- tracing::debug!(
- "BUY {} @ {}: qty={}, cost={}",
- signal.symbol,
- price,
- signal.quantity,
- total_cost
- );
- }
- }
- OrderSide::Sell => {
- let position = self.positions.get(&signal.symbol).copied().unwrap_or(Decimal::ZERO);
- if position >= signal.quantity {
- let proceeds = cost - commission;
- self.capital += proceeds;
- *self.positions.get_mut(&signal.symbol).unwrap() -= signal.quantity;
-
- tracing::debug!(
- "SELL {} @ {}: qty={}, proceeds={}",
- signal.symbol,
- price,
- signal.quantity,
- proceeds
- );
-
- // Record trade (simplified - assumes FIFO)
- // In production, track entry/exit properly
- }
- }
- }
-
- Ok(())
- }
-
- /// Close all open positions
- fn close_all_positions(
- &mut self,
- candle_data: &HashMap<String, Vec<Candle>>,
- ) -> BarterResult<()> {
- for (symbol, quantity) in self.positions.iter() {
- if *quantity > Decimal::ZERO {
- if let Some(candles) = candle_data.get(symbol) {
- if let Some(last_candle) = candles.last() {
- let proceeds = last_candle.close * *quantity;
- let commission = proceeds * self.config.commission_rate;
- self.capital += proceeds - commission;
- }
- }
- }
- }
- self.positions.clear();
- Ok(())
- }
-
- /// Calculate current equity
- fn calculate_equity(
- &self,
- candle_data: &HashMap<String, Vec<Candle>>,
- timestamp: DateTime<Utc>,
- ) -> Decimal {
- let mut equity = self.capital;
-
- for (symbol, quantity) in &self.positions {
- if let Some(candles) = candle_data.get(symbol) {
- if let Some(candle) = candles.iter().find(|c| c.timestamp == timestamp) {
- equity += candle.close * *quantity;
- }
- }
- }
-
- equity
- }
-
- /// Calculate backtest results
- fn calculate_results(&self) -> BarterResult<BacktestResult> {
- let final_equity = self.equity_curve.last().map(|(_, e)| *e).unwrap_or(self.config.initial_capital);
-
- let total_return = if self.config.initial_capital > Decimal::ZERO {
- ((final_equity - self.config.initial_capital) / self.config.initial_capital) * Decimal::new(100, 0)
- } else {
- Decimal::ZERO
- };
-
- // Calculate returns for each period
- let returns: Vec<Decimal> = self
- .equity_curve
- .windows(2)
- .map(|w| {
- let prev = w[0].1;
- let curr = w[1].1;
- if prev > Decimal::ZERO {
- (curr - prev) / prev
- } else {
- Decimal::ZERO
- }
- })
- .collect();
-
- // Sharpe ratio (simplified)
- let avg_return = if !returns.is_empty() {
- returns.iter().sum::<Decimal>() / Decimal::new(returns.len() as i64, 0)
- } else {
- Decimal::ZERO
- };
-
- let variance = if returns.len() > 1 {
- returns
- .iter()
- .map(|r| {
- let diff = *r - avg_return;
- diff * diff // Use multiplication instead of powi
- })
- .sum::<Decimal>()
- / Decimal::new((returns.len() - 1) as i64, 0)
- } else {
- Decimal::ZERO
- };
-
- // Simple sqrt approximation for Decimal
- let std_dev = if variance > Decimal::ZERO {
- // Convert to f64, sqrt, then back to Decimal
- let var_f64: f64 = variance.to_string().parse().unwrap_or(0.0);
- Decimal::try_from(var_f64.sqrt()).unwrap_or(Decimal::ZERO)
- } else {
- Decimal::ZERO
- };
-
- let sharpe_ratio = if std_dev > Decimal::ZERO {
- let annualization_f64 = 252.0_f64.sqrt();
- let annualization = Decimal::try_from(annualization_f64).unwrap_or(Decimal::ONE);
- avg_return / std_dev * annualization
- } else {
- Decimal::ZERO
- };
-
- // Max drawdown
- let mut max_equity = Decimal::ZERO;
- let mut max_drawdown = Decimal::ZERO;
-
- for (_, equity) in &self.equity_curve {
- if *equity > max_equity {
- max_equity = *equity;
- }
- let drawdown = if max_equity > Decimal::ZERO {
- (max_equity - *equity) / max_equity
- } else {
- Decimal::ZERO
- };
- if drawdown > max_drawdown {
- max_drawdown = drawdown;
- }
- }
-
- // Trade statistics
- let total_trades = self.trades.len() as u64;
- let winning_trades = self.trades.iter().filter(|t| t.pnl > Decimal::ZERO).count() as u64;
- let losing_trades = total_trades - winning_trades;
-
- let win_rate = if total_trades > 0 {
- Decimal::new(winning_trades as i64, 0) / Decimal::new(total_trades as i64, 0) * Decimal::new(100, 0)
- } else {
- Decimal::ZERO
- };
-
- let total_wins: Decimal = self
- .trades
- .iter()
- .filter(|t| t.pnl > Decimal::ZERO)
- .map(|t| t.pnl)
- .sum();
-
- let total_losses: Decimal = self
- .trades
- .iter()
- .filter(|t| t.pnl < Decimal::ZERO)
- .map(|t| t.pnl.abs())
- .sum();
-
- let average_win = if winning_trades > 0 {
- total_wins / Decimal::new(winning_trades as i64, 0)
- } else {
- Decimal::ZERO
- };
-
- let average_loss = if losing_trades > 0 {
- total_losses / Decimal::new(losing_trades as i64, 0)
- } else {
- Decimal::ZERO
- };
-
- let profit_factor = if total_losses > Decimal::ZERO {
- total_wins / total_losses
- } else if total_wins > Decimal::ZERO {
- Decimal::new(999, 0) // Very high if no losses
- } else {
- Decimal::ZERO
- };
-
- // Sortino ratio (simplified - using same std for now)
- let sortino_ratio = sharpe_ratio; // TODO: Calculate properly with downside deviation
-
- Ok(BacktestResult {
- total_return,
- sharpe_ratio,
- sortino_ratio,
- max_drawdown,
- win_rate,
- total_trades,
- winning_trades,
- losing_trades,
- average_win,
- average_loss,
- profit_factor,
- final_capital: final_equity,
- equity_curve: self.equity_curve.clone(),
- trades: self.trades.clone(),
- })
- }
-}
-
-/// Backtest runner utility
-pub struct BacktestRunner;
-
-impl BacktestRunner {
- /// Run single backtest
- pub async fn run_backtest(
- config: BacktestConfig,
- strategy: &mut dyn Strategy,
- candle_data: HashMap<String, Vec<Candle>>,
- ) -> BarterResult<BacktestResult> {
- let mut engine = BacktestEngine::new(config);
- engine.run(strategy, candle_data).await
- }
-
- /// Run parameter optimization (grid search)
- pub async fn optimize_parameters(
- base_config: BacktestConfig,
- _strategy_name: &str,
- parameter_grid: HashMap<String, Vec<serde_json::Value>>,
- candle_data: HashMap<String, Vec<Candle>>,
- ) -> BarterResult<Vec<(HashMap<String, serde_json::Value>, BacktestResult)>> {
- let mut results = Vec::new();
-
- // Generate all parameter combinations
- let combinations = Self::generate_combinations(&parameter_grid);
-
- for params in combinations {
- let mut config = base_config.clone();
- config.strategy.parameters = params.clone();
-
- // Create strategy instance (simplified - needs proper factory)
- let mut strategy = crate::barter_integration::strategy::SmaStrategy::new();
-
- let result = Self::run_backtest(
- config,
- &mut strategy,
- candle_data.clone(),
- )
- .await?;
-
- results.push((params, result));
- }
-
- // Sort by Sharpe ratio
- results.sort_by(|a, b| {
- b.1.sharpe_ratio
- .partial_cmp(&a.1.sharpe_ratio)
- .unwrap_or(std::cmp::Ordering::Equal)
- });
-
- Ok(results)
- }
-
- fn generate_combinations(
- grid: &HashMap<String, Vec<serde_json::Value>>,
- ) -> Vec<HashMap<String, serde_json::Value>> {
- if grid.is_empty() {
- return vec![HashMap::new()];
- }
-
- let mut results = vec![HashMap::new()];
-
- for (key, values) in grid {
- let mut new_results = Vec::new();
- for result in results {
- for value in values {
- let mut new_map = result.clone();
- new_map.insert(key.clone(), value.clone());
- new_results.push(new_map);
- }
- }
- results = new_results;
- }
-
- results
- }
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/commands.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/commands.rs
deleted file mode 100644
index de4539e6b..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/commands.rs
+++ /dev/null
@@ -1,312 +0,0 @@
-/// Tauri commands for frontend integration
-use crate::barter_integration::*;
-use tauri::State;
-use std::sync::Arc;
-use tokio::sync::Mutex;
-
-/// Global state for barter integration
-pub struct BarterState {
- pub market_data: Arc<Mutex<market_data::MarketDataManager>>,
- pub execution: Arc<Mutex<execution::ExecutionManager>>,
- pub strategy_registry: Arc<Mutex<strategy::StrategyRegistry>>,
-}
-
-impl BarterState {
- pub fn new(mode: TradingMode) -> Self {
- Self {
- market_data: Arc::new(Mutex::new(market_data::MarketDataManager::new())),
- execution: Arc::new(Mutex::new(execution::ExecutionManager::new(mode))),
- strategy_registry: Arc::new(Mutex::new(strategy::StrategyRegistry::default())),
- }
- }
-}
-
-// ====================
-// Market Data Commands
-// ====================
-
-#[tauri::command]
-pub async fn start_market_stream(
- config: MarketStreamConfig,
- state: State<'_, BarterState>,
-) -> Result<String, String> {
- state
- .market_data
- .lock()
- .await
- .start_stream(config)
- .await
- .map_err(|e| e.to_string())
-}
-
-#[tauri::command]
-pub async fn stop_market_stream(
- stream_id: String,
- state: State<'_, BarterState>,
-) -> Result<(), String> {
- state
- .market_data
- .lock()
- .await
- .stop_stream(&stream_id)
- .await
- .map_err(|e| e.to_string())
-}
-
-#[tauri::command]
-pub async fn get_active_streams(state: State<'_, BarterState>) -> Result<Vec<String>, String> {
- Ok(state.market_data.lock().await.get_active_streams())
-}
-
-#[tauri::command]
-pub async fn subscribe_symbols(
- stream_id: String,
- symbols: Vec<String>,
- state: State<'_, BarterState>,
-) -> Result<(), String> {
- state
- .market_data
- .lock()
- .await
- .subscribe(&stream_id, symbols)
- .await
- .map_err(|e| e.to_string())
-}
-
-#[tauri::command]
-pub async fn unsubscribe_symbols(
- stream_id: String,
- symbols: Vec<String>,
- state: State<'_, BarterState>,
-) -> Result<(), String> {
- state
- .market_data
- .lock()
- .await
- .unsubscribe(&stream_id, symbols)
- .await
- .map_err(|e| e.to_string())
-}
-
-// ====================
-// Execution Commands
-// ====================
-
-#[tauri::command]
-pub async fn submit_order(
- request: OrderRequest,
- state: State<'_, BarterState>,
-) -> Result<OrderResponse, String> {
- state
- .execution
- .lock()
- .await
- .submit_order(request)
- .await
- .map_err(|e| e.to_string())
-}
-
-#[tauri::command]
-pub async fn cancel_order(
- order_id: String,
- state: State<'_, BarterState>,
-) -> Result<OrderResponse, String> {
- state
- .execution
- .lock()
- .await
- .cancel_order(&order_id)
- .await
- .map_err(|e| e.to_string())
-}
-
-#[tauri::command]
-pub async fn get_order(order_id: String, state: State<'_, BarterState>) -> Result<OrderResponse, String> {
- state
- .execution
- .lock()
- .await
- .get_order(&order_id)
- .map_err(|e| e.to_string())
-}
-
-#[tauri::command]
-pub async fn get_all_orders(state: State<'_, BarterState>) -> Result<Vec<OrderResponse>, String> {
- Ok(state.execution.lock().await.get_all_orders())
-}
-
-#[tauri::command]
-pub async fn get_open_orders(state: State<'_, BarterState>) -> Result<Vec<OrderResponse>, String> {
- Ok(state.execution.lock().await.get_open_orders())
-}
-
-#[tauri::command]
-pub async fn get_positions(state: State<'_, BarterState>) -> Result<Vec<Position>, String> {
- Ok(state.execution.lock().await.get_positions())
-}
-
-#[tauri::command]
-pub async fn get_position(
- exchange: Exchange,
- symbol: String,
- state: State<'_, BarterState>,
-) -> Result<Option<Position>, String> {
- Ok(state.execution.lock().await.get_position(&exchange, &symbol))
-}
-
-#[tauri::command]
-pub async fn get_balances(state: State<'_, BarterState>) -> Result<Vec<Balance>, String> {
- Ok(state.execution.lock().await.get_balances())
-}
-
-#[tauri::command]
-pub async fn close_all_positions(
- state: State<'_, BarterState>,
-) -> Result<Vec<OrderResponse>, String> {
- state
- .execution
- .lock()
- .await
- .close_all_positions()
- .await
- .map_err(|e| e.to_string())
-}
-
-// ====================
-// Strategy Commands
-// ====================
-
-#[tauri::command]
-pub async fn list_strategies(state: State<'_, BarterState>) -> Result<Vec<String>, String> {
- Ok(state.strategy_registry.lock().await.list_strategies())
-}
-
-#[tauri::command]
-pub async fn get_strategy_parameters(
- strategy_name: String,
- state: State<'_, BarterState>,
-) -> Result<std::collections::HashMap<String, serde_json::Value>, String> {
- let registry = state.strategy_registry.lock().await;
- registry
- .get(&strategy_name)
- .map(|s| s.get_parameters())
- .ok_or_else(|| format!("Strategy not found: {}", strategy_name))
-}
-
-#[tauri::command]
-pub async fn update_strategy_parameters(
- strategy_name: String,
- parameters: std::collections::HashMap<String, serde_json::Value>,
- state: State<'_, BarterState>,
-) -> Result<(), String> {
- let mut registry = state.strategy_registry.lock().await;
- let strategy = registry
- .get_mut(&strategy_name)
- .ok_or_else(|| format!("Strategy not found: {}", strategy_name))?;
- strategy.as_mut().update_parameters(parameters)
- .map_err(|e| e.to_string())
-}
-
-// ====================
-// Backtest Commands
-// ====================
-
-#[tauri::command]
-pub async fn run_backtest(
- config: BacktestConfig,
- candle_data: std::collections::HashMap<String, Vec<Candle>>,
- _state: State<'_, BarterState>,
-) -> Result<BacktestResult, String> {
- // Create a temporary strategy instance
- let mut strategy = strategy::SmaStrategy::new();
-
- backtest::BacktestRunner::run_backtest(config, &mut strategy, candle_data)
- .await
- .map_err(|e| e.to_string())
-}
-
-#[tauri::command]
-pub async fn optimize_strategy(
- config: BacktestConfig,
- parameter_grid: std::collections::HashMap<String, Vec<serde_json::Value>>,
- candle_data: std::collections::HashMap<String, Vec<Candle>>,
-) -> Result<Vec<(std::collections::HashMap<String, serde_json::Value>, BacktestResult)>, String> {
- backtest::BacktestRunner::optimize_parameters(
- config,
- "SMA Crossover",
- parameter_grid,
- candle_data,
- )
- .await
- .map_err(|e| e.to_string())
-}
-
-// ====================
-// Utility Commands
-// ====================
-
-#[tauri::command]
-pub fn get_supported_exchanges() -> Vec<String> {
- vec![
- "binance".to_string(),
- "bybit".to_string(),
- "coinbase".to_string(),
- "kraken".to_string(),
- "okx".to_string(),
- "bitfinex".to_string(),
- "bitmex".to_string(),
- "gateio".to_string(),
- ]
-}
-
-#[tauri::command]
-pub fn get_trading_modes() -> Vec<String> {
- vec![
- "live".to_string(),
- "paper".to_string(),
- "backtest".to_string(),
- ]
-}
-
-// ====================
-// Data Mapping Commands
-// ====================
-
-#[tauri::command]
-pub async fn parse_databento_dataset(
- file_path: String,
-) -> Result<std::collections::HashMap<String, Vec<Candle>>, String> {
- data_mapper::parse_databento_file(&file_path)
- .map_err(|e| e.to_string())
-}
-
-#[tauri::command]
-pub async fn map_custom_dataset(
- mapping: data_mapper::DatasetMapping,
- rows: Vec<std::collections::HashMap<String, String>>,
- symbol: String,
-) -> Result<Vec<Candle>, String> {
- let mapper = data_mapper::DataMapper::new(mapping);
- let data_rows: Vec<data_mapper::DataRow> = rows
- .into_iter()
- .map(|fields| data_mapper::DataRow { fields })
- .collect();
-
- mapper.map_ohlcv_data(data_rows, &symbol)
- .map_err(|e| e.to_string())
-}
-
-#[tauri::command]
-pub async fn map_tick_dataset(
- mapping: data_mapper::DatasetMapping,
- rows: Vec<std::collections::HashMap<String, String>>,
-) -> Result<std::collections::HashMap<String, Vec<Candle>>, String> {
- let mapper = data_mapper::DataMapper::new(mapping);
- let data_rows: Vec<data_mapper::DataRow> = rows
- .into_iter()
- .map(|fields| data_mapper::DataRow { fields })
- .collect();
-
- mapper.map_tick_data(data_rows)
- .map_err(|e| e.to_string())
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/data_mapper.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/data_mapper.rs
deleted file mode 100644
index ddb82db04..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/data_mapper.rs
+++ /dev/null
@@ -1,378 +0,0 @@
-use crate::barter_integration::types::*;
-use chrono::{DateTime, Utc, TimeZone};
-use rust_decimal::Decimal;
-use std::collections::HashMap;
-use serde::{Deserialize, Serialize};
-
-/// Column mapping configuration for user datasets
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct DatasetMapping {
- pub timestamp_column: String,
- pub timestamp_format: TimestampFormat,
- pub open_column: Option<String>,
- pub high_column: Option<String>,
- pub low_column: Option<String>,
- pub close_column: Option<String>,
- pub volume_column: Option<String>,
- pub price_column: Option<String>, // For tick data
- pub size_column: Option<String>, // For tick data
- pub symbol_column: Option<String>,
- pub aggregation_interval: Option<String>, // "1m", "5m", "1h", etc.
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub enum TimestampFormat {
- UnixSeconds,
- UnixMilliseconds,
- UnixMicroseconds,
- UnixNanoseconds,
- Rfc3339,
- Custom(String),
-}
-
-/// Generic data row that can be mapped
-#[derive(Debug, Clone)]
-pub struct DataRow {
- pub fields: HashMap<String, String>,
-}
-
-/// Trade tick for aggregation
-#[derive(Debug, Clone)]
-struct TradeTick {
- timestamp: DateTime<Utc>,
- price: Decimal,
- size: Decimal,
-}
-
-/// Data mapper for converting user datasets to candle format
-pub struct DataMapper {
- mapping: DatasetMapping,
-}
-
-impl DataMapper {
- pub fn new(mapping: DatasetMapping) -> Self {
- Self { mapping }
- }
-
- /// Parse timestamp based on format
- fn parse_timestamp(&self, value: &str) -> BarterResult<DateTime<Utc>> {
- match &self.mapping.timestamp_format {
- TimestampFormat::UnixSeconds => {
- let secs: i64 = value.parse()
- .map_err(|_| BarterError::Config("Invalid timestamp".into()))?;
- Ok(Utc.timestamp_opt(secs, 0).unwrap())
- }
- TimestampFormat::UnixMilliseconds => {
- let millis: i64 = value.parse()
- .map_err(|_| BarterError::Config("Invalid timestamp".into()))?;
- Ok(Utc.timestamp_millis_opt(millis).unwrap())
- }
- TimestampFormat::UnixMicroseconds => {
- let micros: i64 = value.parse()
- .map_err(|_| BarterError::Config("Invalid timestamp".into()))?;
- Ok(Utc.timestamp_micros(micros).unwrap())
- }
- TimestampFormat::UnixNanoseconds => {
- let nanos: i64 = value.parse()
- .map_err(|_| BarterError::Config("Invalid timestamp".into()))?;
- Ok(Utc.timestamp_nanos(nanos))
- }
- TimestampFormat::Rfc3339 => {
- DateTime::parse_from_rfc3339(value)
- .map(|dt| dt.with_timezone(&Utc))
- .map_err(|_| BarterError::Config("Invalid RFC3339 timestamp".into()))
- }
- TimestampFormat::Custom(format) => {
- // Use chrono format string
- chrono::NaiveDateTime::parse_from_str(value, format)
- .map(|dt| Utc.from_utc_datetime(&dt))
- .map_err(|_| BarterError::Config("Invalid custom timestamp".into()))
- }
- }
- }
-
- /// Parse decimal value
- fn parse_decimal(&self, value: &str) -> BarterResult<Decimal> {
- value.parse::<Decimal>()
- .map_err(|_| BarterError::Config(format!("Invalid decimal: {}", value)))
- }
-
- /// Convert OHLCV data rows to candles
- pub fn map_ohlcv_data(&self, rows: Vec<DataRow>, _symbol: &str) -> BarterResult<Vec<Candle>> {
- let mut candles = Vec::new();
-
- for row in rows {
- let timestamp = self.parse_timestamp(
- row.fields.get(&self.mapping.timestamp_column)
- .ok_or_else(|| BarterError::Config("Timestamp column not found".into()))?
- )?;
-
- let open = if let Some(col) = &self.mapping.open_column {
- self.parse_decimal(row.fields.get(col)
- .ok_or_else(|| BarterError::Config("Open column not found".into()))?)?
- } else {
- Decimal::ZERO
- };
-
- let high = if let Some(col) = &self.mapping.high_column {
- self.parse_decimal(row.fields.get(col)
- .ok_or_else(|| BarterError::Config("High column not found".into()))?)?
- } else {
- open
- };
-
- let low = if let Some(col) = &self.mapping.low_column {
- self.parse_decimal(row.fields.get(col)
- .ok_or_else(|| BarterError::Config("Low column not found".into()))?)?
- } else {
- open
- };
-
- let close = if let Some(col) = &self.mapping.close_column {
- self.parse_decimal(row.fields.get(col)
- .ok_or_else(|| BarterError::Config("Close column not found".into()))?)?
- } else {
- open
- };
-
- let volume = if let Some(col) = &self.mapping.volume_column {
- self.parse_decimal(row.fields.get(col)
- .ok_or_else(|| BarterError::Config("Volume column not found".into()))?)?
- } else {
- Decimal::ZERO
- };
-
- candles.push(Candle {
- timestamp,
- open,
- high,
- low,
- close,
- volume,
- });
- }
-
- Ok(candles)
- }
-
- /// Convert tick data to candles with aggregation
- pub fn map_tick_data(&self, rows: Vec<DataRow>) -> BarterResult<HashMap<String, Vec<Candle>>> {
- // Parse all ticks
- let mut ticks_by_symbol: HashMap<String, Vec<TradeTick>> = HashMap::new();
-
- for row in rows {
- let timestamp = self.parse_timestamp(
- row.fields.get(&self.mapping.timestamp_column)
- .ok_or_else(|| BarterError::Config("Timestamp column not found".into()))?
- )?;
-
- let price = if let Some(col) = &self.mapping.price_column {
- self.parse_decimal(row.fields.get(col)
- .ok_or_else(|| BarterError::Config("Price column not found".into()))?)?
- } else {
- return Err(BarterError::Config("Price column required for tick data".into()));
- };
-
- let size = if let Some(col) = &self.mapping.size_column {
- self.parse_decimal(row.fields.get(col)
- .ok_or_else(|| BarterError::Config("Size column not found".into()))?)?
- } else {
- Decimal::ONE
- };
-
- let symbol = if let Some(col) = &self.mapping.symbol_column {
- row.fields.get(col)
- .ok_or_else(|| BarterError::Config("Symbol column not found".into()))?
- .clone()
- } else {
- "UNKNOWN".to_string()
- };
-
- ticks_by_symbol.entry(symbol).or_insert_with(Vec::new).push(TradeTick {
- timestamp,
- price,
- size,
- });
- }
-
- // Aggregate ticks into candles
- let mut result = HashMap::new();
- let interval_secs = self.parse_interval(
- self.mapping.aggregation_interval.as_deref().unwrap_or("1m")
- )?;
-
- for (symbol, mut ticks) in ticks_by_symbol {
- ticks.sort_by_key(|t| t.timestamp);
- let candles = self.aggregate_ticks(ticks, interval_secs)?;
- result.insert(symbol, candles);
- }
-
- Ok(result)
- }
-
- /// Parse interval string to seconds
- fn parse_interval(&self, interval: &str) -> BarterResult<i64> {
- let num: i64 = interval[..interval.len()-1].parse()
- .map_err(|_| BarterError::Config("Invalid interval".into()))?;
-
- match interval.chars().last().unwrap() {
- 's' => Ok(num),
- 'm' => Ok(num * 60),
- 'h' => Ok(num * 3600),
- 'd' => Ok(num * 86400),
- _ => Err(BarterError::Config("Invalid interval suffix".into()))
- }
- }
-
- /// Aggregate ticks into candles
- fn aggregate_ticks(&self, ticks: Vec<TradeTick>, interval_secs: i64) -> BarterResult<Vec<Candle>> {
- if ticks.is_empty() {
- return Ok(Vec::new());
- }
-
- let mut candles = Vec::new();
- let start_time = ticks[0].timestamp;
- let mut current_bucket_start = start_time.timestamp() - (start_time.timestamp() % interval_secs);
-
- let mut bucket_ticks: Vec<TradeTick> = Vec::new();
-
- for tick in ticks {
- let tick_bucket = tick.timestamp.timestamp() - (tick.timestamp.timestamp() % interval_secs);
-
- if tick_bucket > current_bucket_start {
- // Finalize current bucket
- if !bucket_ticks.is_empty() {
- candles.push(self.create_candle_from_ticks(&bucket_ticks, current_bucket_start)?);
- bucket_ticks.clear();
- }
- current_bucket_start = tick_bucket;
- }
-
- bucket_ticks.push(tick);
- }
-
- // Finalize last bucket
- if !bucket_ticks.is_empty() {
- candles.push(self.create_candle_from_ticks(&bucket_ticks, current_bucket_start)?);
- }
-
- Ok(candles)
- }
-
- /// Create candle from ticks
- fn create_candle_from_ticks(&self, ticks: &[TradeTick], bucket_timestamp: i64) -> BarterResult<Candle> {
- let open = ticks.first().unwrap().price;
- let close = ticks.last().unwrap().price;
- let high = ticks.iter().map(|t| t.price).max().unwrap();
- let low = ticks.iter().map(|t| t.price).min().unwrap();
- let volume: Decimal = ticks.iter().map(|t| t.size).sum();
-
- Ok(Candle {
- timestamp: Utc.timestamp_opt(bucket_timestamp, 0).unwrap(),
- open,
- high,
- low,
- close,
- volume,
- })
- }
-}
-
-/// Parse Databento TradeMsg format specifically (optimized)
-pub fn parse_databento_file(file_path: &str) -> BarterResult<HashMap<String, Vec<Candle>>> {
- use std::fs;
- use rayon::prelude::*;
-
- let content = fs::read_to_string(file_path)
- .map_err(|e| BarterError::Config(format!("Failed to read file: {}", e)))?;
-
- // Parse in parallel
- let ticks_by_instrument: HashMap<u32, Vec<TradeTick>> = content
- .par_lines()
- .filter_map(|line| {
- // Fast inline parsing without regex
- parse_trade_line(line)
- })
- .fold(
- || HashMap::new(),
- |mut acc: HashMap<u32, Vec<TradeTick>>, tick| {
- acc.entry(tick.0).or_insert_with(Vec::new).push(tick.1);
- acc
- }
- )
- .reduce(
- || HashMap::new(),
- |mut acc, map| {
- for (id, mut ticks) in map {
- acc.entry(id).or_insert_with(Vec::new).append(&mut ticks);
- }
- acc
- }
- );
-
- // Aggregate to 1-minute candles
- let mapper = DataMapper::new(DatasetMapping {
- timestamp_column: String::new(),
- timestamp_format: TimestampFormat::UnixNanoseconds,
- open_column: None,
- high_column: None,
- low_column: None,
- close_column: None,
- volume_column: None,
- price_column: None,
- size_column: None,
- symbol_column: None,
- aggregation_interval: Some("1m".to_string()),
- });
-
- let mut result = HashMap::new();
- for (instrument_id, mut ticks) in ticks_by_instrument {
- ticks.sort_by_key(|t| t.timestamp);
- let candles = mapper.aggregate_ticks(ticks, 60)?;
- let symbol = map_instrument_id_to_symbol(instrument_id);
- result.insert(symbol, candles);
- }
-
- Ok(result)
-}
-
-/// Map Databento instrument IDs to symbols
-fn map_instrument_id_to_symbol(id: u32) -> String {
- match id {
- 271726 => "BTC".to_string(),
- 3403 | 13615 => "ES".to_string(),
- 2895 | 13505 => "NQ".to_string(),
- _ => format!("INST_{}", id),
- }
-}
-
-/// Fast inline parser without regex
-#[inline]
-fn parse_trade_line(line: &str) -> Option<(u32, TradeTick)> {
- // TradeMsg { hd: RecordHeader { ... ts_event: 1654179600001940663 }, price: 32619.000000000, size: 1, ...
-
- let ts_start = line.find("ts_event: ")? + 10;
- let ts_end = line[ts_start..].find(' ')?;
- let ts_nanos: i64 = line[ts_start..ts_start + ts_end].parse().ok()?;
-
- let inst_start = line.find("instrument_id: ")? + 15;
- let inst_end = line[inst_start..].find(',')?;
- let instrument_id: u32 = line[inst_start..inst_start + inst_end].parse().ok()?;
-
- let price_start = line.find("price: ")? + 7;
- let price_end = line[price_start..].find(',')?;
- let price: f64 = line[price_start..price_start + price_end].parse().ok()?;
-
- let size_start = line.find("size: ")? + 6;
- let size_end = line[size_start..].find(',')?;
- let size: i64 = line[size_start..size_start + size_end].parse().ok()?;
-
- let timestamp = Utc.timestamp_nanos(ts_nanos);
- let tick = TradeTick {
- timestamp,
- price: Decimal::try_from(price).unwrap_or(Decimal::ZERO),
- size: Decimal::new(size, 0),
- };
-
- Some((instrument_id, tick))
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/execution.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/execution.rs
deleted file mode 100644
index 0e801163e..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/execution.rs
+++ /dev/null
@@ -1,229 +0,0 @@
-use crate::barter_integration::types::*;
-use std::collections::HashMap;
-use parking_lot::RwLock;
-use std::sync::Arc;
-use uuid::Uuid;
-use chrono::Utc;
-
-/// Order execution manager
-pub struct ExecutionManager {
- mode: TradingMode,
- orders: Arc<RwLock<HashMap<String, OrderResponse>>>,
- positions: Arc<RwLock<HashMap<String, Position>>>,
- balances: Arc<RwLock<HashMap<String, Balance>>>,
-}
-
-impl ExecutionManager {
- pub fn new(mode: TradingMode) -> Self {
- Self {
- mode,
- orders: Arc::new(RwLock::new(HashMap::new())),
- positions: Arc::new(RwLock::new(HashMap::new())),
- balances: Arc::new(RwLock::new(HashMap::new())),
- }
- }
-
- /// Submit order
- pub async fn submit_order(&self, request: OrderRequest) -> BarterResult<OrderResponse> {
- let order_id = Uuid::new_v4().to_string();
- let client_order_id = Uuid::new_v4().to_string();
-
- let order = OrderResponse {
- order_id: order_id.clone(),
- client_order_id,
- exchange: request.exchange,
- symbol: request.symbol,
- side: request.side,
- order_type: request.order_type,
- status: OrderStatus::Pending,
- quantity: request.quantity,
- filled_quantity: rust_decimal::Decimal::ZERO,
- price: request.price,
- average_price: None,
- created_at: Utc::now(),
- updated_at: Utc::now(),
- };
-
- // Store order
- self.orders.write().insert(order_id.clone(), order.clone());
-
- // Simulate order processing based on mode
- match self.mode {
- TradingMode::Live => {
- // TODO: Integrate with actual exchange API
- tracing::info!("Live order submitted: {}", order_id);
- }
- TradingMode::Paper => {
- // Simulate order execution
- self.simulate_order_fill(order_id.clone()).await?;
- }
- TradingMode::Backtest => {
- // Backtest mode handled separately
- }
- }
-
- Ok(order)
- }
-
- /// Cancel order
- pub async fn cancel_order(&self, order_id: &str) -> BarterResult<OrderResponse> {
- let mut orders = self.orders.write();
-
- if let Some(order) = orders.get_mut(order_id) {
- if order.status == OrderStatus::Open || order.status == OrderStatus::PartiallyFilled {
- order.status = OrderStatus::Cancelled;
- order.updated_at = Utc::now();
- Ok(order.clone())
- } else {
- Err(BarterError::Order(format!(
- "Cannot cancel order in status: {:?}",
- order.status
- )))
- }
- } else {
- Err(BarterError::Order(format!("Order not found: {}", order_id)))
- }
- }
-
- /// Get order by ID
- pub fn get_order(&self, order_id: &str) -> BarterResult<OrderResponse> {
- self.orders
- .read()
- .get(order_id)
- .cloned()
- .ok_or_else(|| BarterError::Order(format!("Order not found: {}", order_id)))
- }
-
- /// Get all orders
- pub fn get_all_orders(&self) -> Vec<OrderResponse> {
- self.orders.read().values().cloned().collect()
- }
-
- /// Get open orders
- pub fn get_open_orders(&self) -> Vec<OrderResponse> {
- self.orders
- .read()
- .values()
- .filter(|o| o.status == OrderStatus::Open || o.status == OrderStatus::PartiallyFilled)
- .cloned()
- .collect()
- }
-
- /// Get positions
- pub fn get_positions(&self) -> Vec<Position> {
- self.positions.read().values().cloned().collect()
- }
-
- /// Get position for symbol
- pub fn get_position(&self, exchange: &Exchange, symbol: &str) -> Option<Position> {
- let key = format!("{}_{}", format!("{:?}", exchange), symbol);
- self.positions.read().get(&key).cloned()
- }
-
- /// Get balances
- pub fn get_balances(&self) -> Vec<Balance> {
- self.balances.read().values().cloned().collect()
- }
-
- /// Update balance
- pub fn update_balance(&self, asset: String, free: rust_decimal::Decimal, locked: rust_decimal::Decimal) {
- let balance = Balance {
- asset: asset.clone(),
- free,
- locked,
- total: free + locked,
- };
- self.balances.write().insert(asset, balance);
- }
-
- /// Simulate order fill (paper trading)
- async fn simulate_order_fill(&self, order_id: String) -> BarterResult<()> {
- // Simulate network delay
- tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
-
- // Clone order data before updating position
- let order_data = {
- let mut orders = self.orders.write();
- if let Some(order) = orders.get_mut(&order_id) {
- order.status = OrderStatus::Filled;
- order.filled_quantity = order.quantity;
- order.average_price = order.price;
- order.updated_at = Utc::now();
-
- tracing::info!("Order filled (paper): {}", order_id);
- order.clone()
- } else {
- return Ok(());
- }
- };
-
- // Update position after releasing orders lock
- self.update_position_from_order(&order_data);
-
- Ok(())
- }
-
- /// Update position from filled order
- fn update_position_from_order(&self, order: &OrderResponse) {
- let position_key = format!("{}_{}", format!("{:?}", order.exchange), order.symbol);
- let mut positions = self.positions.write();
-
- if let Some(existing_pos) = positions.get_mut(&position_key) {
- // Update existing position
- match order.side {
- OrderSide::Buy => {
- let total_qty = existing_pos.quantity + order.filled_quantity;
- let total_cost = (existing_pos.entry_price * existing_pos.quantity)
- + (order.average_price.unwrap_or_default() * order.filled_quantity);
- existing_pos.entry_price = total_cost / total_qty;
- existing_pos.quantity = total_qty;
- }
- OrderSide::Sell => {
- existing_pos.quantity -= order.filled_quantity;
- }
- }
- } else {
- // Create new position
- let position = Position {
- exchange: order.exchange.clone(),
- symbol: order.symbol.clone(),
- side: order.side,
- quantity: order.filled_quantity,
- entry_price: order.average_price.unwrap_or_default(),
- current_price: order.average_price.unwrap_or_default(),
- unrealized_pnl: rust_decimal::Decimal::ZERO,
- realized_pnl: rust_decimal::Decimal::ZERO,
- };
- positions.insert(position_key, position);
- }
- }
-
- /// Close all positions
- pub async fn close_all_positions(&self) -> BarterResult<Vec<OrderResponse>> {
- let positions = self.get_positions();
- let mut orders = Vec::new();
-
- for position in positions {
- let opposite_side = match position.side {
- OrderSide::Buy => OrderSide::Sell,
- OrderSide::Sell => OrderSide::Buy,
- };
-
- let request = OrderRequest {
- exchange: position.exchange,
- symbol: position.symbol,
- side: opposite_side,
- order_type: OrderType::Market,
- quantity: position.quantity,
- price: None,
- stop_price: None,
- time_in_force: None,
- };
-
- let order = self.submit_order(request).await?;
- orders.push(order);
- }
-
- Ok(orders)
- }
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/market_data.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/market_data.rs
deleted file mode 100644
index 2348bf7d3..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/market_data.rs
+++ /dev/null
@@ -1,133 +0,0 @@
-use crate::barter_integration::types::*;
-use tokio::sync::mpsc;
-use std::collections::HashMap;
-use parking_lot::RwLock;
-use std::sync::Arc;
-
- // Re-export for compatibility
-
-/// Market data manager
-pub struct MarketDataManager {
- streams: Arc<RwLock<HashMap<String, MarketStream>>>,
-}
-
-/// Individual market stream
-struct MarketStream {
- exchange: Exchange,
- symbols: Vec<String>,
- _tx: mpsc::UnboundedSender<MarketEvent>,
-}
-
-/// Market events
-#[derive(Debug, Clone)]
-pub enum MarketEvent {
- Trade(Trade),
- OrderBook(OrderBook),
- Candle(Candle),
-}
-
-impl MarketDataManager {
- pub fn new() -> Self {
- Self {
- streams: Arc::new(RwLock::new(HashMap::new())),
- }
- }
-
- /// Start market data stream
- pub async fn start_stream(
- &self,
- config: MarketStreamConfig,
- ) -> BarterResult<String> {
- let stream_id = format!("{}_{}",
- format!("{:?}", config.exchange).to_lowercase(),
- config.symbols.join("_")
- );
-
- let (tx, mut rx) = mpsc::unbounded_channel();
-
- let stream = MarketStream {
- exchange: config.exchange.clone(),
- symbols: config.symbols.clone(),
- _tx: tx.clone(),
- };
-
- self.streams.write().insert(stream_id.clone(), stream);
-
- // Spawn background task to handle market data
- tokio::spawn(async move {
- while let Some(event) = rx.recv().await {
- // Process market events
- match event {
- MarketEvent::Trade(trade) => {
- tracing::debug!("Received trade: {:?}", trade);
- }
- MarketEvent::OrderBook(_book) => {
- tracing::debug!("Received orderbook update");
- }
- MarketEvent::Candle(candle) => {
- tracing::debug!("Received candle: {:?}", candle);
- }
- }
- }
- });
-
- Ok(stream_id)
- }
-
- /// Stop market data stream
- pub async fn stop_stream(&self, stream_id: &str) -> BarterResult<()> {
- self.streams.write().remove(stream_id);
- Ok(())
- }
-
- /// Get active streams
- pub fn get_active_streams(&self) -> Vec<String> {
- self.streams.read().keys().cloned().collect()
- }
-
- /// Subscribe to specific symbols
- pub async fn subscribe(
- &self,
- stream_id: &str,
- symbols: Vec<String>,
- ) -> BarterResult<()> {
- let mut streams = self.streams.write();
- if let Some(stream) = streams.get_mut(stream_id) {
- for symbol in symbols {
- if !stream.symbols.contains(&symbol) {
- stream.symbols.push(symbol);
- }
- }
- Ok(())
- } else {
- Err(BarterError::MarketData(format!(
- "Stream not found: {}",
- stream_id
- )))
- }
- }
-
- /// Unsubscribe from symbols
- pub async fn unsubscribe(
- &self,
- stream_id: &str,
- symbols: Vec<String>,
- ) -> BarterResult<()> {
- let mut streams = self.streams.write();
- if let Some(stream) = streams.get_mut(stream_id) {
- stream.symbols.retain(|s| !symbols.contains(s));
- Ok(())
- } else {
- Err(BarterError::MarketData(format!(
- "Stream not found: {}",
- stream_id
- )))
- }
- }
-}
-
-impl Default for MarketDataManager {
- fn default() -> Self {
- Self::new()
- }
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/mod.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/mod.rs
deleted file mode 100644
index df9316301..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/mod.rs
+++ /dev/null
@@ -1,34 +0,0 @@
-/// Barter-rs integration module
-/// Provides live trading, paper trading, and backtesting capabilities
-///
-/// Architecture:
-/// - market_data: Stream real-time market data from exchanges
-/// - execution: Execute orders and manage positions
-/// - strategy: Pluggable trading strategy interface
-/// - backtest: Backtesting engine with performance metrics
-/// - types: Common data structures and types
-/// - commands: Tauri commands for frontend integration
-
-pub mod types;
-pub mod market_data;
-pub mod execution;
-pub mod strategy;
-pub mod backtest;
-pub mod commands;
-pub mod data_mapper;
-pub mod risk_management;
-
-#[cfg(test)]
-mod tests;
-
-#[cfg(test)]
-mod test_databento;
-
-#[cfg(test)]
-mod test_csv_mapping;
-
-#[cfg(test)]
-mod test_risk_management;
-
-pub use types::*;
-pub use commands::*;
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/risk_management.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/risk_management.rs
deleted file mode 100644
index 53bb07fb4..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/risk_management.rs
+++ /dev/null
@@ -1,418 +0,0 @@
-/// Risk Management Module
-/// Provides position sizing, stop-loss, risk limits, and leverage controls
-
-use crate::barter_integration::types::*;
-use rust_decimal::Decimal;
-use serde::{Deserialize, Serialize};
-use std::collections::HashMap;
-
-/// Position sizing method
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub enum PositionSizingMethod {
- /// Fixed dollar amount per trade
- FixedAmount(Decimal),
- /// Fixed percentage of portfolio
- FixedPercentage(Decimal),
- /// Kelly Criterion (f = (bp - q) / b where b=odds, p=win prob, q=loss prob)
- Kelly { win_rate: Decimal, avg_win: Decimal, avg_loss: Decimal },
- /// Risk-based (risk % of capital per trade)
- RiskBased { risk_per_trade: Decimal },
- /// Volatility-based (ATR multiplier)
- VolatilityBased { atr_multiplier: Decimal },
-}
-
-/// Stop-loss configuration
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub enum StopLossType {
- /// No stop-loss
- None,
- /// Fixed percentage from entry
- FixedPercentage(Decimal),
- /// Fixed dollar amount
- FixedAmount(Decimal),
- /// Trailing stop (follows price)
- Trailing { percentage: Decimal },
- /// ATR-based stop
- ATRBased { multiplier: Decimal, period: usize },
-}
-
-/// Take-profit configuration
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub enum TakeProfitType {
- /// No take-profit
- None,
- /// Fixed percentage from entry
- FixedPercentage(Decimal),
- /// Fixed dollar amount
- FixedAmount(Decimal),
- /// Risk-reward ratio (e.g., 2:1)
- RiskRewardRatio(Decimal),
-}
-
-/// Risk limits configuration
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct RiskLimits {
- /// Maximum drawdown before stopping (e.g., 0.10 = 10%)
- pub max_drawdown: Option<Decimal>,
- /// Maximum daily loss
- pub max_daily_loss: Option<Decimal>,
- /// Maximum position size as % of portfolio
- pub max_position_size: Option<Decimal>,
- /// Maximum number of concurrent positions
- pub max_positions: Option<usize>,
- /// Maximum leverage allowed
- pub max_leverage: Option<Decimal>,
- /// Maximum risk per trade as % of portfolio
- pub max_risk_per_trade: Option<Decimal>,
-}
-
-/// Risk management configuration
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct RiskConfig {
- pub position_sizing: PositionSizingMethod,
- pub stop_loss: StopLossType,
- pub take_profit: TakeProfitType,
- pub limits: RiskLimits,
-}
-
-impl Default for RiskConfig {
- fn default() -> Self {
- Self {
- position_sizing: PositionSizingMethod::FixedPercentage(Decimal::new(2, 2)), // 2%
- stop_loss: StopLossType::FixedPercentage(Decimal::new(2, 2)), // 2%
- take_profit: TakeProfitType::RiskRewardRatio(Decimal::new(2, 0)), // 2:1
- limits: RiskLimits {
- max_drawdown: Some(Decimal::new(20, 2)), // 20%
- max_daily_loss: Some(Decimal::new(5, 2)), // 5%
- max_position_size: Some(Decimal::new(10, 2)), // 10%
- max_positions: Some(5),
- max_leverage: Some(Decimal::new(3, 0)), // 3x
- max_risk_per_trade: Some(Decimal::new(2, 2)), // 2%
- },
- }
- }
-}
-
-/// Risk manager state
-pub struct RiskManager {
- config: RiskConfig,
- initial_capital: Decimal,
- peak_equity: Decimal,
- daily_start_equity: Decimal,
- active_positions: HashMap<String, PositionRisk>,
-}
-
-/// Position risk tracking
-#[derive(Debug, Clone)]
-struct PositionRisk {
- symbol: String,
- entry_price: Decimal,
- quantity: Decimal,
- stop_loss_price: Option<Decimal>,
- take_profit_price: Option<Decimal>,
- trailing_stop_price: Option<Decimal>,
- atr_values: Vec<Decimal>, // For ATR-based stops
-}
-
-impl RiskManager {
- pub fn new(config: RiskConfig, initial_capital: Decimal) -> Self {
- Self {
- config,
- initial_capital,
- peak_equity: initial_capital,
- daily_start_equity: initial_capital,
- active_positions: HashMap::new(),
- }
- }
-
- /// Calculate position size based on configured method
- pub fn calculate_position_size(
- &self,
- current_capital: Decimal,
- entry_price: Decimal,
- stop_loss_price: Option<Decimal>,
- ) -> BarterResult<Decimal> {
- let size = match &self.config.position_sizing {
- PositionSizingMethod::FixedAmount(amount) => {
- amount / entry_price
- }
- PositionSizingMethod::FixedPercentage(pct) => {
- (current_capital * pct) / entry_price
- }
- PositionSizingMethod::Kelly { win_rate, avg_win, avg_loss } => {
- if *avg_loss == Decimal::ZERO {
- return Err(BarterError::Config("Average loss cannot be zero for Kelly".into()));
- }
- let win_loss_ratio = avg_win / avg_loss;
- let kelly_fraction = (win_rate * win_loss_ratio - (Decimal::ONE - win_rate)) / win_loss_ratio;
- let kelly_fraction = kelly_fraction.max(Decimal::ZERO).min(Decimal::new(25, 2)); // Cap at 25%
- (current_capital * kelly_fraction) / entry_price
- }
- PositionSizingMethod::RiskBased { risk_per_trade } => {
- if let Some(stop_price) = stop_loss_price {
- let risk_amount = current_capital * risk_per_trade;
- let price_risk = (entry_price - stop_price).abs();
- if price_risk == Decimal::ZERO {
- return Err(BarterError::Config("Stop loss too close to entry".into()));
- }
- risk_amount / price_risk
- } else {
- return Err(BarterError::Config("Stop loss required for risk-based sizing".into()));
- }
- }
- PositionSizingMethod::VolatilityBased { atr_multiplier } => {
- // Simplified - would need actual ATR calculation
- (current_capital * Decimal::new(2, 2)) / entry_price / atr_multiplier
- }
- };
-
- // Apply max position size limit
- if let Some(max_pct) = self.config.limits.max_position_size {
- let max_size = (current_capital * max_pct) / entry_price;
- Ok(size.min(max_size))
- } else {
- Ok(size)
- }
- }
-
- /// Calculate stop-loss price
- pub fn calculate_stop_loss(
- &self,
- side: OrderSide,
- entry_price: Decimal,
- atr: Option<Decimal>,
- ) -> Option<Decimal> {
- match &self.config.stop_loss {
- StopLossType::None => None,
- StopLossType::FixedPercentage(pct) => {
- match side {
- OrderSide::Buy => Some(entry_price * (Decimal::ONE - pct)),
- OrderSide::Sell => Some(entry_price * (Decimal::ONE + pct)),
- }
- }
- StopLossType::FixedAmount(amount) => {
- match side {
- OrderSide::Buy => Some(entry_price - amount),
- OrderSide::Sell => Some(entry_price + amount),
- }
- }
- StopLossType::Trailing { percentage } => {
- // Initial stop is same as fixed percentage
- match side {
- OrderSide::Buy => Some(entry_price * (Decimal::ONE - percentage)),
- OrderSide::Sell => Some(entry_price * (Decimal::ONE + percentage)),
- }
- }
- StopLossType::ATRBased { multiplier, .. } => {
- if let Some(atr_value) = atr {
- match side {
- OrderSide::Buy => Some(entry_price - (atr_value * multiplier)),
- OrderSide::Sell => Some(entry_price + (atr_value * multiplier)),
- }
- } else {
- None
- }
- }
- }
- }
-
- /// Calculate take-profit price
- pub fn calculate_take_profit(
- &self,
- side: OrderSide,
- entry_price: Decimal,
- stop_loss_price: Option<Decimal>,
- ) -> Option<Decimal> {
- match &self.config.take_profit {
- TakeProfitType::None => None,
- TakeProfitType::FixedPercentage(pct) => {
- match side {
- OrderSide::Buy => Some(entry_price * (Decimal::ONE + pct)),
- OrderSide::Sell => Some(entry_price * (Decimal::ONE - pct)),
- }
- }
- TakeProfitType::FixedAmount(amount) => {
- match side {
- OrderSide::Buy => Some(entry_price + amount),
- OrderSide::Sell => Some(entry_price - amount),
- }
- }
- TakeProfitType::RiskRewardRatio(ratio) => {
- if let Some(stop_price) = stop_loss_price {
- let risk = (entry_price - stop_price).abs();
- match side {
- OrderSide::Buy => Some(entry_price + (risk * ratio)),
- OrderSide::Sell => Some(entry_price - (risk * ratio)),
- }
- } else {
- None
- }
- }
- }
- }
-
- /// Update trailing stop based on current price
- pub fn update_trailing_stop(
- &mut self,
- symbol: &str,
- current_price: Decimal,
- ) -> Option<Decimal> {
- if let Some(position) = self.active_positions.get_mut(symbol) {
- if let StopLossType::Trailing { percentage } = &self.config.stop_loss {
- let is_long = position.quantity > Decimal::ZERO;
-
- if is_long {
- let new_stop = current_price * (Decimal::ONE - percentage);
- if let Some(current_stop) = position.trailing_stop_price {
- if new_stop > current_stop {
- position.trailing_stop_price = Some(new_stop);
- return Some(new_stop);
- }
- } else {
- position.trailing_stop_price = Some(new_stop);
- return Some(new_stop);
- }
- } else {
- let new_stop = current_price * (Decimal::ONE + percentage);
- if let Some(current_stop) = position.trailing_stop_price {
- if new_stop < current_stop {
- position.trailing_stop_price = Some(new_stop);
- return Some(new_stop);
- }
- } else {
- position.trailing_stop_price = Some(new_stop);
- return Some(new_stop);
- }
- }
- }
- }
- None
- }
-
- /// Check if stop-loss or take-profit is hit
- pub fn check_exit_signals(
- &self,
- symbol: &str,
- current_price: Decimal,
- ) -> Option<ExitSignal> {
- if let Some(position) = self.active_positions.get(symbol) {
- let is_long = position.quantity > Decimal::ZERO;
-
- // Check stop-loss
- let stop_price = position.trailing_stop_price.or(position.stop_loss_price);
- if let Some(stop) = stop_price {
- if (is_long && current_price <= stop) || (!is_long && current_price >= stop) {
- return Some(ExitSignal::StopLoss);
- }
- }
-
- // Check take-profit
- if let Some(tp) = position.take_profit_price {
- if (is_long && current_price >= tp) || (!is_long && current_price <= tp) {
- return Some(ExitSignal::TakeProfit);
- }
- }
- }
- None
- }
-
- /// Check if risk limits are breached
- pub fn check_risk_limits(&mut self, current_equity: Decimal) -> Vec<RiskLimitBreach> {
- let mut breaches = Vec::new();
-
- // Update peak equity
- if current_equity > self.peak_equity {
- self.peak_equity = current_equity;
- }
-
- // Check max drawdown
- if let Some(max_dd) = self.config.limits.max_drawdown {
- let current_dd = (self.peak_equity - current_equity) / self.peak_equity;
- if current_dd > max_dd {
- breaches.push(RiskLimitBreach::MaxDrawdown {
- current: current_dd,
- limit: max_dd
- });
- }
- }
-
- // Check max daily loss
- if let Some(max_daily) = self.config.limits.max_daily_loss {
- let daily_loss = (self.daily_start_equity - current_equity) / self.daily_start_equity;
- if daily_loss > max_daily {
- breaches.push(RiskLimitBreach::MaxDailyLoss {
- current: daily_loss,
- limit: max_daily
- });
- }
- }
-
- // Check max positions
- if let Some(max_pos) = self.config.limits.max_positions {
- if self.active_positions.len() >= max_pos {
- breaches.push(RiskLimitBreach::MaxPositions {
- current: self.active_positions.len(),
- limit: max_pos
- });
- }
- }
-
- breaches
- }
-
- /// Register new position for tracking
- pub fn register_position(
- &mut self,
- symbol: String,
- side: OrderSide,
- entry_price: Decimal,
- quantity: Decimal,
- atr: Option<Decimal>,
- ) {
- let stop_loss = self.calculate_stop_loss(side, entry_price, atr);
- let take_profit = self.calculate_take_profit(side, entry_price, stop_loss);
-
- self.active_positions.insert(
- symbol.clone(),
- PositionRisk {
- symbol,
- entry_price,
- quantity: if side == OrderSide::Buy { quantity } else { -quantity },
- stop_loss_price: stop_loss,
- take_profit_price: take_profit,
- trailing_stop_price: None,
- atr_values: Vec::new(),
- },
- );
- }
-
- /// Remove position from tracking
- pub fn remove_position(&mut self, symbol: &str) {
- self.active_positions.remove(symbol);
- }
-
- /// Reset daily tracking (call at start of new day)
- pub fn reset_daily(&mut self, current_equity: Decimal) {
- self.daily_start_equity = current_equity;
- }
-
- /// Get active position count
- pub fn active_position_count(&self) -> usize {
- self.active_positions.len()
- }
-}
-
-/// Exit signal types
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-pub enum ExitSignal {
- StopLoss,
- TakeProfit,
-}
-
-/// Risk limit breach types
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub enum RiskLimitBreach {
- MaxDrawdown { current: Decimal, limit: Decimal },
- MaxDailyLoss { current: Decimal, limit: Decimal },
- MaxPositions { current: usize, limit: usize },
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/strategy.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/strategy.rs
deleted file mode 100644
index 861d286b5..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/strategy.rs
+++ /dev/null
@@ -1,272 +0,0 @@
-use crate::barter_integration::types::*;
-use rust_decimal::Decimal;
-use std::collections::HashMap;
-use serde::{Serialize, Deserialize};
-
-/// Strategy trait that all trading strategies must implement
-pub trait Strategy: Send + Sync {
- /// Strategy name
- fn name(&self) -> &str;
-
- /// Initialize strategy with configuration
- fn initialize(&mut self, config: &StrategyConfig) -> BarterResult<()>;
-
- /// Process new market data and generate signals
- fn on_market_data(
- &mut self,
- symbol: &str,
- candle: &Candle,
- ) -> BarterResult<Vec<Signal>>;
-
- /// Process trade execution
- fn on_order_filled(&mut self, order: &OrderResponse) -> BarterResult<()>;
-
- /// Risk management check before order submission
- fn validate_order(&self, request: &OrderRequest) -> BarterResult<bool>;
-
- /// Get strategy parameters
- fn get_parameters(&self) -> HashMap<String, serde_json::Value>;
-
- /// Update strategy parameters
- fn update_parameters(&mut self, params: HashMap<String, serde_json::Value>) -> BarterResult<()>;
-}
-
-/// Trading signal
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Signal {
- pub symbol: String,
- pub side: OrderSide,
- pub order_type: OrderType,
- pub quantity: Decimal,
- pub price: Option<Decimal>,
- pub confidence: f64,
- pub reason: String,
-}
-
-/// Simple moving average crossover strategy (example)
-pub struct SmaStrategy {
- name: String,
- fast_period: usize,
- slow_period: usize,
- position_size: Decimal,
- candles: HashMap<String, Vec<Candle>>,
-}
-
-impl SmaStrategy {
- pub fn new() -> Self {
- Self {
- name: "SMA Crossover".to_string(),
- fast_period: 10,
- slow_period: 20,
- position_size: Decimal::new(100, 0),
- candles: HashMap::new(),
- }
- }
-
- fn calculate_sma(&self, candles: &[Candle], period: usize) -> Option<Decimal> {
- if candles.len() < period {
- return None;
- }
-
- let recent: Vec<_> = candles.iter().rev().take(period).collect();
- let sum: Decimal = recent.iter().map(|c| c.close).sum();
- Some(sum / Decimal::new(period as i64, 0))
- }
-}
-
-impl Default for SmaStrategy {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl Strategy for SmaStrategy {
- fn name(&self) -> &str {
- &self.name
- }
-
- fn initialize(&mut self, config: &StrategyConfig) -> BarterResult<()> {
- if let Some(fast) = config.parameters.get("fast_period") {
- if let Some(fast_val) = fast.as_u64() {
- self.fast_period = fast_val as usize;
- }
- }
-
- if let Some(slow) = config.parameters.get("slow_period") {
- if let Some(slow_val) = slow.as_u64() {
- self.slow_period = slow_val as usize;
- }
- }
-
- if let Some(size) = config.parameters.get("position_size") {
- if let Some(size_str) = size.as_str() {
- self.position_size = size_str.parse().map_err(|_| {
- BarterError::Strategy("Invalid position size".to_string())
- })?;
- }
- }
-
- Ok(())
- }
-
- fn on_market_data(
- &mut self,
- symbol: &str,
- candle: &Candle,
- ) -> BarterResult<Vec<Signal>> {
- let candles = self.candles.entry(symbol.to_string()).or_insert_with(Vec::new);
- candles.push(candle.clone());
-
- // Keep only necessary candles
- let max_period = self.slow_period.max(self.fast_period);
- if candles.len() > max_period + 10 {
- candles.drain(0..candles.len() - max_period - 10);
- }
-
- let mut signals = Vec::new();
-
- // Get candle reference after modification
- let candles_ref = self.candles.get(symbol).unwrap();
-
- // Calculate SMAs
- if let (Some(fast_sma), Some(slow_sma)) = (
- self.calculate_sma(candles_ref, self.fast_period),
- self.calculate_sma(candles_ref, self.slow_period),
- ) {
- // Previous SMAs
- if candles_ref.len() > self.slow_period {
- let prev_candles: Vec<_> = candles_ref.iter()
- .take(candles_ref.len() - 1)
- .cloned()
- .collect();
-
- if let (Some(prev_fast), Some(prev_slow)) = (
- self.calculate_sma(&prev_candles, self.fast_period),
- self.calculate_sma(&prev_candles, self.slow_period),
- ) {
- // Bullish crossover
- if fast_sma > slow_sma && prev_fast <= prev_slow {
- signals.push(Signal {
- symbol: symbol.to_string(),
- side: OrderSide::Buy,
- order_type: OrderType::Market,
- quantity: self.position_size,
- price: None,
- confidence: 0.7,
- reason: format!(
- "SMA crossover: fast({}) crossed above slow({})",
- fast_sma, slow_sma
- ),
- });
- }
- // Bearish crossover
- else if fast_sma < slow_sma && prev_fast >= prev_slow {
- signals.push(Signal {
- symbol: symbol.to_string(),
- side: OrderSide::Sell,
- order_type: OrderType::Market,
- quantity: self.position_size,
- price: None,
- confidence: 0.7,
- reason: format!(
- "SMA crossover: fast({}) crossed below slow({})",
- fast_sma, slow_sma
- ),
- });
- }
- }
- }
- }
-
- Ok(signals)
- }
-
- fn on_order_filled(&mut self, _order: &OrderResponse) -> BarterResult<()> {
- // Handle order fills if needed
- Ok(())
- }
-
- fn validate_order(&self, _request: &OrderRequest) -> BarterResult<bool> {
- // Basic validation - can be extended
- Ok(true)
- }
-
- fn get_parameters(&self) -> HashMap<String, serde_json::Value> {
- let mut params = HashMap::new();
- params.insert(
- "fast_period".to_string(),
- serde_json::json!(self.fast_period),
- );
- params.insert(
- "slow_period".to_string(),
- serde_json::json!(self.slow_period),
- );
- params.insert(
- "position_size".to_string(),
- serde_json::json!(self.position_size.to_string()),
- );
- params
- }
-
- fn update_parameters(&mut self, params: HashMap<String, serde_json::Value>) -> BarterResult<()> {
- if let Some(fast) = params.get("fast_period") {
- if let Some(fast_val) = fast.as_u64() {
- self.fast_period = fast_val as usize;
- }
- }
-
- if let Some(slow) = params.get("slow_period") {
- if let Some(slow_val) = slow.as_u64() {
- self.slow_period = slow_val as usize;
- }
- }
-
- if let Some(size) = params.get("position_size") {
- if let Some(size_str) = size.as_str() {
- self.position_size = size_str.parse().map_err(|_| {
- BarterError::Strategy("Invalid position size".to_string())
- })?;
- }
- }
-
- Ok(())
- }
-}
-
-/// Strategy registry
-pub struct StrategyRegistry {
- pub strategies: HashMap<String, Box<dyn Strategy>>,
-}
-
-impl StrategyRegistry {
- pub fn new() -> Self {
- Self {
- strategies: HashMap::new(),
- }
- }
-
- pub fn register(&mut self, strategy: Box<dyn Strategy>) {
- let name = strategy.name().to_string();
- self.strategies.insert(name, strategy);
- }
-
- pub fn get(&self, name: &str) -> Option<&dyn Strategy> {
- self.strategies.get(name).map(|s| s.as_ref())
- }
-
- pub fn get_mut(&mut self, name: &str) -> Option<&mut Box<dyn Strategy>> {
- self.strategies.get_mut(name)
- }
-
- pub fn list_strategies(&self) -> Vec<String> {
- self.strategies.keys().cloned().collect()
- }
-}
-
-impl Default for StrategyRegistry {
- fn default() -> Self {
- let mut registry = Self::new();
- registry.register(Box::new(SmaStrategy::new()));
- registry
- }
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/test_csv_mapping.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/test_csv_mapping.rs
deleted file mode 100644
index f3fe85e5b..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/test_csv_mapping.rs
+++ /dev/null
@@ -1,165 +0,0 @@
-/// Test CSV data mapping and full backtest workflow
-use super::*;
-use std::collections::HashMap;
-
-#[tokio::test]
-async fn test_csv_to_backtest_full_workflow() {
- println!("\n========================================");
- println!(" CSV Data Mapping & Backtest Test");
- println!("========================================\n");
-
- // Step 1: Read CSV file
- let csv_path = "C:/windowsdisk/finceptTerminal/fincept-terminal-desktop/src-tauri/resources/scripts/test_volatile_data.csv";
- let csv_content = std::fs::read_to_string(csv_path)
- .expect("Failed to read CSV file");
-
- println!("✓ Step 1: CSV file loaded ({} bytes)", csv_content.len());
-
- // Step 2: Parse CSV into rows
- let lines: Vec<&str> = csv_content.lines().collect();
- let headers: Vec<&str> = lines[0].split(',').collect();
-
- let mut data_rows = Vec::new();
- for line in lines.iter().skip(1) {
- let values: Vec<&str> = line.split(',').collect();
- let mut row_map = HashMap::new();
- for (i, header) in headers.iter().enumerate() {
- row_map.insert(header.to_string(), values[i].to_string());
- }
- data_rows.push(data_mapper::DataRow { fields: row_map });
- }
-
- println!("✓ Step 2: Parsed {} data rows", data_rows.len());
- println!(" Columns: {}", headers.join(", "));
-
- // Step 3: Create mapping configuration
- let mapping = data_mapper::DatasetMapping {
- timestamp_column: "timestamp".to_string(),
- timestamp_format: data_mapper::TimestampFormat::Rfc3339,
- open_column: Some("open".to_string()),
- high_column: Some("high".to_string()),
- low_column: Some("low".to_string()),
- close_column: Some("close".to_string()),
- volume_column: Some("volume".to_string()),
- price_column: None,
- size_column: None,
- symbol_column: None,
- aggregation_interval: None,
- };
-
- println!("✓ Step 3: Column mapping configured");
-
- // Step 4: Map to candles
- let mapper = data_mapper::DataMapper::new(mapping);
- let candles = mapper.map_ohlcv_data(data_rows, "TEST_STOCK")
- .expect("Failed to map data");
-
- println!("✓ Step 4: Converted to {} candles", candles.len());
- println!("\n--- Sample Candles ---");
- println!("First: {:?}", candles.first().unwrap());
- println!("Last: {:?}", candles.last().unwrap());
-
- // Step 5: Configure backtest
- let config = BacktestConfig {
- start_date: candles.first().unwrap().timestamp,
- end_date: candles.last().unwrap().timestamp,
- initial_capital: rust_decimal::Decimal::new(100000, 0), // $1,000.00
- commission_rate: rust_decimal::Decimal::new(2, 3), // 0.002 = 0.2%
- strategy: StrategyConfig {
- name: "SMA Crossover".to_string(),
- mode: TradingMode::Backtest,
- exchanges: vec![Exchange::Binance],
- symbols: vec!["TEST_STOCK".to_string()],
- parameters: {
- let mut params = HashMap::new();
- params.insert("fast_period".to_string(), serde_json::json!(3));
- params.insert("slow_period".to_string(), serde_json::json!(7));
- params.insert("position_size".to_string(), serde_json::json!("100"));
- params
- },
- },
- };
-
- println!("\n✓ Step 5: Backtest configured");
- println!(" Strategy: SMA Crossover (fast=3, slow=7)");
- println!(" Initial Capital: ${}", config.initial_capital);
- println!(" Commission: {}%", config.commission_rate * rust_decimal::Decimal::new(100, 0));
-
- // Step 6: Run backtest
- let mut strategy = strategy::SmaStrategy::new();
- let mut candle_data = HashMap::new();
- candle_data.insert("TEST_STOCK".to_string(), candles);
-
- let result = backtest::BacktestRunner::run_backtest(
- config.clone(),
- &mut strategy,
- candle_data.clone(),
- )
- .await
- .expect("Backtest failed");
-
- println!("\n✓ Step 6: Backtest completed\n");
-
- // Step 7: Display results
- println!("========================================");
- println!(" BACKTEST RESULTS");
- println!("========================================");
- println!("Total Return: {}%", result.total_return);
- println!("Sharpe Ratio: {}", result.sharpe_ratio);
- println!("Sortino Ratio: {}", result.sortino_ratio);
- println!("Max Drawdown: {}%", result.max_drawdown * rust_decimal::Decimal::new(100, 0));
- println!("Win Rate: {}%", result.win_rate);
- println!("----------------------------------------");
- println!("Total Trades: {}", result.total_trades);
- println!("Winning Trades: {}", result.winning_trades);
- println!("Losing Trades: {}", result.losing_trades);
- println!("Average Win: ${}", result.average_win);
- println!("Average Loss: ${}", result.average_loss);
- println!("Profit Factor: {}", result.profit_factor);
- println!("----------------------------------------");
- println!("Initial Capital: $100000");
- println!("Final Capital: ${}", result.final_capital);
- println!("Net Profit/Loss: ${}", result.final_capital - rust_decimal::Decimal::new(100000, 0));
- println!("========================================\n");
-
- // Step 8: Show equity curve
- println!("--- Equity Curve (Sample) ---");
- let sample_size = 10.min(result.equity_curve.len());
- for i in 0..sample_size {
- let (timestamp, equity) = &result.equity_curve[i];
- println!("{}: ${}", timestamp.format("%H:%M"), equity);
- }
- if result.equity_curve.len() > sample_size {
- println!("... ({} more points)", result.equity_curve.len() - sample_size);
- }
-
- // Step 9: Show trades
- if !result.trades.is_empty() {
- println!("\n--- Trade History ---");
- for (i, trade) in result.trades.iter().enumerate() {
- println!("Trade #{}: {} {} @ ${} -> ${} | P&L: ${} ({}%)",
- i + 1,
- match trade.side {
- OrderSide::Buy => "LONG",
- OrderSide::Sell => "SHORT",
- },
- trade.symbol,
- trade.entry_price,
- trade.exit_price,
- trade.pnl,
- trade.return_pct * rust_decimal::Decimal::new(100, 0)
- );
- }
- } else {
- println!("\n--- No Trades Executed ---");
- println!("Strategy did not generate any signals with current parameters.");
- println!("Try adjusting fast_period/slow_period for more signals.");
- }
-
- println!("\n========================================");
- println!(" Test Completed Successfully!");
- println!("========================================\n");
-
- assert!(result.final_capital > rust_decimal::Decimal::ZERO);
- assert_eq!(result.equity_curve.len(), 50); // 50 candles
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/test_databento.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/test_databento.rs
deleted file mode 100644
index c29f447ac..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/test_databento.rs
+++ /dev/null
@@ -1,81 +0,0 @@
-/// Quick test to parse the actual Databento file and run a backtest
-use super::*;
-use std::collections::HashMap;
-
-#[tokio::test]
-async fn test_parse_real_databento_file() {
- let file_path = "C:/windowsdisk/finceptTerminal/fincept-terminal-desktop/src-tauri/resources/scripts/databento_raw_data.bin";
-
- let result = data_mapper::parse_databento_file(file_path);
-
- match result {
- Ok(candle_data) => {
- println!("=== Databento Parsing Results ===");
- for (symbol, candles) in &candle_data {
- println!("Symbol: {}", symbol);
- println!(" Total Candles: {}", candles.len());
- if !candles.is_empty() {
- println!(" First: {:?}", candles.first().unwrap());
- println!(" Last: {:?}", candles.last().unwrap());
- }
- }
-
- // Run backtest on ES (E-mini S&P 500) if available
- if let Some(es_candles) = candle_data.get("ES") {
- if es_candles.len() >= 10 {
- println!("\n=== Running Backtest on ES (E-mini S&P 500) ===");
-
- let config = BacktestConfig {
- start_date: es_candles.first().unwrap().timestamp,
- end_date: es_candles.last().unwrap().timestamp,
- initial_capital: rust_decimal::Decimal::new(100000, 0),
- commission_rate: rust_decimal::Decimal::new(1, 3),
- strategy: StrategyConfig {
- name: "SMA Crossover".to_string(),
- mode: TradingMode::Backtest,
- exchanges: vec![Exchange::Binance],
- symbols: vec!["ES".to_string()],
- parameters: {
- let mut params = HashMap::new();
- params.insert("fast_period".to_string(), serde_json::json!(3));
- params.insert("slow_period".to_string(), serde_json::json!(5));
- params.insert("position_size".to_string(), serde_json::json!("1"));
- params
- },
- },
- };
-
- let mut strategy = strategy::SmaStrategy::new();
- let mut backtest_data = HashMap::new();
- backtest_data.insert("ES".to_string(), es_candles.clone());
-
- let backtest_result = backtest::BacktestRunner::run_backtest(
- config,
- &mut strategy,
- backtest_data,
- ).await;
-
- match backtest_result {
- Ok(result) => {
- println!("Total Return: {}%", result.total_return);
- println!("Sharpe Ratio: {}", result.sharpe_ratio);
- println!("Max Drawdown: {}%", result.max_drawdown * rust_decimal::Decimal::new(100, 0));
- println!("Win Rate: {}%", result.win_rate);
- println!("Total Trades: {}", result.total_trades);
- println!("Final Capital: ${}", result.final_capital);
- }
- Err(e) => {
- println!("Backtest failed: {}", e);
- }
- }
- }
- }
-
- assert!(!candle_data.is_empty());
- }
- Err(e) => {
- println!("Failed to parse file: {}", e);
- panic!("Parse failed");
- }
- }
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/test_risk_management.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/test_risk_management.rs
deleted file mode 100644
index 54394d1e0..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/test_risk_management.rs
+++ /dev/null
@@ -1,306 +0,0 @@
-/// Risk Management Module Tests
-use super::*;
-use rust_decimal::Decimal;
-
-#[test]
-fn test_fixed_percentage_position_sizing() {
- let config = risk_management::RiskConfig {
- position_sizing: risk_management::PositionSizingMethod::FixedPercentage(
- Decimal::new(5, 2) // 5%
- ),
- ..Default::default()
- };
-
- let manager = risk_management::RiskManager::new(config, Decimal::new(100000, 0));
- let capital = Decimal::new(100000, 0);
- let entry_price = Decimal::new(50, 0);
-
- let size = manager.calculate_position_size(capital, entry_price, None).unwrap();
-
- // 5% of $100,000 = $5,000 / $50 = 100 shares
- assert_eq!(size, Decimal::new(100, 0));
- println!("✓ Fixed percentage sizing: {} shares", size);
-}
-
-#[test]
-fn test_risk_based_position_sizing() {
- let config = risk_management::RiskConfig {
- position_sizing: risk_management::PositionSizingMethod::RiskBased {
- risk_per_trade: Decimal::new(1, 2) // 1% risk per trade
- },
- ..Default::default()
- };
-
- let manager = risk_management::RiskManager::new(config, Decimal::new(100000, 0));
- let capital = Decimal::new(100000, 0);
- let entry_price = Decimal::new(100, 0);
- let stop_loss = Decimal::new(95, 0); // $5 risk per share
-
- let size = manager.calculate_position_size(capital, entry_price, Some(stop_loss)).unwrap();
-
- // 1% of $100,000 = $1,000 risk / $5 per share = 200 shares
- // But capped by max_position_size (10% = $10,000 / $100 = 100 shares)
- assert_eq!(size, Decimal::new(100, 0));
- println!("✓ Risk-based sizing: {} shares (capped by max position size)", size);
-}
-
-#[test]
-fn test_kelly_criterion_position_sizing() {
- let config = risk_management::RiskConfig {
- position_sizing: risk_management::PositionSizingMethod::Kelly {
- win_rate: Decimal::new(60, 2), // 60%
- avg_win: Decimal::new(150, 0),
- avg_loss: Decimal::new(100, 0),
- },
- ..Default::default()
- };
-
- let manager = risk_management::RiskManager::new(config, Decimal::new(100000, 0));
- let capital = Decimal::new(100000, 0);
- let entry_price = Decimal::new(50, 0);
-
- let size = manager.calculate_position_size(capital, entry_price, None).unwrap();
-
- // Kelly = (0.6 * 1.5 - 0.4) / 1.5 = 0.333 = 33.3%
- // Capped at 25% = $25,000 / $50 = 500 shares
- println!("✓ Kelly criterion sizing: {} shares", size);
- assert!(size > Decimal::ZERO);
-}
-
-#[test]
-fn test_fixed_percentage_stop_loss() {
- let config = risk_management::RiskConfig {
- stop_loss: risk_management::StopLossType::FixedPercentage(Decimal::new(2, 2)), // 2%
- ..Default::default()
- };
-
- let manager = risk_management::RiskManager::new(config, Decimal::new(100000, 0));
-
- // Long position
- let entry_price = Decimal::new(100, 0);
- let stop = manager.calculate_stop_loss(OrderSide::Buy, entry_price, None).unwrap();
- assert_eq!(stop, Decimal::new(98, 0)); // 100 * 0.98
- println!("✓ Long stop-loss: ${}", stop);
-
- // Short position
- let stop_short = manager.calculate_stop_loss(OrderSide::Sell, entry_price, None).unwrap();
- assert_eq!(stop_short, Decimal::new(102, 0)); // 100 * 1.02
- println!("✓ Short stop-loss: ${}", stop_short);
-}
-
-#[test]
-fn test_risk_reward_take_profit() {
- let config = risk_management::RiskConfig {
- take_profit: risk_management::TakeProfitType::RiskRewardRatio(Decimal::new(3, 0)), // 3:1
- ..Default::default()
- };
-
- let manager = risk_management::RiskManager::new(config, Decimal::new(100000, 0));
-
- let entry_price = Decimal::new(100, 0);
- let stop_loss = Decimal::new(95, 0); // $5 risk
-
- let tp = manager.calculate_take_profit(OrderSide::Buy, entry_price, Some(stop_loss)).unwrap();
-
- // Risk = $5, Reward = $15 (3:1), TP = $115
- assert_eq!(tp, Decimal::new(115, 0));
- println!("✓ Take-profit at ${} (3:1 R:R)", tp);
-}
-
-#[test]
-fn test_trailing_stop_update() {
- let config = risk_management::RiskConfig {
- stop_loss: risk_management::StopLossType::Trailing {
- percentage: Decimal::new(5, 2) // 5%
- },
- ..Default::default()
- };
-
- let mut manager = risk_management::RiskManager::new(config, Decimal::new(100000, 0));
-
- // Register long position
- manager.register_position(
- "AAPL".to_string(),
- OrderSide::Buy,
- Decimal::new(100, 0),
- Decimal::new(100, 0),
- None,
- );
-
- // Price moves up to $110
- let new_stop = manager.update_trailing_stop("AAPL", Decimal::new(110, 0)).unwrap();
- assert_eq!(new_stop, Decimal::new(1045, 1)); // 110 * 0.95 = 104.5
- println!("✓ Trailing stop updated to ${}", new_stop);
-
- // Price moves up to $120
- let new_stop2 = manager.update_trailing_stop("AAPL", Decimal::new(120, 0)).unwrap();
- assert_eq!(new_stop2, Decimal::new(114, 0)); // 120 * 0.95 = 114
- println!("✓ Trailing stop updated to ${}", new_stop2);
-
- // Price drops to $115 - stop should NOT move down
- let unchanged = manager.update_trailing_stop("AAPL", Decimal::new(115, 0));
- assert!(unchanged.is_none());
- println!("✓ Trailing stop stays at $114 (doesn't move down)");
-}
-
-#[test]
-fn test_exit_signals() {
- let config = risk_management::RiskConfig {
- stop_loss: risk_management::StopLossType::FixedPercentage(Decimal::new(5, 2)),
- take_profit: risk_management::TakeProfitType::FixedPercentage(Decimal::new(10, 2)),
- ..Default::default()
- };
-
- let mut manager = risk_management::RiskManager::new(config, Decimal::new(100000, 0));
-
- manager.register_position(
- "AAPL".to_string(),
- OrderSide::Buy,
- Decimal::new(100, 0),
- Decimal::new(100, 0),
- None,
- );
-
- // Price hits stop-loss at $95
- let signal = manager.check_exit_signals("AAPL", Decimal::new(95, 0));
- assert_eq!(signal, Some(risk_management::ExitSignal::StopLoss));
- println!("✓ Stop-loss triggered at $95");
-
- // Price hits take-profit at $110
- let signal_tp = manager.check_exit_signals("AAPL", Decimal::new(110, 0));
- assert_eq!(signal_tp, Some(risk_management::ExitSignal::TakeProfit));
- println!("✓ Take-profit triggered at $110");
-
- // Price at $105 - no signal
- let no_signal = manager.check_exit_signals("AAPL", Decimal::new(105, 0));
- assert_eq!(no_signal, None);
- println!("✓ No exit signal at $105");
-}
-
-#[test]
-fn test_max_drawdown_limit() {
- let config = risk_management::RiskConfig {
- limits: risk_management::RiskLimits {
- max_drawdown: Some(Decimal::new(10, 2)), // 10%
- ..Default::default()
- },
- ..Default::default()
- };
-
- let mut manager = risk_management::RiskManager::new(config, Decimal::new(100000, 0));
-
- // Equity drops to $89,000 (11% drawdown)
- let breaches = manager.check_risk_limits(Decimal::new(89000, 0));
- assert_eq!(breaches.len(), 1);
-
- if let risk_management::RiskLimitBreach::MaxDrawdown { current, limit } = &breaches[0] {
- println!("✓ Max drawdown breached: {:.2}% (limit: {:.2}%)",
- current * Decimal::new(100, 0),
- limit * Decimal::new(100, 0)
- );
- }
-
- // Equity recovers to $95,000 (5% drawdown) - no breach
- let no_breach = manager.check_risk_limits(Decimal::new(95000, 0));
- assert_eq!(no_breach.len(), 0);
- println!("✓ No breach at 5% drawdown");
-}
-
-#[test]
-fn test_max_positions_limit() {
- let config = risk_management::RiskConfig {
- limits: risk_management::RiskLimits {
- max_positions: Some(3),
- ..Default::default()
- },
- ..Default::default()
- };
-
- let mut manager = risk_management::RiskManager::new(config, Decimal::new(100000, 0));
-
- // Add 3 positions
- manager.register_position("AAPL".into(), OrderSide::Buy, Decimal::new(100, 0), Decimal::new(100, 0), None);
- manager.register_position("GOOGL".into(), OrderSide::Buy, Decimal::new(200, 0), Decimal::new(50, 0), None);
- manager.register_position("MSFT".into(), OrderSide::Buy, Decimal::new(150, 0), Decimal::new(75, 0), None);
-
- assert_eq!(manager.active_position_count(), 3);
-
- let breaches = manager.check_risk_limits(Decimal::new(100000, 0));
- assert_eq!(breaches.len(), 1);
-
- if let risk_management::RiskLimitBreach::MaxPositions { current, limit } = &breaches[0] {
- println!("✓ Max positions reached: {} (limit: {})", current, limit);
- }
-
- // Remove one position
- manager.remove_position("AAPL");
- assert_eq!(manager.active_position_count(), 2);
-
- let no_breach = manager.check_risk_limits(Decimal::new(100000, 0));
- assert_eq!(no_breach.len(), 0);
- println!("✓ Positions under limit: 2/3");
-}
-
-#[test]
-fn test_full_risk_management_workflow() {
- println!("\n=== Full Risk Management Test ===\n");
-
- let config = risk_management::RiskConfig {
- position_sizing: risk_management::PositionSizingMethod::RiskBased {
- risk_per_trade: Decimal::new(1, 2) // 1%
- },
- stop_loss: risk_management::StopLossType::FixedPercentage(Decimal::new(2, 2)), // 2%
- take_profit: risk_management::TakeProfitType::RiskRewardRatio(Decimal::new(3, 0)), // 3:1
- limits: risk_management::RiskLimits {
- max_drawdown: Some(Decimal::new(15, 2)),
- max_positions: Some(5),
- ..Default::default()
- },
- };
-
- let mut manager = risk_management::RiskManager::new(config.clone(), Decimal::new(100000, 0));
- let entry_price = Decimal::new(100, 0);
-
- // Calculate stop-loss
- let stop_loss = manager.calculate_stop_loss(OrderSide::Buy, entry_price, None).unwrap();
- println!("Entry: ${}, Stop-Loss: ${}", entry_price, stop_loss);
-
- // Calculate position size
- let size = manager.calculate_position_size(
- Decimal::new(100000, 0),
- entry_price,
- Some(stop_loss)
- ).unwrap();
- println!("Position size: {} shares (risking 1% = $1,000)", size);
-
- // Calculate take-profit
- let take_profit = manager.calculate_take_profit(OrderSide::Buy, entry_price, Some(stop_loss)).unwrap();
- println!("Take-Profit: ${} (3:1 R:R)\n", take_profit);
-
- // Register position
- manager.register_position(
- "AAPL".to_string(),
- OrderSide::Buy,
- entry_price,
- size,
- None,
- );
-
- // Check limits
- let breaches = manager.check_risk_limits(Decimal::new(100000, 0));
- println!("Risk limit breaches: {}", breaches.len());
-
- // Simulate price movement
- println!("\n--- Price Movement Simulation ---");
-
- // Price moves to $105
- let signal = manager.check_exit_signals("AAPL", Decimal::new(105, 0));
- println!("Price $105: {:?}", signal);
-
- // Price moves to $106 (hit take-profit)
- let signal_tp = manager.check_exit_signals("AAPL", Decimal::new(106, 0));
- println!("Price $106: {:?}", signal_tp);
- assert_eq!(signal_tp, Some(risk_management::ExitSignal::TakeProfit));
-
- println!("\n✓ Full workflow completed successfully");
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/tests.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/tests.rs
deleted file mode 100644
index 428ae4bad..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/tests.rs
+++ /dev/null
@@ -1,169 +0,0 @@
-#[cfg(test)]
-mod tests {
- use super::super::*;
- use super::super::strategy::Strategy;
- use chrono::Utc;
- use rust_decimal::Decimal;
- use std::collections::HashMap;
-
- fn create_demo_candle_data() -> HashMap<String, Vec<Candle>> {
- let mut data = HashMap::new();
- let mut candles = Vec::new();
-
- // Generate 50 demo candles with upward trend
- let base_time = Utc::now() - chrono::Duration::days(50);
- for i in 0..50 {
- let close = Decimal::new(10000 + (i * 100), 0); // Start at 100.00, increase by 1.00 each candle
- candles.push(Candle {
- timestamp: base_time + chrono::Duration::days(i as i64),
- open: close - Decimal::new(50, 0),
- high: close + Decimal::new(100, 0),
- low: close - Decimal::new(150, 0),
- close,
- volume: Decimal::new(1000000, 0),
- });
- }
-
- data.insert("BTC-USD".to_string(), candles);
- data
- }
-
- #[tokio::test]
- async fn test_sma_strategy_initialization() {
- let mut strategy = strategy::SmaStrategy::new();
-
- let mut params = HashMap::new();
- params.insert("fast_period".to_string(), serde_json::json!(5));
- params.insert("slow_period".to_string(), serde_json::json!(10));
- params.insert("position_size".to_string(), serde_json::json!("1.0"));
-
- let config = StrategyConfig {
- name: "Test SMA".to_string(),
- mode: TradingMode::Backtest,
- exchanges: vec![Exchange::Binance],
- symbols: vec!["BTC-USD".to_string()],
- parameters: params,
- };
-
- let result = strategy.initialize(&config);
- assert!(result.is_ok());
- assert_eq!(strategy.name(), "SMA Crossover");
- }
-
- #[tokio::test]
- async fn test_backtest_engine() {
- let config = BacktestConfig {
- start_date: Utc::now() - chrono::Duration::days(50),
- end_date: Utc::now(),
- initial_capital: Decimal::new(100000, 0), // $1000.00
- commission_rate: Decimal::new(1, 3), // 0.001 = 0.1%
- strategy: StrategyConfig {
- name: "SMA Crossover".to_string(),
- mode: TradingMode::Backtest,
- exchanges: vec![Exchange::Binance],
- symbols: vec!["BTC-USD".to_string()],
- parameters: {
- let mut params = HashMap::new();
- params.insert("fast_period".to_string(), serde_json::json!(5));
- params.insert("slow_period".to_string(), serde_json::json!(10));
- params.insert("position_size".to_string(), serde_json::json!("1.0"));
- params
- },
- },
- };
-
- let candle_data = create_demo_candle_data();
- let mut strategy = strategy::SmaStrategy::new();
-
- let result = backtest::BacktestRunner::run_backtest(
- config,
- &mut strategy,
- candle_data,
- )
- .await;
-
- assert!(result.is_ok());
- let backtest_result = result.unwrap();
-
- println!("=== Backtest Results ===");
- println!("Total Return: {}%", backtest_result.total_return);
- println!("Sharpe Ratio: {}", backtest_result.sharpe_ratio);
- println!("Max Drawdown: {}%", backtest_result.max_drawdown * Decimal::new(100, 0));
- println!("Win Rate: {}%", backtest_result.win_rate);
- println!("Total Trades: {}", backtest_result.total_trades);
- println!("Final Capital: ${}", backtest_result.final_capital);
-
- // Basic assertions
- assert!(backtest_result.final_capital > Decimal::ZERO);
- assert!(backtest_result.equity_curve.len() > 0);
- }
-
- #[tokio::test]
- async fn test_execution_manager() {
- let manager = execution::ExecutionManager::new(TradingMode::Paper);
-
- let request = OrderRequest {
- exchange: Exchange::Binance,
- symbol: "BTC-USD".to_string(),
- side: OrderSide::Buy,
- order_type: OrderType::Market,
- quantity: Decimal::new(1, 1), // 0.1
- price: None,
- stop_price: None,
- time_in_force: None,
- };
-
- let result = manager.submit_order(request).await;
- assert!(result.is_ok());
-
- let order = result.unwrap();
- println!("Order submitted: {:?}", order.order_id);
- assert_eq!(order.status, OrderStatus::Pending);
-
- // Wait for simulated fill
- tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;
-
- let filled_order = manager.get_order(&order.order_id);
- assert!(filled_order.is_ok());
- println!("Order status: {:?}", filled_order.unwrap().status);
- }
-
- #[tokio::test]
- async fn test_market_data_manager() {
- let manager = market_data::MarketDataManager::new();
-
- let config = MarketStreamConfig {
- exchange: Exchange::Binance,
- symbols: vec!["BTC-USD".to_string(), "ETH-USD".to_string()],
- subscribe_trades: true,
- subscribe_orderbook: false,
- subscribe_candles: false,
- candle_interval: None,
- };
-
- let result = manager.start_stream(config).await;
- assert!(result.is_ok());
-
- let stream_id = result.unwrap();
- println!("Market stream started: {}", stream_id);
-
- let active_streams = manager.get_active_streams();
- assert!(active_streams.contains(&stream_id));
-
- // Stop stream
- let stop_result = manager.stop_stream(&stream_id).await;
- assert!(stop_result.is_ok());
- }
-
- #[tokio::test]
- async fn test_strategy_registry() {
- let registry = strategy::StrategyRegistry::default();
-
- let strategies = registry.list_strategies();
- assert!(strategies.contains(&"SMA Crossover".to_string()));
-
- let strategy = registry.get("SMA Crossover");
- assert!(strategy.is_some());
- assert_eq!(strategy.unwrap().name(), "SMA Crossover");
- }
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/barter_integration/types.rs b/fincept-terminal-desktop/src-tauri/src/barter_integration/types.rs
deleted file mode 100644
index ef8f22cab..000000000
--- a/fincept-terminal-desktop/src-tauri/src/barter_integration/types.rs
+++ /dev/null
@@ -1,247 +0,0 @@
-use serde::{Deserialize, Serialize};
-use rust_decimal::Decimal;
-use chrono::{DateTime, Utc};
-use std::collections::HashMap;
-
-/// Trading mode
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "lowercase")]
-pub enum TradingMode {
- Live,
- Paper,
- Backtest,
-}
-
-/// Order side
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "lowercase")]
-pub enum OrderSide {
- Buy,
- Sell,
-}
-
-/// Order type
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum OrderType {
- Market,
- Limit,
- StopLoss,
- StopLimit,
-}
-
-/// Order status
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum OrderStatus {
- Pending,
- Open,
- PartiallyFilled,
- Filled,
- Cancelled,
- Rejected,
- Expired,
-}
-
-/// Exchange identifier
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
-#[serde(rename_all = "lowercase")]
-pub enum Exchange {
- Binance,
- Bybit,
- Coinbase,
- Kraken,
- Okx,
- Bitfinex,
- Bitmex,
- Gateio,
-}
-
-/// Market data candlestick
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Candle {
- pub timestamp: DateTime<Utc>,
- pub open: Decimal,
- pub high: Decimal,
- pub low: Decimal,
- pub close: Decimal,
- pub volume: Decimal,
-}
-
-/// Order book level
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct OrderBookLevel {
- pub price: Decimal,
- pub quantity: Decimal,
-}
-
-/// Order book snapshot
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct OrderBook {
- pub timestamp: DateTime<Utc>,
- pub bids: Vec<OrderBookLevel>,
- pub asks: Vec<OrderBookLevel>,
-}
-
-/// Trade data
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Trade {
- pub id: String,
- pub timestamp: DateTime<Utc>,
- pub price: Decimal,
- pub quantity: Decimal,
- pub side: OrderSide,
-}
-
-/// Order request from frontend
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct OrderRequest {
- pub exchange: Exchange,
- pub symbol: String,
- pub side: OrderSide,
- pub order_type: OrderType,
- pub quantity: Decimal,
- pub price: Option<Decimal>,
- pub stop_price: Option<Decimal>,
- pub time_in_force: Option<String>,
-}
-
-/// Order response
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct OrderResponse {
- pub order_id: String,
- pub client_order_id: String,
- pub exchange: Exchange,
- pub symbol: String,
- pub side: OrderSide,
- pub order_type: OrderType,
- pub status: OrderStatus,
- pub quantity: Decimal,
- pub filled_quantity: Decimal,
- pub price: Option<Decimal>,
- pub average_price: Option<Decimal>,
- pub created_at: DateTime<Utc>,
- pub updated_at: DateTime<Utc>,
-}
-
-/// Position information
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Position {
- pub exchange: Exchange,
- pub symbol: String,
- pub side: OrderSide,
- pub quantity: Decimal,
- pub entry_price: Decimal,
- pub current_price: Decimal,
- pub unrealized_pnl: Decimal,
- pub realized_pnl: Decimal,
-}
-
-/// Account balance
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Balance {
- pub asset: String,
- pub free: Decimal,
- pub locked: Decimal,
- pub total: Decimal,
-}
-
-/// Strategy configuration
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct StrategyConfig {
- pub name: String,
- pub mode: TradingMode,
- pub exchanges: Vec<Exchange>,
- pub symbols: Vec<String>,
- pub parameters: HashMap<String, serde_json::Value>,
-}
-
-/// Backtest configuration
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct BacktestConfig {
- pub strategy: StrategyConfig,
- pub start_date: DateTime<Utc>,
- pub end_date: DateTime<Utc>,
- pub initial_capital: Decimal,
- pub commission_rate: Decimal,
-}
-
-/// Backtest result
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct BacktestResult {
- pub total_return: Decimal,
- pub sharpe_ratio: Decimal,
- pub sortino_ratio: Decimal,
- pub max_drawdown: Decimal,
- pub win_rate: Decimal,
- pub total_trades: u64,
- pub winning_trades: u64,
- pub losing_trades: u64,
- pub average_win: Decimal,
- pub average_loss: Decimal,
- pub profit_factor: Decimal,
- pub final_capital: Decimal,
- pub equity_curve: Vec<(DateTime<Utc>, Decimal)>,
- pub trades: Vec<TradeRecord>,
-}
-
-/// Trade record for backtest
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct TradeRecord {
- pub entry_time: DateTime<Utc>,
- pub exit_time: DateTime<Utc>,
- pub symbol: String,
- pub side: OrderSide,
- pub entry_price: Decimal,
- pub exit_price: Decimal,
- pub quantity: Decimal,
- pub pnl: Decimal,
- pub return_pct: Decimal,
-}
-
-/// Market stream configuration
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct MarketStreamConfig {
- pub exchange: Exchange,
- pub symbols: Vec<String>,
- pub subscribe_trades: bool,
- pub subscribe_orderbook: bool,
- pub subscribe_candles: bool,
- pub candle_interval: Option<String>,
-}
-
-/// Error type for barter operations
-#[derive(Debug, thiserror::Error)]
-pub enum BarterError {
- #[error("Exchange error: {0}")]
- Exchange(String),
-
- #[error("Order error: {0}")]
- Order(String),
-
- #[error("Strategy error: {0}")]
- Strategy(String),
-
- #[error("Market data error: {0}")]
- MarketData(String),
-
- #[error("Backtest error: {0}")]
- Backtest(String),
-
- #[error("Configuration error: {0}")]
- Config(String),
-
- #[error("Internal error: {0}")]
- Internal(String),
-}
-
-impl Serialize for BarterError {
- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where
- S: serde::Serializer,
- {
- serializer.serialize_str(&self.to_string())
- }
-}
-
-pub type BarterResult<T> = Result<T, BarterError>;
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/adb.rs b/fincept-terminal-desktop/src-tauri/src/commands/adb.rs
index 71f05eb50..e19adf882 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/adb.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/adb.rs
@@ -1,8 +1,7 @@
// Asian Development Bank data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute ADB Python script command with PyO3
#[tauri::command]
pub async fn execute_adb_command(
app: tauri::AppHandle,
@@ -13,9 +12,7 @@ pub async fn execute_adb_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "adb_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "adb_data.py", cmd_args).await
}
/// Get economic indicators for Asian countries
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs b/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs
index 5621b6422..f1ee959cf 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs
@@ -1,7 +1,6 @@
// Agent Streaming Module - High-performance streaming agent execution
// Uses Tauri events for real-time token streaming and parallel execution
-use crate::utils::python::get_script_path;
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter};
use std::sync::Arc;
@@ -80,7 +79,6 @@ pub async fn execute_agent_streaming(
obj.insert("stream_id".to_string(), serde_json::json!(stream_id.clone()));
}
- let script_path = get_script_path(&app, "agents/finagent_core/core_agent_stream.py")?;
let payload_str = serde_json::to_string(&payload)
.map_err(|e| format!("Failed to serialize payload: {}", e))?;
@@ -101,7 +99,8 @@ pub async fn execute_agent_streaming(
// Execute with streaming callback
match execute_with_stream_callback(
- &script_path,
+ &app_clone,
+ "agents/finagent_core/core_agent_stream.py",
vec![payload_str],
move |chunk_type, content, metadata| {
// Check cancellation
@@ -192,8 +191,6 @@ pub async fn execute_agents_parallel(
let start_time = std::time::Instant::now();
let max_concurrent = max_concurrent.unwrap_or(4);
- let script_path = get_script_path(&app, "agents/finagent_core/core_agent.py")?;
-
// Create semaphore for concurrency control
let semaphore = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
@@ -202,18 +199,19 @@ pub async fn execute_agents_parallel(
for (idx, task) in tasks.into_iter().enumerate() {
let task_id = format!("{}-{}", batch_id, idx);
- let script_path = script_path.clone();
+ let app_clone = app.clone();
let semaphore = semaphore.clone();
let task_start = std::time::Instant::now();
let handle = tokio::spawn(async move {
// Acquire semaphore permit
- let _permit = semaphore.acquire().await.unwrap();
+ let _permit = semaphore.acquire().await
+ .map_err(|e| format!("Semaphore closed: {}", e))?;
let payload_str = serde_json::to_string(&task)
.map_err(|e| format!("Failed to serialize: {}", e))?;
- match crate::python_runtime::execute_python_script_async(&script_path, vec![payload_str]).await {
+ match crate::python::execute(&app_clone, "agents/finagent_core/core_agent.py", vec![payload_str]).await {
Ok(result) => {
let parsed: serde_json::Value = serde_json::from_str(&result)
.unwrap_or(serde_json::json!({"raw": result}));
@@ -285,15 +283,12 @@ pub async fn execute_agent_priority(
payload: serde_json::Value,
priority: u8, // 0=HIGH, 1=NORMAL, 2=LOW
) -> Result<String, String> {
- let script_path = get_script_path(&app, "agents/finagent_core/core_agent.py")?;
let payload_str = serde_json::to_string(&payload)
.map_err(|e| format!("Failed to serialize payload: {}", e))?;
- crate::python_runtime::execute_python_script_async_with_priority(
- &script_path,
- vec![payload_str],
- priority
- ).await
+ // Priority is currently ignored - using standard execute
+ let _ = priority; // Acknowledge unused parameter
+ crate::python::execute(&app, "agents/finagent_core/core_agent.py", vec![payload_str]).await
}
/// Get status of all active agent streams
@@ -312,7 +307,8 @@ pub async fn get_active_agent_streams() -> Result<String, String> {
/// Internal: Execute with streaming callback (simulated for now)
/// In production, this would use a named pipe or socket to get streaming output
async fn execute_with_stream_callback<F>(
- script_path: &std::path::PathBuf,
+ app: &AppHandle,
+ script_name: &str,
args: Vec<String>,
mut callback: F,
) -> Result<String, String>
@@ -325,7 +321,7 @@ where
// Emit thinking indicator
callback("thinking", "Processing your request...", None);
- let result = crate::python_runtime::execute_python_script_async(script_path, args).await?;
+ let result = crate::python::execute(app, script_name, args).await?;
// Parse and emit tokens (simulated chunking for now)
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&result) {
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
index 6f938e632..844f35d65 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
@@ -1,6 +1,5 @@
// agents.rs - Unified agent commands with single JSON payload
-use crate::utils::python::execute_python_subprocess;
-use crate::python_runtime;
+use crate::python;
use serde::{Deserialize, Serialize};
use tauri::Manager;
use std::time::Duration;
@@ -93,12 +92,7 @@ async fn execute_core_agent_with_timeout(
let result = timeout(
Duration::from_secs(timeout_secs),
tokio::task::spawn_blocking(move || {
- execute_python_subprocess(
- &app_clone,
- "agents/finagent_core/main.py",
- &args,
- Some("agno"),
- )
+ python::execute_sync(&app_clone, "agents/finagent_core/main.py", args)
})
).await;
@@ -277,25 +271,6 @@ pub async fn execute_python_agent(
let script_path = get_agent_script_path(&agent_type)
.ok_or_else(|| format!("Unknown agent type: {}", agent_type))?;
- let full_script_path = if cfg!(debug_assertions) {
- let current_dir = std::env::current_dir()
- .map_err(|e| format!("Failed to get current directory: {}", e))?;
- let base_dir = if current_dir.ends_with("src-tauri") {
- current_dir
- } else {
- current_dir.join("src-tauri")
- };
- base_dir.join("resources").join("scripts").join(script_path)
- } else {
- let resource_dir = app.path().resource_dir()
- .map_err(|e| format!("Failed to get resource directory: {}", e))?;
- resource_dir.join("scripts").join(script_path)
- };
-
- if !full_script_path.exists() {
- return Err(format!("Script not found: {}", full_script_path.display()));
- }
-
let args = vec![
"--parameters".to_string(),
serde_json::to_string(&parameters).unwrap_or_default(),
@@ -303,7 +278,7 @@ pub async fn execute_python_agent(
serde_json::to_string(&inputs).unwrap_or_default(),
];
- let result_str = python_runtime::execute_python_script(&full_script_path, args)
+ let result_str = python::execute_sync(&app, script_path, args)
.map_err(|e| {
let execution_time = start_time.elapsed().as_millis() as u64;
format!("Python execution failed after {}ms: {}", execution_time, e)
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agno_trading.rs b/fincept-terminal-desktop/src-tauri/src/commands/agno_trading.rs
index 8890a12fe..2da80a42c 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/agno_trading.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agno_trading.rs
@@ -1,8 +1,7 @@
// Agno Trading Agent Commands
// Provides Rust/Tauri interface to Python-based Agno trading agents
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// List available LLM models
#[tauri::command]
@@ -16,8 +15,7 @@ pub async fn agno_list_models(
args.push(p);
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Recommend best model for a task
@@ -42,8 +40,7 @@ pub async fn agno_recommend_model(
args.push("false".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Validate Agno configuration
@@ -53,8 +50,7 @@ pub async fn agno_validate_config(
config_json: String,
) -> Result<String, String> {
let args = vec!["validate_config".to_string(), config_json];
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Create a new trading agent
@@ -64,8 +60,7 @@ pub async fn agno_create_agent(
agent_config_json: String,
) -> Result<String, String> {
let args = vec!["create_agent".to_string(), agent_config_json];
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Run an agent with a prompt
@@ -82,8 +77,7 @@ pub async fn agno_run_agent(
args.push(sid);
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Analyze market for a given symbol
@@ -116,8 +110,7 @@ pub async fn agno_analyze_market(
args.push("{}".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Generate trading signal
@@ -157,8 +150,7 @@ pub async fn agno_generate_trade_signal(
args.push("{}".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Run risk management analysis
@@ -191,8 +183,7 @@ pub async fn agno_manage_risk(
args.push("{}".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Get configuration template
@@ -209,8 +200,7 @@ pub async fn agno_get_config_template(
args.push("default".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Create multi-model competition
@@ -237,8 +227,7 @@ pub async fn agno_create_competition(
args.push("{}".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Run multi-model competition
@@ -265,8 +254,7 @@ pub async fn agno_run_competition(
args.push("{}".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Get model performance leaderboard
@@ -275,8 +263,7 @@ pub async fn agno_get_leaderboard(
app: tauri::AppHandle,
) -> Result<String, String> {
let args = vec!["get_leaderboard".to_string()];
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Get recent model decisions
@@ -293,8 +280,7 @@ pub async fn agno_get_recent_decisions(
args.push("50".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
// ============================================================================
@@ -325,8 +311,7 @@ pub async fn agno_execute_trade(
args.push("{}".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Close an open position
@@ -349,8 +334,7 @@ pub async fn agno_close_position(
args.push("manual".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Get trade history for an agent
@@ -373,8 +357,7 @@ pub async fn agno_get_agent_trades(
args.push(s);
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Get performance metrics for an agent
@@ -384,8 +367,7 @@ pub async fn agno_get_agent_performance(
agent_id: String,
) -> Result<String, String> {
let args = vec!["get_agent_performance".to_string(), agent_id];
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Get leaderboard from database
@@ -402,8 +384,7 @@ pub async fn agno_get_db_leaderboard(
args.push("20".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Get recent decisions from database
@@ -425,8 +406,7 @@ pub async fn agno_get_db_decisions(
args.push(id);
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Run a Bull/Bear/Analyst debate
@@ -455,8 +435,7 @@ pub async fn agno_run_debate(
args.push("{}".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Get recent debate sessions
@@ -473,8 +452,7 @@ pub async fn agno_get_recent_debates(
args.push("10".to_string());
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Evolve an agent based on performance
@@ -499,8 +477,7 @@ pub async fn agno_evolve_agent(
args.push(n);
}
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Check if agent should evolve
@@ -510,8 +487,7 @@ pub async fn agno_check_evolution(
agent_id: String,
) -> Result<String, String> {
let args = vec!["check_evolution".to_string(), agent_id];
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
/// Get evolution summary for an agent
@@ -521,6 +497,5 @@ pub async fn agno_get_evolution_summary(
agent_id: String,
) -> Result<String, String> {
let args = vec!["get_evolution_summary".to_string(), agent_id];
- let script_path = get_script_path(&app, "agno_trading_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agno_trading_service.py", args).await
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/ai_agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/ai_agents.rs
index 452495bf3..b4f6986ef 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/ai_agents.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/ai_agents.rs
@@ -1,7 +1,6 @@
// AI Agents Commands - Economic, Geopolitical, Hedge Fund, and Investor agents
#![allow(dead_code)]
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
// ECONOMIC AGENTS
@@ -16,8 +15,7 @@ pub async fn execute_economic_agent(
let script_name = format!("agents/EconomicAgents/{}_agent_cli.py", agent_type);
let mut cmd_args = vec![command];
cmd_args.extend(args);
- let script_path = get_script_path(&app, &script_name)?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, &script_name, cmd_args).await
}
#[tauri::command]
@@ -30,8 +28,7 @@ pub async fn run_capitalism_agent(
if let Some(p) = parameters {
args.push(p);
}
- let script_path = get_script_path(&app, "agents/EconomicAgents/capitalism_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/EconomicAgents/capitalism_agent_cli.py", args).await
}
#[tauri::command]
@@ -44,8 +41,7 @@ pub async fn run_keynesian_agent(
if let Some(p) = parameters {
args.push(p);
}
- let script_path = get_script_path(&app, "agents/EconomicAgents/keynesian_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/EconomicAgents/keynesian_agent_cli.py", args).await
}
#[tauri::command]
@@ -58,8 +54,7 @@ pub async fn run_neoliberal_agent(
if let Some(p) = parameters {
args.push(p);
}
- let script_path = get_script_path(&app, "agents/EconomicAgents/neoliberal_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/EconomicAgents/neoliberal_agent_cli.py", args).await
}
#[tauri::command]
@@ -72,8 +67,7 @@ pub async fn run_socialism_agent(
if let Some(p) = parameters {
args.push(p);
}
- let script_path = get_script_path(&app, "agents/EconomicAgents/socialism_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/EconomicAgents/socialism_agent_cli.py", args).await
}
#[tauri::command]
@@ -86,8 +80,7 @@ pub async fn run_mercantilist_agent(
if let Some(p) = parameters {
args.push(p);
}
- let script_path = get_script_path(&app, "agents/EconomicAgents/mercantilist_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/EconomicAgents/mercantilist_agent_cli.py", args).await
}
#[tauri::command]
@@ -100,8 +93,7 @@ pub async fn run_mixed_economy_agent(
if let Some(p) = parameters {
args.push(p);
}
- let script_path = get_script_path(&app, "agents/EconomicAgents/mixed_economy_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/EconomicAgents/mixed_economy_agent_cli.py", args).await
}
// GEOPOLITICS AGENTS
@@ -114,8 +106,7 @@ pub async fn execute_geopolitics_agent(
) -> Result<String, String> {
let mut cmd_args = vec![command];
cmd_args.extend(args);
- let script_path = get_script_path(&app, "agents/GeopoliticsAgents/geopolitics_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "agents/GeopoliticsAgents/geopolitics_agent_cli.py", cmd_args).await
}
// Grand Chessboard Agents
@@ -129,8 +120,7 @@ pub async fn run_eurasian_chessboard_agent(
if let Some(at) = analysis_type {
args.push(at);
}
- let script_path = get_script_path(&app, "agents/GeopoliticsAgents/GrandChessboardAgents/chessboard_agents/eurasian_chessboard_master_agent.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/GeopoliticsAgents/GrandChessboardAgents/chessboard_agents/eurasian_chessboard_master_agent.py", args).await
}
#[tauri::command]
@@ -143,8 +133,7 @@ pub async fn run_geostrategic_players_agent(
if let Some(sp) = strategy_params {
args.push(sp);
}
- let script_path = get_script_path(&app, "agents/GeopoliticsAgents/GrandChessboardAgents/chessboard_agents/geostrategic_players_agent.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/GeopoliticsAgents/GrandChessboardAgents/chessboard_agents/geostrategic_players_agent.py", args).await
}
#[tauri::command]
@@ -157,8 +146,7 @@ pub async fn run_eurasian_balkans_agent(
if let Some(ap) = analysis_params {
args.push(ap);
}
- let script_path = get_script_path(&app, "agents/GeopoliticsAgents/GrandChessboardAgents/chessboard_agents/eurasian_balkans_agent.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/GeopoliticsAgents/GrandChessboardAgents/chessboard_agents/eurasian_balkans_agent.py", args).await
}
// Prisoners of Geography Agents
@@ -174,8 +162,7 @@ pub async fn run_geography_agent(
if let Some(at) = analysis_type {
args.push(at);
}
- let script_path = get_script_path(&app, &script_name)?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, &script_name, args).await
}
// World Order Agents
@@ -191,8 +178,7 @@ pub async fn run_world_order_agent(
if let Some(ap) = analysis_params {
args.push(ap);
}
- let script_path = get_script_path(&app, &script_name)?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, &script_name, args).await
}
#[tauri::command]
@@ -205,8 +191,7 @@ pub async fn run_westphalian_europe_agent(
if let Some(dp) = diplomatic_params {
args.push(dp);
}
- let script_path = get_script_path(&app, "agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/westphalian_europe_agent.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/westphalian_europe_agent.py", args).await
}
#[tauri::command]
@@ -219,8 +204,7 @@ pub async fn run_balance_power_agent(
if let Some(bp) = balance_params {
args.push(bp);
}
- let script_path = get_script_path(&app, "agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/balance_power_agent.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/balance_power_agent.py", args).await
}
// HEDGE FUND AGENTS
@@ -233,8 +217,7 @@ pub async fn execute_hedge_fund_agent(
) -> Result<String, String> {
let mut cmd_args = vec![command];
cmd_args.extend(args);
- let script_path = get_script_path(&app, "agents/hedgeFundAgents/hedge_fund_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "agents/hedgeFundAgents/hedge_fund_agent_cli.py", cmd_args).await
}
#[tauri::command]
@@ -247,8 +230,7 @@ pub async fn run_bridgewater_agent(
if let Some(sp) = strategy_params {
args.push(sp);
}
- let script_path = get_script_path(&app, "agents/hedgeFundAgents/bridgewater_associates_hedge_fund_agent/bridgewater_associates_agent.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/hedgeFundAgents/bridgewater_associates_hedge_fund_agent/bridgewater_associates_agent.py", args).await
}
#[tauri::command]
@@ -261,8 +243,7 @@ pub async fn run_citadel_agent(
if let Some(tp) = trading_params {
args.push(tp);
}
- let script_path = get_script_path(&app, "agents/hedgeFundAgents/citadel_hedge_fund_agent/citadel_agent.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/hedgeFundAgents/citadel_hedge_fund_agent/citadel_agent.py", args).await
}
#[tauri::command]
@@ -275,8 +256,7 @@ pub async fn run_renaissance_agent(
if let Some(qp) = quant_params {
args.push(qp);
}
- let script_path = get_script_path(&app, "agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/renaissance_technologies_agent.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/renaissance_technologies_agent.py", args).await
}
#[tauri::command]
@@ -289,8 +269,7 @@ pub async fn run_de_shaw_agent(
if let Some(cp) = computational_params {
args.push(cp);
}
- let script_path = get_script_path(&app, "agents/hedgeFundAgents/de_shaw_hedge_fund_agent/de_shaw_agent.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/hedgeFundAgents/de_shaw_hedge_fund_agent/de_shaw_agent.py", args).await
}
#[tauri::command]
@@ -303,8 +282,7 @@ pub async fn run_two_sigma_agent(
if let Some(mlp) = ml_params {
args.push(mlp);
}
- let script_path = get_script_path(&app, "agents/hedgeFundAgents/two_sigma_hedge_fund_agent/two_sigma_agent.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/hedgeFundAgents/two_sigma_hedge_fund_agent/two_sigma_agent.py", args).await
}
#[tauri::command]
@@ -317,8 +295,7 @@ pub async fn run_elliott_management_agent(
if let Some(ap) = activist_params {
args.push(ap);
}
- let script_path = get_script_path(&app, "agents/hedgeFundAgents/elliott_management_hedge_fund_agent/elliott_management_agent.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/hedgeFundAgents/elliott_management_hedge_fund_agent/elliott_management_agent.py", args).await
}
#[tauri::command]
@@ -331,8 +308,7 @@ pub async fn run_fincept_hedge_fund_orchestrator(
if let Some(op) = orchestration_params {
args.push(op);
}
- let script_path = get_script_path(&app, "agents/hedgeFundAgents/fincept_hedge_fund/agent_orchestrator.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/hedgeFundAgents/fincept_hedge_fund/agent_orchestrator.py", args).await
}
// TRADER/INVESTOR AGENTS
@@ -347,8 +323,7 @@ pub async fn run_warren_buffett_agent(
if let Some(vp) = value_params {
args.push(vp);
}
- let script_path = get_script_path(&app, "agents/TraderInvestorsAgent/warren_buffett_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/TraderInvestorsAgent/warren_buffett_agent_cli.py", args).await
}
#[tauri::command]
@@ -361,8 +336,7 @@ pub async fn run_benjamin_graham_agent(
if let Some(vp) = value_params {
args.push(vp);
}
- let script_path = get_script_path(&app, "agents/TraderInvestorsAgent/benjamin_graham_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/TraderInvestorsAgent/benjamin_graham_agent_cli.py", args).await
}
#[tauri::command]
@@ -375,8 +349,7 @@ pub async fn run_charlie_munger_agent(
if let Some(mm) = mental_models {
args.push(mm);
}
- let script_path = get_script_path(&app, "agents/TraderInvestorsAgent/charlie_munger_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/TraderInvestorsAgent/charlie_munger_agent_cli.py", args).await
}
#[tauri::command]
@@ -389,8 +362,7 @@ pub async fn run_seth_klarman_agent(
if let Some(mos) = margin_of_safety {
args.push(mos);
}
- let script_path = get_script_path(&app, "agents/TraderInvestorsAgent/seth_klarman_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/TraderInvestorsAgent/seth_klarman_agent_cli.py", args).await
}
#[tauri::command]
@@ -403,8 +375,7 @@ pub async fn run_howard_marks_agent(
if let Some(cp) = cycle_params {
args.push(cp);
}
- let script_path = get_script_path(&app, "agents/TraderInvestorsAgent/howard_marks_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/TraderInvestorsAgent/howard_marks_agent_cli.py", args).await
}
#[tauri::command]
@@ -417,8 +388,7 @@ pub async fn run_joel_greenblatt_agent(
if let Some(mfp) = magic_formula_params {
args.push(mfp);
}
- let script_path = get_script_path(&app, "agents/TraderInvestorsAgent/joel_greenblatt_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/TraderInvestorsAgent/joel_greenblatt_agent_cli.py", args).await
}
#[tauri::command]
@@ -431,8 +401,7 @@ pub async fn run_david_einhorn_agent(
if let Some(sp) = short_params {
args.push(sp);
}
- let script_path = get_script_path(&app, "agents/TraderInvestorsAgent/david_einhorn_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/TraderInvestorsAgent/david_einhorn_agent_cli.py", args).await
}
#[tauri::command]
@@ -445,6 +414,5 @@ pub async fn run_bill_miller_agent(
if let Some(cp) = contrarian_params {
args.push(cp);
}
- let script_path = get_script_path(&app, "agents/TraderInvestorsAgent/bill_miller_agent_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "agents/TraderInvestorsAgent/bill_miller_agent_cli.py", args).await
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/ai_quant_lab.rs b/fincept-terminal-desktop/src-tauri/src/commands/ai_quant_lab.rs
index 80fa76cda..7dbe59bf1 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/ai_quant_lab.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/ai_quant_lab.rs
@@ -1,7 +1,7 @@
// AI Quant Lab Commands - Qlib and RD-Agent integration
// Uses direct subprocess execution to avoid worker pool socket issues on Windows
#![allow(dead_code)]
-use crate::utils::python::execute_python_subprocess;
+use crate::python;
// ============================================================================
// QLIB COMMANDS
@@ -18,28 +18,28 @@ pub async fn qlib_initialize(
let reg = region.unwrap_or_else(|| "cn".to_string());
let args = vec!["initialize".to_string(), uri, reg];
- execute_python_subprocess(&app, "ai_quant_lab/qlib_service.py", &args, Some("qlib"))
+ python::execute_sync(&app, "ai_quant_lab/qlib_service.py", args)
}
/// Check Qlib status and availability
#[tauri::command]
pub async fn qlib_check_status(app: tauri::AppHandle) -> Result<String, String> {
let args = vec!["check_status".to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/qlib_service.py", &args, Some("qlib"))
+ python::execute_sync(&app, "ai_quant_lab/qlib_service.py", args)
}
/// List available pre-trained models
#[tauri::command]
pub async fn qlib_list_models(app: tauri::AppHandle) -> Result<String, String> {
let args = vec!["list_models".to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/qlib_service.py", &args, Some("qlib"))
+ python::execute_sync(&app, "ai_quant_lab/qlib_service.py", args)
}
/// Get factor library information
#[tauri::command]
pub async fn qlib_get_factor_library(app: tauri::AppHandle) -> Result<String, String> {
let args = vec!["get_factor_library".to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/qlib_service.py", &args, Some("qlib"))
+ python::execute_sync(&app, "ai_quant_lab/qlib_service.py", args)
}
/// Fetch market data using Qlib
@@ -59,7 +59,7 @@ pub async fn qlib_get_data(
});
let args = vec!["get_data".to_string(), params.to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/qlib_service.py", &args, Some("qlib"))
+ python::execute_sync(&app, "ai_quant_lab/qlib_service.py", args)
}
/// Train a Qlib model
@@ -77,7 +77,7 @@ pub async fn qlib_train_model(
});
let args = vec!["train_model".to_string(), params.to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/qlib_service.py", &args, Some("qlib"))
+ python::execute_sync(&app, "ai_quant_lab/qlib_service.py", args)
}
/// Run backtest with Qlib
@@ -93,7 +93,7 @@ pub async fn qlib_run_backtest(
});
let args = vec!["run_backtest".to_string(), params.to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/qlib_service.py", &args, Some("qlib"))
+ python::execute_sync(&app, "ai_quant_lab/qlib_service.py", args)
}
/// Optimize portfolio weights
@@ -109,7 +109,7 @@ pub async fn qlib_optimize_portfolio(
});
let args = vec!["optimize_portfolio".to_string(), params.to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/qlib_service.py", &args, Some("qlib"))
+ python::execute_sync(&app, "ai_quant_lab/qlib_service.py", args)
}
// ============================================================================
@@ -128,21 +128,21 @@ pub async fn rdagent_initialize(
vec!["initialize".to_string()]
};
- execute_python_subprocess(&app, "ai_quant_lab/rd_agent_service.py", &args, Some("rdagent"))
+ python::execute_sync(&app, "ai_quant_lab/rd_agent_service.py", args)
}
/// Check RD-Agent status and availability
#[tauri::command]
pub async fn rdagent_check_status(app: tauri::AppHandle) -> Result<String, String> {
let args = vec!["check_status".to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/rd_agent_service.py", &args, Some("rdagent"))
+ python::execute_sync(&app, "ai_quant_lab/rd_agent_service.py", args)
}
/// Get RD-Agent capabilities
#[tauri::command]
pub async fn rdagent_get_capabilities(app: tauri::AppHandle) -> Result<String, String> {
let args = vec!["get_capabilities".to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/rd_agent_service.py", &args, Some("rdagent"))
+ python::execute_sync(&app, "ai_quant_lab/rd_agent_service.py", args)
}
/// Start autonomous factor mining
@@ -162,7 +162,7 @@ pub async fn rdagent_start_factor_mining(
});
let args = vec!["start_factor_mining".to_string(), params.to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/rd_agent_service.py", &args, Some("rdagent"))
+ python::execute_sync(&app, "ai_quant_lab/rd_agent_service.py", args)
}
/// Get factor mining task status
@@ -172,7 +172,7 @@ pub async fn rdagent_get_factor_mining_status(
task_id: String,
) -> Result<String, String> {
let args = vec!["get_factor_mining_status".to_string(), task_id];
- execute_python_subprocess(&app, "ai_quant_lab/rd_agent_service.py", &args, Some("rdagent"))
+ python::execute_sync(&app, "ai_quant_lab/rd_agent_service.py", args)
}
/// Get discovered factors
@@ -182,7 +182,7 @@ pub async fn rdagent_get_discovered_factors(
task_id: String,
) -> Result<String, String> {
let args = vec!["get_discovered_factors".to_string(), task_id];
- execute_python_subprocess(&app, "ai_quant_lab/rd_agent_service.py", &args, Some("rdagent"))
+ python::execute_sync(&app, "ai_quant_lab/rd_agent_service.py", args)
}
/// Optimize model using RD-Agent
@@ -200,7 +200,7 @@ pub async fn rdagent_optimize_model(
});
let args = vec!["optimize_model".to_string(), params.to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/rd_agent_service.py", &args, Some("rdagent"))
+ python::execute_sync(&app, "ai_quant_lab/rd_agent_service.py", args)
}
/// Analyze financial document
@@ -216,7 +216,7 @@ pub async fn rdagent_analyze_document(
});
let args = vec!["analyze_document".to_string(), params.to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/rd_agent_service.py", &args, Some("rdagent"))
+ python::execute_sync(&app, "ai_quant_lab/rd_agent_service.py", args)
}
/// Run autonomous research
@@ -234,5 +234,5 @@ pub async fn rdagent_run_autonomous_research(
});
let args = vec!["run_autonomous_research".to_string(), params.to_string()];
- execute_python_subprocess(&app, "ai_quant_lab/rd_agent_service.py", &args, Some("rdagent"))
+ python::execute_sync(&app, "ai_quant_lab/rd_agent_service.py", args)
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/akshare.rs b/fincept-terminal-desktop/src-tauri/src/commands/akshare.rs
index b26c92170..b9da3c637 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/akshare.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/akshare.rs
@@ -1,6 +1,6 @@
use tauri::command;
use serde::{Deserialize, Serialize};
-use std::process::Command;
+use crate::python;
#[derive(Debug, Serialize, Deserialize)]
pub struct AKShareResponse {
@@ -11,66 +11,29 @@ pub struct AKShareResponse {
pub error: Option<serde_json::Value>,
}
-fn run_python_script(script: &str, endpoint: &str) -> Result<AKShareResponse, String> {
- let output = Command::new("python")
- .arg(format!("resources/scripts/{}", script))
- .arg(endpoint)
- .output()
- .map_err(|e| format!("Failed to execute Python script: {}", e))?;
-
- if output.status.success() {
- let result: AKShareResponse = serde_json::from_slice(&output.stdout)
- .map_err(|e| format!("Failed to parse JSON: {}", e))?;
- Ok(result)
- } else {
- let error_msg = String::from_utf8_lossy(&output.stderr).to_string();
- Err(format!("Script error: {}", error_msg))
- }
+fn run_python_script(app: &tauri::AppHandle, script: &str, endpoint: &str) -> Result<AKShareResponse, String> {
+ let output = python::execute_sync(app, script, vec![endpoint.to_string()])?;
+ serde_json::from_str(&output)
+ .map_err(|e| format!("Failed to parse JSON: {}", e))
}
-fn run_python_script_with_args(script: &str, args: Vec<&str>) -> Result<AKShareResponse, String> {
- let mut cmd = Command::new("python");
- cmd.arg(format!("resources/scripts/{}", script));
- for arg in args {
- cmd.arg(arg);
- }
-
- let output = cmd.output()
- .map_err(|e| format!("Failed to execute Python script: {}", e))?;
-
- if output.status.success() {
- let result: AKShareResponse = serde_json::from_slice(&output.stdout)
- .map_err(|e| format!("Failed to parse JSON: {}", e))?;
- Ok(result)
- } else {
- let error_msg = String::from_utf8_lossy(&output.stderr).to_string();
- Err(format!("Script error: {}", error_msg))
- }
+fn run_python_script_with_args(app: &tauri::AppHandle, script: &str, args: Vec<String>) -> Result<AKShareResponse, String> {
+ let output = python::execute_sync(app, script, args)?;
+ serde_json::from_str(&output)
+ .map_err(|e| format!("Failed to parse JSON: {}", e))
}
-fn run_python_script_with_symbol(script: &str, endpoint: &str, symbol: &str) -> Result<AKShareResponse, String> {
- let output = Command::new("python")
- .arg(format!("resources/scripts/{}", script))
- .arg(endpoint)
- .arg(symbol)
- .output()
- .map_err(|e| format!("Failed to execute Python script: {}", e))?;
-
- if output.status.success() {
- let result: AKShareResponse = serde_json::from_slice(&output.stdout)
- .map_err(|e| format!("Failed to parse JSON: {}", e))?;
- Ok(result)
- } else {
- let error_msg = String::from_utf8_lossy(&output.stderr).to_string();
- Err(format!("Script error: {}", error_msg))
- }
+fn run_python_script_with_symbol(app: &tauri::AppHandle, script: &str, endpoint: &str, symbol: &str) -> Result<AKShareResponse, String> {
+ let output = python::execute_sync(app, script, vec![endpoint.to_string(), symbol.to_string()])?;
+ serde_json::from_str(&output)
+ .map_err(|e| format!("Failed to parse JSON: {}", e))
}
// ==================== GENERIC AKSHARE COMMAND ====================
// This allows the frontend to call any endpoint from any script dynamically
#[command]
-pub async fn akshare_query(script: String, endpoint: String, args: Option<Vec<String>>) -> Result<AKShareResponse, String> {
+pub async fn akshare_query(app: tauri::AppHandle, script: String, endpoint: String, args: Option<Vec<String>>) -> Result<AKShareResponse, String> {
// Validate script name to prevent path traversal
let valid_scripts = vec![
"akshare_data.py",
@@ -105,20 +68,18 @@ pub async fn akshare_query(script: String, endpoint: String, args: Option<Vec<St
return Err(format!("Invalid script: {}. Valid scripts: {:?}", script, valid_scripts));
}
- let mut cmd_args = vec![endpoint.as_str()];
- let arg_refs: Vec<&str>;
- if let Some(ref extra_args) = args {
- arg_refs = extra_args.iter().map(|s| s.as_str()).collect();
- cmd_args.extend(arg_refs.iter());
+ let mut cmd_args = vec![endpoint];
+ if let Some(extra_args) = args {
+ cmd_args.extend(extra_args);
}
- run_python_script_with_args(&script, cmd_args)
+ run_python_script_with_args(&app, &script, cmd_args)
}
// ==================== GET AVAILABLE ENDPOINTS ====================
#[command]
-pub async fn akshare_get_endpoints(script: String) -> Result<AKShareResponse, String> {
+pub async fn akshare_get_endpoints(app: tauri::AppHandle, script: String) -> Result<AKShareResponse, String> {
let valid_scripts = vec![
"akshare_data.py",
"akshare_bonds.py",
@@ -152,107 +113,107 @@ pub async fn akshare_get_endpoints(script: String) -> Result<AKShareResponse, St
return Err(format!("Invalid script: {}", script));
}
- run_python_script(&script, "get_all_endpoints")
+ run_python_script(&app, &script, "get_all_endpoints")
}
// ==================== STOCK MARKET DATA ====================
#[command]
-pub async fn get_stock_cn_spot() -> Result<AKShareResponse, String> {
- run_python_script("akshare_data.py", "stock_zh_spot")
+pub async fn get_stock_cn_spot(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_data.py", "stock_zh_spot")
}
#[command]
-pub async fn get_stock_us_spot() -> Result<AKShareResponse, String> {
- run_python_script("akshare_data.py", "stock_us_spot")
+pub async fn get_stock_us_spot(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_data.py", "stock_us_spot")
}
#[command]
-pub async fn get_stock_hk_spot() -> Result<AKShareResponse, String> {
- run_python_script("akshare_data.py", "stock_hk_spot")
+pub async fn get_stock_hk_spot(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_data.py", "stock_hk_spot")
}
#[command]
-pub async fn get_stock_hot_rank() -> Result<AKShareResponse, String> {
- run_python_script("akshare_data.py", "hot_rank")
+pub async fn get_stock_hot_rank(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_data.py", "hot_rank")
}
#[command]
-pub async fn get_stock_industry_list() -> Result<AKShareResponse, String> {
- run_python_script("akshare_data.py", "industry_list")
+pub async fn get_stock_industry_list(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_data.py", "industry_list")
}
#[command]
-pub async fn get_stock_concept_list() -> Result<AKShareResponse, String> {
- run_python_script("akshare_data.py", "concept_list")
+pub async fn get_stock_concept_list(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_data.py", "concept_list")
}
#[command]
-pub async fn get_stock_hsgt_data() -> Result<AKShareResponse, String> {
- run_python_script("akshare_data.py", "hsgt")
+pub async fn get_stock_hsgt_data(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_data.py", "hsgt")
}
#[command]
-pub async fn get_stock_industry_pe() -> Result<AKShareResponse, String> {
- run_python_script("akshare_data.py", "industry_pe")
+pub async fn get_stock_industry_pe(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_data.py", "industry_pe")
}
// ==================== ECONOMICS ====================
#[command]
-pub async fn get_macro_china_gdp() -> Result<AKShareResponse, String> {
- run_python_script("akshare_economics_china.py", "gdp")
+pub async fn get_macro_china_gdp(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_economics_china.py", "gdp")
}
#[command]
-pub async fn get_macro_china_cpi() -> Result<AKShareResponse, String> {
- run_python_script("akshare_economics_china.py", "cpi")
+pub async fn get_macro_china_cpi(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_economics_china.py", "cpi")
}
#[command]
-pub async fn get_macro_china_pmi() -> Result<AKShareResponse, String> {
- run_python_script("akshare_economics_china.py", "pmi")
+pub async fn get_macro_china_pmi(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_economics_china.py", "pmi")
}
// ==================== BONDS ====================
#[command]
-pub async fn get_bond_china_yield() -> Result<AKShareResponse, String> {
- run_python_script("akshare_bonds.py", "bond_yield")
+pub async fn get_bond_china_yield(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_bonds.py", "bond_yield")
}
// ==================== FUNDS ====================
#[command]
-pub async fn get_fund_etf_spot() -> Result<AKShareResponse, String> {
- run_python_script("akshare_data.py", "etf_spot")
+pub async fn get_fund_etf_spot(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_data.py", "etf_spot")
}
#[command]
-pub async fn get_fund_ranking() -> Result<AKShareResponse, String> {
- run_python_script("akshare_data.py", "fund_rank")
+pub async fn get_fund_ranking(app: tauri::AppHandle) -> Result<AKShareResponse, String> {
+ run_python_script(&app, "akshare_data.py", "fund_rank")
}
// ==================== COMPANY INFORMATION ====================
#[command]
-pub async fn get_stock_cn_info(symbol: String) -> Result<AKShareResponse, String> {
- run_python_script_with_symbol("akshare_company_info.py", "cn_basic", &symbol)
+pub async fn get_stock_cn_info(app: tauri::AppHandle, symbol: String) -> Result<AKShareResponse, String> {
+ run_python_script_with_symbol(&app, "akshare_company_info.py", "cn_basic", &symbol)
}
#[command]
-pub async fn get_stock_cn_profile(symbol: String) -> Result<AKShareResponse, String> {
- run_python_script_with_symbol("akshare_company_info.py", "cn_profile", &symbol)
+pub async fn get_stock_cn_profile(app: tauri::AppHandle, symbol: String) -> Result<AKShareResponse, String> {
+ run_python_script_with_symbol(&app, "akshare_company_info.py", "cn_profile", &symbol)
}
#[command]
-pub async fn get_stock_hk_profile(symbol: String) -> Result<AKShareResponse, String> {
- run_python_script_with_symbol("akshare_company_info.py", "hk_profile", &symbol)
+pub async fn get_stock_hk_profile(app: tauri::AppHandle, symbol: String) -> Result<AKShareResponse, String> {
+ run_python_script_with_symbol(&app, "akshare_company_info.py", "hk_profile", &symbol)
}
#[command]
-pub async fn get_stock_us_info(symbol: String) -> Result<AKShareResponse, String> {
- run_python_script_with_symbol("akshare_company_info.py", "us_info", &symbol)
+pub async fn get_stock_us_info(app: tauri::AppHandle, symbol: String) -> Result<AKShareResponse, String> {
+ run_python_script_with_symbol(&app, "akshare_company_info.py", "us_info", &symbol)
}
// ==================== DATABASE MANAGEMENT ====================
@@ -300,18 +261,9 @@ pub async fn check_akshare_db_status() -> Result<DbStatusResponse, String> {
}
#[command]
-pub async fn build_akshare_database() -> Result<String, String> {
- let output = Command::new("python")
- .arg("resources/scripts/build_akshare_symbols_db.py")
- .output()
- .map_err(|e| format!("Failed to execute database build script: {}", e))?;
-
- if output.status.success() {
- Ok("Database built successfully".to_string())
- } else {
- let error_msg = String::from_utf8_lossy(&output.stderr).to_string();
- Err(format!("Database build failed: {}", error_msg))
- }
+pub async fn build_akshare_database(app: tauri::AppHandle) -> Result<String, String> {
+ python::execute_sync(&app, "build_akshare_symbols_db.py", vec![])
+ .map(|_| "Database built successfully".to_string())
}
#[derive(Debug, Serialize, Deserialize)]
@@ -329,25 +281,16 @@ pub struct Translation {
}
#[command]
-pub async fn translate_batch(texts: Vec<String>, target_lang: String) -> Result<TranslateResponse, String> {
+pub async fn translate_batch(app: tauri::AppHandle, texts: Vec<String>, target_lang: String) -> Result<TranslateResponse, String> {
let texts_json = serde_json::to_string(&texts)
.map_err(|e| format!("Failed to serialize texts: {}", e))?;
- let output = Command::new("python")
- .arg("resources/scripts/translate_text.py")
- .arg("batch")
- .arg(&texts_json)
- .arg("auto")
- .arg(&target_lang)
- .output()
- .map_err(|e| format!("Failed to execute translation script: {}", e))?;
-
- if output.status.success() {
- let result: TranslateResponse = serde_json::from_slice(&output.stdout)
- .map_err(|e| format!("Failed to parse translation response: {}", e))?;
- Ok(result)
- } else {
- let error_msg = String::from_utf8_lossy(&output.stderr).to_string();
- Err(format!("Translation failed: {}", error_msg))
- }
+ let output = python::execute_sync(
+ &app,
+ "translate_text.py",
+ vec!["batch".to_string(), texts_json, "auto".to_string(), target_lang]
+ )?;
+
+ serde_json::from_str(&output)
+ .map_err(|e| format!("Failed to parse translation response: {}", e))
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs
index b0c7d6d0a..ecb03791e 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs
@@ -2,13 +2,14 @@
* Alpha Arena Tauri Commands
* Rust commands for AI trading competition (refactored v2)
* Now with streaming support for real-time progress updates
+ * Refactored to use unified python module API
*/
use tauri::{command, AppHandle, Emitter};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
-use std::process::Command;
use std::collections::HashMap;
+use crate::python;
/// Extract JSON object from output that may contain log lines before it
fn extract_json_from_output(output: &str) -> Result<String, String> {
@@ -62,31 +63,12 @@ pub struct AlphaArenaProgress {
}
/// Execute Python alpha_arena main.py with JSON payload
-async fn execute_alpha_arena_action(action: &str, params: Value, api_keys: Option<HashMap<String, String>>) -> Result<Value, String> {
- // Use proper path separators for the platform
- let python_script_parts = ["alpha_arena", "main.py"];
-
- // Try multiple possible paths for the script
- let possible_paths = vec![
- std::env::current_dir()
- .ok()
- .map(|d| d.join("src-tauri").join("resources").join("scripts").join(python_script_parts[0]).join(python_script_parts[1])),
- std::env::current_dir()
- .ok()
- .map(|d| d.join("resources").join("scripts").join(python_script_parts[0]).join(python_script_parts[1])),
- // Check for bundled resources in release builds
- std::env::current_exe()
- .ok()
- .and_then(|p| p.parent().map(|d| d.to_path_buf()))
- .map(|d| d.join("resources").join("scripts").join(python_script_parts[0]).join(python_script_parts[1])),
- ];
-
- let script_path = possible_paths
- .into_iter()
- .flatten()
- .find(|p| p.exists())
- .ok_or_else(|| format!("Could not find Python script: alpha_arena/main.py. Searched paths failed to locate the script."))?;
-
+async fn execute_alpha_arena_action(
+ app: &AppHandle,
+ action: &str,
+ params: Value,
+ api_keys: Option<HashMap<String, String>>
+) -> Result<Value, String> {
// Create JSON payload with API keys
let payload = json!({
"action": action,
@@ -97,95 +79,15 @@ async fn execute_alpha_arena_action(action: &str, params: Value, api_keys: Optio
.map_err(|e| format!("Failed to serialize payload: {}", e))?;
eprintln!("[Alpha Arena v2] Executing action: {}", action);
- eprintln!("[Alpha Arena v2] Script path: {:?}", script_path);
-
- let script_path_clone = script_path.clone();
- let payload_clone = payload_str.clone();
-
- // Execute directly via subprocess (bypasses worker pool to avoid async deadlocks)
- // The worker pool uses async socket IPC which can deadlock when called from spawn_blocking
- let execution_result = tokio::time::timeout(
- tokio::time::Duration::from_secs(120), // 2 minute timeout
- tokio::task::spawn_blocking(move || {
- eprintln!("[Alpha Arena v2] Using direct subprocess execution");
-
- // Get working directory for script
- let script_dir = script_path_clone.parent()
- .map(|p| p.to_path_buf())
- .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
-
- // Execute Python directly
- let result = Command::new("python")
- .env("PYTHONDONTWRITEBYTECODE", "1")
- .env("PYTHONIOENCODING", "utf-8")
- .current_dir(&script_dir)
- .arg(&script_path_clone)
- .arg(&payload_clone)
- .output()
- .map_err(|e| format!("Failed to execute Python subprocess: {}", e))?;
-
- let stderr = String::from_utf8_lossy(&result.stderr);
- let stdout_str = String::from_utf8_lossy(&result.stdout);
-
- eprintln!("[Alpha Arena v2] ==================== RAW OUTPUT START ====================");
- eprintln!("[Alpha Arena v2] Python exit code: {:?}", result.status.code());
- eprintln!("[Alpha Arena v2] Python stdout length: {} chars", stdout_str.len());
- eprintln!("[Alpha Arena v2] Python stderr length: {} chars", stderr.len());
-
- // Log full stdout (up to 5000 chars for debugging)
- if !stdout_str.is_empty() {
- let stdout_preview: String = stdout_str.chars().take(5000).collect();
- eprintln!("[Alpha Arena v2] RAW STDOUT:\n{}", stdout_preview);
- if stdout_str.len() > 5000 {
- eprintln!("[Alpha Arena v2] ... (truncated, {} more chars)", stdout_str.len() - 5000);
- }
- } else {
- eprintln!("[Alpha Arena v2] STDOUT is EMPTY!");
- }
- // Log full stderr (up to 2000 chars for debugging)
- if !stderr.is_empty() {
- let stderr_preview: String = stderr.chars().take(2000).collect();
- eprintln!("[Alpha Arena v2] RAW STDERR:\n{}", stderr_preview);
- if stderr.len() > 2000 {
- eprintln!("[Alpha Arena v2] ... (truncated, {} more chars)", stderr.len() - 2000);
- }
- }
- eprintln!("[Alpha Arena v2] ==================== RAW OUTPUT END ====================");
-
- if !result.status.success() {
- eprintln!("[Alpha Arena v2] Python process FAILED with exit code: {:?}", result.status.code());
- // Try to extract JSON error from stdout first
- if let Some(json_start) = stdout_str.find('{') {
- if let Some(json_end) = stdout_str.rfind('}') {
- eprintln!("[Alpha Arena v2] Found JSON in stdout despite error exit");
- return Ok(stdout_str[json_start..=json_end].to_string());
- }
- }
- // Then try stderr
- if let Some(json_start) = stderr.find('{') {
- if let Some(json_end) = stderr.rfind('}') {
- eprintln!("[Alpha Arena v2] Found JSON in stderr");
- return Ok(stderr[json_start..=json_end].to_string());
- }
- }
- return Err(format!("Python error (exit code {:?}): {}", result.status.code(), stderr));
- }
+ // Use the unified python module API - execute_sync bypasses worker pool
+ let stdout = python::execute_sync(
+ app,
+ "alpha_arena/main.py",
+ vec![payload_str]
+ )?;
- eprintln!("[Alpha Arena v2] Python process SUCCESS");
- Ok(stdout_str.to_string())
- })
- )
- .await;
-
- let stdout = match execution_result {
- Ok(Ok(Ok(output))) => output,
- Ok(Ok(Err(e))) => return Err(e),
- Ok(Err(e)) => return Err(format!("Task join error: {}", e)),
- Err(_) => return Err("Python script execution timed out after 120 seconds".to_string()),
- };
-
- eprintln!("[Alpha Arena v2] Final output received, length: {} chars", stdout.len());
+ eprintln!("[Alpha Arena v2] Output received, length: {} chars", stdout.len());
// Try to parse JSON from output
let stdout_trimmed = stdout.trim();
@@ -195,18 +97,12 @@ async fn execute_alpha_arena_action(action: &str, params: Value, api_keys: Optio
}
// Find the LAST complete JSON object in output (skip any logging before it)
- // This handles cases where ERROR logs appear before the JSON result
eprintln!("[Alpha Arena v2] Extracting JSON from output...");
let json_str = extract_json_from_output(stdout_trimmed)?;
- eprintln!("[Alpha Arena v2] ==================== EXTRACTED JSON START ====================");
- // Log extracted JSON (up to 3000 chars)
- let json_preview: String = json_str.chars().take(3000).collect();
- eprintln!("{}", json_preview);
- if json_str.len() > 3000 {
- eprintln!("[Alpha Arena v2] ... (truncated, {} more chars)", json_str.len() - 3000);
- }
- eprintln!("[Alpha Arena v2] ==================== EXTRACTED JSON END ====================");
+ // Log extracted JSON preview (up to 1000 chars)
+ let json_preview: String = json_str.chars().take(1000).collect();
+ eprintln!("[Alpha Arena v2] Extracted JSON preview: {}", json_preview);
let parsed: Value = serde_json::from_str(&json_str)
.map_err(|e| format!("Failed to parse JSON: {}\nExtracted JSON: {}", e, json_str))?;
@@ -218,24 +114,6 @@ async fn execute_alpha_arena_action(action: &str, params: Value, api_keys: Optio
if let Some(error) = parsed.get("error") {
eprintln!("[Alpha Arena v2] Response error: {}", error);
}
- if let Some(leaderboard) = parsed.get("leaderboard") {
- if let Some(arr) = leaderboard.as_array() {
- eprintln!("[Alpha Arena v2] Response leaderboard entries: {}", arr.len());
- }
- }
- if let Some(decisions) = parsed.get("decisions") {
- if let Some(arr) = decisions.as_array() {
- eprintln!("[Alpha Arena v2] Response decisions entries: {}", arr.len());
- }
- }
- if let Some(snapshots) = parsed.get("snapshots") {
- if let Some(arr) = snapshots.as_array() {
- eprintln!("[Alpha Arena v2] Response snapshots entries: {}", arr.len());
- }
- }
- if let Some(cycle_number) = parsed.get("cycle_number") {
- eprintln!("[Alpha Arena v2] Response cycle_number: {}", cycle_number);
- }
Ok(parsed)
}
@@ -291,7 +169,7 @@ pub async fn create_alpha_competition(app: AppHandle, config_json: String, api_k
emit_progress(&app, "step", 4, 5, "Creating competition in backend...", None);
// Execute the actual creation with API keys
- let result = execute_alpha_arena_action("create_competition", config, Some(final_api_keys)).await;
+ let result = execute_alpha_arena_action(&app, "create_competition", config, Some(final_api_keys)).await;
match &result {
Ok(value) => {
@@ -339,7 +217,7 @@ pub async fn run_alpha_cycle(app: AppHandle, competition_id: Option<String>) ->
emit_progress(&app, "step", 3, 4, "Executing trading decisions...", None);
- let result = execute_alpha_arena_action("run_cycle", params, None).await;
+ let result = execute_alpha_arena_action(&app, "run_cycle", params, None).await;
match &result {
Ok(value) => {
@@ -362,37 +240,23 @@ pub async fn run_alpha_cycle(app: AppHandle, competition_id: Option<String>) ->
/// Get competition leaderboard
#[command]
-pub async fn get_alpha_leaderboard(competition_id: String) -> Result<Value, String> {
- eprintln!("[Alpha Arena v2] ========================================");
+pub async fn get_alpha_leaderboard(app: AppHandle, competition_id: String) -> Result<Value, String> {
eprintln!("[Alpha Arena v2] get_alpha_leaderboard called for: {}", competition_id);
let params = json!({
"competition_id": competition_id
});
- let result = execute_alpha_arena_action("get_leaderboard", params, None).await;
-
- match &result {
- Ok(value) => {
- eprintln!("[Alpha Arena v2] get_alpha_leaderboard SUCCESS");
- eprintln!("[Alpha Arena v2] Leaderboard response: {}", serde_json::to_string_pretty(value).unwrap_or_default());
- }
- Err(e) => {
- eprintln!("[Alpha Arena v2] get_alpha_leaderboard ERROR: {}", e);
- }
- }
- eprintln!("[Alpha Arena v2] ========================================");
-
- result
+ execute_alpha_arena_action(&app, "get_leaderboard", params, None).await
}
/// Get model trading decisions
#[command]
pub async fn get_alpha_model_decisions(
+ app: AppHandle,
competition_id: String,
model_name: Option<String>
) -> Result<Value, String> {
- eprintln!("[Alpha Arena v2] ========================================");
eprintln!("[Alpha Arena v2] get_alpha_model_decisions called for: {} (model: {:?})", competition_id, model_name);
let params = json!({
@@ -400,83 +264,57 @@ pub async fn get_alpha_model_decisions(
"model_name": model_name
});
- let result = execute_alpha_arena_action("get_decisions", params, None).await;
-
- match &result {
- Ok(value) => {
- eprintln!("[Alpha Arena v2] get_alpha_model_decisions SUCCESS");
- eprintln!("[Alpha Arena v2] Decisions response: {}", serde_json::to_string_pretty(value).unwrap_or_default());
- }
- Err(e) => {
- eprintln!("[Alpha Arena v2] get_alpha_model_decisions ERROR: {}", e);
- }
- }
- eprintln!("[Alpha Arena v2] ========================================");
-
- result
+ execute_alpha_arena_action(&app, "get_decisions", params, None).await
}
/// Get performance snapshots for charts
#[command]
-pub async fn get_alpha_snapshots(competition_id: String) -> Result<Value, String> {
- eprintln!("[Alpha Arena v2] ========================================");
+pub async fn get_alpha_snapshots(app: AppHandle, competition_id: String) -> Result<Value, String> {
eprintln!("[Alpha Arena v2] get_alpha_snapshots called for: {}", competition_id);
let params = json!({
"competition_id": competition_id
});
- let result = execute_alpha_arena_action("get_snapshots", params, None).await;
-
- match &result {
- Ok(value) => {
- eprintln!("[Alpha Arena v2] get_alpha_snapshots SUCCESS");
- eprintln!("[Alpha Arena v2] Snapshots response: {}", serde_json::to_string_pretty(value).unwrap_or_default());
- }
- Err(e) => {
- eprintln!("[Alpha Arena v2] get_alpha_snapshots ERROR: {}", e);
- }
- }
- eprintln!("[Alpha Arena v2] ========================================");
-
- result
+ execute_alpha_arena_action(&app, "get_snapshots", params, None).await
}
/// Start auto-run for competition
#[command]
-pub async fn start_alpha_competition(competition_id: Option<String>) -> Result<Value, String> {
+pub async fn start_alpha_competition(app: AppHandle, competition_id: Option<String>) -> Result<Value, String> {
eprintln!("[Alpha Arena v2] start_alpha_competition called");
let params = json!({
"competition_id": competition_id
});
- execute_alpha_arena_action("start_competition", params, None).await
+ execute_alpha_arena_action(&app, "start_competition", params, None).await
}
/// Stop competition
#[command]
-pub async fn stop_alpha_competition(competition_id: String) -> Result<Value, String> {
+pub async fn stop_alpha_competition(app: AppHandle, competition_id: String) -> Result<Value, String> {
eprintln!("[Alpha Arena v2] stop_alpha_competition called");
let params = json!({
"competition_id": competition_id
});
- execute_alpha_arena_action("stop_competition", params, None).await
+ execute_alpha_arena_action(&app, "stop_competition", params, None).await
}
/// List available trading agents
#[command]
-pub async fn list_alpha_agents() -> Result<Value, String> {
+pub async fn list_alpha_agents(app: AppHandle) -> Result<Value, String> {
eprintln!("[Alpha Arena v2] list_alpha_agents called");
- execute_alpha_arena_action("list_agents", json!({}), None).await
+ execute_alpha_arena_action(&app, "list_agents", json!({}), None).await
}
/// Get evaluation metrics for a model
#[command]
pub async fn get_alpha_evaluation(
+ app: AppHandle,
competition_id: String,
model_name: String
) -> Result<Value, String> {
@@ -487,7 +325,7 @@ pub async fn get_alpha_evaluation(
"model_name": model_name
});
- execute_alpha_arena_action("get_evaluation", params, None).await
+ execute_alpha_arena_action(&app, "get_evaluation", params, None).await
}
/// Get stored API keys (masked for display)
@@ -496,7 +334,6 @@ pub async fn get_alpha_api_keys() -> Result<Value, String> {
eprintln!("[Alpha Arena v2] get_alpha_api_keys called");
// Return masked keys from environment or storage
- // In production, load from secure storage
let providers = vec!["openai", "anthropic", "google", "deepseek", "groq"];
let mut keys: HashMap<String, String> = HashMap::new();
@@ -526,8 +363,7 @@ pub async fn get_alpha_api_keys() -> Result<Value, String> {
pub async fn save_alpha_api_keys(keys: HashMap<String, String>) -> Result<Value, String> {
eprintln!("[Alpha Arena v2] save_alpha_api_keys called");
- // In production, save to secure storage
- // For now, we'll set environment variables for the current session
+ // Set environment variables for the current session
for (provider, key) in &keys {
let env_var = format!("{}_API_KEY", provider.to_uppercase());
std::env::set_var(&env_var, key);
@@ -541,38 +377,38 @@ pub async fn save_alpha_api_keys(keys: HashMap<String, String>) -> Result<Value,
/// List all competitions from the database
#[command]
-pub async fn list_alpha_competitions(limit: Option<u32>) -> Result<Value, String> {
+pub async fn list_alpha_competitions(app: AppHandle, limit: Option<u32>) -> Result<Value, String> {
eprintln!("[Alpha Arena v2] list_alpha_competitions called");
let params = json!({
"limit": limit.unwrap_or(50)
});
- execute_alpha_arena_action("list_competitions", params, None).await
+ execute_alpha_arena_action(&app, "list_competitions", params, None).await
}
/// Get a specific competition by ID
#[command]
-pub async fn get_alpha_competition(competition_id: String) -> Result<Value, String> {
+pub async fn get_alpha_competition(app: AppHandle, competition_id: String) -> Result<Value, String> {
eprintln!("[Alpha Arena v2] get_alpha_competition called");
let params = json!({
"competition_id": competition_id
});
- execute_alpha_arena_action("get_competition", params, None).await
+ execute_alpha_arena_action(&app, "get_competition", params, None).await
}
/// Delete a competition
#[command]
-pub async fn delete_alpha_competition(competition_id: String) -> Result<Value, String> {
+pub async fn delete_alpha_competition(app: AppHandle, competition_id: String) -> Result<Value, String> {
eprintln!("[Alpha Arena v2] delete_alpha_competition called");
let params = json!({
"competition_id": competition_id
});
- execute_alpha_arena_action("delete_competition", params, None).await
+ execute_alpha_arena_action(&app, "delete_competition", params, None).await
}
// ============================================================================
@@ -582,6 +418,7 @@ pub async fn delete_alpha_competition(competition_id: String) -> Result<Value, S
/// Check if a decision requires approval
#[command]
pub async fn check_alpha_approval(
+ app: AppHandle,
decision: Value,
context: Value
) -> Result<Value, String> {
@@ -592,12 +429,13 @@ pub async fn check_alpha_approval(
"context": context
});
- execute_alpha_arena_action("check_approval", params, None).await
+ execute_alpha_arena_action(&app, "check_approval", params, None).await
}
/// Approve a pending decision
#[command]
pub async fn approve_alpha_decision(
+ app: AppHandle,
request_id: String,
approved_by: Option<String>,
notes: Option<String>
@@ -610,12 +448,13 @@ pub async fn approve_alpha_decision(
"notes": notes.unwrap_or_default()
});
- execute_alpha_arena_action("approve_decision", params, None).await
+ execute_alpha_arena_action(&app, "approve_decision", params, None).await
}
/// Reject a pending decision
#[command]
pub async fn reject_alpha_decision(
+ app: AppHandle,
request_id: String,
rejected_by: Option<String>,
notes: Option<String>
@@ -628,28 +467,29 @@ pub async fn reject_alpha_decision(
"notes": notes.unwrap_or_default()
});
- execute_alpha_arena_action("reject_decision", params, None).await
+ execute_alpha_arena_action(&app, "reject_decision", params, None).await
}
/// Get all pending approval requests
#[command]
-pub async fn get_alpha_pending_approvals() -> Result<Value, String> {
+pub async fn get_alpha_pending_approvals(app: AppHandle) -> Result<Value, String> {
eprintln!("[Alpha Arena HITL] get_alpha_pending_approvals called");
- execute_alpha_arena_action("get_pending_approvals", json!({}), None).await
+ execute_alpha_arena_action(&app, "get_pending_approvals", json!({}), None).await
}
/// Get HITL manager status and rules
#[command]
-pub async fn get_alpha_hitl_status() -> Result<Value, String> {
+pub async fn get_alpha_hitl_status(app: AppHandle) -> Result<Value, String> {
eprintln!("[Alpha Arena HITL] get_alpha_hitl_status called");
- execute_alpha_arena_action("get_hitl_status", json!({}), None).await
+ execute_alpha_arena_action(&app, "get_hitl_status", json!({}), None).await
}
/// Update HITL rule settings
#[command]
pub async fn update_alpha_hitl_rule(
+ app: AppHandle,
rule_name: String,
enabled: bool
) -> Result<Value, String> {
@@ -660,7 +500,7 @@ pub async fn update_alpha_hitl_rule(
"enabled": enabled
});
- execute_alpha_arena_action("update_hitl_rule", params, None).await
+ execute_alpha_arena_action(&app, "update_hitl_rule", params, None).await
}
// ============================================================================
@@ -670,6 +510,7 @@ pub async fn update_alpha_hitl_rule(
/// Get portfolio metrics (Sharpe ratio, drawdown, etc.)
#[command]
pub async fn get_alpha_portfolio_metrics(
+ app: AppHandle,
competition_id: String,
model_name: String
) -> Result<Value, String> {
@@ -680,12 +521,13 @@ pub async fn get_alpha_portfolio_metrics(
"model_name": model_name
});
- execute_alpha_arena_action("get_portfolio_metrics", params, None).await
+ execute_alpha_arena_action(&app, "get_portfolio_metrics", params, None).await
}
/// Get equity curve data for charting
#[command]
pub async fn get_alpha_equity_curve(
+ app: AppHandle,
competition_id: String,
model_name: String
) -> Result<Value, String> {
@@ -696,7 +538,7 @@ pub async fn get_alpha_equity_curve(
"model_name": model_name
});
- execute_alpha_arena_action("get_equity_curve", params, None).await
+ execute_alpha_arena_action(&app, "get_equity_curve", params, None).await
}
// ============================================================================
@@ -706,6 +548,7 @@ pub async fn get_alpha_equity_curve(
/// Create a grid strategy agent
#[command]
pub async fn create_alpha_grid_agent(
+ app: AppHandle,
name: String,
upper_price: f64,
lower_price: f64,
@@ -724,19 +567,19 @@ pub async fn create_alpha_grid_agent(
"total_investment": total_investment.unwrap_or(10000.0)
});
- execute_alpha_arena_action("create_grid_agent", params, None).await
+ execute_alpha_arena_action(&app, "create_grid_agent", params, None).await
}
/// Get grid agent status
#[command]
-pub async fn get_alpha_grid_status(agent_name: String) -> Result<Value, String> {
+pub async fn get_alpha_grid_status(app: AppHandle, agent_name: String) -> Result<Value, String> {
eprintln!("[Alpha Arena Grid] get_alpha_grid_status called: {}", agent_name);
let params = json!({
"agent_name": agent_name
});
- execute_alpha_arena_action("get_grid_status", params, None).await
+ execute_alpha_arena_action(&app, "get_grid_status", params, None).await
}
// ============================================================================
@@ -745,19 +588,20 @@ pub async fn get_alpha_grid_status(agent_name: String) -> Result<Value, String>
/// Get research report for a ticker
#[command]
-pub async fn get_alpha_research(ticker: String) -> Result<Value, String> {
+pub async fn get_alpha_research(app: AppHandle, ticker: String) -> Result<Value, String> {
eprintln!("[Alpha Arena Research] get_alpha_research called: {}", ticker);
let params = json!({
"ticker": ticker
});
- execute_alpha_arena_action("get_research", params, None).await
+ execute_alpha_arena_action(&app, "get_research", params, None).await
}
/// Get SEC filings for a ticker
#[command]
pub async fn get_alpha_sec_filings(
+ app: AppHandle,
ticker: String,
form_types: Option<Vec<String>>,
limit: Option<u32>
@@ -770,7 +614,7 @@ pub async fn get_alpha_sec_filings(
"limit": limit.unwrap_or(10)
});
- execute_alpha_arena_action("get_sec_filings", params, None).await
+ execute_alpha_arena_action(&app, "get_sec_filings", params, None).await
}
// ============================================================================
@@ -780,6 +624,7 @@ pub async fn get_alpha_sec_filings(
/// Get technical features for a symbol
#[command]
pub async fn get_alpha_features(
+ app: AppHandle,
symbol: String,
price: f64
) -> Result<Value, String> {
@@ -790,7 +635,7 @@ pub async fn get_alpha_features(
"price": price
});
- execute_alpha_arena_action("get_features", params, None).await
+ execute_alpha_arena_action(&app, "get_features", params, None).await
}
// ============================================================================
@@ -800,6 +645,7 @@ pub async fn get_alpha_features(
/// List all supported brokers
#[command]
pub async fn list_alpha_brokers(
+ app: AppHandle,
broker_type: Option<String>,
region: Option<String>
) -> Result<Value, String> {
@@ -810,24 +656,25 @@ pub async fn list_alpha_brokers(
"region": region
});
- execute_alpha_arena_action("list_brokers", params, None).await
+ execute_alpha_arena_action(&app, "list_brokers", params, None).await
}
/// Get broker details by ID
#[command]
-pub async fn get_alpha_broker(broker_id: String) -> Result<Value, String> {
+pub async fn get_alpha_broker(app: AppHandle, broker_id: String) -> Result<Value, String> {
eprintln!("[Alpha Arena Brokers] get_alpha_broker called: {}", broker_id);
let params = json!({
"broker_id": broker_id
});
- execute_alpha_arena_action("get_broker", params, None).await
+ execute_alpha_arena_action(&app, "get_broker", params, None).await
}
/// Get ticker data from specific broker
#[command]
pub async fn get_alpha_broker_ticker(
+ app: AppHandle,
symbol: String,
broker_id: Option<String>
) -> Result<Value, String> {
@@ -838,7 +685,7 @@ pub async fn get_alpha_broker_ticker(
"broker_id": broker_id.unwrap_or_else(|| "kraken".to_string())
});
- execute_alpha_arena_action("get_broker_ticker", params, None).await
+ execute_alpha_arena_action(&app, "get_broker_ticker", params, None).await
}
// ============================================================================
@@ -848,6 +695,7 @@ pub async fn get_alpha_broker_ticker(
/// Get sentiment analysis for a symbol
#[command]
pub async fn get_alpha_sentiment(
+ app: AppHandle,
symbol: String,
max_articles: Option<u32>
) -> Result<Value, String> {
@@ -858,12 +706,13 @@ pub async fn get_alpha_sentiment(
"max_articles": max_articles.unwrap_or(15)
});
- execute_alpha_arena_action("get_sentiment", params, None).await
+ execute_alpha_arena_action(&app, "get_sentiment", params, None).await
}
/// Get overall market mood from multiple symbols
#[command]
pub async fn get_alpha_market_mood(
+ app: AppHandle,
symbols: Option<Vec<String>>
) -> Result<Value, String> {
eprintln!("[Alpha Arena Sentiment] get_alpha_market_mood called");
@@ -872,7 +721,7 @@ pub async fn get_alpha_market_mood(
"symbols": symbols.unwrap_or_else(|| vec!["SPY".to_string(), "QQQ".to_string(), "BTC".to_string()])
});
- execute_alpha_arena_action("get_market_mood", params, None).await
+ execute_alpha_arena_action(&app, "get_market_mood", params, None).await
}
// ============================================================================
@@ -881,15 +730,16 @@ pub async fn get_alpha_market_mood(
/// List all available trading styles
#[command]
-pub async fn list_alpha_trading_styles() -> Result<Value, String> {
+pub async fn list_alpha_trading_styles(app: AppHandle) -> Result<Value, String> {
eprintln!("[Alpha Arena Styles] list_alpha_trading_styles called");
- execute_alpha_arena_action("list_trading_styles", json!({}), None).await
+ execute_alpha_arena_action(&app, "list_trading_styles", json!({}), None).await
}
/// Create multiple agents with different trading styles using the same provider
#[command]
pub async fn create_alpha_styled_agents(
+ app: AppHandle,
provider: String,
model_id: String,
styles: Option<Vec<String>>,
@@ -904,17 +754,17 @@ pub async fn create_alpha_styled_agents(
"initial_capital": initial_capital.unwrap_or(10000.0)
});
- execute_alpha_arena_action("create_styled_agents", params, None).await
+ execute_alpha_arena_action(&app, "create_styled_agents", params, None).await
}
/// Generic action executor - allows calling any Alpha Arena action dynamically
-/// This is useful for new features that don't have dedicated commands yet
#[command]
pub async fn run_alpha_action(
+ app: AppHandle,
action: String,
params: Value
) -> Result<Value, String> {
eprintln!("[Alpha Arena Generic] run_alpha_action called: {}", action);
- execute_alpha_arena_action(&action, params, None).await
+ execute_alpha_arena_action(&app, &action, params, None).await
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_bridge.rs b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_bridge.rs
index cadb54e8f..6c5826ad4 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_bridge.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_bridge.rs
@@ -34,24 +34,24 @@ pub async fn paper_trading_create_portfolio(
fee_rate: f64,
) -> Result<serde_json::Value, String> {
paper_trading::create_portfolio(&name, initial_balance, &currency, leverage, &margin_mode, fee_rate)
- .map(|p| serde_json::to_value(p).unwrap())
.map_err(|e| e.to_string())
+ .and_then(|p| serde_json::to_value(p).map_err(|e| format!("Serialization error: {}", e)))
}
/// Get paper trading portfolio
#[command]
pub async fn paper_trading_get_portfolio(id: String) -> Result<serde_json::Value, String> {
paper_trading::get_portfolio(&id)
- .map(|p| serde_json::to_value(p).unwrap())
.map_err(|e| e.to_string())
+ .and_then(|p| serde_json::to_value(p).map_err(|e| format!("Serialization error: {}", e)))
}
/// Get positions for portfolio
#[command]
pub async fn paper_trading_get_positions(portfolio_id: String) -> Result<serde_json::Value, String> {
paper_trading::get_positions(&portfolio_id)
- .map(|p| serde_json::to_value(p).unwrap())
.map_err(|e| e.to_string())
+ .and_then(|p| serde_json::to_value(p).map_err(|e| format!("Serialization error: {}", e)))
}
/// Place order
@@ -65,8 +65,8 @@ pub async fn paper_trading_place_order(
price: Option<f64>,
) -> Result<serde_json::Value, String> {
paper_trading::place_order(&portfolio_id, &symbol, &side, &order_type, quantity, price, None, false)
- .map(|o| serde_json::to_value(o).unwrap())
.map_err(|e| e.to_string())
+ .and_then(|o| serde_json::to_value(o).map_err(|e| format!("Serialization error: {}", e)))
}
/// Fill order at price
@@ -76,8 +76,8 @@ pub async fn paper_trading_fill_order(
fill_price: f64,
) -> Result<serde_json::Value, String> {
paper_trading::fill_order(&order_id, fill_price, None)
- .map(|t| serde_json::to_value(t).unwrap())
.map_err(|e| e.to_string())
+ .and_then(|t| serde_json::to_value(t).map_err(|e| format!("Serialization error: {}", e)))
}
/// Get portfolio orders
@@ -87,8 +87,8 @@ pub async fn paper_trading_get_orders(
status: Option<String>,
) -> Result<serde_json::Value, String> {
paper_trading::get_orders(&portfolio_id, status.as_deref())
- .map(|o| serde_json::to_value(o).unwrap())
.map_err(|e| e.to_string())
+ .and_then(|o| serde_json::to_value(o).map_err(|e| format!("Serialization error: {}", e)))
}
/// Get portfolio trades
@@ -98,8 +98,8 @@ pub async fn paper_trading_get_trades(
limit: Option<i64>,
) -> Result<serde_json::Value, String> {
paper_trading::get_trades(&portfolio_id, limit.unwrap_or(100))
- .map(|t| serde_json::to_value(t).unwrap())
.map_err(|e| e.to_string())
+ .and_then(|t| serde_json::to_value(t).map_err(|e| format!("Serialization error: {}", e)))
}
/// Record Alpha Arena decision (stores in SQLite for UI display)
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_v2.rs b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_v2.rs
index 204c6e183..023de5287 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_v2.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_v2.rs
@@ -1,9 +1,20 @@
//! Alpha Arena V2 Commands
//!
//! Tauri commands for the refactored Alpha Arena system.
+//! Refactored to use unified python module API.
-use std::process::Command;
use tauri::AppHandle;
+use crate::python;
+
+/// Extract JSON from output that may contain log lines
+fn extract_json(output: &str) -> Option<String> {
+ if let Some(json_start) = output.find('{') {
+ if let Some(json_end) = output.rfind('}') {
+ return Some(output[json_start..=json_end].to_string());
+ }
+ }
+ None
+}
/// Execute an Alpha Arena action
///
@@ -16,44 +27,12 @@ pub async fn alpha_arena_action(
app: AppHandle,
payload: String,
) -> Result<String, String> {
- // Get the Python executable path
- let python_path = get_python_path(&app)?;
-
- // Get the script path
- let script_path = get_script_path(&app)?;
-
- // Execute Python script
- let output = Command::new(&python_path)
- .arg(&script_path)
- .arg(&payload)
- .current_dir(script_path.parent().unwrap_or(&script_path))
- .output()
- .map_err(|e| format!("Failed to execute Python script: {}", e))?;
-
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- // Try to extract JSON error from stderr
- if let Some(json_start) = stderr.find('{') {
- if let Some(json_end) = stderr.rfind('}') {
- return Ok(stderr[json_start..=json_end].to_string());
- }
- }
- return Err(format!(
- "Python script failed: {}",
- stderr
- ));
- }
-
- let stdout = String::from_utf8_lossy(&output.stdout);
+ // Use the unified python module API
+ let output = python::execute_sync(&app, "alpha_arena/main.py", vec![payload])?;
// Find JSON in output
- if let Some(json_start) = stdout.find('{') {
- if let Some(json_end) = stdout.rfind('}') {
- return Ok(stdout[json_start..=json_end].to_string());
- }
- }
-
- Err("No JSON output from Python script".to_string())
+ extract_json(&output)
+ .ok_or_else(|| "No JSON output from Python script".to_string())
}
/// Get API keys from database
@@ -127,39 +106,3 @@ pub async fn save_api_keys(app: AppHandle, keys: String) -> Result<(), String> {
Ok(())
}
-
-// Helper functions
-fn get_python_path(app: &AppHandle) -> Result<std::path::PathBuf, String> {
- // Check for bundled Python first
- if let Ok(resource_dir) = app.path().resource_dir() {
- let bundled_python = if cfg!(windows) {
- resource_dir.join("python").join("python.exe")
- } else {
- resource_dir.join("python").join("bin").join("python3")
- };
-
- if bundled_python.exists() {
- return Ok(bundled_python);
- }
- }
-
- // Fall back to system Python
- let python_name = if cfg!(windows) { "python" } else { "python3" };
-
- Ok(std::path::PathBuf::from(python_name))
-}
-
-fn get_script_path(app: &AppHandle) -> Result<std::path::PathBuf, String> {
- if let Ok(resource_dir) = app.path().resource_dir() {
- let script = resource_dir
- .join("scripts")
- .join("alpha_arena")
- .join("main.py");
-
- if script.exists() {
- return Ok(script);
- }
- }
-
- Err("Alpha Arena script not found".to_string())
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/alphavantage.rs b/fincept-terminal-desktop/src-tauri/src/commands/alphavantage.rs
index 986e4c49f..541d20f2c 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/alphavantage.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/alphavantage.rs
@@ -1,8 +1,7 @@
// Alpha Vantage data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute Alpha Vantage Python script command with PyO3
#[tauri::command]
pub async fn execute_alphavantage_command(
app: tauri::AppHandle,
@@ -13,9 +12,7 @@ pub async fn execute_alphavantage_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "alphavantage_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "alphavantage_data.py", cmd_args).await
}
/// Get quote for a single symbol
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/analytics.rs
index 8ac8b8f4d..96e96e5d9 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/analytics.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/analytics.rs
@@ -1,9 +1,8 @@
// Analytics Module Commands - Portfolio optimization and technical analysis
#![allow(dead_code)]
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute Technical Indicators command with PyO3
#[tauri::command]
pub async fn execute_technical_indicators(
app: tauri::AppHandle,
@@ -13,12 +12,11 @@ pub async fn execute_technical_indicators(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Get script path and execute with PyO3
- let script_path = get_script_path(&app, "Analytics/technical_indicators.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "Analytics/technical_indicators.py", cmd_args).await
}
-/// Execute PyPortfolioOpt wrapper command with PyO3
+
#[tauri::command]
pub async fn execute_pyportfolioopt(
app: tauri::AppHandle,
@@ -27,11 +25,10 @@ pub async fn execute_pyportfolioopt(
) -> Result<String, String> {
let mut cmd_args = vec![command];
cmd_args.extend(args);
- let script_path = get_script_path(&app, "Analytics/pyportfolioopt_wrapper/core.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "Analytics/pyportfolioopt_wrapper/core.py", cmd_args).await
}
-/// Execute RiskFolio wrapper command with PyO3
+
#[tauri::command]
pub async fn execute_riskfolio(
app: tauri::AppHandle,
@@ -40,11 +37,10 @@ pub async fn execute_riskfolio(
) -> Result<String, String> {
let mut cmd_args = vec![command];
cmd_args.extend(args);
- let script_path = get_script_path(&app, "Analytics/riskfoliolib_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "Analytics/riskfoliolib_wrapper.py", cmd_args).await
}
-/// Execute Skfolio wrapper command with PyO3
+
#[tauri::command]
pub async fn execute_skfolio(
app: tauri::AppHandle,
@@ -53,8 +49,7 @@ pub async fn execute_skfolio(
) -> Result<String, String> {
let mut cmd_args = vec![command];
cmd_args.extend(args);
- let script_path = get_script_path(&app, "Analytics/skfolio_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "Analytics/skfolio_wrapper.py", cmd_args).await
}
// Module-specific commands for alternateInvestment
@@ -68,8 +63,7 @@ pub async fn analyze_digital_assets(
if let Some(at) = analysis_type {
args.push(at);
}
- let script_path = get_script_path(&app, "Analytics/alternateInvestment/digital_assets.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/alternateInvestment/digital_assets.py", args).await
}
#[tauri::command]
@@ -82,8 +76,7 @@ pub async fn analyze_hedge_funds(
if let Some(m) = metrics {
args.push(m);
}
- let script_path = get_script_path(&app, "Analytics/alternateInvestment/hedge_funds.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/alternateInvestment/hedge_funds.py", args).await
}
#[tauri::command]
@@ -96,8 +89,7 @@ pub async fn analyze_real_estate(
if let Some(vm) = valuation_method {
args.push(vm);
}
- let script_path = get_script_path(&app, "Analytics/alternateInvestment/real_estate.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/alternateInvestment/real_estate.py", args).await
}
#[tauri::command]
@@ -110,8 +102,7 @@ pub async fn analyze_private_capital(
if let Some(ap) = analysis_params {
args.push(ap);
}
- let script_path = get_script_path(&app, "Analytics/alternateInvestment/private_capital.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/alternateInvestment/private_capital.py", args).await
}
#[tauri::command]
@@ -124,8 +115,7 @@ pub async fn analyze_natural_resources(
if let Some(ct) = commodity_type {
args.push(ct);
}
- let script_path = get_script_path(&app, "Analytics/alternateInvestment/natural_resources.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/alternateInvestment/natural_resources.py", args).await
}
// Derivatives analytics commands
@@ -139,8 +129,7 @@ pub async fn price_options(
if let Some(pm) = pricing_model {
args.push(pm);
}
- let script_path = get_script_path(&app, "Analytics/derivatives/options.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/derivatives/options.py", args).await
}
#[tauri::command]
@@ -153,8 +142,7 @@ pub async fn analyze_arbitrage(
if let Some(at) = arbitrage_type {
args.push(at);
}
- let script_path = get_script_path(&app, "Analytics/derivatives/arbitrage.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/derivatives/arbitrage.py", args).await
}
#[tauri::command]
@@ -167,8 +155,7 @@ pub async fn analyze_forward_commitments(
if let Some(ct) = contract_type {
args.push(ct);
}
- let script_path = get_script_path(&app, "Analytics/derivatives/forward_commitments.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/derivatives/forward_commitments.py", args).await
}
// Economics analytics commands
@@ -182,8 +169,7 @@ pub async fn analyze_currency(
if let Some(at) = analysis_type {
args.push(at);
}
- let script_path = get_script_path(&app, "Analytics/economics/currency_analysis.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/economics/currency_analysis.py", args).await
}
#[tauri::command]
@@ -196,8 +182,7 @@ pub async fn analyze_growth(
if let Some(ind) = indicators {
args.push(ind);
}
- let script_path = get_script_path(&app, "Analytics/economics/growth_analysis.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/economics/growth_analysis.py", args).await
}
#[tauri::command]
@@ -210,8 +195,7 @@ pub async fn analyze_policy(
if let Some(pt) = policy_type {
args.push(pt);
}
- let script_path = get_script_path(&app, "Analytics/economics/policy_analysis.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/economics/policy_analysis.py", args).await
}
#[tauri::command]
@@ -224,8 +208,7 @@ pub async fn analyze_market_cycles(
if let Some(cp) = cycle_params {
args.push(cp);
}
- let script_path = get_script_path(&app, "Analytics/economics/market_cycles.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/economics/market_cycles.py", args).await
}
#[tauri::command]
@@ -238,8 +221,7 @@ pub async fn analyze_trade_geopolitics(
if let Some(r) = region {
args.push(r);
}
- let script_path = get_script_path(&app, "Analytics/economics/trade_geopolitics.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/economics/trade_geopolitics.py", args).await
}
#[tauri::command]
@@ -252,8 +234,7 @@ pub async fn analyze_capital_flows(
if let Some(ft) = flow_type {
args.push(ft);
}
- let script_path = get_script_path(&app, "Analytics/economics/capital_flows.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/economics/capital_flows.py", args).await
}
// Equity Investment analytics commands
@@ -267,8 +248,7 @@ pub async fn calculate_dcf_valuation(
if let Some(dp) = dcf_params {
args.push(dp);
}
- let script_path = get_script_path(&app, "Analytics/equityInvestment/equity_valuation/dcf_models.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/equityInvestment/equity_valuation/dcf_models.py", args).await
}
#[tauri::command]
@@ -281,8 +261,7 @@ pub async fn calculate_dividend_valuation(
if let Some(mt) = model_type {
args.push(mt);
}
- let script_path = get_script_path(&app, "Analytics/equityInvestment/equity_valuation/dividend_models.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/equityInvestment/equity_valuation/dividend_models.py", args).await
}
#[tauri::command]
@@ -295,8 +274,7 @@ pub async fn calculate_multiples_valuation(
if let Some(m) = multiples {
args.push(m);
}
- let script_path = get_script_path(&app, "Analytics/equityInvestment/equity_valuation/multiples_valuation.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/equityInvestment/equity_valuation/multiples_valuation.py", args).await
}
#[tauri::command]
@@ -309,8 +287,7 @@ pub async fn analyze_fundamental(
if let Some(at) = analysis_type {
args.push(at);
}
- let script_path = get_script_path(&app, "Analytics/equityInvestment/company_analysis/fundamental_analysis.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/equityInvestment/company_analysis/fundamental_analysis.py", args).await
}
#[tauri::command]
@@ -323,8 +300,7 @@ pub async fn analyze_industry(
if let Some(ic) = industry_code {
args.push(ic);
}
- let script_path = get_script_path(&app, "Analytics/equityInvestment/company_analysis/industry_analysis.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/equityInvestment/company_analysis/industry_analysis.py", args).await
}
#[tauri::command]
@@ -337,8 +313,7 @@ pub async fn forecast_financials(
if let Some(fp) = forecast_params {
args.push(fp);
}
- let script_path = get_script_path(&app, "Analytics/equityInvestment/company_analysis/forecasting.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/equityInvestment/company_analysis/forecasting.py", args).await
}
#[tauri::command]
@@ -351,8 +326,7 @@ pub async fn analyze_market_efficiency(
if let Some(et) = efficiency_tests {
args.push(et);
}
- let script_path = get_script_path(&app, "Analytics/equityInvestment/market_analysis/market_efficiency.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/equityInvestment/market_analysis/market_efficiency.py", args).await
}
#[tauri::command]
@@ -365,8 +339,7 @@ pub async fn analyze_index(
if let Some(it) = index_type {
args.push(it);
}
- let script_path = get_script_path(&app, "Analytics/equityInvestment/market_analysis/index_analysis.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/equityInvestment/market_analysis/index_analysis.py", args).await
}
// Portfolio Management analytics commands
@@ -380,8 +353,7 @@ pub async fn analyze_portfolio_risk(
if let Some(rm) = risk_measures {
args.push(rm);
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/risk_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/risk_management.py", args).await
}
#[tauri::command]
@@ -394,8 +366,7 @@ pub async fn analyze_portfolio_performance(
if let Some(b) = benchmark {
args.push(b);
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_analytics.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_analytics.py", args).await
}
#[tauri::command]
@@ -408,8 +379,7 @@ pub async fn optimize_portfolio_management(
if let Some(om) = optimization_method {
args.push(om);
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_management.py", args).await
}
#[tauri::command]
@@ -422,8 +392,7 @@ pub async fn plan_portfolio(
if let Some(pp) = planning_params {
args.push(pp);
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_planning.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_planning.py", args).await
}
#[tauri::command]
@@ -436,8 +405,7 @@ pub async fn analyze_active_management(
if let Some(st) = strategy_type {
args.push(st);
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/active_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/active_management.py", args).await
}
#[tauri::command]
@@ -450,8 +418,7 @@ pub async fn analyze_behavioral_finance(
if let Some(ba) = bias_analysis {
args.push(ba);
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/behavioral_finance.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/behavioral_finance.py", args).await
}
#[tauri::command]
@@ -464,8 +431,7 @@ pub async fn analyze_etf(
if let Some(ap) = analysis_params {
args.push(ap);
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/etf_analytics.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/etf_analytics.py", args).await
}
// Quantitative analytics commands
@@ -479,8 +445,7 @@ pub async fn calculate_quant_metrics(
if let Some(m) = metrics {
args.push(m);
}
- let script_path = get_script_path(&app, "Analytics/quant/quant_modules_3042.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/quant/quant_modules_3042.py", args).await
}
#[tauri::command]
@@ -493,8 +458,7 @@ pub async fn calculate_rates(
if let Some(ct) = calculation_type {
args.push(ct);
}
- let script_path = get_script_path(&app, "Analytics/quant/rate_calculations.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/quant/rate_calculations.py", args).await
}
#[tauri::command]
@@ -511,8 +475,7 @@ pub async fn execute_economics_analytics(
if let Some(c) = config {
args.push(c);
}
- let script_path = get_script_path(&app, "Analytics/economics_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/economics_wrapper.py", args).await
}
#[tauri::command]
@@ -525,12 +488,7 @@ pub async fn execute_statsmodels_analytics(
if let Some(p) = params {
args.push(p);
}
- crate::utils::python::execute_python_subprocess(
- &app,
- "Analytics/statsmodels_cli.py",
- &args,
- Some("statsmodels")
- )
+ python::execute(&app, "Analytics/statsmodels_cli.py", args).await
}
#[tauri::command]
@@ -543,10 +501,5 @@ pub async fn execute_quant_analytics(
if let Some(p) = params {
args.push(p);
}
- crate::utils::python::execute_python_subprocess(
- &app,
- "Analytics/quant_analytics_cli.py",
- &args,
- Some("quant_analytics")
- )
+ python::execute(&app, "Analytics/quant_analytics_cli.py", args).await
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs b/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs
index c85272106..0b6ba09de 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs
@@ -7,11 +7,7 @@
use serde::{Deserialize, Serialize};
use std::process::Command;
-use crate::utils::python;
-
-// Windows-specific imports to hide console windows
-#[cfg(target_os = "windows")]
-use std::os::windows::process::CommandExt;
+use crate::python;
// ============================================================================
// Types
@@ -77,18 +73,23 @@ pub async fn execute_command(command: String) -> Result<CommandResult, String> {
}
}
- // Execute
- let output = Command::new(program)
- .args(args)
- .output()
- .map_err(|e| format!("Failed to execute command: {}", e))?;
-
- Ok(CommandResult {
- success: output.status.success(),
- stdout: String::from_utf8_lossy(&output.stdout).to_string(),
- stderr: String::from_utf8_lossy(&output.stderr).to_string(),
- exit_code: output.status.code().unwrap_or(-1),
- })
+ // Execute in blocking thread to avoid blocking the async runtime
+ let program = program.to_string();
+ let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
+
+ tokio::task::spawn_blocking(move || {
+ let output = Command::new(&program)
+ .args(&args)
+ .output()
+ .map_err(|e| format!("Failed to execute command: {}", e))?;
+
+ Ok(CommandResult {
+ success: output.status.success(),
+ stdout: String::from_utf8_lossy(&output.stdout).to_string(),
+ stderr: String::from_utf8_lossy(&output.stderr).to_string(),
+ exit_code: output.status.code().unwrap_or(-1),
+ })
+ }).await.map_err(|e| format!("Task join error: {}", e))?
}
// Removed kill_lean_process - Lean support discontinued
@@ -106,45 +107,20 @@ pub async fn execute_python_backtest(
args: String,
app: tauri::AppHandle,
) -> Result<String, String> {
- // Use library-specific Python path (switches between numpy1/numpy2 venvs)
- let python_path = python::get_python_path_for_library(&app, Some(&provider))?;
-
- // Build script path - handle both dev and production
- let script_relative_path = format!(
+ // Build script name - handle both dev and production
+ let script_name = format!(
"Analytics/backtesting/{}/{}",
provider.to_lowercase(),
format!("{}_provider.py", provider.to_lowercase())
);
- // Use the central get_script_path utility which handles path resolution
- let script_path = python::get_script_path(&app, &script_relative_path)?;
-
- // Execute Python script
- let mut cmd = Command::new(&python_path);
-
- #[cfg(target_os = "windows")]
- cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
-
- let output = cmd
- .arg(&script_path)
- .arg(&command)
- .arg(&args)
- .output()
- .map_err(|e| format!("Failed to execute Python script: {}", e))?;
-
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- let stdout = String::from_utf8_lossy(&output.stdout);
- // Python providers print JSON errors to stdout then exit(1)
- // Include both stdout and stderr for full error context
- if !stdout.is_empty() {
- return Err(format!("Python script failed: {}", stdout.trim()));
- }
- return Err(format!("Python script failed: {}", stderr));
- }
+ // Build arguments for Python script
+ let script_args = vec![command, args];
+
+ // Execute Python script using new API
+ let output = python::execute(&app, &script_name, script_args).await?;
- let stdout = String::from_utf8_lossy(&output.stdout).to_string();
- Ok(stdout)
+ Ok(output)
}
/**
@@ -265,5 +241,5 @@ pub async fn read_file(path: String) -> Result<String, String> {
// Helper Functions
// ============================================================================
-// Note: get_python_path() has been removed - now using crate::utils::python::get_python_path()
+// Note: get_python_path() has been removed - now using crate::python::get_python_path()
// which properly handles dev vs production mode with #[cfg(debug_assertions)]
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/bea.rs b/fincept-terminal-desktop/src-tauri/src/commands/bea.rs
index c98828215..75d66220f 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/bea.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/bea.rs
@@ -1,21 +1,21 @@
-use crate::utils::python::execute_python_script_simple;
+use crate::python;
use tauri::command;
// ==================== METADATA COMMANDS ====================
#[command]
pub async fn bea_get_dataset_list(app: tauri::AppHandle) -> Result<String, String> {
- execute_python_script_simple(&app, "bea_data.py", &["dataset_list"])
+ python::execute_sync(&app, "bea_data.py", vec!["dataset_list".to_string()])
}
#[command]
pub async fn bea_get_parameter_list(app: tauri::AppHandle, dataset_name: String) -> Result<String, String> {
- execute_python_script_simple(&app, "bea_data.py", &["parameter_list", &dataset_name])
+ python::execute_sync(&app, "bea_data.py", vec!["parameter_list".to_string(), dataset_name])
}
#[command]
pub async fn bea_get_parameter_values(app: tauri::AppHandle, dataset_name: String, parameter_name: String) -> Result<String, String> {
- execute_python_script_simple(&app, "bea_data.py", &["parameter_values", &dataset_name, &parameter_name])
+ python::execute_sync(&app, "bea_data.py", vec!["parameter_values".to_string(), dataset_name, parameter_name])
}
#[command]
@@ -25,7 +25,7 @@ pub async fn bea_get_parameter_values_filtered(
parameter_name: String,
target_parameter: String
) -> Result<String, String> {
- execute_python_script_simple(&app, "bea_data.py", &["parameter_values_filtered", &dataset_name, &parameter_name, &target_parameter])
+ python::execute_sync(&app, "bea_data.py", vec!["parameter_values_filtered".to_string(), dataset_name, parameter_name, target_parameter])
}
// ==================== DATA RETRIEVAL COMMANDS ====================
@@ -33,15 +33,13 @@ pub async fn bea_get_parameter_values_filtered(
#[command]
pub async fn bea_get_nipa_data(app: tauri::AppHandle, table_name: String, frequency: Option<String>, year: Option<String>) -> Result<String, String> {
let freq = frequency.unwrap_or_else(|| "A".to_string());
- let mut args = vec!["nipa", &table_name, &freq];
+ let mut args = vec!["nipa".to_string(), table_name, freq];
- let year_str;
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
#[command]
@@ -52,28 +50,24 @@ pub async fn bea_get_ni_underlying_detail(
year: Option<String>
) -> Result<String, String> {
let freq = frequency.unwrap_or_else(|| "A".to_string());
- let mut args = vec!["ni_underlying", &table_name, &freq];
+ let mut args = vec!["ni_underlying".to_string(), table_name, freq];
- let year_str;
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
#[command]
pub async fn bea_get_fixed_assets(app: tauri::AppHandle, table_name: String, year: Option<String>) -> Result<String, String> {
- let mut args = vec!["fixed_assets", &table_name];
+ let mut args = vec!["fixed_assets".to_string(), table_name];
- let year_str;
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
#[command]
@@ -92,43 +86,30 @@ pub async fn bea_get_mne_data(
let class = classification.unwrap_or_else(|| "Country".to_string());
let footnotes = get_footnotes.unwrap_or_else(|| "No".to_string());
- let mut args = vec!["mne", &direction, &class];
-
- let year_str;
- let country_str;
- let industry_str;
- let state_str;
- let ownership_str;
- let nonbank_str;
+ let mut args = vec!["mne".to_string(), direction, class];
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
if let Some(cnt) = country {
- country_str = cnt;
- args.push(&country_str);
+ args.push(cnt);
}
if let Some(ind) = industry {
- industry_str = ind;
- args.push(&industry_str);
+ args.push(ind);
}
if let Some(st) = state {
- state_str = st;
- args.push(&state_str);
+ args.push(st);
}
if let Some(ol) = ownership_level {
- ownership_str = ol;
- args.push(&ownership_str);
+ args.push(ol);
}
if let Some(nba) = nonbank_affiliates_only {
- nonbank_str = nba;
- args.push(&nonbank_str);
+ args.push(nba);
}
- args.push(&footnotes);
+ args.push(footnotes);
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
#[command]
@@ -142,18 +123,16 @@ pub async fn bea_get_gdp_by_industry(
let freq = frequency.unwrap_or_else(|| "A".to_string());
let ind = industry.unwrap_or_else(|| "ALL".to_string());
- let mut args = vec!["gdp_by_industry", &table_id];
+ let mut args = vec!["gdp_by_industry".to_string(), table_id];
- let year_str;
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- args.push(&freq);
- args.push(&ind);
+ args.push(freq);
+ args.push(ind);
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
#[command]
@@ -167,25 +146,20 @@ pub async fn bea_get_international_transactions(
let aoc = area_or_country.unwrap_or_else(|| "AllCountries".to_string());
let freq = frequency.unwrap_or_else(|| "A".to_string());
- let mut args = vec!["international_transactions"];
-
- let indicator_str;
- let year_str;
+ let mut args = vec!["international_transactions".to_string()];
if let Some(ind) = indicator {
- indicator_str = ind;
- args.push(&indicator_str);
+ args.push(ind);
}
- args.push(&aoc);
- args.push(&freq);
+ args.push(aoc);
+ args.push(freq);
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
#[command]
@@ -198,43 +172,34 @@ pub async fn bea_get_international_investment_position(
) -> Result<String, String> {
let freq = frequency.unwrap_or_else(|| "A".to_string());
- let mut args = vec!["international_investment"];
-
- let toi_str;
- let comp_str;
- let year_str;
+ let mut args = vec!["international_investment".to_string()];
if let Some(toi) = type_of_investment {
- toi_str = toi;
- args.push(&toi_str);
+ args.push(toi);
}
if let Some(comp) = component {
- comp_str = comp;
- args.push(&comp_str);
+ args.push(comp);
}
- args.push(&freq);
+ args.push(freq);
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
#[command]
pub async fn bea_get_input_output(app: tauri::AppHandle, table_id: String, year: Option<String>) -> Result<String, String> {
- let mut args = vec!["input_output", &table_id];
+ let mut args = vec!["input_output".to_string(), table_id];
- let year_str;
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
#[command]
@@ -248,18 +213,16 @@ pub async fn bea_get_underlying_gdp_by_industry(
let freq = frequency.unwrap_or_else(|| "A".to_string());
let ind = industry.unwrap_or_else(|| "ALL".to_string());
- let mut args = vec!["underlying_gdp_industry", &table_id];
+ let mut args = vec!["underlying_gdp_industry".to_string(), table_id];
- let year_str;
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- args.push(&freq);
- args.push(&ind);
+ args.push(freq);
+ args.push(ind);
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
#[command]
@@ -273,36 +236,27 @@ pub async fn bea_get_international_services_trade(
) -> Result<String, String> {
let aoc = area_or_country.unwrap_or_else(|| "AllCountries".to_string());
- let mut args = vec!["international_services"];
-
- let tos_str;
- let td_str;
- let aff_str;
- let year_str;
+ let mut args = vec!["international_services".to_string()];
if let Some(tos) = type_of_service {
- tos_str = tos;
- args.push(&tos_str);
+ args.push(tos);
}
if let Some(td) = trade_direction {
- td_str = td;
- args.push(&td_str);
+ args.push(td);
}
if let Some(aff) = affiliation {
- aff_str = aff;
- args.push(&aff_str);
+ args.push(aff);
}
- args.push(&aoc);
+ args.push(aoc);
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
#[command]
@@ -316,30 +270,26 @@ pub async fn bea_get_regional_data(
let lc = line_code.unwrap_or_else(|| "ALL".to_string());
let gf = geo_fips.unwrap_or_else(|| "STATE".to_string());
- let mut args = vec!["regional", &table_name, &lc, &gf];
+ let mut args = vec!["regional".to_string(), table_name, lc, gf];
- let year_str;
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
// ==================== COMPOSITE COMMANDS ====================
#[command]
pub async fn bea_get_economic_overview(app: tauri::AppHandle, year: Option<String>) -> Result<String, String> {
- let mut args = vec!["economic_overview"];
+ let mut args = vec!["economic_overview".to_string()];
- let year_str;
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
#[command]
@@ -350,13 +300,11 @@ pub async fn bea_get_regional_snapshot(
) -> Result<String, String> {
let gf = geo_fips.unwrap_or_else(|| "STATE".to_string());
- let mut args = vec!["regional_snapshot", &gf];
+ let mut args = vec!["regional_snapshot".to_string(), gf];
- let year_str;
if let Some(yr) = year {
- year_str = yr;
- args.push(&year_str);
+ args.push(yr);
}
- execute_python_script_simple(&app, "bea_data.py", &args)
+ python::execute_sync(&app, "bea_data.py", args)
}
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/bis.rs b/fincept-terminal-desktop/src-tauri/src/commands/bis.rs
index b7d315d66..9eb29022b 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/bis.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/bis.rs
@@ -1,8 +1,7 @@
// BIS (Bank for International Settlements) data commands based on SDMX API
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute BIS Python script command with PyO3
#[tauri::command]
pub async fn execute_bis_command(
app: tauri::AppHandle,
@@ -13,9 +12,7 @@ pub async fn execute_bis_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "bis_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "bis_data.py", cmd_args).await
}
// BASIC DATA QUERY COMMANDS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/bls.rs b/fincept-terminal-desktop/src-tauri/src/commands/bls.rs
index 66b53bdb0..f5e07e6aa 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/bls.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/bls.rs
@@ -1,8 +1,7 @@
// BLS (Bureau of Labor Statistics) data commands based on OpenBB bls provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute BLS Python script command with PyO3
#[tauri::command]
pub async fn execute_bls_command(
app: tauri::AppHandle,
@@ -13,9 +12,8 @@ pub async fn execute_bls_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "bls_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "bls_data.py", cmd_args).await
}
// SERIES DATA COMMANDS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/groww.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/groww.rs
index 98823ad1d..ab6a05d9a 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/groww.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/groww.rs
@@ -72,8 +72,10 @@ fn base32_decode(input: &str) -> Result<Vec<u8>, String> {
let mut bytes = Vec::new();
for chunk in bits.as_bytes().chunks(8) {
if chunk.len() == 8 {
- let byte_str = std::str::from_utf8(chunk).unwrap();
- let byte = u8::from_str_radix(byte_str, 2).unwrap();
+ let byte_str = std::str::from_utf8(chunk)
+ .map_err(|e| format!("Invalid UTF-8 in base32 decode: {}", e))?;
+ let byte = u8::from_str_radix(byte_str, 2)
+ .map_err(|e| format!("Invalid binary digit in base32 decode: {}", e))?;
bytes.push(byte);
}
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/canada_gov.rs b/fincept-terminal-desktop/src-tauri/src/commands/canada_gov.rs
index 5467f6c89..74aa05f84 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/canada_gov.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/canada_gov.rs
@@ -1,6 +1,5 @@
// Canadian Government data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Canada Government Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_canada_gov_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "canada_gov_api.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "canada_gov_api.py", cmd_args).await
}
/// Search Canadian government datasets
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/cboe.rs b/fincept-terminal-desktop/src-tauri/src/commands/cboe.rs
index 933856720..94076bf4d 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/cboe.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/cboe.rs
@@ -1,8 +1,7 @@
// CBOE (Chicago Board Options Exchange) data commands based on OpenBB cboe provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute CBOE Python script command with PyO3
#[tauri::command]
pub async fn execute_cboe_command(
app: tauri::AppHandle,
@@ -13,9 +12,8 @@ pub async fn execute_cboe_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "cboe_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "cboe_data.py", cmd_args).await
}
// EQUITY DATA COMMANDS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/cftc.rs b/fincept-terminal-desktop/src-tauri/src/commands/cftc.rs
index 30a86c24f..b831c28c4 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/cftc.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/cftc.rs
@@ -1,8 +1,7 @@
// CFTC (Commodity Futures Trading Commission) data commands based on OpenBB cftc provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute CFTC Python script command with PyO3
#[tauri::command]
pub async fn execute_cftc_command(
app: tauri::AppHandle,
@@ -13,9 +12,7 @@ pub async fn execute_cftc_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "cftc_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "cftc_data.py", cmd_args).await
}
// COT DATA COMMANDS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/ckan.rs b/fincept-terminal-desktop/src-tauri/src/commands/ckan.rs
index e696ecfd8..821856f34 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/ckan.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/ckan.rs
@@ -1,7 +1,6 @@
// Universal CKAN Data Portals API commands
#![allow(dead_code)]
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Universal CKAN Python script command
#[tauri::command]
@@ -13,8 +12,7 @@ pub async fn execute_ckan_command(
) -> Result<String, String> {
let mut cmd_args = vec!["--country".to_string(), country, "--action".to_string(), action];
cmd_args.extend(args);
- let script_path = get_script_path(&app, "universal_ckan_api.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "universal_ckan_api.py", cmd_args).await
}
/// Get list of supported countries and their portal information
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/coingecko.rs b/fincept-terminal-desktop/src-tauri/src/commands/coingecko.rs
index 791f14706..adba81b12 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/coingecko.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/coingecko.rs
@@ -1,8 +1,7 @@
// CoinGecko cryptocurrency data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute CoinGecko Python script command with PyO3
#[tauri::command]
pub async fn execute_coingecko_command(
app: tauri::AppHandle,
@@ -12,8 +11,7 @@ pub async fn execute_coingecko_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- let script_path = get_script_path(&app, "coingecko.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "coingecko.py", cmd_args).await
}
/// Get cryptocurrency price
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/company_news.rs b/fincept-terminal-desktop/src-tauri/src/commands/company_news.rs
index 97aa09b6a..b492a155b 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/company_news.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/company_news.rs
@@ -1,5 +1,4 @@
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
use tauri::AppHandle;
/// Fetch company news using GNews
@@ -82,18 +81,7 @@ pub async fn get_company_news_help(app: AppHandle) -> Result<String, String> {
/// Internal helper function to execute news commands
async fn execute_news_command(app: AppHandle, args: Vec<String>) -> Result<String, String> {
- let script_name = "fetch_company_news.py";
- let script_path = get_script_path(&app, script_name)
- .map_err(|e| format!("Failed to locate script: {}", e))?;
-
- if !script_path.exists() {
- return Err(format!(
- "Company news script not found at: {}",
- script_path.display()
- ));
- }
-
- match python_runtime::execute_python_script(&script_path, args) {
+ match python::execute(&app, "fetch_company_news.py", args).await {
Ok(output) => {
if output.contains("\"success\":false") || output.contains("\"error\"") {
return Err(output);
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/congress_gov.rs b/fincept-terminal-desktop/src-tauri/src/commands/congress_gov.rs
index f8b21eb40..70addcbc7 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/congress_gov.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/congress_gov.rs
@@ -1,6 +1,5 @@
// Congress.gov data commands based on OpenBB congress_gov provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Congress.gov Python script command
#[tauri::command]
@@ -13,9 +12,7 @@ pub async fn execute_congress_gov_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "congress_gov_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "congress_gov_data.py", cmd_args).await
}
/// Get Congressional bills with various filters
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/data_gov_hk.rs b/fincept-terminal-desktop/src-tauri/src/commands/data_gov_hk.rs
index 2900b0f13..f0e1a4d96 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/data_gov_hk.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/data_gov_hk.rs
@@ -1,6 +1,5 @@
// Hong Kong Government data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Hong Kong Government Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_data_gov_hk_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "data_gov_hk_api.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "data_gov_hk_api.py", cmd_args).await
}
/// Search Hong Kong government datasets
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/database.rs b/fincept-terminal-desktop/src-tauri/src/commands/database.rs
index 4bca412c8..c458f7c3e 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/database.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/database.rs
@@ -198,6 +198,22 @@ pub async fn db_delete_mcp_server(id: String) -> Result<String, String> {
Ok("MCP server deleted successfully".to_string())
}
+#[tauri::command]
+pub async fn db_get_internal_tool_settings() -> Result<Vec<InternalMCPToolSetting>, String> {
+ queries::get_internal_tool_settings().map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+pub async fn db_set_internal_tool_enabled(tool_name: String, category: String, is_enabled: bool) -> Result<String, String> {
+ queries::set_internal_tool_enabled(&tool_name, &category, is_enabled).map_err(|e| e.to_string())?;
+ Ok("Internal tool setting updated".to_string())
+}
+
+#[tauri::command]
+pub async fn db_is_internal_tool_enabled(tool_name: String) -> Result<bool, String> {
+ queries::is_internal_tool_enabled(&tool_name).map_err(|e| e.to_string())
+}
+
// ============================================================================
// Backtesting Commands
// ============================================================================
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/databento.rs b/fincept-terminal-desktop/src-tauri/src/commands/databento.rs
index 4ffea0d75..94f110dc2 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/databento.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/databento.rs
@@ -1,6 +1,5 @@
// Databento market data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Databento Python script command
#[tauri::command]
@@ -13,9 +12,7 @@ pub async fn execute_databento_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "explore_databento_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "explore_databento_data.py", cmd_args).await
}
/// Get market data
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/datagov_au.rs b/fincept-terminal-desktop/src-tauri/src/commands/datagov_au.rs
index 2862ac727..c9a352224 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/datagov_au.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/datagov_au.rs
@@ -1,6 +1,5 @@
// Australian Government data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Australian Government Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_datagov_au_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "datagov_au_api.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "datagov_au_api.py", cmd_args).await
}
/// Search Australian government datasets
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/datagovsg.rs b/fincept-terminal-desktop/src-tauri/src/commands/datagovsg.rs
index aac2106d6..9077a16e6 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/datagovsg.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/datagovsg.rs
@@ -1,6 +1,5 @@
// Singapore Government data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Singapore Government Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_datagovsg_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "datagovsg_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "datagovsg_data.py", cmd_args).await
}
/// Search Singapore government datasets
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/datagovuk.rs b/fincept-terminal-desktop/src-tauri/src/commands/datagovuk.rs
index e2dcf260d..883fa29d6 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/datagovuk.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/datagovuk.rs
@@ -1,6 +1,5 @@
// UK Government data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute UK Government Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_datagovuk_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "datagovuk_api.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "datagovuk_api.py", cmd_args).await
}
/// Search UK government datasets
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/ecb.rs b/fincept-terminal-desktop/src-tauri/src/commands/ecb.rs
index 9263ec97b..a4d91dfe6 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/ecb.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/ecb.rs
@@ -1,8 +1,7 @@
// ECB (European Central Bank) data commands based on OpenBB ECB provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute ECB Python script command with PyO3
#[tauri::command]
pub async fn execute_ecb_command(
app: tauri::AppHandle,
@@ -13,9 +12,7 @@ pub async fn execute_ecb_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "ecb_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "ecb_data.py", cmd_args).await
}
// BASIC DATA ACCESS COMMANDS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/econdb.rs b/fincept-terminal-desktop/src-tauri/src/commands/econdb.rs
index a4e2993fa..570b8a434 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/econdb.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/econdb.rs
@@ -1,6 +1,5 @@
// EconDB economic database commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute EconDB Python script command
#[tauri::command]
@@ -13,9 +12,7 @@ pub async fn execute_econdb_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "econdb_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "econdb_data.py", cmd_args).await
}
/// Get economic series data
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/economic_calendar.rs b/fincept-terminal-desktop/src-tauri/src/commands/economic_calendar.rs
index 54eabe68e..be48062bf 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/economic_calendar.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/economic_calendar.rs
@@ -1,6 +1,5 @@
// Economic calendar events commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Economic Calendar Python script command
#[tauri::command]
@@ -13,9 +12,7 @@ pub async fn execute_economic_calendar_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "economic_calendar.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "economic_calendar.py", cmd_args).await
}
/// Get today's economic events
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/edgar.rs b/fincept-terminal-desktop/src-tauri/src/commands/edgar.rs
index d537b12b0..d350eac71 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/edgar.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/edgar.rs
@@ -1,8 +1,7 @@
// Edgar (SEC filings) data commands using edgartools library
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute Edgar Python script command with PyO3
#[tauri::command]
pub async fn execute_edgar_command(
app: tauri::AppHandle,
@@ -13,7 +12,6 @@ pub async fn execute_edgar_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "edgar_tools.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "edgar_tools.py", cmd_args).await
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/eia.rs b/fincept-terminal-desktop/src-tauri/src/commands/eia.rs
index 22614e0f4..df84480a9 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/eia.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/eia.rs
@@ -1,8 +1,7 @@
// EIA (U.S. Energy Information Administration) data commands based on OpenBB eia provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute EIA Python script command with PyO3
#[tauri::command]
pub async fn execute_eia_command(
app: tauri::AppHandle,
@@ -13,9 +12,7 @@ pub async fn execute_eia_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "eia_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "eia_data.py", cmd_args).await
}
// PETROLEUM STATUS REPORT COMMANDS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/estat_japan.rs b/fincept-terminal-desktop/src-tauri/src/commands/estat_japan.rs
index c12d876ac..b73399d5a 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/estat_japan.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/estat_japan.rs
@@ -1,6 +1,5 @@
// Japan Statistics Bureau data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Japan Statistics Python script command
#[tauri::command]
@@ -13,9 +12,7 @@ pub async fn execute_estat_japan_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "estat_japan_api.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "estat_japan_api.py", cmd_args).await
}
/// Get statistical data
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/federal_reserve.rs b/fincept-terminal-desktop/src-tauri/src/commands/federal_reserve.rs
index 48c3833d9..eb5bd7fea 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/federal_reserve.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/federal_reserve.rs
@@ -1,6 +1,5 @@
// Federal Reserve data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Federal Reserve Python script command
#[tauri::command]
@@ -13,9 +12,7 @@ pub async fn execute_federal_reserve_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "federal_reserve_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "federal_reserve_data.py", cmd_args).await
}
/// Get Federal Funds Rate data
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs
index 40bf03bad..2a3e63866 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs
@@ -1,6 +1,6 @@
// FFN Analytics Commands - Portfolio performance analysis via subprocess
#![allow(dead_code)]
-use crate::utils::python::execute_python_subprocess;
+use crate::python;
// ============================================================================
// FFN ANALYTICS COMMANDS
@@ -10,12 +10,7 @@ use crate::utils::python::execute_python_subprocess;
#[tauri::command]
pub async fn ffn_check_status(app: tauri::AppHandle) -> Result<String, String> {
let args = vec!["check_status".to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/ffn_wrapper/ffn_service.py",
- &args,
- Some("ffn"),
- )
+ python::execute_sync(&app, "ffn_service.py", args)
}
/// Calculate comprehensive performance statistics for price data
@@ -31,12 +26,7 @@ pub async fn ffn_calculate_performance(
});
let args = vec!["calculate_performance".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/ffn_wrapper/ffn_service.py",
- &args,
- Some("ffn"),
- )
+ python::execute_sync(&app, "ffn_service.py", args)
}
/// Calculate drawdown analysis with details
@@ -52,12 +42,7 @@ pub async fn ffn_calculate_drawdowns(
});
let args = vec!["calculate_drawdowns".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/ffn_wrapper/ffn_service.py",
- &args,
- Some("ffn"),
- )
+ python::execute_sync(&app, "ffn_service.py", args)
}
/// Calculate rolling performance metrics
@@ -75,12 +60,7 @@ pub async fn ffn_calculate_rolling_metrics(
});
let args = vec!["calculate_rolling_metrics".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/ffn_wrapper/ffn_service.py",
- &args,
- Some("ffn"),
- )
+ python::execute_sync(&app, "ffn_service.py", args)
}
/// Calculate monthly returns table
@@ -94,12 +74,7 @@ pub async fn ffn_monthly_returns(
});
let args = vec!["monthly_returns".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/ffn_wrapper/ffn_service.py",
- &args,
- Some("ffn"),
- )
+ python::execute_sync(&app, "ffn_service.py", args)
}
/// Rebase prices to a starting value
@@ -115,12 +90,7 @@ pub async fn ffn_rebase_prices(
});
let args = vec!["rebase_prices".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/ffn_wrapper/ffn_service.py",
- &args,
- Some("ffn"),
- )
+ python::execute_sync(&app, "ffn_service.py", args)
}
/// Compare multiple assets performance
@@ -138,12 +108,7 @@ pub async fn ffn_compare_assets(
});
let args = vec!["compare_assets".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/ffn_wrapper/ffn_service.py",
- &args,
- Some("ffn"),
- )
+ python::execute_sync(&app, "ffn_service.py", args)
}
/// Calculate risk metrics (Ulcer Index, etc.)
@@ -159,12 +124,7 @@ pub async fn ffn_risk_metrics(
});
let args = vec!["risk_metrics".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/ffn_wrapper/ffn_service.py",
- &args,
- Some("ffn"),
- )
+ python::execute_sync(&app, "ffn_service.py", args)
}
/// Full portfolio analysis - combines all metrics
@@ -180,12 +140,7 @@ pub async fn ffn_full_analysis(
});
let args = vec!["full_analysis".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/ffn_wrapper/ffn_service.py",
- &args,
- Some("ffn"),
- )
+ python::execute_sync(&app, "ffn_service.py", args)
}
/// Portfolio optimization - calculate optimal weights using various methods
@@ -206,12 +161,7 @@ pub async fn ffn_portfolio_optimization(
});
let args = vec!["portfolio_optimization".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/ffn_wrapper/ffn_service.py",
- &args,
- Some("ffn"),
- )
+ python::execute_sync(&app, "ffn_service.py", args)
}
/// Benchmark comparison - compare portfolio against a benchmark
@@ -231,10 +181,5 @@ pub async fn ffn_benchmark_comparison(
});
let args = vec!["benchmark_comparison".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/ffn_wrapper/ffn_service.py",
- &args,
- Some("ffn"),
- )
+ python::execute_sync(&app, "ffn_service.py", args)
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/financepy.rs b/fincept-terminal-desktop/src-tauri/src/commands/financepy.rs
index d7199129e..02b7d3f80 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/financepy.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/financepy.rs
@@ -1,7 +1,8 @@
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
use tauri::command;
+// FinancePy uses NumPy 1.x venv - must use subprocess execution with library hint
+
// ==================== UTILITIES ====================
#[command]
@@ -10,8 +11,7 @@ pub async fn financepy_create_date(
date_str: String,
) -> Result<String, String> {
let args = vec!["utils_create_date".to_string(), date_str];
- let script_path = get_script_path(&app, "financepy_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute_sync(&app, "financepy_wrapper.py", args)
}
#[command]
@@ -22,8 +22,7 @@ pub async fn financepy_date_range(
freq: String,
) -> Result<String, String> {
let args = vec!["utils_date_range".to_string(), start_date, end_date, freq];
- let script_path = get_script_path(&app, "financepy_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute_sync(&app, "financepy_wrapper.py", args)
}
// ==================== BONDS ====================
@@ -47,8 +46,7 @@ pub async fn financepy_bond_price(
ytm.to_string(),
freq.to_string(),
];
- let script_path = get_script_path(&app, "financepy_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute_sync(&app, "financepy_wrapper.py", args)
}
#[command]
@@ -70,8 +68,7 @@ pub async fn financepy_bond_ytm(
clean_price.to_string(),
freq.to_string(),
];
- let script_path = get_script_path(&app, "financepy_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute_sync(&app, "financepy_wrapper.py", args)
}
// ==================== EQUITY OPTIONS ====================
@@ -99,8 +96,7 @@ pub async fn financepy_equity_option_price(
dividend_yield.to_string(),
option_type,
];
- let script_path = get_script_path(&app, "financepy_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute_sync(&app, "financepy_wrapper.py", args)
}
#[command]
@@ -126,8 +122,7 @@ pub async fn financepy_equity_option_implied_vol(
dividend_yield.to_string(),
option_type,
];
- let script_path = get_script_path(&app, "financepy_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute_sync(&app, "financepy_wrapper.py", args)
}
// ==================== FX OPTIONS ====================
@@ -157,8 +152,7 @@ pub async fn financepy_fx_option_price(
option_type,
notional.to_string(),
];
- let script_path = get_script_path(&app, "financepy_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute_sync(&app, "financepy_wrapper.py", args)
}
// ==================== INTEREST RATE SWAPS ====================
@@ -182,8 +176,7 @@ pub async fn financepy_ibor_swap_price(
notional.to_string(),
discount_rate.to_string(),
];
- let script_path = get_script_path(&app, "financepy_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute_sync(&app, "financepy_wrapper.py", args)
}
// ==================== CREDIT DERIVATIVES ====================
@@ -205,6 +198,5 @@ pub async fn financepy_cds_spread(
notional.to_string(),
spread_bps.to_string(),
];
- let script_path = get_script_path(&app, "financepy_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute_sync(&app, "financepy_wrapper.py", args)
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/financial_analysis.rs b/fincept-terminal-desktop/src-tauri/src/commands/financial_analysis.rs
index 467409239..d311a47fe 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/financial_analysis.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/financial_analysis.rs
@@ -1,8 +1,7 @@
// Financial Analysis Module Commands
// CFA-compliant statement analysis via worker pool or subprocess
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
use serde::{Deserialize, Serialize};
/// Financial data input structure
@@ -90,10 +89,9 @@ pub async fn analyze_income_statement(
) -> Result<String, String> {
let json_data = serde_json::to_string(&data)
.map_err(|e| format!("Failed to serialize data: {}", e))?;
-
+
let args = vec!["analyze_income".to_string(), json_data];
- let script_path = get_script_path(&app, "Analytics/financial_analysis_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/financial_analysis_cli.py", args).await
}
/// Analyze balance sheet
@@ -104,10 +102,9 @@ pub async fn analyze_balance_sheet(
) -> Result<String, String> {
let json_data = serde_json::to_string(&data)
.map_err(|e| format!("Failed to serialize data: {}", e))?;
-
+
let args = vec!["analyze_balance".to_string(), json_data];
- let script_path = get_script_path(&app, "Analytics/financial_analysis_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/financial_analysis_cli.py", args).await
}
/// Analyze cash flow statement
@@ -118,10 +115,9 @@ pub async fn analyze_cash_flow(
) -> Result<String, String> {
let json_data = serde_json::to_string(&data)
.map_err(|e| format!("Failed to serialize data: {}", e))?;
-
+
let args = vec!["analyze_cashflow".to_string(), json_data];
- let script_path = get_script_path(&app, "Analytics/financial_analysis_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/financial_analysis_cli.py", args).await
}
/// Run comprehensive financial analysis
@@ -132,10 +128,9 @@ pub async fn analyze_financial_statements(
) -> Result<String, String> {
let json_data = serde_json::to_string(&data)
.map_err(|e| format!("Failed to serialize data: {}", e))?;
-
+
let args = vec!["analyze_comprehensive".to_string(), json_data];
- let script_path = get_script_path(&app, "Analytics/financial_analysis_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/financial_analysis_cli.py", args).await
}
/// Get key financial metrics summary
@@ -146,10 +141,9 @@ pub async fn get_financial_key_metrics(
) -> Result<String, String> {
let json_data = serde_json::to_string(&data)
.map_err(|e| format!("Failed to serialize data: {}", e))?;
-
+
let args = vec!["get_key_metrics".to_string(), json_data];
- let script_path = get_script_path(&app, "Analytics/financial_analysis_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/financial_analysis_cli.py", args).await
}
/// Convenience command for quick analysis with raw JSON
@@ -160,6 +154,5 @@ pub async fn analyze_financial_json(
json_data: String,
) -> Result<String, String> {
let args = vec![command, json_data];
- let script_path = get_script_path(&app, "Analytics/financial_analysis_cli.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/financial_analysis_cli.py", args).await
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/fiscaldata.rs b/fincept-terminal-desktop/src-tauri/src/commands/fiscaldata.rs
index 89a5d57db..944f475d0 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/fiscaldata.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/fiscaldata.rs
@@ -1,7 +1,6 @@
// U.S. Treasury FiscalData API commands
#![allow(dead_code)]
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute FiscalData Python script command
#[tauri::command]
@@ -12,8 +11,7 @@ pub async fn execute_fiscaldata_command(
) -> Result<String, String> {
let mut cmd_args = vec![command];
cmd_args.extend(args);
- let script_path = get_script_path(&app, "fiscaldata_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "fiscaldata_data.py", cmd_args).await
}
/// Get Debt to the Penny data - Daily public debt outstanding
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/fmp.rs b/fincept-terminal-desktop/src-tauri/src/commands/fmp.rs
index 4766e691b..083477baf 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/fmp.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/fmp.rs
@@ -1,6 +1,5 @@
// FMP (Financial Modeling Prep) data commands based on OpenBB fmp provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
use crate::database::operations;
/// Execute FMP Python script command
@@ -41,9 +40,7 @@ pub async fn execute_fmp_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "fmp_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "fmp_data.py", cmd_args).await
}
// EQUITY DATA COMMANDS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/fortitudo_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/fortitudo_analytics.rs
index 622467706..846dbad44 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/fortitudo_analytics.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/fortitudo_analytics.rs
@@ -1,6 +1,6 @@
// Fortitudo.tech Analytics Commands - Portfolio risk analytics via subprocess
#![allow(dead_code)]
-use crate::utils::python::{execute_python_subprocess, execute_python_subprocess_with_stdin};
+use crate::python;
// ============================================================================
// FORTITUDO ANALYTICS COMMANDS
@@ -10,12 +10,7 @@ use crate::utils::python::{execute_python_subprocess, execute_python_subprocess_
#[tauri::command]
pub async fn fortitudo_check_status(app: tauri::AppHandle) -> Result<String, String> {
let args = vec!["check_status".to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- &args,
- Some("fortitudo"),
- )
+ python::execute_sync(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args)
}
/// Calculate comprehensive portfolio risk metrics (VaR, CVaR, volatility, Sharpe)
@@ -34,13 +29,9 @@ pub async fn fortitudo_portfolio_metrics(
"probabilities": probabilities
});
- execute_python_subprocess_with_stdin(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- "portfolio_metrics",
- &params.to_string(),
- Some("fortitudo"),
- )
+ let args = vec!["portfolio_metrics".to_string(), params.to_string()];
+ let stdin_data = params.to_string();
+ python::execute_with_stdin(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args, &stdin_data)
}
/// Calculate covariance and correlation matrices with statistical moments
@@ -55,13 +46,9 @@ pub async fn fortitudo_covariance_analysis(
"probabilities": probabilities
});
- execute_python_subprocess_with_stdin(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- "covariance_analysis",
- &params.to_string(),
- Some("fortitudo"),
- )
+ let args = vec!["covariance_analysis".to_string(), params.to_string()];
+ let stdin_data = params.to_string();
+ python::execute_with_stdin(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args, &stdin_data)
}
/// Calculate exponentially decaying probabilities for scenario weighting
@@ -76,13 +63,9 @@ pub async fn fortitudo_exp_decay_weighting(
"half_life": half_life.unwrap_or(252)
});
- execute_python_subprocess_with_stdin(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- "exp_decay_weighting",
- &params.to_string(),
- Some("fortitudo"),
- )
+ let args = vec!["exp_decay_weighting".to_string(), params.to_string()];
+ let stdin_data = params.to_string();
+ python::execute_with_stdin(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args, &stdin_data)
}
/// Price options using Black-Scholes model
@@ -106,12 +89,7 @@ pub async fn fortitudo_option_pricing(
});
let args = vec!["option_pricing".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- &args,
- Some("fortitudo"),
- )
+ python::execute_sync(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args)
}
/// Generate option chain for multiple strikes
@@ -135,12 +113,7 @@ pub async fn fortitudo_option_chain(
});
let args = vec!["option_chain".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- &args,
- Some("fortitudo"),
- )
+ python::execute_sync(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args)
}
/// Apply entropy pooling for scenario probability adjustment
@@ -156,12 +129,7 @@ pub async fn fortitudo_entropy_pooling(
});
let args = vec!["entropy_pooling".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- &args,
- Some("fortitudo"),
- )
+ python::execute_sync(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args)
}
/// Calculate exposure stacking portfolio from sample portfolios
@@ -176,13 +144,9 @@ pub async fn fortitudo_exposure_stacking(
"n_partitions": n_partitions.unwrap_or(4)
});
- execute_python_subprocess_with_stdin(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- "exposure_stacking",
- &params.to_string(),
- Some("fortitudo"),
- )
+ let args = vec!["exposure_stacking".to_string(), params.to_string()];
+ let stdin_data = params.to_string();
+ python::execute_with_stdin(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args, &stdin_data)
}
/// Full portfolio risk analysis combining all metrics
@@ -201,13 +165,9 @@ pub async fn fortitudo_full_analysis(
"half_life": half_life.unwrap_or(252)
});
- execute_python_subprocess_with_stdin(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- "full_analysis",
- &params.to_string(),
- Some("fortitudo"),
- )
+ let args = vec!["full_analysis".to_string(), params.to_string()];
+ let stdin_data = params.to_string();
+ python::execute_with_stdin(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args, &stdin_data)
}
/// Calculate option Greeks (Delta, Gamma, Vega, Theta, Rho)
@@ -231,12 +191,7 @@ pub async fn fortitudo_option_greeks(
});
let args = vec!["option_greeks".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- &args,
- Some("fortitudo"),
- )
+ python::execute_sync(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args)
}
/// Mean-Variance portfolio optimization
@@ -261,13 +216,9 @@ pub async fn fortitudo_optimize_mean_variance(
"target_return": target_return
});
- execute_python_subprocess_with_stdin(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- "optimize_mean_variance",
- &params.to_string(),
- Some("fortitudo"),
- )
+ let args = vec!["optimize_mean_variance".to_string(), params.to_string()];
+ let stdin_data = params.to_string();
+ python::execute_with_stdin(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args, &stdin_data)
}
/// Mean-CVaR portfolio optimization
@@ -294,13 +245,9 @@ pub async fn fortitudo_optimize_mean_cvar(
"target_return": target_return
});
- execute_python_subprocess_with_stdin(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- "optimize_mean_cvar",
- &params.to_string(),
- Some("fortitudo"),
- )
+ let args = vec!["optimize_mean_cvar".to_string(), params.to_string()];
+ let stdin_data = params.to_string();
+ python::execute_with_stdin(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args, &stdin_data)
}
/// Generate Mean-Variance efficient frontier
@@ -321,13 +268,9 @@ pub async fn fortitudo_efficient_frontier_mv(
"risk_free_rate": risk_free_rate.unwrap_or(0.0)
});
- execute_python_subprocess_with_stdin(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- "efficient_frontier_mv",
- &params.to_string(),
- Some("fortitudo"),
- )
+ let args = vec!["efficient_frontier_mv".to_string(), params.to_string()];
+ let stdin_data = params.to_string();
+ python::execute_with_stdin(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args, &stdin_data)
}
/// Generate Mean-CVaR efficient frontier
@@ -348,11 +291,7 @@ pub async fn fortitudo_efficient_frontier_cvar(
"max_weight": max_weight
});
- execute_python_subprocess_with_stdin(
- &app,
- "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
- "efficient_frontier_cvar",
- &params.to_string(),
- Some("fortitudo"),
- )
+ let args = vec!["efficient_frontier_cvar".to_string(), params.to_string()];
+ let stdin_data = params.to_string();
+ python::execute_with_stdin(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py", args, &stdin_data)
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/fred.rs b/fincept-terminal-desktop/src-tauri/src/commands/fred.rs
index 173c74c59..1a328dd55 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/fred.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/fred.rs
@@ -1,8 +1,6 @@
// FRED (Federal Reserve Economic Data) commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
-/// Execute FRED Python script command with PyO3
#[tauri::command]
pub async fn execute_fred_command(
app: tauri::AppHandle,
@@ -11,9 +9,7 @@ pub async fn execute_fred_command(
) -> Result<String, String> {
let mut cmd_args = vec![command];
cmd_args.extend(args);
-
- let script_path = get_script_path(&app, "fred_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "fred_data.py", cmd_args).await
}
/// Get FRED series data
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/french_gov.rs b/fincept-terminal-desktop/src-tauri/src/commands/french_gov.rs
index 5fcc99699..5460da2dd 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/french_gov.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/french_gov.rs
@@ -1,6 +1,5 @@
// French Government data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute French Government Python script command
#[tauri::command]
@@ -13,9 +12,7 @@ pub async fn execute_french_gov_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "french_gov_api.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "french_gov_api.py", cmd_args).await
}
/// Search French government datasets
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs
index 671f99ec8..e26da79c5 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs
@@ -1,6 +1,6 @@
// Functime Analytics Commands - Time series forecasting via subprocess
#![allow(dead_code)]
-use crate::utils::python::execute_python_subprocess;
+use crate::python;
// ============================================================================
// FUNCTIME ANALYTICS COMMANDS
@@ -10,12 +10,7 @@ use crate::utils::python::execute_python_subprocess;
#[tauri::command]
pub async fn functime_check_status(app: tauri::AppHandle) -> Result<String, String> {
let args = vec!["check_status".to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Run forecasting with specified model
@@ -44,12 +39,7 @@ pub async fn functime_forecast(
});
let args = vec!["forecast".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Apply preprocessing transformations to time series data
@@ -80,12 +70,7 @@ pub async fn functime_preprocess(
});
let args = vec!["preprocess".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Perform cross-validation splits
@@ -110,12 +95,7 @@ pub async fn functime_cross_validate(
});
let args = vec!["cross_validate".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Calculate forecast accuracy metrics
@@ -134,12 +114,7 @@ pub async fn functime_metrics(
});
let args = vec!["metrics".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Add calendar or holiday features
@@ -160,12 +135,7 @@ pub async fn functime_add_features(
});
let args = vec!["add_features".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Get seasonal period for a frequency
@@ -179,12 +149,7 @@ pub async fn functime_seasonal_period(
});
let args = vec!["seasonal_period".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Run a complete forecasting pipeline with preprocessing and evaluation
@@ -208,12 +173,7 @@ pub async fn functime_full_pipeline(
});
let args = vec!["full_pipeline".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
// ============================================================================
@@ -247,12 +207,7 @@ pub async fn functime_advanced_forecast(
});
let args = vec!["advanced_forecast".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Ensemble forecasting combining multiple models
@@ -274,12 +229,7 @@ pub async fn functime_ensemble(
});
let args = vec!["ensemble".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Automatic ensemble with weight optimization
@@ -297,12 +247,7 @@ pub async fn functime_auto_ensemble(
});
let args = vec!["auto_ensemble".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Anomaly detection in time series
@@ -324,12 +269,7 @@ pub async fn functime_anomaly_detection(
});
let args = vec!["anomaly_detection".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Seasonality analysis (decomposition, strength, detection)
@@ -368,12 +308,7 @@ pub async fn functime_seasonality(
});
let args = vec!["seasonality".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Calculate confidence intervals for forecasts
@@ -395,12 +330,7 @@ pub async fn functime_confidence_intervals(
});
let args = vec!["confidence_intervals".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Feature importance analysis for ML models
@@ -420,12 +350,7 @@ pub async fn functime_feature_importance(
});
let args = vec!["feature_importance".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Advanced cross-validation with model evaluation
@@ -449,12 +374,7 @@ pub async fn functime_advanced_cv(
});
let args = vec!["advanced_cv".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
/// Strategy backtesting for forecasting models
@@ -478,10 +398,5 @@ pub async fn functime_backtest(
});
let args = vec!["backtest".to_string(), params.to_string()];
- execute_python_subprocess(
- &app,
- "Analytics/functime_wrapper/functime_service.py",
- &args,
- Some("functime"),
- )
+ python::execute_sync(&app, "Analytics/functime_wrapper/functime_service.py", args)
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/geocoding.rs b/fincept-terminal-desktop/src-tauri/src/commands/geocoding.rs
index 01e559717..2607e6e7d 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/geocoding.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/geocoding.rs
@@ -1,8 +1,7 @@
// Geocoding commands using geopy Python library
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute geocoding Python script command with PyO3
#[tauri::command]
pub async fn execute_geocoding_command(
app: tauri::AppHandle,
@@ -13,9 +12,8 @@ pub async fn execute_geocoding_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "geocoding_service.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "geocoding_service.py", cmd_args).await
}
/// Search for locations with autocomplete
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/govdata_de.rs b/fincept-terminal-desktop/src-tauri/src/commands/govdata_de.rs
index cece557ab..086a2b7d2 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/govdata_de.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/govdata_de.rs
@@ -1,6 +1,5 @@
// German Government data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute German Government Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_govdata_de_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "govdata_de_api_complete.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "govdata_de_api_complete.py", cmd_args).await
}
/// Search German government datasets
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/government_us.rs b/fincept-terminal-desktop/src-tauri/src/commands/government_us.rs
index 41a9ef24c..0b1ab7a07 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/government_us.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/government_us.rs
@@ -1,6 +1,5 @@
// US Government data commands based on OpenBB government_us provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute US Government Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_government_us_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "government_us_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "government_us_data.py", cmd_args).await
}
/// Get US Treasury prices for a specific date
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/hdx.rs b/fincept-terminal-desktop/src-tauri/src/commands/hdx.rs
index 1573686f0..a87bcfa55 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/hdx.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/hdx.rs
@@ -1,4 +1,4 @@
-use crate::utils::python::execute_python_script_simple;
+use crate::python;
use tauri::command;
#[command]
@@ -7,14 +7,12 @@ pub async fn hdx_search_datasets(
query: String,
limit: Option<i32>,
) -> Result<String, String> {
- let limit_str = limit.map(|l| l.to_string());
- let args: Vec<&str> = if let Some(ref l) = limit_str {
- vec!["search_datasets", &query, l]
- } else {
- vec!["search_datasets", &query]
- };
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ let mut args = vec!["search_datasets".to_string(), query];
+ if let Some(l) = limit {
+ args.push(l.to_string());
+ }
+
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
@@ -22,7 +20,7 @@ pub async fn hdx_get_dataset(
app: tauri::AppHandle,
dataset_id: String,
) -> Result<String, String> {
- execute_python_script_simple(&app, "hdx_data.py", &["get_dataset", &dataset_id])
+ python::execute_sync(&app, "hdx_data.py", vec!["get_dataset".to_string(), dataset_id])
}
#[command]
@@ -31,14 +29,12 @@ pub async fn hdx_search_conflict(
country: String,
limit: Option<i32>,
) -> Result<String, String> {
- let limit_str = limit.map(|l| l.to_string());
- let args: Vec<&str> = if let Some(ref l) = limit_str {
- vec!["search_conflict", &country, l]
- } else {
- vec!["search_conflict", &country]
- };
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ let mut args = vec!["search_conflict".to_string(), country];
+ if let Some(l) = limit {
+ args.push(l.to_string());
+ }
+
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
@@ -47,14 +43,12 @@ pub async fn hdx_search_humanitarian(
country: String,
limit: Option<i32>,
) -> Result<String, String> {
- let limit_str = limit.map(|l| l.to_string());
- let args: Vec<&str> = if let Some(ref l) = limit_str {
- vec!["search_humanitarian", &country, l]
- } else {
- vec!["search_humanitarian", &country]
- };
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ let mut args = vec!["search_humanitarian".to_string(), country];
+ if let Some(l) = limit {
+ args.push(l.to_string());
+ }
+
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
@@ -63,14 +57,12 @@ pub async fn hdx_search_by_country(
country_code: String,
limit: Option<i32>,
) -> Result<String, String> {
- let limit_str = limit.map(|l| l.to_string());
- let args: Vec<&str> = if let Some(ref l) = limit_str {
- vec!["search_by_country", &country_code, l]
- } else {
- vec!["search_by_country", &country_code]
- };
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ let mut args = vec!["search_by_country".to_string(), country_code];
+ if let Some(l) = limit {
+ args.push(l.to_string());
+ }
+
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
@@ -79,14 +71,12 @@ pub async fn hdx_search_by_organization(
org_slug: String,
limit: Option<i32>,
) -> Result<String, String> {
- let limit_str = limit.map(|l| l.to_string());
- let args: Vec<&str> = if let Some(ref l) = limit_str {
- vec!["search_by_organization", &org_slug, l]
- } else {
- vec!["search_by_organization", &org_slug]
- };
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ let mut args = vec!["search_by_organization".to_string(), org_slug];
+ if let Some(l) = limit {
+ args.push(l.to_string());
+ }
+
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
@@ -95,14 +85,12 @@ pub async fn hdx_search_by_topic(
topic: String,
limit: Option<i32>,
) -> Result<String, String> {
- let limit_str = limit.map(|l| l.to_string());
- let args: Vec<&str> = if let Some(ref l) = limit_str {
- vec!["search_by_topic", &topic, l]
- } else {
- vec!["search_by_topic", &topic]
- };
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ let mut args = vec!["search_by_topic".to_string(), topic];
+ if let Some(l) = limit {
+ args.push(l.to_string());
+ }
+
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
@@ -111,14 +99,12 @@ pub async fn hdx_search_by_dataseries(
series_name: String,
limit: Option<i32>,
) -> Result<String, String> {
- let limit_str = limit.map(|l| l.to_string());
- let args: Vec<&str> = if let Some(ref l) = limit_str {
- vec!["search_by_dataseries", &series_name, l]
- } else {
- vec!["search_by_dataseries", &series_name]
- };
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ let mut args = vec!["search_by_dataseries".to_string(), series_name];
+ if let Some(l) = limit {
+ args.push(l.to_string());
+ }
+
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
@@ -126,14 +112,12 @@ pub async fn hdx_list_countries(
app: tauri::AppHandle,
limit: Option<i32>,
) -> Result<String, String> {
- let limit_str = limit.map(|l| l.to_string());
- let args: Vec<&str> = if let Some(ref l) = limit_str {
- vec!["list_countries", l]
- } else {
- vec!["list_countries"]
- };
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ let mut args = vec!["list_countries".to_string()];
+ if let Some(l) = limit {
+ args.push(l.to_string());
+ }
+
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
@@ -141,14 +125,12 @@ pub async fn hdx_list_organizations(
app: tauri::AppHandle,
limit: Option<i32>,
) -> Result<String, String> {
- let limit_str = limit.map(|l| l.to_string());
- let args: Vec<&str> = if let Some(ref l) = limit_str {
- vec!["list_organizations", l]
- } else {
- vec!["list_organizations"]
- };
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ let mut args = vec!["list_organizations".to_string()];
+ if let Some(l) = limit {
+ args.push(l.to_string());
+ }
+
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
@@ -156,14 +138,12 @@ pub async fn hdx_list_topics(
app: tauri::AppHandle,
limit: Option<i32>,
) -> Result<String, String> {
- let limit_str = limit.map(|l| l.to_string());
- let args: Vec<&str> = if let Some(ref l) = limit_str {
- vec!["list_topics", l]
- } else {
- vec!["list_topics"]
- };
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ let mut args = vec!["list_topics".to_string()];
+ if let Some(l) = limit {
+ args.push(l.to_string());
+ }
+
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
@@ -172,14 +152,12 @@ pub async fn hdx_get_resource_url(
dataset_id: String,
resource_index: Option<i32>,
) -> Result<String, String> {
- let index_str = resource_index.map(|i| i.to_string());
- let args: Vec<&str> = if let Some(ref idx) = index_str {
- vec!["get_resource_download_url", &dataset_id, idx]
- } else {
- vec!["get_resource_download_url", &dataset_id]
- };
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ let mut args = vec!["get_resource_download_url".to_string(), dataset_id];
+ if let Some(idx) = resource_index {
+ args.push(idx.to_string());
+ }
+
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
@@ -187,22 +165,18 @@ pub async fn hdx_advanced_search(
app: tauri::AppHandle,
filters: String,
) -> Result<String, String> {
- // Build args vector with owned strings
- let mut args_owned = vec!["advanced_search".to_string()];
+ let mut args = vec!["advanced_search".to_string()];
// Parse filters string and add as arguments
// Expected format: "country:ukr organization:ocha limit:20"
for filter in filters.split_whitespace() {
- args_owned.push(filter.to_string());
+ args.push(filter.to_string());
}
- // Convert to borrowed references
- let args: Vec<&str> = args_owned.iter().map(|s| s.as_str()).collect();
-
- execute_python_script_simple(&app, "hdx_data.py", &args)
+ python::execute_sync(&app, "hdx_data.py", args)
}
#[command]
pub async fn hdx_test_connection(app: tauri::AppHandle) -> Result<String, String> {
- execute_python_script_simple(&app, "hdx_data.py", &["test_connection"])
+ python::execute_sync(&app, "hdx_data.py", vec!["test_connection".to_string()])
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/imf.rs b/fincept-terminal-desktop/src-tauri/src/commands/imf.rs
index 65a6e075f..1d5625849 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/imf.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/imf.rs
@@ -1,8 +1,7 @@
// IMF (International Monetary Fund) data commands based on OpenBB imf provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute IMF Python script command with PyO3
#[tauri::command]
pub async fn execute_imf_command(
app: tauri::AppHandle,
@@ -13,9 +12,7 @@ pub async fn execute_imf_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "imf_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "imf_data.py", cmd_args).await
}
/// Get economic indicators data (IRFCL and FSI)
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/jupyter.rs b/fincept-terminal-desktop/src-tauri/src/commands/jupyter.rs
index 39bc4fe28..321b2d73a 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/jupyter.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/jupyter.rs
@@ -80,7 +80,7 @@ pub async fn execute_python_code(
execution_count: i32,
) -> Result<ExecutionResult, String> {
// Get bundled Python path
- let python_path = crate::utils::python::get_python_path(&app)?;
+ let python_path = crate::python::get_python_path(&app, None)?;
// Verify Python exists
if !python_path.exists() {
@@ -90,32 +90,37 @@ pub async fn execute_python_code(
));
}
- // Create temporary Python script
- let temp_dir = std::env::temp_dir();
- let script_path = temp_dir.join(format!("jupyter_cell_{}.py", execution_count));
+ // Run blocking I/O on a dedicated thread to avoid blocking the async runtime
+ let output = tokio::task::spawn_blocking(move || {
+ // Create temporary Python script
+ let temp_dir = std::env::temp_dir();
+ let script_path = temp_dir.join(format!("jupyter_cell_{}.py", execution_count));
- // Write code to temporary file
- std::fs::write(&script_path, &code)
- .map_err(|e| format!("Failed to write temp script: {}", e))?;
+ // Write code to temporary file
+ std::fs::write(&script_path, &code)
+ .map_err(|e| format!("Failed to write temp script: {}", e))?;
- // Execute Python code
- let mut cmd = Command::new(&python_path);
- cmd.arg(&script_path);
+ // Execute Python code
+ let mut cmd = Command::new(&python_path);
+ cmd.arg(&script_path);
- // Hide console window on Windows
- #[cfg(target_os = "windows")]
- cmd.creation_flags(CREATE_NO_WINDOW);
+ // Hide console window on Windows
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
- // Set PYTHONIOENCODING to UTF-8 for proper encoding
- cmd.env("PYTHONIOENCODING", "utf-8");
+ // Set PYTHONIOENCODING to UTF-8 for proper encoding
+ cmd.env("PYTHONIOENCODING", "utf-8");
- // Execute and capture output
- let output = cmd
- .output()
- .map_err(|e| format!("Failed to execute Python: {}", e))?;
+ // Execute and capture output
+ let result = cmd
+ .output()
+ .map_err(|e| format!("Failed to execute Python: {}", e));
+
+ // Clean up temp file
+ let _ = std::fs::remove_file(&script_path);
- // Clean up temp file
- let _ = std::fs::remove_file(&script_path);
+ result
+ }).await.map_err(|e| format!("Task join error: {}", e))??;
let mut outputs = Vec::new();
@@ -227,7 +232,7 @@ pub async fn create_new_notebook() -> Result<JupyterNotebook, String> {
/// Get Python version from bundled interpreter
#[tauri::command]
pub async fn get_python_version(app: tauri::AppHandle) -> Result<String, String> {
- let python_path = crate::utils::python::get_python_path(&app)?;
+ let python_path = crate::python::get_python_path(&app, None)?;
let mut cmd = Command::new(&python_path);
cmd.arg("--version");
@@ -258,7 +263,7 @@ pub async fn install_python_package(
app: tauri::AppHandle,
package_name: String,
) -> Result<String, String> {
- let python_path = crate::utils::python::get_python_path(&app)?;
+ let python_path = crate::python::get_python_path(&app, None)?;
let mut cmd = Command::new(&python_path);
cmd.args(&["-m", "pip", "install", &package_name]);
@@ -286,7 +291,7 @@ pub async fn install_python_package(
/// List installed Python packages
#[tauri::command]
pub async fn list_python_packages(app: tauri::AppHandle) -> Result<Vec<String>, String> {
- let python_path = crate::utils::python::get_python_path(&app)?;
+ let python_path = crate::python::get_python_path(&app, None)?;
let mut cmd = Command::new(&python_path);
cmd.args(&["-m", "pip", "list", "--format=freeze"]);
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/llm_models.rs b/fincept-terminal-desktop/src-tauri/src/commands/llm_models.rs
index df96a262b..7af618807 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/llm_models.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/llm_models.rs
@@ -3,7 +3,7 @@
use serde::{Deserialize, Serialize};
use tauri::AppHandle;
-use crate::utils::python::execute_python_subprocess;
+use crate::python;
#[derive(Debug, Serialize, Deserialize)]
pub struct LLMProvider {
@@ -43,11 +43,10 @@ pub struct TopProvider {
/// Get all available LLM providers from embedded model data
#[tauri::command]
pub fn get_llm_providers(app: AppHandle) -> Result<Vec<LLMProvider>, String> {
- let output = execute_python_subprocess(
+ let output = python::execute_sync(
&app,
"litellm_models.py",
- &["providers".to_string()],
- None, // No special library required - uses embedded JSON
+ vec!["providers".to_string()],
)?;
let providers: Vec<LLMProvider> = serde_json::from_str(&output)
@@ -68,11 +67,10 @@ pub fn get_llm_providers(app: AppHandle) -> Result<Vec<LLMProvider>, String> {
/// Get all models for a specific provider from embedded model data
#[tauri::command]
pub fn get_llm_models_by_provider(app: AppHandle, provider: String) -> Result<Vec<LLMModel>, String> {
- let output = execute_python_subprocess(
+ let output = python::execute_sync(
&app,
"litellm_models.py",
- &["models".to_string(), provider.clone()],
- None,
+ vec!["models".to_string(), provider.clone()],
)?;
let models: Vec<LLMModel> = serde_json::from_str(&output)
@@ -84,11 +82,10 @@ pub fn get_llm_models_by_provider(app: AppHandle, provider: String) -> Result<Ve
/// Get all models from all providers
#[tauri::command]
pub fn get_all_llm_models(app: AppHandle) -> Result<Vec<LLMModel>, String> {
- let output = execute_python_subprocess(
+ let output = python::execute_sync(
&app,
"litellm_models.py",
- &["models".to_string()],
- None,
+ vec!["models".to_string()],
)?;
let models: Vec<LLMModel> = serde_json::from_str(&output)
@@ -100,11 +97,10 @@ pub fn get_all_llm_models(app: AppHandle) -> Result<Vec<LLMModel>, String> {
/// Get LLM provider statistics
#[tauri::command]
pub fn get_llm_stats(app: AppHandle) -> Result<LLMStats, String> {
- let output = execute_python_subprocess(
+ let output = python::execute_sync(
&app,
"litellm_models.py",
- &["stats".to_string()],
- None,
+ vec!["stats".to_string()],
)?;
let stats: LLMStats = serde_json::from_str(&output)
@@ -116,11 +112,10 @@ pub fn get_llm_stats(app: AppHandle) -> Result<LLMStats, String> {
/// Search models by name or provider
#[tauri::command]
pub fn search_llm_models(app: AppHandle, query: String) -> Result<Vec<LLMModel>, String> {
- let output = execute_python_subprocess(
+ let output = python::execute_sync(
&app,
"litellm_models.py",
- &["search".to_string(), query.clone()],
- None,
+ vec!["search".to_string(), query.clone()],
)?;
let models: Vec<LLMModel> = serde_json::from_str(&output)
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
index df4aaba78..5161a1198 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
@@ -74,7 +74,6 @@ pub mod portfolio_management;
// skfolio - Advanced Portfolio Optimization
pub mod skfolio;
-// PyPortfolioOpt - Portfolio Optimization with PyO3
pub mod pyportfolioopt;
// Technical Analysis
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/multpl.rs b/fincept-terminal-desktop/src-tauri/src/commands/multpl.rs
index 94a9687f4..7f253ece6 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/multpl.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/multpl.rs
@@ -1,6 +1,5 @@
// MULTPL (S&P 500 Multiples) data commands based on OpenBB multpl provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute MULTPL Python script command
#[tauri::command]
@@ -13,9 +12,7 @@ pub async fn execute_multpl_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "multpl_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "multpl_data.py", cmd_args).await
}
// BASIC SERIES DATA COMMANDS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/nasa_gibs.rs b/fincept-terminal-desktop/src-tauri/src/commands/nasa_gibs.rs
index efa2fc239..77f77c324 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/nasa_gibs.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/nasa_gibs.rs
@@ -1,7 +1,6 @@
// NASA GIBS (Global Imagery Browse Services) API commands
#![allow(dead_code)]
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute NASA GIBS Python script command
#[tauri::command]
@@ -12,8 +11,7 @@ pub async fn execute_nasa_gibs_command(
) -> Result<String, String> {
let mut cmd_args = vec![command];
cmd_args.extend(args);
- let script_path = get_script_path(&app, "nasa_gibs_api.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "nasa_gibs_api.py", cmd_args).await
}
/// List all available imagery layers from NASA GIBS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/nasdaq.rs b/fincept-terminal-desktop/src-tauri/src/commands/nasdaq.rs
index d400f545a..f9c0e2dda 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/nasdaq.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/nasdaq.rs
@@ -1,9 +1,8 @@
// NASDAQ data commands based on OpenBB nasdaq provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
use chrono::Datelike;
-/// Execute NASDAQ Python script command with PyO3
+
#[tauri::command]
pub async fn execute_nasdaq_command(
app: tauri::AppHandle,
@@ -14,9 +13,7 @@ pub async fn execute_nasdaq_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "nasdaq_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "nasdaq_data.py", cmd_args).await
}
// EQUITY SEARCH AND SCREENER COMMANDS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/oecd.rs b/fincept-terminal-desktop/src-tauri/src/commands/oecd.rs
index c9d6a06f9..f76cba816 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/oecd.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/oecd.rs
@@ -1,8 +1,7 @@
// OECD data commands based on OpenBB oecd provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
+
-/// Execute OECD Python script command with PyO3
#[tauri::command]
pub async fn execute_oecd_command(
app: tauri::AppHandle,
@@ -13,9 +12,8 @@ pub async fn execute_oecd_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "oecd_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "oecd_data.py", cmd_args).await
}
/// Get real GDP data for specified countries
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/openafrica.rs b/fincept-terminal-desktop/src-tauri/src/commands/openafrica.rs
index 11ab91995..ea53f79a3 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/openafrica.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/openafrica.rs
@@ -1,6 +1,5 @@
// OpenAFRICA data portal commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute OpenAFRICA Python script command
#[tauri::command]
@@ -13,9 +12,7 @@ pub async fn execute_openafrica_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "openafrica_api.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "openafrica_api.py", cmd_args).await
}
/// Search African datasets
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/oscar.rs b/fincept-terminal-desktop/src-tauri/src/commands/oscar.rs
index b9191efe2..a9ee4f0f8 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/oscar.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/oscar.rs
@@ -1,4 +1,4 @@
-use crate::utils::python::execute_python_script_simple;
+use crate::python;
use tauri::command;
// ==================== INSTRUMENTS ENDPOINTS ====================
@@ -16,28 +16,24 @@ pub async fn oscar_get_instruments(
let sort_str = sort.unwrap_or_else(|| "id".to_string());
let order_str = order.unwrap_or_else(|| "asc".to_string());
- let mut args = vec!["instruments", &page_str, &sort_str, &order_str];
+ let mut args = vec!["instruments".to_string(), page_str, sort_str, order_str];
- let filter_on_str;
- let filter_value_str;
if let Some(fo) = filter_on {
- filter_on_str = fo;
- args.push("--filter-on");
- args.push(&filter_on_str);
+ args.push("--filter-on".to_string());
+ args.push(fo);
}
if let Some(fv) = filter_value {
- filter_value_str = fv;
- args.push("--filter-value");
- args.push(&filter_value_str);
+ args.push("--filter-value".to_string());
+ args.push(fv);
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
#[command]
pub async fn oscar_get_instrument_by_slug(app: tauri::AppHandle, slug: String) -> Result<String, String> {
- execute_python_script_simple(&app, "oscar_data.py", &["instrument", &slug])
+ python::execute_sync(&app, "oscar_data.py", vec!["instrument".to_string(), slug])
}
#[command]
@@ -46,15 +42,13 @@ pub async fn oscar_search_instruments_by_type(
instrument_type: String,
page: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["search_instruments_type", &instrument_type];
+ let mut args = vec!["search_instruments_type".to_string(), instrument_type];
- let page_str;
if let Some(p) = page {
- page_str = p.to_string();
- args.push(&page_str);
+ args.push(p.to_string());
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
#[command]
@@ -63,15 +57,13 @@ pub async fn oscar_search_instruments_by_agency(
agency: String,
page: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["search_instruments_agency", &agency];
+ let mut args = vec!["search_instruments_agency".to_string(), agency];
- let page_str;
if let Some(p) = page {
- page_str = p.to_string();
- args.push(&page_str);
+ args.push(p.to_string());
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
#[command]
@@ -81,22 +73,18 @@ pub async fn oscar_search_instruments_by_year_range(
end_year: i32,
page: Option<i32>
) -> Result<String, String> {
- let start_year_str = start_year.to_string();
- let end_year_str = end_year.to_string();
- let mut args = vec!["search_instruments_year", &start_year_str, &end_year_str];
+ let mut args = vec!["search_instruments_year".to_string(), start_year.to_string(), end_year.to_string()];
- let page_str;
if let Some(p) = page {
- page_str = p.to_string();
- args.push(&page_str);
+ args.push(p.to_string());
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
#[command]
pub async fn oscar_get_instrument_classifications(app: tauri::AppHandle) -> Result<String, String> {
- execute_python_script_simple(&app, "oscar_data.py", &["instrument_classifications"])
+ python::execute_sync(&app, "oscar_data.py", vec!["instrument_classifications".to_string()])
}
// ==================== SATELLITES ENDPOINTS ====================
@@ -114,28 +102,24 @@ pub async fn oscar_get_satellites(
let sort_str = sort.unwrap_or_else(|| "id".to_string());
let order_str = order.unwrap_or_else(|| "asc".to_string());
- let mut args = vec!["satellites", &page_str, &sort_str, &order_str];
+ let mut args = vec!["satellites".to_string(), page_str, sort_str, order_str];
- let filter_on_str;
- let filter_value_str;
if let Some(fo) = filter_on {
- filter_on_str = fo;
- args.push("--filter-on");
- args.push(&filter_on_str);
+ args.push("--filter-on".to_string());
+ args.push(fo);
}
if let Some(fv) = filter_value {
- filter_value_str = fv;
- args.push("--filter-value");
- args.push(&filter_value_str);
+ args.push("--filter-value".to_string());
+ args.push(fv);
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
#[command]
pub async fn oscar_get_satellite_by_slug(app: tauri::AppHandle, slug: String) -> Result<String, String> {
- execute_python_script_simple(&app, "oscar_data.py", &["satellite", &slug])
+ python::execute_sync(&app, "oscar_data.py", vec!["satellite".to_string(), slug])
}
#[command]
@@ -144,15 +128,13 @@ pub async fn oscar_search_satellites_by_orbit(
orbit_type: String,
page: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["search_satellites_orbit", &orbit_type];
+ let mut args = vec!["search_satellites_orbit".to_string(), orbit_type];
- let page_str;
if let Some(p) = page {
- page_str = p.to_string();
- args.push(&page_str);
+ args.push(p.to_string());
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
#[command]
@@ -161,15 +143,13 @@ pub async fn oscar_search_satellites_by_agency(
agency: String,
page: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["search_satellites_agency", &agency];
+ let mut args = vec!["search_satellites_agency".to_string(), agency];
- let page_str;
if let Some(p) = page {
- page_str = p.to_string();
- args.push(&page_str);
+ args.push(p.to_string());
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
// ==================== VARIABLES ENDPOINTS ====================
@@ -187,28 +167,24 @@ pub async fn oscar_get_variables(
let sort_str = sort.unwrap_or_else(|| "id".to_string());
let order_str = order.unwrap_or_else(|| "asc".to_string());
- let mut args = vec!["variables", &page_str, &sort_str, &order_str];
+ let mut args = vec!["variables".to_string(), page_str, sort_str, order_str];
- let filter_on_str;
- let filter_value_str;
if let Some(fo) = filter_on {
- filter_on_str = fo;
- args.push("--filter-on");
- args.push(&filter_on_str);
+ args.push("--filter-on".to_string());
+ args.push(fo);
}
if let Some(fv) = filter_value {
- filter_value_str = fv;
- args.push("--filter-value");
- args.push(&filter_value_str);
+ args.push("--filter-value".to_string());
+ args.push(fv);
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
#[command]
pub async fn oscar_get_variable_by_slug(app: tauri::AppHandle, slug: String) -> Result<String, String> {
- execute_python_script_simple(&app, "oscar_data.py", &["variable", &slug])
+ python::execute_sync(&app, "oscar_data.py", vec!["variable".to_string(), slug])
}
#[command]
@@ -217,69 +193,61 @@ pub async fn oscar_search_variables_by_instrument(
instrument: String,
page: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["search_variables_instrument", &instrument];
+ let mut args = vec!["search_variables_instrument".to_string(), instrument];
- let page_str;
if let Some(p) = page {
- page_str = p.to_string();
- args.push(&page_str);
+ args.push(p.to_string());
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
#[command]
pub async fn oscar_get_ecv_variables(app: tauri::AppHandle, page: Option<i32>) -> Result<String, String> {
- let mut args = vec!["ecv_variables"];
+ let mut args = vec!["ecv_variables".to_string()];
- let page_str;
if let Some(p) = page {
- page_str = p.to_string();
- args.push(&page_str);
+ args.push(p.to_string());
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
// ==================== CONVENIENCE METHODS ====================
#[command]
pub async fn oscar_get_space_agencies(app: tauri::AppHandle) -> Result<String, String> {
- execute_python_script_simple(&app, "oscar_data.py", &["space_agencies"])
+ python::execute_sync(&app, "oscar_data.py", vec!["space_agencies".to_string()])
}
#[command]
pub async fn oscar_get_instrument_types(app: tauri::AppHandle) -> Result<String, String> {
- execute_python_script_simple(&app, "oscar_data.py", &["instrument_types"])
+ python::execute_sync(&app, "oscar_data.py", vec!["instrument_types".to_string()])
}
#[command]
pub async fn oscar_search_weather_instruments(app: tauri::AppHandle, page: Option<i32>) -> Result<String, String> {
- let mut args = vec!["weather_instruments"];
+ let mut args = vec!["weather_instruments".to_string()];
- let page_str;
if let Some(p) = page {
- page_str = p.to_string();
- args.push(&page_str);
+ args.push(p.to_string());
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
#[command]
pub async fn oscar_get_climate_monitoring_instruments(app: tauri::AppHandle, page: Option<i32>) -> Result<String, String> {
- let mut args = vec!["climate_instruments"];
+ let mut args = vec!["climate_instruments".to_string()];
- let page_str;
if let Some(p) = page {
- page_str = p.to_string();
- args.push(&page_str);
+ args.push(p.to_string());
}
- execute_python_script_simple(&app, "oscar_data.py", &args)
+ python::execute_sync(&app, "oscar_data.py", args)
}
#[command]
pub async fn oscar_get_overview_statistics(app: tauri::AppHandle) -> Result<String, String> {
- execute_python_script_simple(&app, "oscar_data.py", &["overview_statistics"])
+ python::execute_sync(&app, "oscar_data.py", vec!["overview_statistics".to_string()])
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/pmdarima.rs b/fincept-terminal-desktop/src-tauri/src/commands/pmdarima.rs
index 81739d202..d4f682a29 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/pmdarima.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/pmdarima.rs
@@ -4,41 +4,20 @@
* Auto-ARIMA, ARIMA modeling, preprocessing, and diagnostics
*/
-use std::process::Command;
-
-/// Execute Python script and return JSON result
-fn execute_python_script(script_name: &str, function: &str, args: &str) -> Result<String, String> {
- let script_path = format!("resources/scripts/Analytics/pmdarima_wrapper/{}", script_name);
-
- let output = Command::new("python")
- .arg(&script_path)
- .arg("--function")
- .arg(function)
- .arg("--args")
- .arg(args)
- .output()
- .map_err(|e| format!("Failed to execute Python: {}", e))?;
-
- if !output.status.success() {
- let error = String::from_utf8_lossy(&output.stderr);
- return Err(format!("Python script error: {}", error));
- }
-
- let result = String::from_utf8_lossy(&output.stdout).to_string();
- Ok(result)
-}
+use crate::python;
// ==================== ARIMA COMMANDS ====================
#[tauri::command]
pub async fn pmdarima_fit_auto_arima(
+ app: tauri::AppHandle,
data: Vec<f64>,
seasonal: Option<bool>,
m: Option<i32>,
max_p: Option<i32>,
max_q: Option<i32>
) -> Result<String, String> {
- let args = serde_json::json!({
+ let args_json = serde_json::json!({
"y": data,
"seasonal": seasonal.unwrap_or(false),
"m": m.unwrap_or(1),
@@ -46,18 +25,23 @@ pub async fn pmdarima_fit_auto_arima(
"max_q": max_q.unwrap_or(5)
}).to_string();
- execute_python_script("arima.py", "fit_auto_arima", &args)
+ python::execute_sync(
+ &app,
+ "Analytics/pmdarima_wrapper/arima.py",
+ vec!["--function".to_string(), "fit_auto_arima".to_string(), "--args".to_string(), args_json]
+ )
}
#[tauri::command]
pub async fn pmdarima_forecast_auto_arima(
+ app: tauri::AppHandle,
data: Vec<f64>,
n_periods: i32,
seasonal: Option<bool>,
return_conf_int: Option<bool>,
alpha: Option<f64>
) -> Result<String, String> {
- let args = serde_json::json!({
+ let args_json = serde_json::json!({
"y": data,
"n_periods": n_periods,
"seasonal": seasonal.unwrap_or(false),
@@ -65,11 +49,16 @@ pub async fn pmdarima_forecast_auto_arima(
"alpha": alpha.unwrap_or(0.05)
}).to_string();
- execute_python_script("arima.py", "forecast_auto_arima", &args)
+ python::execute_sync(
+ &app,
+ "Analytics/pmdarima_wrapper/arima.py",
+ vec!["--function".to_string(), "forecast_auto_arima".to_string(), "--args".to_string(), args_json]
+ )
}
#[tauri::command]
pub async fn pmdarima_forecast_arima(
+ app: tauri::AppHandle,
data: Vec<f64>,
p: i32,
d: i32,
@@ -78,7 +67,7 @@ pub async fn pmdarima_forecast_arima(
return_conf_int: Option<bool>,
alpha: Option<f64>
) -> Result<String, String> {
- let args = serde_json::json!({
+ let args_json = serde_json::json!({
"y": data,
"order": [p, d, q],
"n_periods": n_periods,
@@ -86,93 +75,127 @@ pub async fn pmdarima_forecast_arima(
"alpha": alpha.unwrap_or(0.05)
}).to_string();
- execute_python_script("arima.py", "forecast_arima", &args)
+ python::execute_sync(
+ &app,
+ "Analytics/pmdarima_wrapper/arima.py",
+ vec!["--function".to_string(), "forecast_arima".to_string(), "--args".to_string(), args_json]
+ )
}
// ==================== PREPROCESSING COMMANDS ====================
#[tauri::command]
pub async fn pmdarima_boxcox_transform(
+ app: tauri::AppHandle,
data: Vec<f64>
) -> Result<String, String> {
- let args = serde_json::json!({
+ let args_json = serde_json::json!({
"y": data
}).to_string();
- execute_python_script("preprocessing.py", "apply_boxcox_transform", &args)
+ python::execute_sync(
+ &app,
+ "Analytics/pmdarima_wrapper/preprocessing.py",
+ vec!["--function".to_string(), "apply_boxcox_transform".to_string(), "--args".to_string(), args_json]
+ )
}
#[tauri::command]
pub async fn pmdarima_inverse_boxcox(
+ app: tauri::AppHandle,
data: Vec<f64>,
lambda: f64
) -> Result<String, String> {
- let args = serde_json::json!({
+ let args_json = serde_json::json!({
"transformed": data,
"lambda": lambda
}).to_string();
- execute_python_script("preprocessing.py", "inverse_boxcox_transform", &args)
+ python::execute_sync(
+ &app,
+ "Analytics/pmdarima_wrapper/preprocessing.py",
+ vec!["--function".to_string(), "inverse_boxcox_transform".to_string(), "--args".to_string(), args_json]
+ )
}
// ==================== DIAGNOSTICS COMMANDS ====================
#[tauri::command]
pub async fn pmdarima_calculate_acf(
+ app: tauri::AppHandle,
data: Vec<f64>,
nlags: Option<i32>
) -> Result<String, String> {
- let args = serde_json::json!({
+ let args_json = serde_json::json!({
"y": data,
"nlags": nlags.unwrap_or(40)
}).to_string();
- execute_python_script("utils.py", "calculate_acf", &args)
+ python::execute_sync(
+ &app,
+ "Analytics/pmdarima_wrapper/utils.py",
+ vec!["--function".to_string(), "calculate_acf".to_string(), "--args".to_string(), args_json]
+ )
}
#[tauri::command]
pub async fn pmdarima_calculate_pacf(
+ app: tauri::AppHandle,
data: Vec<f64>,
nlags: Option<i32>
) -> Result<String, String> {
- let args = serde_json::json!({
+ let args_json = serde_json::json!({
"y": data,
"nlags": nlags.unwrap_or(40)
}).to_string();
- execute_python_script("utils.py", "calculate_pacf", &args)
+ python::execute_sync(
+ &app,
+ "Analytics/pmdarima_wrapper/utils.py",
+ vec!["--function".to_string(), "calculate_pacf".to_string(), "--args".to_string(), args_json]
+ )
}
#[tauri::command]
pub async fn pmdarima_decompose_timeseries(
+ app: tauri::AppHandle,
data: Vec<f64>,
decomp_type: String,
period: i32
) -> Result<String, String> {
- let args = serde_json::json!({
+ let args_json = serde_json::json!({
"y": data,
"type": decomp_type,
"m": period
}).to_string();
- execute_python_script("utils.py", "decompose_timeseries", &args)
+ python::execute_sync(
+ &app,
+ "Analytics/pmdarima_wrapper/utils.py",
+ vec!["--function".to_string(), "decompose_timeseries".to_string(), "--args".to_string(), args_json]
+ )
}
// ==================== MODEL SELECTION COMMANDS ====================
#[tauri::command]
pub async fn pmdarima_cross_validate(
+ app: tauri::AppHandle,
data: Vec<f64>,
p: i32,
d: i32,
q: i32,
cv_splits: i32
) -> Result<String, String> {
- let args = serde_json::json!({
+ let args_json = serde_json::json!({
"y": data,
"order": [p, d, q],
"cv_splits": cv_splits
}).to_string();
- execute_python_script("model_selection.py", "cross_validate_arima", &args)
+ python::execute_sync(
+ &app,
+ "Analytics/pmdarima_wrapper/model_selection.py",
+ vec!["--function".to_string(), "cross_validate_arima".to_string(), "--args".to_string(), args_json]
+ )
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/polygon.rs b/fincept-terminal-desktop/src-tauri/src/commands/polygon.rs
index a64e0c118..b58344aba 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/polygon.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/polygon.rs
@@ -1,7 +1,6 @@
// Polygon.io data commands
use serde::{Deserialize, Serialize};
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
#[derive(Debug, Serialize, Deserialize)]
pub struct PolygonResponse {
@@ -10,7 +9,7 @@ pub struct PolygonResponse {
pub error: Option<String>,
}
-/// Execute Polygon.io Python script command with PyO3
+
#[tauri::command]
pub async fn execute_polygon_command(
app: tauri::AppHandle,
@@ -25,6 +24,5 @@ pub async fn execute_polygon_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- let script_path = get_script_path(&app, "polygon_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "polygon_data.py", cmd_args).await
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/portfolio.rs b/fincept-terminal-desktop/src-tauri/src/commands/portfolio.rs
index 914eaea8d..7326fcb90 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/portfolio.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/portfolio.rs
@@ -1,6 +1,5 @@
// Portfolio Analytics commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
use serde_json::Value;
/// Calculate portfolio metrics
@@ -24,12 +23,10 @@ pub async fn calculate_portfolio_metrics(
args.push(rfr.to_string());
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_analytics.py")?;
-
// Calculate priority: active tab = HIGH (0), inactive = NORMAL (1)
let priority = if is_active_tab.unwrap_or(false) { 0 } else { 1 };
- python_runtime::execute_python_script_async_with_priority(&script_path, args, priority).await
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_analytics.py", args).await
}
/// Optimize portfolio weights
@@ -52,8 +49,7 @@ pub async fn optimize_portfolio(
args.push(rfr.to_string());
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_analytics.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_analytics.py", args).await
}
/// Generate efficient frontier
@@ -76,8 +72,7 @@ pub async fn generate_efficient_frontier(
args.push(rfr.to_string());
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_analytics.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_analytics.py", args).await
}
/// Get portfolio analytics overview
@@ -127,8 +122,7 @@ pub async fn calculate_risk_metrics(
if let Some(w) = weights {
args.push(w);
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_management.py", args).await
}
/// Generate asset allocation plan
@@ -145,8 +139,7 @@ pub async fn generate_asset_allocation(
risk_tolerance,
years_to_retirement.to_string(),
];
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_management.py", args).await
}
/// Calculate retirement planning
@@ -165,8 +158,7 @@ pub async fn calculate_retirement_plan(
current_savings.to_string(),
annual_contribution.to_string(),
];
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_management.py", args).await
}
/// Analyze behavioral biases
@@ -176,8 +168,7 @@ pub async fn analyze_behavioral_biases(
portfolio_data: String,
) -> Result<String, String> {
let args = vec!["behavioral_analysis".to_string(), portfolio_data];
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_management.py", args).await
}
/// Analyze ETF costs
@@ -188,8 +179,7 @@ pub async fn analyze_etf_costs(
expense_ratios: String,
) -> Result<String, String> {
let args = vec!["etf_analysis".to_string(), symbols, expense_ratios];
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_management.py", args).await
}
// ============================================================================
@@ -214,8 +204,7 @@ pub async fn calculate_active_value_added(
args.push(weights);
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/active_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/active_management.py", args).await
}
/// Calculate information ratio analysis
@@ -231,8 +220,7 @@ pub async fn calculate_active_information_ratio(
benchmark_returns,
];
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/active_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/active_management.py", args).await
}
/// Calculate tracking risk analysis
@@ -248,8 +236,7 @@ pub async fn calculate_active_tracking_risk(
benchmark_returns,
];
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/active_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/active_management.py", args).await
}
/// Comprehensive active management analysis
@@ -265,8 +252,7 @@ pub async fn comprehensive_active_analysis(
benchmark_data,
];
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/active_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/active_management.py", args).await
}
/// Manager selection analysis
@@ -277,8 +263,7 @@ pub async fn analyze_manager_selection(
) -> Result<String, String> {
let args = vec!["manager_selection".to_string(), manager_candidates];
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/active_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/active_management.py", args).await
}
// ============================================================================
@@ -305,8 +290,7 @@ pub async fn comprehensive_risk_analysis(
args.push(pv.to_string());
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/risk_management.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/risk_management.py", args).await
}
// ============================================================================
@@ -328,8 +312,7 @@ pub async fn strategic_asset_allocation(
time_horizon.to_string(),
];
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_planning.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_planning.py", args).await
}
/// Retirement planning calculator
@@ -349,8 +332,7 @@ pub async fn calculate_retirement_planning(
annual_contribution.to_string(),
];
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/portfolio_planning.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/portfolio_planning.py", args).await
}
// ============================================================================
@@ -372,8 +354,7 @@ pub async fn comprehensive_economics_analysis(
args.push("{}".to_string());
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/economics_markets.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/economics_markets.py", args).await
}
/// Business cycle analysis
@@ -384,8 +365,7 @@ pub async fn analyze_business_cycle(
) -> Result<String, String> {
let args = vec!["business_cycle_analysis".to_string(), cycle_phase];
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/economics_markets.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/economics_markets.py", args).await
}
/// Equity risk premium analysis
@@ -405,6 +385,5 @@ pub async fn analyze_equity_risk_premium(
}
}
- let script_path = get_script_path(&app, "Analytics/portfolioManagement/economics_markets.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/portfolioManagement/economics_markets.py", args).await
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/portfolio_management.rs b/fincept-terminal-desktop/src-tauri/src/commands/portfolio_management.rs
index af5098111..425a002f2 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/portfolio_management.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/portfolio_management.rs
@@ -109,6 +109,15 @@ pub async fn portfolio_get_assets(portfolio_id: String) -> Result<Vec<Value>, St
operations::get_portfolio_assets(&portfolio_id).map_err(|e| e.to_string())
}
+#[tauri::command]
+pub async fn portfolio_update_asset_symbol(
+ asset_id: String,
+ new_symbol: String,
+) -> Result<(), String> {
+ operations::update_portfolio_asset_symbol(&asset_id, &new_symbol)
+ .map_err(|e| e.to_string())
+}
+
#[tauri::command]
pub async fn portfolio_get_transactions(
portfolio_id: String,
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/pyportfolioopt.rs b/fincept-terminal-desktop/src-tauri/src/commands/pyportfolioopt.rs
index 82abed795..df624dd3a 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/pyportfolioopt.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/pyportfolioopt.rs
@@ -124,17 +124,12 @@ async fn execute_pyportfolioopt_operation(
operation: &str,
data: serde_json::Value,
) -> Result<String, String> {
- let script_path = crate::utils::python::get_script_path(
- &app,
- "Analytics/pyportfolioopt_wrapper/worker_handler.py"
- )?;
-
let data_json = serde_json::to_string(&data)
.map_err(|e| format!("Failed to serialize data: {}", e))?;
let args = vec![operation.to_string(), data_json];
- crate::python_runtime::execute_python_script(&script_path, args)
+ crate::python::execute(&app, "Analytics/pyportfolioopt_wrapper/worker_handler.py", args).await
}
/// Optimize portfolio using PyPortfolioOpt
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/report_generator.rs b/fincept-terminal-desktop/src-tauri/src/commands/report_generator.rs
index a70524632..807576391 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/report_generator.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/report_generator.rs
@@ -81,7 +81,8 @@ pub async fn generate_report_pdf(
file_size: None,
error: Some(format!("Failed to parse template: {}", e)),
};
- return Ok(serde_json::to_string(&result).unwrap());
+ return serde_json::to_string(&result)
+ .map_err(|e| format!("Serialization error: {}", e));
}
};
@@ -94,7 +95,8 @@ pub async fn generate_report_pdf(
file_size: Some(file_size),
error: None,
};
- Ok(serde_json::to_string(&result).unwrap())
+ serde_json::to_string(&result)
+ .map_err(|e| format!("Serialization error: {}", e))
}
Err(e) => {
let result = ReportGenerationResult {
@@ -103,7 +105,8 @@ pub async fn generate_report_pdf(
file_size: None,
error: Some(e),
};
- Ok(serde_json::to_string(&result).unwrap())
+ serde_json::to_string(&result)
+ .map_err(|e| format!("Serialization error: {}", e))
}
}
}
@@ -429,7 +432,8 @@ pub async fn generate_report_html(
"error": null
});
- Ok(serde_json::to_string(&result).unwrap())
+ serde_json::to_string(&result)
+ .map_err(|e| format!("Serialization error: {}", e))
}
fn html_escape(s: &str) -> String {
@@ -448,7 +452,8 @@ pub async fn create_default_report_template() -> Result<String, String> {
"message": "Using built-in Rust PDF generator",
"template_path": null
});
- Ok(serde_json::to_string(&result).unwrap())
+ serde_json::to_string(&result)
+ .map_err(|e| format!("Serialization error: {}", e))
}
/// Open folder in file explorer
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/sec.rs b/fincept-terminal-desktop/src-tauri/src/commands/sec.rs
index 96de20069..772892963 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/sec.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/sec.rs
@@ -1,6 +1,5 @@
// SEC (Securities and Exchange Commission) data commands based on OpenBB sec provider
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute SEC Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_sec_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "sec_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "sec_data.py", cmd_args).await
}
// COMPANY FILINGS COMMANDS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/sentinelhub.rs b/fincept-terminal-desktop/src-tauri/src/commands/sentinelhub.rs
index b88feaae2..32a6abba4 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/sentinelhub.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/sentinelhub.rs
@@ -1,6 +1,5 @@
// Sentinel Hub satellite data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Sentinel Hub Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_sentinelhub_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "sentinelhub_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "sentinelhub_data.py", cmd_args).await
}
/// Get satellite imagery
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rs b/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rs
index 4d35722f2..066eff0b6 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rs
@@ -1,6 +1,5 @@
// skfolio Portfolio Optimization Commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Optimize portfolio using skfolio
#[tauri::command]
@@ -43,11 +42,8 @@ pub async fn skfolio_optimize_portfolio(
println!("[skfolio] All args: {:?}", args);
- let script_path = get_script_path(&app, "Analytics/skfolio_wrapper.py")?;
- println!("[skfolio] Script path: {:?}", script_path);
-
println!("[skfolio] Executing Python script...");
- let result = python_runtime::execute_python_script(&script_path, args);
+ let result = python::execute(&app, "Analytics/skfolio_wrapper.py", args).await;
match &result {
Ok(output) => {
@@ -92,8 +88,7 @@ pub async fn skfolio_hyperparameter_tuning(
args.push("walk_forward".to_string());
}
- let script_path = get_script_path(&app, "Analytics/skfolio_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/skfolio_wrapper.py", args).await
}
/// Run portfolio backtest
@@ -117,8 +112,7 @@ pub async fn skfolio_backtest_strategy(
args.push(cfg);
}
- let script_path = get_script_path(&app, "Analytics/skfolio_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/skfolio_wrapper.py", args).await
}
/// Perform stress testing
@@ -144,8 +138,7 @@ pub async fn skfolio_stress_test(
args.push(n_simulations.unwrap_or(10000).to_string());
- let script_path = get_script_path(&app, "Analytics/skfolio_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/skfolio_wrapper.py", args).await
}
/// Generate efficient frontier
@@ -177,11 +170,8 @@ pub async fn skfolio_efficient_frontier(
println!("[skfolio] All args: {:?}", args);
- let script_path = get_script_path(&app, "Analytics/skfolio_wrapper.py")?;
- println!("[skfolio] Script path: {:?}", script_path);
-
println!("[skfolio] Executing Python script...");
- let result = python_runtime::execute_python_script(&script_path, args);
+ let result = python::execute(&app, "Analytics/skfolio_wrapper.py", args).await;
match &result {
Ok(output) => {
@@ -214,8 +204,7 @@ pub async fn skfolio_risk_attribution(
weights,
];
- let script_path = get_script_path(&app, "Analytics/skfolio_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/skfolio_wrapper.py", args).await
}
/// Compare multiple strategies
@@ -234,8 +223,7 @@ pub async fn skfolio_compare_strategies(
args.push(metric.unwrap_or_else(|| "sharpe_ratio".to_string()));
- let script_path = get_script_path(&app, "Analytics/skfolio_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/skfolio_wrapper.py", args).await
}
/// Generate comprehensive portfolio report
@@ -256,8 +244,7 @@ pub async fn skfolio_generate_report(
args.push(cfg);
}
- let script_path = get_script_path(&app, "Analytics/skfolio_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/skfolio_wrapper.py", args).await
}
/// Export portfolio weights
@@ -278,8 +265,7 @@ pub async fn skfolio_export_weights(
args.push(fname);
}
- let script_path = get_script_path(&app, "Analytics/skfolio_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/skfolio_wrapper.py", args).await
}
/// Scenario analysis
@@ -297,6 +283,5 @@ pub async fn skfolio_scenario_analysis(
scenarios,
];
- let script_path = get_script_path(&app, "Analytics/skfolio_wrapper.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ python::execute(&app, "Analytics/skfolio_wrapper.py", args).await
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/spain_data.rs b/fincept-terminal-desktop/src-tauri/src/commands/spain_data.rs
index b10b04df5..90255f48d 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/spain_data.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/spain_data.rs
@@ -1,6 +1,5 @@
// Spanish economic data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Spain data Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_spain_data_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "spain_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "spain_data.py", cmd_args).await
}
/// Get Spanish economic indicators
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/swiss_gov.rs b/fincept-terminal-desktop/src-tauri/src/commands/swiss_gov.rs
index f6885ec2a..fbc8856af 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/swiss_gov.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/swiss_gov.rs
@@ -1,6 +1,5 @@
// Swiss Government data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Swiss Government Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_swiss_gov_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "swiss_gov_api.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "swiss_gov_api.py", cmd_args).await
}
/// Search Swiss government datasets
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/technical_analysis.rs b/fincept-terminal-desktop/src-tauri/src/commands/technical_analysis.rs
index 900e6572c..b79fb5893 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/technical_analysis.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/technical_analysis.rs
@@ -1,5 +1,4 @@
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
use tauri::AppHandle;
/// Execute technical analysis Python script
@@ -35,21 +34,8 @@ pub async fn execute_technical_analysis_command(
let mut cmd_args = vec![command.clone()];
cmd_args.extend(args);
- // Get script path
- let script_name = "technicals/technical_analysis.py";
- let script_path = get_script_path(&app, script_name)
- .map_err(|e| format!("Failed to locate script: {}", e))?;
-
- // Verify script exists
- if !script_path.exists() {
- return Err(format!(
- "Technical analysis script not found at: {}",
- script_path.display()
- ));
- }
-
- // Execute Python command with PyO3
- match python_runtime::execute_python_script(&script_path, cmd_args) {
+ // Execute Python script
+ match python::execute(&app, "technicals/technical_analysis.py", cmd_args).await {
Ok(output) => {
// Check if output contains error JSON
if output.contains("\"error\"") {
@@ -117,22 +103,9 @@ pub async fn compute_all_technicals(
app: AppHandle,
historical_data: String,
) -> Result<String, String> {
- // Get script path for compute_technicals.py
- let script_name = "compute_technicals.py";
- let script_path = get_script_path(&app, script_name)
- .map_err(|e| format!("Failed to locate script: {}", e))?;
-
- // Verify script exists
- if !script_path.exists() {
- return Err(format!(
- "Compute technicals script not found at: {}",
- script_path.display()
- ));
- }
-
- // Execute Python command with historical data as argument with PyO3
+ // Execute Python script for compute_technicals.py
let cmd_args = vec![historical_data];
- match python_runtime::execute_python_script(&script_path, cmd_args) {
+ match python::execute(&app, "compute_technicals.py", cmd_args).await {
Ok(output) => {
// Check if output contains error JSON
if output.contains("\"success\":false") || output.contains("\"error\"") {
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/trading_economics.rs b/fincept-terminal-desktop/src-tauri/src/commands/trading_economics.rs
index 40383c6d9..e2840d228 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/trading_economics.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/trading_economics.rs
@@ -1,6 +1,5 @@
// Trading Economics data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute Trading Economics Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_trading_economics_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "trading_economics_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "trading_economics_data.py", cmd_args).await
}
/// Get economic indicators for a country
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/unesco.rs b/fincept-terminal-desktop/src-tauri/src/commands/unesco.rs
index 295f7cd1c..de6c4c0f6 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/unesco.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/unesco.rs
@@ -1,4 +1,4 @@
-use crate::utils::python::execute_python_script_simple;
+use crate::python;
use tauri::command;
// ==================== DATA ENDPOINTS ====================
@@ -15,65 +15,53 @@ pub async fn unesco_get_indicator_data(
indicator_metadata: Option<bool>,
version: Option<String>
) -> Result<String, String> {
- let mut args = vec!["indicator_data"];
+ let mut args = vec!["indicator_data".to_string()];
- let indicator_strs: Vec<String>;
if let Some(indicators) = indicators {
- indicator_strs = indicators;
- for indicator in &indicator_strs {
- args.push(indicator.as_str());
+ for indicator in indicators {
+ args.push(indicator);
}
}
- let geo_unit_strs: Vec<String>;
if let Some(geo_units) = geo_units {
- geo_unit_strs = geo_units;
- for geo_unit in &geo_unit_strs {
- args.push(geo_unit.as_str());
+ for geo_unit in geo_units {
+ args.push(geo_unit);
}
}
- let geo_unit_type_str;
if let Some(gut) = geo_unit_type {
- geo_unit_type_str = gut;
- args.push("--geo-unit-type");
- args.push(&geo_unit_type_str);
+ args.push("--geo-unit-type".to_string());
+ args.push(gut);
}
- let start_year_str;
if let Some(sy) = start_year {
- start_year_str = sy.to_string();
- args.push("--start-year");
- args.push(&start_year_str);
+ args.push("--start-year".to_string());
+ args.push(sy.to_string());
}
- let end_year_str;
if let Some(ey) = end_year {
- end_year_str = ey.to_string();
- args.push("--end-year");
- args.push(&end_year_str);
+ args.push("--end-year".to_string());
+ args.push(ey.to_string());
}
if let Some(footnotes) = footnotes {
if footnotes {
- args.push("--footnotes");
+ args.push("--footnotes".to_string());
}
}
if let Some(indicator_metadata) = indicator_metadata {
if indicator_metadata {
- args.push("--metadata");
+ args.push("--metadata".to_string());
}
}
- let version_str;
if let Some(v) = version {
- version_str = v;
- args.push("--version");
- args.push(&version_str);
+ args.push("--version".to_string());
+ args.push(v);
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
#[command]
@@ -89,93 +77,77 @@ pub async fn unesco_export_indicator_data(
indicator_metadata: Option<bool>,
version: Option<String>
) -> Result<String, String> {
- let mut args = vec!["export_indicator_data", &format_type];
+ let mut args = vec!["export_indicator_data".to_string(), format_type];
- let indicator_strs: Vec<String>;
if let Some(indicators) = indicators {
- indicator_strs = indicators;
- for indicator in &indicator_strs {
- args.push(indicator.as_str());
+ for indicator in indicators {
+ args.push(indicator);
}
}
- let geo_unit_strs: Vec<String>;
if let Some(geo_units) = geo_units {
- geo_unit_strs = geo_units;
- for geo_unit in &geo_unit_strs {
- args.push(geo_unit.as_str());
+ for geo_unit in geo_units {
+ args.push(geo_unit);
}
}
- let geo_unit_type_str;
if let Some(gut) = geo_unit_type {
- geo_unit_type_str = gut;
- args.push("--geo-unit-type");
- args.push(&geo_unit_type_str);
+ args.push("--geo-unit-type".to_string());
+ args.push(gut);
}
- let start_year_str;
if let Some(sy) = start_year {
- start_year_str = sy.to_string();
- args.push("--start-year");
- args.push(&start_year_str);
+ args.push("--start-year".to_string());
+ args.push(sy.to_string());
}
- let end_year_str;
if let Some(ey) = end_year {
- end_year_str = ey.to_string();
- args.push("--end-year");
- args.push(&end_year_str);
+ args.push("--end-year".to_string());
+ args.push(ey.to_string());
}
if let Some(footnotes) = footnotes {
if footnotes {
- args.push("--footnotes");
+ args.push("--footnotes".to_string());
}
}
if let Some(indicator_metadata) = indicator_metadata {
if indicator_metadata {
- args.push("--metadata");
+ args.push("--metadata".to_string());
}
}
- let version_str;
if let Some(v) = version {
- version_str = v;
- args.push("--version");
- args.push(&version_str);
+ args.push("--version".to_string());
+ args.push(v);
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
// ==================== DEFINITIONS ENDPOINTS ====================
#[command]
pub async fn unesco_list_geo_units(app: tauri::AppHandle, version: Option<String>) -> Result<String, String> {
- let mut args = vec!["list_geo_units"];
+ let mut args = vec!["list_geo_units".to_string()];
- let version_str;
if let Some(v) = version {
- version_str = v;
- args.push(&version_str);
+ args.push(v);
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
#[command]
pub async fn unesco_export_geo_units(app: tauri::AppHandle, format_type: String, version: Option<String>) -> Result<String, String> {
- let mut args = vec!["export_geo_units", &format_type];
+ let mut args = vec!["export_geo_units".to_string(), format_type];
- let version_str;
if let Some(v) = version {
- version_str = v;
- args.push(&version_str);
+ args.push(v);
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
#[command]
@@ -185,28 +157,26 @@ pub async fn unesco_list_indicators(
disaggregations: Option<bool>,
version: Option<String>
) -> Result<String, String> {
- let mut args = vec!["list_indicators"];
+ let mut args = vec!["list_indicators".to_string()];
if let Some(glossary_terms) = glossary_terms {
if glossary_terms {
- args.push("--glossary");
+ args.push("--glossary".to_string());
}
}
if let Some(disaggregations) = disaggregations {
if disaggregations {
- args.push("--disaggregations");
+ args.push("--disaggregations".to_string());
}
}
- let version_str;
if let Some(v) = version {
- version_str = v;
- args.push("--version");
- args.push(&version_str);
+ args.push("--version".to_string());
+ args.push(v);
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
#[command]
@@ -217,40 +187,38 @@ pub async fn unesco_export_indicators(
disaggregations: Option<bool>,
version: Option<String>
) -> Result<String, String> {
- let mut args = vec!["export_indicators", &format_type];
+ let mut args = vec!["export_indicators".to_string(), format_type];
if let Some(glossary_terms) = glossary_terms {
if glossary_terms {
- args.push("--glossary");
+ args.push("--glossary".to_string());
}
}
if let Some(disaggregations) = disaggregations {
if disaggregations {
- args.push("--disaggregations");
+ args.push("--disaggregations".to_string());
}
}
- let version_str;
if let Some(v) = version {
- version_str = v;
- args.push("--version");
- args.push(&version_str);
+ args.push("--version".to_string());
+ args.push(v);
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
// ==================== VERSION ENDPOINTS ====================
#[command]
pub async fn unesco_get_default_version(app: tauri::AppHandle) -> Result<String, String> {
- execute_python_script_simple(&app, "unesco_data.py", &["get_default_version"])
+ python::execute_sync(&app, "unesco_data.py", vec!["get_default_version".to_string()])
}
#[command]
pub async fn unesco_list_versions(app: tauri::AppHandle) -> Result<String, String> {
- execute_python_script_simple(&app, "unesco_data.py", &["list_versions"])
+ python::execute_sync(&app, "unesco_data.py", vec!["list_versions".to_string()])
}
// ==================== CONVENIENCE METHODS ====================
@@ -262,31 +230,25 @@ pub async fn unesco_get_education_overview(
start_year: Option<i32>,
end_year: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["education_overview"];
+ let mut args = vec!["education_overview".to_string()];
- let country_code_strs: Vec<String>;
if let Some(country_codes) = country_codes {
- country_code_strs = country_codes;
- for country in &country_code_strs {
- args.push(country.as_str());
+ for country in country_codes {
+ args.push(country);
}
}
- let start_year_str;
if let Some(sy) = start_year {
- start_year_str = sy.to_string();
- args.push("--start-year");
- args.push(&start_year_str);
+ args.push("--start-year".to_string());
+ args.push(sy.to_string());
}
- let end_year_str;
if let Some(ey) = end_year {
- end_year_str = ey.to_string();
- args.push("--end-year");
- args.push(&end_year_str);
+ args.push("--end-year".to_string());
+ args.push(ey.to_string());
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
#[command]
@@ -296,29 +258,23 @@ pub async fn unesco_get_global_education_trends(
start_year: Option<i32>,
end_year: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["global_trends"];
+ let mut args = vec!["global_trends".to_string()];
- let indicator_code_str;
if let Some(ic) = indicator_code {
- indicator_code_str = ic;
- args.push(&indicator_code_str);
+ args.push(ic);
}
- let start_year_str;
if let Some(sy) = start_year {
- start_year_str = sy.to_string();
- args.push("--start-year");
- args.push(&start_year_str);
+ args.push("--start-year".to_string());
+ args.push(sy.to_string());
}
- let end_year_str;
if let Some(ey) = end_year {
- end_year_str = ey.to_string();
- args.push("--end-year");
- args.push(&end_year_str);
+ args.push("--end-year".to_string());
+ args.push(ey.to_string());
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
#[command]
@@ -329,27 +285,23 @@ pub async fn unesco_get_country_comparison(
start_year: Option<i32>,
end_year: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["country_comparison", &indicator_code];
+ let mut args = vec!["country_comparison".to_string(), indicator_code];
- for country in &country_codes {
- args.push(country.as_str());
+ for country in country_codes {
+ args.push(country);
}
- let start_year_str;
if let Some(sy) = start_year {
- start_year_str = sy.to_string();
- args.push("--start-year");
- args.push(&start_year_str);
+ args.push("--start-year".to_string());
+ args.push(sy.to_string());
}
- let end_year_str;
if let Some(ey) = end_year {
- end_year_str = ey.to_string();
- args.push("--end-year");
- args.push(&end_year_str);
+ args.push("--end-year".to_string());
+ args.push(ey.to_string());
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
#[command]
@@ -358,15 +310,13 @@ pub async fn unesco_search_indicators_by_theme(
theme: String,
limit: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["search_by_theme", &theme];
+ let mut args = vec!["search_by_theme".to_string(), theme];
- let limit_str;
if let Some(lim) = limit {
- limit_str = lim.to_string();
- args.push(&limit_str);
+ args.push(lim.to_string());
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
#[command]
@@ -377,31 +327,25 @@ pub async fn unesco_get_regional_education_data(
start_year: Option<i32>,
end_year: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["regional_data", &region_id];
+ let mut args = vec!["regional_data".to_string(), region_id];
- let indicator_code_strs: Vec<String>;
if let Some(indicator_codes) = indicator_codes {
- indicator_code_strs = indicator_codes;
- for indicator in &indicator_code_strs {
- args.push(indicator.as_str());
+ for indicator in indicator_codes {
+ args.push(indicator);
}
}
- let start_year_str;
if let Some(sy) = start_year {
- start_year_str = sy.to_string();
- args.push("--start-year");
- args.push(&start_year_str);
+ args.push("--start-year".to_string());
+ args.push(sy.to_string());
}
- let end_year_str;
if let Some(ey) = end_year {
- end_year_str = ey.to_string();
- args.push("--end-year");
- args.push(&end_year_str);
+ args.push("--end-year".to_string());
+ args.push(ey.to_string());
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
#[command]
@@ -411,31 +355,25 @@ pub async fn unesco_get_science_technology_data(
start_year: Option<i32>,
end_year: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["sti_data"];
+ let mut args = vec!["sti_data".to_string()];
- let country_code_strs: Vec<String>;
if let Some(country_codes) = country_codes {
- country_code_strs = country_codes;
- for country in &country_code_strs {
- args.push(country.as_str());
+ for country in country_codes {
+ args.push(country);
}
}
- let start_year_str;
if let Some(sy) = start_year {
- start_year_str = sy.to_string();
- args.push("--start-year");
- args.push(&start_year_str);
+ args.push("--start-year".to_string());
+ args.push(sy.to_string());
}
- let end_year_str;
if let Some(ey) = end_year {
- end_year_str = ey.to_string();
- args.push("--end-year");
- args.push(&end_year_str);
+ args.push("--end-year".to_string());
+ args.push(ey.to_string());
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
#[command]
@@ -445,31 +383,25 @@ pub async fn unesco_get_culture_data(
start_year: Option<i32>,
end_year: Option<i32>
) -> Result<String, String> {
- let mut args = vec!["culture_data"];
+ let mut args = vec!["culture_data".to_string()];
- let country_code_strs: Vec<String>;
if let Some(country_codes) = country_codes {
- country_code_strs = country_codes;
- for country in &country_code_strs {
- args.push(country.as_str());
+ for country in country_codes {
+ args.push(country);
}
}
- let start_year_str;
if let Some(sy) = start_year {
- start_year_str = sy.to_string();
- args.push("--start-year");
- args.push(&start_year_str);
+ args.push("--start-year".to_string());
+ args.push(sy.to_string());
}
- let end_year_str;
if let Some(ey) = end_year {
- end_year_str = ey.to_string();
- args.push("--end-year");
- args.push(&end_year_str);
+ args.push("--end-year".to_string());
+ args.push(ey.to_string());
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
#[command]
@@ -479,13 +411,13 @@ pub async fn unesco_export_country_dataset(
format_type: String,
include_metadata: Option<bool>
) -> Result<String, String> {
- let mut args = vec!["export_country_dataset", &country_code, &format_type];
+ let mut args = vec!["export_country_dataset".to_string(), country_code, format_type];
if let Some(include_metadata) = include_metadata {
if include_metadata {
- args.push("--metadata");
+ args.push("--metadata".to_string());
}
}
- execute_python_script_simple(&app, "unesco_data.py", &args)
+ python::execute_sync(&app, "unesco_data.py", args)
}
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/wits.rs b/fincept-terminal-desktop/src-tauri/src/commands/wits.rs
index 6f0467306..5d66f64ff 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/wits.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/wits.rs
@@ -1,6 +1,5 @@
// WITS (World Integrated Trade Solution) data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute WITS Python script command
#[tauri::command]
@@ -13,7 +12,6 @@ pub async fn execute_wits_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "wits_trade_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "wits_trade_data.py", cmd_args).await
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/worldbank.rs b/fincept-terminal-desktop/src-tauri/src/commands/worldbank.rs
index 2bb69b1da..a6bf0568c 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/worldbank.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/worldbank.rs
@@ -1,6 +1,5 @@
// World Bank data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute World Bank Python script command
#[tauri::command]
@@ -13,9 +12,8 @@ pub async fn execute_worldbank_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "worldbank_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+
+ python::execute(&app, "worldbank_data.py", cmd_args).await
}
/// Get World Bank indicator data
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/wto.rs b/fincept-terminal-desktop/src-tauri/src/commands/wto.rs
index 0d132feb9..95192bd4a 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/wto.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/wto.rs
@@ -1,6 +1,5 @@
// WTO (World Trade Organization) data commands based on WTO APIs
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::python;
/// Execute WTO Python script command
#[tauri::command]
@@ -13,9 +12,7 @@ pub async fn execute_wto_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "wto_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ python::execute(&app, "wto_data.py", cmd_args).await
}
// REFERENCE AND OVERVIEW COMMANDS
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rs b/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rs
index ab1821339..3d6022496 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rs
@@ -1,5 +1,5 @@
// Yahoo Finance data commands
-use crate::utils::python::execute_python_subprocess;
+use crate::python;
/// Execute Yahoo Finance Python script command via subprocess
/// Uses direct subprocess instead of worker pool to avoid deadlocks on Windows
@@ -14,10 +14,5 @@ pub async fn execute_yfinance_command(
cmd_args.extend(args);
// Execute Python script via subprocess (avoids worker pool deadlocks)
- execute_python_subprocess(
- &app,
- "yfinance_data.py",
- &cmd_args,
- None, // Uses default venv (venv-numpy2)
- )
+ python::execute_sync(&app, "yfinance_data.py", cmd_args)
}
diff --git a/fincept-terminal-desktop/src-tauri/src/data_sources/yfinance.rs b/fincept-terminal-desktop/src-tauri/src/data_sources/yfinance.rs
index 6b91d6f03..2a6ac9217 100644
--- a/fincept-terminal-desktop/src-tauri/src/data_sources/yfinance.rs
+++ b/fincept-terminal-desktop/src-tauri/src/data_sources/yfinance.rs
@@ -1,17 +1,9 @@
// YFinance data source wrapper using Python yfinance
// Modular design: if this fails, app continues working with other data sources
+// Refactored to use unified python module API
use serde::{Deserialize, Serialize};
use anyhow::{Result, Context};
-use std::process::Command;
-use std::path::PathBuf;
-
-// Windows-specific imports to hide console windows
-#[cfg(target_os = "windows")]
-use std::os::windows::process::CommandExt;
-
-#[cfg(target_os = "windows")]
-const CREATE_NO_WINDOW: u32 = 0x08000000;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuoteData {
@@ -40,21 +32,14 @@ pub struct HistoricalData {
}
pub struct YFinanceProvider {
- python_path: PathBuf,
- script_path: PathBuf,
+ app: tauri::AppHandle,
}
impl YFinanceProvider {
/// Create a new YFinance provider instance with runtime paths
pub fn new(app: &tauri::AppHandle) -> Result<Self> {
- let python_path = crate::utils::python::get_python_path(app)
- .map_err(|e| anyhow::anyhow!(e))?;
- let script_path = crate::utils::python::get_script_path(app, "yfinance_data.py")
- .map_err(|e| anyhow::anyhow!(e))?;
-
Ok(Self {
- python_path,
- script_path,
+ app: app.clone(),
})
}
@@ -84,28 +69,13 @@ impl YFinanceProvider {
/// Internal batch fetch method - calls Python yfinance script with multiple symbols
async fn fetch_batch_quotes(&self, symbols: Vec<String>) -> Result<Vec<QuoteData>> {
- let mut cmd = Command::new(&self.python_path);
- cmd.arg(&self.script_path).arg("batch_quotes");
+ let mut args = vec!["batch_quotes".to_string()];
+ args.extend(symbols);
- for symbol in symbols {
- cmd.arg(symbol);
- }
-
- // Hide console window on Windows
- #[cfg(target_os = "windows")]
- cmd.creation_flags(CREATE_NO_WINDOW);
-
- let output = cmd
- .output()
- .context("Failed to execute Python script")?;
-
- if !output.status.success() {
- let error = String::from_utf8_lossy(&output.stderr);
- anyhow::bail!("Python script failed: {}", error);
- }
+ let output = crate::python::execute_sync(&self.app, "yfinance_data.py", args)
+ .map_err(|e| anyhow::anyhow!(e))?;
- let json_output = String::from_utf8_lossy(&output.stdout);
- let quotes: Vec<QuoteData> = serde_json::from_str(&json_output)
+ let quotes: Vec<QuoteData> = serde_json::from_str(&output)
.context("Failed to parse JSON from Python script")?;
Ok(quotes)
@@ -113,26 +83,12 @@ impl YFinanceProvider {
/// Internal fetch method - calls Python yfinance script
async fn fetch_quote(&self, symbol: &str) -> Result<QuoteData> {
- let mut cmd = Command::new(&self.python_path);
- cmd.arg(&self.script_path)
- .arg("quote")
- .arg(symbol);
-
- // Hide console window on Windows
- #[cfg(target_os = "windows")]
- cmd.creation_flags(CREATE_NO_WINDOW);
-
- let output = cmd
- .output()
- .context("Failed to execute Python script")?;
-
- if !output.status.success() {
- let error = String::from_utf8_lossy(&output.stderr);
- anyhow::bail!("Python script failed: {}", error);
- }
+ let args = vec!["quote".to_string(), symbol.to_string()];
+
+ let output = crate::python::execute_sync(&self.app, "yfinance_data.py", args)
+ .map_err(|e| anyhow::anyhow!(e))?;
- let json_output = String::from_utf8_lossy(&output.stdout);
- let quote: QuoteData = serde_json::from_str(&json_output)
+ let quote: QuoteData = serde_json::from_str(&output)
.context("Failed to parse JSON from Python script")?;
Ok(quote)
@@ -162,28 +118,17 @@ impl YFinanceProvider {
start_date: &str,
end_date: &str,
) -> Result<Vec<HistoricalData>> {
- let mut cmd = Command::new(&self.python_path);
- cmd.arg(&self.script_path)
- .arg("historical")
- .arg(symbol)
- .arg(start_date)
- .arg(end_date);
-
- // Hide console window on Windows
- #[cfg(target_os = "windows")]
- cmd.creation_flags(CREATE_NO_WINDOW);
-
- let output = cmd
- .output()
- .context("Failed to execute Python script")?;
-
- if !output.status.success() {
- let error = String::from_utf8_lossy(&output.stderr);
- anyhow::bail!("Python script failed: {}", error);
- }
+ let args = vec![
+ "historical".to_string(),
+ symbol.to_string(),
+ start_date.to_string(),
+ end_date.to_string(),
+ ];
+
+ let output = crate::python::execute_sync(&self.app, "yfinance_data.py", args)
+ .map_err(|e| anyhow::anyhow!(e))?;
- let json_output = String::from_utf8_lossy(&output.stdout);
- let historical: Vec<HistoricalData> = serde_json::from_str(&json_output)
+ let historical: Vec<HistoricalData> = serde_json::from_str(&output)
.context("Failed to parse JSON from Python script")?;
Ok(historical)
@@ -241,26 +186,12 @@ impl YFinanceProvider {
/// Internal info fetch method - calls Python yfinance script
async fn fetch_info(&self, symbol: &str) -> Result<serde_json::Value> {
- let mut cmd = Command::new(&self.python_path);
- cmd.arg(&self.script_path)
- .arg("info")
- .arg(symbol);
-
- // Hide console window on Windows
- #[cfg(target_os = "windows")]
- cmd.creation_flags(CREATE_NO_WINDOW);
-
- let output = cmd
- .output()
- .context("Failed to execute Python script")?;
-
- if !output.status.success() {
- let error = String::from_utf8_lossy(&output.stderr);
- anyhow::bail!("Python script failed: {}", error);
- }
+ let args = vec!["info".to_string(), symbol.to_string()];
- let json_output = String::from_utf8_lossy(&output.stdout);
- let info: serde_json::Value = serde_json::from_str(&json_output)
+ let output = crate::python::execute_sync(&self.app, "yfinance_data.py", args)
+ .map_err(|e| anyhow::anyhow!(e))?;
+
+ let info: serde_json::Value = serde_json::from_str(&output)
.context("Failed to parse JSON from Python script")?;
Ok(info)
@@ -276,26 +207,12 @@ impl YFinanceProvider {
/// Internal financials fetch method - calls Python yfinance script
async fn fetch_financials(&self, symbol: &str) -> Result<serde_json::Value> {
- let mut cmd = Command::new(&self.python_path);
- cmd.arg(&self.script_path)
- .arg("financials")
- .arg(symbol);
-
- // Hide console window on Windows
- #[cfg(target_os = "windows")]
- cmd.creation_flags(CREATE_NO_WINDOW);
-
- let output = cmd
- .output()
- .context("Failed to execute Python script")?;
-
- if !output.status.success() {
- let error = String::from_utf8_lossy(&output.stderr);
- anyhow::bail!("Python script failed: {}", error);
- }
+ let args = vec!["financials".to_string(), symbol.to_string()];
+
+ let output = crate::python::execute_sync(&self.app, "yfinance_data.py", args)
+ .map_err(|e| anyhow::anyhow!(e))?;
- let json_output = String::from_utf8_lossy(&output.stdout);
- let financials: serde_json::Value = serde_json::from_str(&json_output)
+ let financials: serde_json::Value = serde_json::from_str(&output)
.context("Failed to parse JSON from Python script")?;
Ok(financials)
diff --git a/fincept-terminal-desktop/src-tauri/src/database/operations.rs b/fincept-terminal-desktop/src-tauri/src/database/operations.rs
index 0e5decc7b..88d13ff82 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/operations.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/operations.rs
@@ -843,6 +843,18 @@ pub fn get_portfolio_assets(portfolio_id: &str) -> Result<Vec<serde_json::Value>
Ok(assets)
}
+pub fn update_portfolio_asset_symbol(asset_id: &str, new_symbol: &str) -> Result<()> {
+ let pool = get_pool()?;
+ let conn = pool.get()?;
+
+ conn.execute(
+ "UPDATE portfolio_assets SET symbol = ?1, last_updated = CURRENT_TIMESTAMP WHERE id = ?2",
+ params![new_symbol, asset_id],
+ )?;
+
+ Ok(())
+}
+
pub fn get_portfolio_transactions(portfolio_id: &str, limit: Option<i32>) -> Result<Vec<serde_json::Value>> {
let pool = get_pool()?;
let conn = pool.get()?;
diff --git a/fincept-terminal-desktop/src-tauri/src/database/queries.rs b/fincept-terminal-desktop/src-tauri/src/database/queries.rs
index 16413885c..5f0388506 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/queries.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/queries.rs
@@ -75,6 +75,68 @@ pub fn delete_mcp_server(id: &str) -> Result<()> {
Ok(())
}
+// ============================================================================
+// Internal MCP Tool Settings Operations
+// ============================================================================
+
+pub fn get_internal_tool_settings() -> Result<Vec<InternalMCPToolSetting>> {
+ let pool = get_pool()?;
+ let conn = pool.get()?;
+
+ let mut stmt = conn.prepare(
+ "SELECT tool_name, category, is_enabled, updated_at
+ FROM internal_mcp_tool_settings ORDER BY category, tool_name"
+ )?;
+
+ let settings = stmt
+ .query_map([], |row| {
+ Ok(InternalMCPToolSetting {
+ tool_name: row.get(0)?,
+ category: row.get(1)?,
+ is_enabled: row.get::<_, i32>(2)? != 0,
+ updated_at: row.get(3)?,
+ })
+ })?
+ .collect::<std::result::Result<Vec<_>, _>>()?;
+
+ Ok(settings)
+}
+
+pub fn set_internal_tool_enabled(tool_name: &str, category: &str, is_enabled: bool) -> Result<()> {
+ let pool = get_pool()?;
+ let conn = pool.get()?;
+
+ conn.execute(
+ "INSERT OR REPLACE INTO internal_mcp_tool_settings
+ (tool_name, category, is_enabled, updated_at)
+ VALUES (?1, ?2, ?3, CURRENT_TIMESTAMP)",
+ params![
+ tool_name,
+ category,
+ if is_enabled { 1 } else { 0 },
+ ],
+ )?;
+
+ Ok(())
+}
+
+pub fn is_internal_tool_enabled(tool_name: &str) -> Result<bool> {
+ let pool = get_pool()?;
+ let conn = pool.get()?;
+
+ let result: Result<i32, rusqlite::Error> = conn.query_row(
+ "SELECT is_enabled FROM internal_mcp_tool_settings WHERE tool_name = ?1",
+ params![tool_name],
+ |row| row.get(0),
+ );
+
+ match result {
+ Ok(enabled) => Ok(enabled != 0),
+ Err(rusqlite::Error::QueryReturnedNoRows) => Ok(true), // Default to enabled if not in table
+ Err(e) => Err(e.into()),
+ }
+}
+
// ============================================================================
// Backtesting Operations
// ============================================================================
diff --git a/fincept-terminal-desktop/src-tauri/src/database/schema.rs b/fincept-terminal-desktop/src-tauri/src/database/schema.rs
index be1f35122..06208a848 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/schema.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/schema.rs
@@ -355,6 +355,14 @@ pub fn create_schema(conn: &Connection) -> Result<()> {
timestamp TEXT DEFAULT CURRENT_TIMESTAMP
);
+ -- Internal MCP tool settings (for fincept-terminal built-in tools)
+ CREATE TABLE IF NOT EXISTS internal_mcp_tool_settings (
+ tool_name TEXT PRIMARY KEY,
+ category TEXT NOT NULL,
+ is_enabled INTEGER DEFAULT 1,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ );
+
-- OLD: market_data_cache table REMOVED - Use unified cache (fincept_cache.db)
-- Data source connections table
diff --git a/fincept-terminal-desktop/src-tauri/src/database/types.rs b/fincept-terminal-desktop/src-tauri/src/database/types.rs
index 2d78b55e2..0ae8db93b 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/types.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/types.rs
@@ -181,6 +181,14 @@ pub struct MCPTool {
pub created_at: String,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct InternalMCPToolSetting {
+ pub tool_name: String,
+ pub category: String,
+ pub is_enabled: bool,
+ pub updated_at: String,
+}
+
// ============================================================================
// Context Recorder
// ============================================================================
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index a75c0b963..ba5c1d0b2 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -17,10 +17,8 @@ mod commands;
mod utils;
mod setup;
mod database;
-mod python_runtime;
-mod worker_pool;
+mod python;
mod websocket;
-mod barter_integration;
mod services;
mod paper_trading;
@@ -83,7 +81,7 @@ fn spawn_mcp_server(
// Determine if we should use bundled Bun (for npx/bunx commands)
let (fixed_command, fixed_args) = if command == "npx" || command == "bunx" {
// Try to get bundled Bun path
- match utils::python::get_bundled_bun_path(&app) {
+ match python::get_bun_path(&app) {
Ok(bun_path) => {
// Use 'bun x' which is equivalent to 'bunx' or 'npx'
let mut new_args = vec!["x".to_string()];
@@ -606,21 +604,9 @@ async fn execute_python_script(
app: tauri::AppHandle,
script_name: String,
args: Vec<String>,
- env: std::collections::HashMap<String, String>,
+ _env: std::collections::HashMap<String, String>,
) -> Result<String, String> {
- let script_path = utils::python::get_script_path(&app, &script_name)?;
-
- if !script_path.exists() {
- return Err(format!("Script not found at: {:?}", script_path));
- }
-
- // Use worker pool (persistent Python processes) - no new subprocess per call
- worker_pool::execute_python_script_with_priority(
- script_path,
- args,
- "venv-numpy2",
- 1, // NORMAL priority
- ).await
+ python::execute(&app, &script_name, args).await
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
@@ -659,11 +645,6 @@ pub fn run() {
services: services.clone(),
};
- // Initialize Barter trading system (Paper mode by default)
- let barter_state = barter_integration::commands::BarterState::new(
- barter_integration::types::TradingMode::Paper
- );
-
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_shell::init())
@@ -677,7 +658,6 @@ pub fn run() {
processes: Mutex::new(HashMap::new()),
})
.manage(ws_state)
- .manage(barter_state)
.setup(move |app| {
// CRITICAL: Set app handle for router to emit WebSocket events to frontend
let app_handle = app.handle().clone();
@@ -1374,6 +1354,7 @@ pub fn run() {
commands::portfolio_management::portfolio_add_asset,
commands::portfolio_management::portfolio_sell_asset,
commands::portfolio_management::portfolio_get_assets,
+ commands::portfolio_management::portfolio_update_asset_symbol,
commands::portfolio_management::portfolio_get_transactions,
// Portfolio Analytics
commands::portfolio::calculate_portfolio_metrics,
@@ -1396,7 +1377,6 @@ pub fn run() {
commands::skfolio::skfolio_generate_report,
commands::skfolio::skfolio_export_weights,
commands::skfolio::skfolio_scenario_analysis,
- // PyPortfolioOpt - Portfolio Optimization with PyO3
commands::pyportfolioopt::pyportfolioopt_optimize,
commands::pyportfolioopt::pyportfolioopt_efficient_frontier,
commands::pyportfolioopt::pyportfolioopt_discrete_allocation,
@@ -1548,31 +1528,6 @@ pub fn run() {
commands::backtesting::create_directory,
commands::backtesting::write_file,
commands::backtesting::read_file,
- // Barter Trading Commands
- barter_integration::start_market_stream,
- barter_integration::stop_market_stream,
- barter_integration::get_active_streams,
- barter_integration::subscribe_symbols,
- barter_integration::unsubscribe_symbols,
- barter_integration::submit_order,
- barter_integration::cancel_order,
- barter_integration::get_order,
- barter_integration::get_all_orders,
- barter_integration::get_open_orders,
- barter_integration::get_positions,
- barter_integration::get_position,
- barter_integration::get_balances,
- barter_integration::close_all_positions,
- barter_integration::list_strategies,
- barter_integration::get_strategy_parameters,
- barter_integration::update_strategy_parameters,
- barter_integration::run_backtest,
- barter_integration::optimize_strategy,
- barter_integration::get_supported_exchanges,
- barter_integration::get_trading_modes,
- barter_integration::parse_databento_dataset,
- barter_integration::map_custom_dataset,
- barter_integration::map_tick_dataset,
// Company News Commands
commands::company_news::fetch_company_news,
commands::company_news::fetch_news_by_topic,
@@ -1725,6 +1680,9 @@ pub fn run() {
commands::database::db_add_mcp_server,
commands::database::db_get_mcp_servers,
commands::database::db_delete_mcp_server,
+ commands::database::db_get_internal_tool_settings,
+ commands::database::db_set_internal_tool_enabled,
+ commands::database::db_is_internal_tool_enabled,
commands::database::db_save_backtesting_provider,
commands::database::db_get_backtesting_providers,
commands::database::db_save_backtesting_strategy,
@@ -1789,7 +1747,6 @@ pub fn run() {
commands::alpha_arena_bridge::paper_trading_get_orders,
commands::alpha_arena_bridge::paper_trading_get_trades,
commands::alpha_arena_bridge::alpha_arena_record_decision,
- // Financial Statement Analysis - CFA-compliant analysis via PyO3
commands::financial_analysis::analyze_income_statement,
commands::financial_analysis::analyze_balance_sheet,
commands::financial_analysis::analyze_cash_flow,
diff --git a/fincept-terminal-desktop/src-tauri/src/python.rs b/fincept-terminal-desktop/src-tauri/src/python.rs
new file mode 100644
index 000000000..2e5c18420
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/python.rs
@@ -0,0 +1,329 @@
+// Unified Python Runtime Module
+// Provides Python script execution via subprocess
+// Public API: execute(), execute_sync(), execute_with_stdin(), initialize(), get_bun_path()
+
+use std::io::Write;
+use std::path::PathBuf;
+use std::process::{Command, Stdio};
+
+use tauri::Manager;
+
+#[cfg(target_os = "windows")]
+use std::os::windows::process::CommandExt;
+
+#[cfg(target_os = "windows")]
+const CREATE_NO_WINDOW: u32 = 0x08000000;
+
+// Directory names of scripts requiring NumPy 1.x venv.
+// Matched against path components (directory/file names), not arbitrary substrings.
+const NUMPY1_SCRIPTS: &[&str] = &[
+ "vectorbt", "backtesting", "gluonts", "functime", "pyportfolioopt", "financepy",
+];
+
+// ============================================================================
+// INTERNAL: Path Resolution
+// ============================================================================
+
+fn get_install_dir(app: &tauri::AppHandle) -> Result<PathBuf, String> {
+ if cfg!(debug_assertions) {
+ let base = if cfg!(target_os = "windows") {
+ std::env::var("LOCALAPPDATA")
+ .map(PathBuf::from)
+ .unwrap_or_else(|_| PathBuf::from("C:\\Users\\Default\\AppData\\Local"))
+ } else if cfg!(target_os = "macos") {
+ std::env::var("HOME")
+ .map(|h| PathBuf::from(h).join("Library/Application Support"))
+ .unwrap_or_else(|_| PathBuf::from("/tmp"))
+ } else {
+ std::env::var("HOME")
+ .map(|h| PathBuf::from(h).join(".local/share"))
+ .unwrap_or_else(|_| PathBuf::from("/tmp"))
+ };
+ Ok(base.join("fincept-dev"))
+ } else {
+ app.path().app_data_dir()
+ .map_err(|e| format!("Failed to get app data dir: {}", e))
+ }
+}
+
+fn get_venv(script: &str) -> &'static str {
+ // Match against individual path components to avoid false positives
+ // e.g. "Analytics/backtesting/vectorbt/vbt_strategies.py" matches "vectorbt"
+ // but "my_backtesting_report.py" should NOT match if it's just a filename
+ let lower = script.to_lowercase();
+ let needs_numpy1 = NUMPY1_SCRIPTS.iter().any(|keyword| {
+ // Check path components separated by / or \
+ lower.split(&['/', '\\'][..])
+ .any(|component| component == *keyword || component.starts_with(&format!("{}.", keyword)) || component.starts_with(&format!("{}_", keyword)))
+ });
+ if needs_numpy1 { "venv-numpy1" } else { "venv-numpy2" }
+}
+
+fn clean_path(path: PathBuf) -> PathBuf {
+ let s = path.to_string_lossy();
+ if s.len() > 4 && s.starts_with(r"\\?\") {
+ PathBuf::from(&s[4..])
+ } else {
+ path
+ }
+}
+
+fn resolve_python_path(app: &tauri::AppHandle, script: &str) -> Result<PathBuf, String> {
+ let install_dir = get_install_dir(app)?;
+ let venv = get_venv(script);
+
+ let python = if cfg!(target_os = "windows") {
+ install_dir.join(venv).join("Scripts").join("python.exe")
+ } else {
+ install_dir.join(venv).join("bin").join("python3")
+ };
+
+ if python.exists() {
+ return Ok(clean_path(python));
+ }
+
+ #[cfg(debug_assertions)]
+ {
+ let sys = if cfg!(target_os = "windows") { "python" } else { "python3" };
+ if Command::new(sys).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
+ return Ok(PathBuf::from(sys));
+ }
+ }
+
+ Err(format!("Python not found at: {}", python.display()))
+}
+
+fn resolve_script_path(app: &tauri::AppHandle, script: &str) -> Result<PathBuf, String> {
+ let mut candidates = Vec::new();
+
+ if let Ok(res) = app.path().resource_dir() {
+ candidates.push(res.join("scripts").join(script));
+ }
+ if let Ok(exe) = std::env::current_exe() {
+ if let Some(dir) = exe.parent() {
+ candidates.push(dir.join("resources").join("scripts").join(script));
+ candidates.push(dir.join("scripts").join(script));
+ }
+ }
+ if let Ok(cwd) = std::env::current_dir() {
+ candidates.push(cwd.join("resources").join("scripts").join(script));
+ candidates.push(cwd.join("src-tauri").join("resources").join("scripts").join(script));
+ }
+
+ for p in &candidates {
+ if p.exists() {
+ return Ok(clean_path(p.clone()));
+ }
+ }
+
+ Err(format!(
+ "Script '{}' not found. Searched: {}",
+ script,
+ candidates.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(", ")
+ ))
+}
+
+fn extract_json(output: &str) -> Result<String, String> {
+ let lines: Vec<&str> = output.lines().collect();
+
+ // Try last line (compact JSON)
+ if let Some(last) = lines.last() {
+ let t = last.trim();
+ if t.starts_with('{') || t.starts_with('[') {
+ return Ok(t.to_string());
+ }
+ }
+
+ // Try finding JSON from start (multi-line)
+ if let Some(idx) = lines.iter().position(|l| {
+ let t = l.trim();
+ t.starts_with('{') || t.starts_with('[')
+ }) {
+ return Ok(lines[idx..].join("\n").trim().to_string());
+ }
+
+ // No JSON found — return error with diagnostic info
+ let preview = if output.len() > 200 { &output[..200] } else { output };
+ Err(format!(
+ "Script produced non-JSON output: {}",
+ preview.trim()
+ ))
+}
+
+// ============================================================================
+// INTERNAL: Subprocess Execution
+// ============================================================================
+
+fn run_subprocess(
+ python: &PathBuf,
+ script: &PathBuf,
+ args: &[String],
+) -> Result<String, String> {
+ let mut cmd = Command::new(python);
+ cmd.arg(script).args(args)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ let output = cmd.output().map_err(|e| format!("Failed to execute: {}", e))?;
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ if output.status.success() {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ extract_json(&stdout).map_err(|e| {
+ if stderr.is_empty() { e } else { format!("{}\nStderr: {}", e, stderr) }
+ })
+ } else {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let mut msg = format!("Script failed (exit {})", output.status.code().unwrap_or(-1));
+ if !stderr.is_empty() {
+ msg.push_str(&format!(": {}", stderr));
+ }
+ if !stdout.is_empty() {
+ msg.push_str(&format!("\nStdout: {}", stdout));
+ }
+ Err(msg)
+ }
+}
+
+fn run_subprocess_with_stdin(
+ python: &PathBuf,
+ script: &PathBuf,
+ args: &[String],
+ stdin_data: &str,
+) -> Result<String, String> {
+ let mut cmd = Command::new(python);
+ cmd.arg(script).args(args).arg("--stdin")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ let mut child = cmd.spawn().map_err(|e| format!("Failed to spawn: {}", e))?;
+
+ if let Some(mut stdin) = child.stdin.take() {
+ stdin.write_all(stdin_data.as_bytes())
+ .map_err(|e| format!("Failed to write stdin: {}", e))?;
+ // stdin is dropped here, closing the pipe and signaling EOF
+ }
+
+ let output = child.wait_with_output()
+ .map_err(|e| format!("Failed to wait: {}", e))?;
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ if output.status.success() {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ extract_json(&stdout).map_err(|e| {
+ if stderr.is_empty() { e } else { format!("{}\nStderr: {}", e, stderr) }
+ })
+ } else {
+ Err(format!("Script failed: {}", stderr))
+ }
+}
+
+// ============================================================================
+// PUBLIC API
+// ============================================================================
+
+/// Initialize Python runtime (call once at startup)
+/// Validates that the Python executable exists and is runnable.
+pub async fn initialize(app: &tauri::AppHandle) -> Result<(), String> {
+ let install_dir = get_install_dir(app)?;
+
+ // Verify at least one Python venv exists
+ let numpy2_python = if cfg!(target_os = "windows") {
+ install_dir.join("venv-numpy2").join("Scripts").join("python.exe")
+ } else {
+ install_dir.join("venv-numpy2").join("bin").join("python3")
+ };
+
+ if !numpy2_python.exists() {
+ // In debug mode, check system Python
+ #[cfg(debug_assertions)]
+ {
+ let sys = if cfg!(target_os = "windows") { "python" } else { "python3" };
+ if Command::new(sys).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
+ eprintln!("[Python] Initialized with system Python (debug mode)");
+ return Ok(());
+ }
+ }
+ return Err(format!("Python venv not found at: {}", numpy2_python.display()));
+ }
+
+ eprintln!("[Python] Initialized — venv found at: {}", numpy2_python.display());
+ Ok(())
+}
+
+/// Execute Python script (async, uses subprocess execution)
+pub async fn execute(
+ app: &tauri::AppHandle,
+ script: &str,
+ args: Vec<String>,
+) -> Result<String, String> {
+ let script_path = resolve_script_path(app, script)?;
+ let python = resolve_python_path(app, script)?;
+ run_subprocess(&python, &script_path, &args)
+}
+
+/// Execute Python script (sync wrapper)
+pub fn execute_sync(
+ app: &tauri::AppHandle,
+ script: &str,
+ args: Vec<String>,
+) -> Result<String, String> {
+ let script_path = resolve_script_path(app, script)?;
+ let python = resolve_python_path(app, script)?;
+ run_subprocess(&python, &script_path, &args)
+}
+
+/// Execute with stdin data (for large payloads, sync only)
+pub fn execute_with_stdin(
+ app: &tauri::AppHandle,
+ script: &str,
+ args: Vec<String>,
+ stdin_data: &str,
+) -> Result<String, String> {
+ let python = resolve_python_path(app, script)?;
+ let script_path = resolve_script_path(app, script)?;
+ run_subprocess_with_stdin(&python, &script_path, &args, stdin_data)
+}
+
+/// Get Bun executable path
+pub fn get_bun_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {
+ let install_dir = get_install_dir(app)?;
+ let bun = if cfg!(target_os = "windows") {
+ install_dir.join("bun").join("bun.exe")
+ } else {
+ install_dir.join("bun").join("bin").join("bun")
+ };
+
+ #[cfg(debug_assertions)]
+ {
+ let sys = if cfg!(target_os = "windows") { "bun.exe" } else { "bun" };
+ if Command::new(sys).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
+ return Ok(PathBuf::from(sys));
+ }
+ }
+
+ if bun.exists() {
+ Ok(bun)
+ } else {
+ Err(format!("Bun not found at: {}", bun.display()))
+ }
+}
+
+/// Get Python executable path (for jupyter.rs and other direct Python usage)
+/// If library_hint is provided, selects the appropriate venv for that library.
+pub fn get_python_path(app: &tauri::AppHandle, library_hint: Option<&str>) -> Result<PathBuf, String> {
+ let venv_script = library_hint.unwrap_or("numpy2");
+ resolve_python_path(app, venv_script)
+}
+
+/// Get script path (for direct Command usage in data_sources)
+pub fn get_script_path(app: &tauri::AppHandle, script: &str) -> Result<PathBuf, String> {
+ resolve_script_path(app, script)
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/python_runtime.rs b/fincept-terminal-desktop/src-tauri/src/python_runtime.rs
deleted file mode 100644
index 752a369a0..000000000
--- a/fincept-terminal-desktop/src-tauri/src/python_runtime.rs
+++ /dev/null
@@ -1,150 +0,0 @@
-// Python Runtime Module - Worker Pool Integration
-// Provides async/sync execution of Python scripts via persistent worker processes
-// Primary method: Worker pool with Unix Domain Sockets (fast, persistent workers)
-// Fallback method: Direct subprocess execution (slower but reliable)
-
-use std::path::PathBuf;
-
-/// Execute a Python script using the worker pool (async version)
-/// This is the primary execution method - fast, persistent workers, no subprocess spawning
-pub async fn execute_python_script_async(
- script_path: &PathBuf,
- args: Vec<String>,
-) -> Result<String, String> {
- execute_python_script_async_with_priority(script_path, args, 1).await // Default to NORMAL
-}
-
-/// Execute a Python script with custom priority (async version)
-pub async fn execute_python_script_async_with_priority(
- script_path: &PathBuf,
- args: Vec<String>,
- priority: u8,
-) -> Result<String, String> {
- // Determine venv based on script path or library requirements
- let venv = determine_venv_for_script(script_path);
-
- // Use worker pool with priority
- crate::worker_pool::execute_python_script_with_priority(
- script_path.clone(),
- args,
- venv,
- priority,
- ).await
-}
-
-/// Execute a Python script using the worker pool (blocking sync wrapper)
-/// Backward-compatible sync API that internally uses async runtime
-pub fn execute_python_script(
- script_path: &PathBuf,
- args: Vec<String>,
-) -> Result<String, String> {
- // Get or create a tokio runtime handle
- let handle = tokio::runtime::Handle::try_current()
- .ok();
-
- match handle {
- Some(h) => {
- // We're already in a tokio runtime, use block_in_place
- tokio::task::block_in_place(|| {
- h.block_on(execute_python_script_async(script_path, args))
- })
- }
- None => {
- // No runtime, create one temporarily
- let rt = tokio::runtime::Runtime::new()
- .map_err(|e| format!("Failed to create runtime: {}", e))?;
- rt.block_on(execute_python_script_async(script_path, args))
- }
- }
-}
-
-/// Execute Python code directly (for simple calculations)
-/// Note: This spawns a temporary Python process since workers are script-based
-pub async fn execute_python_code(code: &str) -> Result<String, String> {
- // For inline code execution, we need to write to a temp file
- // or use a dedicated eval worker (future enhancement)
- use std::io::Write;
-
- let temp_dir = std::env::temp_dir();
- let script_path = temp_dir.join(format!("temp_code_{}.py", uuid::Uuid::new_v4()));
-
- // Write code to temp file with main() wrapper
- let wrapped_code = format!(
- r#"
-import json
-
-def main(args):
- {}
- # Return result if available
- if 'result' in locals():
- return json.dumps({{"result": result}})
- return json.dumps({{"result": None}})
-
-if __name__ == '__main__':
- import sys
- print(main(sys.argv[1:]))
-"#,
- code
- );
-
- let mut file = std::fs::File::create(&script_path)
- .map_err(|e| format!("Failed to create temp script: {}", e))?;
- file.write_all(wrapped_code.as_bytes())
- .map_err(|e| format!("Failed to write temp script: {}", e))?;
- drop(file);
-
- // Execute using worker pool
- let result = execute_python_script_async(&script_path, vec![]).await;
-
- // Clean up temp file
- let _ = std::fs::remove_file(&script_path);
-
- result
-}
-
-/// Determine which venv to use based on script path
-///
-/// venv-numpy1 (NumPy <2.0): vectorbt, backtesting, gluonts, functime, PyPortfolioOpt, financepy
-/// venv-numpy2 (NumPy 2.x): Everything else including ta, vnpy, edgartools, pyqlib, rdagent, etc.
-fn determine_venv_for_script(script_path: &PathBuf) -> &'static str {
- let path_str = script_path.to_string_lossy().to_lowercase();
-
- // NumPy 1.x libraries (from requirements-numpy1.txt)
- // ONLY libraries that are INCOMPATIBLE with NumPy 2.x go here
- if path_str.contains("vectorbt")
- || path_str.contains("backtesting")
- || path_str.contains("gluonts")
- || path_str.contains("functime")
- || path_str.contains("pyportfolioopt")
- || path_str.contains("financepy")
- {
- return "venv-numpy1";
- }
-
- // NumPy 2.x libraries (DEFAULT - most libraries including modern quant tools)
- // Includes: ta, vnpy, edgartools, pyqlib, rdagent, gs-quant, ffn, fortitudo, finquant, etc.
- "venv-numpy2"
-}
-
-/// Initialize worker pool (async version)
-pub async fn initialize_global_async(python_base_path: PathBuf) -> Result<(), String> {
- crate::worker_pool::initialize_worker_pool(python_base_path).await
-}
-
-/// Initialize worker pool (blocking sync wrapper)
-pub fn initialize_global(python_base_path: PathBuf) -> Result<(), String> {
- let handle = tokio::runtime::Handle::try_current().ok();
-
- match handle {
- Some(h) => {
- tokio::task::block_in_place(|| {
- h.block_on(initialize_global_async(python_base_path))
- })
- }
- None => {
- let rt = tokio::runtime::Runtime::new()
- .map_err(|e| format!("Failed to create runtime: {}", e))?;
- rt.block_on(initialize_global_async(python_base_path))
- }
- }
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/setup.rs b/fincept-terminal-desktop/src-tauri/src/setup.rs
index e7fd179a4..5f884da23 100644
--- a/fincept-terminal-desktop/src-tauri/src/setup.rs
+++ b/fincept-terminal-desktop/src-tauri/src/setup.rs
@@ -722,19 +722,13 @@ pub fn check_setup_status(app: AppHandle) -> Result<SetupStatus, String> {
let needs_setup = !python_installed || !bun_installed || !packages_installed;
- // Initialize worker pool in background if setup is already complete (non-blocking)
- // CRITICAL: Use tauri::async_runtime to ensure worker pool lives in Tauri's persistent runtime
+ // Initialize Python runtime in background if setup is already complete
if !needs_setup && python_installed {
let app_clone = app.clone();
tauri::async_runtime::spawn(async move {
- let install_dir = match get_install_dir(&app_clone) {
- Ok(dir) => dir,
- Err(_e) => {
- return;
- }
- };
-
- let _ = crate::python_runtime::initialize_global_async(install_dir).await;
+ if let Err(e) = crate::python::initialize(&app_clone).await {
+ eprintln!("[Setup] Python initialization failed: {}", e);
+ }
});
}
@@ -821,12 +815,10 @@ pub async fn run_setup(app: AppHandle) -> Result<String, String> {
emit_progress(&app, "complete", 100, "Setup complete!", false);
- // Initialize worker pool in background (non-blocking)
- // CRITICAL: Use tauri::async_runtime to ensure worker pool lives in Tauri's persistent runtime
- let install_dir_clone = install_dir.clone();
- tauri::async_runtime::spawn(async move {
- let _ = crate::python_runtime::initialize_global_async(install_dir_clone).await;
- });
+ // Initialize Python runtime
+ if let Err(e) = crate::python::initialize(&app).await {
+ eprintln!("[Setup] Python initialization warning: {}", e);
+ }
Ok("Setup complete".to_string())
}.await;
diff --git a/fincept-terminal-desktop/src-tauri/src/utils/mod.rs b/fincept-terminal-desktop/src-tauri/src/utils/mod.rs
index c0a088c75..ca3a1f426 100644
--- a/fincept-terminal-desktop/src-tauri/src/utils/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/utils/mod.rs
@@ -1 +1 @@
-pub mod python;
+// Utils module - python functionality moved to crate::python
diff --git a/fincept-terminal-desktop/src-tauri/src/utils/python.rs b/fincept-terminal-desktop/src-tauri/src/utils/python.rs
deleted file mode 100644
index 83e5f1efe..000000000
--- a/fincept-terminal-desktop/src-tauri/src/utils/python.rs
+++ /dev/null
@@ -1,400 +0,0 @@
-// Utility module for Python script execution and path resolution
-// Handles dual-venv setup (NumPy 1.x and NumPy 2.x compatibility)
-// Execution methods:
-// 1. Worker pool via python_runtime (fast, persistent workers)
-// 2. Direct subprocess execution (fallback, more reliable on Windows)
-use std::path::PathBuf;
-use tauri::Manager;
-
-/// NumPy 1.x compatible libraries (use venv-numpy1)
-/// Based on requirements-numpy1.txt - includes backtesting, time series,
-/// portfolio optimization, and quant finance libraries
-const NUMPY1_LIBRARIES: &[&str] = &[
- // Backtesting and trading
- "vectorbt",
- "backtesting",
- // Time series and forecasting
- "gluonts",
- "functime",
- // Portfolio optimization
- "PyPortfolioOpt",
- "pyportfolioopt",
- "finquant",
- // Qlib and RD-Agent (match both script paths and library names)
- "pyqlib",
- "qlib", // matches qlib_service.py paths
- "rdagent",
- "rd_agent", // matches rd_agent_service.py paths
- "gs-quant",
- "gs_quant",
- // Financial modeling libraries (NumPy 1.x dependent due to numba/llvmlite)
- "ffn", // matches ffn_wrapper, ffn_service.py
- "fortitudo", // matches fortitudo_tech_wrapper, fortitudo_service.py
- "financepy",
- // AI Quant Lab uses Qlib/RD-Agent which need NumPy 1.x
- "ai_quant_lab",
-];
-
-/// Determine which venv to use based on library name
-fn get_venv_for_library(library_name: Option<&str>) -> &'static str {
- if let Some(lib) = library_name {
- // Check if library requires NumPy 1.x
- if NUMPY1_LIBRARIES.iter().any(|&numpy1_lib| lib.contains(numpy1_lib)) {
- return "venv-numpy1";
- }
- }
- // Default to NumPy 2.x venv
- "venv-numpy2"
-}
-
-/// Get the Python executable path from app installation directory
-/// Supports dual-venv setup for NumPy 1.x and 2.x compatibility
-/// In production: Uses installed Python from setup.rs
-/// In development: Uses %LOCALAPPDATA%/fincept-dev (matches setup.rs)
-pub fn get_python_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {
- get_python_path_for_library(app, None)
-}
-
-/// Get Python path for a specific library (switches between numpy1 and numpy2 venvs)
-pub fn get_python_path_for_library(app: &tauri::AppHandle, library_name: Option<&str>) -> Result<PathBuf, String> {
- // Get install directory - MUST match setup.rs get_install_dir()
- let install_dir = if cfg!(debug_assertions) {
- // Dev mode: use LOCALAPPDATA/fincept-dev
- let base_dir = if cfg!(target_os = "windows") {
- std::env::var("LOCALAPPDATA")
- .map(PathBuf::from)
- .unwrap_or_else(|_| PathBuf::from("C:\\Users\\Default\\AppData\\Local"))
- } else if cfg!(target_os = "macos") {
- std::env::var("HOME")
- .map(|h| PathBuf::from(h).join("Library/Application Support"))
- .unwrap_or_else(|_| PathBuf::from("/tmp"))
- } else {
- std::env::var("HOME")
- .map(|h| PathBuf::from(h).join(".local/share"))
- .unwrap_or_else(|_| PathBuf::from("/tmp"))
- };
- base_dir.join("fincept-dev")
- } else {
- // Production: use app data directory
- app.path().app_data_dir()
- .map_err(|e| format!("Failed to get app data dir: {}", e))?
- };
-
- // Determine which venv to use based on library
- let venv_name = get_venv_for_library(library_name);
-
- // Platform-specific Python executable location in venv
- let python_exe = if cfg!(target_os = "windows") {
- install_dir.join(format!("{}/Scripts/python.exe", venv_name))
- } else {
- install_dir.join(format!("{}/bin/python3", venv_name))
- };
-
-
- // Check if venv Python exists
- if python_exe.exists() {
- // Strip the \\?\ prefix that can cause issues on Windows
- let path_str = python_exe.to_string_lossy().to_string();
- let clean_path = if path_str.starts_with(r"\\?\") {
- PathBuf::from(&path_str[4..])
- } else {
- python_exe.clone()
- };
- return Ok(clean_path);
- }
-
- // Fallback to system Python in dev mode only
- #[cfg(debug_assertions)]
- {
- use std::process::Command;
- let system_python = if cfg!(target_os = "windows") {
- "python"
- } else {
- "python3"
- };
-
- if let Ok(output) = Command::new(system_python).arg("--version").output() {
- if output.status.success() {
- return Ok(PathBuf::from(system_python));
- }
- }
- }
-
- // If we get here, Python is not available
- Err(format!(
- "Python interpreter not found at: {}\n\n\
- The Python runtime is required to run analytics and data processing features.\n\n\
- Troubleshooting steps:\n\
- 1. Run the setup wizard from the application to install Python\n\
- 2. Ensure both venv-numpy1 and venv-numpy2 are created\n\
- 3. If setup fails, ensure Microsoft Visual C++ Redistributable is installed:\n\
- Download from: https://aka.ms/vs/17/release/vc_redist.x64.exe\n\
- 4. Restart the application after installation",
- python_exe.display()
- ))
-}
-
-/// Get the Bun executable path from app installation directory
-pub fn get_bundled_bun_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {
- // Get install directory - MUST match setup.rs get_install_dir()
- let install_dir = if cfg!(debug_assertions) {
- // Dev mode: use LOCALAPPDATA/fincept-dev
- let base_dir = if cfg!(target_os = "windows") {
- std::env::var("LOCALAPPDATA")
- .map(PathBuf::from)
- .unwrap_or_else(|_| PathBuf::from("C:\\Users\\Default\\AppData\\Local"))
- } else if cfg!(target_os = "macos") {
- std::env::var("HOME")
- .map(|h| PathBuf::from(h).join("Library/Application Support"))
- .unwrap_or_else(|_| PathBuf::from("/tmp"))
- } else {
- std::env::var("HOME")
- .map(|h| PathBuf::from(h).join(".local/share"))
- .unwrap_or_else(|_| PathBuf::from("/tmp"))
- };
- base_dir.join("fincept-dev")
- } else {
- // Production: use app data directory
- app.path().app_data_dir()
- .map_err(|e| format!("Failed to get app data dir: {}", e))?
- };
-
- // Platform-specific Bun executable location
- let bun_exe = if cfg!(target_os = "windows") {
- install_dir.join("bun").join("bun.exe")
- } else {
- install_dir.join("bun").join("bun")
- };
-
- // DEVELOPMENT MODE: Prefer system Bun
- #[cfg(debug_assertions)]
- {
- use std::process::Command;
-
- let system_bun = if cfg!(target_os = "windows") {
- "bun.exe"
- } else {
- "bun"
- };
-
- // Try system Bun first in dev mode
- if let Ok(output) = Command::new(system_bun).arg("--version").output() {
- if output.status.success() {
- return Ok(PathBuf::from(system_bun));
- }
- }
- }
-
- // PRODUCTION MODE or dev fallback: Check bundled Bun
- if bun_exe.exists() {
- return Ok(bun_exe);
- }
-
- // If we get here, Bun is not available
- Err(format!(
- "Bun not found at: {}\n\nPlease run the setup process to install Bun.",
- bun_exe.display()
- ))
-}
-
-/// Get a Python script path at runtime
-/// Works in dev mode, production builds, and CI/CD pipelines
-pub fn get_script_path(app: &tauri::AppHandle, script_name: &str) -> Result<PathBuf, String> {
- // Strategy: Try multiple paths in order until we find the script
-
- let mut candidate_paths = Vec::new();
-
- // 1. Try Tauri's resource_dir (works in production and should work in dev)
- if let Ok(resource_dir) = app.path().resource_dir() {
- candidate_paths.push(resource_dir.join("scripts").join(script_name));
- }
-
- // 2. Try relative to current executable (production fallback)
- if let Ok(exe_path) = std::env::current_exe() {
- if let Some(exe_dir) = exe_path.parent() {
- candidate_paths.push(exe_dir.join("resources").join("scripts").join(script_name));
- candidate_paths.push(exe_dir.join("scripts").join(script_name));
- }
- }
-
- // 3. Try relative to current working directory (dev mode)
- if let Ok(cwd) = std::env::current_dir() {
- // If CWD is src-tauri
- candidate_paths.push(cwd.join("resources").join("scripts").join(script_name));
- // If CWD is project root
- candidate_paths.push(cwd.join("src-tauri").join("resources").join("scripts").join(script_name));
- }
-
- // Try each candidate path
- // Debug logging only in debug builds
- #[cfg(debug_assertions)]
- {
- eprintln!("[SCRIPT_PATH_DEBUG] Searching for: {}", script_name);
- }
-
- for (_i, path) in candidate_paths.iter().enumerate() {
- #[cfg(debug_assertions)]
- {
- eprintln!("[SCRIPT_PATH_DEBUG] Candidate {}: {:?}", _i+1, path);
- }
-
- if path.exists() {
- #[cfg(debug_assertions)]
- {
- eprintln!("[SCRIPT_PATH_DEBUG] Found at candidate {}", _i+1);
- }
-
- // Strip the \\?\ prefix that Python can't handle on Windows
- let path_str = path.to_string_lossy().to_string();
- let clean_path = if path_str.starts_with(r"\\?\") {
- PathBuf::from(&path_str[4..])
- } else {
- path.clone()
- };
-
- return Ok(clean_path);
- }
- }
-
- Err(format!(
- "Script '{}' not found in any of {} candidate locations",
- script_name,
- candidate_paths.len()
- ))
-}
-
-/// Execute Python script with worker pool
-/// This is the primary execution method - fast, persistent workers, no subprocess spawning
-pub fn execute_python_script_simple(
- app: &tauri::AppHandle,
- script_relative_path: &str,
- args: &[&str],
-) -> Result<String, String> {
- let script_path = get_script_path(app, script_relative_path)?;
- let args_vec: Vec<String> = args.iter().map(|s| s.to_string()).collect();
-
- // Execute with worker pool (sync wrapper)
- crate::python_runtime::execute_python_script(&script_path, args_vec)
-}
-
-/// Execute Python script directly using subprocess (bypasses worker pool)
-/// Use this for commands that need specific venv or when worker pool has issues
-/// This is slower but more reliable on Windows
-#[cfg(target_os = "windows")]
-const CREATE_NO_WINDOW: u32 = 0x08000000;
-
-pub fn execute_python_subprocess(
- app: &tauri::AppHandle,
- script_relative_path: &str,
- args: &[String],
- library_hint: Option<&str>,
-) -> Result<String, String> {
- use std::process::Command;
- #[cfg(target_os = "windows")]
- use std::os::windows::process::CommandExt;
-
- let script_path = get_script_path(app, script_relative_path)?;
- let python_path = get_python_path_for_library(app, library_hint)?;
-
- let mut cmd = Command::new(&python_path);
- cmd.arg(&script_path)
- .args(args)
- .stdout(std::process::Stdio::piped())
- .stderr(std::process::Stdio::piped());
-
- #[cfg(target_os = "windows")]
- cmd.creation_flags(CREATE_NO_WINDOW);
-
- let output = cmd.output()
- .map_err(|e| format!("Failed to execute Python: {}", e))?;
-
- if output.status.success() {
- let raw_output = String::from_utf8(output.stdout)
- .map_err(|e| format!("Failed to parse output: {}", e))?;
-
- // Extract JSON from output - handles case where logging/warnings leak to stdout
- // Strategy: Find the last complete JSON object/array in the output.
- // 1. Try the last line first (compact JSON on one line - most common case)
- // 2. If that doesn't start with { or [, search backwards for the JSON start
- // 3. If found on a non-last line, collect from that line to the end (multi-line JSON)
- let lines: Vec<&str> = raw_output.lines().collect();
-
- // First try: check if last line is compact JSON (single-line output)
- if let Some(last) = lines.last() {
- let trimmed = last.trim();
- if trimmed.starts_with('{') || trimmed.starts_with('[') {
- return Ok(trimmed.to_string());
- }
- }
-
- // Second try: find the first line from the start that begins JSON, then take everything from there
- // This handles multi-line (pretty-printed) JSON output
- if let Some(json_start_idx) = lines.iter().position(|line| {
- let trimmed = line.trim();
- trimmed.starts_with('{') || trimmed.starts_with('[')
- }) {
- let json_text: String = lines[json_start_idx..].join("\n");
- let trimmed = json_text.trim();
- if !trimmed.is_empty() {
- return Ok(trimmed.to_string());
- }
- }
-
- // Fallback: return raw output
- Ok(raw_output.trim().to_string())
- } else {
- let stderr = String::from_utf8_lossy(&output.stderr);
- let stdout = String::from_utf8_lossy(&output.stdout);
- Err(format!("Python script failed:\nstderr: {}\nstdout: {}", stderr, stdout))
- }
-}
-
-/// Execute Python script with data passed via stdin (for large payloads)
-/// This avoids Windows command line length limits
-pub fn execute_python_subprocess_with_stdin(
- app: &tauri::AppHandle,
- script_relative_path: &str,
- command: &str,
- stdin_data: &str,
- library_hint: Option<&str>,
-) -> Result<String, String> {
- use std::process::{Command, Stdio};
- use std::io::Write;
- #[cfg(target_os = "windows")]
- use std::os::windows::process::CommandExt;
-
- let script_path = get_script_path(app, script_relative_path)?;
- let python_path = get_python_path_for_library(app, library_hint)?;
-
- let mut cmd = Command::new(&python_path);
- cmd.arg(&script_path)
- .arg(command)
- .arg("--stdin") // Signal to read from stdin
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
-
- #[cfg(target_os = "windows")]
- cmd.creation_flags(CREATE_NO_WINDOW);
-
- let mut child = cmd.spawn()
- .map_err(|e| format!("Failed to spawn Python: {}", e))?;
-
- // Write data to stdin
- if let Some(mut stdin) = child.stdin.take() {
- stdin.write_all(stdin_data.as_bytes())
- .map_err(|e| format!("Failed to write to stdin: {}", e))?;
- }
-
- let output = child.wait_with_output()
- .map_err(|e| format!("Failed to wait for Python: {}", e))?;
-
- if output.status.success() {
- String::from_utf8(output.stdout)
- .map_err(|e| format!("Failed to parse output: {}", e))
- } else {
- let stderr = String::from_utf8_lossy(&output.stderr);
- let stdout = String::from_utf8_lossy(&output.stdout);
- Err(format!("Python script failed:\nstderr: {}\nstdout: {}", stderr, stdout))
- }
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/worker_pool.rs b/fincept-terminal-desktop/src-tauri/src/worker_pool.rs
deleted file mode 100644
index 76331488f..000000000
--- a/fincept-terminal-desktop/src-tauri/src/worker_pool.rs
+++ /dev/null
@@ -1,565 +0,0 @@
-// Worker Pool Manager - Persistent Python processes with Unix Domain Sockets
-use std::path::PathBuf;
-use std::process::{Child, Command, Stdio};
-use std::sync::Arc;
-use std::sync::atomic::{AtomicU64, Ordering};
-use tokio::sync::{Mutex, mpsc};
-use interprocess::local_socket::prelude::*;
-use interprocess::local_socket::GenericNamespaced;
-use serde::{Deserialize, Serialize};
-use std::collections::BinaryHeap;
-use std::io::{Read, Write};
-
-#[cfg(target_os = "windows")]
-use std::os::windows::process::CommandExt;
-
-#[cfg(target_os = "windows")]
-const CREATE_NO_WINDOW: u32 = 0x08000000;
-
-const NUM_WORKERS: usize = 3; // Three Python processes for better concurrency
-const NUM_THREADS: usize = 4; // Number of concurrent scripts per process
-const TASK_TIMEOUT_SECS: u64 = 120; // Maximum time for a task before timeout (LLM calls can take 30-60s+)
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct WorkerTask {
- pub task_id: String,
- pub script_path: String,
- pub args: Vec<String>,
- pub venv: String, // "venv-numpy1" or "venv-numpy2"
- pub priority: u8, // 0=HIGH, 1=NORMAL, 2=LOW
-}
-
-// Priority wrapper for BinaryHeap (min-heap based on priority)
-#[derive(Debug, Clone)]
-struct PrioritizedTask {
- task: WorkerTask,
- sequence: u64, // For FIFO within same priority
-}
-
-impl PartialEq for PrioritizedTask {
- fn eq(&self, other: &Self) -> bool {
- self.task.priority == other.task.priority && self.sequence == other.sequence
- }
-}
-
-impl Eq for PrioritizedTask {}
-
-impl PartialOrd for PrioritizedTask {
- fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
- Some(self.cmp(other))
- }
-}
-
-impl Ord for PrioritizedTask {
- fn cmp(&self, other: &Self) -> std::cmp::Ordering {
- // Reverse order for min-heap (lower priority value = higher priority)
- other.task.priority.cmp(&self.task.priority)
- .then_with(|| self.sequence.cmp(&other.sequence))
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct WorkerResponse {
- pub task_id: String,
- pub status: String, // "success" or "error"
- pub data: String, // JSON result or error message
-}
-
-struct Worker {
- process: Child,
- socket: LocalSocketStream,
-}
-
-pub struct WorkerPool {
- workers: Arc<Mutex<Vec<Worker>>>,
- task_sender: mpsc::UnboundedSender<PrioritizedTask>,
- response_senders: Arc<Mutex<std::collections::HashMap<String, tokio::sync::oneshot::Sender<WorkerResponse>>>>,
- sequence_counter: Arc<AtomicU64>,
- socket_name: String,
-}
-
-impl WorkerPool {
- /// Find worker script in multiple possible locations (dev/prod compatible)
- fn find_worker_script(python_base_path: &PathBuf) -> Result<PathBuf, String> {
- let mut candidate_paths = Vec::new();
-
- // Strategy: Try multiple paths like get_script_path does
-
- // 1. Production: relative to python_base_path parent (install_dir)
- if let Some(install_dir) = python_base_path.parent() {
- candidate_paths.push(install_dir.join("resources").join("scripts").join("worker.py"));
- }
-
- // 2. Dev mode: relative to current working directory
- if let Ok(cwd) = std::env::current_dir() {
- candidate_paths.push(cwd.join("resources").join("scripts").join("worker.py"));
- candidate_paths.push(cwd.join("src-tauri").join("resources").join("scripts").join("worker.py"));
- }
-
- // 3. Production: relative to executable
- if let Ok(exe_path) = std::env::current_exe() {
- if let Some(exe_dir) = exe_path.parent() {
- candidate_paths.push(exe_dir.join("resources").join("scripts").join("worker.py"));
- candidate_paths.push(exe_dir.join("scripts").join("worker.py"));
- }
- }
-
- // Try each candidate path
- for path in candidate_paths.iter() {
- if path.exists() {
- // Strip the \\?\ prefix that can cause issues on Windows
- let path_str = path.to_string_lossy().to_string();
- let clean_path = if path_str.starts_with(r"\\?\") {
- PathBuf::from(&path_str[4..])
- } else {
- path.clone()
- };
- return Ok(clean_path);
- }
- }
-
- Err("Worker script 'worker.py' not found".to_string())
- }
-
- /// Initialize the worker pool
- pub async fn new(python_base_path: PathBuf) -> Result<Self, String> {
- // Create socket name base
- let socket_name = format!("fincept-worker-{}", std::process::id());
-
- // Start multiple worker processes
- let mut workers_vec = Vec::new();
- for i in 0..NUM_WORKERS {
- let worker_socket = format!("{}-{}", socket_name, i);
-
- // Use venv-numpy2 as default (has most modern libraries)
- let worker = Self::spawn_worker(i, &python_base_path, "venv-numpy2", &worker_socket).await?;
- workers_vec.push(worker);
- }
-
- let workers = Arc::new(Mutex::new(workers_vec));
-
- // Create priority queue channel
- let (task_sender, task_receiver) = mpsc::unbounded_channel::<PrioritizedTask>();
- let response_senders = Arc::new(Mutex::new(std::collections::HashMap::new()));
- let sequence_counter = Arc::new(AtomicU64::new(0));
-
- // Spawn queue processor task
- let workers_clone = workers.clone();
- let response_senders_clone = response_senders.clone();
- tokio::spawn(Self::process_queue(task_receiver, workers_clone, response_senders_clone));
-
- Ok(WorkerPool {
- workers,
- task_sender,
- response_senders,
- sequence_counter,
- socket_name,
- })
- }
-
- /// Spawn a single worker process
- async fn spawn_worker(
- worker_id: usize,
- python_base_path: &PathBuf,
- venv_type: &str,
- socket_name: &str,
- ) -> Result<Worker, String> {
- // Get Python executable path
- let python_exe = if cfg!(target_os = "windows") {
- python_base_path.join(format!("{}/Scripts/python.exe", venv_type))
- } else {
- python_base_path.join(format!("{}/bin/python3", venv_type))
- };
-
- if !python_exe.exists() {
- return Err(format!("Python not found at: {:?}", python_exe));
- }
-
- // Get worker script path - try multiple locations for dev/prod compatibility
- let worker_script = Self::find_worker_script(python_base_path)?;
-
- if !worker_script.exists() {
- return Err(format!("Worker script not found at: {:?}", worker_script));
- }
-
-
- // Spawn Python process
- let mut cmd = Command::new(&python_exe);
- cmd.arg(worker_script.to_str().unwrap())
- .arg(socket_name)
- .arg(worker_id.to_string())
- .arg(NUM_THREADS.to_string()) // Pass number of threads
- .stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
-
- #[cfg(target_os = "windows")]
- cmd.creation_flags(CREATE_NO_WINDOW);
-
- let process = cmd.spawn()
- .map_err(|e| format!("Failed to spawn worker {}: {}", worker_id, e))?;
-
- // Wait for worker to start listening with retry logic
- // Python worker creates server socket, so we need to wait for it
- let mut socket: Option<LocalSocketStream> = None;
- let max_retries = 50; // 5 seconds total (50 * 100ms)
-
- for attempt in 0..max_retries {
- tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
-
- match LocalSocketStream::connect(
- socket_name.to_ns_name::<GenericNamespaced>()
- .map_err(|e| format!("Failed to create socket name: {}", e))?
- ) {
- Ok(s) => {
- socket = Some(s);
- break;
- }
- Err(e) => {
- if attempt == max_retries - 1 {
- return Err(format!("Failed to connect to worker {} after {} attempts: {}", worker_id, max_retries, e));
- }
- // Continue retrying silently
- }
- }
- }
-
- let socket = socket.ok_or_else(|| format!("Failed to connect to worker {}", worker_id))?;
-
- Ok(Worker {
- process,
- socket,
- })
- }
-
- /// Process the priority queue - distributes tasks to available workers
- async fn process_queue(
- mut task_receiver: mpsc::UnboundedReceiver<PrioritizedTask>,
- workers: Arc<Mutex<Vec<Worker>>>,
- response_senders: Arc<Mutex<std::collections::HashMap<String, tokio::sync::oneshot::Sender<WorkerResponse>>>>,
- ) {
- let mut priority_queue: BinaryHeap<PrioritizedTask> = BinaryHeap::new();
- let mut worker_index = 0; // Round-robin worker selection
-
- // Spawn response reader tasks for each worker
- for i in 0..NUM_WORKERS {
- let workers_clone = workers.clone();
- let response_senders_clone = response_senders.clone();
-
- tokio::spawn(async move {
- loop {
- tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
-
- let mut workers_lock = workers_clone.lock().await;
- if i >= workers_lock.len() {
- break;
- }
-
- let worker = &mut workers_lock[i];
-
- // Try to read response (non-blocking check)
- let mut len_buf = [0u8; 4];
- if worker.socket.read_exact(&mut len_buf).is_ok() {
- let response_len = u32::from_le_bytes(len_buf) as usize;
- let mut response_buf = vec![0u8; response_len];
-
- if worker.socket.read_exact(&mut response_buf).is_ok() {
- if let Ok(response) = rmp_serde::from_slice::<WorkerResponse>(&response_buf) {
- // Send response back to caller
- let mut senders = response_senders_clone.lock().await;
- if let Some(sender) = senders.remove(&response.task_id) {
- let _ = sender.send(response);
- }
- }
- }
- }
-
- drop(workers_lock);
- }
- });
- }
-
- loop {
- tokio::select! {
- Some(new_task) = task_receiver.recv() => {
- // Add new task to priority queue
- priority_queue.push(new_task);
- }
- _ = tokio::time::sleep(tokio::time::Duration::from_millis(1)) => {
- // Try to dispatch tasks to workers
- if let Some(prioritized_task) = priority_queue.pop() {
- let task = prioritized_task.task;
-
- // Send task to next worker (round-robin)
- let mut workers_lock = workers.lock().await;
- if worker_index < workers_lock.len() {
- let worker = &mut workers_lock[worker_index];
-
- // Serialize and send task
- if let Ok(task_bytes) = rmp_serde::to_vec(&task) {
- let len_bytes = (task_bytes.len() as u32).to_le_bytes();
-
- if worker.socket.write_all(&len_bytes).is_ok()
- && worker.socket.write_all(&task_bytes).is_ok()
- && worker.socket.flush().is_ok() {
- // Round-robin to next worker
- worker_index = (worker_index + 1) % NUM_WORKERS;
- }
- }
- }
- drop(workers_lock);
- }
- }
- }
- }
- }
-
- /// Execute a task using the worker pool with timeout protection
- pub async fn execute_task(&self, task: WorkerTask) -> Result<WorkerResponse, String> {
- let task_id = task.task_id.clone();
-
- // Create response channel
- let (response_tx, response_rx) = tokio::sync::oneshot::channel();
-
- {
- let mut senders = self.response_senders.lock().await;
- senders.insert(task_id.clone(), response_tx);
- }
-
- // Add task to priority queue
- let sequence = self.sequence_counter.fetch_add(1, Ordering::Relaxed);
- let prioritized_task = PrioritizedTask {
- task,
- sequence,
- };
-
- self.task_sender.send(prioritized_task)
- .map_err(|e| format!("Failed to queue task: {}", e))?;
-
- // Wait for response with timeout protection
- let timeout_result = tokio::time::timeout(
- tokio::time::Duration::from_secs(TASK_TIMEOUT_SECS),
- response_rx
- ).await;
-
- match timeout_result {
- Ok(Ok(response)) => Ok(response),
- Ok(Err(e)) => {
- // Channel closed - clean up the sender
- let mut senders = self.response_senders.lock().await;
- senders.remove(&task_id);
- Err(format!("Failed to receive response: {}", e))
- }
- Err(_) => {
- // Timeout - clean up the sender to avoid memory leak
- let mut senders = self.response_senders.lock().await;
- senders.remove(&task_id);
- Err(format!("Task timed out after {} seconds", TASK_TIMEOUT_SECS))
- }
- }
- }
-
- /// Shutdown all workers
- pub async fn shutdown(&self) {
- let mut workers = self.workers.lock().await;
-
- for (_i, worker) in workers.iter_mut().enumerate() {
- let _ = worker.process.kill();
- }
- }
-}
-
-// Global worker pool instance
-use once_cell::sync::OnceCell;
-static WORKER_POOL: OnceCell<Arc<Mutex<Option<WorkerPool>>>> = OnceCell::new();
-
-/// Initialize the global worker pool
-pub async fn initialize_worker_pool(python_base_path: PathBuf) -> Result<(), String> {
- let pool = WorkerPool::new(python_base_path).await?;
-
- WORKER_POOL.get_or_init(|| Arc::new(Mutex::new(Some(pool))));
-
- Ok(())
-}
-
-/// Get the global worker pool
-pub async fn get_worker_pool() -> Result<Arc<Mutex<Option<WorkerPool>>>, String> {
- WORKER_POOL.get()
- .ok_or_else(|| "Worker pool not initialized. Please run setup first.".to_string())
- .map(|pool| pool.clone())
-}
-
-/// Execute a Python script using the worker pool
-pub async fn execute_python_script(
- script_path: PathBuf,
- args: Vec<String>,
- venv: &str,
-) -> Result<String, String> {
- execute_python_script_with_priority(script_path, args, venv, 1).await // Default to NORMAL priority
-}
-
-/// Execute a Python script using the worker pool with custom priority
-/// Falls back to subprocess execution if worker pool is not available
-pub async fn execute_python_script_with_priority(
- script_path: PathBuf,
- args: Vec<String>,
- venv: &str,
- priority: u8,
-) -> Result<String, String> {
- // Try worker pool first
- match get_worker_pool().await {
- Ok(pool_mutex) => {
- let pool_guard = pool_mutex.lock().await;
- if let Some(pool) = pool_guard.as_ref() {
- let task = WorkerTask {
- task_id: uuid::Uuid::new_v4().to_string(),
- script_path: script_path.to_string_lossy().to_string(),
- args: args.clone(),
- venv: venv.to_string(),
- priority,
- };
-
- match pool.execute_task(task).await {
- Ok(response) => {
- if response.status == "success" {
- return Ok(response.data);
- } else {
- return Err(response.data);
- }
- }
- Err(e) => {
- eprintln!("[WorkerPool] Task execution failed, falling back to subprocess: {}", e);
- }
- }
- }
- }
- Err(e) => {
- eprintln!("[WorkerPool] Pool not available ({}), using subprocess fallback", e);
- }
- }
-
- // Fallback to subprocess execution
- execute_python_subprocess(&script_path, &args).await
-}
-
-/// Fallback subprocess execution when worker pool is not available
-async fn execute_python_subprocess(
- script_path: &PathBuf,
- args: &[String],
-) -> Result<String, String> {
- use std::process::Stdio;
-
- // Try to find Python executable
- let python_exe = find_python_executable()?;
-
- let mut cmd = Command::new(&python_exe);
- cmd.arg(script_path)
- .args(args)
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
-
- #[cfg(target_os = "windows")]
- cmd.creation_flags(CREATE_NO_WINDOW);
-
- let output = cmd.output()
- .map_err(|e| format!("Failed to execute Python subprocess: {}", e))?;
-
- if output.status.success() {
- let stdout = String::from_utf8_lossy(&output.stdout).to_string();
- // Extract JSON from output - handles both compact and multi-line JSON
- let lines: Vec<&str> = stdout.lines().collect();
-
- // Try last line first (compact JSON)
- if let Some(last_line) = lines.last() {
- let trimmed = last_line.trim();
- if trimmed.starts_with('{') || trimmed.starts_with('[') {
- return Ok(trimmed.to_string());
- }
- }
-
- // Try finding JSON start from beginning (multi-line JSON)
- if let Some(json_start_idx) = lines.iter().position(|line| {
- let trimmed = line.trim();
- trimmed.starts_with('{') || trimmed.starts_with('[')
- }) {
- let json_text: String = lines[json_start_idx..].join("\n");
- let trimmed = json_text.trim();
- if !trimmed.is_empty() {
- return Ok(trimmed.to_string());
- }
- }
-
- Ok(stdout)
- } else {
- let stderr = String::from_utf8_lossy(&output.stderr);
- Err(format!("Python script failed: {}", stderr))
- }
-}
-
-/// Find Python executable for subprocess fallback
-fn find_python_executable() -> Result<PathBuf, String> {
- // First, try our installed venvs (preferred - has all required packages)
- #[cfg(target_os = "windows")]
- {
- if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {
- // Try venv-numpy2 first (default, has most libraries including ta, yfinance, etc.)
- let venv2_python = PathBuf::from(&local_app_data)
- .join("fincept-dev")
- .join("venv-numpy2")
- .join("Scripts")
- .join("python.exe");
- if venv2_python.exists() {
- return Ok(venv2_python);
- }
-
- // Fall back to venv-numpy1 (for vectorbt, backtesting, etc.)
- let venv1_python = PathBuf::from(&local_app_data)
- .join("fincept-dev")
- .join("venv-numpy1")
- .join("Scripts")
- .join("python.exe");
- if venv1_python.exists() {
- return Ok(venv1_python);
- }
- }
- }
-
- #[cfg(not(target_os = "windows"))]
- {
- // macOS/Linux: Check standard app data locations
- if let Ok(home) = std::env::var("HOME") {
- let base = if cfg!(target_os = "macos") {
- PathBuf::from(&home).join("Library/Application Support/fincept-dev")
- } else {
- PathBuf::from(&home).join(".local/share/fincept-dev")
- };
-
- let venv2_python = base.join("venv-numpy2/bin/python3");
- if venv2_python.exists() {
- return Ok(venv2_python);
- }
-
- let venv1_python = base.join("venv-numpy1/bin/python3");
- if venv1_python.exists() {
- return Ok(venv1_python);
- }
- }
- }
-
- // Fall back to system Python (may not have required packages)
- let candidates = if cfg!(target_os = "windows") {
- vec!["python.exe", "python3.exe", "py.exe"]
- } else {
- vec!["python3", "python"]
- };
-
- for candidate in candidates {
- if let Ok(output) = Command::new(candidate).arg("--version").output() {
- if output.status.success() {
- return Ok(PathBuf::from(candidate));
- }
- }
- }
-
- Err("No Python executable found".to_string())
-}
diff --git a/fincept-terminal-desktop/src/components/chat-mode/ChatModeInterface.tsx b/fincept-terminal-desktop/src/components/chat-mode/ChatModeInterface.tsx
index fab2a51fb..699fc1ade 100644
--- a/fincept-terminal-desktop/src/components/chat-mode/ChatModeInterface.tsx
+++ b/fincept-terminal-desktop/src/components/chat-mode/ChatModeInterface.tsx
@@ -2,21 +2,52 @@
// Fincept-style Chat Mode interface with professional terminal design
import React, { useState, useEffect, useRef } from 'react';
-import { Send, Terminal, Activity, Zap, Database, TrendingUp } from 'lucide-react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { chatModeApiService, ChatModeMessage } from '@/services/data-sources/chatModeApi';
+import { Send, Terminal, Activity, Zap, Database, TrendingUp, Search, Trash2, Download, FileText, Plus } from 'lucide-react';
+import { chatModeApiService, ChatModeMessage, ChatSession } from '@/services/data-sources/chatModeApi';
import ChatMessageBubble from './components/ChatMessageBubble';
import ChatSuggestions from './components/ChatSuggestions';
+// Fincept Terminal Design System Colors
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
+};
+
const ChatModeInterface: React.FC = () => {
- const { colors, fontSize, fontFamily } = useTerminalTheme();
const [messages, setMessages] = useState<ChatModeMessage[]>([]);
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
+ const [isInitializing, setIsInitializing] = useState(true);
+ const [isLoadingMessages, setIsLoadingMessages] = useState(false);
+ const [currentSessionUuid, setCurrentSessionUuid] = useState<string | null>(null);
+ const [sessions, setSessions] = useState<ChatSession[]>([]);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [searchResults, setSearchResults] = useState<any[]>([]);
+ const [showSearch, setShowSearch] = useState(false);
+ const [stats, setStats] = useState<any>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
- const [sessionStartTime] = useState(new Date());
const [currentTime, setCurrentTime] = useState(new Date());
+ const pollIntervalRef = useRef<NodeJS.Timeout | null>(null);
+ const currentSessionUuidRef = useRef<string | null>(null);
+ const isLoadingRef = useRef(false);
+
+ // Keep refs in sync with state
+ useEffect(() => { currentSessionUuidRef.current = currentSessionUuid; }, [currentSessionUuid]);
+ useEffect(() => { isLoadingRef.current = isLoading; }, [isLoading]);
useEffect(() => {
const timer = setInterval(() => setCurrentTime(new Date()), 1000);
@@ -28,46 +59,207 @@ const ChatModeInterface: React.FC = () => {
}, [messages]);
useEffect(() => {
- // Initialize with welcome message
- const welcomeMessage: ChatModeMessage = {
- id: 'welcome',
- role: 'assistant',
- content: `**FINCEPT TERMINAL AI ASSISTANT v3.0**
-
-**SYSTEM READY** | All modules operational | Real-time data feeds active
-
-**AVAILABLE FUNCTIONS:**
-━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-• **MARKET DATA** - Real-time quotes, prices, charts
-• **PORTFOLIO ANALYTICS** - Performance, risk, optimization
-• **NEWS & RESEARCH** - Latest developments, analysis
-• **FUNDAMENTAL DATA** - Financials, ratios, valuations
-• **TECHNICAL ANALYSIS** - Indicators, patterns, signals
-• **DERIVATIVES** - Options pricing, Greeks, volatility
-• **ECONOMICS** - Macro data, indicators, forecasts
-• **CUSTOM QUERIES** - Advanced financial modeling
-
-**READY FOR QUERY** | Type your request below`,
- timestamp: new Date()
+ // Initialize: load or create session
+ initializeSession();
+
+ // Cleanup polling on unmount
+ return () => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ }
};
- setMessages([welcomeMessage]);
}, []);
+ const sortSessionsNewestFirst = (sessionList: ChatSession[]): ChatSession[] => {
+ return [...sessionList].sort((a, b) => {
+ const dateA = new Date(a.updated_at || a.created_at).getTime();
+ const dateB = new Date(b.updated_at || b.created_at).getTime();
+ return dateB - dateA;
+ });
+ };
+
+ const initializeSession = async () => {
+ setIsInitializing(true);
+ try {
+ // Get all sessions from API
+ const sessionsResponse = await chatModeApiService.getSessions();
+
+ if (sessionsResponse.success && sessionsResponse.data?.length > 0) {
+ const sorted = sortSessionsNewestFirst(sessionsResponse.data);
+ setSessions(sorted);
+
+ // Find active session or use most recent (first after sort)
+ const activeSession = sorted.find((s: any) => s.is_active) || sorted[0];
+ setCurrentSessionUuid(activeSession.session_uuid);
+
+ // Load messages for this session
+ await loadSessionMessages(activeSession.session_uuid);
+ } else {
+ // Create new session
+ await createNewSession();
+ }
+
+ // Load stats
+ await loadStats();
+
+ // Start polling for background responses
+ startPolling();
+ } catch (error) {
+ console.error('Failed to initialize session:', error);
+ await createNewSession();
+ } finally {
+ setIsInitializing(false);
+ }
+ };
+
+ const loadSessionMessages = async (sessionUuid: string) => {
+ setIsLoadingMessages(true);
+ try {
+ const sessionData = await chatModeApiService.getSession(sessionUuid);
+ if (sessionData.success && sessionData.data?.messages) {
+ const loadedMessages: ChatModeMessage[] = sessionData.data.messages.map((msg: any) => ({
+ id: msg.message_uuid || msg.id,
+ role: msg.role,
+ content: msg.content,
+ timestamp: new Date(msg.created_at || msg.timestamp),
+ message_uuid: msg.message_uuid
+ }));
+ setMessages(loadedMessages);
+ }
+ } catch (error) {
+ console.error('Failed to load messages:', error);
+ } finally {
+ setIsLoadingMessages(false);
+ }
+ };
+
+ const loadStats = async () => {
+ try {
+ const response = await chatModeApiService.getStats();
+ if (response.success) {
+ setStats(response.data);
+ }
+ } catch (error) {
+ console.error('Failed to load stats:', error);
+ }
+ };
+
+ const createNewSession = async () => {
+ try {
+ const response = await chatModeApiService.createSession('New Chat');
+ if (response.success && response.data) {
+ setCurrentSessionUuid(response.data.session_uuid);
+ setMessages([]);
+ setSessions(prev => [response.data, ...prev]);
+ await chatModeApiService.activateSession(response.data.session_uuid);
+ }
+ } catch (error) {
+ console.error('Failed to create session:', error);
+ }
+ };
+
+ const switchSession = async (sessionUuid: string) => {
+ if (sessionUuid === currentSessionUuid) return;
+ setCurrentSessionUuid(sessionUuid);
+ setMessages([]);
+ await loadSessionMessages(sessionUuid);
+ chatModeApiService.activateSession(sessionUuid).catch(() => {});
+ };
+
+ const deleteSession = async (sessionUuid: string) => {
+ try {
+ await chatModeApiService.deleteSession(sessionUuid);
+ setSessions(prev => prev.filter(s => s.session_uuid !== sessionUuid));
+ if (currentSessionUuid === sessionUuid) {
+ if (sessions.length > 1) {
+ const nextSession = sessions.find(s => s.session_uuid !== sessionUuid);
+ if (nextSession) {
+ await switchSession(nextSession.session_uuid);
+ }
+ } else {
+ await createNewSession();
+ }
+ }
+ } catch (error) {
+ console.error('Failed to delete session:', error);
+ }
+ };
+
+ const handleSearch = async () => {
+ if (!searchQuery.trim()) return;
+
+ try {
+ const response = await chatModeApiService.searchMessages(searchQuery);
+ if (response.success) {
+ setSearchResults(response.data || []);
+ }
+ } catch (error) {
+ console.error('Search failed:', error);
+ }
+ };
+
+ const exportChats = async () => {
+ try {
+ const response = await chatModeApiService.exportSessions();
+ if (response.success && response.data) {
+ const blob = new Blob([JSON.stringify(response.data, null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `fincept-chat-export-${new Date().toISOString()}.json`;
+ a.click();
+ URL.revokeObjectURL(url);
+ }
+ } catch (error) {
+ console.error('Export failed:', error);
+ }
+ };
+
+ const startPolling = () => {
+ // Poll every 3 seconds for new messages (handles background responses)
+ pollIntervalRef.current = setInterval(async () => {
+ if (currentSessionUuidRef.current && isLoadingRef.current) {
+ await refreshMessages();
+ }
+ }, 3000);
+ };
+
+ const refreshMessages = async () => {
+ const sessionUuid = currentSessionUuidRef.current;
+ if (!sessionUuid) return;
+
+ try {
+ const sessionData = await chatModeApiService.getSession(sessionUuid);
+ if (sessionData.success && sessionData.data?.messages) {
+ const loadedMessages: ChatModeMessage[] = sessionData.data.messages.map((msg: any) => ({
+ id: msg.message_uuid || msg.id,
+ role: msg.role,
+ content: msg.content,
+ timestamp: new Date(msg.created_at || msg.timestamp),
+ message_uuid: msg.message_uuid
+ }));
+
+ setMessages(loadedMessages);
+
+ // If we got a response, stop loading
+ const lastMessage = loadedMessages[loadedMessages.length - 1];
+ if (lastMessage && lastMessage.role === 'assistant') {
+ setIsLoading(false);
+ }
+ }
+ } catch (error) {
+ console.error('Failed to refresh messages:', error);
+ }
+ };
+
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
const handleSendMessage = async () => {
- if (!input.trim() || isLoading) return;
-
- const userMessage: ChatModeMessage = {
- id: `user-${Date.now()}`,
- role: 'user',
- content: input.trim(),
- timestamp: new Date()
- };
+ if (!input.trim() || isLoading || !currentSessionUuid) return;
- setMessages(prev => [...prev, userMessage]);
+ const messageContent = input.trim();
setInput('');
// Reset textarea height
@@ -75,34 +267,61 @@ const ChatModeInterface: React.FC = () => {
inputRef.current.style.height = '20px';
}
+ // Immediately add user message to UI
+ const userMessage: ChatModeMessage = {
+ id: `user-${Date.now()}`,
+ role: 'user',
+ content: messageContent,
+ timestamp: new Date()
+ };
+ setMessages(prev => [...prev, userMessage]);
setIsLoading(true);
try {
- const response = await chatModeApiService.quickChat(userMessage.content);
+ // Send message to session
+ const response = await chatModeApiService.sendMessageToSession(currentSessionUuid, messageContent);
if (response.success && response.data) {
- const assistantMessage: ChatModeMessage = {
- id: `assistant-${Date.now()}`,
- role: 'assistant',
- content: response.data.ai_response,
- timestamp: new Date(response.data.timestamp)
- };
-
- setMessages(prev => [...prev, assistantMessage]);
+ // Use the AI message directly from the response instead of re-fetching
+ const aiData = response.data.ai_message;
+ if (aiData) {
+ const aiMessage: ChatModeMessage = {
+ id: aiData.message_uuid || aiData.id || `ai-${Date.now()}`,
+ role: 'assistant',
+ content: aiData.content,
+ timestamp: new Date(aiData.created_at || new Date()),
+ message_uuid: aiData.message_uuid,
+ tokens_used: aiData.tokens_used,
+ response_time_ms: aiData.response_time_ms
+ };
+ setMessages(prev => [...prev, aiMessage]);
+ }
+ setIsLoading(false);
+
+ // Refresh sessions list to update message counts, sorted newest first
+ try {
+ const sessionsResponse = await chatModeApiService.getSessions();
+ if (sessionsResponse.success && sessionsResponse.data?.length > 0) {
+ setSessions(sortSessionsNewestFirst(sessionsResponse.data));
+ }
+ } catch {
+ // Non-critical, ignore
+ }
} else {
throw new Error(response.error || 'Failed to get response');
}
} catch (error) {
console.error('Chat error:', error);
+ setIsLoading(false);
+
+ // Add error message locally
const errorMessage: ChatModeMessage = {
id: `error-${Date.now()}`,
role: 'assistant',
- content: '**ERROR:** Unable to process request. System encountered an exception. Please retry or reformulate query.',
+ content: `**ERROR:** ${error instanceof Error ? error.message : 'Unable to process request. System encountered an exception.'} Please retry or reformulate query.`,
timestamp: new Date()
};
setMessages(prev => [...prev, errorMessage]);
- } finally {
- setIsLoading(false);
}
};
@@ -125,121 +344,281 @@ const ChatModeInterface: React.FC = () => {
height: '100%',
display: 'flex',
flexDirection: 'column',
- backgroundColor: '#000000',
- color: colors.text,
- fontFamily: 'Consolas, "Courier New", monospace',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
overflow: 'hidden'
}}
>
- {/* Fincept-style Header */}
+ {/* Top Navigation Bar */}
<div
style={{
padding: '8px 16px',
- borderBottom: '2px solid #ea580c',
+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
- backgroundColor: '#0a0a0a',
- flexShrink: 0
+ backgroundColor: FINCEPT.HEADER_BG,
+ flexShrink: 0,
+ boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`
}}
>
- <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Terminal size={18} style={{ color: '#ea580c' }} />
- <span style={{ fontSize: '13px', fontWeight: 'bold', color: '#ea580c' }}>
+ <Terminal size={16} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{
+ fontSize: '11px',
+ fontWeight: 700,
+ color: FINCEPT.ORANGE,
+ letterSpacing: '0.5px'
+ }}>
FINCEPT AI TERMINAL
</span>
</div>
- <div style={{ height: '16px', width: '1px', backgroundColor: '#333' }} />
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px', fontSize: '10px' }}>
+ <span style={{ color: FINCEPT.GRAY }}>|</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', fontSize: '9px', letterSpacing: '0.5px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- <Activity size={12} style={{ color: '#22c55e' }} />
- <span style={{ color: '#22c55e' }}>ONLINE</span>
+ <Activity size={12} style={{ color: FINCEPT.GREEN }} />
+ <span style={{ color: FINCEPT.GREEN, fontWeight: 700 }}>ONLINE</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- <Database size={12} style={{ color: '#06b6d4' }} />
- <span style={{ color: '#666' }}>REALTIME</span>
+ <Database size={12} style={{ color: FINCEPT.CYAN }} />
+ <span style={{ color: FINCEPT.GRAY, fontWeight: 700 }}>REALTIME</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- <Zap size={12} style={{ color: '#fbbf24' }} />
- <span style={{ color: '#666' }}>AI READY</span>
+ <Zap size={12} style={{ color: FINCEPT.YELLOW }} />
+ <span style={{ color: FINCEPT.GRAY, fontWeight: 700 }}>AI READY</span>
</div>
</div>
</div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '10px' }}>
- <div style={{ color: '#666' }}>
- SESSION: <span style={{ color: colors.text }}>{sessionStartTime.toLocaleTimeString()}</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', fontSize: '9px', letterSpacing: '0.5px' }}>
+ <div style={{ color: FINCEPT.GRAY }}>
+ SESSION: <span style={{ color: FINCEPT.CYAN }}>{currentSessionUuid ? currentSessionUuid.substring(0, 8) : 'NONE'}</span>
</div>
- <div style={{ color: '#666' }}>
- QUERIES: <span style={{ color: colors.text }}>{Math.max(0, messages.length - 1)}</span>
+ <div style={{ color: FINCEPT.GRAY }}>
+ MESSAGES: <span style={{ color: FINCEPT.CYAN }}>{messages.length}</span>
</div>
- <div style={{ color: '#666' }}>
- TIME: <span style={{ color: colors.text }}>{currentTime.toLocaleTimeString()}</span>
+ <div style={{ color: FINCEPT.GRAY }}>
+ TIME: <span style={{ color: FINCEPT.WHITE }}>{currentTime.toLocaleTimeString()}</span>
</div>
</div>
</div>
{/* Main Content Area */}
<div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
- {/* Left Sidebar - Quick Access */}
+ {/* Left Sidebar - Sessions & Tools */}
<div
style={{
- width: '220px',
- borderRight: '1px solid #1a1a1a',
- backgroundColor: '#0a0a0a',
+ width: '280px',
+ borderRight: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.PANEL_BG,
display: 'flex',
flexDirection: 'column',
flexShrink: 0
}}
>
- <div style={{ padding: '12px', borderBottom: '1px solid #1a1a1a' }}>
- <div style={{ fontSize: '11px', fontWeight: 'bold', color: '#ea580c', marginBottom: '8px' }}>
- QUICK ACCESS
+ {/* Session Controls */}
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
+ }}>
+ SESSIONS ({sessions.length})
+ </span>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={createNewSession}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.ORANGE,
+ border: 'none',
+ borderRadius: '2px',
+ color: FINCEPT.DARK_BG,
+ fontSize: '8px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ letterSpacing: '0.5px'
+ }}
+ title="New Chat"
+ >
+ <Plus size={10} />
+ </button>
+ <button
+ onClick={exportChats}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ color: FINCEPT.GRAY,
+ fontSize: '8px',
+ fontWeight: 700,
+ cursor: 'pointer'
+ }}
+ title="Export Chats"
+ >
+ <Download size={10} />
+ </button>
+ </div>
+ </div>
+
+ {/* Search */}
+ <div style={{ padding: '8px' }}>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <input
+ type="text"
+ placeholder="SEARCH..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
+ style={{
+ flex: 1,
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ color: FINCEPT.WHITE,
+ fontSize: '9px',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}
+ />
+ <button
+ onClick={handleSearch}
+ style={{
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.ORANGE,
+ border: 'none',
+ borderRadius: '2px',
+ cursor: 'pointer'
+ }}
+ >
+ <Search size={10} color={FINCEPT.DARK_BG} />
+ </button>
</div>
</div>
- <div style={{ flex: 1, overflowY: 'auto' }}>
- {[
- { icon: TrendingUp, label: 'MARKET OVERVIEW', color: '#06b6d4' },
- { icon: Database, label: 'PORTFOLIO STATUS', color: '#22c55e' },
- { icon: Activity, label: 'ANALYTICS SUITE', color: '#fbbf24' },
- { icon: Terminal, label: 'CUSTOM QUERIES', color: '#a855f7' }
- ].map((item, idx) => (
+
+ {/* Sessions List */}
+ <div style={{ flex: 1, overflowY: 'auto', padding: '0 8px' }}>
+ {isInitializing && sessions.length === 0 && (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: '24px 12px',
+ gap: '10px'
+ }}>
+ <div className="terminal-spinner" />
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>
+ LOADING SESSIONS...
+ </span>
+ </div>
+ )}
+ {sessions.map((session) => (
<div
- key={idx}
+ key={session.session_uuid}
+ onClick={() => switchSession(session.session_uuid)}
style={{
padding: '10px 12px',
- borderBottom: '1px solid #1a1a1a',
+ backgroundColor: currentSessionUuid === session.session_uuid ? `${FINCEPT.ORANGE}15` : 'transparent',
+ borderLeft: currentSessionUuid === session.session_uuid ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
cursor: 'pointer',
- transition: 'background 0.2s',
- fontSize: '10px'
+ transition: 'all 0.2s',
+ marginBottom: '4px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}
+ onMouseEnter={(e) => {
+ if (currentSessionUuid !== session.session_uuid) {
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (currentSessionUuid !== session.session_uuid) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
}}
- onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#1a1a1a'}
- onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}
>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <item.icon size={14} style={{ color: item.color }} />
- <span style={{ color: '#999' }}>{item.label}</span>
+ <div style={{ flex: 1, overflow: 'hidden' }}>
+ <div style={{
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ fontWeight: 700,
+ marginBottom: '2px',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap'
+ }}>
+ {session.title}
+ </div>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '8px',
+ letterSpacing: '0.5px'
+ }}>
+ {session.message_count} MSGS
+ </div>
</div>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ deleteSession(session.session_uuid);
+ }}
+ style={{
+ padding: '4px',
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: FINCEPT.RED,
+ cursor: 'pointer',
+ display: 'flex'
+ }}
+ >
+ <Trash2 size={10} />
+ </button>
</div>
))}
</div>
- <div style={{ padding: '12px', borderTop: '1px solid #1a1a1a', fontSize: '9px' }}>
- <div style={{ color: '#666', marginBottom: '4px' }}>SYSTEM STATUS</div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
- <span style={{ color: '#666' }}>API:</span>
- <span style={{ color: '#22c55e' }}>CONNECTED</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
- <span style={{ color: '#666' }}>LATENCY:</span>
- <span style={{ color: '#22c55e' }}>42ms</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#666' }}>UPTIME:</span>
- <span style={{ color: colors.text }}>99.9%</span>
+ {/* Stats Footer */}
+ {stats && (
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '9px',
+ letterSpacing: '0.5px'
+ }}>
+ <div style={{ color: FINCEPT.GRAY, marginBottom: '6px', fontWeight: 700 }}>USAGE STATS</div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
+ <span style={{ color: FINCEPT.GRAY }}>TOTAL MSGS:</span>
+ <span style={{ color: FINCEPT.CYAN, fontWeight: 700 }}>{stats.total_messages || 0}</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
+ <span style={{ color: FINCEPT.GRAY }}>TOTAL TOKENS:</span>
+ <span style={{ color: FINCEPT.CYAN, fontWeight: 700 }}>{stats.total_tokens?.toLocaleString() || 0}</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.GRAY }}>AVG RESPONSE:</span>
+ <span style={{ color: FINCEPT.GREEN, fontWeight: 700 }}>{stats.avg_response_time_ms || 0}MS</span>
+ </div>
</div>
- </div>
+ )}
</div>
{/* Messages Area */}
@@ -257,38 +636,71 @@ const ChatModeInterface: React.FC = () => {
flex: 1,
overflowY: 'auto',
padding: '16px',
- backgroundColor: '#000000'
+ backgroundColor: FINCEPT.DARK_BG
}}
className="custom-scrollbar"
>
- {messages.map((message) => (
- <ChatMessageBubble key={message.id} message={message} />
- ))}
-
- {isLoading && (
- <div
- style={{
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- color: '#666',
- fontSize: '11px',
- padding: '12px',
- marginTop: '8px',
- backgroundColor: '#0a0a0a',
- border: '1px solid #1a1a1a'
- }}
- >
- <div className="terminal-spinner" />
- <span>PROCESSING QUERY...</span>
+ {(isInitializing || isLoadingMessages) ? (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ gap: '16px'
+ }}>
+ <div className="terminal-spinner-lg" />
+ <span style={{
+ color: FINCEPT.ORANGE,
+ fontSize: '10px',
+ fontWeight: 700,
+ letterSpacing: '1px'
+ }}>
+ {isInitializing ? 'CONNECTING TO FINCEPT API...' : 'LOADING MESSAGES...'}
+ </span>
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px'
+ }}>
+ PLEASE WAIT
+ </span>
</div>
- )}
+ ) : (
+ <>
+ {messages.map((message) => (
+ <ChatMessageBubble key={message.id} message={message} />
+ ))}
- <div ref={messagesEndRef} />
+ {isLoading && (
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ padding: '10px 12px',
+ marginTop: '8px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px'
+ }}
+ >
+ <div className="terminal-spinner" />
+ <span>PROCESSING QUERY...</span>
+ </div>
+ )}
+
+ <div ref={messagesEndRef} />
+ </>
+ )}
</div>
{/* Suggestions */}
- {messages.length <= 1 && (
+ {!isInitializing && !isLoadingMessages && messages.length <= 1 && (
<div style={{ flexShrink: 0 }}>
<ChatSuggestions onSuggestionClick={handleSuggestionClick} />
</div>
@@ -297,9 +709,9 @@ const ChatModeInterface: React.FC = () => {
{/* Input Area */}
<div
style={{
- padding: '12px 16px',
- borderTop: '2px solid #1a1a1a',
- backgroundColor: '#0a0a0a',
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
flexShrink: 0
}}
>
@@ -308,34 +720,34 @@ const ChatModeInterface: React.FC = () => {
display: 'flex',
gap: '8px',
alignItems: 'flex-end',
- backgroundColor: '#000000',
- border: '1px solid #333',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
padding: '8px'
}}
>
<div style={{ display: 'flex', alignItems: 'center', paddingLeft: '4px' }}>
- <span style={{ color: '#ea580c', fontSize: '12px', fontWeight: 'bold' }}>{'>'}</span>
+ <span style={{ color: FINCEPT.ORANGE, fontSize: '12px', fontWeight: 700 }}>{'>'}</span>
</div>
<textarea
ref={inputRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
- // Auto-resize
const target = e.target as HTMLTextAreaElement;
target.style.height = '20px';
target.style.height = `${Math.min(target.scrollHeight, 100)}px`;
}}
onKeyDown={handleKeyPress}
- placeholder="ENTER QUERY..."
- disabled={isLoading}
+ placeholder={isInitializing ? "CONNECTING..." : "ENTER QUERY..."}
+ disabled={isLoading || isInitializing}
style={{
flex: 1,
background: 'transparent',
border: 'none',
- color: colors.text,
- fontSize: '12px',
- fontFamily: 'Consolas, "Courier New", monospace',
+ color: FINCEPT.WHITE,
+ fontSize: '11px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
resize: 'none',
outline: 'none',
height: '20px',
@@ -347,28 +759,37 @@ const ChatModeInterface: React.FC = () => {
/>
<button
onClick={handleSendMessage}
- disabled={!input.trim() || isLoading}
+ disabled={!input.trim() || isLoading || isInitializing}
style={{
- background: input.trim() && !isLoading ? '#ea580c' : '#333',
+ padding: '8px 16px',
+ backgroundColor: input.trim() && !isLoading && !isInitializing ? FINCEPT.ORANGE : FINCEPT.MUTED,
border: 'none',
- padding: '6px 12px',
- cursor: input.trim() && !isLoading ? 'pointer' : 'not-allowed',
+ borderRadius: '2px',
+ cursor: input.trim() && !isLoading && !isInitializing ? 'pointer' : 'not-allowed',
display: 'flex',
alignItems: 'center',
- gap: '6px',
- color: input.trim() && !isLoading ? '#000' : '#666',
- fontSize: '10px',
- fontWeight: 'bold',
- fontFamily: 'Consolas, "Courier New", monospace',
+ gap: '4px',
+ color: FINCEPT.DARK_BG,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
transition: 'all 0.2s',
- opacity: input.trim() && !isLoading ? 1 : 0.7
+ opacity: input.trim() && !isLoading && !isInitializing ? 1 : 0.5
}}
>
<Send size={12} />
SEND
</button>
</div>
- <div style={{ fontSize: '9px', color: '#666', marginTop: '6px', display: 'flex', justifyContent: 'space-between' }}>
+ <div style={{
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ marginTop: '6px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ letterSpacing: '0.5px'
+ }}>
<span>ENTER TO SEND | SHIFT+ENTER FOR NEW LINE</span>
<span>POWERED BY FINCEPT AI ENGINE</span>
</div>
@@ -378,17 +799,18 @@ const ChatModeInterface: React.FC = () => {
<style>{`
.custom-scrollbar::-webkit-scrollbar {
- width: 8px;
+ width: 6px;
+ height: 6px;
}
.custom-scrollbar::-webkit-scrollbar-track {
- background: #0a0a0a;
+ background: ${FINCEPT.DARK_BG};
}
.custom-scrollbar::-webkit-scrollbar-thumb {
- background: #333;
- border-radius: 4px;
+ background: ${FINCEPT.BORDER};
+ border-radius: 3px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
- background: #555;
+ background: ${FINCEPT.MUTED};
}
.terminal-spinner {
width: 12px;
@@ -398,6 +820,14 @@ const ChatModeInterface: React.FC = () => {
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
+ .terminal-spinner-lg {
+ width: 32px;
+ height: 32px;
+ border: 3px solid #333;
+ border-top-color: #FF8800;
+ border-radius: 50%;
+ animation: spin 0.8s linear infinite;
+ }
@keyframes spin {
to { transform: rotate(360deg); }
}
diff --git a/fincept-terminal-desktop/src/components/chat-mode/components/ChatMessageBubble.tsx b/fincept-terminal-desktop/src/components/chat-mode/components/ChatMessageBubble.tsx
index ab2a36800..4e2e63a1e 100644
--- a/fincept-terminal-desktop/src/components/chat-mode/components/ChatMessageBubble.tsx
+++ b/fincept-terminal-desktop/src/components/chat-mode/components/ChatMessageBubble.tsx
@@ -2,21 +2,39 @@
// Fincept-style message bubble component
import React from 'react';
-import { Terminal, User } from 'lucide-react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { Terminal, User, Clock } from 'lucide-react';
import { ChatModeMessage } from '@/services/data-sources/chatModeApi';
import MarkdownRenderer from '@/components/common/MarkdownRenderer';
+// Fincept Terminal Design System Colors
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
+};
+
interface ChatMessageBubbleProps {
message: ChatModeMessage;
}
const ChatMessageBubble: React.FC<ChatMessageBubbleProps> = ({ message }) => {
- const { colors } = useTerminalTheme();
const isUser = message.role === 'user';
const formatTime = (date: Date) => {
return new Date(date).toLocaleTimeString('en-US', {
+ hour12: false,
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
@@ -24,146 +42,66 @@ const ChatMessageBubble: React.FC<ChatMessageBubbleProps> = ({ message }) => {
};
return (
- <div
- style={{
- marginBottom: '12px',
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{
display: 'flex',
- flexDirection: 'column',
- gap: '4px'
- }}
- >
- {/* Header */}
- <div
- style={{
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- fontSize: '10px',
- color: '#666',
- fontFamily: 'Consolas, "Courier New", monospace'
- }}
- >
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ justifyContent: isUser ? 'flex-end' : 'flex-start',
+ marginBottom: '4px'
+ }}>
+ <div style={{
+ maxWidth: '85%',
+ minWidth: '120px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${isUser ? FINCEPT.YELLOW : FINCEPT.ORANGE}`,
+ borderRadius: '2px',
+ padding: '10px'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '8px',
+ paddingBottom: '6px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ {isUser ? (
+ <User size={12} color={FINCEPT.YELLOW} />
+ ) : (
+ <Terminal size={12} color={FINCEPT.ORANGE} />
+ )}
+ <span style={{
+ color: isUser ? FINCEPT.YELLOW : FINCEPT.ORANGE,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>
+ {isUser ? 'YOU' : 'FINCEPT AI'}
+ </span>
+ <Clock size={10} color={FINCEPT.GRAY} />
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {formatTime(message.timestamp)}
+ </span>
+ </div>
{isUser ? (
- <User size={12} style={{ color: '#06b6d4' }} />
+ <div style={{
+ color: FINCEPT.WHITE,
+ fontSize: '11px',
+ lineHeight: '1.6',
+ whiteSpace: 'pre-wrap',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {message.content}
+ </div>
) : (
- <Terminal size={12} style={{ color: '#ea580c' }} />
+ <MarkdownRenderer content={message.content} />
)}
- <span style={{ color: isUser ? '#06b6d4' : '#ea580c', fontWeight: 'bold' }}>
- {isUser ? 'USER' : 'FINCEPT AI'}
- </span>
</div>
- <span style={{ color: '#333' }}>|</span>
- <span>{formatTime(message.timestamp)}</span>
- </div>
-
- {/* Message Content */}
- <div
- style={{
- background: isUser ? '#0a0a0a' : '#000000',
- border: `1px solid ${isUser ? '#333' : '#1a1a1a'}`,
- borderLeft: `3px solid ${isUser ? '#06b6d4' : '#ea580c'}`,
- padding: '12px 14px',
- fontSize: '12px',
- lineHeight: '1.6',
- fontFamily: 'Consolas, "Courier New", monospace',
- color: colors.text
- }}
- >
- {isUser ? (
- <div style={{ whiteSpace: 'pre-wrap' }}>
- {message.content}
- </div>
- ) : (
- <div className="terminal-markdown">
- <MarkdownRenderer content={message.content} />
- </div>
- )}
</div>
-
- <style>{`
- .terminal-markdown h1,
- .terminal-markdown h2,
- .terminal-markdown h3 {
- color: #ea580c;
- font-weight: bold;
- margin: 8px 0 6px 0;
- }
- .terminal-markdown h1 { font-size: 14px; }
- .terminal-markdown h2 { font-size: 13px; }
- .terminal-markdown h3 { font-size: 12px; }
- .terminal-markdown p {
- margin: 6px 0;
- }
- .terminal-markdown ul,
- .terminal-markdown ol {
- margin: 6px 0 6px 20px;
- }
- .terminal-markdown li {
- margin: 3px 0;
- }
- .terminal-markdown strong {
- color: #ea580c;
- font-weight: bold;
- }
- .terminal-markdown code {
- background: #1a1a1a;
- padding: 2px 6px;
- border-radius: 2px;
- color: #22c55e;
- font-family: 'Consolas', 'Courier New', monospace;
- font-size: 11px;
- }
- .terminal-markdown pre {
- background: #0a0a0a;
- border: 1px solid #333;
- border-left: 3px solid #22c55e;
- padding: 10px;
- margin: 8px 0;
- overflow-x: auto;
- border-radius: 2px;
- }
- .terminal-markdown pre code {
- background: transparent;
- padding: 0;
- }
- .terminal-markdown a {
- color: #06b6d4;
- text-decoration: none;
- border-bottom: 1px dotted #06b6d4;
- }
- .terminal-markdown a:hover {
- color: #22d3ee;
- border-bottom-color: #22d3ee;
- }
- .terminal-markdown blockquote {
- border-left: 3px solid #fbbf24;
- padding-left: 12px;
- margin: 8px 0;
- color: #999;
- }
- .terminal-markdown table {
- border-collapse: collapse;
- margin: 8px 0;
- width: 100%;
- }
- .terminal-markdown th,
- .terminal-markdown td {
- border: 1px solid #333;
- padding: 6px 10px;
- text-align: left;
- }
- .terminal-markdown th {
- background: #1a1a1a;
- color: #ea580c;
- font-weight: bold;
- }
- .terminal-markdown hr {
- border: none;
- border-top: 1px solid #333;
- margin: 12px 0;
- }
- `}</style>
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/chat-mode/components/ChatSuggestions.tsx b/fincept-terminal-desktop/src/components/chat-mode/components/ChatSuggestions.tsx
index e2f28a0fd..989070260 100644
--- a/fincept-terminal-desktop/src/components/chat-mode/components/ChatSuggestions.tsx
+++ b/fincept-terminal-desktop/src/components/chat-mode/components/ChatSuggestions.tsx
@@ -3,14 +3,31 @@
import React from 'react';
import { TrendingUp, Newspaper, PieChart, Calculator, DollarSign, BarChart3 } from 'lucide-react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
+
+// Fincept Terminal Design System Colors
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
+};
interface ChatSuggestionsProps {
onSuggestionClick: (suggestion: string) => void;
}
const ChatSuggestions: React.FC<ChatSuggestionsProps> = ({ onSuggestionClick }) => {
- const { colors, fontSize } = useTerminalTheme();
const suggestions = [
{
@@ -48,20 +65,25 @@ const ChatSuggestions: React.FC<ChatSuggestionsProps> = ({ onSuggestionClick })
return (
<div
style={{
- padding: '0 24px 20px',
- display: 'flex',
- flexDirection: 'column',
- gap: '12px'
+ padding: '12px 16px 16px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderTop: `1px solid ${FINCEPT.BORDER}`
}}
>
- <h3 style={{ color: colors.textMuted, fontSize: fontSize.small, fontWeight: 'bold', margin: 0 }}>
+ <div style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ marginBottom: '12px'
+ }}>
TRY ASKING:
- </h3>
+ </div>
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
- gap: '10px'
+ gap: '8px'
}}
>
{suggestions.map((suggestion, idx) => (
@@ -69,36 +91,41 @@ const ChatSuggestions: React.FC<ChatSuggestionsProps> = ({ onSuggestionClick })
key={idx}
onClick={() => onSuggestionClick(suggestion.text)}
style={{
- background: colors.panel,
- border: `1px solid ${colors.primary}33`,
- borderRadius: '8px',
- padding: '12px 14px',
+ padding: '10px 12px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
cursor: 'pointer',
textAlign: 'left',
display: 'flex',
alignItems: 'center',
- gap: '10px',
+ gap: '8px',
transition: 'all 0.2s',
- color: colors.text,
- fontSize: fontSize.small
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}
onMouseEnter={(e) => {
- e.currentTarget.style.background = `${colors.primary}11`;
- e.currentTarget.style.borderColor = colors.primary;
- e.currentTarget.style.transform = 'translateY(-2px)';
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
}}
onMouseLeave={(e) => {
- e.currentTarget.style.background = colors.panel;
- e.currentTarget.style.borderColor = `${colors.primary}33`;
- e.currentTarget.style.transform = 'translateY(0)';
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
}}
>
- <div style={{ color: colors.primary }}>{suggestion.icon}</div>
+ <div style={{ color: FINCEPT.ORANGE }}>{suggestion.icon}</div>
<div style={{ flex: 1 }}>
- <div style={{ fontSize: fontSize.tiny, color: colors.textMuted, marginBottom: '2px' }}>
- {suggestion.category}
+ <div style={{
+ fontSize: '8px',
+ color: FINCEPT.GRAY,
+ marginBottom: '2px',
+ letterSpacing: '0.5px',
+ fontWeight: 700
+ }}>
+ {suggestion.category.toUpperCase()}
</div>
- <div>{suggestion.text}</div>
+ <div style={{ fontSize: '10px', lineHeight: '1.4' }}>{suggestion.text}</div>
</div>
</button>
))}
diff --git a/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts b/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts
index ce36c1f52..0008fb14f 100644
--- a/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts
+++ b/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts
@@ -114,6 +114,16 @@ export const COMMANDS: Command[] = [
shortcut: 'F10',
keywords: ['ai', 'chat', 'assistant', 'bot', 'help']
},
+ {
+ id: 'notes',
+ name: 'Notes',
+ description: 'Notes and reports',
+ aliases: ['notes', 'note', 'reports', 'docs'],
+ category: 'navigation',
+ action: 'notes',
+ shortcut: 'F11',
+ keywords: ['notes', 'reports', 'documents', 'save', 'write']
+ },
{
id: 'prof',
name: 'Profile',
diff --git a/fincept-terminal-desktop/src/components/common/HeaderSupportButtons.tsx b/fincept-terminal-desktop/src/components/common/HeaderSupportButtons.tsx
index fe50f7fa5..19ac33f66 100644
--- a/fincept-terminal-desktop/src/components/common/HeaderSupportButtons.tsx
+++ b/fincept-terminal-desktop/src/components/common/HeaderSupportButtons.tsx
@@ -3,6 +3,7 @@
import React, { useState } from 'react';
import { MessageSquarePlus, Mail, Newspaper, X, Star, Send, Check } from 'lucide-react';
+import { useAuth } from '@/contexts/AuthContext';
import {
submitContactForm,
submitFeedback,
@@ -219,14 +220,15 @@ const SubmitButton: React.FC<{
// Main component
export const HeaderSupportButtons: React.FC = () => {
+ const { session } = useAuth();
+ const apiKey = session?.api_key || '';
+
// Modal states
const [showFeedback, setShowFeedback] = useState(false);
const [showContact, setShowContact] = useState(false);
const [showNewsletter, setShowNewsletter] = useState(false);
// Feedback form state
- const [feedbackName, setFeedbackName] = useState('');
- const [feedbackEmail, setFeedbackEmail] = useState('');
const [feedbackRating, setFeedbackRating] = useState(0);
const [feedbackText, setFeedbackText] = useState('');
const [feedbackCategory, setFeedbackCategory] = useState('general');
@@ -251,8 +253,6 @@ export const HeaderSupportButtons: React.FC = () => {
// Reset functions
const resetFeedback = () => {
- setFeedbackName('');
- setFeedbackEmail('');
setFeedbackRating(0);
setFeedbackText('');
setFeedbackCategory('general');
@@ -282,18 +282,21 @@ export const HeaderSupportButtons: React.FC = () => {
return;
}
+ if (!apiKey) {
+ setFeedbackError('Please login to submit feedback');
+ return;
+ }
+
setFeedbackLoading(true);
setFeedbackError('');
const data: FeedbackFormData = {
- name: feedbackName || undefined,
- email: feedbackEmail || undefined,
rating: feedbackRating,
feedback_text: feedbackText,
category: feedbackCategory,
};
- const result = await submitFeedback(data);
+ const result = await submitFeedback(data, apiKey);
setFeedbackLoading(false);
if (result.success) {
@@ -441,19 +444,6 @@ export const HeaderSupportButtons: React.FC = () => {
{/* Feedback Modal */}
<Modal isOpen={showFeedback} onClose={() => { setShowFeedback(false); resetFeedback(); }} title="SEND FEEDBACK">
- <InputField
- label="Name"
- value={feedbackName}
- onChange={setFeedbackName}
- placeholder="Your name (optional)"
- />
- <InputField
- label="Email"
- value={feedbackEmail}
- onChange={setFeedbackEmail}
- placeholder="Your email (optional)"
- type="email"
- />
<StarRating rating={feedbackRating} onChange={setFeedbackRating} />
<div style={{ marginBottom: '12px' }}>
<label style={{ color: COLORS.TEXT, fontSize: '11px', display: 'block', marginBottom: '4px' }}>
diff --git a/fincept-terminal-desktop/src/components/common/MarkdownRenderer.tsx b/fincept-terminal-desktop/src/components/common/MarkdownRenderer.tsx
index 2c0a0024e..879306e1d 100644
--- a/fincept-terminal-desktop/src/components/common/MarkdownRenderer.tsx
+++ b/fincept-terminal-desktop/src/components/common/MarkdownRenderer.tsx
@@ -15,163 +15,272 @@ marked.setOptions({
const MARKDOWN_CSS = `
.fincept-md h1 {
- color: #FFA500;
- font-size: 20px;
- font-weight: bold;
- margin-top: 16px;
- margin-bottom: 12px;
- border-bottom: 2px solid #FFA500;
+ color: #FF8800;
+ font-size: 14px;
+ font-weight: 700;
+ margin: 12px 0 8px 0;
+ padding-bottom: 6px;
+ border-bottom: 2px solid #FF8800;
+ letter-spacing: 0.5px;
+ text-transform: uppercase;
}
.fincept-md h2 {
- color: #FFA500;
- font-size: 18px;
- font-weight: bold;
- margin-top: 14px;
- margin-bottom: 10px;
- border-bottom: 1px solid #787878;
+ color: #FFD700;
+ font-size: 12px;
+ font-weight: 700;
+ margin: 10px 0 6px 0;
+ padding-bottom: 4px;
+ border-bottom: 1px solid #2A2A2A;
+ letter-spacing: 0.5px;
}
.fincept-md h3 {
- color: #FFFF00;
- font-size: 16px;
- font-weight: bold;
- margin-top: 12px;
- margin-bottom: 8px;
+ color: #00E5FF;
+ font-size: 11px;
+ font-weight: 700;
+ margin: 8px 0 4px 0;
+ letter-spacing: 0.5px;
}
.fincept-md h4 {
- color: #FFFF00;
- font-size: 15px;
- font-weight: bold;
- margin-top: 10px;
- margin-bottom: 6px;
+ color: #FFFFFF;
+ font-size: 10px;
+ font-weight: 700;
+ margin: 6px 0 3px 0;
+ letter-spacing: 0.5px;
}
.fincept-md h5, .fincept-md h6 {
- color: #FFFFFF;
- font-size: 14px;
- font-weight: bold;
- margin-top: 8px;
- margin-bottom: 4px;
+ color: #787878;
+ font-size: 10px;
+ font-weight: 700;
+ margin: 4px 0 2px 0;
+ letter-spacing: 0.5px;
}
.fincept-md p {
- margin-bottom: 12px;
+ margin: 0 0 8px 0;
color: #FFFFFF;
+ font-size: 11px;
+ line-height: 1.6;
+ font-family: "IBM Plex Mono", Consolas, monospace;
}
.fincept-md ul {
- margin-left: 20px;
- margin-bottom: 12px;
- list-style-type: disc;
+ margin: 0 0 8px 0;
+ padding-left: 16px;
+ list-style-type: none;
color: #FFFFFF;
}
+.fincept-md ul li:before {
+ content: "▸";
+ color: #FF8800;
+ font-weight: bold;
+ display: inline-block;
+ width: 12px;
+ margin-left: -12px;
+}
.fincept-md ol {
- margin-left: 20px;
- margin-bottom: 12px;
+ margin: 0 0 8px 0;
+ padding-left: 16px;
list-style-type: decimal;
color: #FFFFFF;
}
.fincept-md li {
- margin-bottom: 6px;
+ margin-bottom: 4px;
color: #FFFFFF;
+ font-size: 10px;
+ line-height: 1.5;
+ font-family: "IBM Plex Mono", Consolas, monospace;
+}
+.fincept-md li strong {
+ color: #00E5FF;
+ font-weight: 700;
}
.fincept-md pre {
- background-color: #000000;
+ background-color: #0F0F0F;
padding: 0;
- margin: 0 0 12px 0;
+ margin: 0 0 8px 0;
overflow-x: auto;
+ border: 1px solid #2A2A2A;
+ border-radius: 2px;
}
.fincept-md pre code {
display: block;
- background-color: #000000;
- color: #00C800;
- padding: 12px;
- border-radius: 4px;
- font-size: 13px;
- font-family: Consolas, monospace;
- border: 1px solid #787878;
+ background-color: #0F0F0F;
+ color: #00D66F;
+ padding: 8px;
+ border-radius: 2px;
+ font-size: 10px;
+ font-family: "IBM Plex Mono", Consolas, monospace;
overflow-x: auto;
white-space: pre-wrap;
+ line-height: 1.4;
}
.fincept-md code {
- background-color: #000000;
- color: #00C800;
- padding: 2px 6px;
- border-radius: 3px;
- font-size: 13px;
- font-family: Consolas, monospace;
- border: 1px solid #787878;
+ background-color: #0F0F0F;
+ color: #00E5FF;
+ padding: 2px 4px;
+ border-radius: 2px;
+ font-size: 10px;
+ font-family: "IBM Plex Mono", Consolas, monospace;
+ border: 1px solid #2A2A2A;
}
.fincept-md blockquote {
- border-left: 4px solid #FFA500;
- margin-left: 0;
- padding-left: 16px;
- margin-bottom: 12px;
- color: #787878;
+ border-left: 2px solid #FF8800;
+ margin: 0 0 8px 0;
+ padding: 6px 0 6px 12px;
+ background-color: rgba(255, 136, 0, 0.05);
+ color: #FFFFFF;
+ font-size: 10px;
font-style: italic;
+ border-radius: 2px;
}
.fincept-md a {
- color: #FFA500;
+ color: #FF8800;
text-decoration: underline;
cursor: pointer;
+ font-size: 10px;
+}
+.fincept-md a:hover {
+ color: #FFD700;
}
.fincept-md table {
border-collapse: collapse;
width: 100%;
- margin-bottom: 12px;
- border: 1px solid #787878;
+ margin: 8px 0;
+ border: 1px solid #2A2A2A;
+ font-size: 10px;
+ background-color: #0F0F0F;
}
.fincept-md thead {
- background-color: #000000;
+ background-color: #1A1A1A;
}
.fincept-md tr {
- border-bottom: 1px solid #787878;
+ border-bottom: 1px solid #2A2A2A;
}
.fincept-md th {
- padding: 8px;
+ padding: 6px 8px;
text-align: left;
- color: #FFA500;
- font-weight: bold;
- border: 1px solid #787878;
+ color: #FF8800;
+ font-weight: 700;
+ border: 1px solid #2A2A2A;
+ letter-spacing: 0.5px;
+ font-size: 9px;
+ text-transform: uppercase;
}
.fincept-md td {
- padding: 8px;
+ padding: 6px 8px;
color: #FFFFFF;
- border: 1px solid #787878;
+ border: 1px solid #2A2A2A;
+ font-family: "IBM Plex Mono", Consolas, monospace;
}
.fincept-md hr {
border: none;
- border-top: 1px solid #787878;
- margin-top: 16px;
- margin-bottom: 16px;
+ border-top: 1px solid #2A2A2A;
+ margin: 12px 0;
}
.fincept-md strong {
- color: #FFFF00;
- font-weight: bold;
+ color: #00E5FF;
+ font-weight: 700;
}
.fincept-md em {
- color: #FFFFFF;
+ color: #787878;
font-style: italic;
}
.fincept-md del {
- color: #787878;
+ color: #4A4A4A;
text-decoration: line-through;
}
.fincept-md input[type="checkbox"] {
- margin-right: 6px;
+ margin-right: 4px;
+}
+/* Price/Data Cards */
+.price-card {
+ display: inline-flex;
+ flex-direction: column;
+ background-color: #0F0F0F;
+ border: 1px solid #2A2A2A;
+ border-left: 2px solid #FF8800;
+ border-radius: 2px;
+ padding: 6px 8px;
+ margin: 4px 4px 4px 0;
+ min-width: 120px;
+ gap: 2px;
+}
+.price-card-positive { border-left-color: #00D66F; }
+.price-card-negative { border-left-color: #FF3B3B; }
+.price-card-label {
+ font-size: 8px;
+ color: #787878;
+ font-weight: 700;
+ letter-spacing: 0.5px;
+ text-transform: uppercase;
+}
+.price-card-value {
+ font-size: 12px;
+ color: #00E5FF;
+ font-weight: 700;
+ font-family: "IBM Plex Mono", Consolas, monospace;
}
+.price-card-change {
+ font-size: 9px;
+ font-weight: 700;
+}
+.price-card-change.positive { color: #00D66F; }
+.price-card-change.negative { color: #FF3B3B; }
`;
+// Parse content for price data patterns and convert to cards
+const parseDataCards = (text: string): string => {
+ // Pattern: Stock (SYMBOL) - +X.XX% Price: $XXX.XX
+ const stockPattern = /([A-Z][a-zA-Z\s&]+)\s*\(([A-Z:]+)\)\s*-\s*([\+\-]?\d+\.?\d*%)\s*(?:Current|Price):\s*\$?([\d,]+\.?\d*)/g;
+
+ let parsed = text.replace(stockPattern, (match, name, symbol, change, price) => {
+ const isPositive = change.startsWith('+');
+ const cardClass = isPositive ? 'price-card-positive' : 'price-card-negative';
+ const changeClass = isPositive ? 'positive' : 'negative';
+
+ return `<div class="price-card ${cardClass}">
+ <div class="price-card-label">${symbol}</div>
+ <div class="price-card-value">$${price}</div>
+ <div class="price-card-change ${changeClass}">${change}</div>
+ </div>`;
+ });
+
+ // Pattern: Cryptocurrency (SYMBOL) - +X.XX% Price: $XXX Market Cap: $XXB
+ const cryptoPattern = /([A-Z][a-zA-Z\s]+)\s*\(([A-Z]+)\)\s*-\s*([\+\-]?\d+\.?\d*%)\s*Price:\s*\$?([\d,]+\.?\d*)\s*Market Cap:\s*\$?([\d,]+\.?\d*[BMK]?)/g;
+
+ parsed = parsed.replace(cryptoPattern, (match, name, symbol, change, price, mcap) => {
+ const isPositive = change.startsWith('+');
+ const cardClass = isPositive ? 'price-card-positive' : 'price-card-negative';
+ const changeClass = isPositive ? 'positive' : 'negative';
+
+ return `<div class="price-card ${cardClass}">
+ <div class="price-card-label">${symbol} • ${name}</div>
+ <div class="price-card-value">$${price}</div>
+ <div class="price-card-change ${changeClass}">${change} • MC: $${mcap}</div>
+ </div>`;
+ });
+
+ return parsed;
+};
+
const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({ content, style = {} }) => {
const markdownStyles: React.CSSProperties = {
color: '#FFFFFF',
- fontSize: '14px',
+ fontSize: '11px',
lineHeight: '1.6',
+ fontFamily: '"IBM Plex Mono", Consolas, monospace',
...style
};
const html = useMemo(() => {
if (!content || typeof content !== 'string') return '';
try {
- const raw = marked.parse(content) as string;
+ // First, parse data cards from raw content
+ const withCards = parseDataCards(content);
+
+ // Then parse markdown
+ const raw = marked.parse(withCards) as string;
+
return DOMPurify.sanitize(raw, {
- ADD_ATTR: ['target'],
+ ADD_ATTR: ['target', 'class'],
ALLOWED_TAGS: [
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'p', 'br', 'hr',
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 184d7d7ca..6552aee93 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -64,6 +64,7 @@ const Visualization3DTab = React.lazy(() => import('@/components/tabs/visualizat
const PolymarketTab = React.lazy(() => import('@/components/tabs/polymarket'));
const TradeVisualizationTab = React.lazy(() => import('@/components/tabs/trade-visualization'));
const AlphaArenaTab = React.lazy(() => import('@/components/tabs/alpha-arena'));
+const NotesTab = React.lazy(() => import('@/components/tabs/notes').then(m => ({ default: m.NotesTab })));
// Loading fallback component for lazy-loaded tabs
const TabLoadingFallback = () => (
@@ -1063,6 +1064,11 @@ function FinxeptTerminalContent() {
onNavigateToTab={(tabName) => setActiveTab(tabName)}
/>
</TabsContent>
+ <TabsContent value="notes" className="h-full m-0 p-0">
+ <React.Suspense fallback={<TabLoadingFallback />}>
+ <NotesTab />
+ </React.Suspense>
+ </TabsContent>
<TabsContent value="mcp" className="h-full m-0 p-0">
<MCPTab onNavigateToTab={(tabName) => setActiveTab(tabName)} />
</TabsContent>
diff --git a/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTabNew.tsx b/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTabNew.tsx
index 64312d1fe..61f005d45 100644
--- a/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTabNew.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTabNew.tsx
@@ -11,6 +11,7 @@ import { Activity, AlertTriangle, Zap } from 'lucide-react';
import { backtestingRegistry } from '@/services/backtesting/BacktestingProviderRegistry';
import { BacktestRequest } from '@/services/backtesting/interfaces/types';
import { sqliteService } from '@/services/core/sqliteService';
+import { portfolioService, Portfolio } from '@/services/portfolio/portfolioService';
import {
F, panelStyle, BacktestConfigExtended, StrategyType,
ExtendedEquityPoint, ExtendedTrade, AdvancedMetrics, MonthlyReturnsData, RollingMetric,
@@ -36,8 +37,8 @@ const BacktestingTabNew: React.FC = () => {
const [config, setConfig] = useState<BacktestConfigExtended>({
symbols: ['SPY'],
weights: [1.0],
- startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
- endDate: new Date().toISOString().split('T')[0],
+ startDate: new Date(Date.now() - 366 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
+ endDate: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
initialCapital: 100000,
strategyType: 'sma_crossover',
parameters: { fastPeriod: 10, slowPeriod: 20 },
@@ -73,11 +74,42 @@ const BacktestingTabNew: React.FC = () => {
const [showOptimization, setShowOptimization] = useState(false);
const [isOptimizing, setIsOptimizing] = useState(false);
+ // --- Portfolio State ---
+ const [portfolios, setPortfolios] = useState<Portfolio[]>([]);
+
// --- Provider Registration ---
useEffect(() => {
registerProviders();
}, []);
+ // --- Fetch User Portfolios ---
+ useEffect(() => {
+ portfolioService.getPortfolios()
+ .then(setPortfolios)
+ .catch(() => setPortfolios([]));
+ }, []);
+
+ // --- Portfolio Selection Handler ---
+ const handlePortfolioSelect = useCallback(async (portfolioId: string) => {
+ if (!portfolioId) return;
+ try {
+ const assets = await portfolioService.getPortfolioAssets(portfolioId);
+ if (assets.length === 0) return;
+
+ const symbols = assets.map(a => a.symbol);
+ const costBases = assets.map(a => a.quantity * a.avg_buy_price);
+ const totalCost = costBases.reduce((s, c) => s + c, 0);
+
+ const weights = totalCost > 0
+ ? costBases.map(c => c / totalCost)
+ : assets.map(() => 1.0 / assets.length);
+
+ setConfig(prev => ({ ...prev, symbols, weights }));
+ } catch (err) {
+ console.warn('[Backtesting] Failed to load portfolio assets:', err);
+ }
+ }, []);
+
const registerProviders = async () => {
try {
if (!backtestingRegistry.hasProviders()) {
@@ -222,7 +254,10 @@ const BacktestingTabNew: React.FC = () => {
}
} catch (err) {
console.error('[Backtesting] Error:', err);
- setError(String(err));
+ // Clean up double-wrapped error messages
+ let errMsg = String(err).replace(/^Error:\s*/g, '');
+ errMsg = errMsg.replace(/VectorBT backtest failed:\s*VectorBT backtest failed:\s*/g, 'VectorBT backtest failed: ');
+ setError(errMsg);
} finally {
setIsRunning(false);
}
@@ -349,12 +384,13 @@ const BacktestingTabNew: React.FC = () => {
{/* Error Banner */}
{error && (
<div style={{
- display: 'flex', alignItems: 'center', gap: '8px',
+ display: 'flex', alignItems: 'flex-start', gap: '8px',
padding: '8px 14px', backgroundColor: '#1A0000',
borderBottom: `1px solid ${F.RED}`, fontSize: '10px', color: F.RED,
+ maxHeight: '120px', overflowY: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-word',
}}>
- <AlertTriangle size={12} />
- {error}
+ <AlertTriangle size={12} style={{ flexShrink: 0, marginTop: 2 }} />
+ <span>{error}</span>
</div>
)}
@@ -370,6 +406,8 @@ const BacktestingTabNew: React.FC = () => {
availableProviders={availableProviders}
activeProvider={activeProvider}
onProviderChange={handleProviderChange}
+ portfolios={portfolios}
+ onPortfolioSelect={handlePortfolioSelect}
/>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/backtesting/ConfigPanel.tsx b/fincept-terminal-desktop/src/components/tabs/backtesting/ConfigPanel.tsx
index 8d445a98e..634e85038 100644
--- a/fincept-terminal-desktop/src/components/tabs/backtesting/ConfigPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/backtesting/ConfigPanel.tsx
@@ -6,12 +6,13 @@
*/
import React, { useState } from 'react';
-import { ChevronDown, ChevronRight, Play, X, Plus } from 'lucide-react';
+import { ChevronDown, ChevronRight, Play, X, Plus, Briefcase } from 'lucide-react';
import {
F, inputStyle, labelStyle, selectStyle, sectionHeaderStyle, panelStyle, buttonStyle,
BacktestConfigExtended, StrategyType, PositionSizing,
STRATEGY_DEFINITIONS, getDefaultParameters,
} from './backtestingStyles';
+import type { Portfolio } from '@/services/portfolio/portfolioService';
interface ConfigPanelProps {
config: BacktestConfigExtended;
@@ -21,11 +22,14 @@ interface ConfigPanelProps {
availableProviders: string[];
activeProvider: string | null;
onProviderChange: (name: string) => void;
+ portfolios?: Portfolio[];
+ onPortfolioSelect?: (portfolioId: string) => void;
}
const ConfigPanel: React.FC<ConfigPanelProps> = ({
config, onConfigChange, onRunBacktest, isRunning,
availableProviders, activeProvider, onProviderChange,
+ portfolios = [], onPortfolioSelect,
}) => {
const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
symbols: true, strategy: true, dates: true, execution: false, riskManagement: false, benchmark: false,
@@ -67,14 +71,15 @@ const ConfigPanel: React.FC<ConfigPanelProps> = ({
};
const setDateRange = (years: number | 'ytd' | 'max') => {
- const end = new Date().toISOString().split('T')[0];
+ const yesterday = new Date(Date.now() - 1 * 24 * 60 * 60 * 1000);
+ const end = yesterday.toISOString().split('T')[0];
let start: string;
if (years === 'ytd') {
start = `${new Date().getFullYear()}-01-01`;
} else if (years === 'max') {
start = '2000-01-01';
} else {
- const d = new Date();
+ const d = new Date(yesterday);
d.setFullYear(d.getFullYear() - years);
start = d.toISOString().split('T')[0];
}
@@ -109,6 +114,34 @@ const ConfigPanel: React.FC<ConfigPanelProps> = ({
</div>
{expandedSections.symbols && (
<div style={{ padding: '10px 12px' }}>
+ {/* Portfolio Selector */}
+ {portfolios.length > 0 && (
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{ ...labelStyle, display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '4px' }}>
+ <Briefcase size={10} color={F.ORANGE} />
+ FROM PORTFOLIO
+ </label>
+ <select
+ style={selectStyle}
+ defaultValue=""
+ onChange={e => {
+ if (e.target.value && onPortfolioSelect) {
+ onPortfolioSelect(e.target.value);
+ }
+ }}
+ >
+ <option value="">— Select Portfolio —</option>
+ {portfolios.map(p => (
+ <option key={p.id} value={p.id}>{p.name} ({p.currency})</option>
+ ))}
+ </select>
+ <div style={{ fontSize: '8px', color: F.MUTED, marginTop: '2px' }}>
+ Loads symbols &amp; weights from your portfolio
+ </div>
+ </div>
+ )}
+
+ {/* Manual Symbol Input */}
<div style={{ display: 'flex', gap: '4px', marginBottom: '8px' }}>
<input
style={{ ...inputStyle, flex: 1 }}
diff --git a/fincept-terminal-desktop/src/components/tabs/backtesting/EquityCurveChart.tsx b/fincept-terminal-desktop/src/components/tabs/backtesting/EquityCurveChart.tsx
index f590527d0..2922c68da 100644
--- a/fincept-terminal-desktop/src/components/tabs/backtesting/EquityCurveChart.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/backtesting/EquityCurveChart.tsx
@@ -31,11 +31,11 @@ const EquityCurveChart: React.FC<EquityCurveChartProps> = ({ equity, initialCapi
const hasBenchmark = data.some(d => d.benchmark != null && d.benchmark > 0);
- // Scale benchmark to initial capital
+ // Benchmark is already in absolute equity scale from Python
const chartData = data.map(d => ({
date: d.date.split('T')[0],
equity: d.equity,
- benchmark: hasBenchmark && d.benchmark ? d.benchmark * initialCapital : undefined,
+ benchmark: hasBenchmark && d.benchmark ? d.benchmark : undefined,
}));
return (
diff --git a/fincept-terminal-desktop/src/components/tabs/backtesting/ResultsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/backtesting/ResultsPanel.tsx
index 6fb29fb28..be2133fa5 100644
--- a/fincept-terminal-desktop/src/components/tabs/backtesting/ResultsPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/backtesting/ResultsPanel.tsx
@@ -11,6 +11,21 @@ import TradeListView from './TradeListView';
type ResultTab = 'summary' | 'trades' | 'analysis';
+/** Convert nanosecond duration (pandas Timedelta) or bar count to human-readable string */
+function _formatDuration(v: any): string {
+ const n = typeof v === 'number' && isFinite(v) ? v : 0;
+ if (n === 0) return '-';
+ // If value > 1e12, it's nanoseconds from pandas Timedelta
+ if (Math.abs(n) > 1e12) {
+ const days = Math.round(n / 8.64e13); // ns -> days
+ if (days >= 365) return `${(days / 365).toFixed(1)} yrs`;
+ if (days >= 30) return `${(days / 30).toFixed(1)} mo`;
+ return `${days} days`;
+ }
+ // Otherwise treat as bar count
+ return `${n.toFixed(0)} bars`;
+}
+
interface ResultsPanelProps {
performance: Record<string, number>;
statistics: Record<string, number | string>;
@@ -145,10 +160,10 @@ const AnalysisView: React.FC<{
title: 'TRADE ANALYSIS',
rows: [
{ label: 'Payoff Ratio', value: fmtNum(ta.payoffRatio || ta.payoff_ratio, 2), description: 'Avg win / avg loss' },
- { label: 'Avg Trade Duration', value: `${fmtNum(ta.avgDuration || ta.avg_duration, 1)} bars`, description: 'Mean holding period' },
+ { label: 'Avg Trade Duration', value: _formatDuration(ta.avgDuration || ta.avg_duration), description: 'Mean holding period' },
{ label: 'Position Coverage', value: `${(safeNum(ta.positionCoverage || ta.position_coverage) * 100).toFixed(1)}%`, description: 'Time in market' },
- { label: 'Max Consec. Wins', value: String(ta.maxConsecWins || ta.max_consec_wins || statistics.consecutiveWins || 0), description: 'Longest winning streak' },
- { label: 'Max Consec. Losses', value: String(ta.maxConsecLosses || ta.max_consec_losses || statistics.consecutiveLosses || 0), description: 'Longest losing streak' },
+ { label: 'Max Consec. Wins', value: String(ta.winningStreak || ta.maxConsecWins || ta.max_consec_wins || statistics.consecutiveWins || 0), description: 'Longest winning streak' },
+ { label: 'Max Consec. Losses', value: String(ta.losingStreak || ta.maxConsecLosses || ta.max_consec_losses || statistics.consecutiveLosses || 0), description: 'Longest losing streak' },
{ label: 'SQN', value: fmtNum(ta.sqn, 2), description: 'System Quality Number (>2 good, >3 excellent)' },
],
},
@@ -168,8 +183,8 @@ const AnalysisView: React.FC<{
{ label: 'Max Drawdown Duration', value: `${da.maxDuration || da.max_duration || '-'} bars`, description: 'Longest peak-to-recovery' },
{ label: 'Avg Drawdown', value: fmtPct(da.avgDrawdown || da.avg_drawdown), description: 'Average drawdown depth' },
{ label: 'Avg Duration', value: `${fmtNum(da.avgDuration || da.avg_duration, 0)} bars`, description: 'Average drawdown length' },
- { label: 'Drawdown Periods', value: String(da.numPeriods || da.num_periods || '-'), description: 'Total number of drawdown periods' },
- { label: 'Recovery Factor', value: fmtNum(da.recoveryFactor || da.recovery_factor, 2), description: 'Total return / max drawdown' },
+ { label: 'Drawdown Periods', value: String(da.drawdownCount || da.numPeriods || da.num_periods || '-'), description: 'Total number of drawdown periods' },
+ { label: 'Recovery Ratio', value: fmtNum(da.recoveryRatio || da.recoveryFactor || da.recovery_factor, 2), description: 'Avg recovery / avg decline duration' },
],
},
];
diff --git a/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx b/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx
index 75a5663b6..9626f4326 100644
--- a/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx
@@ -3,13 +3,34 @@ import { flushSync } from 'react-dom';
import { Settings, Trash2, Bot, User, Clock, Send, Plus, Search, Edit2, Check, X } from 'lucide-react';
import { useTerminalTheme } from '@/contexts/ThemeContext';
import { useAuth } from '@/contexts/AuthContext';
+import { useBrokerContext } from '@/contexts/BrokerContext';
import { useTranslation } from 'react-i18next';
import { llmApiService, ChatMessage as APIMessage } from '@/services/chat/llmApi';
import { sqliteService, ChatSession, ChatMessage, RecordedContext, LLMConfig, LLMGlobalSettings, ChatStatistics } from '@/services/core/sqliteService';
import { contextRecorderService } from '@/services/data-sources/contextRecorderService';
+import { brokerMCPBridge } from '@/services/mcp/internal/BrokerMCPBridge';
+import { notesMCPBridge } from '@/services/mcp/internal/NotesMCPBridge';
import MarkdownRenderer from '@/components/common/MarkdownRenderer';
import ContextSelector from '@/components/common/ContextSelector';
-import { TabFooter } from '@/components/common/TabFooter';
+
+// Fincept Terminal Design System Colors
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
+};
interface ChatTabProps {
onNavigateToSettings?: () => void;
@@ -28,6 +49,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const auth = useAuth();
const { t } = useTranslation('chat');
+ const { activeAdapter, tradingMode, activeBroker } = useBrokerContext();
const [currentTime, setCurrentTime] = useState(new Date());
const [currentSessionUuid, setCurrentSessionUuid] = useState<string | null>(null);
const [messages, setMessages] = useState<ChatMessage[]>([]);
@@ -68,6 +90,30 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
return MCP_SUPPORTED_PROVIDERS.includes(activeLLMConfig.provider.toLowerCase());
};
+ // Connect broker to MCP bridge
+ useEffect(() => {
+ if (activeAdapter) {
+ brokerMCPBridge.connect({
+ activeAdapter,
+ tradingMode,
+ activeBroker,
+ });
+ console.log(`[Chat MCP] Connected to ${activeBroker} in ${tradingMode} mode`);
+ }
+
+ return () => {
+ brokerMCPBridge.disconnect();
+ };
+ }, [activeAdapter, tradingMode, activeBroker]);
+
+ // Connect notes to MCP bridge
+ useEffect(() => {
+ notesMCPBridge.connect();
+ return () => {
+ notesMCPBridge.disconnect();
+ };
+ }, []);
+
// Initialize database on mount
useEffect(() => {
const initDatabase = async () => {
@@ -214,16 +260,54 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
};
const generateSmartTitle = (message: string): string => {
- const cleanMsg = message.replace(/[^\w\s]/g, '').trim();
- const words = cleanMsg.split(' ');
+ // Clean the message but keep important characters
+ const trimmed = message.trim();
+
+ if (!trimmed) {
+ const now = new Date();
+ return `Chat ${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
+ }
+ // Extract keywords from common patterns
+ const lowerMsg = trimmed.toLowerCase();
+
+ // Check for common financial terms
+ const financialKeywords = [
+ 'market', 'stock', 'portfolio', 'risk', 'analysis',
+ 'trend', 'trading', 'investment', 'price', 'strategy',
+ 'forecast', 'data', 'chart', 'indicator', 'technical'
+ ];
+
+ const foundKeyword = financialKeywords.find(kw => lowerMsg.includes(kw));
+ if (foundKeyword) {
+ return foundKeyword.charAt(0).toUpperCase() + foundKeyword.slice(1) + ' Chat';
+ }
+
+ // Check for question words
+ if (lowerMsg.startsWith('what')) return 'What Query';
+ if (lowerMsg.startsWith('how')) return 'How To';
+ if (lowerMsg.startsWith('why')) return 'Why Question';
+ if (lowerMsg.startsWith('when')) return 'When Query';
+ if (lowerMsg.startsWith('where')) return 'Where Query';
+ if (lowerMsg.startsWith('analyze')) return 'Analysis';
+ if (lowerMsg.startsWith('explain')) return 'Explanation';
+ if (lowerMsg.startsWith('compare')) return 'Comparison';
+ if (lowerMsg.startsWith('calculate')) return 'Calculation';
+ if (lowerMsg.startsWith('show') || lowerMsg.startsWith('get')) return 'Data Request';
+
+ // Extract first 2-3 meaningful words (max 20 chars)
+ const words = trimmed.split(/\s+/).filter(w => w.length > 2);
if (words.length === 0) {
- return `Chat ${new Date().toLocaleString()}`;
- } else if (words.length <= 4) {
- return cleanMsg.substring(0, 40);
- } else {
- return words.slice(0, 4).join(' ') + '...';
+ const now = new Date();
+ return `Chat ${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
+ }
+
+ let title = words.slice(0, 2).join(' ');
+ if (title.length > 20) {
+ title = title.substring(0, 20);
}
+
+ return title;
};
const createNewSession = async (): Promise<string | null> => {
@@ -596,33 +680,61 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
alignItems: 'center',
justifyContent: 'center',
height: '100%',
- backgroundColor: colors.panel
+ backgroundColor: FINCEPT.DARK_BG
}}>
- <div style={{ textAlign: 'center', padding: '24px' }}>
- <Bot size={48} color={colors.primary} style={{ marginBottom: '16px' }} />
- <div style={{ color: colors.primary, fontSize: '20px', fontWeight: 'bold', marginBottom: '8px' }}>
- {t('title')}
+ <div style={{
+ textAlign: 'center',
+ padding: '24px',
+ maxWidth: '400px'
+ }}>
+ <Bot size={48} color={FINCEPT.ORANGE} style={{ marginBottom: '16px', opacity: 0.8 }} />
+ <div style={{
+ color: FINCEPT.ORANGE,
+ fontSize: '16px',
+ fontWeight: 700,
+ marginBottom: '8px',
+ letterSpacing: '0.5px'
+ }}>
+ {t('title').toUpperCase()}
</div>
- <div style={{ color: colors.text, fontSize: '14px', marginBottom: '16px' }}>
+ <div style={{
+ color: FINCEPT.WHITE,
+ fontSize: '11px',
+ marginBottom: '16px',
+ lineHeight: '1.5'
+ }}>
{t('subtitle')}
</div>
- <div style={{ color: colors.warning, fontSize: '12px', marginBottom: '16px' }}>
- Provider: {activeLLMConfig?.provider.toUpperCase() || 'NONE'} | Model: {activeLLMConfig?.model || 'N/A'}
+ <div style={{
+ padding: '6px 12px',
+ backgroundColor: `${FINCEPT.YELLOW}20`,
+ color: FINCEPT.YELLOW,
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ marginBottom: '16px',
+ display: 'inline-block',
+ letterSpacing: '0.5px'
+ }}>
+ PROVIDER: {activeLLMConfig?.provider.toUpperCase() || 'NONE'} | MODEL: {activeLLMConfig?.model || 'N/A'}
</div>
+ <br />
<button
onClick={createNewSession}
style={{
- backgroundColor: colors.primary,
- color: 'black',
+ padding: '8px 16px',
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
border: 'none',
- padding: '10px 20px',
- fontSize: '12px',
- fontWeight: 'bold',
- borderRadius: '4px',
- cursor: 'pointer'
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
}}
>
- {t('header.newChat')}
+ {t('header.newChat').toUpperCase()}
</button>
</div>
</div>
@@ -640,38 +752,61 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
<div style={{
maxWidth: '85%',
minWidth: '120px',
- backgroundColor: colors.panel,
- border: `1px solid ${message.role === 'user' ? colors.warning : colors.primary}`,
- borderRadius: '4px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${message.role === 'user' ? FINCEPT.YELLOW : FINCEPT.ORANGE}`,
+ borderRadius: '2px',
padding: '10px'
}}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '8px',
+ paddingBottom: '6px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
{message.role === 'user' ? (
- <User size={12} color={colors.warning} />
+ <User size={12} color={FINCEPT.YELLOW} />
) : (
- <Bot size={12} color={colors.primary} />
+ <Bot size={12} color={FINCEPT.ORANGE} />
)}
<span style={{
- color: message.role === 'user' ? colors.warning : colors.primary,
- fontSize: '11px',
- fontWeight: 'bold'
+ color: message.role === 'user' ? FINCEPT.YELLOW : FINCEPT.ORANGE,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
}}>
{message.role === 'user' ? 'YOU' : 'AI'}
</span>
- <Clock size={10} color={colors.textMuted} />
- <span style={{ color: colors.textMuted, fontSize: '10px' }}>
+ <Clock size={10} color={FINCEPT.GRAY} />
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
{formatTime(message.timestamp)}
</span>
{message.provider && (
- <span style={{ color: colors.textMuted, fontSize: '10px' }}>
- | {message.provider}
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px'
+ }}>
+ | {message.provider.toUpperCase()}
</span>
)}
</div>
{message.role === 'assistant' && message.content ? (
<MarkdownRenderer content={message.content} />
) : (
- <div style={{ color: colors.text, fontSize: '13px', lineHeight: '1.5', whiteSpace: 'pre-wrap' }}>
+ <div style={{
+ color: FINCEPT.WHITE,
+ fontSize: '11px',
+ lineHeight: '1.6',
+ whiteSpace: 'pre-wrap',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
{message.content || '(Empty message)'}
</div>
)}
@@ -682,8 +817,13 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
} catch (error) {
console.error('Error rendering message:', error, message);
return (
- <div key={message.id} style={{ marginBottom: '12px', color: colors.alert }}>
- Error rendering message
+ <div key={message.id} style={{
+ marginBottom: '12px',
+ color: FINCEPT.RED,
+ fontSize: '10px',
+ letterSpacing: '0.5px'
+ }}>
+ ERROR RENDERING MESSAGE
</div>
);
}
@@ -696,25 +836,41 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
<div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'flex-start' }}>
<div style={{
maxWidth: '85%',
- backgroundColor: colors.panel,
- border: `2px solid ${colors.primary}`,
- borderRadius: '4px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `2px solid ${FINCEPT.ORANGE}`,
+ borderRadius: '2px',
padding: '10px'
}}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
- <Bot size={12} color={colors.primary} />
- <span style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold' }}>
- {t('messages.typing')}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '8px',
+ paddingBottom: '6px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <Bot size={12} color={FINCEPT.ORANGE} />
+ <span style={{
+ color: FINCEPT.ORANGE,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>
+ {t('messages.typing').toUpperCase()}
</span>
</div>
<div style={{
- color: colors.text,
- fontSize: '13px',
- lineHeight: '1.5',
- whiteSpace: 'pre-wrap'
+ color: FINCEPT.WHITE,
+ fontSize: '11px',
+ lineHeight: '1.6',
+ whiteSpace: 'pre-wrap',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}>
{streamingContent}
- <span style={{ color: colors.primary }}>▊</span>
+ <span style={{
+ color: FINCEPT.ORANGE,
+ animation: 'blink 1s infinite'
+ }}>▊</span>
</div>
</div>
</div>
@@ -724,94 +880,133 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
return (
<div style={{
height: '100%',
- backgroundColor: colors.background,
- color: colors.text,
- fontFamily: fontFamily,
- fontWeight: fontWeight,
- fontStyle: fontStyle,
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
display: 'flex',
- flexDirection: 'column',
- fontSize: fontSize.body
+ flexDirection: 'column'
}}>
<style>{`
- /* Transparent/hidden scrollbar styling */
+ /* Scrollbar styling per design system */
*::-webkit-scrollbar {
- width: 8px;
- height: 8px;
+ width: 6px;
+ height: 6px;
}
*::-webkit-scrollbar-track {
- background: transparent;
+ background: ${FINCEPT.DARK_BG};
}
*::-webkit-scrollbar-thumb {
- background: rgba(255, 165, 0, 0.2);
- border-radius: 4px;
+ background: ${FINCEPT.BORDER};
+ border-radius: 3px;
}
*::-webkit-scrollbar-thumb:hover {
- background: rgba(255, 165, 0, 0.4);
+ background: ${FINCEPT.MUTED};
}
/* For Firefox */
* {
scrollbar-width: thin;
- scrollbar-color: rgba(255, 165, 0, 0.2) transparent;
+ scrollbar-color: ${FINCEPT.BORDER} ${FINCEPT.DARK_BG};
+ }
+ /* Input focus states */
+ input:focus, textarea:focus {
+ outline: none;
+ border-color: ${FINCEPT.ORANGE} !important;
+ }
+ /* Blink animation for cursor */
+ @keyframes blink {
+ 0%, 50% { opacity: 1; }
+ 51%, 100% { opacity: 0; }
}
`}</style>
- {/* Compact Header */}
+ {/* Top Navigation Bar */}
<div style={{
- backgroundColor: colors.panel,
- borderBottom: `1px solid ${colors.textMuted}`,
- padding: '6px 10px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,
+ padding: '8px 16px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
- flexShrink: 0
+ flexShrink: 0,
+ boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`
}}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
- <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '12px' }}>{t('title')}</span>
- <span style={{ color: colors.textMuted }}>|</span>
- <span style={{ color: colors.warning, fontSize: '10px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <span style={{
+ color: FINCEPT.ORANGE,
+ fontWeight: 700,
+ fontSize: '11px',
+ letterSpacing: '0.5px'
+ }}>
+ {t('title').toUpperCase()}
+ </span>
+ <span style={{ color: FINCEPT.GRAY }}>|</span>
+ <span style={{
+ color: FINCEPT.YELLOW,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>
{activeLLMConfig?.provider.toUpperCase() || 'NO PROVIDER'}
</span>
- <span style={{ color: colors.textMuted }}>|</span>
- <span style={{ color: colors.text, fontSize: '10px' }}>
+ <span style={{ color: FINCEPT.GRAY }}>|</span>
+ <span style={{
+ color: FINCEPT.WHITE,
+ fontSize: '9px',
+ letterSpacing: '0.5px'
+ }}>
{currentTime.toLocaleTimeString('en-US', { hour12: false })}
</span>
</div>
- <div style={{ display: 'flex', gap: '6px' }}>
+ <div style={{ display: 'flex', gap: '8px' }}>
<button
onClick={() => onNavigateToSettings?.()}
style={{
- backgroundColor: colors.background,
- border: `1px solid ${colors.textMuted}`,
- color: colors.text,
- padding: '4px 8px',
- fontSize: '10px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ padding: '6px 10px',
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
- gap: '4px'
+ gap: '4px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.color = FINCEPT.WHITE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.color = FINCEPT.GRAY;
}}
title="Go to Settings tab to configure LLM providers"
>
<Settings size={12} />
- {t('header.settings')}
+ {t('header.settings').toUpperCase()}
</button>
<button
onClick={createNewSession}
style={{
- backgroundColor: colors.primary,
+ backgroundColor: FINCEPT.ORANGE,
border: 'none',
- color: 'black',
- padding: '4px 8px',
- fontSize: '10px',
- fontWeight: 'bold',
+ color: FINCEPT.DARK_BG,
+ padding: '8px 16px',
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
- gap: '4px'
+ gap: '4px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
}}
>
<Plus size={12} />
- {t('header.newChat')}
+ {t('header.newChat').toUpperCase()}
</button>
</div>
</div>
@@ -820,40 +1015,53 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
<div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
{/* Left Panel - Sessions */}
<div style={{
- width: '250px',
- backgroundColor: colors.panel,
- borderRight: `1px solid ${colors.textMuted}`,
+ width: '280px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden'
}}>
- <div style={{ padding: '8px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
- <div style={{ color: colors.warning, fontSize: '11px', fontWeight: 'bold' }}>
- {t('history.sessions')} ({statistics.totalSessions})
- </div>
+ {/* Section Header */}
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
+ }}>
+ {t('history.sessions').toUpperCase()} ({statistics.totalSessions})
+ </span>
{sessions.length > 0 && (
<button
onClick={deleteAllSessions}
style={{
- backgroundColor: colors.alert,
- color: colors.text,
- border: 'none',
padding: '2px 6px',
+ backgroundColor: `${FINCEPT.RED}20`,
+ color: FINCEPT.RED,
+ border: 'none',
fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
cursor: 'pointer',
- fontWeight: 'bold'
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
}}
title={t('history.deleteAll')}
>
- {t('history.clearAll')}
+ {t('history.clearAll').toUpperCase()}
</button>
)}
</div>
{/* Search */}
<div style={{ position: 'relative', marginBottom: '8px' }}>
- <Search size={12} color={colors.textMuted} style={{ position: 'absolute', left: '6px', top: '6px' }} />
+ <Search size={12} color={FINCEPT.GRAY} style={{ position: 'absolute', left: '8px', top: '9px' }} />
<input
id="session-search"
type="text"
@@ -862,18 +1070,25 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
onChange={(e) => setSearchQuery(e.target.value)}
style={{
width: '100%',
- backgroundColor: colors.background,
- border: `1px solid ${colors.textMuted}`,
- color: colors.text,
- padding: '4px 4px 4px 24px',
- fontSize: '10px'
+ padding: '8px 10px 8px 32px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}
/>
</div>
{/* Stats */}
- <div style={{ fontSize: '9px', color: colors.textMuted, marginBottom: '6px' }}>
- Messages: {statistics.totalMessages} | Tokens: {statistics.totalTokens.toLocaleString()}
+ <div style={{
+ fontSize: '9px',
+ color: FINCEPT.CYAN,
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ MESSAGES: {statistics.totalMessages} | TOKENS: {statistics.totalTokens.toLocaleString()}
</div>
</div>
@@ -883,24 +1098,35 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
style={{
flex: 1,
overflow: 'auto',
- padding: '0 8px 8px'
+ padding: '8px'
}}
>
{filteredSessions.map(session => (
<div
key={session.session_uuid}
style={{
- backgroundColor: currentSessionUuid === session.session_uuid ? colors.primary + '30' : colors.background,
- border: `1px solid ${currentSessionUuid === session.session_uuid ? colors.primary : colors.textMuted}`,
- padding: '6px',
- marginBottom: '4px',
- cursor: renamingSessionId === session.session_uuid ? 'default' : 'pointer'
+ padding: '10px 12px',
+ backgroundColor: currentSessionUuid === session.session_uuid ? `${FINCEPT.ORANGE}15` : 'transparent',
+ borderLeft: currentSessionUuid === session.session_uuid ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
+ cursor: renamingSessionId === session.session_uuid ? 'default' : 'pointer',
+ transition: 'all 0.2s',
+ marginBottom: '4px'
}}
onClick={() => renamingSessionId !== session.session_uuid && selectSession(session.session_uuid)}
+ onMouseEnter={(e) => {
+ if (currentSessionUuid !== session.session_uuid && renamingSessionId !== session.session_uuid) {
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (currentSessionUuid !== session.session_uuid) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
>
{/* Title or Rename Input */}
{renamingSessionId === session.session_uuid ? (
- <div style={{ marginBottom: '3px', display: 'flex', gap: '4px', alignItems: 'center' }}>
+ <div style={{ marginBottom: '6px', display: 'flex', gap: '4px', alignItems: 'center' }}>
<input
type="text"
value={renameValue}
@@ -912,12 +1138,13 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
autoFocus
style={{
flex: 1,
- backgroundColor: colors.background,
- border: `1px solid ${colors.primary}`,
- color: colors.text,
- fontSize: '11px',
- padding: '2px 4px',
- fontFamily: 'Consolas, monospace'
+ padding: '4px 6px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.ORANGE}`,
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ borderRadius: '2px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}
/>
<button
@@ -927,11 +1154,12 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
}}
style={{
backgroundColor: 'transparent',
- color: colors.secondary,
+ color: FINCEPT.GREEN,
border: 'none',
cursor: 'pointer',
padding: '0',
- display: 'flex'
+ display: 'flex',
+ transition: 'all 0.2s'
}}
>
<Check size={12} />
@@ -943,26 +1171,40 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
}}
style={{
backgroundColor: 'transparent',
- color: colors.alert,
+ color: FINCEPT.RED,
border: 'none',
cursor: 'pointer',
padding: '0',
- display: 'flex'
+ display: 'flex',
+ transition: 'all 0.2s'
}}
>
<X size={12} />
</button>
</div>
) : (
- <div style={{ color: colors.text, fontSize: '11px', marginBottom: '3px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ <div style={{
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ marginBottom: '6px',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ fontWeight: 700
+ }}>
{session.title}
</div>
)}
{/* Actions Row */}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <span style={{ color: colors.textMuted, fontSize: '9px' }}>
- {session.message_count} msgs • {formatSessionTime(session.updated_at)}
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {session.message_count} MSGS • {formatSessionTime(session.updated_at)}
</span>
<div style={{ display: 'flex', gap: '6px' }}>
<button
@@ -972,12 +1214,13 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
}}
style={{
backgroundColor: 'transparent',
- color: colors.warning,
+ color: FINCEPT.YELLOW,
border: 'none',
fontSize: '9px',
cursor: 'pointer',
padding: '0',
- display: 'flex'
+ display: 'flex',
+ transition: 'all 0.2s'
}}
title="Rename session"
>
@@ -990,12 +1233,13 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
}}
style={{
backgroundColor: 'transparent',
- color: colors.alert,
+ color: FINCEPT.RED,
border: 'none',
fontSize: '9px',
cursor: 'pointer',
padding: '0',
- display: 'flex'
+ display: 'flex',
+ transition: 'all 0.2s'
}}
title="Delete session"
>
@@ -1011,32 +1255,42 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Center Panel - Chat */}
<div style={{
flex: 1,
- backgroundColor: colors.panel,
+ backgroundColor: FINCEPT.PANEL_BG,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden'
}}>
{/* Chat Header */}
<div style={{
- padding: '6px 10px',
- borderBottom: `1px solid ${colors.textMuted}`,
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}>
- <span style={{ color: colors.text, fontSize: '11px' }}>
- {currentSessionUuid ? sessions.find(s => s.session_uuid === currentSessionUuid)?.title || 'Chat' : 'No Active Session'}
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
+ }}>
+ {currentSessionUuid ? (sessions.find(s => s.session_uuid === currentSessionUuid)?.title || 'CHAT').toUpperCase() : 'NO ACTIVE SESSION'}
</span>
{currentSessionUuid && (
<button
onClick={clearCurrentChat}
style={{
- backgroundColor: colors.alert,
- color: colors.text,
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.RED}20`,
+ color: FINCEPT.RED,
border: 'none',
- padding: '3px 8px',
- fontSize: '9px',
- cursor: 'pointer'
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
}}
>
CLEAR
@@ -1047,18 +1301,25 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
{/* Messages Area with scrollbar */}
<div style={{
flex: 1,
- padding: '10px',
+ padding: '16px',
overflow: 'auto',
- backgroundColor: colors.background
+ backgroundColor: FINCEPT.DARK_BG
}}>
{messages.length === 0 && !streamingContent ? renderWelcomeScreen() : (
<div>
{messages.map(renderMessage)}
{streamingContent && renderStreamingMessage()}
{isTyping && !streamingContent && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', color: colors.textMuted, fontSize: '11px' }}>
- <Bot size={12} />
- <span>{t('messages.thinking')}</span>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ letterSpacing: '0.5px'
+ }}>
+ <Bot size={12} color={FINCEPT.GRAY} />
+ <span>{t('messages.thinking').toUpperCase()}</span>
</div>
)}
<div ref={messagesEndRef} />
@@ -1067,8 +1328,12 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
</div>
{/* Input Area */}
- <div style={{ padding: '8px', borderTop: `1px solid ${colors.textMuted}` }}>
- <div style={{ display: 'flex', gap: '6px' }}>
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderTop: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <div style={{ display: 'flex', gap: '8px' }}>
<textarea
value={messageInput}
onChange={(e) => setMessageInput(e.target.value)}
@@ -1081,179 +1346,300 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
placeholder={t('input.placeholder')}
style={{
flex: 1,
- backgroundColor: colors.background,
- border: `1px solid ${colors.textMuted}`,
- color: colors.text,
- padding: '6px',
- fontSize: '11px',
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
resize: 'none',
height: '60px',
- fontFamily: 'Consolas, monospace'
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
}}
/>
<button
onClick={handleSendMessage}
disabled={!messageInput.trim() || isTyping}
style={{
- backgroundColor: messageInput.trim() && !isTyping ? colors.primary : colors.textMuted,
- color: 'black',
+ padding: '8px 16px',
+ backgroundColor: messageInput.trim() && !isTyping ? FINCEPT.ORANGE : FINCEPT.MUTED,
+ color: FINCEPT.DARK_BG,
border: 'none',
- padding: '6px 12px',
- fontSize: '11px',
- fontWeight: 'bold',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
cursor: messageInput.trim() && !isTyping ? 'pointer' : 'not-allowed',
display: 'flex',
alignItems: 'center',
- gap: '4px'
+ gap: '4px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s',
+ opacity: messageInput.trim() && !isTyping ? 1 : 0.5
}}
>
<Send size={12} />
- {t('input.send')}
+ {t('input.send').toUpperCase()}
</button>
</div>
- <div style={{ color: colors.textMuted, fontSize: '9px', marginTop: '4px' }}>
- {messageInput.length > 0 ? `${messageInput.length} chars` : systemStatus}
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ marginTop: '6px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {messageInput.length > 0 ? `${messageInput.length} CHARS` : systemStatus}
</div>
</div>
</div>
{/* Right Panel - Quick Actions & Context Selector */}
<div style={{
- width: '250px',
- backgroundColor: colors.panel,
- borderLeft: `1px solid ${colors.textMuted}`,
- padding: '8px',
- overflow: 'auto',
+ width: '300px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderLeft: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
flexDirection: 'column',
- gap: '12px'
+ overflow: 'hidden'
}}>
- {/* Context Selector */}
- <div>
- <div style={{ color: colors.warning, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
- {t('panel.dataContexts')}
+ {/* Context Selector Section */}
+ <div style={{
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
+ }}>
+ {t('panel.dataContexts').toUpperCase()}
+ </span>
+ </div>
+ <div style={{ padding: '12px' }}>
+ <ContextSelector
+ chatSessionUuid={currentSessionUuid}
+ onContextsChange={handleContextsChange}
+ />
</div>
- <ContextSelector
- chatSessionUuid={currentSessionUuid}
- onContextsChange={handleContextsChange}
- />
</div>
- {/* Quick Prompts */}
- <div>
- <div style={{ color: colors.warning, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
- {t('panel.quickPrompts')}
+ {/* Quick Prompts Section */}
+ <div style={{
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
+ }}>
+ {t('panel.quickPrompts').toUpperCase()}
+ </span>
+ </div>
+ <div style={{ padding: '12px' }}>
+ {[
+ { cmd: 'MARKET TRENDS', prompt: 'Analyze current market trends and key insights' },
+ { cmd: 'PORTFOLIO', prompt: 'Portfolio diversification recommendations' },
+ { cmd: 'RISK', prompt: 'Investment risk assessment strategies' },
+ { cmd: 'TECHNICAL', prompt: 'Key technical analysis indicators' }
+ ].map(item => (
+ <button
+ key={item.cmd}
+ onClick={() => setMessageInput(item.prompt)}
+ style={{
+ width: '100%',
+ padding: '6px 10px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ textAlign: 'left',
+ cursor: 'pointer',
+ marginBottom: '6px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.color = FINCEPT.WHITE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.color = FINCEPT.GRAY;
+ }}
+ >
+ {item.cmd}
+ </button>
+ ))}
</div>
- {[
- { cmd: 'MARKET TRENDS', prompt: 'Analyze current market trends and key insights' },
- { cmd: 'PORTFOLIO', prompt: 'Portfolio diversification recommendations' },
- { cmd: 'RISK', prompt: 'Investment risk assessment strategies' },
- { cmd: 'TECHNICAL', prompt: 'Key technical analysis indicators' }
- ].map(item => (
- <button
- key={item.cmd}
- onClick={() => setMessageInput(item.prompt)}
- style={{
- width: '100%',
- backgroundColor: colors.background,
- color: colors.text,
- border: `1px solid ${colors.textMuted}`,
- padding: '5px',
- fontSize: '9px',
- textAlign: 'left',
- cursor: 'pointer',
- marginBottom: '4px'
- }}
- >
- {item.cmd}
- </button>
- ))}
</div>
- {/* System Info */}
- <div>
- <div style={{ color: colors.warning, fontSize: '11px', fontWeight: 'bold', marginBottom: '6px' }}>
- {t('panel.systemInfo')}
- </div>
- {activeLLMConfig ? (
- <>
- <div style={{ color: colors.text, fontSize: '9px', marginBottom: '2px' }}>
- Provider: {activeLLMConfig.provider.toUpperCase()}
- </div>
- <div style={{ color: colors.text, fontSize: '9px', marginBottom: '2px' }}>
- Model: {activeLLMConfig.model}
- </div>
- <div style={{ color: colors.text, fontSize: '9px', marginBottom: '2px' }}>
- Temp: {llmGlobalSettings.temperature}
- </div>
- <div style={{ color: colors.secondary, fontSize: '9px', marginBottom: '2px' }}>
- Streaming: Enabled
- </div>
- </>
- ) : (
- <div style={{ color: colors.alert, fontSize: '9px', marginBottom: '6px' }}>
- No LLM provider configured
- </div>
- )}
+ {/* System Info Section */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
<div style={{
- marginTop: '6px',
- paddingTop: '6px',
- borderTop: `1px solid ${colors.textMuted}`
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
}}>
- <div style={{
- color: mcpToolsCount > 0 ? colors.secondary : colors.textMuted,
+ <span style={{
fontSize: '9px',
- marginBottom: '6px'
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
}}>
- MCP Tools: {mcpToolsCount > 0 ? `${mcpToolsCount} Available [OK]` : 'None'}
- </div>
- <button
- onClick={() => onNavigateToTab?.('mcp')}
- style={{
- width: '100%',
- backgroundColor: colors.primary,
- color: 'black',
- border: 'none',
- padding: '5px 8px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- marginBottom: '6px',
- borderRadius: '2px'
- }}
- title="Configure MCP servers and tools"
- >
- 🔧 MCP INTEGRATION
- </button>
- {mcpToolsCount > 0 && !providerSupportsMCP() && activeLLMConfig && (
+ {t('panel.systemInfo').toUpperCase()}
+ </span>
+ </div>
+ <div style={{ padding: '12px' }}>
+ {activeLLMConfig ? (
+ <>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '9px',
+ marginBottom: '4px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ PROVIDER: {activeLLMConfig.provider.toUpperCase()}
+ </div>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '9px',
+ marginBottom: '4px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ MODEL: {activeLLMConfig.model}
+ </div>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '9px',
+ marginBottom: '4px',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ TEMP: {llmGlobalSettings.temperature}
+ </div>
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.GREEN}20`,
+ color: FINCEPT.GREEN,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ display: 'inline-block',
+ letterSpacing: '0.5px'
+ }}>
+ STREAMING: ENABLED
+ </div>
+ </>
+ ) : (
<div style={{
- color: colors.alert,
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.RED}20`,
+ color: FINCEPT.RED,
fontSize: '8px',
- marginTop: '4px',
- padding: '4px',
- backgroundColor: colors.background,
- border: `1px solid ${colors.alert}`,
- borderRadius: '2px'
+ fontWeight: 700,
+ borderRadius: '2px',
+ letterSpacing: '0.5px'
}}>
- [WARN] {activeLLMConfig.provider.toUpperCase()} doesn't support MCP tools
+ NO LLM PROVIDER CONFIGURED
</div>
)}
+ <div style={{
+ marginTop: '12px',
+ paddingTop: '12px',
+ borderTop: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: mcpToolsCount > 0 ? `${FINCEPT.CYAN}20` : `${FINCEPT.MUTED}20`,
+ color: mcpToolsCount > 0 ? FINCEPT.CYAN : FINCEPT.MUTED,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ marginBottom: '8px',
+ letterSpacing: '0.5px',
+ display: 'inline-block'
+ }}>
+ MCP TOOLS: {mcpToolsCount > 0 ? `${mcpToolsCount} AVAILABLE [OK]` : 'NONE'}
+ </div>
+ <button
+ onClick={() => onNavigateToTab?.('mcp')}
+ style={{
+ width: '100%',
+ padding: '8px 16px',
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ marginBottom: '8px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ title="Configure MCP servers and tools"
+ >
+ 🔧 MCP INTEGRATION
+ </button>
+ {mcpToolsCount > 0 && !providerSupportsMCP() && activeLLMConfig && (
+ <div style={{
+ padding: '6px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.RED}`,
+ borderRadius: '2px',
+ color: FINCEPT.RED,
+ fontSize: '8px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>
+ [WARN] {activeLLMConfig.provider.toUpperCase()} DOESN'T SUPPORT MCP TOOLS
+ </div>
+ )}
+ </div>
</div>
</div>
</div>
</div>
- {/* Footer */}
- <TabFooter
- tabName="AI CHAT"
- leftInfo={[
- { label: `Provider: ${activeLLMConfig?.provider.toUpperCase() || 'NONE'}`, color: colors.textMuted },
- { label: `Session: ${currentSessionUuid ? 'Active' : 'None'}`, color: colors.textMuted },
- ]}
- statusInfo={`Messages: ${messages.length} | ${streamingContent ? 'Streaming...' : 'Ready'}`}
- backgroundColor={colors.panel}
- borderColor={colors.textMuted}
- />
+ {/* Status Bar (Bottom) */}
+ <div style={{
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ padding: '4px 16px',
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ letterSpacing: '0.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ <div style={{ display: 'flex', gap: '12px' }}>
+ <span>TAB: AI CHAT</span>
+ <span>|</span>
+ <span>PROVIDER: {activeLLMConfig?.provider.toUpperCase() || 'NONE'}</span>
+ <span>|</span>
+ <span>SESSION: {currentSessionUuid ? 'ACTIVE' : 'NONE'}</span>
+ </div>
+ <div>
+ MESSAGES: {messages.length} | STATUS: {streamingContent ? 'STREAMING...' : 'READY'}
+ </div>
+ </div>
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/tabs/derivatives/DerivativesTab.tsx b/fincept-terminal-desktop/src/components/tabs/derivatives/DerivativesTab.tsx
index 3968d6b37..7a321f93c 100644
--- a/fincept-terminal-desktop/src/components/tabs/derivatives/DerivativesTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/derivatives/DerivativesTab.tsx
@@ -9,22 +9,24 @@ import {
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { useTranslation } from 'react-i18next';
-import { TabFooter } from '@/components/common/TabFooter';
-
-// Fincept-style color palette
-const COLORS = {
- ORANGE: '#FF8800',
- GREEN: '#00D66F',
- RED: '#FF3B3B',
- BLUE: '#0088FF',
- CYAN: '#00E5FF',
- YELLOW: '#FFD700',
- BG: '#0F0F0F',
- PANEL: '#1A1A1A',
- BORDER: '#2A2A2A',
- HOVER: '#1F1F1F',
- TEXT: '#FFFFFF',
- MUTED: '#787878'
+
+// Fincept Design System Colors
+const FINCEPT = {
+ ORANGE: '#FF8800', // Primary accent, CTAs, selected states
+ WHITE: '#FFFFFF', // Primary text
+ RED: '#FF3B3B', // Negative, errors, sell
+ GREEN: '#00D66F', // Positive, success, buy
+ GRAY: '#787878', // Secondary text, labels
+ DARK_BG: '#000000', // Main background
+ PANEL_BG: '#0F0F0F', // Card/panel background
+ HEADER_BG: '#1A1A1A', // Header/toolbar background
+ BORDER: '#2A2A2A', // Borders, dividers
+ HOVER: '#1F1F1F', // Hover state background
+ MUTED: '#4A4A4A', // Disabled, inactive
+ CYAN: '#00E5FF', // Info, data values
+ YELLOW: '#FFD700', // Alerts, prices
+ BLUE: '#0088FF', // Secondary accent
+ PURPLE: '#9D4EDD', // Tertiary accent
};
type InstrumentType = 'bonds' | 'equity-options' | 'fx-options' | 'swaps' | 'credit';
@@ -266,15 +268,15 @@ export function DerivativesTab() {
const renderInstrumentSelector = () => {
const instruments = [
- { id: 'bonds', label: 'Bonds', icon: DollarSign },
- { id: 'equity-options', label: 'Equity Options', icon: TrendingUp },
- { id: 'fx-options', label: 'FX Options', icon: Activity },
- { id: 'swaps', label: 'Interest Rate Swaps', icon: BarChart3 },
- { id: 'credit', label: 'Credit Derivatives', icon: Target }
+ { id: 'bonds', label: 'BONDS', icon: DollarSign },
+ { id: 'equity-options', label: 'EQUITY OPTIONS', icon: TrendingUp },
+ { id: 'fx-options', label: 'FX OPTIONS', icon: Activity },
+ { id: 'swaps', label: 'IR SWAPS', icon: BarChart3 },
+ { id: 'credit', label: 'CREDIT', icon: Target }
];
return (
- <div className="flex gap-2 mb-6 overflow-x-auto pb-2">
+ <div style={{ display: 'flex', gap: '4px', marginBottom: '16px', overflowX: 'auto', paddingBottom: '8px' }}>
{instruments.map(({ id, label, icon: Icon }) => (
<button
key={id}
@@ -283,90 +285,152 @@ export function DerivativesTab() {
setResult(null);
setError(null);
}}
- className={`flex items-center gap-2 px-4 py-2 rounded whitespace-nowrap transition-all ${
- activeInstrument === id
- ? 'bg-orange-500 text-white shadow-lg'
- : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
- }`}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ padding: '6px 12px',
+ backgroundColor: activeInstrument === id ? FINCEPT.ORANGE : 'transparent',
+ color: activeInstrument === id ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ whiteSpace: 'nowrap',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}
>
- <Icon className="w-4 h-4" />
- <span className="text-sm font-medium">{label}</span>
+ <Icon size={12} />
+ <span>{label}</span>
</button>
))}
</div>
);
};
+ // Shared styles
+ const panelStyle: React.CSSProperties = {
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ };
+
+ const sectionHeaderStyle: React.CSSProperties = {
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ };
+
+ const labelStyle: React.CSSProperties = {
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ marginBottom: '4px',
+ display: 'block',
+ };
+
+ const inputStyle: React.CSSProperties = {
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ };
+
+ const primaryButtonStyle: React.CSSProperties = {
+ width: '100%',
+ padding: '8px 16px',
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ fontFamily: '"IBM Plex Mono", monospace',
+ };
+
const renderBondsPanel = () => (
- <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px' }}>
{/* Bond Pricing Calculator */}
- <div className="bg-gray-900 rounded-lg border border-gray-800 p-6">
- <div className="flex items-center gap-2 mb-4">
- <Calculator className="w-5 h-5 text-orange-500" />
- <h3 className="text-lg font-semibold text-white">Bond Price Calculator</h3>
+ <div style={panelStyle}>
+ <div style={sectionHeaderStyle}>
+ <Calculator size={14} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>BOND PRICE CALCULATOR</span>
</div>
- <div className="space-y-4">
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Issue Date</label>
+ <label style={labelStyle}>ISSUE DATE</label>
<input
type="date"
value={bondParams.issueDate}
onChange={(e) => setBondParams({ ...bondParams, issueDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Settlement Date</label>
+ <label style={labelStyle}>SETTLEMENT DATE</label>
<input
type="date"
value={bondParams.settlementDate}
onChange={(e) => setBondParams({ ...bondParams, settlementDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Maturity Date</label>
+ <label style={labelStyle}>MATURITY DATE</label>
<input
type="date"
value={bondParams.maturityDate}
onChange={(e) => setBondParams({ ...bondParams, maturityDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Coupon Rate (%)</label>
+ <label style={labelStyle}>COUPON RATE (%)</label>
<input
type="number"
step="0.1"
value={bondParams.couponRate}
onChange={(e) => setBondParams({ ...bondParams, couponRate: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">YTM (%)</label>
+ <label style={labelStyle}>YTM (%)</label>
<input
type="number"
step="0.1"
value={bondParams.ytm}
onChange={(e) => setBondParams({ ...bondParams, ytm: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Payment Frequency</label>
+ <label style={labelStyle}>PAYMENT FREQUENCY</label>
<select
value={bondParams.freq}
onChange={(e) => setBondParams({ ...bondParams, freq: parseInt(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
>
<option value={1}>Annual</option>
<option value={2}>Semi-Annual</option>
@@ -377,81 +441,84 @@ export function DerivativesTab() {
<button
onClick={calculateBondPrice}
disabled={loading}
- className="w-full bg-orange-500 hover:bg-orange-600 text-white font-medium py-2 rounded transition-colors disabled:opacity-50"
+ style={{
+ ...primaryButtonStyle,
+ opacity: loading ? 0.5 : 1,
+ }}
>
- {loading ? 'Calculating...' : 'Calculate Bond Price'}
+ {loading ? 'CALCULATING...' : 'CALCULATE BOND PRICE'}
</button>
</div>
</div>
{/* YTM Calculator */}
- <div className="bg-gray-900 rounded-lg border border-gray-800 p-6">
- <div className="flex items-center gap-2 mb-4">
- <Percent className="w-5 h-5 text-orange-500" />
- <h3 className="text-lg font-semibold text-white">Yield to Maturity Calculator</h3>
+ <div style={panelStyle}>
+ <div style={sectionHeaderStyle}>
+ <Percent size={14} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>YIELD TO MATURITY</span>
</div>
- <div className="space-y-4">
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Issue Date</label>
+ <label style={labelStyle}>ISSUE DATE</label>
<input
type="date"
value={bondParams.issueDate}
onChange={(e) => setBondParams({ ...bondParams, issueDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Settlement Date</label>
+ <label style={labelStyle}>SETTLEMENT DATE</label>
<input
type="date"
value={bondParams.settlementDate}
onChange={(e) => setBondParams({ ...bondParams, settlementDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Maturity Date</label>
+ <label style={labelStyle}>MATURITY DATE</label>
<input
type="date"
value={bondParams.maturityDate}
onChange={(e) => setBondParams({ ...bondParams, maturityDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Coupon Rate (%)</label>
+ <label style={labelStyle}>COUPON RATE (%)</label>
<input
type="number"
step="0.1"
value={bondParams.couponRate}
onChange={(e) => setBondParams({ ...bondParams, couponRate: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Clean Price</label>
+ <label style={labelStyle}>CLEAN PRICE</label>
<input
type="number"
step="0.01"
value={bondParams.cleanPrice}
onChange={(e) => setBondParams({ ...bondParams, cleanPrice: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Payment Frequency</label>
+ <label style={labelStyle}>PAYMENT FREQUENCY</label>
<select
value={bondParams.freq}
onChange={(e) => setBondParams({ ...bondParams, freq: parseInt(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
>
<option value={1}>Annual</option>
<option value={2}>Semi-Annual</option>
@@ -462,9 +529,12 @@ export function DerivativesTab() {
<button
onClick={calculateBondYTM}
disabled={loading}
- className="w-full bg-orange-500 hover:bg-orange-600 text-white font-medium py-2 rounded transition-colors disabled:opacity-50"
+ style={{
+ ...primaryButtonStyle,
+ opacity: loading ? 0.5 : 1,
+ }}
>
- {loading ? 'Calculating...' : 'Calculate YTM'}
+ {loading ? 'CALCULATING...' : 'CALCULATE YTM'}
</button>
</div>
</div>
@@ -472,99 +542,99 @@ export function DerivativesTab() {
);
const renderEquityOptionsPanel = () => (
- <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px' }}>
{/* Option Pricing */}
- <div className="bg-gray-900 rounded-lg border border-gray-800 p-6">
- <div className="flex items-center gap-2 mb-4">
- <TrendingUp className="w-5 h-5 text-orange-500" />
- <h3 className="text-lg font-semibold text-white">Black-Scholes Option Pricing</h3>
+ <div style={panelStyle}>
+ <div style={sectionHeaderStyle}>
+ <TrendingUp size={14} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>BLACK-SCHOLES PRICING</span>
</div>
- <div className="space-y-4">
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Valuation Date</label>
+ <label style={labelStyle}>VALUATION DATE</label>
<input
type="date"
value={optionParams.valuationDate}
onChange={(e) => setOptionParams({ ...optionParams, valuationDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Expiry Date</label>
+ <label style={labelStyle}>EXPIRY DATE</label>
<input
type="date"
value={optionParams.expiryDate}
onChange={(e) => setOptionParams({ ...optionParams, expiryDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Strike Price</label>
+ <label style={labelStyle}>STRIKE PRICE</label>
<input
type="number"
step="0.01"
value={optionParams.strike}
onChange={(e) => setOptionParams({ ...optionParams, strike: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Spot Price</label>
+ <label style={labelStyle}>SPOT PRICE</label>
<input
type="number"
step="0.01"
value={optionParams.spot}
onChange={(e) => setOptionParams({ ...optionParams, spot: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Volatility (%)</label>
+ <label style={labelStyle}>VOLATILITY (%)</label>
<input
type="number"
step="0.1"
value={optionParams.volatility}
onChange={(e) => setOptionParams({ ...optionParams, volatility: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Risk-Free Rate (%)</label>
+ <label style={labelStyle}>RISK-FREE RATE (%)</label>
<input
type="number"
step="0.1"
value={optionParams.riskFreeRate}
onChange={(e) => setOptionParams({ ...optionParams, riskFreeRate: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Dividend Yield (%)</label>
+ <label style={labelStyle}>DIVIDEND YIELD (%)</label>
<input
type="number"
step="0.1"
value={optionParams.dividendYield}
onChange={(e) => setOptionParams({ ...optionParams, dividendYield: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Option Type</label>
+ <label style={labelStyle}>OPTION TYPE</label>
<select
value={optionParams.optionType}
onChange={(e) => setOptionParams({ ...optionParams, optionType: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
>
<option value="call">Call</option>
<option value="put">Put</option>
@@ -575,105 +645,108 @@ export function DerivativesTab() {
<button
onClick={calculateOptionPrice}
disabled={loading}
- className="w-full bg-orange-500 hover:bg-orange-600 text-white font-medium py-2 rounded transition-colors disabled:opacity-50"
+ style={{
+ ...primaryButtonStyle,
+ opacity: loading ? 0.5 : 1,
+ }}
>
- {loading ? 'Calculating...' : 'Calculate Option Price & Greeks'}
+ {loading ? 'CALCULATING...' : 'CALCULATE PRICE & GREEKS'}
</button>
</div>
</div>
{/* Implied Volatility */}
- <div className="bg-gray-900 rounded-lg border border-gray-800 p-6">
- <div className="flex items-center gap-2 mb-4">
- <Activity className="w-5 h-5 text-orange-500" />
- <h3 className="text-lg font-semibold text-white">Implied Volatility Calculator</h3>
+ <div style={panelStyle}>
+ <div style={sectionHeaderStyle}>
+ <Activity size={14} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>IMPLIED VOLATILITY</span>
</div>
- <div className="space-y-4">
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Valuation Date</label>
+ <label style={labelStyle}>VALUATION DATE</label>
<input
type="date"
value={optionParams.valuationDate}
onChange={(e) => setOptionParams({ ...optionParams, valuationDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Expiry Date</label>
+ <label style={labelStyle}>EXPIRY DATE</label>
<input
type="date"
value={optionParams.expiryDate}
onChange={(e) => setOptionParams({ ...optionParams, expiryDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Strike Price</label>
+ <label style={labelStyle}>STRIKE PRICE</label>
<input
type="number"
step="0.01"
value={optionParams.strike}
onChange={(e) => setOptionParams({ ...optionParams, strike: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Spot Price</label>
+ <label style={labelStyle}>SPOT PRICE</label>
<input
type="number"
step="0.01"
value={optionParams.spot}
onChange={(e) => setOptionParams({ ...optionParams, spot: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Market Option Price</label>
+ <label style={labelStyle}>MARKET OPTION PRICE</label>
<input
type="number"
step="0.01"
value={optionParams.optionPrice}
onChange={(e) => setOptionParams({ ...optionParams, optionPrice: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Risk-Free Rate (%)</label>
+ <label style={labelStyle}>RISK-FREE RATE (%)</label>
<input
type="number"
step="0.1"
value={optionParams.riskFreeRate}
onChange={(e) => setOptionParams({ ...optionParams, riskFreeRate: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Dividend Yield (%)</label>
+ <label style={labelStyle}>DIVIDEND YIELD (%)</label>
<input
type="number"
step="0.1"
value={optionParams.dividendYield}
onChange={(e) => setOptionParams({ ...optionParams, dividendYield: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Option Type</label>
+ <label style={labelStyle}>OPTION TYPE</label>
<select
value={optionParams.optionType}
onChange={(e) => setOptionParams({ ...optionParams, optionType: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
>
<option value="call">Call</option>
<option value="put">Put</option>
@@ -683,9 +756,12 @@ export function DerivativesTab() {
<button
onClick={calculateImpliedVol}
disabled={loading}
- className="w-full bg-orange-500 hover:bg-orange-600 text-white font-medium py-2 rounded transition-colors disabled:opacity-50"
+ style={{
+ ...primaryButtonStyle,
+ opacity: loading ? 0.5 : 1,
+ }}
>
- {loading ? 'Calculating...' : 'Calculate Implied Volatility'}
+ {loading ? 'CALCULATING...' : 'CALCULATE IMPLIED VOL'}
</button>
</div>
</div>
@@ -693,107 +769,107 @@ export function DerivativesTab() {
);
const renderFXOptionsPanel = () => (
- <div className="bg-gray-900 rounded-lg border border-gray-800 p-6 max-w-2xl">
- <div className="flex items-center gap-2 mb-4">
- <Activity className="w-5 h-5 text-orange-500" />
- <h3 className="text-lg font-semibold text-white">FX Vanilla Option Pricing</h3>
+ <div style={{ ...panelStyle, maxWidth: '700px' }}>
+ <div style={sectionHeaderStyle}>
+ <Activity size={14} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>FX VANILLA OPTION PRICING</span>
</div>
- <div className="space-y-4">
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Valuation Date</label>
+ <label style={labelStyle}>VALUATION DATE</label>
<input
type="date"
value={fxParams.valuationDate}
onChange={(e) => setFxParams({ ...fxParams, valuationDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Expiry Date</label>
+ <label style={labelStyle}>EXPIRY DATE</label>
<input
type="date"
value={fxParams.expiryDate}
onChange={(e) => setFxParams({ ...fxParams, expiryDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Strike FX Rate</label>
+ <label style={labelStyle}>STRIKE FX RATE</label>
<input
type="number"
step="0.0001"
value={fxParams.strike}
onChange={(e) => setFxParams({ ...fxParams, strike: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Spot FX Rate</label>
+ <label style={labelStyle}>SPOT FX RATE</label>
<input
type="number"
step="0.0001"
value={fxParams.spot}
onChange={(e) => setFxParams({ ...fxParams, spot: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
- <div className="grid grid-cols-3 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Volatility (%)</label>
+ <label style={labelStyle}>VOLATILITY (%)</label>
<input
type="number"
step="0.1"
value={fxParams.volatility}
onChange={(e) => setFxParams({ ...fxParams, volatility: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Domestic Rate (%)</label>
+ <label style={labelStyle}>DOMESTIC RATE (%)</label>
<input
type="number"
step="0.1"
value={fxParams.domesticRate}
onChange={(e) => setFxParams({ ...fxParams, domesticRate: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Foreign Rate (%)</label>
+ <label style={labelStyle}>FOREIGN RATE (%)</label>
<input
type="number"
step="0.1"
value={fxParams.foreignRate}
onChange={(e) => setFxParams({ ...fxParams, foreignRate: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Notional</label>
+ <label style={labelStyle}>NOTIONAL</label>
<input
type="number"
step="10000"
value={fxParams.notional}
onChange={(e) => setFxParams({ ...fxParams, notional: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Option Type</label>
+ <label style={labelStyle}>OPTION TYPE</label>
<select
value={fxParams.optionType}
onChange={(e) => setFxParams({ ...fxParams, optionType: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
>
<option value="call">Call</option>
<option value="put">Put</option>
@@ -804,60 +880,63 @@ export function DerivativesTab() {
<button
onClick={calculateFXOption}
disabled={loading}
- className="w-full bg-orange-500 hover:bg-orange-600 text-white font-medium py-2 rounded transition-colors disabled:opacity-50"
+ style={{
+ ...primaryButtonStyle,
+ opacity: loading ? 0.5 : 1,
+ }}
>
- {loading ? 'Calculating...' : 'Calculate FX Option Price'}
+ {loading ? 'CALCULATING...' : 'CALCULATE FX OPTION PRICE'}
</button>
</div>
</div>
);
const renderSwapsPanel = () => (
- <div className="bg-gray-900 rounded-lg border border-gray-800 p-6 max-w-2xl">
- <div className="flex items-center gap-2 mb-4">
- <BarChart3 className="w-5 h-5 text-orange-500" />
- <h3 className="text-lg font-semibold text-white">Interest Rate Swap Pricing</h3>
+ <div style={{ ...panelStyle, maxWidth: '700px' }}>
+ <div style={sectionHeaderStyle}>
+ <BarChart3 size={14} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>INTEREST RATE SWAP PRICING</span>
</div>
- <div className="space-y-4">
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Effective Date</label>
+ <label style={labelStyle}>EFFECTIVE DATE</label>
<input
type="date"
value={swapParams.effectiveDate}
onChange={(e) => setSwapParams({ ...swapParams, effectiveDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Maturity Date</label>
+ <label style={labelStyle}>MATURITY DATE</label>
<input
type="date"
value={swapParams.maturityDate}
onChange={(e) => setSwapParams({ ...swapParams, maturityDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
- <div className="grid grid-cols-3 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Fixed Rate (%)</label>
+ <label style={labelStyle}>FIXED RATE (%)</label>
<input
type="number"
step="0.01"
value={swapParams.fixedRate}
onChange={(e) => setSwapParams({ ...swapParams, fixedRate: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Frequency</label>
+ <label style={labelStyle}>FREQUENCY</label>
<select
value={swapParams.freq}
onChange={(e) => setSwapParams({ ...swapParams, freq: parseInt(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
>
<option value={1}>Annual</option>
<option value={2}>Semi-Annual</option>
@@ -865,97 +944,100 @@ export function DerivativesTab() {
</select>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Discount Rate (%)</label>
+ <label style={labelStyle}>DISCOUNT RATE (%)</label>
<input
type="number"
step="0.01"
value={swapParams.discountRate}
onChange={(e) => setSwapParams({ ...swapParams, discountRate: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Notional Amount</label>
+ <label style={labelStyle}>NOTIONAL AMOUNT</label>
<input
type="number"
step="100000"
value={swapParams.notional}
onChange={(e) => setSwapParams({ ...swapParams, notional: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<button
onClick={calculateSwap}
disabled={loading}
- className="w-full bg-orange-500 hover:bg-orange-600 text-white font-medium py-2 rounded transition-colors disabled:opacity-50"
+ style={{
+ ...primaryButtonStyle,
+ opacity: loading ? 0.5 : 1,
+ }}
>
- {loading ? 'Calculating...' : 'Calculate Swap Value'}
+ {loading ? 'CALCULATING...' : 'CALCULATE SWAP VALUE'}
</button>
</div>
</div>
);
const renderCreditPanel = () => (
- <div className="bg-gray-900 rounded-lg border border-gray-800 p-6 max-w-2xl">
- <div className="flex items-center gap-2 mb-4">
- <Target className="w-5 h-5 text-orange-500" />
- <h3 className="text-lg font-semibold text-white">Credit Default Swap Pricing</h3>
+ <div style={{ ...panelStyle, maxWidth: '700px' }}>
+ <div style={sectionHeaderStyle}>
+ <Target size={14} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>CREDIT DEFAULT SWAP PRICING</span>
</div>
- <div className="space-y-4">
- <div className="grid grid-cols-2 gap-3">
+ <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Valuation Date</label>
+ <label style={labelStyle}>VALUATION DATE</label>
<input
type="date"
value={cdsParams.valuationDate}
onChange={(e) => setCdsParams({ ...cdsParams, valuationDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Maturity Date</label>
+ <label style={labelStyle}>MATURITY DATE</label>
<input
type="date"
value={cdsParams.maturityDate}
onChange={(e) => setCdsParams({ ...cdsParams, maturityDate: e.target.value })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
- <div className="grid grid-cols-3 gap-3">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>
<div>
- <label className="block text-xs text-gray-400 mb-1">Recovery Rate (%)</label>
+ <label style={labelStyle}>RECOVERY RATE (%)</label>
<input
type="number"
step="1"
value={cdsParams.recoveryRate}
onChange={(e) => setCdsParams({ ...cdsParams, recoveryRate: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Spread (bps)</label>
+ <label style={labelStyle}>SPREAD (BPS)</label>
<input
type="number"
step="1"
value={cdsParams.spreadBps}
onChange={(e) => setCdsParams({ ...cdsParams, spreadBps: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-gray-400 mb-1">Notional</label>
+ <label style={labelStyle}>NOTIONAL</label>
<input
type="number"
step="1000000"
value={cdsParams.notional}
onChange={(e) => setCdsParams({ ...cdsParams, notional: parseFloat(e.target.value) })}
- className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white"
+ style={inputStyle}
/>
</div>
</div>
@@ -963,9 +1045,12 @@ export function DerivativesTab() {
<button
onClick={calculateCDS}
disabled={loading}
- className="w-full bg-orange-500 hover:bg-orange-600 text-white font-medium py-2 rounded transition-colors disabled:opacity-50"
+ style={{
+ ...primaryButtonStyle,
+ opacity: loading ? 0.5 : 1,
+ }}
>
- {loading ? 'Calculating...' : 'Calculate CDS Value'}
+ {loading ? 'CALCULATING...' : 'CALCULATE CDS VALUE'}
</button>
</div>
</div>
@@ -974,12 +1059,18 @@ export function DerivativesTab() {
const renderResults = () => {
if (error) {
return (
- <div className="mt-6 bg-red-900/20 border border-red-500 rounded-lg p-4">
- <div className="flex items-start gap-2">
- <AlertCircle className="w-5 h-5 text-red-500 mt-0.5" />
+ <div style={{
+ marginTop: '16px',
+ backgroundColor: `${FINCEPT.RED}20`,
+ border: `1px solid ${FINCEPT.RED}`,
+ borderRadius: '2px',
+ padding: '12px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}>
+ <AlertCircle size={14} style={{ color: FINCEPT.RED, marginTop: '2px' }} />
<div>
- <h4 className="text-red-500 font-semibold mb-1">Error</h4>
- <p className="text-sm text-red-300">{error}</p>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.RED, marginBottom: '4px' }}>ERROR</div>
+ <div style={{ fontSize: '10px', color: FINCEPT.RED }}>{error}</div>
</div>
</div>
</div>
@@ -988,45 +1079,92 @@ export function DerivativesTab() {
if (!result) return null;
+ const resultCardStyle: React.CSSProperties = {
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderRadius: '2px',
+ padding: '10px',
+ };
+
+ const resultLabelStyle: React.CSSProperties = {
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ marginBottom: '4px',
+ };
+
+ const resultValueStyle: React.CSSProperties = {
+ fontSize: '12px',
+ fontWeight: 700,
+ color: FINCEPT.CYAN,
+ fontFamily: '"IBM Plex Mono", monospace',
+ };
+
+ const bigResultValueStyle: React.CSSProperties = {
+ fontSize: '16px',
+ fontWeight: 700,
+ color: FINCEPT.ORANGE,
+ fontFamily: '"IBM Plex Mono", monospace',
+ };
+
return (
- <div className="mt-6 bg-gray-900 border border-gray-800 rounded-lg p-6">
- <div className="flex items-center justify-between mb-4">
- <h3 className="text-lg font-semibold text-white">Results</h3>
+ <div style={{
+ marginTop: '16px',
+ ...panelStyle,
+ }}>
+ <div style={{
+ ...sectionHeaderStyle,
+ justifyContent: 'space-between',
+ }}>
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>RESULTS</span>
<button
onClick={copyResults}
- className="flex items-center gap-2 px-3 py-1.5 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded text-sm transition-colors"
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ padding: '4px 8px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ }}
>
- <Copy className="w-4 h-4" />
- Copy
+ <Copy size={10} />
+ COPY
</button>
</div>
- <div className="space-y-3">
+ <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
{/* Bond Results */}
{result.clean_price !== undefined && (
<>
- <div className="grid grid-cols-2 gap-4">
- <div className="bg-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Clean Price</div>
- <div className="text-lg font-semibold text-white">{result.clean_price.toFixed(4)}</div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>CLEAN PRICE</div>
+ <div style={resultValueStyle}>{result.clean_price.toFixed(4)}</div>
</div>
- <div className="bg-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Dirty Price</div>
- <div className="text-lg font-semibold text-white">{result.dirty_price?.toFixed(4)}</div>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>DIRTY PRICE</div>
+ <div style={resultValueStyle}>{result.dirty_price?.toFixed(4)}</div>
</div>
</div>
- <div className="grid grid-cols-3 gap-4">
- <div className="bg-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Duration</div>
- <div className="text-lg font-semibold text-white">{result.duration?.toFixed(2)}</div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>DURATION</div>
+ <div style={resultValueStyle}>{result.duration?.toFixed(2)}</div>
</div>
- <div className="bg-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Convexity</div>
- <div className="text-lg font-semibold text-white">{result.convexity?.toFixed(4)}</div>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>CONVEXITY</div>
+ <div style={resultValueStyle}>{result.convexity?.toFixed(4)}</div>
</div>
- <div className="bg-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Accrued Interest</div>
- <div className="text-lg font-semibold text-white">{result.accrued_interest?.toFixed(4)}</div>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>ACCRUED INT</div>
+ <div style={resultValueStyle}>{result.accrued_interest?.toFixed(4)}</div>
</div>
</div>
</>
@@ -1034,39 +1172,39 @@ export function DerivativesTab() {
{/* YTM Results */}
{result.ytm !== undefined && !result.clean_price && (
- <div className="bg-gray-800 rounded p-4">
- <div className="text-xs text-gray-400 mb-1">Yield to Maturity</div>
- <div className="text-2xl font-bold text-orange-500">{result.ytm.toFixed(4)}%</div>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>YIELD TO MATURITY</div>
+ <div style={bigResultValueStyle}>{result.ytm.toFixed(4)}%</div>
</div>
)}
{/* Option Results */}
{result.price !== undefined && result.greeks && (
<>
- <div className="bg-gray-800 rounded p-4">
- <div className="text-xs text-gray-400 mb-1">Option Price</div>
- <div className="text-2xl font-bold text-orange-500">{result.price.toFixed(4)}</div>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>OPTION PRICE</div>
+ <div style={bigResultValueStyle}>{result.price.toFixed(4)}</div>
</div>
- <div className="grid grid-cols-5 gap-3">
- <div className="bg-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Delta</div>
- <div className="text-sm font-semibold text-white">{result.greeks.delta.toFixed(4)}</div>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '8px' }}>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>DELTA</div>
+ <div style={resultValueStyle}>{result.greeks.delta.toFixed(4)}</div>
</div>
- <div className="bg-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Gamma</div>
- <div className="text-sm font-semibold text-white">{result.greeks.gamma.toFixed(4)}</div>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>GAMMA</div>
+ <div style={resultValueStyle}>{result.greeks.gamma.toFixed(4)}</div>
</div>
- <div className="bg-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Vega</div>
- <div className="text-sm font-semibold text-white">{result.greeks.vega.toFixed(4)}</div>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>VEGA</div>
+ <div style={resultValueStyle}>{result.greeks.vega.toFixed(4)}</div>
</div>
- <div className="bg-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Theta</div>
- <div className="text-sm font-semibold text-white">{result.greeks.theta.toFixed(4)}</div>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>THETA</div>
+ <div style={resultValueStyle}>{result.greeks.theta.toFixed(4)}</div>
</div>
- <div className="bg-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Rho</div>
- <div className="text-sm font-semibold text-white">{result.greeks.rho.toFixed(4)}</div>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>RHO</div>
+ <div style={resultValueStyle}>{result.greeks.rho.toFixed(4)}</div>
</div>
</div>
</>
@@ -1074,15 +1212,23 @@ export function DerivativesTab() {
{/* Implied Vol Results */}
{result.implied_volatility !== undefined && (
- <div className="bg-gray-800 rounded p-4">
- <div className="text-xs text-gray-400 mb-1">Implied Volatility</div>
- <div className="text-2xl font-bold text-orange-500">{result.implied_volatility.toFixed(4)}%</div>
+ <div style={resultCardStyle}>
+ <div style={resultLabelStyle}>IMPLIED VOLATILITY</div>
+ <div style={bigResultValueStyle}>{result.implied_volatility.toFixed(4)}%</div>
</div>
)}
{/* Raw JSON for other results */}
{!result.clean_price && !result.ytm && !result.price && !result.greeks && !result.implied_volatility && (
- <pre className="bg-gray-800 rounded p-4 text-xs text-gray-300 overflow-x-auto">
+ <pre style={{
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderRadius: '2px',
+ padding: '12px',
+ fontSize: '9px',
+ color: FINCEPT.CYAN,
+ overflow: 'auto',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}>
{JSON.stringify(result, null, 2)}
</pre>
)}
@@ -1092,33 +1238,53 @@ export function DerivativesTab() {
};
return (
- <div className="h-full flex flex-col bg-black text-white">
- {/* Header */}
- <div className="bg-gray-900 border-b border-gray-800 px-6 py-4">
- <div className="flex items-center justify-between">
+ <div style={{
+ height: '100%',
+ display: 'flex',
+ flexDirection: 'column',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}>
+ {/* Top Navigation Bar */}
+ <div style={{
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,
+ padding: '8px 16px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`,
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <Calculator size={20} style={{ color: FINCEPT.ORANGE }} />
<div>
- <h1 className="text-2xl font-bold text-white flex items-center gap-2">
- <Calculator className="w-6 h-6 text-orange-500" />
- Derivatives Pricing
+ <h1 style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE, margin: 0 }}>
+ DERIVATIVES PRICING
</h1>
- <p className="text-sm text-gray-400 mt-1">
- Professional derivatives valuation powered by FinancePy
- </p>
- </div>
- <div className="flex items-center gap-3">
- <div className="flex items-center gap-2 bg-green-500/10 px-3 py-1.5 rounded">
- <Zap className="w-4 h-4 text-green-500" />
- <span className="text-xs font-medium text-green-500">FinancePy Active</span>
- </div>
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
+ PROFESSIONAL VALUATION POWERED BY FINANCEPY
+ </span>
</div>
</div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.GREEN}20`,
+ borderRadius: '2px',
+ }}>
+ <Zap size={10} style={{ color: FINCEPT.GREEN }} />
+ <span style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GREEN }}>FINANCEPY ACTIVE</span>
+ </div>
</div>
- {/* Content */}
- <div className="flex-1 overflow-y-auto p-6">
+ {/* Content Area */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
{renderInstrumentSelector()}
- <div className="max-w-7xl mx-auto">
+ <div style={{ maxWidth: '1400px' }}>
{activeInstrument === 'bonds' && renderBondsPanel()}
{activeInstrument === 'equity-options' && renderEquityOptionsPanel()}
{activeInstrument === 'fx-options' && renderFXOptionsPanel()}
@@ -1129,7 +1295,23 @@ export function DerivativesTab() {
</div>
</div>
- <TabFooter tabName="Derivatives" statusInfo="FinancePy v1.0.1" />
+ {/* Status Bar */}
+ <div style={{
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ padding: '4px 16px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ }}>
+ <span>DERIVATIVES TAB</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
+ <span>INSTRUMENT: {activeInstrument.toUpperCase().replace('-', ' ')}</span>
+ <span style={{ color: FINCEPT.CYAN }}>FINANCEPY v1.0.1</span>
+ </div>
+ </div>
</div>
);
}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/components/FinancialAnalysisPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/components/FinancialAnalysisPanel.tsx
index bb66d86dc..1593d1649 100644
--- a/fincept-terminal-desktop/src/components/tabs/equity-research/components/FinancialAnalysisPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/components/FinancialAnalysisPanel.tsx
@@ -1,6 +1,7 @@
// Financial Analysis Panel - Fincept Style
import React, { useState, useCallback } from 'react';
import { invoke } from '@tauri-apps/api/core';
+import { cacheService, CacheService, TTL } from '../../../../services/cache/cacheService';
import { AlertCircle, CheckCircle, BarChart3, DollarSign, PieChart, Activity, FileText, ChevronDown, ChevronUp, Loader2 } from 'lucide-react';
import type { StockInfo } from '../types';
@@ -83,7 +84,19 @@ export const FinancialAnalysisPanel: React.FC<FinancialAnalysisPanelProps> = ({
const run = useCallback(async () => {
setLoading(true);
+
+ const cacheKey = CacheService.key('reference', 'financial-analysis', ticker, selected);
+
try {
+ // Check cache first
+ const cached = await cacheService.get<AnalysisResult>(cacheKey);
+ if (cached) {
+ console.log('Using cached financial analysis for', ticker, selected);
+ setResult(cached.data);
+ setLoading(false);
+ return;
+ }
+
const cmds: Record<AnalysisType, string> = {
income: 'analyze_income_statement',
balance: 'analyze_balance_sheet',
@@ -160,7 +173,13 @@ export const FinancialAnalysisPanel: React.FC<FinancialAnalysisPanelProps> = ({
const res = await invoke<string>(cmds[selected], { data });
const p = JSON.parse(res);
- setResult({ success: p.success !== false, summary: p.summary || p.error, results: p.results, metrics: p.metrics, error: p.error });
+ const analysisResult: AnalysisResult = { success: p.success !== false, summary: p.summary || p.error, results: p.results, metrics: p.metrics, error: p.error };
+ setResult(analysisResult);
+
+ // Cache successful results
+ if (analysisResult.success) {
+ await cacheService.set(cacheKey, analysisResult, 'reference', TTL['1h']);
+ }
} catch (e) {
setResult({ success: false, error: e instanceof Error ? e.message : 'Failed' });
} finally {
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useNews.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useNews.ts
index f3b5729e7..c0743916b 100644
--- a/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useNews.ts
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useNews.ts
@@ -1,5 +1,6 @@
import { useState, useCallback } from 'react';
import { invoke } from '@tauri-apps/api/core';
+import { cacheService, CacheService, TTL } from '../../../../services/cache/cacheService';
import type { NewsData } from '../types';
interface UseNewsReturn {
@@ -8,6 +9,8 @@ interface UseNewsReturn {
fetchNews: (symbol: string, companyName?: string) => Promise<void>;
}
+const NEWS_CATEGORY = 'news';
+
export function useNews(): UseNewsReturn {
const [newsData, setNewsData] = useState<NewsData | null>(null);
const [newsLoading, setNewsLoading] = useState(false);
@@ -21,7 +24,18 @@ export function useNews(): UseNewsReturn {
setNewsLoading(true);
console.log('Fetching news for:', symbol);
+ const cacheKey = CacheService.key(NEWS_CATEGORY, 'company', symbol);
+
try {
+ // Check cache first
+ const cached = await cacheService.get<NewsData>(cacheKey);
+ if (cached) {
+ console.log('Using cached news for', symbol);
+ setNewsData(cached.data);
+ setNewsLoading(false);
+ return;
+ }
+
// Use company name if available, otherwise use symbol
const query = companyName || symbol;
@@ -35,11 +49,18 @@ export function useNews(): UseNewsReturn {
console.log('News response:', response);
+ let parsed: NewsData;
if (typeof response === 'string') {
- const parsed = JSON.parse(response);
- setNewsData(parsed);
+ parsed = JSON.parse(response);
} else {
- setNewsData(response);
+ parsed = response;
+ }
+
+ setNewsData(parsed);
+
+ // Cache the news data
+ if (parsed.success !== false) {
+ await cacheService.set(cacheKey, parsed, NEWS_CATEGORY, TTL['10m']);
}
} catch (error) {
console.error('Error fetching news:', error);
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useStockData.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useStockData.ts
index ab6c4563b..74fd6edf8 100644
--- a/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useStockData.ts
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useStockData.ts
@@ -1,15 +1,8 @@
-import { useState, useRef, useEffect, useCallback } from 'react';
+import { useState, useCallback } from 'react';
import { invoke } from '@tauri-apps/api/core';
+import { cacheService, CacheService, TTL } from '../../../../services/cache/cacheService';
import type { StockInfo, HistoricalData, QuoteData, FinancialsData, ChartPeriod, TechnicalsData } from '../types';
-interface DataCache {
- stockInfo: StockInfo;
- quoteData: QuoteData;
- historicalData: Record<string, HistoricalData[]>;
- financials: FinancialsData;
- timestamp: number;
-}
-
interface UseStockDataReturn {
stockInfo: StockInfo | null;
quoteData: QuoteData | null;
@@ -22,7 +15,9 @@ interface UseStockDataReturn {
computeTechnicals: (historical: HistoricalData[]) => Promise<void>;
}
-const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
+const CACHE_CATEGORY = 'market-quotes';
+const HISTORICAL_CATEGORY = 'market-historical';
+const REFERENCE_CATEGORY = 'reference';
export function useStockData(): UseStockDataReturn {
const [stockInfo, setStockInfo] = useState<StockInfo | null>(null);
@@ -33,28 +28,37 @@ export function useStockData(): UseStockDataReturn {
const [loading, setLoading] = useState(false);
const [technicalsLoading, setTechnicalsLoading] = useState(false);
- const dataCache = useRef<Record<string, DataCache>>({});
-
const fetchStockData = useCallback(async (symbol: string, period: ChartPeriod, forceRefresh = false) => {
setLoading(true);
console.log('Fetching data for:', symbol, '| Force refresh:', forceRefresh);
+ const quoteKey = CacheService.key(CACHE_CATEGORY, 'quote', symbol);
+ const infoKey = CacheService.key(REFERENCE_CATEGORY, 'stock-info', symbol);
+ const historicalKey = CacheService.key(HISTORICAL_CATEGORY, 'historical', symbol, period);
+ const financialsKey = CacheService.key(REFERENCE_CATEGORY, 'financials', symbol);
+
try {
- // Check cache first
- const cached = dataCache.current[symbol];
- const now = Date.now();
-
- if (cached && !forceRefresh && (now - cached.timestamp < CACHE_DURATION)) {
- console.log('Using cached data for', symbol);
- setStockInfo(cached.stockInfo);
- setQuoteData(cached.quoteData);
- setFinancials(cached.financials);
-
- // Check if we have historical data for this period
- if (cached.historicalData[period]) {
- setHistoricalData(cached.historicalData[period]);
- setLoading(false);
- return;
+ // Check cache first (unless force refresh)
+ if (!forceRefresh) {
+ const [cachedQuote, cachedInfo, cachedHistorical, cachedFinancials] = await Promise.all([
+ cacheService.get<QuoteData>(quoteKey),
+ cacheService.get<StockInfo>(infoKey),
+ cacheService.get<HistoricalData[]>(historicalKey),
+ cacheService.get<FinancialsData>(financialsKey),
+ ]);
+
+ // If all core data is cached and fresh, use it
+ if (cachedQuote && cachedInfo && cachedFinancials) {
+ console.log('Using cached data for', symbol);
+ setQuoteData(cachedQuote.data);
+ setStockInfo(cachedInfo.data);
+ setFinancials(cachedFinancials.data);
+
+ if (cachedHistorical) {
+ setHistoricalData(cachedHistorical.data);
+ setLoading(false);
+ return;
+ }
}
}
@@ -67,6 +71,7 @@ export function useStockData(): UseStockDataReturn {
if (quoteResponse.success && quoteResponse.data) {
setQuoteData(quoteResponse.data);
newQuote = quoteResponse.data;
+ await cacheService.set(quoteKey, quoteResponse.data, CACHE_CATEGORY, TTL['5m']);
}
// Fetch stock info
@@ -75,6 +80,7 @@ export function useStockData(): UseStockDataReturn {
if (infoResponse.success && infoResponse.data) {
setStockInfo(infoResponse.data);
newInfo = infoResponse.data;
+ await cacheService.set(infoKey, infoResponse.data, REFERENCE_CATEGORY, TTL['24h']);
}
// Fetch historical data
@@ -93,32 +99,16 @@ export function useStockData(): UseStockDataReturn {
startDate: startDate.toISOString().split('T')[0],
endDate: endDate.toISOString().split('T')[0],
});
- let newHistorical: HistoricalData[] = [];
if (historicalResponse.success && historicalResponse.data) {
setHistoricalData(historicalResponse.data);
- newHistorical = historicalResponse.data;
+ await cacheService.set(historicalKey, historicalResponse.data, HISTORICAL_CATEGORY, TTL['1h']);
}
// Fetch financials
const financialsResponse: any = await invoke('get_financials', { symbol });
- let newFinancials: FinancialsData | null = null;
if (financialsResponse.success && financialsResponse.data) {
setFinancials(financialsResponse.data);
- newFinancials = financialsResponse.data;
- }
-
- // Update cache
- if (newInfo && newQuote && newFinancials) {
- dataCache.current[symbol] = {
- stockInfo: newInfo,
- quoteData: newQuote,
- historicalData: {
- ...((cached?.historicalData) || {}),
- [period]: newHistorical,
- },
- financials: newFinancials,
- timestamp: now,
- };
+ await cacheService.set(financialsKey, financialsResponse.data, REFERENCE_CATEGORY, TTL['24h']);
}
} catch (error) {
console.error('Error fetching stock data:', error);
@@ -137,6 +127,15 @@ export function useStockData(): UseStockDataReturn {
return;
}
+ // Check cache for technicals
+ const techKey = CacheService.keyWithHash('market-quotes', 'technicals', historical.map(d => String(d.timestamp)));
+ const cached = await cacheService.get<TechnicalsData>(techKey);
+ if (cached) {
+ console.log('Using cached technicals data');
+ setTechnicalsData(cached.data);
+ return;
+ }
+
// Convert historical data to format expected by Python script
const historicalJson = JSON.stringify(historical.map(d => ({
timestamp: d.timestamp,
@@ -155,24 +154,30 @@ export function useStockData(): UseStockDataReturn {
console.log('Technicals response:', response);
+ let parsedData: TechnicalsData | null = null;
+
if (typeof response === 'string') {
try {
const parsed = JSON.parse(response);
if (parsed.success && parsed.data && Array.isArray(parsed.data) && parsed.data.length > 0) {
- setTechnicalsData(parsed);
+ parsedData = parsed;
} else {
console.error('Error computing technicals:', parsed.error || 'Invalid data structure');
- setTechnicalsData(null);
}
} catch (parseError) {
console.error('Error parsing technicals response:', parseError);
- setTechnicalsData(null);
}
} else if (response && response.success && response.data && Array.isArray(response.data) && response.data.length > 0) {
- setTechnicalsData(response);
+ parsedData = response;
} else {
console.error('Invalid technicals response structure');
- setTechnicalsData(null);
+ }
+
+ setTechnicalsData(parsedData);
+
+ // Cache the result
+ if (parsedData) {
+ await cacheService.set(techKey, parsedData, CACHE_CATEGORY, TTL['15m']);
}
} catch (error) {
console.error('Error computing technicals:', error);
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/services/momentumIndicators.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/services/momentumIndicators.ts
index dc7bac696..a2fab136b 100644
--- a/fincept-terminal-desktop/src/components/tabs/equity-research/services/momentumIndicators.ts
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/services/momentumIndicators.ts
@@ -1,6 +1,7 @@
// Service for calculating and parsing momentum indicators
import { invoke } from '@tauri-apps/api/core';
+import { cacheService, CacheService, TTL } from '../../../../services/cache/cacheService';
import {
MomentumIndicatorParams,
MomentumIndicatorResult,
@@ -9,6 +10,9 @@ import {
} from '../types';
import * as SignalAnalyzer from '../utils/signalAnalyzer';
+const INDICATOR_CATEGORY = 'market-quotes';
+const HISTORICAL_CATEGORY = 'market-historical';
+
/**
* Fetches historical price data for a symbol
*/
@@ -17,6 +21,15 @@ export async function fetchHistoricalData(
period: string = '1y',
interval: string = '1d'
): Promise<CandleData[]> {
+ const cacheKey = CacheService.key(HISTORICAL_CATEGORY, 'momentum-historical', symbol, period, interval);
+
+ // Check cache
+ const cached = await cacheService.get<CandleData[]>(cacheKey);
+ if (cached) {
+ console.log('Using cached historical data for', symbol);
+ return cached.data;
+ }
+
try {
const result = await invoke<string>('run_python_script', {
scriptName: 'Analytics/equityInvestment/get_historical_data.py',
@@ -29,14 +42,17 @@ export async function fetchHistoricalData(
throw new Error('Invalid historical data format');
}
- return data.map((item: any) => ({
- time: new Date(item.Date || item.timestamp).getTime() / 1000, // Convert to Unix timestamp in seconds
+ const candles: CandleData[] = data.map((item: any) => ({
+ time: new Date(item.Date || item.timestamp).getTime() / 1000,
open: parseFloat(item.Open),
high: parseFloat(item.High),
low: parseFloat(item.Low),
close: parseFloat(item.Close),
volume: parseInt(item.Volume),
}));
+
+ await cacheService.set(cacheKey, candles, HISTORICAL_CATEGORY, TTL['1h']);
+ return candles;
} catch (error) {
console.error('Error fetching historical data:', error);
throw error;
@@ -52,6 +68,11 @@ export async function calculateRSI(
period: string = '1y',
interval: string = '1d'
): Promise<MomentumIndicatorResult['rsi']> {
+ const cacheKey = CacheService.key(INDICATOR_CATEGORY, 'rsi', symbol, period, interval, String(params?.period || 14));
+
+ const cached = await cacheService.get<MomentumIndicatorResult['rsi']>(cacheKey);
+ if (cached) return cached.data;
+
try {
const result = await invoke<string>('run_python_script', {
scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
@@ -76,12 +97,15 @@ export async function calculateRSI(
const currentValue = values[values.length - 1]?.value || 0;
const signal = SignalAnalyzer.analyzeRSI(values, params!);
- return {
+ const rsiResult = {
values,
signal: signal.signal,
current_value: currentValue,
params: params!,
};
+
+ await cacheService.set(cacheKey, rsiResult, INDICATOR_CATEGORY, TTL['15m']);
+ return rsiResult;
} catch (error) {
console.error('Error calculating RSI:', error);
throw error;
@@ -97,6 +121,12 @@ export async function calculateMACD(
period: string = '1y',
interval: string = '1d'
): Promise<MomentumIndicatorResult['macd']> {
+ const cacheKey = CacheService.key(INDICATOR_CATEGORY, 'macd', symbol, period, interval,
+ String(params?.fast_period || 12), String(params?.slow_period || 26), String(params?.signal_period || 9));
+
+ const cached = await cacheService.get<MomentumIndicatorResult['macd']>(cacheKey);
+ if (cached) return cached.data;
+
try {
const result = await invoke<string>('run_python_script', {
scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
@@ -136,7 +166,7 @@ export async function calculateMACD(
const signal = SignalAnalyzer.analyzeMACD(macdLine, signalLine, histogram);
- return {
+ const macdResult = {
macd_line: macdLine,
signal_line: signalLine,
histogram,
@@ -146,6 +176,9 @@ export async function calculateMACD(
current_histogram: currentHistogram,
params: params!,
};
+
+ await cacheService.set(cacheKey, macdResult, INDICATOR_CATEGORY, TTL['15m']);
+ return macdResult;
} catch (error) {
console.error('Error calculating MACD:', error);
throw error;
@@ -161,6 +194,12 @@ export async function calculateStochastic(
period: string = '1y',
interval: string = '1d'
): Promise<MomentumIndicatorResult['stochastic']> {
+ const cacheKey = CacheService.key(INDICATOR_CATEGORY, 'stochastic', symbol, period, interval,
+ String(params?.k_period || 14), String(params?.d_period || 3));
+
+ const cached = await cacheService.get<MomentumIndicatorResult['stochastic']>(cacheKey);
+ if (cached) return cached.data;
+
try {
const result = await invoke<string>('run_python_script', {
scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
@@ -193,7 +232,7 @@ export async function calculateStochastic(
const signal = SignalAnalyzer.analyzeStochastic(kValues, dValues, params!);
- return {
+ const stochasticResult = {
k_values: kValues,
d_values: dValues,
signal: signal.signal,
@@ -201,6 +240,9 @@ export async function calculateStochastic(
current_d: currentD,
params: params!,
};
+
+ await cacheService.set(cacheKey, stochasticResult, INDICATOR_CATEGORY, TTL['15m']);
+ return stochasticResult;
} catch (error) {
console.error('Error calculating Stochastic:', error);
throw error;
@@ -216,6 +258,11 @@ export async function calculateCCI(
period: string = '1y',
interval: string = '1d'
): Promise<MomentumIndicatorResult['cci']> {
+ const cacheKey = CacheService.key(INDICATOR_CATEGORY, 'cci', symbol, period, interval, String(params?.period || 20));
+
+ const cached = await cacheService.get<MomentumIndicatorResult['cci']>(cacheKey);
+ if (cached) return cached.data;
+
try {
const result = await invoke<string>('run_python_script', {
scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
@@ -240,12 +287,15 @@ export async function calculateCCI(
const currentValue = values[values.length - 1]?.value || 0;
const signal = SignalAnalyzer.analyzeCCI(values, params!);
- return {
+ const cciResult = {
values,
signal: signal.signal,
current_value: currentValue,
params: params!,
};
+
+ await cacheService.set(cacheKey, cciResult, INDICATOR_CATEGORY, TTL['15m']);
+ return cciResult;
} catch (error) {
console.error('Error calculating CCI:', error);
throw error;
@@ -261,6 +311,11 @@ export async function calculateROC(
period: string = '1y',
interval: string = '1d'
): Promise<MomentumIndicatorResult['roc']> {
+ const cacheKey = CacheService.key(INDICATOR_CATEGORY, 'roc', symbol, period, interval, String(params?.period || 12));
+
+ const cached = await cacheService.get<MomentumIndicatorResult['roc']>(cacheKey);
+ if (cached) return cached.data;
+
try {
const result = await invoke<string>('run_python_script', {
scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
@@ -285,12 +340,15 @@ export async function calculateROC(
const currentValue = values[values.length - 1]?.value || 0;
const signal = SignalAnalyzer.analyzeROC(values);
- return {
+ const rocResult = {
values,
signal: signal.signal,
current_value: currentValue,
params: params!,
};
+
+ await cacheService.set(cacheKey, rocResult, INDICATOR_CATEGORY, TTL['15m']);
+ return rocResult;
} catch (error) {
console.error('Error calculating ROC:', error);
throw error;
@@ -306,6 +364,11 @@ export async function calculateWilliamsR(
period: string = '1y',
interval: string = '1d'
): Promise<MomentumIndicatorResult['williams_r']> {
+ const cacheKey = CacheService.key(INDICATOR_CATEGORY, 'williams-r', symbol, period, interval, String(params?.period || 14));
+
+ const cached = await cacheService.get<MomentumIndicatorResult['williams_r']>(cacheKey);
+ if (cached) return cached.data;
+
try {
const result = await invoke<string>('run_python_script', {
scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
@@ -330,12 +393,15 @@ export async function calculateWilliamsR(
const currentValue = values[values.length - 1]?.value || 0;
const signal = SignalAnalyzer.analyzeWilliamsR(values, params!);
- return {
+ const williamsResult = {
values,
signal: signal.signal,
current_value: currentValue,
params: params!,
};
+
+ await cacheService.set(cacheKey, williamsResult, INDICATOR_CATEGORY, TTL['15m']);
+ return williamsResult;
} catch (error) {
console.error('Error calculating Williams %R:', error);
throw error;
@@ -351,6 +417,12 @@ export async function calculateAwesomeOscillator(
period: string = '1y',
interval: string = '1d'
): Promise<MomentumIndicatorResult['awesome_oscillator']> {
+ const cacheKey = CacheService.key(INDICATOR_CATEGORY, 'awesome-osc', symbol, period, interval,
+ String(params?.fast_period || 5), String(params?.slow_period || 34));
+
+ const cached = await cacheService.get<MomentumIndicatorResult['awesome_oscillator']>(cacheKey);
+ if (cached) return cached.data;
+
try {
const result = await invoke<string>('run_python_script', {
scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
@@ -376,12 +448,15 @@ export async function calculateAwesomeOscillator(
const currentValue = values[values.length - 1]?.value || 0;
const signal = SignalAnalyzer.analyzeAwesomeOscillator(values);
- return {
+ const aoResult = {
values,
signal: signal.signal,
current_value: currentValue,
params: params!,
};
+
+ await cacheService.set(cacheKey, aoResult, INDICATOR_CATEGORY, TTL['15m']);
+ return aoResult;
} catch (error) {
console.error('Error calculating Awesome Oscillator:', error);
throw error;
@@ -397,6 +472,12 @@ export async function calculateTSI(
period: string = '1y',
interval: string = '1d'
): Promise<MomentumIndicatorResult['tsi']> {
+ const cacheKey = CacheService.key(INDICATOR_CATEGORY, 'tsi', symbol, period, interval,
+ String(params?.long_period || 25), String(params?.short_period || 13), String(params?.signal_period || 13));
+
+ const cached = await cacheService.get<MomentumIndicatorResult['tsi']>(cacheKey);
+ if (cached) return cached.data;
+
try {
const result = await invoke<string>('run_python_script', {
scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
@@ -430,7 +511,7 @@ export async function calculateTSI(
const signal = SignalAnalyzer.analyzeTSI(values, signalLine);
- return {
+ const tsiResult = {
values,
signal_line: signalLine,
signal: signal.signal,
@@ -438,6 +519,9 @@ export async function calculateTSI(
current_signal: currentSignal,
params: params!,
};
+
+ await cacheService.set(cacheKey, tsiResult, INDICATOR_CATEGORY, TTL['15m']);
+ return tsiResult;
} catch (error) {
console.error('Error calculating TSI:', error);
throw error;
@@ -453,6 +537,12 @@ export async function calculateUltimateOscillator(
period: string = '1y',
interval: string = '1d'
): Promise<MomentumIndicatorResult['ultimate_oscillator']> {
+ const cacheKey = CacheService.key(INDICATOR_CATEGORY, 'ultimate-osc', symbol, period, interval,
+ String(params?.period1 || 7), String(params?.period2 || 14), String(params?.period3 || 28));
+
+ const cached = await cacheService.get<MomentumIndicatorResult['ultimate_oscillator']>(cacheKey);
+ if (cached) return cached.data;
+
try {
const result = await invoke<string>('run_python_script', {
scriptName: 'Analytics/technical_analysis/momentum_indicators.py',
@@ -482,12 +572,15 @@ export async function calculateUltimateOscillator(
const currentValue = values[values.length - 1]?.value || 0;
const signal = SignalAnalyzer.analyzeUltimateOscillator(values);
- return {
+ const uoResult = {
values,
signal: signal.signal,
current_value: currentValue,
params: params!,
};
+
+ await cacheService.set(cacheKey, uoResult, INDICATOR_CATEGORY, TTL['15m']);
+ return uoResult;
} catch (error) {
console.error('Error calculating Ultimate Oscillator:', error);
throw error;
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTab.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTab.tsx
index ba1460240..9ebe43659 100644
--- a/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTab.tsx
@@ -89,6 +89,7 @@ export default function MaritimeTab() {
onTogglePlanes={mapControls.togglePlanes}
onToggleSatellites={mapControls.toggleSatellites}
onClearMarkers={mapControls.clearMarkers}
+ onLoadVessels={maritimeData.loadRealVessels}
/>
{/* Center - Globe/Map */}
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabDeck.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabDeck.tsx
deleted file mode 100644
index d4895ad1d..000000000
--- a/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabDeck.tsx
+++ /dev/null
@@ -1,762 +0,0 @@
-import React, { useState, useEffect, useMemo } from 'react';
-import DeckGL from '@deck.gl/react';
-import { ScatterplotLayer, PathLayer } from '@deck.gl/layers';
-import { TileLayer } from '@deck.gl/geo-layers';
-import { BitmapLayer } from '@deck.gl/layers';
-import { useAuth } from '@/contexts/AuthContext';
-import { MarineApiService, VesselData } from '@/services/maritime/marineApi';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { TabFooter } from '@/components/common/TabFooter';
-import { GeocodingService, GeocodeLocation } from '@/services/geopolitics/geocodingService';
-
-const INITIAL_VIEW_STATE = {
- longitude: 72.8,
- latitude: 19.0,
- zoom: 10,
- pitch: 0,
- bearing: 0
-};
-
-const FINCEPT = {
- ORANGE: '#FF6600',
- BLACK: '#000000',
- DARK_BG: '#0F0F0F',
- BORDER: '#333333',
- WHITE: '#FFFFFF',
- GREEN: '#00FF00',
- RED: '#FF0000',
- YELLOW: '#FFD700',
- CYAN: '#00E5FF',
- GRAY: '#888888'
-};
-
-interface VesselPoint {
- position: [number, number, number];
- color: [number, number, number, number];
- imo: string;
- name: string;
- speed: number;
-}
-
-export default function MaritimeTabDeck() {
- const { colors, fontFamily } = useTerminalTheme();
- const { session } = useAuth();
- const apiKey = session?.api_key || null;
-
- const [vessels, setVessels] = useState<VesselData[]>([]);
- const [isLoading, setIsLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [viewState, setViewState] = useState(INITIAL_VIEW_STATE);
- const [selectedVessel, setSelectedVessel] = useState<VesselData | null>(null);
- const [vesselHistory, setVesselHistory] = useState<any[]>([]);
- const [showHistory, setShowHistory] = useState(false);
- const [healthStatus, setHealthStatus] = useState<any>(null);
-
- // Search controls
- const [searchMode, setSearchMode] = useState<'single' | 'multi'>('single');
- const [searchImo, setSearchImo] = useState('');
- const [multiImoInput, setMultiImoInput] = useState('');
- const [searchingVessel, setSearchingVessel] = useState(false);
-
- // Location search
- const [locationSearch, setLocationSearch] = useState('');
- const [searchingLocation, setSearchingLocation] = useState(false);
- const [suggestions, setSuggestions] = useState<GeocodeLocation[]>([]);
- const [showSuggestions, setShowSuggestions] = useState(false);
-
- // Load vessels from API
- const loadVessels = async () => {
- if (!apiKey) {
- setError('No API key available');
- return;
- }
-
- setIsLoading(true);
- setError(null);
-
- try {
- const response = await MarineApiService.searchVesselsByArea(
- { min_lat: 18.5, max_lat: 19.5, min_lng: 72.0, max_lng: 73.5 },
- apiKey
- );
-
- if (response.success && response.data) {
- const validVessels = response.data.vessels.filter(
- v => v.last_pos_latitude && v.last_pos_longitude
- );
- setVessels(validVessels);
- } else {
- setError(response.error || 'Failed to load vessels');
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error');
- } finally {
- setIsLoading(false);
- }
- };
-
- // Search vessel by IMO
- const searchVessel = async () => {
- if (!apiKey || !searchImo.trim()) return;
-
- setSearchingVessel(true);
- setError(null);
-
- try {
- const response = await MarineApiService.getVesselPosition(searchImo.trim(), apiKey);
-
- if (response.success && response.data) {
- const vessel = response.data.vessel;
- setVessels(prev => {
- const exists = prev.find(v => v.imo === vessel.imo);
- if (exists) return prev;
- return [...prev, vessel];
- });
-
- setViewState({
- longitude: parseFloat(vessel.last_pos_longitude),
- latitude: parseFloat(vessel.last_pos_latitude),
- zoom: 14,
- pitch: 0,
- bearing: 0
- });
-
- setSearchImo('');
- } else {
- setError(response.error || 'Vessel not found');
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Search failed');
- } finally {
- setSearchingVessel(false);
- }
- };
-
- // Multi-vessel search
- const searchMultiVessels = async () => {
- if (!apiKey || !multiImoInput.trim()) return;
-
- setSearchingVessel(true);
- setError(null);
-
- try {
- const imos = multiImoInput.split(/[,\s]+/).map(s => s.trim()).filter(s => s.length > 0);
-
- if (imos.length === 0) {
- setError('Please enter at least one IMO number');
- setSearchingVessel(false);
- return;
- }
-
- if (imos.length > 50) {
- setError('Maximum 50 IMO numbers allowed');
- setSearchingVessel(false);
- return;
- }
-
- const response = await MarineApiService.getMultiVesselPositions(imos, apiKey);
-
- if (response.success && response.data && response.data.vessels) {
- const newVessels = response.data.vessels;
-
- setVessels(prev => {
- const combined = [...prev];
- newVessels.forEach(vessel => {
- const exists = combined.find(v => v.imo === vessel.imo);
- if (!exists) combined.push(vessel);
- });
- return combined;
- });
-
- setMultiImoInput('');
-
- if (response.data.not_found_count > 0 && response.data.not_found) {
- setError(`${response.data.not_found_count} vessels not found: ${response.data.not_found.join(', ')}`);
- }
- } else {
- setError(response.error || 'Multi-vessel search failed');
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Search failed');
- } finally {
- setSearchingVessel(false);
- }
- };
-
- // Load vessel history
- const loadVesselHistory = async (vessel: VesselData) => {
- if (!apiKey) return;
-
- setSelectedVessel(vessel);
- setShowHistory(true);
- setError(null);
-
- try {
- const response = await MarineApiService.getVesselHistory(vessel.imo, apiKey);
-
- if (response.success && response.data && response.data.history && response.data.history.positions) {
- setVesselHistory(response.data.history.positions);
- } else {
- setError(response.error || 'Failed to load vessel history');
- setVesselHistory([]);
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'History load failed');
- setVesselHistory([]);
- }
- };
-
- // Load health status
- const loadHealthStatus = async () => {
- if (!apiKey) return;
-
- try {
- const response = await MarineApiService.getMarineHealth(apiKey);
- if (response.success && response.data) {
- setHealthStatus(response.data);
- }
- } catch (err) {
- // Silent fail
- }
- };
-
- // Fetch autocomplete suggestions
- const fetchSuggestions = async (query: string) => {
- if (query.length < 3) {
- setSuggestions([]);
- setShowSuggestions(false);
- return;
- }
-
- try {
- const results = await GeocodingService.searchLocation(query, 5);
- if (results.success && results.suggestions) {
- setSuggestions(results.suggestions);
- setShowSuggestions(results.suggestions.length > 0);
- }
- } catch (err) {
- setSuggestions([]);
- setShowSuggestions(false);
- }
- };
-
- // Geocoding search
- const searchByLocation = async (selectedLocation?: GeocodeLocation) => {
- if (!apiKey) return;
-
- const locationData = selectedLocation || (suggestions.length > 0 ? suggestions[0] : null);
- if (!locationData && !locationSearch.trim()) return;
-
- setSearchingLocation(true);
- setError(null);
- setShowSuggestions(false);
-
- try {
- let bounds;
- if (locationData) {
- bounds = locationData.bbox;
- } else {
- const results = await GeocodingService.searchLocation(locationSearch, 1);
- if (!results.success || !results.suggestions || results.suggestions.length === 0) {
- setError('Location not found');
- setSearchingLocation(false);
- return;
- }
- bounds = results.suggestions[0].bbox;
- }
-
- const vesselResponse = await MarineApiService.searchVesselsByArea(bounds, apiKey);
-
- if (vesselResponse.success && vesselResponse.data) {
- const validVessels = vesselResponse.data.vessels.filter(
- v => v.last_pos_latitude && v.last_pos_longitude
- );
- setVessels(validVessels);
-
- const centerLat = (bounds.min_lat + bounds.max_lat) / 2;
- const centerLng = (bounds.min_lng + bounds.max_lng) / 2;
- setViewState({
- longitude: centerLng,
- latitude: centerLat,
- zoom: 10,
- pitch: 0,
- bearing: 0
- });
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Geocoding failed');
- } finally {
- setSearchingLocation(false);
- }
- };
-
- // Search current viewport
- const searchCurrentView = async () => {
- if (!apiKey) return;
-
- setIsLoading(true);
- setError(null);
-
- try {
- const zoom = viewState.zoom;
- const lat = viewState.latitude;
- const lng = viewState.longitude;
-
- const latDelta = 180 / Math.pow(2, zoom);
- const lngDelta = 360 / Math.pow(2, zoom);
-
- const bounds = {
- min_lat: lat - latDelta,
- max_lat: lat + latDelta,
- min_lng: lng - lngDelta,
- max_lng: lng + lngDelta
- };
-
- const response = await MarineApiService.searchVesselsByArea(bounds, apiKey);
-
- if (response.success && response.data) {
- const validVessels = response.data.vessels.filter(
- v => v.last_pos_latitude && v.last_pos_longitude
- );
- setVessels(validVessels);
- } else {
- setError(response.error || 'Failed to load vessels');
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Search failed');
- } finally {
- setIsLoading(false);
- }
- };
-
- // Auto-load vessels on mount
- useEffect(() => {
- loadVessels();
- loadHealthStatus();
- const interval = setInterval(loadVessels, 300000);
- return () => clearInterval(interval);
- }, [apiKey]);
-
- // Memoized vessel points
- const vesselPoints = useMemo(() => {
- return vessels.map(v => {
- const speed = parseFloat(v.last_pos_speed) || 0;
- let color: [number, number, number, number];
- if (speed < 5) color = [0, 255, 255, 180];
- else if (speed < 15) color = [255, 215, 0, 180];
- else color = [255, 69, 0, 180];
-
- return {
- position: [parseFloat(v.last_pos_longitude), parseFloat(v.last_pos_latitude), 0] as [number, number, number],
- color,
- imo: v.imo,
- name: v.name,
- speed
- };
- });
- }, [vessels]);
-
- // Memoized layers
- const layers = useMemo(() => {
- const allLayers: any[] = [
- new TileLayer({
- id: 'basemap',
- data: 'https://basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
- minZoom: 0,
- maxZoom: 19,
- tileSize: 256,
- renderSubLayers: (props: any) => {
- const { boundingBox } = props.tile;
- return new BitmapLayer(props, {
- data: undefined,
- image: props.data,
- bounds: [boundingBox[0][0], boundingBox[0][1], boundingBox[1][0], boundingBox[1][1]]
- });
- }
- })
- ];
-
- if (showHistory && vesselHistory.length > 0) {
- const pathData = vesselHistory.map(pos => [
- parseFloat(pos.longitude),
- parseFloat(pos.latitude)
- ]);
-
- allLayers.push(
- new PathLayer({
- id: 'vessel-history',
- data: [{ path: pathData }],
- getPath: (d: any) => d.path,
- getColor: [255, 215, 0, 200],
- getWidth: 3,
- widthMinPixels: 2,
- widthMaxPixels: 8,
- jointRounded: true,
- capRounded: true
- })
- );
- }
-
- if (vesselPoints.length > 0) {
- allLayers.push(
- new ScatterplotLayer({
- id: 'vessels',
- data: vesselPoints,
- getPosition: (d: any) => d.position,
- getFillColor: (d: any) => d.color,
- getRadius: 80,
- radiusMinPixels: 4,
- radiusMaxPixels: 20,
- pickable: true,
- autoHighlight: true,
- highlightColor: [255, 255, 255, 100],
- onClick: (info: any) => {
- if (info.object) {
- const vessel = vessels.find(v => v.imo === info.object.imo);
- if (vessel) {
- loadVesselHistory(vessel);
- }
- }
- }
- })
- );
- }
-
- return allLayers;
- }, [vesselPoints, showHistory, vesselHistory, vessels]);
-
- return (
- <div style={{
- width: '100%',
- height: '100%',
- display: 'flex',
- flexDirection: 'column',
- background: colors.background,
- color: colors.text,
- fontFamily: fontFamily,
- position: 'relative',
- overflow: 'hidden'
- }}>
- <style>{`
- @keyframes spin {
- 0% { transform: rotate(0deg); }
- 100% { transform: rotate(360deg); }
- }
- `}</style>
-
- {/* Header */}
- <div style={{
- position: 'absolute',
- top: 0,
- left: 0,
- right: 0,
- background: FINCEPT.BLACK,
- borderBottom: `2px solid ${FINCEPT.ORANGE}`,
- zIndex: 1000,
- fontFamily: 'Consolas, monospace',
- fontSize: '12px'
- }}>
- {/* Title Bar */}
- <div style={{
- padding: '4px 12px',
- display: 'flex',
- alignItems: 'center',
- gap: '12px',
- borderBottom: `1px solid ${FINCEPT.BORDER}`
- }}>
- <div style={{ color: FINCEPT.ORANGE, fontWeight: 'bold', fontSize: '13px' }}>
- MAR&gt;
- </div>
- <div style={{ color: FINCEPT.WHITE, fontWeight: 'bold' }}>
- MARITIME TRACKING
- </div>
- <div style={{ color: FINCEPT.GRAY }}>|</div>
- <div style={{ color: vesselPoints.length > 0 ? FINCEPT.GREEN : FINCEPT.RED, fontWeight: 'bold' }}>
- {vesselPoints.length}/{vessels.length} VESSELS
- </div>
- </div>
-
- {/* Search Controls */}
- <div style={{
- padding: '4px 12px',
- display: 'flex',
- gap: '8px',
- alignItems: 'center',
- flexWrap: 'wrap'
- }}>
- {/* Location Search */}
- <div style={{ position: 'relative' }}>
- <input
- type="text"
- placeholder="Search: Suez Canal..."
- value={locationSearch}
- onChange={(e) => {
- setLocationSearch(e.target.value);
- fetchSuggestions(e.target.value);
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter') searchByLocation();
- else if (e.key === 'Escape') setShowSuggestions(false);
- }}
- onFocus={() => suggestions.length > 0 && setShowSuggestions(true)}
- disabled={searchingLocation}
- style={{
- padding: '4px 8px',
- background: '#1a1a1a',
- border: '1px solid #333',
- color: '#fff',
- fontFamily: 'Consolas, monospace',
- fontSize: '11px',
- width: '160px',
- outline: 'none'
- }}
- />
- {showSuggestions && suggestions.length > 0 && (
- <div style={{
- position: 'absolute',
- top: '100%',
- left: 0,
- width: '160px',
- background: '#1a1a1a',
- border: '1px solid #333',
- borderTop: 'none',
- maxHeight: '200px',
- overflowY: 'auto',
- zIndex: 2000,
- marginTop: '1px'
- }}>
- {suggestions.map((suggestion, idx) => (
- <div
- key={idx}
- onClick={() => {
- setLocationSearch(suggestion.name);
- searchByLocation(suggestion);
- setShowSuggestions(false);
- }}
- style={{
- padding: '6px 8px',
- cursor: 'pointer',
- fontSize: '10px',
- borderBottom: idx < suggestions.length - 1 ? '1px solid #333' : 'none',
- color: '#ccc',
- background: '#1a1a1a'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.background = '#2a2a2a';
- e.currentTarget.style.color = '#fff';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.background = '#1a1a1a';
- e.currentTarget.style.color = '#ccc';
- }}
- >
- {suggestion.name}
- </div>
- ))}
- </div>
- )}
- </div>
-
- <button
- onClick={() => searchByLocation()}
- disabled={searchingLocation || !locationSearch.trim()}
- style={{
- padding: '4px 10px',
- background: '#10b981',
- border: 'none',
- color: '#000',
- fontFamily: 'Consolas, monospace',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: searchingLocation ? 'not-allowed' : 'pointer',
- opacity: searchingLocation ? 0.5 : 1
- }}
- >
- LOCATION
- </button>
-
- <button
- onClick={searchCurrentView}
- disabled={isLoading}
- style={{
- padding: '4px 10px',
- background: '#06b6d4',
- border: 'none',
- color: '#000',
- fontFamily: 'Consolas, monospace',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: isLoading ? 'not-allowed' : 'pointer',
- opacity: isLoading ? 0.5 : 1
- }}
- >
- CURRENT VIEW
- </button>
-
- <div style={{ width: '1px', height: '18px', background: '#333' }} />
-
- <select
- value={searchMode}
- onChange={(e) => setSearchMode(e.target.value as 'single' | 'multi')}
- style={{
- padding: '4px 6px',
- background: '#1a1a1a',
- border: '1px solid #333',
- color: '#fff',
- fontFamily: 'Consolas, monospace',
- fontSize: '10px',
- outline: 'none',
- cursor: 'pointer'
- }}
- >
- <option value="single">SINGLE</option>
- <option value="multi">MULTI</option>
- </select>
-
- {searchMode === 'single' ? (
- <input
- type="text"
- placeholder="IMO"
- value={searchImo}
- onChange={(e) => setSearchImo(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && searchVessel()}
- disabled={searchingVessel}
- style={{
- padding: '4px 8px',
- background: '#1a1a1a',
- border: '1px solid #333',
- color: '#fff',
- fontFamily: 'Consolas, monospace',
- fontSize: '11px',
- width: '100px',
- outline: 'none'
- }}
- />
- ) : (
- <input
- type="text"
- placeholder="IMO1, IMO2..."
- value={multiImoInput}
- onChange={(e) => setMultiImoInput(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && searchMultiVessels()}
- disabled={searchingVessel}
- style={{
- padding: '4px 8px',
- background: '#1a1a1a',
- border: '1px solid #333',
- color: '#fff',
- fontFamily: 'Consolas, monospace',
- fontSize: '11px',
- width: '120px',
- outline: 'none'
- }}
- />
- )}
-
- <button
- onClick={searchMode === 'single' ? searchVessel : searchMultiVessels}
- disabled={searchingVessel || (searchMode === 'single' ? !searchImo.trim() : !multiImoInput.trim())}
- style={{
- padding: '4px 12px',
- background: FINCEPT.ORANGE,
- border: 'none',
- color: '#000',
- fontFamily: 'Consolas, monospace',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: searchingVessel ? 'not-allowed' : 'pointer',
- opacity: searchingVessel ? 0.5 : 1
- }}
- >
- GO
- </button>
-
- {showHistory && (
- <button
- onClick={() => {
- setShowHistory(false);
- setVesselHistory([]);
- setSelectedVessel(null);
- }}
- style={{
- padding: '4px 10px',
- background: '#000',
- border: '1px solid #ffd700',
- color: '#ffd700',
- fontFamily: 'Consolas, monospace',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer'
- }}
- >
- CLEAR
- </button>
- )}
- </div>
- </div>
-
- {/* Error Display */}
- {error && (
- <div style={{
- position: 'absolute',
- top: '80px',
- left: '20px',
- right: '20px',
- padding: '12px 20px',
- background: 'rgba(255, 0, 0, 0.2)',
- border: '1px solid #ff0000',
- borderRadius: '4px',
- color: '#ff6b6b',
- fontFamily: 'Consolas, monospace',
- fontSize: '13px',
- zIndex: 10
- }}>
- ERROR: {error}
- </div>
- )}
-
- {/* Deck.gl Map */}
- <div style={{ flex: 1, position: 'relative', background: '#000', minHeight: 0 }}>
- <DeckGL
- viewState={viewState}
- onViewStateChange={({ viewState: vs }: any) => setViewState(vs)}
- controller={true}
- layers={layers}
- width="100%"
- height="100%"
- style={{ position: 'absolute', inset: '0' }}
- getTooltip={({ object }: any) => object && {
- html: `<strong>${object.name}</strong><br/>IMO: ${object.imo}<br/>Speed: ${object.speed.toFixed(1)} kts`,
- style: {
- backgroundColor: '#000',
- color: '#fff',
- padding: '8px',
- borderRadius: '4px',
- border: '1px solid #ff6600',
- fontFamily: 'Consolas, monospace',
- fontSize: '11px'
- }
- }}
- />
- </div>
-
- {/* Footer */}
- <div style={{ flexShrink: 0 }}>
- <TabFooter
- tabName="MARITIME TRACKING"
- leftInfo={[
- { label: 'VESSELS', value: `${vesselPoints.length}/${vessels.length}`, color: vesselPoints.length > 0 ? '#10b981' : '#ef4444' },
- { label: 'ZONE', value: 'MUMBAI', color: '#fbbf24' },
- { label: 'ENGINE', value: 'DECK.GL v9.2', color: '#06b6d4' },
- ...(healthStatus ? [{ label: 'API', value: healthStatus.status.toUpperCase(), color: healthStatus.status === 'healthy' ? '#10b981' : '#ef4444' }] : []),
- ...(selectedVessel ? [{ label: 'TRACKING', value: selectedVessel.name, color: '#ffd700' }] : []),
- ...(showHistory && vesselHistory.length > 0 ? [{ label: 'HISTORY', value: `${vesselHistory.length} PTS`, color: '#ffd700' }] : [])
- ]}
- statusInfo={`REAL-TIME AIS DATA | AUTO-REFRESH: 5MIN | ${new Date().toLocaleTimeString()}`}
- backgroundColor="#000000"
- borderColor="#ff6600"
- />
- </div>
- </div>
- );
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabKepler.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabKepler.tsx
deleted file mode 100644
index 7886d4354..000000000
--- a/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabKepler.tsx
+++ /dev/null
@@ -1,383 +0,0 @@
-// MaritimeTabKepler.tsx - Professional Maritime Intelligence with Kepler.gl
-// NO DUMMY DATA - Only real vessel data from Marine API
-
-import React, { useState, useEffect, useMemo } from 'react';
-// @ts-ignore - Kepler.gl types are not fully compatible
-import KeplerGl from 'kepler.gl/components';
-// @ts-ignore
-import { addDataToMap, wrapTo } from 'kepler.gl/actions';
-import { useDispatch } from 'react-redux';
-import { useAuth } from '@/contexts/AuthContext';
-import { MarineApiService, VesselData } from '@/services/maritime/marineApi';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { TabFooter } from '@/components/common/TabFooter';
-import { useTranslation } from 'react-i18next';
-
-interface VesselGeoJSON {
- type: 'FeatureCollection';
- features: Array<{
- type: 'Feature';
- geometry: {
- type: 'Point';
- coordinates: [number, number]; // [lng, lat]
- };
- properties: {
- imo: string;
- name: string;
- speed: string;
- angle: string;
- from_port?: string;
- to_port?: string;
- last_updated: string;
- };
- }>;
-}
-
-export default function MaritimeTabKepler() {
- const { colors, fontSize, fontFamily } = useTerminalTheme();
- const { t } = useTranslation('maritime');
- const { session } = useAuth();
- const dispatch = useDispatch();
- const apiKey = session?.api_key || null;
-
- const [vessels, setVessels] = useState<VesselData[]>([]);
- const [isLoading, setIsLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [searchImo, setSearchImo] = useState('');
- const [searchingVessel, setSearchingVessel] = useState(false);
- const [vesselCount, setVesselCount] = useState(0);
-
- // Load vessels from API - Mumbai area
- const loadVessels = async () => {
- if (!apiKey) {
- setError('No API key available');
- return;
- }
-
- setIsLoading(true);
- setError(null);
-
- try {
- const response = await MarineApiService.searchVesselsByArea(
- {
- min_lat: 18.5,
- max_lat: 19.5,
- min_lng: 72.0,
- max_lng: 73.5
- },
- apiKey
- );
-
- if (response.success && response.data) {
- const validVessels = response.data.vessels.filter(
- v => v.last_pos_latitude && v.last_pos_longitude
- );
- setVessels(validVessels);
- setVesselCount(validVessels.length);
- } else {
- setError(response.error || 'Failed to load vessels');
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error');
- } finally {
- setIsLoading(false);
- }
- };
-
- // Search specific vessel by IMO
- const searchVessel = async () => {
- if (!apiKey || !searchImo.trim()) return;
-
- setSearchingVessel(true);
- setError(null);
-
- try {
- const response = await MarineApiService.getVesselPosition(searchImo.trim(), apiKey);
-
- if (response.success && response.data) {
- // Add searched vessel to the map
- setVessels(prev => {
- const exists = prev.find(v => v.imo === response.data!.vessel.imo);
- if (exists) return prev;
- return [...prev, response.data!.vessel];
- });
- setSearchImo('');
- } else {
- setError(response.error || 'Vessel not found');
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Search failed');
- } finally {
- setSearchingVessel(false);
- }
- };
-
- // Convert vessel data to GeoJSON for Kepler.gl
- const vesselGeoJSON: VesselGeoJSON = useMemo(() => ({
- type: 'FeatureCollection',
- features: vessels.map(v => ({
- type: 'Feature',
- geometry: {
- type: 'Point',
- coordinates: [parseFloat(v.last_pos_longitude), parseFloat(v.last_pos_latitude)]
- },
- properties: {
- imo: v.imo,
- name: v.name,
- speed: v.last_pos_speed,
- angle: v.last_pos_angle,
- from_port: v.route_from_port_name || undefined,
- to_port: v.route_to_port_name || undefined,
- last_updated: v.last_pos_updated_at || 'Unknown'
- }
- }))
- }), [vessels]);
-
- // Load vessel data into Kepler.gl
- useEffect(() => {
- if (vessels.length > 0) {
- const dataset = {
- info: {
- label: 'Marine Vessels',
- id: 'marine_vessels'
- },
- data: {
- fields: [
- { name: 'imo', type: 'string' },
- { name: 'name', type: 'string' },
- { name: 'speed', type: 'real' },
- { name: 'angle', type: 'real' },
- { name: 'from_port', type: 'string' },
- { name: 'to_port', type: 'string' },
- { name: 'lat', type: 'real' },
- { name: 'lng', type: 'real' },
- { name: 'last_updated', type: 'timestamp' }
- ],
- rows: vessels.map(v => [
- v.imo,
- v.name,
- parseFloat(v.last_pos_speed),
- parseFloat(v.last_pos_angle),
- v.route_from_port_name || '',
- v.route_to_port_name || '',
- parseFloat(v.last_pos_latitude),
- parseFloat(v.last_pos_longitude),
- v.last_pos_updated_at || ''
- ])
- }
- };
-
- const config = {
- version: 'v1',
- config: {
- visState: {
- filters: [],
- layers: [
- {
- id: 'vessels',
- type: 'point',
- config: {
- dataId: 'marine_vessels',
- label: 'Vessels',
- color: [0, 255, 255],
- columns: {
- lat: 'lat',
- lng: 'lng'
- },
- isVisible: true,
- visConfig: {
- radius: 8,
- fixedRadius: false,
- opacity: 0.8,
- outline: false,
- thickness: 2,
- colorRange: {
- name: 'Global Warming',
- type: 'sequential',
- category: 'Uber',
- colors: ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']
- },
- radiusRange: [0, 50]
- }
- },
- visualChannels: {
- colorField: {
- name: 'speed',
- type: 'real'
- },
- colorScale: 'quantile',
- sizeField: null,
- sizeScale: 'linear'
- }
- }
- ]
- },
- mapState: {
- latitude: 19.0,
- longitude: 72.8,
- zoom: 10
- },
- mapStyle: {
- styleType: 'dark'
- }
- }
- };
-
- dispatch(
- wrapTo(
- 'maritime',
- addDataToMap({
- datasets: dataset,
- options: {
- centerMap: true,
- readOnly: false
- },
- config
- })
- )
- );
- }
- }, [vessels, dispatch]);
-
- // Auto-load vessels on mount
- useEffect(() => {
- loadVessels();
- const interval = setInterval(loadVessels, 300000); // Refresh every 5 minutes
- return () => clearInterval(interval);
- }, [apiKey]);
-
- return (
- <div
- style={{
- width: '100%',
- height: '100vh',
- display: 'flex',
- flexDirection: 'column',
- background: colors.background,
- color: colors.text,
- fontFamily: fontFamily,
- fontSize: `${fontSize}px`
- }}
- >
- {/* Header Controls */}
- <div
- style={{
- padding: '12px 20px',
- background: 'rgba(0, 0, 0, 0.8)',
- borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- gap: '20px',
- flexWrap: 'wrap'
- }}
- >
- {/* Title */}
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#00ffff' }}>
- 🚢 MARITIME INTELLIGENCE
- </div>
- <div
- style={{
- padding: '4px 12px',
- background: vesselCount > 0 ? 'rgba(0, 255, 0, 0.2)' : 'rgba(255, 0, 0, 0.2)',
- border: `1px solid ${vesselCount > 0 ? '#00ff00' : '#ff0000'}`,
- borderRadius: '4px',
- fontSize: '12px',
- fontWeight: 'bold'
- }}
- >
- {vesselCount} VESSELS
- </div>
- </div>
-
- {/* IMO Search */}
- <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
- <input
- type="text"
- placeholder="Search by IMO..."
- value={searchImo}
- onChange={(e) => setSearchImo(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && searchVessel()}
- disabled={searchingVessel}
- style={{
- padding: '8px 12px',
- background: 'rgba(0, 0, 0, 0.6)',
- border: '1px solid rgba(255, 255, 255, 0.2)',
- borderRadius: '4px',
- color: colors.text,
- fontFamily: 'Consolas, monospace',
- fontSize: '13px',
- width: '200px'
- }}
- />
- <button
- onClick={searchVessel}
- disabled={searchingVessel || !searchImo.trim()}
- style={{
- padding: '8px 16px',
- background: searchingVessel ? '#333' : '#0a0a0a',
- border: '1px solid #00ffff',
- borderRadius: '4px',
- color: '#00ffff',
- fontFamily: 'Consolas, monospace',
- fontSize: '12px',
- fontWeight: 'bold',
- cursor: searchingVessel ? 'not-allowed' : 'pointer',
- opacity: searchingVessel ? 0.5 : 1
- }}
- >
- {searchingVessel ? 'SEARCHING...' : 'SEARCH'}
- </button>
- <button
- onClick={loadVessels}
- disabled={isLoading}
- style={{
- padding: '8px 16px',
- background: '#0a0a0a',
- border: '1px solid #ffd700',
- borderRadius: '4px',
- color: '#ffd700',
- fontFamily: 'Consolas, monospace',
- fontSize: '12px',
- fontWeight: 'bold',
- cursor: isLoading ? 'not-allowed' : 'pointer',
- opacity: isLoading ? 0.5 : 1
- }}
- >
- {isLoading ? 'LOADING...' : '🔄 REFRESH'}
- </button>
- </div>
- </div>
-
- {/* Error Display */}
- {error && (
- <div
- style={{
- padding: '12px 20px',
- background: 'rgba(255, 0, 0, 0.2)',
- border: '1px solid #ff0000',
- color: '#ff6b6b',
- fontFamily: 'Consolas, monospace',
- fontSize: '13px'
- }}
- >
- ⚠️ {error}
- </div>
- )}
-
- {/* Kepler.gl Map */}
- <div style={{ flex: 1, position: 'relative' }}>
- <KeplerGl
- id="maritime"
- mapboxApiAccessToken={import.meta.env.VITE_MAPBOX_TOKEN || ''}
- width={window.innerWidth}
- height={window.innerHeight - 120}
- theme="dark"
- />
- </div>
-
- <TabFooter tabName="maritime" />
- </div>
- );
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/components/LeftPanel.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/components/LeftPanel.tsx
index 32a526786..96ee32445 100644
--- a/fincept-terminal-desktop/src/components/tabs/maritime/components/LeftPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/components/LeftPanel.tsx
@@ -20,6 +20,7 @@ interface LeftPanelProps {
onTogglePlanes: () => void;
onToggleSatellites: () => void;
onClearMarkers: () => void;
+ onLoadVessels: () => void;
}
export const LeftPanel: React.FC<LeftPanelProps> = ({
@@ -38,7 +39,8 @@ export const LeftPanel: React.FC<LeftPanelProps> = ({
onToggleShips,
onTogglePlanes,
onToggleSatellites,
- onClearMarkers
+ onClearMarkers,
+ onLoadVessels
}) => {
return (
<div style={{
@@ -82,6 +84,25 @@ export const LeftPanel: React.FC<LeftPanelProps> = ({
</div>
)}
+ {/* Load Vessels Button */}
+ <button
+ onClick={onLoadVessels}
+ disabled={isLoadingVessels}
+ style={{
+ width: '100%',
+ background: isLoadingVessels ? '#1a1a1a' : '#0a0a0a',
+ color: isLoadingVessels ? '#888' : '#0ff',
+ border: '1px solid #0ff',
+ padding: '8px',
+ fontSize: '10px',
+ cursor: isLoadingVessels ? 'not-allowed' : 'pointer',
+ fontWeight: 'bold',
+ marginBottom: '8px'
+ }}
+ >
+ {isLoadingVessels ? '⏳ LOADING...' : realVesselsCount > 0 ? '🔄 REFRESH VESSELS' : '📡 LOAD VESSEL DATA'}
+ </button>
+
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
<StatBox label="TOTAL VESSELS" value={intelligence.active_vessels} color="#0ff" />
<StatBox label="DISPLAYED" value={realVesselsCount} color="#00ff00" />
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/hooks/useMaritimeData.ts b/fincept-terminal-desktop/src/components/tabs/maritime/hooks/useMaritimeData.ts
index 71bab17e4..55723c9f5 100644
--- a/fincept-terminal-desktop/src/components/tabs/maritime/hooks/useMaritimeData.ts
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/hooks/useMaritimeData.ts
@@ -130,12 +130,8 @@ export function useMaritimeData({ apiKey, onVesselsUpdate }: UseMaritimeDataProp
}
}, [apiKey, searchImo]);
- // Load vessels on mount and refresh periodically
- useEffect(() => {
- loadRealVessels();
- const interval = setInterval(loadRealVessels, VESSEL_REFRESH_INTERVAL);
- return () => clearInterval(interval);
- }, [loadRealVessels]);
+ // NOTE: Auto-fetch removed - vessels are only loaded when explicitly requested
+ // Call loadRealVessels() manually from the component when the tab is opened
// Update timestamp periodically
useEffect(() => {
diff --git a/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx b/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx
index 215f42849..02aededff 100644
--- a/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx
@@ -29,11 +29,11 @@ const useMarketCategory = (
return useCache<QuoteData[]>({
key: `markets:global:${category}:${tickerHash}`,
category: 'market-quotes',
- fetcher: () => marketDataService.getEnhancedQuotes(tickers),
+ fetcher: () => marketDataService.getQuotes(tickers),
ttl: '10m',
enabled: enabled && tickers.length > 0,
refetchInterval,
- staleWhileRevalidate: false // Fetch fresh data, don't use stale
+ staleWhileRevalidate: true
});
};
@@ -55,11 +55,11 @@ const useRegionalMarket = (
return useCache<QuoteData[]>({
key: `markets:regional:${region}:${tickerHash}`,
category: 'market-quotes',
- fetcher: () => marketDataService.getEnhancedQuotes(symbols),
+ fetcher: () => marketDataService.getQuotes(symbols),
ttl: '10m',
enabled: enabled && symbols.length > 0,
refetchInterval,
- staleWhileRevalidate: false // Fetch fresh data, don't use stale
+ staleWhileRevalidate: true
});
};
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/MCPToolsManagement.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/MCPToolsManagement.tsx
new file mode 100644
index 000000000..c7b99a481
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/MCPToolsManagement.tsx
@@ -0,0 +1,498 @@
+// MCP Tools Management - Manage both internal and external MCP tools
+import React, { useState, useEffect } from 'react';
+import { Settings, ToggleLeft, ToggleRight, Search, Filter, CheckCircle, XCircle, AlertCircle } from 'lucide-react';
+import { mcpToolService } from '@/services/mcp/mcpToolService';
+import { INTERNAL_SERVER_ID } from '@/services/mcp/internal';
+
+interface MCPToolWithStatus {
+ serverId: string;
+ serverName: string;
+ name: string;
+ description?: string;
+ category?: string;
+ isEnabled: boolean;
+ isInternal: boolean;
+}
+
+interface MCPToolsManagementProps {
+ onClose?: () => void;
+}
+
+// Tool categories
+const TOOL_CATEGORIES = [
+ { id: 'navigation', label: 'Navigation', color: '#10b981' },
+ { id: 'trading', label: 'Trading', color: '#3b82f6' },
+ { id: 'crypto-trading', label: 'Crypto Trading', color: '#f59e0b' },
+ { id: 'portfolio', label: 'Portfolio', color: '#8b5cf6' },
+ { id: 'dashboard', label: 'Dashboard', color: '#f97316' },
+ { id: 'settings', label: 'Settings', color: '#6366f1' },
+ { id: 'workspace', label: 'Workspace', color: '#ec4899' },
+ { id: 'backtesting', label: 'Backtesting', color: '#14b8a6' },
+ { id: 'market-data', label: 'Market Data', color: '#06b6d4' },
+ { id: 'workflow', label: 'Workflow', color: '#84cc16' },
+ { id: 'notes', label: 'Notes & Reports', color: '#22d3ee' },
+ { id: 'external', label: 'External Tools', color: '#FFA500' },
+];
+
+const MCPToolsManagement: React.FC<MCPToolsManagementProps> = ({ onClose }) => {
+ const [tools, setTools] = useState<MCPToolWithStatus[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [searchTerm, setSearchTerm] = useState('');
+ const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
+ const [statusMessage, setStatusMessage] = useState('Loading tools...');
+
+ // Colors
+ const ORANGE = '#FFA500';
+ const WHITE = '#FFFFFF';
+ const GRAY = '#787878';
+ const DARK_BG = '#0a0a0a';
+ const PANEL_BG = '#1a1a1a';
+ const BORDER = '#2d2d2d';
+ const GREEN = '#10b981';
+ const RED = '#ef4444';
+
+ useEffect(() => {
+ loadTools();
+ }, []);
+
+ const loadTools = async () => {
+ try {
+ setLoading(true);
+ setStatusMessage('Loading tools...');
+
+ // Get all internal tools (including disabled)
+ const internalTools = await mcpToolService.getAllInternalTools();
+
+ // Get all tools (enabled only)
+ const allTools = await mcpToolService.getAllTools();
+
+ // Create a map to track which tools are enabled
+ const enabledTools = new Set(allTools.map(t => `${t.serverId}__${t.name}`));
+
+ // Categorize internal tools
+ const categorizedInternalTools: MCPToolWithStatus[] = internalTools.map(tool => {
+ const key = `${tool.serverId}__${tool.name}`;
+ const category = getToolCategory(tool.name);
+
+ return {
+ serverId: tool.serverId,
+ serverName: tool.serverName,
+ name: tool.name,
+ description: tool.description,
+ category,
+ isEnabled: enabledTools.has(key),
+ isInternal: true,
+ };
+ });
+
+ // Add external tools
+ const externalTools: MCPToolWithStatus[] = allTools
+ .filter(t => t.serverId !== INTERNAL_SERVER_ID)
+ .map(tool => ({
+ serverId: tool.serverId,
+ serverName: tool.serverName,
+ name: tool.name,
+ description: tool.description,
+ category: 'external',
+ isEnabled: true, // External tools are always enabled if server is running
+ isInternal: false,
+ }));
+
+ setTools([...categorizedInternalTools, ...externalTools]);
+ setStatusMessage(`${categorizedInternalTools.length + externalTools.length} tools loaded`);
+ setLoading(false);
+ } catch (error) {
+ console.error('Failed to load tools:', error);
+ setStatusMessage('Error loading tools');
+ setLoading(false);
+ }
+ };
+
+ const getToolCategory = (toolName: string): string => {
+ const categoryMap: Record<string, string> = {
+ // Navigation
+ navigate_tab: 'navigation',
+ navigate_screen: 'navigation',
+ get_active_tab: 'navigation',
+ open_settings_section: 'navigation',
+
+ // Trading
+ place_order: 'trading',
+ cancel_order: 'trading',
+ modify_order: 'trading',
+ get_positions: 'trading',
+ get_balance: 'trading',
+ get_orders: 'trading',
+ get_holdings: 'trading',
+ close_position: 'trading',
+
+ // Crypto Trading
+ crypto_place_market_order: 'crypto-trading',
+ crypto_place_limit_order: 'crypto-trading',
+ crypto_place_stop_loss: 'crypto-trading',
+ crypto_cancel_order: 'crypto-trading',
+ crypto_cancel_all_orders: 'crypto-trading',
+ crypto_get_positions: 'crypto-trading',
+ crypto_close_position: 'crypto-trading',
+ crypto_get_balance: 'crypto-trading',
+ crypto_get_holdings: 'crypto-trading',
+ crypto_get_orders: 'crypto-trading',
+ crypto_get_ticker: 'crypto-trading',
+ crypto_get_orderbook: 'crypto-trading',
+ crypto_add_to_watchlist: 'crypto-trading',
+ crypto_remove_from_watchlist: 'crypto-trading',
+ crypto_search_symbol: 'crypto-trading',
+ crypto_switch_trading_mode: 'crypto-trading',
+ crypto_switch_broker: 'crypto-trading',
+ crypto_get_portfolio_value: 'crypto-trading',
+ crypto_get_pnl: 'crypto-trading',
+ crypto_set_stop_loss_for_position: 'crypto-trading',
+ crypto_set_take_profit: 'crypto-trading',
+
+ // Portfolio
+ create_portfolio: 'portfolio',
+ list_portfolios: 'portfolio',
+ add_asset: 'portfolio',
+ remove_asset: 'portfolio',
+ add_transaction: 'portfolio',
+ get_portfolio_summary: 'portfolio',
+
+ // Dashboard
+ add_widget: 'dashboard',
+ remove_widget: 'dashboard',
+ list_widgets: 'dashboard',
+ configure_widget: 'dashboard',
+
+ // Settings
+ set_theme: 'settings',
+ get_theme: 'settings',
+ set_language: 'settings',
+ get_settings: 'settings',
+ set_setting: 'settings',
+
+ // Workspace
+ save_workspace: 'workspace',
+ load_workspace: 'workspace',
+ list_workspaces: 'workspace',
+ delete_workspace: 'workspace',
+
+ // Backtesting
+ run_backtest: 'backtesting',
+ optimize_strategy: 'backtesting',
+ get_historical_data: 'backtesting',
+
+ // Market Data
+ get_quote: 'market-data',
+ add_to_watchlist: 'market-data',
+ remove_from_watchlist: 'market-data',
+ search_symbol: 'market-data',
+
+ // Workflow
+ create_workflow: 'workflow',
+ run_workflow: 'workflow',
+ stop_workflow: 'workflow',
+ list_workflows: 'workflow',
+
+ // Notes
+ create_note: 'notes',
+ list_notes: 'notes',
+ delete_note: 'notes',
+ generate_report: 'notes',
+ };
+
+ return categoryMap[toolName] || 'other';
+ };
+
+ const handleToggleTool = async (tool: MCPToolWithStatus) => {
+ if (!tool.isInternal) {
+ // External tools can't be disabled individually - must stop the server
+ alert('External tools are managed through their MCP servers. Stop the server to disable all its tools.');
+ return;
+ }
+
+ try {
+ const newState = !tool.isEnabled;
+ setStatusMessage(`${newState ? 'Enabling' : 'Disabling'} ${tool.name}...`);
+
+ await mcpToolService.setInternalToolEnabled(tool.name, tool.category || 'other', newState);
+
+ // Update local state
+ setTools(prev => prev.map(t =>
+ t.name === tool.name && t.serverId === tool.serverId
+ ? { ...t, isEnabled: newState }
+ : t
+ ));
+
+ setStatusMessage(`${tool.name} ${newState ? 'enabled' : 'disabled'}`);
+ } catch (error) {
+ console.error('Failed to toggle tool:', error);
+ setStatusMessage(`Error toggling ${tool.name}`);
+ }
+ };
+
+ // Filter tools
+ const filteredTools = tools.filter(tool => {
+ const matchesSearch = !searchTerm ||
+ tool.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
+ tool.description?.toLowerCase().includes(searchTerm.toLowerCase());
+
+ const matchesCategory = !selectedCategory || tool.category === selectedCategory;
+
+ return matchesSearch && matchesCategory;
+ });
+
+ // Group by category
+ const toolsByCategory = filteredTools.reduce((acc, tool) => {
+ const category = tool.category || 'other';
+ if (!acc[category]) acc[category] = [];
+ acc[category].push(tool);
+ return acc;
+ }, {} as Record<string, MCPToolWithStatus[]>);
+
+ const getCategoryColor = (categoryId: string) => {
+ const category = TOOL_CATEGORIES.find(c => c.id === categoryId);
+ return category?.color || GRAY;
+ };
+
+ const getCategoryLabel = (categoryId: string) => {
+ const category = TOOL_CATEGORIES.find(c => c.id === categoryId);
+ return category?.label || 'Other';
+ };
+
+ return (
+ <div style={{
+ width: '100%',
+ height: '100%',
+ backgroundColor: DARK_BG,
+ color: WHITE,
+ fontFamily: 'Consolas, monospace',
+ display: 'flex',
+ flexDirection: 'column',
+ fontSize: '11px',
+ }}>
+ {/* Header */}
+ <div style={{
+ backgroundColor: PANEL_BG,
+ borderBottom: `1px solid ${BORDER}`,
+ padding: '12px 16px',
+ flexShrink: 0,
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <Settings size={16} color={ORANGE} />
+ <span style={{ color: ORANGE, fontSize: '14px', fontWeight: 'bold' }}>
+ MCP TOOLS MANAGEMENT
+ </span>
+ <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
+ <span style={{ color: GRAY, fontSize: '11px' }}>
+ {tools.filter(t => t.isEnabled).length} enabled | {tools.length} total
+ </span>
+ </div>
+
+ {onClose && (
+ <button
+ onClick={onClose}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '6px 12px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold',
+ }}
+ >
+ CLOSE
+ </button>
+ )}
+ </div>
+
+ {/* Search and Filter Row */}
+ <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
+ <div style={{ flex: 1, position: 'relative' }}>
+ <Search
+ size={14}
+ style={{
+ position: 'absolute',
+ left: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ color: GRAY,
+ }}
+ />
+ <input
+ type="text"
+ placeholder="Search tools..."
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ style={{
+ width: '100%',
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '8px 12px 8px 36px',
+ fontSize: '11px',
+ borderRadius: '4px',
+ outline: 'none',
+ }}
+ />
+ </div>
+
+ <select
+ value={selectedCategory || ''}
+ onChange={(e) => setSelectedCategory(e.target.value || null)}
+ style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '8px 12px',
+ fontSize: '11px',
+ borderRadius: '4px',
+ outline: 'none',
+ cursor: 'pointer',
+ }}
+ >
+ <option value="">All Categories</option>
+ {TOOL_CATEGORIES.map(cat => (
+ <option key={cat.id} value={cat.id}>{cat.label}</option>
+ ))}
+ </select>
+ </div>
+ </div>
+
+ {/* Tools List */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
+ {loading ? (
+ <div style={{ textAlign: 'center', padding: '40px', color: GRAY }}>
+ Loading tools...
+ </div>
+ ) : Object.keys(toolsByCategory).length === 0 ? (
+ <div style={{ textAlign: 'center', padding: '40px', color: GRAY }}>
+ No tools found
+ </div>
+ ) : (
+ Object.entries(toolsByCategory).map(([category, categoryTools]) => (
+ <div key={category} style={{ marginBottom: '24px' }}>
+ {/* Category Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${BORDER}`,
+ }}>
+ <div
+ style={{
+ width: '4px',
+ height: '16px',
+ backgroundColor: getCategoryColor(category),
+ borderRadius: '2px',
+ }}
+ />
+ <span style={{
+ color: getCategoryColor(category),
+ fontSize: '12px',
+ fontWeight: 'bold',
+ textTransform: 'uppercase',
+ }}>
+ {getCategoryLabel(category)} ({categoryTools.length})
+ </span>
+ </div>
+
+ {/* Tools in Category */}
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(350px, 1fr))', gap: '12px' }}>
+ {categoryTools.map(tool => (
+ <div
+ key={`${tool.serverId}__${tool.name}`}
+ style={{
+ backgroundColor: PANEL_BG,
+ border: `1px solid ${tool.isEnabled ? getCategoryColor(category) + '60' : BORDER}`,
+ borderRadius: '6px',
+ padding: '12px',
+ transition: 'all 0.2s',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: '8px' }}>
+ <div style={{ flex: 1 }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
+ <span style={{ color: WHITE, fontSize: '12px', fontWeight: 'bold' }}>
+ {tool.name}
+ </span>
+ {tool.isInternal ? (
+ tool.isEnabled ? (
+ <CheckCircle size={12} color={GREEN} />
+ ) : (
+ <XCircle size={12} color={RED} />
+ )
+ ) : (
+ <AlertCircle size={12} color={ORANGE} />
+ )}
+ </div>
+ <div style={{ color: GRAY, fontSize: '9px', marginBottom: '4px' }}>
+ {tool.serverName}
+ </div>
+ {tool.description && (
+ <div style={{ color: GRAY, fontSize: '10px', lineHeight: '1.4' }}>
+ {tool.description.length > 100
+ ? tool.description.substring(0, 100) + '...'
+ : tool.description}
+ </div>
+ )}
+ </div>
+
+ {tool.isInternal && (
+ <button
+ onClick={() => handleToggleTool(tool)}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: tool.isEnabled ? GREEN : GRAY,
+ cursor: 'pointer',
+ padding: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ flexShrink: 0,
+ }}
+ title={tool.isEnabled ? 'Click to disable' : 'Click to enable'}
+ >
+ {tool.isEnabled ? <ToggleRight size={24} /> : <ToggleLeft size={24} />}
+ </button>
+ )}
+ </div>
+
+ {!tool.isInternal && (
+ <div style={{
+ fontSize: '8px',
+ color: GRAY,
+ fontStyle: 'italic',
+ marginTop: '4px',
+ }}>
+ Managed by external server
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+
+ {/* Footer */}
+ <div style={{
+ backgroundColor: PANEL_BG,
+ borderTop: `1px solid ${BORDER}`,
+ padding: '8px 16px',
+ fontSize: '9px',
+ color: GRAY,
+ flexShrink: 0,
+ }}>
+ <span style={{ color: ORANGE }}>●</span> {statusMessage}
+ </div>
+ </div>
+ );
+};
+
+export default MCPToolsManagement;
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx
index 7433072ab..37f7a4ea3 100644
--- a/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx
@@ -5,15 +5,18 @@ import React, { useState, useEffect } from 'react';
import { Plus, RefreshCw, Search, Play, Square, Trash2, Settings, Zap, CheckCircle, XCircle, AlertCircle, MessageSquare } from 'lucide-react';
import { mcpManager, MCPServerWithStats } from '../../../services/mcp/mcpManager';
import { sqliteService } from '../../../services/core/sqliteService';
+import { useBrokerContext } from '../../../contexts/BrokerContext';
+import { brokerMCPBridge } from '../../../services/mcp/internal/BrokerMCPBridge';
import MCPMarketplace from './marketplace/MCPMarketplace';
import MCPAddServerModal from './MCPAddServerModal';
+import MCPToolsManagement from './MCPToolsManagement';
interface MCPTabProps {
onNavigateToTab?: (tabName: string) => void;
}
const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
- const [view, setView] = useState<'marketplace' | 'installed'>('marketplace');
+ const [view, setView] = useState<'marketplace' | 'installed' | 'tools'>('marketplace');
const [servers, setServers] = useState<MCPServerWithStats[]>([]);
const [tools, setTools] = useState<any[]>([]);
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
@@ -21,6 +24,9 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
const [statusMessage, setStatusMessage] = useState('Initializing...');
const [searchTerm, setSearchTerm] = useState('');
+ // Broker context for MCP bridge
+ const { activeAdapter, tradingMode, activeBroker } = useBrokerContext();
+
// Fincept colors
const ORANGE = '#FFA500';
const WHITE = '#FFFFFF';
@@ -32,12 +38,32 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
const RED = '#ef4444';
const YELLOW = '#f59e0b';
+ // Connect broker to MCP bridge
+ useEffect(() => {
+ if (activeAdapter) {
+ brokerMCPBridge.connect({
+ activeAdapter,
+ tradingMode,
+ activeBroker,
+ });
+ console.log(`[MCP] Connected to ${activeBroker} in ${tradingMode} mode`);
+ }
+
+ return () => {
+ brokerMCPBridge.disconnect();
+ };
+ }, [activeAdapter, tradingMode, activeBroker]);
+
useEffect(() => {
const initializeServers = async () => {
try {
// Ensure database is initialized first
await sqliteService.initialize();
+ // Initialize MCP tool service to load internal tools
+ const { mcpToolService } = await import('../../../services/mcp/mcpToolService');
+ await mcpToolService.initialize();
+
// Don't auto-start here - DashboardScreen already handles it
// Just load the data
await loadData();
@@ -63,11 +89,15 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
const serversData = await mcpManager.getServersWithStats();
setServers(serversData);
- const toolsData = await sqliteService.getMCPTools();
+ // Load all tools (internal + external)
+ const { mcpToolService } = await import('../../../services/mcp/mcpToolService');
+ const toolsData = await mcpToolService.getAllTools();
setTools(toolsData);
const runningCount = serversData.filter(s => s.status === 'running').length;
- setStatusMessage(`${runningCount} running | ${toolsData.length} tools available`);
+ const internalToolsCount = toolsData.filter(t => t.serverId === 'fincept-terminal').length;
+ const externalToolsCount = toolsData.length - internalToolsCount;
+ setStatusMessage(`${runningCount} servers running | ${internalToolsCount} internal + ${externalToolsCount} external tools`);
} catch (error) {
console.error('Failed to load MCP data:', error);
setStatusMessage('Error loading data');
@@ -201,7 +231,7 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
</span>
<div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
<span style={{ color: GRAY, fontSize: '11px' }}>
- {servers.length} Installed | {runningServers} Running | {tools.length} Tools
+ {servers.length} Servers | {runningServers} Running | {tools.filter(t => t.serverId === 'fincept-terminal').length} Internal + {tools.filter(t => t.serverId !== 'fincept-terminal').length} External Tools
</span>
</div>
@@ -281,6 +311,22 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
MY SERVERS ({servers.length})
</button>
+ <button
+ onClick={() => setView('tools')}
+ style={{
+ backgroundColor: view === 'tools' ? ORANGE : 'transparent',
+ color: view === 'tools' ? 'black' : WHITE,
+ border: `1px solid ${view === 'tools' ? ORANGE : BORDER}`,
+ padding: '6px 12px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold'
+ }}
+ >
+ ALL TOOLS ({tools.length})
+ </button>
+
<button
onClick={() => setIsAddModalOpen(true)}
style={{
@@ -357,6 +403,9 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
{view === 'marketplace' ? (
/* Marketplace View */
<MCPMarketplace onInstall={handleInstallServer} installedServers={servers} />
+ ) : view === 'tools' ? (
+ /* Tools Management View */
+ <MCPToolsManagement />
) : (
/* Installed Servers View */
<div>
@@ -397,6 +446,104 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))',
gap: '16px',
}}>
+ {/* Internal Tools Card - Always show first */}
+ <div
+ style={{
+ backgroundColor: PANEL_BG,
+ border: `2px solid ${ORANGE}`,
+ borderRadius: '6px',
+ padding: '16px',
+ transition: 'all 0.2s',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.boxShadow = `0 0 16px ${ORANGE}60`;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.boxShadow = 'none';
+ }}
+ >
+ {/* Server Header */}
+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px', marginBottom: '12px' }}>
+ <span style={{ fontSize: '28px' }}>⚡</span>
+ <div style={{ flex: 1 }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
+ <h3 style={{
+ color: WHITE,
+ fontSize: '13px',
+ fontWeight: 'bold',
+ }}>
+ Fincept Terminal (Internal)
+ </h3>
+ <CheckCircle size={14} color={GREEN} />
+ </div>
+ <div style={{
+ display: 'inline-block',
+ backgroundColor: `${GREEN}20`,
+ color: GREEN,
+ padding: '2px 8px',
+ fontSize: '9px',
+ borderRadius: '3px',
+ textTransform: 'uppercase',
+ fontWeight: 'bold',
+ }}>
+ BUILT-IN
+ </div>
+ </div>
+ </div>
+
+ {/* Description */}
+ <p style={{
+ color: GRAY,
+ fontSize: '10px',
+ lineHeight: '1.5',
+ marginBottom: '12px',
+ }}>
+ Built-in tools for terminal control, trading, portfolio management, backtesting, and more. Always available.
+ </p>
+
+ {/* Stats */}
+ <div style={{
+ display: 'flex',
+ gap: '16px',
+ marginBottom: '12px',
+ fontSize: '10px',
+ color: GRAY,
+ }}>
+ <div>
+ <span style={{ color: WHITE, fontWeight: 'bold' }}>
+ {tools.filter(t => t.serverId === 'fincept-terminal').length}
+ </span> tools
+ </div>
+ <div>
+ <span style={{ color: GREEN }}>●</span> Always Active
+ </div>
+ </div>
+
+ {/* Actions */}
+ <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
+ <button
+ onClick={() => setView('tools')}
+ style={{
+ backgroundColor: ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '6px 10px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ fontWeight: 'bold',
+ }}
+ >
+ <Settings size={10} />
+ MANAGE TOOLS
+ </button>
+ </div>
+ </div>
+
+ {/* External Server Cards */}
{filteredServers.map(server => {
const healthInfo = mcpManager.getServerHealthInfo(server.id);
return (
@@ -602,34 +749,49 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
msOverflowStyle: 'none',
}}>
<div style={{
- color: ORANGE,
- fontSize: '11px',
- fontWeight: 'bold',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '16px',
marginBottom: '8px',
- letterSpacing: '0.5px'
}}>
- AVAILABLE TOOLS ({tools.length})
+ <div style={{
+ color: ORANGE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ letterSpacing: '0.5px'
+ }}>
+ AVAILABLE TOOLS ({tools.length})
+ </div>
+ <div style={{ fontSize: '9px', color: GRAY }}>
+ <span style={{ color: GREEN }}>⚡ {tools.filter(t => t.serverId === 'fincept-terminal').length} Internal</span>
+ {' | '}
+ <span style={{ color: ORANGE }}>{tools.filter(t => t.serverId !== 'fincept-terminal').length} External</span>
+ </div>
</div>
{tools.length === 0 ? (
<div style={{ color: GRAY, fontSize: '10px', textAlign: 'center', padding: '20px' }}>
- No tools available. Start an MCP server to see its tools.
+ No tools available. The internal tools will appear when the application initializes.
</div>
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '8px' }}>
- {tools.map(tool => (
+ {tools.map((tool, index) => (
<div
- key={tool.id}
+ key={`${tool.serverId}__${tool.name}__${index}`}
style={{
backgroundColor: DARK_BG,
- border: `1px solid ${BORDER}`,
+ border: `1px solid ${tool.serverId === 'fincept-terminal' ? GREEN + '40' : BORDER}`,
padding: '6px 8px',
fontSize: '9px',
borderRadius: '3px',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '2px' }}>
- <Settings size={10} style={{ color: ORANGE }} />
+ {tool.serverId === 'fincept-terminal' ? (
+ <span style={{ color: GREEN }}>⚡</span>
+ ) : (
+ <Settings size={10} style={{ color: ORANGE }} />
+ )}
<span style={{ color: WHITE, fontWeight: 'bold' }}>{tool.name}</span>
</div>
{tool.description && (
@@ -637,6 +799,9 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
{tool.description.substring(0, 50)}{tool.description.length > 50 ? '...' : ''}
</div>
)}
+ <div style={{ color: GRAY, fontSize: '7px', marginLeft: '16px', marginTop: '2px' }}>
+ {tool.serverName}
+ </div>
</div>
))}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
index 7ca5ba75e..9a6f4bf43 100644
--- a/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
@@ -1,7 +1,6 @@
import React, { useState, useEffect, useCallback, useRef } from 'react';
-import { Info, Settings } from 'lucide-react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { fetchAllNews, type NewsArticle, getRSSFeedCount, getActiveSources, isUsingMockData, setNewsCacheTTL, invalidateNewsCache } from '@/services/news/newsService';
+import { Info, Settings, RefreshCw, Clock, Zap, Newspaper, ExternalLink, Copy, BookOpen } from 'lucide-react';
+import { fetchAllNews, type NewsArticle, getRSSFeedCount, getActiveSources, isUsingMockData, setNewsCacheTTL } from '@/services/news/newsService';
import { contextRecorderService } from '@/services/data-sources/contextRecorderService';
import RecordingControlPanel from '@/components/common/RecordingControlPanel';
import { TimezoneSelector } from '@/components/common/TimezoneSelector';
@@ -10,16 +9,112 @@ import { analyzeNewsArticle, type NewsAnalysisData, getSentimentColor, getUrgenc
import { createNewsTabTour } from '@/components/tabs/tours/newsTabTour';
import RSSFeedSettingsModal from './RSSFeedSettingsModal';
-// Extend Window interface for Tauri
declare global {
- interface Window {
- __TAURI__?: any;
- }
+ interface Window { __TAURI__?: any; }
}
+// ── FINCEPT Design System ──
+const F = {
+ ORANGE: '#FF8800', WHITE: '#FFFFFF', RED: '#FF3B3B', GREEN: '#00D66F',
+ GRAY: '#787878', DARK_BG: '#000000', PANEL_BG: '#0F0F0F', HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A', HOVER: '#1F1F1F', MUTED: '#4A4A4A', CYAN: '#00E5FF',
+ YELLOW: '#FFD700', BLUE: '#0088FF', PURPLE: '#9D4EDD',
+};
+const FONT = '"IBM Plex Mono","Consolas",monospace';
+
+// ── Helpers ──
+const priColor = (p: string) => ({ FLASH: F.RED, URGENT: F.ORANGE, BREAKING: F.YELLOW, ROUTINE: F.GRAY }[p] || F.MUTED);
+const sentColor = (s: string) => ({ BULLISH: F.GREEN, BEARISH: F.RED, NEUTRAL: F.YELLOW }[s] || F.MUTED);
+const impColor = (i: string) => ({ HIGH: F.RED, MEDIUM: F.YELLOW, LOW: F.GREEN }[i] || F.MUTED);
+
+// ── Section Header ──
+const SectionHead: React.FC<{ title: string; right?: React.ReactNode }> = ({ title, right }) => (
+ <div style={{
+ padding: '4px 8px', backgroundColor: F.HEADER_BG, borderBottom: `1px solid ${F.BORDER}`,
+ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0,
+ }}>
+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>{title}</span>
+ {right && <span style={{ fontSize: '8px', color: F.CYAN }}>{right}</span>}
+ </div>
+);
+
+// ── Compact Row ──
+const NewsRow: React.FC<{
+ article: NewsArticle; selected: boolean; onClick: () => void;
+}> = ({ article, selected, onClick }) => (
+ <div
+ onClick={onClick}
+ style={{
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '3px 6px', cursor: 'pointer',
+ backgroundColor: selected ? `${F.ORANGE}15` : 'transparent',
+ borderLeft: selected ? `2px solid ${F.ORANGE}` : `2px solid transparent`,
+ borderBottom: `1px solid ${F.BORDER}08`,
+ transition: 'background 0.15s',
+ minHeight: '20px',
+ }}
+ onMouseEnter={e => { if (!selected) e.currentTarget.style.backgroundColor = F.HOVER; }}
+ onMouseLeave={e => { if (!selected) e.currentTarget.style.backgroundColor = 'transparent'; }}
+ >
+ <span style={{ color: F.MUTED, fontSize: '8px', minWidth: '38px', flexShrink: 0 }}>{article.time}</span>
+ <span style={{
+ color: priColor(article.priority), fontSize: '7px', fontWeight: 700,
+ minWidth: '40px', flexShrink: 0, letterSpacing: '0.3px',
+ }}>{article.priority}</span>
+ <span style={{
+ color: F.CYAN, fontSize: '7px', fontWeight: 700,
+ minWidth: '55px', flexShrink: 0, letterSpacing: '0.3px',
+ }}>{article.source}</span>
+ <span style={{
+ color: F.WHITE, fontSize: '9px', fontWeight: selected ? 700 : 400,
+ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
+ }}>{article.headline}</span>
+ <span style={{
+ color: sentColor(article.sentiment), fontSize: '7px', fontWeight: 700,
+ minWidth: '28px', flexShrink: 0, textAlign: 'right',
+ }}>{article.sentiment?.charAt(0) || '-'}</span>
+ <span style={{
+ color: impColor(article.impact), fontSize: '7px', fontWeight: 700,
+ minWidth: '10px', flexShrink: 0, textAlign: 'center',
+ }}>{article.impact?.charAt(0) || '-'}</span>
+ </div>
+);
+
+// ── Alert Row (for left sidebar) ──
+const AlertRow: React.FC<{ article: NewsArticle; onClick: () => void }> = ({ article, onClick }) => (
+ <div onClick={onClick} style={{
+ padding: '4px 6px', cursor: 'pointer',
+ borderLeft: `2px solid ${priColor(article.priority)}`,
+ marginBottom: '2px', transition: 'background 0.15s',
+ }}
+ onMouseEnter={e => e.currentTarget.style.backgroundColor = F.HOVER}
+ onMouseLeave={e => e.currentTarget.style.backgroundColor = 'transparent'}
+ >
+ <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '1px' }}>
+ <span style={{ color: priColor(article.priority), fontSize: '7px', fontWeight: 700 }}>{article.priority}</span>
+ <span style={{ color: F.MUTED, fontSize: '7px' }}>{article.time}</span>
+ </div>
+ <div style={{
+ color: F.WHITE, fontSize: '8px', fontWeight: 700, lineHeight: '1.2',
+ overflow: 'hidden', textOverflow: 'ellipsis',
+ display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' as any,
+ }}>{article.headline}</div>
+ </div>
+);
+
+// ── Stat Row ──
+const StatRow: React.FC<{ label: string; value: number | string; color: string }> = ({ label, value, color }) => (
+ <div style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0', fontSize: '8px' }}>
+ <span style={{ color: F.GRAY }}>{label}</span>
+ <span style={{ color, fontWeight: 700 }}>{value}</span>
+ </div>
+);
+
+// ══════════════════════════════════════════════════════════════
+// MAIN COMPONENT
+// ══════════════════════════════════════════════════════════════
const NewsTab: React.FC = () => {
const { t } = useTranslation('news');
- const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
const [activeFilter, setActiveFilter] = useState('ALL');
const [newsUpdateCount, setNewsUpdateCount] = useState(0);
@@ -30,7 +125,7 @@ const NewsTab: React.FC = () => {
const [feedCount, setFeedCount] = useState(9);
const [selectedArticle, setSelectedArticle] = useState<NewsArticle | null>(null);
const [showWebView, setShowWebView] = useState(false);
- const [refreshInterval, setRefreshInterval] = useState(10); // minutes
+ const [refreshInterval, setRefreshInterval] = useState(10);
const [showIntervalSettings, setShowIntervalSettings] = useState(false);
const [isRecording, setIsRecording] = useState(false);
const [analysisData, setAnalysisData] = useState<NewsAnalysisData | null>(null);
@@ -38,1588 +133,543 @@ const NewsTab: React.FC = () => {
const [showAnalysis, setShowAnalysis] = useState(false);
const [showFeedSettings, setShowFeedSettings] = useState(false);
- // Function to record current news data
+ // ── Data loading ──
const recordCurrentData = async () => {
if (newsArticles.length > 0) {
try {
const sources = await getActiveSources();
- const recordData = {
- articles: newsArticles,
- totalCount: newsArticles.length,
+ await contextRecorderService.recordApiResponse('News', 'news-feed', {
+ articles: newsArticles, totalCount: newsArticles.length,
alertCount: newsArticles.filter(a => a.priority === 'FLASH' || a.priority === 'URGENT').length,
- sources: sources,
- timestamp: new Date().toISOString(),
- filter: activeFilter
- };
- await contextRecorderService.recordApiResponse(
- 'News',
- 'news-feed',
- recordData,
- `News Feed (Snapshot) - ${new Date().toLocaleString()}`,
- ['news', 'rss', 'snapshot', activeFilter.toLowerCase()]
- );
- } catch (error) {
- // Silently handle recording errors
- }
+ sources, timestamp: new Date().toISOString(), filter: activeFilter,
+ }, `News Feed (Snapshot) - ${new Date().toLocaleString()}`, ['news', 'rss', 'snapshot', activeFilter.toLowerCase()]);
+ } catch { /* silent */ }
}
};
- // Manual refresh function - always fetches fresh data (bypasses cache)
- const handleRefresh = useCallback(async (forceRefresh: boolean = true) => {
+ const handleRefresh = useCallback(async (forceRefresh = true) => {
setLoading(true);
try {
- // Force refresh bypasses cache to get fresh data
const [articles, sources, count] = await Promise.all([
- fetchAllNews(forceRefresh),
- getActiveSources(),
- getRSSFeedCount()
+ fetchAllNews(forceRefresh), getActiveSources(), getRSSFeedCount(),
]);
setNewsArticles(articles);
setAlertCount(articles.filter(a => a.priority === 'FLASH' || a.priority === 'URGENT').length);
setActiveSources(sources);
setFeedCount(count);
setNewsUpdateCount(prev => prev + 1);
-
- // Record data if recording is active
if (isRecording && articles.length > 0) {
try {
- const recordData = {
- articles: articles,
- totalCount: articles.length,
+ await contextRecorderService.recordApiResponse('News', 'news-feed', {
+ articles, totalCount: articles.length,
alertCount: articles.filter(a => a.priority === 'FLASH' || a.priority === 'URGENT').length,
- sources: sources,
- timestamp: new Date().toISOString(),
- filter: activeFilter
- };
- await contextRecorderService.recordApiResponse(
- 'News',
- 'news-feed',
- recordData,
- `News Feed - ${new Date().toLocaleString()}`,
- ['news', 'rss', 'live-feed', activeFilter.toLowerCase()]
- );
- } catch (error) {
- // Silently handle recording errors
- }
+ sources, timestamp: new Date().toISOString(), filter: activeFilter,
+ }, `News Feed - ${new Date().toLocaleString()}`, ['news', 'rss', 'live-feed', activeFilter.toLowerCase()]);
+ } catch { /* silent */ }
}
- } catch (error) {
- // Silently handle fetch errors
- } finally {
- setLoading(false);
- }
+ } catch { /* silent */ } finally { setLoading(false); }
}, [isRecording, activeFilter]);
- // Handle AI analysis of article
const handleAnalyzeArticle = async () => {
if (!selectedArticle?.link) return;
-
- setAnalyzingArticle(true);
- setShowAnalysis(false);
- setAnalysisData(null);
-
+ setAnalyzingArticle(true); setShowAnalysis(false); setAnalysisData(null);
try {
const result = await analyzeNewsArticle(selectedArticle.link);
-
- if (result.success && 'data' in result) {
- setAnalysisData(result.data);
- setShowAnalysis(true);
- } else if ('error' in result) {
- console.error('Analysis failed:', result.error);
- }
- } catch (error) {
- console.error('Analysis error:', error);
- } finally {
- setAnalyzingArticle(false);
- }
+ if (result.success && 'data' in result) { setAnalysisData(result.data); setShowAnalysis(true); }
+ } catch { /* silent */ } finally { setAnalyzingArticle(false); }
};
- // Track if this is the initial mount to use cached data
const isInitialMount = useRef(true);
+ useEffect(() => { setNewsCacheTTL(refreshInterval); }, [refreshInterval]);
- // Update cache TTL when refresh interval changes
useEffect(() => {
- setNewsCacheTTL(refreshInterval);
- }, [refreshInterval]);
-
- // Fetch real news on mount and based on refresh interval
- useEffect(() => {
- const loadNews = async (forceRefresh: boolean = false) => {
+ const loadNews = async (force = false) => {
setLoading(true);
try {
- // On initial mount, try to use cached data; on interval refreshes, force fresh data
- const [articles, sources, count] = await Promise.all([
- fetchAllNews(forceRefresh),
- getActiveSources(),
- getRSSFeedCount()
- ]);
+ const [articles, sources, count] = await Promise.all([fetchAllNews(force), getActiveSources(), getRSSFeedCount()]);
setNewsArticles(articles);
setAlertCount(articles.filter(a => a.priority === 'FLASH' || a.priority === 'URGENT').length);
- setActiveSources(sources);
- setFeedCount(count);
+ setActiveSources(sources); setFeedCount(count);
setNewsUpdateCount(prev => prev + 1);
-
- // Record data if recording is active
- if (isRecording && articles.length > 0) {
- try {
- const recordData = {
- articles: articles,
- totalCount: articles.length,
- alertCount: articles.filter(a => a.priority === 'FLASH' || a.priority === 'URGENT').length,
- sources: sources,
- timestamp: new Date().toISOString(),
- filter: activeFilter
- };
- await contextRecorderService.recordApiResponse(
- 'News',
- 'news-feed',
- recordData,
- `News Feed - ${new Date().toLocaleString()}`,
- ['news', 'rss', 'live-feed', activeFilter.toLowerCase()]
- );
- } catch (error) {
- // Silently handle recording errors
- }
- }
- } catch (error) {
- // Silently handle fetch errors
- } finally {
- setLoading(false);
- }
+ } catch { /* silent */ } finally { setLoading(false); }
};
-
- // On initial mount, use cached data if available
- // Otherwise, interval refreshes force fresh data
- if (isInitialMount.current) {
- isInitialMount.current = false;
- loadNews(false); // Use cache on initial mount
- } else {
- loadNews(true); // Force refresh when interval changes
- }
-
- // Refresh news based on user interval - ALWAYS force fresh data on interval
- const newsRefreshInterval = setInterval(() => {
- console.log(`[NewsTab] Auto-refresh triggered (${refreshInterval}min interval) - fetching fresh data`);
- loadNews(true); // Always force refresh on interval
- }, refreshInterval * 60 * 1000);
-
- return () => clearInterval(newsRefreshInterval);
+ if (isInitialMount.current) { isInitialMount.current = false; loadNews(false); } else { loadNews(true); }
+ const iv = setInterval(() => loadNews(true), refreshInterval * 60 * 1000);
+ return () => clearInterval(iv);
}, [refreshInterval, isRecording, activeFilter]);
useEffect(() => {
- const timer = setInterval(() => {
- setCurrentTime(new Date());
- }, 1000);
- return () => clearInterval(timer);
+ const t = setInterval(() => setCurrentTime(new Date()), 1000);
+ return () => clearInterval(t);
}, []);
- // Generate continuous ticker text with all news items
- const generateContinuousTickerText = () => {
- if (newsArticles.length === 0) {
- return t('messages.loadingFeeds');
- }
-
- // Create a long string of all news items
- return newsArticles.map(article =>
- `🔴 ${article.priority} | ${article.source} | ${article.headline.toUpperCase()} `
- ).join('');
- };
-
- const newsTickerText = generateContinuousTickerText();
-
- // Calculate animation duration based on content length (more content = slower speed)
- // Base: 1600 seconds for 1000 characters, scale proportionally
- const tickerDuration = Math.max(1200, Math.min(4800, (newsTickerText.length / 1000) * 1600));
-
- const getPriorityColor = (priority: string) => {
- switch (priority) {
- case 'FLASH': return colors.alert;
- case 'URGENT': return colors.primary;
- case 'BREAKING': return colors.warning;
- case 'ROUTINE': return colors.secondary;
- default: return colors.textMuted;
- }
- };
-
- const getArticleSentimentColor = (sentiment: string) => {
- switch (sentiment) {
- case 'BULLISH': return colors.secondary;
- case 'BEARISH': return colors.alert;
- case 'NEUTRAL': return colors.warning;
- default: return colors.textMuted;
- }
- };
-
- const getImpactColor = (impact: string) => {
- switch (impact) {
- case 'HIGH': return colors.alert;
- case 'MEDIUM': return colors.warning;
- case 'LOW': return colors.secondary;
- default: return colors.textMuted;
- }
- };
-
+ // ── Derived data ──
const filteredNews = activeFilter === 'ALL'
? newsArticles
- : newsArticles.filter(article => article.category === activeFilter);
-
- // Calculate stats from real data
- const bullishCount = newsArticles.filter(a => a.sentiment === 'BULLISH').length;
- const bearishCount = newsArticles.filter(a => a.sentiment === 'BEARISH').length;
- const neutralCount = newsArticles.filter(a => a.sentiment === 'NEUTRAL').length;
- const totalCount = newsArticles.length || 1;
- const sentimentScore = ((bullishCount - bearishCount) / totalCount).toFixed(2);
-
- // Category counts
- const breakingCount = newsArticles.filter(a => a.priority === 'BREAKING' || a.priority === 'FLASH').length;
- const earningsCount = newsArticles.filter(a => a.category === 'EARNINGS').length;
- const economicCount = newsArticles.filter(a => a.category === 'ECONOMIC').length;
+ : newsArticles.filter(a => a.category === activeFilter);
+
+ const urgentNews = newsArticles.filter(a => a.priority === 'FLASH' || a.priority === 'URGENT' || a.priority === 'BREAKING');
+
+ const bullish = newsArticles.filter(a => a.sentiment === 'BULLISH').length;
+ const bearish = newsArticles.filter(a => a.sentiment === 'BEARISH').length;
+ const neutral = newsArticles.filter(a => a.sentiment === 'NEUTRAL').length;
+ const total = newsArticles.length || 1;
+ const score = ((bullish - bearish) / total).toFixed(2);
+
+ const catCounts: Record<string, number> = {};
+ newsArticles.forEach(a => { catCounts[a.category] = (catCounts[a.category] || 0) + 1; });
+
+ // Ticker
+ const tickerText = newsArticles.length === 0 ? t('messages.loadingFeeds')
+ : newsArticles.map(a => `${a.priority} | ${a.source} | ${a.headline.toUpperCase()} `).join('');
+ const tickerDur = Math.max(1200, Math.min(4800, (tickerText.length / 1000) * 1600));
+
+ // Filter defs
+ const filters = [
+ { key: 'F1', label: 'ALL', f: 'ALL' }, { key: 'F2', label: 'MKT', f: 'MARKETS' },
+ { key: 'F3', label: 'ERN', f: 'EARNINGS' }, { key: 'F4', label: 'ECO', f: 'ECONOMIC' },
+ { key: 'F5', label: 'TCH', f: 'TECH' }, { key: 'F6', label: 'NRG', f: 'ENERGY' },
+ { key: 'F7', label: 'BNK', f: 'BANKING' }, { key: 'F8', label: 'CRY', f: 'CRYPTO' },
+ { key: 'F9', label: 'GEO', f: 'GEOPOLITICS' },
+ ];
+
+ // ── Open article externally ──
+ const openExternal = async (url: string) => {
+ try {
+ if (window.__TAURI__) {
+ const { openUrl } = await import('@tauri-apps/plugin-opener');
+ await openUrl(url);
+ } else {
+ window.open(url, '_blank', 'noopener');
+ }
+ } catch { await navigator.clipboard.writeText(url); }
+ };
+ // ══════════════════════════════════════════════════════════════
+ // RENDER
+ // ══════════════════════════════════════════════════════════════
return (
<div style={{
- height: '100%',
- backgroundColor: colors.background,
- color: colors.text,
- fontFamily: fontFamily,
- fontWeight: fontWeight,
- fontStyle: fontStyle,
- overflow: 'hidden',
- display: 'flex',
- flexDirection: 'column',
- fontSize: fontSize.body
+ height: '100%', backgroundColor: F.DARK_BG, color: F.WHITE, fontFamily: FONT,
+ overflow: 'hidden', display: 'flex', flexDirection: 'column', fontSize: '9px',
}}>
- {/* Complex Header with News Ticker */}
+
+ {/* ── TOP NAV ── */}
<div style={{
- backgroundColor: colors.panel,
- borderBottom: `1px solid ${colors.textMuted}`,
- padding: '4px 8px',
- flexShrink: 0
+ backgroundColor: F.HEADER_BG, borderBottom: `2px solid ${F.ORANGE}`,
+ padding: '4px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
+ boxShadow: `0 2px 8px ${F.ORANGE}20`, flexShrink: 0, position: 'relative',
}}>
- {/* Main Status Line */}
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px' }}>
- <span style={{ color: colors.primary, fontWeight: 'bold' }}>{t('title')}</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.alert, fontWeight: 'bold', animation: 'blink 1s infinite' }}>{t('header.liveFeed')}</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.warning }}>{t('header.alerts')}: {alertCount}</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.secondary }}>● {feedCount} {t('header.sources')}</span>
- <span style={{ color: colors.text }}>|</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Newspaper size={12} style={{ color: F.ORANGE }} />
+ <span style={{ color: F.ORANGE, fontWeight: 700, fontSize: '10px', letterSpacing: '0.5px' }}>
+ {t('title')}
+ </span>
+ <span style={{ color: F.BORDER }}>|</span>
+ <span style={{ color: F.RED, fontWeight: 700, fontSize: '8px', animation: 'blink 1s infinite' }}>LIVE</span>
+ <span style={{ color: F.BORDER }}>|</span>
+ <span style={{ color: F.YELLOW, fontSize: '8px', fontWeight: 700 }}>ALT:{alertCount}</span>
+ <span style={{ color: F.BORDER }}>|</span>
+ <span style={{ color: F.GREEN, fontSize: '8px', fontWeight: 700 }}>{feedCount}SRC</span>
+ <span style={{ color: F.BORDER }}>|</span>
<TimezoneSelector compact />
- <span style={{ color: colors.text }}>|</span>
- <button
- onClick={() => {
- const tour = createNewsTabTour();
- tour.drive();
- }}
- style={{
- backgroundColor: colors.info,
- color: colors.background,
- border: 'none',
- padding: '2px 8px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- borderRadius: '2px',
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- title="Start news tour"
- >
- <Info size={12} />
- HELP
- </button>
- <span style={{ color: colors.text }}>|</span>
- <button
- id="news-refresh"
- onClick={() => handleRefresh(true)}
- disabled={loading}
- style={{
- backgroundColor: loading ? colors.textMuted : colors.secondary,
- color: colors.background,
- border: 'none',
- padding: '2px 8px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: loading ? 'not-allowed' : 'pointer',
- borderRadius: '2px',
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- title="Refresh news feeds"
- >
- 🔄 {loading ? t('header.updating') : t('header.refresh')}
- </button>
- <span style={{ color: colors.text }}>|</span>
- <button
- id="news-interval-settings"
- onClick={() => setShowIntervalSettings(!showIntervalSettings)}
- style={{
- backgroundColor: colors.info,
- color: colors.background,
- border: 'none',
- padding: '2px 8px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- borderRadius: '2px'
- }}
- title="Auto-refresh settings"
- >
- ⏱ {refreshInterval}min
- </button>
- <span style={{ color: colors.text }}>|</span>
- <button
- onClick={() => setShowFeedSettings(true)}
- style={{
- backgroundColor: colors.purple,
- color: colors.text,
- border: 'none',
- padding: '2px 8px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- borderRadius: '2px',
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- title="RSS Feed Settings"
- >
- <Settings size={12} />
- SOURCES
- </button>
- <span style={{ color: colors.text }}>|</span>
- <RecordingControlPanel
- tabName="News"
- onRecordingChange={setIsRecording}
- onRecordingStart={recordCurrentData}
- />
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <button onClick={() => { createNewsTabTour().drive(); }}
+ style={{ padding: '2px 6px', background: 'none', border: `1px solid ${F.BORDER}`, color: F.GRAY, fontSize: '8px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '3px' }}
+ ><Info size={9} />HELP</button>
+ <button id="news-refresh" onClick={() => handleRefresh(true)} disabled={loading}
+ style={{ padding: '2px 6px', backgroundColor: loading ? F.MUTED : F.ORANGE, color: loading ? F.GRAY : F.DARK_BG, border: 'none', fontSize: '8px', fontWeight: 700, cursor: loading ? 'not-allowed' : 'pointer', borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '3px' }}
+ ><RefreshCw size={9} />{loading ? 'WAIT' : 'REFRESH'}</button>
+ <button id="news-interval-settings" onClick={() => setShowIntervalSettings(!showIntervalSettings)}
+ style={{ padding: '2px 6px', background: 'none', border: `1px solid ${F.BORDER}`, color: F.GRAY, fontSize: '8px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '3px' }}
+ ><Clock size={9} />{refreshInterval}M</button>
+ <button onClick={() => setShowFeedSettings(true)}
+ style={{ padding: '2px 6px', background: 'none', border: `1px solid ${F.BORDER}`, color: F.GRAY, fontSize: '8px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '3px' }}
+ ><Settings size={9} />SRC</button>
+ <RecordingControlPanel tabName="News" onRecordingChange={setIsRecording} onRecordingStart={recordCurrentData} />
</div>
- {/* Interval Settings Dropdown */}
{showIntervalSettings && (
- <div style={{
- position: 'absolute',
- top: '30px',
- right: '8px',
- backgroundColor: colors.panel,
- border: `2px solid ${colors.primary}`,
- borderRadius: '4px',
- padding: '8px',
- zIndex: 1000,
- boxShadow: `0 4px 8px rgba(0,0,0,0.3)`
- }}>
- <div style={{ fontSize: '11px', color: colors.warning, fontWeight: 'bold', marginBottom: '6px' }}>
- {t('autoRefresh.title')}
- </div>
- {[1, 2, 5, 10, 15, 30].map(min => (
- <button
- key={min}
- onClick={() => {
- setRefreshInterval(min);
- setShowIntervalSettings(false);
- }}
- style={{
- width: '100%',
- backgroundColor: refreshInterval === min ? colors.primary : colors.background,
- color: refreshInterval === min ? colors.background : colors.text,
- border: `1px solid ${colors.textMuted}`,
- padding: '4px 8px',
- fontSize: '10px',
- fontWeight: refreshInterval === min ? 'bold' : 'normal',
- cursor: 'pointer',
- marginBottom: '2px',
- textAlign: 'left'
- }}
- >
- {min} {min > 1 ? t('autoRefresh.minutes') : t('autoRefresh.minute')}
- </button>
+ <div style={{ position: 'absolute', top: '100%', right: 12, backgroundColor: F.PANEL_BG, border: `1px solid ${F.ORANGE}`, borderRadius: '2px', padding: '6px', zIndex: 1000, marginTop: '2px' }}>
+ <div style={{ fontSize: '8px', color: F.GRAY, fontWeight: 700, marginBottom: '4px', letterSpacing: '0.5px' }}>INTERVAL</div>
+ {[1, 2, 5, 10, 15, 30].map(m => (
+ <button key={m} onClick={() => { setRefreshInterval(m); setShowIntervalSettings(false); }}
+ style={{ width: '100%', backgroundColor: refreshInterval === m ? F.ORANGE : 'transparent', color: refreshInterval === m ? F.DARK_BG : F.WHITE, border: `1px solid ${refreshInterval === m ? F.ORANGE : F.BORDER}`, padding: '2px 6px', fontSize: '8px', fontWeight: 700, cursor: 'pointer', marginBottom: '1px', textAlign: 'left', borderRadius: '2px' }}
+ >{m}min</button>
))}
</div>
)}
+ </div>
- {/* News Ticker - Continuous seamless scroll like Fincept */}
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px', marginBottom: '2px' }}>
- <span style={{ color: colors.warning, fontWeight: 'bold' }}>{t('messages.breaking')}:</span>
- <div className="ticker-wrap" style={{
- flex: 1,
- overflow: 'hidden',
- position: 'relative',
- height: '20px'
- }}>
- <div className="ticker-move">
- <span className="ticker-item">{newsTickerText}</span>
- <span className="ticker-item">{newsTickerText}</span>
- </div>
+ {/* ── TICKER ── */}
+ <div style={{ backgroundColor: F.PANEL_BG, borderBottom: `1px solid ${F.BORDER}`, padding: '2px 12px', display: 'flex', alignItems: 'center', gap: '6px', flexShrink: 0 }}>
+ <span style={{ color: F.RED, fontWeight: 700, fontSize: '8px', flexShrink: 0 }}>BREAKING:</span>
+ <div className="ticker-wrap" style={{ flex: 1, overflow: 'hidden', height: '14px' }}>
+ <div className="ticker-move">
+ <span className="ticker-item">{tickerText}</span>
+ <span className="ticker-item">{tickerText}</span>
</div>
- <span style={{ color: colors.secondary, fontSize: '9px' }}>
- ● {t('header.live')}
- </span>
</div>
+ <span style={{ color: loading ? F.YELLOW : F.GREEN, fontSize: '8px', fontWeight: 700, flexShrink: 0 }}>
+ {loading ? 'UPD' : (isUsingMockData() ? 'DEMO' : 'LIVE')}
+ </span>
+ </div>
- {/* Sources and Stats */}
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '10px', flexWrap: 'wrap' }}>
- <span style={{ color: colors.textMuted }}>{t('header.activeSources')}:</span>
- {activeSources.slice(0, 12).map((source, idx) => (
- <span key={idx} style={{ color: colors.secondary }}>{source}●</span>
- ))}
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.textMuted }}>{t('header.articles')}:</span>
- <span style={{ color: colors.accent }}>{newsArticles.length}</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.textMuted }}>{t('header.status')}:</span>
- <span style={{ color: loading ? colors.warning : colors.secondary }}>
- {loading ? t('header.updating') : (isUsingMockData() ? `● ${t('header.demoMode')}` : `● ${t('header.live')}`)}
- </span>
- </div>
+ {/* ── FILTER BAR ── */}
+ <div id="news-filters" style={{ backgroundColor: F.HEADER_BG, borderBottom: `1px solid ${F.BORDER}`, padding: '2px 6px', flexShrink: 0, display: 'flex', gap: '2px' }}>
+ {filters.map(item => (
+ <button key={item.key} onClick={() => setActiveFilter(item.f)}
+ style={{
+ padding: '2px 8px', backgroundColor: activeFilter === item.f ? F.ORANGE : 'transparent',
+ color: activeFilter === item.f ? F.DARK_BG : F.GRAY, border: 'none',
+ fontSize: '8px', fontWeight: 700, letterSpacing: '0.3px', cursor: 'pointer', borderRadius: '2px',
+ }}>
+ <span style={{ color: activeFilter === item.f ? F.DARK_BG : F.MUTED, marginRight: '2px', fontSize: '7px' }}>{item.key}</span>
+ {item.label}
+ {catCounts[item.f] ? <span style={{ marginLeft: '3px', opacity: 0.6 }}>({catCounts[item.f]})</span> : null}
+ </button>
+ ))}
</div>
- {/* Function Keys Bar */}
- <div id="news-filters" style={{
- backgroundColor: colors.panel,
- borderBottom: `1px solid ${colors.textMuted}`,
- padding: '2px 4px',
- flexShrink: 0
+ {/* ── COLUMN HEADER for feed table ── */}
+ <div style={{
+ display: 'flex', alignItems: 'center', gap: '6px', padding: '2px 6px',
+ backgroundColor: F.HEADER_BG, borderBottom: `1px solid ${F.BORDER}`, flexShrink: 0,
+ fontSize: '7px', fontWeight: 700, color: F.MUTED, letterSpacing: '0.5px',
}}>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: '2px' }}>
- {[
- { key: "F1", label: "ALL", filter: "ALL" },
- { key: "F2", label: "MARKETS", filter: "MARKETS" },
- { key: "F3", label: "EARNINGS", filter: "EARNINGS" },
- { key: "F4", label: "ECON", filter: "ECONOMIC" },
- { key: "F5", label: "TECH", filter: "TECH" },
- { key: "F6", label: "ENERGY", filter: "ENERGY" },
- { key: "F7", label: "BANKING", filter: "BANKING" },
- { key: "F8", label: "CRYPTO", filter: "CRYPTO" },
- { key: "F9", label: "GEOPO", filter: "GEOPOLITICS" },
- { key: "F10", label: "FLASH", filter: "FLASH" },
- { key: "F11", label: "URGENT", filter: "URGENT" },
- { key: "F12", label: "REFRESH", filter: "REFRESH" }
- ].map(item => (
- <button key={item.key}
- onClick={() => {
- if (item.filter === 'REFRESH') {
- window.location.reload();
- } else if (item.filter === 'FLASH') {
- setActiveFilter('ALL');
- setNewsArticles(prev => prev.filter(a => a.priority === 'FLASH'));
- } else if (item.filter === 'URGENT') {
- setActiveFilter('ALL');
- setNewsArticles(prev => prev.filter(a => a.priority === 'URGENT' || a.priority === 'FLASH'));
- } else {
- setActiveFilter(item.filter);
- }
- }}
- style={{
- backgroundColor: activeFilter === item.filter ? colors.primary : colors.background,
- border: `1px solid ${colors.textMuted}`,
- color: activeFilter === item.filter ? colors.background : colors.text,
- padding: '2px 4px',
- fontSize: '9px',
- height: '16px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- fontWeight: activeFilter === item.filter ? 'bold' : 'normal',
- cursor: 'pointer'
- }}>
- <span style={{ color: colors.warning }}>{item.key}:</span>
- <span style={{ marginLeft: '2px' }}>{item.label}</span>
- </button>
- ))}
- </div>
+ <span style={{ minWidth: '38px' }}>TIME</span>
+ <span style={{ minWidth: '40px' }}>PRI</span>
+ <span style={{ minWidth: '55px' }}>SOURCE</span>
+ <span style={{ flex: 1 }}>HEADLINE</span>
+ <span style={{ minWidth: '28px', textAlign: 'right' }}>SNT</span>
+ <span style={{ minWidth: '10px', textAlign: 'center' }}>I</span>
</div>
- {/* Main Content - 3 Column Dense News Layout */}
- <div style={{ flex: 1, overflow: 'auto', padding: '4px', backgroundColor: '#050505' }}>
- <div style={{ display: 'flex', gap: '4px', height: '100%' }}>
-
- {/* Left Panel - Breaking News Stream (Primary Feed) */}
- <div id="news-primary-feed" style={{
- flex: 1,
- backgroundColor: colors.panel,
- border: `1px solid ${colors.textMuted}`,
- padding: '4px',
- overflow: 'auto'
- }}>
- <div style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
- {t('feeds.primary')} [{activeFilter}]
- </div>
- <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
-
- {loading && newsArticles.length === 0 ? (
- <div style={{ color: colors.warning, fontSize: '10px', textAlign: 'center', padding: '20px' }}>
- Loading news from {feedCount} RSS feeds...
- </div>
- ) : filteredNews.length === 0 ? (
- <div style={{ color: colors.textMuted, fontSize: '10px', textAlign: 'center', padding: '20px' }}>
- No articles found for filter: {activeFilter}
- </div>
- ) : null}
-
- {filteredNews.slice(0, Math.ceil(filteredNews.length / 3)).map((article, index) => (
- <div key={article.id} style={{
- marginBottom: '6px',
- borderLeft: `3px solid ${getPriorityColor(article.priority)}`,
- paddingLeft: '4px',
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- cursor: article.link ? 'pointer' : 'default'
- }}
- onClick={() => setSelectedArticle(article)}
- >
- <div style={{ display: 'flex', gap: '4px', marginBottom: '1px', fontSize: '8px' }}>
- <span style={{ color: colors.textMuted, minWidth: '50px' }}>{article.time}</span>
- <span style={{ color: getPriorityColor(article.priority), fontWeight: 'bold', minWidth: '60px' }}>
- [{article.priority}]
- </span>
- <span style={{ color: colors.info, minWidth: '50px' }}>[{article.category}]</span>
- <span style={{ color: colors.purple, minWidth: '30px' }}>{article.region}</span>
- <span style={{ color: getArticleSentimentColor(article.sentiment), minWidth: '50px' }}>{article.sentiment}</span>
- </div>
-
- <div style={{ color: colors.text, fontWeight: 'bold', fontSize: '10px', lineHeight: '1.2', marginBottom: '2px' }}>
- {article.headline}
- </div>
-
- <div style={{ color: colors.textMuted, fontSize: '9px', lineHeight: '1.2', marginBottom: '2px' }}>
- {article.summary}
- </div>
+ {/* ══ MAIN CONTENT ══ */}
+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', gap: '1px', backgroundColor: F.BORDER }}>
+
+ {/* ── LEFT SIDEBAR: Alerts + Stats ── */}
+ <div style={{ width: '200px', flexShrink: 0, backgroundColor: F.PANEL_BG, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ {/* Breaking Alerts */}
+ <SectionHead title="BREAKING / URGENT" right={`${urgentNews.length}`} />
+ <div style={{ flex: 1, overflow: 'auto', padding: '2px' }}>
+ {urgentNews.length === 0 ? (
+ <div style={{ padding: '12px', color: F.MUTED, fontSize: '8px', textAlign: 'center' }}>NO ALERTS</div>
+ ) : urgentNews.slice(0, 20).map(a => (
+ <AlertRow key={a.id} article={a} onClick={() => setSelectedArticle(a)} />
+ ))}
+ </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '8px' }}>
- <span style={{ color: colors.accent }}>{article.source}</span>
- <span style={{ color: getImpactColor(article.impact) }}>IMPACT: {article.impact}</span>
- </div>
- </div>
+ {/* Category Breakdown */}
+ <SectionHead title="CATEGORY BREAKDOWN" />
+ <div style={{ padding: '4px 6px', borderBottom: `1px solid ${F.BORDER}` }}>
+ {Object.entries(catCounts).sort((a, b) => b[1] - a[1]).slice(0, 8).map(([cat, count]) => (
+ <StatRow key={cat} label={cat} value={count} color={F.CYAN} />
))}
</div>
- {/* Center Panel - Secondary News Feed */}
- <div style={{
- flex: 1,
- backgroundColor: colors.panel,
- border: `1px solid ${colors.textMuted}`,
- padding: '4px',
- overflow: 'auto'
- }}>
- <div style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
- {t('feeds.secondary')} [{activeFilter}]
+ {/* Sentiment */}
+ <SectionHead title="SENTIMENT" />
+ <div style={{ padding: '4px 6px' }}>
+ <StatRow label="BULLISH" value={`${bullish} (${Math.round((bullish / total) * 100)}%)`} color={F.GREEN} />
+ <StatRow label="BEARISH" value={`${bearish} (${Math.round((bearish / total) * 100)}%)`} color={F.RED} />
+ <StatRow label="NEUTRAL" value={`${neutral} (${Math.round((neutral / total) * 100)}%)`} color={F.YELLOW} />
+ <div style={{ marginTop: '4px', paddingTop: '4px', borderTop: `1px solid ${F.BORDER}` }}>
+ <StatRow label="NET SCORE" value={`${score} ${parseFloat(score) > 0 ? 'BULL' : parseFloat(score) < 0 ? 'BEAR' : 'FLAT'}`}
+ color={parseFloat(score) > 0 ? F.GREEN : parseFloat(score) < 0 ? F.RED : F.YELLOW} />
</div>
- <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
-
- {filteredNews.slice(Math.ceil(filteredNews.length / 3), Math.ceil(filteredNews.length * 2 / 3)).map((article, index) => (
- <div key={article.id} style={{
- marginBottom: '6px',
- borderLeft: `3px solid ${getPriorityColor(article.priority)}`,
- paddingLeft: '4px',
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- cursor: article.link ? 'pointer' : 'default'
- }}
- onClick={() => setSelectedArticle(article)}
- >
- <div style={{ display: 'flex', gap: '4px', marginBottom: '1px', fontSize: '8px' }}>
- <span style={{ color: colors.textMuted, minWidth: '50px' }}>{article.time}</span>
- <span style={{ color: getPriorityColor(article.priority), fontWeight: 'bold', minWidth: '60px' }}>
- [{article.priority}]
- </span>
- <span style={{ color: colors.info, minWidth: '50px' }}>[{article.category}]</span>
- <span style={{ color: colors.purple, minWidth: '30px' }}>{article.region}</span>
- <span style={{ color: getArticleSentimentColor(article.sentiment), minWidth: '50px' }}>{article.sentiment}</span>
- </div>
-
- <div style={{ color: colors.text, fontWeight: 'bold', fontSize: '10px', lineHeight: '1.2', marginBottom: '2px' }}>
- {article.headline}
- </div>
+ {/* Sentiment bar */}
+ <div style={{ marginTop: '4px', height: '3px', backgroundColor: F.BORDER, borderRadius: '2px', display: 'flex', overflow: 'hidden' }}>
+ <div style={{ width: `${Math.round((bullish / total) * 100)}%`, backgroundColor: F.GREEN }} />
+ <div style={{ width: `${Math.round((neutral / total) * 100)}%`, backgroundColor: F.YELLOW }} />
+ <div style={{ width: `${Math.round((bearish / total) * 100)}%`, backgroundColor: F.RED }} />
+ </div>
+ </div>
- <div style={{ color: colors.textMuted, fontSize: '9px', lineHeight: '1.2', marginBottom: '2px' }}>
- {article.summary}
- </div>
+ {/* Quick Stats */}
+ <SectionHead title="FEED STATS" />
+ <div style={{ padding: '4px 6px' }}>
+ <StatRow label="TOTAL" value={newsArticles.length} color={F.CYAN} />
+ <StatRow label="FEEDS" value={feedCount} color={F.CYAN} />
+ <StatRow label="UPDATES" value={newsUpdateCount} color={F.CYAN} />
+ <StatRow label="FILTER" value={activeFilter} color={F.ORANGE} />
+ </div>
+ </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '8px' }}>
- <span style={{ color: colors.accent }}>{article.source}</span>
- <span style={{ color: getImpactColor(article.impact) }}>IMPACT: {article.impact}</span>
- </div>
+ {/* ── CENTER: Dense News Feed ── */}
+ <div id="news-primary-feed" style={{ flex: 1, backgroundColor: F.PANEL_BG, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {loading && newsArticles.length === 0 ? (
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', color: F.MUTED, fontSize: '9px' }}>
+ <RefreshCw size={16} className="animate-spin" style={{ marginBottom: '6px', opacity: 0.5 }} />
+ Loading {feedCount} feeds...
</div>
+ ) : filteredNews.length === 0 ? (
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', color: F.MUTED, fontSize: '9px' }}>
+ <Newspaper size={16} style={{ marginBottom: '6px', opacity: 0.5 }} />
+ No articles for: {activeFilter}
+ </div>
+ ) : filteredNews.map(article => (
+ <NewsRow key={article.id} article={article}
+ selected={selectedArticle?.id === article.id}
+ onClick={() => { setSelectedArticle(article); setShowAnalysis(false); setAnalysisData(null); setShowWebView(false); }}
+ />
))}
</div>
+ </div>
- {/* Right Panel - AI Analytics */}
- <div id="news-ai-analysis" style={{
- width: '500px',
- backgroundColor: colors.panel,
- border: `1px solid ${colors.textMuted}`,
- padding: '8px',
- overflowY: 'auto',
- overflowX: 'hidden',
- display: 'flex',
- flexDirection: 'column',
- maxHeight: '100%'
- }}>
- {/* News Analytics Section */}
- <div style={{ flex: 1, minHeight: '600px', overflowY: 'auto' }}>
- <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '0.5px' }}>
- {t('analytics.title')}
- </div>
- <div style={{ borderBottom: `2px solid ${colors.primary}`, marginBottom: '12px' }}></div>
-
- {showAnalysis && analysisData ? (
- /* AI Analysis Display */
- <div style={{ fontSize: '11px' }}>
- {/* Header */}
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- marginBottom: '12px',
- padding: '8px',
- background: 'rgba(147, 51, 234, 0.1)',
- border: `1px solid #9333ea`
- }}>
- <span style={{ color: '#9333ea', fontSize: '11px', fontWeight: 'bold' }}>
- AI POWERED ANALYSIS
- </span>
- <span style={{ fontSize: '9px', color: colors.textMuted }}>
- {analysisData.credits_used} CREDITS | {analysisData.credits_remaining.toLocaleString()} REMAINING
- </span>
+ {/* ── RIGHT: Article Detail + AI Analysis ── */}
+ <div id="news-ai-analysis" style={{ width: '340px', flexShrink: 0, backgroundColor: F.PANEL_BG, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ {selectedArticle ? (
+ <>
+ {/* Article Detail */}
+ <SectionHead title="ARTICLE DETAIL" right={selectedArticle.time} />
+ <div style={{ overflow: 'auto', flex: 1, padding: '6px' }}>
+ {/* Show web view or detail */}
+ {showWebView ? (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <button onClick={() => setShowWebView(false)}
+ style={{ padding: '3px 8px', backgroundColor: F.ORANGE, color: F.DARK_BG, border: 'none', fontSize: '8px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px' }}
+ >BACK</button>
+ <span style={{ color: F.GRAY, fontSize: '8px', fontWeight: 700, display: 'flex', alignItems: 'center' }}>READER VIEW</span>
+ </div>
+ <div style={{ padding: '4px 6px', borderBottom: `2px solid ${F.ORANGE}` }}>
+ <div style={{ display: 'flex', gap: '4px', marginBottom: '6px' }}>
+ {[{ label: selectedArticle.priority, color: priColor(selectedArticle.priority) },
+ { label: selectedArticle.category, color: F.CYAN },
+ { label: selectedArticle.sentiment, color: sentColor(selectedArticle.sentiment) },
+ ].map((b, i) => (
+ <span key={i} style={{ padding: '1px 4px', backgroundColor: `${b.color}20`, color: b.color, fontSize: '7px', fontWeight: 700, borderRadius: '2px' }}>{b.label}</span>
+ ))}
+ </div>
+ <div style={{ fontSize: '11px', fontWeight: 700, lineHeight: '1.3', color: F.WHITE, marginBottom: '4px' }}>{selectedArticle.headline}</div>
+ <div style={{ fontSize: '8px', color: F.GRAY, display: 'flex', gap: '8px' }}>
+ <span>{selectedArticle.source}</span>
+ <span>{selectedArticle.region}</span>
+ {selectedArticle.tickers?.length > 0 && <span style={{ color: F.CYAN }}>{selectedArticle.tickers.join(', ')}</span>}
+ </div>
+ </div>
+ <div style={{ fontSize: '9px', lineHeight: '1.6', color: F.WHITE }}>{selectedArticle.summary}</div>
+ <div style={{ padding: '8px', backgroundColor: `${F.ORANGE}10`, border: `1px solid ${F.ORANGE}`, borderRadius: '2px', fontSize: '8px', color: F.GRAY }}>
+ <span style={{ color: F.YELLOW, fontWeight: 700 }}>NOTE: </span>
+ RSS summary shown. Click "OPEN" for full article.
+ </div>
+ {selectedArticle.link && (
+ <button onClick={() => openExternal(selectedArticle.link!)}
+ style={{ padding: '4px 8px', backgroundColor: F.BLUE, color: F.WHITE, border: 'none', fontSize: '8px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '4px', justifyContent: 'center' }}
+ ><ExternalLink size={10} />OPEN FULL ARTICLE</button>
+ )}
</div>
+ ) : (
+ <>
+ {/* Priority + Meta badges */}
+ <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap', marginBottom: '4px' }}>
+ {[
+ { label: selectedArticle.priority, color: priColor(selectedArticle.priority) },
+ { label: selectedArticle.category, color: F.CYAN },
+ { label: selectedArticle.sentiment, color: sentColor(selectedArticle.sentiment) },
+ { label: selectedArticle.region, color: F.PURPLE },
+ { label: `IMPACT: ${selectedArticle.impact}`, color: impColor(selectedArticle.impact) },
+ ].map((b, i) => (
+ <span key={i} style={{ padding: '1px 5px', backgroundColor: `${b.color}15`, color: b.color, fontSize: '7px', fontWeight: 700, borderRadius: '2px', border: `1px solid ${b.color}30` }}>{b.label}</span>
+ ))}
+ </div>
- {/* Summary */}
- <div style={{ marginBottom: '16px' }}>
- <div style={{
- fontSize: '10px',
- color: colors.warning,
- fontWeight: 'bold',
- marginBottom: '6px',
- letterSpacing: '0.5px'
- }}>
- SUMMARY
+ {/* Source + time */}
+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '8px', color: F.GRAY, marginBottom: '6px' }}>
+ <span style={{ color: F.CYAN, fontWeight: 700 }}>{selectedArticle.source}</span>
+ <span>{selectedArticle.time}</span>
</div>
+
+ {/* Headline */}
<div style={{
- fontSize: '11px',
- color: colors.text,
- lineHeight: '1.6',
- padding: '8px',
- background: 'rgba(255,255,255,0.02)',
- border: `1px solid ${colors.textMuted}`
- }}>
- {analysisData.analysis.summary}
- </div>
- </div>
+ color: F.WHITE, fontSize: '11px', fontWeight: 700, lineHeight: '1.3', marginBottom: '6px',
+ padding: '6px', backgroundColor: F.DARK_BG, borderLeft: `2px solid ${priColor(selectedArticle.priority)}`, borderRadius: '2px',
+ }}>{selectedArticle.headline}</div>
- {/* Key Points */}
- {analysisData.analysis.key_points.length > 0 && (
- <div style={{ marginBottom: '16px' }}>
- <div style={{
- fontSize: '10px',
- color: colors.warning,
- fontWeight: 'bold',
- marginBottom: '6px',
- letterSpacing: '0.5px'
- }}>
- KEY POINTS
- </div>
- <div style={{
- padding: '8px',
- background: 'rgba(255,255,255,0.02)',
- border: `1px solid ${colors.textMuted}`
- }}>
- {analysisData.analysis.key_points.map((point, idx) => (
- <div key={idx} style={{
- marginBottom: '6px',
- fontSize: '10px',
- color: colors.text,
- paddingLeft: '12px',
- borderLeft: `2px solid ${colors.primary}`,
- lineHeight: '1.5'
- }}>
- {point}
- </div>
+ {/* Tickers */}
+ {selectedArticle.tickers && selectedArticle.tickers.length > 0 && (
+ <div style={{ display: 'flex', gap: '3px', marginBottom: '6px', flexWrap: 'wrap' }}>
+ {selectedArticle.tickers.map((t, i) => (
+ <span key={i} style={{ padding: '1px 5px', backgroundColor: `${F.GREEN}15`, color: F.GREEN, fontSize: '7px', fontWeight: 700, borderRadius: '2px', border: `1px solid ${F.GREEN}30` }}>{t}</span>
))}
</div>
- </div>
- )}
+ )}
- {/* Sentiment & Market Impact Grid */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '16px' }}>
- <div>
- <div style={{
- fontSize: '10px',
- color: colors.warning,
- fontWeight: 'bold',
- marginBottom: '6px',
- letterSpacing: '0.5px'
- }}>
- SENTIMENT
- </div>
- <div style={{
- padding: '8px',
- background: 'rgba(0,0,0,0.3)',
- border: `1px solid ${colors.textMuted}`,
- fontSize: '10px'
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: colors.textMuted }}>Score:</span>
- <span style={{ color: getSentimentColor(analysisData.analysis.sentiment.score), fontWeight: 'bold' }}>
- {analysisData.analysis.sentiment.score.toFixed(2)}
- </span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: colors.textMuted }}>Intensity:</span>
- <span style={{ color: colors.text }}>{analysisData.analysis.sentiment.intensity.toFixed(2)}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: colors.textMuted }}>Confidence:</span>
- <span style={{ color: colors.secondary }}>
- {(analysisData.analysis.sentiment.confidence * 100).toFixed(0)}%
- </span>
- </div>
+ {/* Summary */}
+ <div style={{ color: F.GRAY, fontSize: '9px', lineHeight: '1.5', marginBottom: '8px' }}>{selectedArticle.summary}</div>
+
+ {/* Action buttons */}
+ {selectedArticle.link && (
+ <div style={{ display: 'flex', gap: '3px', marginBottom: '8px' }}>
+ <button onClick={() => setShowWebView(true)}
+ style={{ flex: 1, padding: '4px', backgroundColor: F.GREEN, color: F.DARK_BG, border: 'none', fontSize: '8px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '3px' }}
+ ><BookOpen size={9} />READ</button>
+ <button onClick={() => openExternal(selectedArticle.link!)}
+ style={{ flex: 1, padding: '4px', backgroundColor: F.BLUE, color: F.WHITE, border: 'none', fontSize: '8px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '3px' }}
+ ><ExternalLink size={9} />OPEN</button>
+ <button onClick={() => { navigator.clipboard.writeText(selectedArticle.link!); }}
+ style={{ padding: '4px 8px', background: 'none', border: `1px solid ${F.BORDER}`, color: F.GRAY, fontSize: '8px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '3px' }}
+ ><Copy size={9} /></button>
+ <button onClick={handleAnalyzeArticle} disabled={analyzingArticle}
+ style={{ flex: 1, padding: '4px', backgroundColor: analyzingArticle ? F.MUTED : F.PURPLE, color: F.WHITE, border: 'none', fontSize: '8px', fontWeight: 700, cursor: analyzingArticle ? 'not-allowed' : 'pointer', borderRadius: '2px', opacity: analyzingArticle ? 0.5 : 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '3px' }}
+ ><Zap size={9} />{analyzingArticle ? 'WAIT' : 'AI'}</button>
</div>
- </div>
- <div>
- <div style={{
- fontSize: '10px',
- color: colors.warning,
- fontWeight: 'bold',
- marginBottom: '6px',
- letterSpacing: '0.5px'
- }}>
- MARKET IMPACT
- </div>
- <div style={{
- padding: '8px',
- background: 'rgba(0,0,0,0.3)',
- border: `1px solid ${colors.textMuted}`,
- fontSize: '10px'
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: colors.textMuted }}>Urgency:</span>
- <span style={{
- color: getUrgencyColor(analysisData.analysis.market_impact.urgency),
- fontWeight: 'bold'
- }}>
- {analysisData.analysis.market_impact.urgency}
- </span>
+ )}
+
+ {/* AI Analysis Results */}
+ {showAnalysis && analysisData && (
+ <div style={{ borderTop: `1px solid ${F.BORDER}`, paddingTop: '6px' }}>
+ <div style={{ padding: '4px 6px', backgroundColor: `${F.PURPLE}15`, border: `1px solid ${F.PURPLE}`, borderRadius: '2px', marginBottom: '6px', display: 'flex', justifyContent: 'space-between', fontSize: '7px' }}>
+ <span style={{ color: F.PURPLE, fontWeight: 700 }}>AI ANALYSIS</span>
+ <span style={{ color: F.GRAY }}>{analysisData.credits_used}CR | {analysisData.credits_remaining.toLocaleString()}REM</span>
</div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: colors.textMuted }}>Prediction:</span>
- <span style={{ color: colors.text, textTransform: 'uppercase', fontSize: '9px' }}>
- {analysisData.analysis.market_impact.prediction.replace('_', ' ')}
- </span>
+
+ {/* Summary */}
+ <div style={{ fontSize: '8px', color: F.WHITE, lineHeight: '1.5', padding: '4px 6px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px', marginBottom: '6px' }}>
+ {analysisData.analysis.summary}
</div>
- </div>
- </div>
- </div>
- {/* Risk Signals */}
- <div style={{ marginBottom: '16px' }}>
- <div style={{
- fontSize: '10px',
- color: colors.warning,
- fontWeight: 'bold',
- marginBottom: '6px',
- letterSpacing: '0.5px'
- }}>
- RISK SIGNALS
- </div>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
- {Object.entries(analysisData.analysis.risk_signals).map(([type, signal]) => (
- <div key={type} style={{
- padding: '8px',
- background: 'rgba(0,0,0,0.3)',
- border: `1px solid ${colors.textMuted}`,
- fontSize: '10px'
- }}>
- <div style={{
- color: getRiskColor(signal.level),
- fontWeight: 'bold',
- marginBottom: '4px',
- fontSize: '9px',
- letterSpacing: '0.3px'
- }}>
- {type.toUpperCase()}: {signal.level.toUpperCase()}
+ {/* Key points */}
+ {analysisData.analysis.key_points.length > 0 && (
+ <div style={{ marginBottom: '6px' }}>
+ <div style={{ fontSize: '7px', color: F.GRAY, fontWeight: 700, marginBottom: '3px', letterSpacing: '0.5px' }}>KEY POINTS</div>
+ {analysisData.analysis.key_points.map((p, i) => (
+ <div key={i} style={{ fontSize: '8px', color: F.WHITE, paddingLeft: '6px', borderLeft: `2px solid ${F.ORANGE}`, marginBottom: '3px', lineHeight: '1.3' }}>{p}</div>
+ ))}
</div>
- {signal.details && (
- <div style={{
- color: colors.textMuted,
- fontSize: '9px',
- lineHeight: '1.4'
- }}>
- {signal.details}
- </div>
- )}
- </div>
- ))}
- </div>
- </div>
+ )}
- {/* Topics & Keywords */}
- {(analysisData.analysis.topics.length > 0 || analysisData.analysis.keywords.length > 0) && (
- <div style={{ marginBottom: '16px' }}>
- {analysisData.analysis.topics.length > 0 && (
- <div style={{ marginBottom: '12px' }}>
- <div style={{
- fontSize: '10px',
- color: colors.warning,
- fontWeight: 'bold',
- marginBottom: '6px',
- letterSpacing: '0.5px'
- }}>
- TOPICS
+ {/* Sentiment + Impact grid */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px', marginBottom: '6px' }}>
+ <div style={{ padding: '4px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px', fontSize: '7px' }}>
+ <div style={{ color: F.GRAY, fontWeight: 700, marginBottom: '2px' }}>SENTIMENT</div>
+ <StatRow label="Score" value={analysisData.analysis.sentiment.score.toFixed(2)} color={getSentimentColor(analysisData.analysis.sentiment.score)} />
+ <StatRow label="Intensity" value={analysisData.analysis.sentiment.intensity.toFixed(2)} color={F.CYAN} />
+ <StatRow label="Confidence" value={`${(analysisData.analysis.sentiment.confidence * 100).toFixed(0)}%`} color={F.GREEN} />
</div>
- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
- {analysisData.analysis.topics.map((topic, idx) => (
- <span key={idx} style={{
- background: 'rgba(147, 51, 234, 0.2)',
- padding: '4px 8px',
- fontSize: '9px',
- color: colors.text,
- border: '1px solid #9333ea',
- fontWeight: 'bold',
- letterSpacing: '0.3px'
- }}>
- {topic}
- </span>
- ))}
+ <div style={{ padding: '4px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px', fontSize: '7px' }}>
+ <div style={{ color: F.GRAY, fontWeight: 700, marginBottom: '2px' }}>MARKET IMPACT</div>
+ <StatRow label="Urgency" value={analysisData.analysis.market_impact.urgency} color={getUrgencyColor(analysisData.analysis.market_impact.urgency)} />
+ <StatRow label="Prediction" value={analysisData.analysis.market_impact.prediction.replace('_', ' ').toUpperCase()} color={F.CYAN} />
</div>
</div>
- )}
- {analysisData.analysis.keywords.length > 0 && (
- <div>
- <div style={{
- fontSize: '10px',
- color: colors.warning,
- fontWeight: 'bold',
- marginBottom: '6px',
- letterSpacing: '0.5px'
- }}>
- KEYWORDS
- </div>
- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
- {analysisData.analysis.keywords.slice(0, 8).map((keyword, idx) => (
- <span key={idx} style={{
- background: 'rgba(100, 100, 100, 0.2)',
- padding: '4px 8px',
- fontSize: '9px',
- color: colors.textMuted,
- border: `1px solid ${colors.textMuted}`
- }}>
- {keyword}
- </span>
+
+ {/* Risk Signals */}
+ <div style={{ marginBottom: '6px' }}>
+ <div style={{ fontSize: '7px', color: F.GRAY, fontWeight: 700, marginBottom: '3px', letterSpacing: '0.5px' }}>RISK SIGNALS</div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '3px' }}>
+ {Object.entries(analysisData.analysis.risk_signals).map(([type, signal]) => (
+ <div key={type} style={{ padding: '3px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px', fontSize: '7px' }}>
+ <span style={{ color: getRiskColor(signal.level), fontWeight: 700 }}>{type.toUpperCase()}: {signal.level.toUpperCase()}</span>
+ {signal.details && <div style={{ color: F.MUTED, fontSize: '7px', marginTop: '1px' }}>{signal.details}</div>}
+ </div>
))}
</div>
</div>
- )}
- </div>
- )}
- {/* Entities */}
- {analysisData.analysis.entities.organizations.length > 0 && (
- <div>
- <div style={{
- fontSize: '10px',
- color: colors.warning,
- fontWeight: 'bold',
- marginBottom: '6px',
- letterSpacing: '0.5px'
- }}>
- ORGANIZATIONS
- </div>
- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
- {analysisData.analysis.entities.organizations.map((org, idx) => (
- <div key={idx} style={{
- background: 'rgba(0,0,0,0.3)',
- padding: '6px 10px',
- border: `1px solid ${colors.textMuted}`,
- fontSize: '10px'
- }}>
- <div style={{ color: colors.text, fontWeight: 'bold', marginBottom: '2px' }}>
- {org.name}
- </div>
- <div style={{ color: colors.textMuted, fontSize: '9px' }}>
- {org.sector} {org.ticker ? `| ${org.ticker}` : ''}
- </div>
+ {/* Topics + Keywords */}
+ {(analysisData.analysis.topics.length > 0 || analysisData.analysis.keywords.length > 0) && (
+ <div style={{ marginBottom: '6px' }}>
+ {analysisData.analysis.topics.length > 0 && (
+ <>
+ <div style={{ fontSize: '7px', color: F.GRAY, fontWeight: 700, marginBottom: '2px' }}>TOPICS</div>
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '2px', marginBottom: '4px' }}>
+ {analysisData.analysis.topics.map((t, i) => (
+ <span key={i} style={{ padding: '1px 4px', backgroundColor: `${F.PURPLE}20`, color: F.WHITE, fontSize: '7px', fontWeight: 700, borderRadius: '2px', border: `1px solid ${F.PURPLE}` }}>{t}</span>
+ ))}
+ </div>
+ </>
+ )}
+ {analysisData.analysis.keywords.length > 0 && (
+ <>
+ <div style={{ fontSize: '7px', color: F.GRAY, fontWeight: 700, marginBottom: '2px' }}>KEYWORDS</div>
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '2px' }}>
+ {analysisData.analysis.keywords.slice(0, 8).map((k, i) => (
+ <span key={i} style={{ padding: '1px 4px', backgroundColor: `${F.MUTED}20`, color: F.GRAY, fontSize: '7px', borderRadius: '2px', border: `1px solid ${F.MUTED}` }}>{k}</span>
+ ))}
+ </div>
+ </>
+ )}
</div>
- ))}
- </div>
- </div>
- )}
- </div>
- ) : (
- /* Default Analytics Display */
- <>
- {/* Sentiment Analysis */}
- <div style={{ marginBottom: '16px', fontSize: '10px' }}>
- <div style={{ color: colors.warning, fontWeight: 'bold', marginBottom: '6px', letterSpacing: '0.5px' }}>
- SENTIMENT ANALYSIS
- </div>
- <div style={{
- padding: '8px',
- background: 'rgba(255,255,255,0.02)',
- border: `1px solid ${colors.textMuted}`
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: colors.textMuted }}>Bullish Articles:</span>
- <span style={{ color: colors.secondary }}>{bullishCount} ({Math.round((bullishCount / totalCount) * 100)}%)</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: colors.textMuted }}>Bearish Articles:</span>
- <span style={{ color: colors.alert }}>{bearishCount} ({Math.round((bearishCount / totalCount) * 100)}%)</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: colors.textMuted }}>Neutral Articles:</span>
- <span style={{ color: colors.warning }}>{neutralCount} ({Math.round((neutralCount / totalCount) * 100)}%)</span>
- </div>
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- marginTop: '8px',
- paddingTop: '8px',
- borderTop: `1px solid ${colors.textMuted}`
- }}>
- <span style={{ color: colors.accent, fontWeight: 'bold' }}>Sentiment Score:</span>
- <span style={{
- color: parseFloat(sentimentScore) > 0 ? colors.secondary : parseFloat(sentimentScore) < 0 ? colors.alert : colors.warning,
- fontWeight: 'bold'
- }}>
- {sentimentScore} ({parseFloat(sentimentScore) > 0 ? 'BULLISH' : parseFloat(sentimentScore) < 0 ? 'BEARISH' : 'NEUTRAL'})
- </span>
- </div>
- </div>
- </div>
+ )}
- {/* News Flow Statistics */}
- <div style={{ marginBottom: '16px', fontSize: '10px' }}>
- <div style={{ color: colors.warning, fontWeight: 'bold', marginBottom: '6px', letterSpacing: '0.5px' }}>
- NEWS FLOW STATS
- </div>
- <div style={{
- padding: '8px',
- background: 'rgba(255,255,255,0.02)',
- border: `1px solid ${colors.textMuted}`
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: colors.textMuted }}>Total Articles:</span>
- <span style={{ color: colors.text }}>{newsArticles.length}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: colors.textMuted }}>Breaking News:</span>
- <span style={{ color: colors.alert }}>{breakingCount}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: colors.textMuted }}>Earnings Reports:</span>
- <span style={{ color: colors.info }}>{earningsCount}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: colors.textMuted }}>Economic Data:</span>
- <span style={{ color: colors.purple }}>{economicCount}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: colors.textMuted }}>High Priority:</span>
- <span style={{ color: colors.primary }}>{alertCount}</span>
+ {/* Entities */}
+ {analysisData.analysis.entities.organizations.length > 0 && (
+ <div>
+ <div style={{ fontSize: '7px', color: F.GRAY, fontWeight: 700, marginBottom: '2px' }}>ORGANIZATIONS</div>
+ {analysisData.analysis.entities.organizations.map((org, i) => (
+ <div key={i} style={{ padding: '3px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px', fontSize: '7px', marginBottom: '2px' }}>
+ <span style={{ color: F.WHITE, fontWeight: 700 }}>{org.name}</span>
+ <span style={{ color: F.GRAY, marginLeft: '4px' }}>{org.sector} {org.ticker ? `| ${org.ticker}` : ''}</span>
+ </div>
+ ))}
+ </div>
+ )}
</div>
- </div>
- </div>
-
- <div style={{
- padding: '12px',
- background: 'rgba(147, 51, 234, 0.1)',
- border: `1px solid #9333ea`,
- textAlign: 'center',
- fontSize: '10px',
- color: colors.textMuted
- }}>
- Select an article and click AI ANALYZE for detailed insights
- </div>
- </>
- )}
- </div>
-
- {/* Tertiary News Feed */}
- <div style={{
- borderTop: `2px solid ${colors.textMuted}`,
- paddingTop: '4px',
- marginTop: '12px',
- flex: '0 0 auto',
- maxHeight: '300px',
- overflowY: 'auto'
- }}>
- <div style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
- {t('feeds.additional')}
+ )}
+ </>
+ )}
</div>
- <div style={{ borderBottom: `1px solid ${colors.textMuted}`, marginBottom: '4px' }}></div>
-
- {filteredNews.slice(Math.ceil(filteredNews.length * 2 / 3)).map((article, index) => (
- <div key={article.id} style={{
- marginBottom: '6px',
- borderLeft: `3px solid ${getPriorityColor(article.priority)}`,
- paddingLeft: '4px',
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- cursor: article.link ? 'pointer' : 'default'
- }}
- onClick={() => setSelectedArticle(article)}
- >
- <div style={{ display: 'flex', gap: '4px', marginBottom: '1px', fontSize: '8px' }}>
- <span style={{ color: colors.textMuted, minWidth: '50px' }}>{article.time}</span>
- <span style={{ color: getPriorityColor(article.priority), fontWeight: 'bold', minWidth: '60px' }}>
- [{article.priority}]
- </span>
- <span style={{ color: colors.info, minWidth: '50px' }}>[{article.category}]</span>
- </div>
-
- <div style={{ color: colors.text, fontWeight: 'bold', fontSize: '10px', lineHeight: '1.2', marginBottom: '2px' }}>
- {article.headline}
- </div>
-
- <div style={{ color: colors.textMuted, fontSize: '9px', lineHeight: '1.2', marginBottom: '2px' }}>
- {article.summary.slice(0, 150)}...
- </div>
-
- <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '8px' }}>
- <span style={{ color: colors.accent }}>{article.source}</span>
- <span style={{ color: getArticleSentimentColor(article.sentiment) }}>{article.sentiment}</span>
- </div>
- </div>
- ))}
- </div>
- </div>
+ </>
+ ) : (
+ /* No article selected */
+ <>
+ <SectionHead title="ARTICLE DETAIL" />
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: F.MUTED, padding: '20px', textAlign: 'center' }}>
+ <Newspaper size={20} style={{ marginBottom: '8px', opacity: 0.3 }} />
+ <div style={{ fontSize: '9px', fontWeight: 700, marginBottom: '4px' }}>SELECT AN ARTICLE</div>
+ <div style={{ fontSize: '8px' }}>Click any row in the feed to view details, read the full article, or run AI analysis.</div>
+ </div>
+ </>
+ )}
</div>
</div>
- {/* Status Bar */}
+ {/* ── STATUS BAR ── */}
<div style={{
- borderTop: `1px solid ${colors.textMuted}`,
- backgroundColor: colors.panel,
- padding: '2px 8px',
- fontSize: '10px',
- color: colors.textMuted,
- flexShrink: 0
+ backgroundColor: F.HEADER_BG, borderTop: `1px solid ${F.BORDER}`,
+ padding: '2px 12px', fontSize: '8px', color: F.GRAY, flexShrink: 0,
+ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
}}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <div style={{ display: 'flex', gap: '16px' }}>
- <span>FinceptTerminal Professional News v1.0.0 | Real-time from {feedCount} RSS feeds</span>
- <span>Articles: {newsArticles.length} | Filter: {activeFilter} | Updates: {newsUpdateCount}</span>
- </div>
- <div style={{ display: 'flex', gap: '16px' }}>
- <span>High Priority: {alertCount} | Sentiment: {sentimentScore}</span>
- <span>Session: {currentTime.toTimeString().substring(0, 8)}</span>
- <span style={{ color: loading ? colors.warning : colors.secondary }}>
- {loading ? 'UPDATING...' : 'FEED: LIVE'}
- </span>
- </div>
+ <div style={{ display: 'flex', gap: '12px' }}>
+ <span>FINCEPT NEWS v1.0</span>
+ <span style={{ color: F.BORDER }}>|</span>
+ <span>FEEDS:<span style={{ color: F.CYAN }}>{feedCount}</span></span>
+ <span style={{ color: F.BORDER }}>|</span>
+ <span>ART:<span style={{ color: F.CYAN }}>{newsArticles.length}</span></span>
+ <span style={{ color: F.BORDER }}>|</span>
+ <span>FLT:<span style={{ color: F.ORANGE }}>{activeFilter}</span></span>
+ <span style={{ color: F.BORDER }}>|</span>
+ <span>UPD:<span style={{ color: F.CYAN }}>{newsUpdateCount}</span></span>
</div>
- </div>
-
- {/* Article Detail Modal */}
- {selectedArticle && (
- <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
- }}
- onClick={() => setSelectedArticle(null)}
- >
- <div id="news-article-detail" style={{
- backgroundColor: colors.panel,
- border: `2px solid ${colors.primary}`,
- borderRadius: '4px',
- width: showWebView ? '90vw' : '600px',
- maxWidth: '95vw',
- height: showWebView ? '90vh' : 'auto',
- maxHeight: '90vh',
- display: 'flex',
- flexDirection: 'column',
- overflow: 'hidden',
- boxShadow: `0 0 20px ${colors.primary}`,
- transition: 'all 0.3s ease'
- }}
- onClick={(e) => e.stopPropagation()}
- >
- {/* Modal Header */}
- <div style={{
- backgroundColor: colors.background,
- borderBottom: `2px solid ${colors.primary}`,
- padding: '8px 12px',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', gap: '8px', alignItems: 'center', fontSize: '11px' }}>
- <span style={{ color: colors.primary, fontWeight: 'bold' }}>ARTICLE DETAILS</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: getPriorityColor(selectedArticle.priority), fontWeight: 'bold' }}>
- [{selectedArticle.priority}]
- </span>
- <span style={{ color: colors.info }}>[{selectedArticle.category}]</span>
- </div>
- <button
- onClick={() => {
- setSelectedArticle(null);
- setShowWebView(false);
- }}
- style={{
- backgroundColor: colors.alert,
- color: colors.text,
- border: 'none',
- padding: '4px 8px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- borderRadius: '2px'
- }}
- >
- ✕ CLOSE
- </button>
- </div>
-
- {/* Modal Content */}
- <div style={{
- padding: showWebView ? '0' : '12px',
- overflow: 'auto',
- flex: 1,
- display: 'flex',
- flexDirection: 'column'
- }}>
- {/* Reader View */}
- {showWebView && selectedArticle.link ? (
- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
- {/* Reader View Header */}
- <div style={{
- backgroundColor: colors.background,
- padding: '8px',
- borderBottom: `1px solid ${colors.textMuted}`,
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- fontSize: '10px'
- }}>
- <button
- onClick={() => setShowWebView(false)}
- style={{
- backgroundColor: colors.primary,
- color: colors.background,
- border: 'none',
- padding: '4px 8px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- borderRadius: '2px'
- }}
- >
- ← BACK TO SUMMARY
- </button>
- <span style={{ color: colors.textMuted }}>|</span>
- <span style={{ color: colors.warning, fontWeight: 'bold' }}>READER VIEW</span>
- <span style={{ color: colors.textMuted }}>|</span>
- <span style={{ color: colors.text, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
- {selectedArticle.source}
- </span>
- <button
- onClick={async () => {
- if (window.__TAURI__) {
- const { openUrl } = await import('@tauri-apps/plugin-opener');
- await openUrl(selectedArticle.link!);
- } else {
- window.open(selectedArticle.link, '_blank');
- }
- }}
- style={{
- backgroundColor: colors.info,
- color: colors.text,
- border: 'none',
- padding: '4px 8px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- borderRadius: '2px'
- }}
- >
- 🔗 OPEN FULL ARTICLE
- </button>
- </div>
-
- {/* Reader View Content */}
- <div style={{
- flex: 1,
- overflow: 'auto',
- padding: '24px',
- backgroundColor: '#1a1a1a',
- color: '#e0e0e0'
- }}>
- {/* Article Header */}
- <div style={{
- marginBottom: '24px',
- paddingBottom: '16px',
- borderBottom: `2px solid ${colors.primary}`
- }}>
- <div style={{
- display: 'flex',
- gap: '8px',
- marginBottom: '12px',
- fontSize: '11px'
- }}>
- <span style={{
- backgroundColor: getPriorityColor(selectedArticle.priority),
- color: colors.background,
- padding: '2px 8px',
- borderRadius: '2px',
- fontWeight: 'bold'
- }}>
- {selectedArticle.priority}
- </span>
- <span style={{
- backgroundColor: colors.info,
- color: colors.text,
- padding: '2px 8px',
- borderRadius: '2px',
- fontWeight: 'bold'
- }}>
- {selectedArticle.category}
- </span>
- <span style={{
- backgroundColor: getArticleSentimentColor(selectedArticle.sentiment),
- color: colors.background,
- padding: '2px 8px',
- borderRadius: '2px',
- fontWeight: 'bold'
- }}>
- {selectedArticle.sentiment}
- </span>
- </div>
-
- <h1 style={{
- fontSize: '24px',
- fontWeight: 'bold',
- lineHeight: '1.3',
- marginBottom: '12px',
- color: colors.text
- }}>
- {selectedArticle.headline}
- </h1>
-
- <div style={{
- display: 'flex',
- gap: '16px',
- fontSize: '12px',
- color: colors.textMuted
- }}>
- <span>📰 {selectedArticle.source}</span>
- <span>🕒 {selectedArticle.time}</span>
- <span>🌍 {selectedArticle.region}</span>
- {selectedArticle.tickers && selectedArticle.tickers.length > 0 && (
- <span>📊 {selectedArticle.tickers.join(', ')}</span>
- )}
- </div>
- </div>
-
- {/* Article Content */}
- <div style={{
- fontSize: '16px',
- lineHeight: '1.8',
- color: '#d0d0d0',
- maxWidth: '800px',
- margin: '0 auto'
- }}>
- <p style={{ marginBottom: '16px', fontSize: '18px', fontWeight: '500', color: '#e0e0e0' }}>
- {selectedArticle.summary}
- </p>
-
- <div style={{
- backgroundColor: 'rgba(255, 165, 0, 0.1)',
- border: `1px solid ${colors.primary}`,
- borderRadius: '4px',
- padding: '16px',
- marginTop: '24px'
- }}>
- <p style={{ fontSize: '14px', color: colors.warning, marginBottom: '8px', fontWeight: 'bold' }}>
- ℹ️ Reader View Limitation
- </p>
- <p style={{ fontSize: '13px', lineHeight: '1.6', color: colors.textMuted, marginBottom: '12px' }}>
- Most news websites block embedding for security reasons. This reader view shows the article summary from the RSS feed.
- </p>
- <p style={{ fontSize: '13px', lineHeight: '1.6', color: colors.textMuted }}>
- For the complete article with images, videos, and full content, please click the "🔗 OPEN FULL ARTICLE" button above to view it in your browser.
- </p>
- </div>
- </div>
- </div>
- </div>
- ) : (
- <>
- {/* Article Metadata */}
- <div style={{
- display: 'grid',
- gridTemplateColumns: '1fr 1fr',
- gap: '8px',
- marginBottom: '12px',
- padding: '8px',
- backgroundColor: 'rgba(255, 165, 0, 0.05)',
- border: `1px solid ${colors.textMuted}`,
- fontSize: '10px'
- }}>
- <div>
- <span style={{ color: colors.textMuted }}>SOURCE: </span>
- <span style={{ color: colors.accent, fontWeight: 'bold' }}>{selectedArticle.source}</span>
- </div>
- <div>
- <span style={{ color: colors.textMuted }}>TIME: </span>
- <span style={{ color: colors.text }}>{selectedArticle.time}</span>
- </div>
- <div>
- <span style={{ color: colors.textMuted }}>REGION: </span>
- <span style={{ color: colors.purple }}>{selectedArticle.region}</span>
- </div>
- <div>
- <span style={{ color: colors.textMuted }}>SENTIMENT: </span>
- <span style={{ color: getArticleSentimentColor(selectedArticle.sentiment), fontWeight: 'bold' }}>
- {selectedArticle.sentiment}
- </span>
- </div>
- <div>
- <span style={{ color: colors.textMuted }}>IMPACT: </span>
- <span style={{ color: getImpactColor(selectedArticle.impact), fontWeight: 'bold' }}>
- {selectedArticle.impact}
- </span>
- </div>
- {selectedArticle.tickers && selectedArticle.tickers.length > 0 && (
- <div>
- <span style={{ color: colors.textMuted }}>TICKERS: </span>
- <span style={{ color: colors.secondary, fontWeight: 'bold' }}>
- {selectedArticle.tickers.join(', ')}
- </span>
- </div>
- )}
- </div>
-
- {/* Article Headline */}
- <div style={{
- color: colors.text,
- fontSize: '14px',
- fontWeight: 'bold',
- lineHeight: '1.4',
- marginBottom: '12px',
- padding: '8px',
- backgroundColor: 'rgba(255, 255, 255, 0.05)',
- borderLeft: `4px solid ${getPriorityColor(selectedArticle.priority)}`
- }}>
- {selectedArticle.headline}
- </div>
-
- {/* Article Summary */}
- <div style={{
- color: colors.textMuted,
- fontSize: '12px',
- lineHeight: '1.6',
- marginBottom: '16px'
- }}>
- {selectedArticle.summary}
- </div>
-
- {/* Action Buttons */}
- {selectedArticle.link && (
- <div style={{
- display: 'flex',
- gap: '8px',
- paddingTop: '12px',
- borderTop: `1px solid ${colors.textMuted}`
- }}>
- <button
- onClick={(e) => {
- e.stopPropagation();
- setShowWebView(true);
- }}
- style={{
- backgroundColor: colors.secondary,
- color: colors.background,
- border: 'none',
- padding: '6px 12px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- borderRadius: '2px',
- flex: 1
- }}
- >
- READ IN APP
- </button>
- <button
- onClick={async (e) => {
- e.stopPropagation();
- const link = selectedArticle.link;
-
- if (!link) {
- return;
- }
-
- try {
- if (window.__TAURI__) {
- const { openUrl } = await import('@tauri-apps/plugin-opener');
- await openUrl(link);
- } else {
- const a = document.createElement('a');
- a.href = link;
- a.target = '_blank';
- a.rel = 'noopener noreferrer';
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- }
- } catch (error) {
- await navigator.clipboard.writeText(link);
- }
- }}
- style={{
- backgroundColor: colors.info,
- color: colors.text,
- border: 'none',
- padding: '6px 12px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- borderRadius: '2px',
- flex: 1
- }}
- >
- OPEN IN BROWSER
- </button>
- <button
- onClick={(e) => {
- e.stopPropagation();
- const link = selectedArticle.link;
- if (link) {
- navigator.clipboard.writeText(link);
- e.currentTarget.textContent = 'COPIED!';
- setTimeout(() => {
- e.currentTarget.textContent = 'COPY LINK';
- }, 2000);
- }
- }}
- style={{
- backgroundColor: colors.textMuted,
- color: colors.text,
- border: 'none',
- padding: '6px 12px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- borderRadius: '2px'
- }}
- title="Copy link to clipboard"
- >
- COPY LINK
- </button>
- <button
- onClick={(e) => {
- e.stopPropagation();
- handleAnalyzeArticle();
- }}
- disabled={analyzingArticle}
- style={{
- backgroundColor: analyzingArticle ? colors.textMuted : '#9333ea',
- color: colors.text,
- border: 'none',
- padding: '6px 12px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: analyzingArticle ? 'not-allowed' : 'pointer',
- borderRadius: '2px',
- opacity: analyzingArticle ? 0.6 : 1
- }}
- title="AI-powered analysis (10 credits)"
- >
- {analyzingArticle ? 'ANALYZING...' : 'AI ANALYZE'}
- </button>
- </div>
- )}
- </>
- )}
- </div>
- </div>
+ <div style={{ display: 'flex', gap: '12px' }}>
+ <span>PRI:<span style={{ color: F.RED }}>{alertCount}</span></span>
+ <span style={{ color: F.BORDER }}>|</span>
+ <span>SNT:<span style={{ color: parseFloat(score) > 0 ? F.GREEN : parseFloat(score) < 0 ? F.RED : F.YELLOW }}>{score}</span></span>
+ <span style={{ color: F.BORDER }}>|</span>
+ <span>{currentTime.toTimeString().substring(0, 8)}</span>
+ <span style={{ color: F.BORDER }}>|</span>
+ <span style={{ color: loading ? F.YELLOW : F.GREEN, fontWeight: 700 }}>{loading ? 'UPD' : 'LIVE'}</span>
</div>
- )}
+ </div>
- {/* CSS for animations and transparent scrollbars */}
+ {/* ── CSS ── */}
<style>{`
- .ticker-wrap {
- width: 100%;
- overflow: hidden;
- background-color: transparent;
- padding: 0;
- }
-
- .ticker-move {
- display: inline-block;
- white-space: nowrap;
- animation: tickerScroll ${tickerDuration}s linear infinite;
- padding-right: 100%;
- }
-
- .ticker-item {
- display: inline-block;
- padding-right: 3em;
- color: ${colors.text};
- font-size: 11px;
- white-space: nowrap;
- }
-
- @keyframes tickerScroll {
- 0% {
- transform: translateX(0);
- }
- 100% {
- transform: translateX(-50%);
- }
- }
-
- @keyframes blink {
- 0%, 50% { opacity: 1; }
- 51%, 100% { opacity: 0.3; }
- }
-
- /* Transparent scrollbars for all browsers */
- * {
- scrollbar-width: thin;
- scrollbar-color: rgba(120, 120, 120, 0.3) transparent;
- }
-
- *::-webkit-scrollbar {
- width: 8px;
- height: 8px;
- }
-
- *::-webkit-scrollbar-track {
- background: transparent;
- }
-
- *::-webkit-scrollbar-thumb {
- background-color: rgba(120, 120, 120, 0.3);
- border-radius: 4px;
- border: 2px solid transparent;
- }
-
- *::-webkit-scrollbar-thumb:hover {
- background-color: rgba(120, 120, 120, 0.5);
- }
-
- *::-webkit-scrollbar-corner {
- background: transparent;
- }
+ .ticker-wrap{width:100%;overflow:hidden;background:transparent;padding:0}
+ .ticker-move{display:inline-block;white-space:nowrap;animation:tickerScroll ${tickerDur}s linear infinite;padding-right:100%}
+ .ticker-item{display:inline-block;padding-right:3em;color:${F.WHITE};font-size:9px;white-space:nowrap;font-family:${FONT}}
+ @keyframes tickerScroll{0%{transform:translateX(0)}100%{transform:translateX(-50%)}}
+ @keyframes blink{0%,50%{opacity:1}51%,100%{opacity:.3}}
+ *::-webkit-scrollbar{width:5px;height:5px}
+ *::-webkit-scrollbar-track{background:${F.DARK_BG}}
+ *::-webkit-scrollbar-thumb{background:${F.BORDER};border-radius:3px}
+ *::-webkit-scrollbar-thumb:hover{background:${F.MUTED}}
`}</style>
- {/* RSS Feed Settings Modal */}
- <RSSFeedSettingsModal
- isOpen={showFeedSettings}
- onClose={() => setShowFeedSettings(false)}
- onFeedsUpdated={() => handleRefresh(true)}
- />
+ <RSSFeedSettingsModal isOpen={showFeedSettings} onClose={() => setShowFeedSettings(false)} onFeedsUpdated={() => handleRefresh(true)} />
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/tabs/news/RSSFeedSettingsModal.tsx b/fincept-terminal-desktop/src/components/tabs/news/RSSFeedSettingsModal.tsx
index ffd3dc112..435382553 100644
--- a/fincept-terminal-desktop/src/components/tabs/news/RSSFeedSettingsModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/news/RSSFeedSettingsModal.tsx
@@ -1,7 +1,6 @@
// RSS Feed Settings Modal - Allows users to manage their RSS news sources
import React, { useState, useEffect } from 'react';
import { Plus, Trash2, Edit2, Check, X, ExternalLink, RefreshCw, AlertCircle } from 'lucide-react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
import {
getUserRSSFeeds,
getDefaultFeeds,
@@ -23,6 +22,27 @@ import {
type RSSFeed,
} from '@/services/news/rssFeedService';
+// FINCEPT Design System Colors
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
+};
+
+const FONT_FAMILY = '"IBM Plex Mono", "Consolas", monospace';
+
interface RSSFeedSettingsModalProps {
isOpen: boolean;
onClose: () => void;
@@ -34,16 +54,12 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
onClose,
onFeedsUpdated,
}) => {
- const { colors } = useTerminalTheme();
-
- // State
const [activeTab, setActiveTab] = useState<'user' | 'default'>('user');
const [userFeeds, setUserFeeds] = useState<UserRSSFeed[]>([]);
const [defaultFeeds, setDefaultFeeds] = useState<RSSFeed[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
- // Add/Edit form state
const [showAddForm, setShowAddForm] = useState(false);
const [editingFeed, setEditingFeed] = useState<UserRSSFeed | null>(null);
const [formData, setFormData] = useState({
@@ -59,7 +75,6 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
const [submitting, setSubmitting] = useState(false);
const [deletedDefaultCount, setDeletedDefaultCount] = useState(0);
- // Load feeds
useEffect(() => {
if (isOpen) {
loadFeeds();
@@ -86,7 +101,6 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}
};
- // Test URL
const handleTestUrl = async () => {
if (!isValidRSSUrl(formData.url)) {
setFormError('Please enter a valid URL');
@@ -110,7 +124,6 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}
};
- // Add feed
const handleAddFeed = async () => {
if (!formData.name.trim()) {
setFormError('Name is required');
@@ -145,7 +158,6 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}
};
- // Update feed
const handleUpdateFeed = async () => {
if (!editingFeed) return;
if (!formData.name.trim()) {
@@ -182,7 +194,6 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}
};
- // Delete feed
const handleDeleteFeed = async (id: string) => {
if (!confirm('Are you sure you want to delete this RSS feed?')) return;
try {
@@ -194,7 +205,6 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}
};
- // Toggle user feed
const handleToggleFeed = async (id: string, enabled: boolean) => {
try {
await toggleUserRSSFeed(id, enabled);
@@ -207,7 +217,6 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}
};
- // Toggle default feed
const handleToggleDefaultFeed = async (feedId: string, enabled: boolean) => {
try {
await toggleDefaultRSSFeed(feedId, enabled);
@@ -220,7 +229,6 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}
};
- // Delete default feed
const handleDeleteDefaultFeed = async (feedId: string) => {
try {
await deleteDefaultRSSFeed(feedId);
@@ -232,7 +240,6 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}
};
- // Restore all default feeds
const handleRestoreAllDefaults = async () => {
try {
await restoreAllDefaultFeeds();
@@ -243,7 +250,6 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
}
};
- // Edit feed
const handleEditFeed = (feed: UserRSSFeed) => {
setEditingFeed(feed);
setFormData({
@@ -258,7 +264,6 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
setTestResult(null);
};
- // Reset form
const resetForm = () => {
setShowAddForm(false);
setEditingFeed(null);
@@ -288,51 +293,51 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
alignItems: 'center',
justifyContent: 'center',
zIndex: 10000,
+ fontFamily: FONT_FAMILY,
}}
onClick={onClose}
>
<div
style={{
- backgroundColor: colors.panel,
- border: `2px solid ${colors.primary}`,
- borderRadius: '4px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.ORANGE}`,
+ borderRadius: '2px',
width: '800px',
maxWidth: '95vw',
maxHeight: '85vh',
display: 'flex',
flexDirection: 'column',
- boxShadow: 'none',
}}
onClick={e => e.stopPropagation()}
>
{/* Header */}
<div
style={{
- backgroundColor: colors.background,
- borderBottom: `2px solid ${colors.primary}`,
- padding: '12px 16px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,
+ padding: '10px 16px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '14px' }}>
+ <span style={{ color: FINCEPT.ORANGE, fontWeight: 700, fontSize: '11px', letterSpacing: '0.5px' }}>
RSS FEED SETTINGS
</span>
- <span style={{ color: colors.textMuted, fontSize: '11px' }}>
- Manage your news sources
+ <span style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>
+ MANAGE YOUR NEWS SOURCES
</span>
</div>
<button
onClick={onClose}
style={{
- backgroundColor: colors.alert,
- color: colors.text,
+ padding: '4px 10px',
+ backgroundColor: FINCEPT.RED,
+ color: FINCEPT.WHITE,
border: 'none',
- padding: '6px 12px',
- fontSize: '11px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
cursor: 'pointer',
borderRadius: '2px',
display: 'flex',
@@ -340,7 +345,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
gap: '4px',
}}
>
- <X size={14} /> CLOSE
+ <X size={12} /> CLOSE
</button>
</div>
@@ -348,21 +353,21 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
<div
style={{
display: 'flex',
- borderBottom: `1px solid ${colors.textMuted}`,
- backgroundColor: colors.background,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.HEADER_BG,
}}
>
<button
onClick={() => setActiveTab('user')}
style={{
- padding: '10px 20px',
- backgroundColor: activeTab === 'user' ? colors.panel : 'transparent',
- color: activeTab === 'user' ? colors.primary : colors.textMuted,
+ padding: '8px 16px',
+ backgroundColor: activeTab === 'user' ? FINCEPT.ORANGE : 'transparent',
+ color: activeTab === 'user' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
border: 'none',
- borderBottom: activeTab === 'user' ? `2px solid ${colors.primary}` : 'none',
cursor: 'pointer',
- fontSize: '12px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
}}
>
MY FEEDS ({userFeeds.length})
@@ -370,14 +375,14 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
<button
onClick={() => setActiveTab('default')}
style={{
- padding: '10px 20px',
- backgroundColor: activeTab === 'default' ? colors.panel : 'transparent',
- color: activeTab === 'default' ? colors.primary : colors.textMuted,
+ padding: '8px 16px',
+ backgroundColor: activeTab === 'default' ? FINCEPT.ORANGE : 'transparent',
+ color: activeTab === 'default' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
border: 'none',
- borderBottom: activeTab === 'default' ? `2px solid ${colors.primary}` : 'none',
cursor: 'pointer',
- fontSize: '12px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
}}
>
DEFAULT FEEDS ({defaultFeeds.length})
@@ -387,12 +392,34 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{/* Content */}
<div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
{loading ? (
- <div style={{ textAlign: 'center', padding: '40px', color: colors.textMuted }}>
- Loading feeds...
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ color: FINCEPT.MUTED,
+ fontSize: '10px',
+ textAlign: 'center',
+ padding: '40px',
+ }}>
+ <RefreshCw size={20} style={{ marginBottom: '8px', opacity: 0.5 }} className="animate-spin" />
+ <span>Loading feeds...</span>
</div>
) : error ? (
- <div style={{ textAlign: 'center', padding: '40px', color: colors.alert }}>
- {error}
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ color: FINCEPT.RED,
+ fontSize: '10px',
+ textAlign: 'center',
+ padding: '40px',
+ }}>
+ <AlertCircle size={20} style={{ marginBottom: '8px', opacity: 0.5 }} />
+ <span>{error}</span>
</div>
) : activeTab === 'user' ? (
<>
@@ -402,55 +429,55 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
style={{
textAlign: 'center',
padding: '40px 20px',
- backgroundColor: 'rgba(255, 200, 0, 0.05)',
- border: `1px dashed ${colors.warning}`,
- borderRadius: '4px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.YELLOW}`,
+ borderRadius: '2px',
marginBottom: '16px',
}}
>
- <AlertCircle size={32} style={{ color: colors.warning, marginBottom: '12px' }} />
- <div style={{ color: colors.text, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
- No RSS Feeds Available
+ <AlertCircle size={24} style={{ color: FINCEPT.YELLOW, marginBottom: '12px' }} />
+ <div style={{ color: FINCEPT.WHITE, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
+ NO RSS FEEDS AVAILABLE
</div>
- <div style={{ color: colors.textMuted, fontSize: '12px', marginBottom: '16px' }}>
- All feeds have been deleted. Add a new feed or restore defaults to see news.
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px', marginBottom: '16px' }}>
+ All feeds have been deleted. Add a new feed or restore defaults.
</div>
- <div style={{ display: 'flex', gap: '12px', justifyContent: 'center' }}>
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>
<button
onClick={() => setShowAddForm(true)}
style={{
- padding: '10px 20px',
- backgroundColor: colors.secondary,
- color: colors.background,
+ padding: '8px 16px',
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
border: 'none',
- borderRadius: '4px',
+ borderRadius: '2px',
cursor: 'pointer',
- fontSize: '12px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
display: 'flex',
alignItems: 'center',
- gap: '6px',
+ gap: '4px',
}}
>
- <Plus size={14} /> ADD NEW FEED
+ <Plus size={12} /> ADD NEW FEED
</button>
<button
onClick={handleRestoreAllDefaults}
style={{
- padding: '10px 20px',
- backgroundColor: colors.info,
- color: colors.text,
- border: 'none',
- borderRadius: '4px',
+ padding: '8px 16px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ borderRadius: '2px',
cursor: 'pointer',
- fontSize: '12px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
display: 'flex',
alignItems: 'center',
- gap: '6px',
+ gap: '4px',
}}
>
- <RefreshCw size={14} /> RESTORE DEFAULTS
+ <RefreshCw size={12} /> RESTORE DEFAULTS
</button>
</div>
</div>
@@ -462,22 +489,24 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
onClick={() => setShowAddForm(true)}
style={{
width: '100%',
- padding: '12px',
- backgroundColor: 'rgba(0, 255, 0, 0.1)',
- border: `1px dashed ${colors.secondary}`,
- borderRadius: '4px',
- color: colors.secondary,
+ padding: '10px',
+ backgroundColor: 'transparent',
+ border: `1px dashed ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ color: FINCEPT.GRAY,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- gap: '8px',
- fontSize: '12px',
- fontWeight: 'bold',
- marginBottom: '16px',
+ gap: '6px',
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '12px',
+ transition: 'all 0.2s',
+ letterSpacing: '0.5px',
}}
>
- <Plus size={16} /> ADD NEW RSS FEED
+ <Plus size={12} /> ADD NEW RSS FEED
</button>
)}
@@ -485,15 +514,15 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{showAddForm && (
<div
style={{
- padding: '16px',
- backgroundColor: colors.background,
- border: `1px solid ${colors.primary}`,
- borderRadius: '4px',
- marginBottom: '16px',
+ padding: '12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.ORANGE}`,
+ borderRadius: '2px',
+ marginBottom: '12px',
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
- <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '12px' }}>
+ <span style={{ color: FINCEPT.ORANGE, fontWeight: 700, fontSize: '9px', letterSpacing: '0.5px' }}>
{editingFeed ? 'EDIT RSS FEED' : 'ADD NEW RSS FEED'}
</span>
<button
@@ -501,37 +530,37 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
style={{
background: 'none',
border: 'none',
- color: colors.textMuted,
+ color: FINCEPT.GRAY,
cursor: 'pointer',
}}
>
- <X size={16} />
+ <X size={14} />
</button>
</div>
{formError && (
<div
style={{
- padding: '8px 12px',
- backgroundColor: 'rgba(255, 0, 0, 0.1)',
- border: `1px solid ${colors.alert}`,
+ padding: '6px 10px',
+ backgroundColor: `${FINCEPT.RED}20`,
+ color: FINCEPT.RED,
+ fontSize: '9px',
+ fontWeight: 700,
borderRadius: '2px',
- color: colors.alert,
- fontSize: '11px',
marginBottom: '12px',
display: 'flex',
alignItems: 'center',
- gap: '8px',
+ gap: '6px',
}}
>
- <AlertCircle size={14} /> {formError}
+ <AlertCircle size={12} /> {formError}
</div>
)}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
{/* Name */}
<div>
- <label style={{ color: colors.textMuted, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
DISPLAY NAME *
</label>
<input
@@ -541,19 +570,20 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
placeholder="e.g., Bloomberg Markets"
style={{
width: '100%',
- padding: '8px',
- backgroundColor: colors.panel,
- border: `1px solid ${colors.textMuted}`,
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
borderRadius: '2px',
- color: colors.text,
- fontSize: '12px',
+ fontSize: '10px',
+ fontFamily: FONT_FAMILY,
}}
/>
</div>
{/* Source Name */}
<div>
- <label style={{ color: colors.textMuted, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
SOURCE NAME (SHORT) *
</label>
<input
@@ -563,12 +593,13 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
placeholder="e.g., BLOOMBERG"
style={{
width: '100%',
- padding: '8px',
- backgroundColor: colors.panel,
- border: `1px solid ${colors.textMuted}`,
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
borderRadius: '2px',
- color: colors.text,
- fontSize: '12px',
+ fontSize: '10px',
+ fontFamily: FONT_FAMILY,
textTransform: 'uppercase',
}}
/>
@@ -576,7 +607,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{/* URL */}
<div style={{ gridColumn: '1 / -1' }}>
- <label style={{ color: colors.textMuted, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
RSS FEED URL *
</label>
<div style={{ display: 'flex', gap: '8px' }}>
@@ -590,32 +621,33 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
placeholder="https://example.com/rss/feed"
style={{
flex: 1,
- padding: '8px',
- backgroundColor: colors.panel,
- border: `1px solid ${testResult === true ? colors.secondary : testResult === false ? colors.alert : colors.textMuted}`,
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${testResult === true ? FINCEPT.GREEN : testResult === false ? FINCEPT.RED : FINCEPT.BORDER}`,
borderRadius: '2px',
- color: colors.text,
- fontSize: '12px',
+ fontSize: '10px',
+ fontFamily: FONT_FAMILY,
}}
/>
<button
onClick={handleTestUrl}
disabled={testing || !formData.url}
style={{
- padding: '8px 12px',
- backgroundColor: testing ? colors.textMuted : colors.info,
- color: colors.text,
+ padding: '8px 16px',
+ backgroundColor: testing ? FINCEPT.MUTED : FINCEPT.BLUE,
+ color: FINCEPT.WHITE,
border: 'none',
borderRadius: '2px',
cursor: testing || !formData.url ? 'not-allowed' : 'pointer',
- fontSize: '11px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
display: 'flex',
alignItems: 'center',
gap: '4px',
}}
>
- {testing ? <RefreshCw size={14} className="animate-spin" /> : testResult === true ? <Check size={14} /> : <ExternalLink size={14} />}
+ {testing ? <RefreshCw size={12} className="animate-spin" /> : testResult === true ? <Check size={12} /> : <ExternalLink size={12} />}
{testing ? 'TESTING...' : testResult === true ? 'VALID' : 'TEST URL'}
</button>
</div>
@@ -623,7 +655,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{/* Category */}
<div>
- <label style={{ color: colors.textMuted, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
CATEGORY
</label>
<select
@@ -631,12 +663,13 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
onChange={e => setFormData(prev => ({ ...prev, category: e.target.value }))}
style={{
width: '100%',
- padding: '8px',
- backgroundColor: colors.panel,
- border: `1px solid ${colors.textMuted}`,
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
borderRadius: '2px',
- color: colors.text,
- fontSize: '12px',
+ fontSize: '10px',
+ fontFamily: FONT_FAMILY,
}}
>
{RSS_CATEGORIES.map(cat => (
@@ -649,7 +682,7 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{/* Region */}
<div>
- <label style={{ color: colors.textMuted, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, display: 'block', marginBottom: '4px', letterSpacing: '0.5px' }}>
REGION
</label>
<select
@@ -657,12 +690,13 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
onChange={e => setFormData(prev => ({ ...prev, region: e.target.value }))}
style={{
width: '100%',
- padding: '8px',
- backgroundColor: colors.panel,
- border: `1px solid ${colors.textMuted}`,
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
borderRadius: '2px',
- color: colors.text,
- fontSize: '12px',
+ fontSize: '10px',
+ fontFamily: FONT_FAMILY,
}}
>
{RSS_REGIONS.map(reg => (
@@ -675,18 +709,18 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
</div>
{/* Submit Buttons */}
- <div style={{ display: 'flex', gap: '8px', marginTop: '16px', justifyContent: 'flex-end' }}>
+ <div style={{ display: 'flex', gap: '8px', marginTop: '12px', justifyContent: 'flex-end' }}>
<button
onClick={resetForm}
style={{
- padding: '8px 16px',
- backgroundColor: colors.textMuted,
- color: colors.text,
- border: 'none',
+ padding: '6px 12px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
borderRadius: '2px',
cursor: 'pointer',
- fontSize: '11px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
}}
>
CANCEL
@@ -695,14 +729,14 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
onClick={editingFeed ? handleUpdateFeed : handleAddFeed}
disabled={submitting}
style={{
- padding: '8px 16px',
- backgroundColor: submitting ? colors.textMuted : colors.secondary,
- color: colors.background,
+ padding: '6px 12px',
+ backgroundColor: submitting ? FINCEPT.MUTED : FINCEPT.ORANGE,
+ color: submitting ? FINCEPT.GRAY : FINCEPT.DARK_BG,
border: 'none',
borderRadius: '2px',
cursor: submitting ? 'not-allowed' : 'pointer',
- fontSize: '11px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
}}
>
{submitting ? 'SAVING...' : editingFeed ? 'UPDATE FEED' : 'ADD FEED'}
@@ -715,72 +749,53 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{userFeeds.length === 0 ? (
<div
style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ color: FINCEPT.MUTED,
+ fontSize: '10px',
textAlign: 'center',
padding: '40px',
- color: colors.textMuted,
- fontSize: '12px',
}}
>
- No custom feeds yet. Add your first RSS feed above!
+ <span>No custom feeds yet. Add your first RSS feed above.</span>
</div>
) : (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
{userFeeds.map(feed => (
<div
key={feed.id}
style={{
- padding: '12px',
- backgroundColor: feed.enabled ? colors.background : 'rgba(0,0,0,0.3)',
- border: `1px solid ${feed.enabled ? colors.textMuted : 'rgba(100,100,100,0.3)'}`,
- borderRadius: '4px',
- opacity: feed.enabled ? 1 : 0.6,
+ padding: '10px 12px',
+ backgroundColor: feed.enabled ? FINCEPT.DARK_BG : `${FINCEPT.MUTED}10`,
+ border: `1px solid ${feed.enabled ? FINCEPT.BORDER : FINCEPT.MUTED}`,
+ borderRadius: '2px',
+ opacity: feed.enabled ? 1 : 0.7,
+ transition: 'all 0.2s',
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
<div style={{ flex: 1 }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
- <span style={{ color: colors.text, fontWeight: 'bold', fontSize: '12px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' }}>
+ <span style={{ color: FINCEPT.WHITE, fontWeight: 700, fontSize: '10px' }}>
{feed.name}
</span>
- <span
- style={{
- padding: '2px 6px',
- backgroundColor: colors.info,
- color: colors.text,
- fontSize: '9px',
- fontWeight: 'bold',
- borderRadius: '2px',
- }}
- >
+ <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.CYAN}20`, color: FINCEPT.CYAN, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{feed.source_name}
</span>
- <span
- style={{
- padding: '2px 6px',
- backgroundColor: colors.purple,
- color: colors.text,
- fontSize: '9px',
- borderRadius: '2px',
- }}
- >
+ <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.PURPLE}20`, color: FINCEPT.PURPLE, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{getCategoryLabel(feed.category)}
</span>
- <span
- style={{
- padding: '2px 6px',
- backgroundColor: colors.warning,
- color: colors.background,
- fontSize: '9px',
- borderRadius: '2px',
- }}
- >
+ <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.YELLOW}20`, color: FINCEPT.YELLOW, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{getRegionLabel(feed.region)}
</span>
</div>
<div
style={{
- color: colors.textMuted,
- fontSize: '10px',
+ color: FINCEPT.MUTED,
+ fontSize: '9px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
@@ -790,50 +805,47 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{feed.url}
</div>
</div>
- <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
- {/* Toggle */}
+ <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
<button
onClick={() => handleToggleFeed(feed.id, !feed.enabled)}
style={{
padding: '4px 8px',
- backgroundColor: feed.enabled ? colors.secondary : colors.textMuted,
- color: feed.enabled ? colors.background : colors.text,
+ backgroundColor: feed.enabled ? FINCEPT.GREEN : FINCEPT.MUTED,
+ color: feed.enabled ? FINCEPT.DARK_BG : FINCEPT.GRAY,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
}}
>
{feed.enabled ? 'ON' : 'OFF'}
</button>
- {/* Edit */}
<button
onClick={() => handleEditFeed(feed)}
style={{
padding: '4px 8px',
- backgroundColor: colors.info,
- color: colors.text,
- border: 'none',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
borderRadius: '2px',
cursor: 'pointer',
}}
>
- <Edit2 size={14} />
+ <Edit2 size={12} />
</button>
- {/* Delete */}
<button
onClick={() => handleDeleteFeed(feed.id)}
style={{
padding: '4px 8px',
- backgroundColor: colors.alert,
- color: colors.text,
+ backgroundColor: FINCEPT.RED,
+ color: FINCEPT.WHITE,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
}}
>
- <Trash2 size={14} />
+ <Trash2 size={12} />
</button>
</div>
</div>
@@ -847,40 +859,40 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
<div>
<div
style={{
- padding: '12px',
- backgroundColor: 'rgba(0, 255, 0, 0.05)',
- border: `1px solid ${colors.secondary}`,
- borderRadius: '4px',
- marginBottom: '16px',
- color: colors.textMuted,
- fontSize: '11px',
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ marginBottom: '12px',
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<span>
- These are the default RSS feeds that come with Fincept Terminal. You can enable, disable, or delete them.
+ Default RSS feeds included with Fincept Terminal. Toggle or remove as needed.
</span>
{deletedDefaultCount > 0 && (
<button
onClick={handleRestoreAllDefaults}
style={{
- padding: '6px 12px',
- backgroundColor: colors.info,
- color: colors.text,
+ padding: '4px 10px',
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
display: 'flex',
alignItems: 'center',
gap: '4px',
whiteSpace: 'nowrap',
}}
>
- <RefreshCw size={12} /> RESTORE ALL ({deletedDefaultCount})
+ <RefreshCw size={10} /> RESTORE ALL ({deletedDefaultCount})
</button>
)}
</div>
@@ -891,110 +903,77 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
style={{
textAlign: 'center',
padding: '40px 20px',
- backgroundColor: 'rgba(255, 200, 0, 0.05)',
- border: `1px dashed ${colors.warning}`,
- borderRadius: '4px',
- marginBottom: '16px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.YELLOW}`,
+ borderRadius: '2px',
+ marginBottom: '12px',
}}
>
- <AlertCircle size={32} style={{ color: colors.warning, marginBottom: '12px' }} />
- <div style={{ color: colors.text, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
- All Default Feeds Deleted
+ <AlertCircle size={24} style={{ color: FINCEPT.YELLOW, marginBottom: '12px' }} />
+ <div style={{ color: FINCEPT.WHITE, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
+ ALL DEFAULT FEEDS DELETED
</div>
- <div style={{ color: colors.textMuted, fontSize: '12px', marginBottom: '16px' }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px', marginBottom: '16px' }}>
You have deleted all {deletedDefaultCount} default feeds. Click below to restore them.
</div>
<button
onClick={handleRestoreAllDefaults}
style={{
- padding: '10px 20px',
- backgroundColor: colors.info,
- color: colors.text,
+ padding: '8px 16px',
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
border: 'none',
- borderRadius: '4px',
+ borderRadius: '2px',
cursor: 'pointer',
- fontSize: '12px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
display: 'flex',
alignItems: 'center',
gap: '6px',
margin: '0 auto',
}}
>
- <RefreshCw size={14} /> RESTORE ALL DEFAULT FEEDS
+ <RefreshCw size={12} /> RESTORE ALL DEFAULT FEEDS
</button>
</div>
)}
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
{defaultFeeds.map(feed => (
<div
key={feed.id || feed.url}
style={{
- padding: '12px',
- backgroundColor: feed.enabled ? colors.background : 'rgba(0,0,0,0.3)',
- border: `1px solid ${feed.enabled ? colors.textMuted : 'rgba(100,100,100,0.3)'}`,
- borderRadius: '4px',
- opacity: feed.enabled ? 1 : 0.6,
+ padding: '10px 12px',
+ backgroundColor: feed.enabled ? FINCEPT.DARK_BG : `${FINCEPT.MUTED}10`,
+ border: `1px solid ${feed.enabled ? FINCEPT.BORDER : FINCEPT.MUTED}`,
+ borderRadius: '2px',
+ opacity: feed.enabled ? 1 : 0.7,
+ transition: 'all 0.2s',
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
<div style={{ flex: 1 }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
- <span style={{ color: colors.text, fontWeight: 'bold', fontSize: '12px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' }}>
+ <span style={{ color: FINCEPT.WHITE, fontWeight: 700, fontSize: '10px' }}>
{feed.name}
</span>
- <span
- style={{
- padding: '2px 6px',
- backgroundColor: colors.secondary,
- color: colors.background,
- fontSize: '9px',
- fontWeight: 'bold',
- borderRadius: '2px',
- }}
- >
+ <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.GREEN}20`, color: FINCEPT.GREEN, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
DEFAULT
</span>
- <span
- style={{
- padding: '2px 6px',
- backgroundColor: colors.info,
- color: colors.text,
- fontSize: '9px',
- fontWeight: 'bold',
- borderRadius: '2px',
- }}
- >
+ <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.CYAN}20`, color: FINCEPT.CYAN, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{feed.source}
</span>
- <span
- style={{
- padding: '2px 6px',
- backgroundColor: colors.purple,
- color: colors.text,
- fontSize: '9px',
- borderRadius: '2px',
- }}
- >
+ <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.PURPLE}20`, color: FINCEPT.PURPLE, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{getCategoryLabel(feed.category)}
</span>
- <span
- style={{
- padding: '2px 6px',
- backgroundColor: colors.warning,
- color: colors.background,
- fontSize: '9px',
- borderRadius: '2px',
- }}
- >
+ <span style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.YELLOW}20`, color: FINCEPT.YELLOW, fontSize: '8px', fontWeight: 700, borderRadius: '2px' }}>
{getRegionLabel(feed.region)}
</span>
</div>
<div
style={{
- color: colors.textMuted,
- fontSize: '10px',
+ color: FINCEPT.MUTED,
+ fontSize: '9px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
@@ -1004,36 +983,34 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
{feed.url}
</div>
</div>
- <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
- {/* Toggle */}
+ <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
<button
onClick={() => feed.id && handleToggleDefaultFeed(feed.id, !feed.enabled)}
style={{
padding: '4px 8px',
- backgroundColor: feed.enabled ? colors.secondary : colors.textMuted,
- color: feed.enabled ? colors.background : colors.text,
+ backgroundColor: feed.enabled ? FINCEPT.GREEN : FINCEPT.MUTED,
+ color: feed.enabled ? FINCEPT.DARK_BG : FINCEPT.GRAY,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 'bold',
+ fontSize: '9px',
+ fontWeight: 700,
}}
>
{feed.enabled ? 'ON' : 'OFF'}
</button>
- {/* Delete */}
<button
onClick={() => feed.id && handleDeleteDefaultFeed(feed.id)}
style={{
padding: '4px 8px',
- backgroundColor: colors.alert,
- color: colors.text,
+ backgroundColor: FINCEPT.RED,
+ color: FINCEPT.WHITE,
border: 'none',
borderRadius: '2px',
cursor: 'pointer',
}}
>
- <Trash2 size={14} />
+ <Trash2 size={12} />
</button>
</div>
</div>
@@ -1044,38 +1021,43 @@ const RSSFeedSettingsModal: React.FC<RSSFeedSettingsModalProps> = ({
)}
</div>
- {/* Footer */}
+ {/* Footer / Status Bar */}
<div
style={{
- borderTop: `1px solid ${colors.textMuted}`,
- padding: '10px 16px',
- backgroundColor: colors.background,
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ padding: '6px 16px',
+ backgroundColor: FINCEPT.HEADER_BG,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
- fontSize: '10px',
- color: colors.textMuted,
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
}}
>
<span>
- Total Sources: {defaultFeeds.length + userFeeds.filter(f => f.enabled).length} active ({defaultFeeds.length} default + {userFeeds.filter(f => f.enabled).length} custom)
+ TOTAL: <span style={{ color: FINCEPT.CYAN }}>{defaultFeeds.length + userFeeds.filter(f => f.enabled).length}</span> ACTIVE
+ <span style={{ color: FINCEPT.BORDER }}> | </span>
+ <span style={{ color: FINCEPT.CYAN }}>{defaultFeeds.length}</span> DEFAULT
+ <span style={{ color: FINCEPT.BORDER }}> | </span>
+ <span style={{ color: FINCEPT.CYAN }}>{userFeeds.filter(f => f.enabled).length}</span> CUSTOM
</span>
<button
onClick={loadFeeds}
style={{
- padding: '4px 8px',
- backgroundColor: colors.info,
- color: colors.text,
- border: 'none',
+ padding: '4px 10px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
borderRadius: '2px',
cursor: 'pointer',
- fontSize: '10px',
+ fontSize: '9px',
+ fontWeight: 700,
display: 'flex',
alignItems: 'center',
gap: '4px',
}}
>
- <RefreshCw size={12} /> REFRESH
+ <RefreshCw size={10} /> REFRESH
</button>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/components/NoteEditor.tsx b/fincept-terminal-desktop/src/components/tabs/notes/components/NoteEditor.tsx
index a49f4e86f..46db583a3 100644
--- a/fincept-terminal-desktop/src/components/tabs/notes/components/NoteEditor.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/notes/components/NoteEditor.tsx
@@ -242,7 +242,7 @@ export const NoteEditor: React.FC<NoteEditorProps> = ({
{/* Reminder Date */}
<div style={{ marginBottom: '12px' }}>
<label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
- REMINDER DATE
+ REMINDER DATE (Click to select)
</label>
<input
type="datetime-local"
@@ -255,8 +255,11 @@ export const NoteEditor: React.FC<NoteEditorProps> = ({
border: `1px solid ${FINCEPT.BORDER}`,
color: FINCEPT.WHITE,
fontSize: '10px',
- outline: 'none'
+ outline: 'none',
+ cursor: 'pointer',
+ colorScheme: 'dark'
}}
+ placeholder="Select date and time"
/>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx
index 451618f3b..df3c6634d 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx
@@ -1,6 +1,6 @@
/**
* Portfolio Management Tab - Fincept Terminal Style
- * Professional portfolio tracking and analytics interface
+ * Three-panel terminal layout with professional portfolio tracking and analytics
*/
import React, { useState, useEffect } from 'react';
@@ -27,7 +27,7 @@ import ConfirmDeleteModal from './modals/ConfirmDeleteModal';
import { usePortfolioOperations } from './hooks/usePortfolioOperations';
import { formatCurrency, formatPercent } from './portfolio/utils';
import { TabFooter } from '@/components/common/TabFooter';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS, COMMON_STYLES } from './finceptStyles';
+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS, COMMON_STYLES, LAYOUT } from './finceptStyles';
type SubTab = 'positions' | 'history' | 'analytics' | 'sectors' | 'performance' | 'risk' | 'reports' | 'alerts' | 'active-mgmt' | 'optimization';
@@ -163,56 +163,33 @@ const PortfolioTab: React.FC = () => {
<div style={{
...COMMON_STYLES.container,
}}>
- {/* Fincept-Style Header */}
+ {/* Top Navigation Bar */}
<div style={{
...COMMON_STYLES.header,
height: 'auto',
- padding: '6px 8px',
- gap: '6px',
- flexWrap: 'wrap'
+ padding: '6px 16px',
+ gap: '8px',
+ flexWrap: 'nowrap',
}}>
{/* Title */}
- <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- <Briefcase size={12} color={FINCEPT.ORANGE} style={{ filter: EFFECTS.ICON_GLOW_ORANGE }} />
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexShrink: 0 }}>
+ <Briefcase size={14} color={FINCEPT.ORANGE} style={{ filter: EFFECTS.ICON_GLOW_ORANGE }} />
<span style={{
- fontSize: '10px',
+ fontSize: TYPOGRAPHY.BODY,
fontWeight: TYPOGRAPHY.BOLD,
color: FINCEPT.ORANGE,
- letterSpacing: '0.5px',
- textShadow: EFFECTS.ORANGE_GLOW
+ letterSpacing: TYPOGRAPHY.WIDE,
+ textShadow: EFFECTS.ORANGE_GLOW,
+ textTransform: 'uppercase' as const,
}}>
PORTFOLIO
</span>
</div>
- <button
- onClick={() => {
- const tour = createPortfolioTabTour((tab: string) => setActiveSubTab(tab as any));
- tour.drive();
- }}
- style={{
- backgroundColor: FINCEPT.BLUE,
- color: FINCEPT.DARK_BG,
- border: 'none',
- padding: '2px 6px',
- fontSize: '8px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '2px',
- borderRadius: '2px'
- }}
- title="Start portfolio tour"
- >
- <Info size={10} />
- HELP
- </button>
-
- <div style={{ ...COMMON_STYLES.verticalDivider, height: '14px' }} />
+ <div style={{ ...COMMON_STYLES.verticalDivider, height: '16px' }} />
{/* Sub-tab Navigation */}
- <div id="portfolio-subtabs" style={{ display: 'flex', gap: '3px', flex: 1, overflowX: 'auto', overflowY: 'hidden' }}>
+ <div id="portfolio-subtabs" style={{ display: 'flex', gap: '2px', flex: 1, overflowX: 'auto', overflowY: 'hidden' }}>
{subTabs.map(tab => {
const Icon = tab.icon;
const isActive = activeSubTab === tab.id;
@@ -222,23 +199,16 @@ const PortfolioTab: React.FC = () => {
onClick={() => setActiveSubTab(tab.id)}
disabled={!selectedPortfolio}
style={{
+ ...COMMON_STYLES.tabButton(isActive),
display: 'flex',
alignItems: 'center',
- gap: '2px',
- padding: '3px 6px',
- fontSize: '8px',
- fontWeight: TYPOGRAPHY.SEMIBOLD,
- letterSpacing: '0.3px',
- color: !selectedPortfolio ? FINCEPT.MUTED : (isActive ? FINCEPT.DARK_BG : FINCEPT.CYAN),
- backgroundColor: isActive ? FINCEPT.ORANGE : 'transparent',
- border: isActive ? BORDERS.ORANGE : BORDERS.STANDARD,
- borderRadius: '2px',
+ gap: '3px',
+ padding: '4px 8px',
+ fontFamily: TYPOGRAPHY.MONO,
cursor: selectedPortfolio ? 'pointer' : 'not-allowed',
- transition: EFFECTS.TRANSITION_FAST,
- outline: 'none',
opacity: selectedPortfolio ? 1 : 0.5,
whiteSpace: 'nowrap',
- flexShrink: 0
+ flexShrink: 0,
}}
onMouseEnter={(e) => {
if (!isActive && selectedPortfolio) {
@@ -249,7 +219,7 @@ const PortfolioTab: React.FC = () => {
onMouseLeave={(e) => {
if (!isActive) {
e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = selectedPortfolio ? FINCEPT.CYAN : FINCEPT.MUTED;
+ e.currentTarget.style.color = selectedPortfolio ? FINCEPT.GRAY : FINCEPT.MUTED;
}
}}
>
@@ -260,80 +230,33 @@ const PortfolioTab: React.FC = () => {
})}
</div>
- <div style={{ ...COMMON_STYLES.verticalDivider, height: '14px' }} />
-
- {/* Portfolio Selector & Actions */}
- <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- {portfolios.length > 0 && (
- <select
- id="portfolio-selector"
- value={selectedPortfolio?.id || ''}
- onChange={(e) => {
- const portfolio = portfolios.find(p => p.id === e.target.value);
- if (portfolio) setSelectedPortfolio(portfolio);
- }}
- style={{
- padding: '2px 4px',
- backgroundColor: FINCEPT.DARK_BG,
- border: BORDERS.STANDARD,
- color: FINCEPT.WHITE,
- fontSize: '8px',
- fontWeight: TYPOGRAPHY.BOLD,
- fontFamily: TYPOGRAPHY.MONO,
- cursor: 'pointer',
- outline: 'none',
- minWidth: 'auto',
- maxWidth: '200px',
- width: 'auto'
- }}
- >
- <option value="" disabled>SELECT</option>
- {portfolios.map(portfolio => (
- <option key={portfolio.id} value={portfolio.id}>
- {portfolio.name}
- </option>
- ))}
- </select>
- )}
-
- <button
- id="portfolio-create"
- onClick={() => setShowCreatePortfolio(true)}
- style={{
- padding: '2px 4px',
- backgroundColor: FINCEPT.DARK_BG,
- border: BORDERS.ORANGE,
- color: FINCEPT.ORANGE,
- fontSize: '8px',
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '2px',
- fontWeight: TYPOGRAPHY.BOLD
- }}
- >
- <Plus size={9} />
- NEW
- </button>
+ <div style={{ ...COMMON_STYLES.verticalDivider, height: '16px' }} />
+ {/* Actions */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', flexShrink: 0 }}>
{selectedPortfolio && (
<>
<button
id="portfolio-buy"
onClick={() => setShowAddAsset(true)}
style={{
- padding: '2px 4px',
- backgroundColor: FINCEPT.DARK_BG,
- border: BORDERS.STANDARD,
+ padding: '3px 8px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.GREEN}`,
+ borderRadius: '2px',
color: FINCEPT.GREEN,
- fontSize: '8px',
+ fontSize: TYPOGRAPHY.TINY,
+ fontWeight: TYPOGRAPHY.BOLD,
+ fontFamily: TYPOGRAPHY.MONO,
+ letterSpacing: TYPOGRAPHY.WIDE,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
- gap: '2px'
+ gap: '3px',
+ transition: EFFECTS.TRANSITION_FAST,
}}
>
- <Plus size={9} />
+ <ArrowUpRight size={9} />
BUY
</button>
@@ -341,18 +264,23 @@ const PortfolioTab: React.FC = () => {
id="portfolio-sell"
onClick={() => setShowSellAsset(true)}
style={{
- padding: '2px 4px',
- backgroundColor: FINCEPT.DARK_BG,
- border: BORDERS.STANDARD,
+ padding: '3px 8px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.RED}`,
+ borderRadius: '2px',
color: FINCEPT.RED,
- fontSize: '8px',
+ fontSize: TYPOGRAPHY.TINY,
+ fontWeight: TYPOGRAPHY.BOLD,
+ fontFamily: TYPOGRAPHY.MONO,
+ letterSpacing: TYPOGRAPHY.WIDE,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
- gap: '2px'
+ gap: '3px',
+ transition: EFFECTS.TRANSITION_FAST,
}}
>
- <Trash2 size={9} />
+ <ArrowDownRight size={9} />
SELL
</button>
@@ -361,14 +289,16 @@ const PortfolioTab: React.FC = () => {
onClick={refreshPortfolioData}
disabled={refreshing}
style={{
- padding: '2px 4px',
- backgroundColor: FINCEPT.DARK_BG,
+ padding: '3px 6px',
+ backgroundColor: 'transparent',
border: BORDERS.STANDARD,
+ borderRadius: '2px',
color: refreshing ? FINCEPT.MUTED : FINCEPT.CYAN,
- fontSize: '8px',
+ fontSize: TYPOGRAPHY.TINY,
cursor: refreshing ? 'wait' : 'pointer',
display: 'flex',
- alignItems: 'center'
+ alignItems: 'center',
+ transition: EFFECTS.TRANSITION_FAST,
}}
>
<RefreshCw size={9} className={refreshing ? 'animate-spin' : ''} />
@@ -378,121 +308,430 @@ const PortfolioTab: React.FC = () => {
id="portfolio-export"
onClick={exportToCSV}
style={{
- padding: '2px 4px',
- backgroundColor: FINCEPT.DARK_BG,
+ padding: '3px 6px',
+ backgroundColor: 'transparent',
border: BORDERS.STANDARD,
+ borderRadius: '2px',
color: FINCEPT.CYAN,
- fontSize: '8px',
+ fontSize: TYPOGRAPHY.TINY,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
- gap: '2px'
+ gap: '3px',
+ transition: EFFECTS.TRANSITION_FAST,
}}
>
<Download size={9} />
</button>
</>
)}
+
+ <button
+ onClick={() => {
+ const tour = createPortfolioTabTour((tab: string) => setActiveSubTab(tab as any));
+ tour.drive();
+ }}
+ style={{
+ padding: '3px 6px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BLUE}`,
+ borderRadius: '2px',
+ color: FINCEPT.BLUE,
+ fontSize: TYPOGRAPHY.TINY,
+ fontWeight: TYPOGRAPHY.BOLD,
+ fontFamily: TYPOGRAPHY.MONO,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '2px',
+ transition: EFFECTS.TRANSITION_FAST,
+ }}
+ title="Start portfolio tour"
+ >
+ <Info size={9} />
+ HELP
+ </button>
</div>
</div>
- {/* Sub-tab Content */}
- <div style={{ flex: 1, overflow: 'hidden' }}>
- {!selectedPortfolio ? (
+ {/* Three-Panel Layout */}
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* Left Panel - Portfolio List */}
+ <div style={{
+ width: '280px',
+ flexShrink: 0,
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ }}>
+ {/* Left Panel Header */}
<div style={{
- height: '100%',
+ padding: SPACING.DEFAULT,
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
- flexDirection: 'column',
alignItems: 'center',
- justifyContent: 'center',
- gap: SPACING.XLARGE,
- backgroundColor: FINCEPT.DARK_BG
+ justifyContent: 'space-between',
}}>
- <Briefcase size={80} color={FINCEPT.MUTED} style={{ opacity: 0.3 }} />
+ <span style={{ ...COMMON_STYLES.dataLabel }}>PORTFOLIOS</span>
+ <button
+ id="portfolio-create"
+ onClick={() => setShowCreatePortfolio(true)}
+ style={{
+ padding: '2px 8px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.ORANGE}`,
+ borderRadius: '2px',
+ color: FINCEPT.ORANGE,
+ fontSize: TYPOGRAPHY.TINY,
+ fontWeight: TYPOGRAPHY.BOLD,
+ fontFamily: TYPOGRAPHY.MONO,
+ letterSpacing: TYPOGRAPHY.WIDE,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '3px',
+ transition: EFFECTS.TRANSITION_FAST,
+ }}
+ >
+ <Plus size={9} />
+ NEW
+ </button>
+ </div>
+
+ {/* Portfolio List */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {portfolios.length === 0 ? (
+ <div style={{
+ ...COMMON_STYLES.emptyState,
+ padding: SPACING.XLARGE,
+ height: 'auto',
+ }}>
+ <Briefcase size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />
+ <span>No portfolios yet</span>
+ <span style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY, marginTop: '4px' }}>
+ Click NEW to create one
+ </span>
+ </div>
+ ) : (
+ portfolios.map(portfolio => {
+ const isSelected = selectedPortfolio?.id === portfolio.id;
+ return (
+ <div
+ key={portfolio.id}
+ onClick={() => setSelectedPortfolio(portfolio)}
+ style={{
+ padding: '10px 12px',
+ backgroundColor: isSelected ? `${FINCEPT.ORANGE}15` : 'transparent',
+ borderLeft: isSelected ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
+ cursor: 'pointer',
+ transition: EFFECTS.TRANSITION_STANDARD,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}
+ onMouseEnter={(e) => {
+ if (!isSelected) e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ }}
+ onMouseLeave={(e) => {
+ if (!isSelected) e.currentTarget.style.backgroundColor = 'transparent';
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '4px' }}>
+ <span style={{
+ color: isSelected ? FINCEPT.ORANGE : FINCEPT.WHITE,
+ fontSize: TYPOGRAPHY.SMALL,
+ fontWeight: TYPOGRAPHY.BOLD,
+ fontFamily: TYPOGRAPHY.MONO,
+ }}>
+ {portfolio.name}
+ </span>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ handleDeletePortfolio(portfolio.id);
+ }}
+ style={{
+ background: 'none',
+ border: 'none',
+ color: FINCEPT.MUTED,
+ cursor: 'pointer',
+ padding: '2px',
+ display: 'flex',
+ transition: EFFECTS.TRANSITION_FAST,
+ }}
+ onMouseEnter={(e) => { e.currentTarget.style.color = FINCEPT.RED; }}
+ onMouseLeave={(e) => { e.currentTarget.style.color = FINCEPT.MUTED; }}
+ >
+ <Trash2 size={10} />
+ </button>
+ </div>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ <span style={{ ...COMMON_STYLES.dataLabel, fontSize: '8px' }}>
+ {portfolio.currency}
+ </span>
+ {portfolio.owner && (
+ <span style={{ ...COMMON_STYLES.dataLabel, fontSize: '8px' }}>
+ {portfolio.owner}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>
+
+ {/* Center Content */}
+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
+ {!selectedPortfolio ? (
<div style={{
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.HEADING,
- textAlign: 'center',
- fontWeight: TYPOGRAPHY.SEMIBOLD,
- letterSpacing: TYPOGRAPHY.WIDE,
- fontFamily: TYPOGRAPHY.MONO
+ ...COMMON_STYLES.emptyState,
+ gap: SPACING.LARGE,
}}>
- NO PORTFOLIO SELECTED
+ <Briefcase size={48} color={FINCEPT.MUTED} style={{ opacity: 0.2 }} />
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: TYPOGRAPHY.SUBHEADING,
+ fontWeight: TYPOGRAPHY.BOLD,
+ letterSpacing: '1px',
+ fontFamily: TYPOGRAPHY.MONO,
+ textTransform: 'uppercase' as const,
+ }}>
+ NO PORTFOLIO SELECTED
+ </div>
+ <div style={{
+ color: FINCEPT.MUTED,
+ fontSize: TYPOGRAPHY.SMALL,
+ fontFamily: TYPOGRAPHY.MONO,
+ }}>
+ {portfolios.length === 0 ? 'Create a new portfolio to get started' : 'Select a portfolio from the left panel'}
+ </div>
</div>
+ ) : !portfolioSummary ? (
<div style={{
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.DEFAULT,
- textAlign: 'center',
- fontFamily: TYPOGRAPHY.MONO
+ ...COMMON_STYLES.emptyState,
}}>
- {portfolios.length === 0 ? 'Create a new portfolio to get started' : 'Select a portfolio from the dropdown above'}
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: TYPOGRAPHY.BODY,
+ fontWeight: TYPOGRAPHY.SEMIBOLD,
+ letterSpacing: '1px',
+ fontFamily: TYPOGRAPHY.MONO,
+ }}>
+ LOADING PORTFOLIO DATA...
+ </div>
</div>
- {portfolios.length === 0 && (
- <button
- onClick={() => setShowCreatePortfolio(true)}
- style={{
- marginTop: SPACING.LARGE,
- padding: `${SPACING.MEDIUM} ${SPACING.LARGE}`,
- backgroundColor: FINCEPT.ORANGE,
- border: BORDERS.ORANGE,
- color: FINCEPT.DARK_BG,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- letterSpacing: TYPOGRAPHY.WIDE,
- cursor: 'pointer',
- transition: EFFECTS.TRANSITION_STANDARD,
- fontFamily: TYPOGRAPHY.MONO
- }}
- onMouseEnter={(e) => e.currentTarget.style.opacity = '0.85'}
- onMouseLeave={(e) => e.currentTarget.style.opacity = '1'}
- >
- + CREATE PORTFOLIO
- </button>
- )}
- </div>
- ) : !portfolioSummary ? (
+ ) : (
+ <div style={{ flex: 1, overflow: 'hidden' }}>
+ {activeSubTab === 'positions' && <div id="positions-view" style={{ height: '100%' }}><PositionsView portfolioSummary={portfolioSummary} /></div>}
+ {activeSubTab === 'history' && <div id="history-view" style={{ height: '100%' }}><HistoryView transactions={transactions} currency={currency} /></div>}
+ {activeSubTab === 'analytics' && <div id="analytics-view" style={{ height: '100%' }}><AnalyticsView portfolioSummary={portfolioSummary} /></div>}
+ {activeSubTab === 'sectors' && <div id="sectors-view" style={{ height: '100%' }}><SectorsView portfolioSummary={portfolioSummary} /></div>}
+ {activeSubTab === 'performance' && <div id="performance-view" style={{ height: '100%' }}><PerformanceView portfolioSummary={portfolioSummary} /></div>}
+ {activeSubTab === 'risk' && <div id="risk-view" style={{ height: '100%' }}><RiskMetricsView portfolioSummary={portfolioSummary} /></div>}
+ {activeSubTab === 'optimization' && <div id="optimization-view" style={{ height: '100%' }}><PortfolioOptimizationView portfolioSummary={portfolioSummary} /></div>}
+ {activeSubTab === 'reports' && <div id="reports-view" style={{ height: '100%' }}><ReportsView portfolioSummary={portfolioSummary} transactions={transactions} /></div>}
+ {activeSubTab === 'alerts' && <div id="alerts-view" style={{ height: '100%' }}><AlertsView portfolioSummary={portfolioSummary} /></div>}
+ {activeSubTab === 'active-mgmt' && (
+ <div id="active-mgmt-view" style={{ height: '100%' }}>
+ <ActiveManagementView
+ portfolioId={selectedPortfolio.id}
+ portfolioData={{
+ returns: portfolioSummary.holdings.length > 0
+ ? portfolioSummary.holdings.map(h => (h.day_change_percent || 0) / 100)
+ : [],
+ weights: portfolioSummary.holdings.map(h => h.weight / 100)
+ }}
+ />
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Right Panel - Quick Summary */}
+ <div style={{
+ width: '300px',
+ flexShrink: 0,
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderLeft: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ }}>
+ {/* Right Panel Header */}
<div style={{
- height: '100%',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.SUBHEADING,
- fontWeight: TYPOGRAPHY.SEMIBOLD,
- letterSpacing: TYPOGRAPHY.WIDE,
- fontFamily: TYPOGRAPHY.MONO
+ padding: SPACING.DEFAULT,
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
}}>
- LOADING PORTFOLIO DATA...
+ <span style={{ ...COMMON_STYLES.dataLabel }}>PORTFOLIO SUMMARY</span>
</div>
- ) : (
- <>
- {activeSubTab === 'positions' && <div id="positions-view"><PositionsView portfolioSummary={portfolioSummary} /></div>}
- {activeSubTab === 'history' && <div id="history-view"><HistoryView transactions={transactions} currency={currency} /></div>}
- {activeSubTab === 'analytics' && <div id="analytics-view"><AnalyticsView portfolioSummary={portfolioSummary} /></div>}
- {activeSubTab === 'sectors' && <div id="sectors-view"><SectorsView portfolioSummary={portfolioSummary} /></div>}
- {activeSubTab === 'performance' && <div id="performance-view"><PerformanceView portfolioSummary={portfolioSummary} /></div>}
- {activeSubTab === 'risk' && <div id="risk-view"><RiskMetricsView portfolioSummary={portfolioSummary} /></div>}
- {activeSubTab === 'optimization' && <div id="optimization-view"><PortfolioOptimizationView portfolioSummary={portfolioSummary} /></div>}
- {activeSubTab === 'reports' && <div id="reports-view"><ReportsView portfolioSummary={portfolioSummary} transactions={transactions} /></div>}
- {activeSubTab === 'alerts' && <div id="alerts-view"><AlertsView portfolioSummary={portfolioSummary} /></div>}
- {activeSubTab === 'active-mgmt' && (
- <div id="active-mgmt-view">
- <ActiveManagementView
- portfolioId={selectedPortfolio.id}
- portfolioData={{
- returns: portfolioSummary.holdings.length > 0
- ? portfolioSummary.holdings.map(h => (h.day_change_percent || 0) / 100)
- : [],
- weights: portfolioSummary.holdings.map(h => h.weight / 100)
- }}
- />
+
+ {/* Summary Content */}
+ <div style={{ flex: 1, overflow: 'auto', padding: SPACING.DEFAULT }}>
+ {!portfolioSummary ? (
+ <div style={{
+ ...COMMON_STYLES.emptyState,
+ height: 'auto',
+ padding: SPACING.XLARGE,
+ }}>
+ <DollarSign size={24} style={{ marginBottom: '8px', opacity: 0.3 }} />
+ <span>Select a portfolio</span>
+ </div>
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.MEDIUM }}>
+ {/* Total Value Card */}
+ <div style={{
+ ...COMMON_STYLES.metricCard,
+ borderColor: FINCEPT.ORANGE,
+ padding: SPACING.DEFAULT,
+ }}>
+ <div style={{ ...COMMON_STYLES.dataLabel }}>TOTAL VALUE</div>
+ <div style={{
+ color: FINCEPT.ORANGE,
+ fontSize: TYPOGRAPHY.HEADING,
+ fontWeight: TYPOGRAPHY.BOLD,
+ fontFamily: TYPOGRAPHY.MONO,
+ }}>
+ {formatCurrency(portfolioSummary.total_market_value, currency)}
+ </div>
+ </div>
+
+ {/* Total P&L */}
+ <div style={{
+ ...COMMON_STYLES.metricCard,
+ borderColor: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ padding: SPACING.DEFAULT,
+ }}>
+ <div style={{ ...COMMON_STYLES.dataLabel }}>UNREALIZED P&L</div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}>
+ {portfolioSummary.total_unrealized_pnl >= 0
+ ? <ArrowUpRight size={14} color={FINCEPT.GREEN} />
+ : <ArrowDownRight size={14} color={FINCEPT.RED} />
+ }
+ <span style={{
+ color: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ fontSize: TYPOGRAPHY.SUBHEADING,
+ fontWeight: TYPOGRAPHY.BOLD,
+ fontFamily: TYPOGRAPHY.MONO,
+ }}>
+ {portfolioSummary.total_unrealized_pnl >= 0 ? '+' : ''}{formatCurrency(portfolioSummary.total_unrealized_pnl, currency)}
+ </span>
+ </div>
+ <div style={{
+ color: portfolioSummary.total_unrealized_pnl_percent >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ fontSize: TYPOGRAPHY.SMALL,
+ fontFamily: TYPOGRAPHY.MONO,
+ }}>
+ {formatPercent(portfolioSummary.total_unrealized_pnl_percent)}
+ </div>
+ </div>
+
+ {/* Cost Basis */}
+ <div style={{ ...COMMON_STYLES.metricCard, padding: SPACING.DEFAULT }}>
+ <div style={{ ...COMMON_STYLES.dataLabel }}>COST BASIS</div>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: TYPOGRAPHY.SUBHEADING,
+ fontWeight: TYPOGRAPHY.BOLD,
+ fontFamily: TYPOGRAPHY.MONO,
+ }}>
+ {formatCurrency(portfolioSummary.total_cost_basis, currency)}
+ </div>
+ </div>
+
+ {/* Day Change */}
+ <div style={{ ...COMMON_STYLES.metricCard, padding: SPACING.DEFAULT }}>
+ <div style={{ ...COMMON_STYLES.dataLabel }}>DAY CHANGE</div>
+ <div style={{
+ color: portfolioSummary.total_day_change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ fontSize: TYPOGRAPHY.BODY,
+ fontWeight: TYPOGRAPHY.BOLD,
+ fontFamily: TYPOGRAPHY.MONO,
+ }}>
+ {portfolioSummary.total_day_change >= 0 ? '+' : ''}{formatCurrency(portfolioSummary.total_day_change, currency)}
+ <span style={{ marginLeft: '6px', fontSize: TYPOGRAPHY.SMALL }}>
+ ({formatPercent(portfolioSummary.total_day_change_percent)})
+ </span>
+ </div>
+ </div>
+
+ {/* Divider */}
+ <div style={COMMON_STYLES.divider} />
+
+ {/* Quick Stats */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.MEDIUM }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <span style={{ ...COMMON_STYLES.dataLabel }}>POSITIONS</span>
+ <span style={{ ...COMMON_STYLES.dataValue }}>{portfolioSummary.total_positions}</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <span style={{ ...COMMON_STYLES.dataLabel }}>CURRENCY</span>
+ <span style={{ ...COMMON_STYLES.dataValue }}>{currency}</span>
+ </div>
+ </div>
+
+ {/* Divider */}
+ <div style={COMMON_STYLES.divider} />
+
+ {/* Top Holdings */}
+ <div>
+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.MEDIUM }}>TOP HOLDINGS</div>
+ {portfolioSummary.holdings
+ .slice()
+ .sort((a, b) => b.weight - a.weight)
+ .slice(0, 5)
+ .map(holding => (
+ <div key={holding.id} style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ padding: '4px 0',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <div>
+ <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.SMALL, fontWeight: TYPOGRAPHY.BOLD, fontFamily: TYPOGRAPHY.MONO }}>
+ {holding.symbol}
+ </div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, fontFamily: TYPOGRAPHY.MONO }}>
+ {holding.weight.toFixed(1)}%
+ </div>
+ </div>
+ <div style={{ textAlign: 'right' }}>
+ <div style={{
+ color: holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ fontSize: TYPOGRAPHY.SMALL,
+ fontWeight: TYPOGRAPHY.BOLD,
+ fontFamily: TYPOGRAPHY.MONO,
+ }}>
+ {holding.unrealized_pnl >= 0 ? '+' : ''}{formatCurrency(holding.unrealized_pnl, currency)}
+ </div>
+ <div style={{
+ color: holding.unrealized_pnl_percent >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ fontSize: TYPOGRAPHY.TINY,
+ fontFamily: TYPOGRAPHY.MONO,
+ }}>
+ {formatPercent(holding.unrealized_pnl_percent)}
+ </div>
+ </div>
+ </div>
+ ))
+ }
+ </div>
</div>
)}
- </>
- )}
+ </div>
+ </div>
</div>
- {/* Tab Footer */}
+ {/* Status Bar (Bottom) */}
<TabFooter
tabName="PORTFOLIO MANAGER"
backgroundColor={FINCEPT.HEADER_BG}
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/finceptStyles.ts b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/finceptStyles.ts
index 41301e997..53d5ffc80 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/finceptStyles.ts
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/finceptStyles.ts
@@ -158,10 +158,11 @@ export const COMMON_STYLES = {
flexDirection: 'column' as const,
},
- // Panel
+ // Panel (per design system: 2px radius)
panel: {
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.STANDARD,
+ borderRadius: '2px',
padding: SPACING.DEFAULT,
},
@@ -177,87 +178,155 @@ export const COMMON_STYLES = {
boxShadow: EFFECTS.PANEL_SHADOW,
},
- // Section Header
+ // Section Header (panel-style with background per design system)
sectionHeader: {
+ padding: SPACING.DEFAULT,
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.SUBHEADING,
+ fontSize: '11px',
fontWeight: TYPOGRAPHY.BOLD,
letterSpacing: TYPOGRAPHY.WIDE,
textTransform: 'uppercase' as const,
marginBottom: SPACING.MEDIUM,
},
- // Data Label
+ // Data Label (per design system: 9px, bold, GRAY, letter-spacing, UPPERCASE)
dataLabel: {
color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.SMALL,
- fontWeight: TYPOGRAPHY.SEMIBOLD,
+ fontSize: '9px',
+ fontWeight: TYPOGRAPHY.BOLD,
+ letterSpacing: '0.5px',
textTransform: 'uppercase' as const,
},
- // Data Value
+ // Data Value (per design system: 10px, CYAN, monospace)
dataValue: {
- color: FINCEPT.WHITE,
- fontSize: TYPOGRAPHY.DEFAULT,
+ color: FINCEPT.CYAN,
+ fontSize: '10px',
fontWeight: TYPOGRAPHY.REGULAR,
fontFamily: TYPOGRAPHY.MONO,
},
- // Metric Card
+ // Metric Card (per design system: panel bg, 2px radius, border)
metricCard: {
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.STANDARD,
+ borderRadius: '2px',
padding: SPACING.DEFAULT,
display: 'flex',
flexDirection: 'column' as const,
gap: SPACING.SMALL,
},
- // Button Primary
+ // Button Primary (per design system: 8px 16px, orange bg, dark text, 9px bold, 2px radius)
buttonPrimary: {
- padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,
+ padding: '8px 16px',
backgroundColor: FINCEPT.ORANGE,
- border: BORDERS.ORANGE,
color: FINCEPT.DARK_BG,
- fontSize: TYPOGRAPHY.BODY,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
fontWeight: TYPOGRAPHY.BOLD,
cursor: 'pointer',
transition: EFFECTS.TRANSITION_STANDARD,
textTransform: 'uppercase' as const,
+ letterSpacing: '0.5px',
},
- // Button Secondary
+ // Button Secondary / Outline (per design system: 6px 10px, transparent, border, 9px bold)
buttonSecondary: {
- padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,
+ padding: '6px 10px',
backgroundColor: 'transparent',
border: BORDERS.STANDARD,
- color: FINCEPT.WHITE,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.SEMIBOLD,
+ color: FINCEPT.GRAY,
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: TYPOGRAPHY.BOLD,
cursor: 'pointer',
transition: EFFECTS.TRANSITION_STANDARD,
textTransform: 'uppercase' as const,
+ letterSpacing: '0.5px',
},
- // Input Field
+ // Input Field (per design system: dark bg, 8px 10px padding, 10px, 2px radius)
inputField: {
width: '100%',
- padding: SPACING.MEDIUM,
+ padding: '8px 10px',
backgroundColor: FINCEPT.DARK_BG,
- border: BORDERS.STANDARD,
color: FINCEPT.WHITE,
- fontSize: TYPOGRAPHY.BODY,
- fontFamily: TYPOGRAPHY.MONO,
+ border: BORDERS.STANDARD,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
outline: 'none',
},
- // Table Header
+ // Tab Button (per design system: 6px 12px, 9px bold, letter-spacing)
+ tabButton: (isActive: boolean) => ({
+ padding: '6px 12px',
+ backgroundColor: isActive ? FINCEPT.ORANGE : 'transparent',
+ color: isActive ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: TYPOGRAPHY.BOLD,
+ letterSpacing: '0.5px',
+ cursor: 'pointer',
+ transition: EFFECTS.TRANSITION_FAST,
+ textTransform: 'uppercase' as const,
+ }),
+
+ // Status Badge Success
+ badgeSuccess: {
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.GREEN}20`,
+ color: FINCEPT.GREEN,
+ fontSize: '8px',
+ fontWeight: TYPOGRAPHY.BOLD,
+ borderRadius: '2px',
+ },
+
+ // Status Badge Error
+ badgeError: {
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.RED}20`,
+ color: FINCEPT.RED,
+ fontSize: '8px',
+ fontWeight: TYPOGRAPHY.BOLD,
+ borderRadius: '2px',
+ },
+
+ // Status Badge Info
+ badgeInfo: {
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.CYAN}20`,
+ color: FINCEPT.CYAN,
+ fontSize: '8px',
+ fontWeight: TYPOGRAPHY.BOLD,
+ borderRadius: '2px',
+ },
+
+ // Empty State (per design system)
+ emptyState: {
+ display: 'flex',
+ flexDirection: 'column' as const,
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ color: FINCEPT.MUTED,
+ fontSize: '10px',
+ textAlign: 'center' as const,
+ },
+
+ // Table Header (per design system: HEADER_BG, ORANGE text, 9px bold, UPPERCASE)
tableHeader: {
backgroundColor: FINCEPT.HEADER_BG,
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.BODY,
+ fontSize: '9px',
fontWeight: TYPOGRAPHY.BOLD,
- padding: SPACING.SMALL,
+ letterSpacing: '0.5px',
+ padding: '8px 12px',
textAlign: 'left' as const,
borderBottom: BORDERS.ORANGE,
textTransform: 'uppercase' as const,
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/AddAssetModal.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/AddAssetModal.tsx
index 29b3cc157..0c6b83099 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/AddAssetModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/AddAssetModal.tsx
@@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react';
+import { invoke } from '@tauri-apps/api/core';
import { marketDataService } from '../../../../services/markets/marketDataService';
import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, createFocusHandlers } from '../finceptStyles';
@@ -27,21 +28,48 @@ const AddAssetModal: React.FC<AddAssetModalProps> = ({
}) => {
const [fetchingPrice, setFetchingPrice] = useState(false);
const [priceError, setPriceError] = useState<string | null>(null);
+ const [resolvedExchange, setResolvedExchange] = useState<string>('');
- // Auto-fetch price when symbol changes
+ // Auto-resolve symbol and fetch price when symbol changes
useEffect(() => {
- const fetchPrice = async () => {
- const symbol = formState.symbol.trim().toUpperCase();
+ const resolveAndFetch = async () => {
+ const rawSymbol = formState.symbol.trim().toUpperCase();
- if (!symbol || symbol.length < 2) {
+ if (!rawSymbol || rawSymbol.length < 2) {
+ setResolvedExchange('');
return;
}
setFetchingPrice(true);
setPriceError(null);
+ setResolvedExchange('');
try {
- const quote = await marketDataService.getQuote(symbol);
+ // Step 1: Resolve the symbol to its correct yfinance form
+ // e.g. "PIDILITIND" → "PIDILITIND.NS", "AAPL" → "AAPL"
+ let symbolToUse = rawSymbol;
+ try {
+ const resolveOutput = await invoke<string>('execute_yfinance_command', {
+ command: 'resolve_symbol',
+ args: [rawSymbol],
+ });
+ const resolved = JSON.parse(resolveOutput);
+ if (resolved.found && resolved.resolved_symbol) {
+ symbolToUse = resolved.resolved_symbol;
+ // Update the symbol field to the resolved form so it gets stored correctly
+ if (symbolToUse !== rawSymbol) {
+ onSymbolChange(symbolToUse);
+ }
+ if (resolved.exchange) {
+ setResolvedExchange(resolved.exchange);
+ }
+ }
+ } catch (resolveErr) {
+ console.warn('[AddAsset] Symbol resolution failed, using as-is:', resolveErr);
+ }
+
+ // Step 2: Fetch the quote using the resolved symbol
+ const quote = await marketDataService.getQuote(symbolToUse);
if (quote && quote.price) {
onPriceChange(quote.price.toFixed(2));
@@ -58,7 +86,7 @@ const AddAssetModal: React.FC<AddAssetModalProps> = ({
};
// Debounce: wait 800ms after user stops typing
- const timer = setTimeout(fetchPrice, 800);
+ const timer = setTimeout(resolveAndFetch, 800);
return () => clearTimeout(timer);
}, [formState.symbol]);
@@ -144,7 +172,7 @@ const AddAssetModal: React.FC<AddAssetModalProps> = ({
)}
{!fetchingPrice && !priceError && formState.price && formState.symbol && (
<span style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.TINY }}>
- ✓ Auto-fetched
+ {resolvedExchange ? `✓ ${resolvedExchange}` : '✓ Auto-fetched'}
</span>
)}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ActiveManagementView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ActiveManagementView.tsx
index 510e951e0..f7554ad07 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ActiveManagementView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ActiveManagementView.tsx
@@ -2,7 +2,7 @@ import React, { useState, useEffect } from 'react';
import { TrendingUp, TrendingDown, Target, Activity, Award, AlertTriangle } from 'lucide-react';
import { activeManagementService, type ComprehensiveAnalysisResult } from '@/services/portfolio/activeManagementService';
import { formatPercent, formatNumber } from './utils';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../finceptStyles';
+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, EFFECTS } from '../finceptStyles';
interface ActiveManagementViewProps {
portfolioId: string;
@@ -70,14 +70,31 @@ const ActiveManagementView: React.FC<ActiveManagementViewProps> = ({ portfolioId
<div style={{
height: '100%',
backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.XLARGE,
+ padding: '24px',
textAlign: 'center',
fontFamily: TYPOGRAPHY.MONO
}}>
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.SUBHEADING, marginBottom: SPACING.MEDIUM }}>
+ <div style={{
+ color: FINCEPT.ORANGE,
+ fontSize: '13px',
+ fontWeight: 700,
+ marginBottom: '8px',
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>
Running Active Management Analysis...
</div>
- <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-orange-500 mx-auto"></div>
+ <div
+ className="animate-spin"
+ style={{
+ width: '32px',
+ height: '32px',
+ borderRadius: '50%',
+ border: '2px solid transparent',
+ borderBottomColor: FINCEPT.ORANGE,
+ margin: '0 auto'
+ }}
+ />
</div>
);
}
@@ -87,17 +104,18 @@ const ActiveManagementView: React.FC<ActiveManagementViewProps> = ({ portfolioId
<div style={{
height: '100%',
backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.XLARGE,
+ padding: '24px',
fontFamily: TYPOGRAPHY.MONO
}}>
<div style={{
- padding: SPACING.DEFAULT,
+ padding: '12px',
backgroundColor: 'rgba(255,59,59,0.1)',
border: BORDERS.RED,
+ borderRadius: '2px',
color: FINCEPT.RED,
- fontSize: TYPOGRAPHY.DEFAULT
+ fontSize: '10px'
}}>
- <AlertTriangle size={16} style={{ display: 'inline-block', marginRight: SPACING.SMALL }} />
+ <AlertTriangle size={16} style={{ display: 'inline-block', marginRight: '4px' }} />
{error}
</div>
</div>
@@ -109,13 +127,13 @@ const ActiveManagementView: React.FC<ActiveManagementViewProps> = ({ portfolioId
<div style={{
height: '100%',
backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.XLARGE,
+ padding: '24px',
textAlign: 'center',
fontFamily: TYPOGRAPHY.MONO
}}>
- <Activity size={48} color={FINCEPT.GRAY} style={{ margin: `0 auto ${SPACING.MEDIUM}` }} />
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.DEFAULT }}>No analysis data yet</div>
- <div style={{ marginTop: SPACING.SMALL, fontSize: TYPOGRAPHY.BODY, color: FINCEPT.GRAY }}>
+ <Activity size={48} color={FINCEPT.GRAY} style={{ margin: '0 auto 8px' }} />
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>No analysis data yet</div>
+ <div style={{ marginTop: '4px', fontSize: '11px', color: FINCEPT.GRAY }}>
Portfolio needs return data to perform active management analysis
</div>
</div>
@@ -133,46 +151,68 @@ const ActiveManagementView: React.FC<ActiveManagementViewProps> = ({ portfolioId
}}>
{/* Header */}
<div style={{
- backgroundColor: FINCEPT.PANEL_BG,
+ ...COMMON_STYLES.sectionHeader,
borderBottom: BORDERS.ORANGE,
- padding: SPACING.MEDIUM,
+ padding: '8px',
position: 'sticky',
top: 0,
- zIndex: 10
+ zIndex: 10,
+ marginBottom: '0px'
}}>
<div style={{
color: FINCEPT.ORANGE,
- fontWeight: TYPOGRAPHY.BOLD,
- fontSize: TYPOGRAPHY.SUBHEADING,
- marginBottom: SPACING.SMALL
+ fontWeight: 700,
+ fontSize: '11px',
+ marginBottom: '4px',
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
}}>
ACTIVE MANAGEMENT ANALYTICS
</div>
- <div style={{ display: 'flex', gap: SPACING.XLARGE, fontSize: TYPOGRAPHY.BODY }}>
+ <div style={{ display: 'flex', gap: '24px', fontSize: '10px' }}>
<div>
- <span style={{ color: FINCEPT.GRAY }}>BENCHMARK: </span>
- <span style={{ color: FINCEPT.CYAN }}>{benchmarkSymbol}</span>
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>BENCHMARK: </span>
+ <span style={{ color: FINCEPT.CYAN, fontSize: '10px' }}>{benchmarkSymbol}</span>
</div>
<div>
- <span style={{ color: FINCEPT.GRAY }}>QUALITY RATING: </span>
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>QUALITY RATING: </span>
<span style={{
color: active_management_assessment.quality_rating === 'Excellent' ? FINCEPT.GREEN :
active_management_assessment.quality_rating === 'Good' ? FINCEPT.CYAN :
active_management_assessment.quality_rating === 'Average' ? FINCEPT.YELLOW : FINCEPT.RED,
- fontWeight: TYPOGRAPHY.BOLD
+ fontWeight: 700,
+ fontSize: '10px'
}}>
{active_management_assessment.quality_rating}
</span>
</div>
<div>
- <span style={{ color: FINCEPT.GRAY }}>QUALITY SCORE: </span>
- <span style={{ color: FINCEPT.WHITE }}>{active_management_assessment.quality_score}/100</span>
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>QUALITY SCORE: </span>
+ <span style={{ color: FINCEPT.CYAN, fontSize: '10px' }}>{active_management_assessment.quality_score}/100</span>
</div>
</div>
</div>
{/* Key Metrics Grid */}
- <div style={{ padding: SPACING.MEDIUM, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: SPACING.MEDIUM }}>
+ <div style={{ padding: '8px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '8px' }}>
{/* Active Return */}
<MetricCard
title="ACTIVE RETURN"
@@ -229,36 +269,51 @@ const ActiveManagementView: React.FC<ActiveManagementViewProps> = ({ portfolioId
</div>
{/* Value Decomposition */}
- <div style={{ padding: `0 ${SPACING.MEDIUM} ${SPACING.MEDIUM}` }}>
+ <div style={{ padding: '0 8px 8px' }}>
<div style={{
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.STANDARD,
- padding: SPACING.MEDIUM
+ borderRadius: '2px',
+ padding: '8px'
}}>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.MEDIUM
+ ...COMMON_STYLES.sectionHeader,
+ marginBottom: '8px',
+ padding: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
}}>
VALUE ADDED DECOMPOSITION
</div>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: SPACING.MEDIUM, fontSize: TYPOGRAPHY.BODY }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '8px', fontSize: '11px' }}>
<div>
- <div style={{ color: FINCEPT.GRAY, marginBottom: SPACING.TINY }}>ALLOCATION EFFECT</div>
- <div style={{ color: FINCEPT.WHITE, fontSize: TYPOGRAPHY.SUBHEADING, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '2px'
+ }}>ALLOCATION EFFECT</div>
+ <div style={{ color: FINCEPT.CYAN, fontSize: '13px', fontWeight: 700 }}>
{formatPercent(value_added_analysis.value_added_decomposition.estimated_allocation_effect)}
</div>
</div>
<div>
- <div style={{ color: FINCEPT.GRAY, marginBottom: SPACING.TINY }}>SELECTION EFFECT</div>
- <div style={{ color: FINCEPT.WHITE, fontSize: TYPOGRAPHY.SUBHEADING, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '2px'
+ }}>SELECTION EFFECT</div>
+ <div style={{ color: FINCEPT.CYAN, fontSize: '13px', fontWeight: 700 }}>
{formatPercent(value_added_analysis.value_added_decomposition.estimated_selection_effect)}
</div>
</div>
</div>
{value_added_analysis.value_added_decomposition.note && (
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.SMALL, marginTop: SPACING.SMALL, fontStyle: 'italic' }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '4px', fontStyle: 'italic' }}>
Note: {value_added_analysis.value_added_decomposition.note}
</div>
)}
@@ -266,24 +321,27 @@ const ActiveManagementView: React.FC<ActiveManagementViewProps> = ({ portfolioId
</div>
{/* Strengths & Improvements */}
- <div style={{ padding: `0 ${SPACING.MEDIUM} ${SPACING.MEDIUM}`, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.MEDIUM }}>
+ <div style={{ padding: '0 8px 8px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
{/* Strengths */}
<div style={{
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.GREEN,
- padding: SPACING.MEDIUM
+ borderRadius: '2px',
+ padding: '8px'
}}>
<div style={{
color: FINCEPT.GREEN,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.SMALL
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '4px'
}}>
KEY STRENGTHS
</div>
- <ul style={{ margin: 0, paddingLeft: SPACING.DEFAULT, fontSize: TYPOGRAPHY.BODY, color: FINCEPT.WHITE }}>
+ <ul style={{ margin: 0, paddingLeft: '12px', fontSize: '10px', color: FINCEPT.WHITE }}>
{active_management_assessment.key_strengths.map((strength, idx) => (
- <li key={idx} style={{ marginBottom: SPACING.TINY }}>{strength}</li>
+ <li key={idx} style={{ marginBottom: '2px' }}>{strength}</li>
))}
</ul>
</div>
@@ -292,19 +350,22 @@ const ActiveManagementView: React.FC<ActiveManagementViewProps> = ({ portfolioId
<div style={{
backgroundColor: FINCEPT.PANEL_BG,
border: `1px solid ${FINCEPT.YELLOW}`,
- padding: SPACING.MEDIUM
+ borderRadius: '2px',
+ padding: '8px'
}}>
<div style={{
color: FINCEPT.YELLOW,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.SMALL
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '4px'
}}>
AREAS FOR IMPROVEMENT
</div>
- <ul style={{ margin: 0, paddingLeft: SPACING.DEFAULT, fontSize: TYPOGRAPHY.BODY, color: FINCEPT.WHITE }}>
+ <ul style={{ margin: 0, paddingLeft: '12px', fontSize: '10px', color: FINCEPT.WHITE }}>
{active_management_assessment.areas_for_improvement.map((area, idx) => (
- <li key={idx} style={{ marginBottom: SPACING.TINY }}>{area}</li>
+ <li key={idx} style={{ marginBottom: '2px' }}>{area}</li>
))}
</ul>
</div>
@@ -312,23 +373,26 @@ const ActiveManagementView: React.FC<ActiveManagementViewProps> = ({ portfolioId
{/* Recommendations */}
{improvement_recommendations && improvement_recommendations.length > 0 && (
- <div style={{ padding: `0 ${SPACING.MEDIUM} ${SPACING.MEDIUM}` }}>
+ <div style={{ padding: '0 8px 8px' }}>
<div style={{
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.CYAN,
- padding: SPACING.MEDIUM
+ borderRadius: '2px',
+ padding: '8px'
}}>
<div style={{
color: FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.SMALL
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '4px'
}}>
IMPROVEMENT RECOMMENDATIONS
</div>
- <ul style={{ margin: 0, paddingLeft: SPACING.DEFAULT, fontSize: TYPOGRAPHY.BODY, color: FINCEPT.WHITE }}>
+ <ul style={{ margin: 0, paddingLeft: '12px', fontSize: '10px', color: FINCEPT.WHITE }}>
{improvement_recommendations.map((rec, idx) => (
- <li key={idx} style={{ marginBottom: SPACING.TINY }}>{rec}</li>
+ <li key={idx} style={{ marginBottom: '2px' }}>{rec}</li>
))}
</ul>
</div>
@@ -348,37 +412,54 @@ interface MetricCardProps {
}
const MetricCard: React.FC<MetricCardProps> = ({ title, value, icon, color, subtitle }) => {
+ const [hovered, setHovered] = useState(false);
+
return (
- <div style={{
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
- padding: SPACING.MEDIUM
- }}>
+ <div
+ style={{
+ backgroundColor: hovered ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ border: BORDERS.STANDARD,
+ borderRadius: '2px',
+ padding: '12px',
+ transition: EFFECTS.TRANSITION_STANDARD,
+ cursor: 'default'
+ }}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
+ >
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
- marginBottom: SPACING.SMALL
+ marginBottom: '4px'
}}>
<div style={{
color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.SMALL,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
}}>
{title}
</div>
<div style={{ color }}>{icon}</div>
</div>
<div style={{
- color,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.TINY
+ color: FINCEPT.CYAN,
+ fontSize: '15px',
+ fontWeight: 700,
+ marginBottom: '2px'
}}>
{value}
</div>
{subtitle && (
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.SMALL }}>{subtitle}</div>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>{subtitle}</div>
)}
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AlertsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AlertsView.tsx
index bf42319ce..11a7f920c 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AlertsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AlertsView.tsx
@@ -1,8 +1,8 @@
-import React from 'react';
+import React, { useState } from 'react';
import { PortfolioSummary } from '../../../../services/portfolio/portfolioService';
import { formatCurrency } from './utils';
import { Bell } from 'lucide-react';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../finceptStyles';
+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, EFFECTS } from '../finceptStyles';
interface AlertsViewProps {
portfolioSummary: PortfolioSummary;
@@ -10,6 +10,7 @@ interface AlertsViewProps {
const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
const currency = portfolioSummary.portfolio.currency;
+ const [hoveredCard, setHoveredCard] = useState<string | null>(null);
return (
<div style={{
@@ -32,16 +33,32 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
textAlign: 'center',
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.ORANGE,
+ borderRadius: '2px',
marginBottom: SPACING.LARGE
}}>
<Bell size={64} color={FINCEPT.ORANGE} style={{ margin: `0 auto ${SPACING.MEDIUM}` }} />
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.SUBHEADING, fontWeight: TYPOGRAPHY.BOLD, marginBottom: SPACING.SMALL }}>
+ <div style={{
+ color: FINCEPT.ORANGE,
+ fontSize: '13px',
+ fontWeight: 700,
+ marginBottom: SPACING.SMALL,
+ fontFamily: TYPOGRAPHY.MONO
+ }}>
PRICE ALERTS FEATURE
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.DEFAULT, marginBottom: SPACING.MEDIUM }}>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '11px',
+ marginBottom: SPACING.MEDIUM,
+ fontFamily: TYPOGRAPHY.MONO
+ }}>
This feature is not yet implemented.
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY }}>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '11px',
+ fontFamily: TYPOGRAPHY.MONO
+ }}>
Price alerts will allow you to set notifications for:
</div>
</div>
@@ -56,12 +73,27 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
<div style={{
padding: SPACING.MEDIUM,
backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD
+ border: BORDERS.STANDARD,
+ borderRadius: '2px'
}}>
- <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.DEFAULT, fontWeight: TYPOGRAPHY.BOLD, marginBottom: SPACING.SMALL }}>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: SPACING.SMALL,
+ fontFamily: TYPOGRAPHY.MONO
+ }}>
PLANNED FEATURES
</div>
- <ul style={{ margin: 0, paddingLeft: SPACING.DEFAULT, fontSize: TYPOGRAPHY.BODY, color: FINCEPT.WHITE }}>
+ <ul style={{
+ margin: 0,
+ paddingLeft: SPACING.DEFAULT,
+ fontSize: '10px',
+ color: FINCEPT.WHITE,
+ fontFamily: TYPOGRAPHY.MONO
+ }}>
<li style={{ marginBottom: SPACING.TINY }}>Price target alerts</li>
<li style={{ marginBottom: SPACING.TINY }}>Stop loss notifications</li>
<li style={{ marginBottom: SPACING.TINY }}>Take profit alerts</li>
@@ -73,12 +105,27 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
<div style={{
padding: SPACING.MEDIUM,
backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD
+ border: BORDERS.STANDARD,
+ borderRadius: '2px'
}}>
- <div style={{ color: FINCEPT.GREEN, fontSize: TYPOGRAPHY.DEFAULT, fontWeight: TYPOGRAPHY.BOLD, marginBottom: SPACING.SMALL }}>
+ <div style={{
+ color: FINCEPT.GREEN,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: SPACING.SMALL,
+ fontFamily: TYPOGRAPHY.MONO
+ }}>
NOTIFICATION CHANNELS
</div>
- <ul style={{ margin: 0, paddingLeft: SPACING.DEFAULT, fontSize: TYPOGRAPHY.BODY, color: FINCEPT.WHITE }}>
+ <ul style={{
+ margin: 0,
+ paddingLeft: SPACING.DEFAULT,
+ fontSize: '10px',
+ color: FINCEPT.WHITE,
+ fontFamily: TYPOGRAPHY.MONO
+ }}>
<li style={{ marginBottom: SPACING.TINY }}>Desktop notifications</li>
<li style={{ marginBottom: SPACING.TINY }}>Email alerts</li>
<li style={{ marginBottom: SPACING.TINY }}>SMS notifications (Premium)</li>
@@ -91,11 +138,14 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
{/* Position-Based Alert Suggestions Preview */}
<div style={{
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
marginBottom: SPACING.MEDIUM,
paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.ORANGE
+ borderBottom: BORDERS.ORANGE,
+ fontFamily: TYPOGRAPHY.MONO
}}>
SUGGESTED ALERTS FOR YOUR POSITIONS (PREVIEW)
</div>
@@ -109,15 +159,21 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
{portfolioSummary.holdings.slice(0, 4).map(holding => {
const stopLoss = holding.avg_buy_price * 0.9;
const takeProfit = holding.avg_buy_price * 1.2;
+ const isHovered = hoveredCard === holding.id;
return (
<div
key={holding.id}
+ onMouseEnter={() => setHoveredCard(holding.id)}
+ onMouseLeave={() => setHoveredCard(null)}
style={{
padding: SPACING.MEDIUM,
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD,
- opacity: 0.6
+ backgroundColor: isHovered ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ border: isHovered ? BORDERS.CYAN : BORDERS.STANDARD,
+ borderRadius: '2px',
+ opacity: 0.6,
+ transition: EFFECTS.TRANSITION_STANDARD,
+ cursor: 'default'
}}
>
<div style={{
@@ -125,31 +181,60 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
justifyContent: 'space-between',
marginBottom: SPACING.SMALL
}}>
- <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.DEFAULT, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '10px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO
+ }}>
{holding.symbol}
</div>
- <div style={{ color: FINCEPT.WHITE, fontSize: TYPOGRAPHY.BODY }}>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '10px',
+ fontFamily: TYPOGRAPHY.MONO
+ }}>
{formatCurrency(holding.current_price, currency)}
</div>
</div>
- <div style={{ fontSize: TYPOGRAPHY.SMALL, marginBottom: SPACING.SMALL }}>
+ <div style={{ fontSize: '10px', marginBottom: SPACING.SMALL }}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
- marginBottom: SPACING.TINY,
- color: FINCEPT.GRAY
+ marginBottom: SPACING.TINY
}}>
- <span>Stop Loss (10%):</span>
- <span style={{ color: FINCEPT.RED }}>{formatCurrency(stopLoss, currency)}</span>
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ fontFamily: TYPOGRAPHY.MONO
+ }}>Stop Loss (10%):</span>
+ <span style={{
+ color: FINCEPT.RED,
+ fontSize: '10px',
+ fontFamily: TYPOGRAPHY.MONO
+ }}>{formatCurrency(stopLoss, currency)}</span>
</div>
<div style={{
display: 'flex',
- justifyContent: 'space-between',
- color: FINCEPT.GRAY
+ justifyContent: 'space-between'
}}>
- <span>Take Profit (20%):</span>
- <span style={{ color: FINCEPT.GREEN }}>{formatCurrency(takeProfit, currency)}</span>
+ <span style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ fontFamily: TYPOGRAPHY.MONO
+ }}>Take Profit (20%):</span>
+ <span style={{
+ color: FINCEPT.GREEN,
+ fontSize: '10px',
+ fontFamily: TYPOGRAPHY.MONO
+ }}>{formatCurrency(takeProfit, currency)}</span>
</div>
</div>
@@ -161,11 +246,14 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
backgroundColor: FINCEPT.GRAY,
color: FINCEPT.DARK_BG,
border: 'none',
- fontSize: TYPOGRAPHY.SMALL,
- fontWeight: TYPOGRAPHY.BOLD,
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
cursor: 'not-allowed',
fontFamily: TYPOGRAPHY.MONO,
- opacity: 0.5
+ opacity: 0.5,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
}}
>
COMING SOON
@@ -179,17 +267,25 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {
<div style={{
padding: SPACING.DEFAULT,
backgroundColor: 'rgba(255,136,0,0.05)',
- border: BORDERS.ORANGE
+ border: BORDERS.ORANGE,
+ borderRadius: '2px'
}}>
<div style={{
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.SMALL
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: SPACING.SMALL,
+ fontFamily: TYPOGRAPHY.MONO
}}>
IMPLEMENTATION STATUS
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY }}>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '10px',
+ fontFamily: TYPOGRAPHY.MONO
+ }}>
The price alerts system requires backend implementation including:
<ul style={{ marginTop: SPACING.SMALL, paddingLeft: SPACING.DEFAULT }}>
<li>Database schema for price alert conditions</li>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AnalyticsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AnalyticsView.tsx
index 034670fb1..bb6810012 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AnalyticsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/AnalyticsView.tsx
@@ -2,7 +2,7 @@ import React, { useState, useEffect } from 'react';
import { PortfolioSummary, portfolioService } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatPercent, formatLargeNumber } from './utils';
import { TrendingUp, Activity, PieChart, Target } from 'lucide-react';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, GRID_TEMPLATES } from '../finceptStyles';
+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, GRID_TEMPLATES, EFFECTS } from '../finceptStyles';
interface AnalyticsViewProps {
portfolioSummary: PortfolioSummary;
@@ -18,6 +18,13 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
const [loadingOptimization, setLoadingOptimization] = useState(false);
const [analyticsError, setAnalyticsError] = useState<string | null>(null);
+ // Hover state tracking
+ const [hoveredGainer, setHoveredGainer] = useState<string | null>(null);
+ const [hoveredLoser, setHoveredLoser] = useState<string | null>(null);
+ const [hoveredPosition, setHoveredPosition] = useState<string | null>(null);
+ const [hoveredAllocation, setHoveredAllocation] = useState<string | null>(null);
+ const [hoveredOptimize, setHoveredOptimize] = useState(false);
+
// Calculate key metrics
const totalValue = portfolioSummary.total_market_value;
const totalPnL = portfolioSummary.total_unrealized_pnl;
@@ -94,10 +101,11 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
<div style={{
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.RED,
+ borderRadius: '2px',
padding: SPACING.DEFAULT,
marginBottom: SPACING.LARGE,
color: FINCEPT.RED,
- fontSize: TYPOGRAPHY.BODY
+ fontSize: '10px'
}}>
[WARN] {analyticsError}
</div>
@@ -108,6 +116,7 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
<div style={{
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.CYAN,
+ borderRadius: '2px',
padding: SPACING.LARGE,
marginBottom: SPACING.LARGE,
}}>
@@ -119,11 +128,13 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
}}>
<div style={{
color: FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
+ fontSize: '11px',
+ fontWeight: 700,
display: 'flex',
alignItems: 'center',
- gap: SPACING.SMALL
+ gap: SPACING.SMALL,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const
}}>
<Activity size={14} color={FINCEPT.CYAN} />
ADVANCED PORTFOLIO METRICS (Python-Powered)
@@ -131,17 +142,16 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
<button
onClick={loadOptimization}
disabled={loadingOptimization}
+ onMouseEnter={() => setHoveredOptimize(true)}
+ onMouseLeave={() => setHoveredOptimize(false)}
style={{
- background: loadingOptimization ? FINCEPT.MUTED : FINCEPT.ORANGE,
- color: FINCEPT.DARK_BG,
- border: 'none',
- padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,
- fontSize: TYPOGRAPHY.SMALL,
- fontWeight: TYPOGRAPHY.BOLD,
+ ...COMMON_STYLES.buttonPrimary,
+ background: loadingOptimization ? FINCEPT.MUTED : (hoveredOptimize ? '#FF9922' : FINCEPT.ORANGE),
cursor: loadingOptimization ? 'not-allowed' : 'pointer',
display: 'flex',
alignItems: 'center',
- gap: SPACING.SMALL
+ gap: SPACING.SMALL,
+ opacity: loadingOptimization ? 0.6 : 1,
}}
>
<Target size={10} />
@@ -151,32 +161,32 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
<div style={{ ...GRID_TEMPLATES.autoFit('120px'), marginTop: SPACING.DEFAULT }}>
<div style={{ textAlign: 'center' }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, marginBottom: SPACING.SMALL }}>SHARPE RATIO</div>
- <div style={{ color: FINCEPT.GREEN, fontSize: TYPOGRAPHY.HEADING, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>SHARPE RATIO</div>
+ <div style={{ color: FINCEPT.GREEN, fontSize: '15px', fontWeight: 700 }}>
{advancedMetrics.sharpe_ratio?.toFixed(2) || 'N/A'}
</div>
</div>
<div style={{ textAlign: 'center' }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, marginBottom: SPACING.SMALL }}>VOLATILITY</div>
- <div style={{ color: FINCEPT.YELLOW, fontSize: TYPOGRAPHY.HEADING, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>VOLATILITY</div>
+ <div style={{ color: FINCEPT.YELLOW, fontSize: '15px', fontWeight: 700 }}>
{(advancedMetrics.portfolio_volatility * 100)?.toFixed(2)}%
</div>
</div>
<div style={{ textAlign: 'center' }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, marginBottom: SPACING.SMALL }}>VaR (95%)</div>
- <div style={{ color: FINCEPT.RED, fontSize: TYPOGRAPHY.HEADING, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>VaR (95%)</div>
+ <div style={{ color: FINCEPT.RED, fontSize: '15px', fontWeight: 700 }}>
{(advancedMetrics.value_at_risk_95 * 100)?.toFixed(2)}%
</div>
</div>
<div style={{ textAlign: 'center' }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, marginBottom: SPACING.SMALL }}>MAX DRAWDOWN</div>
- <div style={{ color: FINCEPT.RED, fontSize: TYPOGRAPHY.HEADING, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>MAX DRAWDOWN</div>
+ <div style={{ color: FINCEPT.RED, fontSize: '15px', fontWeight: 700 }}>
{(advancedMetrics.max_drawdown * 100)?.toFixed(2)}%
</div>
</div>
<div style={{ textAlign: 'center' }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, marginBottom: SPACING.SMALL }}>ANNUAL RETURN</div>
- <div style={{ color: FINCEPT.GREEN, fontSize: TYPOGRAPHY.HEADING, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>ANNUAL RETURN</div>
+ <div style={{ color: FINCEPT.GREEN, fontSize: '15px', fontWeight: 700 }}>
{(advancedMetrics.portfolio_return * 100)?.toFixed(2)}%
</div>
</div>
@@ -191,8 +201,10 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
}}>
<div style={{
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.BOLD,
+ fontSize: '10px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
marginBottom: SPACING.MEDIUM
}}>
OPTIMIZED ALLOCATION (Max Sharpe Ratio)
@@ -208,26 +220,27 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
padding: SPACING.SMALL,
backgroundColor: FINCEPT.DARK_BG,
border: BORDERS.STANDARD,
+ borderRadius: '2px',
}}>
<div style={{
color: FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.SMALL,
- fontWeight: TYPOGRAPHY.BOLD,
+ fontSize: '10px',
+ fontWeight: 700,
marginBottom: SPACING.TINY
}}>
{holding.symbol}
</div>
- <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
Current: {currentWeight.toFixed(1)}%
</div>
- <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.YELLOW }}>
+ <div style={{ fontSize: '9px', color: FINCEPT.YELLOW }}>
Optimal: {optimalWeight.toFixed(1)}%
</div>
<div style={{
- fontSize: TYPOGRAPHY.TINY,
+ fontSize: '9px',
color: diff > 0 ? FINCEPT.GREEN : diff < 0 ? FINCEPT.RED : FINCEPT.GRAY
}}>
- {diff > 0 ? '↑' : diff < 0 ? '↓' : '='} {Math.abs(diff).toFixed(1)}%
+ {diff > 0 ? '\u2191' : diff < 0 ? '\u2193' : '='} {Math.abs(diff).toFixed(1)}%
</div>
</div>
);
@@ -235,16 +248,16 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
</div>
<div style={{
marginTop: SPACING.MEDIUM,
- fontSize: TYPOGRAPHY.SMALL,
+ fontSize: '10px',
color: FINCEPT.GRAY
}}>
- Optimized Sharpe: <span style={{ color: FINCEPT.GREEN, fontWeight: TYPOGRAPHY.BOLD }}>
+ Optimized Sharpe: <span style={{ color: FINCEPT.GREEN, fontWeight: 700 }}>
{optimizedPortfolio.sharpe_ratio?.toFixed(2)}
</span> |
- Expected Return: <span style={{ color: FINCEPT.GREEN, fontWeight: TYPOGRAPHY.BOLD }}>
+ Expected Return: <span style={{ color: FINCEPT.GREEN, fontWeight: 700 }}>
{(optimizedPortfolio.expected_return * 100)?.toFixed(2)}%
</span> |
- Volatility: <span style={{ color: FINCEPT.YELLOW, fontWeight: TYPOGRAPHY.BOLD }}>
+ Volatility: <span style={{ color: FINCEPT.YELLOW, fontWeight: 700 }}>
{(optimizedPortfolio.volatility * 100)?.toFixed(2)}%
</span>
</div>
@@ -258,11 +271,12 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
<div style={{
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.CYAN,
+ borderRadius: '2px',
padding: SPACING.LARGE,
marginBottom: SPACING.LARGE,
textAlign: 'center',
color: FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.BODY
+ fontSize: '10px'
}}>
Loading advanced analytics...
</div>
@@ -280,15 +294,16 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
}}>
<div style={{ ...COMMON_STYLES.dataLabel }}>TOTAL VALUE</div>
<div style={{
- color: FINCEPT.YELLOW,
- fontSize: TYPOGRAPHY.LARGE,
- fontWeight: TYPOGRAPHY.BOLD
+ color: FINCEPT.CYAN,
+ fontSize: '16px',
+ fontWeight: 700
}}>
{formatLargeNumber(totalValue, currency)}
</div>
<div style={{
color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.TINY,
+ fontSize: '9px',
+ letterSpacing: '0.5px',
marginTop: SPACING.TINY
}}>
{formatCurrency(totalValue, currency)}
@@ -303,15 +318,15 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
<div style={{ ...COMMON_STYLES.dataLabel }}>TOTAL P&L</div>
<div style={{
color: totalPnL >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.LARGE,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '16px',
+ fontWeight: 700
}}>
{totalPnL >= 0 ? '+' : ''}{formatLargeNumber(totalPnL, currency)}
</div>
<div style={{
- color: totalPnL >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.BODY,
- marginTop: SPACING.TINY
+ ...(totalPnL >= 0 ? COMMON_STYLES.badgeSuccess : COMMON_STYLES.badgeError),
+ marginTop: SPACING.TINY,
+ display: 'inline-block'
}}>
{formatPercent(totalPnLPercent)}
</div>
@@ -325,15 +340,15 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
<div style={{ ...COMMON_STYLES.dataLabel }}>DAY CHANGE</div>
<div style={{
color: dayChange >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.LARGE,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '16px',
+ fontWeight: 700
}}>
{dayChange >= 0 ? '+' : ''}{formatLargeNumber(dayChange, currency)}
</div>
<div style={{
- color: dayChange >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.BODY,
- marginTop: SPACING.TINY
+ ...(dayChange >= 0 ? COMMON_STYLES.badgeSuccess : COMMON_STYLES.badgeError),
+ marginTop: SPACING.TINY,
+ display: 'inline-block'
}}>
{formatPercent(dayChangePercent)}
</div>
@@ -347,15 +362,15 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
<div style={{ ...COMMON_STYLES.dataLabel }}>POSITIONS</div>
<div style={{
color: FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.LARGE,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '16px',
+ fontWeight: 700
}}>
{positionsCount}
</div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.TINY,
- marginTop: SPACING.TINY
+ ...COMMON_STYLES.badgeInfo,
+ marginTop: SPACING.TINY,
+ display: 'inline-block'
}}>
Active Holdings
</div>
@@ -367,44 +382,47 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Top Gainers */}
<div>
<div style={{
+ ...COMMON_STYLES.sectionHeader,
color: FINCEPT.GREEN,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
+ borderBottom: BORDERS.GREEN,
marginBottom: SPACING.MEDIUM,
- paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.GREEN
}}>
TOP GAINERS
</div>
{topGainers.length === 0 ? (
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY, padding: SPACING.MEDIUM }}>No data</div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px', padding: SPACING.MEDIUM }}>No data</div>
) : (
topGainers.map(holding => (
<div
key={holding.id}
+ onMouseEnter={() => setHoveredGainer(holding.id)}
+ onMouseLeave={() => setHoveredGainer(null)}
style={{
padding: SPACING.MEDIUM,
marginBottom: SPACING.SMALL,
- backgroundColor: FINCEPT.PANEL_BG,
+ backgroundColor: hoveredGainer === holding.id ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
borderLeft: `3px solid ${FINCEPT.GREEN}`,
+ borderRadius: '2px',
display: 'flex',
justifyContent: 'space-between',
- alignItems: 'center'
+ alignItems: 'center',
+ transition: EFFECTS.TRANSITION_STANDARD,
+ cursor: 'default'
}}
>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
{holding.symbol}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', letterSpacing: '0.5px' }}>
{formatCurrency(holding.market_value, currency)}
</div>
</div>
<div style={{ textAlign: 'right' }}>
- <div style={{ color: FINCEPT.GREEN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ ...COMMON_STYLES.badgeSuccess }}>
+{formatPercent(holding.unrealized_pnl_percent)}
</div>
- <div style={{ color: FINCEPT.GREEN, fontSize: TYPOGRAPHY.TINY }}>
+ <div style={{ color: FINCEPT.GREEN, fontSize: '9px', marginTop: SPACING.TINY }}>
+{formatCurrency(holding.unrealized_pnl, currency)}
</div>
</div>
@@ -416,44 +434,47 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Top Losers */}
<div>
<div style={{
+ ...COMMON_STYLES.sectionHeader,
color: FINCEPT.RED,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
+ borderBottom: BORDERS.RED,
marginBottom: SPACING.MEDIUM,
- paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.RED
}}>
TOP LOSERS
</div>
{topLosers.length === 0 ? (
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY, padding: SPACING.MEDIUM }}>No data</div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px', padding: SPACING.MEDIUM }}>No data</div>
) : (
topLosers.map(holding => (
<div
key={holding.id}
+ onMouseEnter={() => setHoveredLoser(holding.id)}
+ onMouseLeave={() => setHoveredLoser(null)}
style={{
padding: SPACING.MEDIUM,
marginBottom: SPACING.SMALL,
- backgroundColor: FINCEPT.PANEL_BG,
+ backgroundColor: hoveredLoser === holding.id ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
borderLeft: `3px solid ${FINCEPT.RED}`,
+ borderRadius: '2px',
display: 'flex',
justifyContent: 'space-between',
- alignItems: 'center'
+ alignItems: 'center',
+ transition: EFFECTS.TRANSITION_STANDARD,
+ cursor: 'default'
}}
>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
{holding.symbol}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', letterSpacing: '0.5px' }}>
{formatCurrency(holding.market_value, currency)}
</div>
</div>
<div style={{ textAlign: 'right' }}>
- <div style={{ color: FINCEPT.RED, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ ...COMMON_STYLES.badgeError }}>
{formatPercent(holding.unrealized_pnl_percent)}
</div>
- <div style={{ color: FINCEPT.RED, fontSize: TYPOGRAPHY.TINY }}>
+ <div style={{ color: FINCEPT.RED, fontSize: '9px', marginTop: SPACING.TINY }}>
{formatCurrency(holding.unrealized_pnl, currency)}
</div>
</div>
@@ -465,46 +486,50 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Largest Positions */}
<div>
<div style={{
+ ...COMMON_STYLES.sectionHeader,
color: FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
+ borderBottom: BORDERS.CYAN,
marginBottom: SPACING.MEDIUM,
- paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.CYAN
}}>
LARGEST POSITIONS
</div>
{largestPositions.length === 0 ? (
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY, padding: SPACING.MEDIUM }}>No data</div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px', padding: SPACING.MEDIUM }}>No data</div>
) : (
largestPositions.map(holding => (
<div
key={holding.id}
+ onMouseEnter={() => setHoveredPosition(holding.id)}
+ onMouseLeave={() => setHoveredPosition(null)}
style={{
padding: SPACING.MEDIUM,
marginBottom: SPACING.SMALL,
- backgroundColor: FINCEPT.PANEL_BG,
+ backgroundColor: hoveredPosition === holding.id ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
borderLeft: `3px solid ${FINCEPT.CYAN}`,
+ borderRadius: '2px',
display: 'flex',
justifyContent: 'space-between',
- alignItems: 'center'
+ alignItems: 'center',
+ transition: EFFECTS.TRANSITION_STANDARD,
+ cursor: 'default'
}}
>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
{holding.symbol}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', letterSpacing: '0.5px' }}>
Weight: {holding.weight.toFixed(1)}%
</div>
</div>
<div style={{ textAlign: 'right' }}>
- <div style={{ color: FINCEPT.WHITE, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
{formatLargeNumber(holding.market_value, currency)}
</div>
<div style={{
- color: holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.TINY
+ ...(holding.unrealized_pnl >= 0 ? COMMON_STYLES.badgeSuccess : COMMON_STYLES.badgeError),
+ marginTop: SPACING.TINY,
+ display: 'inline-block'
}}>
{formatPercent(holding.unrealized_pnl_percent)}
</div>
@@ -518,12 +543,10 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{/* Allocation Summary */}
<div>
<div style={{
+ ...COMMON_STYLES.sectionHeader,
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
+ borderBottom: BORDERS.ORANGE,
marginBottom: SPACING.DEFAULT,
- paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.ORANGE
}}>
ALLOCATION BREAKDOWN
</div>
@@ -536,10 +559,15 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
{portfolioSummary.holdings.map(holding => (
<div
key={holding.id}
+ onMouseEnter={() => setHoveredAllocation(holding.id)}
+ onMouseLeave={() => setHoveredAllocation(null)}
style={{
padding: SPACING.MEDIUM,
- backgroundColor: FINCEPT.PANEL_BG,
+ backgroundColor: hoveredAllocation === holding.id ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
border: BORDERS.STANDARD,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD,
+ cursor: 'default'
}}
>
<div style={{
@@ -548,10 +576,10 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
alignItems: 'center',
marginBottom: SPACING.SMALL
}}>
- <span style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <span style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
{holding.symbol}
</span>
- <span style={{ color: FINCEPT.YELLOW, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <span style={{ color: FINCEPT.YELLOW, fontSize: '10px', fontWeight: 700 }}>
{holding.weight.toFixed(1)}%
</span>
</div>
@@ -559,25 +587,28 @@ const AnalyticsView: React.FC<AnalyticsViewProps> = ({ portfolioSummary }) => {
width: '100%',
height: '4px',
backgroundColor: FINCEPT.BORDER,
+ borderRadius: '2px',
overflow: 'hidden'
}}>
<div style={{
width: `${holding.weight}%`,
height: '100%',
backgroundColor: FINCEPT.YELLOW,
- transition: 'width 0.3s'
+ transition: 'width 0.3s',
+ borderRadius: '2px'
}} />
</div>
<div style={{
marginTop: SPACING.SMALL,
display: 'flex',
justifyContent: 'space-between',
- fontSize: TYPOGRAPHY.TINY,
- color: FINCEPT.GRAY
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px'
}}>
<span>{formatLargeNumber(holding.market_value, currency)}</span>
<span style={{
- color: holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED
+ ...(holding.unrealized_pnl >= 0 ? COMMON_STYLES.badgeSuccess : COMMON_STYLES.badgeError),
}}>
{formatPercent(holding.unrealized_pnl_percent)}
</span>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/HistoryView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/HistoryView.tsx
index 3b8827597..42f36ae73 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/HistoryView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/HistoryView.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import { Transaction } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatNumber, formatDateTime } from './utils';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../finceptStyles';
+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS, COMMON_STYLES } from '../finceptStyles';
interface HistoryViewProps {
transactions: Transaction[];
@@ -15,24 +15,23 @@ const HistoryView: React.FC<HistoryViewProps> = ({ transactions, currency }) =>
display: 'flex',
flexDirection: 'column',
backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.DEFAULT,
- overflow: 'hidden'
+ overflow: 'hidden',
+ fontFamily: TYPOGRAPHY.MONO,
}}>
{/* Section Header */}
<div style={{
...COMMON_STYLES.sectionHeader,
- marginBottom: SPACING.MEDIUM
+ marginBottom: '0px',
}}>
TRANSACTION HISTORY
</div>
{transactions.length === 0 ? (
<div style={{
- padding: SPACING.XLARGE,
- textAlign: 'center',
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontFamily: TYPOGRAPHY.MONO
+ ...COMMON_STYLES.emptyState,
+ padding: '24px',
+ height: 'auto',
+ flex: 1,
}}>
No transactions yet
</div>
@@ -42,15 +41,16 @@ const HistoryView: React.FC<HistoryViewProps> = ({ transactions, currency }) =>
<div style={{
display: 'grid',
gridTemplateColumns: '1.5fr 1fr 0.8fr 1fr 1fr 1fr 2fr',
- gap: SPACING.MEDIUM,
- padding: SPACING.MEDIUM,
+ gap: '8px',
+ padding: '8px 12px',
backgroundColor: FINCEPT.HEADER_BG,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.BOLD,
- borderBottom: BORDERS.ORANGE,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ borderBottom: `1px solid ${FINCEPT.ORANGE}`,
position: 'sticky',
top: 0,
- zIndex: 1
+ zIndex: 1,
}}>
<div style={{ color: FINCEPT.ORANGE }}>DATE</div>
<div style={{ color: FINCEPT.ORANGE }}>SYMBOL</div>
@@ -68,33 +68,42 @@ const HistoryView: React.FC<HistoryViewProps> = ({ transactions, currency }) =>
style={{
display: 'grid',
gridTemplateColumns: '1.5fr 1fr 0.8fr 1fr 1fr 1fr 2fr',
- gap: SPACING.MEDIUM,
- padding: SPACING.MEDIUM,
+ gap: '8px',
+ padding: '8px 12px',
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent',
borderLeft: `3px solid ${txn.transaction_type === 'BUY' ? FINCEPT.GREEN : FINCEPT.RED}`,
- fontSize: TYPOGRAPHY.BODY,
+ fontSize: '10px',
marginBottom: '1px',
fontFamily: TYPOGRAPHY.MONO,
minHeight: '32px',
- alignItems: 'center'
+ alignItems: 'center',
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = FINCEPT.HOVER; }}
+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent'; }}
>
<div style={{ color: FINCEPT.GRAY }}>
{formatDateTime(txn.transaction_date)}
</div>
- <div style={{ color: FINCEPT.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{txn.symbol}</div>
- <div style={{
- color: txn.transaction_type === 'BUY' ? FINCEPT.GREEN : FINCEPT.RED,
- fontWeight: TYPOGRAPHY.BOLD
- }}>
- {txn.transaction_type}
+ <div style={{ color: FINCEPT.CYAN, fontWeight: 600 }}>{txn.symbol}</div>
+ <div>
+ <span style={{
+ padding: '2px 6px',
+ backgroundColor: txn.transaction_type === 'BUY' ? `${FINCEPT.GREEN}20` : `${FINCEPT.RED}20`,
+ color: txn.transaction_type === 'BUY' ? FINCEPT.GREEN : FINCEPT.RED,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ }}>
+ {txn.transaction_type}
+ </span>
</div>
- <div style={{ color: FINCEPT.WHITE, textAlign: 'right' }}>{formatNumber(txn.quantity, 4)}</div>
- <div style={{ color: FINCEPT.WHITE, textAlign: 'right' }}>{formatCurrency(txn.price, currency)}</div>
- <div style={{ color: FINCEPT.YELLOW, textAlign: 'right', fontWeight: TYPOGRAPHY.SEMIBOLD }}>
+ <div style={{ color: FINCEPT.CYAN, textAlign: 'right' }}>{formatNumber(txn.quantity, 4)}</div>
+ <div style={{ color: FINCEPT.CYAN, textAlign: 'right' }}>{formatCurrency(txn.price, currency)}</div>
+ <div style={{ color: FINCEPT.YELLOW, textAlign: 'right', fontWeight: 600 }}>
{formatCurrency(txn.total_value, currency)}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.SMALL }}>{txn.notes || '-'}</div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>{txn.notes || '-'}</div>
</div>
))}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PerformanceView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PerformanceView.tsx
index cdf338a78..1b34b5459 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PerformanceView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PerformanceView.tsx
@@ -1,7 +1,7 @@
import React, { useState, useEffect } from 'react';
import { PortfolioSummary, portfolioService, PortfolioSnapshot } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatPercent } from './utils';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../finceptStyles';
+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS, COMMON_STYLES } from '../finceptStyles';
interface PerformanceViewProps {
portfolioSummary: PortfolioSummary;
@@ -14,10 +14,13 @@ interface PerformanceDataPoint {
changePercent: number;
}
+const FONT_FAMILY = TYPOGRAPHY.MONO;
+
const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) => {
const currency = portfolioSummary.portfolio.currency;
const [performanceData, setPerformanceData] = useState<PerformanceDataPoint[]>([]);
const [loading, setLoading] = useState(true);
+ const [hoveredRow, setHoveredRow] = useState<number | null>(null);
useEffect(() => {
const loadPerformanceData = async () => {
@@ -86,12 +89,12 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
backgroundColor: FINCEPT.DARK_BG,
padding: SPACING.XLARGE,
textAlign: 'center',
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily: FONT_FAMILY
}}>
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.SUBHEADING, marginBottom: SPACING.SMALL }}>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '11px', fontWeight: 700, marginBottom: SPACING.SMALL }}>
Loading performance data...
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
Fetching portfolio snapshots from database
</div>
</div>
@@ -105,12 +108,12 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
backgroundColor: FINCEPT.DARK_BG,
padding: SPACING.XLARGE,
textAlign: 'center',
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily: FONT_FAMILY
}}>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.SUBHEADING, marginBottom: SPACING.SMALL }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '11px', fontWeight: 700, marginBottom: SPACING.SMALL }}>
No performance data available
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
Portfolio snapshots will be created automatically as you use the application
</div>
</div>
@@ -167,7 +170,7 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
backgroundColor: FINCEPT.DARK_BG,
padding: SPACING.DEFAULT,
overflow: 'auto',
- fontFamily: TYPOGRAPHY.MONO
+ fontFamily: FONT_FAMILY
}}>
<div style={{
...COMMON_STYLES.sectionHeader,
@@ -185,13 +188,20 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
}}>
<div style={{
...COMMON_STYLES.metricCard,
+ borderRadius: '2px',
border: periodReturn >= 0 ? BORDERS.GREEN : BORDERS.RED
}}>
- <div style={COMMON_STYLES.dataLabel}>PERIOD RETURN</div>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const
+ }}>PERIOD RETURN</div>
<div style={{
color: periodReturn >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.SUBHEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '10px',
+ fontWeight: 700
}}>
{formatPercent(periodReturn)}
</div>
@@ -199,13 +209,20 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
<div style={{
...COMMON_STYLES.metricCard,
+ borderRadius: '2px',
border: periodGain >= 0 ? BORDERS.GREEN : BORDERS.RED
}}>
- <div style={COMMON_STYLES.dataLabel}>PERIOD GAIN</div>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const
+ }}>PERIOD GAIN</div>
<div style={{
color: periodGain >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.SUBHEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '10px',
+ fontWeight: 700
}}>
{formatCurrency(periodGain, currency)}
</div>
@@ -213,13 +230,20 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
<div style={{
...COMMON_STYLES.metricCard,
+ borderRadius: '2px',
border: `1px solid ${FINCEPT.YELLOW}`
}}>
- <div style={COMMON_STYLES.dataLabel}>CURRENT VALUE</div>
<div style={{
- color: FINCEPT.YELLOW,
- fontSize: TYPOGRAPHY.SUBHEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const
+ }}>CURRENT VALUE</div>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '10px',
+ fontWeight: 700
}}>
{formatCurrency(latestValue, currency)}
</div>
@@ -227,13 +251,20 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
<div style={{
...COMMON_STYLES.metricCard,
+ borderRadius: '2px',
border: BORDERS.CYAN
}}>
- <div style={COMMON_STYLES.dataLabel}>START VALUE</div>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const
+ }}>START VALUE</div>
<div style={{
color: FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.SUBHEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '10px',
+ fontWeight: 700
}}>
{formatCurrency(earliestValue, currency)}
</div>
@@ -241,13 +272,20 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
<div style={{
...COMMON_STYLES.metricCard,
+ borderRadius: '2px',
border: BORDERS.ORANGE
}}>
- <div style={COMMON_STYLES.dataLabel}>VOLATILITY</div>
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const
+ }}>VOLATILITY</div>
<div style={{
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.SUBHEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '10px',
+ fontWeight: 700
}}>
{((valueRange / earliestValue) * 100).toFixed(2)}%
</div>
@@ -256,8 +294,9 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
{/* Chart */}
<div style={{
- backgroundColor: 'rgba(0,0,0,0.3)',
+ backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.STANDARD,
+ borderRadius: '2px',
padding: SPACING.DEFAULT,
marginBottom: SPACING.LARGE
}}>
@@ -284,7 +323,7 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
textAnchor="end"
fill={FINCEPT.GRAY}
fontSize="9"
- fontFamily={TYPOGRAPHY.MONO}
+ fontFamily={FONT_FAMILY}
>
{formatCurrency(value, currency)}
</text>
@@ -304,7 +343,7 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
textAnchor="middle"
fill={FINCEPT.GRAY}
fontSize="8"
- fontFamily={TYPOGRAPHY.MONO}
+ fontFamily={FONT_FAMILY}
>
{d.date.substring(5)}
</text>
@@ -356,7 +395,7 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
fill={FINCEPT.YELLOW}
fontSize="10"
fontWeight="bold"
- fontFamily={TYPOGRAPHY.MONO}
+ fontFamily={FONT_FAMILY}
>
COST BASIS
</text>
@@ -369,7 +408,7 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
fill={FINCEPT.ORANGE}
fontSize="12"
fontWeight="bold"
- fontFamily={TYPOGRAPHY.MONO}
+ fontFamily={FONT_FAMILY}
>
PORTFOLIO VALUE OVER TIME
</text>
@@ -379,8 +418,10 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
{/* Performance Table */}
<div style={{
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
marginBottom: SPACING.SMALL,
paddingBottom: SPACING.SMALL,
borderBottom: BORDERS.ORANGE
@@ -396,8 +437,9 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
gap: SPACING.SMALL,
padding: SPACING.SMALL,
backgroundColor: FINCEPT.HEADER_BG,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.BOLD,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
position: 'sticky',
top: 0,
zIndex: 1,
@@ -413,32 +455,40 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
{performanceData.slice().reverse().map((d, index) => (
<div
key={d.date}
+ onMouseEnter={() => setHoveredRow(index)}
+ onMouseLeave={() => setHoveredRow(null)}
style={{
display: 'grid',
gridTemplateColumns: '1fr 1.2fr 1fr 1fr',
gap: SPACING.SMALL,
padding: SPACING.SMALL,
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent',
+ backgroundColor: hoveredRow === index
+ ? FINCEPT.HOVER
+ : index % 2 === 0
+ ? 'rgba(255,255,255,0.03)'
+ : 'transparent',
borderLeft: `3px solid ${d.changePercent >= 0 ? FINCEPT.GREEN : FINCEPT.RED}`,
- fontSize: TYPOGRAPHY.BODY,
- marginBottom: '2px'
+ fontSize: '10px',
+ marginBottom: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD,
+ cursor: 'default'
}}
>
<div style={{ color: FINCEPT.GRAY }}>{d.date}</div>
- <div style={{ color: FINCEPT.WHITE, textAlign: 'right', fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.CYAN, textAlign: 'right', fontWeight: 700 }}>
{formatCurrency(d.value, currency)}
</div>
<div style={{
color: d.change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
textAlign: 'right',
- fontWeight: TYPOGRAPHY.BOLD
+ fontWeight: 700
}}>
{formatCurrency(d.change, currency)}
</div>
<div style={{
color: d.changePercent >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
textAlign: 'right',
- fontWeight: TYPOGRAPHY.BOLD
+ fontWeight: 700
}}>
{formatPercent(d.changePercent)}
</div>
@@ -453,7 +503,8 @@ const PerformanceView: React.FC<PerformanceViewProps> = ({ portfolioSummary }) =
padding: SPACING.MEDIUM,
backgroundColor: 'rgba(255,136,0,0.05)',
border: BORDERS.ORANGE,
- fontSize: TYPOGRAPHY.SMALL,
+ borderRadius: '2px',
+ fontSize: '10px',
color: FINCEPT.GRAY
}}>
<strong style={{ color: FINCEPT.ORANGE }}>TIP:</strong> Portfolio snapshots are created automatically.
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PortfolioOptimizationView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PortfolioOptimizationView.tsx
index 3e219d825..da894d910 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PortfolioOptimizationView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PortfolioOptimizationView.tsx
@@ -4,6 +4,7 @@ import { TrendingUp, BarChart3, PieChart, LineChart, Target, Shield, Calculator,
import { PortfolioSummary } from '../../../../services/portfolio/portfolioService';
import { LineChart as RechartsLine, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Scatter, ScatterChart, ZAxis } from 'recharts';
import { getSetting, saveSetting } from '@/services/core/sqliteService';
+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, EFFECTS } from '../finceptStyles';
// Library selection
const LIBRARIES = [
@@ -624,14 +625,14 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
return (
<div style={{
height: '100%',
- backgroundColor: '#000000',
- color: '#FFFFFF',
- fontFamily: 'IBM Plex Mono, monospace',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ fontFamily: TYPOGRAPHY.MONO,
overflow: 'auto',
- padding: '16px'
+ padding: SPACING.LARGE
}}>
{/* Navigation Tabs */}
- <div style={{ display: 'flex', gap: '8px', marginBottom: '24px', borderBottom: '1px solid #333' }}>
+ <div style={{ display: 'flex', gap: SPACING.MEDIUM, marginBottom: SPACING.XLARGE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
{[
{ id: 'optimize', label: 'OPTIMIZE', icon: Calculator },
{ id: 'frontier', label: 'EFFICIENT FRONTIER', icon: LineChart },
@@ -643,18 +644,22 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
key={id}
onClick={() => setActiveTab(id as any)}
style={{
- padding: '8px 16px',
- backgroundColor: activeTab === id ? '#FF8800' : 'transparent',
- color: activeTab === id ? '#000' : '#FFF',
+ padding: '6px 12px',
+ backgroundColor: activeTab === id ? FINCEPT.ORANGE : 'transparent',
+ color: activeTab === id ? FINCEPT.DARK_BG : FINCEPT.GRAY,
border: 'none',
- borderBottom: activeTab === id ? '2px solid #FF8800' : '2px solid transparent',
+ borderBottom: activeTab === id ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
+ borderRadius: '2px',
cursor: 'pointer',
- fontFamily: 'inherit',
- fontSize: '11px',
- fontWeight: 'bold',
+ fontFamily: TYPOGRAPHY.MONO,
+ fontSize: TYPOGRAPHY.TINY,
+ fontWeight: TYPOGRAPHY.BOLD,
+ letterSpacing: TYPOGRAPHY.WIDE,
+ textTransform: 'uppercase' as const,
+ transition: EFFECTS.TRANSITION_STANDARD,
display: 'flex',
alignItems: 'center',
- gap: '4px'
+ gap: SPACING.SMALL
}}
>
<Icon size={14} />
@@ -672,20 +677,21 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- border: '1px solid #333',
+ border: BORDERS.STANDARD,
+ borderRadius: '2px',
flexDirection: 'column',
- gap: '8px',
+ gap: SPACING.MEDIUM,
padding: '20px'
}}>
<div style={{
width: '32px',
height: '32px',
- border: '3px solid #333',
- borderTop: '3px solid #00E5FF',
+ border: `3px solid ${FINCEPT.BORDER}`,
+ borderTop: `3px solid ${FINCEPT.CYAN}`,
borderRadius: '50%',
animation: 'spin 1s linear infinite'
}} />
- <div style={{ color: '#00E5FF', fontSize: '11px', fontWeight: '500' }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY, fontWeight: 500 }}>
{activeTab === 'optimize' && 'Optimizing...'}
{activeTab === 'backtest' && 'Running Backtest...'}
{activeTab === 'allocation' && 'Calculating...'}
@@ -703,12 +709,13 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{/* Error Display */}
{error && (
<div style={{
- padding: '12px',
- backgroundColor: 'rgba(255,59,59,0.1)',
- border: '1px solid #FF3B3B',
- color: '#FF3B3B',
- marginBottom: '16px',
- fontSize: '11px'
+ padding: SPACING.DEFAULT,
+ backgroundColor: `${FINCEPT.RED}1A`,
+ border: BORDERS.RED,
+ borderRadius: '2px',
+ color: FINCEPT.RED,
+ marginBottom: SPACING.LARGE,
+ fontSize: TYPOGRAPHY.BODY
}}>
ERROR: {error}
</div>
@@ -716,23 +723,20 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{/* OPTIMIZE TAB */}
{activeTab === 'optimize' && (
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.XLARGE }}>
{/* Configuration Panel */}
<div>
<div style={{
- color: '#FF8800',
- fontSize: '12px',
- fontWeight: 'bold',
- marginBottom: '16px',
- borderBottom: '1px solid #FF8800',
- paddingBottom: '8px'
+ ...COMMON_STYLES.sectionHeader,
+ borderBottom: `1px solid ${FINCEPT.ORANGE}`,
+ paddingBottom: SPACING.MEDIUM
}}>
OPTIMIZATION CONFIGURATION
</div>
{/* Library Selection */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <div style={{ marginBottom: SPACING.LARGE }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
OPTIMIZATION LIBRARY
</label>
<select
@@ -747,13 +751,8 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
}
}}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
>
{LIBRARIES.map(lib => (
@@ -765,19 +764,20 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{/* Portfolio Info */}
{portfolioSummary && portfolioSummary.portfolio && (
<div style={{
- marginBottom: '16px',
- padding: '8px 12px',
- backgroundColor: '#0F0F0F',
- border: '1px solid #333',
- borderLeft: '3px solid #00E5FF'
+ marginBottom: SPACING.LARGE,
+ padding: `${SPACING.MEDIUM} ${SPACING.DEFAULT}`,
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: BORDERS.STANDARD,
+ borderLeft: `3px solid ${FINCEPT.CYAN}`,
+ borderRadius: '2px'
}}>
- <div style={{ fontSize: '9px', color: '#787878', marginBottom: '4px' }}>
+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>
OPTIMIZING PORTFOLIO
</div>
- <div style={{ fontSize: '11px', color: '#00E5FF', fontWeight: 'bold' }}>
+ <div style={{ fontSize: TYPOGRAPHY.BODY, color: FINCEPT.CYAN, fontWeight: TYPOGRAPHY.BOLD }}>
{portfolioSummary.portfolio.name}
</div>
- <div style={{ fontSize: '9px', color: '#787878', marginTop: '4px' }}>
+ <div style={{ ...COMMON_STYLES.dataLabel, marginTop: SPACING.SMALL }}>
{portfolioSummary.holdings?.length || 0} holdings • Total Value: {new Intl.NumberFormat('en-US', {
style: 'currency',
currency: portfolioSummary.portfolio.currency || 'USD'
@@ -787,11 +787,11 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
)}
{/* Asset Symbols */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <div style={{ marginBottom: SPACING.LARGE }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
ASSET SYMBOLS (comma-separated)
{portfolioSummary?.holdings && portfolioSummary.holdings.length > 0 && (
- <span style={{ color: '#00E5FF', marginLeft: '8px', fontSize: '9px' }}>
+ <span style={{ color: FINCEPT.CYAN, marginLeft: SPACING.MEDIUM, fontSize: TYPOGRAPHY.TINY }}>
• From portfolio
</span>
)}
@@ -801,39 +801,29 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
value={assetSymbols}
onChange={(e) => setAssetSymbols(e.target.value)}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
placeholder="AAPL,GOOGL,MSFT,AMZN,TSLA"
/>
{(!portfolioSummary || portfolioSummary.holdings.length === 0) && (
- <div style={{ fontSize: '9px', color: '#FF8800', marginTop: '4px' }}>
+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.ORANGE, marginTop: SPACING.SMALL }}>
No portfolio selected. Using default symbols.
</div>
)}
</div>
{/* Optimization Method */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <div style={{ marginBottom: SPACING.LARGE }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
OPTIMIZATION METHOD
</label>
<select
value={config.optimization_method}
onChange={(e) => setConfig({ ...config, optimization_method: e.target.value })}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
>
{(library === 'skfolio' ? SKFOLIO_METHODS : PYPORTFOLIOOPT_METHODS).map(m => (
@@ -843,21 +833,16 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
</div>
{/* Objective */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <div style={{ marginBottom: SPACING.LARGE }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
OBJECTIVE FUNCTION
</label>
<select
value={config.objective}
onChange={(e) => setConfig({ ...config, objective: e.target.value })}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
>
{(library === 'skfolio' ? SKFOLIO_OBJECTIVES : PYPORTFOLIOOPT_OBJECTIVES).map(o => (
@@ -868,21 +853,16 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{/* skfolio-specific: Risk Measure */}
{library === 'skfolio' && (
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <div style={{ marginBottom: SPACING.LARGE }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
RISK MEASURE
</label>
<select
value={skfolioConfig.risk_measure}
onChange={(e) => setSkfolioConfig({ ...skfolioConfig, risk_measure: e.target.value })}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
>
{SKFOLIO_RISK_MEASURES.map(r => (
@@ -893,21 +873,16 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
)}
{/* Expected Returns Method */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <div style={{ marginBottom: SPACING.LARGE }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
EXPECTED RETURNS METHOD
</label>
<select
value={config.expected_returns_method}
onChange={(e) => setConfig({ ...config, expected_returns_method: e.target.value })}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
>
{EXPECTED_RETURNS_METHODS.map(m => (
@@ -917,21 +892,16 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
</div>
{/* Risk Model */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <div style={{ marginBottom: SPACING.LARGE }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
RISK MODEL
</label>
<select
value={config.risk_model_method}
onChange={(e) => setConfig({ ...config, risk_model_method: e.target.value })}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
>
{RISK_MODELS.map(m => (
@@ -941,8 +911,8 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
</div>
{/* Risk-Free Rate */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <div style={{ marginBottom: SPACING.LARGE }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
RISK-FREE RATE (%)
</label>
<input
@@ -951,21 +921,16 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
value={config.risk_free_rate * 100}
onChange={(e) => setConfig({ ...config, risk_free_rate: parseFloat(e.target.value) / 100 })}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
/>
</div>
{/* Weight Bounds */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '16px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.MEDIUM, marginBottom: SPACING.LARGE }}>
<div>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
MIN WEIGHT (%)
</label>
<input
@@ -974,18 +939,13 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
value={config.weight_bounds_min * 100}
onChange={(e) => setConfig({ ...config, weight_bounds_min: parseFloat(e.target.value) / 100 })}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
/>
</div>
<div>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
MAX WEIGHT (%)
</label>
<input
@@ -994,21 +954,16 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
value={config.weight_bounds_max * 100}
onChange={(e) => setConfig({ ...config, weight_bounds_max: parseFloat(e.target.value) / 100 })}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
/>
</div>
</div>
{/* L2 Regularization */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <div style={{ marginBottom: SPACING.LARGE }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
L2 REGULARIZATION (Gamma)
</label>
<input
@@ -1017,20 +972,15 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
value={config.gamma}
onChange={(e) => setConfig({ ...config, gamma: parseFloat(e.target.value) })}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
/>
</div>
{/* Portfolio Value */}
- <div style={{ marginBottom: '16px' }}>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <div style={{ marginBottom: SPACING.LARGE }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
TOTAL PORTFOLIO VALUE ($)
</label>
<input
@@ -1039,13 +989,8 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
value={config.total_portfolio_value}
onChange={(e) => setConfig({ ...config, total_portfolio_value: parseFloat(e.target.value) })}
style={{
- width: '100%',
- padding: '8px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
/>
</div>
@@ -1056,36 +1001,39 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
disabled={loadingAction === 'optimize'}
style={{
width: '100%',
- padding: '12px',
- backgroundColor: loadingAction === 'optimize' ? '#4A4A4A' : '#FF8800',
- color: loadingAction === 'optimize' ? '#787878' : '#000',
- border: loadingAction === 'optimize' ? '1px solid #666' : 'none',
- fontFamily: 'inherit',
- fontSize: '12px',
- fontWeight: 'bold',
+ padding: `${SPACING.DEFAULT} ${SPACING.LARGE}`,
+ backgroundColor: loadingAction === 'optimize' ? FINCEPT.MUTED : FINCEPT.ORANGE,
+ color: loadingAction === 'optimize' ? FINCEPT.GRAY : FINCEPT.DARK_BG,
+ border: loadingAction === 'optimize' ? `1px solid ${FINCEPT.GRAY}` : 'none',
+ borderRadius: '2px',
+ fontFamily: TYPOGRAPHY.MONO,
+ fontSize: TYPOGRAPHY.SMALL,
+ fontWeight: TYPOGRAPHY.BOLD,
+ letterSpacing: TYPOGRAPHY.WIDE,
+ textTransform: 'uppercase' as const,
cursor: loadingAction === 'optimize' ? 'not-allowed' : 'pointer',
opacity: loadingAction === 'optimize' ? 0.6 : 1,
- transition: 'all 0.2s ease',
+ transition: EFFECTS.TRANSITION_STANDARD,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- gap: '8px'
+ gap: SPACING.MEDIUM
}}
>
<Target size={16} />
{loadingAction === 'optimize' ? 'OPTIMIZING...' : 'RUN OPTIMIZATION'}
</button>
{loadingAction === 'optimize' && (
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px', marginTop: '12px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: SPACING.MEDIUM, marginTop: SPACING.DEFAULT }}>
<div style={{
width: '16px',
height: '16px',
- border: '2px solid #333',
- borderTop: '2px solid #00E5FF',
+ border: `2px solid ${FINCEPT.BORDER}`,
+ borderTop: `2px solid ${FINCEPT.CYAN}`,
borderRadius: '50%',
animation: 'spin 0.8s linear infinite'
}} />
- <span style={{ color: '#00E5FF', fontSize: '11px' }}>Running optimization...</span>
+ <span style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY }}>Running optimization...</span>
</div>
)}
</div>
@@ -1093,12 +1041,9 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{/* Results Panel */}
<div>
<div style={{
- color: '#FF8800',
- fontSize: '12px',
- fontWeight: 'bold',
- marginBottom: '16px',
- borderBottom: '1px solid #FF8800',
- paddingBottom: '8px'
+ ...COMMON_STYLES.sectionHeader,
+ borderBottom: `1px solid ${FINCEPT.ORANGE}`,
+ paddingBottom: SPACING.MEDIUM
}}>
OPTIMIZATION RESULTS
</div>
@@ -1106,47 +1051,47 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{results?.performance_metrics && (
<>
{/* Performance Metrics */}
- <div style={{ marginBottom: '24px' }}>
- <div style={{ color: '#00E5FF', fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
+ <div style={{ marginBottom: SPACING.XLARGE }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD, marginBottom: SPACING.MEDIUM }}>
PERFORMANCE METRICS
</div>
- <div style={{ backgroundColor: '#0F0F0F', padding: '12px', border: '1px solid #333' }}>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px', fontSize: '10px' }}>
+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, padding: SPACING.DEFAULT, border: BORDERS.STANDARD, borderRadius: '2px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: SPACING.DEFAULT, fontSize: TYPOGRAPHY.SMALL }}>
<div>
- <div style={{ color: '#787878' }}>Expected Annual Return</div>
- <div style={{ color: '#00D66F', fontSize: '14px', fontWeight: 'bold' }}>
+ <div style={{ color: FINCEPT.GRAY }}>Expected Annual Return</div>
+ <div style={{ color: FINCEPT.GREEN, fontSize: '14px', fontWeight: TYPOGRAPHY.BOLD }}>
{(results.performance_metrics.expected_annual_return * 100).toFixed(2)}%
</div>
</div>
<div>
- <div style={{ color: '#787878' }}>Annual Volatility</div>
- <div style={{ color: '#FFD700', fontSize: '14px', fontWeight: 'bold' }}>
+ <div style={{ color: FINCEPT.GRAY }}>Annual Volatility</div>
+ <div style={{ color: FINCEPT.YELLOW, fontSize: '14px', fontWeight: TYPOGRAPHY.BOLD }}>
{results.performance_metrics.annual_volatility > 0
? `${(results.performance_metrics.annual_volatility * 100).toFixed(2)}%`
: 'N/A'}
</div>
</div>
<div>
- <div style={{ color: '#787878' }}>Sharpe Ratio</div>
- <div style={{ color: '#FF8800', fontSize: '14px', fontWeight: 'bold' }}>
+ <div style={{ color: FINCEPT.GRAY }}>Sharpe Ratio</div>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '14px', fontWeight: TYPOGRAPHY.BOLD }}>
{results.performance_metrics.sharpe_ratio.toFixed(3)}
</div>
</div>
<div>
- <div style={{ color: '#787878' }}>Sortino Ratio</div>
- <div style={{ color: '#00E5FF', fontSize: '14px', fontWeight: 'bold' }}>
+ <div style={{ color: FINCEPT.GRAY }}>Sortino Ratio</div>
+ <div style={{ color: FINCEPT.CYAN, fontSize: '14px', fontWeight: TYPOGRAPHY.BOLD }}>
{results.performance_metrics.sortino_ratio?.toFixed(3) || 'N/A'}
</div>
</div>
<div>
- <div style={{ color: '#787878' }}>Calmar Ratio</div>
- <div style={{ color: '#9C27B0', fontSize: '14px', fontWeight: 'bold' }}>
+ <div style={{ color: FINCEPT.GRAY }}>Calmar Ratio</div>
+ <div style={{ color: FINCEPT.PURPLE, fontSize: '14px', fontWeight: TYPOGRAPHY.BOLD }}>
{results.performance_metrics.calmar_ratio?.toFixed(3) || 'N/A'}
</div>
</div>
<div>
- <div style={{ color: '#787878' }}>Max Drawdown</div>
- <div style={{ color: '#FF5252', fontSize: '14px', fontWeight: 'bold' }}>
+ <div style={{ color: FINCEPT.GRAY }}>Max Drawdown</div>
+ <div style={{ color: FINCEPT.RED, fontSize: '14px', fontWeight: TYPOGRAPHY.BOLD }}>
{results.performance_metrics.max_drawdown
? `${(results.performance_metrics.max_drawdown * 100).toFixed(2)}%`
: 'N/A'}
@@ -1158,32 +1103,34 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{/* Portfolio Weights */}
{results.weights && (
- <div style={{ marginBottom: '24px' }}>
- <div style={{ color: '#00E5FF', fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
+ <div style={{ marginBottom: SPACING.XLARGE }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD, marginBottom: SPACING.MEDIUM }}>
OPTIMAL WEIGHTS
</div>
- <div style={{ backgroundColor: '#0F0F0F', border: '1px solid #333', maxHeight: '300px', overflow: 'auto' }}>
+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, border: BORDERS.STANDARD, borderRadius: '2px', maxHeight: '300px', overflow: 'auto' }}>
{Object.entries(results.weights)
.sort(([, a], [, b]) => b - a)
.map(([symbol, weight]) => (
<div
key={symbol}
style={{
- padding: '8px 12px',
- borderBottom: '1px solid #1A1A1A',
+ padding: `${SPACING.MEDIUM} ${SPACING.DEFAULT}`,
+ borderBottom: `1px solid ${FINCEPT.HEADER_BG}`,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
- fontSize: '10px'
+ fontSize: TYPOGRAPHY.SMALL,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
>
- <span style={{ color: '#00E5FF', fontWeight: 'bold' }}>{symbol}</span>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: FINCEPT.CYAN, fontWeight: TYPOGRAPHY.BOLD }}>{symbol}</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.MEDIUM }}>
<div
style={{
width: '100px',
height: '6px',
- backgroundColor: '#1A1A1A',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderRadius: '2px',
position: 'relative',
overflow: 'hidden'
}}
@@ -1195,11 +1142,11 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
top: 0,
height: '100%',
width: `${weight * 100}%`,
- backgroundColor: '#FF8800'
+ backgroundColor: FINCEPT.ORANGE
}}
/>
</div>
- <span style={{ color: '#FFF', width: '60px', textAlign: 'right' }}>
+ <span style={{ color: FINCEPT.WHITE, width: '60px', textAlign: 'right' }}>
{(weight * 100).toFixed(2)}%
</span>
</div>
@@ -1210,23 +1157,27 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
)}
{/* Export Buttons */}
- <div style={{ display: 'flex', gap: '8px' }}>
+ <div style={{ display: 'flex', gap: SPACING.MEDIUM }}>
<button
onClick={() => handleExport('json')}
style={{
flex: 1,
- padding: '8px',
- backgroundColor: '#00D66F',
- color: '#000',
+ padding: `${SPACING.MEDIUM} ${SPACING.LARGE}`,
+ backgroundColor: FINCEPT.GREEN,
+ color: FINCEPT.DARK_BG,
border: 'none',
- fontFamily: 'inherit',
- fontSize: '10px',
- fontWeight: 'bold',
+ borderRadius: '2px',
+ fontFamily: TYPOGRAPHY.MONO,
+ fontSize: TYPOGRAPHY.TINY,
+ fontWeight: TYPOGRAPHY.BOLD,
+ letterSpacing: TYPOGRAPHY.WIDE,
+ textTransform: 'uppercase' as const,
cursor: 'pointer',
+ transition: EFFECTS.TRANSITION_STANDARD,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- gap: '4px'
+ gap: SPACING.SMALL
}}
>
<Download size={12} />
@@ -1236,18 +1187,22 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
onClick={() => handleExport('csv')}
style={{
flex: 1,
- padding: '8px',
- backgroundColor: '#00E5FF',
- color: '#000',
+ padding: `${SPACING.MEDIUM} ${SPACING.LARGE}`,
+ backgroundColor: FINCEPT.CYAN,
+ color: FINCEPT.DARK_BG,
border: 'none',
- fontFamily: 'inherit',
- fontSize: '10px',
- fontWeight: 'bold',
+ borderRadius: '2px',
+ fontFamily: TYPOGRAPHY.MONO,
+ fontSize: TYPOGRAPHY.TINY,
+ fontWeight: TYPOGRAPHY.BOLD,
+ letterSpacing: TYPOGRAPHY.WIDE,
+ textTransform: 'uppercase' as const,
cursor: 'pointer',
+ transition: EFFECTS.TRANSITION_STANDARD,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- gap: '4px'
+ gap: SPACING.SMALL
}}
>
<Download size={12} />
@@ -1261,10 +1216,11 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
<div style={{
padding: '48px',
textAlign: 'center',
- color: '#787878',
- fontSize: '11px',
- backgroundColor: '#0F0F0F',
- border: '1px solid #333'
+ color: FINCEPT.GRAY,
+ fontSize: TYPOGRAPHY.BODY,
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: BORDERS.STANDARD,
+ borderRadius: '2px'
}}>
Configure parameters and click "RUN OPTIMIZATION" to see results
</div>
@@ -1277,15 +1233,15 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{activeTab === 'frontier' && (
<div>
{/* Configuration Panel */}
- <div style={{ backgroundColor: '#0F0F0F', padding: '16px', border: '1px solid #333', marginBottom: '16px' }}>
- <div style={{ color: '#00E5FF', fontSize: '11px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, padding: SPACING.LARGE, border: BORDERS.STANDARD, borderRadius: '2px', marginBottom: SPACING.LARGE }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD, marginBottom: SPACING.DEFAULT }}>
FRONTIER PARAMETERS
</div>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.DEFAULT }}>
{/* Number of portfolios */}
<div>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
NUMBER OF POINTS
</label>
<input
@@ -1295,13 +1251,8 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
min="10"
max="500"
style={{
- width: '100%',
- padding: '6px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
/>
</div>
@@ -1309,20 +1260,15 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{/* Risk Measure for skfolio */}
{library === 'skfolio' && (
<div>
- <label style={{ color: '#787878', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ <label style={{ ...COMMON_STYLES.dataLabel, display: 'block', marginBottom: SPACING.SMALL }}>
RISK MEASURE
</label>
<select
value={skfolioConfig.risk_measure}
onChange={(e) => setSkfolioConfig({ ...skfolioConfig, risk_measure: e.target.value })}
style={{
- width: '100%',
- padding: '6px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333',
- color: '#FFF',
- fontFamily: 'inherit',
- fontSize: '11px'
+ ...COMMON_STYLES.inputField,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
>
{SKFOLIO_RISK_MEASURES.map(rm => (
@@ -1334,36 +1280,33 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
</div>
</div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '24px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.DEFAULT, marginBottom: SPACING.XLARGE }}>
<button
onClick={handleGenerateFrontier}
disabled={loadingAction === 'frontier'}
style={{
- padding: '12px 24px',
- backgroundColor: loadingAction === 'frontier' ? '#4A4A4A' : '#FF8800',
- color: loadingAction === 'frontier' ? '#787878' : '#000',
- border: loadingAction === 'frontier' ? '1px solid #666' : 'none',
- fontFamily: 'inherit',
- fontSize: '12px',
- fontWeight: 'bold',
+ ...COMMON_STYLES.buttonPrimary,
+ padding: `${SPACING.DEFAULT} ${SPACING.XLARGE}`,
+ backgroundColor: loadingAction === 'frontier' ? FINCEPT.MUTED : FINCEPT.ORANGE,
+ color: loadingAction === 'frontier' ? FINCEPT.GRAY : FINCEPT.DARK_BG,
+ border: loadingAction === 'frontier' ? `1px solid ${FINCEPT.GRAY}` : 'none',
cursor: loadingAction === 'frontier' ? 'not-allowed' : 'pointer',
opacity: loadingAction === 'frontier' ? 0.6 : 1,
- transition: 'all 0.2s ease',
}}
>
{loadingAction === 'frontier' ? 'GENERATING...' : 'GENERATE EFFICIENT FRONTIER'}
</button>
{loadingAction === 'frontier' && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.MEDIUM }}>
<div style={{
width: '16px',
height: '16px',
- border: '2px solid #333',
- borderTop: '2px solid #00E5FF',
+ border: `2px solid ${FINCEPT.BORDER}`,
+ borderTop: `2px solid ${FINCEPT.CYAN}`,
borderRadius: '50%',
animation: 'spin 0.8s linear infinite'
}} />
- <span style={{ color: '#00E5FF', fontSize: '11px' }}>Generating frontier...</span>
+ <span style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY }}>Generating frontier...</span>
<style>{`
@keyframes spin {
0% { transform: rotate(0deg); }
@@ -1375,8 +1318,8 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
</div>
{results?.efficient_frontier && results.efficient_frontier.returns && (
- <div style={{ backgroundColor: '#0F0F0F', padding: '24px', border: '1px solid #333', marginTop: '16px' }}>
- <div style={{ color: '#00E5FF', fontSize: '12px', fontWeight: 'bold', marginBottom: '16px' }}>
+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, padding: SPACING.XLARGE, border: BORDERS.STANDARD, borderRadius: '2px', marginTop: SPACING.LARGE }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.SUBHEADING, fontWeight: TYPOGRAPHY.BOLD, marginBottom: SPACING.LARGE }}>
EFFICIENT FRONTIER ({results.efficient_frontier.returns?.length || 0} points)
</div>
@@ -1394,10 +1337,10 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
const sharpe = payload.sharpe || 0;
// Color gradient based on Sharpe ratio (green for high, yellow for medium, red for low)
- let fillColor = '#FF3B3B'; // Red for low Sharpe
- if (sharpe > 1.5) fillColor = '#00FF88'; // Green for high Sharpe
- else if (sharpe > 0.8) fillColor = '#FFD700'; // Gold for medium Sharpe
- else if (sharpe > 0.3) fillColor = '#FF8800'; // Orange for okay Sharpe
+ let fillColor: string = FINCEPT.RED; // Red for low Sharpe
+ if (sharpe > 1.5) fillColor = FINCEPT.GREEN; // Green for high Sharpe
+ else if (sharpe > 0.8) fillColor = FINCEPT.YELLOW; // Gold for medium Sharpe
+ else if (sharpe > 0.3) fillColor = FINCEPT.ORANGE; // Orange for okay Sharpe
return (
<circle
@@ -1417,9 +1360,9 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
<ScatterChart margin={{ top: 20, right: 30, bottom: 40, left: 60 }}>
<defs>
<linearGradient id="frontierGradient" x1="0" y1="0" x2="1" y2="1">
- <stop offset="0%" stopColor="#FF3B3B" stopOpacity={0.8} />
- <stop offset="50%" stopColor="#FFD700" stopOpacity={0.8} />
- <stop offset="100%" stopColor="#00FF88" stopOpacity={0.8} />
+ <stop offset="0%" stopColor={FINCEPT.RED} stopOpacity={0.8} />
+ <stop offset="50%" stopColor={FINCEPT.YELLOW} stopOpacity={0.8} />
+ <stop offset="100%" stopColor={FINCEPT.GREEN} stopOpacity={0.8} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="#333" strokeOpacity={0.3} />
@@ -1428,29 +1371,29 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
dataKey="volatility"
name="Volatility"
unit="%"
- stroke="#787878"
- tick={{ fill: '#787878', fontSize: 10 }}
- label={{ value: 'Annual Volatility (%)', position: 'insideBottom', offset: -15, fill: '#787878', fontSize: 11 }}
+ stroke={FINCEPT.GRAY}
+ tick={{ fill: FINCEPT.GRAY, fontSize: 10 }}
+ label={{ value: 'Annual Volatility (%)', position: 'insideBottom', offset: -15, fill: FINCEPT.GRAY, fontSize: 11 }}
/>
<YAxis
type="number"
dataKey="returns"
name="Returns"
unit="%"
- stroke="#787878"
- tick={{ fill: '#787878', fontSize: 10 }}
- label={{ value: 'Annual Returns (%)', angle: -90, position: 'insideLeft', offset: -40, fill: '#787878', fontSize: 11 }}
+ stroke={FINCEPT.GRAY}
+ tick={{ fill: FINCEPT.GRAY, fontSize: 10 }}
+ label={{ value: 'Annual Returns (%)', angle: -90, position: 'insideLeft', offset: -40, fill: FINCEPT.GRAY, fontSize: 11 }}
/>
<Tooltip
contentStyle={{
- backgroundColor: '#1A1A1A',
- border: '1px solid #00E5FF',
- borderRadius: '4px',
- fontSize: '10px',
- padding: '8px'
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.CYAN}`,
+ borderRadius: '2px',
+ fontSize: TYPOGRAPHY.SMALL,
+ padding: SPACING.MEDIUM
}}
- labelStyle={{ color: '#00E5FF' }}
- itemStyle={{ color: '#FFF' }}
+ labelStyle={{ color: FINCEPT.CYAN }}
+ itemStyle={{ color: FINCEPT.WHITE }}
formatter={(value: any, name: string) => {
if (name === 'Volatility') return [`${value}%`, 'Volatility'];
if (name === 'Returns') return [`${value}%`, 'Returns'];
@@ -1462,7 +1405,7 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
name="Efficient Frontier"
data={chartData}
fill="url(#frontierGradient)"
- line={{ stroke: '#00E5FF', strokeWidth: 1, strokeOpacity: 0.5 }}
+ line={{ stroke: FINCEPT.CYAN, strokeWidth: 1, strokeOpacity: 0.5 }}
shape={<CustomDot />}
isAnimationActive={false}
/>
@@ -1472,12 +1415,12 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
})()}
{/* Legend */}
- <div style={{ marginTop: '16px', fontSize: '10px', color: '#787878', textAlign: 'center' }}>
+ <div style={{ marginTop: SPACING.LARGE, fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.GRAY, textAlign: 'center' }}>
Each point represents an optimal portfolio. Color indicates Sharpe ratio:
- <span style={{ color: '#00FF88', marginLeft: '8px' }}>● High {'>1.5'}</span>
- <span style={{ color: '#FFD700', marginLeft: '8px' }}>● Good (0.8-1.5)</span>
- <span style={{ color: '#FF8800', marginLeft: '8px' }}>● Medium (0.3-0.8)</span>
- <span style={{ color: '#FF3B3B', marginLeft: '8px' }}>● Low {'<0.3'}</span>
+ <span style={{ color: FINCEPT.GREEN, marginLeft: SPACING.MEDIUM }}>● High {'>1.5'}</span>
+ <span style={{ color: FINCEPT.YELLOW, marginLeft: SPACING.MEDIUM }}>● Good (0.8-1.5)</span>
+ <span style={{ color: FINCEPT.ORANGE, marginLeft: SPACING.MEDIUM }}>● Medium (0.3-0.8)</span>
+ <span style={{ color: FINCEPT.RED, marginLeft: SPACING.MEDIUM }}>● Low {'<0.3'}</span>
</div>
</div>
)}
@@ -1487,36 +1430,33 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{/* BACKTEST TAB */}
{activeTab === 'backtest' && (
<div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '24px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.DEFAULT, marginBottom: SPACING.XLARGE }}>
<button
onClick={handleBacktest}
disabled={loadingAction === 'backtest'}
style={{
- padding: '12px 24px',
- backgroundColor: loadingAction === 'backtest' ? '#4A4A4A' : '#FF8800',
- color: loadingAction === 'backtest' ? '#787878' : '#000',
- border: loadingAction === 'backtest' ? '1px solid #666' : 'none',
- fontFamily: 'inherit',
- fontSize: '12px',
- fontWeight: 'bold',
+ ...COMMON_STYLES.buttonPrimary,
+ padding: `${SPACING.DEFAULT} ${SPACING.XLARGE}`,
+ backgroundColor: loadingAction === 'backtest' ? FINCEPT.MUTED : FINCEPT.ORANGE,
+ color: loadingAction === 'backtest' ? FINCEPT.GRAY : FINCEPT.DARK_BG,
+ border: loadingAction === 'backtest' ? `1px solid ${FINCEPT.GRAY}` : 'none',
cursor: loadingAction === 'backtest' ? 'not-allowed' : 'pointer',
opacity: loadingAction === 'backtest' ? 0.6 : 1,
- transition: 'all 0.2s ease',
}}
>
{loadingAction === 'backtest' ? 'RUNNING BACKTEST...' : 'RUN BACKTEST'}
</button>
{loadingAction === 'backtest' && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.MEDIUM }}>
<div style={{
width: '16px',
height: '16px',
- border: '2px solid #333',
- borderTop: '2px solid #00E5FF',
+ border: `2px solid ${FINCEPT.BORDER}`,
+ borderTop: `2px solid ${FINCEPT.CYAN}`,
borderRadius: '50%',
animation: 'spin 0.8s linear infinite'
}} />
- <span style={{ color: '#00E5FF', fontSize: '11px' }}>Running backtest...</span>
+ <span style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY }}>Running backtest...</span>
<style>{`
@keyframes spin {
0% { transform: rotate(0deg); }
@@ -1528,17 +1468,17 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
</div>
{results?.backtest_results && (
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: SPACING.DEFAULT }}>
{[
- { label: 'Annual Return', value: results.backtest_results.annual_return, color: '#00D66F', format: '%' },
- { label: 'Annual Volatility', value: results.backtest_results.annual_volatility, color: '#FFD700', format: '%' },
- { label: 'Sharpe Ratio', value: results.backtest_results.sharpe_ratio, color: '#FF8800', format: '' },
- { label: 'Max Drawdown', value: results.backtest_results.max_drawdown, color: '#FF3B3B', format: '%' },
- { label: 'Calmar Ratio', value: results.backtest_results.calmar_ratio, color: '#00E5FF', format: '' },
+ { label: 'Annual Return', value: results.backtest_results.annual_return, color: FINCEPT.GREEN, format: '%' },
+ { label: 'Annual Volatility', value: results.backtest_results.annual_volatility, color: FINCEPT.YELLOW, format: '%' },
+ { label: 'Sharpe Ratio', value: results.backtest_results.sharpe_ratio, color: FINCEPT.ORANGE, format: '' },
+ { label: 'Max Drawdown', value: results.backtest_results.max_drawdown, color: FINCEPT.RED, format: '%' },
+ { label: 'Calmar Ratio', value: results.backtest_results.calmar_ratio, color: FINCEPT.CYAN, format: '' },
].map(metric => (
- <div key={metric.label} style={{ backgroundColor: '#0F0F0F', padding: '16px', border: '1px solid #333' }}>
- <div style={{ color: '#787878', fontSize: '9px', marginBottom: '4px' }}>{metric.label}</div>
- <div style={{ color: metric.color, fontSize: '18px', fontWeight: 'bold' }}>
+ <div key={metric.label} style={{ ...COMMON_STYLES.metricCard, padding: SPACING.LARGE }}>
+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>{metric.label}</div>
+ <div style={{ color: metric.color, fontSize: '18px', fontWeight: TYPOGRAPHY.BOLD }}>
{metric.format === '%'
? `${(metric.value * 100).toFixed(2)}%`
: metric.value.toFixed(3)
@@ -1554,36 +1494,33 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{/* ALLOCATION TAB */}
{activeTab === 'allocation' && (
<div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '24px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.DEFAULT, marginBottom: SPACING.XLARGE }}>
<button
onClick={handleDiscreteAllocation}
disabled={loadingAction === 'allocation' || !results?.weights}
style={{
- padding: '12px 24px',
- backgroundColor: (loadingAction === 'allocation' || !results?.weights) ? '#4A4A4A' : '#FF8800',
- color: (loadingAction === 'allocation' || !results?.weights) ? '#787878' : '#000',
- border: (loadingAction === 'allocation' || !results?.weights) ? '1px solid #666' : 'none',
- fontFamily: 'inherit',
- fontSize: '12px',
- fontWeight: 'bold',
+ ...COMMON_STYLES.buttonPrimary,
+ padding: `${SPACING.DEFAULT} ${SPACING.XLARGE}`,
+ backgroundColor: (loadingAction === 'allocation' || !results?.weights) ? FINCEPT.MUTED : FINCEPT.ORANGE,
+ color: (loadingAction === 'allocation' || !results?.weights) ? FINCEPT.GRAY : FINCEPT.DARK_BG,
+ border: (loadingAction === 'allocation' || !results?.weights) ? `1px solid ${FINCEPT.GRAY}` : 'none',
cursor: (loadingAction === 'allocation' || !results?.weights) ? 'not-allowed' : 'pointer',
opacity: (loadingAction === 'allocation' || !results?.weights) ? 0.6 : 1,
- transition: 'all 0.2s ease',
}}
>
{loadingAction === 'allocation' ? 'CALCULATING...' : 'CALCULATE DISCRETE ALLOCATION'}
</button>
{loadingAction === 'allocation' && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.MEDIUM }}>
<div style={{
width: '16px',
height: '16px',
- border: '2px solid #333',
- borderTop: '2px solid #00E5FF',
+ border: `2px solid ${FINCEPT.BORDER}`,
+ borderTop: `2px solid ${FINCEPT.CYAN}`,
borderRadius: '50%',
animation: 'spin 0.8s linear infinite'
}} />
- <span style={{ color: '#00E5FF', fontSize: '11px' }}>Calculating allocation...</span>
+ <span style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY }}>Calculating allocation...</span>
<style>{`
@keyframes spin {
0% { transform: rotate(0deg); }
@@ -1596,58 +1533,59 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{!results?.weights && (
<div style={{
- padding: '16px',
- backgroundColor: 'rgba(255,136,0,0.1)',
- border: '1px solid #FF8800',
- color: '#FF8800',
- marginBottom: '24px',
- fontSize: '11px',
- borderRadius: '4px'
+ padding: SPACING.LARGE,
+ backgroundColor: `${FINCEPT.ORANGE}1A`,
+ border: BORDERS.ORANGE,
+ color: FINCEPT.ORANGE,
+ marginBottom: SPACING.XLARGE,
+ fontSize: TYPOGRAPHY.BODY,
+ borderRadius: '2px'
}}>
- ℹ️ Please run optimization first to get portfolio weights
+ Please run optimization first to get portfolio weights
</div>
)}
{results?.discrete_allocation && (
<div>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', marginBottom: '24px' }}>
- <div style={{ backgroundColor: '#0F0F0F', padding: '16px', border: '1px solid #333' }}>
- <div style={{ color: '#787878', fontSize: '9px' }}>Total Value</div>
- <div style={{ color: '#00E5FF', fontSize: '18px', fontWeight: 'bold' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: SPACING.DEFAULT, marginBottom: SPACING.XLARGE }}>
+ <div style={{ ...COMMON_STYLES.metricCard, padding: SPACING.LARGE }}>
+ <div style={{ ...COMMON_STYLES.dataLabel }}>Total Value</div>
+ <div style={{ color: FINCEPT.CYAN, fontSize: '18px', fontWeight: TYPOGRAPHY.BOLD }}>
${results.discrete_allocation.total_value.toLocaleString()}
</div>
</div>
- <div style={{ backgroundColor: '#0F0F0F', padding: '16px', border: '1px solid #333' }}>
- <div style={{ color: '#787878', fontSize: '9px' }}>Allocated</div>
- <div style={{ color: '#00D66F', fontSize: '18px', fontWeight: 'bold' }}>
+ <div style={{ ...COMMON_STYLES.metricCard, padding: SPACING.LARGE }}>
+ <div style={{ ...COMMON_STYLES.dataLabel }}>Allocated</div>
+ <div style={{ color: FINCEPT.GREEN, fontSize: '18px', fontWeight: TYPOGRAPHY.BOLD }}>
${(results.discrete_allocation.total_value - results.discrete_allocation.leftover_cash).toLocaleString()}
</div>
</div>
- <div style={{ backgroundColor: '#0F0F0F', padding: '16px', border: '1px solid #333' }}>
- <div style={{ color: '#787878', fontSize: '9px' }}>Leftover Cash</div>
- <div style={{ color: '#FFD700', fontSize: '18px', fontWeight: 'bold' }}>
+ <div style={{ ...COMMON_STYLES.metricCard, padding: SPACING.LARGE }}>
+ <div style={{ ...COMMON_STYLES.dataLabel }}>Leftover Cash</div>
+ <div style={{ color: FINCEPT.YELLOW, fontSize: '18px', fontWeight: TYPOGRAPHY.BOLD }}>
${results.discrete_allocation.leftover_cash.toLocaleString()}
</div>
</div>
</div>
- <div style={{ backgroundColor: '#0F0F0F', padding: '16px', border: '1px solid #333' }}>
- <div style={{ color: '#00E5FF', fontSize: '11px', fontWeight: 'bold', marginBottom: '12px' }}>
+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, padding: SPACING.LARGE, border: BORDERS.STANDARD, borderRadius: '2px' }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD, marginBottom: SPACING.DEFAULT }}>
SHARE ALLOCATION
</div>
{Object.entries(results.discrete_allocation.allocation).map(([symbol, shares]) => (
<div
key={symbol}
style={{
- padding: '8px 0',
- borderBottom: '1px solid #1A1A1A',
+ padding: `${SPACING.MEDIUM} 0`,
+ borderBottom: `1px solid ${FINCEPT.HEADER_BG}`,
display: 'flex',
justifyContent: 'space-between',
- fontSize: '11px'
+ fontSize: TYPOGRAPHY.BODY,
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
>
- <span style={{ color: '#00E5FF', fontWeight: 'bold' }}>{symbol}</span>
- <span style={{ color: '#FFF' }}>{shares} shares</span>
+ <span style={{ color: FINCEPT.CYAN, fontWeight: TYPOGRAPHY.BOLD }}>{symbol}</span>
+ <span style={{ color: FINCEPT.WHITE }}>{shares} shares</span>
</div>
))}
</div>
@@ -1659,12 +1597,13 @@ const PortfolioOptimizationView: React.FC<PortfolioOptimizationViewProps> = ({ p
{/* RISK ANALYSIS TAB */}
{activeTab === 'risk' && (
<div style={{
- padding: '24px',
+ padding: SPACING.XLARGE,
textAlign: 'center',
- backgroundColor: '#0F0F0F',
- border: '1px solid #333',
- color: '#787878',
- fontSize: '11px'
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: BORDERS.STANDARD,
+ borderRadius: '2px',
+ color: FINCEPT.GRAY,
+ fontSize: TYPOGRAPHY.BODY
}}>
Risk decomposition and correlation matrix analysis coming soon...
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsx
index 948923802..9fb230d96 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import { PortfolioSummary } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatNumber, formatPercent } from './utils';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../finceptStyles';
+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS, COMMON_STYLES } from '../finceptStyles';
interface PositionsViewProps {
portfolioSummary: PortfolioSummary;
@@ -16,13 +16,13 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
display: 'flex',
flexDirection: 'column',
backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.DEFAULT,
- overflow: 'hidden'
+ overflow: 'hidden',
+ fontFamily: TYPOGRAPHY.MONO,
}}>
{/* Section Header */}
<div style={{
...COMMON_STYLES.sectionHeader,
- marginBottom: SPACING.MEDIUM
+ marginBottom: '0px',
}}>
CURRENT POSITIONS
</div>
@@ -33,15 +33,16 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
<div style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr 1fr 1fr 1.2fr 1fr',
- gap: SPACING.MEDIUM,
- padding: SPACING.MEDIUM,
+ gap: '8px',
+ padding: '8px 12px',
backgroundColor: FINCEPT.HEADER_BG,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.BOLD,
- borderBottom: BORDERS.ORANGE,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ borderBottom: `1px solid ${FINCEPT.ORANGE}`,
position: 'sticky',
top: 0,
- zIndex: 1
+ zIndex: 1,
}}>
<div style={{ color: FINCEPT.ORANGE }}>SYMBOL</div>
<div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>QTY</div>
@@ -57,11 +58,9 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
{/* Position Rows */}
{portfolioSummary.holdings.length === 0 ? (
<div style={{
- padding: SPACING.XLARGE,
- textAlign: 'center',
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontFamily: TYPOGRAPHY.MONO
+ ...COMMON_STYLES.emptyState,
+ padding: '24px',
+ height: 'auto',
}}>
No positions yet. Click BUY to add your first position.
</div>
@@ -72,35 +71,38 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr 1fr 1fr 1.2fr 1fr',
- gap: SPACING.MEDIUM,
- padding: SPACING.MEDIUM,
+ gap: '8px',
+ padding: '8px 12px',
backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent',
borderLeft: `3px solid ${holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED}`,
- fontSize: TYPOGRAPHY.BODY,
+ fontSize: '10px',
marginBottom: '1px',
fontFamily: TYPOGRAPHY.MONO,
minHeight: '32px',
- alignItems: 'center'
+ alignItems: 'center',
+ transition: EFFECTS.TRANSITION_STANDARD,
}}
+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = FINCEPT.HOVER; }}
+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent'; }}
>
- <div style={{ color: FINCEPT.CYAN, fontWeight: TYPOGRAPHY.BOLD }}>{holding.symbol}</div>
- <div style={{ color: FINCEPT.WHITE, textAlign: 'right' }}>{formatNumber(holding.quantity, 4)}</div>
+ <div style={{ color: FINCEPT.CYAN, fontWeight: 700 }}>{holding.symbol}</div>
+ <div style={{ color: FINCEPT.CYAN, textAlign: 'right' }}>{formatNumber(holding.quantity, 4)}</div>
<div style={{ color: FINCEPT.GRAY, textAlign: 'right' }}>{formatCurrency(holding.avg_buy_price, currency)}</div>
- <div style={{ color: FINCEPT.WHITE, textAlign: 'right' }}>{formatCurrency(holding.current_price, currency)}</div>
- <div style={{ color: FINCEPT.WHITE, textAlign: 'right', fontWeight: TYPOGRAPHY.SEMIBOLD }}>
+ <div style={{ color: FINCEPT.CYAN, textAlign: 'right' }}>{formatCurrency(holding.current_price, currency)}</div>
+ <div style={{ color: FINCEPT.WHITE, textAlign: 'right', fontWeight: 600 }}>
{formatCurrency(holding.market_value, currency)}
</div>
<div style={{ color: FINCEPT.GRAY, textAlign: 'right' }}>{formatCurrency(holding.cost_basis, currency)}</div>
<div style={{ textAlign: 'right' }}>
<div style={{
color: holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontWeight: TYPOGRAPHY.SEMIBOLD
+ fontWeight: 600,
}}>
{holding.unrealized_pnl >= 0 ? '+' : ''}{formatCurrency(holding.unrealized_pnl, currency)}
</div>
<div style={{
color: holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.SMALL
+ fontSize: '9px',
}}>
{formatPercent(holding.unrealized_pnl_percent)}
</div>
@@ -108,18 +110,17 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
<div style={{ textAlign: 'right' }}>
<div style={{
color: holding.day_change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontWeight: TYPOGRAPHY.REGULAR
}}>
{holding.day_change >= 0 ? '+' : ''}{formatCurrency(holding.day_change, currency)}
</div>
<div style={{
color: holding.day_change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.SMALL
+ fontSize: '9px',
}}>
{formatPercent(holding.day_change_percent)}
</div>
</div>
- <div style={{ color: FINCEPT.YELLOW, textAlign: 'right', fontWeight: TYPOGRAPHY.SEMIBOLD }}>
+ <div style={{ color: FINCEPT.YELLOW, textAlign: 'right', fontWeight: 600 }}>
{formatNumber(holding.weight)}%
</div>
</div>
@@ -131,16 +132,16 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
<div style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr 1fr 1fr 1.2fr 1fr',
- gap: SPACING.MEDIUM,
- padding: SPACING.MEDIUM,
+ gap: '8px',
+ padding: '8px 12px',
backgroundColor: FINCEPT.PANEL_BG,
- borderTop: BORDERS.ORANGE_THICK,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.BOLD,
- marginTop: SPACING.MEDIUM,
+ borderTop: `2px solid ${FINCEPT.ORANGE}`,
+ fontSize: '10px',
+ fontWeight: 700,
+ marginTop: '8px',
fontFamily: TYPOGRAPHY.MONO,
minHeight: '36px',
- alignItems: 'center'
+ alignItems: 'center',
}}>
<div style={{ color: FINCEPT.ORANGE }}>TOTAL</div>
<div></div>
@@ -154,26 +155,26 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {
</div>
<div style={{ textAlign: 'right' }}>
<div style={{
- color: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED
+ color: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
}}>
{portfolioSummary.total_unrealized_pnl >= 0 ? '+' : ''}{formatCurrency(portfolioSummary.total_unrealized_pnl, currency)}
</div>
<div style={{
color: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.SMALL
+ fontSize: '9px',
}}>
{formatPercent(portfolioSummary.total_unrealized_pnl_percent)}
</div>
</div>
<div style={{ textAlign: 'right' }}>
<div style={{
- color: portfolioSummary.total_day_change >= 0 ? FINCEPT.GREEN : FINCEPT.RED
+ color: portfolioSummary.total_day_change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
}}>
{portfolioSummary.total_day_change >= 0 ? '+' : ''}{formatCurrency(portfolioSummary.total_day_change, currency)}
</div>
<div style={{
color: portfolioSummary.total_day_change >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.SMALL
+ fontSize: '9px',
}}>
{formatPercent(portfolioSummary.total_day_change_percent)}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ReportsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ReportsView.tsx
index 68de7d343..9c2ee20f7 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ReportsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/ReportsView.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import { PortfolioSummary, Transaction } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatPercent, calculateTaxLiability } from './utils';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../finceptStyles';
+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, EFFECTS } from '../finceptStyles';
interface ReportsViewProps {
portfolioSummary: PortfolioSummary;
@@ -45,13 +45,22 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
}}>
<div style={{
...COMMON_STYLES.metricCard,
- border: BORDERS.ORANGE
+ border: BORDERS.ORANGE,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <div style={COMMON_STYLES.dataLabel}>TOTAL TAX LIABILITY</div>
+ <div style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const
+ }}>TOTAL TAX LIABILITY</div>
<div style={{
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '15px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO
}}>
{formatCurrency(taxCalculation.totalTax, currency)}
</div>
@@ -59,19 +68,28 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
...COMMON_STYLES.metricCard,
- border: BORDERS.GREEN
+ border: BORDERS.GREEN,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <div style={COMMON_STYLES.dataLabel}>LONG-TERM GAINS</div>
+ <div style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const
+ }}>LONG-TERM GAINS</div>
<div style={{
color: FINCEPT.GREEN,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '15px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO
}}>
{formatCurrency(taxCalculation.longTermGains, currency)}
</div>
<div style={{
color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.TINY,
+ fontSize: '9px',
marginTop: SPACING.TINY
}}>
Tax: {formatCurrency(taxCalculation.longTermTax, currency)}
@@ -80,19 +98,28 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
...COMMON_STYLES.metricCard,
- border: `1px solid ${FINCEPT.YELLOW}`
+ border: `1px solid ${FINCEPT.YELLOW}`,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <div style={COMMON_STYLES.dataLabel}>SHORT-TERM GAINS</div>
+ <div style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const
+ }}>SHORT-TERM GAINS</div>
<div style={{
color: FINCEPT.YELLOW,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '15px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO
}}>
{formatCurrency(taxCalculation.shortTermGains, currency)}
</div>
<div style={{
color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.TINY,
+ fontSize: '9px',
marginTop: SPACING.TINY
}}>
Tax: {formatCurrency(taxCalculation.shortTermTax, currency)}
@@ -101,19 +128,28 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
...COMMON_STYLES.metricCard,
- border: BORDERS.CYAN
+ border: BORDERS.CYAN,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <div style={COMMON_STYLES.dataLabel}>UNREALIZED GAINS</div>
+ <div style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const
+ }}>UNREALIZED GAINS</div>
<div style={{
color: portfolioSummary.total_unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '15px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO
}}>
{formatCurrency(portfolioSummary.total_unrealized_pnl, currency)}
</div>
<div style={{
color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.TINY,
+ fontSize: '9px',
marginTop: SPACING.TINY
}}>
Not taxable until sold
@@ -123,12 +159,8 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
{/* Tax Breakdown */}
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.MEDIUM,
- paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.ORANGE
+ ...COMMON_STYLES.sectionHeader,
+ marginBottom: SPACING.MEDIUM
}}>
TAX BREAKDOWN (FIFO METHOD)
</div>
@@ -137,6 +169,7 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
padding: SPACING.DEFAULT,
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.STANDARD,
+ borderRadius: '2px',
marginBottom: SPACING.XLARGE
}}>
<div style={{
@@ -146,12 +179,13 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
marginBottom: SPACING.MEDIUM,
padding: SPACING.MEDIUM,
backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: BORDERS.ORANGE
+ borderBottom: BORDERS.ORANGE,
+ borderRadius: '2px'
}}>
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>CATEGORY</div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD, textAlign: 'right' }}>GAINS</div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD, textAlign: 'right' }}>TAX RATE</div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD, textAlign: 'right' }}>TAX DUE</div>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>CATEGORY</div>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const, textAlign: 'right' }}>GAINS</div>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const, textAlign: 'right' }}>TAX RATE</div>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const, textAlign: 'right' }}>TAX DUE</div>
</div>
<div style={{
@@ -161,16 +195,18 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
padding: SPACING.MEDIUM,
backgroundColor: 'rgba(255,215,0,0.05)',
borderLeft: `3px solid ${FINCEPT.YELLOW}`,
- marginBottom: SPACING.SMALL
+ borderRadius: '2px',
+ marginBottom: SPACING.SMALL,
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <div style={{ color: FINCEPT.YELLOW, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.YELLOW, fontSize: '10px', fontWeight: 700 }}>
Short-Term Capital Gains (&lt; 1 year)
</div>
- <div style={{ color: FINCEPT.WHITE, fontSize: TYPOGRAPHY.BODY, textAlign: 'right' }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: '10px', textAlign: 'right' }}>
{formatCurrency(taxCalculation.shortTermGains, currency)}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY, textAlign: 'right' }}>15%</div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.BODY, textAlign: 'right', fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px', textAlign: 'right' }}>15%</div>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '10px', textAlign: 'right', fontWeight: 700 }}>
{formatCurrency(taxCalculation.shortTermTax, currency)}
</div>
</div>
@@ -182,16 +218,18 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
padding: SPACING.MEDIUM,
backgroundColor: 'rgba(0,214,111,0.05)',
borderLeft: `3px solid ${FINCEPT.GREEN}`,
- marginBottom: SPACING.SMALL
+ borderRadius: '2px',
+ marginBottom: SPACING.SMALL,
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <div style={{ color: FINCEPT.GREEN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.GREEN, fontSize: '10px', fontWeight: 700 }}>
Long-Term Capital Gains (&gt; 1 year)
</div>
- <div style={{ color: FINCEPT.WHITE, fontSize: TYPOGRAPHY.BODY, textAlign: 'right' }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: '10px', textAlign: 'right' }}>
{formatCurrency(taxCalculation.longTermGains, currency)}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY, textAlign: 'right' }}>20%</div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.BODY, textAlign: 'right', fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px', textAlign: 'right' }}>20%</div>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '10px', textAlign: 'right', fontWeight: 700 }}>
{formatCurrency(taxCalculation.longTermTax, currency)}
</div>
</div>
@@ -203,12 +241,13 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
padding: SPACING.MEDIUM,
backgroundColor: 'rgba(255,136,0,0.1)',
borderTop: `2px solid ${FINCEPT.ORANGE}`,
+ borderRadius: '2px',
marginTop: SPACING.SMALL
}}>
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.DEFAULT, fontWeight: TYPOGRAPHY.BOLD }}>TOTAL TAX DUE</div>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '11px', fontWeight: 700 }}>TOTAL TAX DUE</div>
<div></div>
<div></div>
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.SUBHEADING, textAlign: 'right', fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '13px', textAlign: 'right', fontWeight: 700 }}>
{formatCurrency(taxCalculation.totalTax, currency)}
</div>
</div>
@@ -219,12 +258,8 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
{/* Transaction Summary */}
<div>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.MEDIUM,
- paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.ORANGE
+ ...COMMON_STYLES.sectionHeader,
+ marginBottom: SPACING.MEDIUM
}}>
TRANSACTION SUMMARY
</div>
@@ -232,17 +267,19 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
padding: SPACING.DEFAULT,
backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD
+ border: BORDERS.STANDARD,
+ borderRadius: '2px'
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
marginBottom: SPACING.SMALL,
paddingBottom: SPACING.SMALL,
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY }}>Total Transactions:</span>
- <span style={{ color: FINCEPT.WHITE, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Total Transactions:</span>
+ <span style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
{transactions.length}
</span>
</div>
@@ -252,10 +289,11 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
justifyContent: 'space-between',
marginBottom: SPACING.SMALL,
paddingBottom: SPACING.SMALL,
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY }}>Buy Transactions:</span>
- <span style={{ color: FINCEPT.GREEN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Buy Transactions:</span>
+ <span style={{ color: FINCEPT.GREEN, fontSize: '10px', fontWeight: 700 }}>
{transactions.filter(t => t.transaction_type === 'BUY').length}
</span>
</div>
@@ -265,20 +303,22 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
justifyContent: 'space-between',
marginBottom: SPACING.SMALL,
paddingBottom: SPACING.SMALL,
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY }}>Sell Transactions:</span>
- <span style={{ color: FINCEPT.RED, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Sell Transactions:</span>
+ <span style={{ color: FINCEPT.RED, fontSize: '10px', fontWeight: 700 }}>
{transactions.filter(t => t.transaction_type === 'SELL').length}
</span>
</div>
<div style={{
display: 'flex',
- justifyContent: 'space-between'
+ justifyContent: 'space-between',
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY }}>Current Positions:</span>
- <span style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Current Positions:</span>
+ <span style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
{portfolioSummary.holdings.length}
</span>
</div>
@@ -288,12 +328,8 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
{/* Dividend Information */}
<div>
<div style={{
- color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.MEDIUM,
- paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.ORANGE
+ ...COMMON_STYLES.sectionHeader,
+ marginBottom: SPACING.MEDIUM
}}>
DIVIDEND INCOME
</div>
@@ -301,27 +337,30 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
padding: SPACING.DEFAULT,
backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD
+ border: BORDERS.STANDARD,
+ borderRadius: '2px'
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
marginBottom: SPACING.SMALL,
paddingBottom: SPACING.SMALL,
- borderBottom: `1px solid ${FINCEPT.BORDER}`
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY }}>Total Dividends (YTD):</span>
- <span style={{ color: FINCEPT.GREEN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Total Dividends (YTD):</span>
+ <span style={{ color: FINCEPT.GREEN, fontSize: '10px', fontWeight: 700 }}>
{formatCurrency(totalDividends, currency)}
</span>
</div>
<div style={{
display: 'flex',
- justifyContent: 'space-between'
+ justifyContent: 'space-between',
+ transition: EFFECTS.TRANSITION_STANDARD
}}>
- <span style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY }}>Portfolio Yield:</span>
- <span style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.BODY, fontWeight: TYPOGRAPHY.BOLD }}>
+ <span style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase' as const }}>Portfolio Yield:</span>
+ <span style={{ color: FINCEPT.CYAN, fontSize: '10px', fontWeight: 700 }}>
{dividendYield.toFixed(2)}%
</span>
</div>
@@ -334,12 +373,15 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
marginTop: SPACING.XLARGE,
padding: SPACING.DEFAULT,
backgroundColor: 'rgba(255,136,0,0.05)',
- border: BORDERS.ORANGE
+ border: BORDERS.ORANGE,
+ borderRadius: '2px'
}}>
<div style={{
+ fontSize: '9px',
+ fontWeight: 700,
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase' as const,
marginBottom: SPACING.MEDIUM
}}>
EXPORT OPTIONS
@@ -349,7 +391,7 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<button style={{
...COMMON_STYLES.buttonPrimary,
backgroundColor: FINCEPT.ORANGE,
- borderColor: FINCEPT.ORANGE
+ color: FINCEPT.DARK_BG
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = '0.85';
@@ -363,7 +405,7 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<button style={{
...COMMON_STYLES.buttonPrimary,
backgroundColor: FINCEPT.GREEN,
- borderColor: FINCEPT.GREEN
+ color: FINCEPT.DARK_BG
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = '0.85';
@@ -377,7 +419,6 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<button style={{
...COMMON_STYLES.buttonPrimary,
backgroundColor: FINCEPT.CYAN,
- borderColor: FINCEPT.CYAN,
color: FINCEPT.DARK_BG
}}
onMouseEnter={(e) => {
@@ -392,7 +433,7 @@ const ReportsView: React.FC<ReportsViewProps> = ({ portfolioSummary, transaction
<div style={{
marginTop: SPACING.MEDIUM,
- fontSize: TYPOGRAPHY.TINY,
+ fontSize: '9px',
color: FINCEPT.GRAY
}}>
Reports are generated for the current tax year. Consult with a tax professional for accurate filing.
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/RiskMetricsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/RiskMetricsView.tsx
index 573ad4117..0e5aae065 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/RiskMetricsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/RiskMetricsView.tsx
@@ -1,7 +1,6 @@
import React, { useState, useEffect } from 'react';
import { PortfolioSummary, portfolioService } from '../../../../services/portfolio/portfolioService';
import {
- FINCEPT_COLORS,
formatPercent,
calculateSharpeRatio,
calculateBeta,
@@ -9,7 +8,7 @@ import {
calculateMaxDrawdown,
calculateVaR
} from './utils';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../finceptStyles';
+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, EFFECTS } from '../finceptStyles';
interface RiskMetricsViewProps {
portfolioSummary: PortfolioSummary;
@@ -19,6 +18,7 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
const [loading, setLoading] = useState(true);
const [portfolioReturns, setPortfolioReturns] = useState<number[]>([]);
const [portfolioValues, setPortfolioValues] = useState<number[]>([]);
+ const [hoveredCard, setHoveredCard] = useState<string | null>(null);
useEffect(() => {
const loadRiskData = async () => {
@@ -105,14 +105,14 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div style={{
height: '100%',
backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.XLARGE,
+ padding: '24px',
textAlign: 'center',
fontFamily: TYPOGRAPHY.MONO
}}>
- <div style={{ color: FINCEPT.ORANGE, fontSize: TYPOGRAPHY.SUBHEADING, marginBottom: SPACING.SMALL }}>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '11px', marginBottom: '4px' }}>
Loading risk metrics...
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.BODY }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
Calculating portfolio risk from historical data
</div>
</div>
@@ -123,24 +123,29 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div style={{
height: '100%',
backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.DEFAULT,
+ padding: '12px',
overflow: 'auto',
fontFamily: TYPOGRAPHY.MONO
}}>
<div style={{
...COMMON_STYLES.sectionHeader,
- marginBottom: SPACING.LARGE
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: BORDERS.STANDARD,
+ marginBottom: '16px',
+ borderRadius: '2px'
}}>
RISK METRICS & ANALYTICS {hasInsufficientData && '(LIMITED DATA)'}
</div>
{hasInsufficientData && (
<div style={{
- padding: SPACING.MEDIUM,
- marginBottom: SPACING.DEFAULT,
+ padding: '8px',
+ marginBottom: '12px',
backgroundColor: 'rgba(255,136,0,0.1)',
- border: BORDERS.ORANGE,
- fontSize: TYPOGRAPHY.BODY,
+ border: `1px solid ${FINCEPT.ORANGE}`,
+ borderRadius: '2px',
+ fontSize: '10px',
color: FINCEPT.ORANGE
}}>
[WARN] <strong>INSUFFICIENT HISTORICAL DATA:</strong> Risk metrics require at least 5 days of portfolio snapshots for accurate calculations.
@@ -152,153 +157,230 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(3, 1fr)',
- gap: SPACING.DEFAULT,
- marginBottom: SPACING.XLARGE
+ gap: '12px',
+ marginBottom: '24px'
}}>
{/* Overall Risk Level */}
- <div style={{
- padding: SPACING.DEFAULT,
- backgroundColor: FINCEPT.PANEL_BG,
- border: `2px solid ${riskLevel.color}`
- }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.SMALL, marginBottom: SPACING.SMALL }}>OVERALL RISK</div>
+ <div
+ style={{
+ padding: '12px',
+ backgroundColor: hoveredCard === 'risk' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ border: `2px solid ${riskLevel.color}`,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
+ }}
+ onMouseEnter={() => setHoveredCard('risk')}
+ onMouseLeave={() => setHoveredCard(null)}
+ >
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '4px'
+ }}>OVERALL RISK</div>
<div style={{
color: riskLevel.color,
- fontSize: TYPOGRAPHY.LARGE,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.TINY
+ fontSize: '16px',
+ fontWeight: 700,
+ marginBottom: '2px'
}}>
{riskLevel.level}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>
Based on Sharpe Ratio: {sharpeRatio.toFixed(2)}
</div>
</div>
{/* Beta Rating */}
- <div style={{
- padding: SPACING.DEFAULT,
- backgroundColor: FINCEPT.PANEL_BG,
- border: `2px solid ${betaRating.color}`
- }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.SMALL, marginBottom: SPACING.SMALL }}>MARKET SENSITIVITY</div>
+ <div
+ style={{
+ padding: '12px',
+ backgroundColor: hoveredCard === 'beta-overview' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ border: `2px solid ${betaRating.color}`,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
+ }}
+ onMouseEnter={() => setHoveredCard('beta-overview')}
+ onMouseLeave={() => setHoveredCard(null)}
+ >
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '4px'
+ }}>MARKET SENSITIVITY</div>
<div style={{
color: betaRating.color,
- fontSize: TYPOGRAPHY.LARGE,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.TINY
+ fontSize: '16px',
+ fontWeight: 700,
+ marginBottom: '2px'
}}>
{betaRating.rating}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>
Beta: {beta.toFixed(2)}
</div>
</div>
{/* Volatility Rating */}
- <div style={{
- padding: SPACING.DEFAULT,
- backgroundColor: FINCEPT.PANEL_BG,
- border: `2px solid ${volatilityRating.color}`
- }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.SMALL, marginBottom: SPACING.SMALL }}>VOLATILITY</div>
+ <div
+ style={{
+ padding: '12px',
+ backgroundColor: hoveredCard === 'vol-overview' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ border: `2px solid ${volatilityRating.color}`,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
+ }}
+ onMouseEnter={() => setHoveredCard('vol-overview')}
+ onMouseLeave={() => setHoveredCard(null)}
+ >
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '4px'
+ }}>VOLATILITY</div>
<div style={{
color: volatilityRating.color,
- fontSize: TYPOGRAPHY.LARGE,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.TINY
+ fontSize: '16px',
+ fontWeight: 700,
+ marginBottom: '2px'
}}>
{volatilityRating.rating}
</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>
Annualized: {volatility.toFixed(2)}%
</div>
</div>
</div>
{/* Detailed Metrics Grid */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.DEFAULT, marginBottom: SPACING.XLARGE }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '24px' }}>
{/* Left Column - Return Metrics */}
<div>
<div style={{
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.MEDIUM,
- paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.ORANGE
+ fontSize: '11px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '8px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${FINCEPT.ORANGE}`
}}>
RISK-ADJUSTED RETURNS
</div>
{/* Sharpe Ratio */}
- <div style={{
- padding: SPACING.MEDIUM,
- marginBottom: SPACING.MEDIUM,
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD
- }}>
+ <div
+ style={{
+ padding: '8px',
+ marginBottom: '8px',
+ backgroundColor: hoveredCard === 'sharpe' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ border: BORDERS.STANDARD,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
+ }}
+ onMouseEnter={() => setHoveredCard('sharpe')}
+ onMouseLeave={() => setHoveredCard(null)}
+ >
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.DEFAULT, fontWeight: TYPOGRAPHY.BOLD }}>SHARPE RATIO</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, marginTop: SPACING.TINY }}>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '10px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>SHARPE RATIO</div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
Risk-adjusted return measure
</div>
</div>
<div style={{
color: sharpeRatio > 1 ? FINCEPT.GREEN : sharpeRatio > 0 ? FINCEPT.YELLOW : FINCEPT.RED,
- fontSize: TYPOGRAPHY.LARGE,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '16px',
+ fontWeight: 700
}}>
{sharpeRatio.toFixed(3)}
</div>
</div>
- <div style={{ marginTop: SPACING.SMALL, fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>
+ <div style={{ marginTop: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>
{'> 2: Excellent | 1-2: Good | 0-1: Fair | < 0: Poor'}
</div>
</div>
{/* Beta */}
- <div style={{
- padding: SPACING.MEDIUM,
- marginBottom: SPACING.MEDIUM,
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD
- }}>
+ <div
+ style={{
+ padding: '8px',
+ marginBottom: '8px',
+ backgroundColor: hoveredCard === 'beta' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ border: BORDERS.STANDARD,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
+ }}
+ onMouseEnter={() => setHoveredCard('beta')}
+ onMouseLeave={() => setHoveredCard(null)}
+ >
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.DEFAULT, fontWeight: TYPOGRAPHY.BOLD }}>BETA (β)</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, marginTop: SPACING.TINY }}>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '10px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>BETA ({'\u03B2'})</div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
Market correlation coefficient
</div>
</div>
- <div style={{ color: betaRating.color, fontSize: TYPOGRAPHY.LARGE, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: betaRating.color, fontSize: '16px', fontWeight: 700 }}>
{beta.toFixed(3)}
</div>
</div>
- <div style={{ marginTop: SPACING.SMALL, fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>
+ <div style={{ marginTop: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>
{'< 1: Less volatile | 1: Market neutral | > 1: More volatile'}
</div>
</div>
{/* Volatility */}
- <div style={{
- padding: SPACING.MEDIUM,
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD
- }}>
+ <div
+ style={{
+ padding: '8px',
+ backgroundColor: hoveredCard === 'volatility' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ border: BORDERS.STANDARD,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
+ }}
+ onMouseEnter={() => setHoveredCard('volatility')}
+ onMouseLeave={() => setHoveredCard(null)}
+ >
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.DEFAULT, fontWeight: TYPOGRAPHY.BOLD }}>VOLATILITY</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, marginTop: SPACING.TINY }}>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '10px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>VOLATILITY</div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
Annualized standard deviation
</div>
</div>
- <div style={{ color: volatilityRating.color, fontSize: TYPOGRAPHY.LARGE, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: volatilityRating.color, fontSize: '16px', fontWeight: 700 }}>
{volatility.toFixed(2)}%
</div>
</div>
- <div style={{ marginTop: SPACING.SMALL, fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>
+ <div style={{ marginTop: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>
Lower volatility indicates more stable returns
</div>
</div>
@@ -308,91 +390,130 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
<div>
<div style={{
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.MEDIUM,
- paddingBottom: SPACING.SMALL,
- borderBottom: BORDERS.ORANGE
+ fontSize: '11px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '8px',
+ paddingBottom: '4px',
+ borderBottom: `1px solid ${FINCEPT.ORANGE}`
}}>
DOWNSIDE RISK METRICS
</div>
{/* Maximum Drawdown */}
- <div style={{
- padding: SPACING.MEDIUM,
- marginBottom: SPACING.MEDIUM,
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD
- }}>
+ <div
+ style={{
+ padding: '8px',
+ marginBottom: '8px',
+ backgroundColor: hoveredCard === 'drawdown' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ border: BORDERS.STANDARD,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
+ }}
+ onMouseEnter={() => setHoveredCard('drawdown')}
+ onMouseLeave={() => setHoveredCard(null)}
+ >
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.DEFAULT, fontWeight: TYPOGRAPHY.BOLD }}>MAX DRAWDOWN</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, marginTop: SPACING.TINY }}>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '10px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>MAX DRAWDOWN</div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
Largest peak-to-trough decline
</div>
</div>
<div style={{
color: maxDrawdown > 20 ? FINCEPT.RED : maxDrawdown > 10 ? FINCEPT.ORANGE : FINCEPT.GREEN,
- fontSize: TYPOGRAPHY.LARGE,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '16px',
+ fontWeight: 700
}}>
-{maxDrawdown.toFixed(2)}%
</div>
</div>
- <div style={{ marginTop: SPACING.SMALL, fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>
+ <div style={{ marginTop: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>
Maximum loss from peak value
</div>
</div>
{/* Value at Risk */}
- <div style={{
- padding: SPACING.MEDIUM,
- marginBottom: SPACING.MEDIUM,
- backgroundColor: FINCEPT.PANEL_BG,
- border: BORDERS.STANDARD
- }}>
+ <div
+ style={{
+ padding: '8px',
+ marginBottom: '8px',
+ backgroundColor: hoveredCard === 'var' ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ border: BORDERS.STANDARD,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
+ }}
+ onMouseEnter={() => setHoveredCard('var')}
+ onMouseLeave={() => setHoveredCard(null)}
+ >
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
- <div style={{ color: FINCEPT.CYAN, fontSize: TYPOGRAPHY.DEFAULT, fontWeight: TYPOGRAPHY.BOLD }}>VALUE AT RISK (95%)</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, marginTop: SPACING.TINY }}>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '10px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>VALUE AT RISK (95%)</div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
Expected loss at 95% confidence
</div>
</div>
<div style={{
color: var95 < -0.03 ? FINCEPT.RED : var95 < -0.02 ? FINCEPT.ORANGE : FINCEPT.YELLOW,
- fontSize: TYPOGRAPHY.LARGE,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '16px',
+ fontWeight: 700
}}>
{(var95 * 100).toFixed(2)}%
</div>
</div>
- <div style={{ marginTop: SPACING.SMALL, fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>
+ <div style={{ marginTop: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>
5% chance of losing more than this in a day
</div>
</div>
{/* Risk Score */}
- <div style={{
- padding: SPACING.MEDIUM,
- backgroundColor: 'rgba(255,59,59,0.05)',
- border: `2px solid ${riskLevel.color}`
- }}>
+ <div
+ style={{
+ padding: '8px',
+ backgroundColor: hoveredCard === 'composite' ? 'rgba(255,59,59,0.08)' : 'rgba(255,59,59,0.05)',
+ border: `2px solid ${riskLevel.color}`,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD
+ }}
+ onMouseEnter={() => setHoveredCard('composite')}
+ onMouseLeave={() => setHoveredCard(null)}
+ >
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
- <div style={{ color: riskLevel.color, fontSize: TYPOGRAPHY.DEFAULT, fontWeight: TYPOGRAPHY.BOLD }}>COMPOSITE RISK SCORE</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.TINY, marginTop: SPACING.TINY }}>
+ <div style={{
+ color: riskLevel.color,
+ fontSize: '10px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>COMPOSITE RISK SCORE</div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
Weighted risk assessment
</div>
</div>
- <div style={{ color: riskLevel.color, fontSize: TYPOGRAPHY.LARGE, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: riskLevel.color, fontSize: '16px', fontWeight: 700 }}>
{((1 / (sharpeRatio + 1)) * 100).toFixed(0)}/100
</div>
</div>
- <div style={{ marginTop: SPACING.SMALL }}>
+ <div style={{ marginTop: '4px' }}>
<div style={{
width: '100%',
height: '8px',
backgroundColor: FINCEPT.HOVER,
+ borderRadius: '2px',
overflow: 'hidden'
}}>
<div style={{
@@ -409,47 +530,86 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
{/* Risk Recommendations */}
<div style={{
- padding: SPACING.DEFAULT,
+ padding: '12px',
backgroundColor: 'rgba(255,136,0,0.05)',
- border: BORDERS.ORANGE
+ border: `1px solid ${FINCEPT.ORANGE}`,
+ borderRadius: '2px'
}}>
<div style={{
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.MEDIUM
+ fontSize: '11px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '8px'
}}>
RISK MANAGEMENT RECOMMENDATIONS
</div>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.MEDIUM }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
{sharpeRatio < 1 && (
- <div style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.WHITE, padding: SPACING.SMALL, backgroundColor: 'rgba(255,59,59,0.1)' }}>
+ <div style={{
+ fontSize: '10px',
+ color: FINCEPT.WHITE,
+ padding: '4px',
+ backgroundColor: 'rgba(255,59,59,0.1)',
+ borderRadius: '2px'
+ }}>
[WARN] <strong>LOW SHARPE RATIO:</strong> Consider diversifying to improve risk-adjusted returns
</div>
)}
{beta > 1.5 && (
- <div style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.WHITE, padding: SPACING.SMALL, backgroundColor: 'rgba(255,136,0,0.1)' }}>
+ <div style={{
+ fontSize: '10px',
+ color: FINCEPT.WHITE,
+ padding: '4px',
+ backgroundColor: 'rgba(255,136,0,0.1)',
+ borderRadius: '2px'
+ }}>
[WARN] <strong>HIGH BETA:</strong> Portfolio is more volatile than market. Consider defensive assets
</div>
)}
{volatility > 25 && (
- <div style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.WHITE, padding: SPACING.SMALL, backgroundColor: 'rgba(255,59,59,0.1)' }}>
+ <div style={{
+ fontSize: '10px',
+ color: FINCEPT.WHITE,
+ padding: '4px',
+ backgroundColor: 'rgba(255,59,59,0.1)',
+ borderRadius: '2px'
+ }}>
[WARN] <strong>HIGH VOLATILITY:</strong> Consider adding bonds or stable assets to reduce swings
</div>
)}
{maxDrawdown > 20 && (
- <div style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.WHITE, padding: SPACING.SMALL, backgroundColor: 'rgba(255,59,59,0.1)' }}>
+ <div style={{
+ fontSize: '10px',
+ color: FINCEPT.WHITE,
+ padding: '4px',
+ backgroundColor: 'rgba(255,59,59,0.1)',
+ borderRadius: '2px'
+ }}>
[WARN] <strong>LARGE DRAWDOWN:</strong> Review stop-loss strategies and position sizing
</div>
)}
{sharpeRatio > 2 && (
- <div style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.WHITE, padding: SPACING.SMALL, backgroundColor: 'rgba(0,214,111,0.1)' }}>
+ <div style={{
+ fontSize: '10px',
+ color: FINCEPT.WHITE,
+ padding: '4px',
+ backgroundColor: 'rgba(0,214,111,0.1)',
+ borderRadius: '2px'
+ }}>
[OK] <strong>EXCELLENT SHARPE:</strong> Portfolio shows strong risk-adjusted performance
</div>
)}
{beta >= 0.8 && beta <= 1.2 && (
- <div style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.WHITE, padding: SPACING.SMALL, backgroundColor: 'rgba(0,229,255,0.1)' }}>
+ <div style={{
+ fontSize: '10px',
+ color: FINCEPT.WHITE,
+ padding: '4px',
+ backgroundColor: 'rgba(0,229,255,0.1)',
+ borderRadius: '2px'
+ }}>
[OK] <strong>BALANCED BETA:</strong> Good market correlation, neither too aggressive nor defensive
</div>
)}
@@ -458,11 +618,12 @@ const RiskMetricsView: React.FC<RiskMetricsViewProps> = ({ portfolioSummary }) =
{/* Disclaimer */}
<div style={{
- marginTop: SPACING.DEFAULT,
- padding: SPACING.MEDIUM,
+ marginTop: '12px',
+ padding: '8px',
backgroundColor: FINCEPT.HOVER,
border: BORDERS.STANDARD,
- fontSize: TYPOGRAPHY.TINY,
+ borderRadius: '2px',
+ fontSize: '9px',
color: FINCEPT.GRAY
}}>
<strong style={{ color: FINCEPT.ORANGE }}>DISCLAIMER:</strong> Risk metrics are calculated from portfolio snapshot history.
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsx
index 11686ffca..2c9b8c976 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsx
@@ -2,7 +2,7 @@ import React, { useMemo, useEffect, useState } from 'react';
import { PortfolioSummary, PortfolioHolding } from '../../../../services/portfolio/portfolioService';
import { formatCurrency, formatPercent } from './utils';
import { sectorService } from '../../../../services/data-sources/sectorService';
-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../finceptStyles';
+import { FINCEPT, BORDERS, COMMON_STYLES, TYPOGRAPHY, EFFECTS } from '../finceptStyles';
interface SectorsViewProps {
portfolioSummary: PortfolioSummary;
@@ -16,10 +16,14 @@ interface SectorAllocation {
color: string;
}
+
const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
const currency = portfolioSummary.portfolio.currency;
const [sectorsLoaded, setSectorsLoaded] = useState(false);
const [, forceUpdate] = useState(0);
+ const [hoveredSectorRow, setHoveredSectorRow] = useState<string | null>(null);
+ const [hoveredHoldingRow, setHoveredHoldingRow] = useState<string | null>(null);
+ const [hoveredLegendRow, setHoveredLegendRow] = useState<string | null>(null);
// Fincept color palette for sectors
const sectorColors = [
@@ -109,29 +113,31 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
<div style={{
height: '100%',
backgroundColor: FINCEPT.DARK_BG,
- padding: SPACING.DEFAULT,
+ padding: '12px',
overflow: 'auto',
fontFamily: TYPOGRAPHY.MONO
}}>
{/* Section Header */}
<div style={{
...COMMON_STYLES.sectionHeader,
- marginBottom: SPACING.LARGE
+ marginBottom: '16px'
}}>
SECTOR ALLOCATION
</div>
{!sectorsLoaded && portfolioSummary.holdings.length > 0 && (
<div style={{
- padding: SPACING.MEDIUM,
- marginBottom: SPACING.MEDIUM,
+ padding: '8px',
+ marginBottom: '8px',
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.CYAN,
+ borderRadius: '2px',
color: FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.BODY,
+ fontSize: '11px',
+ fontFamily: TYPOGRAPHY.MONO,
display: 'flex',
alignItems: 'center',
- gap: SPACING.SMALL
+ gap: '4px'
}}>
<span style={{ animation: 'pulse 1.5s infinite' }}>●</span>
Loading sector data from API...
@@ -140,22 +146,23 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
{sectorAllocations.length === 0 ? (
<div style={{
- padding: SPACING.XLARGE,
+ padding: '24px',
textAlign: 'center',
color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.DEFAULT
+ fontSize: '11px',
+ fontFamily: TYPOGRAPHY.MONO
}}>
No sector data available. Add holdings with sector information.
</div>
) : (
- <div style={{ display: 'grid', gridTemplateColumns: '400px 1fr', gap: SPACING.XLARGE }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '400px 1fr', gap: '24px' }}>
{/* Pie Chart */}
<div style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
}}>
- <svg width="300" height="300" style={{ marginBottom: SPACING.LARGE }}>
+ <svg width="300" height="300" style={{ marginBottom: '16px' }}>
{/* Pie segments */}
{pieData.map((sector, index) => (
<g key={sector.sector}>
@@ -173,8 +180,8 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
y={centerY + (radius * 0.7) * Math.sin((((sector.startAngle + sector.endAngle) / 2) - 90) * Math.PI / 180)}
textAnchor="middle"
fill={FINCEPT.WHITE}
- fontSize={TYPOGRAPHY.DEFAULT}
- fontWeight={TYPOGRAPHY.BOLD}
+ fontSize="11px"
+ fontWeight={700}
fontFamily={TYPOGRAPHY.MONO}
>
{sector.weight.toFixed(1)}%
@@ -196,8 +203,8 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
y={centerY - 10}
textAnchor="middle"
fill={FINCEPT.ORANGE}
- fontSize={TYPOGRAPHY.SUBHEADING}
- fontWeight={TYPOGRAPHY.BOLD}
+ fontSize="13px"
+ fontWeight={700}
fontFamily={TYPOGRAPHY.MONO}
>
SECTORS
@@ -207,8 +214,8 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
y={centerY + 10}
textAnchor="middle"
fill={FINCEPT.WHITE}
- fontSize={TYPOGRAPHY.HEADING}
- fontWeight={TYPOGRAPHY.BOLD}
+ fontSize="15px"
+ fontWeight={700}
fontFamily={TYPOGRAPHY.MONO}
>
{sectorAllocations.length}
@@ -220,36 +227,44 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
{sectorAllocations.map(sector => (
<div
key={sector.sector}
+ onMouseEnter={() => setHoveredLegendRow(sector.sector)}
+ onMouseLeave={() => setHoveredLegendRow(null)}
style={{
display: 'flex',
alignItems: 'center',
- marginBottom: SPACING.SMALL,
- padding: SPACING.SMALL,
- backgroundColor: FINCEPT.PANEL_BG,
- borderLeft: `4px solid ${sector.color}`
+ marginBottom: '4px',
+ padding: '4px',
+ backgroundColor: hoveredLegendRow === sector.sector ? FINCEPT.HOVER : FINCEPT.PANEL_BG,
+ borderLeft: `4px solid ${sector.color}`,
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD,
+ cursor: 'default'
}}
>
<div style={{
width: '12px',
height: '12px',
backgroundColor: sector.color,
- marginRight: SPACING.MEDIUM,
- border: BORDERS.STANDARD
+ marginRight: '8px',
+ border: BORDERS.STANDARD,
+ borderRadius: '2px'
}} />
<div style={{ flex: 1 }}>
<span style={{
color: FINCEPT.WHITE,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '11px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO
}}>
{sector.sector}
</span>
</div>
<div style={{ textAlign: 'right' }}>
<span style={{
- color: FINCEPT.YELLOW,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.BOLD
+ color: FINCEPT.CYAN,
+ fontSize: '10px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO
}}>
{sector.weight.toFixed(1)}%
</span>
@@ -263,10 +278,13 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
<div>
<div style={{
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.DEFAULT,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.MEDIUM,
- paddingBottom: SPACING.SMALL,
+ fontSize: '11px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '8px',
+ paddingBottom: '4px',
borderBottom: BORDERS.ORANGE
}}>
SECTOR BREAKDOWN
@@ -276,13 +294,17 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
<div style={{
display: 'grid',
gridTemplateColumns: '1.5fr 1fr 1fr 1fr',
- gap: SPACING.MEDIUM,
- padding: SPACING.MEDIUM,
+ gap: '8px',
+ padding: '8px 12px',
backgroundColor: FINCEPT.HEADER_BG,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.BOLD,
+ fontSize: '9px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
borderBottom: BORDERS.ORANGE,
- marginBottom: SPACING.SMALL
+ marginBottom: '4px',
+ borderRadius: '2px'
}}>
<div style={{ color: FINCEPT.ORANGE }}>SECTOR</div>
<div style={{ color: FINCEPT.ORANGE, textAlign: 'right' }}>VALUE</div>
@@ -292,148 +314,174 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {
{/* Sector Rows */}
{sectorAllocations.map((sector, index) => {
+ const sectorKey = sector.sector;
return (
- <div key={sector.sector} style={{ marginBottom: SPACING.DEFAULT }}>
+ <div key={sectorKey} style={{ marginBottom: '12px' }}>
{/* Sector Summary Row */}
- <div style={{
- display: 'grid',
- gridTemplateColumns: '1.5fr 1fr 1fr 1fr',
- gap: SPACING.MEDIUM,
- padding: SPACING.MEDIUM,
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent',
- borderLeft: `3px solid ${sector.color}`,
- fontSize: TYPOGRAPHY.BODY,
- marginBottom: SPACING.SMALL,
- minHeight: '32px',
- alignItems: 'center'
- }}>
- <div style={{ color: sector.color, fontWeight: TYPOGRAPHY.BOLD }}>
+ <div
+ onMouseEnter={() => setHoveredSectorRow(sectorKey)}
+ onMouseLeave={() => setHoveredSectorRow(null)}
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1.5fr 1fr 1fr 1fr',
+ gap: '8px',
+ padding: '8px',
+ backgroundColor: hoveredSectorRow === sectorKey
+ ? FINCEPT.HOVER
+ : index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent',
+ borderLeft: `3px solid ${sector.color}`,
+ borderRadius: '2px',
+ fontSize: '11px',
+ fontFamily: TYPOGRAPHY.MONO,
+ marginBottom: '4px',
+ minHeight: '32px',
+ alignItems: 'center',
+ transition: EFFECTS.TRANSITION_STANDARD,
+ cursor: 'default'
+ }}
+ >
+ <div style={{ color: sector.color, fontWeight: 700 }}>
{sector.sector}
</div>
- <div style={{ color: FINCEPT.YELLOW, textAlign: 'right', fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.CYAN, textAlign: 'right', fontWeight: 700, fontSize: '10px' }}>
{formatCurrency(sector.value, currency)}
</div>
- <div style={{ color: FINCEPT.YELLOW, textAlign: 'right', fontWeight: TYPOGRAPHY.BOLD }}>
+ <div style={{ color: FINCEPT.CYAN, textAlign: 'right', fontWeight: 700, fontSize: '10px' }}>
{sector.weight.toFixed(2)}%
</div>
- <div style={{ color: FINCEPT.CYAN, textAlign: 'right' }}>
+ <div style={{ color: FINCEPT.CYAN, textAlign: 'right', fontSize: '10px' }}>
{sector.holdings.length}
</div>
</div>
{/* Holdings in Sector */}
- {sector.holdings.map(holding => (
- <div
- key={holding.id}
- style={{
- display: 'grid',
- gridTemplateColumns: '1.5fr 1fr 1fr 1fr',
- gap: SPACING.MEDIUM,
- padding: `${SPACING.SMALL} ${SPACING.MEDIUM} ${SPACING.SMALL} ${SPACING.LARGE}`,
- backgroundColor: 'rgba(255,255,255,0.01)',
- fontSize: TYPOGRAPHY.SMALL,
- borderLeft: `1px solid ${sector.color}`,
- marginLeft: SPACING.MEDIUM,
- minHeight: '28px',
- alignItems: 'center'
- }}
- >
- <div style={{ color: FINCEPT.CYAN }}>└─ {holding.symbol}</div>
- <div style={{ color: FINCEPT.WHITE, textAlign: 'right' }}>
- {formatCurrency(holding.market_value, currency)}
+ {sector.holdings.map(holding => {
+ const holdingKey = `${sectorKey}-${holding.id}`;
+ return (
+ <div
+ key={holding.id}
+ onMouseEnter={() => setHoveredHoldingRow(holdingKey)}
+ onMouseLeave={() => setHoveredHoldingRow(null)}
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1.5fr 1fr 1fr 1fr',
+ gap: '8px',
+ padding: '4px 8px 4px 16px',
+ backgroundColor: hoveredHoldingRow === holdingKey
+ ? FINCEPT.HOVER
+ : 'rgba(255,255,255,0.01)',
+ fontSize: '10px',
+ fontFamily: TYPOGRAPHY.MONO,
+ borderLeft: `1px solid ${sector.color}`,
+ marginLeft: '8px',
+ minHeight: '28px',
+ alignItems: 'center',
+ borderRadius: '2px',
+ transition: EFFECTS.TRANSITION_STANDARD,
+ cursor: 'default'
+ }}
+ >
+ <div style={{ color: FINCEPT.CYAN }}>{'\u2514\u2500'} {holding.symbol}</div>
+ <div style={{ color: FINCEPT.WHITE, textAlign: 'right' }}>
+ {formatCurrency(holding.market_value, currency)}
+ </div>
+ <div style={{ color: FINCEPT.GRAY, textAlign: 'right' }}>
+ {holding.weight.toFixed(2)}%
+ </div>
+ <div style={{
+ color: holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ textAlign: 'right',
+ fontWeight: 600
+ }}>
+ {formatPercent(holding.unrealized_pnl_percent)}
+ </div>
</div>
- <div style={{ color: FINCEPT.GRAY, textAlign: 'right' }}>
- {holding.weight.toFixed(2)}%
- </div>
- <div style={{
- color: holding.unrealized_pnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
- textAlign: 'right',
- fontWeight: TYPOGRAPHY.SEMIBOLD
- }}>
- {formatPercent(holding.unrealized_pnl_percent)}
- </div>
- </div>
- ))}
+ );
+ })}
</div>
);
})}
{/* Sector Statistics */}
<div style={{
- marginTop: SPACING.LARGE,
- padding: SPACING.DEFAULT,
+ marginTop: '16px',
+ padding: '12px',
backgroundColor: FINCEPT.PANEL_BG,
border: BORDERS.ORANGE,
+ borderRadius: '2px'
}}>
<div style={{
color: FINCEPT.ORANGE,
- fontSize: TYPOGRAPHY.BODY,
- fontWeight: TYPOGRAPHY.BOLD,
- marginBottom: SPACING.MEDIUM
+ fontSize: '9px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ marginBottom: '8px'
}}>
DIVERSIFICATION METRICS
</div>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.DEFAULT }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
<div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.SMALL,
- marginBottom: SPACING.TINY
+ ...COMMON_STYLES.dataLabel,
+ marginBottom: '2px'
}}>
Total Sectors
</div>
<div style={{
color: FINCEPT.CYAN,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '15px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO
}}>
{sectorAllocations.length}
</div>
</div>
<div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.SMALL,
- marginBottom: SPACING.TINY
+ ...COMMON_STYLES.dataLabel,
+ marginBottom: '2px'
}}>
Largest Sector
</div>
<div style={{
color: FINCEPT.YELLOW,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '15px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO
}}>
{sectorAllocations[0]?.sector || 'N/A'} ({sectorAllocations[0]?.weight.toFixed(1)}%)
</div>
</div>
<div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.SMALL,
- marginBottom: SPACING.TINY
+ ...COMMON_STYLES.dataLabel,
+ marginBottom: '2px'
}}>
Concentration Risk
</div>
<div style={{
color: sectorAllocations[0]?.weight > 40 ? FINCEPT.RED : sectorAllocations[0]?.weight > 25 ? FINCEPT.YELLOW : FINCEPT.GREEN,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '15px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO
}}>
{sectorAllocations[0]?.weight > 40 ? 'HIGH' : sectorAllocations[0]?.weight > 25 ? 'MEDIUM' : 'LOW'}
</div>
</div>
<div>
<div style={{
- color: FINCEPT.GRAY,
- fontSize: TYPOGRAPHY.SMALL,
- marginBottom: SPACING.TINY
+ ...COMMON_STYLES.dataLabel,
+ marginBottom: '2px'
}}>
Diversification
</div>
<div style={{
color: sectorAllocations.length >= 5 ? FINCEPT.GREEN : sectorAllocations.length >= 3 ? FINCEPT.YELLOW : FINCEPT.RED,
- fontSize: TYPOGRAPHY.HEADING,
- fontWeight: TYPOGRAPHY.BOLD
+ fontSize: '15px',
+ fontWeight: 700,
+ fontFamily: TYPOGRAPHY.MONO
}}>
{sectorAllocations.length >= 5 ? 'GOOD' : sectorAllocations.length >= 3 ? 'MODERATE' : 'POOR'}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx b/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
index 25e39cdac..e826906e5 100644
--- a/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
@@ -1,16 +1,16 @@
-// File: src/components/tabs/ProfileTab.tsx
-// Fincept-style Professional Profile & Account Management Interface
+// File: src/components/tabs/profile/ProfileTab.tsx
+// Fincept Terminal – Profile & Account Management (FINCEPT Design System)
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { UserApiService } from '@/services/auth/userApi';
import { TabHeader } from '@/components/common/TabHeader';
import { TabFooter } from '@/components/common/TabFooter';
-import { useTranslation } from 'react-i18next';
import {
User, CreditCard, Activity, Shield, Key, RefreshCw,
- LogOut, Crown, Zap, FileText, CheckCircle, AlertCircle, Eye, EyeOff, BarChart,
- MessageSquarePlus, Mail, Newspaper, Star, Send, Check, HeadphonesIcon
+ LogOut, Zap, CheckCircle, AlertCircle, Eye, EyeOff, BarChart,
+ MessageSquarePlus, Mail, Newspaper, Star, Send, Check, HeadphonesIcon,
+ FileText, Package, Calendar,
} from 'lucide-react';
import {
submitContactForm,
@@ -20,415 +20,299 @@ import {
type FeedbackFormData,
} from '@/services/support/supportApi';
-// Fincept Professional Color Palette
-const COLORS = {
- ORANGE: '#ea580c',
- WHITE: '#ffffff',
- RED: '#ef4444',
- GREEN: '#10b981',
- GRAY: '#6b7280',
+// ─── FINCEPT Design System Colors ─────────────────────────────────────────────
+const F = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
DARK_BG: '#000000',
- PANEL_BG: '#0a0a0a',
- HEADER_BG: '#1a1a1a',
- CYAN: '#06b6d4',
- YELLOW: '#eab308',
- BORDER: '#262626',
- MUTED: '#737373'
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
};
+const FONT = '"IBM Plex Mono", "Consolas", monospace';
+
+// ─── Types (matched to actual API responses) ─────────────────────────────────
+// GET /payment/subscription → { success, data: { user_id, account_type, credit_balance, ... } }
+interface AccountSubscriptionData {
+ user_id: number;
+ account_type: string;
+ credit_balance: number;
+ credits_expire_at: string | null;
+ support_type: string;
+ last_credit_purchase_at: string | null;
+ created_at: string;
+}
+
+// GET /payment/payments → { success, data: { payments: [...], pagination: {...} } }
+interface PaymentHistoryItem {
+ payment_uuid: string;
+ payment_gateway: string;
+ amount_usd: number;
+ currency: string;
+ status: string;
+ plan_name: string;
+ credits_purchased: number | null;
+ payment_method: string | null;
+ created_at: string;
+ completed_at: string | null;
+}
+
+interface UsageData {
+ total_requests?: number;
+ month_requests?: number;
+ week_requests?: number;
+}
+
type Section = 'overview' | 'usage' | 'security' | 'billing' | 'support';
+// ─── Main Component ───────────────────────────────────────────────────────────
const ProfileTab: React.FC = () => {
- const { t } = useTranslation('profile');
const { session, logout, refreshUserData } = useAuth();
const [activeSection, setActiveSection] = useState<Section>('overview');
const [loading, setLoading] = useState(false);
- const [usageData, setUsageData] = useState<any>(null);
- const [paymentHistory, setPaymentHistory] = useState<any[]>([]);
+ const [usageData, setUsageData] = useState<UsageData | null>(null);
+ const [subscriptionData, setSubscriptionData] = useState<AccountSubscriptionData | null>(null);
+ const [paymentHistory, setPaymentHistory] = useState<PaymentHistoryItem[]>([]);
const [showApiKey, setShowApiKey] = useState(false);
const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);
const [showRegenerateConfirm, setShowRegenerateConfirm] = useState(false);
+ const [error, setError] = useState<string | null>(null);
- useEffect(() => {
- fetchSectionData();
- }, [activeSection, session]);
-
- const fetchSectionData = async () => {
+ const fetchSectionData = useCallback(async () => {
if (!session?.api_key) return;
setLoading(true);
+ setError(null);
try {
if (activeSection === 'usage') {
const result = session.user_type === 'guest'
? await UserApiService.getGuestUsage(session.api_key)
: await UserApiService.getUserUsage(session.api_key);
if (result.success) setUsageData(result.data);
+ else setError(result.error || 'Failed to load usage data');
} else if (activeSection === 'billing') {
- const result = await UserApiService.getPaymentHistory(session.api_key, 1, 10);
- if (result.success) setPaymentHistory(result.data?.payments || []);
+ // /payment/subscription returns account-level data
+ // /payment/payments returns actual payment history (NOT /payment/history which is 404)
+ const [subResult, historyResult] = await Promise.all([
+ UserApiService.getUserSubscription(session.api_key),
+ UserApiService.getPaymentHistory(session.api_key, 1, 20),
+ ]);
+ if (subResult.success && subResult.data) {
+ // API wraps in { success, message, data: { ... } }
+ const raw = subResult.data as any;
+ const d = raw?.data || raw;
+ setSubscriptionData(d);
+ }
+ if (historyResult.success && historyResult.data) {
+ const raw = historyResult.data as any;
+ const payments = raw?.data?.payments || raw?.payments || [];
+ setPaymentHistory(payments);
+ }
+ if (!subResult.success && !historyResult.success) {
+ setError('Failed to load billing data');
+ }
}
- } catch (error) {
- // Silently handle errors
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Network error');
} finally {
setLoading(false);
}
- };
+ }, [activeSection, session]);
- const handleLogout = async () => {
- setShowLogoutConfirm(true);
- };
+ useEffect(() => {
+ fetchSectionData();
+ }, [fetchSectionData]);
const confirmLogout = async () => {
setShowLogoutConfirm(false);
await logout();
};
- const handleRegenerateKey = async () => {
- if (!session?.api_key) return;
- setShowRegenerateConfirm(true);
- };
-
const confirmRegenerateKey = async () => {
if (!session?.api_key) return;
setShowRegenerateConfirm(false);
setLoading(true);
const result = await UserApiService.regenerateApiKey(session.api_key);
setLoading(false);
- if (result.success) {
- await refreshUserData();
- }
+ if (result.success) await refreshUserData();
};
const accountType = session?.user_info?.account_type || 'free';
const credits = session?.user_info?.credit_balance || 0;
const username = session?.user_info?.username || session?.user_info?.email || 'User';
const email = session?.user_info?.email || 'N/A';
- const apiKey = session?.api_key || '';
- const headerActions = (
- <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
- <div style={{
- padding: '6px 12px',
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- fontFamily: 'monospace',
- fontSize: '11px'
- }}>
- <span style={{ color: COLORS.MUTED }}>{t('extracted.credits')} </span>
- <span style={{ color: COLORS.CYAN, fontWeight: 'bold' }}>{credits.toLocaleString()}</span>
- </div>
- <div style={{
- padding: '6px 12px',
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- fontFamily: 'monospace',
- fontSize: '11px'
- }}>
- <span style={{ color: COLORS.MUTED }}>{t('extracted.plan')} </span>
- <span style={{ color: COLORS.ORANGE, fontWeight: 'bold' }}>{accountType.toUpperCase()}</span>
- </div>
- <button
- type="button"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- fetchSectionData();
- }}
- style={{
- padding: '6px 12px',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- cursor: 'pointer',
- fontFamily: 'monospace',
- fontSize: '11px',
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <RefreshCw size={12} />
- {t('refresh')}
- </button>
- </div>
- );
+ const sections: { id: Section; label: string; icon: React.ElementType }[] = [
+ { id: 'overview', label: 'OVERVIEW', icon: User },
+ { id: 'usage', label: 'USAGE', icon: Activity },
+ { id: 'security', label: 'SECURITY', icon: Shield },
+ { id: 'billing', label: 'BILLING', icon: CreditCard },
+ { id: 'support', label: 'SUPPORT', icon: HeadphonesIcon },
+ ];
return (
- <div style={{
- height: '100%',
- display: 'flex',
- flexDirection: 'column',
- backgroundColor: COLORS.DARK_BG,
- fontFamily: 'Consolas, "Courier New", monospace'
- }}>
+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: F.DARK_BG, fontFamily: FONT }}>
<TabHeader
- title={t('extracted.profileAccount')}
+ title="PROFILE & ACCOUNT"
subtitle={`${username} | ${email}`}
icon={<User size={20} />}
- actions={headerActions}
+ actions={
+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
+ <Badge label="CREDITS" value={credits.toLocaleString()} color={F.CYAN} />
+ <Badge label="PLAN" value={accountType.toUpperCase()} color={F.ORANGE} />
+ <SecondaryBtn icon={<RefreshCw size={10} />} label="REFRESH" onClick={fetchSectionData} />
+ </div>
+ }
/>
- {/* Navigation Bar */}
- <div style={{
- borderBottom: `1px solid ${COLORS.BORDER}`,
- backgroundColor: COLORS.HEADER_BG,
- display: 'flex',
- gap: '0',
- flexShrink: 0
- }}>
- {[
- { id: 'overview', label: 'OVERVIEW', icon: User },
- { id: 'usage', label: 'USAGE & CREDITS', icon: Activity },
- { id: 'security', label: 'SECURITY', icon: Shield },
- { id: 'billing', label: 'BILLING', icon: CreditCard },
- { id: 'support', label: 'SUPPORT', icon: HeadphonesIcon },
- ].map(section => (
+ {/* Tab Navigation */}
+ <div style={{ borderBottom: `1px solid ${F.BORDER}`, backgroundColor: F.HEADER_BG, display: 'flex', flexShrink: 0 }}>
+ {sections.map(s => (
<button
- key={section.id}
- onClick={() => setActiveSection(section.id as Section)}
+ key={s.id}
+ onClick={() => setActiveSection(s.id)}
style={{
- padding: '10px 20px',
- backgroundColor: activeSection === section.id ? COLORS.PANEL_BG : 'transparent',
+ padding: '6px 12px',
+ backgroundColor: activeSection === s.id ? F.ORANGE : 'transparent',
+ color: activeSection === s.id ? F.DARK_BG : F.GRAY,
border: 'none',
- borderBottom: activeSection === section.id ? `2px solid ${COLORS.ORANGE}` : '2px solid transparent',
- color: activeSection === section.id ? COLORS.ORANGE : COLORS.MUTED,
+ fontSize: '9px',
+ fontWeight: 700,
+ fontFamily: FONT,
+ letterSpacing: '0.5px',
cursor: 'pointer',
- fontFamily: 'monospace',
- fontSize: '11px',
- fontWeight: 'bold',
display: 'flex',
alignItems: 'center',
gap: '6px',
- transition: 'all 0.2s'
+ transition: 'all 0.2s',
}}
>
- {React.createElement(section.icon, { size: 14 })}
- {section.label}
+ {React.createElement(s.icon, { size: 12 })}
+ {s.label}
</button>
))}
</div>
- {/* Content Area */}
- <div style={{
- flex: 1,
- overflow: 'auto',
- padding: '16px',
- minHeight: 0,
- display: 'flex',
- flexDirection: 'column'
- }}>
- {activeSection === 'overview' && <OverviewSection session={session} onLogout={handleLogout} />}
- {activeSection === 'usage' && <UsageSection usageData={usageData} loading={loading} session={session} />}
+ {/* Error Banner */}
+ {error && (
+ <div style={{
+ padding: '8px 16px',
+ backgroundColor: `${F.RED}20`,
+ borderBottom: `1px solid ${F.RED}`,
+ color: F.RED,
+ fontSize: '9px',
+ fontFamily: FONT,
+ fontWeight: 700,
+ }}>
+ {error}
+ </div>
+ )}
+
+ {/* Content */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '16px', minHeight: 0, display: 'flex', flexDirection: 'column' }}>
+ {activeSection === 'overview' && (
+ <OverviewSection session={session} onLogout={() => setShowLogoutConfirm(true)} />
+ )}
+ {activeSection === 'usage' && (
+ <UsageSection usageData={usageData} loading={loading} session={session} />
+ )}
{activeSection === 'security' && (
<SecuritySection
session={session}
- onRegenerateKey={handleRegenerateKey}
+ onRegenerateKey={() => setShowRegenerateConfirm(true)}
loading={loading}
showApiKey={showApiKey}
setShowApiKey={setShowApiKey}
/>
)}
- {activeSection === 'billing' && <BillingSection paymentHistory={paymentHistory} loading={loading} />}
+ {activeSection === 'billing' && (
+ <BillingSection
+ subscriptionData={subscriptionData}
+ paymentHistory={paymentHistory}
+ loading={loading}
+ />
+ )}
{activeSection === 'support' && <SupportSection />}
</div>
<TabFooter
tabName="PROFILE"
leftInfo={[
- { label: 'USER', value: username, color: COLORS.CYAN },
- { label: 'TYPE', value: session?.user_type?.toUpperCase(), color: COLORS.WHITE }
+ { label: 'USER', value: username, color: F.CYAN },
+ { label: 'TYPE', value: session?.user_type?.toUpperCase(), color: F.WHITE },
]}
- statusInfo={`Last Updated: ${new Date().toLocaleTimeString()}`}
+ statusInfo={`Updated: ${new Date().toLocaleTimeString()}`}
/>
- {/* Logout Confirmation Modal */}
+ {/* Logout Modal */}
{showLogoutConfirm && (
- <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: 1000
- }}>
- <div style={{
- backgroundColor: COLORS.PANEL_BG,
- border: `2px solid ${COLORS.ORANGE}`,
- padding: '24px',
- maxWidth: '400px',
- width: '90%'
- }}>
- <div style={{
- color: COLORS.ORANGE,
- fontSize: '14px',
- fontWeight: 'bold',
- marginBottom: '16px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}>
- <LogOut size={18} />
- CONFIRM LOGOUT
- </div>
- <div style={{
- color: COLORS.MUTED,
- fontSize: '11px',
- marginBottom: '16px'
- }}>
- Are you sure you want to logout from Fincept Terminal?
- </div>
- <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
- <button
- onClick={() => setShowLogoutConfirm(false)}
- style={{
- padding: '8px 16px',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- cursor: 'pointer',
- fontSize: '11px',
- fontFamily: 'monospace'
- }}
- >
- CANCEL
- </button>
- <button
- onClick={confirmLogout}
- style={{
- padding: '8px 16px',
- backgroundColor: COLORS.RED,
- border: 'none',
- color: COLORS.WHITE,
- cursor: 'pointer',
- fontSize: '11px',
- fontFamily: 'monospace',
- fontWeight: 'bold'
- }}
- >
- LOGOUT
- </button>
- </div>
- </div>
- </div>
+ <ConfirmModal
+ icon={<LogOut size={16} />}
+ title="CONFIRM LOGOUT"
+ message="Are you sure you want to logout from Fincept Terminal?"
+ confirmLabel="LOGOUT"
+ confirmColor={F.RED}
+ onCancel={() => setShowLogoutConfirm(false)}
+ onConfirm={confirmLogout}
+ />
)}
- {/* Regenerate API Key Confirmation Modal */}
+ {/* Regenerate Key Modal */}
{showRegenerateConfirm && (
- <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: 1000
- }}>
- <div style={{
- backgroundColor: COLORS.PANEL_BG,
- border: `2px solid ${COLORS.ORANGE}`,
- padding: '24px',
- maxWidth: '400px',
- width: '90%'
- }}>
- <div style={{
- color: COLORS.ORANGE,
- fontSize: '14px',
- fontWeight: 'bold',
- marginBottom: '16px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}>
- <Key size={18} />
- REGENERATE API KEY
- </div>
- <div style={{
- color: COLORS.MUTED,
- fontSize: '11px',
- marginBottom: '16px'
- }}>
- Your current API key will be invalidated. Are you sure you want to continue?
- </div>
- <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
- <button
- onClick={() => setShowRegenerateConfirm(false)}
- style={{
- padding: '8px 16px',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- cursor: 'pointer',
- fontSize: '11px',
- fontFamily: 'monospace'
- }}
- >
- CANCEL
- </button>
- <button
- onClick={confirmRegenerateKey}
- disabled={loading}
- style={{
- padding: '8px 16px',
- backgroundColor: COLORS.ORANGE,
- border: 'none',
- color: COLORS.WHITE,
- cursor: loading ? 'not-allowed' : 'pointer',
- fontSize: '11px',
- fontFamily: 'monospace',
- fontWeight: 'bold',
- opacity: loading ? 0.5 : 1
- }}
- >
- {loading ? 'REGENERATING...' : 'CONFIRM'}
- </button>
- </div>
- </div>
- </div>
+ <ConfirmModal
+ icon={<Key size={16} />}
+ title="REGENERATE API KEY"
+ message="Your current API key will be invalidated. Are you sure you want to continue?"
+ confirmLabel={loading ? 'REGENERATING...' : 'CONFIRM'}
+ confirmColor={F.ORANGE}
+ disabled={loading}
+ onCancel={() => setShowRegenerateConfirm(false)}
+ onConfirm={confirmRegenerateKey}
+ />
)}
</div>
);
};
-// Overview Section
+// ─── Overview Section ─────────────────────────────────────────────────────────
const OverviewSection: React.FC<{ session: any; onLogout: () => void }> = ({ session, onLogout }) => {
const accountType = session?.user_info?.account_type || 'free';
-
return (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
- {/* Account Info */}
- <DataPanel title="ACCOUNT INFORMATION" icon={<User size={16} />}>
+ <Panel title="ACCOUNT INFORMATION" icon={<User size={14} />}>
<DataRow label="USERNAME" value={session?.user_info?.username || 'N/A'} />
<DataRow label="EMAIL" value={session?.user_info?.email || 'N/A'} />
<DataRow label="USER TYPE" value={session?.user_type?.toUpperCase() || 'N/A'} />
- <DataRow label="ACCOUNT TYPE" value={accountType.toUpperCase()} valueColor={COLORS.ORANGE} />
+ <DataRow label="ACCOUNT TYPE" value={accountType.toUpperCase()} valueColor={F.ORANGE} />
<DataRow
label="EMAIL VERIFIED"
value={session?.user_info?.is_verified ? 'YES' : 'NO'}
- valueColor={session?.user_info?.is_verified ? COLORS.GREEN : COLORS.RED}
+ valueColor={session?.user_info?.is_verified ? F.GREEN : F.RED}
/>
<DataRow
label="2FA ENABLED"
value={session?.user_info?.mfa_enabled ? 'YES' : 'NO'}
- valueColor={session?.user_info?.mfa_enabled ? COLORS.GREEN : COLORS.RED}
+ valueColor={session?.user_info?.mfa_enabled ? F.GREEN : F.RED}
/>
- </DataPanel>
+ </Panel>
- {/* Credits & Balance */}
- <DataPanel title="CREDITS & BALANCE" icon={<Zap size={16} />}>
- <div style={{ padding: '20px 0', textAlign: 'center', borderBottom: `1px solid ${COLORS.BORDER}` }}>
- <div style={{ fontSize: '36px', color: COLORS.CYAN, fontWeight: 'bold', marginBottom: '8px' }}>
+ <Panel title="CREDITS & BALANCE" icon={<Zap size={14} />}>
+ <div style={{ padding: '20px 0', textAlign: 'center', borderBottom: `1px solid ${F.BORDER}` }}>
+ <div style={{ fontSize: '36px', color: F.CYAN, fontWeight: 700, marginBottom: '8px', fontFamily: FONT }}>
{(session?.user_info?.credit_balance || 0).toLocaleString()}
</div>
- <div style={{ fontSize: '11px', color: COLORS.MUTED }}>AVAILABLE CREDITS</div>
+ <div style={{ fontSize: '9px', color: F.GRAY, letterSpacing: '0.5px', fontWeight: 700 }}>AVAILABLE CREDITS</div>
</div>
<div style={{ padding: '12px 0' }}>
- <DataRow label="PLAN" value={accountType.toUpperCase()} valueColor={COLORS.ORANGE} />
+ <DataRow label="PLAN" value={accountType.toUpperCase()} valueColor={F.ORANGE} />
{session?.user_type === 'guest' && (
<>
<DataRow label="DAILY LIMIT" value={session?.daily_limit?.toString() || '0'} />
@@ -436,25 +320,21 @@ const OverviewSection: React.FC<{ session: any; onLogout: () => void }> = ({ ses
</>
)}
</div>
- </DataPanel>
+ </Panel>
- {/* Quick Actions */}
<div style={{ gridColumn: '1 / -1' }}>
- <DataPanel title="QUICK ACTIONS" icon={<Activity size={16} />}>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', padding: '8px 0' }}>
- <ActionButton label="REFRESH DATA" onClick={() => window.location.reload()} />
- <ActionButton label="UPGRADE PLAN" onClick={() => {}} />
- <ActionButton label="SETTINGS" onClick={() => {}} />
- <ActionButton label="LOGOUT" onClick={onLogout} danger />
+ <Panel title="QUICK ACTIONS" icon={<Activity size={14} />}>
+ <div style={{ display: 'flex', gap: '12px', padding: '8px 0' }}>
+ <ActionBtn label="LOGOUT" onClick={onLogout} danger />
</div>
- </DataPanel>
+ </Panel>
</div>
</div>
);
};
-// Usage Section
-const UsageSection: React.FC<{ usageData: any; loading: boolean; session: any }> = ({ usageData, loading, session }) => {
+// ─── Usage Section ────────────────────────────────────────────────────────────
+const UsageSection: React.FC<{ usageData: UsageData | null; loading: boolean; session: any }> = ({ usageData, loading, session }) => {
const credits = session?.user_info?.credit_balance || 0;
const dailyLimit = session?.daily_limit || 0;
const requestsToday = session?.requests_today || 0;
@@ -462,50 +342,53 @@ const UsageSection: React.FC<{ usageData: any; loading: boolean; session: any }>
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- <DataPanel title="CREDIT BALANCE" icon={<Zap size={16} />}>
+ <Panel title="CREDIT BALANCE" icon={<Zap size={14} />}>
<div style={{ padding: '20px 0', textAlign: 'center' }}>
- <div style={{ fontSize: '48px', color: COLORS.CYAN, fontWeight: 'bold', marginBottom: '8px' }}>
+ <div style={{ fontSize: '48px', color: F.CYAN, fontWeight: 700, marginBottom: '8px', fontFamily: FONT }}>
{credits.toLocaleString()}
</div>
- <div style={{ fontSize: '11px', color: COLORS.MUTED }}>AVAILABLE CREDITS</div>
+ <div style={{ fontSize: '9px', color: F.GRAY, letterSpacing: '0.5px', fontWeight: 700 }}>AVAILABLE CREDITS</div>
</div>
- </DataPanel>
+ </Panel>
{session?.user_type === 'guest' && (
- <DataPanel title="DAILY USAGE LIMIT" icon={<Activity size={16} />}>
+ <Panel title="DAILY USAGE LIMIT" icon={<Activity size={14} />}>
<div style={{ padding: '12px 0' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px', fontSize: '11px' }}>
- <span style={{ color: COLORS.MUTED }}>REQUESTS TODAY</span>
- <span style={{ color: COLORS.WHITE, fontWeight: 'bold' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px', fontSize: '10px' }}>
+ <span style={{ color: F.GRAY, fontWeight: 700, fontSize: '9px', letterSpacing: '0.5px' }}>REQUESTS TODAY</span>
+ <span style={{ color: F.WHITE, fontWeight: 700, fontFamily: FONT }}>
{requestsToday} / {dailyLimit}
</span>
</div>
- <div style={{ height: '8px', backgroundColor: COLORS.HEADER_BG, position: 'relative' }}>
+ <div style={{ height: '6px', backgroundColor: F.HEADER_BG, borderRadius: '2px', position: 'relative' }}>
<div style={{
height: '100%',
- width: `${usagePercent}%`,
- backgroundColor: usagePercent >= 90 ? COLORS.RED : COLORS.GREEN,
- transition: 'width 0.3s'
+ width: `${Math.min(usagePercent, 100)}%`,
+ backgroundColor: usagePercent >= 90 ? F.RED : usagePercent >= 70 ? F.YELLOW : F.GREEN,
+ borderRadius: '2px',
+ transition: 'width 0.3s',
}} />
</div>
</div>
- </DataPanel>
+ </Panel>
)}
- {usageData && (
- <DataPanel title="USAGE STATISTICS" icon={<BarChart size={16} />}>
+ {loading ? (
+ <LoadingState message="Loading usage data..." />
+ ) : usageData ? (
+ <Panel title="USAGE STATISTICS" icon={<BarChart size={14} />}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px', padding: '12px 0' }}>
<StatBox label="TOTAL REQUESTS" value={usageData.total_requests || 0} />
<StatBox label="THIS MONTH" value={usageData.month_requests || 0} />
<StatBox label="THIS WEEK" value={usageData.week_requests || 0} />
</div>
- </DataPanel>
- )}
+ </Panel>
+ ) : null}
</div>
);
};
-// Security Section
+// ─── Security Section ─────────────────────────────────────────────────────────
const SecuritySection: React.FC<{
session: any;
onRegenerateKey: () => void;
@@ -515,10 +398,10 @@ const SecuritySection: React.FC<{
}> = ({ session, onRegenerateKey, loading, showApiKey, setShowApiKey }) => {
const { refreshUserData } = useAuth();
const apiKey = session?.api_key || '';
- const [mfaLoading, setMfaLoading] = React.useState(false);
- const [showPasswordPrompt, setShowPasswordPrompt] = React.useState(false);
- const [password, setPassword] = React.useState('');
- const [statusMessage, setStatusMessage] = React.useState<{ type: 'success' | 'error', text: string } | null>(null);
+ const [mfaLoading, setMfaLoading] = useState(false);
+ const [showPasswordPrompt, setShowPasswordPrompt] = useState(false);
+ const [password, setPassword] = useState('');
+ const [statusMessage, setStatusMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
const handleEnableMFA = async () => {
if (!session?.api_key) return;
@@ -527,18 +410,15 @@ const SecuritySection: React.FC<{
const result = await UserApiService.enableMFA(session.api_key);
setMfaLoading(false);
if (result.success) {
- setStatusMessage({ type: 'success', text: 'MFA enabled! You will receive OTP codes via email during login.' });
- setTimeout(async () => {
- await refreshUserData();
- setStatusMessage(null);
- }, 2000);
+ setStatusMessage({ type: 'success', text: 'MFA enabled! OTP codes will be sent via email during login.' });
+ setTimeout(async () => { await refreshUserData(); setStatusMessage(null); }, 2000);
} else {
setStatusMessage({ type: 'error', text: result.error || 'Failed to enable MFA' });
setTimeout(() => setStatusMessage(null), 3000);
}
};
- const handleDisableMFA = async () => {
+ const handleDisableMFA = () => {
if (!session?.api_key) return;
setShowPasswordPrompt(true);
setStatusMessage(null);
@@ -558,10 +438,7 @@ const SecuritySection: React.FC<{
setPassword('');
if (result.success) {
setStatusMessage({ type: 'success', text: 'MFA disabled successfully!' });
- setTimeout(async () => {
- await refreshUserData();
- setStatusMessage(null);
- }, 2000);
+ setTimeout(async () => { await refreshUserData(); setStatusMessage(null); }, 2000);
} else {
setStatusMessage({ type: 'error', text: result.error || 'Failed to disable MFA' });
setTimeout(() => setStatusMessage(null), 3000);
@@ -570,277 +447,213 @@ const SecuritySection: React.FC<{
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- <DataPanel title="API KEY MANAGEMENT" icon={<Key size={16} />}>
+ <Panel title="API KEY MANAGEMENT" icon={<Key size={14} />}>
<div style={{ padding: '12px 0' }}>
<div style={{ display: 'flex', gap: '8px', marginBottom: '12px' }}>
<div style={{
flex: 1,
- padding: '10px',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- fontFamily: 'monospace',
- fontSize: '11px',
- color: COLORS.MUTED,
+ padding: '8px 10px',
+ backgroundColor: F.DARK_BG,
+ border: `1px solid ${F.BORDER}`,
+ borderRadius: '2px',
+ fontFamily: FONT,
+ fontSize: '10px',
+ color: F.GRAY,
overflow: 'hidden',
- textOverflow: 'ellipsis'
+ textOverflow: 'ellipsis',
}}>
- {showApiKey ? apiKey : apiKey.slice(0, 20) + '•'.repeat(Math.max(0, apiKey.length - 20))}
+ {showApiKey ? apiKey : apiKey.slice(0, 20) + '\u2022'.repeat(Math.max(0, apiKey.length - 20))}
</div>
- <button
+ <SecondaryBtn
+ icon={showApiKey ? <EyeOff size={10} /> : <Eye size={10} />}
+ label={showApiKey ? 'HIDE' : 'SHOW'}
onClick={() => setShowApiKey(!showApiKey)}
- style={{
- padding: '10px 16px',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- cursor: 'pointer',
- fontSize: '11px',
- fontFamily: 'monospace'
- }}
- >
- {showApiKey ? <><EyeOff size={12} /> HIDE</> : <><Eye size={12} /> SHOW</>}
- </button>
- <button
+ />
+ <PrimaryBtn
+ label={loading ? 'REGENERATING...' : 'REGENERATE'}
onClick={onRegenerateKey}
disabled={loading}
- style={{
- padding: '10px 16px',
- backgroundColor: COLORS.ORANGE,
- border: `1px solid ${COLORS.ORANGE}`,
- color: COLORS.WHITE,
- cursor: loading ? 'not-allowed' : 'pointer',
- fontSize: '11px',
- fontFamily: 'monospace',
- opacity: loading ? 0.5 : 1
- }}
- >
- {loading ? 'REGENERATING...' : 'REGENERATE'}
- </button>
+ />
</div>
- <div style={{ fontSize: '10px', color: COLORS.MUTED }}>
- ⚠ Keep your API key secure. Never share it publicly.
+ <div style={{ fontSize: '9px', color: F.MUTED, fontFamily: FONT }}>
+ Keep your API key secure. Never share it publicly.
</div>
</div>
- </DataPanel>
+ </Panel>
- <DataPanel title="SECURITY STATUS" icon={<Shield size={16} />}>
+ <Panel title="SECURITY STATUS" icon={<Shield size={14} />}>
<div style={{ padding: '8px 0' }}>
- {/* Status Message */}
{statusMessage && (
- <div style={{
- padding: '8px 12px',
- backgroundColor: statusMessage.type === 'success' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)',
- border: `1px solid ${statusMessage.type === 'success' ? COLORS.GREEN : COLORS.RED}`,
- color: statusMessage.type === 'success' ? COLORS.GREEN : COLORS.RED,
- fontSize: '10px',
- marginBottom: '12px',
- fontFamily: 'monospace'
- }}>
- {statusMessage.text}
- </div>
+ <StatusBadge type={statusMessage.type} text={statusMessage.text} />
)}
-
- <SecurityRow
- label="EMAIL VERIFICATION"
- enabled={session?.user_info?.is_verified}
- />
+ <SecurityRow label="EMAIL VERIFICATION" enabled={session?.user_info?.is_verified} />
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: '10px 0',
- borderBottom: `1px solid ${COLORS.BORDER}`
+ borderBottom: `1px solid ${F.BORDER}`,
}}>
- <span style={{ color: COLORS.WHITE, fontSize: '11px' }}>MULTI-FACTOR AUTHENTICATION (EMAIL-BASED)</span>
+ <span style={{ color: F.WHITE, fontSize: '10px', fontFamily: FONT }}>MULTI-FACTOR AUTH (EMAIL)</span>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
- <span style={{
- color: session?.user_info?.mfa_enabled ? COLORS.GREEN : COLORS.RED,
- fontSize: '11px',
- fontWeight: 'bold'
- }}>
- {session?.user_info?.mfa_enabled ? 'ENABLED' : 'DISABLED'}
- </span>
- {session?.user_info?.mfa_enabled ? (
- <CheckCircle size={14} color={COLORS.GREEN} />
- ) : (
- <AlertCircle size={14} color={COLORS.RED} />
- )}
- </div>
- <button
+ <EnabledBadge enabled={session?.user_info?.mfa_enabled} />
+ <PrimaryBtn
+ label={mfaLoading ? 'PROCESSING...' : session?.user_info?.mfa_enabled ? 'DISABLE' : 'ENABLE'}
onClick={session?.user_info?.mfa_enabled ? handleDisableMFA : handleEnableMFA}
disabled={mfaLoading}
- style={{
- padding: '6px 12px',
- backgroundColor: session?.user_info?.mfa_enabled ? COLORS.RED : COLORS.GREEN,
- border: 'none',
- color: COLORS.WHITE,
- cursor: mfaLoading ? 'not-allowed' : 'pointer',
- fontSize: '10px',
- fontFamily: 'monospace',
- fontWeight: 'bold',
- opacity: mfaLoading ? 0.5 : 1
- }}
- >
- {mfaLoading ? 'PROCESSING...' : (session?.user_info?.mfa_enabled ? 'DISABLE' : 'ENABLE')}
- </button>
+ color={session?.user_info?.mfa_enabled ? F.RED : F.GREEN}
+ />
</div>
</div>
</div>
- </DataPanel>
+ </Panel>
- {/* Password Prompt Modal for Disabling MFA */}
+ {/* Password prompt for MFA disable */}
{showPasswordPrompt && (
- <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: 1000
- }}>
- <div style={{
- backgroundColor: COLORS.PANEL_BG,
- border: `2px solid ${COLORS.ORANGE}`,
- padding: '24px',
- maxWidth: '400px',
- width: '90%'
- }}>
- <div style={{
- color: COLORS.ORANGE,
- fontSize: '14px',
- fontWeight: 'bold',
+ <ConfirmModal
+ icon={<Shield size={16} />}
+ title="DISABLE MULTI-FACTOR AUTH"
+ message="Enter your password to confirm disabling MFA:"
+ confirmLabel={mfaLoading ? 'PROCESSING...' : 'CONFIRM DISABLE'}
+ confirmColor={F.RED}
+ disabled={mfaLoading}
+ onCancel={() => { setShowPasswordPrompt(false); setPassword(''); }}
+ onConfirm={confirmDisableMFA}
+ >
+ <input
+ type="password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && confirmDisableMFA()}
+ placeholder="Enter your password"
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: F.DARK_BG,
+ border: `1px solid ${F.BORDER}`,
+ borderRadius: '2px',
+ color: F.WHITE,
+ fontSize: '10px',
+ fontFamily: FONT,
marginBottom: '16px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}>
- <Shield size={18} />
- DISABLE MULTI-FACTOR AUTHENTICATION
- </div>
- <div style={{
- color: COLORS.MUTED,
- fontSize: '11px',
- marginBottom: '16px'
- }}>
- Please enter your password to confirm disabling MFA:
- </div>
- <input
- type="password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- onKeyPress={(e) => e.key === 'Enter' && confirmDisableMFA()}
- placeholder="Enter your password"
- style={{
- width: '100%',
- padding: '10px',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- fontSize: '11px',
- fontFamily: 'monospace',
- marginBottom: '16px'
- }}
- />
- <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
- <button
- onClick={() => {
- setShowPasswordPrompt(false);
- setPassword('');
- }}
- style={{
- padding: '8px 16px',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- cursor: 'pointer',
- fontSize: '11px',
- fontFamily: 'monospace'
- }}
- >
- CANCEL
- </button>
- <button
- onClick={confirmDisableMFA}
- disabled={mfaLoading}
- style={{
- padding: '8px 16px',
- backgroundColor: COLORS.RED,
- border: 'none',
- color: COLORS.WHITE,
- cursor: mfaLoading ? 'not-allowed' : 'pointer',
- fontSize: '11px',
- fontFamily: 'monospace',
- fontWeight: 'bold',
- opacity: mfaLoading ? 0.5 : 1
- }}
- >
- {mfaLoading ? 'PROCESSING...' : 'CONFIRM DISABLE'}
- </button>
- </div>
- </div>
- </div>
+ }}
+ />
+ </ConfirmModal>
)}
</div>
);
};
-// Billing Section
-const BillingSection: React.FC<{ paymentHistory: any[]; loading: boolean }> = ({ paymentHistory, loading }) => {
+// ─── Billing Section ──────────────────────────────────────────────────────────
+const BillingSection: React.FC<{
+ subscriptionData: AccountSubscriptionData | null;
+ paymentHistory: PaymentHistoryItem[];
+ loading: boolean;
+}> = ({ subscriptionData, paymentHistory, loading }) => {
+ if (loading) {
+ return <LoadingState message="Loading billing data..." />;
+ }
+
+ const daysUntilExpiry = subscriptionData?.credits_expire_at
+ ? Math.max(0, Math.ceil((new Date(subscriptionData.credits_expire_at).getTime() - Date.now()) / (1000 * 60 * 60 * 24)))
+ : null;
+
return (
- <DataPanel title="PAYMENT HISTORY" icon={<FileText size={16} />}>
- {loading ? (
- <div style={{ padding: '40px', textAlign: 'center', color: COLORS.MUTED }}>LOADING...</div>
- ) : paymentHistory.length === 0 ? (
- <div style={{ padding: '40px', textAlign: 'center', color: COLORS.MUTED }}>NO PAYMENT HISTORY</div>
- ) : (
- <table style={{ width: '100%', fontSize: '11px', fontFamily: 'monospace', borderCollapse: 'collapse' }}>
- <thead>
- <tr style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}>
- <th style={{ padding: '8px', textAlign: 'left', color: COLORS.MUTED }}>DATE</th>
- <th style={{ padding: '8px', textAlign: 'left', color: COLORS.MUTED }}>PLAN</th>
- <th style={{ padding: '8px', textAlign: 'right', color: COLORS.MUTED }}>AMOUNT</th>
- <th style={{ padding: '8px', textAlign: 'right', color: COLORS.MUTED }}>STATUS</th>
- </tr>
- </thead>
- <tbody>
- {paymentHistory.map((payment, index) => (
- <tr key={index} style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}>
- <td style={{ padding: '8px', color: COLORS.WHITE }}>
- {new Date(payment.created_at).toLocaleDateString()}
- </td>
- <td style={{ padding: '8px', color: COLORS.WHITE }}>
- {payment.plan_name || 'PURCHASE'}
- </td>
- <td style={{ padding: '8px', textAlign: 'right', color: COLORS.CYAN, fontWeight: 'bold' }}>
- ${payment.amount}
- </td>
- <td style={{
- padding: '8px',
- textAlign: 'right',
- color: payment.status === 'success' ? COLORS.GREEN : COLORS.RED,
- fontWeight: 'bold'
- }}>
- {payment.status.toUpperCase()}
- </td>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {/* Account & Plan Info */}
+ <Panel title="ACCOUNT & PLAN" icon={<Package size={14} />}>
+ {subscriptionData ? (
+ <div style={{ padding: '8px 0' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px', marginBottom: '16px' }}>
+ <StatBox label="PLAN" value={subscriptionData.account_type.toUpperCase()} isText color={F.ORANGE} />
+ <StatBox label="CREDITS" value={subscriptionData.credit_balance} color={F.CYAN} />
+ {daysUntilExpiry !== null ? (
+ <StatBox label="CREDITS EXPIRE IN" value={`${daysUntilExpiry}d`} isText color={daysUntilExpiry <= 7 ? F.RED : F.GREEN} />
+ ) : (
+ <StatBox label="SUPPORT" value={subscriptionData.support_type.toUpperCase()} isText />
+ )}
+ </div>
+ <DataRow label="SUPPORT TYPE" value={subscriptionData.support_type.toUpperCase()} />
+ <DataRow label="MEMBER SINCE" value={new Date(subscriptionData.created_at).toLocaleDateString()} />
+ {subscriptionData.credits_expire_at && (
+ <DataRow
+ label="CREDITS EXPIRE"
+ value={new Date(subscriptionData.credits_expire_at).toLocaleDateString()}
+ valueColor={daysUntilExpiry !== null && daysUntilExpiry <= 7 ? F.RED : F.CYAN}
+ />
+ )}
+ {subscriptionData.last_credit_purchase_at && (
+ <DataRow label="LAST PURCHASE" value={new Date(subscriptionData.last_credit_purchase_at).toLocaleDateString()} />
+ )}
+ </div>
+ ) : (
+ <EmptyState icon={Package} message="No account data available" />
+ )}
+ </Panel>
+
+ {/* Payment History */}
+ <Panel title="PAYMENT HISTORY" icon={<FileText size={14} />}>
+ {paymentHistory.length === 0 ? (
+ <EmptyState icon={CreditCard} message="No payment history" />
+ ) : (
+ <table style={{ width: '100%', fontSize: '10px', fontFamily: FONT, borderCollapse: 'collapse' }}>
+ <thead>
+ <tr style={{ borderBottom: `1px solid ${F.BORDER}` }}>
+ {['DATE', 'PLAN', 'GATEWAY', 'AMOUNT', 'STATUS'].map(h => (
+ <th key={h} style={{
+ padding: '8px',
+ textAlign: h === 'AMOUNT' || h === 'STATUS' ? 'right' : 'left',
+ color: F.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ }}>
+ {h}
+ </th>
+ ))}
</tr>
- ))}
- </tbody>
- </table>
- )}
- </DataPanel>
+ </thead>
+ <tbody>
+ {paymentHistory.map((p) => (
+ <tr key={p.payment_uuid} style={{ borderBottom: `1px solid ${F.BORDER}`, transition: 'all 0.2s' }}>
+ <td style={{ padding: '8px', color: F.WHITE }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Calendar size={10} color={F.GRAY} />
+ {new Date(p.created_at).toLocaleDateString()}
+ </div>
+ </td>
+ <td style={{ padding: '8px', color: F.WHITE }}>{p.plan_name || 'PURCHASE'}</td>
+ <td style={{ padding: '8px', color: F.GRAY }}>{p.payment_gateway || p.payment_method || 'N/A'}</td>
+ <td style={{ padding: '8px', textAlign: 'right', color: F.CYAN, fontWeight: 700 }}>
+ ${p.amount_usd}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>
+ <span style={{
+ padding: '2px 6px',
+ backgroundColor: p.status === 'success' || p.status === 'completed' ? `${F.GREEN}20` : p.status === 'pending' ? `${F.YELLOW}20` : `${F.RED}20`,
+ color: p.status === 'success' || p.status === 'completed' ? F.GREEN : p.status === 'pending' ? F.YELLOW : F.RED,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ }}>
+ {p.status.toUpperCase()}
+ </span>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </Panel>
+ </div>
);
};
-// Support Section - Feedback, Contact, Newsletter
+// ─── Support Section ──────────────────────────────────────────────────────────
const SupportSection: React.FC = () => {
- // Feedback form state
- const [feedbackName, setFeedbackName] = useState('');
- const [feedbackEmail, setFeedbackEmail] = useState('');
+ const { session } = useAuth();
+
+ // Feedback
const [feedbackRating, setFeedbackRating] = useState(0);
const [feedbackText, setFeedbackText] = useState('');
const [feedbackCategory, setFeedbackCategory] = useState('general');
@@ -848,7 +661,7 @@ const SupportSection: React.FC = () => {
const [feedbackSuccess, setFeedbackSuccess] = useState(false);
const [feedbackError, setFeedbackError] = useState('');
- // Contact form state
+ // Contact
const [contactName, setContactName] = useState('');
const [contactEmail, setContactEmail] = useState('');
const [contactSubject, setContactSubject] = useState('');
@@ -857,62 +670,23 @@ const SupportSection: React.FC = () => {
const [contactSuccess, setContactSuccess] = useState(false);
const [contactError, setContactError] = useState('');
- // Newsletter state
+ // Newsletter
const [newsletterEmail, setNewsletterEmail] = useState('');
const [newsletterLoading, setNewsletterLoading] = useState(false);
const [newsletterSuccess, setNewsletterSuccess] = useState(false);
const [newsletterError, setNewsletterError] = useState('');
- // Reset functions
- const resetFeedback = () => {
- setFeedbackName('');
- setFeedbackEmail('');
- setFeedbackRating(0);
- setFeedbackText('');
- setFeedbackCategory('general');
- setFeedbackSuccess(false);
- setFeedbackError('');
- };
-
- const resetContact = () => {
- setContactName('');
- setContactEmail('');
- setContactSubject('');
- setContactMessage('');
- setContactSuccess(false);
- setContactError('');
- };
-
- const resetNewsletter = () => {
- setNewsletterEmail('');
- setNewsletterSuccess(false);
- setNewsletterError('');
- };
-
- // Submit handlers
const handleFeedbackSubmit = async () => {
- if (!feedbackRating || !feedbackText.trim()) {
- setFeedbackError('Please provide a rating and feedback');
- return;
- }
-
+ if (!feedbackRating || !feedbackText.trim()) { setFeedbackError('Please provide a rating and feedback'); return; }
+ if (!session?.api_key) { setFeedbackError('Please login to submit feedback'); return; }
setFeedbackLoading(true);
setFeedbackError('');
-
- const data: FeedbackFormData = {
- name: feedbackName || undefined,
- email: feedbackEmail || undefined,
- rating: feedbackRating,
- feedback_text: feedbackText,
- category: feedbackCategory,
- };
-
- const result = await submitFeedback(data);
+ const data: FeedbackFormData = { rating: feedbackRating, feedback_text: feedbackText, category: feedbackCategory };
+ const result = await submitFeedback(data, session.api_key);
setFeedbackLoading(false);
-
if (result.success) {
setFeedbackSuccess(true);
- setTimeout(() => resetFeedback(), 3000);
+ setTimeout(() => { setFeedbackRating(0); setFeedbackText(''); setFeedbackCategory('general'); setFeedbackSuccess(false); }, 3000);
} else {
setFeedbackError(result.error || 'Failed to submit feedback');
}
@@ -920,210 +694,57 @@ const SupportSection: React.FC = () => {
const handleContactSubmit = async () => {
if (!contactName.trim() || !contactEmail.trim() || !contactSubject.trim() || !contactMessage.trim()) {
- setContactError('Please fill in all required fields');
- return;
+ setContactError('Please fill in all required fields'); return;
}
-
setContactLoading(true);
setContactError('');
-
- const data: ContactFormData = {
- name: contactName,
- email: contactEmail,
- subject: contactSubject,
- message: contactMessage,
- };
-
+ const data: ContactFormData = { name: contactName, email: contactEmail, subject: contactSubject, message: contactMessage };
const result = await submitContactForm(data);
setContactLoading(false);
-
if (result.success) {
setContactSuccess(true);
- setTimeout(() => resetContact(), 3000);
+ setTimeout(() => { setContactName(''); setContactEmail(''); setContactSubject(''); setContactMessage(''); setContactSuccess(false); }, 3000);
} else {
setContactError(result.error || 'Failed to submit contact form');
}
};
const handleNewsletterSubmit = async () => {
- if (!newsletterEmail.trim()) {
- setNewsletterError('Please enter your email');
- return;
- }
-
+ if (!newsletterEmail.trim()) { setNewsletterError('Please enter your email'); return; }
setNewsletterLoading(true);
setNewsletterError('');
-
- const result = await subscribeToNewsletter({
- email: newsletterEmail,
- source: 'profile_tab',
- });
+ const result = await subscribeToNewsletter({ email: newsletterEmail, source: 'profile_tab' });
setNewsletterLoading(false);
-
if (result.success) {
setNewsletterSuccess(true);
- setTimeout(() => resetNewsletter(), 3000);
+ setTimeout(() => { setNewsletterEmail(''); setNewsletterSuccess(false); }, 3000);
} else {
setNewsletterError(result.error || 'Failed to subscribe');
}
};
- // Input field component
- const InputField: React.FC<{
- label: string;
- value: string;
- onChange: (value: string) => void;
- placeholder?: string;
- type?: string;
- required?: boolean;
- multiline?: boolean;
- rows?: number;
- }> = ({ label, value, onChange, placeholder, type = 'text', required, multiline, rows = 4 }) => (
- <div style={{ marginBottom: '12px' }}>
- <label style={{ color: COLORS.WHITE, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- {label} {required && <span style={{ color: COLORS.RED }}>*</span>}
- </label>
- {multiline ? (
- <textarea
- value={value}
- onChange={(e) => onChange(e.target.value)}
- placeholder={placeholder}
- rows={rows}
- style={{
- width: '100%',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- padding: '8px',
- fontSize: '11px',
- fontFamily: 'Consolas, monospace',
- resize: 'vertical',
- }}
- />
- ) : (
- <input
- type={type}
- value={value}
- onChange={(e) => onChange(e.target.value)}
- placeholder={placeholder}
- style={{
- width: '100%',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- padding: '8px',
- fontSize: '11px',
- fontFamily: 'Consolas, monospace',
- }}
- />
- )}
- </div>
- );
-
- // Star rating component
- const StarRating: React.FC<{ rating: number; onChange: (rating: number) => void }> = ({ rating, onChange }) => (
- <div style={{ marginBottom: '12px' }}>
- <label style={{ color: COLORS.WHITE, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- Rating <span style={{ color: COLORS.RED }}>*</span>
- </label>
- <div style={{ display: 'flex', gap: '4px' }}>
- {[1, 2, 3, 4, 5].map((star) => (
- <button
- key={star}
- onClick={() => onChange(star)}
- style={{
- background: 'transparent',
- border: 'none',
- cursor: 'pointer',
- padding: '2px',
- }}
- >
- <Star
- size={20}
- fill={star <= rating ? COLORS.YELLOW : 'transparent'}
- color={star <= rating ? COLORS.YELLOW : COLORS.MUTED}
- />
- </button>
- ))}
- </div>
- </div>
- );
-
- // Submit button component
- const SubmitButton: React.FC<{
- onClick: () => void;
- loading: boolean;
- success: boolean;
- text: string;
- color?: string;
- }> = ({ onClick, loading, success, text, color = COLORS.ORANGE }) => (
- <button
- onClick={onClick}
- disabled={loading}
- style={{
- width: '100%',
- backgroundColor: success ? COLORS.GREEN : color,
- color: COLORS.WHITE,
- border: 'none',
- padding: '10px 16px',
- fontSize: '11px',
- fontWeight: 'bold',
- fontFamily: 'monospace',
- cursor: loading ? 'not-allowed' : 'pointer',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- gap: '8px',
- opacity: loading ? 0.7 : 1,
- }}
- >
- {loading ? (
- 'SUBMITTING...'
- ) : success ? (
- <>
- <Check size={14} /> SUCCESS!
- </>
- ) : (
- <>
- <Send size={14} /> {text}
- </>
- )}
- </button>
- );
-
return (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
- {/* Feedback Form */}
- <DataPanel title="SEND FEEDBACK" icon={<MessageSquarePlus size={16} />}>
- <InputField
- label="Name"
- value={feedbackName}
- onChange={setFeedbackName}
- placeholder="Your name (optional)"
- />
- <InputField
- label="Email"
- value={feedbackEmail}
- onChange={setFeedbackEmail}
- placeholder="Your email (optional)"
- type="email"
- />
- <StarRating rating={feedbackRating} onChange={setFeedbackRating} />
+ {/* Feedback */}
+ <Panel title="SEND FEEDBACK" icon={<MessageSquarePlus size={14} />}>
+ <div style={{ marginBottom: '12px' }}>
+ <Label text="RATING" required />
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {[1, 2, 3, 4, 5].map(s => (
+ <button key={s} onClick={() => setFeedbackRating(s)} style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: '2px' }}>
+ <Star size={18} fill={s <= feedbackRating ? F.YELLOW : 'transparent'} color={s <= feedbackRating ? F.YELLOW : F.MUTED} />
+ </button>
+ ))}
+ </div>
+ </div>
<div style={{ marginBottom: '12px' }}>
- <label style={{ color: COLORS.WHITE, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
- Category
- </label>
+ <Label text="CATEGORY" />
<select
value={feedbackCategory}
onChange={(e) => setFeedbackCategory(e.target.value)}
style={{
- width: '100%',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: COLORS.WHITE,
- padding: '8px',
- fontSize: '11px',
- fontFamily: 'Consolas, monospace',
+ width: '100%', padding: '8px 10px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`,
+ borderRadius: '2px', color: F.WHITE, fontSize: '10px', fontFamily: FONT,
}}
>
<option value="general">General</option>
@@ -1134,153 +755,67 @@ const SupportSection: React.FC = () => {
<option value="data">Data Quality</option>
</select>
</div>
- <InputField
- label="Feedback"
- value={feedbackText}
- onChange={setFeedbackText}
- placeholder="Tell us what you think..."
- multiline
- rows={3}
- required
- />
- {feedbackError && (
- <div style={{ color: COLORS.RED, fontSize: '10px', marginBottom: '12px' }}>{feedbackError}</div>
- )}
- <SubmitButton
- onClick={handleFeedbackSubmit}
- loading={feedbackLoading}
- success={feedbackSuccess}
- text="SUBMIT FEEDBACK"
- />
- </DataPanel>
-
- {/* Contact Form */}
- <DataPanel title="CONTACT US" icon={<Mail size={16} />}>
- <InputField
- label="Name"
- value={contactName}
- onChange={setContactName}
- placeholder="Your name"
- required
- />
- <InputField
- label="Email"
- value={contactEmail}
- onChange={setContactEmail}
- placeholder="[email protected]"
- type="email"
- required
- />
- <InputField
- label="Subject"
- value={contactSubject}
- onChange={setContactSubject}
- placeholder="Subject of your message"
- required
- />
- <InputField
- label="Message"
- value={contactMessage}
- onChange={setContactMessage}
- placeholder="Your message..."
- multiline
- rows={3}
- required
- />
- {contactError && (
- <div style={{ color: COLORS.RED, fontSize: '10px', marginBottom: '12px' }}>{contactError}</div>
- )}
- <SubmitButton
- onClick={handleContactSubmit}
- loading={contactLoading}
- success={contactSuccess}
- text="SEND MESSAGE"
- color="#3b82f6"
- />
- </DataPanel>
-
- {/* Newsletter Subscription */}
+ <InputField label="FEEDBACK" value={feedbackText} onChange={setFeedbackText} placeholder="Tell us what you think..." multiline rows={3} required />
+ {feedbackError && <div style={{ color: F.RED, fontSize: '9px', marginBottom: '8px' }}>{feedbackError}</div>}
+ <SubmitBtn onClick={handleFeedbackSubmit} loading={feedbackLoading} success={feedbackSuccess} text="SUBMIT FEEDBACK" />
+ </Panel>
+
+ {/* Contact */}
+ <Panel title="CONTACT US" icon={<Mail size={14} />}>
+ <InputField label="NAME" value={contactName} onChange={setContactName} placeholder="Your name" required />
+ <InputField label="EMAIL" value={contactEmail} onChange={setContactEmail} placeholder="[email protected]" type="email" required />
+ <InputField label="SUBJECT" value={contactSubject} onChange={setContactSubject} placeholder="Subject of your message" required />
+ <InputField label="MESSAGE" value={contactMessage} onChange={setContactMessage} placeholder="Your message..." multiline rows={3} required />
+ {contactError && <div style={{ color: F.RED, fontSize: '9px', marginBottom: '8px' }}>{contactError}</div>}
+ <SubmitBtn onClick={handleContactSubmit} loading={contactLoading} success={contactSuccess} text="SEND MESSAGE" color={F.BLUE} />
+ </Panel>
+
+ {/* Newsletter */}
<div style={{ gridColumn: '1 / -1' }}>
- <DataPanel title="NEWSLETTER SUBSCRIPTION" icon={<Newspaper size={16} />}>
+ <Panel title="NEWSLETTER SUBSCRIPTION" icon={<Newspaper size={14} />}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '12px', alignItems: 'flex-end' }}>
<div>
- <p style={{ color: COLORS.MUTED, fontSize: '10px', marginBottom: '12px', lineHeight: '1.5' }}>
- Stay updated with the latest features, market insights, and Fincept news delivered to your inbox.
+ <p style={{ color: F.GRAY, fontSize: '10px', marginBottom: '12px', lineHeight: '1.5' }}>
+ Stay updated with the latest features, market insights, and Fincept news.
</p>
- <InputField
- label="Email Address"
- value={newsletterEmail}
- onChange={setNewsletterEmail}
- placeholder="[email protected]"
- type="email"
- required
- />
- {newsletterError && (
- <div style={{ color: COLORS.RED, fontSize: '10px', marginBottom: '8px' }}>{newsletterError}</div>
- )}
+ <InputField label="EMAIL ADDRESS" value={newsletterEmail} onChange={setNewsletterEmail} placeholder="[email protected]" type="email" required />
+ {newsletterError && <div style={{ color: F.RED, fontSize: '9px', marginBottom: '8px' }}>{newsletterError}</div>}
</div>
<div style={{ paddingBottom: newsletterError ? '28px' : '0' }}>
- <button
+ <PrimaryBtn
+ label={newsletterLoading ? 'SUBSCRIBING...' : newsletterSuccess ? 'SUBSCRIBED!' : 'SUBSCRIBE'}
onClick={handleNewsletterSubmit}
disabled={newsletterLoading}
- style={{
- backgroundColor: newsletterSuccess ? COLORS.GREEN : '#10b981',
- color: COLORS.WHITE,
- border: 'none',
- padding: '10px 24px',
- fontSize: '11px',
- fontWeight: 'bold',
- fontFamily: 'monospace',
- cursor: newsletterLoading ? 'not-allowed' : 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- opacity: newsletterLoading ? 0.7 : 1,
- whiteSpace: 'nowrap',
- }}
- >
- {newsletterLoading ? (
- 'SUBSCRIBING...'
- ) : newsletterSuccess ? (
- <>
- <Check size={14} /> SUBSCRIBED!
- </>
- ) : (
- <>
- <Newspaper size={14} /> SUBSCRIBE
- </>
- )}
- </button>
+ color={newsletterSuccess ? F.GREEN : F.GREEN}
+ icon={newsletterSuccess ? <Check size={12} /> : <Newspaper size={12} />}
+ />
</div>
</div>
- <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '8px' }}>
+ <p style={{ color: F.MUTED, fontSize: '9px', marginTop: '8px' }}>
You can unsubscribe at any time. We respect your privacy.
</p>
- </DataPanel>
+ </Panel>
</div>
</div>
);
};
-// Helper Components
-const DataPanel: React.FC<{ title: string; icon: React.ReactNode; children: React.ReactNode }> = ({ title, icon, children }) => (
- <div style={{
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- padding: '16px'
- }}>
+// ─── Shared UI Components (FINCEPT Design System) ─────────────────────────────
+
+const Panel: React.FC<{ title: string; icon: React.ReactNode; children: React.ReactNode }> = ({ title, icon, children }) => (
+ <div style={{ backgroundColor: F.PANEL_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px' }}>
<div style={{
+ padding: '12px',
+ backgroundColor: F.HEADER_BG,
+ borderBottom: `1px solid ${F.BORDER}`,
display: 'flex',
alignItems: 'center',
gap: '8px',
- marginBottom: '12px',
- paddingBottom: '8px',
- borderBottom: `1px solid ${COLORS.BORDER}`
}}>
- <span style={{ color: COLORS.ORANGE }}>{icon}</span>
- <span style={{ color: COLORS.WHITE, fontSize: '12px', fontWeight: 'bold' }}>{title}</span>
+ <span style={{ color: F.ORANGE }}>{icon}</span>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>{title}</span>
</div>
- {children}
+ <div style={{ padding: '12px' }}>{children}</div>
</div>
);
@@ -1289,73 +824,325 @@ const DataRow: React.FC<{ label: string; value: string; valueColor?: string }> =
display: 'flex',
justifyContent: 'space-between',
padding: '6px 0',
- fontSize: '11px',
- borderBottom: `1px solid ${COLORS.BORDER}`
+ fontSize: '10px',
+ borderBottom: `1px solid ${F.BORDER}`,
+ fontFamily: FONT,
+ }}>
+ <span style={{ color: F.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px' }}>{label}</span>
+ <span style={{ color: valueColor || F.WHITE, fontWeight: 700 }}>{value}</span>
+ </div>
+);
+
+const StatBox: React.FC<{ label: string; value: number | string; isText?: boolean; color?: string }> = ({ label, value, isText, color }) => (
+ <div style={{
+ padding: '12px',
+ backgroundColor: F.HEADER_BG,
+ border: `1px solid ${F.BORDER}`,
+ borderRadius: '2px',
+ textAlign: 'center',
+ }}>
+ <div style={{ fontSize: isText ? '14px' : '24px', color: color || F.CYAN, fontWeight: 700, fontFamily: FONT }}>
+ {typeof value === 'number' ? value.toLocaleString() : value}
+ </div>
+ <div style={{ fontSize: '9px', color: F.GRAY, marginTop: '4px', fontWeight: 700, letterSpacing: '0.5px' }}>{label}</div>
+ </div>
+);
+
+const SecurityRow: React.FC<{ label: string; enabled: boolean }> = ({ label, enabled }) => (
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ padding: '10px 0',
+ borderBottom: `1px solid ${F.BORDER}`,
+ }}>
+ <span style={{ color: F.WHITE, fontSize: '10px', fontFamily: FONT }}>{label}</span>
+ <EnabledBadge enabled={enabled} />
+ </div>
+);
+
+const EnabledBadge: React.FC<{ enabled: boolean }> = ({ enabled }) => (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <span style={{
+ padding: '2px 6px',
+ backgroundColor: enabled ? `${F.GREEN}20` : `${F.RED}20`,
+ color: enabled ? F.GREEN : F.RED,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ }}>
+ {enabled ? 'ENABLED' : 'DISABLED'}
+ </span>
+ {enabled ? <CheckCircle size={12} color={F.GREEN} /> : <AlertCircle size={12} color={F.RED} />}
+ </div>
+);
+
+const Badge: React.FC<{ label: string; value: string; color: string }> = ({ label, value, color }) => (
+ <div style={{
+ padding: '6px 10px',
+ backgroundColor: F.PANEL_BG,
+ border: `1px solid ${F.BORDER}`,
+ borderRadius: '2px',
+ fontFamily: FONT,
+ fontSize: '9px',
}}>
- <span style={{ color: COLORS.MUTED }}>{label}</span>
- <span style={{ color: valueColor || COLORS.WHITE, fontWeight: 'bold' }}>{value}</span>
+ <span style={{ color: F.GRAY, fontWeight: 700, letterSpacing: '0.5px' }}>{label} </span>
+ <span style={{ color, fontWeight: 700 }}>{value}</span>
</div>
);
-const ActionButton: React.FC<{ label: string; onClick: () => void; danger?: boolean }> = ({ label, onClick, danger }) => (
+const PrimaryBtn: React.FC<{
+ label: string;
+ onClick: () => void;
+ disabled?: boolean;
+ color?: string;
+ icon?: React.ReactNode;
+}> = ({ label, onClick, disabled, color = F.ORANGE, icon }) => (
<button
onClick={onClick}
+ disabled={disabled}
style={{
- padding: '12px',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- color: danger ? COLORS.RED : COLORS.WHITE,
- cursor: 'pointer',
- fontSize: '10px',
- fontFamily: 'monospace',
- fontWeight: 'bold',
- transition: 'all 0.2s'
+ padding: '8px 16px',
+ backgroundColor: color,
+ color: F.DARK_BG,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ fontFamily: FONT,
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ opacity: disabled ? 0.5 : 1,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ transition: 'all 0.2s',
}}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = COLORS.BORDER;
+ >
+ {icon}
+ {label}
+ </button>
+);
+
+const SecondaryBtn: React.FC<{ label: string; onClick: () => void; icon?: React.ReactNode }> = ({ label, onClick, icon }) => (
+ <button
+ onClick={(e) => { e.preventDefault(); e.stopPropagation(); onClick(); }}
+ style={{
+ padding: '6px 10px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${F.BORDER}`,
+ borderRadius: '2px',
+ color: F.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ fontFamily: FONT,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ transition: 'all 0.2s',
}}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = COLORS.HEADER_BG;
+ >
+ {icon}
+ {label}
+ </button>
+);
+
+const ActionBtn: React.FC<{ label: string; onClick: () => void; danger?: boolean }> = ({ label, onClick, danger }) => (
+ <button
+ onClick={onClick}
+ style={{
+ padding: '8px 16px',
+ backgroundColor: danger ? F.RED : F.ORANGE,
+ color: F.DARK_BG,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ fontFamily: FONT,
+ cursor: 'pointer',
+ transition: 'all 0.2s',
}}
>
{label}
</button>
);
-const StatBox: React.FC<{ label: string; value: number }> = ({ label, value }) => (
+const Label: React.FC<{ text: string; required?: boolean }> = ({ text, required }) => (
+ <label style={{ color: F.GRAY, fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px', display: 'block', marginBottom: '4px' }}>
+ {text} {required && <span style={{ color: F.RED }}>*</span>}
+ </label>
+);
+
+const InputField: React.FC<{
+ label: string;
+ value: string;
+ onChange: (v: string) => void;
+ placeholder?: string;
+ type?: string;
+ required?: boolean;
+ multiline?: boolean;
+ rows?: number;
+}> = ({ label, value, onChange, placeholder, type = 'text', required, multiline, rows = 4 }) => (
+ <div style={{ marginBottom: '12px' }}>
+ <Label text={label} required={required} />
+ {multiline ? (
+ <textarea
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ rows={rows}
+ style={{
+ width: '100%', padding: '8px 10px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`,
+ borderRadius: '2px', color: F.WHITE, fontSize: '10px', fontFamily: FONT, resize: 'vertical',
+ }}
+ />
+ ) : (
+ <input
+ type={type}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ style={{
+ width: '100%', padding: '8px 10px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`,
+ borderRadius: '2px', color: F.WHITE, fontSize: '10px', fontFamily: FONT,
+ }}
+ />
+ )}
+ </div>
+);
+
+const SubmitBtn: React.FC<{
+ onClick: () => void;
+ loading: boolean;
+ success: boolean;
+ text: string;
+ color?: string;
+}> = ({ onClick, loading, success, text, color = F.ORANGE }) => (
+ <button
+ onClick={onClick}
+ disabled={loading}
+ style={{
+ width: '100%',
+ backgroundColor: success ? F.GREEN : color,
+ color: F.DARK_BG,
+ border: 'none',
+ borderRadius: '2px',
+ padding: '8px 16px',
+ fontSize: '9px',
+ fontWeight: 700,
+ fontFamily: FONT,
+ cursor: loading ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ opacity: loading ? 0.7 : 1,
+ transition: 'all 0.2s',
+ }}
+ >
+ {loading ? 'SUBMITTING...' : success ? <><Check size={12} /> SUCCESS!</> : <><Send size={12} /> {text}</>}
+ </button>
+);
+
+const StatusBadge: React.FC<{ type: 'success' | 'error'; text: string }> = ({ type, text }) => (
<div style={{
- padding: '12px',
- backgroundColor: COLORS.HEADER_BG,
- border: `1px solid ${COLORS.BORDER}`,
- textAlign: 'center'
+ padding: '8px 12px',
+ backgroundColor: type === 'success' ? `${F.GREEN}15` : `${F.RED}15`,
+ border: `1px solid ${type === 'success' ? F.GREEN : F.RED}`,
+ borderRadius: '2px',
+ color: type === 'success' ? F.GREEN : F.RED,
+ fontSize: '9px',
+ marginBottom: '12px',
+ fontFamily: FONT,
+ fontWeight: 700,
}}>
- <div style={{ fontSize: '24px', color: COLORS.CYAN, fontWeight: 'bold' }}>{value.toLocaleString()}</div>
- <div style={{ fontSize: '10px', color: COLORS.MUTED, marginTop: '4px' }}>{label}</div>
+ {text}
</div>
);
-const SecurityRow: React.FC<{ label: string; enabled: boolean }> = ({ label, enabled }) => (
+const LoadingState: React.FC<{ message: string }> = ({ message }) => (
<div style={{
display: 'flex',
- justifyContent: 'space-between',
+ flexDirection: 'column',
alignItems: 'center',
- padding: '10px 0',
- borderBottom: `1px solid ${COLORS.BORDER}`
+ justifyContent: 'center',
+ padding: '40px',
+ color: F.MUTED,
+ fontSize: '10px',
+ fontFamily: FONT,
}}>
- <span style={{ color: COLORS.WHITE, fontSize: '11px' }}>{label}</span>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
- <span style={{
- color: enabled ? COLORS.GREEN : COLORS.RED,
+ <RefreshCw size={20} style={{ marginBottom: '8px', opacity: 0.5 }} className="animate-spin" />
+ <span>{message}</span>
+ </div>
+);
+
+const EmptyState: React.FC<{ icon: React.ElementType; message: string }> = ({ icon: Icon, message }) => (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: '32px',
+ color: F.MUTED,
+ fontSize: '10px',
+ textAlign: 'center',
+ fontFamily: FONT,
+ }}>
+ <Icon size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />
+ <span>{message}</span>
+ </div>
+);
+
+const ConfirmModal: React.FC<{
+ icon: React.ReactNode;
+ title: string;
+ message: string;
+ confirmLabel: string;
+ confirmColor: string;
+ disabled?: boolean;
+ onCancel: () => void;
+ onConfirm: () => void;
+ children?: React.ReactNode;
+}> = ({ icon, title, message, confirmLabel, confirmColor, disabled, onCancel, onConfirm, children }) => (
+ <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: 1000,
+ }}>
+ <div style={{
+ backgroundColor: F.PANEL_BG,
+ border: `1px solid ${F.ORANGE}`,
+ borderRadius: '2px',
+ padding: '24px',
+ maxWidth: '400px',
+ width: '90%',
+ }}>
+ <div style={{
+ color: F.ORANGE,
fontSize: '11px',
- fontWeight: 'bold'
+ fontWeight: 700,
+ marginBottom: '16px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ fontFamily: FONT,
+ letterSpacing: '0.5px',
}}>
- {enabled ? 'ENABLED' : 'DISABLED'}
- </span>
- {enabled ? (
- <CheckCircle size={14} color={COLORS.GREEN} />
- ) : (
- <AlertCircle size={14} color={COLORS.RED} />
- )}
+ {icon}
+ {title}
+ </div>
+ <div style={{ color: F.GRAY, fontSize: '10px', marginBottom: '16px', fontFamily: FONT, lineHeight: '1.5' }}>
+ {message}
+ </div>
+ {children}
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
+ <SecondaryBtn label="CANCEL" onClick={onCancel} />
+ <PrimaryBtn label={confirmLabel} onClick={onConfirm} disabled={disabled} color={confirmColor} />
+ </div>
</div>
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/AddStockModal.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/AddStockModal.tsx
index 26ce88b2f..ddd99d719 100644
--- a/fincept-terminal-desktop/src/components/tabs/watchlist/AddStockModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/AddStockModal.tsx
@@ -1,5 +1,5 @@
import React, { useState } from 'react';
-import { FINCEPT_COLORS } from './utils';
+import { FINCEPT, FONT_FAMILY } from './utils';
interface AddStockModalProps {
onClose: () => void;
@@ -14,17 +14,14 @@ const AddStockModal: React.FC<AddStockModalProps> = ({ onClose, onAdd, existingS
const handleAdd = async () => {
const trimmedSymbol = symbol.trim().toUpperCase();
-
if (!trimmedSymbol) {
alert('Please enter a stock symbol');
return;
}
-
if (existingSymbols.includes(trimmedSymbol)) {
alert(`${trimmedSymbol} is already in this watchlist`);
return;
}
-
setLoading(true);
try {
await onAdd(trimmedSymbol, notes.trim());
@@ -37,12 +34,6 @@ const AddStockModal: React.FC<AddStockModalProps> = ({ onClose, onAdd, existingS
}
};
- const handleKeyPress = (e: React.KeyboardEvent) => {
- if (e.key === 'Enter' && !loading && symbol.trim()) {
- handleAdd();
- }
- };
-
return (
<div style={{
position: 'fixed',
@@ -50,107 +41,150 @@ const AddStockModal: React.FC<AddStockModalProps> = ({ onClose, onAdd, existingS
left: 0,
right: 0,
bottom: 0,
- backgroundColor: 'rgba(0,0,0,0.8)',
+ backgroundColor: 'rgba(0,0,0,0.85)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- zIndex: 1000
+ zIndex: 1000,
+ fontFamily: FONT_FAMILY
}}>
<div style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `2px solid ${FINCEPT_COLORS.GREEN}`,
- padding: '24px',
- minWidth: '400px'
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ minWidth: '400px',
+ maxWidth: '480px',
+ boxShadow: `0 4px 24px rgba(0,0,0,0.6), 0 0 1px ${FINCEPT.GREEN}40`
}}>
+ {/* Modal Header */}
<div style={{
- color: FINCEPT_COLORS.GREEN,
- fontSize: '14px',
- fontWeight: 'bold',
- marginBottom: '16px'
+ padding: '12px 16px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
}}>
- ADD STOCK TO WATCHLIST
+ <div style={{
+ width: '8px',
+ height: '8px',
+ backgroundColor: FINCEPT.GREEN,
+ borderRadius: '2px'
+ }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.GREEN, letterSpacing: '0.5px' }}>
+ ADD STOCK TO WATCHLIST
+ </span>
</div>
- <div style={{ marginBottom: '12px' }}>
- <label style={{
- color: FINCEPT_COLORS.GRAY,
- fontSize: '10px',
- display: 'block',
- marginBottom: '4px'
- }}>
- SYMBOL *
- </label>
- <input
- type="text"
- value={symbol}
- onChange={(e) => setSymbol(e.target.value.toUpperCase())}
- onKeyPress={handleKeyPress}
- style={{
- width: '100%',
- background: FINCEPT_COLORS.PANEL_BG,
- border: `1px solid ${FINCEPT_COLORS.GRAY}`,
- color: FINCEPT_COLORS.WHITE,
- padding: '8px',
- fontSize: '14px',
- fontFamily: 'Consolas, monospace',
- textTransform: 'uppercase',
- fontWeight: 'bold',
- letterSpacing: '1px'
- }}
- placeholder="AAPL"
- maxLength={10}
- autoFocus
- />
- <div style={{
- color: FINCEPT_COLORS.GRAY,
- fontSize: '9px',
- marginTop: '4px'
- }}>
- Enter stock ticker symbol (e.g., AAPL, MSFT, GOOGL)
+ {/* Modal Body */}
+ <div style={{ padding: '16px' }}>
+ {/* Symbol Field */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ display: 'block',
+ marginBottom: '6px'
+ }}>
+ SYMBOL *
+ </label>
+ <input
+ type="text"
+ value={symbol}
+ onChange={(e) => setSymbol(e.target.value.toUpperCase())}
+ onKeyDown={(e) => e.key === 'Enter' && !loading && symbol.trim() && handleAdd()}
+ style={{
+ width: '100%',
+ padding: '10px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '14px',
+ fontFamily: FONT_FAMILY,
+ fontWeight: 700,
+ letterSpacing: '1px',
+ textTransform: 'uppercase',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => { e.currentTarget.style.borderColor = FINCEPT.GREEN; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ placeholder="AAPL"
+ maxLength={10}
+ autoFocus
+ />
+ <div style={{
+ color: FINCEPT.MUTED,
+ fontSize: '9px',
+ marginTop: '4px'
+ }}>
+ ENTER STOCK TICKER (E.G., AAPL, MSFT, GOOGL)
+ </div>
</div>
- </div>
- <div style={{ marginBottom: '16px' }}>
- <label style={{
- color: FINCEPT_COLORS.GRAY,
- fontSize: '10px',
- display: 'block',
- marginBottom: '4px'
- }}>
- NOTES (OPTIONAL)
- </label>
- <textarea
- value={notes}
- onChange={(e) => setNotes(e.target.value)}
- style={{
- width: '100%',
- background: FINCEPT_COLORS.PANEL_BG,
- border: `1px solid ${FINCEPT_COLORS.GRAY}`,
- color: FINCEPT_COLORS.WHITE,
- padding: '8px',
- fontSize: '11px',
- fontFamily: 'Consolas, monospace',
- resize: 'vertical',
- minHeight: '60px'
- }}
- placeholder="Add notes about this stock..."
- maxLength={200}
- />
+ {/* Notes Field */}
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ display: 'block',
+ marginBottom: '6px'
+ }}>
+ NOTES (OPTIONAL)
+ </label>
+ <textarea
+ value={notes}
+ onChange={(e) => setNotes(e.target.value)}
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontFamily: FONT_FAMILY,
+ resize: 'vertical',
+ minHeight: '60px',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => { e.currentTarget.style.borderColor = FINCEPT.GREEN; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ placeholder="Add notes about this stock..."
+ maxLength={200}
+ />
+ </div>
</div>
- <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
+ {/* Modal Footer */}
+ <div style={{
+ padding: '12px 16px',
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ gap: '8px',
+ justifyContent: 'flex-end'
+ }}>
<button
onClick={onClose}
disabled={loading}
style={{
- background: FINCEPT_COLORS.GRAY,
- color: 'black',
- border: 'none',
- padding: '8px 16px',
- fontSize: '10px',
- fontWeight: 'bold',
+ padding: '6px 16px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
cursor: loading ? 'not-allowed' : 'pointer',
- opacity: loading ? 0.5 : 1
+ opacity: loading ? 0.5 : 1,
+ fontFamily: FONT_FAMILY,
+ transition: 'all 0.2s'
}}
>
CANCEL
@@ -159,13 +193,15 @@ const AddStockModal: React.FC<AddStockModalProps> = ({ onClose, onAdd, existingS
onClick={handleAdd}
disabled={loading || !symbol.trim()}
style={{
- background: (!symbol.trim() || loading) ? FINCEPT_COLORS.GRAY : FINCEPT_COLORS.GREEN,
- color: 'black',
+ padding: '6px 16px',
+ backgroundColor: (!symbol.trim() || loading) ? FINCEPT.MUTED : FINCEPT.GREEN,
+ color: FINCEPT.DARK_BG,
border: 'none',
- padding: '8px 16px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: (!symbol.trim() || loading) ? 'not-allowed' : 'pointer'
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: (!symbol.trim() || loading) ? 'not-allowed' : 'pointer',
+ fontFamily: FONT_FAMILY
}}
>
{loading ? 'ADDING...' : 'ADD STOCK'}
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/CreateWatchlistModal.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/CreateWatchlistModal.tsx
index 7a24b82cd..ff4d551d4 100644
--- a/fincept-terminal-desktop/src/components/tabs/watchlist/CreateWatchlistModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/CreateWatchlistModal.tsx
@@ -1,5 +1,5 @@
import React, { useState } from 'react';
-import { FINCEPT_COLORS, WATCHLIST_COLORS } from './utils';
+import { FINCEPT, FONT_FAMILY, WATCHLIST_COLORS } from './utils';
interface CreateWatchlistModalProps {
onClose: () => void;
@@ -20,7 +20,6 @@ const CreateWatchlistModal: React.FC<CreateWatchlistModalProps> = ({ onClose, on
alert('Please enter a watchlist name');
return;
}
-
setLoading(true);
try {
await onCreate(name.trim(), description.trim(), selectedColor);
@@ -40,126 +39,175 @@ const CreateWatchlistModal: React.FC<CreateWatchlistModalProps> = ({ onClose, on
left: 0,
right: 0,
bottom: 0,
- backgroundColor: 'rgba(0,0,0,0.8)',
+ backgroundColor: 'rgba(0,0,0,0.85)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- zIndex: 1000
+ zIndex: 1000,
+ fontFamily: FONT_FAMILY
}}>
<div style={{
- backgroundColor: FINCEPT_COLORS.DARK_BG,
- border: `2px solid ${FINCEPT_COLORS.ORANGE}`,
- padding: '24px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
minWidth: '400px',
- maxWidth: '500px'
+ maxWidth: '480px',
+ boxShadow: `0 4px 24px rgba(0,0,0,0.6), 0 0 1px ${FINCEPT.ORANGE}40`
}}>
+ {/* Modal Header */}
<div style={{
- color: FINCEPT_COLORS.ORANGE,
- fontSize: '14px',
- fontWeight: 'bold',
- marginBottom: '16px'
+ padding: '12px 16px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
}}>
- CREATE NEW WATCHLIST
+ <div style={{
+ width: '8px',
+ height: '8px',
+ backgroundColor: FINCEPT.ORANGE,
+ borderRadius: '2px'
+ }} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.ORANGE, letterSpacing: '0.5px' }}>
+ CREATE NEW WATCHLIST
+ </span>
</div>
- <div style={{ marginBottom: '12px' }}>
- <label style={{
- color: FINCEPT_COLORS.GRAY,
- fontSize: '10px',
- display: 'block',
- marginBottom: '4px'
- }}>
- WATCHLIST NAME *
- </label>
- <input
- type="text"
- value={name}
- onChange={(e) => setName(e.target.value)}
- style={{
- width: '100%',
- background: FINCEPT_COLORS.PANEL_BG,
- border: `1px solid ${FINCEPT_COLORS.GRAY}`,
- color: FINCEPT_COLORS.WHITE,
- padding: '8px',
- fontSize: '11px',
- fontFamily: 'Consolas, monospace'
- }}
- placeholder="My Watchlist"
- maxLength={50}
- />
- </div>
+ {/* Modal Body */}
+ <div style={{ padding: '16px' }}>
+ {/* Name Field */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ display: 'block',
+ marginBottom: '6px'
+ }}>
+ WATCHLIST NAME *
+ </label>
+ <input
+ type="text"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && !loading && name.trim() && handleCreate()}
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontFamily: FONT_FAMILY,
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ placeholder="My Watchlist"
+ maxLength={50}
+ autoFocus
+ />
+ </div>
- <div style={{ marginBottom: '12px' }}>
- <label style={{
- color: FINCEPT_COLORS.GRAY,
- fontSize: '10px',
- display: 'block',
- marginBottom: '4px'
- }}>
- DESCRIPTION
- </label>
- <textarea
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- style={{
- width: '100%',
- background: FINCEPT_COLORS.PANEL_BG,
- border: `1px solid ${FINCEPT_COLORS.GRAY}`,
- color: FINCEPT_COLORS.WHITE,
- padding: '8px',
- fontSize: '11px',
- fontFamily: 'Consolas, monospace',
- resize: 'vertical',
- minHeight: '60px'
- }}
- placeholder="Optional description..."
- maxLength={200}
- />
- </div>
+ {/* Description Field */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ display: 'block',
+ marginBottom: '6px'
+ }}>
+ DESCRIPTION
+ </label>
+ <textarea
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontFamily: FONT_FAMILY,
+ resize: 'vertical',
+ minHeight: '60px',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ placeholder="Optional description..."
+ maxLength={200}
+ />
+ </div>
- <div style={{ marginBottom: '16px' }}>
- <label style={{
- color: FINCEPT_COLORS.GRAY,
- fontSize: '10px',
- display: 'block',
- marginBottom: '8px'
- }}>
- COLOR
- </label>
- <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
- {WATCHLIST_COLORS.map(color => (
- <button
- key={color}
- onClick={() => setSelectedColor(color)}
- style={{
- width: '32px',
- height: '32px',
- backgroundColor: color,
- border: selectedColor === color
- ? `3px solid ${FINCEPT_COLORS.WHITE}`
- : `1px solid ${FINCEPT_COLORS.GRAY}`,
- cursor: 'pointer',
- borderRadius: '2px'
- }}
- title={color}
- />
- ))}
+ {/* Color Picker */}
+ <div style={{ marginBottom: '16px' }}>
+ <label style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.GRAY,
+ letterSpacing: '0.5px',
+ display: 'block',
+ marginBottom: '8px'
+ }}>
+ COLOR
+ </label>
+ <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
+ {WATCHLIST_COLORS.map(color => (
+ <button
+ key={color}
+ onClick={() => setSelectedColor(color)}
+ style={{
+ width: '28px',
+ height: '28px',
+ backgroundColor: color,
+ border: selectedColor === color
+ ? `2px solid ${FINCEPT.WHITE}`
+ : `1px solid ${FINCEPT.BORDER}`,
+ cursor: 'pointer',
+ borderRadius: '2px',
+ transition: 'all 0.2s',
+ boxShadow: selectedColor === color ? `0 0 6px ${color}60` : 'none'
+ }}
+ title={color}
+ />
+ ))}
+ </div>
</div>
</div>
- <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
+ {/* Modal Footer */}
+ <div style={{
+ padding: '12px 16px',
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ gap: '8px',
+ justifyContent: 'flex-end'
+ }}>
<button
onClick={onClose}
disabled={loading}
style={{
- background: FINCEPT_COLORS.GRAY,
- color: 'black',
- border: 'none',
- padding: '8px 16px',
- fontSize: '10px',
- fontWeight: 'bold',
+ padding: '6px 16px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
cursor: loading ? 'not-allowed' : 'pointer',
- opacity: loading ? 0.5 : 1
+ opacity: loading ? 0.5 : 1,
+ fontFamily: FONT_FAMILY,
+ transition: 'all 0.2s'
}}
>
CANCEL
@@ -168,13 +216,15 @@ const CreateWatchlistModal: React.FC<CreateWatchlistModalProps> = ({ onClose, on
onClick={handleCreate}
disabled={loading || !name.trim()}
style={{
- background: (!name.trim() || loading) ? FINCEPT_COLORS.GRAY : FINCEPT_COLORS.ORANGE,
- color: 'black',
+ padding: '6px 16px',
+ backgroundColor: (!name.trim() || loading) ? FINCEPT.MUTED : FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
border: 'none',
- padding: '8px 16px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: (!name.trim() || loading) ? 'not-allowed' : 'pointer'
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: (!name.trim() || loading) ? 'not-allowed' : 'pointer',
+ fontFamily: FONT_FAMILY
}}
>
{loading ? 'CREATING...' : 'CREATE'}
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/StockDetailPanel.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/StockDetailPanel.tsx
index 0312a9058..cf887c662 100644
--- a/fincept-terminal-desktop/src/components/tabs/watchlist/StockDetailPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/StockDetailPanel.tsx
@@ -1,36 +1,43 @@
import React from 'react';
import { WatchlistStockWithQuote } from '../../../services/core/watchlistService';
-import { FINCEPT_COLORS, formatCurrency, formatPercent, formatVolume, getChangeColor } from './utils';
+import { FINCEPT, FONT_FAMILY, formatCurrency, formatPercent, formatVolume, getChangeColor } from './utils';
+import { Eye, StickyNote, Clock } from 'lucide-react';
interface StockDetailPanelProps {
stock: WatchlistStockWithQuote | null;
}
-const StockDetailPanel: React.FC<StockDetailPanelProps> = ({ stock }) => {
- const { ORANGE, WHITE, GRAY, GREEN, RED, YELLOW, CYAN, PANEL_BG } = FINCEPT_COLORS;
+const StatRow: React.FC<{ label: string; value: string; color?: string }> = ({ label, value, color }) => (
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ padding: '6px 0',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>{label}</span>
+ <span style={{ fontSize: '10px', color: color || FINCEPT.CYAN, fontWeight: 700 }}>{value}</span>
+ </div>
+);
+const StockDetailPanel: React.FC<StockDetailPanelProps> = ({ stock }) => {
if (!stock) {
return (
<div style={{
- width: '320px',
- backgroundColor: PANEL_BG,
- border: `1px solid ${GRAY}`,
- padding: '12px',
+ width: '300px',
+ backgroundColor: FINCEPT.PANEL_BG,
overflow: 'auto',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
- color: GRAY,
- fontSize: '11px',
- textAlign: 'center'
+ color: FINCEPT.MUTED,
+ fontSize: '10px',
+ textAlign: 'center',
+ fontFamily: FONT_FAMILY,
+ flexShrink: 0
}}>
- <div style={{ marginBottom: '8px', fontSize: '12px' }}>
- NO STOCK SELECTED
- </div>
- <div>
- Click on a stock to view details
- </div>
+ <Eye size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />
+ <span>SELECT A STOCK TO VIEW DETAILS</span>
</div>
);
}
@@ -39,158 +46,179 @@ const StockDetailPanel: React.FC<StockDetailPanelProps> = ({ stock }) => {
return (
<div style={{
- width: '320px',
- backgroundColor: PANEL_BG,
- border: `1px solid ${GRAY}`,
- padding: '4px',
- overflow: 'auto'
+ width: '300px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ overflow: 'auto',
+ display: 'flex',
+ flexDirection: 'column',
+ fontFamily: FONT_FAMILY,
+ flexShrink: 0
}}>
+ {/* Section Header */}
<div style={{
- color: ORANGE,
- fontSize: '11px',
- fontWeight: 'bold',
- marginBottom: '4px'
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
}}>
- STOCK DETAIL: {stock.symbol}
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
+ STOCK DETAIL
+ </span>
</div>
- <div style={{ borderBottom: `1px solid ${GRAY}`, marginBottom: '8px' }}></div>
- {!quote ? (
+ {/* Symbol & Price Hero */}
+ <div style={{
+ padding: '16px 12px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
<div style={{
- padding: '16px',
- textAlign: 'center',
- color: RED,
- fontSize: '10px'
+ color: FINCEPT.CYAN,
+ fontSize: '14px',
+ fontWeight: 700,
+ letterSpacing: '1px',
+ marginBottom: '8px'
}}>
- Failed to load market data
+ {stock.symbol}
</div>
- ) : (
- <>
- {/* Price Info */}
- <div style={{ marginBottom: '12px' }}>
- <div style={{
- padding: '6px',
- backgroundColor: 'rgba(255,165,0,0.1)',
- marginBottom: '4px'
- }}>
- <div style={{
- color: GRAY,
- fontSize: '9px',
- marginBottom: '2px'
- }}>
- LAST PRICE
- </div>
- <div style={{
- color: WHITE,
- fontSize: '20px',
- fontWeight: 'bold'
- }}>
- {formatCurrency(quote.price)}
- </div>
- <div style={{
- color: getChangeColor(quote.change),
- fontSize: '12px'
- }}>
- {formatCurrency(quote.change)} ({formatPercent(quote.change_percent)})
- </div>
- </div>
- </div>
- {/* Trading Stats */}
+ {!quote ? (
<div style={{
+ padding: '12px',
+ backgroundColor: `${FINCEPT.RED}20`,
+ color: FINCEPT.RED,
fontSize: '9px',
- lineHeight: '1.5',
- marginBottom: '12px'
+ fontWeight: 700,
+ borderRadius: '2px',
+ textAlign: 'center'
}}>
+ FAILED TO LOAD MARKET DATA
+ </div>
+ ) : (
+ <>
<div style={{
- display: 'flex',
- justifyContent: 'space-between',
- marginBottom: '2px'
- }}>
- <span style={{ color: GRAY }}>Open:</span>
- <span style={{ color: WHITE }}>{formatCurrency(quote.open)}</span>
- </div>
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- marginBottom: '2px'
- }}>
- <span style={{ color: GRAY }}>Prev Close:</span>
- <span style={{ color: WHITE }}>{formatCurrency(quote.previous_close)}</span>
- </div>
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- marginBottom: '2px'
- }}>
- <span style={{ color: GRAY }}>Day High:</span>
- <span style={{ color: GREEN }}>{formatCurrency(quote.high)}</span>
- </div>
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- marginBottom: '2px'
+ color: FINCEPT.WHITE,
+ fontSize: '24px',
+ fontWeight: 700,
+ marginBottom: '4px'
}}>
- <span style={{ color: GRAY }}>Day Low:</span>
- <span style={{ color: RED }}>{formatCurrency(quote.low)}</span>
+ {formatCurrency(quote.price)}
</div>
- <div style={{
- borderTop: `1px solid ${GRAY}`,
- marginTop: '4px',
- paddingTop: '4px'
- }}>
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- marginBottom: '2px'
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{
+ padding: '2px 6px',
+ backgroundColor: `${getChangeColor(quote.change)}20`,
+ color: getChangeColor(quote.change),
+ fontSize: '10px',
+ fontWeight: 700,
+ borderRadius: '2px'
}}>
- <span style={{ color: GRAY }}>Volume:</span>
- <span style={{ color: YELLOW }}>{formatVolume(quote.volume)}</span>
- </div>
+ {formatPercent(quote.change_percent)}
+ </span>
+ <span style={{
+ color: getChangeColor(quote.change),
+ fontSize: '10px'
+ }}>
+ {formatCurrency(quote.change)}
+ </span>
</div>
- </div>
+ </>
+ )}
+ </div>
- {/* Notes Section */}
- {stock.notes && (
- <div style={{
- borderTop: `1px solid ${GRAY}`,
- paddingTop: '8px',
- marginTop: '8px'
- }}>
- <div style={{
- color: YELLOW,
- fontSize: '10px',
- fontWeight: 'bold',
- marginBottom: '4px'
- }}>
- NOTES
+ {/* Trading Stats */}
+ {quote && (
+ <div style={{ padding: '12px' }}>
+ <StatRow label="OPEN" value={formatCurrency(quote.open)} color={FINCEPT.WHITE} />
+ <StatRow label="PREV CLOSE" value={formatCurrency(quote.previous_close)} color={FINCEPT.WHITE} />
+ <StatRow label="DAY HIGH" value={formatCurrency(quote.high)} color={FINCEPT.GREEN} />
+ <StatRow label="DAY LOW" value={formatCurrency(quote.low)} color={FINCEPT.RED} />
+ <StatRow label="VOLUME" value={formatVolume(quote.volume)} color={FINCEPT.YELLOW} />
+
+ {/* Day Range Visual */}
+ {quote.high && quote.low && quote.price && (
+ <div style={{ marginTop: '12px' }}>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '6px' }}>
+ DAY RANGE
</div>
- <div style={{
- fontSize: '9px',
- color: WHITE,
- backgroundColor: 'rgba(255,255,255,0.05)',
- padding: '6px',
- borderLeft: `2px solid ${CYAN}`,
- whiteSpace: 'pre-wrap',
- wordBreak: 'break-word'
- }}>
- {stock.notes}
+ <div style={{ position: 'relative', height: '4px', backgroundColor: FINCEPT.BORDER, borderRadius: '2px' }}>
+ <div style={{
+ position: 'absolute',
+ left: '0',
+ right: '0',
+ height: '100%',
+ background: `linear-gradient(to right, ${FINCEPT.RED}, ${FINCEPT.GREEN})`,
+ borderRadius: '2px',
+ opacity: 0.5
+ }} />
+ <div style={{
+ position: 'absolute',
+ left: `${Math.min(100, Math.max(0, ((quote.price - quote.low) / (quote.high - quote.low)) * 100))}%`,
+ top: '-3px',
+ width: '10px',
+ height: '10px',
+ backgroundColor: FINCEPT.ORANGE,
+ borderRadius: '50%',
+ transform: 'translateX(-5px)',
+ boxShadow: `0 0 4px ${FINCEPT.ORANGE}80`
+ }} />
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '4px' }}>
+ <span style={{ fontSize: '8px', color: FINCEPT.RED }}>{formatCurrency(quote.low)}</span>
+ <span style={{ fontSize: '8px', color: FINCEPT.GREEN }}>{formatCurrency(quote.high)}</span>
</div>
</div>
)}
+ </div>
+ )}
- {/* Timestamp */}
+ {/* Notes Section */}
+ {stock.notes && (
+ <div style={{
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ padding: '12px'
+ }}>
<div style={{
- borderTop: `1px solid ${GRAY}`,
- paddingTop: '8px',
- marginTop: '12px',
- fontSize: '8px',
- color: GRAY,
- textAlign: 'center'
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ marginBottom: '8px'
}}>
- Last Updated: {new Date(quote.timestamp * 1000).toLocaleString()}
+ <StickyNote size={10} style={{ color: FINCEPT.YELLOW }} />
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
+ NOTES
+ </span>
</div>
- </>
+ <div style={{
+ fontSize: '10px',
+ color: FINCEPT.WHITE,
+ backgroundColor: FINCEPT.DARK_BG,
+ padding: '8px',
+ borderLeft: `2px solid ${FINCEPT.CYAN}`,
+ borderRadius: '2px',
+ whiteSpace: 'pre-wrap',
+ wordBreak: 'break-word',
+ lineHeight: '1.5'
+ }}>
+ {stock.notes}
+ </div>
+ </div>
+ )}
+
+ {/* Timestamp */}
+ {quote && (
+ <div style={{
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ padding: '8px 12px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ marginTop: 'auto'
+ }}>
+ <Clock size={10} style={{ color: FINCEPT.MUTED }} />
+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>
+ {new Date(quote.timestamp * 1000).toLocaleString()}
+ </span>
+ </div>
)}
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/StockListView.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/StockListView.tsx
index 2799559a1..d21b91f5b 100644
--- a/fincept-terminal-desktop/src/components/tabs/watchlist/StockListView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/StockListView.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import { WatchlistStockWithQuote } from '../../../services/core/watchlistService';
-import { FINCEPT_COLORS, formatCurrency, formatPercent, formatVolume, getChangeColor, SortCriteria } from './utils';
-import { Trash2 } from 'lucide-react';
+import { FINCEPT, FONT_FAMILY, formatCurrency, formatPercent, formatVolume, getChangeColor, SortCriteria } from './utils';
+import { Trash2, ArrowUpDown, Inbox } from 'lucide-react';
interface StockListViewProps {
stocks: WatchlistStockWithQuote[];
@@ -11,8 +11,16 @@ interface StockListViewProps {
onStockClick: (stock: WatchlistStockWithQuote) => void;
onRemoveStock: (symbol: string) => void;
selectedSymbol?: string;
+ isLoading?: boolean;
}
+const SORT_OPTIONS: { key: SortCriteria; label: string }[] = [
+ { key: 'TICKER', label: 'TICKER' },
+ { key: 'CHANGE', label: 'CHANGE' },
+ { key: 'VOLUME', label: 'VOLUME' },
+ { key: 'PRICE', label: 'PRICE' },
+];
+
const StockListView: React.FC<StockListViewProps> = ({
stocks,
watchlistName,
@@ -20,10 +28,9 @@ const StockListView: React.FC<StockListViewProps> = ({
onSortChange,
onStockClick,
onRemoveStock,
- selectedSymbol
+ selectedSymbol,
+ isLoading
}) => {
- const { ORANGE, WHITE, GRAY, GREEN, RED, YELLOW, CYAN, DARK_BG, PANEL_BG } = FINCEPT_COLORS;
-
const handleRemove = (e: React.MouseEvent, symbol: string) => {
e.stopPropagation();
if (confirm(`Remove ${symbol} from watchlist?`)) {
@@ -34,125 +41,113 @@ const StockListView: React.FC<StockListViewProps> = ({
return (
<div style={{
flex: 1,
- backgroundColor: PANEL_BG,
- border: `1px solid ${GRAY}`,
- padding: '4px',
- overflow: 'auto'
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${FINCEPT.BORDER}`,
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column',
+ fontFamily: FONT_FAMILY
}}>
+ {/* Section Header */}
<div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
justifyContent: 'space-between',
- alignItems: 'center',
- marginBottom: '4px'
+ alignItems: 'center'
}}>
- <div style={{
- color: ORANGE,
- fontSize: '11px',
- fontWeight: 'bold'
- }}>
- WATCHLIST: {watchlistName}
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
+ {watchlistName.toUpperCase()} ({stocks.length})
+ </span>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {SORT_OPTIONS.map(opt => (
+ <button
+ key={opt.key}
+ onClick={() => onSortChange(opt.key)}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: sortBy === opt.key ? FINCEPT.ORANGE : 'transparent',
+ color: sortBy === opt.key ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ border: sortBy === opt.key ? 'none' : `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '8px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ cursor: 'pointer',
+ fontFamily: FONT_FAMILY,
+ transition: 'all 0.2s'
+ }}
+ >
+ {opt.label}
+ </button>
+ ))}
</div>
+ </div>
+
+ {/* Table */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {/* Table Header */}
<div style={{
- display: 'flex',
+ display: 'grid',
+ gridTemplateColumns: '1fr 90px 100px 90px 36px',
gap: '4px',
- fontSize: '9px'
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ position: 'sticky',
+ top: 0,
+ zIndex: 1
}}>
- <button
- onClick={() => onSortChange('TICKER')}
- style={{
- padding: '2px 6px',
- backgroundColor: sortBy === 'TICKER' ? ORANGE : DARK_BG,
- color: sortBy === 'TICKER' ? DARK_BG : WHITE,
- border: `1px solid ${GRAY}`,
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- fontWeight: sortBy === 'TICKER' ? 'bold' : 'normal'
- }}
- >
- TICKER
- </button>
- <button
- onClick={() => onSortChange('CHANGE')}
- style={{
- padding: '2px 6px',
- backgroundColor: sortBy === 'CHANGE' ? ORANGE : DARK_BG,
- color: sortBy === 'CHANGE' ? DARK_BG : WHITE,
- border: `1px solid ${GRAY}`,
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- fontWeight: sortBy === 'CHANGE' ? 'bold' : 'normal'
- }}
- >
- CHANGE
- </button>
- <button
- onClick={() => onSortChange('VOLUME')}
- style={{
- padding: '2px 6px',
- backgroundColor: sortBy === 'VOLUME' ? ORANGE : DARK_BG,
- color: sortBy === 'VOLUME' ? DARK_BG : WHITE,
- border: `1px solid ${GRAY}`,
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- fontWeight: sortBy === 'VOLUME' ? 'bold' : 'normal'
- }}
- >
- VOLUME
- </button>
- <button
- onClick={() => onSortChange('PRICE')}
- style={{
- padding: '2px 6px',
- backgroundColor: sortBy === 'PRICE' ? ORANGE : DARK_BG,
- color: sortBy === 'PRICE' ? DARK_BG : WHITE,
- border: `1px solid ${GRAY}`,
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- fontWeight: sortBy === 'PRICE' ? 'bold' : 'normal'
- }}
- >
- PRICE
- </button>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>SYMBOL</span>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', textAlign: 'right' }}>PRICE</span>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', textAlign: 'right' }}>CHANGE</span>
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', textAlign: 'right' }}>VOLUME</span>
+ <span />
</div>
- </div>
- <div style={{ borderBottom: `1px solid ${GRAY}`, marginBottom: '8px' }}></div>
- {stocks.length === 0 ? (
- <div style={{
- padding: '32px',
- textAlign: 'center',
- color: GRAY,
- fontSize: '11px'
- }}>
- <div style={{ marginBottom: '8px', fontSize: '12px' }}>
- No stocks in this watchlist yet
- </div>
- <div>
- Click "ADD STOCK" to add stocks
+ {isLoading && stocks.length === 0 ? (
+ // Skeleton loading
+ <div style={{ padding: '8px 12px' }}>
+ {Array.from({ length: 8 }).map((_, i) => (
+ <div key={i} style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 90px 100px 90px 36px',
+ gap: '4px',
+ padding: '10px 0',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ {[0, 1, 2, 3].map(j => (
+ <div key={j} style={{
+ backgroundColor: FINCEPT.BORDER,
+ height: '10px',
+ borderRadius: '2px',
+ opacity: 0.5,
+ width: j === 0 ? '60%' : '70%',
+ marginLeft: j > 0 ? 'auto' : undefined
+ }} />
+ ))}
+ <div />
+ </div>
+ ))}
</div>
- </div>
- ) : (
- <>
- {/* Table Header */}
+ ) : stocks.length === 0 ? (
<div style={{
- display: 'grid',
- gridTemplateColumns: '100px 90px 90px 90px 50px',
- gap: '4px',
- padding: '4px',
- backgroundColor: 'rgba(255,255,255,0.05)',
- fontSize: '9px',
- fontWeight: 'bold',
- marginBottom: '2px'
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '200px',
+ color: FINCEPT.MUTED,
+ fontSize: '10px',
+ textAlign: 'center'
}}>
- <div style={{ color: GRAY }}>SYMBOL</div>
- <div style={{ color: GRAY }}>PRICE</div>
- <div style={{ color: GRAY }}>CHANGE</div>
- <div style={{ color: GRAY }}>VOLUME</div>
- <div style={{ color: GRAY }}>ACTION</div>
+ <Inbox size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />
+ <span>NO STOCKS IN THIS WATCHLIST</span>
+ <span style={{ fontSize: '9px', marginTop: '4px' }}>CLICK "ADD STOCK" TO GET STARTED</span>
</div>
-
- {/* Stock Rows */}
- {stocks.map((stock) => {
+ ) : (
+ stocks.map((stock) => {
const quote = stock.quote;
const isSelected = selectedSymbol === stock.symbol;
@@ -162,32 +157,32 @@ const StockListView: React.FC<StockListViewProps> = ({
onClick={() => onStockClick(stock)}
style={{
display: 'grid',
- gridTemplateColumns: '100px 90px 90px 90px 50px',
+ gridTemplateColumns: '1fr 90px 100px 90px 36px',
gap: '4px',
- padding: '8px 4px',
- backgroundColor: isSelected
- ? 'rgba(255,165,0,0.1)'
- : 'rgba(255,255,255,0.02)',
- borderLeft: `3px solid ${quote ? getChangeColor(quote.change) : GRAY}`,
- fontSize: '10px',
- marginBottom: '1px',
+ padding: '10px 12px',
+ backgroundColor: isSelected ? `${FINCEPT.ORANGE}15` : 'transparent',
+ borderLeft: isSelected ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
cursor: 'pointer',
- transition: 'background-color 0.2s'
+ transition: 'all 0.2s',
+ alignItems: 'center'
}}
onMouseEnter={(e) => {
if (!isSelected) {
- e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.05)';
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
}
}}
onMouseLeave={(e) => {
if (!isSelected) {
- e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.02)';
+ e.currentTarget.style.backgroundColor = 'transparent';
}
}}
>
+ {/* Symbol */}
<div style={{
- color: CYAN,
- fontWeight: 'bold',
+ color: FINCEPT.CYAN,
+ fontWeight: 700,
+ fontSize: '10px',
letterSpacing: '0.5px'
}}>
{stock.symbol}
@@ -195,62 +190,60 @@ const StockListView: React.FC<StockListViewProps> = ({
{quote ? (
<>
- <div style={{
- color: WHITE,
- fontWeight: 'bold'
- }}>
+ {/* Price */}
+ <div style={{ color: FINCEPT.WHITE, fontWeight: 700, fontSize: '10px', textAlign: 'right' }}>
{formatCurrency(quote.price)}
</div>
- <div>
- <div style={{
- color: getChangeColor(quote.change)
- }}>
- {formatCurrency(quote.change)}
+
+ {/* Change */}
+ <div style={{ textAlign: 'right' }}>
+ <div style={{ color: getChangeColor(quote.change), fontSize: '10px', fontWeight: 700 }}>
+ {formatPercent(quote.change_percent)}
</div>
- <div style={{
- color: getChangeColor(quote.change_percent),
- fontSize: '8px'
- }}>
- ({formatPercent(quote.change_percent)})
+ <div style={{ color: getChangeColor(quote.change), fontSize: '8px' }}>
+ {formatCurrency(quote.change)}
</div>
</div>
- <div style={{
- color: YELLOW
- }}>
+
+ {/* Volume */}
+ <div style={{ color: FINCEPT.YELLOW, fontSize: '10px', textAlign: 'right' }}>
{formatVolume(quote.volume)}
</div>
</>
) : (
<>
- <div style={{ color: GRAY }}>N/A</div>
- <div style={{ color: GRAY }}>N/A</div>
- <div style={{ color: GRAY }}>N/A</div>
+ <div style={{ color: FINCEPT.MUTED, fontSize: '10px', textAlign: 'right' }}>--</div>
+ <div style={{ color: FINCEPT.MUTED, fontSize: '10px', textAlign: 'right' }}>--</div>
+ <div style={{ color: FINCEPT.MUTED, fontSize: '10px', textAlign: 'right' }}>--</div>
</>
)}
- <div>
+ {/* Remove */}
+ <div style={{ display: 'flex', justifyContent: 'center' }}>
<button
onClick={(e) => handleRemove(e, stock.symbol)}
style={{
background: 'transparent',
border: 'none',
- color: RED,
+ color: FINCEPT.MUTED,
cursor: 'pointer',
- padding: '2px',
+ padding: '4px',
display: 'flex',
- alignItems: 'center',
- justifyContent: 'center'
+ borderRadius: '2px',
+ transition: 'all 0.2s'
}}
+ onMouseEnter={(e) => { e.currentTarget.style.color = FINCEPT.RED; }}
+ onMouseLeave={(e) => { e.currentTarget.style.color = FINCEPT.MUTED; }}
title={`Remove ${stock.symbol}`}
>
- <Trash2 size={14} />
+ <Trash2 size={12} />
</button>
</div>
</div>
);
- })}
- </>
- )}
+ })
+ )}
+ </div>
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistSidebar.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistSidebar.tsx
index 4a1fb3b88..5e8024184 100644
--- a/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistSidebar.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistSidebar.tsx
@@ -1,8 +1,8 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { Watchlist } from '../../../services/core/watchlistService';
-import { FINCEPT_COLORS } from './utils';
-import { Trash2, Plus } from 'lucide-react';
+import { FINCEPT, FONT_FAMILY } from './utils';
+import { Trash2, Plus, TrendingUp, TrendingDown, BarChart2, List } from 'lucide-react';
interface WatchlistSidebarProps {
watchlists: Array<Watchlist & { stock_count: number }>;
@@ -27,7 +27,6 @@ const WatchlistSidebar: React.FC<WatchlistSidebarProps> = ({
volumeLeaders
}) => {
const { t } = useTranslation('watchlist');
- const { ORANGE, WHITE, GRAY, GREEN, RED, CYAN, YELLOW, DARK_BG, PANEL_BG } = FINCEPT_COLORS;
const handleDelete = (e: React.MouseEvent, watchlistId: string) => {
e.stopPropagation();
@@ -37,101 +36,106 @@ const WatchlistSidebar: React.FC<WatchlistSidebarProps> = ({
return (
<div style={{
width: '280px',
- backgroundColor: PANEL_BG,
- border: `1px solid ${GRAY}`,
- padding: '4px',
- overflow: 'auto',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${FINCEPT.BORDER}`,
+ overflow: 'hidden',
display: 'flex',
- flexDirection: 'column'
+ flexDirection: 'column',
+ fontFamily: FONT_FAMILY,
+ flexShrink: 0
}}>
- {/* Watchlist Groups */}
+ {/* Section Header */}
<div style={{
- color: ORANGE,
- fontSize: '11px',
- fontWeight: 'bold',
- marginBottom: '4px',
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}>
- <span>{t('sidebar.groups')} ({watchlists.length})</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <List size={12} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
+ WATCHLISTS ({watchlists.length})
+ </span>
+ </div>
<button
onClick={onCreateWatchlist}
style={{
- background: 'transparent',
- border: `1px solid ${ORANGE}`,
- color: ORANGE,
- padding: '2px 4px',
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ borderRadius: '2px',
fontSize: '8px',
+ fontWeight: 700,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '2px'
}}
- title="Create new watchlist"
>
- <Plus size={10} />
- {t('sidebar.new')}
+ <Plus size={10} /> NEW
</button>
</div>
- <div style={{ borderBottom: `1px solid ${GRAY}`, marginBottom: '8px' }}></div>
- <div style={{ flex: 1, overflow: 'auto', marginBottom: '8px' }}>
+ {/* Watchlist Items */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '4px 0' }}>
{watchlists.length === 0 ? (
<div style={{
- padding: '16px',
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100px',
+ color: FINCEPT.MUTED,
+ fontSize: '10px',
textAlign: 'center',
- color: GRAY,
- fontSize: '10px'
+ padding: '16px'
}}>
- {t('sidebar.noWatchlists')}
- <br />
- {t('sidebar.clickNew')}
+ <List size={20} style={{ marginBottom: '8px', opacity: 0.5 }} />
+ <span>{t('sidebar.noWatchlists')}</span>
+ <span style={{ marginTop: '4px', fontSize: '9px' }}>{t('sidebar.clickNew')}</span>
</div>
) : (
watchlists.map((watchlist) => (
<div
key={watchlist.id}
style={{
- width: '100%',
+ padding: '10px 12px',
+ backgroundColor: selectedWatchlistId === watchlist.id ? `${FINCEPT.ORANGE}15` : 'transparent',
+ borderLeft: selectedWatchlistId === watchlist.id
+ ? `2px solid ${FINCEPT.ORANGE}`
+ : '2px solid transparent',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
display: 'flex',
justifyContent: 'space-between',
- alignItems: 'center',
- padding: '8px',
- marginBottom: '3px',
- backgroundColor: selectedWatchlistId === watchlist.id
- ? 'rgba(255,165,0,0.1)'
- : 'rgba(255,255,255,0.02)',
- border: `1px solid ${selectedWatchlistId === watchlist.id ? ORANGE : 'transparent'}`,
- cursor: 'pointer',
- fontSize: '10px',
- fontFamily: 'Consolas, monospace',
- transition: 'all 0.2s'
+ alignItems: 'center'
}}
onClick={() => onSelectWatchlist(watchlist.id)}
onMouseEnter={(e) => {
if (selectedWatchlistId !== watchlist.id) {
- e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.05)';
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
}
}}
onMouseLeave={(e) => {
if (selectedWatchlistId !== watchlist.id) {
- e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.02)';
+ e.currentTarget.style.backgroundColor = 'transparent';
}
}}
>
- <div style={{ flex: 1 }}>
+ <div>
<div style={{
- color: watchlist.color,
- fontWeight: 'bold',
- marginBottom: '2px'
+ color: selectedWatchlistId === watchlist.id ? FINCEPT.WHITE : watchlist.color,
+ fontWeight: 700,
+ fontSize: '10px',
+ marginBottom: '2px',
+ letterSpacing: '0.3px'
}}>
{watchlist.name}
</div>
- <div style={{
- color: CYAN,
- fontSize: '9px'
- }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>
{watchlist.stock_count} {t('sidebar.stocks')}
</div>
</div>
@@ -140,11 +144,15 @@ const WatchlistSidebar: React.FC<WatchlistSidebarProps> = ({
style={{
background: 'transparent',
border: 'none',
- color: RED,
+ color: FINCEPT.MUTED,
cursor: 'pointer',
- padding: '2px',
- display: 'flex'
+ padding: '4px',
+ display: 'flex',
+ borderRadius: '2px',
+ transition: 'all 0.2s'
}}
+ onMouseEnter={(e) => { e.currentTarget.style.color = FINCEPT.RED; }}
+ onMouseLeave={(e) => { e.currentTarget.style.color = FINCEPT.MUTED; }}
title={`Delete ${watchlist.name}`}
>
<Trash2 size={12} />
@@ -154,125 +162,104 @@ const WatchlistSidebar: React.FC<WatchlistSidebarProps> = ({
)}
</div>
- {/* Market Movers */}
+ {/* Market Movers Section */}
{marketMovers && marketMovers.gainers.length > 0 && (
- <div style={{
- borderTop: `1px solid ${GRAY}`,
- marginTop: '8px',
- paddingTop: '8px',
- marginBottom: '8px'
- }}>
+ <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}` }}>
<div style={{
- color: YELLOW,
- fontSize: '10px',
- fontWeight: 'bold',
- marginBottom: '4px'
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
}}>
- {t('sidebar.marketMovers')}
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
+ MARKET MOVERS
+ </span>
</div>
- {marketMovers.gainers.slice(0, 3).map((item, index) => (
- <div
- key={`gainer-${index}`}
- style={{
- display: 'flex',
- justifyContent: 'space-between',
- padding: '3px',
- marginBottom: '2px',
- backgroundColor: 'rgba(255,255,255,0.02)',
- fontSize: '9px'
- }}
- >
- <div>
- <span style={{ color: CYAN }}>{item.symbol}</span>
- <span style={{
- color: GRAY,
- marginLeft: '4px',
- fontSize: '8px'
- }}>
- [{t('sidebar.gainer')}]
+ <div style={{ padding: '4px 8px' }}>
+ {marketMovers.gainers.slice(0, 3).map((item, index) => (
+ <div
+ key={`gainer-${index}`}
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ padding: '4px 4px',
+ fontSize: '9px'
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <TrendingUp size={10} style={{ color: FINCEPT.GREEN }} />
+ <span style={{ color: FINCEPT.CYAN }}>{item.symbol}</span>
+ </div>
+ <span style={{ color: FINCEPT.GREEN, fontWeight: 700 }}>
+ +{item.quote?.change_percent.toFixed(2)}%
</span>
</div>
- <span style={{
- color: GREEN,
- fontWeight: 'bold'
- }}>
- +{item.quote?.change_percent.toFixed(2)}%
- </span>
- </div>
- ))}
- {marketMovers.losers.slice(0, 2).map((item, index) => (
- <div
- key={`loser-${index}`}
- style={{
- display: 'flex',
- justifyContent: 'space-between',
- padding: '3px',
- marginBottom: '2px',
- backgroundColor: 'rgba(255,255,255,0.02)',
- fontSize: '9px'
- }}
- >
- <div>
- <span style={{ color: CYAN }}>{item.symbol}</span>
- <span style={{
- color: GRAY,
- marginLeft: '4px',
- fontSize: '8px'
- }}>
- [{t('sidebar.loser')}]
+ ))}
+ {marketMovers.losers.slice(0, 2).map((item, index) => (
+ <div
+ key={`loser-${index}`}
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ padding: '4px 4px',
+ fontSize: '9px'
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <TrendingDown size={10} style={{ color: FINCEPT.RED }} />
+ <span style={{ color: FINCEPT.CYAN }}>{item.symbol}</span>
+ </div>
+ <span style={{ color: FINCEPT.RED, fontWeight: 700 }}>
+ {item.quote?.change_percent.toFixed(2)}%
</span>
</div>
- <span style={{
- color: RED,
- fontWeight: 'bold'
- }}>
- {item.quote?.change_percent.toFixed(2)}%
- </span>
- </div>
- ))}
+ ))}
+ </div>
</div>
)}
- {/* Volume Leaders */}
+ {/* Volume Leaders Section */}
{volumeLeaders && volumeLeaders.length > 0 && (
- <div style={{
- borderTop: `1px solid ${GRAY}`,
- marginTop: '8px',
- paddingTop: '8px'
- }}>
+ <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}` }}>
<div style={{
- color: YELLOW,
- fontSize: '10px',
- fontWeight: 'bold',
- marginBottom: '4px'
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
}}>
- {t('sidebar.volumeLeaders')}
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
+ VOLUME LEADERS
+ </span>
</div>
- {volumeLeaders.slice(0, 4).map((item, index) => {
- const volume = item.quote?.volume || 0;
- const volumeStr = volume >= 1_000_000
- ? `${(volume / 1_000_000).toFixed(1)}M`
- : volume >= 1_000
- ? `${(volume / 1_000).toFixed(1)}K`
- : volume.toString();
+ <div style={{ padding: '4px 8px 8px' }}>
+ {volumeLeaders.slice(0, 4).map((item, index) => {
+ const volume = item.quote?.volume || 0;
+ const volumeStr = volume >= 1_000_000
+ ? `${(volume / 1_000_000).toFixed(1)}M`
+ : volume >= 1_000
+ ? `${(volume / 1_000).toFixed(1)}K`
+ : volume.toString();
- return (
- <div
- key={`volume-${index}`}
- style={{
- display: 'flex',
- justifyContent: 'space-between',
- padding: '3px',
- marginBottom: '2px',
- backgroundColor: 'rgba(255,255,255,0.02)',
- fontSize: '9px'
- }}
- >
- <span style={{ color: CYAN }}>{item.symbol}</span>
- <span style={{ color: WHITE }}>{volumeStr}</span>
- </div>
- );
- })}
+ return (
+ <div
+ key={`volume-${index}`}
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ padding: '4px 4px',
+ fontSize: '9px'
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <BarChart2 size={10} style={{ color: FINCEPT.YELLOW }} />
+ <span style={{ color: FINCEPT.CYAN }}>{item.symbol}</span>
+ </div>
+ <span style={{ color: FINCEPT.WHITE, fontWeight: 700 }}>{volumeStr}</span>
+ </div>
+ );
+ })}
+ </div>
</div>
)}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistTab.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistTab.tsx
index d75cb3a00..80415b7fc 100644
--- a/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistTab.tsx
@@ -1,5 +1,5 @@
import React, { useState, useEffect, useCallback } from 'react';
-import { RefreshCw, Download, WifiOff } from 'lucide-react';
+import { RefreshCw, Download, WifiOff, Plus, BarChart3 } from 'lucide-react';
import {
watchlistService,
Watchlist,
@@ -9,40 +9,26 @@ import { contextRecorderService } from '@/services/data-sources/contextRecorderS
import { useWatchlistStocks, useMarketMovers, useVolumeLeaders } from '@/hooks/useWatchlist';
import WatchlistSidebar from './WatchlistSidebar';
import StockListView from './StockListView';
-import { TabFooter } from '@/components/common/TabFooter';
import StockDetailPanel from './StockDetailPanel';
import CreateWatchlistModal from './CreateWatchlistModal';
import AddStockModal from './AddStockModal';
import RecordingControlPanel from '@/components/common/RecordingControlPanel';
-import { getFinceptColors, SortCriteria, sortStocks, getNextWatchlistColor } from './utils';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { FINCEPT, FONT_FAMILY, SortCriteria, sortStocks, getNextWatchlistColor } from './utils';
import { useTranslation } from 'react-i18next';
const WatchlistTab: React.FC = () => {
- const { colors: themeColors } = useTerminalTheme();
const { t } = useTranslation('watchlist');
- const FINCEPT_COLORS = getFinceptColors();
const [currentTime, setCurrentTime] = useState(new Date());
const [watchlists, setWatchlists] = useState<Array<Watchlist & { stock_count: number }>>([]);
const [selectedWatchlist, setSelectedWatchlist] = useState<(Watchlist & { stock_count: number }) | null>(null);
const [selectedStock, setSelectedStock] = useState<WatchlistStockWithQuote | null>(null);
const [loading, setLoading] = useState(false);
-
- // Sort and view states
const [sortBy, setSortBy] = useState<SortCriteria>('CHANGE');
-
- // Modal states
const [showCreateWatchlist, setShowCreateWatchlist] = useState(false);
const [showAddStock, setShowAddStock] = useState(false);
-
- // Recording state
const [isRecording, setIsRecording] = useState(false);
- // ============================================================================
- // Cached data fetching using unified cache hooks
- // ============================================================================
-
- // Fetch stocks for selected watchlist (cached, auto-refresh every 10 min)
+ // Cached data fetching
const {
data: stocks,
isLoading: stocksLoading,
@@ -53,10 +39,9 @@ const WatchlistTab: React.FC = () => {
invalidate: invalidateStocks
} = useWatchlistStocks(selectedWatchlist?.id || null, {
enabled: !!selectedWatchlist,
- refetchInterval: 10 * 60 * 1000 // 10 minutes
+ refetchInterval: 10 * 60 * 1000
});
- // Fetch market movers (cached)
const {
data: marketMovers,
refresh: refreshMovers
@@ -65,7 +50,6 @@ const WatchlistTab: React.FC = () => {
refetchInterval: 10 * 60 * 1000
});
- // Fetch volume leaders (cached)
const {
data: volumeLeaders,
refresh: refreshVolume
@@ -74,19 +58,12 @@ const WatchlistTab: React.FC = () => {
refetchInterval: 10 * 60 * 1000
});
- // Combined refresh function
const refreshWatchlistData = useCallback(async () => {
- await Promise.all([
- refreshStocks(),
- refreshMovers(),
- refreshVolume()
- ]);
+ await Promise.all([refreshStocks(), refreshMovers(), refreshVolume()]);
}, [refreshStocks, refreshMovers, refreshVolume]);
- // Stocks array with fallback to empty
const stocksList = stocks || [];
- // Function to record current watchlist data
const recordCurrentData = async () => {
if (selectedWatchlist && stocksList.length > 0) {
try {
@@ -100,7 +77,6 @@ const WatchlistTab: React.FC = () => {
})),
timestamp: new Date().toISOString()
};
- console.log('[WatchlistTab] Recording current data:', recordData);
await contextRecorderService.recordApiResponse(
'Watchlist',
'watchlist-stocks',
@@ -108,15 +84,12 @@ const WatchlistTab: React.FC = () => {
`Watchlist (Snapshot): ${selectedWatchlist.name} - ${new Date().toLocaleString()}`,
['watchlist', 'stocks', 'snapshot']
);
- console.log('[WatchlistTab] Current data recorded successfully');
} catch (error) {
console.error('[WatchlistTab] Failed to record current data:', error);
}
}
};
- const { ORANGE, WHITE, RED, GREEN, GRAY, DARK_BG, PANEL_BG, CYAN, YELLOW } = FINCEPT_COLORS;
-
// Initialize service and load watchlists
useEffect(() => {
const initService = async () => {
@@ -133,21 +106,15 @@ const WatchlistTab: React.FC = () => {
initService();
}, []);
- // Update time
useEffect(() => {
- const timer = setInterval(() => {
- setCurrentTime(new Date());
- }, 1000);
+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);
return () => clearInterval(timer);
}, []);
- // Load watchlists
const loadWatchlists = async () => {
try {
const result = await watchlistService.getWatchlistsWithCounts();
setWatchlists(result);
-
- // Select first watchlist if none selected
if (result.length > 0 && !selectedWatchlist) {
setSelectedWatchlist(result[0]);
}
@@ -156,17 +123,13 @@ const WatchlistTab: React.FC = () => {
}
};
- // Update selected stock when stocks list changes
useEffect(() => {
if (selectedStock && stocksList.length > 0) {
const updated = stocksList.find(s => s.symbol === selectedStock.symbol);
- if (updated) {
- setSelectedStock(updated);
- }
+ if (updated) setSelectedStock(updated);
}
}, [stocksList]);
- // Record data when recording is active and stocks change
useEffect(() => {
if (isRecording && selectedWatchlist && stocksList.length > 0) {
const recordData = {
@@ -191,38 +154,28 @@ const WatchlistTab: React.FC = () => {
}
}, [stocksList, isRecording, selectedWatchlist]);
- // Create new watchlist
const handleCreateWatchlist = async (name: string, description: string, color: string) => {
try {
const newWatchlist = await watchlistService.createWatchlist(name, description, color);
await loadWatchlists();
-
- // Find and select the newly created watchlist
const updated = await watchlistService.getWatchlistsWithCounts();
const created = updated.find(w => w.id === newWatchlist.id);
- if (created) {
- setSelectedWatchlist(created);
- }
+ if (created) setSelectedWatchlist(created);
} catch (error) {
console.error('[WatchlistTab] Error creating watchlist:', error);
throw error;
}
};
- // Delete watchlist
const handleDeleteWatchlist = async (watchlistId: string) => {
- if (!confirm('Are you sure you want to delete this watchlist? This action cannot be undone.')) {
- return;
- }
-
+ if (!confirm('Are you sure you want to delete this watchlist? This action cannot be undone.')) return;
try {
await watchlistService.deleteWatchlist(watchlistId);
await loadWatchlists();
-
if (selectedWatchlist?.id === watchlistId) {
setSelectedWatchlist(watchlists.length > 1 ? watchlists[0] : null);
setSelectedStock(null);
- await invalidateStocks(); // Clear cached stocks for deleted watchlist
+ await invalidateStocks();
}
} catch (error) {
console.error('[WatchlistTab] Error deleting watchlist:', error);
@@ -230,44 +183,35 @@ const WatchlistTab: React.FC = () => {
}
};
- // Add stock to watchlist
const handleAddStock = async (symbol: string, notes: string) => {
if (!selectedWatchlist) return;
-
try {
await watchlistService.addStock(selectedWatchlist.id, symbol, notes);
- await invalidateStocks(); // Invalidate cache to refetch
+ await invalidateStocks();
await refreshStocks();
- await loadWatchlists(); // Update counts
+ await loadWatchlists();
} catch (error) {
console.error('[WatchlistTab] Error adding stock:', error);
throw error;
}
};
- // Remove stock from watchlist
const handleRemoveStock = async (symbol: string) => {
if (!selectedWatchlist) return;
-
try {
await watchlistService.removeStock(selectedWatchlist.id, symbol);
- await invalidateStocks(); // Invalidate cache to refetch
+ await invalidateStocks();
await refreshStocks();
- await loadWatchlists(); // Update counts
-
- if (selectedStock?.symbol === symbol) {
- setSelectedStock(null);
- }
+ await loadWatchlists();
+ if (selectedStock?.symbol === symbol) setSelectedStock(null);
} catch (error) {
console.error('[WatchlistTab] Error removing stock:', error);
alert('Failed to remove stock');
}
};
- // Export watchlist to CSV
const handleExportCSV = async () => {
if (!selectedWatchlist) return;
-
try {
const csv = await watchlistService.exportWatchlistCSV(selectedWatchlist.id);
const blob = new Blob([csv], { type: 'text/csv' });
@@ -285,184 +229,227 @@ const WatchlistTab: React.FC = () => {
}
};
- // Get sorted stocks
const sortedStocks = sortStocks(stocksList, sortBy);
-
- // Derive refreshing state from cache
const refreshing = stocksRefreshing;
return (
<div style={{
height: '100%',
- backgroundColor: DARK_BG,
- color: WHITE,
- fontFamily: 'Consolas, monospace',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ fontFamily: FONT_FAMILY,
overflow: 'hidden',
display: 'flex',
flexDirection: 'column'
}}>
<style>{`
- *::-webkit-scrollbar { width: 8px; height: 8px; }
- *::-webkit-scrollbar-track { background: #1a1a1a; }
- *::-webkit-scrollbar-thumb { background: #404040; border-radius: 4px; }
- *::-webkit-scrollbar-thumb:hover { background: #525252; }
+ *::-webkit-scrollbar { width: 6px; height: 6px; }
+ *::-webkit-scrollbar-track { background: ${FINCEPT.DARK_BG}; }
+ *::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; border-radius: 3px; }
+ *::-webkit-scrollbar-thumb:hover { background: ${FINCEPT.MUTED}; }
+ @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
+ .wl-spin { animation: spin 1s linear infinite; }
`}</style>
- {/* Header Bar */}
+ {/* Top Navigation Bar */}
<div style={{
- backgroundColor: PANEL_BG,
- borderBottom: `1px solid ${GRAY}`,
- padding: '8px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,
+ padding: '8px 16px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`,
flexShrink: 0
}}>
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: ORANGE, fontWeight: 'bold', fontSize: '14px' }}>
- FINCEPT {t('title')} MONITOR
- </span>
- <span style={{ color: WHITE }}>|</span>
- <span style={{ color: refreshing ? ORANGE : GREEN, fontSize: '10px' }}>
- ● {refreshing ? t('header.updating') : t('header.live')}
- </span>
- <span style={{ color: WHITE }}>|</span>
- <span style={{ color: CYAN, fontSize: '11px' }}>
- {currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC
- </span>
- </div>
-
- <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
- <RecordingControlPanel
- tabName="Watchlist"
- onRecordingChange={setIsRecording}
- onRecordingStart={recordCurrentData}
- />
- <button
- onClick={refreshWatchlistData}
- disabled={!selectedWatchlist || refreshing}
- style={{
- background: selectedWatchlist && !refreshing ? GREEN : GRAY,
- color: 'black',
- border: 'none',
- padding: '4px 12px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: selectedWatchlist && !refreshing ? 'pointer' : 'not-allowed',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- opacity: selectedWatchlist && !refreshing ? 1 : 0.5
- }}
- >
- <RefreshCw size={12} />
- {t('header.export').replace('EXPORT', 'REFRESH')}
- </button>
- <button
- onClick={handleExportCSV}
- disabled={!selectedWatchlist}
- style={{
- background: selectedWatchlist ? CYAN : GRAY,
- color: 'black',
- border: 'none',
- padding: '4px 12px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: selectedWatchlist ? 'pointer' : 'not-allowed',
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <BarChart3 size={16} style={{ color: FINCEPT.ORANGE }} />
+ <span style={{ color: FINCEPT.ORANGE, fontWeight: 700, fontSize: '12px', letterSpacing: '0.5px' }}>
+ WATCHLIST MONITOR
+ </span>
+ <span style={{ color: FINCEPT.BORDER }}>|</span>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: refreshing ? FINCEPT.ORANGE : FINCEPT.GREEN,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <span style={{
+ width: '6px',
+ height: '6px',
+ borderRadius: '50%',
+ backgroundColor: refreshing ? FINCEPT.ORANGE : FINCEPT.GREEN,
+ display: 'inline-block'
+ }} />
+ {refreshing ? 'UPDATING' : 'LIVE'}
+ </span>
+ <span style={{ color: FINCEPT.BORDER }}>|</span>
+ <span style={{ color: FINCEPT.CYAN, fontSize: '10px' }}>
+ {currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC
+ </span>
+ {isOffline && (
+ <>
+ <span style={{ color: FINCEPT.BORDER }}>|</span>
+ <span style={{
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.ORANGE}20`,
+ color: FINCEPT.ORANGE,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
display: 'flex',
alignItems: 'center',
- gap: '4px',
- opacity: selectedWatchlist ? 1 : 0.5
- }}
- >
- <Download size={12} />
- {t('header.export')} CSV
- </button>
- </div>
+ gap: '4px'
+ }}>
+ <WifiOff size={10} /> OFFLINE
+ </span>
+ </>
+ )}
+ {isStale && !isOffline && (
+ <>
+ <span style={{ color: FINCEPT.BORDER }}>|</span>
+ <span style={{
+ padding: '2px 6px',
+ backgroundColor: `${FINCEPT.YELLOW}20`,
+ color: FINCEPT.YELLOW,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px'
+ }}>
+ STALE
+ </span>
+ </>
+ )}
</div>
- {/* Summary Bar */}
- {selectedWatchlist && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '11px', marginTop: '8px' }}>
- <span style={{ color: GRAY }}>{t('title')}:</span>
- <span style={{ color: YELLOW, fontWeight: 'bold' }}>
- {selectedWatchlist.name}
- </span>
- <span style={{ color: WHITE }}>|</span>
- <span style={{ color: GRAY }}>{t('list.symbols')}:</span>
- <span style={{ color: CYAN }}>{stocksList.length}</span>
- {isOffline && (
- <>
- <span style={{ color: WHITE }}>|</span>
- <span style={{ color: ORANGE, display: 'flex', alignItems: 'center', gap: '4px' }}>
- <WifiOff size={12} /> OFFLINE
- </span>
- </>
- )}
- {isStale && !isOffline && (
- <>
- <span style={{ color: WHITE }}>|</span>
- <span style={{ color: YELLOW }}>STALE DATA</span>
- </>
- )}
- </div>
- )}
- </div>
-
- {/* Function Keys Bar */}
- <div style={{
- backgroundColor: PANEL_BG,
- borderBottom: `1px solid ${GRAY}`,
- padding: '4px 8px',
- flexShrink: 0
- }}>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: '4px' }}>
- {[
- { key: "F1", label: "ADD STOCK", action: () => setShowAddStock(true) },
- { key: "F2", label: "REFRESH", action: refreshWatchlistData },
- { key: "F3", label: "EXPORT", action: handleExportCSV },
- { key: "F4", label: "SORT", action: () => setSortBy('CHANGE') },
- { key: "F5", label: "CREATE", action: () => setShowCreateWatchlist(true) },
- { key: "F6", label: "TICKER", action: () => setSortBy('TICKER') },
- { key: "F7", label: "PRICE", action: () => setSortBy('PRICE') },
- { key: "F8", label: "VOLUME", action: () => setSortBy('VOLUME') },
- { key: "F9", label: "UNUSED", action: () => { } },
- { key: "F10", label: "UNUSED", action: () => { } },
- { key: "F11", label: "UNUSED", action: () => { } },
- { key: "F12", label: "HELP", action: () => { } }
- ].map(item => (
+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
+ <RecordingControlPanel
+ tabName="Watchlist"
+ onRecordingChange={setIsRecording}
+ onRecordingStart={recordCurrentData}
+ />
+ {selectedWatchlist && (
<button
- key={item.key}
- onClick={() => {
- if (item.label === "ADD STOCK" || item.label === "CREATE") {
- item.action();
- } else if (selectedWatchlist) {
- item.action();
- }
- }}
- disabled={!selectedWatchlist && item.label !== "CREATE"}
+ onClick={() => setShowAddStock(true)}
style={{
- backgroundColor: DARK_BG,
- border: `1px solid ${GRAY}`,
- color: WHITE,
- padding: '4px 6px',
+ padding: '6px 10px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
fontSize: '9px',
- cursor: (selectedWatchlist || item.label === "CREATE") ? 'pointer' : 'not-allowed',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: 'pointer',
display: 'flex',
alignItems: 'center',
- justifyContent: 'center',
- gap: '2px',
- opacity: (!selectedWatchlist && item.label !== "CREATE") ? 0.5 : 1
+ gap: '4px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.color = FINCEPT.WHITE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.color = FINCEPT.GRAY;
}}
>
- <span style={{ color: YELLOW }}>{item.key}:</span>
- <span>{item.label}</span>
+ <Plus size={10} /> ADD STOCK
</button>
- ))}
+ )}
+ <button
+ onClick={refreshWatchlistData}
+ disabled={!selectedWatchlist || refreshing}
+ style={{
+ padding: '6px 10px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: selectedWatchlist && !refreshing ? 'pointer' : 'not-allowed',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ opacity: selectedWatchlist && !refreshing ? 1 : 0.5,
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (selectedWatchlist && !refreshing) {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.color = FINCEPT.WHITE;
+ }
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.color = FINCEPT.GRAY;
+ }}
+ >
+ <RefreshCw size={10} className={refreshing ? 'wl-spin' : ''} /> REFRESH
+ </button>
+ <button
+ onClick={handleExportCSV}
+ disabled={!selectedWatchlist}
+ style={{
+ padding: '6px 10px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ cursor: selectedWatchlist ? 'pointer' : 'not-allowed',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ opacity: selectedWatchlist ? 1 : 0.5,
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (selectedWatchlist) {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.color = FINCEPT.WHITE;
+ }
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.color = FINCEPT.GRAY;
+ }}
+ >
+ <Download size={10} /> EXPORT
+ </button>
</div>
</div>
- {/* Main Content */}
+ {/* Summary Info Bar */}
+ {selectedWatchlist && (
+ <div style={{
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ padding: '6px 16px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '16px',
+ fontSize: '9px',
+ flexShrink: 0
+ }}>
+ <span style={{ color: FINCEPT.GRAY, fontWeight: 700, letterSpacing: '0.5px' }}>ACTIVE LIST</span>
+ <span style={{ color: FINCEPT.YELLOW, fontWeight: 700 }}>{selectedWatchlist.name.toUpperCase()}</span>
+ <span style={{ color: FINCEPT.BORDER }}>|</span>
+ <span style={{ color: FINCEPT.GRAY, fontWeight: 700, letterSpacing: '0.5px' }}>SYMBOLS</span>
+ <span style={{ color: FINCEPT.CYAN }}>{stocksList.length}</span>
+ <span style={{ color: FINCEPT.BORDER }}>|</span>
+ <span style={{ color: FINCEPT.GRAY, fontWeight: 700, letterSpacing: '0.5px' }}>SORT</span>
+ <span style={{ color: FINCEPT.CYAN }}>{sortBy}</span>
+ </div>
+ )}
+
+ {/* Main Three-Panel Content */}
<div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
- {/* Left Sidebar - Watchlist Groups */}
+ {/* Left Panel - Sidebar */}
<WatchlistSidebar
watchlists={watchlists}
selectedWatchlistId={selectedWatchlist?.id || null}
@@ -484,11 +471,12 @@ const WatchlistTab: React.FC = () => {
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
- gap: '16px'
+ color: FINCEPT.MUTED,
+ fontSize: '10px',
+ textAlign: 'center'
}}>
- <div style={{ color: GRAY, fontSize: '14px' }}>
- {t('emptyState.selectWatchlist')}
- </div>
+ <BarChart3 size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />
+ <span>SELECT A WATCHLIST TO VIEW</span>
</div>
) : (
<StockListView
@@ -499,6 +487,7 @@ const WatchlistTab: React.FC = () => {
onStockClick={setSelectedStock}
onRemoveStock={handleRemoveStock}
selectedSymbol={selectedStock?.symbol}
+ isLoading={stocksLoading}
/>
)}
@@ -508,25 +497,27 @@ const WatchlistTab: React.FC = () => {
{/* Status Bar */}
<div style={{
- borderTop: `1px solid ${GRAY}`,
- backgroundColor: PANEL_BG,
- padding: '4px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ padding: '4px 16px',
fontSize: '9px',
- color: GRAY,
+ color: FINCEPT.GRAY,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
flexShrink: 0
}}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <span>Fincept Watchlist Monitor v2.0.0 | Real-time tracking with yfinance integration | Unified Cache</span>
- {selectedWatchlist && (
- <span>
- Watchlist: {selectedWatchlist.name} | Stocks: {stocksList.length} |
- Status: <span style={{ color: isOffline ? ORANGE : GREEN }}>{isOffline ? 'OFFLINE' : 'CONNECTED'}</span>
- </span>
- )}
+ <span>FINCEPT WATCHLIST v2.0 | REAL-TIME TRACKING | UNIFIED CACHE</span>
+ <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
+ <span>LISTS: <span style={{ color: FINCEPT.CYAN }}>{watchlists.length}</span></span>
+ <span>STOCKS: <span style={{ color: FINCEPT.CYAN }}>{stocksList.length}</span></span>
+ <span>STATUS: <span style={{ color: isOffline ? FINCEPT.ORANGE : FINCEPT.GREEN }}>
+ {loading || stocksLoading ? 'LOADING' : isOffline ? 'OFFLINE' : 'CONNECTED'}
+ </span></span>
</div>
</div>
- {/* Create Watchlist Modal */}
+ {/* Modals */}
{showCreateWatchlist && (
<CreateWatchlistModal
onClose={() => setShowCreateWatchlist(false)}
@@ -534,8 +525,6 @@ const WatchlistTab: React.FC = () => {
existingColors={watchlists.map(w => w.color)}
/>
)}
-
- {/* Add Stock Modal */}
{showAddStock && selectedWatchlist && (
<AddStockModal
onClose={() => setShowAddStock(false)}
@@ -543,16 +532,6 @@ const WatchlistTab: React.FC = () => {
existingSymbols={stocksList.map(s => s.symbol)}
/>
)}
-
- {/* Footer */}
- <TabFooter
- tabName="WATCHLIST"
- leftInfo={[
- { label: `Lists: ${watchlists.length}`, color: '#6b7280' },
- { label: selectedWatchlist ? `"${selectedWatchlist.name}"` : 'No list selected', color: '#06b6d4' },
- ]}
- statusInfo={`Stocks: ${stocksList.length} | ${loading || stocksLoading ? 'Loading...' : isOffline ? 'Offline' : 'Ready'}`}
- />
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/utils.ts b/fincept-terminal-desktop/src/components/tabs/watchlist/utils.ts
index edc128604..36b086161 100644
--- a/fincept-terminal-desktop/src/components/tabs/watchlist/utils.ts
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/utils.ts
@@ -1,25 +1,30 @@
// Watchlist Utilities - Shared constants, formatting, and helper functions
-import { terminalThemeService } from '@/services/core/terminalThemeService';
-
-// Fincept Color Scheme
-export const getFinceptColors = () => {
- const theme = terminalThemeService.getTheme();
- return {
- ORANGE: theme.colors.primary,
- WHITE: theme.colors.text,
- RED: theme.colors.alert,
- GREEN: theme.colors.secondary,
- YELLOW: theme.colors.warning,
- GRAY: theme.colors.textMuted,
- BLUE: theme.colors.info,
- PURPLE: theme.colors.purple,
- CYAN: theme.colors.accent,
- DARK_BG: theme.colors.background,
- PANEL_BG: theme.colors.panel
- };
+
+// Fincept Design System Color Palette
+export const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
};
-export const FINCEPT_COLORS = getFinceptColors();
+// Legacy export for backwards compat
+export const FINCEPT_COLORS = FINCEPT;
+export const getFinceptColors = () => FINCEPT;
+
+// Font family constant
+export const FONT_FAMILY = '"IBM Plex Mono", "Consolas", monospace';
// Format currency values
export const formatCurrency = (value: number | undefined | null): string => {
@@ -58,8 +63,8 @@ export const formatVolume = (value: number | undefined | null): string => {
// Get color based on value (positive/negative)
export const getChangeColor = (value: number | undefined | null): string => {
- if (value === undefined || value === null) return FINCEPT_COLORS.GRAY;
- return value >= 0 ? FINCEPT_COLORS.GREEN : FINCEPT_COLORS.RED;
+ if (value === undefined || value === null) return FINCEPT.GRAY;
+ return value >= 0 ? FINCEPT.GREEN : FINCEPT.RED;
};
// Sort stocks by different criteria
@@ -104,13 +109,13 @@ export const sortStocks = <T extends { symbol: string; quote: any }>(
// Default watchlist colors
export const WATCHLIST_COLORS = [
- '#FFA500', // Orange
- '#6496FA', // Blue
- '#00C800', // Green
- '#00FFFF', // Cyan
- '#C864FF', // Purple
- '#FFFF00', // Yellow
- '#FF0000', // Red
+ '#FF8800', // Orange
+ '#0088FF', // Blue
+ '#00D66F', // Green
+ '#00E5FF', // Cyan
+ '#9D4EDD', // Purple
+ '#FFD700', // Yellow
+ '#FF3B3B', // Red
'#FFFFFF', // White
];
@@ -121,5 +126,5 @@ export const getNextWatchlistColor = (existingColors: string[]): string => {
return color;
}
}
- return WATCHLIST_COLORS[0]; // Fallback to orange
+ return WATCHLIST_COLORS[0];
};
diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/vectorbt/VectorBTAdapter.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/vectorbt/VectorBTAdapter.ts
index ef0263a20..f5cd4e38e 100644
--- a/fincept-terminal-desktop/src/services/backtesting/adapters/vectorbt/VectorBTAdapter.ts
+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/vectorbt/VectorBTAdapter.ts
@@ -119,7 +119,12 @@ export class VectorBTAdapter extends BaseBacktestingAdapter {
const result = this.extractJSON(stdout);
if (!result.success) {
- throw new Error(result.error || 'VectorBT backtest failed');
+ // Include logs from Python in the error for debugging
+ const logs = result?.data?.logs || result?.logs || [];
+ const logsStr = Array.isArray(logs) && logs.length > 0
+ ? `\nLogs: ${logs.slice(-5).join('\n')}`
+ : '';
+ throw new Error((result.error || 'VectorBT backtest failed') + logsStr);
}
return result.data as BacktestResult;
diff --git a/fincept-terminal-desktop/src/services/cache/cacheService.ts b/fincept-terminal-desktop/src/services/cache/cacheService.ts
index 0f298ba92..62b5e3abd 100644
--- a/fincept-terminal-desktop/src/services/cache/cacheService.ts
+++ b/fincept-terminal-desktop/src/services/cache/cacheService.ts
@@ -108,7 +108,7 @@ function parseTTL(ttl: number | TTLPreset): number {
// Cache Service Class
// ============================================================================
-class CacheService {
+export class CacheService {
private initialized = false;
private initializing = false;
private initPromise: Promise<boolean> | null = null;
diff --git a/fincept-terminal-desktop/src/services/chat/llmApi.ts b/fincept-terminal-desktop/src/services/chat/llmApi.ts
index 16b74b606..d68e6b739 100644
--- a/fincept-terminal-desktop/src/services/chat/llmApi.ts
+++ b/fincept-terminal-desktop/src/services/chat/llmApi.ts
@@ -479,16 +479,33 @@ class LLMApiService {
const url = config.baseUrl || 'https://finceptbackend.share.zrok.io/research/llm';
try {
- const userMessage = messages.filter(m => m.role === 'user').pop()?.content || '';
+ // Build full prompt including system message and conversation history
const systemPrompt = messages.find(m => m.role === 'system')?.content || '';
+ const conversationParts: string[] = [];
+
+ if (systemPrompt) {
+ conversationParts.push(`System: ${systemPrompt}`);
+ }
+
+ // Add conversation history
+ for (const msg of messages) {
+ if (msg.role === 'user') {
+ conversationParts.push(`User: ${msg.content}`);
+ } else if (msg.role === 'assistant') {
+ conversationParts.push(`Assistant: ${msg.content}`);
+ }
+ }
+
+ const fullPrompt = conversationParts.join('\n\n');
const requestBody = {
- prompt: userMessage,
- system_prompt: systemPrompt,
+ prompt: fullPrompt,
temperature: config.temperature,
max_tokens: config.maxTokens
};
+ llmLogger.debug('Fincept API request:', { url, bodyKeys: Object.keys(requestBody) });
+
const response = await fetch(url, {
method: 'POST',
headers: {
@@ -500,10 +517,12 @@ class LLMApiService {
if (!response.ok) {
const error = await response.json().catch(() => ({}));
+ llmLogger.error('Fincept API error response:', error);
throw new Error(error.detail || error.message || `Fincept API error: ${response.status}`);
}
const data = await response.json();
+ llmLogger.debug('Fincept API response:', data);
// Response can be nested in data.data.response or directly in data.response
const responseData = data.data || data;
@@ -526,6 +545,7 @@ class LLMApiService {
}
};
} catch (error) {
+ llmLogger.error('Fincept API Error:', error);
return {
content: '',
error: error instanceof Error ? error.message : 'Fincept API error'
@@ -930,7 +950,7 @@ class LLMApiService {
}
}
- // Fincept with tools support (OpenAI-compatible)
+ // Fincept with tools support - falls back to regular call since tools not supported
private async callFinceptWithTools(
messages: ChatMessage[],
config: LLMConfig,
@@ -938,89 +958,9 @@ class LLMApiService {
onStream?: StreamCallback,
onToolCall?: (toolName: string, args: any, result?: any) => void
): Promise<LLMResponse> {
- const url = config.baseUrl || 'https://finceptbackend.share.zrok.io/research/llm';
-
- try {
- const response = await fetch(url, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-API-Key': config.apiKey || ''
- },
- body: JSON.stringify({
- messages: messages,
- tools: tools,
- temperature: config.temperature,
- max_tokens: config.maxTokens
- })
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.detail || errorData.message || `Fincept error: ${response.status}`);
- }
-
- const data = await response.json();
-
- // Check for tool calls
- if (data.tool_calls && data.tool_calls.length > 0) {
- let toolResults = '';
-
- for (const toolCall of data.tool_calls) {
- const functionName = toolCall.function?.name || toolCall.name;
- const args = typeof toolCall.function?.arguments === 'string'
- ? JSON.parse(toolCall.function.arguments)
- : toolCall.args || {};
-
- const parts = functionName.split('__');
- if (parts.length === 2) {
- const [serverId, toolName] = parts;
- onToolCall?.(toolName, args);
-
- try {
- const { mcpManager } = await import('../mcp/mcpManager');
- const result = await mcpManager.callTool(serverId, toolName, args);
- onToolCall?.(toolName, args, result);
- toolResults += `\n**Tool: ${toolName}**\nResult: ${JSON.stringify(result, null, 2)}\n`;
- } catch (toolError) {
- toolResults += `\n**Tool: ${toolName}**\nError: ${toolError instanceof Error ? toolError.message : 'Unknown error'}\n`;
- }
- }
- }
-
- if (toolResults) {
- const followUpMessages: ChatMessage[] = [
- ...messages,
- { role: 'assistant', content: `I used the following tools:\n${toolResults}` },
- { role: 'user', content: 'Please provide a summary based on the tool results above.' }
- ];
-
- return this.chat(followUpMessages[followUpMessages.length - 1].content, followUpMessages.slice(0, -1), onStream);
- }
- }
-
- const content = data.response || data.content || data.choices?.[0]?.message?.content || '';
-
- if (onStream && content) {
- onStream(content, false);
- onStream('', true);
- }
-
- return {
- content,
- usage: {
- promptTokens: data.usage?.prompt_tokens || 0,
- completionTokens: data.usage?.completion_tokens || 0,
- totalTokens: data.usage?.total_tokens || 0
- }
- };
- } catch (error) {
- llmLogger.error('Fincept with tools error:', error);
- return {
- content: '',
- error: error instanceof Error ? error.message : 'Fincept API error'
- };
- }
+ // Fincept LLM API doesn't support tools, fall back to regular call
+ llmLogger.warn('Fincept API does not support tools, falling back to regular chat');
+ return this.callFincept(messages, config, onStream);
}
// OpenRouter with tools support
diff --git a/fincept-terminal-desktop/src/services/core/sqliteService.ts b/fincept-terminal-desktop/src/services/core/sqliteService.ts
index aee593849..98ff68ef1 100644
--- a/fincept-terminal-desktop/src/services/core/sqliteService.ts
+++ b/fincept-terminal-desktop/src/services/core/sqliteService.ts
@@ -511,10 +511,29 @@ export const getMCPServers = async (): Promise<MCPServer[]> => {
return await invoke<MCPServer[]>('db_get_mcp_servers');
};
+export interface InternalMCPToolSetting {
+ tool_name: string;
+ category: string;
+ is_enabled: boolean;
+ updated_at: string;
+}
+
export const deleteMCPServer = async (id: string): Promise<void> => {
await invoke('db_delete_mcp_server', { id });
};
+export const getInternalToolSettings = async (): Promise<InternalMCPToolSetting[]> => {
+ return await invoke<InternalMCPToolSetting[]>('db_get_internal_tool_settings');
+};
+
+export const setInternalToolEnabled = async (toolName: string, category: string, isEnabled: boolean): Promise<void> => {
+ await invoke('db_set_internal_tool_enabled', { toolName, category, isEnabled });
+};
+
+export const isInternalToolEnabled = async (toolName: string): Promise<boolean> => {
+ return await invoke<boolean>('db_is_internal_tool_enabled', { toolName });
+};
+
// ==================== BACKTESTING ====================
export interface BacktestingProvider {
diff --git a/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts b/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts
index a3a2c2a7f..58a12ce2a 100644
--- a/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts
+++ b/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts
@@ -326,6 +326,253 @@ class ChatModeApiService {
};
}
}
+
+ /**
+ * Bulk delete sessions (registered users only)
+ */
+ async bulkDeleteSessions(sessionUuids: string[]): Promise<ChatModeResponse> {
+ try {
+ await this.initialize();
+
+ const response = await fetch(`${this.baseUrl}/chat/sessions/bulk-delete`, {
+ method: 'DELETE',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(this.apiKey && { 'X-API-Key': this.apiKey })
+ },
+ body: JSON.stringify({ session_uuids: sessionUuids })
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to bulk delete: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+
+ if (result.success) {
+ return { success: true, data: result.data };
+ }
+
+ throw new Error(result.message || 'Unknown error');
+ } catch (error) {
+ console.error('Bulk delete error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to bulk delete sessions'
+ };
+ }
+ }
+
+ /**
+ * Activate a specific session (deactivates others)
+ */
+ async activateSession(sessionUuid: string): Promise<ChatModeResponse> {
+ try {
+ await this.initialize();
+
+ const response = await fetch(`${this.baseUrl}/chat/sessions/${sessionUuid}/activate`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(this.apiKey && { 'X-API-Key': this.apiKey })
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to activate session: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+
+ if (result.success) {
+ return { success: true, data: result.data };
+ }
+
+ throw new Error(result.message || 'Unknown error');
+ } catch (error) {
+ console.error('Activate session error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to activate session'
+ };
+ }
+ }
+
+ /**
+ * Search messages across all sessions
+ */
+ async searchMessages(query: string, limit: number = 20): Promise<ChatModeResponse> {
+ try {
+ await this.initialize();
+
+ const response = await fetch(`${this.baseUrl}/chat/search?query=${encodeURIComponent(query)}&limit=${limit}`, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(this.apiKey && { 'X-API-Key': this.apiKey })
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to search: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+
+ if (result.success) {
+ return { success: true, data: result.data };
+ }
+
+ throw new Error(result.message || 'Unknown error');
+ } catch (error) {
+ console.error('Search messages error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to search messages'
+ };
+ }
+ }
+
+ /**
+ * Get chat usage statistics
+ */
+ async getStats(): Promise<ChatModeResponse> {
+ try {
+ await this.initialize();
+
+ const response = await fetch(`${this.baseUrl}/chat/stats`, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(this.apiKey && { 'X-API-Key': this.apiKey })
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to get stats: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+
+ if (result.success) {
+ return { success: true, data: result.data };
+ }
+
+ throw new Error(result.message || 'Unknown error');
+ } catch (error) {
+ console.error('Get stats error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to get stats'
+ };
+ }
+ }
+
+ /**
+ * Export sessions to JSON (registered users only)
+ */
+ async exportSessions(sessionUuids?: string[]): Promise<ChatModeResponse> {
+ try {
+ await this.initialize();
+
+ const response = await fetch(`${this.baseUrl}/chat/export`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(this.apiKey && { 'X-API-Key': this.apiKey })
+ },
+ body: JSON.stringify({ session_uuids: sessionUuids || [] })
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to export: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+
+ if (result.success) {
+ return { success: true, data: result.data };
+ }
+
+ throw new Error(result.message || 'Unknown error');
+ } catch (error) {
+ console.error('Export sessions error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to export sessions'
+ };
+ }
+ }
+
+ /**
+ * Get conversation templates (registered users)
+ */
+ async getTemplates(): Promise<ChatModeResponse> {
+ try {
+ await this.initialize();
+
+ const response = await fetch(`${this.baseUrl}/chat/templates`, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(this.apiKey && { 'X-API-Key': this.apiKey })
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to get templates: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+
+ if (result.success) {
+ return { success: true, data: result.data };
+ }
+
+ throw new Error(result.message || 'Unknown error');
+ } catch (error) {
+ console.error('Get templates error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to get templates'
+ };
+ }
+ }
+
+ /**
+ * Start session from template
+ */
+ async startFromTemplate(templateId: string): Promise<ChatModeResponse> {
+ try {
+ await this.initialize();
+
+ const response = await fetch(`${this.baseUrl}/chat/templates/${templateId}/start`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(this.apiKey && { 'X-API-Key': this.apiKey })
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to start from template: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+
+ if (result.success) {
+ return { success: true, data: result.data };
+ }
+
+ throw new Error(result.message || 'Unknown error');
+ } catch (error) {
+ console.error('Start from template error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to start from template'
+ };
+ }
+ }
}
export const chatModeApiService = new ChatModeApiService();
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/BrokerMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/BrokerMCPBridge.ts
new file mode 100644
index 000000000..58fd5d58b
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/BrokerMCPBridge.ts
@@ -0,0 +1,285 @@
+// Broker MCP Bridge - Connects BrokerContext to MCP Internal Tools
+// Provides unified trading interface for all brokers via MCP
+
+import { terminalMCPProvider } from './TerminalMCPProvider';
+import type { IExchangeAdapter } from '@/brokers/crypto/types';
+import type { PaperTradingAdapter } from '@/paper-trading';
+
+interface BrokerMCPBridgeConfig {
+ activeAdapter: IExchangeAdapter | PaperTradingAdapter | null;
+ tradingMode: 'live' | 'paper';
+ activeBroker: string;
+}
+
+/**
+ * Bridge that connects BrokerContext to MCP tools
+ * Allows AI to control trading across all brokers (Kraken, Binance, HyperLiquid, etc.)
+ */
+export class BrokerMCPBridge {
+ private config: BrokerMCPBridgeConfig | null = null;
+
+ /**
+ * Initialize or update the bridge with broker context
+ */
+ connect(config: BrokerMCPBridgeConfig): void {
+ this.config = config;
+ this.updateMCPContexts();
+ }
+
+ /**
+ * Disconnect and clear contexts
+ */
+ disconnect(): void {
+ this.config = null;
+ terminalMCPProvider.setContexts({
+ placeTrade: undefined,
+ cancelOrder: undefined,
+ modifyOrder: undefined,
+ getPositions: undefined,
+ getBalance: undefined,
+ getOrders: undefined,
+ getHoldings: undefined,
+ closePosition: undefined,
+ });
+ }
+
+ /**
+ * Update MCP contexts with current adapter methods
+ */
+ private updateMCPContexts(): void {
+ if (!this.config?.activeAdapter) {
+ console.warn('[BrokerMCPBridge] No active adapter available');
+ return;
+ }
+
+ const { activeAdapter, tradingMode, activeBroker } = this.config;
+
+ terminalMCPProvider.setContexts({
+ // Place trade (market, limit, stop, etc.)
+ placeTrade: async (params: any) => {
+ try {
+ const order = await activeAdapter.createOrder(
+ params.symbol,
+ params.order_type || 'market',
+ params.side,
+ params.amount || params.quantity,
+ params.price,
+ {
+ stopPrice: params.stop_price,
+ ...params
+ }
+ );
+ return {
+ success: true,
+ orderId: order.id,
+ symbol: order.symbol,
+ side: order.side,
+ type: order.type,
+ amount: order.amount,
+ price: order.price,
+ status: order.status,
+ timestamp: order.timestamp,
+ };
+ } catch (error: any) {
+ throw new Error(`Failed to place order: ${error.message}`);
+ }
+ },
+
+ // Cancel order
+ cancelOrder: async (orderId: string) => {
+ try {
+ // Try to extract symbol from order ID or fetch open orders to find it
+ const openOrders = await activeAdapter.fetchOpenOrders();
+ const order = openOrders.find(o => o.id === orderId);
+
+ if (!order) {
+ throw new Error(`Order ${orderId} not found`);
+ }
+
+ const cancelled = await activeAdapter.cancelOrder(orderId, order.symbol);
+ return {
+ success: true,
+ orderId: cancelled.id,
+ status: cancelled.status,
+ };
+ } catch (error: any) {
+ throw new Error(`Failed to cancel order: ${error.message}`);
+ }
+ },
+
+ // Modify order (cancel + replace)
+ modifyOrder: async (orderId: string, updates: any) => {
+ try {
+ const openOrders = await activeAdapter.fetchOpenOrders();
+ const order = openOrders.find(o => o.id === orderId);
+
+ if (!order) {
+ throw new Error(`Order ${orderId} not found`);
+ }
+
+ // Cancel existing order
+ await activeAdapter.cancelOrder(orderId, order.symbol);
+
+ // Place new order with updates
+ const newOrder = await activeAdapter.createOrder(
+ order.symbol,
+ order.type as any,
+ order.side as any,
+ updates.quantity || order.amount,
+ updates.price || order.price
+ );
+
+ return {
+ success: true,
+ oldOrderId: orderId,
+ newOrderId: newOrder.id,
+ newOrder,
+ };
+ } catch (error: any) {
+ throw new Error(`Failed to modify order: ${error.message}`);
+ }
+ },
+
+ // Get positions
+ getPositions: async () => {
+ try {
+ const positions = await activeAdapter.fetchPositions();
+ return positions.map(p => ({
+ symbol: p.symbol,
+ side: p.side,
+ amount: p.contracts || p.contractSize || 0,
+ entryPrice: p.entryPrice,
+ markPrice: p.markPrice,
+ unrealizedPnl: p.unrealizedPnl,
+ leverage: p.leverage,
+ marginType: p.marginMode,
+ liquidationPrice: p.liquidationPrice,
+ }));
+ } catch (error: any) {
+ console.error('[BrokerMCPBridge] Failed to fetch positions:', error);
+ return [];
+ }
+ },
+
+ // Get balance
+ getBalance: async () => {
+ try {
+ const balance = await activeAdapter.fetchBalance();
+ return balance;
+ } catch (error: any) {
+ throw new Error(`Failed to fetch balance: ${error.message}`);
+ }
+ },
+
+ // Get orders
+ getOrders: async (filters?: any) => {
+ try {
+ let orders: any[] = [];
+
+ if (!filters?.status || filters.status === 'open' || filters.status === 'all') {
+ const openOrders = await activeAdapter.fetchOpenOrders(filters?.symbol);
+ orders.push(...openOrders);
+ }
+
+ // Try to fetch closed orders if adapter supports it
+ if (!filters?.status || filters.status === 'closed' || filters.status === 'all') {
+ try {
+ if ('fetchClosedOrders' in activeAdapter && typeof activeAdapter.fetchClosedOrders === 'function') {
+ const closedOrders = await activeAdapter.fetchClosedOrders(filters?.symbol, filters?.limit || 100);
+ orders.push(...closedOrders);
+ }
+ } catch (err) {
+ console.warn('[BrokerMCPBridge] Closed orders not supported by adapter');
+ }
+ }
+
+ return orders.map(o => ({
+ id: o.id,
+ symbol: o.symbol,
+ type: o.type,
+ side: o.side,
+ amount: o.amount,
+ price: o.price,
+ status: o.status,
+ timestamp: o.timestamp,
+ filled: o.filled,
+ remaining: o.remaining,
+ cost: o.cost,
+ fee: o.fee,
+ }));
+ } catch (error: any) {
+ throw new Error(`Failed to fetch orders: ${error.message}`);
+ }
+ },
+
+ // Get holdings (balance formatted as holdings)
+ getHoldings: async () => {
+ try {
+ const balance = await activeAdapter.fetchBalance();
+ const holdings = Object.entries(balance.total || {})
+ .filter(([_, amount]) => (amount as number) > 0)
+ .map(([currency, amount]) => ({
+ currency,
+ amount: amount as number,
+ free: balance.free?.[currency] || 0,
+ used: balance.used?.[currency] || 0,
+ }));
+ return holdings;
+ } catch (error: any) {
+ throw new Error(`Failed to fetch holdings: ${error.message}`);
+ }
+ },
+
+ // Close position
+ closePosition: async (symbol: string) => {
+ try {
+ const positions = await activeAdapter.fetchPositions([symbol]);
+ const position = positions.find(p => p.symbol === symbol);
+
+ if (!position) {
+ throw new Error(`No open position for ${symbol}`);
+ }
+
+ // Determine close side (opposite of position side)
+ const closeSide = position.side === 'long' ? 'sell' : 'buy';
+ const amount = Math.abs(position.contracts || position.contractSize || 0);
+
+ const closeOrder = await activeAdapter.createOrder(
+ symbol,
+ 'market',
+ closeSide as any,
+ amount
+ );
+
+ return {
+ success: true,
+ symbol,
+ closedPosition: position,
+ closeOrder,
+ };
+ } catch (error: any) {
+ throw new Error(`Failed to close position: ${error.message}`);
+ }
+ },
+ });
+
+ console.log(`[BrokerMCPBridge] Connected to ${activeBroker} (${tradingMode} mode)`);
+ }
+
+ /**
+ * Check if bridge is connected
+ */
+ isConnected(): boolean {
+ return this.config !== null && this.config.activeAdapter !== null;
+ }
+
+ /**
+ * Get current configuration
+ */
+ getConfig(): BrokerMCPBridgeConfig | null {
+ return this.config;
+ }
+}
+
+// Singleton instance
+export const brokerMCPBridge = new BrokerMCPBridge();
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/NotesMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/NotesMCPBridge.ts
new file mode 100644
index 000000000..d294e0544
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/NotesMCPBridge.ts
@@ -0,0 +1,102 @@
+// Notes MCP Bridge - Connects notesService to MCP Internal Tools
+
+import { terminalMCPProvider } from './TerminalMCPProvider';
+import { notesService } from '@/services/core/notesService';
+
+/**
+ * Bridge that connects notesService to MCP tools
+ * Allows AI to manage notes via chat
+ */
+export class NotesMCPBridge {
+ private connected: boolean = false;
+
+ /**
+ * Connect notes service to MCP contexts
+ */
+ connect(): void {
+ if (this.connected) return;
+
+ terminalMCPProvider.setContexts({
+ // Create note
+ createNote: async (title: string, content: string) => {
+ const noteId = await notesService.createNote({
+ title,
+ content,
+ category: 'GENERAL',
+ priority: 'MEDIUM',
+ sentiment: 'NEUTRAL',
+ tags: '',
+ tickers: '',
+ is_favorite: false,
+ is_archived: false,
+ color_code: '#1E293B',
+ attachments: '[]',
+ reminder_date: null,
+ word_count: content.split(/\s+/).length,
+ });
+ return { id: noteId, title, content };
+ },
+
+ // List notes
+ listNotes: async () => {
+ const notes = await notesService.getAllNotes();
+ return notes.map(note => ({
+ id: note.id,
+ title: note.title,
+ content: note.content.substring(0, 200) + (note.content.length > 200 ? '...' : ''),
+ category: note.category,
+ priority: note.priority,
+ tags: note.tags,
+ created_at: note.created_at,
+ updated_at: note.updated_at,
+ is_favorite: note.is_favorite,
+ }));
+ },
+
+ // Delete note
+ deleteNote: async (id: string) => {
+ await notesService.deleteNote(Number(id));
+ },
+
+ // Generate report (placeholder)
+ generateReport: async (params: any) => {
+ // TODO: Implement report generation
+ return {
+ success: false,
+ message: 'Report generation not yet implemented',
+ params,
+ };
+ },
+ });
+
+ this.connected = true;
+ console.log('[NotesMCPBridge] Connected notes service to MCP');
+ }
+
+ /**
+ * Disconnect and clear contexts
+ */
+ disconnect(): void {
+ if (!this.connected) return;
+
+ terminalMCPProvider.setContexts({
+ createNote: undefined,
+ listNotes: undefined,
+ deleteNote: undefined,
+ generateReport: undefined,
+ });
+
+ this.connected = false;
+ console.log('[NotesMCPBridge] Disconnected notes service from MCP');
+ }
+
+ /**
+ * Check if bridge is connected
+ */
+ isConnected(): boolean {
+ return this.connected;
+ }
+}
+
+// Singleton instance
+export const notesMCPBridge = new NotesMCPBridge();
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/TerminalMCPProvider.ts b/fincept-terminal-desktop/src/services/mcp/internal/TerminalMCPProvider.ts
index 373e9de67..1d3fd27d4 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/TerminalMCPProvider.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/TerminalMCPProvider.ts
@@ -6,6 +6,7 @@ import { InternalTool, InternalToolResult, TerminalContexts, INTERNAL_SERVER_ID,
class TerminalMCPProvider {
private tools = new Map<string, InternalTool>();
private contexts: TerminalContexts = {};
+ private disabledTools = new Set<string>();
registerTool(tool: InternalTool): void {
this.tools.set(tool.name, tool);
@@ -21,11 +22,36 @@ class TerminalMCPProvider {
this.tools.delete(name);
}
+ setToolEnabled(name: string, enabled: boolean): void {
+ if (enabled) {
+ this.disabledTools.delete(name);
+ } else {
+ this.disabledTools.add(name);
+ }
+ }
+
+ isToolEnabled(name: string): boolean {
+ return !this.disabledTools.has(name);
+ }
+
setContexts(contexts: Partial<TerminalContexts>): void {
this.contexts = { ...this.contexts, ...contexts };
}
listTools(): MCPTool[] {
+ return Array.from(this.tools.values())
+ .filter(tool => !this.disabledTools.has(tool.name))
+ .map(tool => ({
+ serverId: INTERNAL_SERVER_ID,
+ serverName: INTERNAL_SERVER_NAME,
+ name: tool.name,
+ description: tool.description,
+ inputSchema: tool.inputSchema,
+ }));
+ }
+
+ listAllTools(): MCPTool[] {
+ // List all tools including disabled ones (for management UI)
return Array.from(this.tools.values()).map(tool => ({
serverId: INTERNAL_SERVER_ID,
serverName: INTERNAL_SERVER_NAME,
@@ -48,6 +74,15 @@ class TerminalMCPProvider {
};
}
+ if (this.disabledTools.has(name)) {
+ return {
+ success: false,
+ error: `Tool is disabled: ${name}`,
+ toolName: name,
+ serverId: INTERNAL_SERVER_ID,
+ };
+ }
+
try {
const result: InternalToolResult = await tool.handler(args, this.contexts);
return {
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/index.ts b/fincept-terminal-desktop/src/services/mcp/internal/index.ts
index 15a092460..a636d1641 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/index.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/index.ts
@@ -11,6 +11,7 @@ import { backtestingTools } from './tools/backtesting';
import { marketDataTools } from './tools/market-data';
import { workflowTools } from './tools/workflow';
import { notesTools } from './tools/notes';
+import { cryptoTradingTools } from './tools/crypto-trading';
// Register all tool modules
terminalMCPProvider.registerTools(navigationTools);
@@ -23,7 +24,10 @@ terminalMCPProvider.registerTools(backtestingTools);
terminalMCPProvider.registerTools(marketDataTools);
terminalMCPProvider.registerTools(workflowTools);
terminalMCPProvider.registerTools(notesTools);
+terminalMCPProvider.registerTools(cryptoTradingTools);
export { terminalMCPProvider } from './TerminalMCPProvider';
+export { brokerMCPBridge } from './BrokerMCPBridge';
+export { notesMCPBridge } from './NotesMCPBridge';
export { INTERNAL_SERVER_ID, INTERNAL_SERVER_NAME } from './types';
export type { TerminalContexts, InternalTool, InternalToolResult } from './types';
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/crypto-trading.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/crypto-trading.ts
new file mode 100644
index 000000000..ba943559c
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/crypto-trading.ts
@@ -0,0 +1,496 @@
+// Crypto Trading MCP Tools - Unified multi-broker crypto trading tools
+import { InternalTool } from '../types';
+
+export const cryptoTradingTools: InternalTool[] = [
+ // === ORDER MANAGEMENT ===
+ {
+ name: 'crypto_place_market_order',
+ description: 'Place a market order for crypto (buy/sell at current market price)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair (e.g., BTC/USD, ETH/USDT)' },
+ side: { type: 'string', description: 'Order side', enum: ['buy', 'sell'] },
+ amount: { type: 'number', description: 'Amount in base currency (e.g., 0.1 BTC)' },
+ },
+ required: ['symbol', 'side', 'amount'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.placeTrade) {
+ return { success: false, error: 'Trading context not available. Ensure broker is connected.' };
+ }
+ const result = await contexts.placeTrade({
+ ...args,
+ order_type: 'market',
+ });
+ return { success: true, data: result, message: `Market ${args.side} order placed: ${args.amount} ${args.symbol}` };
+ },
+ },
+ {
+ name: 'crypto_place_limit_order',
+ description: 'Place a limit order for crypto (buy/sell at specified price)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair (e.g., BTC/USD, ETH/USDT)' },
+ side: { type: 'string', description: 'Order side', enum: ['buy', 'sell'] },
+ amount: { type: 'number', description: 'Amount in base currency' },
+ price: { type: 'number', description: 'Limit price' },
+ },
+ required: ['symbol', 'side', 'amount', 'price'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.placeTrade) {
+ return { success: false, error: 'Trading context not available' };
+ }
+ const result = await contexts.placeTrade({
+ ...args,
+ order_type: 'limit',
+ });
+ return { success: true, data: result, message: `Limit ${args.side} order placed: ${args.amount} ${args.symbol} @ ${args.price}` };
+ },
+ },
+ {
+ name: 'crypto_place_stop_loss',
+ description: 'Place a stop-loss order for crypto (auto-sell when price drops)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair' },
+ side: { type: 'string', description: 'Order side', enum: ['buy', 'sell'] },
+ amount: { type: 'number', description: 'Amount in base currency' },
+ stop_price: { type: 'number', description: 'Stop trigger price' },
+ limit_price: { type: 'number', description: 'Limit price (optional, for stop-limit)' },
+ },
+ required: ['symbol', 'side', 'amount', 'stop_price'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.placeTrade) {
+ return { success: false, error: 'Trading context not available' };
+ }
+ const result = await contexts.placeTrade({
+ ...args,
+ order_type: args.limit_price ? 'stop_limit' : 'stop',
+ });
+ return { success: true, data: result, message: `Stop order placed: ${args.side} ${args.amount} ${args.symbol} @ stop ${args.stop_price}` };
+ },
+ },
+ {
+ name: 'crypto_cancel_order',
+ description: 'Cancel a pending crypto order by ID',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ order_id: { type: 'string', description: 'Order ID to cancel' },
+ symbol: { type: 'string', description: 'Trading pair (required for some exchanges)' },
+ },
+ required: ['order_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.cancelOrder) {
+ return { success: false, error: 'Trading context not available' };
+ }
+ const result = await contexts.cancelOrder(args.order_id);
+ return { success: true, data: result, message: `Order ${args.order_id} cancelled` };
+ },
+ },
+ {
+ name: 'crypto_cancel_all_orders',
+ description: 'Cancel all open orders for a symbol or all symbols',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair (optional, cancels all if not provided)' },
+ },
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getOrders || !contexts.cancelOrder) {
+ return { success: false, error: 'Trading context not available' };
+ }
+ const orders = await contexts.getOrders({ status: 'open' });
+ const targetOrders = args.symbol
+ ? orders.filter((o: any) => o.symbol === args.symbol)
+ : orders;
+
+ const results = await Promise.allSettled(
+ targetOrders.map((o: any) => contexts.cancelOrder!(o.id))
+ );
+ const cancelled = results.filter(r => r.status === 'fulfilled').length;
+ return {
+ success: true,
+ data: { cancelled, total: targetOrders.length },
+ message: `Cancelled ${cancelled}/${targetOrders.length} orders`
+ };
+ },
+ },
+
+ // === POSITION MANAGEMENT ===
+ {
+ name: 'crypto_get_positions',
+ description: 'Get all open crypto positions across exchanges',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Filter by trading pair (optional)' },
+ },
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getPositions) {
+ return { success: false, error: 'Trading context not available' };
+ }
+ const positions = await contexts.getPositions();
+ const filtered = args.symbol
+ ? positions.filter((p: any) => p.symbol === args.symbol)
+ : positions;
+ return { success: true, data: filtered };
+ },
+ },
+ {
+ name: 'crypto_close_position',
+ description: 'Close an open position for a crypto pair',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair to close position for' },
+ percentage: { type: 'number', description: 'Percentage of position to close (1-100, default 100)' },
+ },
+ required: ['symbol'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.closePosition) {
+ return { success: false, error: 'Trading context not available' };
+ }
+ const result = await contexts.closePosition(args.symbol);
+ return { success: true, data: result, message: `Position closed for ${args.symbol}` };
+ },
+ },
+
+ // === ACCOUNT INFO ===
+ {
+ name: 'crypto_get_balance',
+ description: 'Get account balance and available funds',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ currency: { type: 'string', description: 'Filter by currency (e.g., USD, BTC, ETH)' },
+ },
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getBalance) {
+ return { success: false, error: 'Trading context not available' };
+ }
+ const balance = await contexts.getBalance();
+ if (args.currency) {
+ const filtered = balance[args.currency] || { free: 0, used: 0, total: 0 };
+ return { success: true, data: { [args.currency]: filtered } };
+ }
+ return { success: true, data: balance };
+ },
+ },
+ {
+ name: 'crypto_get_holdings',
+ description: 'Get all crypto holdings with current values',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getHoldings) {
+ return { success: false, error: 'Trading context not available' };
+ }
+ const holdings = await contexts.getHoldings();
+ return { success: true, data: holdings };
+ },
+ },
+
+ // === ORDER HISTORY ===
+ {
+ name: 'crypto_get_orders',
+ description: 'Get order history with optional filters',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Filter by trading pair' },
+ status: { type: 'string', description: 'Filter by status', enum: ['open', 'closed', 'cancelled', 'all'] },
+ limit: { type: 'number', description: 'Number of orders to return (default 100)' },
+ },
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getOrders) {
+ return { success: false, error: 'Trading context not available' };
+ }
+ const orders = await contexts.getOrders(args);
+ return { success: true, data: orders };
+ },
+ },
+
+ // === MARKET DATA ===
+ {
+ name: 'crypto_get_ticker',
+ description: 'Get real-time ticker data for a crypto pair',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair (e.g., BTC/USD)' },
+ },
+ required: ['symbol'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getQuote) {
+ return { success: false, error: 'Market data context not available' };
+ }
+ const ticker = await contexts.getQuote(args.symbol);
+ return { success: true, data: ticker };
+ },
+ },
+ {
+ name: 'crypto_get_orderbook',
+ description: 'Get order book (bids/asks) for a crypto pair',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair' },
+ limit: { type: 'number', description: 'Number of price levels (default 20)' },
+ },
+ required: ['symbol'],
+ },
+ handler: async (args, contexts) => {
+ // Order book would need to be added to contexts
+ return { success: false, error: 'Order book context not yet implemented' };
+ },
+ },
+
+ // === WATCHLIST ===
+ {
+ name: 'crypto_add_to_watchlist',
+ description: 'Add a crypto pair to watchlist',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair to add' },
+ },
+ required: ['symbol'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.addToWatchlist) {
+ return { success: false, error: 'Watchlist context not available' };
+ }
+ await contexts.addToWatchlist(args.symbol);
+ return { success: true, message: `${args.symbol} added to watchlist` };
+ },
+ },
+ {
+ name: 'crypto_remove_from_watchlist',
+ description: 'Remove a crypto pair from watchlist',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair to remove' },
+ },
+ required: ['symbol'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.removeFromWatchlist) {
+ return { success: false, error: 'Watchlist context not available' };
+ }
+ await contexts.removeFromWatchlist(args.symbol);
+ return { success: true, message: `${args.symbol} removed from watchlist` };
+ },
+ },
+ {
+ name: 'crypto_search_symbol',
+ description: 'Search for crypto trading pairs by keyword',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Search query (e.g., BTC, ethereum)' },
+ },
+ required: ['query'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.searchSymbol) {
+ return { success: false, error: 'Search context not available' };
+ }
+ const results = await contexts.searchSymbol(args.query);
+ return { success: true, data: results };
+ },
+ },
+
+ // === TRADING MODE ===
+ {
+ name: 'crypto_switch_trading_mode',
+ description: 'Switch between live and paper trading mode',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mode: { type: 'string', description: 'Trading mode', enum: ['live', 'paper'] },
+ },
+ required: ['mode'],
+ },
+ handler: async (args, _contexts) => {
+ // This would need to be integrated with BrokerContext
+ return { success: false, error: 'Trading mode switching not yet implemented in MCP' };
+ },
+ },
+ {
+ name: 'crypto_switch_broker',
+ description: 'Switch active crypto exchange/broker',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ broker: { type: 'string', description: 'Broker ID (kraken, binance, hyperliquid, etc.)' },
+ },
+ required: ['broker'],
+ },
+ handler: async (args, _contexts) => {
+ // This would need to be integrated with BrokerContext
+ return { success: false, error: 'Broker switching not yet implemented in MCP' };
+ },
+ },
+
+ // === PORTFOLIO METRICS ===
+ {
+ name: 'crypto_get_portfolio_value',
+ description: 'Get total portfolio value in quote currency',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ quote: { type: 'string', description: 'Quote currency (default USD)' },
+ },
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getHoldings || !contexts.getQuote) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ const holdings = await contexts.getHoldings();
+ const quote = args.quote || 'USD';
+
+ // Calculate total value (simplified)
+ let totalValue = 0;
+ for (const holding of holdings) {
+ if (holding.currency === quote) {
+ totalValue += holding.amount;
+ } else {
+ const ticker = await contexts.getQuote(`${holding.currency}/${quote}`);
+ totalValue += holding.amount * ticker.last;
+ }
+ }
+
+ return { success: true, data: { totalValue, quote, holdings: holdings.length } };
+ },
+ },
+ {
+ name: 'crypto_get_pnl',
+ description: 'Get profit/loss for positions or overall portfolio',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair (optional, returns all if not provided)' },
+ timeframe: { type: 'string', description: 'Timeframe', enum: ['day', 'week', 'month', 'all'] },
+ },
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getPositions) {
+ return { success: false, error: 'PnL context not available' };
+ }
+ const positions = await contexts.getPositions();
+ const filtered = args.symbol
+ ? positions.filter((p: any) => p.symbol === args.symbol)
+ : positions;
+
+ const totalPnl = filtered.reduce((sum: number, p: any) => sum + (p.unrealizedPnl || 0), 0);
+ return {
+ success: true,
+ data: {
+ pnl: totalPnl,
+ positions: filtered.length,
+ timeframe: args.timeframe || 'all'
+ }
+ };
+ },
+ },
+
+ // === RISK MANAGEMENT ===
+ {
+ name: 'crypto_set_stop_loss_for_position',
+ description: 'Set stop-loss for an existing position',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair' },
+ stop_price: { type: 'number', description: 'Stop price trigger' },
+ percentage: { type: 'number', description: 'Stop loss as percentage below entry (e.g., 5 for 5%)' },
+ },
+ required: ['symbol'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getPositions || !contexts.placeTrade) {
+ return { success: false, error: 'Risk management context not available' };
+ }
+
+ const positions = await contexts.getPositions();
+ const position = positions.find((p: any) => p.symbol === args.symbol);
+
+ if (!position) {
+ return { success: false, error: `No open position for ${args.symbol}` };
+ }
+
+ const stopPrice = args.stop_price || position.entryPrice * (1 - (args.percentage || 5) / 100);
+
+ const result = await contexts.placeTrade({
+ symbol: args.symbol,
+ side: position.side === 'long' ? 'sell' : 'buy',
+ amount: Math.abs(position.amount),
+ order_type: 'stop',
+ stop_price: stopPrice,
+ });
+
+ return {
+ success: true,
+ data: result,
+ message: `Stop-loss set for ${args.symbol} at ${stopPrice}`
+ };
+ },
+ },
+ {
+ name: 'crypto_set_take_profit',
+ description: 'Set take-profit for an existing position',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ symbol: { type: 'string', description: 'Trading pair' },
+ target_price: { type: 'number', description: 'Target price' },
+ percentage: { type: 'number', description: 'Take profit as percentage above entry (e.g., 10 for 10%)' },
+ },
+ required: ['symbol'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getPositions || !contexts.placeTrade) {
+ return { success: false, error: 'Risk management context not available' };
+ }
+
+ const positions = await contexts.getPositions();
+ const position = positions.find((p: any) => p.symbol === args.symbol);
+
+ if (!position) {
+ return { success: false, error: `No open position for ${args.symbol}` };
+ }
+
+ const targetPrice = args.target_price || position.entryPrice * (1 + (args.percentage || 10) / 100);
+
+ const result = await contexts.placeTrade({
+ symbol: args.symbol,
+ side: position.side === 'long' ? 'sell' : 'buy',
+ amount: Math.abs(position.amount),
+ order_type: 'limit',
+ price: targetPrice,
+ });
+
+ return {
+ success: true,
+ data: result,
+ message: `Take-profit set for ${args.symbol} at ${targetPrice}`
+ };
+ },
+ },
+];
diff --git a/fincept-terminal-desktop/src/services/mcp/mcpToolService.ts b/fincept-terminal-desktop/src/services/mcp/mcpToolService.ts
index 5cae98c15..d74f5be8f 100644
--- a/fincept-terminal-desktop/src/services/mcp/mcpToolService.ts
+++ b/fincept-terminal-desktop/src/services/mcp/mcpToolService.ts
@@ -38,6 +38,30 @@ class MCPToolService {
private toolCache: MCPTool[] = [];
private cacheTimestamp: number = 0;
private cacheTTL: number = 5000; // 5 seconds cache
+ private initialized: boolean = false;
+
+ /**
+ * Initialize the service by loading disabled tool settings
+ */
+ async initialize(): Promise<void> {
+ if (this.initialized) return;
+
+ try {
+ const { getInternalToolSettings } = await import('../core/sqliteService');
+ const settings = await getInternalToolSettings();
+
+ // Apply settings to internal provider
+ for (const setting of settings) {
+ terminalMCPProvider.setToolEnabled(setting.tool_name, setting.is_enabled);
+ }
+
+ this.initialized = true;
+ } catch (error) {
+ mcpLogger.error('Failed to initialize MCP tool service:', error);
+ // Continue anyway - all tools will be enabled by default
+ this.initialized = true;
+ }
+ }
/**
* Get all available MCP tools from running servers
@@ -45,6 +69,9 @@ class MCPToolService {
*/
async getAllTools(): Promise<MCPTool[]> {
try {
+ // Ensure initialized
+ await this.initialize();
+
const now = Date.now();
// Return cached tools if still valid
@@ -72,6 +99,24 @@ class MCPToolService {
}
}
+ /**
+ * Get all internal tools including disabled ones (for management UI)
+ */
+ async getAllInternalTools(): Promise<MCPTool[]> {
+ await this.initialize();
+ return terminalMCPProvider.listAllTools();
+ }
+
+ /**
+ * Set whether an internal tool is enabled
+ */
+ async setInternalToolEnabled(toolName: string, category: string, enabled: boolean): Promise<void> {
+ const { setInternalToolEnabled } = await import('../core/sqliteService');
+ await setInternalToolEnabled(toolName, category, enabled);
+ terminalMCPProvider.setToolEnabled(toolName, enabled);
+ this.clearCache(); // Clear cache to force refresh
+ }
+
/**
* Execute an MCP tool directly without LLM assistance
* Used by Node Editor for direct tool execution
diff --git a/fincept-terminal-desktop/src/services/portfolio/portfolioService.ts b/fincept-terminal-desktop/src/services/portfolio/portfolioService.ts
index e1f0bde49..b1b138f96 100644
--- a/fincept-terminal-desktop/src/services/portfolio/portfolioService.ts
+++ b/fincept-terminal-desktop/src/services/portfolio/portfolioService.ts
@@ -82,6 +82,7 @@ export interface PortfolioSummary {
class PortfolioService {
private isInitialized = false;
+ private symbolsMigrated = false;
/**
* Initialize database connection
@@ -91,6 +92,63 @@ class PortfolioService {
if (this.isInitialized) return;
this.isInitialized = true;
portfolioLogger.info('Using Rust SQLite backend - no initialization needed');
+
+ // Run one-time symbol migration (resolves bare symbols like "PIDILITIND" → "PIDILITIND.NS")
+ if (!this.symbolsMigrated) {
+ this.symbolsMigrated = true;
+ this.migrateSymbols().catch(err =>
+ portfolioLogger.warn(`Symbol migration skipped: ${err}`)
+ );
+ }
+ }
+
+ /**
+ * One-time migration: resolve bare symbols to yfinance-compatible forms.
+ * e.g. "PIDILITIND" → "PIDILITIND.NS", "AAPL" stays "AAPL"
+ * Only touches symbols that have no '.' in them (not yet resolved).
+ */
+ private async migrateSymbols(): Promise<void> {
+ try {
+ const portfolios = await invoke<Portfolio[]>('portfolio_get_all');
+ for (const portfolio of portfolios) {
+ const assets = await invoke<PortfolioAsset[]>('portfolio_get_assets', {
+ portfolioId: portfolio.id,
+ });
+
+ for (const asset of assets) {
+ // Skip symbols that already have an exchange suffix
+ if (asset.symbol.includes('.') || asset.symbol.includes('-') ||
+ asset.symbol.includes('=') || asset.symbol.startsWith('^')) {
+ continue;
+ }
+
+ try {
+ const resolveOutput = await invoke<string>('execute_yfinance_command', {
+ command: 'resolve_symbol',
+ args: [asset.symbol],
+ });
+ const resolved = JSON.parse(resolveOutput);
+
+ if (resolved.found && resolved.resolved_symbol &&
+ resolved.resolved_symbol !== asset.symbol) {
+ await invoke('portfolio_update_asset_symbol', {
+ assetId: asset.id,
+ newSymbol: resolved.resolved_symbol,
+ });
+ portfolioLogger.info(
+ `Migrated symbol: ${asset.symbol} → ${resolved.resolved_symbol}`
+ );
+ }
+ } catch (resolveErr) {
+ portfolioLogger.warn(
+ `Failed to resolve symbol ${asset.symbol}: ${resolveErr}`
+ );
+ }
+ }
+ }
+ } catch (err) {
+ portfolioLogger.warn(`Symbol migration error: ${err}`);
+ }
}
async createPortfolio(name: string, owner: string, currency: string = 'USD', description?: string): Promise<Portfolio> {
diff --git a/fincept-terminal-desktop/src/services/support/supportApi.ts b/fincept-terminal-desktop/src/services/support/supportApi.ts
index efad955bf..81a04be48 100644
--- a/fincept-terminal-desktop/src/services/support/supportApi.ts
+++ b/fincept-terminal-desktop/src/services/support/supportApi.ts
@@ -11,8 +11,6 @@ export interface ContactFormData {
}
export interface FeedbackFormData {
- name?: string;
- email?: string;
rating: number;
feedback_text: string;
category?: string;
@@ -69,16 +67,21 @@ export async function submitContactForm(data: ContactFormData): Promise<ApiRespo
}
/**
- * Submit feedback (public endpoint)
+ * Submit feedback (requires authentication)
*/
-export async function submitFeedback(data: FeedbackFormData): Promise<ApiResponse> {
+export async function submitFeedback(data: FeedbackFormData, apiKey: string): Promise<ApiResponse> {
try {
const response = await fetch(`${API_BASE_URL}/support/feedback`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
+ 'X-API-Key': apiKey,
},
- body: JSON.stringify(data),
+ body: JSON.stringify({
+ rating: data.rating,
+ feedback_text: data.feedback_text,
+ category: data.category || 'general',
+ }),
});
const result = await response.json();